diff --git a/apps/api/README.md b/apps/api/README.md index 4256b95e..099517c5 100644 --- a/apps/api/README.md +++ b/apps/api/README.md @@ -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. diff --git a/apps/api/package.json b/apps/api/package.json index 38609455..6a2ee566 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -11,6 +11,7 @@ "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", diff --git a/apps/api/src/modules/auction/auction.controller.ts b/apps/api/src/modules/auction/auction.controller.ts index 0f7e55a2..b15a6c35 100644 --- a/apps/api/src/modules/auction/auction.controller.ts +++ b/apps/api/src/modules/auction/auction.controller.ts @@ -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, diff --git a/apps/api/src/modules/auction/auction.gateway.spec.ts b/apps/api/src/modules/auction/auction.gateway.spec.ts index 03b204b5..673cea6c 100644 --- a/apps/api/src/modules/auction/auction.gateway.spec.ts +++ b/apps/api/src/modules/auction/auction.gateway.spec.ts @@ -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> = []; @@ -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) { diff --git a/apps/api/src/modules/auction/auction.gateway.ts b/apps/api/src/modules/auction/auction.gateway.ts index df2527e9..7b5493ad 100644 --- a/apps/api/src/modules/auction/auction.gateway.ts +++ b/apps/api/src/modules/auction/auction.gateway.ts @@ -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 + >(); 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 { - 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({ diff --git a/apps/api/src/modules/auction/auction.service.ts b/apps/api/src/modules/auction/auction.service.ts index 103f992e..7e58b37a 100644 --- a/apps/api/src/modules/auction/auction.service.ts +++ b/apps/api/src/modules/auction/auction.service.ts @@ -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); } diff --git a/apps/api/src/modules/community-stats/community-stats-cache-retry.spec.ts b/apps/api/src/modules/community-stats/community-stats-cache-retry.spec.ts new file mode 100644 index 00000000..609c4c4b --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats-cache-retry.spec.ts @@ -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, [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((done, fail) => { + resolve = done; + reject = fail; + }); + return { promise, resolve, reject }; +} diff --git a/apps/api/src/modules/community-stats/community-stats-cache.service.ts b/apps/api/src/modules/community-stats/community-stats-cache.service.ts index b4421a81..b1514597 100644 --- a/apps/api/src/modules/community-stats/community-stats-cache.service.ts +++ b/apps/api/src/modules/community-stats/community-stats-cache.service.ts @@ -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(); + 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 { + 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 { + 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 { + 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(key: CommunityStatsCacheKey): Promise { 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 { + public async invalidateCommunity( + communityId: string, + timeoutMs?: number, + ): Promise { 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) { diff --git a/apps/api/src/modules/community-stats/community-stats-raw-recovery.spec.ts b/apps/api/src/modules/community-stats/community-stats-raw-recovery.spec.ts new file mode 100644 index 00000000..826ff28b --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats-raw-recovery.spec.ts @@ -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; + buildBaseDataset: () => Promise; + matchDetailInFlight: Map; + }; + 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; + buildBaseDataset: () => Promise; + }; + 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(value: T) { + return { + select() { + return this; + }, + lean() { + return this; + }, + exec: async () => value, + }; +} diff --git a/apps/api/src/modules/community-stats/community-stats.controller.ts b/apps/api/src/modules/community-stats/community-stats.controller.ts index 982f4f66..c7936637 100644 --- a/apps/api/src/modules/community-stats/community-stats.controller.ts +++ b/apps/api/src/modules/community-stats/community-stats.controller.ts @@ -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, }; } diff --git a/apps/api/src/modules/community-stats/community-stats.module.ts b/apps/api/src/modules/community-stats/community-stats.module.ts index 9b19a740..d2054705 100644 --- a/apps/api/src/modules/community-stats/community-stats.module.ts +++ b/apps/api/src/modules/community-stats/community-stats.module.ts @@ -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, diff --git a/apps/api/src/modules/community-stats/community-stats.service.spec.ts b/apps/api/src/modules/community-stats/community-stats.service.spec.ts index 940e7860..e1fc3f95 100644 --- a/apps/api/src/modules/community-stats/community-stats.service.spec.ts +++ b/apps/api/src/modules/community-stats/community-stats.service.spec.ts @@ -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; + }, + '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 }, + '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; 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; 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; 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, diff --git a/apps/api/src/modules/community-stats/community-stats.service.ts b/apps/api/src/modules/community-stats/community-stats.service.ts index e3709984..5bbd6313 100644 --- a/apps/api/src/modules/community-stats/community-stats.service.ts +++ b/apps/api/src/modules/community-stats/community-stats.service.ts @@ -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; + competition?: InternalMatchCompetition; +} + +interface CachedMatchPage extends Omit { + cards: Array<{ + card: InternalMatchCardView; + sourceCompetitionId?: string; + sourceRevision?: number; + }>; } @Injectable() @@ -71,6 +92,8 @@ export class CommunityStatsService { string, Promise >(); + private readonly fragmentRepairs = new Map>(); + private readonly rawRecoveryRetryAfter = new Map(); constructor( private readonly connectionService: ConnectionService, @@ -84,67 +107,141 @@ export class CommunityStatsService { filters: CommunityStatsFilters; }): Promise { const key = this.cacheKey('matches', params.communityId, params.filters); - const cached = await this.cacheService.get(key); - if (cached) return cached; + const cached = await this.cacheService.get(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 { 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 { - const key = this.cacheKey( - 'leaderboard', - params.communityId, - params.filters, - ); - const cached = await this.cacheService.get(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(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(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 { + 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(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 { + 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 { - 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 { + 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(); + 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 { + 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 { return this.cacheService.invalidateCommunity(communityId.toString()); } - private async buildBaseDataset( + private async buildSeasonDataset( communityId: mongoose.Types.ObjectId, filters: CommunityStatsFilters, - ): Promise { + ) { 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> = []; const records: InternalRecord[] = []; - const detailsByMatchId = new Map(); - 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 { + 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[], ): 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(); 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(); + 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 { diff --git a/apps/api/src/modules/community-stats/community-stats.types.ts b/apps/api/src/modules/community-stats/community-stats.types.ts index 928a7471..d86fafc2 100644 --- a/apps/api/src/modules/community-stats/community-stats.types.ts +++ b/apps/api/src/modules/community-stats/community-stats.types.ts @@ -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; diff --git a/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts b/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts index e9ab7223..4f16f457 100644 --- a/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts +++ b/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts @@ -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, diff --git a/apps/api/src/modules/community-stats/match-stats.repository.ts b/apps/api/src/modules/community-stats/match-stats.repository.ts index 0c5fd3ea..e42c517a 100644 --- a/apps/api/src/modules/community-stats/match-stats.repository.ts +++ b/apps/api/src/modules/community-stats/match-stats.repository.ts @@ -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 = { communityId: params.communityId }; + const conditions: Array> = []; + 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() .exec(); } diff --git a/apps/api/src/modules/community-stats/match-stats.service.ts b/apps/api/src/modules/community-stats/match-stats.service.ts index e099c294..a2eced11 100644 --- a/apps/api/src/modules/community-stats/match-stats.service.ts +++ b/apps/api/src/modules/community-stats/match-stats.service.ts @@ -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, diff --git a/apps/api/src/modules/community-stats/match-stats.types.ts b/apps/api/src/modules/community-stats/match-stats.types.ts index a864c124..c22d504a 100644 --- a/apps/api/src/modules/community-stats/match-stats.types.ts +++ b/apps/api/src/modules/community-stats/match-stats.types.ts @@ -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; diff --git a/apps/api/src/modules/global/database/match-stats-raw-index.ts b/apps/api/src/modules/global/database/match-stats-raw-index.ts new file mode 100644 index 00000000..a3a0b06c --- /dev/null +++ b/apps/api/src/modules/global/database/match-stats-raw-index.ts @@ -0,0 +1,4 @@ +export const MATCH_STATS_RIOT_MATCH_INDEX = { + key: { 'gameDetails.riotMatchId': 1 as const }, + options: { name: 'gameDetails.riotMatchId_1' }, +}; diff --git a/apps/api/src/modules/global/database/migrations/20261111-match-stats-raw-index.spec.ts b/apps/api/src/modules/global/database/migrations/20261111-match-stats-raw-index.spec.ts new file mode 100644 index 00000000..42c04fd7 --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/20261111-match-stats-raw-index.spec.ts @@ -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; +} diff --git a/apps/api/src/modules/global/database/migrations/20261111-match-stats-raw-index.ts b/apps/api/src/modules/global/database/migrations/20261111-match-stats-raw-index.ts new file mode 100644 index 00000000..f8bb70fe --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/20261111-match-stats-raw-index.ts @@ -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 }, + }; +} diff --git a/apps/api/src/modules/global/database/migrations/run-match-stats-raw-index.ts b/apps/api/src/modules/global/database/migrations/run-match-stats-raw-index.ts new file mode 100644 index 00000000..e05eac4c --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/run-match-stats-raw-index.ts @@ -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 { + 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; + }); +} diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index c30b51c6..58fee7a5 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -14,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']; @@ -1019,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; @@ -1051,6 +1060,7 @@ export interface MatchStatsGameDetail { gameCreation: number; gameDuration: number; gameVersion?: string; + rawAvailable?: boolean; winnerSide: TeamSide; timeline: MatchStatsTimelinePoint[]; timelineLoaded?: boolean; @@ -2535,7 +2545,7 @@ export const MatchStatsSchema: mongoose.Schema = new Schema( { timestamps: true, collection: 'match_stats' }, ) as mongoose.Schema; -MatchStatsSchema.index({ communityId: 1, scheduledAt: -1 }); +MatchStatsSchema.index({ communityId: 1, scheduledAt: -1, matchId: -1 }); MatchStatsSchema.index({ communityId: 1, gameCreationMin: 1, @@ -2544,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 } diff --git a/apps/api/src/modules/legacy-import/legacy-import-result-cutover.spec.ts b/apps/api/src/modules/legacy-import/legacy-import-result-cutover.spec.ts index c15bbdd6..2c4c7336 100644 --- a/apps/api/src/modules/legacy-import/legacy-import-result-cutover.spec.ts +++ b/apps/api/src/modules/legacy-import/legacy-import-result-cutover.spec.ts @@ -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; 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; const service = createService({ connectionService, communityStatsService }); diff --git a/apps/api/src/modules/legacy-import/legacy-import.service.spec.ts b/apps/api/src/modules/legacy-import/legacy-import.service.spec.ts index 231d6cb9..a27e07dd 100644 --- a/apps/api/src/modules/legacy-import/legacy-import.service.spec.ts +++ b/apps/api/src/modules/legacy-import/legacy-import.service.spec.ts @@ -59,6 +59,7 @@ describe('LegacyImportService member job completion', () => { releaseLockIfOwned: jest.fn().mockResolvedValue(true), } as unknown as jest.Mocked; const communityStatsService = { + refreshForRiotMatches: jest.fn().mockResolvedValue(undefined), invalidateCommunity: jest.fn().mockResolvedValue(undefined), } as unknown as jest.Mocked; const service = new LegacyImportService( diff --git a/apps/api/src/modules/legacy-import/legacy-import.service.ts b/apps/api/src/modules/legacy-import/legacy-import.service.ts index 5b320bed..198c2026 100644 --- a/apps/api/src/modules/legacy-import/legacy-import.service.ts +++ b/apps/api/src/modules/legacy-import/legacy-import.service.ts @@ -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 = { @@ -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; } diff --git a/apps/api/src/modules/match-history/match-history.query.spec.ts b/apps/api/src/modules/match-history/match-history.query.spec.ts index d786d7d2..f5e35b0b 100644 --- a/apps/api/src/modules/match-history/match-history.query.spec.ts +++ b/apps/api/src/modules/match-history/match-history.query.spec.ts @@ -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, diff --git a/apps/api/src/modules/match-history/match-history.service.ts b/apps/api/src/modules/match-history/match-history.service.ts index b1d6c518..a4eb0cd4 100644 --- a/apps/api/src/modules/match-history/match-history.service.ts +++ b/apps/api/src/modules/match-history/match-history.service.ts @@ -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( diff --git a/apps/api/src/modules/match-history/match-history.types.ts b/apps/api/src/modules/match-history/match-history.types.ts index 29d7393d..a0e4aae1 100644 --- a/apps/api/src/modules/match-history/match-history.types.ts +++ b/apps/api/src/modules/match-history/match-history.types.ts @@ -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; diff --git a/apps/api/src/modules/match/match.controller.ts b/apps/api/src/modules/match/match.controller.ts index 2f5ddbef..bee6e213 100644 --- a/apps/api/src/modules/match/match.controller.ts +++ b/apps/api/src/modules/match/match.controller.ts @@ -1,7 +1,9 @@ import type { + HallOfFameResponse, MatchDetailResponse, MatchEventType, MatchListResponse, + MatchListView, } from '@lolympus/contracts'; import { BadRequestException, @@ -17,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'; @@ -89,10 +92,38 @@ export class MatchController { @Query('sort') sort?: 'asc' | 'desc', @Query('includeResults') includeResults?: string, @Query('eventType') eventType?: MatchEventType, + @Query('view') view?: MatchListView, + @Query('asOf') asOf?: string, ): Promise { 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, @@ -103,11 +134,15 @@ export class MatchController { 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) => { @@ -121,11 +156,26 @@ export class MatchController { : {}), }); const historyResult = historyResults?.get(summary._id); - return historyResult ? { ...summary, historyResult } : summary; + 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 { + return this.matchService.getHallOfFame(communityId); + } + @Get(':matchId') @AllowPublicAccess() public async getMatch( @@ -135,7 +185,7 @@ export class MatchController { @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, ): Promise { 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) => @@ -143,6 +193,8 @@ export class MatchController { ), ), }); + const progress = await this.matchService.getEventProgress([match]); + return { ...summary, eventProgress: progress.get(summary._id) }; } @Patch(':matchId') @@ -258,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 { + 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) diff --git a/apps/api/src/modules/match/match.service.spec.ts b/apps/api/src/modules/match/match.service.spec.ts index 1278cbc0..4e379a3e 100644 --- a/apps/api/src/modules/match/match.service.spec.ts +++ b/apps/api/src/modules/match/match.service.spec.ts @@ -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[] = []; 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,7 +375,7 @@ describe('MatchService', () => { communityId, scheduledAt: { $lt: scheduledTo }, }); - expect(sort).toHaveBeenCalledWith({ scheduledAt: -1 }); + expect(sort).toHaveBeenCalledWith({ scheduledAt: -1, _id: -1 }); }); it.each([ diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts index 70e42ccf..24801260 100644 --- a/apps/api/src/modules/match/match.service.ts +++ b/apps/api/src/modules/match/match.service.ts @@ -1,4 +1,12 @@ -import type { MatchEventType, MatchHistoryResult } from '@lolympus/contracts'; +import type { + HallOfFameResponse, + MatchEventStage, + MatchEventType, + MatchHistoryResult, + MatchId, + MatchListView, + UserId, +} from '@lolympus/contracts'; import { BadRequestException, ConflictException, @@ -9,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, @@ -62,6 +71,8 @@ interface ListMatchesQuery { scheduledFrom?: Date; scheduledTo?: Date; sort?: 'asc' | 'desc'; + view?: MatchListView; + asOf?: Date; } interface ListMatchesPageQuery extends ListMatchesQuery { @@ -77,6 +88,10 @@ interface MatchListFilter { $gte?: Date; $lt?: Date; }; + $or?: Array<{ + status: MatchStatus | { $in: MatchStatus[] }; + scheduledAt?: { $lt: Date }; + }>; } interface JoinMatchParams { @@ -219,6 +234,203 @@ export class MatchService { return results; } + public async getHallOfFame( + communityId: mongoose.Types.ObjectId, + ): Promise { + 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 & { + _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(); + 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 { if (match.shortCode) return match; @@ -714,10 +926,26 @@ 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; + query.eventType === 'inhouse' + ? { $in: ['inhouse', null] } + : query.eventType; } if (query.scheduledFrom || query.scheduledTo) { filter.scheduledAt = {}; @@ -727,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 { diff --git a/apps/api/src/modules/riot/riot-archive-recovery.spec.ts b/apps/api/src/modules/riot/riot-archive-recovery.spec.ts new file mode 100644 index 00000000..4ca2ea13 --- /dev/null +++ b/apps/api/src/modules/riot/riot-archive-recovery.spec.ts @@ -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([ + 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; + }; + 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([ + ['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, + ) => 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, + ) => operation(), + } as never, + {} as never, + {} as never, + ); + const importer = service as unknown as { + importSingleMatch: ( + id: string, + job: unknown, + users: unknown, + ) => Promise; + }; + expect(await importer.importSingleMatch('KR_1', {}, {})).toBe('duplicate'); + expect(refreshForRiotMatches).not.toHaveBeenCalled(); + }); +}); + +function query(value: T) { + return { + select() { + return this; + }, + lean() { + return this; + }, + sort() { + return this; + }, + limit() { + return this; + }, + exec: async () => value, + }; +} diff --git a/apps/api/src/modules/riot/riot-multi-kill.ts b/apps/api/src/modules/riot/riot-multi-kill.ts new file mode 100644 index 00000000..608e298d --- /dev/null +++ b/apps/api/src/modules/riot/riot-multi-kill.ts @@ -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, + }; +} diff --git a/apps/api/src/modules/riot/riot-recent-matches.service.ts b/apps/api/src/modules/riot/riot-recent-matches.service.ts index b3e6f76b..ea2176ae 100644 --- a/apps/api/src/modules/riot/riot-recent-matches.service.ts +++ b/apps/api/src/modules/riot/riot-recent-matches.service.ts @@ -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(); 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: { diff --git a/apps/api/src/modules/riot/riot.module.ts b/apps/api/src/modules/riot/riot.module.ts index 0989de8d..de57d8e8 100644 --- a/apps/api/src/modules/riot/riot.module.ts +++ b/apps/api/src/modules/riot/riot.module.ts @@ -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, diff --git a/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts b/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts index 7cbf9e4a..27f5fd10 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts @@ -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(), diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts index 2521588a..9029a44f 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts @@ -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, diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.ts b/apps/api/src/modules/tournament-result/tournament-result.service.ts index c900b987..336af3bc 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.ts @@ -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 = { @@ -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; } diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 8220085f..c11dbd10 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -8,7 +8,7 @@ import { useLocation, useNavigate, } from "react-router"; -import { lazy, Suspense, useState, type FormEvent, type ReactNode } from "react"; +import { useState, type FormEvent, type ReactNode } from "react"; import { useMsal } from "@azure/msal-react"; import { LogOut, Moon, Search, Sun } from "lucide-react"; import DevAuthSwitcher from "./components/DevAuthSwitcher"; @@ -31,12 +31,6 @@ import MatchAdminPage from "./pages/admin/MatchAdminPage"; import TournamentCodesPage from "./pages/admin/TournamentCodesPage"; import { PlainPage, Tooltip, pageWidthClass } from "./ui"; -const InternalStatsPreview = import.meta.env.DEV - ? lazy(() => import("./preview/InternalStatsPreview")) - : null; -const MatchFlowsPreview = import.meta.env.DEV - ? lazy(() => import("./preview/MatchFlowsPreview")) - : null; 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"; @@ -367,26 +361,6 @@ function App() { path="/communities/:cid/internal-stats" element={} /> - {InternalStatsPreview && ( - 전적 목업을 불러오는 중}> - - - } - /> - )} - {MatchFlowsPreview && ( - 내전 목업을 불러오는 중}> - - - } - /> - )} } diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts index 5ffab52b..4f62ef61 100644 --- a/apps/web/src/api/hooks.ts +++ b/apps/web/src/api/hooks.ts @@ -5,9 +5,11 @@ import type { CompetitionCommandResponse, CompetitionDetailResponse, CreateSeriesAdjudicationRequest, + HallOfFameResponse, MatchDetailResponse, MatchEventType, MatchLifecycleStatus, + MatchListView, MatchListResponse, ReverseSeriesResultRequest, SeriesId, @@ -33,6 +35,7 @@ import type { ApiCommunity, ApiCommunityUserSearchCandidate, ApiEnqueueRefreshResult, + ApiHistorySeason, ApiInternalMatchDetailResponse, ApiInternalMatchListResponse, ApiLeaderboardResponse, @@ -72,6 +75,8 @@ interface MatchesQueryOptions { scheduledFrom?: string; scheduledTo?: string; sort?: 'asc' | 'desc'; + view?: MatchListView; + asOf?: string; } interface MatchesPageQueryOptions extends MatchesQueryOptions { @@ -91,6 +96,9 @@ export interface CommunityInternalStatsFilters { to?: string; championId?: number; limit?: number; + query?: string; + format?: 'pair' | 'tournament'; + playerId?: string; } function createMatchesPath( @@ -108,6 +116,8 @@ function createMatchesPath( 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}` : ''}`; @@ -161,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( + `/communities/${communityId}/matches/hall-of-fame`, + { auth: 'none' }, + ), + enabled: Boolean(communityId), + }); +} + export function useMatches( options: MatchesQueryOptions, communityId = DEFAULT_COMMUNITY_ID, @@ -180,6 +201,8 @@ export function useMatches( options.scheduledTo ?? null, options.sort ?? null, options.eventType ?? null, + options.view ?? null, + options.asOf ?? null, ], queryFn: async () => { const response = await authScope.fetch( @@ -211,6 +234,8 @@ export function useMatchesPage( options.sort ?? null, options.includeResults ?? false, options.eventType ?? null, + options.view ?? null, + options.asOf ?? null, ], queryFn: () => authScope.fetch( @@ -676,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)); @@ -700,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( 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), }); } @@ -727,6 +761,7 @@ export function useCommunityLeaderboard( filters.from ?? null, filters.to ?? null, filters.championId ?? null, + filters.query ?? null, ], queryFn: () => apiFetch( @@ -739,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, diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index 932892e5..c454e7f6 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -1,6 +1,13 @@ import type { GrandFinalGameCount, + GameAnalysisAvailability, + GameId, + GameSlotId, + InternalMatchCompetition, + InternalMatchResultPresentation, + SeriesId, MatchEventType, + RecentMatchParticipantRank, MatchGameMode, MatchPosition, MatchPositionPreferenceView, @@ -530,6 +537,7 @@ export interface ApiRecentMatchTeamParticipant { championId: number; championLevel: number; teamPosition: string; + tier?: RecentMatchParticipantRank; kills: number; deaths: number; assists: number; @@ -588,7 +596,7 @@ export interface ApiRecentMatchView { summonerSpells: [number, number]; perks: ApiRunePerks; teams: ApiRecentMatchTeam[]; - /** 최대 연속 처치 수. API가 아직 내려주지 않아 화면은 없을 때를 견딘다. */ + /** 경기에서 기록한 최대 연속 처치 수. */ largestMultiKill?: number; } @@ -606,6 +614,7 @@ export interface ApiInternalMatchCard { status: 'finished' | 'in-progress'; gameCount: number; winnerTeamIndex?: number; + resultPresentation?: InternalMatchResultPresentation; seriesResults: Array<{ teamAIndex: number; teamBIndex: number; @@ -636,6 +645,7 @@ export interface ApiInternalMatchCard { export interface ApiInternalMatchListResponse { matches: ApiInternalMatchCard[]; nextCursor: number | null; + nextCursorMatchId?: string; season: ApiHistorySeason; } @@ -663,6 +673,7 @@ export interface ApiLeaderboardRow { export interface ApiLeaderboardResponse { rows: ApiLeaderboardRow[]; season: ApiHistorySeason; + matchedUserIds?: string[]; } export interface ApiLeaderHighlight { @@ -681,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; @@ -692,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; diff --git a/apps/web/src/api/useAuctionSocket.ts b/apps/web/src/api/useAuctionSocket.ts index ceb54a3d..5ac676a5 100644 --- a/apps/web/src/api/useAuctionSocket.ts +++ b/apps/web/src/api/useAuctionSocket.ts @@ -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(null); const resyncRequesterRef = useRef + ); +} + +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 ( +
+ {game.analysisAvailability && game.analysisAvailability !== "available" && ( + + )} + {game.teams.map((team) => ( +
+

+ {teamIndexLabel(team.teamIndex, teams.find(({ teamIndex }) => teamIndex === team.teamIndex)?.name)} + {" · "}{team.side === "blue" ? "블루" : "레드"}{" · "}{team.win ? "승리" : "패배"} +

+ {team.participants.length > 0 ? ( + + + + + + + + + + {team.participants.map((participant) => { + const icon = championIconUrl(manifest, participant.championId); + const champion = championDisplayName(manifest, participant.championId); + return ( + + + + + + ); + })} + +
선수챔피언K/D/A
+ {participant.userId ? ( + + {participant.summonerName} + + ) : participant.summonerName} + + + {icon && } + {champion ?? "챔피언 미확인"} + + + {participant.kills}/{participant.deaths}/{participant.assists} +
+ ) : ( +

저장된 선수 기록이 없습니다.

+ )} +
+ ))} +
+ ); +} diff --git a/apps/web/src/components/HomeHallOfFame.tsx b/apps/web/src/components/HomeHallOfFame.tsx index 45a8a2f0..ae69b670 100644 --- a/apps/web/src/components/HomeHallOfFame.tsx +++ b/apps/web/src/components/HomeHallOfFame.tsx @@ -1,8 +1,8 @@ -import type { MatchPosition } from '@lolympus/contracts'; +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 } from '../api/hooks'; +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'; @@ -10,61 +10,14 @@ import { positionLabel } from '../lib/league'; import { pageWidthClass } from '../ui/layout'; import './HomeHallOfFame.css'; -// The roster featured on the home page is curated independently of match results. -const FEATURED_TEAM = { - name: '똥칼라파워', - captainUserId: '69f090029bf765ff8e54faae', - members: [ - { - userId: '6a36268cf3a6fd12921ca016', - position: 'TOP', - gameName: 'ALLM', - tagLine: 'ALL', - profileIconId: 6091, - }, - { - userId: '69f090029bf765ff8e54faae', - position: 'JGL', - gameName: 'OPIS', - tagLine: '2283', - profileIconId: 7146, - }, - { - userId: '69f090039bf765ff8e54facf', - position: 'MID', - gameName: '우 킨', - tagLine: '안우킨', - profileIconId: 6622, - }, - { - userId: '6a37c488f3a6fd12921cf2b4', - position: 'ADC', - gameName: '말 안해도 알잖아', - tagLine: 'Ф x Ф', - profileIconId: 6379, - }, - { - userId: '69f090069bf765ff8e54fb5a', - position: 'SUP', - gameName: '툭치면 크르릉', - tagLine: 'KR1', - profileIconId: 4020, - }, - ] satisfies Array<{ - userId: string; - position: MatchPosition; - gameName: string; - tagLine: string; - profileIconId: number; - }>, -}; +const POSITION_ORDER: MatchPosition[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP']; export default function HomeHallOfFame({ introReady, }: { introReady: boolean; }) { - const { data: manifest } = useDdragonManifest(); + const hallOfFame = useHallOfFame(); const sectionRef = useRef(null); const [playIntro, setPlayIntro] = useState(false); @@ -89,95 +42,131 @@ export default function HomeHallOfFame({ 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.
-
-

- - 명예의 전당 - - - {FEATURED_TEAM.name} - - - - 직전 멸망전 우승 - -

- + {hallOfFame.isPending ? ( +

명예의 전당을 불러오는 중

+ ) : hallOfFame.isError ? ( +

+ 명예의 전당을 불러오지 못했습니다.{' '} + +

+ ) : featuredMatch && hallOfFame.data.teams.length > 0 ? ( +
+ {hallOfFame.data.teams.map((team, index) => ( + + ))} +
+ ) : ( +

확정된 멸망전 우승팀이 없습니다.

+ )}
); } + +function FeaturedTeam({ + team, + match, +}: { + team: HallOfFameResponse['teams'][number]; + match: NonNullable; +}) { + 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 ( +
+

+ + 명예의 전당 + + + {team.name} + + + + 직전 멸망전 우승 + +

+ + ); +} diff --git a/apps/web/src/components/InternalGameAnalysisTabs.tsx b/apps/web/src/components/InternalGameAnalysisTabs.tsx index bd8f5a33..e75d68f0 100644 --- a/apps/web/src/components/InternalGameAnalysisTabs.tsx +++ b/apps/web/src/components/InternalGameAnalysisTabs.tsx @@ -15,6 +15,7 @@ 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"; @@ -992,6 +993,9 @@ export function InternalGameAnalysisPanel({ if (activeTab === "scoreboard") { return <>{scoreboard}; } + if (selectedGame.analysisAvailability && selectedGame.analysisAvailability !== "available") { + return ; + } if (activeTab === "build") { return ( diff --git a/apps/web/src/components/competition/CompetitionAdminControls.tsx b/apps/web/src/components/competition/CompetitionAdminControls.tsx index 7d3910da..73594d91 100644 --- a/apps/web/src/components/competition/CompetitionAdminControls.tsx +++ b/apps/web/src/components/competition/CompetitionAdminControls.tsx @@ -133,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], + }), ]); } diff --git a/apps/web/src/components/competition/TeamTournamentCodes.tsx b/apps/web/src/components/competition/TeamTournamentCodes.tsx index 7a720640..52490673 100644 --- a/apps/web/src/components/competition/TeamTournamentCodes.tsx +++ b/apps/web/src/components/competition/TeamTournamentCodes.tsx @@ -55,7 +55,7 @@ export function TeamTournamentCodes({ return (

- 이 경기에 배정된 토너먼트 코드가 없습니다. + 표시할 세트 정보가 아직 없습니다.

); diff --git a/apps/web/src/components/rankBadgeUtils.ts b/apps/web/src/components/rankBadgeUtils.ts index 7467afed..c284ce8b 100644 --- a/apps/web/src/components/rankBadgeUtils.ts +++ b/apps/web/src/components/rankBadgeUtils.ts @@ -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 & Partial> | 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`; } diff --git a/apps/web/src/config.ts b/apps/web/src/config.ts index bad4ac61..e932cda5 100644 --- a/apps/web/src/config.ts +++ b/apps/web/src/config.ts @@ -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( - (callback) => subscribeToWindowChanges(CAPTAIN_SIDE_CHANGED_EVENT, callback), - getDevCaptainTeamIndex, - () => null, - ); -} - export function useTheme(): AppTheme { return useSyncExternalStore( (callback) => subscribeToWindowChanges(THEME_CHANGED_EVENT, callback), diff --git a/apps/web/src/lib/internal-game-evidence.ts b/apps/web/src/lib/internal-game-evidence.ts new file mode 100644 index 00000000..6e0defc4 --- /dev/null +++ b/apps/web/src/lib/internal-game-evidence.ts @@ -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; +} diff --git a/apps/web/src/lib/internal-match-series.ts b/apps/web/src/lib/internal-match-series.ts index 8a2bafaf..03202f6e 100644 --- a/apps/web/src/lib/internal-match-series.ts +++ b/apps/web/src/lib/internal-match-series.ts @@ -1,8 +1,4 @@ -import type { - CompetitionDetailResponse, - CompetitionGameView, - SeriesProjection, -} from '@lolympus/contracts'; +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'; @@ -23,22 +19,17 @@ export interface RecordedSeries { export function groupRecordedSets( detail: ApiInternalMatchDetailResponse, - competition?: CompetitionDetailResponse, ) { - const projection = competition?.projection; - const officialByMatchId = new Map(); - for (const game of projection?.games ?? []) { - if (game.evidence.type === 'riot') - officialByMatchId.set(game.evidence.riotMatchId, game); - } + 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(); for (const game of detail.games) { - const official = officialByMatchId.get(game.riotMatchId); - const series = official && seriesById.get(official.seriesId); + 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); @@ -48,11 +39,7 @@ export function groupRecordedSets( detail.match.teams.find((team) => team.teamIndex === index)?.name, ), ); - const id = - series?.seriesId ?? - (indexes.length === 2 - ? `teams:${indexes.join('-')}` - : `game:${game.gameNumber}`); + const id = series?.seriesId ?? `game:${game.gameNumber}`; const matchup = names.join(' vs ') || `${game.gameNumber}세트`; const label = series && series.stage.type !== 'pair' diff --git a/apps/web/src/lib/internal-stats-presentation.ts b/apps/web/src/lib/internal-stats-presentation.ts index fac5315a..dc61d99f 100644 --- a/apps/web/src/lib/internal-stats-presentation.ts +++ b/apps/web/src/lib/internal-stats-presentation.ts @@ -1,4 +1,9 @@ -import type { ApiInternalMatchCard, ApiLeaderboardRow } from '../api/types'; +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: '경기 수' }, @@ -71,46 +76,34 @@ export function getMainLane(byLane: ApiLeaderboardRow['byLane']) { return main?.lane; } -type MatchOutcomeSource = Pick< - ApiInternalMatchCard, - 'winnerTeamIndex' | 'seriesResults' | 'teams' ->; -type MatchTeam = ApiInternalMatchCard['teams'][number]; - -export type InternalMatchOutcome = - | { - type: 'score'; - left: MatchTeam; - right: MatchTeam; - leftWins: number; - rightWins: number; - winner?: MatchTeam; - } - | { type: 'winner'; winner: MatchTeam }; - -/** 목록 행에서 바로 보여줄 결과. 두 팀 단일 시리즈는 스코어, 그 외는 우승팀. */ -export function getInternalMatchOutcome( - match: MatchOutcomeSource, -): InternalMatchOutcome | undefined { - const team = (index: number | undefined) => - match.teams.find(({ teamIndex }) => teamIndex === index); - const winner = team(match.winnerTeamIndex); - - if (match.teams.length === 2 && match.seriesResults.length === 1) { - const [series] = match.seriesResults; - const left = team(series.teamAIndex); - const right = team(series.teamBIndex); - if (left && right) { - return { - type: 'score', - left, - right, - leftWins: series.teamAWins, - rightWins: series.teamBWins, - winner: winner ?? team(series.winnerTeamIndex), - }; - } +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}개 확정` : '결과 확정 전'; } - return winner ? { type: 'winner', winner } : undefined; + 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 ?? '')}`; + } + } } diff --git a/apps/web/src/lib/multi-kill.ts b/apps/web/src/lib/multi-kill.ts index b152def3..c4ed4019 100644 --- a/apps/web/src/lib/multi-kill.ts +++ b/apps/web/src/lib/multi-kill.ts @@ -11,18 +11,6 @@ export function multiKillLabel(largestMultiKill: number | undefined) { return MULTI_KILL_LABELS[Math.min(5, Math.floor(largestMultiKill))]; } -/** - * 개발 화면 전용 목업. 최근 경기 응답에 `largestMultiKill`이 아직 없어서, 배지 - * 디자인을 확인할 수 있도록 킬 수로 값을 지어낸다. 실제 기록이 아니므로 - * 운영 빌드에서는 호출하지 않는다. - */ -export function mockLargestMultiKill(kills: number) { - if (kills >= 15) return 4; - if (kills >= 11) return 3; - if (kills >= 7) return 2; - return 0; -} - /** 요약의 포지션 비율을 높은 순으로 정리한다. */ export function rankPositionRates( rates: Partial>, diff --git a/apps/web/src/pages/AuctionPage.tsx b/apps/web/src/pages/AuctionPage.tsx index ed4570e0..f33d8b1a 100644 --- a/apps/web/src/pages/AuctionPage.tsx +++ b/apps/web/src/pages/AuctionPage.tsx @@ -35,11 +35,7 @@ import { useAuctionSocket, type BidLatencyDiagnostics, } from "../api/useAuctionSocket"; -import { - DEFAULT_COMMUNITY_ID, - setDevCaptainTeamIndex, - useDevCaptainTeamIndex, -} from "../config"; +import { DEFAULT_COMMUNITY_ID } from "../config"; import { ApiError } from "../lib/api"; import { mergeAuctionState } from "../api/auction-state"; import { @@ -1929,7 +1925,6 @@ export default function AuctionPage() { const undoMutation = useUndoAuction(DEFAULT_COMMUNITY_ID); const resetAuctionMutation = useResetAuction(DEFAULT_COMMUNITY_ID); const socket = useAuctionSocket(id); - const captainTeamIndex = useDevCaptainTeamIndex(); const [assignedPositionDraft, setAssignedPositionDraft] = useState<{ playerId: string | null; position: Position; @@ -1995,29 +1990,12 @@ export default function AuctionPage() { const setAssignedPosition = (position: Position) => { setAssignedPositionDraft({ playerId: currentPlayerId, position }); }; - const availableTeamIndexes = useMemo(() => { - const indexes = new Set( - (auctionState?.teams ?? []).map((team) => team.teamIndex), - ); - return [...indexes].sort((left, right) => left - right); - }, [auctionState?.teams]); - const captainRole: CaptainRole | null = - captainTeamIndex === null - ? null - : { - teamIndex: captainTeamIndex, - }; + const captainTeam = currentUser && auctionState?.teams.find( + (team) => team.captainUserId === currentUser._id, + ); + const captainRole: CaptainRole | null = captainTeam ? { teamIndex: captainTeam.teamIndex } : null; const chatSenderLabel = resolveChatSenderLabel(currentUser, captainRole); - useEffect(() => { - if (availableTeamIndexes.length === 0) return; - if ( - captainTeamIndex !== null && - !availableTeamIndexes.includes(captainTeamIndex) - ) { - setDevCaptainTeamIndex(availableTeamIndexes[0]); - } - }, [availableTeamIndexes, captainTeamIndex]); useEffect(() => { if (!socket.resetAt || !id) return; @@ -2299,28 +2277,9 @@ export default function AuctionPage() { } actions={ -
- {/* 임시 운영용: 로그인/권한 확인 없이 조작자 역할을 선택할 수 있게 열어둔다. */} - -
+ + {captainTeam ? teamIndexLabel(captainTeam.teamIndex, captainTeam.name) + " 팀장" : "관전자"} + } />
- teams.find(({ teamId }) => teamId === id)?.name ?? '팀 미확인'; - const outcome = projection.outcome; - if (projection.phase === 'cancelled') return '취소'; - if (projection.phase !== 'completed' || !outcome) return '결과 확정 전'; - - 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 (projection.series.length !== 1) return '시리즈 종료'; - const series = projection.series[0]; - if (!shouldDisplaySeriesHistoryScore(series)) - return getSeriesHistoryResultLabel(series) ?? '시리즈 종료'; - const [left, right] = series.entries; - return `${teamName(left.teamId ?? '')} ${left.gameWins} : ${right.gameWins} ${teamName(right.teamId ?? '')}`; - } - } -} - -/** 팀원 프로필을 겹쳐 보여주는 작은 묶음. */ -function MemberStack({ - members, - manifest, -}: { - members: ApiInternalMatchCard['teams'][number]['members']; - manifest: Manifest; -}) { - if (members.length === 0) return null; - return ( - - ); -} - -/** 펼치지 않아도 보이는 결과 요약. 목록 응답에 담긴 값만 쓴다. */ -function MatchOutcomeSummary({ - match, - recordedGameCount, - manifest, -}: { - match: ApiInternalMatchCard; - recordedGameCount: number; - manifest: Manifest; -}) { - const outcome = getInternalMatchOutcome(match); - if (!outcome) { - return ( - - {match.status === 'in-progress' && ( - - 진행 중 - - )} - {recordedGameCount}세트 수집 - - ); - } - - if (outcome.type === 'score') { - const { left, right, leftWins, rightWins, winner } = outcome; - const nameClass = (team: typeof left) => - `min-w-0 truncate ${winner?.teamIndex === team.teamIndex ? 'font-bold text-content' : ''}`; - return ( - - {left.name} - - {leftWins} : {rightWins} - - {right.name} - - ); - } - - return ( - - 우승 - - {outcome.winner.name} - - - - ); -} - function MatchCard({ match, communityId, - manifest, }: { match: ApiInternalMatchCard; communityId: string; - manifest: Manifest; }) { - const [open, setOpen] = useState(false); - const competition = useCompetition(match.matchId, communityId, open); + const result = match.resultPresentation; const location = useLocation(); const backTo = `${location.pathname}${location.search}`; const recordedGames = match.games.filter( @@ -224,10 +110,7 @@ function MatchCard({ return (
  • -
    setOpen(event.currentTarget.open)} - > +
    @@ -243,76 +126,62 @@ function MatchCard({ - {competition.data ? ( - - - - ) : ( - - )} + + {formatOfficialMatchResult(result)} + - {open && ( -
    -
    -

    - {competition.isLoading - ? '공식 결과를 확인하는 중' - : competition.data - ? '수집된 세트 기록' - : '공식 시리즈 정보를 확인할 수 없습니다'} -

    - - 내전 기록 전체 보기 → - -
    - {recordedGames.length > 0 && ( -
      - {recordedGames.map((game) => { - const winner = match.teams.find( - ({ teamIndex }) => teamIndex === game.winnerTeamIndex, - ); - return ( -
    • - - 전체 {game.gameNumber}세트 ·{' '} - {winner ? `${winner.name} 승` : '팀 미확인'} - - {game.riotMatchId && ( - - 상세 분석 - - )} -
    • - ); - })} -
    - )} +
    +
    +

    + {recordedGames.length > 0 ? '수집된 세트 기록' : '수집된 세트 기록 없음'} +

    + + 내전 기록 전체 보기 → +
    - )} + {recordedGames.length > 0 && ( +
      + {recordedGames.map((game) => { + const winner = match.teams.find( + ({ teamIndex }) => teamIndex === game.winnerTeamIndex, + ); + return ( +
    • + + 전체 {game.gameNumber}세트 ·{' '} + {winner ? `${winner.name} 승` : '팀 미확인'} + + {game.riotMatchId && ( + + 상세 분석 + + )} +
    • + ); + })} +
    + )} +
  • ); @@ -567,7 +436,7 @@ export default function CommunityInternalStatsPage() { const isRanking = searchParams.get('view') === 'ranking'; const seasonId = searchParams.get('seasonId') || 'current'; const query = searchParams.get('q') ?? ''; - const keyword = query.trim().toLocaleLowerCase('ko-KR'); + const keyword = useDeferredValue(query.trim().slice(0, 100)); const format = searchParams.get('format'); const playerId = searchParams.get('player'); const sort = parseLeaderboardSort(searchParams.get('sort')); @@ -579,12 +448,18 @@ export default function CommunityInternalStatsPage() { limit: 12, }; const communityQuery = useCommunity(communityId); + const seasonsQuery = useCommunityStatsSeasons(communityId); const matchesQuery = useCommunityInternalStatsMatches( - filters, + { + ...filters, + query: isRanking ? undefined : keyword, + format: format === 'pair' || format === 'tournament' ? format : undefined, + playerId: playerId ?? undefined, + }, communityId, !isRanking, ); - const leaderboardQuery = useCommunityLeaderboard(filters, communityId); + const leaderboardQuery = useCommunityLeaderboard({ ...filters, query: isRanking ? keyword : undefined }, communityId); const insightsQuery = useTeamInsights(filters, communityId); const { data: ddragon } = useDdragonManifest(); const matches = @@ -599,24 +474,12 @@ export default function CommunityInternalStatsPage() { sort, ); const player = leaderboardRows.find((row) => row.userId === playerId); - const visibleMatches = matches.filter((match) => { - const matchType = match.teams.length === 2 ? 'pair' : 'tournament'; - return ( - ((format !== 'pair' && format !== 'tournament') || - matchType === format) && - (!playerId || - match.teams.some((team) => - team.members.some((member) => member.userId === playerId), - )) && - match.title.toLocaleLowerCase('ko-KR').includes(keyword) - ); - }); - const visiblePlayers = leaderboardRows.filter((row) => - row.summonerName.toLocaleLowerCase('ko-KR').includes(keyword), - ); - const hasMatchFilters = Boolean( - keyword || format === 'pair' || format === 'tournament' || playerId, - ); + const matchedUsers = leaderboardQuery.data?.matchedUserIds; + const visiblePlayers = isRanking && keyword + ? leaderboardRows.filter((row) => matchedUsers?.includes(row.userId)) + : leaderboardRows; + const hasMatchFilters = Boolean(keyword || format || playerId); + const confirmedSideWinRate = insights?.sideWinRate.confirmed; const title = isRanking ? '선수 순위' : '최근 내전'; if (!communityId) { @@ -673,7 +536,11 @@ export default function CommunityInternalStatsPage() { > - {seasonId !== 'current' && seasonId !== 'all' && ( + {seasonsQuery.data?.seasons + .filter(({ id }) => id !== 'current' && id !== 'all') + .map(({ id, label }) => )} + {seasonId !== 'current' && seasonId !== 'all' && + !seasonsQuery.data?.seasons.some(({ id }) => id === seasonId) && ( )} @@ -703,6 +570,7 @@ export default function CommunityInternalStatsPage() { updateParam('q', event.target.value)} @@ -716,7 +584,7 @@ export default function CommunityInternalStatsPage() {

    {title}{' '} - {isRanking ? visiblePlayers.length : visibleMatches.length} + {isRanking ? visiblePlayers.length : matches.length}

    {isRanking ? ( @@ -841,34 +709,28 @@ export default function CommunityInternalStatsPage() { } />
    - ) : visibleMatches.length === 0 ? ( + ) : matches.length === 0 ? ( ) : (
      - {visibleMatches.map((match) => ( + {matches.map((match) => ( ))}
    )} {matchesQuery.hasNextPage && (
    - {hasMatchFilters && ( -

    - 필터는 불러온 {matches.length}건에 적용됩니다. -

    - )} {matchesQuery.isFetchNextPageError && (

    {insightsQuery.isLoading ? ( + ) : confirmedSideWinRate ? ( + ) : insights ? ( - +

    확정 세트 표본을 확인할 수 없습니다.

    ) : ( @@ -156,7 +159,7 @@ function UpcomingMatches({

    {match.status === 'recruiting' ? label - : HOME_MATCH_STATUS[match.status]}{' '} + : getMatchStageLabel(match)}{' '} · {capacity}

    + {matches.length === 0 && ( + + )} + {footer} ); } @@ -238,13 +245,13 @@ function HistoryResult({ match }: { match: MatchSummaryResponse }) { tone={match.status === 'in-progress' ? 'live' : 'neutral'} dot={match.status === 'in-progress'} > - {HOME_MATCH_STATUS[match.status]} + {getMatchStageLabel(match)} ); } return ( - {HOME_MATCH_STATUS[match.status]} + {getMatchStageLabel(match)} ); } @@ -764,7 +771,7 @@ function RankingPreview({ statsPath }: { statsPath: string }) { ); } -interface HistoryPaginationProps { +interface MatchPaginationProps { page: number; pageCount: number; total: number; @@ -773,14 +780,14 @@ interface HistoryPaginationProps { onNext: () => void; } -function HistoryPagination({ +function MatchPagination({ page, pageCount, total, isFetching, onPrevious, onNext, -}: HistoryPaginationProps) { +}: MatchPaginationProps) { return (
    @@ -814,32 +821,43 @@ export default function HomePage({ eventType }: { eventType?: MatchEventType }) const eventLabel = MATCH_EVENT_LABEL[selectedEventType]; const [timelineNow] = useState(() => new Date().toISOString()); const [searchParams, setSearchParams] = useSearchParams(); - const requestedPage = Number(searchParams.get('page')); - const historyPage = - showArchive && Number.isSafeInteger(requestedPage) && requestedPage > 0 - ? requestedPage - : 1; - const historyLimit = showArchive - ? HISTORY_MATCH_PAGE_SIZE - : HOME_HISTORY_LIMIT; - function setHistoryPage(page: number) { - const params = new URLSearchParams(searchParams); - if (page > 1) params.set('page', String(page)); - else params.delete('page'); - setSearchParams(params, { preventScrollReset: true }); + function getPage(key: 'page' | 'activePage') { + const page = Number(searchParams.get(key)); + return showArchive && Number.isSafeInteger(page) && page > 0 ? page : 1; + } + const historyPage = getPage('page'); + const activePage = getPage('activePage'); + const historyLimit = showArchive ? MATCH_ARCHIVE_PAGE_SIZE : HOME_HISTORY_LIMIT; + const activeLimit = showArchive ? MATCH_ARCHIVE_PAGE_SIZE : UPCOMING_MATCH_LIST_LIMIT; + function setPage(key: 'page' | 'activePage', page: number) { + setSearchParams((previous) => { + const params = new URLSearchParams(previous); + if (page > 1) params.set(key, String(page)); + else params.delete(key); + return params; + }, { preventScrollReset: true }); } const upcomingMatchesQuery = useMatches({ eventType: selectedEventType, + view: 'upcoming', + asOf: timelineNow, limit: UPCOMING_MATCH_LIST_LIMIT, - scheduledFrom: timelineNow, sort: 'asc', }); + const activeMatchesQuery = useMatchesPage({ + eventType: selectedEventType, + view: 'active', + asOf: timelineNow, + limit: activeLimit, + page: activePage, + sort: 'desc', + }); const historyMatchesQuery = useMatchesPage({ eventType: selectedEventType, + view: 'history', + asOf: timelineNow, limit: historyLimit, page: historyPage, - status: showArchive ? undefined : 'finished', - scheduledTo: showArchive ? timelineNow : undefined, sort: 'desc', includeResults: true, }); @@ -860,6 +878,11 @@ export default function HomePage({ eventType }: { eventType?: MatchEventType }) const bannerMatch = showArchive ? undefined : nextMatch; const visibleUpcomingMatches = showArchive ? allUpcomingMatches : upcomingMatches; const historyTotal = historyMatchesQuery.data?.total ?? 0; + const activeTotal = activeMatchesQuery.data?.total ?? 0; + const activePageCount = Math.max( + 1, + Math.ceil(activeTotal / (activeMatchesQuery.data?.limit ?? activeLimit)), + ); const historyPageCount = Math.max( 1, Math.ceil(historyTotal / (historyMatchesQuery.data?.limit ?? historyLimit)), @@ -882,6 +905,31 @@ export default function HomePage({ eventType }: { eventType?: MatchEventType })

    {eventLabel} 일정

    )} + {activeMatchesQuery.isError && !activeMatchesQuery.data ? ( + void activeMatchesQuery.refetch()} />} /> + ) : activeMatchesQuery.isPlaceholderData ? ( + + + + + ) : activeMatchesQuery.data && + (activeMatchesQuery.data.matches.length > 0 || activePage > 1) ? ( + 1 || activePage > 1) && ( + setPage('activePage', Math.min(activePage - 1, activePageCount))} + onNext={() => setPage('activePage', activePage + 1)} + /> + )} + /> + ) : null} {upcomingMatchesQuery.isLoading ? ( {eventLabel} 일정을 불러오는 중 @@ -921,7 +969,7 @@ export default function HomePage({ eventType }: { eventType?: MatchEventType }) > )} - {showArchive && !hasHistoryError && historyTotal > 0 && ( - 0 || historyPage > 1) && ( + setHistoryPage(Math.max(1, historyPage - 1))} - onNext={() => setHistoryPage(historyPage + 1)} + onPrevious={() => setPage('page', Math.min(historyPage - 1, historyPageCount))} + onNext={() => setPage('page', historyPage + 1)} /> )} diff --git a/apps/web/src/pages/InternalMatchDetailPage.tsx b/apps/web/src/pages/InternalMatchDetailPage.tsx index e2161141..971d4f7f 100644 --- a/apps/web/src/pages/InternalMatchDetailPage.tsx +++ b/apps/web/src/pages/InternalMatchDetailPage.tsx @@ -1,7 +1,8 @@ import { Link, useLocation, useParams } from "react-router"; -import { useCompetition, useDdragonManifest, useInternalMatchDetail } from "../api/hooks"; +import { useDdragonManifest, useInternalMatchDetail } from "../api/hooks"; import type { ApiInternalMatchDetailResponse, TeamSide } from "../api/types"; import { DEFAULT_COMMUNITY_ID } from "../config"; +import { ApiError } from "../lib/api"; import { championDisplayName, championIconUrl, @@ -12,12 +13,16 @@ import { } from "../lib/league"; import { internalMatchGamePath } from "../lib/internal-match-routes"; import { groupRecordedSets } from "../lib/internal-match-series"; +import { riotMatchIdForDisplay } from "../lib/internal-game-evidence"; +import { formatOfficialMatchResult } from "../lib/internal-stats-presentation"; import { LANE_LABELS } from "../lib/riot-history"; import { ItemIcon } from "../components/ItemTooltip"; +import { BasicGameScoreboard } from "../components/BasicGameScoreboard"; import { Btn, EmptyNote, + ErrorNote, LoadingNote, MetaDot, PageBody, @@ -101,17 +106,22 @@ function GamePanel({ communityId, matchId, game, + teams, ordinal, + riotMatchId, manifest, }: { communityId: string; matchId: string; game: ApiInternalMatchDetailResponse["games"][number]; + teams: ApiInternalMatchDetailResponse["match"]["teams"]; ordinal?: number; + riotMatchId: string | null; manifest: ReturnType["data"]; }) { const location = useLocation(); const historyBackTo = `${location.pathname}${location.search}${location.hash}`; + const hasAnalysis = !game.analysisAvailability || game.analysisAvailability === "available"; return (
    @@ -125,8 +135,10 @@ function GamePanel({

    {formatDateTime(game.gameCreation)} ·{" "} - {formatDuration(game.gameDuration)} ·{" "} - {game.riotMatchId} + {formatDuration(game.gameDuration)} + {riotMatchId && ( + <> · {riotMatchId} + )}

    @@ -135,7 +147,7 @@ function GamePanel({ state={{ backTo: historyBackTo }} className="inline-flex h-7 items-center rounded-full bg-primary-tint px-3 text-xs font-bold text-primary transition-colors hover:brightness-95" > - 상세 분석 + {hasAnalysis ? "상세 분석" : "경기 기록"} {game.teams.map((team) => (
    - {game.teams.map((team) => ( + {hasAnalysis ? game.teams.map((team) => (
    - ))} + )) : } ); } @@ -260,7 +272,6 @@ export default function InternalMatchDetailPage() { ? requestedBack : `/communities/${communityId}/internal-stats`; const detailQuery = useInternalMatchDetail(matchId, communityId); - const competition = useCompetition(matchId, communityId); const { data: ddragon } = useDdragonManifest(); const detail = detailQuery.data; @@ -272,7 +283,15 @@ export default function InternalMatchDetailPage() { ); } - if (detailQuery.error || !detail) { + if (detailQuery.isError && !(detailQuery.error instanceof ApiError && detailQuery.error.status === 404)) { + return ( + + void detailQuery.refetch()}>다시 시도} /> + + ); + } + if (!detail) { return ( !detail.games.some((record) => record.gameId === game.id), + ) ?? []; return ( <> @@ -305,6 +328,12 @@ export default function InternalMatchDetailPage() { {detail.match.teams.length}팀 {detail.games.length}세트 수집 + {competition && ( + <> + + {formatOfficialMatchResult(detail.match.resultPresentation)} + + )} } actions={ @@ -314,7 +343,7 @@ export default function InternalMatchDetailPage() { } /> - {detail.games.length === 0 && ( + {detail.games.length === 0 && unanalysedGames.length === 0 && ( @@ -324,14 +353,27 @@ export default function InternalMatchDetailPage() {

    {group.label} - {group.series ? "시리즈" : "대진"} · {group.sets.length}세트 수집 + {group.series ? "시리즈" : "공식 시리즈 정보 없음"} · {group.sets.length}세트 수집

    {group.sets.map(({ game, official }) => ( - + ))} ))} + {unanalysedGames.length > 0 && ( + +

    공식 세트 결과

    +
      + {unanalysedGames.map((game) => ( +
    • + 전체 {game.displayNumber}세트 · {competition?.teams.find((team) => team.teamId === game.winnerTeamId)?.name ?? "팀 미확인"} 승리 + {" · "}{game.evidence.type === "legacy" ? "Riot 원본 없음" : "상세 분석 준비 중"} +
    • + ))} +
    +
    + )}
    ); diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index 51012e7a..df9b5b66 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -61,6 +61,7 @@ import { } from "../components/competition/match-detail-tabs"; import { DEFAULT_COMMUNITY_ID, useAuthUserId } from "../config"; import { apiFetch, ApiError } from "../lib/api"; +import { getMatchStageLabel } from "./home-match-presentation"; import { profileIconUrl } from "../lib/ddragon"; import { POSITION_ORDER, @@ -1000,6 +1001,9 @@ function MatchRegistration({ joining, error, onJoin, + cancelling, + cancelError, + onCancel, }: { match: MatchDetailView; canJoin: boolean; @@ -1008,6 +1012,9 @@ function MatchRegistration({ joining: boolean; error: Error | null; onJoin: (position: Position) => void; + cancelling: boolean; + cancelError: Error | null; + onCancel: () => void; }) { const [selectedPosition, setSelectedPosition] = useState(); const position = selectedPosition ?? initialPosition; @@ -1059,6 +1066,13 @@ function MatchRegistration({ ) )} {error && } + {match.joined && canJoin && ( + + 참가 신청 취소 + + )} + {cancelError && } ); } @@ -1452,6 +1466,12 @@ export default function MatchDetailPage() { const navigate = useNavigate(); const [searchParams, setSearchParams] = useSearchParams(); const queryClient = useQueryClient(); + function invalidateMatchLists() { + return Promise.all([ + queryClient.invalidateQueries({ queryKey: ["matches", DEFAULT_COMMUNITY_ID] }), + queryClient.invalidateQueries({ queryKey: ["matches-page", DEFAULT_COMMUNITY_ID] }), + ]); + } const authUserId = useAuthUserId(); const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); const competitionEnabled = Boolean( @@ -1527,9 +1547,7 @@ export default function MatchDetailPage() { queryClient.invalidateQueries({ queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null], }), - queryClient.invalidateQueries({ - queryKey: ["matches", DEFAULT_COMMUNITY_ID], - }), + invalidateMatchLists(), ]); }, onError: () => { @@ -1537,6 +1555,19 @@ export default function MatchDetailPage() { }, }); + const cancelJoinMutation = useMutation({ + mutationFn: () => apiFetch( + `/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants`, + { method: "DELETE" }, + ), + onSettled: async () => { + await Promise.all([ + queryClient.invalidateQueries({ queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null] }), + invalidateMatchLists(), + ]); + }, + }); + const addParticipantMutation = useMutation({ mutationFn: ({ userId, @@ -1557,9 +1588,7 @@ export default function MatchDetailPage() { onSuccess: async () => { await Promise.all([ queryClient.invalidateQueries({ queryKey: matchQueryKey }), - queryClient.invalidateQueries({ - queryKey: ["matches", DEFAULT_COMMUNITY_ID], - }), + invalidateMatchLists(), ]); }, }); @@ -1591,9 +1620,7 @@ export default function MatchDetailPage() { }, onSettled: () => { void queryClient.invalidateQueries({ queryKey: matchQueryKey }); - void queryClient.invalidateQueries({ - queryKey: ["matches", DEFAULT_COMMUNITY_ID], - }); + void invalidateMatchLists(); }, }); @@ -1686,6 +1713,7 @@ export default function MatchDetailPage() { queryClient.invalidateQueries({ queryKey: ["auction", DEFAULT_COMMUNITY_ID, id ?? null], }), + invalidateMatchLists(), ]); navigate(`/match/${id}/auction`); }, @@ -1845,13 +1873,15 @@ export default function MatchDetailPage() { } const match = mapApiMatchToMatchDetail(matchQuery.data); - const si = statusBadge(match.status); + const si = { ...statusBadge(match.status), label: getMatchStageLabel(matchQuery.data) }; const auctionNotStarted = auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404; const activeAuction = auctionNotStarted ? null : auctionQuery.data; const showAuctionLink = Boolean(activeAuction); const hasTeamProgress = Boolean(competitionQuery.data?.teams.length) && - (match.status === "in-progress" || match.status === "finished"); + (matchQuery.data.eventProgress?.stage === "team-ready" || + match.status === "in-progress" || + match.status === "finished"); const auctionParticipantPool = buildAuctionParticipantPool( matchQuery.data.participants, ); @@ -2010,6 +2040,9 @@ export default function MatchDetailPage() { joining={joinMatchMutation.isPending} error={joinMatchMutation.error} onJoin={joinMatchMutation.mutate} + cancelling={cancelJoinMutation.isPending} + cancelError={cancelJoinMutation.error} + onCancel={() => cancelJoinMutation.mutate()} /> )} diff --git a/apps/web/src/pages/MatchGameDetailPage.tsx b/apps/web/src/pages/MatchGameDetailPage.tsx index cde4b46c..afc58f48 100644 --- a/apps/web/src/pages/MatchGameDetailPage.tsx +++ b/apps/web/src/pages/MatchGameDetailPage.tsx @@ -13,7 +13,7 @@ import { XAxis, YAxis, } from "recharts"; -import { useCompetition, useDdragonManifest, useInternalMatchDetail } from "../api/hooks"; +import { useDdragonManifest, useInternalMatchDetail } from "../api/hooks"; import type { ApiInternalMatchDetailResponse, TeamSide } from "../api/types"; import { DEFAULT_COMMUNITY_ID } from "../config"; import { @@ -30,7 +30,10 @@ import { internalMatchGamePath, } from "../lib/internal-match-routes"; import { selectInternalMatchGame } from "../lib/internal-match-game-selection"; +import { ApiError } from "../lib/api"; +import { BasicGameScoreboard } from "../components/BasicGameScoreboard"; import { groupRecordedSets, type RecordedSeries } from "../lib/internal-match-series"; +import { riotMatchIdForDisplay } from "../lib/internal-game-evidence"; import { getSeriesHistoryResultLabel, shouldDisplaySeriesHistoryScore } from "../components/competition/competition-series-history"; import { LANE_LABELS } from "../lib/riot-history"; import { @@ -58,6 +61,7 @@ import { import { Btn, EmptyNote, + ErrorNote, LoadingNote, MetaDot, PageBody, @@ -1626,15 +1630,16 @@ function MatchScoreHero({ }) { const selectedSeries = group.series; const officialGame = group.sets.find(({ game }) => game === selectedGame)?.official; + const riotMatchId = riotMatchIdForDisplay(selectedGame, officialGame); const setLabel = officialGame ? `${officialGame.ordinal}세트` : `전체 ${selectedGame.gameNumber}세트`; const [leftTeam, rightTeam] = selectedGame.teams; - const getScore = (side: TeamSide) => selectedSeries?.entries.find( - (entry) => entry.teamId === officialGame?.teams[side].teamId, - )?.gameWins; - const leftScore = leftTeam && getScore(leftTeam.side); - const rightScore = rightTeam && getScore(rightTeam.side); - const showSeriesScore = selectedSeries && shouldDisplaySeriesHistoryScore(selectedSeries) && leftScore !== undefined && rightScore !== undefined; - const decision = selectedSeries?.status === "completed" ? getSeriesHistoryResultLabel(selectedSeries) : null; + const teamName = (teamId: string | null) => + detail.competition?.teams.find((team) => team.teamId === teamId)?.name ?? "팀 미확인"; + const seriesSummary = selectedSeries && shouldDisplaySeriesHistoryScore(selectedSeries) + ? `${selectedSeries.status === "in-progress" ? "시리즈 현재" : "시리즈 최종"} · ${selectedSeries.entries.map( + ({ teamId, gameWins }) => `${teamName(teamId)} ${gameWins}`, + ).join(" : ")}` + : selectedSeries?.status === "completed" ? getSeriesHistoryResultLabel(selectedSeries) : null; const sideTone = (side: TeamSide) => side === "blue" ? "text-win" : "text-loss"; @@ -1666,8 +1671,18 @@ function MatchScoreHero({ {formatDuration(selectedGame.gameDuration)} - - {selectedGame.riotMatchId} + {riotMatchId && ( + <> + + {riotMatchId} + + )} + {seriesSummary && ( + <> + + {seriesSummary} + + )} } actions={ @@ -1687,16 +1702,7 @@ function MatchScoreHero({
    - {showSeriesScore ? ( - <> -
    {leftScore} : {rightScore}
    -
    - {selectedSeries.status === "in-progress" ? "시리즈 진행 스코어" : "시리즈 스코어"} -
    - - ) : ( -
    {decision ?? "세트 결과"}
    - )} +
    세트 결과
    + void detailQuery.refetch()}>다시 시도} /> + + ); + } + if (!detail) { return ( sets.some(({ game }) => game === selectedGame)); if (!selectedGame || !group) { + const officialGame = detail.competition?.projection.games.find( + (game) => game.displayNumber === requestedGameNumber, + ); + if (officialGame) { + const winner = detail.competition?.teams.find((team) => team.teamId === officialGame.winnerTeamId); + return ( + + {backTarget.label}} + /> + + ); + } const hasRecordedGames = detail.games.length > 0; const requestedGameLabel = Number.isSafeInteger(requestedGameNumber) && requestedGameNumber > 0 @@ -1805,38 +1835,39 @@ export default function MatchGameDetailPage() { navigationState={navigationState} /> - - - - -
    - - + - } - /> -
    + +
    + + + } + /> +
    + + ) : ( + + )} ); diff --git a/apps/web/src/pages/UserHistoryPage.tsx b/apps/web/src/pages/UserHistoryPage.tsx index abec7f9e..dc4d8a6a 100644 --- a/apps/web/src/pages/UserHistoryPage.tsx +++ b/apps/web/src/pages/UserHistoryPage.tsx @@ -52,11 +52,11 @@ import { RANK_FILTER_TABS, } from "../lib/riot-history"; import { - mockLargestMultiKill, multiKillLabel, rankPositionRates, } from "../lib/multi-kill"; import { ResponsiveTierLabel } from "../components/RankBadge"; +import { formatRankDetail } from "../components/rankBadgeUtils"; import { InternalGameAnalysisPanel, InternalGameDetailTabBar, @@ -647,8 +647,12 @@ function ParticipantRow({ > {participantName}
    - {/* 티어 (임시: 백엔드 연동 전까지 비움 — 라인은 행 순서로 식별) */} -
    —
    + {participant.tier && ( +
    + {formatRankDetail(participant.tier)} +
    + )}
    @@ -782,10 +786,9 @@ function resolveInternalDetailGame( match: ApiRecentMatchView, ) { if (!detail) return undefined; - return ( - detail.games.find((game) => game.gameNumber === match.gameNumber) ?? - detail.games.find((game) => game.riotMatchId === match.matchId) ?? - detail.games[0] + return detail.games.find( + (game) => game.riotMatchId === match.matchId && + (match.gameNumber === undefined || game.gameNumber === match.gameNumber), ); } @@ -914,14 +917,7 @@ function RecentMatchCard({ ownerParticipantId: string; }) { const [expanded, setExpanded] = useState(false); - // 응답에 값이 없을 때 개발 화면에서만 목업으로 배지 모양을 확인한다. - const isMockMultiKill = - match.largestMultiKill === undefined && import.meta.env.DEV; - const multiKill = multiKillLabel( - isMockMultiKill - ? mockLargestMultiKill(match.kills) - : match.largestMultiKill, - ); + const multiKill = multiKillLabel(match.largestMultiKill); const championName = championDisplayName(manifest, match.championId) ?? String(match.championId); const outcome = match.remake ? "remake" : match.win ? "win" : "loss"; @@ -964,7 +960,6 @@ function RecentMatchCard({ {multiKill && ( {multiKill} diff --git a/apps/web/src/pages/home-match-presentation.ts b/apps/web/src/pages/home-match-presentation.ts index 1a88f422..277c935a 100644 --- a/apps/web/src/pages/home-match-presentation.ts +++ b/apps/web/src/pages/home-match-presentation.ts @@ -1,4 +1,4 @@ -import type { MatchDetailResponse } from '@lolympus/contracts'; +import type { MatchDetailResponse, MatchEventStage } from '@lolympus/contracts'; const scheduleFormatter = new Intl.DateTimeFormat('ko-KR', { timeZone: 'Asia/Seoul', @@ -10,16 +10,25 @@ const scheduleFormatter = new Intl.DateTimeFormat('ko-KR', { hourCycle: 'h23', }); -export const HOME_MATCH_STATUS = { +const MATCH_STAGE_LABEL: Record = { recruiting: '모집 중', - 'team-built': '팀빌딩', + auction: '경매 중', + 'team-ready': '팀 편성 완료', + 'team-check': '팀빌딩 상태 확인 필요', 'in-progress': '진행 중', finished: '종료', -} as const; +}; + +export function getMatchStageLabel( + match: Pick, +) { + return MATCH_STAGE_LABEL[match.eventProgress?.stage ?? + (match.status === 'team-built' ? 'team-check' : match.status)]; +} type HomeMatchEnrollment = Pick< MatchDetailResponse, - 'status' | 'joined' | 'participants' | 'maxParticipants' + 'status' | 'eventProgress' | 'joined' | 'participants' | 'maxParticipants' >; export function getHomeMatchSchedule(scheduledAt: string) { @@ -92,8 +101,7 @@ export function getNextMatchBanner( const regularTitle = /^(?:[월화수목금토일]요일\s*(?:정기\s*)?|정기\s*)내전$/u; const title = regularTitle.test(match.title.trim()) ? '정기 내전' : match.title; - let status: string = HOME_MATCH_STATUS[match.status]; - if (match.status === 'team-built') status = '팀 편성'; + let status = getMatchStageLabel(match); if (match.status === 'recruiting') { if (match.joined) status = '신청 완료'; else if (!canApply) status = match.maxParticipants > 0 ? '정원 마감' : '모집 마감'; diff --git a/apps/web/src/preview/InternalStatsPreview.tsx b/apps/web/src/preview/InternalStatsPreview.tsx deleted file mode 100644 index 8b66e489..00000000 --- a/apps/web/src/preview/InternalStatsPreview.tsx +++ /dev/null @@ -1,416 +0,0 @@ -import { ChevronDown, Search, X } from 'lucide-react'; -import { Link, useSearchParams } from 'react-router'; -import { DEFAULT_COMMUNITY_ID } from '../config'; -import { getHomeMatchSchedule } from '../pages/home-match-presentation'; -import { Chip, EmptyNote, pageWidthClass } from '../ui'; -import { - previewSeasons, - type PreviewMatch, - type PreviewPlayer, -} from './internal-stats-fixtures'; - -const formats = [ - { value: '', label: '전체' }, - { value: 'pair', label: '두 팀 내전' }, - { value: 'tournament', label: '대회' }, -] as const; - -function MatchResult({ result }: { result: PreviewMatch['result'] }) { - switch (result.kind) { - case 'series': - return ( - - {result.series.teams[0]} - - {result.series.score.join(' : ')} - - {result.series.teams[1]} - - ); - case 'tournament': - return ( - - - 우승 - - {result.champion} - - ); - case 'collecting': - return ( - - 결과 수집 중{' '} - - {result.recordedGames}세트 - - - ); - case 'unavailable': - return 공식 결과 없음; - } -} - -function MatchDetails({ result }: { result: PreviewMatch['result'] }) { - if (result.kind === 'collecting') { - return ( -

    - 수집된 {result.recordedGames}세트를 확인 중입니다. 순위와 우승팀은 대회 - 결과가 확정되면 표시됩니다. -

    - ); - } - if (result.kind === 'unavailable') { - return

    내전 일정은 종료됐고 공식 결과가 등록되지 않았습니다.

    ; - } - - const series = result.kind === 'tournament' ? result.final : result.series; - return ( - <> -

    - {result.kind === 'tournament' ? '결승 시리즈' : '시리즈 결과'} - - {series.teams[0]} {series.score.join(' : ')} {series.teams[1]} - -

    -
      - {series.games.map((game, index) => ( -
    1. - - {index + 1}세트 ·{' '} - - {game.winner} 승리 - - - {game.duration} -
    2. - ))} -
    - - ); -} - -function MatchRow({ match }: { match: PreviewMatch }) { - const schedule = getHomeMatchSchedule(match.scheduledAt); - return ( -
  • -
    - - - - ·{' '} - {match.teamCount}팀 - - - {match.title} - - - - - - -
    - -
    -
    -
  • - ); -} - -function Ranking({ - players, - season, -}: { - players: (PreviewPlayer & { rank: number })[]; - season: string; -}) { - return ( - - - - - - - - - - - - - - - - - {players.map((player) => { - const total = player.wins + player.losses; - const search = new URLSearchParams({ season, player: player.id }); - return ( - - - - - - - ); - })} - -
    - 순위 - - 선수 - - 세트 - - 승률 -
    - {player.rank} - - - {player.name} - - #{player.tag} - - -

    {player.position}

    -
    {total} - {Math.round((player.wins / total) * 100)}% -
    - ); -} - -function SeasonSummary({ - season, - playerCount, - sideWins, -}: { - season: string; - playerCount: number; - sideWins: [number, number]; -}) { - const [blue, red] = sideWins; - const total = blue + red; - const blueShare = Math.round((blue / total) * 100); - return ( - - ); -} - -export default function InternalStatsPreview() { - const [params, setParams] = useSearchParams(); - const season = params.get('season') === '2025' ? '2025' : '2026'; - const view = params.get('view') === 'ranking' ? 'ranking' : 'matches'; - const data = previewSeasons[season]; - const query = params.get('q') ?? ''; - const keyword = query.trim().toLocaleLowerCase('ko-KR'); - const format = - formats.find(({ value }) => value === params.get('format'))?.value ?? ''; - const player = data.players.find(({ id }) => id === params.get('player')); - const matches = data.matches.filter((match) => { - const matchFormat = match.teamCount === 2 ? 'pair' : 'tournament'; - return ( - (!format || matchFormat === format) && - (!player || match.playerIds.includes(player.id)) && - match.title.toLocaleLowerCase('ko-KR').includes(keyword) - ); - }); - const players = data.players - .map((entry, index) => ({ ...entry, rank: index + 1 })) - .filter(({ name, tag }) => - `${name}#${tag}`.toLocaleLowerCase('ko-KR').includes(keyword), - ); - const isRanking = view === 'ranking'; - const sectionTitle = isRanking ? '선수 순위' : '최근 내전'; - const count = isRanking ? players.length : matches.length; - - function updateParam(key: string, value: string) { - const next = new URLSearchParams(params); - if (value) next.set(key, value); - else next.delete(key); - if (key === 'view' || key === 'season') { - next.delete('q'); - next.delete('format'); - next.delete('player'); - } - setParams(next, { replace: key === 'q', preventScrollReset: true }); - } - - return ( -
    -
    -
    -
    -
    - - 목업 데이터 - - - 현재 전적 화면 보기 - -
    -

    - 내전 전적 -

    -

    - 최근 내전 결과와 시즌별 선수 순위 -

    -
    - -
    - -
    -
    -
    -
    - updateParam('view', '')} - > - 최근 내전 - - updateParam('view', 'ranking')} - > - 선수 순위 - -
    - -
    - -
    -
    -

    - {sectionTitle}{' '} - - {count} - -

    - {isRanking ? ( - 승률 순 - ) : ( -
    - {formats.map(({ value, label }) => ( - updateParam('format', value)} - > - {label} - - ))} -
    - )} -
    - {!isRanking && player && ( -
    - updateParam('player', '')} - aria-label={`${player.name} 참가 내전 필터 해제`} - > - {player.name} 참가 내전{' '} - -
    - )} - {count === 0 ? ( - - ) : isRanking ? ( - - ) : ( -
      - {matches.map((match) => ( - - ))} -
    - )} -
    -
    - -
    -
    -
    - ); -} diff --git a/apps/web/src/preview/MatchFlowsPreview.tsx b/apps/web/src/preview/MatchFlowsPreview.tsx deleted file mode 100644 index baf736ca..00000000 --- a/apps/web/src/preview/MatchFlowsPreview.tsx +++ /dev/null @@ -1,292 +0,0 @@ -import { useState, type ReactNode } from "react"; -import { Link, useSearchParams } from "react-router"; -import { Btn, Chip, Pill, pageWidthClass } from "../ui"; -import "./match-flows-preview.css"; - -const flows = [ - { id: "signup", name: "참가 신청" }, - { id: "auction", name: "경매" }, - { id: "team", name: "팀 진행·대진" }, - { id: "ops", name: "운영" }, -] as const; - -const teams = [ - { name: "별무리", points: 430, players: 3, open: "정글 · 서포터" }, - { name: "여울", points: 520, players: 2, open: "탑 · 미드 · 원딜" }, - { name: "밤편지", points: 370, players: 4, open: "원딜" }, - { name: "서릿길", points: 480, players: 3, open: "탑 · 미드" }, -] as const; - -const opsItems = [ - { id: "code", type: "코드", title: "1세트 코드 발급 대기", context: "토요 내전 · 준결승 2경기", action: "예시 코드 발급", done: "발급됨", detail: "별무리와 여울의 1세트입니다. 발급되면 두 팀의 팀 진행 화면에 표시됩니다." }, - { id: "result", type: "결과", title: "수집된 결과 확인", context: "수요 내전 · 결승 2세트", action: "예시 결과 확인 완료", done: "확인 완료", detail: "수집된 결과는 여울 승리입니다. 내전과 세트를 확인한 뒤 검토를 마칠 수 있습니다." }, - { id: "import", type: "과거 기록", title: "중복 후보 2건 검토", context: "11월 1일~7일 · 수집 완료 18건", action: "예시 검토 완료", done: "검토 완료", detail: "같은 Riot 경기 ID가 이미 등록된 기록입니다. 두 기록을 비교한 뒤 정리하는 단계입니다." }, -] as const; - -const headings = { - signup: { label: "참가 신청", title: "토요 내전", detail: "11월 14일 (토) 21:00 · 소환사의 협곡 · 4팀" }, - auction: { label: "팀빌딩", title: "토요 내전 경매", detail: "현재 선수와 팀 포인트를 한 화면에서 확인하세요." }, - team: { label: "팀 진행", title: "별무리의 다음 경기", detail: "토요 내전 · 더블 엘리미네이션" }, - ops: { label: "운영", title: "확인할 작업", detail: "코드 발급, 결과 확인, 과거 기록 검토를 모았습니다." }, -} as const; - -function Panel({ title, children }: { title: string; children: ReactNode }) { - return ( -
    -

    {title}

    -
    {children}
    -
    - ); -} - -function PreviewControl({ label, children }: { label: string; children: ReactNode }) { - return ( - - ); -} - -const selectClass = "min-h-10 max-w-full rounded-field border border-line-strong bg-card px-2.5 text-sm text-content"; - -function Signup() { - const [full, setFull] = useState(false); - const [position, setPosition] = useState(""); - const [entry, setEntry] = useState<"joined" | "waiting" | null>(null); - const enrolled = full ? 20 : entry === "joined" ? 19 : 18; - const positions = ["탑", "정글", "미드", "원딜", "서포터"]; - - return ( - <> - - - -
    - -
    -

    - {entry === "joined" ? "참가 확정" : entry === "waiting" ? "대기 신청 완료" : full ? "현재 정원이 찼습니다" : "2자리 남았어요"} -

    - {enrolled}/20명 -
    - - {entry ? ( -
    -

    - {entry === "joined" ? `희망 포지션은 ${position}입니다. 20:50까지 디스코드 대기실에 입장해 주세요.` : `희망 포지션은 ${position}입니다. 현재 대기 1번이며 빈자리가 생기면 순서대로 안내합니다.`} -

    -
    setEntry(null)}>신청 취소
    -
    - ) : ( -
    { - event.preventDefault(); - setEntry(full ? "waiting" : "joined"); - }}> -
    - 희망 포지션 -
    - {positions.map((role) => ( - - ))} -
    -
    -
    {full ? "대기 신청" : "참가 신청"}
    -
    - )} -
    - -
    -
    신청 마감
    20:30
    -
    디스코드 집결
    20:50
    -
    내전 시작
    21:00
    -
    -
    - 참가 규칙 -

    희망 포지션과 실제 배정은 다를 수 있습니다. 불참 시 모집 마감 전 신청을 취소해 주세요.

    -
    -
    -
    - - ); -} - -function Auction() { - const [spectator, setSpectator] = useState(false); - const [closed, setClosed] = useState(false); - const [bids, setBids] = useState([{ team: "밤편지", points: 120 }, { team: "여울", points: 110 }]); - const current = bids[0]; - const nextBid = current.points + 10; - - return ( - <> -
    - - - - setClosed(!closed)}>입찰 마감 상태 -
    -
    - -
    -

    초승달 #MOON

    다이아몬드 2 · 정글 / 서포터

    - {closed ? "입찰 마감" : "입찰 중"} -
    -
    -

    {closed ? "최종 낙찰가" : "현재 최고가"}

    {current.points}P

    {current.team}

    - {!spectator &&

    별무리 잔여

    {closed && current.team === "별무리" ? teams[0].points - current.points : teams[0].points}P

    } -
    - {!spectator && !closed && ( -
    - setBids([{ team: "별무리", points: nextBid }, ...bids])}>{current.team === "별무리" ? "현재 최고 입찰" : `${nextBid}P 입찰`} -

    낙찰될 때 포인트가 차감됩니다.

    -
    - )} -
    -
    최근 내전 전적

    최근 8세트 · 5승 3패 · KDA 3.6

    -
    현재 선수 입찰 기록 · {bids.length}건
      {bids.map((bid) =>
    1. {bid.team}{bid.points}P
    2. )}
    -
    -
    - -
      - {teams.map((team) => { - const won = closed && current.team === team.name; - return ( -
    • -

      {team.name}

      {won ? "선수 1명 낙찰" : `빈 포지션 · ${team.open}`}

      -

      {team.points - (won ? current.points : 0)}P

      {team.players + Number(won)}/5명

      -
    • - ); - })} -
    -
    -
    - - ); -} - -function TeamProgress() { - const [issued, setIssued] = useState(false); - const [codeStatus, setCodeStatus] = useState(""); - const code = "DEMO-ONLY-01"; - - async function copyCode() { - try { - await navigator.clipboard.writeText(code); - setCodeStatus("예시 코드를 복사했습니다."); - } catch { - setCodeStatus("복사할 수 없습니다. 코드를 직접 선택해 주세요."); - } - } - - return ( - <> -
    { setIssued(!issued); setCodeStatus(""); }}>코드 발급 상태
    -
    - -

    준결승 · 3전 2선승 · 21:30

    -

    별무리 vs 여울

    -
    -

    1세트 토너먼트 코드

    {issued ? "발급됨" : "발급 대기"}
    - {issued ? ( -
    {code} void copyCode()}>코드 복사
    - ) :

    운영자가 코드를 발급하면 이곳에서 복사할 수 있습니다.

    } -

    {codeStatus}

    -
    -
    - 다른 세트 상태 -

    2세트 · 발급 대기

    3세트 · 필요 시 진행

    -
    -
    - -
      -
    • 1라운드 · 종료

      별무리 2 : 0 밤편지

    • -
    • 준결승 · 2대진

      별무리 vs 여울 · 21:30

      서릿길 vs 파도 · 21:30

    • -
    • 결승 · 대진 미정
    • -
    -
    -
    - - ); -} - -function Operations() { - const [filter, setFilter] = useState("전체"); - const [done, setDone] = useState([]); - const [message, setMessage] = useState(""); - const shown = opsItems.filter((item) => filter === "전체" || filter === item.type); - - return ( - <> -
    - {["전체", ...opsItems.map((item) => item.type)].map((type) => ( - setFilter(type)}>{type} - ))} -
    - -
      - {shown.map((item) => { - const completed = done.includes(item.id); - return ( -
    • -
      - - {item.title}{completed ? item.done : "확인 필요"}{item.context} - -
      -

      {item.detail}

      - {!completed && { setDone([...done, item.id]); setMessage(`${item.title} · ${item.done}`); }}>{item.action}} -
      -
      -
    • - ); - })} -
    -

    {message}

    -
    - - ); -} - -export default function MatchFlowsPreview() { - const [params] = useSearchParams(); - const active = flows.find((flow) => flow.id === params.get("flow"))?.id ?? "signup"; - const heading = headings[active]; - - return ( -
    -
    - UX 목업샘플 데이터로 보는 내전 흐름 -
    - -
    -

    {heading.label}

    -

    {heading.title}

    -

    {heading.detail}

    -
    -
    - {active === "signup" && } - {active === "auction" && } - {active === "team" && } - {active === "ops" && } -
    -
    - ); -} diff --git a/apps/web/src/preview/internal-stats-fixtures.ts b/apps/web/src/preview/internal-stats-fixtures.ts deleted file mode 100644 index ca9306eb..00000000 --- a/apps/web/src/preview/internal-stats-fixtures.ts +++ /dev/null @@ -1,150 +0,0 @@ -type Series = { - teams: [string, string]; - score: [number, number]; - games: { winner: string; duration: string }[]; -}; - -type MatchResult = - | { kind: 'series'; series: Series } - | { kind: 'tournament'; champion: string; final: Series } - | { kind: 'collecting'; recordedGames: number } - | { kind: 'unavailable' }; - -export type PreviewMatch = { - id: string; - title: string; - scheduledAt: string; - teamCount: number; - playerIds: string[]; - result: MatchResult; -}; - -export type PreviewPlayer = { - id: string; - name: string; - tag: string; - position: string; - wins: number; - losses: number; -}; - -type PreviewSeason = { - matches: PreviewMatch[]; - players: PreviewPlayer[]; - sideWins: [blue: number, red: number]; -}; - -const final: Series = { - teams: ['별빛', '바람'], - score: [2, 1], - games: [ - { winner: '별빛', duration: '30:42' }, - { winner: '바람', duration: '28:17' }, - { winner: '별빛', duration: '34:11' }, - ], -}; - -export const previewSeasons: Record<'2026' | '2025', PreviewSeason> = { - '2026': { - sideWins: [24, 21], - matches: [ - { - id: 'autumn-league', - title: '가을 내전 리그', - scheduledAt: '2026-11-08T12:00:00+09:00', - teamCount: 8, - playerIds: ['star', 'wind', 'forest'], - result: { kind: 'collecting', recordedGames: 16 }, - }, - { - id: 'loly-cup', - title: '롤림푸스 컵', - scheduledAt: '2026-11-07T21:00:00+09:00', - teamCount: 4, - playerIds: ['star', 'wind', 'forest', 'dawn'], - result: { kind: 'tournament', champion: '별빛', final }, - }, - { - id: 'saturday', - title: '토요일 정기 내전', - scheduledAt: '2026-10-31T21:00:00+09:00', - teamCount: 2, - playerIds: ['star', 'wind', 'dawn'], - result: { kind: 'series', series: final }, - }, - { - id: 'friday', - title: '금요일 심야 내전', - scheduledAt: '2026-10-30T22:00:00+09:00', - teamCount: 2, - playerIds: ['forest', 'dawn'], - result: { kind: 'unavailable' }, - }, - ], - players: [ - { - id: 'star', - name: '별빛', - tag: 'LTS', - position: '미드', - wins: 12, - losses: 5, - }, - { - id: 'wind', - name: '바람', - tag: 'LTS', - position: '정글', - wins: 10, - losses: 6, - }, - { - id: 'forest', - name: '숲길', - tag: 'KR1', - position: '서포터', - wins: 8, - losses: 6, - }, - { - id: 'dawn', - name: '새벽', - tag: 'KR1', - position: '원딜', - wins: 7, - losses: 8, - }, - ], - }, - '2025': { - sideWins: [2, 1], - matches: [ - { - id: 'winter', - title: '겨울 시즌 마감전', - scheduledAt: '2025-12-20T21:00:00+09:00', - teamCount: 2, - playerIds: ['star', 'wind'], - result: { kind: 'series', series: final }, - }, - ], - players: [ - { - id: 'star', - name: '별빛', - tag: 'LTS', - position: '미드', - wins: 2, - losses: 1, - }, - { - id: 'wind', - name: '바람', - tag: 'LTS', - position: '정글', - wins: 1, - losses: 2, - }, - ], - }, -}; diff --git a/apps/web/src/preview/match-flows-preview.css b/apps/web/src/preview/match-flows-preview.css deleted file mode 100644 index f76b07ea..00000000 --- a/apps/web/src/preview/match-flows-preview.css +++ /dev/null @@ -1,48 +0,0 @@ -.match-flows-title { - font-size: clamp(1.5rem, 5vw, 2rem); -} - -.match-flows-panel { - border-radius: 12px; - box-shadow: 0 3px 10px color-mix(in srgb, var(--color-palette-black) 3%, transparent); -} - -.match-flows-link[aria-current="page"] { - border-color: transparent; - background: var(--lts-ink); - color: var(--lts-on-ink); -} - -.match-flows-capacity { - appearance: none; - overflow: hidden; - border-radius: 999px; - background-color: var(--lts-sunken-strong); -} - -.match-flows-capacity::-webkit-progress-bar { - background-color: var(--lts-sunken-strong); -} - -.match-flows-capacity::-webkit-progress-value { - background-color: var(--color-brand-coral); -} - -.match-flows-capacity::-moz-progress-bar { - background-color: var(--color-brand-coral); -} - -.match-flows-task { - max-width: calc(100% - 1.25rem); -} - -.match-flows-task-context { - flex-basis: 100%; -} - -@media (min-width: 48rem) { - .match-flows-grid { - grid-template-columns: minmax(0, 1fr) minmax(16rem, 0.6fr); - align-items: start; - } -} diff --git a/apps/web/test/home-match-presentation.test.ts b/apps/web/test/home-match-presentation.test.ts index cadd3c31..cd694856 100644 --- a/apps/web/test/home-match-presentation.test.ts +++ b/apps/web/test/home-match-presentation.test.ts @@ -78,6 +78,6 @@ test('uses neutral titles and distinguishes registration states on the next matc assert.equal(getNextMatchBanner({ ...match, maxParticipants: 0 }).status, '모집 마감'); assert.deepEqual( getNextMatchBanner({ ...fullMatch, title: '토요일 시즌 결승 내전', status: 'team-built' }), - { title: '토요일 시즌 결승 내전', status: '팀 편성', capacity: '1/1명', canApply: false }, + { title: '토요일 시즌 결승 내전', status: '팀빌딩 상태 확인 필요', capacity: '1/1명', canApply: false }, ); }); diff --git a/apps/web/test/internal-game-evidence.test.ts b/apps/web/test/internal-game-evidence.test.ts new file mode 100644 index 00000000..e7b530fa --- /dev/null +++ b/apps/web/test/internal-game-evidence.test.ts @@ -0,0 +1,40 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import type { CompetitionGameView } from '@lolympus/contracts'; +import { riotMatchIdForDisplay } from '../src/lib/internal-game-evidence.ts'; + +test('keeps a real Riot ID visible even when analysis is missing', () => { + const game = { + gameId: 'game-1', + riotMatchId: 'KR_123', + analysisAvailability: 'missing', + }; + const official = { + evidence: { type: 'riot', riotMatchId: 'KR_123' }, + } as CompetitionGameView; + assert.equal(riotMatchIdForDisplay(game, official), 'KR_123'); +}); + +test('does not label a legacy evidence reference as a Riot ID', () => { + const official = { + evidence: { type: 'legacy', legacyReference: 'KR_123' }, + } as CompetitionGameView; + assert.equal( + riotMatchIdForDisplay({ riotMatchId: 'KR_123' }, official), + null, + ); + assert.equal( + riotMatchIdForDisplay({ riotMatchId: 'match:legacy:123' }), + null, + ); + assert.equal(riotMatchIdForDisplay({ riotMatchId: 'KR_TEMP_123' }), null); +}); + +test('shows a real Riot ID on unmigrated records and hides unresolved official references', () => { + assert.equal(riotMatchIdForDisplay({ riotMatchId: 'KR_123' }), 'KR_123'); + assert.equal(riotMatchIdForDisplay({ riotMatchId: 'NA1_123' }), 'NA1_123'); + assert.equal( + riotMatchIdForDisplay({ riotMatchId: 'KR_123', gameId: 'unresolved' }), + null, + ); +}); diff --git a/apps/web/test/internal-stats-presentation.test.ts b/apps/web/test/internal-stats-presentation.test.ts index 86f1ddb2..97910ef7 100644 --- a/apps/web/test/internal-stats-presentation.test.ts +++ b/apps/web/test/internal-stats-presentation.test.ts @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { - getInternalMatchOutcome, + formatOfficialMatchResult, getMainLane, parseLeaderboardSort, rankLeaderboardByLane, @@ -74,32 +74,23 @@ test('picks the most played lane', () => { assert.equal(getMainLane({}), undefined); }); -test('shows a score for a single two-team series and a winner otherwise', () => { - const team = (teamIndex: number) => ({ - teamIndex, - name: `${teamIndex + 1}팀`, - members: [], - }); - const pair = getInternalMatchOutcome({ - winnerTeamIndex: 1, - teams: [team(0), team(1)], - seriesResults: [ - { teamAIndex: 0, teamBIndex: 1, teamAWins: 1, teamBWins: 2 }, - ], - }); - assert.equal(pair?.type, 'score'); - assert.equal(pair?.type === 'score' && pair.rightWins, 2); - assert.equal(pair?.winner?.name, '2팀'); - - const tournament = getInternalMatchOutcome({ - winnerTeamIndex: 2, - teams: [team(0), team(1), team(2), team(3)], - seriesResults: [], - }); - assert.deepEqual(tournament, { type: 'winner', winner: team(2) }); - - assert.equal( - getInternalMatchOutcome({ teams: [team(0), team(1)], seriesResults: [] }), - undefined, - ); +test('displays official tournament winners by ID and keeps older records neutral', () => { + const champion = 'winner' as import('@lolympus/contracts').TeamId; + assert.equal(formatOfficialMatchResult({ + type: 'official', + competitionId: 'tournament' as import('@lolympus/contracts').CompetitionId, + sourceRevision: 10, + phase: 'completed', + formatType: 'double-elimination', + completedSeriesCount: 2, + teams: [{ teamId: champion, name: '별무리' }], + outcome: { + type: 'double-elimination', + championTeamId: champion, + placements: [{ rank: 1, teamId: champion }], + completedAt: '2026-11-10T00:00:00Z', + }, + }), '우승 · 별무리'); + assert.equal(formatOfficialMatchResult({ type: 'legacy' }), '과거 기록'); + assert.equal(formatOfficialMatchResult(undefined), '공식 결과 확인 불가'); }); diff --git a/packages/contracts/src/match.ts b/packages/contracts/src/match.ts index 30582dba..097c7cf6 100644 --- a/packages/contracts/src/match.ts +++ b/packages/contracts/src/match.ts @@ -1,4 +1,4 @@ -import type { CompetitionPhase } from "./competition.js"; +import type { CompetitionDetailResponse, CompetitionOutcome, CompetitionPhase } from "./competition.js"; import type { CompetitionFormatType } from "./format.js"; import type { CommunityId, @@ -23,6 +23,14 @@ export type MatchGameMode = | "double-elimination"; export type MatchEventType = "inhouse" | "tournament"; +export type MatchListView = "active" | "upcoming" | "history"; +export type MatchEventStage = + | "recruiting" + | "auction" + | "team-ready" + | "team-check" + | "in-progress" + | "finished"; export type GrandFinalGameCount = 1 | 3 | 5; export type MatchPosition = "TOP" | "JGL" | "MID" | "ADC" | "SUP"; @@ -48,6 +56,13 @@ export interface MatchTierView { fetchedAt: IsoDateTime; } +export interface RecentMatchParticipantRank { + tier: string; + rank?: string; + leaguePoints?: number; + fetchedAt: IsoDateTime; +} + export interface MatchParticipantView { userId: UserId; gameName?: string; @@ -88,6 +103,7 @@ export interface MatchDetailResponse { description: string; mapId: number; status: MatchLifecycleStatus; + eventProgress?: { stage: MatchEventStage }; scheduledAt: IsoDateTime; maxParticipants: number; gameCount: number; @@ -126,6 +142,42 @@ export interface MatchSummaryResponse extends MatchDetailResponse { historyResult?: MatchHistoryResult; } +export interface HallOfFameResponse { + match: { id: MatchId; title: string } | null; + teams: Array<{ + name: string; + captainUserId?: UserId; + members: Array<{ + userId: UserId; + position?: MatchPosition; + gameName?: string; + tagLine?: string; + profileIconId?: number; + }>; + }>; +} + +export type InternalMatchResultPresentation = + | { + type: "official"; + competitionId: CompetitionId; + sourceRevision: number; + phase: CompetitionPhase; + formatType: CompetitionFormatType; + teams: Array<{ teamId: TeamId; name: string }>; + completedSeriesCount: number; + outcome?: CompetitionOutcome; + singleSeries?: SeriesProjection; + } + | { type: "legacy" | "unavailable" }; + +export type InternalMatchCompetition = Pick< + CompetitionDetailResponse, + "id" | "revision" | "teams" | "projection" +>; + +export type GameAnalysisAvailability = "available" | "missing"; + export interface TeamTournamentCodeView { gameSlotId: GameSlotId; seriesId: SeriesId;