Compare commits

..
6 Commits
Author SHA1 Message Date
dahyeon 0d7617e2d2 feat: connect tournament views to APIs and recover archived stats
Remove development previews and complete hall of fame, match history, official results, and multi-kill API integration.

Fix active match pagination and team-ready controls, preserve basic scoreboards, and recover statistics when Riot archives arrive.

Use bounded in-process cache invalidation retries and add the Riot match lookup index migration with regression coverage.
2026-11-11 02:00:35 +09:00
dahyeon 20e1e6ec04 feat(web): show winning teams in recent match results 2026-11-10 23:05:59 +09:00
dahyeon 664af15255 feat: refresh the home page and separate match event types
Add an inhouse hero, Hall of Fame, rankings, and event-specific schedules. Carry the event type through the API and admin tools, and improve results and player history displays.
2026-11-10 22:13:55 +09:00
dahyeon 7e0cd7cb19 fix: keep best-of-three grand finals open for results
Allow a separate grand final format and repair prematurely completed finals without dropping accepted games. Replay the correction record alongside subsequent results.
2026-11-10 18:49:26 +09:00
dahyeon 38a89b5374 feat: improve tournament workflows and prune outdated docs 2026-11-10 15:31:19 +09:00
dahyeon da7b502936 feat(web): refresh the app with Astryx and coral branding 2026-11-10 13:35:11 +09:00
244 changed files with 11931 additions and 5076 deletions

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
{
"version": "0.0.1",
"configurations": [
{
"name": "web-staging",
"runtimeExecutable": "pnpm",
"runtimeArgs": ["--filter", "web", "start:staging"],
"port": 5173
}
]
}
+5 -5
View File
@@ -23,11 +23,11 @@ website/LICENSE
*.md
!README.md
!docs/specs/internal-match-game-analysis.md
!docs/plans/internal-match-game-analysis-p0-p1.md
!docs/specs/double-elimination-connector-routing.md
!docs/plans/double-elimination-connector-routing.md
!docs/plans/redis-8.10-optimization.md
!design-qa.md
!docs/specs/home-banner-production.md
!docs/specs/match-status-and-result-presentation.md
!docs/ux-audit-2026-11-10/06-ui-improvement-review.md
!docs/ux-audit-2026-11-10/07-visual-design-review.md
/tmp/
/user-game-history/
/*.txt
+5 -1
View File
@@ -144,7 +144,9 @@ pnpm --filter api build
`test:redis`는 PATH의 `redis-server` 또는 `REDIS_TEST_SERVER`에 지정한 실행 파일로 Redis 8.10.x를 직접 실행합니다. 임의의 로컬 포트와 일회용 암호를 사용하고, 저장을 비활성화하며, 종료 후 프로세스와 임시 디렉터리를 정리합니다. 애플리케이션 Redis 연결 설정은 사용하지 않습니다. Windows에서는 PowerShell에서 `$env:REDIS_TEST_SERVER = 'C:\tools\redis\redis-server.exe'`처럼 지정할 수 있습니다.
커뮤니티 통계 캐시는 `riot:communitystats:v2:{communityId}:scope` Hash로 전환됩니다. 항목별 TTL은 일반 5분, 완성된 상세 24시간, 미완성 상세 60초를 유지합니다. 이전 String 캐시는 기존 TTL로 만료되며 새 캐시는 첫 조회에 생성됩니다. 구버전과 신버전은 무효화 대상이 다르므로 API 인스턴스를 같은 버전으로 함께 전환해야 합니다. 구현 범위와 검증 기록은 [Redis 변경 계획](docs/plans/redis-8.10-optimization.md)을 참고하세요.
커뮤니티 통계 캐시는 `riot:communitystats:v2:{communityId}:scope` Hash를 사용합니다. 항목별 TTL은 일반 5분, 완성된 상세 24시간, 미완성 상세 60초입니다. 이전 String 캐시는 기존 TTL로 만료되며 새 캐시는 첫 조회에 생성됩니다. 구버전과 신버전은 무효화 대상이 다르므로 배포와 롤백 모두 API 인스턴스를 같은 버전으로 함께 전환해야 합니다.
스트림이 계속 커지면 소비자 그룹별 미처리 항목을 확인합니다. 사용이 중단된 그룹도 미처리 항목을 계속 보존할 수 있습니다.
### API New Relic APM
@@ -171,6 +173,8 @@ API 성능 계측은 기본 비활성화이며 필요할 때 `API_PERF_OBSERVABI
카카오톡 기반 명령어 기능은 Dakao(커스텀 카카오톡 게이트웨이) 연동이 필요합니다. Dakao가 실행 중이 아니거나 NATS를 통해 API 서버와 연결되어 있지 않으면 일정 조회, 내전 참가, 참가 취소, 계정 등록 같은 카카오톡 명령어는 사용할 수 없습니다.
카카오톡 방을 옮긴 뒤에는 새 방에서 `!내전 데이터이관 예전 닉네임`을 실행합니다. 같은 커뮤니티에서 Riot 계정이 등록된 기존 사용자의 카카오톡 ID만 바뀝니다. 기존 사용자 ID, 권한, 참가 기록은 유지됩니다. 닉네임이 중복되거나 새 ID가 이미 다른 사용자에 연결돼 있으면 운영자가 확인합니다. 계정 소유권 확인은 운영 절차에서 담당합니다.
## 커맨드
| Command | Description |
+33
View File
@@ -117,6 +117,39 @@ The index is `{ auctionCancellationCleanupRetryAt: 1 }`, restricted to
`{ auctionCancellationCleanupPending: true }`. The worker only reads due pending
entries; it no longer scans legacy cancellation markers without a pending flag.
## Riot archive recovery
Newly saved or repaired Riot match data refreshes affected internal match
statistics at the same Competition revision. Existing archives and duplicate
imports do not trigger recovery. Recovery failures are logged and do not block
result collection or match refresh. Only communities with recovered statistics
have their caches invalidated, once per recovery batch; one failed rebuild does
not prevent other successful rebuilds from being reflected. Detail
requests also check for newly archived data when a cached game is missing raw
data. An absent archive does not trigger a rebuild or a Riot match fetch. If a
detail rebuild makes no progress, the process waits 60 seconds before retrying
that source revision and does not invalidate the community cache.
Recovery cache invalidations first try Redis with a one-second command timeout.
On failure they return immediately and schedule up to three in-process retries,
waiting 1, 5, then 30 seconds between attempts. A community has one retry budget;
additional immediate failures do not reset it, and a successful current request
cancels the pending retry. Timers are unreferenced and cleared on shutdown.
Retries are not persisted or resumed after a restart. Detail requests detect
newly archived raw data even behind a stale cache, and other response caches
expire after five minutes. A detail response whose immediate invalidation fails
is returned without being cached. No Mongo invalidation collection or periodic
queue scan is used.
Before deploying this recovery path, add its Riot ID lookup index. The migration
defaults to dry-run and leaves other indexes and game records unchanged.
```bash
pnpm --filter api stats:indexes -- --env staging --dry-run
pnpm --filter api stats:indexes -- --env staging --apply
# Use --env prod for production.
```
## Deployment
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
+2
View File
@@ -9,7 +9,9 @@
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"competition:migrate": "ts-node src/modules/global/database/migrations/run-competition-domain.ts",
"competition:repair-grand-final": "ts-node src/modules/global/database/migrations/repair-grand-final-bo3.ts",
"auction:indexes": "ts-node src/modules/global/database/migrations/run-auction-cancellation-index.ts",
"stats:indexes": "ts-node src/modules/global/database/migrations/run-match-stats-raw-index.ts",
"seed:dev": "ts-node src/seed.ts",
"seed:dakao-participant": "ts-node src/seed-dakao-participant.ts",
"start:dev": "NODE_ENV=dev NEW_RELIC_HOME=. node --import newrelic/esm-loader.mjs -r newrelic dist/main.js",
@@ -80,7 +80,7 @@ export class AuctionController {
return this.auctionService.getStateByMatchId(matchId);
}
// 공개 — 팀장 2명만 쓸 엔드포인트(트러스트 기반, 10명 동시 관전).
// 공개 입찰 기록 조회.
@Get('bids/history')
@AllowPublicAccess()
public async getBidHistory(
@@ -106,14 +106,20 @@ export class AuctionController {
}
@Post('bids')
@AllowPublicAccess()
@Roles('admin', 'owner', 'member')
@UseGuards(RolesGuard)
@HttpCode(HttpStatus.OK)
public async placeBid(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: PlaceBidDto,
) {
this.assertSameCommunity(currentUser, communityId);
return this.auctionService.placeBid({
matchId,
bidderUserId: currentUser._id,
teamIndex: body.bidderTeamIndex,
amount: body.bidPointAmount,
bidRequestId: body.bidRequestId,
@@ -78,6 +78,8 @@ describe('AuctionGateway', () => {
expect(broadcast).not.toHaveBeenCalled();
});
const bidderUserId = new mongoose.Types.ObjectId();
function createGateway(params?: {
getCurrentRedisTimestampMS?: jest.Mock;
placeBidDelta?: jest.Mock;
@@ -112,6 +114,23 @@ describe('AuctionGateway', () => {
};
}
it('requires an authenticated user before forwarding a bid', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const { gateway, auctionService } = createGateway();
const ack = jest.fn();
await gateway.handleBid(
{ data: { matchId }, emit: jest.fn() } as never,
{ bidderTeamIndex: 1, bidPointAmount: 100 },
ack,
);
expect(auctionService.placeBidDelta).not.toHaveBeenCalled();
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({ rejected: true }),
);
});
it('broadcasts a bid delta and acknowledges the matching bid request', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const auctionBidHistoryEntry = {
@@ -133,7 +152,10 @@ describe('AuctionGateway', () => {
const ack = jest.fn();
await gateway.handleBid(
{ data: { matchId }, emit: jest.fn() } as never,
{
data: { matchId, user: { _id: bidderUserId } },
emit: jest.fn(),
} as never,
{
bidPointAmount: 120,
bidderTeamIndex: 2,
@@ -147,6 +169,7 @@ describe('AuctionGateway', () => {
expect(placeBidDelta).toHaveBeenCalledWith({
amount: 120,
bidRequestId: 'bid-1',
bidderUserId,
clientObservedAuctionLifecycleId: 'life-1',
clientObservedCurrentBidRoundPlayerUserId: 'player-1',
matchId: new mongoose.Types.ObjectId(matchId),
@@ -200,7 +223,10 @@ describe('AuctionGateway', () => {
const ack = jest.fn();
await gateway.handleBid(
{ data: { matchId }, emit: jest.fn() } as never,
{
data: { matchId, user: { _id: bidderUserId } },
emit: jest.fn(),
} as never,
{
bidPointAmount: 50,
bidderTeamIndex: 1,
@@ -247,7 +273,10 @@ describe('AuctionGateway', () => {
const ack = jest.fn();
await gateway.handleBid(
{ data: { matchId }, emit: socketEmit } as never,
{
data: { matchId, user: { _id: bidderUserId } },
emit: socketEmit,
} as never,
{
bidPointAmount: 50,
bidderTeamIndex: 1,
@@ -318,7 +347,10 @@ describe('AuctionGateway', () => {
revision: 3,
});
const socketEmit = jest.fn();
const socket = { data: { matchId }, emit: socketEmit };
const socket = {
data: { matchId, user: { _id: bidderUserId } },
emit: socketEmit,
};
const { gateway } = createGateway({ placeBidDelta });
const acknowledgements: Array<Record<string, unknown>> = [];
@@ -359,7 +391,10 @@ describe('AuctionGateway', () => {
currentHighestBidPointAmount: 50,
revision: 3,
});
const socket = { data: { matchId }, emit: jest.fn() };
const socket = {
data: { matchId, user: { _id: bidderUserId } },
emit: jest.fn(),
};
const { gateway } = createGateway({ placeBidDelta });
for (let index = 0; index < 8; index += 1) {
@@ -1,4 +1,4 @@
import { Logger } from '@nestjs/common';
import { ForbiddenException, Logger } from '@nestjs/common';
import { randomUUID } from 'crypto';
import { performance } from 'perf_hooks';
import {
@@ -86,6 +86,7 @@ interface AuctionSocketData {
identity?: IdentityDocument;
matchId?: string;
user?: UserDocument;
devUser?: UserDocument;
}
type AuctionSocket = Socket<
@@ -114,6 +115,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
private server!: Namespace;
private readonly logger = new Logger(AuctionGateway.name);
private readonly socketAuthentication = new WeakMap<
AuctionSocket,
Promise<void>
>();
constructor(
private readonly auctionService: AuctionService,
@@ -130,8 +135,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
}
public async handleConnection(socket: AuctionSocket) {
const authentication = this.authenticateSocket(socket);
this.socketAuthentication.set(socket, authentication);
try {
await this.authenticateSocket(socket);
await authentication;
this.logger.debug(`Auction client connected: ${socket.id}`);
} catch (err) {
this.logger.warn(
@@ -153,11 +160,13 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
return;
}
await socket.join(payload.matchId);
socket.data.matchId = payload.matchId;
try {
socket.data.matchId = undefined;
socket.data.user = undefined;
await this.socketAuthentication.get(socket);
await socket.join(payload.matchId);
await this.resolveSocketUserForMatch(socket, payload.matchId);
socket.data.matchId = payload.matchId;
const auction = await this.auctionService.getByMatchId(
new mongoose.Types.ObjectId(payload.matchId),
);
@@ -240,11 +249,17 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
}
try {
const bidderUserId = this.resolveSocketUserId(socket);
if (!bidderUserId)
throw new ForbiddenException(
'팀장 계정으로 로그인해야 입찰할 수 있습니다.',
);
const bidResult = await this.auctionService.placeBidDelta({
matchId: new mongoose.Types.ObjectId(matchId),
teamIndex: payload.bidderTeamIndex,
amount: payload.bidPointAmount,
bidRequestId,
bidderUserId,
clientObservedBidRoundId: payload.clientObservedBidRoundId,
clientObservedAuctionLifecycleId:
payload.clientObservedAuctionLifecycleId,
@@ -573,14 +588,13 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
this.readHandshakeUserId(socket),
);
if (fallback) {
socket.data.user = fallback.user;
socket.data.devUser = fallback.user;
socket.data.identity = fallback.identity;
return;
}
const token = this.readHandshakeToken(socket);
if (!token) {
// 임시 운영용: 경매 진행 중에는 로그인 없이도 관전/팀장 모드 선택/입찰을 허용한다.
return;
}
@@ -622,14 +636,22 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
socket: AuctionSocket,
matchId: string,
): Promise<void> {
if (socket.data.user || !socket.data.identity) return;
const devUser = socket.data.devUser;
const identity = socket.data.identity;
if (!devUser && !identity) return;
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(matchId).select({
communityId: 1,
});
if (!match) return;
if (devUser) {
socket.data.user = devUser.communityId.equals(match.communityId)
? devUser
: undefined;
return;
}
if (!identity) return;
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findOne({
@@ -1,5 +1,6 @@
import {
BadRequestException,
ForbiddenException,
ConflictException,
Injectable,
InternalServerErrorException,
@@ -795,6 +796,10 @@ export class AuctionService {
}
const team = this.findAuctionTeamByIndex(auction, params.teamIndex);
if (!team) throw new BadRequestException('Unknown team.');
this.assertBidderIsCaptain(
params.bidderUserId,
team.captainUserId.toString(),
);
if (params.amount <= auction.currentBid) {
throw new BadRequestException('Bid must exceed current bid.');
}
@@ -807,8 +812,6 @@ export class AuctionService {
'Bid must reserve minimum points for remaining slots.',
);
}
// 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다.
await this.recordSnapshot(auction, 'bid', params.bidderUserId);
auction.currentBid = params.amount;
auction.currentBidderTeamIndex = params.teamIndex;
@@ -929,6 +932,10 @@ export class AuctionService {
if (!bidContext.bidderTeamCaptainUserId) {
throw new BadRequestException('Unknown team.');
}
this.assertBidderIsCaptain(
params.bidderUserId,
bidContext.bidderTeamCaptainUserId,
);
const auctionLifecycleId =
params.clientObservedAuctionLifecycleId ?? bidContext.auctionLifecycleId;
@@ -1005,6 +1012,10 @@ export class AuctionService {
(entry) => Number(entry.teamIndex) === params.teamIndex,
);
if (!team) throw new BadRequestException('Unknown team.');
this.assertBidderIsCaptain(
params.bidderUserId,
this.stringFromState(team.captainUserId),
);
const auctionLifecycleId =
params.clientObservedAuctionLifecycleId ??
@@ -2906,6 +2917,15 @@ export class AuctionService {
return auction.teams.find((team) => team.teamIndex === teamIndex);
}
private assertBidderIsCaptain(
bidderUserId: mongoose.Types.ObjectId | undefined,
captainUserId: string,
) {
if (bidderUserId && bidderUserId.toString() !== captainUserId) {
throw new ForbiddenException('해당 팀의 팀장만 입찰할 수 있습니다.');
}
}
private createDeadline(secondsFromNow: number): Date {
return new Date(Date.now() + secondsFromNow * 1000);
}
@@ -0,0 +1,198 @@
import { Logger } from '@nestjs/common';
import { CommunityStatsCacheService } from './community-stats-cache.service';
describe('Community stats cache invalidation retries', () => {
let service: CommunityStatsCacheService;
let invalidate: jest.SpyInstance<Promise<number>, [string, number?]>;
beforeEach(() => {
jest.useFakeTimers();
jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
service = new CommunityStatsCacheService({} as never);
invalidate = jest
.spyOn(service, 'invalidateCommunity')
.mockRejectedValue(new Error('Redis down'));
});
afterEach(() => {
service.onModuleDestroy();
jest.restoreAllMocks();
jest.useRealTimers();
});
it('returns true even when successful invalidation deletes no cache entries', async () => {
invalidate.mockResolvedValue(0);
expect(await service.invalidateCommunityWithRetry('community')).toBe(true);
expect(invalidate).toHaveBeenCalledWith('community', 1_000);
expect(jest.getTimerCount()).toBe(0);
});
it('returns false immediately, then retries at most three times with increasing delays', async () => {
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
expect(invalidate).toHaveBeenCalledTimes(1);
for (const [index, delay] of [1_000, 5_000, 30_000].entries()) {
await jest.advanceTimersByTimeAsync(delay - 1);
expect(invalidate).toHaveBeenCalledTimes(index + 1);
await jest.advanceTimersByTimeAsync(1);
expect(invalidate).toHaveBeenCalledTimes(index + 2);
}
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(4);
expect(Logger.prototype.warn).toHaveBeenCalledWith(
expect.stringContaining('retries exhausted for community'),
);
});
it('does not reset the scheduled delay or remaining budget after another immediate failure', async () => {
await service.invalidateCommunityWithRetry('community');
await jest.advanceTimersByTimeAsync(1_000);
expect(invalidate).toHaveBeenCalledTimes(2);
await jest.advanceTimersByTimeAsync(2_000);
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
expect(jest.getTimerCount()).toBe(1);
await jest.advanceTimersByTimeAsync(2_999);
expect(invalidate).toHaveBeenCalledTimes(3);
await jest.advanceTimersByTimeAsync(1);
expect(invalidate).toHaveBeenCalledTimes(4);
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
await jest.advanceTimersByTimeAsync(30_000);
expect(invalidate).toHaveBeenCalledTimes(6);
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(6);
});
it.each(['immediate', 'background'] as const)(
'cancels remaining retries after a successful %s attempt',
async (attempt) => {
await service.invalidateCommunityWithRetry('community');
invalidate.mockResolvedValue(0);
if (attempt === 'immediate') {
expect(await service.invalidateCommunityWithRetry('community')).toBe(
true,
);
} else {
await jest.advanceTimersByTimeAsync(1_000);
}
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(2);
},
);
it('unrefs every retry timer so it does not keep the process alive', async () => {
const setTimeoutSpy = jest.spyOn(global, 'setTimeout');
await service.invalidateCommunityWithRetry('community');
for (const delay of [1_000, 5_000, 30_000]) {
const timer = setTimeoutSpy.mock.results.at(-1)!.value as NodeJS.Timeout;
expect(timer.hasRef()).toBe(false);
await jest.advanceTimersByTimeAsync(delay);
}
});
it('keeps different communities independent when one continues to fail', async () => {
await service.invalidateCommunityWithRetry('first');
await service.invalidateCommunityWithRetry('second');
invalidate.mockImplementation(async (id) => {
if (id === 'first') throw new Error('still unavailable');
return 1;
});
await jest.advanceTimersByTimeAsync(36_000);
expect(invalidate.mock.calls.filter(([id]) => id === 'first')).toHaveLength(
4,
);
expect(
invalidate.mock.calls.filter(([id]) => id === 'second'),
).toHaveLength(2);
expect(jest.getTimerCount()).toBe(0);
});
it('clears scheduled retries on shutdown', async () => {
await service.invalidateCommunityWithRetry('community');
service.onModuleDestroy();
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(1);
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
expect(invalidate).toHaveBeenCalledTimes(1);
});
it.each(['shutdown', 'immediate success'] as const)(
'does not reschedule an in-flight retry after %s',
async (finish) => {
await service.invalidateCommunityWithRetry('community');
const pending = deferred();
invalidate.mockImplementationOnce(() => pending.promise);
await jest.advanceTimersByTimeAsync(1_000);
expect(invalidate).toHaveBeenCalledTimes(2);
if (finish === 'shutdown') {
service.onModuleDestroy();
} else {
invalidate.mockResolvedValueOnce(1);
expect(await service.invalidateCommunityWithRetry('community')).toBe(
true,
);
}
pending.reject(new Error('late failure'));
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(finish === 'shutdown' ? 2 : 3);
expect(jest.getTimerCount()).toBe(0);
},
);
it('does not cancel a newer failed request when an older immediate attempt succeeds late', async () => {
const pending = deferred();
invalidate.mockImplementationOnce(() => pending.promise);
const first = service.invalidateCommunityWithRetry('community');
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
pending.resolve(1);
expect(await first).toBe(true);
expect(jest.getTimerCount()).toBe(1);
invalidate.mockResolvedValue(1);
await jest.advanceTimersByTimeAsync(1_000);
expect(invalidate).toHaveBeenCalledTimes(3);
expect(jest.getTimerCount()).toBe(0);
});
it('preserves the retry budget when an immediate request fails during an in-flight retry', async () => {
await service.invalidateCommunityWithRetry('community');
const pending = deferred();
invalidate.mockImplementationOnce(() => pending.promise);
await jest.advanceTimersByTimeAsync(1_000);
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
await jest.advanceTimersByTimeAsync(5_000);
expect(invalidate).toHaveBeenCalledTimes(3);
pending.resolve(1);
await jest.advanceTimersByTimeAsync(5_000);
expect(invalidate).toHaveBeenCalledTimes(4);
await jest.advanceTimersByTimeAsync(30_000);
expect(invalidate).toHaveBeenCalledTimes(5);
expect(jest.getTimerCount()).toBe(0);
});
it('does not restart an exhausted budget when an older immediate request fails late', async () => {
await service.invalidateCommunityWithRetry('community');
await jest.advanceTimersByTimeAsync(6_000);
const pending = deferred();
invalidate.mockImplementationOnce(() => pending.promise);
const immediate = service.invalidateCommunityWithRetry('community');
await jest.advanceTimersByTimeAsync(30_000);
expect(invalidate).toHaveBeenCalledTimes(5);
pending.reject(new Error('late failure'));
expect(await immediate).toBe(false);
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(5);
});
});
function deferred() {
let resolve!: (value: number) => void;
let reject!: (reason: Error) => void;
const promise = new Promise<number>((done, fail) => {
resolve = done;
reject = fail;
});
return { promise, resolve, reject };
}
@@ -1,9 +1,15 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
import { randomUUID } from 'crypto';
import { RedisService } from '../global/redis/redis.service';
const COMMUNITY_STATS_TTL_SECONDS = 5 * 60;
const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60;
const INVALIDATION_RETRY_DELAYS_MS = [1_000, 5_000, 30_000] as const;
interface InvalidationRetry {
attempts: number;
requestVersion: number;
timer?: NodeJS.Timeout;
}
const CACHE_SCOPES = [
'matches',
'leaderboard',
@@ -64,11 +70,105 @@ return deleted
`;
@Injectable()
export class CommunityStatsCacheService {
export class CommunityStatsCacheService implements OnModuleDestroy {
private readonly logger = new Logger(CommunityStatsCacheService.name);
private readonly invalidationRetries = new Map<string, InvalidationRetry>();
private destroyed = false;
constructor(private readonly redisService: RedisService) {}
public onModuleDestroy(): void {
this.destroyed = true;
for (const pending of this.invalidationRetries.values()) {
if (pending.timer) clearTimeout(pending.timer);
}
this.invalidationRetries.clear();
}
// Only the immediate attempt determines whether the caller may cache its response.
public async invalidateCommunityWithRetry(
communityId: string,
): Promise<boolean> {
if (this.destroyed) return false;
const pending = this.invalidationRetries.get(communityId) ?? {
attempts: 0,
requestVersion: 0,
};
this.invalidationRetries.set(communityId, pending);
const version = ++pending.requestVersion;
const succeeded = await this.tryInvalidateCommunity(communityId);
if (succeeded && pending.requestVersion === version) {
this.clearInvalidationRetry(communityId, pending);
} else if (!succeeded) {
// An existing retry keeps its remaining budget, including while in flight.
this.scheduleInvalidationRetry(communityId, pending);
}
return succeeded;
}
private scheduleInvalidationRetry(
communityId: string,
pending: InvalidationRetry,
): void {
if (
this.destroyed ||
this.invalidationRetries.get(communityId) !== pending ||
pending.timer
)
return;
const delay = INVALIDATION_RETRY_DELAYS_MS[pending.attempts];
if (delay === undefined) {
this.clearInvalidationRetry(communityId, pending);
this.logger.warn(
`Stats cache invalidation retries exhausted for ${communityId}; detail recovery and cache expiry will refresh stale responses.`,
);
return;
}
pending.attempts += 1;
pending.timer = setTimeout(
() => void this.retryInvalidation(communityId, pending),
delay,
);
pending.timer.unref();
}
private async retryInvalidation(
communityId: string,
pending: InvalidationRetry,
): Promise<void> {
const version = pending.requestVersion;
const succeeded = await this.tryInvalidateCommunity(communityId);
if (this.invalidationRetries.get(communityId) !== pending) return;
pending.timer = undefined;
// An older completion must not cancel a newer request's retry.
if (succeeded && pending.requestVersion === version) {
this.clearInvalidationRetry(communityId, pending);
} else {
this.scheduleInvalidationRetry(communityId, pending);
}
}
private clearInvalidationRetry(
communityId: string,
pending: InvalidationRetry,
): void {
if (this.invalidationRetries.get(communityId) !== pending) return;
if (pending.timer) clearTimeout(pending.timer);
this.invalidationRetries.delete(communityId);
}
private async tryInvalidateCommunity(communityId: string): Promise<boolean> {
try {
await this.invalidateCommunity(communityId, 1_000);
return true;
} catch (error) {
this.logger.warn(
`Stats cache invalidation failed for ${communityId}: ${String(error)}`,
);
return false;
}
}
public async get<T>(key: CommunityStatsCacheKey): Promise<T | null> {
const reply = await this.redisService
.raw()
@@ -117,19 +217,25 @@ export class CommunityStatsCacheService {
return this.set(key, value, COMMUNITY_STATS_DETAIL_TTL_SECONDS);
}
public async invalidateCommunity(communityId: string): Promise<number> {
public async invalidateCommunity(
communityId: string,
timeoutMs?: number,
): Promise<number> {
const prefix = communityPrefix(communityId);
const deleted = Number(
await this.redisService
.raw()
.sendCommand([
'EVAL',
INVALIDATE_CACHE_SCRIPT,
String(CACHE_SCOPES.length + 1),
`${prefix}:generation`,
...CACHE_SCOPES.map((scope) => `${prefix}:${scope}`),
randomUUID(),
]),
.sendCommand(
[
'EVAL',
INVALIDATE_CACHE_SCRIPT,
String(CACHE_SCOPES.length + 1),
`${prefix}:generation`,
...CACHE_SCOPES.map((scope) => `${prefix}:${scope}`),
randomUUID(),
],
timeoutMs === undefined ? undefined : { timeout: timeoutMs },
),
);
if (deleted > 0) {
@@ -0,0 +1,321 @@
import mongoose from 'mongoose';
import { CommunityStatsService } from './community-stats.service';
import { CommunityStatsCacheKey } from './community-stats-cache.service';
import type { InternalMatchDetailResponse } from './community-stats.types';
describe('Community stats raw archive recovery', () => {
it.each([true, false])(
'recovers a cached missing game even if invalidation needs retry (%s)',
async (invalidationSucceeds) => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
let archived = false;
let enriched = false;
let generation = 'before';
let cached: InternalMatchDetailResponse | null = null;
const exists = jest.fn(() => query(archived ? { _id: 'archive' } : null));
const buildAndUpsert = jest.fn(async () => {
enriched = true;
});
const invalidateCommunity = jest.fn(async () => {
if (!invalidationSucceeds) return false;
cached = null;
generation = 'after';
return true;
});
const setDetail = jest.fn(
async (
key: CommunityStatsCacheKey,
value: InternalMatchDetailResponse,
) => {
expect(key.generation).toBe(generation);
cached = value;
},
);
const service = new CommunityStatsService(
{ getModel: async () => ({ exists }) } as never,
{
get: async (key: CommunityStatsCacheKey) => {
key.generation = generation;
return cached;
},
setDetail,
invalidateCommunityWithRetry: invalidateCommunity,
} as never,
{} as never,
{ buildAndUpsert } as never,
);
const internals = service as unknown as {
getDetailRevision: () => Promise<string>;
buildBaseDataset: () => Promise<unknown>;
matchDetailInFlight: Map<string, unknown>;
};
jest
.spyOn(internals, 'getDetailRevision')
.mockResolvedValue('same-revision');
jest
.spyOn(internals, 'buildBaseDataset')
.mockImplementation(async () => ({
matches: [{ matchId: matchId.toString() }],
detailsByMatchId: new Map([
[
matchId.toString(),
[
{
gameNumber: 1,
riotMatchId: 'KR_1',
rawAvailable: enriched,
timelineLoaded: enriched,
teams: [],
},
],
],
]),
competition: {
projection: {
games: [
{
id: 'official-game',
displayNumber: 1,
evidence: { type: 'riot', riotMatchId: 'KR_1' },
},
],
},
},
}));
const missing = await service.getMatchDetail({ communityId, matchId });
expect(missing.games[0].analysisAvailability).toBe('missing');
expect(await service.getMatchDetail({ communityId, matchId })).toBe(
missing,
);
expect(buildAndUpsert).not.toHaveBeenCalled();
archived = true;
const recovered = await service.getMatchDetail({ communityId, matchId });
expect(recovered.games[0]).toMatchObject({
gameId: 'official-game',
analysisAvailability: 'available',
riotMatchId: 'KR_1',
});
expect(buildAndUpsert).toHaveBeenCalledWith(matchId, {
includeTimeline: true,
});
expect(invalidateCommunity).toHaveBeenCalledWith(communityId.toString());
expect(internals.matchDetailInFlight.size).toBe(0);
expect(setDetail).toHaveBeenCalledTimes(invalidationSucceeds ? 2 : 1);
expect(await service.getMatchDetail({ communityId, matchId })).toEqual(
recovered,
);
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
},
);
it('rebuilds only affected missing fragments and invalidates every affected community after the writes', async () => {
const first = new mongoose.Types.ObjectId();
const second = new mongoose.Types.ObjectId();
const fragments = [
{
matchId: new mongoose.Types.ObjectId(),
communityId: first,
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: false }],
},
{
matchId: new mongoose.Types.ObjectId(),
communityId: first,
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: true }],
},
{
matchId: new mongoose.Types.ObjectId(),
communityId: second,
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: false }],
},
];
const order: string[] = [];
const buildAndUpsert = jest.fn(async () => {
order.push('build');
});
const invalidateCommunity = jest.fn(async () => {
order.push('invalidate');
return true;
});
const findByRiotMatchIds = jest.fn().mockResolvedValue(fragments);
const service = new CommunityStatsService(
{
getModel: async () => ({ find: () => query([{ matchId: 'KR_1' }]) }),
} as never,
{ invalidateCommunityWithRetry: invalidateCommunity } as never,
{
findByRiotMatchIds,
findByMatch: async () => ({
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: true }],
}),
} as never,
{ buildAndUpsert } as never,
);
await service.refreshForRiotMatches(['KR_1', 'KR_1', 'KR_ABSENT']);
expect(findByRiotMatchIds).toHaveBeenCalledWith(['KR_1']);
expect(buildAndUpsert.mock.calls).toEqual([
[fragments[0].matchId],
[fragments[2].matchId],
]);
expect(invalidateCommunity.mock.calls).toEqual([
[first.toString()],
[second.toString()],
]);
expect(order).toEqual(['build', 'build', 'invalidate', 'invalidate']);
});
it('does not invalidate already enriched games or builds that make no progress', async () => {
const game = { riotMatchId: 'KR_1', rawAvailable: false };
const fragment = {
matchId: new mongoose.Types.ObjectId(),
communityId: new mongoose.Types.ObjectId(),
gameDetails: [game],
};
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const invalidateCommunity = jest.fn();
const service = new CommunityStatsService(
{
getModel: async () => ({ find: () => query([{ matchId: 'KR_1' }]) }),
} as never,
{ invalidateCommunityWithRetry: invalidateCommunity } as never,
{
findByRiotMatchIds: async () => [fragment],
findByMatch: async () => fragment,
} as never,
{ buildAndUpsert } as never,
);
await service.refreshForRiotMatches(['KR_1']);
game.rawAvailable = true;
await service.refreshForRiotMatches(['KR_1']);
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
expect(invalidateCommunity).not.toHaveBeenCalled();
});
it('does not rebuild when raw is still absent', async () => {
const findByRiotMatchIds = jest.fn();
const buildAndUpsert = jest.fn();
const service = new CommunityStatsService(
{ getModel: async () => ({ find: () => query([]) }) } as never,
{} as never,
{ findByRiotMatchIds } as never,
{ buildAndUpsert } as never,
);
await service.refreshForRiotMatches(['KR_1']);
expect(findByRiotMatchIds).not.toHaveBeenCalled();
expect(buildAndUpsert).not.toHaveBeenCalled();
});
it('invalidates successful communities once even when another game fails mid-batch', async () => {
const communities = Array.from(
{ length: 4 },
() => new mongoose.Types.ObjectId(),
);
const fragments = [0, 1, 0, 2, 3].map((community, index) => ({
matchId: new mongoose.Types.ObjectId(),
communityId: communities[community],
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: index === 4 }],
}));
const buildAndUpsert = jest.fn(async (matchId: mongoose.Types.ObjectId) => {
const fragment = fragments.find((item) => item.matchId === matchId)!;
if (fragment === fragments[1]) throw new Error('one build fails');
fragment.gameDetails[0].rawAvailable = true;
});
const invalidate = jest.fn().mockResolvedValue(true);
const service = new CommunityStatsService(
{
getModel: async () => ({ find: () => query([{ matchId: 'KR_1' }]) }),
} as never,
{ invalidateCommunityWithRetry: invalidate } as never,
{
findByRiotMatchIds: async () => fragments,
findByMatch: async (id: mongoose.Types.ObjectId) =>
fragments.find((item) => item.matchId === id),
} as never,
{ buildAndUpsert } as never,
);
await service.refreshForRiotMatches(['KR_1']);
expect(buildAndUpsert).toHaveBeenCalledTimes(4);
expect(invalidate.mock.calls).toEqual([
[communities[0].toString()],
[communities[2].toString()],
]);
});
it('backs off raw recovery that makes no progress and does not invalidate the community', async () => {
let now = 1000;
const clock = jest.spyOn(Date, 'now').mockImplementation(() => now);
try {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
let cached: InternalMatchDetailResponse | null = null;
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const invalidate = jest.fn();
const service = new CommunityStatsService(
{
getModel: async () => ({ exists: () => query({ _id: 'archive' }) }),
} as never,
{
get: async () => cached,
setDetail: async (
_key: unknown,
value: InternalMatchDetailResponse,
) => {
cached = value;
},
invalidateCommunityWithRetry: invalidate,
} as never,
{} as never,
{ buildAndUpsert } as never,
);
const internals = service as unknown as {
getDetailRevision: () => Promise<string>;
buildBaseDataset: () => Promise<unknown>;
};
jest
.spyOn(internals, 'getDetailRevision')
.mockResolvedValue('same-revision');
jest.spyOn(internals, 'buildBaseDataset').mockResolvedValue({
matches: [{ matchId: matchId.toString() }],
detailsByMatchId: new Map([
[
matchId.toString(),
[
{
gameNumber: 1,
riotMatchId: 'KR_1',
rawAvailable: false,
timelineLoaded: false,
teams: [],
},
],
],
]),
});
await service.getMatchDetail({ communityId, matchId });
await service.getMatchDetail({ communityId, matchId });
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
now += 60_000;
await service.getMatchDetail({ communityId, matchId });
expect(buildAndUpsert).toHaveBeenCalledTimes(2);
expect(invalidate).not.toHaveBeenCalled();
} finally {
clock.mockRestore();
}
});
});
function query<T>(value: T) {
return {
select() {
return this;
},
lean() {
return this;
},
exec: async () => value,
};
}
@@ -1,4 +1,10 @@
import { Controller, Get, Param, Query } from '@nestjs/common';
import {
BadRequestException,
Controller,
Get,
Param,
Query,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
@@ -9,6 +15,15 @@ import type { CommunityStatsFilters } from './community-stats.types';
export class CommunityStatsController {
constructor(private readonly communityStatsService: CommunityStatsService) {}
@Get('internal-stats/seasons')
@AllowPublicAccess()
public getSeasons(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
) {
return this.communityStatsService.getSeasons(communityId);
}
@Get('internal-stats/matches')
@AllowPublicAccess()
public getMatches(
@@ -20,7 +35,30 @@ export class CommunityStatsController {
@Query('championId') championId?: string,
@Query('cursor') cursor?: string,
@Query('limit') limit?: string,
@Query('q') query?: string,
@Query('format') format?: string,
@Query('playerId') playerId?: string,
@Query('cursorMatchId') cursorMatchId?: string,
) {
if (format !== undefined && format !== 'pair' && format !== 'tournament') {
throw new BadRequestException('Invalid format.');
}
if (playerId !== undefined && !mongoose.isObjectIdOrHexString(playerId)) {
throw new BadRequestException('Invalid playerId.');
}
if (
cursorMatchId !== undefined &&
(!mongoose.isObjectIdOrHexString(cursorMatchId) ||
this.toNumber(cursor) === undefined)
) {
throw new BadRequestException('Invalid cursor.');
}
if (
cursor !== undefined &&
Number.isNaN(new Date(this.toNumber(cursor) ?? NaN).getTime())
) {
throw new BadRequestException('Invalid cursor.');
}
return this.communityStatsService.getMatches({
communityId,
filters: this.toFilters({
@@ -30,6 +68,10 @@ export class CommunityStatsController {
championId,
cursor,
limit,
query,
format,
playerId,
cursorMatchId,
}),
});
}
@@ -43,10 +85,11 @@ export class CommunityStatsController {
@Query('from') from?: string,
@Query('to') to?: string,
@Query('championId') championId?: string,
@Query('q') query?: string,
) {
return this.communityStatsService.getLeaderboard({
communityId,
filters: this.toFilters({ seasonId, from, to, championId }),
filters: this.toFilters({ seasonId, from, to, championId, query }),
});
}
@@ -110,7 +153,17 @@ export class CommunityStatsController {
championId?: string;
cursor?: string;
limit?: string;
query?: string;
format?: CommunityStatsFilters['format'];
playerId?: string;
cursorMatchId?: string;
}): CommunityStatsFilters {
if (
params.query !== undefined &&
(typeof params.query !== 'string' || params.query.length > 100)
) {
throw new BadRequestException('Invalid search query.');
}
return {
seasonId: params.seasonId,
from: params.from,
@@ -118,6 +171,10 @@ export class CommunityStatsController {
championId: this.toNumber(params.championId),
cursor: this.toNumber(params.cursor),
limit: this.toNumber(params.limit),
query: params.query?.trim(),
format: params.format,
playerId: params.playerId,
cursorMatchId: params.cursorMatchId,
};
}
@@ -1,4 +1,4 @@
import { Module } from '@nestjs/common';
import { forwardRef, Module } from '@nestjs/common';
import { RiotModule } from '../riot/riot.module';
import { CommunityStatsCacheService } from './community-stats-cache.service';
import { CommunityStatsController } from './community-stats.controller';
@@ -8,7 +8,7 @@ import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
@Module({
imports: [RiotModule],
imports: [forwardRef(() => RiotModule)],
controllers: [CommunityStatsController],
providers: [
CommunityStatsService,
@@ -86,6 +86,244 @@ function record(matchId: mongoose.Types.ObjectId): InternalRecord {
}
describe('CommunityStatsService', () => {
it('reads the official result again on a filtered page cache hit and excludes games from stale revisions', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const playerId = new mongoose.Types.ObjectId().toString();
const scheduledAt = new Date('2026-06-18T12:00:00Z');
const matchCard = {
matchId: matchId.toString(),
scheduledAt: scheduledAt.toISOString(),
games: [{ gameNumber: 1, winnerTeamIndex: 1 }],
};
const findMatchPage = jest.fn().mockResolvedValue([
{
matchId,
scheduledAt,
matchCard,
gameDetails: [{ gameNumber: 1, gameCreation: 1000 }],
sourceCompetitionId: competitionId,
sourceRevision: 4,
},
{ matchId: new mongoose.Types.ObjectId() },
]);
const source = {
_id: competitionId,
matchId,
communityId,
revision: 4,
createdAt: scheduledAt,
updatedAt: scheduledAt,
teams: [],
projection: {
phase: 'completed',
formatType: 'double-elimination',
series: [],
outcome: { type: 'double-elimination', championTeamId: 'winner' },
},
};
const find = jest.fn().mockReturnValue({
select: () => ({ lean: () => ({ exec: async () => [source] }) }),
});
let cachedPage: unknown = null;
const service = new CommunityStatsService(
{
getModel: async (name: string) =>
name === 'community'
? { findById: () => ({ exec: async () => ({ _id: communityId }) }) }
: { find },
} as unknown as ConnectionService,
{
get: async () => cachedPage,
set: async (_key: unknown, page: unknown) => {
cachedPage = JSON.parse(JSON.stringify(page));
},
} as unknown as CommunityStatsCacheService,
{ findMatchPage } as unknown as MatchStatsRepository,
{} as MatchStatsService,
);
jest
.spyOn(
service as unknown as {
repairCommunityFragments: () => Promise<number>;
},
'repairCommunityFragments',
)
.mockResolvedValue(0);
const params = {
communityId,
filters: {
seasonId: 'all',
query: '결승',
format: 'tournament' as const,
playerId,
limit: 1,
},
};
const initial = await service.getMatches(params);
expect(initial.matches[0]).toMatchObject({
games: [{ gameNumber: 1 }],
resultPresentation: {
type: 'official',
phase: 'completed',
sourceRevision: 4,
outcome: { championTeamId: 'winner' },
},
});
Object.assign(source, {
revision: 5,
projection: {
...source.projection,
phase: 'running',
outcome: undefined,
},
});
const result = await service.getMatches(params);
expect(findMatchPage).toHaveBeenCalledWith(
expect.objectContaining({
query: '결승',
format: 'tournament',
playerId,
limit: 2,
}),
);
expect(find).toHaveBeenCalledWith({
communityId,
matchId: { $in: [matchId] },
});
expect(findMatchPage).toHaveBeenCalledTimes(1);
expect(find).toHaveBeenCalledTimes(2);
expect(result.matches[0]).toMatchObject({
games: [],
resultPresentation: {
type: 'official',
competitionId: competitionId.toString(),
sourceRevision: 5,
phase: 'running',
},
});
expect(result.nextCursor).toBe(scheduledAt.getTime());
expect(result.nextCursorMatchId).toBe(matchId.toString());
});
it.each(['legacy', 'riot', 'unlinked'] as const)(
'preserves the scoreboard without retrying a missing Riot archive for %s evidence',
async (type) => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match = { matchId: matchId.toString() };
const participant = record(matchId);
const matchKey = type === 'legacy' ? 'legacy-reference' : 'KR_1';
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const set = jest.fn();
const setDetail = jest.fn();
const service = new CommunityStatsService(
{
getModel: async () => ({ exists: () => ({ exec: async () => null }) }),
} as unknown as ConnectionService,
{
get: async () => null,
set,
setDetail,
} as unknown as CommunityStatsCacheService,
{} as MatchStatsRepository,
{ buildAndUpsert } as unknown as MatchStatsService,
);
jest
.spyOn(
service as unknown as { getDetailRevision: () => Promise<string> },
'getDetailRevision',
)
.mockResolvedValue('revision-1');
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
jest.fn().mockResolvedValue({
matches: [match],
detailsByMatchId: new Map([
[
match.matchId,
[
{
gameNumber: 1,
riotMatchId: matchKey,
gameCreation: 1000,
gameDuration: 1800,
rawAvailable: false,
timelineLoaded: false,
teams: [
{
teamIndex: 1,
side: 'blue',
win: true,
objectives: objectives(),
participants: [participant],
},
],
},
],
],
]),
competition:
type === 'unlinked'
? undefined
: {
projection: {
games: [
{
id: 'game-1',
seriesId: 'series-1',
gameSlotId: 'slot-1',
ordinal: 1,
displayNumber: 1,
evidence:
type === 'legacy'
? { type, legacyReference: matchKey }
: { type, riotMatchId: matchKey },
},
],
},
},
});
const response = await service.getMatchDetail({ communityId, matchId });
const afterCacheMiss = await service.getMatchDetail({
communityId,
matchId,
});
expect(response.games).toHaveLength(1);
expect(response.games).toMatchObject([
{
...(type === 'unlinked' ? {} : { gameId: 'game-1' }),
analysisAvailability: 'missing',
teams: [
{
win: true,
participants: [
{
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
championId: participant.championId,
},
],
},
],
},
]);
expect(afterCacheMiss).toEqual(response);
expect(buildAndUpsert).not.toHaveBeenCalled();
expect(set).not.toHaveBeenCalled();
expect(setDetail).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenCalledWith(
expect.objectContaining({ field: expect.stringContaining(':r8:') }),
response,
);
},
);
it('ignores detail caches missing unified events or containing invalid checkpoints', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
@@ -222,7 +460,13 @@ describe('CommunityStatsService', () => {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<MatchStatsService>;
const service = new CommunityStatsService(
{} as ConnectionService,
{
getModel: jest.fn().mockResolvedValue({
findOne: () => ({
select: () => ({ lean: () => ({ exec: async () => null }) }),
}),
}),
} as unknown as ConnectionService,
cacheService,
{} as MatchStatsRepository,
matchStatsService,
@@ -284,7 +528,7 @@ describe('CommunityStatsService', () => {
expect(setDetail).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenNthCalledWith(
2,
expect.objectContaining({ field: expect.stringContaining(':r4:') }),
expect.objectContaining({ field: expect.stringContaining(':r8:') }),
invalidCheckpointResponse,
);
});
@@ -309,6 +553,7 @@ describe('CommunityStatsService', () => {
gameCreation: 1_000,
gameDuration: 1_800,
winnerSide: 'blue',
rawAvailable: true,
timelineLoaded: false,
timeline: [],
objectiveEvents: [],
@@ -361,7 +606,13 @@ describe('CommunityStatsService', () => {
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const service = new CommunityStatsService(
{} as ConnectionService,
{
getModel: jest.fn().mockResolvedValue({
findOne: () => ({
select: () => ({ lean: () => ({ exec: async () => null }) }),
}),
}),
} as unknown as ConnectionService,
cacheService,
{} as MatchStatsRepository,
{ buildAndUpsert } as unknown as MatchStatsService,
@@ -378,9 +629,13 @@ describe('CommunityStatsService', () => {
const backedOff = await service.getMatchDetail({ communityId, matchId });
expect(backedOff).toBe(fallback);
expect(fallback.games[0].analysisAvailability).toBe('available');
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
expect(buildAndUpsert).toHaveBeenCalledWith(matchId, {
includeTimeline: true,
});
expect(set).toHaveBeenCalledWith(
expect.objectContaining({ field: expect.stringContaining(':r4:') }),
expect.objectContaining({ field: expect.stringContaining(':r8:') }),
fallback,
60,
);
@@ -392,7 +647,7 @@ describe('CommunityStatsService', () => {
expect(buildAndUpsert).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenCalledTimes(1);
expect(setDetail).toHaveBeenCalledWith(
expect.objectContaining({ field: expect.stringContaining(':r4:') }),
expect.objectContaining({ field: expect.stringContaining(':r8:') }),
recovered,
);
});
@@ -459,7 +714,13 @@ describe('CommunityStatsService', () => {
setDetail,
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const service = new CommunityStatsService(
{} as ConnectionService,
{
getModel: jest.fn().mockResolvedValue({
findOne: () => ({
select: () => ({ lean: () => ({ exec: async () => null }) }),
}),
}),
} as unknown as ConnectionService,
cacheService,
{} as MatchStatsRepository,
{} as MatchStatsService,
@@ -1,3 +1,9 @@
import type {
CompetitionGameView,
GameAnalysisAvailability,
InternalMatchCompetition,
InternalMatchResultPresentation,
} from '@lolympus/contracts';
import {
BadRequestException,
Injectable,
@@ -5,8 +11,14 @@ import {
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { presentCompetitionDetail } from '../competition/competition.presenter';
import type { Competition } from '../competition/competition.schema';
import { ConnectionService } from '../global/database/connection.service';
import type { CommunityDocument, RiotLane } from '../global/database/schema';
import type {
CommunityDocument,
MatchStatsDocument,
RiotLane,
} from '../global/database/schema';
import type {
HistorySeasonDto,
RecentMatchView,
@@ -43,7 +55,7 @@ const DEFAULT_LIST_LIMIT = 20;
const MAX_LIST_LIMIT = 50;
const MAX_MATCH_SCAN = 300;
const MIN_HIGHLIGHT_GAMES = 5;
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 4;
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 8;
const INCOMPLETE_MATCH_DETAIL_TTL_SECONDS = 60;
interface CommunityStatsContext {
@@ -58,6 +70,15 @@ interface BaseDataset {
matches: InternalMatchCardView[];
records: InternalRecord[];
detailsByMatchId: Map<string, InternalGameDetail[]>;
competition?: InternalMatchCompetition;
}
interface CachedMatchPage extends Omit<InternalMatchListResponse, 'matches'> {
cards: Array<{
card: InternalMatchCardView;
sourceCompetitionId?: string;
sourceRevision?: number;
}>;
}
@Injectable()
@@ -71,6 +92,8 @@ export class CommunityStatsService {
string,
Promise<UserInternalHistoryResponse>
>();
private readonly fragmentRepairs = new Map<string, Promise<number>>();
private readonly rawRecoveryRetryAfter = new Map<string, number>();
constructor(
private readonly connectionService: ConnectionService,
@@ -84,67 +107,141 @@ export class CommunityStatsService {
filters: CommunityStatsFilters;
}): Promise<InternalMatchListResponse> {
const key = this.cacheKey('matches', params.communityId, params.filters);
const cached = await this.cacheService.get<InternalMatchListResponse>(key);
if (cached) return cached;
const cached = await this.cacheService.get<CachedMatchPage>(key);
const page =
cached ?? (await this.loadMatchPage(params.communityId, params.filters));
if (!cached) await this.cacheService.set(key, page);
const { cards, ...pagination } = page;
if (cards.length === 0) return { ...pagination, matches: [] };
const matchIds = cards.map(
({ card }) => new mongoose.Types.ObjectId(card.matchId),
);
const CompetitionModel =
await this.connectionService.getModel('competition');
const competitions = await CompetitionModel.find({
communityId: params.communityId,
matchId: { $in: matchIds },
})
.select({
matchId: 1,
communityId: 1,
schemaVersion: 1,
revision: 1,
phase: 1,
format: 1,
createdAt: 1,
updatedAt: 1,
'teams.teamId': 1,
'teams.name': 1,
'teams.displayOrder': 1,
'projection.phase': 1,
'projection.formatType': 1,
'projection.outcome': 1,
'projection.series': 1,
})
.lean()
.exec();
const official = new Map(
competitions.map((competition) => [
competition.matchId.toString(),
this.presentOfficialResult(competition),
]),
);
return {
...pagination,
matches: cards.map(({ card, sourceCompetitionId, sourceRevision }) => {
const resultPresentation = official.get(card.matchId) ?? {
type: sourceCompetitionId
? ('unavailable' as const)
: ('legacy' as const),
};
const canUseGames =
resultPresentation.type === 'legacy' ||
(resultPresentation.type === 'official' &&
sourceCompetitionId === resultPresentation.competitionId &&
sourceRevision === resultPresentation.sourceRevision);
return {
...(canUseGames ? card : this.adjustCardForRange(card, [])),
resultPresentation,
};
}),
};
}
private async loadMatchPage(
communityId: mongoose.Types.ObjectId,
filters: CommunityStatsFilters,
): Promise<CachedMatchPage> {
const limit = this.clampLimit(
params.filters.limit,
filters.limit,
DEFAULT_LIST_LIMIT,
MAX_LIST_LIMIT,
);
const dataset = await this.buildBaseDataset(
params.communityId,
params.filters,
);
const filtered = params.filters.championId
? dataset.matches.filter((match) =>
dataset.records.some(
(record) =>
record.matchId === match.matchId &&
record.championId === params.filters.championId,
),
)
: dataset.matches;
const cursor = params.filters.cursor;
const page = filtered
.filter(
(match) => !cursor || new Date(match.scheduledAt).getTime() < cursor,
)
.slice(0, limit + 1);
const context = await this.resolveContext(communityId, filters);
await this.repairCommunityFragments(communityId);
const page = await this.matchStatsRepository.findMatchPage({
...filters,
communityId,
from: context.from?.getTime(),
to: context.to?.getTime(),
limit: limit + 1,
});
const visible = page.slice(0, limit);
const response: InternalMatchListResponse = {
matches: visible,
nextCursor:
page.length > limit
? new Date(visible[visible.length - 1]?.scheduledAt ?? 0).getTime()
: null,
season: dataset.season,
const last = page.length > limit ? visible.at(-1) : undefined;
return {
cards: visible.map((fragment) => ({
card: this.adjustCardForRange(
fragment.matchCard as unknown as InternalMatchCardView,
(fragment.gameDetails ?? []).filter((game) =>
this.isGameInRange(game.gameCreation, context),
),
),
sourceCompetitionId: fragment.sourceCompetitionId?.toString(),
sourceRevision: fragment.sourceRevision,
})),
nextCursor: last?.scheduledAt.getTime() ?? null,
nextCursorMatchId: last?.matchId.toString(),
season: context.season,
};
await this.cacheService.set(key, response);
return response;
}
public async getSeasons(communityId: mongoose.Types.ObjectId) {
const { community } = await this.resolveContext(communityId, {});
return { seasons: this.resolveSeasons(community) };
}
public async getLeaderboard(params: {
communityId: mongoose.Types.ObjectId;
filters: CommunityStatsFilters;
}): Promise<LeaderboardResponse> {
const key = this.cacheKey(
'leaderboard',
params.communityId,
params.filters,
);
const cached = await this.cacheService.get<LeaderboardResponse>(key);
if (cached) return cached;
const dataset = await this.buildBaseDataset(
params.communityId,
params.filters,
);
const records = this.applyChampionFilter(dataset.records, params.filters);
const rows = this.buildLeaderboardRows(records);
const response = { rows, season: dataset.season };
await this.cacheService.set(key, response);
return response;
const { query, ...filters } = params.filters;
const key = this.cacheKey('leaderboard', params.communityId, filters);
let response = await this.cacheService.get<LeaderboardResponse>(key);
if (!response) {
const dataset = await this.buildSeasonDataset(
params.communityId,
filters,
);
const records = this.applyChampionFilter(dataset.records, filters);
response = {
rows: this.buildLeaderboardRows(records),
season: dataset.season,
};
await this.cacheService.set(key, response);
}
const keyword = query?.toLocaleLowerCase('ko-KR');
if (!keyword) return response;
return {
...response,
matchedUserIds: response.rows
.filter(({ summonerName, tagLine }) =>
(tagLine ? summonerName + '#' + tagLine : summonerName)
.toLocaleLowerCase('ko-KR')
.includes(keyword),
)
.map(({ userId }) => userId),
};
}
public async getTeamInsights(params: {
@@ -159,13 +256,13 @@ export class CommunityStatsService {
const cached = await this.cacheService.get<TeamInsightsResponse>(key);
if (cached) return cached;
const dataset = await this.buildBaseDataset(
const dataset = await this.buildSeasonDataset(
params.communityId,
params.filters,
);
const records = this.applyChampionFilter(dataset.records, params.filters);
const rows = this.buildLeaderboardRows(records);
const gameDetails = [...dataset.detailsByMatchId.values()].flat();
const gameDetails = dataset.gameDetails;
const blueGames = gameDetails.length;
const redGames = gameDetails.length;
const blueWins = gameDetails.filter(
@@ -174,6 +271,7 @@ export class CommunityStatsService {
const redWins = gameDetails.filter(
(game) => game.winnerSide === 'red',
).length;
const confirmedGames = blueWins + redWins;
const response: TeamInsightsResponse = {
season: dataset.season,
@@ -182,6 +280,11 @@ export class CommunityStatsService {
red: this.percent(redWins, redGames),
bluePicks: blueGames,
redPicks: redGames,
confirmed: {
sampleSize: confirmedGames,
blue: this.percent(blueWins, confirmedGames),
red: this.percent(redWins, confirmedGames),
},
},
topKda: this.toHighlight(
rows
@@ -222,29 +325,56 @@ export class CommunityStatsService {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
}): Promise<InternalMatchDetailResponse> {
const revision = await this.getDetailRevision(
params.communityId,
params.matchId,
);
const key = new CommunityStatsCacheKey(
params.communityId.toString(),
'matchDetail',
`v${MATCH_STATS_BUILDER_VERSION}:r${MATCH_DETAIL_RESPONSE_CACHE_VERSION}:${params.matchId.toString()}`,
`v${MATCH_STATS_BUILDER_VERSION}:r${MATCH_DETAIL_RESPONSE_CACHE_VERSION}:${params.matchId.toString()}:${revision}`,
);
const cached =
await this.cacheService.get<InternalMatchDetailResponse>(key);
if (cached && isCompleteMatchDetailResponse(cached)) return cached;
if (
cached &&
isCompleteMatchDetailResponse(cached) &&
(!this.canRetryRawRecovery(key) ||
!(await this.hasArchivedMissingRaw(cached.games, cached.competition)))
) {
return cached;
}
const inFlight = this.matchDetailInFlight.get(key.identity);
const identity = key.identity;
const inFlight = this.matchDetailInFlight.get(identity);
if (inFlight) return inFlight;
const promise = this.buildMatchDetailResponse(params, key);
this.matchDetailInFlight.set(key.identity, promise);
this.matchDetailInFlight.set(identity, promise);
try {
return await promise;
} finally {
if (this.matchDetailInFlight.get(key.identity) === promise) {
this.matchDetailInFlight.delete(key.identity);
if (this.matchDetailInFlight.get(identity) === promise) {
this.matchDetailInFlight.delete(identity);
}
}
}
private async getDetailRevision(
communityId: mongoose.Types.ObjectId,
matchId: mongoose.Types.ObjectId,
): Promise<string> {
const CompetitionModel =
await this.connectionService.getModel('competition');
const source = await CompetitionModel.findOne({ communityId, matchId })
.select({ _id: 1, revision: 1, projectorVersion: 1 })
.lean()
.exec();
return source
? `${source._id.toString()}:${source.revision}:${source.projectorVersion}`
: 'legacy';
}
private async buildMatchDetailResponse(
params: {
communityId: mongoose.Types.ObjectId;
@@ -252,27 +382,101 @@ export class CommunityStatsService {
},
key: CommunityStatsCacheKey,
): Promise<InternalMatchDetailResponse> {
const dataset = await this.buildBaseDataset(params.communityId, {
seasonId: 'all',
});
const match = dataset.matches.find(
let dataset = await this.buildBaseDataset(
params.communityId,
{
seasonId: 'all',
},
params.matchId,
);
let match = dataset.matches.find(
(item) => item.matchId === params.matchId.toString(),
);
if (!match) throw new NotFoundException('Internal match not found.');
let gameDetails = dataset.detailsByMatchId.get(match.matchId) ?? [];
if (gameDetails.some((game) => game.timelineLoaded !== true)) {
let games = linkDetailGames(dataset, match.matchId);
const missingBefore = new Set(
games
.filter(
({ analysisAvailability }) => analysisAvailability === 'missing',
)
.map(({ game }) => game.riotMatchId),
);
const rawRestored =
this.canRetryRawRecovery(key) &&
(await this.hasArchivedMissingRaw(
games.map(({ game, official, analysisAvailability }) => ({
riotMatchId: game.riotMatchId,
gameId: official?.id,
analysisAvailability,
})),
dataset.competition,
));
let canCacheResponse = true;
if (rawRestored || games.some(needsDetailHydration)) {
if (rawRestored) this.deferRawRecovery(key);
await this.matchStatsService.buildAndUpsert(params.matchId, {
includeTimeline: true,
});
const refreshedDataset = await this.buildBaseDataset(params.communityId, {
seasonId: 'all',
});
gameDetails = refreshedDataset.detailsByMatchId.get(match.matchId) ?? [];
const refreshedDataset = await this.buildBaseDataset(
params.communityId,
{
seasonId: 'all',
},
params.matchId,
);
const refreshedMatch = refreshedDataset.matches.find(
(item) => item.matchId === params.matchId.toString(),
);
if (!refreshedMatch)
throw new NotFoundException('Internal match not found.');
dataset = refreshedDataset;
match = refreshedMatch;
games = linkDetailGames(dataset, match.matchId);
const rawImproved = games.some(
({ game, analysisAvailability }) =>
missingBefore.has(game.riotMatchId) &&
analysisAvailability === 'available',
);
if (rawImproved) {
canCacheResponse = await this.cacheService.invalidateCommunityWithRetry(
params.communityId.toString(),
);
if (canCacheResponse) {
try {
// Read the new generation before caching the rebuilt response.
await this.cacheService.get(key);
} catch (error) {
canCacheResponse = false;
this.logger.warn(
`Stats detail cache refresh failed: ${String(error)}`,
);
}
}
}
if (
!games.some(
({ game, analysisAvailability }) =>
missingBefore.has(game.riotMatchId) &&
analysisAvailability === 'missing',
)
) {
this.rawRecoveryRetryAfter.delete(key.field);
}
}
const response: InternalMatchDetailResponse = {
match,
games: gameDetails.map((game) => ({
competition: dataset.competition,
games: games.map(({ game, official, analysisAvailability }) => ({
gameNumber: game.gameNumber,
analysisAvailability,
...(official
? {
gameId: official.id,
gameSlotId: official.gameSlotId,
seriesId: official.seriesId,
ordinal: official.ordinal,
}
: {}),
riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
@@ -325,7 +529,12 @@ export class CommunityStatsService {
})),
})),
};
if (gameDetails.every((game) => game.timelineLoaded === true)) {
if (!canCacheResponse) return response;
if (
!games.some(needsDetailHydration) &&
(!dataset.competition ||
response.games.length === dataset.competition.projection.games.length)
) {
await this.cacheService.setDetail(key, response);
} else {
await this.cacheService.set(
@@ -367,65 +576,260 @@ export class CommunityStatsService {
}
}
public async refreshForRiotMatches(riotMatchIds: string[]): Promise<void> {
if (riotMatchIds.length === 0) return;
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const archived = await RiotMatchModel.find({
matchId: { $in: [...new Set(riotMatchIds)] },
'raw.info': { $exists: true },
})
.select({ matchId: 1 })
.lean()
.exec();
const ids = new Set(archived.map((match) => match.matchId));
if (ids.size === 0) return;
const fragments = await this.matchStatsRepository.findByRiotMatchIds([
...ids,
]);
const communityIds = new Map<string, mongoose.Types.ObjectId>();
for (const fragment of fragments) {
const missingIds = new Set(
fragment.gameDetails
.filter(
(game) => ids.has(game.riotMatchId) && game.rawAvailable === false,
)
.map((game) => game.riotMatchId),
);
if (missingIds.size === 0) continue;
try {
// Raw enrichment must run even when the Competition revision is current.
await this.matchStatsService.buildAndUpsert(fragment.matchId);
} catch (error) {
this.logger.warn(
`Stats recovery failed for ${fragment.matchId.toString()}: ${String(error)}`,
);
}
try {
// A builder can return without writing, or fail during post-write checks.
// Only actual enrichment should cause a community-wide invalidation.
const updated = await this.matchStatsRepository.findByMatch(
fragment.matchId,
);
if (
updated?.gameDetails.some(
(game) =>
missingIds.has(game.riotMatchId) && game.rawAvailable === true,
)
) {
communityIds.set(
fragment.communityId.toString(),
fragment.communityId,
);
}
} catch (error) {
this.logger.warn(
`Could not verify stats recovery for ${fragment.matchId.toString()}: ${String(error)}`,
);
}
}
for (const communityId of communityIds.values()) {
await this.cacheService.invalidateCommunityWithRetry(
communityId.toString(),
);
}
}
private canRetryRawRecovery(key: CommunityStatsCacheKey): boolean {
return (this.rawRecoveryRetryAfter.get(key.field) ?? 0) <= Date.now();
}
private deferRawRecovery(key: CommunityStatsCacheKey): void {
const now = Date.now();
for (const [field, retryAt] of this.rawRecoveryRetryAfter) {
if (retryAt <= now) this.rawRecoveryRetryAfter.delete(field);
}
if (this.rawRecoveryRetryAfter.size >= 1000) {
this.rawRecoveryRetryAfter.delete(
this.rawRecoveryRetryAfter.keys().next().value!,
);
}
this.rawRecoveryRetryAfter.set(
key.field,
now + INCOMPLETE_MATCH_DETAIL_TTL_SECONDS * 1000,
);
}
private async hasArchivedMissingRaw(
games: Array<
Pick<
InternalMatchDetailResponse['games'][number],
'riotMatchId' | 'gameId' | 'analysisAvailability'
>
>,
competition?: InternalMatchCompetition,
): Promise<boolean> {
const officialById = new Map(
competition?.projection.games.map((game) => [game.id, game]),
);
const ids = games
.filter(
(game) =>
game.analysisAvailability === 'missing' &&
(!competition ||
(game.gameId &&
officialById.get(game.gameId)?.evidence.type === 'riot')),
)
.map((game) => game.riotMatchId);
if (ids.length === 0) return false;
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
return Boolean(
await RiotMatchModel.exists({
matchId: { $in: ids },
'raw.info': { $exists: true },
}).exec(),
);
}
public invalidateCommunity(
communityId: mongoose.Types.ObjectId,
): Promise<number> {
return this.cacheService.invalidateCommunity(communityId.toString());
}
private async buildBaseDataset(
private async buildSeasonDataset(
communityId: mongoose.Types.ObjectId,
filters: CommunityStatsFilters,
): Promise<BaseDataset> {
) {
const context = await this.resolveContext(communityId, filters);
let fragments = await this.matchStatsRepository.findByCommunity({
await this.repairCommunityFragments(communityId);
const fragments = await this.matchStatsRepository.findSeasonStats({
communityId,
fromGameCreation: context.from?.getTime(),
toGameCreation: context.to?.getTime(),
limit: MAX_MATCH_SCAN,
from: context.from?.getTime(),
to: context.to?.getTime(),
});
const rebuilt = await this.rebuildMissingOrStaleFragments(communityId);
if (rebuilt > 0) {
fragments = await this.matchStatsRepository.findByCommunity({
communityId,
fromGameCreation: context.from?.getTime(),
toGameCreation: context.to?.getTime(),
limit: MAX_MATCH_SCAN,
});
}
const cards: InternalMatchCardView[] = [];
const gameDetails: Array<Pick<InternalGameDetail, 'winnerSide'>> = [];
const records: InternalRecord[] = [];
const detailsByMatchId = new Map<string, InternalGameDetail[]>();
for (const fragment of fragments) {
const filteredGames = fragment.gameDetails
.filter((game) => this.isGameInRange(game.gameCreation, context))
.sort((left, right) => left.gameNumber - right.gameNumber);
if (filteredGames.length === 0) continue;
const card = this.adjustCardForRange(
fragment.matchCard as unknown as InternalMatchCardView,
filteredGames,
);
cards.push(card);
detailsByMatchId.set(fragment.matchId.toString(), filteredGames);
const allowedGameNumbers = new Set(
filteredGames.map((game) => game.gameNumber),
const games = fragment.gameDetails.filter((game) =>
this.isGameInRange(game.gameCreation, context),
);
const gameNumbers = new Set(games.map(({ gameNumber }) => gameNumber));
gameDetails.push(...games);
records.push(
...fragment.records.filter((record) =>
allowedGameNumbers.has(record.gameNumber),
...fragment.records.filter(({ gameNumber }) =>
gameNumbers.has(gameNumber),
),
);
}
return { season: context.season, records, gameDetails };
}
private async buildBaseDataset(
communityId: mongoose.Types.ObjectId,
filters: CommunityStatsFilters,
matchId: mongoose.Types.ObjectId,
): Promise<BaseDataset> {
const context = await this.resolveContext(communityId, filters);
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findOne({ _id: matchId, communityId })
.lean()
.exec();
if (!match) throw new NotFoundException('Internal match not found.');
const CompetitionModel =
await this.connectionService.getModel('competition');
const [source, stored] = await Promise.all([
CompetitionModel.findOne({ matchId, communityId }).lean().exec(),
this.matchStatsRepository.findByMatch(matchId),
]);
const isCurrent = (fragment: MatchStatsDocument | null) =>
Boolean(
fragment?.communityId.equals(communityId) &&
fragment.builderVersion >= MATCH_STATS_BUILDER_VERSION &&
(source
? fragment.sourceCompetitionId?.equals(source._id) &&
fragment.sourceRevision === source.revision &&
fragment.projectorVersion === source.projectorVersion
: !fragment.sourceCompetitionId && !match.competitionId),
);
let fragment = stored;
if (!isCurrent(fragment) && (source || match.result?.games.length)) {
await this.matchStatsService.buildAndUpsert(matchId);
fragment = await this.matchStatsRepository.findByMatch(matchId);
}
if (!isCurrent(fragment)) fragment = null;
if (!fragment && !source && !match.competitionId) {
throw new NotFoundException('Internal match not found.');
}
const competition =
source &&
presentCompetitionDetail({
...source,
teams: source.teams.map((team) => ({
...team,
members: team.members.map((member) => ({ ...member })),
})),
});
const resultPresentation: InternalMatchResultPresentation = source
? this.presentOfficialResult(source)
: { type: match.competitionId ? 'unavailable' : 'legacy' };
const card = (fragment?.matchCard as unknown as
| InternalMatchCardView
| undefined) ?? {
matchId: matchId.toString(),
title: match.title,
scheduledAt: match.scheduledAt.toISOString(),
status: match.status === 'finished' ? 'finished' : 'in-progress',
gameCount: match.gameCount,
seriesResults: [],
games: [],
teams: match.teams.map(({ teamIndex, name }) => ({
teamIndex,
name,
members: [],
})),
};
return {
season: context.season,
matches: cards,
records,
detailsByMatchId,
matches: [{ ...card, resultPresentation }],
records: fragment?.records ?? [],
detailsByMatchId: new Map([
[matchId.toString(), fragment?.gameDetails ?? []],
]),
competition: competition
? {
id: competition.id,
revision: competition.revision,
teams: competition.teams,
projection: competition.projection,
}
: undefined,
};
}
private presentOfficialResult(
source: Competition & { _id: mongoose.Types.ObjectId },
): InternalMatchResultPresentation {
const competition = presentCompetitionDetail({
...source,
teams: source.teams.map((team) => ({ ...team, members: [] })),
});
const { projection } = competition;
return {
type: 'official',
competitionId: competition.id,
sourceRevision: competition.revision,
phase: projection.phase,
formatType: projection.formatType,
teams: competition.teams.map(({ teamId, name }) => ({ teamId, name })),
completedSeriesCount: projection.series.filter(
({ status }) => status === 'completed',
).length,
outcome: projection.outcome,
singleSeries:
projection.formatType === 'paired-series' &&
projection.series.length === 1
? projection.series[0]
: undefined,
};
}
@@ -442,13 +846,25 @@ export class CommunityStatsService {
params.filters,
);
const userId = params.userId.toString();
const fragments = await this.matchStatsRepository.findUserRecordFragments({
const fragmentQuery = {
communityId: params.communityId,
userId: params.userId,
fromGameCreation: context.from?.getTime(),
toGameCreation: context.to?.getTime(),
limit: MAX_MATCH_SCAN,
});
};
let fragments =
await this.matchStatsRepository.findUserRecordFragments(fragmentQuery);
const stale = fragments.filter(
(fragment) => fragment.builderVersion < MATCH_STATS_BUILDER_VERSION,
);
if (stale.length > 0) {
for (const { matchId } of stale) {
await this.matchStatsService.buildAndUpsert(matchId);
}
fragments =
await this.matchStatsRepository.findUserRecordFragments(fragmentQuery);
}
const allUserRecords = this.extractUserRecords(fragments, userId, context);
const records = this.applyChampionFilter(allUserRecords, params.filters);
const limit = this.clampLimit(params.filters.limit, 30, 50);
@@ -621,9 +1037,22 @@ export class CommunityStatsService {
return rebuilt;
}
private repairCommunityFragments(communityId: mongoose.Types.ObjectId) {
const key = communityId.toString();
const inFlight = this.fragmentRepairs.get(key);
if (inFlight) return inFlight;
const repair = this.rebuildMissingOrStaleFragments(communityId).finally(
() => {
this.fragmentRepairs.delete(key);
},
);
this.fragmentRepairs.set(key, repair);
return repair;
}
private adjustCardForRange(
card: InternalMatchCardView,
filteredGames: InternalGameDetail[],
filteredGames: Pick<InternalGameDetail, 'gameNumber'>[],
): InternalMatchCardView {
const allowedGameNumbers = new Set(
filteredGames.map((game) => game.gameNumber),
@@ -706,13 +1135,20 @@ export class CommunityStatsService {
: season.startedAt
? new Date(season.startedAt)
: null;
const to = filters.to ? new Date(filters.to) : null;
const to = filters.to
? new Date(filters.to)
: season.endedAt
? new Date(season.endedAt)
: null;
if (from && Number.isNaN(from.getTime())) {
throw new BadRequestException('Invalid from date.');
}
if (to && Number.isNaN(to.getTime())) {
throw new BadRequestException('Invalid to date.');
}
if (from && to && from.getTime() > to.getTime()) {
throw new BadRequestException('Invalid date range.');
}
return { community, season, from, to };
}
@@ -761,7 +1197,9 @@ export class CommunityStatsService {
private buildLeaderboardRows(records: InternalRecord[]): LeaderboardRow[] {
const byUser = new Map<string, InternalRecord[]>();
for (const record of records) {
byUser.set(record.userId, [...(byUser.get(record.userId) ?? []), record]);
const rows = byUser.get(record.userId);
if (rows) rows.push(record);
else byUser.set(record.userId, [record]);
}
return [...byUser.entries()]
.map(([userId, rows]) => this.toLeaderboardRow(userId, rows))
@@ -816,6 +1254,7 @@ export class CommunityStatsService {
return {
userId,
summonerName: first?.summonerName ?? 'Unknown',
tagLine: first?.tagLine || undefined,
profileIconId: first?.profileIconId ?? 0,
games: records.length,
wins,
@@ -907,10 +1346,22 @@ export class CommunityStatsService {
totalKills: kills,
totalDeaths: deaths,
totalAssists: assists,
doubleKills: 0,
tripleKills: 0,
quadraKills: 0,
pentaKills: 0,
doubleKills: rows.reduce(
(sum, row) => sum + (row.multiKills?.doubleKills ?? 0),
0,
),
tripleKills: rows.reduce(
(sum, row) => sum + (row.multiKills?.tripleKills ?? 0),
0,
),
quadraKills: rows.reduce(
(sum, row) => sum + (row.multiKills?.quadraKills ?? 0),
0,
),
pentaKills: rows.reduce(
(sum, row) => sum + (row.multiKills?.pentaKills ?? 0),
0,
),
avgCs: this.average(this.sum(rows, 'cs'), rows.length),
avgCsPerMin: this.average(this.sum(rows, 'cs'), gameMinutes),
};
@@ -980,6 +1431,7 @@ export class CommunityStatsService {
championLevel: record.championLevel,
teamPosition: record.teamPosition,
kills: record.kills,
largestMultiKill: record.multiKills?.largestMultiKill,
deaths: record.deaths,
assists: record.assists,
kda: this.kda(record.kills, record.deaths, record.assists),
@@ -1006,6 +1458,14 @@ export class CommunityStatsService {
puuid: participant.userId,
gameName: participant.summonerName,
tagLine: '',
tier: participant.tier
? {
tier: participant.tier.tier,
rank: participant.tier.rank,
leaguePoints: participant.tier.leaguePoints,
fetchedAt: new Date(participant.tier.fetchedAt).toISOString(),
}
: undefined,
championId: participant.championId,
championLevel: participant.championLevel,
teamPosition: participant.teamPosition,
@@ -1161,13 +1621,18 @@ export class CommunityStatsService {
communityId.toString(),
cacheScope,
JSON.stringify([
scope,
MATCH_STATS_BUILDER_VERSION,
scope === 'matches' ? 'matches-page-v1' : scope,
filters.seasonId ?? 'current',
filters.from ?? '',
filters.to ?? '',
filters.championId ?? '',
filters.cursor ?? '',
filters.limit ?? '',
filters.query ?? '',
filters.format ?? '',
filters.playerId ?? '',
filters.cursorMatchId ?? '',
]),
);
}
@@ -1210,6 +1675,46 @@ export class CommunityStatsService {
}
}
interface LinkedDetailGame {
game: InternalGameDetail;
official?: CompetitionGameView;
analysisAvailability: GameAnalysisAvailability;
}
function linkDetailGames(
dataset: BaseDataset,
matchId: string,
): LinkedDetailGame[] {
const officialByEvidence = new Map<string, CompetitionGameView | null>();
for (const game of dataset.competition?.projection.games ?? []) {
const evidence =
game.evidence.type === 'riot'
? game.evidence.riotMatchId
: game.evidence.legacyReference;
const key = JSON.stringify([game.displayNumber, evidence]);
officialByEvidence.set(key, officialByEvidence.has(key) ? null : game);
}
return (dataset.detailsByMatchId.get(matchId) ?? []).flatMap((game) => {
const official = officialByEvidence.get(
JSON.stringify([game.gameNumber, game.riotMatchId]),
);
if (dataset.competition && !official) return [];
// A Riot ID is evidence, not a pending raw fetch. Detail hydration only
// fetches timelines for matches whose raw data is already archived.
const analysisAvailability: GameAnalysisAvailability =
game.rawAvailable === false ? 'missing' : 'available';
return [{ game, official: official ?? undefined, analysisAvailability }];
});
}
function needsDetailHydration({
game,
analysisAvailability,
}: LinkedDetailGame) {
return analysisAvailability === 'available' && game.timelineLoaded !== true;
}
function isCompleteMatchDetailResponse(
response: InternalMatchDetailResponse,
): boolean {
@@ -1,3 +1,11 @@
import type {
GameAnalysisAvailability,
GameId,
GameSlotId,
InternalMatchCompetition,
InternalMatchResultPresentation,
SeriesId,
} from '@lolympus/contracts';
import type {
MatchStatsParticipantCheckpoints,
MatchStatsItemBuildEvent,
@@ -19,11 +27,16 @@ export interface CommunityStatsFilters {
championId?: number;
cursor?: number;
limit?: number;
query?: string;
format?: 'pair' | 'tournament';
playerId?: string;
cursorMatchId?: string;
}
export interface InternalMatchListResponse {
matches: InternalMatchCardView[];
nextCursor: number | null;
nextCursorMatchId?: string;
season: HistorySeasonDto;
}
@@ -34,6 +47,7 @@ export interface InternalMatchCardView {
status: 'finished' | 'in-progress';
gameCount: number;
winnerTeamIndex?: number;
resultPresentation?: InternalMatchResultPresentation;
seriesResults: Array<{
teamAIndex: number;
teamBIndex: number;
@@ -64,11 +78,13 @@ export interface InternalMatchCardView {
export interface LeaderboardResponse {
rows: LeaderboardRow[];
season: HistorySeasonDto;
matchedUserIds?: string[];
}
export interface LeaderboardRow {
userId: string;
summonerName: string;
tagLine?: string;
profileIconId: number;
games: number;
wins: number;
@@ -105,6 +121,7 @@ export interface TeamInsightsResponse {
red: number;
bluePicks: number;
redPicks: number;
confirmed: { sampleSize: number; blue: number; red: number };
};
topKda: LeaderHighlight | null;
mostKills: LeaderHighlight | null;
@@ -116,8 +133,14 @@ export interface TeamInsightsResponse {
export interface InternalMatchDetailResponse {
match: InternalMatchCardView;
competition?: InternalMatchCompetition;
games: Array<{
gameNumber: number;
gameId?: GameId;
analysisAvailability?: GameAnalysisAvailability;
gameSlotId?: GameSlotId;
seriesId?: SeriesId;
ordinal?: number;
riotMatchId: string;
gameCreation: number;
gameDuration: number;
@@ -1,4 +1,5 @@
import { Injectable } from '@nestjs/common';
import { readMultiKills } from '../riot/riot-multi-kill';
import mongoose from 'mongoose';
import type {
MatchDocument,
@@ -183,6 +184,7 @@ export class MatchStatsFragmentBuilder {
winnerSide: game.winnerSide,
timeline: this.toTimeline(raw, rawTeamIdBySide, usableTimeline),
timelineLoaded: Boolean(usableTimeline),
rawAvailable: true,
objectiveEvents,
timelineEvents,
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
@@ -253,6 +255,7 @@ export class MatchStatsFragmentBuilder {
winnerSide: game.winnerSide,
timeline: [],
timelineLoaded: false,
rawAvailable: false,
objectiveEvents: [],
timelineEvents: [],
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
@@ -349,6 +352,8 @@ export class MatchStatsFragmentBuilder {
rawParticipant?.individualPosition ||
'',
kills: participant.kills,
multiKills: readMultiKills(rawParticipant),
tier: snapshot?.tier,
deaths: participant.deaths,
assists: participant.assists,
win: participant.win,
@@ -5,7 +5,7 @@ import type { MatchStats, MatchStatsDocument } from '../global/database/schema';
export type MatchStatsUserRecordFragment = Pick<
MatchStats,
'matchId' | 'records'
'matchId' | 'records' | 'builderVersion'
>;
export type MatchStatsDetailFragment = Pick<
@@ -152,6 +152,111 @@ export class MatchStatsRepository {
return MatchStatsModel.findOne({ matchId }).exec();
}
public async findByRiotMatchIds(riotMatchIds: string[]) {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
return MatchStatsModel.find({
'gameDetails.riotMatchId': { $in: riotMatchIds },
})
.select({
matchId: 1,
communityId: 1,
'gameDetails.riotMatchId': 1,
'gameDetails.rawAvailable': 1,
})
.lean()
.exec();
}
public async findMatchPage(params: {
communityId: mongoose.Types.ObjectId;
from?: number;
to?: number;
query?: string;
format?: 'pair' | 'tournament';
playerId?: string;
championId?: number;
cursor?: number;
cursorMatchId?: string;
limit: number;
}) {
const model = await this.connectionService.getModel('matchStats');
const filter: Record<string, unknown> = { communityId: params.communityId };
const conditions: Array<Record<string, unknown>> = [];
const gameCreation = {
...(params.from === undefined ? {} : { $gte: params.from }),
...(params.to === undefined ? {} : { $lte: params.to }),
};
if (Object.keys(gameCreation).length > 0) {
conditions.push({
$or: [
{ gameDetails: { $elemMatch: { gameCreation } } },
{
'gameDetails.0': { $exists: false },
gameCreationMin: gameCreation,
},
],
});
}
if (params.from !== undefined)
filter.gameCreationMax = { $gte: params.from };
if (params.to !== undefined) filter.gameCreationMin = { $lte: params.to };
if (params.championId) {
filter.records = {
$elemMatch: {
championId: params.championId,
...(Object.keys(gameCreation).length > 0 ? { gameCreation } : {}),
},
};
}
if (params.query) {
filter['matchCard.title'] = {
$regex: params.query.replace(/[.*+?^$\x7b\x7d()|[\]\\]/g, '\\$&'),
$options: 'i',
};
}
if (params.format) {
filter['matchCard.teams.1'] = { $exists: true };
filter['matchCard.teams.2'] = { $exists: params.format === 'tournament' };
}
if (params.playerId) {
filter['matchCard.teams.members.userId'] = params.playerId;
}
if (params.cursor !== undefined) {
const cursor = new Date(params.cursor);
if (params.cursorMatchId) {
conditions.push({
$or: [
{ scheduledAt: { $lt: cursor } },
{
scheduledAt: cursor,
matchId: {
$lt: new mongoose.Types.ObjectId(params.cursorMatchId),
},
},
],
});
} else {
filter.scheduledAt = { $lt: cursor };
}
}
if (conditions.length > 0) filter.$and = conditions;
return model
.find(filter)
.select({
matchId: 1,
scheduledAt: 1,
matchCard: 1,
sourceCompetitionId: 1,
sourceRevision: 1,
'gameDetails.gameNumber': 1,
'gameDetails.gameCreation': 1,
})
.sort({ scheduledAt: -1, matchId: -1 })
.limit(params.limit)
.lean()
.exec();
}
public async findByCommunity(params: {
communityId: mongoose.Types.ObjectId;
fromGameCreation?: number;
@@ -175,6 +280,51 @@ export class MatchStatsRepository {
.exec();
}
public async findSeasonStats(params: {
communityId: mongoose.Types.ObjectId;
from?: number;
to?: number;
}) {
const model = await this.connectionService.getModel('matchStats');
return model
.find({
communityId: params.communityId,
...(params.from === undefined
? {}
: { gameCreationMax: { $gte: params.from } }),
...(params.to === undefined
? {}
: { gameCreationMin: { $lte: params.to } }),
})
.select({
_id: 0,
'records.userId': 1,
'records.summonerName': 1,
'records.tagLine': 1,
'records.profileIconId': 1,
'records.gameCreation': 1,
'records.gameNumber': 1,
'records.matchId': 1,
'records.championId': 1,
'records.teamPosition': 1,
'records.win': 1,
'records.kills': 1,
'records.deaths': 1,
'records.assists': 1,
'records.gpm': 1,
'records.csPerMin': 1,
'records.killParticipation': 1,
'records.visionScore': 1,
'records.damageShare': 1,
'gameDetails.gameCreation': 1,
'gameDetails.gameNumber': 1,
'gameDetails.winnerSide': 1,
})
.sort({ scheduledAt: -1 })
.lean()
.exec();
}
public async findByUser(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
@@ -202,7 +352,7 @@ export class MatchStatsRepository {
return MatchStatsModel.find(filter)
.sort({ scheduledAt: -1 })
.limit(params.limit ?? 300)
.select({ _id: 0, matchId: 1, records: 1 })
.select({ _id: 0, matchId: 1, records: 1, builderVersion: 1 })
.lean<MatchStatsUserRecordFragment[]>()
.exec();
}
@@ -47,7 +47,7 @@ export class MatchStatsService {
? competitionStatsSource(match, competition)
: undefined;
const sourceMatch = competitionSource?.match ?? match;
if (!this.isEligible(sourceMatch)) {
if (!this.isEligible(sourceMatch) && competition?.phase !== 'completed') {
if (competitionSource) {
await this.repository.deleteByMatch(matchId, {
sourceCompetitionId: competitionSource.sourceCompetitionId,
@@ -4,7 +4,7 @@ import type {
} from '../global/database/schema';
import type { InternalMatchCardView } from './community-stats.types';
export const MATCH_STATS_BUILDER_VERSION = 10;
export const MATCH_STATS_BUILDER_VERSION = 11;
export type InternalRecord = MatchStatsRecord;
export type InternalGameDetail = MatchStatsGameDetail;
@@ -5,6 +5,7 @@ import {
CompetitionBootstrapService,
type CompetitionBootstrapMatch,
} from './competition-bootstrap.service';
import type { SeriesDefinition } from './domain/series-graph';
describe('CompetitionBootstrapService', () => {
it('creates a deterministic paired-Series Competition and immutable snapshots', async () => {
@@ -210,6 +211,40 @@ describe('CompetitionBootstrapService', () => {
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
});
it('gives a configured BO3 grand final three slots without changing the other stage rules', async () => {
const harness = createHarness();
const service = new CompetitionBootstrapService(harness.connectionService);
const match = matchSnapshot({
gameMode: 'double-elimination',
teamCount: 4,
gameCount: 5,
});
match.doubleElimination = {
teamCount: 4,
resetFinalEnabled: true,
grandFinalGameCount: 3,
seeds: [1, 2, 3, 4].map((teamIndex) => ({
seedNumber: teamIndex,
teamIndex,
})),
};
await service.bootstrap(match);
const { format, seriesGraph } = harness.insertedPayloads[0];
expect(format).toMatchObject({
rules: {
upper: { maxGames: 5, winsRequired: 3 },
lower: { maxGames: 1, winsRequired: 1 },
grandFinal: { maxGames: 3, winsRequired: 2 },
resetFinal: { maxGames: 1, winsRequired: 1 },
},
});
expect(
seriesGraph.find(({ code }) => code === 'GF')?.gameSlots,
).toHaveLength(3);
});
it('rejects incomplete and duplicate team assignments before opening a transaction', async () => {
const cases: Array<[string, (match: CompetitionBootstrapMatch) => void]> = [
[
@@ -451,7 +486,7 @@ interface InsertPayload {
legacyTeamIndex: number;
seedNumber: number;
}>;
seriesGraph: Array<{ code?: string; rule: unknown }>;
seriesGraph: SeriesDefinition[];
[key: string]: any;
}
@@ -41,6 +41,7 @@ export interface CompetitionBootstrapMatch {
doubleElimination?: {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
grandFinalGameCount?: 1 | 3 | 5;
seeds: Array<{ seedNumber: number; teamIndex: number }>;
};
}
@@ -514,6 +515,8 @@ function mapMatchFormat(
winsRequired: 1,
maxGames: 1,
};
const grandFinalGameCount =
match.doubleElimination?.grandFinalGameCount ?? 1;
return {
type: 'double-elimination',
teamCount: teams.length,
@@ -525,7 +528,11 @@ function mapMatchFormat(
maxGames: match.gameCount,
},
lower: { ...bestOfOne },
grandFinal: { ...bestOfOne },
grandFinal: {
type: 'first-to',
winsRequired: Math.floor(grandFinalGameCount / 2) + 1,
maxGames: grandFinalGameCount,
},
resetFinal: { ...bestOfOne },
},
};
@@ -821,7 +821,7 @@ function buildOutbox(
};
}
function factForProjection(
export function factForProjection(
fact: Readonly<Record<string, unknown>>,
): Readonly<Record<string, unknown>> {
const plain = toPlain(fact) as Readonly<Record<string, unknown>>;
@@ -13,6 +13,7 @@ export const COMPETITION_FACT_TYPES = [
'game-voided',
'series-adjudicated',
'adjudication-reversed',
'grand-final-rule-corrected',
] as const;
export type CompetitionFactType = (typeof COMPETITION_FACT_TYPES)[number];
@@ -200,6 +201,7 @@ export interface CompetitionFact {
adjudicationFactId?: mongoose.Types.ObjectId;
decision?: Record<string, unknown>;
reason?: string;
ruleCorrection?: { previousMaxGames: 1; nextMaxGames: 3 };
createdAt: Date;
updatedAt: Date;
}
@@ -339,6 +341,7 @@ export const CompetitionFactSchema = new Schema<CompetitionFact>(
adjudicationFactId: { type: Schema.Types.ObjectId },
decision: { type: Schema.Types.Mixed },
reason: { type: String },
ruleCorrection: { type: Schema.Types.Mixed },
},
{ timestamps: true, collection: 'competition_fact' },
);
@@ -131,7 +131,12 @@ export interface CompetitionProjection {
export function projectCompetition(
input: ProjectCompetitionInput,
): CompetitionProjection {
assertPrimaryFactTargetsGraph(input.seriesGraph, input.facts);
// The repair commits the corrected graph and its audit fact together. The
// audit fact occupies a revision but is not a game or adjudication.
const resultFacts = input.facts.filter(
(fact) => !isRecord(fact) || fact.type !== 'grand-final-rule-corrected',
);
assertPrimaryFactTargetsGraph(input.seriesGraph, resultFacts);
const teamBySeed = new Map<number, string>();
const knownTeams = new Set<string>();
for (const team of input.teams) {
@@ -169,7 +174,7 @@ export function projectCompetition(
teamBySeed,
projectedById,
),
facts: input.facts,
facts: resultFacts,
active: false,
}),
);
@@ -188,7 +193,7 @@ export function projectCompetition(
projectSeries({
definition: asProjectorDefinition(definition),
participants,
facts: input.facts,
facts: resultFacts,
}),
);
remaining.delete(seriesId);
@@ -211,7 +216,7 @@ export function projectCompetition(
projectSeries({
definition: asProjectorDefinition(definition),
participants,
facts: input.facts,
facts: resultFacts,
...(definition.activation ? { active: false } : {}),
}),
);
@@ -221,7 +226,7 @@ export function projectCompetition(
const gameProjection = projectGamesAndSlots(
input.seriesGraph,
series,
input.facts,
resultFacts,
);
const common = {
competitionId: input.competitionId,
@@ -88,6 +88,7 @@ export interface DoubleEliminationEvent {
export interface DoubleEliminationBracket {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
grandFinalGameCount?: 1 | 3 | 5;
resetFinalCreated: boolean;
seeds: DoubleEliminationSeed[];
bracketMatches: DoubleEliminationBracketMatch[];
@@ -98,6 +99,7 @@ export interface DoubleEliminationBracket {
export interface BuildDoubleEliminationBracketOptions {
resetFinalEnabled: boolean;
winnerBracketGameCount?: number;
grandFinalGameCount?: 1 | 3 | 5;
}
export interface DoubleEliminationSeriesRule {
@@ -146,6 +148,9 @@ export function buildDoubleEliminationBracket(
const bracket: DoubleEliminationBracket = {
teamCount: seededTeamIndexes.length,
resetFinalEnabled: options.resetFinalEnabled,
...(options.grandFinalGameCount === undefined
? {}
: { grandFinalGameCount: options.grandFinalGameCount }),
resetFinalCreated: false,
seeds,
bracketMatches:
@@ -171,11 +176,17 @@ export function resolveDoubleEliminationSeriesRule(
bracketMatchId: string;
roundNumber: number;
},
options: { winnerBracketGameCount?: number } = {},
options: Pick<
BuildDoubleEliminationBracketOptions,
'winnerBracketGameCount' | 'grandFinalGameCount'
> = {},
): DoubleEliminationSeriesRule {
if (params.bracketSide === 'winner') {
return seriesRule(options.winnerBracketGameCount ?? 3);
}
if (params.bracketSide === 'grand-final') {
return seriesRule(options.grandFinalGameCount ?? 1);
}
return seriesRule(1);
}
@@ -431,6 +442,7 @@ function rebuildWithSeeds(
): DoubleEliminationBracket {
const next = buildDoubleEliminationBracket(teamIndexes, {
resetFinalEnabled: bracket.resetFinalEnabled,
grandFinalGameCount: bracket.grandFinalGameCount,
});
next.events = [
...bracket.events,
@@ -0,0 +1,4 @@
export const MATCH_STATS_RIOT_MATCH_INDEX = {
key: { 'gameDetails.riotMatchId': 1 as const },
options: { name: 'gameDetails.riotMatchId_1' },
};
@@ -0,0 +1,47 @@
import type { mongo } from 'mongoose';
import { migrateMatchStatsRawIndex } from './20261111-match-stats-raw-index';
import { MATCH_STATS_RIOT_MATCH_INDEX } from '../match-stats-raw-index';
import { parseMatchStatsIndexOptions } from './run-match-stats-raw-index';
it('defaults to a read-only plan and validates the target environment', async () => {
expect(parseMatchStatsIndexOptions(['--env', 'prod']).dryRun).toBe(true);
expect(() => parseMatchStatsIndexOptions(['--env', 'unknown'])).toThrow();
const createIndex = jest.fn();
await migrateMatchStatsRawIndex(database([], createIndex));
expect(createIndex).not.toHaveBeenCalled();
});
it('adds only the lookup index and accepts an identical existing index', async () => {
const { key, options } = MATCH_STATS_RIOT_MATCH_INDEX;
const createIndex = jest.fn();
const result = await migrateMatchStatsRawIndex(
database([{ key, ...options }], createIndex),
{ dryRun: false },
);
expect(result.alreadyPresent).toBe(true);
expect(createIndex).toHaveBeenCalledWith(key, options);
});
it('rejects an incompatible existing index without dropping or recreating it', async () => {
const { key, options } = MATCH_STATS_RIOT_MATCH_INDEX;
const createIndex = jest.fn();
await expect(
migrateMatchStatsRawIndex(
database([{ key, ...options, unique: true }], createIndex),
{ dryRun: false },
),
).rejects.toThrow('different definition');
expect(createIndex).not.toHaveBeenCalled();
});
function database(indexes: unknown[], createIndex: jest.Mock): mongo.Db {
return {
collection: (name: string) => {
expect(name).toBe('match_stats');
return {
listIndexes: () => ({ toArray: async () => indexes }),
createIndex,
};
},
} as unknown as mongo.Db;
}
@@ -0,0 +1,38 @@
import type { mongo } from 'mongoose';
import { MATCH_STATS_RIOT_MATCH_INDEX } from '../match-stats-raw-index';
/** Adds the lookup index without dropping indexes or modifying game records. */
export async function migrateMatchStatsRawIndex(
db: mongo.Db,
{ dryRun = true }: { dryRun?: boolean } = {},
) {
const { key, options } = MATCH_STATS_RIOT_MATCH_INDEX;
const collection = db.collection('match_stats');
const indexes = await collection
.listIndexes()
.toArray()
.catch((error: unknown) => {
if (error instanceof Error && 'code' in error && error.code === 26)
return [];
throw error;
});
const existing = indexes.find((index) => index.name === options.name);
if (
existing &&
(JSON.stringify(existing.key) !== JSON.stringify(key) ||
existing.unique === true ||
existing.sparse === true ||
existing.hidden === true ||
existing.partialFilterExpression !== undefined)
) {
throw new Error(
`Index ${options.name} already exists with a different definition.`,
);
}
if (!dryRun) await collection.createIndex(key, options);
return {
dryRun,
alreadyPresent: Boolean(existing),
index: { key, ...options },
};
}
@@ -0,0 +1,293 @@
import mongoose from 'mongoose';
import { projectCompetition } from '../../../competition/domain/competition-projector';
import { generateSeriesGraph } from '../../../competition/domain/series-graph';
import {
parseGrandFinalRepairOptions,
planGrandFinalBo3Repair,
repairGrandFinalBo3,
} from './repair-grand-final-bo3';
describe('grand final BO3 repair', () => {
it.each([false, true])(
'keeps game 28 and finishes only after two wins (split: %s)',
(split) => {
const input = finishedTournament();
const plan = planGrandFinalBo3Repair(input);
expect(plan.before.phase).toBe('completed');
expect(plan.preservedGame).toBe(28);
expect(plan.newGameNumbers).toEqual([29, 30]);
expect(plan.projection.games).toEqual(plan.before.games);
expect(plan.projection).toMatchObject({
phase: 'running',
placements: [],
});
expect(plan.projection).not.toHaveProperty('outcome');
expect(
plan.projection.series.find(
({ seriesId }) => seriesId === plan.seriesId,
),
).toMatchObject({
status: 'in-progress',
entries: [
{ slot: 'A', gameWins: 1 },
{ slot: 'B', gameWins: 0 },
],
});
const facts = [
...input.facts,
{
id: 'rule-audit',
type: 'grand-final-rule-corrected',
seriesId: plan.seriesId,
revision: plan.projection.sourceRevision,
ordinalWithinRevision: 1,
},
];
const replay = () =>
projectCompetition({
...input,
facts,
revision: facts.length,
format: plan.format,
seriesGraph: plan.seriesGraph,
});
expect(replay()).toEqual(plan.projection);
const second = replay().gameSlots.find(
({ displayNumber }) => displayNumber === 29,
)!;
facts.push(acceptedGame(second, facts.length + 1, split ? 'B' : 'A'));
if (split) {
expect(replay().phase).toBe('running');
const third = replay().gameSlots.find(
({ displayNumber }) => displayNumber === 30,
)!;
expect(third.status).toBe('ready');
facts.push(acceptedGame(third, facts.length + 1, 'A'));
}
const completed = replay();
expect(completed.phase).toBe('completed');
expect(
completed.gameSlots.find(({ displayNumber }) => displayNumber === 30)
?.status,
).toBe(split ? 'completed' : 'inactive');
expect(completed.games.at(-1)?.displayNumber).toBe(split ? 30 : 29);
},
);
it('refuses to reopen a bracket that enables a reset final', () => {
const input = finishedTournament();
expect(() =>
planGrandFinalBo3Repair({
...input,
format: { ...input.format, resetFinalEnabled: true },
}),
).toThrow('no reset or later series');
});
it('requires a target and a reviewed revision before applying', () => {
const target = ['--match-id', '000000000000000000000001', '--env', 'prod'];
expect(parseGrandFinalRepairOptions(target)).toMatchObject({
apply: false,
});
expect(() => parseGrandFinalRepairOptions(['--apply', ...target])).toThrow(
'--expected-revision',
);
expect(
parseGrandFinalRepairOptions([
'--apply',
...target,
'--expected-revision',
'23',
]),
).toMatchObject({ apply: true, expectedRevision: 23 });
});
it('previews without writes and applies the graph, match status and audit in one transaction', async () => {
const input = finishedTournament();
const competitionId = new mongoose.Types.ObjectId(input.competitionId);
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
competitionId,
communityId,
gameMode: 'double-elimination',
status: 'finished',
teamBuiltAt: new Date(),
doubleElimination: { resetFinalEnabled: false },
resultPollState: { state: 'complete' },
};
const competition = {
...input,
_id: competitionId,
schemaVersion: 1,
phase: 'completed',
teams: input.teams.map((team) => ({
...team,
teamId: new mongoose.Types.ObjectId(team.teamId),
})),
projection: projectCompetition(input),
};
const query = (value: unknown) => ({
session: jest.fn().mockReturnThis(),
lean: jest.fn().mockReturnThis(),
sort: jest.fn().mockReturnThis(),
exec: jest.fn().mockResolvedValue(value),
});
const update = () => jest.fn(() => query({ matchedCount: 1 }));
const models = {
match: { findById: jest.fn(() => query(match)), updateOne: update() },
competition: {
findOne: jest.fn(() => query(competition)),
updateOne: update(),
},
competitionFact: {
find: jest.fn(() => query(input.facts)),
insertMany: jest.fn(),
},
competitionOutbox: { insertMany: jest.fn() },
};
const session = {
withTransaction: jest.fn((run: () => unknown) => run()),
endSession: jest.fn(),
};
const connections = {
getModel: jest.fn((name: keyof typeof models) => models[name]),
createSession: jest.fn().mockResolvedValue(session),
} as never;
const options = { matchId, nodeEnv: 'prod', apply: false };
const preview = await repairGrandFinalBo3(connections, options);
expect(preview).toMatchObject({
mode: 'dry-run',
preservedGame: 28,
newGameNumbers: [29, 30],
});
expect(models.match.updateOne).not.toHaveBeenCalled();
expect(models.competition.updateOne).not.toHaveBeenCalled();
expect(models.competitionFact.insertMany).not.toHaveBeenCalled();
expect(models.competitionOutbox.insertMany).not.toHaveBeenCalled();
await expect(
repairGrandFinalBo3(connections, {
...options,
apply: true,
expectedRevision: preview.revisionBefore,
}),
).resolves.toMatchObject({
mode: 'applied',
phase: 'completed -> running',
});
expect(session.withTransaction).toHaveBeenCalledTimes(1);
expect(models.match.updateOne).toHaveBeenCalledWith(
{ _id: matchId, status: 'finished', competitionId },
{
$set: expect.objectContaining({
status: 'in-progress',
'resultPollState.state': 'polling',
}),
},
{ session, runValidators: true },
);
expect(models.competition.updateOne).toHaveBeenCalledWith(
{ _id: competitionId, revision: preview.revisionBefore },
{
$set: expect.objectContaining({
phase: 'running',
revision: preview.revisionAfter,
}),
},
{ session, runValidators: true },
);
expect(models.competitionFact.insertMany).toHaveBeenCalledWith(
[
expect.objectContaining({
type: 'grand-final-rule-corrected',
revision: preview.revisionAfter,
}),
],
{ session },
);
expect(models.competitionOutbox.insertMany).toHaveBeenCalledWith(
[
expect.objectContaining({
type: 'competition.projection-updated',
revision: preview.revisionAfter,
}),
],
{ session },
);
});
});
function finishedTournament() {
const competitionId = '000000000000000000000001';
const teams = Array.from({ length: 8 }, (_, index) => ({
teamId: (index + 1).toString(16).padStart(24, '0'),
displayOrder: index + 1,
seedNumber: index + 1,
}));
const bo1 = { type: 'first-to', maxGames: 1, winsRequired: 1 } as const;
const format = {
type: 'double-elimination' as const,
teamCount: 8 as const,
resetFinalEnabled: false,
rules: {
upper: { ...bo1, maxGames: 3, winsRequired: 2 },
lower: bo1,
grandFinal: bo1,
resetFinal: bo1,
},
};
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
const facts: Record<string, unknown>[] = [];
const input = {
competitionId,
teams,
format,
seriesGraph,
facts,
projectorVersion: 1,
revision: 0,
};
for (let index = 0; index < 28; index += 1) {
const slot = projectCompetition(input).gameSlots.find(
({ status }) => status === 'ready',
);
if (!slot) break;
facts.push(acceptedGame(slot, index + 1, 'A'));
input.revision += 1;
}
return input;
}
function acceptedGame(
slot: ReturnType<typeof projectCompetition>['gameSlots'][number],
revision: number,
winner: 'A' | 'B',
): Record<string, unknown> {
const [a, b] = slot.entries;
const recordedAt = new Date(Date.UTC(2026, 6, 26, 0, revision)).toISOString();
return {
id: `fact-${revision}`,
type: 'game-accepted',
revision,
ordinalWithinRevision: 1,
gameId: `game-${revision}`,
seriesId: slot.seriesId,
gameSlotId: slot.id,
ordinal: slot.ordinal,
recordedAt,
occurredAt: recordedAt,
evidence: { type: 'riot', riotMatchId: `KR_${revision}` },
mapping: {
blueTeamId: a.teamId,
redTeamId: b.teamId,
winnerTeamId: winner === 'A' ? a.teamId : b.teamId,
participantAssignments: [],
},
};
}
@@ -0,0 +1,410 @@
import 'reflect-metadata';
import { ConfigService } from '@nestjs/config';
import mongoose from 'mongoose';
import { createHash } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import { factForProjection } from '../../../competition/competition-command.service';
import { projectCompetition } from '../../../competition/domain/competition-projector';
import {
generateSeriesGraph,
type CompetitionGraphFormat,
type CompetitionGraphTeam,
type SeriesDefinition,
} from '../../../competition/domain/series-graph';
import { SecretService } from '../../secret/secret.service';
import { ConnectionService, resolveMongoDbName } from '../connection.service';
const CORRECTION_TYPE = 'grand-final-rule-corrected' as const;
const BO3 = { type: 'first-to', winsRequired: 2, maxGames: 3 } as const;
interface RepairInput {
competitionId: string;
revision: number;
projectorVersion: number;
teams: readonly CompetitionGraphTeam[];
format: CompetitionGraphFormat;
seriesGraph: readonly SeriesDefinition[];
facts: readonly Record<string, unknown>[];
}
export function planGrandFinalBo3Repair(input: RepairInput) {
const { format, seriesGraph, facts } = input;
const final = seriesGraph.find(({ stage }) => stage.type === 'grand-final');
if (
format.type !== 'double-elimination' ||
format.resetFinalEnabled ||
format.rules.grandFinal.type !== 'first-to' ||
format.rules.grandFinal.maxGames !== 1 ||
format.rules.grandFinal.winsRequired !== 1 ||
!final ||
!isDeepStrictEqual(final.rule, format.rules.grandFinal) ||
final.gameSlots.length !== 1 ||
seriesGraph.some(
({ stage }) => stage.displayOrder > final.stage.displayOrder,
)
) {
throw new Error(
'Expected a BO1 grand final with no reset or later series.',
);
}
const before = projectCompetition(input);
const previousFinal = before.series.find(
({ seriesId }) => seriesId === final.id,
);
const finalGames = before.games.filter(
({ seriesId }) => seriesId === final.id,
);
const firstGame = finalGames[0];
if (
before.phase !== 'completed' ||
previousFinal?.status !== 'completed' ||
previousFinal.outcome.type !== 'played' ||
finalGames.length !== 1 ||
firstGame.ordinal !== 1 ||
firstGame.evidence.type !== 'riot' ||
facts.filter((fact) => fact.seriesId === final.id).length !== 1
) {
throw new Error(
'Expected exactly one Riot result and no other final facts.',
);
}
const correctedFormat = {
...format,
rules: { ...format.rules, grandFinal: BO3 },
};
const generatedFinal = generateSeriesGraph({
competitionId: input.competitionId,
teams: input.teams,
format: correctedFormat,
}).find(({ stage }) => stage.type === 'grand-final');
if (
generatedFinal?.id !== final.id ||
!isDeepStrictEqual(generatedFinal.gameSlots[0], final.gameSlots[0])
) {
throw new Error(
'The existing grand final does not match its stable slot identity.',
);
}
const correctedGraph = seriesGraph.map((series) =>
series.id === final.id
? { ...series, rule: BO3, gameSlots: generatedFinal.gameSlots }
: series,
);
const projection = projectCompetition({
...input,
revision: input.revision + 1,
format: correctedFormat,
seriesGraph: correctedGraph,
});
const readySlots = projection.gameSlots.filter(
({ status }) => status === 'ready',
);
if (
projection.phase !== 'running' ||
!isDeepStrictEqual(projection.games, before.games) ||
readySlots.length !== 2 ||
readySlots.some(
(slot, index) =>
slot.seriesId !== final.id ||
slot.ordinal !== index + 2 ||
slot.displayNumber !== firstGame.displayNumber + index + 1,
) ||
!isDeepStrictEqual(
projection.series.filter(({ seriesId }) => seriesId !== final.id),
before.series.filter(({ seriesId }) => seriesId !== final.id),
)
) {
throw new Error(
'Repair would change existing results or fail to reopen the final.',
);
}
return {
before,
format: correctedFormat,
seriesGraph: correctedGraph,
projection,
seriesId: final.id,
preservedGame: firstGame.displayNumber,
newGameNumbers: readySlots.map(({ displayNumber }) => displayNumber),
};
}
interface CliOptions {
matchId: mongoose.Types.ObjectId;
nodeEnv: string;
expectedRevision?: number;
apply: boolean;
}
export function parseGrandFinalRepairOptions(argv: string[]): CliOptions {
let matchId: mongoose.Types.ObjectId | undefined;
let nodeEnv = 'dev';
let expectedRevision: number | undefined;
let apply = false;
for (let index = 0; index < argv.length; index += 1) {
switch (argv[index]) {
case '--':
break;
case '--apply':
apply = true;
break;
case '--match-id': {
const value = argv[++index];
if (!/^[a-f\d]{24}$/i.test(value ?? '')) {
throw new Error('--match-id must be a 24-character ObjectId.');
}
matchId = new mongoose.Types.ObjectId(value);
break;
}
case '--env':
nodeEnv = argv[++index];
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
throw new Error('--env must be dev, staging, or prod.');
}
break;
case '--expected-revision': {
const value = argv[++index];
expectedRevision = Number(value);
if (
!/^\d+$/.test(value ?? '') ||
!Number.isSafeInteger(expectedRevision)
) {
throw new Error('--expected-revision must be a nonnegative integer.');
}
break;
}
default:
throw new Error(`Unknown argument: ${argv[index]}`);
}
}
if (!matchId || (apply && expectedRevision === undefined)) {
throw new Error(
'--match-id is required; --apply also requires --expected-revision from the dry run.',
);
}
return { matchId, nodeEnv, expectedRevision, apply };
}
export async function repairGrandFinalBo3(
connectionService: ConnectionService,
options: CliOptions,
) {
if (options.apply && options.expectedRevision === undefined) {
throw new Error('An expected revision is required to apply the repair.');
}
const [Match, Competition, Fact, Outbox] = await Promise.all([
connectionService.getModel('match'),
connectionService.getModel('competition'),
connectionService.getModel('competitionFact'),
connectionService.getModel('competitionOutbox'),
]);
async function run(session: mongoose.ClientSession | null) {
const match = await Match.findById(options.matchId)
.session(session)
.lean()
.exec();
if (
!match?.competitionId ||
match.gameMode !== 'double-elimination' ||
match.status !== 'finished' ||
!match.teamBuiltAt ||
!match.doubleElimination
) {
throw new Error(
'Expected a finished double-elimination Match with a linked Competition.',
);
}
const competition = await Competition.findOne({
_id: match.competitionId,
matchId: match._id,
communityId: match.communityId,
})
.session(session)
.lean()
.exec();
if (!competition || competition.phase !== 'completed') {
throw new Error('Expected a completed Competition linked to this Match.');
}
if (
options.expectedRevision !== undefined &&
competition.revision !== options.expectedRevision
) {
throw new Error(
`Competition revision is ${competition.revision}; run the preview again.`,
);
}
const facts = await Fact.find({ competitionId: competition._id })
.sort({ revision: 1, ordinalWithinRevision: 1 })
.session(session)
.lean()
.exec();
const plan = planGrandFinalBo3Repair({
competitionId: competition._id.toHexString(),
revision: competition.revision,
projectorVersion: competition.projectorVersion,
teams: competition.teams.map(({ teamId, displayOrder, seedNumber }) => ({
teamId: teamId.toHexString(),
displayOrder,
seedNumber,
})),
format: competition.format as unknown as CompetitionGraphFormat,
seriesGraph: competition.seriesGraph as unknown as SeriesDefinition[],
facts: facts.map((fact) => factForProjection({ ...fact })),
});
if (!isDeepStrictEqual(plan.before, competition.projection)) {
throw new Error(
'The fact ledger does not reproduce the stored projection.',
);
}
const revision = plan.projection.sourceRevision;
if (session) {
const now = new Date();
const idempotencyKey = `repair:grand-final-bo3:${competition._id.toHexString()}`;
const requestHash = createHash('sha256')
.update(idempotencyKey)
.digest('hex');
const commandId = `cmpcmd_${requestHash.slice(0, 32)}`;
const receipt = {
competitionId: competition._id,
revision,
commandId,
idempotencyKey,
requestHash,
};
const factId = new mongoose.Types.ObjectId();
const competitionWrite = await Competition.updateOne(
{ _id: competition._id, revision: competition.revision },
{
$set: {
revision,
format: plan.format,
seriesGraph: plan.seriesGraph,
projection: plan.projection,
phase: plan.projection.phase,
},
},
{ session, runValidators: true },
).exec();
const matchWrite = await Match.updateOne(
{ _id: match._id, status: 'finished', competitionId: competition._id },
{
$set: {
status: 'in-progress',
'doubleElimination.grandFinalGameCount': 3,
...(match.resultPollState
? {
'resultPollState.state': 'polling',
'resultPollState.matchedCount': plan.projection.games.length,
}
: {}),
},
},
{ session, runValidators: true },
).exec();
if (
competitionWrite.matchedCount !== 1 ||
matchWrite.matchedCount !== 1
) {
throw new Error(
'Match or Competition changed during repair; run the preview again.',
);
}
await Fact.insertMany(
[
{
...receipt,
_id: factId,
type: CORRECTION_TYPE,
ordinalWithinRevision: 1,
schemaVersion: competition.schemaVersion,
actor: { type: 'system' },
seriesId: new mongoose.Types.ObjectId(plan.seriesId),
occurredAt: now,
recordedAt: now,
reason:
'Restore the intended BO3 grand final without voiding the first game.',
ruleCorrection: { previousMaxGames: 1, nextMaxGames: 3 },
},
],
{ session },
);
await Outbox.insertMany(
[
{
...receipt,
eventId: `${commandId}:competition-projected`,
type: 'competition.projection-updated',
payload: {
competitionId: competition._id.toHexString(),
sourceRevision: revision,
factIds: [factId.toHexString()],
projection: plan.projection,
phase: plan.projection.phase,
updatedAt: now,
},
state: 'pending',
availableAt: now,
},
],
{ session },
);
}
return {
mode: session ? 'applied' : 'dry-run',
database: resolveMongoDbName(options.nodeEnv),
matchId: match._id.toHexString(),
competitionId: competition._id.toHexString(),
revisionBefore: competition.revision,
revisionAfter: revision,
phase: `${competition.phase} -> ${plan.projection.phase}`,
preservedGame: plan.preservedGame,
totalPreservedGames: plan.projection.games.length,
newGameNumbers: plan.newGameNumbers,
};
}
if (!options.apply) return run(null);
const session = await connectionService.createSession();
if (!session) throw new Error('Repair requires a MongoDB transaction.');
try {
return await session.withTransaction(() => run(session));
} finally {
await session.endSession();
}
}
async function main() {
const args = process.argv.slice(2);
if (args.includes('--help')) {
process.stdout.write(
'Usage: pnpm --filter api competition:repair-grand-final --env <dev|staging|prod> --match-id <id> [--expected-revision <n> --apply]\n',
);
return;
}
const options = parseGrandFinalRepairOptions(args);
process.env.NODE_ENV = options.nodeEnv;
process.env.MONGODB_AUTO_INDEX = 'false';
const connections = new ConnectionService(
new SecretService(new ConfigService()),
);
const connection = await connections.getConnection();
try {
process.stdout.write(
`${JSON.stringify(await repairGrandFinalBo3(connections, options), null, 2)}\n`,
);
} finally {
await connection.close();
}
}
if (require.main === module) {
void main().catch((error: unknown) => {
process.stderr.write(
`${error instanceof Error ? error.message : String(error)}\n`,
);
process.exitCode = 1;
});
}
@@ -0,0 +1,102 @@
import 'reflect-metadata';
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { ConnectionService, resolveMongoDbName } from '../connection.service';
import { SecretModule } from '../../secret/secret.module';
import { migrateMatchStatsRawIndex } from './20261111-match-stats-raw-index';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: [
resolve(__dirname, '../../../../../../project.env'),
resolve(process.cwd(), '../project.env'),
resolve(process.cwd(), 'apps/project.env'),
resolve(process.cwd(), 'project.env'),
],
}),
SecretModule,
],
providers: [ConnectionService],
})
class MigrationModule {}
export function parseMatchStatsIndexOptions(argv: string[]) {
let dryRun = true;
let help = false;
let nodeEnv = process.env.NODE_ENV ?? 'dev';
for (let index = 0; index < argv.length; index++) {
const argument = argv[index];
if (argument === '--') continue;
if (argument === '--apply') dryRun = false;
else if (argument === '--dry-run') dryRun = true;
else if (argument === '--help' || argument === '-h') help = true;
else if (argument === '--env') nodeEnv = argv[++index] ?? '';
else if (argument.startsWith('--env=')) nodeEnv = argument.slice(6);
else throw new Error(`Unknown argument: ${argument}`);
}
if (!help && !['dev', 'staging', 'prod'].includes(nodeEnv)) {
throw new Error('--env must be dev, staging, or prod.');
}
return { dryRun, help, nodeEnv };
}
async function main(): Promise<void> {
const options = parseMatchStatsIndexOptions(process.argv.slice(2));
if (options.help) {
console.log(`Usage:
pnpm --filter api stats:indexes -- --env staging --dry-run
pnpm --filter api stats:indexes -- --env prod --apply
Defaults to dry-run. --env accepts dev, staging, or prod (NODE_ENV or dev by default).
Creates the internal stats Riot match ID index; does not modify documents.`);
return;
}
// Use the same optional machine environment as the existing migration runners.
const machineHome = process.env.HOME ?? process.env.USERPROFILE;
if (machineHome) {
const contents = await readFile(
resolve(machineHome, 'source/global-env-vars.txt'),
'utf8',
).catch(() => '');
for (const line of contents.split(/\r?\n/)) {
const match = line.trim().match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
if (match) process.env[match[1]] = match[2].replace(/^["']|["']$/g, '');
}
}
process.env.NODE_ENV = options.nodeEnv;
// Even a dry-run with auto-index enabled in the environment must not write.
process.env.MONGODB_AUTO_INDEX = 'false';
const app = await NestFactory.createApplicationContext(MigrationModule, {
logger: ['warn', 'error'],
});
try {
const connection = await app.get(ConnectionService).getConnection();
if (!connection.db) throw new Error('MongoDB connection has no db handle.');
const result = await migrateMatchStatsRawIndex(connection.db, options);
console.log(
JSON.stringify(
{
env: options.nodeEnv,
db: resolveMongoDbName(options.nodeEnv),
...result,
},
null,
2,
),
);
} finally {
await app.close();
}
}
if (require.main === module) {
void main().catch((error: unknown) => {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
});
}
+19 -1
View File
@@ -1,4 +1,5 @@
import mongoose, { Schema, HydratedDocument } from 'mongoose';
import type { MatchEventType } from '@lolympus/contracts';
import type {
RiotPlatformRoute,
RiotRegionalRoute,
@@ -13,6 +14,7 @@ import {
} from '../../competition/competition.schema';
import { ModelDefinition } from './types';
import { AUCTION_CANCELLATION_CLEANUP_INDEX } from './auction-cancellation-index';
import { MATCH_STATS_RIOT_MATCH_INDEX } from './match-stats-raw-index';
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
export const POSITIONS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
@@ -38,6 +40,8 @@ export const MATCH_STATUSES: MatchStatus[] = [
'finished',
];
export const MATCH_EVENT_TYPES = ['inhouse', 'tournament'] as const satisfies readonly MatchEventType[];
export type TeamSide = 'blue' | 'red';
export const TEAM_SIDES: TeamSide[] = ['blue', 'red'];
@@ -644,6 +648,7 @@ export interface DoubleEliminationEvent {
export interface DoubleEliminationBracket {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
grandFinalGameCount?: 1 | 3 | 5;
resetFinalCreated: boolean;
seeds: DoubleEliminationSeed[];
bracketMatches: DoubleEliminationBracketMatch[];
@@ -685,6 +690,7 @@ export interface Match extends MongooseTimestamps {
competitionId?: mongoose.Types.ObjectId;
shortCode?: string;
title: string;
eventType?: MatchEventType;
description: string;
mapId: number; // Riot Match-V5 mapId (11=소환사의 협곡, 12=ARAM 등)
status: MatchStatus;
@@ -1014,6 +1020,14 @@ export interface MatchStatsRecord {
championLevel: number;
teamPosition: string;
kills: number;
multiKills?: {
doubleKills: number;
tripleKills: number;
quadraKills: number;
pentaKills: number;
largestMultiKill: number;
};
tier?: TierInfo;
deaths: number;
assists: number;
win: boolean;
@@ -1046,6 +1060,7 @@ export interface MatchStatsGameDetail {
gameCreation: number;
gameDuration: number;
gameVersion?: string;
rawAvailable?: boolean;
winnerSide: TeamSide;
timeline: MatchStatsTimelinePoint[];
timelineLoaded?: boolean;
@@ -1850,6 +1865,7 @@ const DoubleEliminationBracketSubSchema = new Schema<DoubleEliminationBracket>(
{
teamCount: { type: Number, enum: [4, 8], required: true },
resetFinalEnabled: { type: Boolean, required: true, default: false },
grandFinalGameCount: { type: Number, enum: [1, 3, 5] },
resetFinalCreated: { type: Boolean, required: true, default: false },
seeds: {
type: [DoubleEliminationSeedSubSchema],
@@ -1952,6 +1968,7 @@ export const MatchSchema = new Schema<Match>(
maxlength: 6,
},
title: { type: String, required: true },
eventType: { type: String, enum: MATCH_EVENT_TYPES, default: 'inhouse' },
description: { type: String, required: false, default: '' },
mapId: { type: Number, required: true, default: 11 },
status: {
@@ -2528,7 +2545,7 @@ export const MatchStatsSchema: mongoose.Schema<MatchStats> = new Schema(
{ timestamps: true, collection: 'match_stats' },
) as mongoose.Schema<MatchStats>;
MatchStatsSchema.index({ communityId: 1, scheduledAt: -1 });
MatchStatsSchema.index({ communityId: 1, scheduledAt: -1, matchId: -1 });
MatchStatsSchema.index({
communityId: 1,
gameCreationMin: 1,
@@ -2537,6 +2554,7 @@ 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);
export const tournamentModelDefinitions: Array<
ModelDefinition & { name: keyof TournamentModelTypes }
@@ -389,6 +389,7 @@ describe('Legacy import Competition result cutover', () => {
}),
} as unknown as ConnectionService;
const communityStatsService = {
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<CommunityStatsService>;
const service = createService({
@@ -642,6 +643,7 @@ function createService(
{} as RiotMatchService,
options.communityStatsService ??
({
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as unknown as CommunityStatsService),
options.matchStatsService ?? ({} as MatchStatsService),
@@ -977,6 +979,7 @@ function createBulkDeleteFailureHarness(options: {
}),
} as unknown as ConnectionService;
const communityStatsService = {
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
invalidateCommunity: jest.fn().mockResolvedValue(0),
} as unknown as jest.Mocked<CommunityStatsService>;
const service = createService({ connectionService, communityStatsService });
@@ -59,6 +59,7 @@ describe('LegacyImportService member job completion', () => {
releaseLockIfOwned: jest.fn().mockResolvedValue(true),
} as unknown as jest.Mocked<DistributedLockService>;
const communityStatsService = {
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<CommunityStatsService>;
const service = new LegacyImportService(
@@ -797,7 +797,9 @@ export class LegacyImportService {
'evidence.type': 'riot',
'evidence.riotMatchId': riotMatchId,
});
if (existing) return 'duplicate';
if (existing) {
return 'duplicate';
}
const detail = await this.ensureRiotMatchPersisted(
riotMatchId,
@@ -930,7 +932,9 @@ export class LegacyImportService {
const stored = await RiotMatchModel.findOne({
matchId: riotMatchId,
}).exec();
if (isRiotMatchDto(stored?.raw)) return stored.raw;
if (isRiotMatchDto(stored?.raw)) {
return stored.raw;
}
const dto = await this.riotMatchService.getMatch(riotMatchId, { region });
const payload: Partial<StoredRiotMatch> = {
@@ -948,6 +952,13 @@ export class LegacyImportService {
{ $set: payload },
{ upsert: true },
).exec();
await this.communityStatsService
.refreshForRiotMatches([dto.metadata.matchId])
.catch((error: unknown) => {
this.logger.warn(
`Stats recovery failed after saving ${dto.metadata.matchId}: ${String(error)}`,
);
});
return dto;
}
@@ -18,6 +18,11 @@ describe('MatchHistoryService champion filtering', () => {
'KR_2',
]);
expect(first.nextCursor).toBe(SEASON_START + 2_000);
expect(first.matches[0].largestMultiKill).toBe(3);
expect(first.matches[0].teams[0].participants[0].tier).toMatchObject({
tier: 'GOLD',
rank: 'II',
});
const second = await harness.service.getRecentMatches({
...harness.scope,
filters: { ...filters, cursor: first.nextCursor! },
@@ -130,6 +135,34 @@ function createHarness() {
});
const models = {
user: {
find: () => ({
select: () => ({
lean: () => ({
exec: async () => [
{
riotAccounts: [
{
puuid: 'player',
tierHistory: [
{
queueType: 'RANKED_SOLO_5x5',
tier: 'PLATINUM',
recordedAt: new Date(SEASON_START + 4_000),
},
{
queueType: 'RANKED_SOLO_5x5',
tier: 'GOLD',
rank: 'II',
recordedAt: new Date(SEASON_START),
},
],
},
],
},
],
}),
}),
}),
findById: () => ({
exec: async () => ({
_id: userId,
@@ -168,6 +201,7 @@ function storedMatch(sequence: number, championId: number, queueId = 420) {
teamId: 100,
win: true,
kills: 5,
tripleKills: 1,
deaths: 2,
assists: 3,
totalMinionsKilled: 100,
@@ -21,6 +21,7 @@ import {
type RiotRankFilter,
} from '../riot/riot-queue.constants';
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
import { readMultiKills } from '../riot/riot-multi-kill';
import type {
ChampionStatsResponse,
ChampionStatsRow,
@@ -218,6 +219,7 @@ export class MatchHistoryService {
.map((doc) => this.toRecentMatchView(doc, context.account.puuid))
.filter((view): view is RecentMatchView => Boolean(view));
const page = views.slice(0, limit);
await this.attachRecordedRanks(params.communityId, page);
return {
matches: page,
@@ -230,6 +232,64 @@ export class MatchHistoryService {
};
}
private async attachRecordedRanks(
communityId: mongoose.Types.ObjectId,
page: RecentMatchView[],
) {
const ranked = page.filter(
(game) => game.queueId === 420 || game.queueId === 440,
);
const puuids = new Set(
ranked.flatMap((game) =>
game.teams.flatMap((team) =>
team.participants.map(({ puuid }) => puuid),
),
),
);
if (puuids.size === 0) return;
const UserModel = await this.connectionService.getModel('user');
const users = await UserModel.find({
communityId,
'riotAccounts.puuid': { $in: [...puuids] },
})
.select({ 'riotAccounts.puuid': 1, 'riotAccounts.tierHistory': 1 })
.lean()
.exec();
const history = new Map(
users.flatMap(({ riotAccounts }) =>
riotAccounts
.filter(({ puuid }) => puuids.has(puuid))
.map(({ puuid, tierHistory }) => [puuid, tierHistory ?? []] as const),
),
);
for (const game of ranked) {
const queueType =
game.queueId === 420 ? 'RANKED_SOLO_5x5' : 'RANKED_FLEX_SR';
for (const participant of game.teams.flatMap(
(team) => team.participants,
)) {
const snapshot = history
.get(participant.puuid)
?.filter(
(entry) =>
entry.queueType === queueType &&
entry.recordedAt.getTime() <= game.gameCreation,
)
.sort(
(left, right) =>
right.recordedAt.getTime() - left.recordedAt.getTime(),
)[0];
if (snapshot)
participant.tier = {
tier: snapshot.tier,
rank: snapshot.rank,
leaguePoints: snapshot.leaguePoints,
fetchedAt: snapshot.recordedAt.toISOString(),
};
}
}
}
private async resolveContext(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
@@ -593,6 +653,7 @@ export class MatchHistoryService {
championLevel: participant.champLevel,
teamPosition: participant.teamPosition || participant.individualPosition,
kills: participant.kills,
largestMultiKill: readMultiKills(participant)?.largestMultiKill,
deaths: participant.deaths,
assists: participant.assists,
kda: this.resolveKda(
@@ -1,4 +1,5 @@
import type { MatchStatsRunePerks, RiotLane } from '../global/database/schema';
import type { RecentMatchParticipantRank } from '@lolympus/contracts';
import type {
RiotQueueGroup,
RiotRankFilter,
@@ -115,6 +116,7 @@ export interface RecentMatchTeamParticipantView {
championId: number;
championLevel: number;
teamPosition: string;
tier?: RecentMatchParticipantRank;
kills: number;
deaths: number;
assists: number;
@@ -147,6 +149,7 @@ export interface RecentMatchView {
championLevel: number;
teamPosition: string;
kills: number;
largestMultiKill?: number;
deaths: number;
assists: number;
kda: number;
@@ -3,7 +3,7 @@ import { BadRequestException, ValidationPipe } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validateSync } from 'class-validator';
import mongoose from 'mongoose';
import { CreateMatchDto, JoinMatchDto } from './create-match.dto';
import { CreateMatchDto, JoinMatchDto, UpdateMatchDto } from './create-match.dto';
describe('CreateMatchDto game mode cutover', () => {
it('rejects the removed live bracket mode', () => {
@@ -61,3 +61,48 @@ describe('JoinMatchDto self-join boundary', () => {
}
});
});
describe('Grand final format validation', () => {
it('allows BO3 on creation and rejects an even game count on update', () => {
const create = plainToInstance(CreateMatchDto, {
title: 'Competition',
scheduledAt: '2026-07-13T10:00:00.000Z',
gameMode: 'double-elimination',
doubleEliminationGrandFinalGameCount: 3,
});
expect(validateSync(create)).toEqual([]);
const update = plainToInstance(UpdateMatchDto, {
doubleEliminationGrandFinalGameCount: 2,
});
expect(validateSync(update)).toEqual([
expect.objectContaining({ property: 'doubleEliminationGrandFinalGameCount' }),
]);
});
});
describe('Match event type validation', () => {
it.each(['inhouse', 'tournament', undefined])(
'accepts %s in create and update requests',
(eventType) => {
expect(
validateSync(
plainToInstance(CreateMatchDto, {
title: 'Competition',
scheduledAt: '2026-07-13T10:00:00.000Z',
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' }),
]);
});
});
@@ -1,3 +1,4 @@
import type { GrandFinalGameCount, MatchEventType } from '@lolympus/contracts';
import { Type } from 'class-transformer';
import {
ArrayMaxSize,
@@ -14,11 +15,12 @@ import {
MaxLength,
Min,
MinLength,
ValidateIf,
ValidateNested,
ValidationArguments,
ValidationOptions,
} from 'class-validator';
import { POSITIONS } from '../../global/database/schema';
import { MATCH_EVENT_TYPES, POSITIONS } from '../../global/database/schema';
import type { MatchGameMode, Position } from '../../global/database/schema';
const LIVE_MATCH_GAME_MODES = [
@@ -82,6 +84,10 @@ export class CreateMatchDto {
@MaxLength(128)
title!: string;
@ValidateIf((_object, value) => value !== undefined)
@IsIn(MATCH_EVENT_TYPES)
eventType?: MatchEventType;
@IsOptional()
@IsString()
@MaxLength(2048)
@@ -119,6 +125,10 @@ export class CreateMatchDto {
@IsBoolean()
doubleEliminationResetFinalEnabled?: boolean;
@IsOptional()
@IsIn([1, 3, 5])
doubleEliminationGrandFinalGameCount?: GrandFinalGameCount;
@IsOptional()
@IsArray()
@IsString({ each: true })
@@ -145,6 +155,10 @@ export class UpdateMatchDto {
@MaxLength(128)
title?: string;
@ValidateIf((_object, value) => value !== undefined)
@IsIn(MATCH_EVENT_TYPES)
eventType?: MatchEventType;
@IsOptional()
@IsString()
@MaxLength(2048)
@@ -183,6 +197,10 @@ export class UpdateMatchDto {
@IsBoolean()
doubleEliminationResetFinalEnabled?: boolean;
@IsOptional()
@IsIn([1, 3, 5])
doubleEliminationGrandFinalGameCount?: GrandFinalGameCount;
@IsOptional()
@IsArray()
@IsString({ each: true })
@@ -0,0 +1,168 @@
import mongoose from 'mongoose';
import {
summarizeMatchHistoryResult,
type HistoryCompetition,
} from './match-history-result';
const firstId = new mongoose.Types.ObjectId();
const secondId = new mongoose.Types.ObjectId();
const thirdId = new mongoose.Types.ObjectId();
const teams = [
{
teamId: firstId,
name: '첫 팀',
displayOrder: 1,
seedNumber: 1,
members: [],
},
{
teamId: secondId,
name: '둘째 팀',
displayOrder: 2,
seedNumber: 2,
members: [],
},
{
teamId: thirdId,
name: '셋째 팀',
displayOrder: 3,
seedNumber: 3,
members: [],
},
];
const finishedMatch = {
status: 'finished' as const,
competitionId: new mongoose.Types.ObjectId(),
teams: [],
};
const singleSeries = {
status: 'completed',
entries: [
{ teamId: secondId.toString(), gameWins: 2 },
{ teamId: firstId.toString(), gameWins: 1 },
],
outcome: { type: 'played', winnerTeamId: secondId.toString() },
};
describe('summarizeMatchHistoryResult', () => {
it('shows played scores only for one completed series between two teams', () => {
const competition: HistoryCompetition = {
teams: teams.slice(0, 2),
projection: {
series: [singleSeries],
outcome: { type: 'paired-series' },
},
};
expect(summarizeMatchHistoryResult(finishedMatch, competition)).toEqual({
type: 'score',
teamAWins: 2,
teamBWins: 1,
teamAName: '둘째 팀',
teamBName: '첫 팀',
winnerTeamName: '둘째 팀',
});
expect(
summarizeMatchHistoryResult(
{ ...finishedMatch, status: 'in-progress' },
competition,
),
).toBeUndefined();
expect(
summarizeMatchHistoryResult(finishedMatch, {
...competition,
projection: {
...competition.projection,
series: [singleSeries, singleSeries],
},
}),
).toBeUndefined();
});
it('shows adjudication without a score even if some games were played', () => {
expect(
summarizeMatchHistoryResult(finishedMatch, {
teams: teams.slice(0, 2),
projection: {
series: [
{
...singleSeries,
outcome: { ...singleSeries.outcome, type: 'forfeit' },
},
],
outcome: { type: 'paired-series' },
},
}),
).toEqual({
type: 'decision',
decision: 'forfeit',
winnerTeamName: '둘째 팀',
});
});
it('uses the tournament winner or joint leaders instead of a series score', () => {
expect(
summarizeMatchHistoryResult(finishedMatch, {
teams,
projection: {
series: [singleSeries],
outcome: {
type: 'double-elimination',
championTeamId: thirdId.toString(),
},
},
}),
).toEqual({ type: 'winners', teamNames: ['셋째 팀'] });
expect(
summarizeMatchHistoryResult(finishedMatch, {
teams,
projection: {
series: [singleSeries],
outcome: {
type: 'round-robin',
leaderTeamIds: [firstId.toString(), secondId.toString()],
},
},
}),
).toEqual({ type: 'winners', teamNames: ['첫 팀', '둘째 팀'] });
});
it('uses collected games for legacy two-team records without a Competition', () => {
const match = {
status: 'finished' as const,
teams: [
{ teamIndex: 2, name: '둘째 팀', members: [] },
{ teamIndex: 1, name: '첫 팀', members: [] },
],
result: {
winnerTeamIndex: 2,
riotMatchIds: ['KR_1'],
games: [
{
gameNumber: 1,
riotMatchId: 'KR_1',
blueTeamIndex: 1,
redTeamIndex: 2,
winnerTeamIndex: 2,
winnerSide: 'red' as const,
gameCreation: 0,
gameDuration: 1800,
participants: [],
},
],
},
};
expect(summarizeMatchHistoryResult(match)).toEqual({
type: 'score',
teamAWins: 0,
teamBWins: 1,
teamAName: '첫 팀',
teamBName: '둘째 팀',
winnerTeamName: '둘째 팀',
});
expect(
summarizeMatchHistoryResult({ ...match, competitionId: firstId }),
).toBeUndefined();
});
});
@@ -0,0 +1,121 @@
import type { MatchHistoryResult } from '@lolympus/contracts';
import type { Competition } from '../competition/competition.schema';
import type { CompetitionProjection } from '../competition/domain/competition-projector';
import type { Match } from '../global/database/schema';
type HistoryMatch = Pick<
Match,
'status' | 'competitionId' | 'teams' | 'result' | 'doubleElimination'
>;
export type HistoryCompetition = Pick<Competition, 'projection' | 'teams'>;
export function summarizeMatchHistoryResult(
match: HistoryMatch,
competition?: HistoryCompetition,
): MatchHistoryResult | undefined {
if (match.status !== 'finished') return;
if (!match.competitionId) return summarizeLegacyResult(match);
if (!competition) return;
const { series, outcome } = competition.projection as Pick<
CompetitionProjection,
'series' | 'outcome'
>;
if (!outcome) return;
const teamName = (teamId: string | null) => {
const team = competition.teams.find(
(item) => String(item.teamId) === teamId,
);
return team && (team.name.trim() || `${team.displayOrder}팀`);
};
const singleSeries = series?.length === 1 ? series[0] : undefined;
if (competition.teams.length === 2 && singleSeries?.status === 'completed') {
const decision = singleSeries.outcome;
const winnerTeamName =
decision.type === 'draw' ? undefined : teamName(decision.winnerTeamId);
if (
decision.type === 'played' ||
(decision.type === 'draw' && decision.basis.type === 'played')
) {
const [teamA, teamB] = singleSeries.entries;
return {
type: 'score',
teamAWins: teamA.gameWins,
teamBWins: teamB.gameWins,
teamAName: teamName(teamA.teamId),
teamBName: teamName(teamB.teamId),
winnerTeamName,
};
}
return { type: 'decision', decision: decision.type, winnerTeamName };
}
const winnerIds =
outcome.type === 'double-elimination'
? [outcome.championTeamId]
: outcome.type === 'round-robin'
? outcome.leaderTeamIds
: [];
const teamNames = winnerIds.map(teamName);
if (teamNames.length > 0 && teamNames.every((name) => name !== undefined)) {
return { type: 'winners', teamNames };
}
}
function summarizeLegacyResult(
match: HistoryMatch,
): MatchHistoryResult | undefined {
const placement = match.doubleElimination?.placements.firstTeamIndex;
if (placement !== undefined) {
const champion = match.teams.find((team) => team.teamIndex === placement);
if (champion) {
return {
type: 'winners',
teamNames: [champion.name.trim() || `${placement}팀`],
};
}
}
if (match.teams.length !== 2 || !match.result?.games.length) return;
const [teamA, teamB] = [...match.teams].sort(
(a, b) => a.teamIndex - b.teamIndex,
);
const { games } = match.result;
const teamIndices = new Set([teamA.teamIndex, teamB.teamIndex]);
if (
games.some(
({ blueTeamIndex, redTeamIndex }) =>
blueTeamIndex === redTeamIndex ||
!teamIndices.has(blueTeamIndex) ||
!teamIndices.has(redTeamIndex),
)
)
return;
const teamAWins = games.filter(
(game) => game.winnerTeamIndex === teamA.teamIndex,
).length;
const teamBWins = games.filter(
(game) => game.winnerTeamIndex === teamB.teamIndex,
).length;
if (teamAWins + teamBWins !== games.length) return;
const winner = match.teams.find(
(team) => team.teamIndex === match.result?.winnerTeamIndex,
);
if (
winner &&
(teamAWins === teamBWins ||
winner.teamIndex !==
(teamAWins > teamBWins ? teamA.teamIndex : teamB.teamIndex))
)
return;
return {
type: 'score',
teamAWins,
teamBWins,
teamAName: teamA.name.trim() || `${teamA.teamIndex}팀`,
teamBName: teamB.name.trim() || `${teamB.teamIndex}팀`,
winnerTeamName: winner && (winner.name.trim() || `${winner.teamIndex}팀`),
};
}
@@ -75,6 +75,7 @@ describe('presentPublicMatch', () => {
communityId: oid('2').toString(),
competitionId: oid('3').toString(),
title: '내전',
eventType: 'inhouse',
doubleEliminationResetFinalEnabled: false,
scheduledAt: '2026-07-12T10:00:00.000Z',
participants: [
@@ -1,4 +1,8 @@
import type { MatchDetailResponse, MatchTierView } from '@lolympus/contracts';
import type {
MatchDetailResponse,
MatchEventType,
MatchTierView,
} from '@lolympus/contracts';
import type {
MatchGameMode,
MatchStatus,
@@ -13,6 +17,7 @@ interface PublicMatchSource {
competitionId?: IdLike;
shortCode?: string;
title: string;
eventType?: MatchEventType;
description: string;
mapId: number;
status: MatchStatus;
@@ -21,7 +26,7 @@ interface PublicMatchSource {
gameCount: number;
gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
doubleElimination?: { resetFinalEnabled?: boolean };
doubleElimination?: { resetFinalEnabled?: boolean; grandFinalGameCount?: 1 | 3 | 5 };
hostUserId?: IdLike;
participants: Array<{
userId: IdLike;
@@ -67,6 +72,7 @@ export function presentPublicMatch(
: {}),
...(source.shortCode ? { shortCode: source.shortCode } : {}),
title: source.title,
eventType: source.eventType ?? 'inhouse',
description: source.description,
mapId: source.mapId,
status: source.status,
@@ -81,6 +87,8 @@ export function presentPublicMatch(
? {
doubleEliminationResetFinalEnabled:
source.doubleElimination?.resetFinalEnabled ?? false,
doubleEliminationGrandFinalGameCount:
source.doubleElimination?.grandFinalGameCount ?? 1,
}
: {}),
...(source.hostUserId
@@ -1,12 +1,84 @@
import 'reflect-metadata';
import { GUARDS_METADATA } from '@nestjs/common/constants';
import mongoose from 'mongoose';
import { plainToInstance } from 'class-transformer';
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from '../auth/allow-public-access.decorator';
import { ROLES_KEY } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import type { UserDocument } from '../global/database/schema';
import { UpdateMatchDto } from './dto/create-match.dto';
import { MatchController } from './match.controller';
describe('MatchController history summaries', () => {
it('only attaches the page results when requested', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = { _id: new mongoose.Types.ObjectId() };
const summary = { _id: match._id.toString() };
const historyResult = { type: 'score', teamAWins: 2, teamBWins: 1 };
const matchService = {
listPage: jest
.fn()
.mockResolvedValue({ matches: [match], total: 1, page: 1, limit: 10 }),
serialize: jest.fn().mockReturnValue(summary),
getHistoryResults: jest
.fn()
.mockResolvedValue(new Map([[summary._id, historyResult]])),
};
const controller = new MatchController(matchService as never);
await expect(
controller.listMatches(undefined, communityId),
).resolves.toMatchObject({
matches: [summary],
});
expect(matchService.getHistoryResults).not.toHaveBeenCalled();
await expect(
controller.listMatches(
undefined,
communityId,
undefined,
'10',
'1',
undefined,
undefined,
undefined,
'desc',
'true',
'tournament',
),
).resolves.toMatchObject({ matches: [{ ...summary, historyResult }] });
expect(matchService.listPage).toHaveBeenLastCalledWith(
expect.objectContaining({ eventType: 'tournament' }),
);
expect(matchService.getHistoryResults).toHaveBeenCalledWith(communityId, [
match,
]);
});
});
describe('MatchController partial updates', () => {
it('passes only supplied fields when reclassifying a match', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const user = { _id: new mongoose.Types.ObjectId(), communityId };
const matchService = {
update: jest.fn().mockResolvedValue({ participants: [] }),
serialize: jest.fn(),
};
const controller = new MatchController(matchService as never);
const body = plainToInstance(UpdateMatchDto, { eventType: 'tournament' });
await controller.updateMatch(user as UserDocument, communityId, matchId, body);
expect(matchService.update).toHaveBeenCalledWith({
communityId,
matchId,
patch: { eventType: 'tournament' },
});
});
});
describe('MatchController participant access', () => {
function createController() {
const joinedMatch = { _id: new mongoose.Types.ObjectId() };
+92 -6
View File
@@ -1,6 +1,9 @@
import type {
HallOfFameResponse,
MatchDetailResponse,
MatchEventType,
MatchListResponse,
MatchListView,
} from '@lolympus/contracts';
import {
BadRequestException,
@@ -16,6 +19,7 @@ import {
Query,
UseGuards,
} from '@nestjs/common';
import { isISO8601 } from 'class-validator';
import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { CurrentUser } from '../auth/current-user.decorator';
@@ -23,6 +27,7 @@ import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { MatchStatus, UserDocument } from '../global/database/schema';
import { MATCH_EVENT_TYPES } from '../global/database/schema';
import {
AddParticipantDto,
CreateMatchDto,
@@ -51,6 +56,7 @@ export class MatchController {
hostUserId: currentUser._id,
data: {
title: body.title,
eventType: body.eventType,
description: body.description ?? '',
mapId: body.mapId ?? 11,
scheduledAt: body.scheduledAt,
@@ -60,6 +66,8 @@ export class MatchController {
roundRobinMaxRounds: body.roundRobinMaxRounds,
doubleEliminationResetFinalEnabled:
body.doubleEliminationResetFinalEnabled,
doubleEliminationGrandFinalGameCount:
body.doubleEliminationGrandFinalGameCount,
prizes: body.prizes ?? [],
notices: body.notices ?? [],
schedule: body.schedule ?? [],
@@ -82,21 +90,63 @@ export class MatchController {
@Query('scheduledFrom') scheduledFrom?: string,
@Query('scheduledTo') scheduledTo?: string,
@Query('sort') sort?: 'asc' | 'desc',
@Query('includeResults') includeResults?: string,
@Query('eventType') eventType?: MatchEventType,
@Query('view') view?: MatchListView,
@Query('asOf') asOf?: string,
): Promise<MatchListResponse> {
if (eventType !== undefined && !MATCH_EVENT_TYPES.includes(eventType)) {
throw new BadRequestException('Invalid eventType.');
}
if (
view !== undefined &&
view !== 'active' &&
view !== 'upcoming' &&
view !== 'history'
) {
throw new BadRequestException('Invalid view.');
}
if (
view &&
(status !== undefined ||
scheduledFrom !== undefined ||
scheduledTo !== undefined)
) {
throw new BadRequestException(
'view cannot be combined with status or schedule filters.',
);
}
const asOfDate = this.toOptionalDate(asOf);
if (
asOf !== undefined &&
(typeof asOf !== 'string' ||
!isISO8601(asOf, { strict: true, strictSeparator: true }) ||
!asOfDate)
)
throw new BadRequestException('Invalid asOf.');
const result = await this.matchService.listPage({
communityId,
status,
eventType,
limit: this.toOptionalNumber(limit),
page: this.toOptionalNumber(page),
offset: this.toOptionalNumber(offset),
scheduledFrom: this.toOptionalDate(scheduledFrom),
scheduledTo: this.toOptionalDate(scheduledTo),
sort,
...(view ? { view, asOf: asOfDate } : {}),
});
const historyResults =
includeResults === 'true'
? await this.matchService.getHistoryResults(communityId, result.matches)
: undefined;
const eventProgress = view
? await this.matchService.getEventProgress(result.matches)
: undefined;
return {
...result,
matches: result.matches.map((match) =>
this.matchService.serialize(match, {
matches: result.matches.map((match) => {
const summary = this.matchService.serialize(match, {
...(currentUser
? {
joined: match.participants.some((participant) =>
@@ -104,11 +154,28 @@ export class MatchController {
),
}
: {}),
}),
),
});
const historyResult = historyResults?.get(summary._id);
return {
...summary,
...(historyResult ? { historyResult } : {}),
...(eventProgress
? { eventProgress: eventProgress.get(summary._id) }
: {}),
};
}),
};
}
@Get('hall-of-fame')
@AllowPublicAccess()
public getHallOfFame(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
): Promise<HallOfFameResponse> {
return this.matchService.getHallOfFame(communityId);
}
@Get(':matchId')
@AllowPublicAccess()
public async getMatch(
@@ -118,7 +185,7 @@ export class MatchController {
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
): Promise<MatchDetailResponse> {
const match = await this.matchService.getById(matchId, communityId);
return this.matchService.serialize(match, {
const summary = this.matchService.serialize(match, {
joined: Boolean(
currentUser &&
match.participants.some((participant) =>
@@ -126,6 +193,8 @@ export class MatchController {
),
),
});
const progress = await this.matchService.getEventProgress([match]);
return { ...summary, eventProgress: progress.get(summary._id) };
}
@Patch(':matchId')
@@ -142,7 +211,7 @@ export class MatchController {
const match = await this.matchService.update({
matchId,
communityId,
patch: body,
patch: mongoose.omitUndefined({ ...body }),
});
return this.matchService.serialize(match, {
joined: match.participants.some((participant) =>
@@ -241,6 +310,23 @@ export class MatchController {
}
// 관리자 전용 — 참가자 강제 제외.
@Delete(':matchId/participants')
@Roles('admin', 'owner', 'member')
@UseGuards(RolesGuard)
public async cancelJoin(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
): Promise<MatchDetailResponse> {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.cancelJoin({
matchId,
userId: currentUser._id,
});
return this.matchService.serialize(match, { joined: false });
}
@Delete(':matchId/participants/:userId')
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
@@ -2,6 +2,104 @@ import mongoose from 'mongoose';
import { MatchService } from './match.service';
describe('MatchService', () => {
it('selects the official hall-of-fame roster by team ID when names repeat', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const championId = new mongoose.Types.ObjectId();
const captainUserId = new mongoose.Types.ObjectId();
const MatchModel = {
aggregate: jest.fn().mockReturnValue({
exec: async () => [
{
_id: matchId,
title: '멸망전',
official: [
{
projection: {
outcome: {
type: 'double-elimination',
championTeamId: championId.toString(),
},
},
teams: [
{
teamId: new mongoose.Types.ObjectId(),
name: '별무리',
members: [],
},
{
teamId: championId,
name: '별무리',
captainUserId,
members: [
{
userId: captainUserId,
assignedPosition: 'TOP',
gameName: '별빛',
},
],
},
],
},
],
},
],
}),
};
const CompetitionModel = { collection: { name: 'competition' } };
const service = new MatchService(
{
getModel: async (name: string) =>
name === 'match' ? MatchModel : CompetitionModel,
} as never,
{} as never,
{} as never,
{} as never,
);
await expect(service.getHallOfFame(communityId)).resolves.toMatchObject({
match: { id: matchId.toString(), title: '멸망전' },
teams: [
{
name: '별무리',
captainUserId: captainUserId.toString(),
members: [
{
userId: captainUserId.toString(),
position: 'TOP',
gameName: '별빛',
},
],
},
],
});
const [pipeline] = MatchModel.aggregate.mock.calls[0];
expect(pipeline[0]).toMatchObject({
$match: {
communityId,
eventType: 'tournament',
$or: [
{ competitionId: { $type: 'objectId' } },
expect.objectContaining({ competitionId: null, status: 'finished' }),
],
},
});
expect(pipeline[0].$match).not.toHaveProperty('status');
expect(pipeline[2]).toMatchObject({
$lookup: {
pipeline: [
expect.objectContaining({
$match: expect.objectContaining({
communityId,
phase: 'completed',
}),
}),
expect.anything(),
],
},
});
});
function createServiceWithCreateModels() {
const createdPayloads: Record<string, unknown>[] = [];
const MatchModel = {
@@ -195,7 +293,7 @@ describe('MatchService', () => {
expect(MatchModel.find).toHaveBeenCalledWith({ communityId });
expect(MatchModel.countDocuments).toHaveBeenCalledWith({ communityId });
expect(sort).toHaveBeenCalledWith({ scheduledAt: -1 });
expect(sort).toHaveBeenCalledWith({ scheduledAt: -1, _id: -1 });
expect(skip).toHaveBeenCalledWith(5);
expect(limit).toHaveBeenCalledWith(5);
expect(page).toEqual({
@@ -254,7 +352,7 @@ describe('MatchService', () => {
communityId,
scheduledAt: { $gte: scheduledFrom },
});
expect(sort).toHaveBeenCalledWith({ scheduledAt: 1 });
expect(sort).toHaveBeenCalledWith({ scheduledAt: 1, _id: 1 });
});
it('filters past matches and keeps newest first for history sections', async () => {
@@ -277,9 +375,31 @@ describe('MatchService', () => {
communityId,
scheduledAt: { $lt: scheduledTo },
});
expect(sort).toHaveBeenCalledWith({ scheduledAt: -1 });
expect(sort).toHaveBeenCalledWith({ scheduledAt: -1, _id: -1 });
});
it.each([
['inhouse', { $in: ['inhouse', null] }],
['tournament', 'tournament'],
] as const)(
'filters both results and pagination totals for %s events',
async (eventType, expectedEventType) => {
const communityId = new mongoose.Types.ObjectId();
const scheduledTo = new Date('2026-06-08T12:00:00.000Z');
const { service, MatchModel } = createServiceWithListModel();
await service.listPage({ communityId, scheduledTo, eventType });
const expectedFilter = {
communityId,
scheduledAt: { $lt: scheduledTo },
eventType: expectedEventType,
};
expect(MatchModel.find).toHaveBeenCalledWith(expectedFilter);
expect(MatchModel.countDocuments).toHaveBeenCalledWith(expectedFilter);
},
);
it('uses saved user preferences when joining without explicit positions', async () => {
const communityId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
@@ -531,6 +651,7 @@ describe('MatchService', () => {
gameCount: 5,
gameMode: 'double-elimination',
doubleEliminationResetFinalEnabled: true,
doubleEliminationGrandFinalGameCount: 3,
},
});
@@ -543,6 +664,7 @@ describe('MatchService', () => {
doubleElimination: {
teamCount: 4,
resetFinalEnabled: true,
grandFinalGameCount: 3,
resetFinalCreated: false,
seeds: [],
bracketMatches: [],
@@ -635,6 +757,26 @@ describe('MatchService', () => {
expect(match.set).not.toHaveBeenCalled();
});
it('allows reclassifying a finished match without altering its competition settings', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = {
communityId,
status: 'finished',
set: jest.fn(),
save: jest.fn().mockResolvedValue(undefined),
};
const { service } = createService(match);
await service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { eventType: 'tournament' },
});
expect(match.set).toHaveBeenCalledWith({ eventType: 'tournament' });
expect(match.save).toHaveBeenCalledTimes(1);
});
it('rejects game count changes after recruiting', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = {
+304 -2
View File
@@ -1,3 +1,12 @@
import type {
HallOfFameResponse,
MatchEventStage,
MatchEventType,
MatchHistoryResult,
MatchId,
MatchListView,
UserId,
} from '@lolympus/contracts';
import {
BadRequestException,
ConflictException,
@@ -8,6 +17,7 @@ import {
import mongoose from 'mongoose';
import { MatchStatsService } from '../community-stats/match-stats.service';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import type { CompetitionProjection } from '../competition/domain/competition-projector';
import { ConnectionService } from '../global/database/connection.service';
import {
Match,
@@ -20,6 +30,10 @@ import {
} from '../global/database/schema';
import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants';
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
import {
summarizeMatchHistoryResult,
type HistoryCompetition,
} from './match-history-result';
import { presentPublicMatch } from './match-public.presenter';
const MATCH_SHORT_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
@@ -32,6 +46,7 @@ const DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT = 3;
interface DoubleEliminationConfigInput {
doubleEliminationResetFinalEnabled?: boolean;
doubleEliminationGrandFinalGameCount?: 1 | 3 | 5;
}
interface CreateMatchParams {
@@ -51,10 +66,13 @@ interface UpdateMatchParams {
interface ListMatchesQuery {
communityId: mongoose.Types.ObjectId;
status?: MatchStatus;
eventType?: MatchEventType;
limit?: number;
scheduledFrom?: Date;
scheduledTo?: Date;
sort?: 'asc' | 'desc';
view?: MatchListView;
asOf?: Date;
}
interface ListMatchesPageQuery extends ListMatchesQuery {
@@ -65,10 +83,15 @@ interface ListMatchesPageQuery extends ListMatchesQuery {
interface MatchListFilter {
communityId: mongoose.Types.ObjectId;
status?: MatchStatus;
eventType?: MatchEventType | { $in: (MatchEventType | null)[] };
scheduledAt?: {
$gte?: Date;
$lt?: Date;
};
$or?: Array<{
status: MatchStatus | { $in: MatchStatus[] };
scheduledAt?: { $lt: Date };
}>;
}
interface JoinMatchParams {
@@ -170,6 +193,244 @@ export class MatchService {
};
}
public async getHistoryResults(
communityId: mongoose.Types.ObjectId,
matches: readonly MatchDocument[],
): Promise<Map<string, MatchHistoryResult>> {
const finished = matches.filter((match) => match.status === 'finished');
const competitionIds = finished.flatMap((match) =>
match.competitionId ? [match.competitionId] : [],
);
const competitions = new Map<string, HistoryCompetition>();
if (competitionIds.length > 0) {
const CompetitionModel =
await this.connectionService.getModel('competition');
const completed = await CompetitionModel.find({
_id: { $in: competitionIds },
communityId,
phase: 'completed',
})
.select({
matchId: 1,
'teams.teamId': 1,
'teams.name': 1,
'teams.displayOrder': 1,
'projection.outcome': 1,
'projection.series': 1,
})
.lean()
.exec();
for (const competition of completed) {
competitions.set(competition.matchId.toString(), competition);
}
}
const results = new Map<string, MatchHistoryResult>();
for (const match of finished) {
const id = match._id.toString();
const result = summarizeMatchHistoryResult(match, competitions.get(id));
if (result) results.set(id, result);
}
return results;
}
public async getHallOfFame(
communityId: mongoose.Types.ObjectId,
): Promise<HallOfFameResponse> {
const [MatchModel, CompetitionModel] = await Promise.all([
this.connectionService.getModel('match'),
this.connectionService.getModel('competition'),
]);
const legacyChampion = {
competitionId: null,
status: 'finished',
'doubleElimination.placements.firstTeamIndex': { $type: 'number' },
};
const [match] = await MatchModel.aggregate<
Pick<Match, 'title' | 'teams' | 'participants' | 'doubleElimination'> & {
_id: mongoose.Types.ObjectId;
official: HistoryCompetition[];
}
>([
{
$match: {
communityId,
eventType: 'tournament',
$or: [{ competitionId: { $type: 'objectId' } }, legacyChampion],
},
},
{ $sort: { scheduledAt: -1, _id: -1 } },
{
$lookup: {
from: CompetitionModel.collection.name,
localField: 'competitionId',
foreignField: '_id',
let: { matchId: '$_id' },
pipeline: [
{
$match: {
communityId,
phase: 'completed',
$expr: { $eq: ['$matchId', '$$matchId'] },
$or: [
{ 'projection.outcome.type': 'double-elimination' },
{
'projection.outcome.type': 'round-robin',
'projection.outcome.leaderTeamIds.0': { $exists: true },
},
],
},
},
{ $project: { teams: 1, 'projection.outcome': 1 } },
],
as: 'official',
},
},
{
$match: { $or: [{ 'official.0': { $exists: true } }, legacyChampion] },
},
{ $limit: 1 },
{
$project: {
title: 1,
teams: 1,
participants: 1,
doubleElimination: 1,
official: 1,
},
},
]).exec();
if (!match) return { match: null, teams: [] };
const featuredMatch = {
id: match._id.toString() as MatchId,
title: match.title,
};
const [competition] = match.official;
if (competition) {
const { outcome } = competition.projection as Pick<
CompetitionProjection,
'outcome'
>;
const winnerIds =
outcome?.type === 'double-elimination'
? [outcome.championTeamId]
: outcome?.type === 'round-robin'
? outcome.leaderTeamIds
: [];
const teams = competition.teams
.filter((team) => winnerIds.includes(team.teamId.toString()))
.map((team) => ({
name: team.name.trim() || `${team.displayOrder}팀`,
captainUserId: team.captainUserId?.toString() as UserId | undefined,
members: team.members.map((member) => ({
userId: member.userId.toString() as UserId,
position: POSITIONS.find(
(position) => position === member.assignedPosition,
),
gameName: member.gameName,
tagLine: member.tagLine,
profileIconId: member.profileIconId,
})),
}));
return { match: featuredMatch, teams };
}
const placement = match.doubleElimination?.placements.firstTeamIndex;
const champion =
placement === undefined
? undefined
: match.teams.find((team) => team.teamIndex === placement);
if (!champion) return { match: featuredMatch, teams: [] };
const participants = new Map(
match.participants.map((participant) => [
participant.userId.toString(),
participant,
]),
);
return {
match: featuredMatch,
teams: [
{
name: champion.name.trim() || `${champion.teamIndex}팀`,
captainUserId: champion.captainUserId?.toString() as
| UserId
| undefined,
members: champion.members.map((member) => {
const userId = member.userId.toString() as UserId;
const participant = participants.get(userId);
return {
userId,
position: member.assignedPosition,
gameName: participant?.gameName,
tagLine: participant?.tagLine,
profileIconId: participant?.profileIconId,
};
}),
},
],
};
}
public async getEventProgress(matches: readonly MatchDocument[]) {
const teamBuilding = matches.filter(
(match) => match.status === 'team-built',
);
const byMatchId = new Map<string, MatchEventStage>();
if (teamBuilding.length > 0) {
const AuctionModel = await this.connectionService.getModel('auction');
const auctions = await AuctionModel.find({
matchId: { $in: teamBuilding.map(({ _id }) => _id) },
})
.select({
matchId: 1,
phase: 1,
auctionLifecycleId: 1,
startupCompleted: 1,
matchSideEffectStatus: 1,
})
.lean()
.exec();
for (const auction of auctions) {
const match = teamBuilding.find(({ _id }) =>
_id.equals(auction.matchId),
);
if (
!match ||
(auction.auctionLifecycleId &&
auction.auctionLifecycleId ===
match.lastCancelledAuctionLifecycleId)
)
continue;
if (
auction.matchSideEffectStatus === 'failed' ||
auction.startupCompleted === false ||
(auction.phase === 'complete' &&
(auction.matchSideEffectStatus === 'pending' ||
auction.matchSideEffectStatus === 'processing'))
) {
byMatchId.set(match._id.toString(), 'team-check');
} else if (auction.phase !== 'complete') {
byMatchId.set(match._id.toString(), 'auction');
}
}
}
return new Map(
matches.map((match) => {
const id = match._id.toString();
const stage: MatchEventStage =
match.status !== 'team-built'
? match.status
: (byMatchId.get(id) ??
(match.teams.length >= 2 &&
(match.competitionId || match.teamBuiltAt)
? 'team-ready'
: 'team-check'));
return [id, { stage }] as const;
}),
);
}
public async ensureShortCode(match: MatchDocument): Promise<MatchDocument> {
if (match.shortCode) return match;
@@ -232,6 +493,14 @@ export class MatchService {
'maxParticipants, gameCount, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
);
}
if (
previousStatus !== 'recruiting' &&
'doubleEliminationGrandFinalGameCount' in params.patch
) {
throw new BadRequestException(
'Grand final game count can only be changed while recruiting.',
);
}
const patchToSet =
previousStatus === 'recruiting'
? this.normalizeMatchConfig({
@@ -246,6 +515,10 @@ export class MatchService {
params.patch.doubleEliminationResetFinalEnabled ??
params.patch.doubleElimination?.resetFinalEnabled ??
match.doubleElimination?.resetFinalEnabled,
doubleEliminationGrandFinalGameCount:
params.patch.doubleEliminationGrandFinalGameCount ??
params.patch.doubleElimination?.grandFinalGameCount ??
match.doubleElimination?.grandFinalGameCount,
})
: this.stripMatchConfigInput(params.patch);
match.set(patchToSet);
@@ -360,6 +633,9 @@ export class MatchService {
input.doubleEliminationResetFinalEnabled ??
input.doubleElimination?.resetFinalEnabled ??
false,
grandFinalGameCount:
input.doubleEliminationGrandFinalGameCount ??
input.doubleElimination?.grandFinalGameCount,
resetFinalCreated: false,
seeds: [],
bracketMatches: [],
@@ -381,6 +657,7 @@ export class MatchService {
>(input: T): Partial<Match> {
const patch = { ...input };
delete patch.doubleEliminationResetFinalEnabled;
delete patch.doubleEliminationGrandFinalGameCount;
return patch;
}
@@ -649,6 +926,27 @@ export class MatchService {
communityId: query.communityId,
};
if (query.status) filter.status = query.status;
if (query.view === 'history') filter.status = 'finished';
if (query.view === 'upcoming') {
filter.status = 'recruiting';
filter.scheduledAt = { $gte: query.asOf ?? new Date() };
}
if (query.view === 'active') {
filter.$or = [
{ status: { $in: ['team-built', 'in-progress'] } },
{
status: 'recruiting',
scheduledAt: { $lt: query.asOf ?? new Date() },
},
];
}
if (query.eventType) {
// MongoDB matches missing fields as well as explicit null values.
filter.eventType =
query.eventType === 'inhouse'
? { $in: ['inhouse', null] }
: query.eventType;
}
if (query.scheduledFrom || query.scheduledTo) {
filter.scheduledAt = {};
if (query.scheduledFrom) filter.scheduledAt.$gte = query.scheduledFrom;
@@ -657,8 +955,12 @@ export class MatchService {
return filter;
}
private buildListSort(sort?: 'asc' | 'desc'): { scheduledAt: 1 | -1 } {
return { scheduledAt: sort === 'asc' ? 1 : -1 };
private buildListSort(sort?: 'asc' | 'desc'): {
scheduledAt: 1 | -1;
_id: 1 | -1;
} {
const direction = sort === 'asc' ? 1 : -1;
return { scheduledAt: direction, _id: direction };
}
private normalizeListLimit(limit?: number): number {
@@ -0,0 +1,191 @@
import { Test } from '@nestjs/testing';
import { ConfigService } from '@nestjs/config';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service';
import { RedisService } from '../global/redis/redis.service';
import { DistributedLockService } from '../global/redis/distributed-lock.service';
import { LegacyImportService } from '../legacy-import/legacy-import.service';
import { TournamentResultService } from '../tournament-result/tournament-result.service';
import { RiotModule } from './riot.module';
import { RiotRecentMatchesService } from './riot-recent-matches.service';
import type { RiotMatchDto } from './riot.types';
const detail = {
metadata: { matchId: 'KR_1', participants: [] },
info: { participants: [], teams: [], queueId: 420 },
} as unknown as RiotMatchDto;
describe('Riot raw persistence recovery hooks', () => {
it('resolves the Riot and community stats providers without external connections', async () => {
const external = new Set<unknown>([
ConnectionService,
RedisService,
DistributedLockService,
ConfigService,
]);
const module = await Test.createTestingModule({ imports: [RiotModule] })
.useMocker((token) => (external.has(token) ? {} : undefined))
.compile();
expect(module.get(RiotRecentMatchesService)).toBeInstanceOf(
RiotRecentMatchesService,
);
expect(module.get(CommunityStatsService)).toBeInstanceOf(
CommunityStatsService,
);
await module.close();
});
it.each([
['legacy', false],
['legacy', true],
['tournament', false],
['tournament', true],
] as const)(
'returns saved %s raw data even if stats recovery fails (%s), without retrying stored raw',
async (kind, recoveryFails) => {
let stored: { raw: RiotMatchDto } | null = null;
const events: string[] = [];
const updateOne = jest.fn(() => ({
exec: async () => {
stored = { raw: detail };
events.push('save');
},
}));
const connection = {
getModel: async () => ({
findOne: () => ({ exec: async () => stored }),
updateOne,
}),
};
const getMatch = jest.fn().mockResolvedValue(detail);
const refreshForRiotMatches = jest.fn(async () => {
expect(stored?.raw).toBe(detail);
events.push('refresh');
if (recoveryFails) throw new Error('Stats unavailable');
});
const stats = { refreshForRiotMatches };
const service =
kind === 'legacy'
? new LegacyImportService(
connection as never,
{} as never,
{ getMatch } as never,
stats as never,
{} as never,
{} as never,
{} as never,
{} as never,
)
: new TournamentResultService(
connection as never,
{ getMatch } as never,
{} as never,
stats as never,
{} as never,
{} as never,
{} as never,
{} as never,
);
const archive = service as unknown as {
ensureRiotMatchPersisted: (
id: string,
region: string,
) => Promise<RiotMatchDto>;
};
expect(await archive.ensureRiotMatchPersisted('KR_1', 'asia')).toBe(
detail,
);
expect(await archive.ensureRiotMatchPersisted('KR_1', 'asia')).toBe(
detail,
);
expect(events).toEqual(['save', 'refresh']);
expect(getMatch).toHaveBeenCalledTimes(1);
expect(refreshForRiotMatches).toHaveBeenCalledWith(['KR_1']);
},
);
it.each([false, true])(
'refreshes only newly fetched recent matches and tolerates recovery failure (%s)',
async (recoveryFails) => {
const stored = new Map<string, { matchId: string; raw: RiotMatchDto }>([
['KR_2', { matchId: 'KR_2', raw: detail }],
]);
const refreshForRiotMatches = jest.fn(async () => {
expect(stored.has('KR_1')).toBe(true);
if (recoveryFails) throw new Error('Stats unavailable');
});
const getMatch = jest.fn().mockResolvedValue(detail);
const service = new RiotRecentMatchesService(
{
getModel: async () => ({
find: () => query([...stored.values()]),
updateOne: () => ({
exec: async () => {
stored.set('KR_1', { matchId: 'KR_1', raw: detail });
},
}),
}),
} as never,
{ getMatchIdsByPuuid: async () => ['KR_1'], getMatch } as never,
{
runWithLock: async (
_options: unknown,
operation: () => Promise<unknown>,
) => operation(),
} as never,
{ refreshForRiotMatches } as never,
);
await service.syncRecentMatches({ puuid: 'player' });
await service.syncRecentMatches({ puuid: 'player' });
expect(getMatch).toHaveBeenCalledTimes(1);
expect(refreshForRiotMatches).toHaveBeenCalledTimes(1);
expect(refreshForRiotMatches).toHaveBeenCalledWith(['KR_1']);
},
);
it('skips stats recovery for duplicate legacy import facts', async () => {
const refreshForRiotMatches = jest.fn();
const service = new LegacyImportService(
{ getModel: async () => ({ exists: async () => true }) } as never,
{} as never,
{} as never,
{ refreshForRiotMatches } as never,
{} as never,
{
runWithLock: async (
_options: unknown,
operation: () => Promise<unknown>,
) => operation(),
} as never,
{} as never,
{} as never,
);
const importer = service as unknown as {
importSingleMatch: (
id: string,
job: unknown,
users: unknown,
) => Promise<string>;
};
expect(await importer.importSingleMatch('KR_1', {}, {})).toBe('duplicate');
expect(refreshForRiotMatches).not.toHaveBeenCalled();
});
});
function query<T>(value: T) {
return {
select() {
return this;
},
lean() {
return this;
},
sort() {
return this;
},
limit() {
return this;
},
exec: async () => value,
};
}
@@ -0,0 +1,28 @@
import type { RiotMatchParticipantDto } from './riot.types';
export function readMultiKills(participant?: RiotMatchParticipantDto) {
if (!participant) return undefined;
const count = (key: string) => {
const value = participant[key];
return typeof value === 'number' && Number.isInteger(value) && value > 0
? value
: 0;
};
const doubleKills = count('doubleKills');
const tripleKills = count('tripleKills');
const quadraKills = count('quadraKills');
const pentaKills = count('pentaKills');
const largestMultiKill = Math.max(
count('largestMultiKill'),
pentaKills ? 5 : quadraKills ? 4 : tripleKills ? 3 : doubleKills ? 2 : 0,
);
return {
doubleKills,
tripleKills,
quadraKills,
pentaKills,
largestMultiKill,
};
}
@@ -1,4 +1,5 @@
import { Injectable, Logger } from '@nestjs/common';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import type {
RiotMatchDocument,
RiotMatch as StoredRiotMatch,
@@ -23,6 +24,7 @@ export class RiotRecentMatchesService {
private readonly connectionService: ConnectionService,
private readonly matchService: RiotMatchService,
private readonly distributedLockService: DistributedLockService,
private readonly communityStatsService: CommunityStatsService,
) {}
public async syncRecentMatches(params: {
@@ -34,6 +36,7 @@ export class RiotRecentMatchesService {
const region = params.region ?? DEFAULT_REGION;
const limit = params.limit ?? RIOT_RECENT_MATCH_LIMIT;
const queueId = params.queueId ?? RIOT_SOLO_QUEUE_ID;
const savedMatchIds = new Set<string>();
const result = await this.distributedLockService.runWithLock(
{
lockKey: `distributed-lock:riot-recent-matches:sync:puuid:${params.puuid}`,
@@ -57,6 +60,7 @@ export class RiotRecentMatchesService {
await this.connectionService.getModel('riotMatch');
const existingMatches = await RiotMatchModel.find({
matchId: { $in: matchIds },
'raw.info': { $exists: true },
})
.select({ matchId: 1 })
.lean()
@@ -94,9 +98,10 @@ export class RiotRecentMatchesService {
await RiotMatchModel.updateOne(
{ matchId: dto.metadata.matchId },
{ $setOnInsert: payload },
{ $set: payload },
{ upsert: true },
).exec();
savedMatchIds.add(dto.metadata.matchId);
} catch (error: unknown) {
this.logger.warn(
`Skipping Riot match ${matchId} while syncing ${params.puuid}: ${
@@ -111,7 +116,19 @@ export class RiotRecentMatchesService {
},
);
return result ?? this.loadFromDb({ puuid: params.puuid, limit, queueId });
const matches =
result ??
(await this.loadFromDb({ puuid: params.puuid, limit, queueId }));
if (savedMatchIds.size > 0) {
await this.communityStatsService
.refreshForRiotMatches([...savedMatchIds])
.catch((error: unknown) => {
this.logger.warn(
`Stats recovery failed after recent match sync: ${String(error)}`,
);
});
}
return matches;
}
public async ensureFreshForQueue(params: {
+3 -2
View File
@@ -1,4 +1,5 @@
import { Module } from '@nestjs/common';
import { forwardRef, Module } from '@nestjs/common';
import { CommunityStatsModule } from '../community-stats/community-stats.module';
import { SecretModule } from '../global/secret/secret.module';
import { RiotAccountEnrichmentService } from './riot-account-enrichment.service';
import { RiotAccountService } from './riot-account.service';
@@ -15,7 +16,7 @@ import { RiotSummonerService } from './riot-summoner.service';
import { RiotWebhookController } from './riot-webhook.controller';
@Module({
imports: [SecretModule],
imports: [SecretModule, forwardRef(() => CommunityStatsModule)],
controllers: [RiotWebhookController, RiotDdragonController],
providers: [
RiotRateLimiterService,
@@ -975,6 +975,7 @@ export class TournamentCodeService {
shuffledTeamIndexes,
{
resetFinalEnabled: match.doubleElimination?.resetFinalEnabled ?? false,
grandFinalGameCount: match.doubleElimination?.grandFinalGameCount,
winnerBracketGameCount:
match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
},
@@ -203,7 +203,10 @@ describe('TournamentResultService Competition cutover', () => {
connectionService as never,
{ getMatch: jest.fn().mockResolvedValue(detail) } as never,
{} as never,
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
{
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as never,
{
runWithLock: jest.fn(),
runWithRenewedLock: jest.fn(),
@@ -312,7 +312,10 @@ function pollHarness(params: {
connectionService as never,
riotMatchService as never,
riotJobQueueService as never,
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
{
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as never,
distributedLockService as never,
{ bootstrap: jest.fn().mockResolvedValue(readyCompetition) } as never,
commandService as never,
@@ -717,7 +717,9 @@ export class TournamentResultService {
const stored = await RiotMatchModel.findOne({
matchId: riotMatchId,
}).exec();
if (isRiotMatchDto(stored?.raw)) return stored.raw;
if (isRiotMatchDto(stored?.raw)) {
return stored.raw;
}
const dto = await this.riotMatchService.getMatch(riotMatchId, { region });
const payload: Partial<StoredRiotMatch> = {
@@ -732,9 +734,16 @@ export class TournamentResultService {
};
await RiotMatchModel.updateOne(
{ matchId: dto.metadata.matchId },
{ $setOnInsert: payload },
{ $set: payload },
{ upsert: true },
).exec();
await this.communityStatsService
.refreshForRiotMatches([dto.metadata.matchId])
.catch((error: unknown) => {
this.logger.warn(
`Stats recovery failed after saving ${dto.metadata.matchId}: ${errorMessage(error)}`,
);
});
return dto;
}
+3 -1
View File
@@ -19,10 +19,13 @@
"preview": "vite preview"
},
"dependencies": {
"@astryxdesign/core": "0.7.11",
"@astryxdesign/theme-neutral": "0.7.11",
"@azure/msal-browser": "^5.8.0",
"@azure/msal-react": "^5.3.1",
"@lolympus/contracts": "workspace:*",
"@newrelic/browser-agent": "^1.318.0",
"@stylexjs/stylex": "0.19.1",
"@tanstack/react-query": "^5.100.1",
"lucide-react": "^1.14.0",
"react": "^19.2.8",
@@ -38,7 +41,6 @@
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"daisyui": "^5.5.19",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
-1
View File
@@ -1 +0,0 @@
/* App-specific styles — currently using Tailwind + daisyUI */
+256 -61
View File
@@ -1,10 +1,19 @@
import { BrowserRouter, Link, Route, Routes } from "react-router";
import type { ReactNode } from "react";
import {
BrowserRouter,
Link,
matchPath,
Navigate,
Route,
Routes,
useLocation,
useNavigate,
} from "react-router";
import { useState, type FormEvent, type ReactNode } from "react";
import { useMsal } from "@azure/msal-react";
import { Moon, Sun } from "lucide-react";
import { LogOut, Moon, Search, Sun } from "lucide-react";
import DevAuthSwitcher from "./components/DevAuthSwitcher";
import { DEFAULT_COMMUNITY_ID, setTheme, useTheme } from "./config";
import { useCommunity } from "./api/hooks";
import { useCommunity, useMatch, useMe } from "./api/hooks";
import { isMsalConfigured } from "./lib/auth/msal.config";
import AuthCallbackPage from "./pages/AuthCallback";
import HomePage from "./pages/HomePage";
@@ -20,6 +29,11 @@ import LegacyImportPage from "./pages/admin/LegacyImportPage";
import LegacyMatchesPage from "./pages/admin/LegacyMatchesPage";
import MatchAdminPage from "./pages/admin/MatchAdminPage";
import TournamentCodesPage from "./pages/admin/TournamentCodesPage";
import { PlainPage, Tooltip, pageWidthClass } from "./ui";
const NAV_ICON_BUTTON_CLASS =
"grid size-10 shrink-0 place-items-center rounded-field text-content-muted transition-colors hover:bg-sunken-strong hover:text-content md:size-11";
function MsalHeaderActions() {
const { accounts, instance } = useMsal();
@@ -28,7 +42,7 @@ function MsalHeaderActions() {
if (!account) {
return (
<Link
className="btn btn-ghost btn-sm px-2 text-base-content/60 hover:text-base-content"
className="inline-flex h-10 items-center whitespace-nowrap rounded-full border border-line-strong px-3.5 text-sm font-semibold text-content transition-colors hover:bg-sunken md:h-11 md:px-4 md:text-[15px]"
to="/login"
>
로그인
@@ -36,15 +50,24 @@ function MsalHeaderActions() {
);
}
const name = account.name ?? account.username;
return (
<button
type="button"
className="btn btn-ghost btn-sm px-3 max-w-[45vw] sm:max-w-none"
onClick={() => void instance.logoutRedirect()}
>
<span className="truncate">{account.name ?? account.username}</span>
<span className="hidden shrink-0 sm:inline">로그아웃</span>
</button>
<div className="flex min-w-0 items-center gap-1">
<span className="hidden max-w-40 truncate text-sm font-medium text-content-muted lg:block">
{name}
</span>
<Tooltip content="로그아웃" placement="below">
<button
type="button"
className={NAV_ICON_BUTTON_CLASS}
aria-label={`${name} 로그아웃`}
onClick={() => void instance.logoutRedirect()}
>
<LogOut className="size-[18px] md:size-5" aria-hidden="true" />
</button>
</Tooltip>
</div>
);
}
@@ -56,32 +79,187 @@ function ThemeToggle() {
const Icon = nextTheme === "dark" ? Moon : Sun;
return (
<span className="tooltip tooltip-bottom" data-tip={label}>
<Tooltip content={label} placement="below">
<button
type="button"
className="btn btn-ghost btn-sm btn-square text-base-content/60 hover:text-base-content"
className={NAV_ICON_BUTTON_CLASS}
aria-label={label}
onClick={() => setTheme(nextTheme)}
>
<Icon className="size-4" aria-hidden="true" />
<Icon className="size-[18px] md:size-5" aria-hidden="true" />
</button>
</span>
</Tooltip>
);
}
function PrimaryNavLink({
to,
sectionPaths = [],
children,
}: {
to: string;
sectionPaths?: string[];
children: ReactNode;
}) {
const { pathname } = useLocation();
const current = matchPath(to, pathname)
? "page"
: sectionPaths.some((pattern) => matchPath(pattern, pathname))
? "location"
: undefined;
return (
<Link
to={to}
aria-current={current}
className={`relative inline-flex h-full items-center whitespace-nowrap px-2.5 text-base font-semibold transition-colors focus-visible:-outline-offset-2 sm:px-4 md:px-7 md:text-xl ${
current
? "text-content-strong after:absolute after:inset-x-2.5 after:bottom-0 after:h-[3px] after:rounded-t-full after:bg-primary sm:after:inset-x-4 md:after:inset-x-7"
: "text-content-subtle hover:text-content-strong"
}`}
>
{children}
</Link>
);
}
/** 선수 이름으로 전적 순위표를 바로 찾는 머리글 검색. */
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;
const matchQuery = useMatch(matchId);
const isTournamentMatch = matchQuery.data?.eventType === "tournament";
const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID);
const meQuery = useMe();
const communityLabel = communityQuery.data?.name ?? "LOLYMPUS";
const role = meQuery.data?.memberships.find(
(membership) => membership.community?._id === DEFAULT_COMMUNITY_ID,
)?.user?.role;
const canManage = role === "owner" || role === "admin";
const statsPath = `/communities/${DEFAULT_COMMUNITY_ID}/internal-stats`;
const adminPath = `/admin/communities/${DEFAULT_COMMUNITY_ID}`;
return (
<>
<header className="h-(--app-header-row-height) shrink-0 border-b border-line bg-card dark:bg-ink">
<div
className={`${pageWidthClass("xl")} grid h-full grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center sm:gap-x-3`}
>
<Link
className="col-start-2 row-start-1 flex h-full items-center text-content-strong"
to="/"
aria-label={`${communityLabel} 홈`}
>
<span className="max-w-32 truncate text-xl font-extrabold tracking-[-0.02em] md:max-w-48 md:text-[22px]">
{communityLabel}
</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>
{isMsalConfigured && (
<div className="col-start-3 row-start-1 min-w-0 justify-self-end sm:shrink-0">
<MsalHeaderActions />
</div>
)}
</div>
</div>
</header>
{DEFAULT_COMMUNITY_ID && (
<nav
aria-label="주 메뉴"
className="sticky top-0 z-50 flex h-(--app-header-nav-height) shrink-0 justify-center gap-0.5 border-b border-line bg-card sm:gap-2 md:gap-5 dark:bg-ink"
>
<PrimaryNavLink to="/">홈</PrimaryNavLink>
<PrimaryNavLink
to="/inhouse"
sectionPaths={isTournamentMatch ? undefined : ["/match/*"]}
>
내전
</PrimaryNavLink>
<PrimaryNavLink
to="/tournaments"
sectionPaths={isTournamentMatch ? ["/match/*"] : undefined}
>
멸망전
</PrimaryNavLink>
<PrimaryNavLink
to={statsPath}
sectionPaths={[`${statsPath}/*`, "/users/:userId/history"]}
>
전적
</PrimaryNavLink>
{canManage && (
<PrimaryNavLink
to={`${adminPath}/matches`}
sectionPaths={[`${adminPath}/*`]}
>
운영
</PrimaryNavLink>
)}
</nav>
)}
</>
);
}
function AppFooter() {
return (
<footer className="border-t border-base-content/10 bg-base-100">
<div className="max-w-5xl mx-auto px-4 sm:px-6 py-8 text-xs text-base-content/35">
<nav className="flex items-center gap-4 mb-4 font-semibold text-base-content/45">
<Link to="/terms" className="hover:text-base-content">
<footer className="border-t border-line">
<div
className={`${pageWidthClass("xl")} flex flex-col gap-3 py-8 text-xs text-content-subtle`}
>
<nav
aria-label="정책"
className="flex items-center gap-4 font-semibold text-content-muted"
>
<Link to="/terms" className="hover:text-content">
서비스 이용약관
</Link>
<Link to="/privacy" className="hover:text-base-content">
<Link to="/privacy" className="hover:text-content">
개인정보처리방침
</Link>
</nav>
<p className="leading-relaxed max-w-4xl">
<p className="max-w-4xl leading-relaxed">
© 2026 LOLYMPUS. LOLYMPUS is not endorsed by Riot Games and does not
reflect the views or opinions of Riot Games or anyone officially
involved in producing or managing League of Legends. League of Legends
@@ -101,55 +279,71 @@ function LegalPage({
children: ReactNode;
}) {
return (
<main className="max-w-3xl mx-auto px-4 sm:px-6 py-12">
<Link
to="/"
className="inline-flex text-xs text-base-content/40 hover:text-base-content mb-5"
>
← 홈으로
</Link>
<h1 className="text-2xl font-black text-base-content">{title}</h1>
<div className="mt-6 space-y-4 text-sm leading-7 text-base-content/60">
<PlainPage width="md" className="py-12">
<h1 className="text-2xl font-extrabold">{title}</h1>
<div className="lts-panel mt-6 space-y-4 p-6 text-sm leading-7 text-content-muted">
{children}
</div>
</main>
</PlainPage>
);
}
function App() {
const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID);
const communityLabel = communityQuery.data?.name ?? "LOLYMPUS";
function NotFoundPage() {
return (
<PlainPage width="md" className="py-24 text-center">
<p className="tabular text-5xl font-extrabold text-content-disabled">
404
</p>
<h1 className="mt-4 text-xl font-bold">
페이지를 찾을 수 없습니다
</h1>
<p className="mt-2 text-sm text-content-muted">
주소가 바뀌었거나 삭제된 내전일 수 있습니다.
</p>
<Link
to="/inhouse"
className="mt-6 inline-flex h-10 items-center rounded-field bg-primary px-5 text-sm font-bold text-primary-content"
>
내전 목록으로
</Link>
</PlainPage>
);
}
function HomeRoute() {
const { search, hash } = useLocation();
const params = new URLSearchParams(search);
if (params.get("history") === "all") {
params.delete("history");
return (
<Navigate
replace
to={{ pathname: "/inhouse", search: params.toString(), hash }}
/>
);
}
return <HomePage />;
}
function App() {
return (
<BrowserRouter>
<div className="min-h-screen bg-base-100 flex flex-col">
<nav className="bg-base-100 border-b border-base-content/10 sticky top-0 z-50">
<div className="max-w-5xl mx-auto px-4 sm:px-6 flex items-center justify-between h-12">
<Link
className="text-base font-bold tracking-tight text-base-content"
to="/"
>
{communityLabel}
</Link>
<div className="flex items-center gap-3">
{/* {DEFAULT_COMMUNITY_ID ? (
<span className="text-xs uppercase tracking-wider text-base-content/25">
API Live
</span>
) : (
<span className="text-xs uppercase tracking-wider text-amber-500/70">
Set `VITE_DEFAULT_COMMUNITY_ID`
</span>
)} */}
<ThemeToggle />
{isMsalConfigured && <MsalHeaderActions />}
</div>
</div>
</nav>
<div
className={`lts-app-shell flex min-h-screen flex-col bg-body ${DEFAULT_COMMUNITY_ID ? "" : "[--app-header-nav-height:0px]"}`}
>
<AppHeader />
<div className="flex-1">
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/" element={<HomeRoute />} />
<Route
path="/inhouse"
element={<HomePage key="inhouse" eventType="inhouse" />}
/>
<Route
path="/tournaments"
element={<HomePage key="tournament" eventType="tournament" />}
/>
<Route path="/login" element={<LoginPage />} />
<Route path="/auth/callback" element={<AuthCallbackPage />} />
<Route path="/match/:id" element={<MatchDetailPage />} />
@@ -226,6 +420,7 @@ function App() {
</LegalPage>
}
/>
<Route path="*" element={<NotFoundPage />} />
</Routes>
</div>
<AppFooter />
+62 -5
View File
@@ -5,8 +5,11 @@ import type {
CompetitionCommandResponse,
CompetitionDetailResponse,
CreateSeriesAdjudicationRequest,
HallOfFameResponse,
MatchDetailResponse,
MatchEventType,
MatchLifecycleStatus,
MatchListView,
MatchListResponse,
ReverseSeriesResultRequest,
SeriesId,
@@ -32,6 +35,7 @@ import type {
ApiCommunity,
ApiCommunityUserSearchCandidate,
ApiEnqueueRefreshResult,
ApiHistorySeason,
ApiInternalMatchDetailResponse,
ApiInternalMatchListResponse,
ApiLeaderboardResponse,
@@ -64,12 +68,19 @@ const DDRAGON_MANIFEST_STALE_MS = 24 * 60 * 60 * 1000;
interface MatchesQueryOptions {
status?: MatchLifecycleStatus;
eventType?: MatchEventType;
limit?: number;
page?: number;
offset?: number;
scheduledFrom?: string;
scheduledTo?: string;
sort?: 'asc' | 'desc';
view?: MatchListView;
asOf?: string;
}
interface MatchesPageQueryOptions extends MatchesQueryOptions {
includeResults?: boolean;
}
export interface UserHistoryFilters {
@@ -85,14 +96,18 @@ export interface CommunityInternalStatsFilters {
to?: string;
championId?: number;
limit?: number;
query?: string;
format?: 'pair' | 'tournament';
playerId?: string;
}
function createMatchesPath(
communityId: string,
options: MatchesQueryOptions = {},
options: MatchesPageQueryOptions = {},
) {
const searchParams = new URLSearchParams();
if (options.status) searchParams.set('status', options.status);
if (options.eventType) searchParams.set('eventType', options.eventType);
if (options.limit) searchParams.set('limit', String(options.limit));
if (options.page) searchParams.set('page', String(options.page));
if (options.offset) searchParams.set('offset', String(options.offset));
@@ -100,6 +115,9 @@ function createMatchesPath(
searchParams.set('scheduledFrom', options.scheduledFrom);
if (options.scheduledTo) searchParams.set('scheduledTo', options.scheduledTo);
if (options.sort) searchParams.set('sort', options.sort);
if (options.includeResults) searchParams.set('includeResults', 'true');
if (options.view) searchParams.set('view', options.view);
if (options.asOf) searchParams.set('asOf', options.asOf);
const queryString = searchParams.toString();
return `/communities/${communityId}/matches${queryString ? `?${queryString}` : ''}`;
@@ -153,6 +171,17 @@ export function useCommunity(communityId = DEFAULT_COMMUNITY_ID) {
});
}
export function useHallOfFame(communityId = DEFAULT_COMMUNITY_ID) {
return useQuery({
queryKey: ['hall-of-fame', communityId],
queryFn: () => apiFetch<HallOfFameResponse>(
`/communities/${communityId}/matches/hall-of-fame`,
{ auth: 'none' },
),
enabled: Boolean(communityId),
});
}
export function useMatches(
options: MatchesQueryOptions,
communityId = DEFAULT_COMMUNITY_ID,
@@ -171,6 +200,9 @@ export function useMatches(
options.scheduledFrom ?? null,
options.scheduledTo ?? null,
options.sort ?? null,
options.eventType ?? null,
options.view ?? null,
options.asOf ?? null,
],
queryFn: async () => {
const response = await authScope.fetch<MatchListResponse>(
@@ -183,7 +215,7 @@ export function useMatches(
}
export function useMatchesPage(
options: MatchesQueryOptions,
options: MatchesPageQueryOptions,
communityId = DEFAULT_COMMUNITY_ID,
) {
const authScope = useOptionalAuthQueryScope();
@@ -200,6 +232,10 @@ export function useMatchesPage(
options.scheduledFrom ?? null,
options.scheduledTo ?? null,
options.sort ?? null,
options.includeResults ?? false,
options.eventType ?? null,
options.view ?? null,
options.asOf ?? null,
],
queryFn: () =>
authScope.fetch<MatchListResponse>(
@@ -665,6 +701,9 @@ function createCommunityInternalStatsPath(
if (filters.championId)
searchParams.set('championId', String(filters.championId));
if (filters.limit) searchParams.set('limit', String(filters.limit));
if (filters.query) searchParams.set('q', filters.query);
if (filters.format) searchParams.set('format', filters.format);
if (filters.playerId) searchParams.set('playerId', filters.playerId);
for (const [key, value] of Object.entries(extra)) {
if (value !== null && value !== undefined && value !== '') {
searchParams.set(key, String(value));
@@ -689,16 +728,22 @@ export function useCommunityInternalStatsMatches(
filters.to ?? null,
filters.championId ?? null,
filters.limit ?? null,
filters.query ?? null,
filters.format ?? null,
filters.playerId ?? null,
],
queryFn: ({ pageParam }) =>
apiFetch<ApiInternalMatchListResponse>(
createCommunityInternalStatsPath(communityId, 'matches', filters, {
cursor: pageParam,
cursor: pageParam?.cursor,
cursorMatchId: pageParam?.matchId,
}),
{ auth: 'none' },
),
initialPageParam: null as number | null,
getNextPageParam: (lastPage) => lastPage.nextCursor,
initialPageParam: null as { cursor: number; matchId?: string } | null,
getNextPageParam: (lastPage) => lastPage.nextCursor === null
? null
: { cursor: lastPage.nextCursor, matchId: lastPage.nextCursorMatchId },
enabled: Boolean(communityId && enabled),
});
}
@@ -716,6 +761,7 @@ export function useCommunityLeaderboard(
filters.from ?? null,
filters.to ?? null,
filters.championId ?? null,
filters.query ?? null,
],
queryFn: () =>
apiFetch<ApiLeaderboardResponse>(
@@ -728,6 +774,17 @@ export function useCommunityLeaderboard(
});
}
export function useCommunityStatsSeasons(communityId = DEFAULT_COMMUNITY_ID) {
return useQuery({
queryKey: ['community-stats-seasons', communityId],
queryFn: () => apiFetch<{ seasons: ApiHistorySeason[] }>(
`/communities/${communityId}/internal-stats/seasons`,
{ auth: 'none' },
),
enabled: Boolean(communityId),
});
}
export function useTeamInsights(
filters: CommunityInternalStatsFilters,
communityId = DEFAULT_COMMUNITY_ID,
+4 -4
View File
@@ -354,15 +354,15 @@ export function formatTierLabel(tier?: ApiTierInfo) {
export function getTierColorToken(tier?: ApiTierInfo) {
switch (tier?.tier) {
case "CHALLENGER":
return "text-amber-400";
return "text-gold";
case "GRANDMASTER":
return "text-red-400";
return "text-loss";
case "MASTER":
return "text-fuchsia-400";
case "DIAMOND":
return "text-cyan-400";
case "EMERALD":
return "text-emerald-400";
return "text-leaf";
case "PLATINUM":
return "text-teal-300";
case "GOLD":
@@ -370,7 +370,7 @@ export function getTierColorToken(tier?: ApiTierInfo) {
case "SILVER":
return "text-gray-300";
case "BRONZE":
return "text-amber-700";
return "text-gold";
case "IRON":
return "text-stone-400";
default:
+24
View File
@@ -1,4 +1,13 @@
import type {
GrandFinalGameCount,
GameAnalysisAvailability,
GameId,
GameSlotId,
InternalMatchCompetition,
InternalMatchResultPresentation,
SeriesId,
MatchEventType,
RecentMatchParticipantRank,
MatchGameMode,
MatchPosition,
MatchPositionPreferenceView,
@@ -274,6 +283,7 @@ export interface MeResponse {
export interface MatchMutationRequest {
title: string;
eventType?: MatchEventType;
description?: string;
mapId?: number;
scheduledAt: string;
@@ -282,6 +292,7 @@ export interface MatchMutationRequest {
gameMode?: MatchGameMode;
roundRobinMaxRounds?: number;
doubleEliminationResetFinalEnabled?: boolean;
doubleEliminationGrandFinalGameCount?: GrandFinalGameCount;
prizes?: string[];
notices?: string[];
schedule?: MatchScheduleItemView[];
@@ -526,6 +537,7 @@ export interface ApiRecentMatchTeamParticipant {
championId: number;
championLevel: number;
teamPosition: string;
tier?: RecentMatchParticipantRank;
kills: number;
deaths: number;
assists: number;
@@ -584,6 +596,8 @@ export interface ApiRecentMatchView {
summonerSpells: [number, number];
perks: ApiRunePerks;
teams: ApiRecentMatchTeam[];
/** 경기에서 기록한 최대 연속 처치 수. */
largestMultiKill?: number;
}
export interface ApiRecentMatchesResponse {
@@ -600,6 +614,7 @@ export interface ApiInternalMatchCard {
status: 'finished' | 'in-progress';
gameCount: number;
winnerTeamIndex?: number;
resultPresentation?: InternalMatchResultPresentation;
seriesResults: Array<{
teamAIndex: number;
teamBIndex: number;
@@ -630,6 +645,7 @@ export interface ApiInternalMatchCard {
export interface ApiInternalMatchListResponse {
matches: ApiInternalMatchCard[];
nextCursor: number | null;
nextCursorMatchId?: string;
season: ApiHistorySeason;
}
@@ -657,6 +673,7 @@ export interface ApiLeaderboardRow {
export interface ApiLeaderboardResponse {
rows: ApiLeaderboardRow[];
season: ApiHistorySeason;
matchedUserIds?: string[];
}
export interface ApiLeaderHighlight {
@@ -675,6 +692,7 @@ export interface ApiTeamInsightsResponse {
red: number;
bluePicks: number;
redPicks: number;
confirmed?: { sampleSize: number; blue: number; red: number };
};
topKda: ApiLeaderHighlight | null;
mostKills: ApiLeaderHighlight | null;
@@ -686,8 +704,14 @@ export interface ApiTeamInsightsResponse {
export interface ApiInternalMatchDetailResponse {
match: ApiInternalMatchCard;
competition?: InternalMatchCompetition;
games: Array<{
gameNumber: number;
gameId?: GameId;
analysisAvailability?: GameAnalysisAvailability;
gameSlotId?: GameSlotId;
seriesId?: SeriesId;
ordinal?: number;
riotMatchId: string;
gameCreation: number;
gameDuration: number;
+11 -2
View File
@@ -1,7 +1,10 @@
import { InteractionStatus } from '@azure/msal-browser';
import { useMsal } from '@azure/msal-react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { io, type Socket } from 'socket.io-client';
import { API_BASE_URL, useAuthUserId } from '../config';
import { acquireAccessToken } from '../lib/auth/token-provider';
import { isMsalConfigured } from '../lib/auth/msal.config';
import type { ApiAuction, ApiAuctionChatMessage, Position } from './types';
import {
createAuctionResyncRequester,
@@ -140,8 +143,14 @@ function mergeChatMessages(
export function useAuctionSocket(matchId: string | undefined) {
const authUserId = useAuthUserId();
const connectionKey = matchId
? JSON.stringify([matchId, authUserId ?? null])
const { accounts, inProgress, instance } = useMsal();
const accountId = isMsalConfigured
? (instance.getActiveAccount() ?? accounts[0])?.homeAccountId
: undefined;
const waitingForLogin = isMsalConfigured && !authUserId &&
(inProgress === InteractionStatus.Startup || inProgress === InteractionStatus.HandleRedirect);
const connectionKey = matchId && !waitingForLogin
? JSON.stringify([matchId, authUserId ?? null, accountId ?? null])
: null;
const socketRef = useRef<Socket | null>(null);
const resyncRequesterRef = useRef<ReturnType<
+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 12" shape-rendering="crispEdges">
<path fill="#2b1b12" d="M1 0h1v1h-1zM7 0h1v1h-1zM13 0h1v1h-1zM0 1h1v1h-1zM2 1h1v1h-1zM6 1h1v1h-1zM8 1h1v1h-1zM12 1h1v1h-1zM14 1h1v1h-1zM0 2h1v1h-1zM2 2h1v1h-1zM6 2h1v1h-1zM8 2h1v1h-1zM12 2h1v1h-1zM14 2h1v1h-1zM0 3h1v1h-1zM3 3h1v1h-1zM5 3h1v1h-1zM9 3h1v1h-1zM11 3h1v1h-1zM14 3h1v1h-1zM0 4h1v1h-1zM4 4h1v1h-1zM10 4h1v1h-1zM14 4h1v1h-1zM0 5h1v1h-1zM14 5h1v1h-1zM0 6h1v1h-1zM14 6h1v1h-1zM0 7h1v1h-1zM14 7h1v1h-1zM0 8h15v1h-15zM0 9h1v1h-1zM14 9h1v1h-1zM0 10h1v1h-1zM14 10h1v1h-1zM1 11h13v1h-13z"/>
<path fill="#fff4a8" d="M1 1h1v1h-1zM7 1h1v1h-1zM13 1h1v1h-1zM1 4h1v1h-1zM1 5h1v1h-1z"/>
<path fill="#ffd91a" d="M1 2h1v1h-1zM7 2h1v1h-1zM1 3h2v1h-2zM6 3h3v1h-3zM12 3h1v1h-1zM2 4h2v1h-2zM5 4h5v1h-5zM11 4h2v1h-2zM2 5h11v1h-11zM1 6h1v1h-1zM3 6h4v1h-4zM8 6h4v1h-4zM1 7h11v1h-11zM1 9h1v1h-1zM3 9h1v1h-1zM5 9h1v1h-1zM7 9h1v1h-1zM9 9h1v1h-1zM11 9h1v1h-1z"/>
<path fill="#f08a24" d="M13 2h1v1h-1zM13 3h1v1h-1zM13 4h1v1h-1zM13 5h1v1h-1zM13 6h1v1h-1zM12 7h2v1h-2zM2 9h1v1h-1zM4 9h1v1h-1zM6 9h1v1h-1zM8 9h1v1h-1zM10 9h1v1h-1zM12 9h2v1h-2zM1 10h13v1h-13z"/>
<path fill="#e5372b" d="M2 6h1v1h-1zM7 6h1v1h-1zM12 6h1v1h-1z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

+6
View File
@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" shape-rendering="crispEdges">
<path fill="#2b1b12" d="M2 0h9v1h-9zM0 1h3v1h-3zM10 1h3v1h-3zM0 2h1v1h-1zM2 2h1v1h-1zM10 2h1v1h-1zM12 2h1v1h-1zM0 3h1v1h-1zM2 3h1v1h-1zM10 3h1v1h-1zM12 3h1v1h-1zM0 4h3v1h-3zM10 4h3v1h-3zM2 5h1v1h-1zM10 5h1v1h-1zM3 6h1v1h-1zM9 6h1v1h-1zM4 7h1v1h-1zM8 7h1v1h-1zM5 8h1v1h-1zM7 8h1v1h-1zM5 9h1v1h-1zM7 9h1v1h-1zM4 10h1v1h-1zM8 10h1v1h-1zM3 11h1v1h-1zM9 11h1v1h-1zM3 12h7v1h-7z"/>
<path fill="#fff4a8" d="M3 1h1v1h-1zM3 2h1v1h-1zM3 3h1v1h-1zM3 4h1v1h-1z"/>
<path fill="#ffd91a" d="M4 1h5v1h-5zM4 2h5v1h-5zM4 3h5v1h-5zM4 4h5v1h-5zM3 5h6v1h-6zM4 6h4v1h-4zM5 7h2v1h-2zM6 8h1v1h-1zM5 10h3v1h-3zM4 11h4v1h-4z"/>
<path fill="#f08a24" d="M9 1h1v1h-1zM9 2h1v1h-1zM9 3h1v1h-1zM9 4h1v1h-1zM9 5h1v1h-1zM8 6h1v1h-1zM7 7h1v1h-1zM6 9h1v1h-1zM8 11h1v1h-1z"/>
</svg>

After

Width:  |  Height:  |  Size: 844 B

+82
View File
@@ -0,0 +1,82 @@
import type { ReactNode } from "react";
import { NavLink } from "react-router";
import { PageBody, PageHero } from "../ui";
const ADMIN_SECTIONS = [
{ path: "matches", label: "대회 관리" },
{ path: "tournament-codes", label: "토너먼트 코드" },
{ path: "legacy-import", label: "과거 기록 가져오기" },
{ path: "legacy-matches", label: "과거 기록 정리" },
] as const;
/**
* 운영 화면 공통 틀. 네 개의 운영 도구를 한 줄 탭으로 오갈 수 있게 한다.
*/
export function AdminPage({
communityId,
title,
description,
actions,
children,
}: {
communityId: string;
title: string;
description?: string;
actions?: ReactNode;
children: ReactNode;
}) {
return (
<>
<PageHero
width="xl"
eyebrow="운영"
title={title}
meta={description}
actions={actions}
/>
<PageBody width="xl">
<nav
aria-label="운영 메뉴"
className="lts-panel mb-5 grid grid-cols-2 gap-1 p-1 sm:flex sm:flex-wrap"
>
{ADMIN_SECTIONS.map((section) => (
<NavLink
key={section.path}
to={`/admin/communities/${communityId}/${section.path}`}
className={({ isActive }) =>
`flex min-h-10 items-center justify-center rounded-[10px] px-2 py-2 text-center text-xs font-bold transition-colors sm:px-4 sm:text-sm ${
isActive
? "bg-secondary text-secondary-content"
: "text-content-muted hover:bg-sunken hover:text-content"
}`
}
>
{section.label}
</NavLink>
))}
</nav>
{children}
</PageBody>
</>
);
}
/** 운영 화면의 권한·설정 안내. */
export function AdminNotice({
title,
children,
}: {
title: string;
children?: ReactNode;
}) {
return (
<main className="mx-auto w-full max-w-3xl px-4 py-16 sm:px-6">
<div className="lts-panel px-6 py-10 text-center">
<h1 className="text-lg font-bold">{title}</h1>
{children && (
<div className="mt-2 text-sm text-content-muted">{children}</div>
)}
</div>
</main>
);
}
@@ -0,0 +1,87 @@
import { Link, useLocation } from "react-router";
import type { ApiInternalMatchDetailResponse, DdragonManifest } from "../api/types";
import { championDisplayName, championIconUrl } from "../lib/ddragon";
import { teamIndexLabel } from "../lib/league";
import { EmptyNote } from "../ui";
export function GameAnalysisNotice() {
return (
<EmptyNote
size="sm"
title="Riot 원본이 없는 경기 기록"
description="저장된 경기 결과와 선수별 KDA를 볼 수 있습니다."
/>
);
}
export function BasicGameScoreboard({
game,
teams,
manifest,
}: {
game: ApiInternalMatchDetailResponse["games"][number];
teams: ApiInternalMatchDetailResponse["match"]["teams"];
manifest: DdragonManifest | null | undefined;
}) {
const location = useLocation();
const backTo = `${location.pathname}${location.search}${location.hash}`;
return (
<div className="space-y-3 p-4">
{game.analysisAvailability && game.analysisAvailability !== "available" && (
<GameAnalysisNotice />
)}
{game.teams.map((team) => (
<section key={team.side} className="overflow-hidden rounded-lg border border-line bg-card">
<h4 className="border-b border-line px-3 py-2 text-sm font-semibold">
{teamIndexLabel(team.teamIndex, teams.find(({ teamIndex }) => teamIndex === team.teamIndex)?.name)}
{" · "}{team.side === "blue" ? "블루" : "레드"}{" · "}{team.win ? "승리" : "패배"}
</h4>
{team.participants.length > 0 ? (
<table className="w-full text-left text-sm">
<thead className="text-xs text-content-muted">
<tr>
<th scope="col" className="px-3 py-2">선수</th>
<th scope="col" className="px-3 py-2">챔피언</th>
<th scope="col" className="px-3 py-2 text-right">K/D/A</th>
</tr>
</thead>
<tbody className="divide-y divide-line">
{team.participants.map((participant) => {
const icon = championIconUrl(manifest, participant.championId);
const champion = championDisplayName(manifest, participant.championId);
return (
<tr key={`${participant.userId}-${participant.championId}`}>
<td className="px-3 py-2">
{participant.userId ? (
<Link
to={`/users/${participant.userId}/history?queueGroup=internal`}
state={{ backTo }}
className="font-semibold hover:underline"
>
{participant.summonerName}
</Link>
) : participant.summonerName}
</td>
<td className="px-3 py-2">
<span className="flex items-center gap-2">
{icon && <img src={icon} alt="" className="size-6 rounded" />}
{champion ?? "챔피언 미확인"}
</span>
</td>
<td className="whitespace-nowrap px-3 py-2 text-right tabular">
{participant.kills}/{participant.deaths}/{participant.assists}
</td>
</tr>
);
})}
</tbody>
</table>
) : (
<p className="px-3 py-2 text-sm text-content-muted">저장된 선수 기록이 없습니다.</p>
)}
</section>
))}
</div>
);
}
+49 -20
View File
@@ -1,6 +1,8 @@
import { useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { FlaskConical, X } from 'lucide-react';
import { setAuthUserId, useAuthUserId } from '../config';
import { Button } from '../ui';
export default function DevAuthSwitcher() {
const authUserId = useAuthUserId();
@@ -17,12 +19,16 @@ export default function DevAuthSwitcher() {
);
}
/**
* 개발 서버 전용 인증 전환기. 기본은 접힌 알약이라 화면을 가리지 않는다.
*/
function DevAuthSwitcherForm({
authUserId,
}: {
authUserId: string | null;
}) {
const queryClient = useQueryClient();
const [isOpen, setIsOpen] = useState(false);
const [inputValue, setInputValue] = useState(authUserId ?? '');
function updateAuthUserId(nextValue: string | null) {
@@ -30,37 +36,60 @@ function DevAuthSwitcherForm({
void queryClient.invalidateQueries();
}
return (
<div className="fixed right-4 bottom-4 z-50 w-72 border border-base-content/10 bg-base-100/95 backdrop-blur px-3 py-3 shadow-xl">
<div className="text-xs font-bold uppercase tracking-wider text-base-content/35">
if (!isOpen) {
return (
<button
type="button"
className="dev-auth-switcher fixed bottom-3 right-3 z-50 inline-flex h-8 items-center gap-1.5 rounded-full border border-line-strong bg-card px-3 text-xs font-semibold text-content-muted shadow-card hover:text-content"
onClick={() => setIsOpen(true)}
>
<FlaskConical className="size-3.5" aria-hidden="true" />
Dev Auth
</div>
<div className="mt-2 text-xs text-base-content/45">
X-Auth-User-Id
<span
aria-hidden="true"
className={`size-1.5 rounded-full ${authUserId ? 'bg-leaf' : 'bg-content-disabled'}`}
/>
</button>
);
}
return (
<div className="dev-auth-switcher lts-panel fixed bottom-3 right-3 z-50 w-72 p-3">
<div className="flex items-center justify-between">
<span className="text-xs font-bold text-content-muted">
Dev Auth · X-Auth-User-Id
</span>
<button
type="button"
aria-label="닫기"
className="grid size-6 place-items-center rounded-full text-content-subtle hover:bg-sunken hover:text-content"
onClick={() => setIsOpen(false)}
>
<X className="size-3.5" aria-hidden="true" />
</button>
</div>
<input
value={inputValue}
onChange={(event) => setInputValue(event.target.value)}
placeholder="Mongo User ID"
className="mt-1 w-full border border-base-content/10 bg-transparent px-2 py-2 text-xs text-base-content focus:outline-none focus:border-primary/30"
aria-label="Mongo User ID"
className="lts-input mt-2 text-xs"
/>
<div className="mt-2 flex items-center gap-2">
<button
type="button"
className="btn btn-primary btn-xs px-3"
<Button
label="Set"
size="sm"
variant="primary"
onClick={() => updateAuthUserId(inputValue)}
>
Set
</button>
<button
type="button"
className="btn btn-ghost btn-xs px-3"
/>
<Button
label="Clear"
size="sm"
variant="ghost"
onClick={() => updateAuthUserId(null)}
>
Clear
</button>
/>
</div>
<div className="mt-2 text-xs text-base-content/35 break-all">
<div className="mt-2 break-all text-xs text-content-subtle">
현재값: {authUserId ?? '없음'}
</div>
</div>
@@ -0,0 +1,52 @@
.lts-hall {
--lts-hall-slant: 10px;
/* Paint the muted band edge to edge without leaving the page-width column. */
background: var(--color-background-muted);
box-shadow: 0 0 0 100vmax var(--color-background-muted);
clip-path: inset(0 -100vmax);
}
.lts-hall-card {
border-radius: 1.25rem;
}
.lts-hall-player,
.lts-hall-portrait {
border-radius: 0.75rem;
}
.lts-hall-pixel {
image-rendering: pixelated;
}
.lts-hall-crown {
rotate: 14deg;
}
@media (prefers-reduced-motion: no-preference) {
.lts-hall[data-intro] .lts-hall-portrait img {
animation: lts-hall-reveal 110ms linear
calc(180ms + var(--lts-hall-order) * 48ms) backwards;
}
}
@keyframes lts-hall-reveal {
from {
clip-path: polygon(
0 0,
0 0,
calc(0px - var(--lts-hall-slant)) 100%,
0 100%
);
}
to {
clip-path: polygon(
0 0,
calc(100% + var(--lts-hall-slant)) 0,
100% 100%,
0 100%
);
}
}
+172
View File
@@ -0,0 +1,172 @@
import type { HallOfFameResponse, MatchPosition } from '@lolympus/contracts';
import { ChevronRight, UserRound } from 'lucide-react';
import { useEffect, useRef, useState, type CSSProperties } from 'react';
import { Link } from 'react-router';
import { useDdragonManifest, useHallOfFame } from '../api/hooks';
import captainCrown from '../assets/captain-crown.svg';
import pixelTrophy from '../assets/pixel-trophy.svg';
import { profileIconUrl } from '../lib/ddragon';
import { positionLabel } from '../lib/league';
import { pageWidthClass } from '../ui/layout';
import './HomeHallOfFame.css';
const POSITION_ORDER: MatchPosition[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
export default function HomeHallOfFame({
introReady,
}: {
introReady: boolean;
}) {
const hallOfFame = useHallOfFame();
const sectionRef = useRef<HTMLElement>(null);
const [playIntro, setPlayIntro] = useState(false);
useEffect(() => {
const section = sectionRef.current;
if (
!introReady ||
!section ||
typeof IntersectionObserver === 'undefined' ||
window.matchMedia('(prefers-reduced-motion: reduce)').matches
) {
return;
}
const observer = new IntersectionObserver(
([entry]) => {
if (entry?.isIntersecting) setPlayIntro(true);
},
{ threshold: 0.5 },
);
observer.observe(section);
return () => observer.disconnect();
}, [introReady]);
const featuredMatch = hallOfFame.data?.match;
return (
// The second grid column is left empty on purpose: it reserves room for a
// small companion card beside the hall of fame.
<section
ref={sectionRef}
aria-label="명예의 전당"
className={`${pageWidthClass()} lts-hall grid gap-8 py-6 md:py-8 lg:grid-cols-[minmax(0,1fr)_20rem]`}
data-intro={playIntro ? '' : undefined}
>
{hallOfFame.isPending ? (
<p role="status">명예의 전당을 불러오는 중</p>
) : hallOfFame.isError ? (
<p role="status">
명예의 전당을 불러오지 못했습니다.{' '}
<button type="button" className="underline" onClick={() => void hallOfFame.refetch()}>
다시 시도
</button>
</p>
) : featuredMatch && hallOfFame.data.teams.length > 0 ? (
<div className="space-y-3">
{hallOfFame.data.teams.map((team, index) => (
<FeaturedTeam key={index} team={team} match={featuredMatch} />
))}
</div>
) : (
<p className="text-sm text-content-muted">확정된 멸망전 우승팀이 없습니다.</p>
)}
</section>
);
}
function FeaturedTeam({
team,
match,
}: {
team: HallOfFameResponse['teams'][number];
match: NonNullable<HallOfFameResponse['match']>;
}) {
const { data: manifest } = useDdragonManifest();
const members = [...team.members].sort(
(left, right) =>
(left.position ? POSITION_ORDER.indexOf(left.position) : POSITION_ORDER.length) -
(right.position ? POSITION_ORDER.indexOf(right.position) : POSITION_ORDER.length),
);
return (
<div className="lts-hall-card flex min-w-0 flex-col gap-4 bg-card p-5 sm:flex-row sm:gap-5">
<h2 className="min-w-0 sm:w-36 sm:shrink-0">
<span
className="block text-sm font-semibold text-content-muted"
>
명예의 전당
</span>
<span className="mt-2 block text-2xl leading-tight font-extrabold tracking-tight [overflow-wrap:anywhere]">
{team.name}
</span>
<span className="mt-1 flex items-center gap-1 text-xs font-semibold text-content-muted">
<img src={pixelTrophy} alt="" className="lts-hall-pixel size-4" />
<Link to={`/match/${match.id}`} title={match.title} className="hover:underline">직전 멸망전 우승</Link>
</span>
</h2>
<div className="h-px bg-line sm:h-auto sm:w-px" aria-hidden="true" />
<ul
className="grid min-w-0 flex-1 gap-1 sm:grid-cols-5 sm:content-center sm:items-start"
aria-label="우승팀 선수"
>
{members.map(
({ userId, position, gameName, tagLine, profileIconId }, index) => {
const icon = profileIconId === undefined ? undefined : profileIconUrl(manifest, profileIconId);
const isCaptain = userId === team.captainUserId;
return (
<li key={userId} className="min-w-0">
<Link
to={`/users/${userId}/history?queueGroup=internal`}
className="lts-hall-player group flex h-full items-center gap-2.5 px-2 py-2 transition-colors hover:bg-sunken focus-visible:-outline-offset-2 sm:flex-col sm:gap-2 sm:py-3 sm:text-center"
>
<span className="relative shrink-0">
{isCaptain && (
<img
src={captainCrown}
alt="팀장"
className="lts-hall-crown lts-hall-pixel absolute -top-2.5 -right-2.5 z-10 w-6"
/>
)}
<span
className="lts-hall-portrait relative grid size-10 place-items-center overflow-hidden bg-sunken-strong text-content-muted sm:size-13"
style={{ '--lts-hall-order': index } as CSSProperties}
>
<UserRound className="size-5" aria-hidden="true" />
{icon && <img
key={icon}
src={icon}
alt=""
className="absolute inset-0 size-full object-cover"
onError={(event) => {
event.currentTarget.hidden = true;
}}
/>}
</span>
</span>
<span className="min-w-0 flex-1 sm:w-full sm:flex-none">
<span className="block text-xs font-semibold text-content-muted">
{position ? positionLabel[position] : "포지션 미확인"}
</span>
<span className="flex flex-wrap items-baseline gap-x-1.5 sm:flex-col sm:items-center">
<span className="text-sm font-bold [overflow-wrap:anywhere] group-hover:underline">
{gameName ?? "선수 프로필"}
</span>
<span className="text-xs text-content-muted [overflow-wrap:anywhere]">
{tagLine && `#${tagLine}`}
</span>
</span>
</span>
<ChevronRight
className="size-4 shrink-0 text-content-muted sm:hidden"
aria-hidden="true"
/>
</Link>
</li>
);
},
)}
</ul>
</div>
);
}
@@ -15,7 +15,9 @@ import {
type NormalizedLanePosition,
} from "../lib/internal-game-matchups";
import { ItemIcon, RuneIcon, RuneStyleIcon } from "./ItemTooltip";
import { GameAnalysisNotice } from "./BasicGameScoreboard";
import { Tab, TabList } from "@astryxdesign/core/TabList";
export type InternalGameDetailTab = "scoreboard" | "matchup" | "build";
type InternalGameDetail = ApiInternalMatchDetailResponse["games"][number];
@@ -36,10 +38,10 @@ const SKILL_ROWS: Array<{
label: string;
className: string;
}> = [
{ slot: 1, label: "Q", className: "bg-blue-500 text-white" },
{ slot: 1, label: "Q", className: "bg-win text-white" },
{ slot: 2, label: "W", className: "bg-cyan-500 text-white" },
{ slot: 3, label: "E", className: "bg-amber-500 text-black" },
{ slot: 4, label: "R", className: "bg-red-500 text-white" },
{ slot: 4, label: "R", className: "bg-loss text-white" },
];
const STAT_PERK_LABELS: Record<number, string> = {
@@ -71,16 +73,16 @@ function formatSignedNumber(value: number) {
function sideTone(side: TeamSide) {
return side === "blue"
? {
border: "border-blue-500/20",
bg: "bg-blue-500/5",
text: "text-blue-400",
bar: "bg-blue-500",
border: "border-win-line",
bg: "bg-win-tint",
text: "text-win",
bar: "bg-win",
}
: {
border: "border-red-500/20",
bg: "bg-red-500/5",
text: "text-red-400",
bar: "bg-red-500",
border: "border-loss-line",
bg: "bg-loss-tint",
text: "text-loss",
bar: "bg-loss",
};
}
@@ -611,11 +613,11 @@ function SkillBuildPanel({
</div>
{skillEvents.length > 0 ? (
<div className="mt-3 overflow-x-auto">
<div className="min-w-[610px] space-y-1">
<div className="min-w-[400px] space-y-1">
{SKILL_ROWS.map((row) => (
<div
key={`skill-row-${row.slot}`}
className="grid grid-cols-[2rem_repeat(18,minmax(1.45rem,1fr))] gap-1"
className="grid grid-cols-[2rem_repeat(18,minmax(1.1rem,1fr))] gap-0.5"
>
<div
className={`flex h-7 items-center justify-center text-xs font-bold ${row.className}`}
@@ -672,7 +674,7 @@ function MatchupMetricRow({
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-2 px-3 py-1.5 text-xs">
<span
className={`text-right tabular-nums ${
blueLead ? "font-bold text-blue-400" : "text-base-content/55"
blueLead ? "font-bold text-win" : "text-base-content/55"
}`}
>
{blueText}
@@ -687,7 +689,7 @@ function MatchupMetricRow({
</span>
<span
className={`tabular-nums ${
redLead ? "font-bold text-red-400" : "text-base-content/55"
redLead ? "font-bold text-loss" : "text-base-content/55"
}`}
>
{redText}
@@ -899,11 +901,11 @@ function LaneMatchupPanel({
<section className="overflow-hidden border border-base-content/10 bg-base-100">
<div className="border-b border-base-content/8 px-4 py-3">
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-3 text-xs font-bold">
<span className="truncate text-right text-blue-400">
<span className="truncate text-right text-win">
{blueTeamName}
</span>
<span className="text-base-content/20">VS</span>
<span className="truncate text-red-400">{redTeamName}</span>
<span className="truncate text-loss">{redTeamName}</span>
</div>
<div
className="mx-auto mt-3 flex w-fit border border-base-content/10"
@@ -959,28 +961,19 @@ export function InternalGameDetailTabBar({
onChange: (tab: InternalGameDetailTab) => void;
}) {
return (
<div
className="flex flex-wrap border-b border-base-content/8"
role="tablist"
<TabList
aria-label="상세 분석"
value={activeTab}
hasDivider
onChange={(next) => {
const tab = DETAIL_TABS.find((candidate) => candidate.id === next);
if (tab) onChange(tab.id);
}}
>
{DETAIL_TABS.map((tab) => (
<button
key={tab.id}
type="button"
role="tab"
aria-selected={activeTab === tab.id}
onClick={() => onChange(tab.id)}
className={`border-b-2 px-3 py-2 text-xs font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary ${
activeTab === tab.id
? "border-primary bg-primary/5 text-primary"
: "border-transparent text-base-content/45 hover:text-base-content"
}`}
>
{tab.label}
</button>
<Tab key={tab.id} value={tab.id} label={tab.label} />
))}
</div>
</TabList>
);
}
@@ -1000,6 +993,9 @@ export function InternalGameAnalysisPanel({
if (activeTab === "scoreboard") {
return <>{scoreboard}</>;
}
if (selectedGame.analysisAvailability && selectedGame.analysisAvailability !== "available") {
return <GameAnalysisNotice />;
}
if (activeTab === "build") {
return (
+6 -6
View File
@@ -289,7 +289,7 @@ function SummonerSpellTooltipContent({
return (
<div className="space-y-2">
<div className="font-black text-[#f0d878]">
<div className="font-black text-item-highlight">
{spell?.name ?? `스펠 ${spellId}`}
</div>
{descriptionHtml ? (
@@ -320,7 +320,7 @@ function RuneTooltipContent({
return (
<div className="space-y-2">
<div className="font-black text-[#f0d878]">
<div className="font-black text-item-highlight">
{rune?.name ?? (runeId ? `룬 ${runeId}` : "룬")}
</div>
{rune?.shortDesc ? (
@@ -349,7 +349,7 @@ function RuneStyleTooltipContent({
return (
<div className="space-y-2">
<div className="font-black text-[#f0d878]">
<div className="font-black text-item-highlight">
{style?.name ?? (styleId ? `룬 ${styleId}` : "룬")}
</div>
<div className="text-white/55">룬 스타일</div>
@@ -371,7 +371,7 @@ function ItemTooltipContent({
return (
<div className="space-y-2">
<div className="font-black text-[#f0d878]">
<div className="font-black text-item-highlight">
{item?.name ?? `아이템 ${itemId}`}
</div>
{item?.plaintext ? (
@@ -390,8 +390,8 @@ function ItemTooltipContent({
{item?.gold.total ? (
<div className="border-t border-white/10 pt-2 font-bold text-white">
가격:
<span className="text-[#f0d878]">{item.gold.total}</span>{" "}
<span className="text-[#f0d878]">
<span className="text-item-highlight">{item.gold.total}</span>{" "}
<span className="text-item-highlight">
({item.gold.base || item.gold.total})
</span>
</div>
+10 -9
View File
@@ -1,4 +1,5 @@
import type { ApiTierInfo } from "../api/types";
import { Tooltip } from "@astryxdesign/core/Tooltip";
import { formatRankBadge, formatRankDetail } from "./rankBadgeUtils";
type RankBadgeSize = "sm" | "md";
@@ -9,9 +10,12 @@ const SIZE_CLASSES: Record<RankBadgeSize, string> = {
md: "h-[18px] min-w-[20px]",
};
const TOOLTIP_CLASSES: Record<RankBadgeTooltipPlacement, string> = {
left: "tooltip-left",
bottom: "tooltip-bottom",
const TOOLTIP_PLACEMENT: Record<
RankBadgeTooltipPlacement,
"start" | "below"
> = {
left: "start",
bottom: "below",
};
function rankBadgeClass(tier: ApiTierInfo | undefined) {
@@ -53,17 +57,14 @@ export function RankBadge({
const tooltip = formatRankDetail(tier);
return (
<span
className={`tooltip ${TOOLTIP_CLASSES[tooltipPlacement]}`}
data-tip={tooltip}
>
<Tooltip content={tooltip} placement={TOOLTIP_PLACEMENT[tooltipPlacement]}>
<span
className={`inline-flex ${SIZE_CLASSES[size]} shrink-0 items-center justify-center whitespace-nowrap rounded-[3px] border px-1 text-xs font-black leading-none ${rankBadgeClass(tier)}`}
className={`inline-flex ${SIZE_CLASSES[size]} shrink-0 items-center justify-center whitespace-nowrap rounded-[5px] border px-1 text-[11px] font-extrabold leading-none ${rankBadgeClass(tier)}`}
aria-label={tooltip}
>
{formatRankBadge(tier)}
</span>
</span>
</Tooltip>
);
}
+8 -8
View File
@@ -406,7 +406,7 @@ export default function TierHistoryChart({
</button>
))}
<select
className="h-7 border border-base-content/10 bg-base-100 px-2 text-xs text-base-content focus:border-primary/30 focus:outline-none"
className="lts-select"
value={period}
onChange={(event) => {
const nextPeriod = event.target.value as PeriodKey;
@@ -526,13 +526,13 @@ export default function TierHistoryChart({
r={3}
stroke="currentColor"
fill="currentColor"
className="text-amber-400"
className="text-gold"
label={{
value: formatTierCompactLabel(summary.peak),
position: "top",
fill: "currentColor",
fontSize: 10,
className: "text-amber-400",
className: "text-gold",
}}
/>
)}
@@ -544,7 +544,7 @@ export default function TierHistoryChart({
fill="currentColor"
className={
isSamePoint(summary.peak, summary.last)
? "text-amber-400"
? "text-gold"
: "text-primary"
}
label={{
@@ -553,7 +553,7 @@ export default function TierHistoryChart({
fill: "currentColor",
fontSize: 10,
className: isSamePoint(summary.peak, summary.last)
? "text-amber-400"
? "text-gold"
: "text-primary",
}}
/>
@@ -582,7 +582,7 @@ export default function TierHistoryChart({
</span>
<span className="text-base-content/45">
최고{" "}
<span className="font-bold text-amber-400">
<span className="font-bold text-gold">
{formatTierLabel(summary.peak)}
</span>
</span>
@@ -591,9 +591,9 @@ export default function TierHistoryChart({
<span
className={`font-bold ${
summary.direction === "up"
? "text-green-500"
? "text-leaf"
: summary.direction === "down"
? "text-red-400"
? "text-loss"
: "text-base-content/55"
}`}
>
@@ -16,6 +16,7 @@ import {
} from "../../api/hooks";
import { ApiError } from "../../lib/api";
import { Btn } from "../../ui/Btn";
type AdjudicationType = SeriesAdjudicationDecision["type"];
const ADJUDICATION_LABELS: Record<AdjudicationType, string> = {
@@ -132,6 +133,15 @@ export function CompetitionAdminControls({
queryClient.invalidateQueries({
queryKey: ["matches-page", communityId],
}),
queryClient.invalidateQueries({
queryKey: ["community-internal-stats-matches", communityId],
}),
queryClient.invalidateQueries({
queryKey: ["community-internal-stats-match", communityId, matchId],
}),
queryClient.invalidateQueries({
queryKey: ["hall-of-fame", communityId],
}),
]);
}
@@ -312,7 +322,7 @@ export function CompetitionAdminControls({
<label className="mt-4 block text-xs font-bold text-base-content/55">
Series
<select
className="mt-1.5 h-10 w-full border border-base-content/15 bg-base-100 px-3 text-sm focus:border-warning/50 focus:outline-none"
className="lts-select mt-1.5 w-full"
value={effectiveSelectedSeriesId}
disabled={commandPending}
onChange={(event) => handleSelectedSeriesChange(event.target.value)}
@@ -364,7 +374,7 @@ export function CompetitionAdminControls({
<label className="text-xs font-bold text-base-content/50">
판정 유형
<select
className="mt-1.5 h-10 w-full border border-base-content/15 bg-base-100 px-3 text-sm focus:border-warning/50 focus:outline-none"
className="lts-select mt-1.5 w-full"
value={effectiveAdjudicationType}
disabled={adjudicationMutation.isPending}
onChange={(event) => {
@@ -395,7 +405,7 @@ export function CompetitionAdminControls({
<label className="text-xs font-bold text-base-content/50">
승리 팀
<select
className="mt-1.5 h-10 w-full border border-base-content/15 bg-base-100 px-3 text-sm focus:border-warning/50 focus:outline-none"
className="lts-select mt-1.5 w-full"
value={effectiveWinnerTeamId}
disabled={adjudicationMutation.isPending}
onChange={(event) => {
@@ -419,7 +429,7 @@ export function CompetitionAdminControls({
<label className="block text-xs font-bold text-base-content/50">
판정 사유
<textarea
className="mt-1.5 min-h-24 w-full resize-y border border-base-content/15 bg-base-100 px-3 py-2 text-sm focus:border-warning/50 focus:outline-none"
className="lts-textarea mt-1.5 min-h-24 w-full resize-y"
maxLength={2000}
value={adjudicationReason}
disabled={adjudicationMutation.isPending}
@@ -432,9 +442,9 @@ export function CompetitionAdminControls({
required
/>
</label>
<button
<Btn
type="submit"
className="btn btn-warning btn-sm px-4 text-xs"
variant="secondary"
disabled={
adjudicationMutation.isPending ||
!adjudicationReason.trim() ||
@@ -443,7 +453,7 @@ export function CompetitionAdminControls({
}
>
{adjudicationMutation.isPending ? "기록 중..." : "판정 기록"}
</button>
</Btn>
</form>
) : canReverse && selectedSeries ? (
<form className="mt-4 space-y-3" onSubmit={handlePreviewSubmit}>
@@ -464,7 +474,7 @@ export function CompetitionAdminControls({
<input
type="radio"
name="reversal-mode"
className="radio radio-warning radio-xs mt-0.5"
className="lts-checkbox mt-0.5"
value={mode}
checked={reversalMode === mode}
disabled={
@@ -495,7 +505,7 @@ export function CompetitionAdminControls({
<label className="block text-xs font-bold text-base-content/50">
되돌리기 사유
<textarea
className="mt-1.5 min-h-24 w-full resize-y border border-base-content/15 bg-base-100 px-3 py-2 text-sm focus:border-warning/50 focus:outline-none"
className="lts-textarea mt-1.5 min-h-24 w-full resize-y"
maxLength={2000}
value={reversalReason}
disabled={previewMutation.isPending || reversalMutation.isPending}
@@ -511,9 +521,9 @@ export function CompetitionAdminControls({
/>
</label>
<button
<Btn
type="submit"
className="btn btn-outline btn-sm px-4 text-xs"
variant="secondary"
disabled={
previewMutation.isPending ||
reversalMutation.isPending ||
@@ -521,7 +531,7 @@ export function CompetitionAdminControls({
}
>
{previewMutation.isPending ? "계산 중..." : "영향 미리보기"}
</button>
</Btn>
{reversalPreview && (
<ReversalImpactPanel
@@ -632,21 +642,20 @@ function ReversalImpactPanel({
<label className="mt-3 flex items-start gap-2 text-xs text-base-content/60">
<input
type="checkbox"
className="checkbox checkbox-error checkbox-xs mt-0.5"
className="lts-checkbox mt-0.5"
checked={confirmed}
disabled={!previewIsCurrent || executing}
onChange={(event) => onConfirmedChange(event.target.checked)}
/>
표시된 Series, 사실, 코드 및 통계 영향을 확인했습니다.
</label>
<button
type="button"
className="btn btn-error btn-sm mt-3 px-4 text-xs"
<Btn
variant="destructive" className="mt-3"
disabled={!confirmed || !previewIsCurrent || executing}
onClick={onExecute}
>
{executing ? "되돌리는 중..." : "Hash 확인 후 되돌리기"}
</button>
</Btn>
</div>
);
}
@@ -16,9 +16,11 @@ import { SeriesScoreCard } from "./SeriesScoreCard";
export function CompetitionResults({
competition,
view = "all",
showTeamLink = true,
}: {
competition: CompetitionDetailResponse;
view?: "all" | "bracket" | "games";
showTeamLink?: boolean;
}) {
const { projection } = competition;
const teamById = new Map(
@@ -59,24 +61,18 @@ export function CompetitionResults({
<section className="mb-6 space-y-4" aria-labelledby="competition-heading">
<header className="flex flex-wrap items-end justify-between gap-3 border-b border-base-content/10 pb-3">
<div>
<p className="text-[11px] font-bold uppercase tracking-wider text-base-content/35">
Competition
</p>
<h2 id="competition-heading" className="mt-1 text-lg font-bold">
공식 경기 일정·결과
대진표·순위
</h2>
</div>
<div className="flex items-center gap-3">
<span className="text-xs text-base-content/40">
revision {competition.revision}
</span>
{showTeamLink && (
<Link
to={`/match/${competition.matchId}/team`}
className="border border-base-content/10 px-2.5 py-1.5 text-xs font-bold text-base-content/55 hover:border-primary/30 hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
>
팀 진행
팀 경기 현황
</Link>
</div>
)}
</header>
{projection.outcome && (
@@ -136,8 +132,8 @@ function GenericRoundGrid({
teamById: Map<TeamId, CompetitionDetailResponse["teams"][number]>;
}) {
return (
<div className="overflow-x-auto pb-2">
<div className="grid min-w-max auto-cols-[17rem] grid-flow-col gap-4">
<div className="pb-2 md:overflow-x-auto">
<div className="grid gap-4 md:min-w-max md:auto-cols-[17rem] md:grid-flow-col">
{rounds.map((round) => (
<RoundColumn
key={`${round.stage}:${round.roundNumber ?? 0}`}
@@ -169,12 +165,13 @@ function RoundColumn({
{bracketRoundLabel(round.stage, round.roundNumber)}
</h3>
<div className="space-y-3">
{round.seriesIds.map((seriesId) => {
{round.seriesIds.map((seriesId, index) => {
const series = seriesById.get(seriesId);
return series ? (
<SeriesScoreCard
key={series.seriesId}
series={series}
displayLabel={`${index + 1}경기`}
teamById={teamById}
/>
) : null;
@@ -23,6 +23,10 @@ export function DoubleEliminationMobileBracket({
projection.series.map((series) => [series.seriesId, series]),
);
const nodeById = new Map(layout.nodes.map((node) => [node.seriesId, node]));
const isCurrentRound = (seriesIds: readonly SeriesId[]) => seriesIds.some((seriesId) => {
const status = seriesById.get(seriesId)?.status;
return status === "ready" || status === "in-progress";
});
const sections = [
{
key: "upper",
@@ -71,20 +75,20 @@ export function DoubleEliminationMobileBracket({
{section.description}
</p>
</div>
<div className="space-y-5">
<div className="space-y-2">
{groups.map((group) => (
<section
<details
key={`${group.stage}:${group.roundNumber}`}
aria-labelledby={`${bracketId}-${group.stage}-${group.roundNumber}`}
open={groups.length === 1 || isCurrentRound(group.seriesIds)}
className="group lts-panel"
>
<h4
id={`${bracketId}-${group.stage}-${group.roundNumber}`}
className="mb-2 text-xs font-bold text-content-muted"
aria-label={group.accessibleLabel}
<summary
className="cursor-pointer px-3 py-3 text-sm font-semibold hover:bg-sunken"
>
{group.label}
</h4>
<div className="space-y-3">
{group.accessibleLabel}
<span className="ml-2 text-xs font-medium text-content-muted">{group.seriesIds.length}경기</span>
</summary>
<div className="space-y-3 border-t border-line p-3">
{group.seriesIds.map((seriesId) => {
const series = seriesById.get(seriesId);
if (!series) return null;
@@ -113,7 +117,7 @@ export function DoubleEliminationMobileBracket({
);
})}
</div>
</section>
</details>
))}
</div>
</section>
@@ -55,9 +55,9 @@ export function MatchDetailTabBar({
}
return (
<div className="sticky top-12 z-40 -mx-4 border-y border-base-content/10 bg-base-100/95 px-4 backdrop-blur sm:-mx-6 sm:px-6">
<div className="lts-panel sticky top-(--app-header-nav-height) z-40 p-1">
<div
className="flex overflow-x-auto"
className="no-scrollbar flex gap-1 overflow-x-auto"
role="tablist"
aria-label="내전 상세"
>
@@ -77,10 +77,10 @@ export function MatchDetailTabBar({
tabIndex={selected ? 0 : -1}
onClick={() => onChange(tab.id)}
onKeyDown={(event) => handleKeyDown(event, tab.id)}
className={`min-h-11 flex-none whitespace-nowrap border-b-2 px-4 text-xs font-bold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary ${
className={`h-10 flex-none whitespace-nowrap rounded-[10px] px-4 text-sm font-bold transition-colors sm:px-5 ${
selected
? "border-primary bg-primary/5 text-base-content"
: "border-transparent text-base-content/45 hover:bg-base-content/[0.03] hover:text-base-content"
? "bg-secondary text-secondary-content"
: "text-content-muted hover:bg-sunken hover:text-content"
}`}
>
{tab.label}
@@ -86,11 +86,6 @@ export function SeriesScoreCard({
<span className="block truncate text-[11px] font-bold leading-3 text-base-content/75">
{identity.label}
</span>
{identity.code && (
<span className="mt-0.5 block truncate font-mono text-[9px] leading-[10px] text-content-subtle">
{identity.code}
</span>
)}
</span>
<span
className={`inline-flex shrink-0 items-center gap-1 border px-1 py-0.5 text-[10px] font-bold leading-3 ${STATUS_TONE_CLASS[presentation.tone]}`}
@@ -58,9 +58,6 @@ export function TeamSeriesCard({
{displayLabel}
</h3>
<div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-content-muted">
{series.code && (
<code className="break-all font-mono">{series.code}</code>
)}
<span>{seriesRuleLabel(series)}</span>
</div>
</div>
@@ -55,7 +55,7 @@ export function TeamTournamentCodes({
return (
<div className="border-t border-base-content/10 px-4 py-5 sm:px-5">
<p role="status" className="text-sm text-content-muted">
이 경기에 배정된 토너먼트 코드가 없습니다.
표시할 세트 정보가 아직 없습니다.
</p>
</div>
);
@@ -99,19 +99,10 @@ export function TeamTournamentCodes({
}
}
return (
<section
className="border-t border-base-content/10"
aria-label={`${seriesLabel} 토너먼트 코드`}
>
<div className="flex flex-wrap items-baseline justify-between gap-2 bg-base-200/25 px-4 py-2.5 sm:px-5">
<h4 className="text-sm font-bold text-base-content">게임 코드</h4>
<p className="text-xs text-content-muted">
세트에 맞는 코드를 복사해 클라이언트에 입력하세요.
</p>
</div>
<ol className="divide-y divide-base-content/10">
{assignments.map((assignment) => {
const nextAssignment = assignments.find((assignment) => assignment.state !== "used") ?? assignments[0];
const otherAssignments = assignments.filter((assignment) => assignment !== nextAssignment);
function renderAssignment(assignment: TeamTournamentCodeView) {
const slotId = String(assignment.gameSlotId);
const presentation = getTournamentCodePresentation(assignment, now);
const isCopying = copyingSlotId === slotId;
@@ -127,7 +118,7 @@ export function TeamTournamentCodes({
{assignment.ordinal}세트
</p>
<p className="mt-0.5 text-xs text-content-muted">
전체 Game {assignment.displayNumber}
전체 {assignment.displayNumber}경기
</p>
</div>
@@ -139,7 +130,7 @@ export function TeamTournamentCodes({
/>
) : (
<p className="text-sm font-bold text-content-muted">
발급 대기 중
발급되면 이곳에서 복사할 수 있습니다.
</p>
)}
{assignment.code &&
@@ -199,8 +190,29 @@ export function TeamTournamentCodes({
</div>
</li>
);
})}
}
return (
<section
className="border-t border-base-content/10 bg-sunken/50"
aria-label={`${seriesLabel} 토너먼트 코드`}
>
<div className="px-4 pt-3 sm:px-5">
<h4 className="text-sm font-bold">토너먼트 코드</h4>
</div>
<ol>
{renderAssignment(nextAssignment)}
</ol>
{otherAssignments.length > 0 && (
<details className="border-t border-line">
<summary className="cursor-pointer px-4 py-3 text-sm font-semibold hover:bg-sunken sm:px-5">
다른 세트 코드 · {otherAssignments.length}개
</summary>
<ol className="divide-y divide-line border-t border-line">
{otherAssignments.map(renderAssignment)}
</ol>
</details>
)}
{feedback && (
<p
@@ -251,7 +263,7 @@ function AutoSizingCodeField({
<textarea
ref={fieldRef}
aria-label={label}
className="block min-h-11 w-full resize-none overflow-hidden border border-base-content/15 bg-base-100 px-3 py-2 font-mono text-sm font-bold leading-5 text-base-content focus-visible:ring-2 focus-visible:ring-primary"
className="lts-textarea min-h-11 w-full resize-none overflow-hidden font-mono font-bold leading-5"
onClick={(event) => event.currentTarget.select()}
onFocus={(event) => event.currentTarget.select()}
readOnly
+2 -2
View File
@@ -36,10 +36,10 @@ export function formatRankBadge(tier: ApiTierInfo | undefined) {
return rank ? `${tierInitial}${rank}` : tierInitial;
}
export function formatRankDetail(tier: ApiTierInfo | undefined) {
export function formatRankDetail(tier: Pick<ApiTierInfo, "tier"> & Partial<Pick<ApiTierInfo, "rank" | "leaguePoints">> | undefined) {
if (!tier) return "랭크 정보 없음";
const tierName = TIER_NAMES[tier.tier] ?? tier.tier;
const rank = normalizeRank(tier.rank);
const label = rank ? `${tierName} ${rank}` : tierName;
return `${label} - ${tier.leaguePoints} LP`;
return tier.leaguePoints === undefined ? label : `${label} - ${tier.leaguePoints} LP`;
}
-37
View File
@@ -1,11 +1,8 @@
import { useSyncExternalStore } from 'react';
const AUTH_USER_ID_STORAGE_KEY = 'lolympus.authUserId';
const DEV_CAPTAIN_TEAM_INDEX_STORAGE_KEY = 'lolympus.devCaptainTeamIndex';
const LEGACY_DEV_CAPTAIN_SIDE_STORAGE_KEY = 'lolympus.devCaptainSide';
const THEME_STORAGE_KEY = 'lolympus.theme';
const AUTH_USER_CHANGED_EVENT = 'lolympus:auth-user-changed';
const CAPTAIN_SIDE_CHANGED_EVENT = 'lolympus:captain-side-changed';
const THEME_CHANGED_EVENT = 'lolympus:theme-changed';
export type AppTheme = 'light' | 'dark';
@@ -58,32 +55,6 @@ export function setAuthUserId(userId: string | null) {
dispatchWindowEvent(AUTH_USER_CHANGED_EVENT);
}
export function getDevCaptainTeamIndex(): number | null {
if (typeof window === 'undefined') return null;
const value = window.localStorage.getItem(DEV_CAPTAIN_TEAM_INDEX_STORAGE_KEY);
const parsed = Number(value);
if (Number.isInteger(parsed) && parsed > 0) return parsed;
const legacy = window.localStorage.getItem(LEGACY_DEV_CAPTAIN_SIDE_STORAGE_KEY);
if (legacy === 'blue') return 1;
if (legacy === 'red') return 2;
return null;
}
export function setDevCaptainTeamIndex(teamIndex: number | null) {
if (typeof window === 'undefined') return;
if (teamIndex && Number.isInteger(teamIndex) && teamIndex > 0) {
window.localStorage.setItem(
DEV_CAPTAIN_TEAM_INDEX_STORAGE_KEY,
String(teamIndex),
);
} else {
window.localStorage.removeItem(DEV_CAPTAIN_TEAM_INDEX_STORAGE_KEY);
}
dispatchWindowEvent(CAPTAIN_SIDE_CHANGED_EVENT);
}
function normalizeTheme(value: string | null | undefined): AppTheme {
return value === 'dark' ? 'dark' : 'light';
}
@@ -126,14 +97,6 @@ export function useAuthUserId(): string | null {
);
}
export function useDevCaptainTeamIndex(): number | null {
return useSyncExternalStore<number | null>(
(callback) => subscribeToWindowChanges(CAPTAIN_SIDE_CHANGED_EVENT, callback),
getDevCaptainTeamIndex,
() => null,
);
}
export function useTheme(): AppTheme {
return useSyncExternalStore<AppTheme>(
(callback) => subscribeToWindowChanges(THEME_CHANGED_EVENT, callback),
+495 -122
View File
@@ -1,137 +1,520 @@
@import url("https://fonts.googleapis.com/css2?family=Asta+Sans:wght@300..800&family=Gamja+Flower&display=swap");
/*
* LOLYMPUS 스타일 진입점.
*
* 레이어 순서(낮음 → 높음):
* reset → theme → base → astryx-base → astryx-theme → lolympus → components → utilities
*
* Astryx(core + Neutral 테마)가 프리미티브의 모양을 맡고, `lolympus` 레이어가
* Neutral 토큰을 LOLYMPUS 팔레트로 덮는다. Tailwind 유틸리티는 아래 @theme 매핑을
* 통해 같은 토큰을 읽으므로 라이트/다크 전환은 토큰 한 곳에서만 일어난다.
*/
@layer reset, theme, base, astryx-base, astryx-theme, lolympus, components, utilities;
@import "tailwindcss/theme.css" layer(theme);
@import "tailwindcss/preflight.css" layer(base);
@import "@astryxdesign/core/reset.css";
@import "@astryxdesign/core/astryx.css";
@import "@astryxdesign/theme-neutral/theme.css";
@import "tailwindcss/utilities.css" layer(utilities);
@import "tailwindcss";
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));
@plugin "daisyui" {
themes:
light --default,
dark;
@font-face {
font-family: "SuitVariable";
src: url("https://cdn.jsdelivr.net/gh/Project-Noonnu/2611030106@font-variable-845/variable-845/SUIT-Variable.woff2") format("woff2");
font-style: normal;
font-weight: 100 900;
font-display: swap;
}
/* ── 브랜드 원색 ──
실제 색상값은 이곳에서만 관리하고, 화면에서는 아래의 의미 토큰을 사용한다. */
/* ── 원색 ──
실제 색상값은 이곳에서만 관리한다. 화면은 아래 역할 토큰을 쓴다. */
@theme static {
--color-brand-coral: oklch(0.708008 0.234375 24);
--color-brand-violet: oklch(0.481934 0.285938 285);
--color-brand-gold: oklch(0.853027 0.2 90);
--color-brand-cyan: oklch(70% 0.14523 200);
--color-brand-coral: oklch(70.8008% .234375 24);
--color-brand-ink: #22252e;
--color-brand-gold: #f2b01e;
--color-brand-leaf: #2f9e58;
/* 기본 표면과 테두리 */
--color-palette-white: #ffffff;
--color-palette-black: #000000;
--color-palette-body-dark: #14161b;
--color-palette-card-dark: #1e2129;
--color-palette-popover-dark: #272b35;
--color-palette-muted-light: #eff0f5;
--color-palette-muted-dark: #262a33;
--color-palette-sunken-dark: #181b21;
--color-palette-sunken-strong-light: #e7eaf1;
--color-palette-sunken-strong-dark: #2b2f39;
--color-palette-line-light: #e2e4eb;
--color-palette-line-dark: #ffffff17;
--color-palette-line-strong-light: #d2d6e1;
--color-palette-line-strong-dark: #484d5a;
--color-palette-shadow-light: #26283808;
--color-palette-shadow-dark: #00000033;
/* 글자 */
--color-palette-title-light: #454757;
--color-palette-text-light: #3d3f4c;
--color-palette-text-strong-light: #262838;
--color-palette-text-dark: #f1f2f5;
--color-palette-text-secondary-dark: #b3b9c6;
--color-palette-text-subtle-light: #6d707f;
--color-palette-text-disabled-light: #9297a5;
--color-palette-text-disabled-dark: #6f7685;
--color-palette-coral-ink: #261b19;
--color-palette-gold-ink: #2a1f04;
--color-palette-item-highlight: #f0d878;
/* 경기 결과와 상태 */
--color-palette-win-text-light: #2456a2;
--color-palette-win-text-dark: #a2c4ff;
--color-palette-win-fill-light: #4279ca;
--color-palette-win-fill-dark: #6598e7;
--color-palette-win-tint-dark: #202b3d;
--color-palette-loss-text-light: #a92e42;
--color-palette-loss-text-dark: #ffabb3;
--color-palette-loss-fill-light: #d75464;
--color-palette-loss-fill-dark: #ea7583;
--color-palette-loss-tint-dark: #39272b;
--color-palette-gold-text-light: #805213;
--color-palette-gold-text-dark: #f1cd82;
--color-palette-gold-tint-light: #fbf2df;
--color-palette-gold-tint-dark: #3b3020;
--color-palette-leaf-text-light: #246a46;
--color-palette-leaf-text-dark: #9cd8b2;
--color-palette-leaf-fill-dark: #5cba82;
--color-palette-leaf-tint-light: #eaf4ed;
--color-palette-leaf-tint-dark: #23352a;
}
html {
scrollbar-gutter: stable;
@layer lolympus {
:root,
[data-astryx-theme="neutral"] {
/* 글자 */
--font-family-body:
"SuitVariable", -apple-system, BlinkMacSystemFont, system-ui,
"Apple SD Gothic Neo", "Noto Sans KR", "Malgun Gothic", sans-serif;
--font-family-heading: var(--font-family-body);
/* 카드, 조작 요소, 작은 이미지의 모서리 */
--radius-inner: 0.375rem;
--radius-element: 0.5rem;
--radius-container: 0.75rem;
--radius-page: 0.75rem;
/* 조작 요소 높이: 칩(32) · 기본 버튼(36) · 강조 버튼과 탭(40) */
--size-element-sm: 2rem;
--size-element-md: 2.25rem;
--size-element-lg: 2.5rem;
/* 흰 기본 표면과 옅은 보조 표면 */
--color-background-body: light-dark(var(--color-palette-white), var(--color-palette-body-dark));
--color-background-card: light-dark(var(--color-palette-white), var(--color-palette-card-dark));
--color-background-surface: var(--color-background-card);
--color-background-popover: light-dark(var(--color-palette-white), var(--color-palette-popover-dark));
--color-background-muted: light-dark(var(--color-palette-muted-light), var(--color-palette-muted-dark));
/* 글자·선 */
--color-text-primary: light-dark(var(--color-palette-text-light), var(--color-palette-text-dark));
--lts-text-title: light-dark(var(--color-palette-title-light), var(--color-palette-text-dark));
--lts-text-strong: light-dark(var(--color-palette-text-strong-light), var(--color-palette-text-dark));
--color-text-secondary: light-dark(
var(--color-palette-title-light),
var(--color-palette-text-secondary-dark)
);
/* 흰 표면의 보조 글자. 옅은 배경의 작은 글자는 secondary를 쓴다. */
--lts-text-subtle: light-dark(var(--color-palette-text-subtle-light), var(--color-palette-text-secondary-dark));
--color-text-disabled: light-dark(
var(--color-palette-text-disabled-light),
var(--color-palette-text-disabled-dark)
);
--color-icon-primary: var(--color-text-primary);
--color-icon-secondary: var(--color-text-secondary);
--color-border: light-dark(var(--color-palette-line-light), var(--color-palette-line-dark));
--color-border-emphasized: light-dark(
var(--color-palette-line-strong-light),
var(--color-palette-line-strong-dark)
);
/* 주 액션: 브랜드 코랄 위에 짙은 글자 */
--color-accent: var(--color-brand-coral);
--color-on-accent: var(--color-palette-coral-ink);
--color-accent-muted: light-dark(
color-mix(in oklab, var(--color-brand-coral) 13%, var(--color-background-card)),
color-mix(in oklab, var(--color-brand-coral) 25%, var(--color-background-body))
);
--color-text-accent: light-dark(
color-mix(in oklab, var(--color-brand-coral) 70%, var(--color-palette-black)),
color-mix(in oklab, var(--color-brand-coral) 66%, var(--color-palette-white))
);
--color-icon-accent: var(--color-text-accent);
/* 선택된 필터와 탭 */
--lts-ink: light-dark(var(--color-brand-ink), var(--color-palette-text-dark));
--lts-on-ink: light-dark(var(--color-palette-white), var(--color-palette-text-strong-light));
/* 제목 영역은 본문과 같은 계열의 단색 표면을 쓴다. */
--lts-hero: var(--lts-sunken);
--lts-hero-raised: var(--color-background-card);
--lts-hero-line: var(--color-border);
--lts-on-hero: var(--color-text-primary);
--lts-on-hero-muted: var(--color-text-secondary);
/* 들어간 표면(표 머리, 통계 칸, 입력 배경) */
--lts-sunken: light-dark(var(--color-palette-muted-light), var(--color-palette-sunken-dark));
--lts-sunken-strong: light-dark(
var(--color-palette-sunken-strong-light),
var(--color-palette-sunken-strong-dark)
);
/* 경기 결과와 진영 */
--lts-win: light-dark(var(--color-palette-win-text-light), var(--color-palette-win-text-dark));
--lts-win-fill: light-dark(var(--color-palette-win-fill-light), var(--color-palette-win-fill-dark));
--lts-win-tint: light-dark(
color-mix(in srgb, var(--color-palette-win-fill-light) 5%, var(--color-palette-white)),
var(--color-palette-win-tint-dark)
);
--lts-win-line: color-mix(in srgb, var(--lts-win-fill) 25%, var(--color-background-card));
--lts-loss: light-dark(var(--color-palette-loss-text-light), var(--color-palette-loss-text-dark));
--lts-loss-fill: light-dark(var(--color-palette-loss-fill-light), var(--color-palette-loss-fill-dark));
--lts-loss-tint: light-dark(
color-mix(in srgb, var(--color-palette-loss-fill-light) 5%, var(--color-palette-white)),
var(--color-palette-loss-tint-dark)
);
--lts-loss-line: color-mix(in srgb, var(--lts-loss-fill) 25%, var(--color-background-card));
--lts-gold: light-dark(var(--color-palette-gold-text-light), var(--color-palette-gold-text-dark));
--lts-gold-fill: var(--color-brand-gold);
--lts-gold-tint: light-dark(var(--color-palette-gold-tint-light), var(--color-palette-gold-tint-dark));
--lts-leaf: light-dark(var(--color-palette-leaf-text-light), var(--color-palette-leaf-text-dark));
--lts-leaf-fill: light-dark(var(--color-brand-leaf), var(--color-palette-leaf-fill-dark));
--lts-leaf-tint: light-dark(var(--color-palette-leaf-tint-light), var(--color-palette-leaf-tint-dark));
--lts-shadow-card: 0 3px 10px
light-dark(var(--color-palette-shadow-light), var(--color-palette-shadow-dark));
}
}
body {
margin: 0;
font-family:
"Asta Sans",
-apple-system,
BlinkMacSystemFont,
system-ui,
Roboto,
"Helvetica Neue",
"Segoe UI",
"Apple SD Gothic Neo",
"Noto Sans KR",
"Malgun Gothic",
"Apple Color Emoji",
"Segoe UI Emoji",
"Segoe UI Symbol",
sans-serif;
font-size: 15px;
line-height: 1.55;
@layer base {
html {
scrollbar-gutter: stable;
}
body {
margin: 0;
background: var(--color-background-body);
color: var(--color-text-primary);
font-family: var(--font-family-body);
font-size: 15px;
line-height: 1.55;
-webkit-font-smoothing: antialiased;
}
}
/* ── 가독성 개선: 의미 기반 텍스트 대비 토큰 ──
폰트 크기는 표준 스케일 토큰(text-xs=12px / text-sm=14px …)을 사용한다.
새 코드에서는 text-content-subtle/muted/disabled를 우선 사용한다. */
:root,
[data-theme="light"] {
--lts-text-subtle-strength: 66%;
--lts-text-muted-strength: 72%;
--lts-text-disabled-strength: 50%;
--lts-content-subtle: color-mix(
in oklab,
var(--color-base-content) var(--lts-text-subtle-strength),
transparent
);
--lts-content-muted: color-mix(
in oklab,
var(--color-base-content) var(--lts-text-muted-strength),
transparent
);
--lts-content-disabled: color-mix(
in oklab,
var(--color-base-content) var(--lts-text-disabled-strength),
transparent
);
}
@layer lolympus {
/* Neutral의 prose 초기화는 h/p에 크기·색을 직접 지정한다. 화면 마크업은
부모에게서 상속받는 것을 전제로 작성했으므로 상속으로 되돌린다.
Astryx의 Heading/Text는 자체 클래스로 모양을 정하므로 영향이 없다. */
:where(h1, h2, h3, h4, h5, h6, p, small) {
font-family: inherit;
font-size: inherit;
font-weight: inherit;
line-height: inherit;
color: inherit;
}
[data-theme="dark"] {
--lts-text-subtle-strength: 66%;
--lts-text-muted-strength: 76%;
--lts-text-disabled-strength: 52%;
:where(h1, h2, h3, h4, h5, h6) {
color: var(--lts-text-title);
}
/* 테두리를 두른 상자·칩의 기본 모서리. rounded-* 유틸리티가 항상 이긴다. */
:where(
div,
section,
article,
aside,
li,
ul,
a,
form,
label,
details,
summary,
span,
button,
img
).border {
border-radius: var(--radius-element);
}
:where(button, [role="button"]) {
border-radius: var(--radius-element);
}
/* 챔피언·아이템·프로필 그림과 그 틀은 살짝 둥글린다. */
:where(img) {
border-radius: var(--radius-inner);
}
:where(div, span).overflow-hidden:has(> img:only-child) {
border-radius: var(--radius-inner);
}
:focus-visible {
outline: 2px solid var(--color-text-accent);
outline-offset: 2px;
}
/* 버튼은 칩과 같은 알약 모양으로 통일한다. */
.astryx-button {
border-radius: 999px;
font-weight: 600;
}
.astryx-button:where([data-size="md"], [data-size="lg"]) {
padding-inline: 1rem;
}
}
/* ── Tailwind 유틸리티 ↔ 토큰 매핑 ──
base-100·primary 같은 이름은 기존 마크업과의 호환을 위해 유지한다. 새 코드는
card / sunken / ink / win / loss 같은 역할 이름을 쓴다. */
@theme inline {
--color-content-subtle: var(--lts-content-subtle);
--color-content-muted: var(--lts-content-muted);
--color-content-disabled: var(--lts-content-disabled);
--color-bracket-winner: var(--color-brand-coral);
--font-sans: var(--font-family-body);
--color-base-100: var(--color-background-card);
--color-base-200: var(--lts-sunken);
--color-base-300: var(--lts-sunken-strong);
--color-base-content: var(--color-text-primary);
--color-body: var(--color-background-body);
--color-card: var(--color-background-card);
--color-sunken: var(--lts-sunken);
--color-sunken-strong: var(--lts-sunken-strong);
--color-line: var(--color-border);
--color-line-strong: var(--color-border-emphasized);
--color-content: var(--color-text-primary);
--text-color-content-strong: var(--lts-text-strong);
--color-content-muted: var(--color-text-secondary);
--color-content-subtle: var(--lts-text-subtle);
--color-content-disabled: var(--color-text-disabled);
/* ink 유틸리티는 페이지 머리 띠 표면을 가리킨다. 짙은 채움은 secondary를 쓴다. */
--color-ink: var(--lts-hero);
--color-ink-raised: var(--lts-hero-raised);
--color-ink-line: var(--lts-hero-line);
--color-on-ink: var(--lts-on-hero);
--color-on-ink-muted: var(--lts-on-hero-muted);
/* primary: 채움은 브랜드 코랄, 글자·선은 테마에 맞춘 코랄 */
--color-primary: var(--color-accent);
--text-color-primary: var(--color-text-accent);
--text-decoration-color-primary: var(--color-text-accent);
--color-primary-content: var(--color-on-accent);
--color-primary-tint: var(--color-accent-muted);
--color-secondary: var(--lts-ink);
--color-secondary-content: var(--lts-on-ink);
--text-color-secondary: var(--color-text-secondary);
--color-accent: var(--lts-gold-fill);
--text-color-accent: var(--lts-gold);
--color-accent-content: var(--color-palette-gold-ink);
--color-win: var(--lts-win-fill);
--text-color-win: var(--lts-win);
--color-win-tint: var(--lts-win-tint);
--color-win-line: var(--lts-win-line);
--color-loss: var(--lts-loss-fill);
--text-color-loss: var(--lts-loss);
--color-loss-tint: var(--lts-loss-tint);
--color-loss-line: var(--lts-loss-line);
--color-gold: var(--lts-gold-fill);
--text-color-gold: var(--lts-gold);
--color-gold-tint: var(--lts-gold-tint);
--color-leaf: var(--lts-leaf-fill);
--text-color-leaf: var(--lts-leaf);
--color-leaf-tint: var(--lts-leaf-tint);
--color-info: var(--lts-win-fill);
--text-color-info: var(--lts-win);
--color-info-content: var(--color-palette-white);
--color-success: var(--lts-leaf-fill);
--text-color-success: var(--lts-leaf);
--color-success-content: var(--color-palette-white);
--color-warning: var(--lts-gold-fill);
--text-color-warning: var(--lts-gold);
--color-warning-content: var(--color-palette-gold-ink);
--color-error: var(--lts-loss-fill);
--text-color-error: var(--lts-loss);
--color-error-content: var(--color-palette-white);
--text-color-item-highlight: var(--color-palette-item-highlight);
--color-bracket-winner: var(--color-text-accent);
--radius-box: var(--radius-container);
--radius-field: var(--radius-element);
--shadow-card: var(--lts-shadow-card);
}
@layer utilities {
/* 기존 text-base-content/nn 알파 클래스 호환 shim.
hover/focus 상태 유틸이 specificity로 이길 수 있도록 !important를 쓰지 않는다. */
/* 낮은 알파의 본문색 글자는 대비가 무너진다. 보조 글자색으로 올려 붙인다.
hover/focus 유틸이 specificity로 이길 수 있도록 !important를 쓰지 않는다. */
.text-base-content\/15,
.text-base-content\/20,
.text-base-content\/25,
.text-base-content\/30,
.text-base-content\/35 {
color: var(--lts-content-subtle);
}
.text-base-content\/35,
.text-base-content\/40,
.text-base-content\/45,
.text-base-content\/50,
.text-base-content\/55 {
color: var(--lts-content-muted);
.text-base-content\/55,
.text-base-content\/60,
.text-base-content\/65,
.text-base-content\/70 {
color: var(--color-text-secondary);
}
.tabular {
font-variant-numeric: tabular-nums;
}
/* 이전/다음 조작이 따로 있는 가로 스크롤 띠에서 스크롤바를 숨긴다. */
.no-scrollbar {
scrollbar-width: none;
}
.no-scrollbar::-webkit-scrollbar {
display: none;
}
}
/* ── 라이트 테마 의미 색상 ── */
[data-theme="light"] {
/* ── 포인트 4색 (primary 주 액션 / secondary 강조 / accent 하이라이트 / info 정보·보조) ── */
@layer components {
.lts-app-shell {
--app-header-row-height: 3.25rem;
/* 페이지 내부 고정 탭의 위쪽 여백은 메뉴 줄 높이만 사용한다. */
--app-header-nav-height: 3rem;
--app-header-height: calc(var(--app-header-row-height) + var(--app-header-nav-height));
}
/* 코랄레드 — primary 117곳 즉시 반영 */
--color-primary: var(--color-brand-coral);
--color-primary-content: oklch(98% 0 0); /* 흰 글자 */
@media (width >= 48rem) {
.lts-app-shell {
--app-header-row-height: 3.5rem;
--app-header-nav-height: 4rem;
}
}
/* 바이올렛 — 버튼·뱃지·보더용 */
--color-secondary: var(--color-brand-violet);
--color-secondary-content: oklch(98% 0 0); /* 흰 글자 */
.lts-home-hero {
--hero-backdrop: var(--color-palette-body-dark);
background: var(--hero-backdrop);
color: var(--color-palette-white);
}
/* 골드 — 배경·보더·아이콘만. 텍스트색(text-accent)으론 쓰지 말 것 */
--color-accent: var(--color-brand-gold);
--color-accent-content: oklch(22% 0.03 80); /* 어두운 글자 */
.lts-home-hero::before {
content: "";
position: absolute;
inset: 0;
z-index: -1;
background: linear-gradient(
90deg,
color-mix(in srgb, var(--hero-backdrop) 92%, transparent),
color-mix(in srgb, var(--hero-backdrop) 80%, transparent) 55%,
color-mix(in srgb, var(--hero-backdrop) 45%, transparent)
);
}
/* 시안 — 정보·링크·보조 강조. L70이라 흰배경 텍스트는 약함 → 배경/보더 위주 */
--color-info: var(--color-brand-cyan);
--color-info-content: oklch(24% 0.03 215); /* 어두운 글자 */
@media (width >= 48rem) {
.lts-home-hero::before {
background: linear-gradient(
90deg,
var(--hero-backdrop),
color-mix(in srgb, var(--hero-backdrop) 78%, transparent) 35%,
color-mix(in srgb, var(--hero-backdrop) 10%, transparent) 80%,
var(--hero-backdrop)
);
}
}
/* 텍스트 기본 진하기 (회색 알파의 기준색). 낮출수록 전체가 진해짐 */
--color-base-content: oklch(21% 0.006 285.885);
/* 흰 카드. 페이지의 기본 데이터 그릇이다. */
.lts-panel {
background: var(--color-background-card);
border: 1px solid var(--color-border);
border-radius: var(--radius-container);
box-shadow: var(--lts-shadow-card);
}
/* 표면 톤 */
--color-base-100: oklch(100% 0 0); /* 페이지/카드 배경 */
--color-base-200: oklch(98% 0 0); /* 살짝 들어간 표면 */
--color-base-300: oklch(95% 0 0); /* 구분선/보더 */
}
/* 표: 머리는 들어간 표면, 행은 선 하나로만 나눈다. */
.lts-table {
width: 100%;
border-collapse: collapse;
font-size: 0.875rem;
}
.lts-table thead th {
background: var(--lts-sunken);
color: var(--color-text-secondary);
font-size: 0.75rem;
font-weight: 600;
text-align: left;
padding: 0.5rem 0.75rem;
white-space: nowrap;
border-bottom: 1px solid var(--color-border);
}
.lts-table tbody td {
padding: 0.625rem 0.75rem;
border-bottom: 1px solid var(--color-border);
}
.lts-table tbody tr:last-child td {
border-bottom: 0;
}
/* 경기 결과 기록의 링크 강조는 양쪽 테마에서 같은 브랜드 코랄을 쓴다.
전역 dark primary는 유지해 다른 화면의 기존 색상 의미를 바꾸지 않는다. */
.competition-series-history {
--color-primary: var(--color-brand-coral);
/* 네이티브 입력. 옵션이 많은 운영 폼은 네이티브 조작을 유지하고 모양만 맞춘다. */
.lts-input,
.lts-select,
.lts-textarea {
width: 100%;
min-height: 2.25rem;
padding: 0.375rem 0.75rem;
background: var(--color-background-card);
color: var(--color-text-primary);
border: 1px solid var(--color-border-emphasized);
border-radius: var(--radius-element);
font-size: 0.875rem;
line-height: 1.4;
transition:
border-color 120ms,
box-shadow 120ms;
}
.lts-input::placeholder,
.lts-textarea::placeholder {
color: var(--lts-text-subtle);
}
.lts-input:hover,
.lts-select:hover,
.lts-textarea:hover {
border-color: var(--lts-text-subtle);
}
.lts-input:focus-visible,
.lts-select:focus-visible,
.lts-textarea:focus-visible {
outline: none;
border-color: var(--color-text-accent);
box-shadow: 0 0 0 3px var(--color-accent-muted);
}
.lts-input:disabled,
.lts-select:disabled,
.lts-textarea:disabled {
background: var(--lts-sunken);
color: var(--color-text-disabled);
cursor: not-allowed;
}
.lts-textarea {
min-height: 5rem;
resize: vertical;
}
.lts-checkbox {
width: 1rem;
height: 1rem;
accent-color: var(--color-text-accent);
}
}
/* ── 실시간 입찰 피드백 모션 ──
@@ -172,32 +555,22 @@ body {
.animate-outbid-shake {
animation: lts-outbid-shake 0.4s ease-in-out;
}
/* 홈 순위 카드: 넘긴 방향에서 새 순위가 밀려 들어온다. */
@keyframes lts-rank-slide-in {
from {
opacity: 0;
transform: translateX(var(--lts-rank-slide-from, 1.5rem));
}
}
.lts-rank-slide {
animation: lts-rank-slide-in 280ms cubic-bezier(0.22, 1, 0.36, 1);
}
@media (prefers-reduced-motion: reduce) {
.lts-rank-slide,
.animate-bid-pop,
.animate-outbid-shake {
animation: none;
}
}
/* poro.gg style: 모든 모서리 각지게 */
*,
*::before,
*::after {
border-radius: 0 !important;
}
/* daisyUI badge만 살짝 둥글게 (pill 형태) */
.badge {
border-radius: 2px !important;
}
/* 버튼도 각지게 */
.btn {
border-radius: 0 !important;
}
/* daisyUI 버튼의 흰색 inset 하이라이트 제거 — 색 위에 흰색을 6% 얹어
채도를 깎던 주범(P3/쨍한 색일수록 도드라짐). drop shadow(입체감)는 유지. */
.btn {
box-shadow: var(--btn-shadow) !important;
}
+7 -7
View File
@@ -3,18 +3,18 @@ import type { DdragonManifest } from '../api/types';
const FALLBACK_VERSION = '15.24.1';
const FALLBACK_CDN = 'https://ddragon.leagueoflegends.com/cdn';
const DDRAGON_DESCRIPTION_TAG_CLASSES: Record<string, string> = {
active: 'text-[#f0d878] font-semibold',
attention: 'text-[#f0d878] font-semibold',
active: 'text-item-highlight font-semibold',
attention: 'text-item-highlight font-semibold',
flavorText: 'text-white/45 italic',
healing: 'text-emerald-300 font-semibold',
keywordMajor: 'text-[#f0d878] font-semibold',
keywordName: 'text-[#f0d878] font-semibold',
keywordMajor: 'text-item-highlight font-semibold',
keywordName: 'text-item-highlight font-semibold',
keywordStealth: 'text-violet-300 font-semibold',
mainText: 'text-white/80',
ornnBonus: 'text-[#f0d878] font-semibold',
passive: 'text-[#f0d878] font-semibold',
ornnBonus: 'text-item-highlight font-semibold',
passive: 'text-item-highlight font-semibold',
rarityGeneric: 'text-white/55',
rarityLegendary: 'text-[#f0d878] font-semibold',
rarityLegendary: 'text-item-highlight font-semibold',
rarityMythic: 'text-violet-300 font-semibold',
rules: 'text-white/45',
shield: 'text-sky-300 font-semibold',
@@ -0,0 +1,17 @@
import type { CompetitionGameView } from '@lolympus/contracts';
export function riotMatchIdForDisplay(
game: { riotMatchId: string; gameId?: string },
official?: CompetitionGameView,
): string | null {
if (official) {
return official.evidence.type === 'riot'
? official.evidence.riotMatchId
: null;
}
// Unmigrated records have no official evidence. Only display real Riot IDs,
// never synthetic legacy references stored in the same field.
return !game.gameId && /^[A-Z0-9]+_\d+$/.test(game.riotMatchId)
? game.riotMatchId
: null;
}
+61
View File
@@ -0,0 +1,61 @@
import type { CompetitionGameView, SeriesProjection } from '@lolympus/contracts';
import type { ApiInternalMatchDetailResponse } from '../api/types';
import { bracketRoundAccessibleLabel } from '../components/competition/double-elimination-bracket-layout';
import { teamIndexLabel } from './league';
type RecordedGame = ApiInternalMatchDetailResponse['games'][number];
export interface RecordedSet {
game: RecordedGame;
official?: CompetitionGameView;
}
export interface RecordedSeries {
id: string;
label: string;
series?: SeriesProjection;
sets: RecordedSet[];
}
export function groupRecordedSets(
detail: ApiInternalMatchDetailResponse,
) {
const projection = detail.competition?.projection;
const officialById = new Map(projection?.games.map((game) => [game.id, game]));
const seriesById = new Map(
projection?.series.map((series) => [series.seriesId, series]),
);
const groups = new Map<string, RecordedSeries>();
for (const game of detail.games) {
const official = game.gameId && officialById.get(game.gameId);
const series = game.seriesId && seriesById.get(game.seriesId);
const indexes = [
...new Set(game.teams.map(({ teamIndex }) => teamIndex)),
].sort((a, b) => a - b);
const names = indexes.map((index) =>
teamIndexLabel(
index,
detail.match.teams.find((team) => team.teamIndex === index)?.name,
),
);
const id = series?.seriesId ?? `game:${game.gameNumber}`;
const matchup = names.join(' vs ') || `${game.gameNumber}세트`;
const label =
series && series.stage.type !== 'pair'
? `${bracketRoundAccessibleLabel(series.stage.type, series.stage.roundNumber)} · ${matchup}`
: matchup;
const group = groups.get(id) ?? { id, label, series, sets: [] };
group.sets.push({ game, official });
groups.set(id, group);
}
for (const group of groups.values()) {
group.sets.sort(
(left, right) =>
(left.official?.ordinal ?? left.game.gameNumber) -
(right.official?.ordinal ?? right.game.gameNumber),
);
}
return [...groups.values()];
}
@@ -0,0 +1,109 @@
import type { InternalMatchResultPresentation } from '@lolympus/contracts';
import type { ApiLeaderboardRow } from '../api/types';
import {
getSeriesHistoryResultLabel,
shouldDisplaySeriesHistoryScore,
} from '../components/competition/competition-series-history.ts';
export const LEADERBOARD_SORTS = [
{ value: 'games', label: '경기 수' },
{ value: 'winRate', label: '승률' },
{ value: 'kda', label: 'KDA' },
] as const;
export type LeaderboardSort = (typeof LEADERBOARD_SORTS)[number]['value'];
/** 이 판수에 못 미치는 선수는 승률·KDA 정렬에서 뒤로 보낸다. */
export const LEADERBOARD_MIN_GAMES = 5;
export function parseLeaderboardSort(value: string | null): LeaderboardSort {
return value === 'winRate' || value === 'kda' ? value : 'games';
}
/**
* 순위표 정렬. `games`는 서버가 준 순서를 그대로 쓴다. 승률·KDA는 표본이 적은
* 선수가 위로 올라오지 않도록 최소 판수를 채운 선수를 먼저 놓는다.
*/
export function sortLeaderboardRows<
T extends Pick<ApiLeaderboardRow, 'games' | 'winRate' | 'kda'>,
>(rows: readonly T[], sort: LeaderboardSort): T[] {
if (sort === 'games') return [...rows];
const qualifies = (row: T) => row.games >= LEADERBOARD_MIN_GAMES;
return [...rows].sort(
(a, b) =>
Number(qualifies(b)) - Number(qualifies(a)) ||
b[sort] - a[sort] ||
b.games - a.games,
);
}
/**
* 한 라인만의 순위표. 그 라인 기록이 있는 선수만 남기고 전적을 라인 전적으로
* 바꾼 뒤 승률 순으로 놓는다. 최소 판수도 그 라인 판수로 따진다.
*/
export function rankLeaderboardByLane<
T extends Pick<
ApiLeaderboardRow,
'games' | 'wins' | 'losses' | 'winRate' | 'kda' | 'byLane'
>,
>(rows: readonly T[], lane: keyof ApiLeaderboardRow['byLane']): T[] {
const laneRows = rows.flatMap((row) => {
const stats = row.byLane[lane];
if (!stats || stats.games <= 0) return [];
return [
{
...row,
games: stats.games,
wins: stats.wins,
losses: stats.games - stats.wins,
winRate: Math.round((stats.wins / stats.games) * 100),
kda: stats.kda,
},
];
});
return sortLeaderboardRows(laneRows, 'winRate');
}
/** 가장 많이 플레이한 라인. 기록이 없으면 undefined. */
export function getMainLane(byLane: ApiLeaderboardRow['byLane']) {
let main: { lane: string; games: number } | undefined;
for (const [lane, stats] of Object.entries(byLane)) {
if (stats && stats.games > 0 && (!main || stats.games > main.games)) {
main = { lane, games: stats.games };
}
}
return main?.lane;
}
export function formatOfficialMatchResult(
result: InternalMatchResultPresentation | undefined,
) {
if (result?.type !== 'official') {
return result?.type === 'legacy' ? '과거 기록' : '공식 결과 확인 불가';
}
const { phase, outcome, teams, singleSeries, completedSeriesCount } = result;
const teamName = (id: string) =>
teams.find(({ teamId }) => teamId === id)?.name ?? '팀 미확인';
if (phase === 'cancelled') return '취소';
if (phase !== 'completed' || !outcome) {
return completedSeriesCount > 0 ? `시리즈 ${completedSeriesCount}개 확정` : '결과 확정 전';
}
switch (outcome.type) {
case 'double-elimination':
return `우승 · ${teamName(outcome.championTeamId)}`;
case 'round-robin':
return outcome.leaderTeamIds.length > 0
? `${outcome.leaderTeamIds.length > 1 ? '공동 1위' : '우승'} · ${outcome.leaderTeamIds.map(teamName).join(', ')}`
: '대회 종료';
case 'paired-series': {
if (!singleSeries) return '시리즈 종료';
const series = singleSeries;
if (!shouldDisplaySeriesHistoryScore(series))
return getSeriesHistoryResultLabel(series) ?? '시리즈 종료';
const [left, right] = series.entries;
return `${teamName(left.teamId ?? '')} ${left.gameWins} : ${right.gameWins} ${teamName(right.teamId ?? '')}`;
}
}
}
+41 -16
View File
@@ -23,30 +23,55 @@ export const positionIcon: Record<Position, string> = {
SUP: supportIcon,
};
// 팀 식별색. 8팀 대회까지 서로 다른 색을 쓰고 그 이상은 순환한다.
const TEAM_TONES = [
{
border: 'border-blue-500/20',
bg: 'bg-blue-500/5',
text: 'text-blue-400',
bar: 'bg-blue-500',
border: "border-blue-500/30",
bg: "bg-blue-500/8",
text: "text-blue-600 dark:text-blue-300",
bar: "bg-blue-500",
},
{
border: 'border-red-500/20',
bg: 'bg-red-500/5',
text: 'text-red-400',
bar: 'bg-red-500',
border: "border-red-500/30",
bg: "bg-red-500/8",
text: "text-red-600 dark:text-red-300",
bar: "bg-red-500",
},
{
border: 'border-emerald-500/20',
bg: 'bg-emerald-500/5',
text: 'text-emerald-400',
bar: 'bg-emerald-500',
border: "border-emerald-500/30",
bg: "bg-emerald-500/8",
text: "text-emerald-600 dark:text-emerald-300",
bar: "bg-emerald-500",
},
{
border: 'border-amber-500/20',
bg: 'bg-amber-500/5',
text: 'text-amber-400',
bar: 'bg-amber-500',
border: "border-amber-500/30",
bg: "bg-amber-500/8",
text: "text-amber-700 dark:text-amber-300",
bar: "bg-amber-500",
},
{
border: "border-violet-500/30",
bg: "bg-violet-500/8",
text: "text-violet-600 dark:text-violet-300",
bar: "bg-violet-500",
},
{
border: "border-cyan-500/30",
bg: "bg-cyan-500/8",
text: "text-cyan-600 dark:text-cyan-300",
bar: "bg-cyan-500",
},
{
border: "border-pink-500/30",
bg: "bg-pink-500/8",
text: "text-pink-600 dark:text-pink-300",
bar: "bg-pink-500",
},
{
border: "border-lime-500/30",
bg: "bg-lime-500/8",
text: "text-lime-700 dark:text-lime-300",
bar: "bg-lime-500",
},
];
+6
View File
@@ -0,0 +1,6 @@
import type { MatchEventType } from '@lolympus/contracts';
export const MATCH_EVENT_LABEL: Record<MatchEventType, string> = {
inhouse: '내전',
tournament: '멸망전',
};
+24
View File
@@ -0,0 +1,24 @@
const MULTI_KILL_LABELS: Record<number, string> = {
2: '더블킬',
3: '트리플킬',
4: '쿼드라킬',
5: '펜타킬',
};
/** 한 경기의 최대 연속 처치 수를 배지 문구로 바꾼다. 2 미만이면 배지가 없다. */
export function multiKillLabel(largestMultiKill: number | undefined) {
if (!largestMultiKill || largestMultiKill < 2) return;
return MULTI_KILL_LABELS[Math.min(5, Math.floor(largestMultiKill))];
}
/** 요약의 포지션 비율을 높은 순으로 정리한다. */
export function rankPositionRates(
rates: Partial<Record<string, number>>,
limit = 2,
) {
return Object.entries(rates)
.filter((entry): entry is [string, number] => (entry[1] ?? 0) > 0)
.sort((a, b) => b[1] - a[1])
.slice(0, limit)
.map(([lane, rate]) => ({ lane, rate }));
}
+4 -1
View File
@@ -6,6 +6,7 @@ import './index.css';
import App from './App.tsx';
import { MsalAppProvider } from './lib/auth/MsalAppProvider.tsx';
import { initializeTheme } from './config.ts';
import { AppTheme } from './ui/AppTheme.tsx';
initializeNewRelicBrowserAgent();
initializeTheme();
@@ -24,7 +25,9 @@ createRoot(document.getElementById('root')!).render(
<StrictMode>
<MsalAppProvider>
<QueryClientProvider client={queryClient}>
<App />
<AppTheme>
<App />
</AppTheme>
</QueryClientProvider>
</MsalAppProvider>
</StrictMode>,
+97
View File
@@ -0,0 +1,97 @@
import { Button } from "@astryxdesign/core/Button";
import { Tab, TabList } from "@astryxdesign/core/TabList";
import { useId, type ButtonHTMLAttributes, type ReactNode } from "react";
export function AuctionAstryxTabs<T extends string>({
label,
value,
onChange,
tabs,
panelClassName,
children,
}: {
label: string;
value: T;
onChange: (value: T) => void;
tabs: readonly { value: T; label: string; count?: number }[];
panelClassName: string;
children: ReactNode;
}) {
const id = useId();
return (
<>
<TabList
className="auction-astryx-tabs"
role="tablist"
aria-label={label}
size="md"
hasDivider
value={value}
onChange={(next) => {
const tab = tabs.find((tab) => tab.value === next);
if (tab) onChange(tab.value);
}}
>
{tabs.map((tab) => (
<Tab
key={tab.value}
id={`${id}-${tab.value}-tab`}
panelId={`${id}-${tab.value}-panel`}
value={tab.value}
label={tab.label}
endContent={
tab.count === undefined ? undefined : (
<span className="auction-tab-count">{tab.count}</span>
)
}
/>
))}
</TabList>
{tabs.map((tab) => (
<div
key={tab.value}
role="tabpanel"
id={`${id}-${tab.value}-panel`}
aria-labelledby={`${id}-${tab.value}-tab`}
hidden={tab.value !== value}
tabIndex={0}
className={tab.value === value ? panelClassName : undefined}
>
{tab.value === value && children}
</div>
))}
</>
);
}
export function AuctionAction({
variant = "primary",
icon,
type = "button",
disabled,
onClick,
title,
children,
}: Pick<
ButtonHTMLAttributes<HTMLButtonElement>,
"type" | "className" | "disabled" | "onClick" | "title"
> & {
variant?: "primary" | "secondary" | "destructive";
icon?: ReactNode;
children: string;
}) {
return (
<Button
variant={variant}
size="md"
type={type}
isDisabled={disabled}
onClick={onClick}
tooltip={title}
icon={icon}
label={children}
width={type === "submit" ? "100%" : undefined}
/>
);
}
File diff suppressed because it is too large. Load diff
+4 -3
View File
@@ -1,5 +1,6 @@
import { useEffect } from 'react';
import { useNavigate } from 'react-router';
import { LoadingNote, PlainPage } from '../ui';
export default function AuthCallbackPage() {
const navigate = useNavigate();
@@ -10,8 +11,8 @@ export default function AuthCallbackPage() {
}, [navigate]);
return (
<main className="max-w-5xl mx-auto px-4 sm:px-6 py-20 text-center">
<span className="text-sm text-base-content/45">로그인 처리 중...</span>
</main>
<PlainPage>
<LoadingNote label="로그인 처리 중" />
</PlainPage>
);
}
Loaded 100 of 244 files, more files were not shown because too many files have changed in this diff. Show more