feat: connect tournament views to APIs and recover archived stats

Remove development previews and complete hall of fame, match history, official results, and multi-kill API integration.

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

Use bounded in-process cache invalidation retries and add the Riot match lookup index migration with regression coverage.
This commit is contained in:
dahyeon committed 2026-11-11 02:00:35 +09:00
1 parent 20e1e6ec04
commit 0d7617e2d2
70 files changed
+3739 -1793

No files matched your search

+33
View File
@@ -117,6 +117,39 @@ The index is `{ auctionCancellationCleanupRetryAt: 1 }`, restricted to
`{ auctionCancellationCleanupPending: true }`. The worker only reads due pending `{ auctionCancellationCleanupPending: true }`. The worker only reads due pending
entries; it no longer scans legacy cancellation markers without a pending flag. 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 ## 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. 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.
+1
View File
@@ -11,6 +11,7 @@
"competition:migrate": "ts-node src/modules/global/database/migrations/run-competition-domain.ts", "competition:migrate": "ts-node src/modules/global/database/migrations/run-competition-domain.ts",
"competition:repair-grand-final": "ts-node src/modules/global/database/migrations/repair-grand-final-bo3.ts", "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", "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:dev": "ts-node src/seed.ts",
"seed:dakao-participant": "ts-node src/seed-dakao-participant.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", "start:dev": "NODE_ENV=dev NEW_RELIC_HOME=. node --import newrelic/esm-loader.mjs -r newrelic dist/main.js",
@@ -80,7 +80,7 @@ export class AuctionController {
return this.auctionService.getStateByMatchId(matchId); return this.auctionService.getStateByMatchId(matchId);
} }
// 공개 — 팀장 2명만 쓸 엔드포인트(트러스트 기반, 10명 동시 관전). // 공개 입찰 기록 조회.
@Get('bids/history') @Get('bids/history')
@AllowPublicAccess() @AllowPublicAccess()
public async getBidHistory( public async getBidHistory(
@@ -106,14 +106,20 @@ export class AuctionController {
} }
@Post('bids') @Post('bids')
@AllowPublicAccess() @Roles('admin', 'owner', 'member')
@UseGuards(RolesGuard)
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
public async placeBid( public async placeBid(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: PlaceBidDto, @Body() body: PlaceBidDto,
) { ) {
this.assertSameCommunity(currentUser, communityId);
return this.auctionService.placeBid({ return this.auctionService.placeBid({
matchId, matchId,
bidderUserId: currentUser._id,
teamIndex: body.bidderTeamIndex, teamIndex: body.bidderTeamIndex,
amount: body.bidPointAmount, amount: body.bidPointAmount,
bidRequestId: body.bidRequestId, bidRequestId: body.bidRequestId,
@@ -78,6 +78,8 @@ describe('AuctionGateway', () => {
expect(broadcast).not.toHaveBeenCalled(); expect(broadcast).not.toHaveBeenCalled();
}); });
const bidderUserId = new mongoose.Types.ObjectId();
function createGateway(params?: { function createGateway(params?: {
getCurrentRedisTimestampMS?: jest.Mock; getCurrentRedisTimestampMS?: jest.Mock;
placeBidDelta?: 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 () => { it('broadcasts a bid delta and acknowledges the matching bid request', async () => {
const matchId = new mongoose.Types.ObjectId().toString(); const matchId = new mongoose.Types.ObjectId().toString();
const auctionBidHistoryEntry = { const auctionBidHistoryEntry = {
@@ -133,7 +152,10 @@ describe('AuctionGateway', () => {
const ack = jest.fn(); const ack = jest.fn();
await gateway.handleBid( await gateway.handleBid(
{ data: { matchId }, emit: jest.fn() } as never, {
data: { matchId, user: { _id: bidderUserId } },
emit: jest.fn(),
} as never,
{ {
bidPointAmount: 120, bidPointAmount: 120,
bidderTeamIndex: 2, bidderTeamIndex: 2,
@@ -147,6 +169,7 @@ describe('AuctionGateway', () => {
expect(placeBidDelta).toHaveBeenCalledWith({ expect(placeBidDelta).toHaveBeenCalledWith({
amount: 120, amount: 120,
bidRequestId: 'bid-1', bidRequestId: 'bid-1',
bidderUserId,
clientObservedAuctionLifecycleId: 'life-1', clientObservedAuctionLifecycleId: 'life-1',
clientObservedCurrentBidRoundPlayerUserId: 'player-1', clientObservedCurrentBidRoundPlayerUserId: 'player-1',
matchId: new mongoose.Types.ObjectId(matchId), matchId: new mongoose.Types.ObjectId(matchId),
@@ -200,7 +223,10 @@ describe('AuctionGateway', () => {
const ack = jest.fn(); const ack = jest.fn();
await gateway.handleBid( await gateway.handleBid(
{ data: { matchId }, emit: jest.fn() } as never, {
data: { matchId, user: { _id: bidderUserId } },
emit: jest.fn(),
} as never,
{ {
bidPointAmount: 50, bidPointAmount: 50,
bidderTeamIndex: 1, bidderTeamIndex: 1,
@@ -247,7 +273,10 @@ describe('AuctionGateway', () => {
const ack = jest.fn(); const ack = jest.fn();
await gateway.handleBid( await gateway.handleBid(
{ data: { matchId }, emit: socketEmit } as never, {
data: { matchId, user: { _id: bidderUserId } },
emit: socketEmit,
} as never,
{ {
bidPointAmount: 50, bidPointAmount: 50,
bidderTeamIndex: 1, bidderTeamIndex: 1,
@@ -318,7 +347,10 @@ describe('AuctionGateway', () => {
revision: 3, revision: 3,
}); });
const socketEmit = jest.fn(); const socketEmit = jest.fn();
const socket = { data: { matchId }, emit: socketEmit }; const socket = {
data: { matchId, user: { _id: bidderUserId } },
emit: socketEmit,
};
const { gateway } = createGateway({ placeBidDelta }); const { gateway } = createGateway({ placeBidDelta });
const acknowledgements: Array<Record<string, unknown>> = []; const acknowledgements: Array<Record<string, unknown>> = [];
@@ -359,7 +391,10 @@ describe('AuctionGateway', () => {
currentHighestBidPointAmount: 50, currentHighestBidPointAmount: 50,
revision: 3, revision: 3,
}); });
const socket = { data: { matchId }, emit: jest.fn() }; const socket = {
data: { matchId, user: { _id: bidderUserId } },
emit: jest.fn(),
};
const { gateway } = createGateway({ placeBidDelta }); const { gateway } = createGateway({ placeBidDelta });
for (let index = 0; index < 8; index += 1) { for (let index = 0; index < 8; index += 1) {
@@ -1,4 +1,4 @@
import { Logger } from '@nestjs/common'; import { ForbiddenException, Logger } from '@nestjs/common';
import { randomUUID } from 'crypto'; import { randomUUID } from 'crypto';
import { performance } from 'perf_hooks'; import { performance } from 'perf_hooks';
import { import {
@@ -86,6 +86,7 @@ interface AuctionSocketData {
identity?: IdentityDocument; identity?: IdentityDocument;
matchId?: string; matchId?: string;
user?: UserDocument; user?: UserDocument;
devUser?: UserDocument;
} }
type AuctionSocket = Socket< type AuctionSocket = Socket<
@@ -114,6 +115,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
private server!: Namespace; private server!: Namespace;
private readonly logger = new Logger(AuctionGateway.name); private readonly logger = new Logger(AuctionGateway.name);
private readonly socketAuthentication = new WeakMap<
AuctionSocket,
Promise<void>
>();
constructor( constructor(
private readonly auctionService: AuctionService, private readonly auctionService: AuctionService,
@@ -130,8 +135,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
} }
public async handleConnection(socket: AuctionSocket) { public async handleConnection(socket: AuctionSocket) {
const authentication = this.authenticateSocket(socket);
this.socketAuthentication.set(socket, authentication);
try { try {
await this.authenticateSocket(socket); await authentication;
this.logger.debug(`Auction client connected: ${socket.id}`); this.logger.debug(`Auction client connected: ${socket.id}`);
} catch (err) { } catch (err) {
this.logger.warn( this.logger.warn(
@@ -153,11 +160,13 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
return; return;
} }
await socket.join(payload.matchId);
socket.data.matchId = payload.matchId;
try { 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); await this.resolveSocketUserForMatch(socket, payload.matchId);
socket.data.matchId = payload.matchId;
const auction = await this.auctionService.getByMatchId( const auction = await this.auctionService.getByMatchId(
new mongoose.Types.ObjectId(payload.matchId), new mongoose.Types.ObjectId(payload.matchId),
); );
@@ -240,11 +249,17 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
} }
try { try {
const bidderUserId = this.resolveSocketUserId(socket);
if (!bidderUserId)
throw new ForbiddenException(
'팀장 계정으로 로그인해야 입찰할 수 있습니다.',
);
const bidResult = await this.auctionService.placeBidDelta({ const bidResult = await this.auctionService.placeBidDelta({
matchId: new mongoose.Types.ObjectId(matchId), matchId: new mongoose.Types.ObjectId(matchId),
teamIndex: payload.bidderTeamIndex, teamIndex: payload.bidderTeamIndex,
amount: payload.bidPointAmount, amount: payload.bidPointAmount,
bidRequestId, bidRequestId,
bidderUserId,
clientObservedBidRoundId: payload.clientObservedBidRoundId, clientObservedBidRoundId: payload.clientObservedBidRoundId,
clientObservedAuctionLifecycleId: clientObservedAuctionLifecycleId:
payload.clientObservedAuctionLifecycleId, payload.clientObservedAuctionLifecycleId,
@@ -573,14 +588,13 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
this.readHandshakeUserId(socket), this.readHandshakeUserId(socket),
); );
if (fallback) { if (fallback) {
socket.data.user = fallback.user; socket.data.devUser = fallback.user;
socket.data.identity = fallback.identity; socket.data.identity = fallback.identity;
return; return;
} }
const token = this.readHandshakeToken(socket); const token = this.readHandshakeToken(socket);
if (!token) { if (!token) {
// 임시 운영용: 경매 진행 중에는 로그인 없이도 관전/팀장 모드 선택/입찰을 허용한다.
return; return;
} }
@@ -622,14 +636,22 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
socket: AuctionSocket, socket: AuctionSocket,
matchId: string, matchId: string,
): Promise<void> { ): Promise<void> {
if (socket.data.user || !socket.data.identity) return; const devUser = socket.data.devUser;
const identity = socket.data.identity; const identity = socket.data.identity;
if (!devUser && !identity) return;
const MatchModel = await this.connectionService.getModel('match'); const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(matchId).select({ const match = await MatchModel.findById(matchId).select({
communityId: 1, communityId: 1,
}); });
if (!match) return; 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 UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findOne({ const user = await UserModel.findOne({
@@ -1,5 +1,6 @@
import { import {
BadRequestException, BadRequestException,
ForbiddenException,
ConflictException, ConflictException,
Injectable, Injectable,
InternalServerErrorException, InternalServerErrorException,
@@ -795,6 +796,10 @@ export class AuctionService {
} }
const team = this.findAuctionTeamByIndex(auction, params.teamIndex); const team = this.findAuctionTeamByIndex(auction, params.teamIndex);
if (!team) throw new BadRequestException('Unknown team.'); if (!team) throw new BadRequestException('Unknown team.');
this.assertBidderIsCaptain(
params.bidderUserId,
team.captainUserId.toString(),
);
if (params.amount <= auction.currentBid) { if (params.amount <= auction.currentBid) {
throw new BadRequestException('Bid must exceed current bid.'); throw new BadRequestException('Bid must exceed current bid.');
} }
@@ -807,8 +812,6 @@ export class AuctionService {
'Bid must reserve minimum points for remaining slots.', 'Bid must reserve minimum points for remaining slots.',
); );
} }
// 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다.
await this.recordSnapshot(auction, 'bid', params.bidderUserId); await this.recordSnapshot(auction, 'bid', params.bidderUserId);
auction.currentBid = params.amount; auction.currentBid = params.amount;
auction.currentBidderTeamIndex = params.teamIndex; auction.currentBidderTeamIndex = params.teamIndex;
@@ -929,6 +932,10 @@ export class AuctionService {
if (!bidContext.bidderTeamCaptainUserId) { if (!bidContext.bidderTeamCaptainUserId) {
throw new BadRequestException('Unknown team.'); throw new BadRequestException('Unknown team.');
} }
this.assertBidderIsCaptain(
params.bidderUserId,
bidContext.bidderTeamCaptainUserId,
);
const auctionLifecycleId = const auctionLifecycleId =
params.clientObservedAuctionLifecycleId ?? bidContext.auctionLifecycleId; params.clientObservedAuctionLifecycleId ?? bidContext.auctionLifecycleId;
@@ -1005,6 +1012,10 @@ export class AuctionService {
(entry) => Number(entry.teamIndex) === params.teamIndex, (entry) => Number(entry.teamIndex) === params.teamIndex,
); );
if (!team) throw new BadRequestException('Unknown team.'); if (!team) throw new BadRequestException('Unknown team.');
this.assertBidderIsCaptain(
params.bidderUserId,
this.stringFromState(team.captainUserId),
);
const auctionLifecycleId = const auctionLifecycleId =
params.clientObservedAuctionLifecycleId ?? params.clientObservedAuctionLifecycleId ??
@@ -2906,6 +2917,15 @@ export class AuctionService {
return auction.teams.find((team) => team.teamIndex === teamIndex); 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 { private createDeadline(secondsFromNow: number): Date {
return new Date(Date.now() + secondsFromNow * 1000); return new Date(Date.now() + secondsFromNow * 1000);
} }
@@ -0,0 +1,198 @@
import { Logger } from '@nestjs/common';
import { CommunityStatsCacheService } from './community-stats-cache.service';
describe('Community stats cache invalidation retries', () => {
let service: CommunityStatsCacheService;
let invalidate: jest.SpyInstance<Promise<number>, [string, number?]>;
beforeEach(() => {
jest.useFakeTimers();
jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
service = new CommunityStatsCacheService({} as never);
invalidate = jest
.spyOn(service, 'invalidateCommunity')
.mockRejectedValue(new Error('Redis down'));
});
afterEach(() => {
service.onModuleDestroy();
jest.restoreAllMocks();
jest.useRealTimers();
});
it('returns true even when successful invalidation deletes no cache entries', async () => {
invalidate.mockResolvedValue(0);
expect(await service.invalidateCommunityWithRetry('community')).toBe(true);
expect(invalidate).toHaveBeenCalledWith('community', 1_000);
expect(jest.getTimerCount()).toBe(0);
});
it('returns false immediately, then retries at most three times with increasing delays', async () => {
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
expect(invalidate).toHaveBeenCalledTimes(1);
for (const [index, delay] of [1_000, 5_000, 30_000].entries()) {
await jest.advanceTimersByTimeAsync(delay - 1);
expect(invalidate).toHaveBeenCalledTimes(index + 1);
await jest.advanceTimersByTimeAsync(1);
expect(invalidate).toHaveBeenCalledTimes(index + 2);
}
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(4);
expect(Logger.prototype.warn).toHaveBeenCalledWith(
expect.stringContaining('retries exhausted for community'),
);
});
it('does not reset the scheduled delay or remaining budget after another immediate failure', async () => {
await service.invalidateCommunityWithRetry('community');
await jest.advanceTimersByTimeAsync(1_000);
expect(invalidate).toHaveBeenCalledTimes(2);
await jest.advanceTimersByTimeAsync(2_000);
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
expect(jest.getTimerCount()).toBe(1);
await jest.advanceTimersByTimeAsync(2_999);
expect(invalidate).toHaveBeenCalledTimes(3);
await jest.advanceTimersByTimeAsync(1);
expect(invalidate).toHaveBeenCalledTimes(4);
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
await jest.advanceTimersByTimeAsync(30_000);
expect(invalidate).toHaveBeenCalledTimes(6);
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(6);
});
it.each(['immediate', 'background'] as const)(
'cancels remaining retries after a successful %s attempt',
async (attempt) => {
await service.invalidateCommunityWithRetry('community');
invalidate.mockResolvedValue(0);
if (attempt === 'immediate') {
expect(await service.invalidateCommunityWithRetry('community')).toBe(
true,
);
} else {
await jest.advanceTimersByTimeAsync(1_000);
}
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(2);
},
);
it('unrefs every retry timer so it does not keep the process alive', async () => {
const setTimeoutSpy = jest.spyOn(global, 'setTimeout');
await service.invalidateCommunityWithRetry('community');
for (const delay of [1_000, 5_000, 30_000]) {
const timer = setTimeoutSpy.mock.results.at(-1)!.value as NodeJS.Timeout;
expect(timer.hasRef()).toBe(false);
await jest.advanceTimersByTimeAsync(delay);
}
});
it('keeps different communities independent when one continues to fail', async () => {
await service.invalidateCommunityWithRetry('first');
await service.invalidateCommunityWithRetry('second');
invalidate.mockImplementation(async (id) => {
if (id === 'first') throw new Error('still unavailable');
return 1;
});
await jest.advanceTimersByTimeAsync(36_000);
expect(invalidate.mock.calls.filter(([id]) => id === 'first')).toHaveLength(
4,
);
expect(
invalidate.mock.calls.filter(([id]) => id === 'second'),
).toHaveLength(2);
expect(jest.getTimerCount()).toBe(0);
});
it('clears scheduled retries on shutdown', async () => {
await service.invalidateCommunityWithRetry('community');
service.onModuleDestroy();
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(1);
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
expect(invalidate).toHaveBeenCalledTimes(1);
});
it.each(['shutdown', 'immediate success'] as const)(
'does not reschedule an in-flight retry after %s',
async (finish) => {
await service.invalidateCommunityWithRetry('community');
const pending = deferred();
invalidate.mockImplementationOnce(() => pending.promise);
await jest.advanceTimersByTimeAsync(1_000);
expect(invalidate).toHaveBeenCalledTimes(2);
if (finish === 'shutdown') {
service.onModuleDestroy();
} else {
invalidate.mockResolvedValueOnce(1);
expect(await service.invalidateCommunityWithRetry('community')).toBe(
true,
);
}
pending.reject(new Error('late failure'));
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(finish === 'shutdown' ? 2 : 3);
expect(jest.getTimerCount()).toBe(0);
},
);
it('does not cancel a newer failed request when an older immediate attempt succeeds late', async () => {
const pending = deferred();
invalidate.mockImplementationOnce(() => pending.promise);
const first = service.invalidateCommunityWithRetry('community');
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
pending.resolve(1);
expect(await first).toBe(true);
expect(jest.getTimerCount()).toBe(1);
invalidate.mockResolvedValue(1);
await jest.advanceTimersByTimeAsync(1_000);
expect(invalidate).toHaveBeenCalledTimes(3);
expect(jest.getTimerCount()).toBe(0);
});
it('preserves the retry budget when an immediate request fails during an in-flight retry', async () => {
await service.invalidateCommunityWithRetry('community');
const pending = deferred();
invalidate.mockImplementationOnce(() => pending.promise);
await jest.advanceTimersByTimeAsync(1_000);
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
await jest.advanceTimersByTimeAsync(5_000);
expect(invalidate).toHaveBeenCalledTimes(3);
pending.resolve(1);
await jest.advanceTimersByTimeAsync(5_000);
expect(invalidate).toHaveBeenCalledTimes(4);
await jest.advanceTimersByTimeAsync(30_000);
expect(invalidate).toHaveBeenCalledTimes(5);
expect(jest.getTimerCount()).toBe(0);
});
it('does not restart an exhausted budget when an older immediate request fails late', async () => {
await service.invalidateCommunityWithRetry('community');
await jest.advanceTimersByTimeAsync(6_000);
const pending = deferred();
invalidate.mockImplementationOnce(() => pending.promise);
const immediate = service.invalidateCommunityWithRetry('community');
await jest.advanceTimersByTimeAsync(30_000);
expect(invalidate).toHaveBeenCalledTimes(5);
pending.reject(new Error('late failure'));
expect(await immediate).toBe(false);
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(5);
});
});
function deferred() {
let resolve!: (value: number) => void;
let reject!: (reason: Error) => void;
const promise = new Promise<number>((done, fail) => {
resolve = done;
reject = fail;
});
return { promise, resolve, reject };
}
@@ -1,9 +1,15 @@
import { Injectable, Logger } from '@nestjs/common'; import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
import { randomUUID } from 'crypto'; import { randomUUID } from 'crypto';
import { RedisService } from '../global/redis/redis.service'; import { RedisService } from '../global/redis/redis.service';
const COMMUNITY_STATS_TTL_SECONDS = 5 * 60; const COMMUNITY_STATS_TTL_SECONDS = 5 * 60;
const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 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 = [ const CACHE_SCOPES = [
'matches', 'matches',
'leaderboard', 'leaderboard',
@@ -64,11 +70,105 @@ return deleted
`; `;
@Injectable() @Injectable()
export class CommunityStatsCacheService { export class CommunityStatsCacheService implements OnModuleDestroy {
private readonly logger = new Logger(CommunityStatsCacheService.name); private readonly logger = new Logger(CommunityStatsCacheService.name);
private readonly invalidationRetries = new Map<string, InvalidationRetry>();
private destroyed = false;
constructor(private readonly redisService: RedisService) {} constructor(private readonly redisService: RedisService) {}
public onModuleDestroy(): void {
this.destroyed = true;
for (const pending of this.invalidationRetries.values()) {
if (pending.timer) clearTimeout(pending.timer);
}
this.invalidationRetries.clear();
}
// Only the immediate attempt determines whether the caller may cache its response.
public async invalidateCommunityWithRetry(
communityId: string,
): Promise<boolean> {
if (this.destroyed) return false;
const pending = this.invalidationRetries.get(communityId) ?? {
attempts: 0,
requestVersion: 0,
};
this.invalidationRetries.set(communityId, pending);
const version = ++pending.requestVersion;
const succeeded = await this.tryInvalidateCommunity(communityId);
if (succeeded && pending.requestVersion === version) {
this.clearInvalidationRetry(communityId, pending);
} else if (!succeeded) {
// An existing retry keeps its remaining budget, including while in flight.
this.scheduleInvalidationRetry(communityId, pending);
}
return succeeded;
}
private scheduleInvalidationRetry(
communityId: string,
pending: InvalidationRetry,
): void {
if (
this.destroyed ||
this.invalidationRetries.get(communityId) !== pending ||
pending.timer
)
return;
const delay = INVALIDATION_RETRY_DELAYS_MS[pending.attempts];
if (delay === undefined) {
this.clearInvalidationRetry(communityId, pending);
this.logger.warn(
`Stats cache invalidation retries exhausted for ${communityId}; detail recovery and cache expiry will refresh stale responses.`,
);
return;
}
pending.attempts += 1;
pending.timer = setTimeout(
() => void this.retryInvalidation(communityId, pending),
delay,
);
pending.timer.unref();
}
private async retryInvalidation(
communityId: string,
pending: InvalidationRetry,
): Promise<void> {
const version = pending.requestVersion;
const succeeded = await this.tryInvalidateCommunity(communityId);
if (this.invalidationRetries.get(communityId) !== pending) return;
pending.timer = undefined;
// An older completion must not cancel a newer request's retry.
if (succeeded && pending.requestVersion === version) {
this.clearInvalidationRetry(communityId, pending);
} else {
this.scheduleInvalidationRetry(communityId, pending);
}
}
private clearInvalidationRetry(
communityId: string,
pending: InvalidationRetry,
): void {
if (this.invalidationRetries.get(communityId) !== pending) return;
if (pending.timer) clearTimeout(pending.timer);
this.invalidationRetries.delete(communityId);
}
private async tryInvalidateCommunity(communityId: string): Promise<boolean> {
try {
await this.invalidateCommunity(communityId, 1_000);
return true;
} catch (error) {
this.logger.warn(
`Stats cache invalidation failed for ${communityId}: ${String(error)}`,
);
return false;
}
}
public async get<T>(key: CommunityStatsCacheKey): Promise<T | null> { public async get<T>(key: CommunityStatsCacheKey): Promise<T | null> {
const reply = await this.redisService const reply = await this.redisService
.raw() .raw()
@@ -117,19 +217,25 @@ export class CommunityStatsCacheService {
return this.set(key, value, COMMUNITY_STATS_DETAIL_TTL_SECONDS); return this.set(key, value, COMMUNITY_STATS_DETAIL_TTL_SECONDS);
} }
public async invalidateCommunity(communityId: string): Promise<number> { public async invalidateCommunity(
communityId: string,
timeoutMs?: number,
): Promise<number> {
const prefix = communityPrefix(communityId); const prefix = communityPrefix(communityId);
const deleted = Number( const deleted = Number(
await this.redisService await this.redisService
.raw() .raw()
.sendCommand([ .sendCommand(
'EVAL', [
INVALIDATE_CACHE_SCRIPT, 'EVAL',
String(CACHE_SCOPES.length + 1), INVALIDATE_CACHE_SCRIPT,
`${prefix}:generation`, String(CACHE_SCOPES.length + 1),
...CACHE_SCOPES.map((scope) => `${prefix}:${scope}`), `${prefix}:generation`,
randomUUID(), ...CACHE_SCOPES.map((scope) => `${prefix}:${scope}`),
]), randomUUID(),
],
timeoutMs === undefined ? undefined : { timeout: timeoutMs },
),
); );
if (deleted > 0) { if (deleted > 0) {
@@ -0,0 +1,321 @@
import mongoose from 'mongoose';
import { CommunityStatsService } from './community-stats.service';
import { CommunityStatsCacheKey } from './community-stats-cache.service';
import type { InternalMatchDetailResponse } from './community-stats.types';
describe('Community stats raw archive recovery', () => {
it.each([true, false])(
'recovers a cached missing game even if invalidation needs retry (%s)',
async (invalidationSucceeds) => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
let archived = false;
let enriched = false;
let generation = 'before';
let cached: InternalMatchDetailResponse | null = null;
const exists = jest.fn(() => query(archived ? { _id: 'archive' } : null));
const buildAndUpsert = jest.fn(async () => {
enriched = true;
});
const invalidateCommunity = jest.fn(async () => {
if (!invalidationSucceeds) return false;
cached = null;
generation = 'after';
return true;
});
const setDetail = jest.fn(
async (
key: CommunityStatsCacheKey,
value: InternalMatchDetailResponse,
) => {
expect(key.generation).toBe(generation);
cached = value;
},
);
const service = new CommunityStatsService(
{ getModel: async () => ({ exists }) } as never,
{
get: async (key: CommunityStatsCacheKey) => {
key.generation = generation;
return cached;
},
setDetail,
invalidateCommunityWithRetry: invalidateCommunity,
} as never,
{} as never,
{ buildAndUpsert } as never,
);
const internals = service as unknown as {
getDetailRevision: () => Promise<string>;
buildBaseDataset: () => Promise<unknown>;
matchDetailInFlight: Map<string, unknown>;
};
jest
.spyOn(internals, 'getDetailRevision')
.mockResolvedValue('same-revision');
jest
.spyOn(internals, 'buildBaseDataset')
.mockImplementation(async () => ({
matches: [{ matchId: matchId.toString() }],
detailsByMatchId: new Map([
[
matchId.toString(),
[
{
gameNumber: 1,
riotMatchId: 'KR_1',
rawAvailable: enriched,
timelineLoaded: enriched,
teams: [],
},
],
],
]),
competition: {
projection: {
games: [
{
id: 'official-game',
displayNumber: 1,
evidence: { type: 'riot', riotMatchId: 'KR_1' },
},
],
},
},
}));
const missing = await service.getMatchDetail({ communityId, matchId });
expect(missing.games[0].analysisAvailability).toBe('missing');
expect(await service.getMatchDetail({ communityId, matchId })).toBe(
missing,
);
expect(buildAndUpsert).not.toHaveBeenCalled();
archived = true;
const recovered = await service.getMatchDetail({ communityId, matchId });
expect(recovered.games[0]).toMatchObject({
gameId: 'official-game',
analysisAvailability: 'available',
riotMatchId: 'KR_1',
});
expect(buildAndUpsert).toHaveBeenCalledWith(matchId, {
includeTimeline: true,
});
expect(invalidateCommunity).toHaveBeenCalledWith(communityId.toString());
expect(internals.matchDetailInFlight.size).toBe(0);
expect(setDetail).toHaveBeenCalledTimes(invalidationSucceeds ? 2 : 1);
expect(await service.getMatchDetail({ communityId, matchId })).toEqual(
recovered,
);
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
},
);
it('rebuilds only affected missing fragments and invalidates every affected community after the writes', async () => {
const first = new mongoose.Types.ObjectId();
const second = new mongoose.Types.ObjectId();
const fragments = [
{
matchId: new mongoose.Types.ObjectId(),
communityId: first,
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: false }],
},
{
matchId: new mongoose.Types.ObjectId(),
communityId: first,
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: true }],
},
{
matchId: new mongoose.Types.ObjectId(),
communityId: second,
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: false }],
},
];
const order: string[] = [];
const buildAndUpsert = jest.fn(async () => {
order.push('build');
});
const invalidateCommunity = jest.fn(async () => {
order.push('invalidate');
return true;
});
const findByRiotMatchIds = jest.fn().mockResolvedValue(fragments);
const service = new CommunityStatsService(
{
getModel: async () => ({ find: () => query([{ matchId: 'KR_1' }]) }),
} as never,
{ invalidateCommunityWithRetry: invalidateCommunity } as never,
{
findByRiotMatchIds,
findByMatch: async () => ({
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: true }],
}),
} as never,
{ buildAndUpsert } as never,
);
await service.refreshForRiotMatches(['KR_1', 'KR_1', 'KR_ABSENT']);
expect(findByRiotMatchIds).toHaveBeenCalledWith(['KR_1']);
expect(buildAndUpsert.mock.calls).toEqual([
[fragments[0].matchId],
[fragments[2].matchId],
]);
expect(invalidateCommunity.mock.calls).toEqual([
[first.toString()],
[second.toString()],
]);
expect(order).toEqual(['build', 'build', 'invalidate', 'invalidate']);
});
it('does not invalidate already enriched games or builds that make no progress', async () => {
const game = { riotMatchId: 'KR_1', rawAvailable: false };
const fragment = {
matchId: new mongoose.Types.ObjectId(),
communityId: new mongoose.Types.ObjectId(),
gameDetails: [game],
};
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const invalidateCommunity = jest.fn();
const service = new CommunityStatsService(
{
getModel: async () => ({ find: () => query([{ matchId: 'KR_1' }]) }),
} as never,
{ invalidateCommunityWithRetry: invalidateCommunity } as never,
{
findByRiotMatchIds: async () => [fragment],
findByMatch: async () => fragment,
} as never,
{ buildAndUpsert } as never,
);
await service.refreshForRiotMatches(['KR_1']);
game.rawAvailable = true;
await service.refreshForRiotMatches(['KR_1']);
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
expect(invalidateCommunity).not.toHaveBeenCalled();
});
it('does not rebuild when raw is still absent', async () => {
const findByRiotMatchIds = jest.fn();
const buildAndUpsert = jest.fn();
const service = new CommunityStatsService(
{ getModel: async () => ({ find: () => query([]) }) } as never,
{} as never,
{ findByRiotMatchIds } as never,
{ buildAndUpsert } as never,
);
await service.refreshForRiotMatches(['KR_1']);
expect(findByRiotMatchIds).not.toHaveBeenCalled();
expect(buildAndUpsert).not.toHaveBeenCalled();
});
it('invalidates successful communities once even when another game fails mid-batch', async () => {
const communities = Array.from(
{ length: 4 },
() => new mongoose.Types.ObjectId(),
);
const fragments = [0, 1, 0, 2, 3].map((community, index) => ({
matchId: new mongoose.Types.ObjectId(),
communityId: communities[community],
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: index === 4 }],
}));
const buildAndUpsert = jest.fn(async (matchId: mongoose.Types.ObjectId) => {
const fragment = fragments.find((item) => item.matchId === matchId)!;
if (fragment === fragments[1]) throw new Error('one build fails');
fragment.gameDetails[0].rawAvailable = true;
});
const invalidate = jest.fn().mockResolvedValue(true);
const service = new CommunityStatsService(
{
getModel: async () => ({ find: () => query([{ matchId: 'KR_1' }]) }),
} as never,
{ invalidateCommunityWithRetry: invalidate } as never,
{
findByRiotMatchIds: async () => fragments,
findByMatch: async (id: mongoose.Types.ObjectId) =>
fragments.find((item) => item.matchId === id),
} as never,
{ buildAndUpsert } as never,
);
await service.refreshForRiotMatches(['KR_1']);
expect(buildAndUpsert).toHaveBeenCalledTimes(4);
expect(invalidate.mock.calls).toEqual([
[communities[0].toString()],
[communities[2].toString()],
]);
});
it('backs off raw recovery that makes no progress and does not invalidate the community', async () => {
let now = 1000;
const clock = jest.spyOn(Date, 'now').mockImplementation(() => now);
try {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
let cached: InternalMatchDetailResponse | null = null;
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const invalidate = jest.fn();
const service = new CommunityStatsService(
{
getModel: async () => ({ exists: () => query({ _id: 'archive' }) }),
} as never,
{
get: async () => cached,
setDetail: async (
_key: unknown,
value: InternalMatchDetailResponse,
) => {
cached = value;
},
invalidateCommunityWithRetry: invalidate,
} as never,
{} as never,
{ buildAndUpsert } as never,
);
const internals = service as unknown as {
getDetailRevision: () => Promise<string>;
buildBaseDataset: () => Promise<unknown>;
};
jest
.spyOn(internals, 'getDetailRevision')
.mockResolvedValue('same-revision');
jest.spyOn(internals, 'buildBaseDataset').mockResolvedValue({
matches: [{ matchId: matchId.toString() }],
detailsByMatchId: new Map([
[
matchId.toString(),
[
{
gameNumber: 1,
riotMatchId: 'KR_1',
rawAvailable: false,
timelineLoaded: false,
teams: [],
},
],
],
]),
});
await service.getMatchDetail({ communityId, matchId });
await service.getMatchDetail({ communityId, matchId });
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
now += 60_000;
await service.getMatchDetail({ communityId, matchId });
expect(buildAndUpsert).toHaveBeenCalledTimes(2);
expect(invalidate).not.toHaveBeenCalled();
} finally {
clock.mockRestore();
}
});
});
function query<T>(value: T) {
return {
select() {
return this;
},
lean() {
return this;
},
exec: async () => value,
};
}
@@ -1,4 +1,10 @@
import { Controller, Get, Param, Query } from '@nestjs/common'; import {
BadRequestException,
Controller,
Get,
Param,
Query,
} from '@nestjs/common';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe'; import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
@@ -9,6 +15,15 @@ import type { CommunityStatsFilters } from './community-stats.types';
export class CommunityStatsController { export class CommunityStatsController {
constructor(private readonly communityStatsService: CommunityStatsService) {} 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') @Get('internal-stats/matches')
@AllowPublicAccess() @AllowPublicAccess()
public getMatches( public getMatches(
@@ -20,7 +35,30 @@ export class CommunityStatsController {
@Query('championId') championId?: string, @Query('championId') championId?: string,
@Query('cursor') cursor?: string, @Query('cursor') cursor?: string,
@Query('limit') limit?: 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({ return this.communityStatsService.getMatches({
communityId, communityId,
filters: this.toFilters({ filters: this.toFilters({
@@ -30,6 +68,10 @@ export class CommunityStatsController {
championId, championId,
cursor, cursor,
limit, limit,
query,
format,
playerId,
cursorMatchId,
}), }),
}); });
} }
@@ -43,10 +85,11 @@ export class CommunityStatsController {
@Query('from') from?: string, @Query('from') from?: string,
@Query('to') to?: string, @Query('to') to?: string,
@Query('championId') championId?: string, @Query('championId') championId?: string,
@Query('q') query?: string,
) { ) {
return this.communityStatsService.getLeaderboard({ return this.communityStatsService.getLeaderboard({
communityId, 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; championId?: string;
cursor?: string; cursor?: string;
limit?: string; limit?: string;
query?: string;
format?: CommunityStatsFilters['format'];
playerId?: string;
cursorMatchId?: string;
}): CommunityStatsFilters { }): CommunityStatsFilters {
if (
params.query !== undefined &&
(typeof params.query !== 'string' || params.query.length > 100)
) {
throw new BadRequestException('Invalid search query.');
}
return { return {
seasonId: params.seasonId, seasonId: params.seasonId,
from: params.from, from: params.from,
@@ -118,6 +171,10 @@ export class CommunityStatsController {
championId: this.toNumber(params.championId), championId: this.toNumber(params.championId),
cursor: this.toNumber(params.cursor), cursor: this.toNumber(params.cursor),
limit: this.toNumber(params.limit), limit: this.toNumber(params.limit),
query: params.query?.trim(),
format: params.format,
playerId: params.playerId,
cursorMatchId: params.cursorMatchId,
}; };
} }
@@ -1,4 +1,4 @@
import { Module } from '@nestjs/common'; import { forwardRef, Module } from '@nestjs/common';
import { RiotModule } from '../riot/riot.module'; import { RiotModule } from '../riot/riot.module';
import { CommunityStatsCacheService } from './community-stats-cache.service'; import { CommunityStatsCacheService } from './community-stats-cache.service';
import { CommunityStatsController } from './community-stats.controller'; import { CommunityStatsController } from './community-stats.controller';
@@ -8,7 +8,7 @@ import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service'; import { MatchStatsService } from './match-stats.service';
@Module({ @Module({
imports: [RiotModule], imports: [forwardRef(() => RiotModule)],
controllers: [CommunityStatsController], controllers: [CommunityStatsController],
providers: [ providers: [
CommunityStatsService, CommunityStatsService,
@@ -86,6 +86,244 @@ function record(matchId: mongoose.Types.ObjectId): InternalRecord {
} }
describe('CommunityStatsService', () => { describe('CommunityStatsService', () => {
it('reads the official result again on a filtered page cache hit and excludes games from stale revisions', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const playerId = new mongoose.Types.ObjectId().toString();
const scheduledAt = new Date('2026-06-18T12:00:00Z');
const matchCard = {
matchId: matchId.toString(),
scheduledAt: scheduledAt.toISOString(),
games: [{ gameNumber: 1, winnerTeamIndex: 1 }],
};
const findMatchPage = jest.fn().mockResolvedValue([
{
matchId,
scheduledAt,
matchCard,
gameDetails: [{ gameNumber: 1, gameCreation: 1000 }],
sourceCompetitionId: competitionId,
sourceRevision: 4,
},
{ matchId: new mongoose.Types.ObjectId() },
]);
const source = {
_id: competitionId,
matchId,
communityId,
revision: 4,
createdAt: scheduledAt,
updatedAt: scheduledAt,
teams: [],
projection: {
phase: 'completed',
formatType: 'double-elimination',
series: [],
outcome: { type: 'double-elimination', championTeamId: 'winner' },
},
};
const find = jest.fn().mockReturnValue({
select: () => ({ lean: () => ({ exec: async () => [source] }) }),
});
let cachedPage: unknown = null;
const service = new CommunityStatsService(
{
getModel: async (name: string) =>
name === 'community'
? { findById: () => ({ exec: async () => ({ _id: communityId }) }) }
: { find },
} as unknown as ConnectionService,
{
get: async () => cachedPage,
set: async (_key: unknown, page: unknown) => {
cachedPage = JSON.parse(JSON.stringify(page));
},
} as unknown as CommunityStatsCacheService,
{ findMatchPage } as unknown as MatchStatsRepository,
{} as MatchStatsService,
);
jest
.spyOn(
service as unknown as {
repairCommunityFragments: () => Promise<number>;
},
'repairCommunityFragments',
)
.mockResolvedValue(0);
const params = {
communityId,
filters: {
seasonId: 'all',
query: '결승',
format: 'tournament' as const,
playerId,
limit: 1,
},
};
const initial = await service.getMatches(params);
expect(initial.matches[0]).toMatchObject({
games: [{ gameNumber: 1 }],
resultPresentation: {
type: 'official',
phase: 'completed',
sourceRevision: 4,
outcome: { championTeamId: 'winner' },
},
});
Object.assign(source, {
revision: 5,
projection: {
...source.projection,
phase: 'running',
outcome: undefined,
},
});
const result = await service.getMatches(params);
expect(findMatchPage).toHaveBeenCalledWith(
expect.objectContaining({
query: '결승',
format: 'tournament',
playerId,
limit: 2,
}),
);
expect(find).toHaveBeenCalledWith({
communityId,
matchId: { $in: [matchId] },
});
expect(findMatchPage).toHaveBeenCalledTimes(1);
expect(find).toHaveBeenCalledTimes(2);
expect(result.matches[0]).toMatchObject({
games: [],
resultPresentation: {
type: 'official',
competitionId: competitionId.toString(),
sourceRevision: 5,
phase: 'running',
},
});
expect(result.nextCursor).toBe(scheduledAt.getTime());
expect(result.nextCursorMatchId).toBe(matchId.toString());
});
it.each(['legacy', 'riot', 'unlinked'] as const)(
'preserves the scoreboard without retrying a missing Riot archive for %s evidence',
async (type) => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match = { matchId: matchId.toString() };
const participant = record(matchId);
const matchKey = type === 'legacy' ? 'legacy-reference' : 'KR_1';
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const set = jest.fn();
const setDetail = jest.fn();
const service = new CommunityStatsService(
{
getModel: async () => ({ exists: () => ({ exec: async () => null }) }),
} as unknown as ConnectionService,
{
get: async () => null,
set,
setDetail,
} as unknown as CommunityStatsCacheService,
{} as MatchStatsRepository,
{ buildAndUpsert } as unknown as MatchStatsService,
);
jest
.spyOn(
service as unknown as { getDetailRevision: () => Promise<string> },
'getDetailRevision',
)
.mockResolvedValue('revision-1');
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
jest.fn().mockResolvedValue({
matches: [match],
detailsByMatchId: new Map([
[
match.matchId,
[
{
gameNumber: 1,
riotMatchId: matchKey,
gameCreation: 1000,
gameDuration: 1800,
rawAvailable: false,
timelineLoaded: false,
teams: [
{
teamIndex: 1,
side: 'blue',
win: true,
objectives: objectives(),
participants: [participant],
},
],
},
],
],
]),
competition:
type === 'unlinked'
? undefined
: {
projection: {
games: [
{
id: 'game-1',
seriesId: 'series-1',
gameSlotId: 'slot-1',
ordinal: 1,
displayNumber: 1,
evidence:
type === 'legacy'
? { type, legacyReference: matchKey }
: { type, riotMatchId: matchKey },
},
],
},
},
});
const response = await service.getMatchDetail({ communityId, matchId });
const afterCacheMiss = await service.getMatchDetail({
communityId,
matchId,
});
expect(response.games).toHaveLength(1);
expect(response.games).toMatchObject([
{
...(type === 'unlinked' ? {} : { gameId: 'game-1' }),
analysisAvailability: 'missing',
teams: [
{
win: true,
participants: [
{
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
championId: participant.championId,
},
],
},
],
},
]);
expect(afterCacheMiss).toEqual(response);
expect(buildAndUpsert).not.toHaveBeenCalled();
expect(set).not.toHaveBeenCalled();
expect(setDetail).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenCalledWith(
expect.objectContaining({ field: expect.stringContaining(':r8:') }),
response,
);
},
);
it('ignores detail caches missing unified events or containing invalid checkpoints', async () => { it('ignores detail caches missing unified events or containing invalid checkpoints', async () => {
const communityId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId();
@@ -222,7 +460,13 @@ describe('CommunityStatsService', () => {
buildAndUpsert: jest.fn().mockResolvedValue(undefined), buildAndUpsert: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<MatchStatsService>; } as unknown as jest.Mocked<MatchStatsService>;
const service = new CommunityStatsService( const service = new CommunityStatsService(
{} as ConnectionService, {
getModel: jest.fn().mockResolvedValue({
findOne: () => ({
select: () => ({ lean: () => ({ exec: async () => null }) }),
}),
}),
} as unknown as ConnectionService,
cacheService, cacheService,
{} as MatchStatsRepository, {} as MatchStatsRepository,
matchStatsService, matchStatsService,
@@ -284,7 +528,7 @@ describe('CommunityStatsService', () => {
expect(setDetail).toHaveBeenCalledTimes(2); expect(setDetail).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenNthCalledWith( expect(setDetail).toHaveBeenNthCalledWith(
2, 2,
expect.objectContaining({ field: expect.stringContaining(':r4:') }), expect.objectContaining({ field: expect.stringContaining(':r8:') }),
invalidCheckpointResponse, invalidCheckpointResponse,
); );
}); });
@@ -309,6 +553,7 @@ describe('CommunityStatsService', () => {
gameCreation: 1_000, gameCreation: 1_000,
gameDuration: 1_800, gameDuration: 1_800,
winnerSide: 'blue', winnerSide: 'blue',
rawAvailable: true,
timelineLoaded: false, timelineLoaded: false,
timeline: [], timeline: [],
objectiveEvents: [], objectiveEvents: [],
@@ -361,7 +606,13 @@ describe('CommunityStatsService', () => {
} as unknown as jest.Mocked<CommunityStatsCacheService>; } as unknown as jest.Mocked<CommunityStatsCacheService>;
const buildAndUpsert = jest.fn().mockResolvedValue(undefined); const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const service = new CommunityStatsService( const service = new CommunityStatsService(
{} as ConnectionService, {
getModel: jest.fn().mockResolvedValue({
findOne: () => ({
select: () => ({ lean: () => ({ exec: async () => null }) }),
}),
}),
} as unknown as ConnectionService,
cacheService, cacheService,
{} as MatchStatsRepository, {} as MatchStatsRepository,
{ buildAndUpsert } as unknown as MatchStatsService, { buildAndUpsert } as unknown as MatchStatsService,
@@ -378,9 +629,13 @@ describe('CommunityStatsService', () => {
const backedOff = await service.getMatchDetail({ communityId, matchId }); const backedOff = await service.getMatchDetail({ communityId, matchId });
expect(backedOff).toBe(fallback); expect(backedOff).toBe(fallback);
expect(fallback.games[0].analysisAvailability).toBe('available');
expect(buildAndUpsert).toHaveBeenCalledTimes(1); expect(buildAndUpsert).toHaveBeenCalledTimes(1);
expect(buildAndUpsert).toHaveBeenCalledWith(matchId, {
includeTimeline: true,
});
expect(set).toHaveBeenCalledWith( expect(set).toHaveBeenCalledWith(
expect.objectContaining({ field: expect.stringContaining(':r4:') }), expect.objectContaining({ field: expect.stringContaining(':r8:') }),
fallback, fallback,
60, 60,
); );
@@ -392,7 +647,7 @@ describe('CommunityStatsService', () => {
expect(buildAndUpsert).toHaveBeenCalledTimes(2); expect(buildAndUpsert).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenCalledTimes(1); expect(setDetail).toHaveBeenCalledTimes(1);
expect(setDetail).toHaveBeenCalledWith( expect(setDetail).toHaveBeenCalledWith(
expect.objectContaining({ field: expect.stringContaining(':r4:') }), expect.objectContaining({ field: expect.stringContaining(':r8:') }),
recovered, recovered,
); );
}); });
@@ -459,7 +714,13 @@ describe('CommunityStatsService', () => {
setDetail, setDetail,
} as unknown as jest.Mocked<CommunityStatsCacheService>; } as unknown as jest.Mocked<CommunityStatsCacheService>;
const service = new CommunityStatsService( const service = new CommunityStatsService(
{} as ConnectionService, {
getModel: jest.fn().mockResolvedValue({
findOne: () => ({
select: () => ({ lean: () => ({ exec: async () => null }) }),
}),
}),
} as unknown as ConnectionService,
cacheService, cacheService,
{} as MatchStatsRepository, {} as MatchStatsRepository,
{} as MatchStatsService, {} as MatchStatsService,
@@ -1,3 +1,9 @@
import type {
CompetitionGameView,
GameAnalysisAvailability,
InternalMatchCompetition,
InternalMatchResultPresentation,
} from '@lolympus/contracts';
import { import {
BadRequestException, BadRequestException,
Injectable, Injectable,
@@ -5,8 +11,14 @@ import {
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import mongoose from 'mongoose'; 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 { 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 { import type {
HistorySeasonDto, HistorySeasonDto,
RecentMatchView, RecentMatchView,
@@ -43,7 +55,7 @@ const DEFAULT_LIST_LIMIT = 20;
const MAX_LIST_LIMIT = 50; const MAX_LIST_LIMIT = 50;
const MAX_MATCH_SCAN = 300; const MAX_MATCH_SCAN = 300;
const MIN_HIGHLIGHT_GAMES = 5; 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; const INCOMPLETE_MATCH_DETAIL_TTL_SECONDS = 60;
interface CommunityStatsContext { interface CommunityStatsContext {
@@ -58,6 +70,15 @@ interface BaseDataset {
matches: InternalMatchCardView[]; matches: InternalMatchCardView[];
records: InternalRecord[]; records: InternalRecord[];
detailsByMatchId: Map<string, InternalGameDetail[]>; detailsByMatchId: Map<string, InternalGameDetail[]>;
competition?: InternalMatchCompetition;
}
interface CachedMatchPage extends Omit<InternalMatchListResponse, 'matches'> {
cards: Array<{
card: InternalMatchCardView;
sourceCompetitionId?: string;
sourceRevision?: number;
}>;
} }
@Injectable() @Injectable()
@@ -71,6 +92,8 @@ export class CommunityStatsService {
string, string,
Promise<UserInternalHistoryResponse> Promise<UserInternalHistoryResponse>
>(); >();
private readonly fragmentRepairs = new Map<string, Promise<number>>();
private readonly rawRecoveryRetryAfter = new Map<string, number>();
constructor( constructor(
private readonly connectionService: ConnectionService, private readonly connectionService: ConnectionService,
@@ -84,67 +107,141 @@ export class CommunityStatsService {
filters: CommunityStatsFilters; filters: CommunityStatsFilters;
}): Promise<InternalMatchListResponse> { }): Promise<InternalMatchListResponse> {
const key = this.cacheKey('matches', params.communityId, params.filters); const key = this.cacheKey('matches', params.communityId, params.filters);
const cached = await this.cacheService.get<InternalMatchListResponse>(key); const cached = await this.cacheService.get<CachedMatchPage>(key);
if (cached) return cached; const page =
cached ?? (await this.loadMatchPage(params.communityId, params.filters));
if (!cached) await this.cacheService.set(key, page);
const { cards, ...pagination } = page;
if (cards.length === 0) return { ...pagination, matches: [] };
const matchIds = cards.map(
({ card }) => new mongoose.Types.ObjectId(card.matchId),
);
const CompetitionModel =
await this.connectionService.getModel('competition');
const competitions = await CompetitionModel.find({
communityId: params.communityId,
matchId: { $in: matchIds },
})
.select({
matchId: 1,
communityId: 1,
schemaVersion: 1,
revision: 1,
phase: 1,
format: 1,
createdAt: 1,
updatedAt: 1,
'teams.teamId': 1,
'teams.name': 1,
'teams.displayOrder': 1,
'projection.phase': 1,
'projection.formatType': 1,
'projection.outcome': 1,
'projection.series': 1,
})
.lean()
.exec();
const official = new Map(
competitions.map((competition) => [
competition.matchId.toString(),
this.presentOfficialResult(competition),
]),
);
return {
...pagination,
matches: cards.map(({ card, sourceCompetitionId, sourceRevision }) => {
const resultPresentation = official.get(card.matchId) ?? {
type: sourceCompetitionId
? ('unavailable' as const)
: ('legacy' as const),
};
const canUseGames =
resultPresentation.type === 'legacy' ||
(resultPresentation.type === 'official' &&
sourceCompetitionId === resultPresentation.competitionId &&
sourceRevision === resultPresentation.sourceRevision);
return {
...(canUseGames ? card : this.adjustCardForRange(card, [])),
resultPresentation,
};
}),
};
}
private async loadMatchPage(
communityId: mongoose.Types.ObjectId,
filters: CommunityStatsFilters,
): Promise<CachedMatchPage> {
const limit = this.clampLimit( const limit = this.clampLimit(
params.filters.limit, filters.limit,
DEFAULT_LIST_LIMIT, DEFAULT_LIST_LIMIT,
MAX_LIST_LIMIT, MAX_LIST_LIMIT,
); );
const dataset = await this.buildBaseDataset( const context = await this.resolveContext(communityId, filters);
params.communityId, await this.repairCommunityFragments(communityId);
params.filters, const page = await this.matchStatsRepository.findMatchPage({
); ...filters,
const filtered = params.filters.championId communityId,
? dataset.matches.filter((match) => from: context.from?.getTime(),
dataset.records.some( to: context.to?.getTime(),
(record) => limit: limit + 1,
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 visible = page.slice(0, limit); const visible = page.slice(0, limit);
const response: InternalMatchListResponse = { const last = page.length > limit ? visible.at(-1) : undefined;
matches: visible, return {
nextCursor: cards: visible.map((fragment) => ({
page.length > limit card: this.adjustCardForRange(
? new Date(visible[visible.length - 1]?.scheduledAt ?? 0).getTime() fragment.matchCard as unknown as InternalMatchCardView,
: null, (fragment.gameDetails ?? []).filter((game) =>
season: dataset.season, 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: { public async getLeaderboard(params: {
communityId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId;
filters: CommunityStatsFilters; filters: CommunityStatsFilters;
}): Promise<LeaderboardResponse> { }): Promise<LeaderboardResponse> {
const key = this.cacheKey( const { query, ...filters } = params.filters;
'leaderboard', const key = this.cacheKey('leaderboard', params.communityId, filters);
params.communityId, let response = await this.cacheService.get<LeaderboardResponse>(key);
params.filters, if (!response) {
); const dataset = await this.buildSeasonDataset(
const cached = await this.cacheService.get<LeaderboardResponse>(key); params.communityId,
if (cached) return cached; filters,
);
const dataset = await this.buildBaseDataset( const records = this.applyChampionFilter(dataset.records, filters);
params.communityId, response = {
params.filters, rows: this.buildLeaderboardRows(records),
); season: dataset.season,
const records = this.applyChampionFilter(dataset.records, params.filters); };
const rows = this.buildLeaderboardRows(records); await this.cacheService.set(key, response);
const response = { rows, season: dataset.season }; }
await this.cacheService.set(key, response); const keyword = query?.toLocaleLowerCase('ko-KR');
return response; 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: { public async getTeamInsights(params: {
@@ -159,13 +256,13 @@ export class CommunityStatsService {
const cached = await this.cacheService.get<TeamInsightsResponse>(key); const cached = await this.cacheService.get<TeamInsightsResponse>(key);
if (cached) return cached; if (cached) return cached;
const dataset = await this.buildBaseDataset( const dataset = await this.buildSeasonDataset(
params.communityId, params.communityId,
params.filters, params.filters,
); );
const records = this.applyChampionFilter(dataset.records, params.filters); const records = this.applyChampionFilter(dataset.records, params.filters);
const rows = this.buildLeaderboardRows(records); const rows = this.buildLeaderboardRows(records);
const gameDetails = [...dataset.detailsByMatchId.values()].flat(); const gameDetails = dataset.gameDetails;
const blueGames = gameDetails.length; const blueGames = gameDetails.length;
const redGames = gameDetails.length; const redGames = gameDetails.length;
const blueWins = gameDetails.filter( const blueWins = gameDetails.filter(
@@ -174,6 +271,7 @@ export class CommunityStatsService {
const redWins = gameDetails.filter( const redWins = gameDetails.filter(
(game) => game.winnerSide === 'red', (game) => game.winnerSide === 'red',
).length; ).length;
const confirmedGames = blueWins + redWins;
const response: TeamInsightsResponse = { const response: TeamInsightsResponse = {
season: dataset.season, season: dataset.season,
@@ -182,6 +280,11 @@ export class CommunityStatsService {
red: this.percent(redWins, redGames), red: this.percent(redWins, redGames),
bluePicks: blueGames, bluePicks: blueGames,
redPicks: redGames, redPicks: redGames,
confirmed: {
sampleSize: confirmedGames,
blue: this.percent(blueWins, confirmedGames),
red: this.percent(redWins, confirmedGames),
},
}, },
topKda: this.toHighlight( topKda: this.toHighlight(
rows rows
@@ -222,29 +325,56 @@ export class CommunityStatsService {
communityId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId;
}): Promise<InternalMatchDetailResponse> { }): Promise<InternalMatchDetailResponse> {
const revision = await this.getDetailRevision(
params.communityId,
params.matchId,
);
const key = new CommunityStatsCacheKey( const key = new CommunityStatsCacheKey(
params.communityId.toString(), params.communityId.toString(),
'matchDetail', '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 = const cached =
await this.cacheService.get<InternalMatchDetailResponse>(key); await this.cacheService.get<InternalMatchDetailResponse>(key);
if (cached && isCompleteMatchDetailResponse(cached)) return cached; if (
cached &&
isCompleteMatchDetailResponse(cached) &&
(!this.canRetryRawRecovery(key) ||
!(await this.hasArchivedMissingRaw(cached.games, cached.competition)))
) {
return cached;
}
const inFlight = this.matchDetailInFlight.get(key.identity); const identity = key.identity;
const inFlight = this.matchDetailInFlight.get(identity);
if (inFlight) return inFlight; if (inFlight) return inFlight;
const promise = this.buildMatchDetailResponse(params, key); const promise = this.buildMatchDetailResponse(params, key);
this.matchDetailInFlight.set(key.identity, promise); this.matchDetailInFlight.set(identity, promise);
try { try {
return await promise; return await promise;
} finally { } finally {
if (this.matchDetailInFlight.get(key.identity) === promise) { if (this.matchDetailInFlight.get(identity) === promise) {
this.matchDetailInFlight.delete(key.identity); this.matchDetailInFlight.delete(identity);
} }
} }
} }
private async getDetailRevision(
communityId: mongoose.Types.ObjectId,
matchId: mongoose.Types.ObjectId,
): Promise<string> {
const CompetitionModel =
await this.connectionService.getModel('competition');
const source = await CompetitionModel.findOne({ communityId, matchId })
.select({ _id: 1, revision: 1, projectorVersion: 1 })
.lean()
.exec();
return source
? `${source._id.toString()}:${source.revision}:${source.projectorVersion}`
: 'legacy';
}
private async buildMatchDetailResponse( private async buildMatchDetailResponse(
params: { params: {
communityId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId;
@@ -252,27 +382,101 @@ export class CommunityStatsService {
}, },
key: CommunityStatsCacheKey, key: CommunityStatsCacheKey,
): Promise<InternalMatchDetailResponse> { ): Promise<InternalMatchDetailResponse> {
const dataset = await this.buildBaseDataset(params.communityId, { let dataset = await this.buildBaseDataset(
seasonId: 'all', params.communityId,
}); {
const match = dataset.matches.find( seasonId: 'all',
},
params.matchId,
);
let match = dataset.matches.find(
(item) => item.matchId === params.matchId.toString(), (item) => item.matchId === params.matchId.toString(),
); );
if (!match) throw new NotFoundException('Internal match not found.'); if (!match) throw new NotFoundException('Internal match not found.');
let gameDetails = dataset.detailsByMatchId.get(match.matchId) ?? []; let games = linkDetailGames(dataset, match.matchId);
if (gameDetails.some((game) => game.timelineLoaded !== true)) { 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, { await this.matchStatsService.buildAndUpsert(params.matchId, {
includeTimeline: true, includeTimeline: true,
}); });
const refreshedDataset = await this.buildBaseDataset(params.communityId, { const refreshedDataset = await this.buildBaseDataset(
seasonId: 'all', params.communityId,
}); {
gameDetails = refreshedDataset.detailsByMatchId.get(match.matchId) ?? []; 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 = { const response: InternalMatchDetailResponse = {
match, match,
games: gameDetails.map((game) => ({ competition: dataset.competition,
games: games.map(({ game, official, analysisAvailability }) => ({
gameNumber: game.gameNumber, gameNumber: game.gameNumber,
analysisAvailability,
...(official
? {
gameId: official.id,
gameSlotId: official.gameSlotId,
seriesId: official.seriesId,
ordinal: official.ordinal,
}
: {}),
riotMatchId: game.riotMatchId, riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation, gameCreation: game.gameCreation,
gameDuration: game.gameDuration, 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); await this.cacheService.setDetail(key, response);
} else { } else {
await this.cacheService.set( await this.cacheService.set(
@@ -367,65 +576,260 @@ export class CommunityStatsService {
} }
} }
public async refreshForRiotMatches(riotMatchIds: string[]): Promise<void> {
if (riotMatchIds.length === 0) return;
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const archived = await RiotMatchModel.find({
matchId: { $in: [...new Set(riotMatchIds)] },
'raw.info': { $exists: true },
})
.select({ matchId: 1 })
.lean()
.exec();
const ids = new Set(archived.map((match) => match.matchId));
if (ids.size === 0) return;
const fragments = await this.matchStatsRepository.findByRiotMatchIds([
...ids,
]);
const communityIds = new Map<string, mongoose.Types.ObjectId>();
for (const fragment of fragments) {
const missingIds = new Set(
fragment.gameDetails
.filter(
(game) => ids.has(game.riotMatchId) && game.rawAvailable === false,
)
.map((game) => game.riotMatchId),
);
if (missingIds.size === 0) continue;
try {
// Raw enrichment must run even when the Competition revision is current.
await this.matchStatsService.buildAndUpsert(fragment.matchId);
} catch (error) {
this.logger.warn(
`Stats recovery failed for ${fragment.matchId.toString()}: ${String(error)}`,
);
}
try {
// A builder can return without writing, or fail during post-write checks.
// Only actual enrichment should cause a community-wide invalidation.
const updated = await this.matchStatsRepository.findByMatch(
fragment.matchId,
);
if (
updated?.gameDetails.some(
(game) =>
missingIds.has(game.riotMatchId) && game.rawAvailable === true,
)
) {
communityIds.set(
fragment.communityId.toString(),
fragment.communityId,
);
}
} catch (error) {
this.logger.warn(
`Could not verify stats recovery for ${fragment.matchId.toString()}: ${String(error)}`,
);
}
}
for (const communityId of communityIds.values()) {
await this.cacheService.invalidateCommunityWithRetry(
communityId.toString(),
);
}
}
private canRetryRawRecovery(key: CommunityStatsCacheKey): boolean {
return (this.rawRecoveryRetryAfter.get(key.field) ?? 0) <= Date.now();
}
private deferRawRecovery(key: CommunityStatsCacheKey): void {
const now = Date.now();
for (const [field, retryAt] of this.rawRecoveryRetryAfter) {
if (retryAt <= now) this.rawRecoveryRetryAfter.delete(field);
}
if (this.rawRecoveryRetryAfter.size >= 1000) {
this.rawRecoveryRetryAfter.delete(
this.rawRecoveryRetryAfter.keys().next().value!,
);
}
this.rawRecoveryRetryAfter.set(
key.field,
now + INCOMPLETE_MATCH_DETAIL_TTL_SECONDS * 1000,
);
}
private async hasArchivedMissingRaw(
games: Array<
Pick<
InternalMatchDetailResponse['games'][number],
'riotMatchId' | 'gameId' | 'analysisAvailability'
>
>,
competition?: InternalMatchCompetition,
): Promise<boolean> {
const officialById = new Map(
competition?.projection.games.map((game) => [game.id, game]),
);
const ids = games
.filter(
(game) =>
game.analysisAvailability === 'missing' &&
(!competition ||
(game.gameId &&
officialById.get(game.gameId)?.evidence.type === 'riot')),
)
.map((game) => game.riotMatchId);
if (ids.length === 0) return false;
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
return Boolean(
await RiotMatchModel.exists({
matchId: { $in: ids },
'raw.info': { $exists: true },
}).exec(),
);
}
public invalidateCommunity( public invalidateCommunity(
communityId: mongoose.Types.ObjectId, communityId: mongoose.Types.ObjectId,
): Promise<number> { ): Promise<number> {
return this.cacheService.invalidateCommunity(communityId.toString()); return this.cacheService.invalidateCommunity(communityId.toString());
} }
private async buildBaseDataset( private async buildSeasonDataset(
communityId: mongoose.Types.ObjectId, communityId: mongoose.Types.ObjectId,
filters: CommunityStatsFilters, filters: CommunityStatsFilters,
): Promise<BaseDataset> { ) {
const context = await this.resolveContext(communityId, filters); const context = await this.resolveContext(communityId, filters);
let fragments = await this.matchStatsRepository.findByCommunity({ await this.repairCommunityFragments(communityId);
const fragments = await this.matchStatsRepository.findSeasonStats({
communityId, communityId,
fromGameCreation: context.from?.getTime(), from: context.from?.getTime(),
toGameCreation: context.to?.getTime(), to: context.to?.getTime(),
limit: MAX_MATCH_SCAN,
}); });
const rebuilt = await this.rebuildMissingOrStaleFragments(communityId); const gameDetails: Array<Pick<InternalGameDetail, 'winnerSide'>> = [];
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 records: InternalRecord[] = []; const records: InternalRecord[] = [];
const detailsByMatchId = new Map<string, InternalGameDetail[]>();
for (const fragment of fragments) { for (const fragment of fragments) {
const filteredGames = fragment.gameDetails const games = fragment.gameDetails.filter((game) =>
.filter((game) => this.isGameInRange(game.gameCreation, context)) 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 gameNumbers = new Set(games.map(({ gameNumber }) => gameNumber));
gameDetails.push(...games);
records.push( records.push(
...fragment.records.filter((record) => ...fragment.records.filter(({ gameNumber }) =>
allowedGameNumbers.has(record.gameNumber), gameNumbers.has(gameNumber),
), ),
); );
} }
return { season: context.season, records, gameDetails };
}
private async buildBaseDataset(
communityId: mongoose.Types.ObjectId,
filters: CommunityStatsFilters,
matchId: mongoose.Types.ObjectId,
): Promise<BaseDataset> {
const context = await this.resolveContext(communityId, filters);
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findOne({ _id: matchId, communityId })
.lean()
.exec();
if (!match) throw new NotFoundException('Internal match not found.');
const CompetitionModel =
await this.connectionService.getModel('competition');
const [source, stored] = await Promise.all([
CompetitionModel.findOne({ matchId, communityId }).lean().exec(),
this.matchStatsRepository.findByMatch(matchId),
]);
const isCurrent = (fragment: MatchStatsDocument | null) =>
Boolean(
fragment?.communityId.equals(communityId) &&
fragment.builderVersion >= MATCH_STATS_BUILDER_VERSION &&
(source
? fragment.sourceCompetitionId?.equals(source._id) &&
fragment.sourceRevision === source.revision &&
fragment.projectorVersion === source.projectorVersion
: !fragment.sourceCompetitionId && !match.competitionId),
);
let fragment = stored;
if (!isCurrent(fragment) && (source || match.result?.games.length)) {
await this.matchStatsService.buildAndUpsert(matchId);
fragment = await this.matchStatsRepository.findByMatch(matchId);
}
if (!isCurrent(fragment)) fragment = null;
if (!fragment && !source && !match.competitionId) {
throw new NotFoundException('Internal match not found.');
}
const competition =
source &&
presentCompetitionDetail({
...source,
teams: source.teams.map((team) => ({
...team,
members: team.members.map((member) => ({ ...member })),
})),
});
const resultPresentation: InternalMatchResultPresentation = source
? this.presentOfficialResult(source)
: { type: match.competitionId ? 'unavailable' : 'legacy' };
const card = (fragment?.matchCard as unknown as
| InternalMatchCardView
| undefined) ?? {
matchId: matchId.toString(),
title: match.title,
scheduledAt: match.scheduledAt.toISOString(),
status: match.status === 'finished' ? 'finished' : 'in-progress',
gameCount: match.gameCount,
seriesResults: [],
games: [],
teams: match.teams.map(({ teamIndex, name }) => ({
teamIndex,
name,
members: [],
})),
};
return { return {
season: context.season, season: context.season,
matches: cards, matches: [{ ...card, resultPresentation }],
records, records: fragment?.records ?? [],
detailsByMatchId, 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, params.filters,
); );
const userId = params.userId.toString(); const userId = params.userId.toString();
const fragments = await this.matchStatsRepository.findUserRecordFragments({ const fragmentQuery = {
communityId: params.communityId, communityId: params.communityId,
userId: params.userId, userId: params.userId,
fromGameCreation: context.from?.getTime(), fromGameCreation: context.from?.getTime(),
toGameCreation: context.to?.getTime(), toGameCreation: context.to?.getTime(),
limit: MAX_MATCH_SCAN, 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 allUserRecords = this.extractUserRecords(fragments, userId, context);
const records = this.applyChampionFilter(allUserRecords, params.filters); const records = this.applyChampionFilter(allUserRecords, params.filters);
const limit = this.clampLimit(params.filters.limit, 30, 50); const limit = this.clampLimit(params.filters.limit, 30, 50);
@@ -621,9 +1037,22 @@ export class CommunityStatsService {
return rebuilt; 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( private adjustCardForRange(
card: InternalMatchCardView, card: InternalMatchCardView,
filteredGames: InternalGameDetail[], filteredGames: Pick<InternalGameDetail, 'gameNumber'>[],
): InternalMatchCardView { ): InternalMatchCardView {
const allowedGameNumbers = new Set( const allowedGameNumbers = new Set(
filteredGames.map((game) => game.gameNumber), filteredGames.map((game) => game.gameNumber),
@@ -706,13 +1135,20 @@ export class CommunityStatsService {
: season.startedAt : season.startedAt
? new Date(season.startedAt) ? new Date(season.startedAt)
: null; : 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())) { if (from && Number.isNaN(from.getTime())) {
throw new BadRequestException('Invalid from date.'); throw new BadRequestException('Invalid from date.');
} }
if (to && Number.isNaN(to.getTime())) { if (to && Number.isNaN(to.getTime())) {
throw new BadRequestException('Invalid to date.'); throw new BadRequestException('Invalid to date.');
} }
if (from && to && from.getTime() > to.getTime()) {
throw new BadRequestException('Invalid date range.');
}
return { community, season, from, to }; return { community, season, from, to };
} }
@@ -761,7 +1197,9 @@ export class CommunityStatsService {
private buildLeaderboardRows(records: InternalRecord[]): LeaderboardRow[] { private buildLeaderboardRows(records: InternalRecord[]): LeaderboardRow[] {
const byUser = new Map<string, InternalRecord[]>(); const byUser = new Map<string, InternalRecord[]>();
for (const record of records) { 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()] return [...byUser.entries()]
.map(([userId, rows]) => this.toLeaderboardRow(userId, rows)) .map(([userId, rows]) => this.toLeaderboardRow(userId, rows))
@@ -816,6 +1254,7 @@ export class CommunityStatsService {
return { return {
userId, userId,
summonerName: first?.summonerName ?? 'Unknown', summonerName: first?.summonerName ?? 'Unknown',
tagLine: first?.tagLine || undefined,
profileIconId: first?.profileIconId ?? 0, profileIconId: first?.profileIconId ?? 0,
games: records.length, games: records.length,
wins, wins,
@@ -907,10 +1346,22 @@ export class CommunityStatsService {
totalKills: kills, totalKills: kills,
totalDeaths: deaths, totalDeaths: deaths,
totalAssists: assists, totalAssists: assists,
doubleKills: 0, doubleKills: rows.reduce(
tripleKills: 0, (sum, row) => sum + (row.multiKills?.doubleKills ?? 0),
quadraKills: 0, 0,
pentaKills: 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), avgCs: this.average(this.sum(rows, 'cs'), rows.length),
avgCsPerMin: this.average(this.sum(rows, 'cs'), gameMinutes), avgCsPerMin: this.average(this.sum(rows, 'cs'), gameMinutes),
}; };
@@ -980,6 +1431,7 @@ export class CommunityStatsService {
championLevel: record.championLevel, championLevel: record.championLevel,
teamPosition: record.teamPosition, teamPosition: record.teamPosition,
kills: record.kills, kills: record.kills,
largestMultiKill: record.multiKills?.largestMultiKill,
deaths: record.deaths, deaths: record.deaths,
assists: record.assists, assists: record.assists,
kda: this.kda(record.kills, record.deaths, record.assists), kda: this.kda(record.kills, record.deaths, record.assists),
@@ -1006,6 +1458,14 @@ export class CommunityStatsService {
puuid: participant.userId, puuid: participant.userId,
gameName: participant.summonerName, gameName: participant.summonerName,
tagLine: '', 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, championId: participant.championId,
championLevel: participant.championLevel, championLevel: participant.championLevel,
teamPosition: participant.teamPosition, teamPosition: participant.teamPosition,
@@ -1161,13 +1621,18 @@ export class CommunityStatsService {
communityId.toString(), communityId.toString(),
cacheScope, cacheScope,
JSON.stringify([ JSON.stringify([
scope, MATCH_STATS_BUILDER_VERSION,
scope === 'matches' ? 'matches-page-v1' : scope,
filters.seasonId ?? 'current', filters.seasonId ?? 'current',
filters.from ?? '', filters.from ?? '',
filters.to ?? '', filters.to ?? '',
filters.championId ?? '', filters.championId ?? '',
filters.cursor ?? '', filters.cursor ?? '',
filters.limit ?? '', filters.limit ?? '',
filters.query ?? '',
filters.format ?? '',
filters.playerId ?? '',
filters.cursorMatchId ?? '',
]), ]),
); );
} }
@@ -1210,6 +1675,46 @@ export class CommunityStatsService {
} }
} }
interface LinkedDetailGame {
game: InternalGameDetail;
official?: CompetitionGameView;
analysisAvailability: GameAnalysisAvailability;
}
function linkDetailGames(
dataset: BaseDataset,
matchId: string,
): LinkedDetailGame[] {
const officialByEvidence = new Map<string, CompetitionGameView | null>();
for (const game of dataset.competition?.projection.games ?? []) {
const evidence =
game.evidence.type === 'riot'
? game.evidence.riotMatchId
: game.evidence.legacyReference;
const key = JSON.stringify([game.displayNumber, evidence]);
officialByEvidence.set(key, officialByEvidence.has(key) ? null : game);
}
return (dataset.detailsByMatchId.get(matchId) ?? []).flatMap((game) => {
const official = officialByEvidence.get(
JSON.stringify([game.gameNumber, game.riotMatchId]),
);
if (dataset.competition && !official) return [];
// A Riot ID is evidence, not a pending raw fetch. Detail hydration only
// fetches timelines for matches whose raw data is already archived.
const analysisAvailability: GameAnalysisAvailability =
game.rawAvailable === false ? 'missing' : 'available';
return [{ game, official: official ?? undefined, analysisAvailability }];
});
}
function needsDetailHydration({
game,
analysisAvailability,
}: LinkedDetailGame) {
return analysisAvailability === 'available' && game.timelineLoaded !== true;
}
function isCompleteMatchDetailResponse( function isCompleteMatchDetailResponse(
response: InternalMatchDetailResponse, response: InternalMatchDetailResponse,
): boolean { ): boolean {
@@ -1,3 +1,11 @@
import type {
GameAnalysisAvailability,
GameId,
GameSlotId,
InternalMatchCompetition,
InternalMatchResultPresentation,
SeriesId,
} from '@lolympus/contracts';
import type { import type {
MatchStatsParticipantCheckpoints, MatchStatsParticipantCheckpoints,
MatchStatsItemBuildEvent, MatchStatsItemBuildEvent,
@@ -19,11 +27,16 @@ export interface CommunityStatsFilters {
championId?: number; championId?: number;
cursor?: number; cursor?: number;
limit?: number; limit?: number;
query?: string;
format?: 'pair' | 'tournament';
playerId?: string;
cursorMatchId?: string;
} }
export interface InternalMatchListResponse { export interface InternalMatchListResponse {
matches: InternalMatchCardView[]; matches: InternalMatchCardView[];
nextCursor: number | null; nextCursor: number | null;
nextCursorMatchId?: string;
season: HistorySeasonDto; season: HistorySeasonDto;
} }
@@ -34,6 +47,7 @@ export interface InternalMatchCardView {
status: 'finished' | 'in-progress'; status: 'finished' | 'in-progress';
gameCount: number; gameCount: number;
winnerTeamIndex?: number; winnerTeamIndex?: number;
resultPresentation?: InternalMatchResultPresentation;
seriesResults: Array<{ seriesResults: Array<{
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
@@ -64,11 +78,13 @@ export interface InternalMatchCardView {
export interface LeaderboardResponse { export interface LeaderboardResponse {
rows: LeaderboardRow[]; rows: LeaderboardRow[];
season: HistorySeasonDto; season: HistorySeasonDto;
matchedUserIds?: string[];
} }
export interface LeaderboardRow { export interface LeaderboardRow {
userId: string; userId: string;
summonerName: string; summonerName: string;
tagLine?: string;
profileIconId: number; profileIconId: number;
games: number; games: number;
wins: number; wins: number;
@@ -105,6 +121,7 @@ export interface TeamInsightsResponse {
red: number; red: number;
bluePicks: number; bluePicks: number;
redPicks: number; redPicks: number;
confirmed: { sampleSize: number; blue: number; red: number };
}; };
topKda: LeaderHighlight | null; topKda: LeaderHighlight | null;
mostKills: LeaderHighlight | null; mostKills: LeaderHighlight | null;
@@ -116,8 +133,14 @@ export interface TeamInsightsResponse {
export interface InternalMatchDetailResponse { export interface InternalMatchDetailResponse {
match: InternalMatchCardView; match: InternalMatchCardView;
competition?: InternalMatchCompetition;
games: Array<{ games: Array<{
gameNumber: number; gameNumber: number;
gameId?: GameId;
analysisAvailability?: GameAnalysisAvailability;
gameSlotId?: GameSlotId;
seriesId?: SeriesId;
ordinal?: number;
riotMatchId: string; riotMatchId: string;
gameCreation: number; gameCreation: number;
gameDuration: number; gameDuration: number;
@@ -1,4 +1,5 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { readMultiKills } from '../riot/riot-multi-kill';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import type { import type {
MatchDocument, MatchDocument,
@@ -183,6 +184,7 @@ export class MatchStatsFragmentBuilder {
winnerSide: game.winnerSide, winnerSide: game.winnerSide,
timeline: this.toTimeline(raw, rawTeamIdBySide, usableTimeline), timeline: this.toTimeline(raw, rawTeamIdBySide, usableTimeline),
timelineLoaded: Boolean(usableTimeline), timelineLoaded: Boolean(usableTimeline),
rawAvailable: true,
objectiveEvents, objectiveEvents,
timelineEvents, timelineEvents,
teams: (['blue', 'red'] as TeamSide[]).map((side) => { teams: (['blue', 'red'] as TeamSide[]).map((side) => {
@@ -253,6 +255,7 @@ export class MatchStatsFragmentBuilder {
winnerSide: game.winnerSide, winnerSide: game.winnerSide,
timeline: [], timeline: [],
timelineLoaded: false, timelineLoaded: false,
rawAvailable: false,
objectiveEvents: [], objectiveEvents: [],
timelineEvents: [], timelineEvents: [],
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({ teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
@@ -349,6 +352,8 @@ export class MatchStatsFragmentBuilder {
rawParticipant?.individualPosition || rawParticipant?.individualPosition ||
'', '',
kills: participant.kills, kills: participant.kills,
multiKills: readMultiKills(rawParticipant),
tier: snapshot?.tier,
deaths: participant.deaths, deaths: participant.deaths,
assists: participant.assists, assists: participant.assists,
win: participant.win, win: participant.win,
@@ -5,7 +5,7 @@ import type { MatchStats, MatchStatsDocument } from '../global/database/schema';
export type MatchStatsUserRecordFragment = Pick< export type MatchStatsUserRecordFragment = Pick<
MatchStats, MatchStats,
'matchId' | 'records' 'matchId' | 'records' | 'builderVersion'
>; >;
export type MatchStatsDetailFragment = Pick< export type MatchStatsDetailFragment = Pick<
@@ -152,6 +152,111 @@ export class MatchStatsRepository {
return MatchStatsModel.findOne({ matchId }).exec(); return MatchStatsModel.findOne({ matchId }).exec();
} }
public async findByRiotMatchIds(riotMatchIds: string[]) {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
return MatchStatsModel.find({
'gameDetails.riotMatchId': { $in: riotMatchIds },
})
.select({
matchId: 1,
communityId: 1,
'gameDetails.riotMatchId': 1,
'gameDetails.rawAvailable': 1,
})
.lean()
.exec();
}
public async findMatchPage(params: {
communityId: mongoose.Types.ObjectId;
from?: number;
to?: number;
query?: string;
format?: 'pair' | 'tournament';
playerId?: string;
championId?: number;
cursor?: number;
cursorMatchId?: string;
limit: number;
}) {
const model = await this.connectionService.getModel('matchStats');
const filter: Record<string, unknown> = { communityId: params.communityId };
const conditions: Array<Record<string, unknown>> = [];
const gameCreation = {
...(params.from === undefined ? {} : { $gte: params.from }),
...(params.to === undefined ? {} : { $lte: params.to }),
};
if (Object.keys(gameCreation).length > 0) {
conditions.push({
$or: [
{ gameDetails: { $elemMatch: { gameCreation } } },
{
'gameDetails.0': { $exists: false },
gameCreationMin: gameCreation,
},
],
});
}
if (params.from !== undefined)
filter.gameCreationMax = { $gte: params.from };
if (params.to !== undefined) filter.gameCreationMin = { $lte: params.to };
if (params.championId) {
filter.records = {
$elemMatch: {
championId: params.championId,
...(Object.keys(gameCreation).length > 0 ? { gameCreation } : {}),
},
};
}
if (params.query) {
filter['matchCard.title'] = {
$regex: params.query.replace(/[.*+?^$\x7b\x7d()|[\]\\]/g, '\\$&'),
$options: 'i',
};
}
if (params.format) {
filter['matchCard.teams.1'] = { $exists: true };
filter['matchCard.teams.2'] = { $exists: params.format === 'tournament' };
}
if (params.playerId) {
filter['matchCard.teams.members.userId'] = params.playerId;
}
if (params.cursor !== undefined) {
const cursor = new Date(params.cursor);
if (params.cursorMatchId) {
conditions.push({
$or: [
{ scheduledAt: { $lt: cursor } },
{
scheduledAt: cursor,
matchId: {
$lt: new mongoose.Types.ObjectId(params.cursorMatchId),
},
},
],
});
} else {
filter.scheduledAt = { $lt: cursor };
}
}
if (conditions.length > 0) filter.$and = conditions;
return model
.find(filter)
.select({
matchId: 1,
scheduledAt: 1,
matchCard: 1,
sourceCompetitionId: 1,
sourceRevision: 1,
'gameDetails.gameNumber': 1,
'gameDetails.gameCreation': 1,
})
.sort({ scheduledAt: -1, matchId: -1 })
.limit(params.limit)
.lean()
.exec();
}
public async findByCommunity(params: { public async findByCommunity(params: {
communityId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId;
fromGameCreation?: number; fromGameCreation?: number;
@@ -175,6 +280,51 @@ export class MatchStatsRepository {
.exec(); .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: { public async findByUser(params: {
communityId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId;
@@ -202,7 +352,7 @@ export class MatchStatsRepository {
return MatchStatsModel.find(filter) return MatchStatsModel.find(filter)
.sort({ scheduledAt: -1 }) .sort({ scheduledAt: -1 })
.limit(params.limit ?? 300) .limit(params.limit ?? 300)
.select({ _id: 0, matchId: 1, records: 1 }) .select({ _id: 0, matchId: 1, records: 1, builderVersion: 1 })
.lean<MatchStatsUserRecordFragment[]>() .lean<MatchStatsUserRecordFragment[]>()
.exec(); .exec();
} }
@@ -47,7 +47,7 @@ export class MatchStatsService {
? competitionStatsSource(match, competition) ? competitionStatsSource(match, competition)
: undefined; : undefined;
const sourceMatch = competitionSource?.match ?? match; const sourceMatch = competitionSource?.match ?? match;
if (!this.isEligible(sourceMatch)) { if (!this.isEligible(sourceMatch) && competition?.phase !== 'completed') {
if (competitionSource) { if (competitionSource) {
await this.repository.deleteByMatch(matchId, { await this.repository.deleteByMatch(matchId, {
sourceCompetitionId: competitionSource.sourceCompetitionId, sourceCompetitionId: competitionSource.sourceCompetitionId,
@@ -4,7 +4,7 @@ import type {
} from '../global/database/schema'; } from '../global/database/schema';
import type { InternalMatchCardView } from './community-stats.types'; 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 InternalRecord = MatchStatsRecord;
export type InternalGameDetail = MatchStatsGameDetail; export type InternalGameDetail = MatchStatsGameDetail;
@@ -0,0 +1,4 @@
export const MATCH_STATS_RIOT_MATCH_INDEX = {
key: { 'gameDetails.riotMatchId': 1 as const },
options: { name: 'gameDetails.riotMatchId_1' },
};
@@ -0,0 +1,47 @@
import type { mongo } from 'mongoose';
import { migrateMatchStatsRawIndex } from './20261111-match-stats-raw-index';
import { MATCH_STATS_RIOT_MATCH_INDEX } from '../match-stats-raw-index';
import { parseMatchStatsIndexOptions } from './run-match-stats-raw-index';
it('defaults to a read-only plan and validates the target environment', async () => {
expect(parseMatchStatsIndexOptions(['--env', 'prod']).dryRun).toBe(true);
expect(() => parseMatchStatsIndexOptions(['--env', 'unknown'])).toThrow();
const createIndex = jest.fn();
await migrateMatchStatsRawIndex(database([], createIndex));
expect(createIndex).not.toHaveBeenCalled();
});
it('adds only the lookup index and accepts an identical existing index', async () => {
const { key, options } = MATCH_STATS_RIOT_MATCH_INDEX;
const createIndex = jest.fn();
const result = await migrateMatchStatsRawIndex(
database([{ key, ...options }], createIndex),
{ dryRun: false },
);
expect(result.alreadyPresent).toBe(true);
expect(createIndex).toHaveBeenCalledWith(key, options);
});
it('rejects an incompatible existing index without dropping or recreating it', async () => {
const { key, options } = MATCH_STATS_RIOT_MATCH_INDEX;
const createIndex = jest.fn();
await expect(
migrateMatchStatsRawIndex(
database([{ key, ...options, unique: true }], createIndex),
{ dryRun: false },
),
).rejects.toThrow('different definition');
expect(createIndex).not.toHaveBeenCalled();
});
function database(indexes: unknown[], createIndex: jest.Mock): mongo.Db {
return {
collection: (name: string) => {
expect(name).toBe('match_stats');
return {
listIndexes: () => ({ toArray: async () => indexes }),
createIndex,
};
},
} as unknown as mongo.Db;
}
@@ -0,0 +1,38 @@
import type { mongo } from 'mongoose';
import { MATCH_STATS_RIOT_MATCH_INDEX } from '../match-stats-raw-index';
/** Adds the lookup index without dropping indexes or modifying game records. */
export async function migrateMatchStatsRawIndex(
db: mongo.Db,
{ dryRun = true }: { dryRun?: boolean } = {},
) {
const { key, options } = MATCH_STATS_RIOT_MATCH_INDEX;
const collection = db.collection('match_stats');
const indexes = await collection
.listIndexes()
.toArray()
.catch((error: unknown) => {
if (error instanceof Error && 'code' in error && error.code === 26)
return [];
throw error;
});
const existing = indexes.find((index) => index.name === options.name);
if (
existing &&
(JSON.stringify(existing.key) !== JSON.stringify(key) ||
existing.unique === true ||
existing.sparse === true ||
existing.hidden === true ||
existing.partialFilterExpression !== undefined)
) {
throw new Error(
`Index ${options.name} already exists with a different definition.`,
);
}
if (!dryRun) await collection.createIndex(key, options);
return {
dryRun,
alreadyPresent: Boolean(existing),
index: { key, ...options },
};
}
@@ -0,0 +1,102 @@
import 'reflect-metadata';
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { ConnectionService, resolveMongoDbName } from '../connection.service';
import { SecretModule } from '../../secret/secret.module';
import { migrateMatchStatsRawIndex } from './20261111-match-stats-raw-index';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: [
resolve(__dirname, '../../../../../../project.env'),
resolve(process.cwd(), '../project.env'),
resolve(process.cwd(), 'apps/project.env'),
resolve(process.cwd(), 'project.env'),
],
}),
SecretModule,
],
providers: [ConnectionService],
})
class MigrationModule {}
export function parseMatchStatsIndexOptions(argv: string[]) {
let dryRun = true;
let help = false;
let nodeEnv = process.env.NODE_ENV ?? 'dev';
for (let index = 0; index < argv.length; index++) {
const argument = argv[index];
if (argument === '--') continue;
if (argument === '--apply') dryRun = false;
else if (argument === '--dry-run') dryRun = true;
else if (argument === '--help' || argument === '-h') help = true;
else if (argument === '--env') nodeEnv = argv[++index] ?? '';
else if (argument.startsWith('--env=')) nodeEnv = argument.slice(6);
else throw new Error(`Unknown argument: ${argument}`);
}
if (!help && !['dev', 'staging', 'prod'].includes(nodeEnv)) {
throw new Error('--env must be dev, staging, or prod.');
}
return { dryRun, help, nodeEnv };
}
async function main(): Promise<void> {
const options = parseMatchStatsIndexOptions(process.argv.slice(2));
if (options.help) {
console.log(`Usage:
pnpm --filter api stats:indexes -- --env staging --dry-run
pnpm --filter api stats:indexes -- --env prod --apply
Defaults to dry-run. --env accepts dev, staging, or prod (NODE_ENV or dev by default).
Creates the internal stats Riot match ID index; does not modify documents.`);
return;
}
// Use the same optional machine environment as the existing migration runners.
const machineHome = process.env.HOME ?? process.env.USERPROFILE;
if (machineHome) {
const contents = await readFile(
resolve(machineHome, 'source/global-env-vars.txt'),
'utf8',
).catch(() => '');
for (const line of contents.split(/\r?\n/)) {
const match = line.trim().match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
if (match) process.env[match[1]] = match[2].replace(/^["']|["']$/g, '');
}
}
process.env.NODE_ENV = options.nodeEnv;
// Even a dry-run with auto-index enabled in the environment must not write.
process.env.MONGODB_AUTO_INDEX = 'false';
const app = await NestFactory.createApplicationContext(MigrationModule, {
logger: ['warn', 'error'],
});
try {
const connection = await app.get(ConnectionService).getConnection();
if (!connection.db) throw new Error('MongoDB connection has no db handle.');
const result = await migrateMatchStatsRawIndex(connection.db, options);
console.log(
JSON.stringify(
{
env: options.nodeEnv,
db: resolveMongoDbName(options.nodeEnv),
...result,
},
null,
2,
),
);
} finally {
await app.close();
}
}
if (require.main === module) {
void main().catch((error: unknown) => {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
});
}
+12 -1
View File
@@ -14,6 +14,7 @@ import {
} from '../../competition/competition.schema'; } from '../../competition/competition.schema';
import { ModelDefinition } from './types'; import { ModelDefinition } from './types';
import { AUCTION_CANCELLATION_CLEANUP_INDEX } from './auction-cancellation-index'; 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 type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
export const POSITIONS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP']; export const POSITIONS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
@@ -1019,6 +1020,14 @@ export interface MatchStatsRecord {
championLevel: number; championLevel: number;
teamPosition: string; teamPosition: string;
kills: number; kills: number;
multiKills?: {
doubleKills: number;
tripleKills: number;
quadraKills: number;
pentaKills: number;
largestMultiKill: number;
};
tier?: TierInfo;
deaths: number; deaths: number;
assists: number; assists: number;
win: boolean; win: boolean;
@@ -1051,6 +1060,7 @@ export interface MatchStatsGameDetail {
gameCreation: number; gameCreation: number;
gameDuration: number; gameDuration: number;
gameVersion?: string; gameVersion?: string;
rawAvailable?: boolean;
winnerSide: TeamSide; winnerSide: TeamSide;
timeline: MatchStatsTimelinePoint[]; timeline: MatchStatsTimelinePoint[];
timelineLoaded?: boolean; timelineLoaded?: boolean;
@@ -2535,7 +2545,7 @@ export const MatchStatsSchema: mongoose.Schema<MatchStats> = new Schema(
{ timestamps: true, collection: 'match_stats' }, { timestamps: true, collection: 'match_stats' },
) as mongoose.Schema<MatchStats>; ) as mongoose.Schema<MatchStats>;
MatchStatsSchema.index({ communityId: 1, scheduledAt: -1 }); MatchStatsSchema.index({ communityId: 1, scheduledAt: -1, matchId: -1 });
MatchStatsSchema.index({ MatchStatsSchema.index({
communityId: 1, communityId: 1,
gameCreationMin: 1, gameCreationMin: 1,
@@ -2544,6 +2554,7 @@ MatchStatsSchema.index({
MatchStatsSchema.index({ communityId: 1, userIds: 1 }); MatchStatsSchema.index({ communityId: 1, userIds: 1 });
MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 }); MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 });
MatchStatsSchema.index({ communityId: 1, championIds: 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< export const tournamentModelDefinitions: Array<
ModelDefinition & { name: keyof TournamentModelTypes } ModelDefinition & { name: keyof TournamentModelTypes }
@@ -389,6 +389,7 @@ describe('Legacy import Competition result cutover', () => {
}), }),
} as unknown as ConnectionService; } as unknown as ConnectionService;
const communityStatsService = { const communityStatsService = {
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
invalidateCommunity: jest.fn().mockResolvedValue(undefined), invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<CommunityStatsService>; } as unknown as jest.Mocked<CommunityStatsService>;
const service = createService({ const service = createService({
@@ -642,6 +643,7 @@ function createService(
{} as RiotMatchService, {} as RiotMatchService,
options.communityStatsService ?? options.communityStatsService ??
({ ({
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
invalidateCommunity: jest.fn().mockResolvedValue(undefined), invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as unknown as CommunityStatsService), } as unknown as CommunityStatsService),
options.matchStatsService ?? ({} as MatchStatsService), options.matchStatsService ?? ({} as MatchStatsService),
@@ -977,6 +979,7 @@ function createBulkDeleteFailureHarness(options: {
}), }),
} as unknown as ConnectionService; } as unknown as ConnectionService;
const communityStatsService = { const communityStatsService = {
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
invalidateCommunity: jest.fn().mockResolvedValue(0), invalidateCommunity: jest.fn().mockResolvedValue(0),
} as unknown as jest.Mocked<CommunityStatsService>; } as unknown as jest.Mocked<CommunityStatsService>;
const service = createService({ connectionService, communityStatsService }); const service = createService({ connectionService, communityStatsService });
@@ -59,6 +59,7 @@ describe('LegacyImportService member job completion', () => {
releaseLockIfOwned: jest.fn().mockResolvedValue(true), releaseLockIfOwned: jest.fn().mockResolvedValue(true),
} as unknown as jest.Mocked<DistributedLockService>; } as unknown as jest.Mocked<DistributedLockService>;
const communityStatsService = { const communityStatsService = {
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
invalidateCommunity: jest.fn().mockResolvedValue(undefined), invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<CommunityStatsService>; } as unknown as jest.Mocked<CommunityStatsService>;
const service = new LegacyImportService( const service = new LegacyImportService(
@@ -797,7 +797,9 @@ export class LegacyImportService {
'evidence.type': 'riot', 'evidence.type': 'riot',
'evidence.riotMatchId': riotMatchId, 'evidence.riotMatchId': riotMatchId,
}); });
if (existing) return 'duplicate'; if (existing) {
return 'duplicate';
}
const detail = await this.ensureRiotMatchPersisted( const detail = await this.ensureRiotMatchPersisted(
riotMatchId, riotMatchId,
@@ -930,7 +932,9 @@ export class LegacyImportService {
const stored = await RiotMatchModel.findOne({ const stored = await RiotMatchModel.findOne({
matchId: riotMatchId, matchId: riotMatchId,
}).exec(); }).exec();
if (isRiotMatchDto(stored?.raw)) return stored.raw; if (isRiotMatchDto(stored?.raw)) {
return stored.raw;
}
const dto = await this.riotMatchService.getMatch(riotMatchId, { region }); const dto = await this.riotMatchService.getMatch(riotMatchId, { region });
const payload: Partial<StoredRiotMatch> = { const payload: Partial<StoredRiotMatch> = {
@@ -948,6 +952,13 @@ export class LegacyImportService {
{ $set: payload }, { $set: payload },
{ upsert: true }, { upsert: true },
).exec(); ).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; return dto;
} }
@@ -18,6 +18,11 @@ describe('MatchHistoryService champion filtering', () => {
'KR_2', 'KR_2',
]); ]);
expect(first.nextCursor).toBe(SEASON_START + 2_000); 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({ const second = await harness.service.getRecentMatches({
...harness.scope, ...harness.scope,
filters: { ...filters, cursor: first.nextCursor! }, filters: { ...filters, cursor: first.nextCursor! },
@@ -130,6 +135,34 @@ function createHarness() {
}); });
const models = { const models = {
user: { 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: () => ({ findById: () => ({
exec: async () => ({ exec: async () => ({
_id: userId, _id: userId,
@@ -168,6 +201,7 @@ function storedMatch(sequence: number, championId: number, queueId = 420) {
teamId: 100, teamId: 100,
win: true, win: true,
kills: 5, kills: 5,
tripleKills: 1,
deaths: 2, deaths: 2,
assists: 3, assists: 3,
totalMinionsKilled: 100, totalMinionsKilled: 100,
@@ -21,6 +21,7 @@ import {
type RiotRankFilter, type RiotRankFilter,
} from '../riot/riot-queue.constants'; } from '../riot/riot-queue.constants';
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types'; import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
import { readMultiKills } from '../riot/riot-multi-kill';
import type { import type {
ChampionStatsResponse, ChampionStatsResponse,
ChampionStatsRow, ChampionStatsRow,
@@ -218,6 +219,7 @@ export class MatchHistoryService {
.map((doc) => this.toRecentMatchView(doc, context.account.puuid)) .map((doc) => this.toRecentMatchView(doc, context.account.puuid))
.filter((view): view is RecentMatchView => Boolean(view)); .filter((view): view is RecentMatchView => Boolean(view));
const page = views.slice(0, limit); const page = views.slice(0, limit);
await this.attachRecordedRanks(params.communityId, page);
return { return {
matches: page, 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: { private async resolveContext(params: {
communityId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId;
@@ -593,6 +653,7 @@ export class MatchHistoryService {
championLevel: participant.champLevel, championLevel: participant.champLevel,
teamPosition: participant.teamPosition || participant.individualPosition, teamPosition: participant.teamPosition || participant.individualPosition,
kills: participant.kills, kills: participant.kills,
largestMultiKill: readMultiKills(participant)?.largestMultiKill,
deaths: participant.deaths, deaths: participant.deaths,
assists: participant.assists, assists: participant.assists,
kda: this.resolveKda( kda: this.resolveKda(
@@ -1,4 +1,5 @@
import type { MatchStatsRunePerks, RiotLane } from '../global/database/schema'; import type { MatchStatsRunePerks, RiotLane } from '../global/database/schema';
import type { RecentMatchParticipantRank } from '@lolympus/contracts';
import type { import type {
RiotQueueGroup, RiotQueueGroup,
RiotRankFilter, RiotRankFilter,
@@ -115,6 +116,7 @@ export interface RecentMatchTeamParticipantView {
championId: number; championId: number;
championLevel: number; championLevel: number;
teamPosition: string; teamPosition: string;
tier?: RecentMatchParticipantRank;
kills: number; kills: number;
deaths: number; deaths: number;
assists: number; assists: number;
@@ -147,6 +149,7 @@ export interface RecentMatchView {
championLevel: number; championLevel: number;
teamPosition: string; teamPosition: string;
kills: number; kills: number;
largestMultiKill?: number;
deaths: number; deaths: number;
assists: number; assists: number;
kda: number; kda: number;
+71 -2
View File
@@ -1,7 +1,9 @@
import type { import type {
HallOfFameResponse,
MatchDetailResponse, MatchDetailResponse,
MatchEventType, MatchEventType,
MatchListResponse, MatchListResponse,
MatchListView,
} from '@lolympus/contracts'; } from '@lolympus/contracts';
import { import {
BadRequestException, BadRequestException,
@@ -17,6 +19,7 @@ import {
Query, Query,
UseGuards, UseGuards,
} from '@nestjs/common'; } from '@nestjs/common';
import { isISO8601 } from 'class-validator';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { CurrentUser } from '../auth/current-user.decorator'; import { CurrentUser } from '../auth/current-user.decorator';
@@ -89,10 +92,38 @@ export class MatchController {
@Query('sort') sort?: 'asc' | 'desc', @Query('sort') sort?: 'asc' | 'desc',
@Query('includeResults') includeResults?: string, @Query('includeResults') includeResults?: string,
@Query('eventType') eventType?: MatchEventType, @Query('eventType') eventType?: MatchEventType,
@Query('view') view?: MatchListView,
@Query('asOf') asOf?: string,
): Promise<MatchListResponse> { ): Promise<MatchListResponse> {
if (eventType !== undefined && !MATCH_EVENT_TYPES.includes(eventType)) { if (eventType !== undefined && !MATCH_EVENT_TYPES.includes(eventType)) {
throw new BadRequestException('Invalid 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({ const result = await this.matchService.listPage({
communityId, communityId,
status, status,
@@ -103,11 +134,15 @@ export class MatchController {
scheduledFrom: this.toOptionalDate(scheduledFrom), scheduledFrom: this.toOptionalDate(scheduledFrom),
scheduledTo: this.toOptionalDate(scheduledTo), scheduledTo: this.toOptionalDate(scheduledTo),
sort, sort,
...(view ? { view, asOf: asOfDate } : {}),
}); });
const historyResults = const historyResults =
includeResults === 'true' includeResults === 'true'
? await this.matchService.getHistoryResults(communityId, result.matches) ? await this.matchService.getHistoryResults(communityId, result.matches)
: undefined; : undefined;
const eventProgress = view
? await this.matchService.getEventProgress(result.matches)
: undefined;
return { return {
...result, ...result,
matches: result.matches.map((match) => { matches: result.matches.map((match) => {
@@ -121,11 +156,26 @@ export class MatchController {
: {}), : {}),
}); });
const historyResult = historyResults?.get(summary._id); 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<HallOfFameResponse> {
return this.matchService.getHallOfFame(communityId);
}
@Get(':matchId') @Get(':matchId')
@AllowPublicAccess() @AllowPublicAccess()
public async getMatch( public async getMatch(
@@ -135,7 +185,7 @@ export class MatchController {
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
): Promise<MatchDetailResponse> { ): Promise<MatchDetailResponse> {
const match = await this.matchService.getById(matchId, communityId); const match = await this.matchService.getById(matchId, communityId);
return this.matchService.serialize(match, { const summary = this.matchService.serialize(match, {
joined: Boolean( joined: Boolean(
currentUser && currentUser &&
match.participants.some((participant) => 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') @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<MatchDetailResponse> {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.cancelJoin({
matchId,
userId: currentUser._id,
});
return this.matchService.serialize(match, { joined: false });
}
@Delete(':matchId/participants/:userId') @Delete(':matchId/participants/:userId')
@Roles('admin', 'owner') @Roles('admin', 'owner')
@UseGuards(RolesGuard) @UseGuards(RolesGuard)
@@ -2,6 +2,104 @@ import mongoose from 'mongoose';
import { MatchService } from './match.service'; import { MatchService } from './match.service';
describe('MatchService', () => { 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() { function createServiceWithCreateModels() {
const createdPayloads: Record<string, unknown>[] = []; const createdPayloads: Record<string, unknown>[] = [];
const MatchModel = { const MatchModel = {
@@ -195,7 +293,7 @@ describe('MatchService', () => {
expect(MatchModel.find).toHaveBeenCalledWith({ communityId }); expect(MatchModel.find).toHaveBeenCalledWith({ communityId });
expect(MatchModel.countDocuments).toHaveBeenCalledWith({ communityId }); expect(MatchModel.countDocuments).toHaveBeenCalledWith({ communityId });
expect(sort).toHaveBeenCalledWith({ scheduledAt: -1 }); expect(sort).toHaveBeenCalledWith({ scheduledAt: -1, _id: -1 });
expect(skip).toHaveBeenCalledWith(5); expect(skip).toHaveBeenCalledWith(5);
expect(limit).toHaveBeenCalledWith(5); expect(limit).toHaveBeenCalledWith(5);
expect(page).toEqual({ expect(page).toEqual({
@@ -254,7 +352,7 @@ describe('MatchService', () => {
communityId, communityId,
scheduledAt: { $gte: scheduledFrom }, 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 () => { it('filters past matches and keeps newest first for history sections', async () => {
@@ -277,7 +375,7 @@ describe('MatchService', () => {
communityId, communityId,
scheduledAt: { $lt: scheduledTo }, scheduledAt: { $lt: scheduledTo },
}); });
expect(sort).toHaveBeenCalledWith({ scheduledAt: -1 }); expect(sort).toHaveBeenCalledWith({ scheduledAt: -1, _id: -1 });
}); });
it.each([ it.each([
+236 -4
View File
@@ -1,4 +1,12 @@
import type { MatchEventType, MatchHistoryResult } from '@lolympus/contracts'; import type {
HallOfFameResponse,
MatchEventStage,
MatchEventType,
MatchHistoryResult,
MatchId,
MatchListView,
UserId,
} from '@lolympus/contracts';
import { import {
BadRequestException, BadRequestException,
ConflictException, ConflictException,
@@ -9,6 +17,7 @@ import {
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { MatchStatsService } from '../community-stats/match-stats.service'; import { MatchStatsService } from '../community-stats/match-stats.service';
import { CommunityStatsService } from '../community-stats/community-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 { ConnectionService } from '../global/database/connection.service';
import { import {
Match, Match,
@@ -62,6 +71,8 @@ interface ListMatchesQuery {
scheduledFrom?: Date; scheduledFrom?: Date;
scheduledTo?: Date; scheduledTo?: Date;
sort?: 'asc' | 'desc'; sort?: 'asc' | 'desc';
view?: MatchListView;
asOf?: Date;
} }
interface ListMatchesPageQuery extends ListMatchesQuery { interface ListMatchesPageQuery extends ListMatchesQuery {
@@ -77,6 +88,10 @@ interface MatchListFilter {
$gte?: Date; $gte?: Date;
$lt?: Date; $lt?: Date;
}; };
$or?: Array<{
status: MatchStatus | { $in: MatchStatus[] };
scheduledAt?: { $lt: Date };
}>;
} }
interface JoinMatchParams { interface JoinMatchParams {
@@ -219,6 +234,203 @@ export class MatchService {
return results; return results;
} }
public async getHallOfFame(
communityId: mongoose.Types.ObjectId,
): Promise<HallOfFameResponse> {
const [MatchModel, CompetitionModel] = await Promise.all([
this.connectionService.getModel('match'),
this.connectionService.getModel('competition'),
]);
const legacyChampion = {
competitionId: null,
status: 'finished',
'doubleElimination.placements.firstTeamIndex': { $type: 'number' },
};
const [match] = await MatchModel.aggregate<
Pick<Match, 'title' | 'teams' | 'participants' | 'doubleElimination'> & {
_id: mongoose.Types.ObjectId;
official: HistoryCompetition[];
}
>([
{
$match: {
communityId,
eventType: 'tournament',
$or: [{ competitionId: { $type: 'objectId' } }, legacyChampion],
},
},
{ $sort: { scheduledAt: -1, _id: -1 } },
{
$lookup: {
from: CompetitionModel.collection.name,
localField: 'competitionId',
foreignField: '_id',
let: { matchId: '$_id' },
pipeline: [
{
$match: {
communityId,
phase: 'completed',
$expr: { $eq: ['$matchId', '$$matchId'] },
$or: [
{ 'projection.outcome.type': 'double-elimination' },
{
'projection.outcome.type': 'round-robin',
'projection.outcome.leaderTeamIds.0': { $exists: true },
},
],
},
},
{ $project: { teams: 1, 'projection.outcome': 1 } },
],
as: 'official',
},
},
{
$match: { $or: [{ 'official.0': { $exists: true } }, legacyChampion] },
},
{ $limit: 1 },
{
$project: {
title: 1,
teams: 1,
participants: 1,
doubleElimination: 1,
official: 1,
},
},
]).exec();
if (!match) return { match: null, teams: [] };
const featuredMatch = {
id: match._id.toString() as MatchId,
title: match.title,
};
const [competition] = match.official;
if (competition) {
const { outcome } = competition.projection as Pick<
CompetitionProjection,
'outcome'
>;
const winnerIds =
outcome?.type === 'double-elimination'
? [outcome.championTeamId]
: outcome?.type === 'round-robin'
? outcome.leaderTeamIds
: [];
const teams = competition.teams
.filter((team) => winnerIds.includes(team.teamId.toString()))
.map((team) => ({
name: team.name.trim() || `${team.displayOrder}팀`,
captainUserId: team.captainUserId?.toString() as UserId | undefined,
members: team.members.map((member) => ({
userId: member.userId.toString() as UserId,
position: POSITIONS.find(
(position) => position === member.assignedPosition,
),
gameName: member.gameName,
tagLine: member.tagLine,
profileIconId: member.profileIconId,
})),
}));
return { match: featuredMatch, teams };
}
const placement = match.doubleElimination?.placements.firstTeamIndex;
const champion =
placement === undefined
? undefined
: match.teams.find((team) => team.teamIndex === placement);
if (!champion) return { match: featuredMatch, teams: [] };
const participants = new Map(
match.participants.map((participant) => [
participant.userId.toString(),
participant,
]),
);
return {
match: featuredMatch,
teams: [
{
name: champion.name.trim() || `${champion.teamIndex}팀`,
captainUserId: champion.captainUserId?.toString() as
| UserId
| undefined,
members: champion.members.map((member) => {
const userId = member.userId.toString() as UserId;
const participant = participants.get(userId);
return {
userId,
position: member.assignedPosition,
gameName: participant?.gameName,
tagLine: participant?.tagLine,
profileIconId: participant?.profileIconId,
};
}),
},
],
};
}
public async getEventProgress(matches: readonly MatchDocument[]) {
const teamBuilding = matches.filter(
(match) => match.status === 'team-built',
);
const byMatchId = new Map<string, MatchEventStage>();
if (teamBuilding.length > 0) {
const AuctionModel = await this.connectionService.getModel('auction');
const auctions = await AuctionModel.find({
matchId: { $in: teamBuilding.map(({ _id }) => _id) },
})
.select({
matchId: 1,
phase: 1,
auctionLifecycleId: 1,
startupCompleted: 1,
matchSideEffectStatus: 1,
})
.lean()
.exec();
for (const auction of auctions) {
const match = teamBuilding.find(({ _id }) =>
_id.equals(auction.matchId),
);
if (
!match ||
(auction.auctionLifecycleId &&
auction.auctionLifecycleId ===
match.lastCancelledAuctionLifecycleId)
)
continue;
if (
auction.matchSideEffectStatus === 'failed' ||
auction.startupCompleted === false ||
(auction.phase === 'complete' &&
(auction.matchSideEffectStatus === 'pending' ||
auction.matchSideEffectStatus === 'processing'))
) {
byMatchId.set(match._id.toString(), 'team-check');
} else if (auction.phase !== 'complete') {
byMatchId.set(match._id.toString(), 'auction');
}
}
}
return new Map(
matches.map((match) => {
const id = match._id.toString();
const stage: MatchEventStage =
match.status !== 'team-built'
? match.status
: (byMatchId.get(id) ??
(match.teams.length >= 2 &&
(match.competitionId || match.teamBuiltAt)
? 'team-ready'
: 'team-check'));
return [id, { stage }] as const;
}),
);
}
public async ensureShortCode(match: MatchDocument): Promise<MatchDocument> { public async ensureShortCode(match: MatchDocument): Promise<MatchDocument> {
if (match.shortCode) return match; if (match.shortCode) return match;
@@ -714,10 +926,26 @@ export class MatchService {
communityId: query.communityId, communityId: query.communityId,
}; };
if (query.status) filter.status = query.status; 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) { if (query.eventType) {
// MongoDB matches missing fields as well as explicit null values. // MongoDB matches missing fields as well as explicit null values.
filter.eventType = filter.eventType =
query.eventType === 'inhouse' ? { $in: ['inhouse', null] } : query.eventType; query.eventType === 'inhouse'
? { $in: ['inhouse', null] }
: query.eventType;
} }
if (query.scheduledFrom || query.scheduledTo) { if (query.scheduledFrom || query.scheduledTo) {
filter.scheduledAt = {}; filter.scheduledAt = {};
@@ -727,8 +955,12 @@ export class MatchService {
return filter; return filter;
} }
private buildListSort(sort?: 'asc' | 'desc'): { scheduledAt: 1 | -1 } { private buildListSort(sort?: 'asc' | 'desc'): {
return { scheduledAt: sort === 'asc' ? 1 : -1 }; scheduledAt: 1 | -1;
_id: 1 | -1;
} {
const direction = sort === 'asc' ? 1 : -1;
return { scheduledAt: direction, _id: direction };
} }
private normalizeListLimit(limit?: number): number { private normalizeListLimit(limit?: number): number {
@@ -0,0 +1,191 @@
import { Test } from '@nestjs/testing';
import { ConfigService } from '@nestjs/config';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service';
import { RedisService } from '../global/redis/redis.service';
import { DistributedLockService } from '../global/redis/distributed-lock.service';
import { LegacyImportService } from '../legacy-import/legacy-import.service';
import { TournamentResultService } from '../tournament-result/tournament-result.service';
import { RiotModule } from './riot.module';
import { RiotRecentMatchesService } from './riot-recent-matches.service';
import type { RiotMatchDto } from './riot.types';
const detail = {
metadata: { matchId: 'KR_1', participants: [] },
info: { participants: [], teams: [], queueId: 420 },
} as unknown as RiotMatchDto;
describe('Riot raw persistence recovery hooks', () => {
it('resolves the Riot and community stats providers without external connections', async () => {
const external = new Set<unknown>([
ConnectionService,
RedisService,
DistributedLockService,
ConfigService,
]);
const module = await Test.createTestingModule({ imports: [RiotModule] })
.useMocker((token) => (external.has(token) ? {} : undefined))
.compile();
expect(module.get(RiotRecentMatchesService)).toBeInstanceOf(
RiotRecentMatchesService,
);
expect(module.get(CommunityStatsService)).toBeInstanceOf(
CommunityStatsService,
);
await module.close();
});
it.each([
['legacy', false],
['legacy', true],
['tournament', false],
['tournament', true],
] as const)(
'returns saved %s raw data even if stats recovery fails (%s), without retrying stored raw',
async (kind, recoveryFails) => {
let stored: { raw: RiotMatchDto } | null = null;
const events: string[] = [];
const updateOne = jest.fn(() => ({
exec: async () => {
stored = { raw: detail };
events.push('save');
},
}));
const connection = {
getModel: async () => ({
findOne: () => ({ exec: async () => stored }),
updateOne,
}),
};
const getMatch = jest.fn().mockResolvedValue(detail);
const refreshForRiotMatches = jest.fn(async () => {
expect(stored?.raw).toBe(detail);
events.push('refresh');
if (recoveryFails) throw new Error('Stats unavailable');
});
const stats = { refreshForRiotMatches };
const service =
kind === 'legacy'
? new LegacyImportService(
connection as never,
{} as never,
{ getMatch } as never,
stats as never,
{} as never,
{} as never,
{} as never,
{} as never,
)
: new TournamentResultService(
connection as never,
{ getMatch } as never,
{} as never,
stats as never,
{} as never,
{} as never,
{} as never,
{} as never,
);
const archive = service as unknown as {
ensureRiotMatchPersisted: (
id: string,
region: string,
) => Promise<RiotMatchDto>;
};
expect(await archive.ensureRiotMatchPersisted('KR_1', 'asia')).toBe(
detail,
);
expect(await archive.ensureRiotMatchPersisted('KR_1', 'asia')).toBe(
detail,
);
expect(events).toEqual(['save', 'refresh']);
expect(getMatch).toHaveBeenCalledTimes(1);
expect(refreshForRiotMatches).toHaveBeenCalledWith(['KR_1']);
},
);
it.each([false, true])(
'refreshes only newly fetched recent matches and tolerates recovery failure (%s)',
async (recoveryFails) => {
const stored = new Map<string, { matchId: string; raw: RiotMatchDto }>([
['KR_2', { matchId: 'KR_2', raw: detail }],
]);
const refreshForRiotMatches = jest.fn(async () => {
expect(stored.has('KR_1')).toBe(true);
if (recoveryFails) throw new Error('Stats unavailable');
});
const getMatch = jest.fn().mockResolvedValue(detail);
const service = new RiotRecentMatchesService(
{
getModel: async () => ({
find: () => query([...stored.values()]),
updateOne: () => ({
exec: async () => {
stored.set('KR_1', { matchId: 'KR_1', raw: detail });
},
}),
}),
} as never,
{ getMatchIdsByPuuid: async () => ['KR_1'], getMatch } as never,
{
runWithLock: async (
_options: unknown,
operation: () => Promise<unknown>,
) => operation(),
} as never,
{ refreshForRiotMatches } as never,
);
await service.syncRecentMatches({ puuid: 'player' });
await service.syncRecentMatches({ puuid: 'player' });
expect(getMatch).toHaveBeenCalledTimes(1);
expect(refreshForRiotMatches).toHaveBeenCalledTimes(1);
expect(refreshForRiotMatches).toHaveBeenCalledWith(['KR_1']);
},
);
it('skips stats recovery for duplicate legacy import facts', async () => {
const refreshForRiotMatches = jest.fn();
const service = new LegacyImportService(
{ getModel: async () => ({ exists: async () => true }) } as never,
{} as never,
{} as never,
{ refreshForRiotMatches } as never,
{} as never,
{
runWithLock: async (
_options: unknown,
operation: () => Promise<unknown>,
) => operation(),
} as never,
{} as never,
{} as never,
);
const importer = service as unknown as {
importSingleMatch: (
id: string,
job: unknown,
users: unknown,
) => Promise<string>;
};
expect(await importer.importSingleMatch('KR_1', {}, {})).toBe('duplicate');
expect(refreshForRiotMatches).not.toHaveBeenCalled();
});
});
function query<T>(value: T) {
return {
select() {
return this;
},
lean() {
return this;
},
sort() {
return this;
},
limit() {
return this;
},
exec: async () => value,
};
}
@@ -0,0 +1,28 @@
import type { RiotMatchParticipantDto } from './riot.types';
export function readMultiKills(participant?: RiotMatchParticipantDto) {
if (!participant) return undefined;
const count = (key: string) => {
const value = participant[key];
return typeof value === 'number' && Number.isInteger(value) && value > 0
? value
: 0;
};
const doubleKills = count('doubleKills');
const tripleKills = count('tripleKills');
const quadraKills = count('quadraKills');
const pentaKills = count('pentaKills');
const largestMultiKill = Math.max(
count('largestMultiKill'),
pentaKills ? 5 : quadraKills ? 4 : tripleKills ? 3 : doubleKills ? 2 : 0,
);
return {
doubleKills,
tripleKills,
quadraKills,
pentaKills,
largestMultiKill,
};
}
@@ -1,4 +1,5 @@
import { Injectable, Logger } from '@nestjs/common'; import { Injectable, Logger } from '@nestjs/common';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import type { import type {
RiotMatchDocument, RiotMatchDocument,
RiotMatch as StoredRiotMatch, RiotMatch as StoredRiotMatch,
@@ -23,6 +24,7 @@ export class RiotRecentMatchesService {
private readonly connectionService: ConnectionService, private readonly connectionService: ConnectionService,
private readonly matchService: RiotMatchService, private readonly matchService: RiotMatchService,
private readonly distributedLockService: DistributedLockService, private readonly distributedLockService: DistributedLockService,
private readonly communityStatsService: CommunityStatsService,
) {} ) {}
public async syncRecentMatches(params: { public async syncRecentMatches(params: {
@@ -34,6 +36,7 @@ export class RiotRecentMatchesService {
const region = params.region ?? DEFAULT_REGION; const region = params.region ?? DEFAULT_REGION;
const limit = params.limit ?? RIOT_RECENT_MATCH_LIMIT; const limit = params.limit ?? RIOT_RECENT_MATCH_LIMIT;
const queueId = params.queueId ?? RIOT_SOLO_QUEUE_ID; const queueId = params.queueId ?? RIOT_SOLO_QUEUE_ID;
const savedMatchIds = new Set<string>();
const result = await this.distributedLockService.runWithLock( const result = await this.distributedLockService.runWithLock(
{ {
lockKey: `distributed-lock:riot-recent-matches:sync:puuid:${params.puuid}`, lockKey: `distributed-lock:riot-recent-matches:sync:puuid:${params.puuid}`,
@@ -57,6 +60,7 @@ export class RiotRecentMatchesService {
await this.connectionService.getModel('riotMatch'); await this.connectionService.getModel('riotMatch');
const existingMatches = await RiotMatchModel.find({ const existingMatches = await RiotMatchModel.find({
matchId: { $in: matchIds }, matchId: { $in: matchIds },
'raw.info': { $exists: true },
}) })
.select({ matchId: 1 }) .select({ matchId: 1 })
.lean() .lean()
@@ -94,9 +98,10 @@ export class RiotRecentMatchesService {
await RiotMatchModel.updateOne( await RiotMatchModel.updateOne(
{ matchId: dto.metadata.matchId }, { matchId: dto.metadata.matchId },
{ $setOnInsert: payload }, { $set: payload },
{ upsert: true }, { upsert: true },
).exec(); ).exec();
savedMatchIds.add(dto.metadata.matchId);
} catch (error: unknown) { } catch (error: unknown) {
this.logger.warn( this.logger.warn(
`Skipping Riot match ${matchId} while syncing ${params.puuid}: ${ `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: { public async ensureFreshForQueue(params: {
+3 -2
View File
@@ -1,4 +1,5 @@
import { Module } from '@nestjs/common'; import { forwardRef, Module } from '@nestjs/common';
import { CommunityStatsModule } from '../community-stats/community-stats.module';
import { SecretModule } from '../global/secret/secret.module'; import { SecretModule } from '../global/secret/secret.module';
import { RiotAccountEnrichmentService } from './riot-account-enrichment.service'; import { RiotAccountEnrichmentService } from './riot-account-enrichment.service';
import { RiotAccountService } from './riot-account.service'; import { RiotAccountService } from './riot-account.service';
@@ -15,7 +16,7 @@ import { RiotSummonerService } from './riot-summoner.service';
import { RiotWebhookController } from './riot-webhook.controller'; import { RiotWebhookController } from './riot-webhook.controller';
@Module({ @Module({
imports: [SecretModule], imports: [SecretModule, forwardRef(() => CommunityStatsModule)],
controllers: [RiotWebhookController, RiotDdragonController], controllers: [RiotWebhookController, RiotDdragonController],
providers: [ providers: [
RiotRateLimiterService, RiotRateLimiterService,
@@ -203,7 +203,10 @@ describe('TournamentResultService Competition cutover', () => {
connectionService as never, connectionService as never,
{ getMatch: jest.fn().mockResolvedValue(detail) } as never, { getMatch: jest.fn().mockResolvedValue(detail) } as never,
{} 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(), runWithLock: jest.fn(),
runWithRenewedLock: jest.fn(), runWithRenewedLock: jest.fn(),
@@ -312,7 +312,10 @@ function pollHarness(params: {
connectionService as never, connectionService as never,
riotMatchService as never, riotMatchService as never,
riotJobQueueService 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, distributedLockService as never,
{ bootstrap: jest.fn().mockResolvedValue(readyCompetition) } as never, { bootstrap: jest.fn().mockResolvedValue(readyCompetition) } as never,
commandService as never, commandService as never,
@@ -717,7 +717,9 @@ export class TournamentResultService {
const stored = await RiotMatchModel.findOne({ const stored = await RiotMatchModel.findOne({
matchId: riotMatchId, matchId: riotMatchId,
}).exec(); }).exec();
if (isRiotMatchDto(stored?.raw)) return stored.raw; if (isRiotMatchDto(stored?.raw)) {
return stored.raw;
}
const dto = await this.riotMatchService.getMatch(riotMatchId, { region }); const dto = await this.riotMatchService.getMatch(riotMatchId, { region });
const payload: Partial<StoredRiotMatch> = { const payload: Partial<StoredRiotMatch> = {
@@ -732,9 +734,16 @@ export class TournamentResultService {
}; };
await RiotMatchModel.updateOne( await RiotMatchModel.updateOne(
{ matchId: dto.metadata.matchId }, { matchId: dto.metadata.matchId },
{ $setOnInsert: payload }, { $set: payload },
{ upsert: true }, { upsert: true },
).exec(); ).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; return dto;
} }
+1 -27
View File
@@ -8,7 +8,7 @@ import {
useLocation, useLocation,
useNavigate, useNavigate,
} from "react-router"; } 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 { useMsal } from "@azure/msal-react";
import { LogOut, Moon, Search, Sun } from "lucide-react"; import { LogOut, Moon, Search, Sun } from "lucide-react";
import DevAuthSwitcher from "./components/DevAuthSwitcher"; import DevAuthSwitcher from "./components/DevAuthSwitcher";
@@ -31,12 +31,6 @@ import MatchAdminPage from "./pages/admin/MatchAdminPage";
import TournamentCodesPage from "./pages/admin/TournamentCodesPage"; import TournamentCodesPage from "./pages/admin/TournamentCodesPage";
import { PlainPage, Tooltip, pageWidthClass } from "./ui"; 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 = 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"; "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" path="/communities/:cid/internal-stats"
element={<CommunityInternalStatsPage />} element={<CommunityInternalStatsPage />}
/> />
{InternalStatsPreview && (
<Route
path="/preview/internal-stats"
element={
<Suspense fallback={<PlainPage>전적 목업을 불러오는 중</PlainPage>}>
<InternalStatsPreview />
</Suspense>
}
/>
)}
{MatchFlowsPreview && (
<Route
path="/preview/match-flows"
element={
<Suspense fallback={<PlainPage>내전 목업을 불러오는 중</PlainPage>}>
<MatchFlowsPreview />
</Suspense>
}
/>
)}
<Route <Route
path="/communities/:cid/internal-stats/match/:matchId" path="/communities/:cid/internal-stats/match/:matchId"
element={<InternalMatchDetailPage />} element={<InternalMatchDetailPage />}
+49 -3
View File
@@ -5,9 +5,11 @@ import type {
CompetitionCommandResponse, CompetitionCommandResponse,
CompetitionDetailResponse, CompetitionDetailResponse,
CreateSeriesAdjudicationRequest, CreateSeriesAdjudicationRequest,
HallOfFameResponse,
MatchDetailResponse, MatchDetailResponse,
MatchEventType, MatchEventType,
MatchLifecycleStatus, MatchLifecycleStatus,
MatchListView,
MatchListResponse, MatchListResponse,
ReverseSeriesResultRequest, ReverseSeriesResultRequest,
SeriesId, SeriesId,
@@ -33,6 +35,7 @@ import type {
ApiCommunity, ApiCommunity,
ApiCommunityUserSearchCandidate, ApiCommunityUserSearchCandidate,
ApiEnqueueRefreshResult, ApiEnqueueRefreshResult,
ApiHistorySeason,
ApiInternalMatchDetailResponse, ApiInternalMatchDetailResponse,
ApiInternalMatchListResponse, ApiInternalMatchListResponse,
ApiLeaderboardResponse, ApiLeaderboardResponse,
@@ -72,6 +75,8 @@ interface MatchesQueryOptions {
scheduledFrom?: string; scheduledFrom?: string;
scheduledTo?: string; scheduledTo?: string;
sort?: 'asc' | 'desc'; sort?: 'asc' | 'desc';
view?: MatchListView;
asOf?: string;
} }
interface MatchesPageQueryOptions extends MatchesQueryOptions { interface MatchesPageQueryOptions extends MatchesQueryOptions {
@@ -91,6 +96,9 @@ export interface CommunityInternalStatsFilters {
to?: string; to?: string;
championId?: number; championId?: number;
limit?: number; limit?: number;
query?: string;
format?: 'pair' | 'tournament';
playerId?: string;
} }
function createMatchesPath( function createMatchesPath(
@@ -108,6 +116,8 @@ function createMatchesPath(
if (options.scheduledTo) searchParams.set('scheduledTo', options.scheduledTo); if (options.scheduledTo) searchParams.set('scheduledTo', options.scheduledTo);
if (options.sort) searchParams.set('sort', options.sort); if (options.sort) searchParams.set('sort', options.sort);
if (options.includeResults) searchParams.set('includeResults', 'true'); 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(); const queryString = searchParams.toString();
return `/communities/${communityId}/matches${queryString ? `?${queryString}` : ''}`; 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<HallOfFameResponse>(
`/communities/${communityId}/matches/hall-of-fame`,
{ auth: 'none' },
),
enabled: Boolean(communityId),
});
}
export function useMatches( export function useMatches(
options: MatchesQueryOptions, options: MatchesQueryOptions,
communityId = DEFAULT_COMMUNITY_ID, communityId = DEFAULT_COMMUNITY_ID,
@@ -180,6 +201,8 @@ export function useMatches(
options.scheduledTo ?? null, options.scheduledTo ?? null,
options.sort ?? null, options.sort ?? null,
options.eventType ?? null, options.eventType ?? null,
options.view ?? null,
options.asOf ?? null,
], ],
queryFn: async () => { queryFn: async () => {
const response = await authScope.fetch<MatchListResponse>( const response = await authScope.fetch<MatchListResponse>(
@@ -211,6 +234,8 @@ export function useMatchesPage(
options.sort ?? null, options.sort ?? null,
options.includeResults ?? false, options.includeResults ?? false,
options.eventType ?? null, options.eventType ?? null,
options.view ?? null,
options.asOf ?? null,
], ],
queryFn: () => queryFn: () =>
authScope.fetch<MatchListResponse>( authScope.fetch<MatchListResponse>(
@@ -676,6 +701,9 @@ function createCommunityInternalStatsPath(
if (filters.championId) if (filters.championId)
searchParams.set('championId', String(filters.championId)); searchParams.set('championId', String(filters.championId));
if (filters.limit) searchParams.set('limit', String(filters.limit)); 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)) { for (const [key, value] of Object.entries(extra)) {
if (value !== null && value !== undefined && value !== '') { if (value !== null && value !== undefined && value !== '') {
searchParams.set(key, String(value)); searchParams.set(key, String(value));
@@ -700,16 +728,22 @@ export function useCommunityInternalStatsMatches(
filters.to ?? null, filters.to ?? null,
filters.championId ?? null, filters.championId ?? null,
filters.limit ?? null, filters.limit ?? null,
filters.query ?? null,
filters.format ?? null,
filters.playerId ?? null,
], ],
queryFn: ({ pageParam }) => queryFn: ({ pageParam }) =>
apiFetch<ApiInternalMatchListResponse>( apiFetch<ApiInternalMatchListResponse>(
createCommunityInternalStatsPath(communityId, 'matches', filters, { createCommunityInternalStatsPath(communityId, 'matches', filters, {
cursor: pageParam, cursor: pageParam?.cursor,
cursorMatchId: pageParam?.matchId,
}), }),
{ auth: 'none' }, { auth: 'none' },
), ),
initialPageParam: null as number | null, initialPageParam: null as { cursor: number; matchId?: string } | null,
getNextPageParam: (lastPage) => lastPage.nextCursor, getNextPageParam: (lastPage) => lastPage.nextCursor === null
? null
: { cursor: lastPage.nextCursor, matchId: lastPage.nextCursorMatchId },
enabled: Boolean(communityId && enabled), enabled: Boolean(communityId && enabled),
}); });
} }
@@ -727,6 +761,7 @@ export function useCommunityLeaderboard(
filters.from ?? null, filters.from ?? null,
filters.to ?? null, filters.to ?? null,
filters.championId ?? null, filters.championId ?? null,
filters.query ?? null,
], ],
queryFn: () => queryFn: () =>
apiFetch<ApiLeaderboardResponse>( apiFetch<ApiLeaderboardResponse>(
@@ -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( export function useTeamInsights(
filters: CommunityInternalStatsFilters, filters: CommunityInternalStatsFilters,
communityId = DEFAULT_COMMUNITY_ID, communityId = DEFAULT_COMMUNITY_ID,
+19 -1
View File
@@ -1,6 +1,13 @@
import type { import type {
GrandFinalGameCount, GrandFinalGameCount,
GameAnalysisAvailability,
GameId,
GameSlotId,
InternalMatchCompetition,
InternalMatchResultPresentation,
SeriesId,
MatchEventType, MatchEventType,
RecentMatchParticipantRank,
MatchGameMode, MatchGameMode,
MatchPosition, MatchPosition,
MatchPositionPreferenceView, MatchPositionPreferenceView,
@@ -530,6 +537,7 @@ export interface ApiRecentMatchTeamParticipant {
championId: number; championId: number;
championLevel: number; championLevel: number;
teamPosition: string; teamPosition: string;
tier?: RecentMatchParticipantRank;
kills: number; kills: number;
deaths: number; deaths: number;
assists: number; assists: number;
@@ -588,7 +596,7 @@ export interface ApiRecentMatchView {
summonerSpells: [number, number]; summonerSpells: [number, number];
perks: ApiRunePerks; perks: ApiRunePerks;
teams: ApiRecentMatchTeam[]; teams: ApiRecentMatchTeam[];
/** 최대 연속 처치 수. API가 아직 내려주지 않아 화면은 없을 때를 견딘다. */ /** 경기에서 기록한 최대 연속 처치 수. */
largestMultiKill?: number; largestMultiKill?: number;
} }
@@ -606,6 +614,7 @@ export interface ApiInternalMatchCard {
status: 'finished' | 'in-progress'; status: 'finished' | 'in-progress';
gameCount: number; gameCount: number;
winnerTeamIndex?: number; winnerTeamIndex?: number;
resultPresentation?: InternalMatchResultPresentation;
seriesResults: Array<{ seriesResults: Array<{
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
@@ -636,6 +645,7 @@ export interface ApiInternalMatchCard {
export interface ApiInternalMatchListResponse { export interface ApiInternalMatchListResponse {
matches: ApiInternalMatchCard[]; matches: ApiInternalMatchCard[];
nextCursor: number | null; nextCursor: number | null;
nextCursorMatchId?: string;
season: ApiHistorySeason; season: ApiHistorySeason;
} }
@@ -663,6 +673,7 @@ export interface ApiLeaderboardRow {
export interface ApiLeaderboardResponse { export interface ApiLeaderboardResponse {
rows: ApiLeaderboardRow[]; rows: ApiLeaderboardRow[];
season: ApiHistorySeason; season: ApiHistorySeason;
matchedUserIds?: string[];
} }
export interface ApiLeaderHighlight { export interface ApiLeaderHighlight {
@@ -681,6 +692,7 @@ export interface ApiTeamInsightsResponse {
red: number; red: number;
bluePicks: number; bluePicks: number;
redPicks: number; redPicks: number;
confirmed?: { sampleSize: number; blue: number; red: number };
}; };
topKda: ApiLeaderHighlight | null; topKda: ApiLeaderHighlight | null;
mostKills: ApiLeaderHighlight | null; mostKills: ApiLeaderHighlight | null;
@@ -692,8 +704,14 @@ export interface ApiTeamInsightsResponse {
export interface ApiInternalMatchDetailResponse { export interface ApiInternalMatchDetailResponse {
match: ApiInternalMatchCard; match: ApiInternalMatchCard;
competition?: InternalMatchCompetition;
games: Array<{ games: Array<{
gameNumber: number; gameNumber: number;
gameId?: GameId;
analysisAvailability?: GameAnalysisAvailability;
gameSlotId?: GameSlotId;
seriesId?: SeriesId;
ordinal?: number;
riotMatchId: string; riotMatchId: string;
gameCreation: number; gameCreation: number;
gameDuration: number; gameDuration: number;
+11 -2
View File
@@ -1,7 +1,10 @@
import { InteractionStatus } from '@azure/msal-browser';
import { useMsal } from '@azure/msal-react';
import { useCallback, useEffect, useRef, useState } from 'react'; import { useCallback, useEffect, useRef, useState } from 'react';
import { io, type Socket } from 'socket.io-client'; import { io, type Socket } from 'socket.io-client';
import { API_BASE_URL, useAuthUserId } from '../config'; import { API_BASE_URL, useAuthUserId } from '../config';
import { acquireAccessToken } from '../lib/auth/token-provider'; import { acquireAccessToken } from '../lib/auth/token-provider';
import { isMsalConfigured } from '../lib/auth/msal.config';
import type { ApiAuction, ApiAuctionChatMessage, Position } from './types'; import type { ApiAuction, ApiAuctionChatMessage, Position } from './types';
import { import {
createAuctionResyncRequester, createAuctionResyncRequester,
@@ -140,8 +143,14 @@ function mergeChatMessages(
export function useAuctionSocket(matchId: string | undefined) { export function useAuctionSocket(matchId: string | undefined) {
const authUserId = useAuthUserId(); const authUserId = useAuthUserId();
const connectionKey = matchId const { accounts, inProgress, instance } = useMsal();
? JSON.stringify([matchId, authUserId ?? null]) 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; : null;
const socketRef = useRef<Socket | null>(null); const socketRef = useRef<Socket | null>(null);
const resyncRequesterRef = useRef<ReturnType< const resyncRequesterRef = useRef<ReturnType<
@@ -0,0 +1,87 @@
import { Link, useLocation } from "react-router";
import type { ApiInternalMatchDetailResponse, DdragonManifest } from "../api/types";
import { championDisplayName, championIconUrl } from "../lib/ddragon";
import { teamIndexLabel } from "../lib/league";
import { EmptyNote } from "../ui";
export function GameAnalysisNotice() {
return (
<EmptyNote
size="sm"
title="Riot 원본이 없는 경기 기록"
description="저장된 경기 결과와 선수별 KDA를 볼 수 있습니다."
/>
);
}
export function BasicGameScoreboard({
game,
teams,
manifest,
}: {
game: ApiInternalMatchDetailResponse["games"][number];
teams: ApiInternalMatchDetailResponse["match"]["teams"];
manifest: DdragonManifest | null | undefined;
}) {
const location = useLocation();
const backTo = `${location.pathname}${location.search}${location.hash}`;
return (
<div className="space-y-3 p-4">
{game.analysisAvailability && game.analysisAvailability !== "available" && (
<GameAnalysisNotice />
)}
{game.teams.map((team) => (
<section key={team.side} className="overflow-hidden rounded-lg border border-line bg-card">
<h4 className="border-b border-line px-3 py-2 text-sm font-semibold">
{teamIndexLabel(team.teamIndex, teams.find(({ teamIndex }) => teamIndex === team.teamIndex)?.name)}
{" · "}{team.side === "blue" ? "블루" : "레드"}{" · "}{team.win ? "승리" : "패배"}
</h4>
{team.participants.length > 0 ? (
<table className="w-full text-left text-sm">
<thead className="text-xs text-content-muted">
<tr>
<th scope="col" className="px-3 py-2">선수</th>
<th scope="col" className="px-3 py-2">챔피언</th>
<th scope="col" className="px-3 py-2 text-right">K/D/A</th>
</tr>
</thead>
<tbody className="divide-y divide-line">
{team.participants.map((participant) => {
const icon = championIconUrl(manifest, participant.championId);
const champion = championDisplayName(manifest, participant.championId);
return (
<tr key={`${participant.userId}-${participant.championId}`}>
<td className="px-3 py-2">
{participant.userId ? (
<Link
to={`/users/${participant.userId}/history?queueGroup=internal`}
state={{ backTo }}
className="font-semibold hover:underline"
>
{participant.summonerName}
</Link>
) : participant.summonerName}
</td>
<td className="px-3 py-2">
<span className="flex items-center gap-2">
{icon && <img src={icon} alt="" className="size-6 rounded" />}
{champion ?? "챔피언 미확인"}
</span>
</td>
<td className="whitespace-nowrap px-3 py-2 text-right tabular">
{participant.kills}/{participant.deaths}/{participant.assists}
</td>
</tr>
);
})}
</tbody>
</table>
) : (
<p className="px-3 py-2 text-sm text-content-muted">저장된 선수 기록이 없습니다.</p>
)}
</section>
))}
</div>
);
}
+121 -132
View File
@@ -1,8 +1,8 @@
import type { MatchPosition } from '@lolympus/contracts'; import type { HallOfFameResponse, MatchPosition } from '@lolympus/contracts';
import { ChevronRight, UserRound } from 'lucide-react'; import { ChevronRight, UserRound } from 'lucide-react';
import { useEffect, useRef, useState, type CSSProperties } from 'react'; import { useEffect, useRef, useState, type CSSProperties } from 'react';
import { Link } from 'react-router'; import { Link } from 'react-router';
import { useDdragonManifest } from '../api/hooks'; import { useDdragonManifest, useHallOfFame } from '../api/hooks';
import captainCrown from '../assets/captain-crown.svg'; import captainCrown from '../assets/captain-crown.svg';
import pixelTrophy from '../assets/pixel-trophy.svg'; import pixelTrophy from '../assets/pixel-trophy.svg';
import { profileIconUrl } from '../lib/ddragon'; import { profileIconUrl } from '../lib/ddragon';
@@ -10,61 +10,14 @@ import { positionLabel } from '../lib/league';
import { pageWidthClass } from '../ui/layout'; import { pageWidthClass } from '../ui/layout';
import './HomeHallOfFame.css'; import './HomeHallOfFame.css';
// The roster featured on the home page is curated independently of match results. const POSITION_ORDER: MatchPosition[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
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;
}>,
};
export default function HomeHallOfFame({ export default function HomeHallOfFame({
introReady, introReady,
}: { }: {
introReady: boolean; introReady: boolean;
}) { }) {
const { data: manifest } = useDdragonManifest(); const hallOfFame = useHallOfFame();
const sectionRef = useRef<HTMLElement>(null); const sectionRef = useRef<HTMLElement>(null);
const [playIntro, setPlayIntro] = useState(false); const [playIntro, setPlayIntro] = useState(false);
@@ -89,95 +42,131 @@ export default function HomeHallOfFame({
return () => observer.disconnect(); return () => observer.disconnect();
}, [introReady]); }, [introReady]);
const featuredMatch = hallOfFame.data?.match;
return ( return (
// The second grid column is left empty on purpose: it reserves room for a // The second grid column is left empty on purpose: it reserves room for a
// small companion card beside the hall of fame. // small companion card beside the hall of fame.
<section <section
ref={sectionRef} ref={sectionRef}
aria-labelledby="home-hall-of-fame" aria-label="명예의 전당"
className={`${pageWidthClass()} lts-hall grid gap-8 py-6 md:py-8 lg:grid-cols-[minmax(0,1fr)_20rem]`} className={`${pageWidthClass()} lts-hall grid gap-8 py-6 md:py-8 lg:grid-cols-[minmax(0,1fr)_20rem]`}
data-intro={playIntro ? '' : undefined} data-intro={playIntro ? '' : undefined}
> >
<div className="lts-hall-card flex min-w-0 flex-col gap-4 bg-card p-5 sm:flex-row sm:gap-5"> {hallOfFame.isPending ? (
<h2 className="min-w-0 sm:w-36 sm:shrink-0"> <p role="status">명예의 전당을 불러오는 중</p>
<span ) : hallOfFame.isError ? (
id="home-hall-of-fame" <p role="status">
className="block text-sm font-semibold text-content-muted" 명예의 전당을 불러오지 못했습니다.{' '}
> <button type="button" className="underline" onClick={() => void hallOfFame.refetch()}>
명예의 전당 다시 시도
</span> </button>
<span className="mt-2 block text-2xl leading-tight font-extrabold tracking-tight [overflow-wrap:anywhere]"> </p>
{FEATURED_TEAM.name} ) : featuredMatch && hallOfFame.data.teams.length > 0 ? (
</span> <div className="space-y-3">
<span className="mt-1 flex items-center gap-1 text-xs font-semibold text-content-muted"> {hallOfFame.data.teams.map((team, index) => (
<img src={pixelTrophy} alt="" className="lts-hall-pixel size-4" /> <FeaturedTeam key={index} team={team} match={featuredMatch} />
직전 멸망전 우승 ))}
</span> </div>
</h2> ) : (
<div className="h-px bg-line sm:h-auto sm:w-px" aria-hidden="true" /> <p className="text-sm text-content-muted">확정된 멸망전 우승팀이 없습니다.</p>
<ul )}
className="grid min-w-0 flex-1 gap-1 sm:grid-cols-5 sm:content-center sm:items-start"
aria-label="우승팀 선수"
>
{FEATURED_TEAM.members.map(
({ userId, position, gameName, tagLine, profileIconId }, index) => {
const icon = profileIconUrl(manifest, profileIconId);
const isCaptain = userId === FEATURED_TEAM.captainUserId;
return (
<li key={userId} className="min-w-0">
<Link
to={`/users/${userId}/history?queueGroup=internal`}
className="lts-hall-player group flex h-full items-center gap-2.5 px-2 py-2 transition-colors hover:bg-sunken focus-visible:-outline-offset-2 sm:flex-col sm:gap-2 sm:py-3 sm:text-center"
>
<span className="relative shrink-0">
{isCaptain && (
<img
src={captainCrown}
alt="팀장"
className="lts-hall-crown lts-hall-pixel absolute -top-2.5 -right-2.5 z-10 w-6"
/>
)}
<span
className="lts-hall-portrait relative grid size-10 place-items-center overflow-hidden bg-sunken-strong text-content-muted sm:size-13"
style={{ '--lts-hall-order': index } as CSSProperties}
>
<UserRound className="size-5" aria-hidden="true" />
<img
key={icon}
src={icon}
alt=""
className="absolute inset-0 size-full object-cover"
onError={(event) => {
event.currentTarget.hidden = true;
}}
/>
</span>
</span>
<span className="min-w-0 flex-1 sm:w-full sm:flex-none">
<span className="block text-xs font-semibold text-content-muted">
{positionLabel[position]}
</span>
<span className="flex flex-wrap items-baseline gap-x-1.5 sm:flex-col sm:items-center">
<span className="text-sm font-bold [overflow-wrap:anywhere] group-hover:underline">
{gameName}
</span>
<span className="text-xs text-content-muted [overflow-wrap:anywhere]">
#{tagLine}
</span>
</span>
</span>
<ChevronRight
className="size-4 shrink-0 text-content-muted sm:hidden"
aria-hidden="true"
/>
</Link>
</li>
);
},
)}
</ul>
</div>
</section> </section>
); );
} }
function FeaturedTeam({
team,
match,
}: {
team: HallOfFameResponse['teams'][number];
match: NonNullable<HallOfFameResponse['match']>;
}) {
const { data: manifest } = useDdragonManifest();
const members = [...team.members].sort(
(left, right) =>
(left.position ? POSITION_ORDER.indexOf(left.position) : POSITION_ORDER.length) -
(right.position ? POSITION_ORDER.indexOf(right.position) : POSITION_ORDER.length),
);
return (
<div className="lts-hall-card flex min-w-0 flex-col gap-4 bg-card p-5 sm:flex-row sm:gap-5">
<h2 className="min-w-0 sm:w-36 sm:shrink-0">
<span
className="block text-sm font-semibold text-content-muted"
>
명예의 전당
</span>
<span className="mt-2 block text-2xl leading-tight font-extrabold tracking-tight [overflow-wrap:anywhere]">
{team.name}
</span>
<span className="mt-1 flex items-center gap-1 text-xs font-semibold text-content-muted">
<img src={pixelTrophy} alt="" className="lts-hall-pixel size-4" />
<Link to={`/match/${match.id}`} title={match.title} className="hover:underline">직전 멸망전 우승</Link>
</span>
</h2>
<div className="h-px bg-line sm:h-auto sm:w-px" aria-hidden="true" />
<ul
className="grid min-w-0 flex-1 gap-1 sm:grid-cols-5 sm:content-center sm:items-start"
aria-label="우승팀 선수"
>
{members.map(
({ userId, position, gameName, tagLine, profileIconId }, index) => {
const icon = profileIconId === undefined ? undefined : profileIconUrl(manifest, profileIconId);
const isCaptain = userId === team.captainUserId;
return (
<li key={userId} className="min-w-0">
<Link
to={`/users/${userId}/history?queueGroup=internal`}
className="lts-hall-player group flex h-full items-center gap-2.5 px-2 py-2 transition-colors hover:bg-sunken focus-visible:-outline-offset-2 sm:flex-col sm:gap-2 sm:py-3 sm:text-center"
>
<span className="relative shrink-0">
{isCaptain && (
<img
src={captainCrown}
alt="팀장"
className="lts-hall-crown lts-hall-pixel absolute -top-2.5 -right-2.5 z-10 w-6"
/>
)}
<span
className="lts-hall-portrait relative grid size-10 place-items-center overflow-hidden bg-sunken-strong text-content-muted sm:size-13"
style={{ '--lts-hall-order': index } as CSSProperties}
>
<UserRound className="size-5" aria-hidden="true" />
{icon && <img
key={icon}
src={icon}
alt=""
className="absolute inset-0 size-full object-cover"
onError={(event) => {
event.currentTarget.hidden = true;
}}
/>}
</span>
</span>
<span className="min-w-0 flex-1 sm:w-full sm:flex-none">
<span className="block text-xs font-semibold text-content-muted">
{position ? positionLabel[position] : "포지션 미확인"}
</span>
<span className="flex flex-wrap items-baseline gap-x-1.5 sm:flex-col sm:items-center">
<span className="text-sm font-bold [overflow-wrap:anywhere] group-hover:underline">
{gameName ?? "선수 프로필"}
</span>
<span className="text-xs text-content-muted [overflow-wrap:anywhere]">
{tagLine && `#${tagLine}`}
</span>
</span>
</span>
<ChevronRight
className="size-4 shrink-0 text-content-muted sm:hidden"
aria-hidden="true"
/>
</Link>
</li>
);
},
)}
</ul>
</div>
);
}
@@ -15,6 +15,7 @@ import {
type NormalizedLanePosition, type NormalizedLanePosition,
} from "../lib/internal-game-matchups"; } from "../lib/internal-game-matchups";
import { ItemIcon, RuneIcon, RuneStyleIcon } from "./ItemTooltip"; import { ItemIcon, RuneIcon, RuneStyleIcon } from "./ItemTooltip";
import { GameAnalysisNotice } from "./BasicGameScoreboard";
import { Tab, TabList } from "@astryxdesign/core/TabList"; import { Tab, TabList } from "@astryxdesign/core/TabList";
export type InternalGameDetailTab = "scoreboard" | "matchup" | "build"; export type InternalGameDetailTab = "scoreboard" | "matchup" | "build";
@@ -992,6 +993,9 @@ export function InternalGameAnalysisPanel({
if (activeTab === "scoreboard") { if (activeTab === "scoreboard") {
return <>{scoreboard}</>; return <>{scoreboard}</>;
} }
if (selectedGame.analysisAvailability && selectedGame.analysisAvailability !== "available") {
return <GameAnalysisNotice />;
}
if (activeTab === "build") { if (activeTab === "build") {
return ( return (
@@ -133,6 +133,15 @@ export function CompetitionAdminControls({
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ["matches-page", communityId], 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],
}),
]); ]);
} }
@@ -55,7 +55,7 @@ export function TeamTournamentCodes({
return ( return (
<div className="border-t border-base-content/10 px-4 py-5 sm:px-5"> <div className="border-t border-base-content/10 px-4 py-5 sm:px-5">
<p role="status" className="text-sm text-content-muted"> <p role="status" className="text-sm text-content-muted">
이 경기에 배정된 토너먼트 코드가 없습니다. 표시할 세트 정보가 아직 없습니다.
</p> </p>
</div> </div>
); );
+2 -2
View File
@@ -36,10 +36,10 @@ export function formatRankBadge(tier: ApiTierInfo | undefined) {
return rank ? `${tierInitial}${rank}` : tierInitial; return rank ? `${tierInitial}${rank}` : tierInitial;
} }
export function formatRankDetail(tier: ApiTierInfo | undefined) { export function formatRankDetail(tier: Pick<ApiTierInfo, "tier"> & Partial<Pick<ApiTierInfo, "rank" | "leaguePoints">> | undefined) {
if (!tier) return "랭크 정보 없음"; if (!tier) return "랭크 정보 없음";
const tierName = TIER_NAMES[tier.tier] ?? tier.tier; const tierName = TIER_NAMES[tier.tier] ?? tier.tier;
const rank = normalizeRank(tier.rank); const rank = normalizeRank(tier.rank);
const label = rank ? `${tierName} ${rank}` : tierName; const label = rank ? `${tierName} ${rank}` : tierName;
return `${label} - ${tier.leaguePoints} LP`; return tier.leaguePoints === undefined ? label : `${label} - ${tier.leaguePoints} LP`;
} }
-37
View File
@@ -1,11 +1,8 @@
import { useSyncExternalStore } from 'react'; import { useSyncExternalStore } from 'react';
const AUTH_USER_ID_STORAGE_KEY = 'lolympus.authUserId'; 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 THEME_STORAGE_KEY = 'lolympus.theme';
const AUTH_USER_CHANGED_EVENT = 'lolympus:auth-user-changed'; 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'; const THEME_CHANGED_EVENT = 'lolympus:theme-changed';
export type AppTheme = 'light' | 'dark'; export type AppTheme = 'light' | 'dark';
@@ -58,32 +55,6 @@ export function setAuthUserId(userId: string | null) {
dispatchWindowEvent(AUTH_USER_CHANGED_EVENT); 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 { function normalizeTheme(value: string | null | undefined): AppTheme {
return value === 'dark' ? 'dark' : 'light'; return value === 'dark' ? 'dark' : 'light';
} }
@@ -126,14 +97,6 @@ export function useAuthUserId(): string | null {
); );
} }
export function useDevCaptainTeamIndex(): number | null {
return useSyncExternalStore<number | null>(
(callback) => subscribeToWindowChanges(CAPTAIN_SIDE_CHANGED_EVENT, callback),
getDevCaptainTeamIndex,
() => null,
);
}
export function useTheme(): AppTheme { export function useTheme(): AppTheme {
return useSyncExternalStore<AppTheme>( return useSyncExternalStore<AppTheme>(
(callback) => subscribeToWindowChanges(THEME_CHANGED_EVENT, callback), (callback) => subscribeToWindowChanges(THEME_CHANGED_EVENT, callback),
@@ -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;
}
+6 -19
View File
@@ -1,8 +1,4 @@
import type { import type { CompetitionGameView, SeriesProjection } from '@lolympus/contracts';
CompetitionDetailResponse,
CompetitionGameView,
SeriesProjection,
} from '@lolympus/contracts';
import type { ApiInternalMatchDetailResponse } from '../api/types'; import type { ApiInternalMatchDetailResponse } from '../api/types';
import { bracketRoundAccessibleLabel } from '../components/competition/double-elimination-bracket-layout'; import { bracketRoundAccessibleLabel } from '../components/competition/double-elimination-bracket-layout';
import { teamIndexLabel } from './league'; import { teamIndexLabel } from './league';
@@ -23,22 +19,17 @@ export interface RecordedSeries {
export function groupRecordedSets( export function groupRecordedSets(
detail: ApiInternalMatchDetailResponse, detail: ApiInternalMatchDetailResponse,
competition?: CompetitionDetailResponse,
) { ) {
const projection = competition?.projection; const projection = detail.competition?.projection;
const officialByMatchId = new Map<string, CompetitionGameView>(); const officialById = new Map(projection?.games.map((game) => [game.id, game]));
for (const game of projection?.games ?? []) {
if (game.evidence.type === 'riot')
officialByMatchId.set(game.evidence.riotMatchId, game);
}
const seriesById = new Map( const seriesById = new Map(
projection?.series.map((series) => [series.seriesId, series]), projection?.series.map((series) => [series.seriesId, series]),
); );
const groups = new Map<string, RecordedSeries>(); const groups = new Map<string, RecordedSeries>();
for (const game of detail.games) { for (const game of detail.games) {
const official = officialByMatchId.get(game.riotMatchId); const official = game.gameId && officialById.get(game.gameId);
const series = official && seriesById.get(official.seriesId); const series = game.seriesId && seriesById.get(game.seriesId);
const indexes = [ const indexes = [
...new Set(game.teams.map(({ teamIndex }) => teamIndex)), ...new Set(game.teams.map(({ teamIndex }) => teamIndex)),
].sort((a, b) => a - b); ].sort((a, b) => a - b);
@@ -48,11 +39,7 @@ export function groupRecordedSets(
detail.match.teams.find((team) => team.teamIndex === index)?.name, detail.match.teams.find((team) => team.teamIndex === index)?.name,
), ),
); );
const id = const id = series?.seriesId ?? `game:${game.gameNumber}`;
series?.seriesId ??
(indexes.length === 2
? `teams:${indexes.join('-')}`
: `game:${game.gameNumber}`);
const matchup = names.join(' vs ') || `${game.gameNumber}세트`; const matchup = names.join(' vs ') || `${game.gameNumber}세트`;
const label = const label =
series && series.stage.type !== 'pair' series && series.stage.type !== 'pair'
+34 -41
View File
@@ -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 = [ export const LEADERBOARD_SORTS = [
{ value: 'games', label: '경기 수' }, { value: 'games', label: '경기 수' },
@@ -71,46 +76,34 @@ export function getMainLane(byLane: ApiLeaderboardRow['byLane']) {
return main?.lane; return main?.lane;
} }
type MatchOutcomeSource = Pick< export function formatOfficialMatchResult(
ApiInternalMatchCard, result: InternalMatchResultPresentation | undefined,
'winnerTeamIndex' | 'seriesResults' | 'teams' ) {
>; if (result?.type !== 'official') {
type MatchTeam = ApiInternalMatchCard['teams'][number]; return result?.type === 'legacy' ? '과거 기록' : '공식 결과 확인 불가';
}
export type InternalMatchOutcome = const { phase, outcome, teams, singleSeries, completedSeriesCount } = result;
| { const teamName = (id: string) =>
type: 'score'; teams.find(({ teamId }) => teamId === id)?.name ?? '팀 미확인';
left: MatchTeam; if (phase === 'cancelled') return '취소';
right: MatchTeam; if (phase !== 'completed' || !outcome) {
leftWins: number; return completedSeriesCount > 0 ? `시리즈 ${completedSeriesCount}개 확정` : '결과 확정 전';
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),
};
}
} }
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 ?? '')}`;
}
}
} }
-12
View File
@@ -11,18 +11,6 @@ export function multiKillLabel(largestMultiKill: number | undefined) {
return MULTI_KILL_LABELS[Math.min(5, Math.floor(largestMultiKill))]; 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( export function rankPositionRates(
rates: Partial<Record<string, number>>, rates: Partial<Record<string, number>>,
+8 -49
View File
@@ -35,11 +35,7 @@ import {
useAuctionSocket, useAuctionSocket,
type BidLatencyDiagnostics, type BidLatencyDiagnostics,
} from "../api/useAuctionSocket"; } from "../api/useAuctionSocket";
import { import { DEFAULT_COMMUNITY_ID } from "../config";
DEFAULT_COMMUNITY_ID,
setDevCaptainTeamIndex,
useDevCaptainTeamIndex,
} from "../config";
import { ApiError } from "../lib/api"; import { ApiError } from "../lib/api";
import { mergeAuctionState } from "../api/auction-state"; import { mergeAuctionState } from "../api/auction-state";
import { import {
@@ -1929,7 +1925,6 @@ export default function AuctionPage() {
const undoMutation = useUndoAuction(DEFAULT_COMMUNITY_ID); const undoMutation = useUndoAuction(DEFAULT_COMMUNITY_ID);
const resetAuctionMutation = useResetAuction(DEFAULT_COMMUNITY_ID); const resetAuctionMutation = useResetAuction(DEFAULT_COMMUNITY_ID);
const socket = useAuctionSocket(id); const socket = useAuctionSocket(id);
const captainTeamIndex = useDevCaptainTeamIndex();
const [assignedPositionDraft, setAssignedPositionDraft] = useState<{ const [assignedPositionDraft, setAssignedPositionDraft] = useState<{
playerId: string | null; playerId: string | null;
position: Position; position: Position;
@@ -1995,29 +1990,12 @@ export default function AuctionPage() {
const setAssignedPosition = (position: Position) => { const setAssignedPosition = (position: Position) => {
setAssignedPositionDraft({ playerId: currentPlayerId, position }); setAssignedPositionDraft({ playerId: currentPlayerId, position });
}; };
const availableTeamIndexes = useMemo(() => { const captainTeam = currentUser && auctionState?.teams.find(
const indexes = new Set( (team) => team.captainUserId === currentUser._id,
(auctionState?.teams ?? []).map((team) => team.teamIndex), );
); const captainRole: CaptainRole | null = captainTeam ? { teamIndex: captainTeam.teamIndex } : null;
return [...indexes].sort((left, right) => left - right);
}, [auctionState?.teams]);
const captainRole: CaptainRole | null =
captainTeamIndex === null
? null
: {
teamIndex: captainTeamIndex,
};
const chatSenderLabel = resolveChatSenderLabel(currentUser, captainRole); const chatSenderLabel = resolveChatSenderLabel(currentUser, captainRole);
useEffect(() => {
if (availableTeamIndexes.length === 0) return;
if (
captainTeamIndex !== null &&
!availableTeamIndexes.includes(captainTeamIndex)
) {
setDevCaptainTeamIndex(availableTeamIndexes[0]);
}
}, [availableTeamIndexes, captainTeamIndex]);
useEffect(() => { useEffect(() => {
if (!socket.resetAt || !id) return; if (!socket.resetAt || !id) return;
@@ -2299,28 +2277,9 @@ export default function AuctionPage() {
</> </>
} }
actions={ actions={
<div className="w-40"> <span className="text-sm font-semibold" aria-label="경매 참여 역할">
{/* 임시 운영용: 로그인/권한 확인 없이 조작자 역할을 선택할 수 있게 열어둔다. */} {captainTeam ? teamIndexLabel(captainTeam.teamIndex, captainTeam.name) + " 팀장" : "관전자"}
<select </span>
aria-label="경매 참여 역할"
value={captainTeamIndex ?? "spectator"}
onChange={(event) =>
setDevCaptainTeamIndex(
event.target.value === "spectator"
? null
: Number(event.target.value),
)
}
className="lts-select"
>
<option value="spectator">관전자</option>
{availableTeamIndexes.map((teamIndex) => (
<option key={teamIndex} value={teamIndex}>
{teamIndexLabel(teamIndex)} 팀장
</option>
))}
</select>
</div>
} }
/> />
<main <main
+82 -222
View File
@@ -1,12 +1,11 @@
import { useState } from 'react'; import { useDeferredValue, useState } from 'react';
import type { CompetitionDetailResponse } from '@lolympus/contracts';
import { ChevronDown, Search, X } from 'lucide-react'; import { ChevronDown, Search, X } from 'lucide-react';
import { Link, useLocation, useParams, useSearchParams } from 'react-router'; import { Link, useLocation, useParams, useSearchParams } from 'react-router';
import { import {
useCommunity, useCommunity,
useCompetition,
useCommunityInternalStatsMatches, useCommunityInternalStatsMatches,
useCommunityLeaderboard, useCommunityLeaderboard,
useCommunityStatsSeasons,
useDdragonManifest, useDdragonManifest,
useTeamInsights, useTeamInsights,
} from '../api/hooks'; } from '../api/hooks';
@@ -22,7 +21,7 @@ import {
profileIconUrl, profileIconUrl,
} from '../lib/ddragon'; } from '../lib/ddragon';
import { import {
getInternalMatchOutcome, formatOfficialMatchResult,
getMainLane, getMainLane,
LEADERBOARD_MIN_GAMES, LEADERBOARD_MIN_GAMES,
LEADERBOARD_SORTS, LEADERBOARD_SORTS,
@@ -38,10 +37,6 @@ import {
getHistoryMatchTitle, getHistoryMatchTitle,
getHomeMatchSchedule, getHomeMatchSchedule,
} from './home-match-presentation'; } from './home-match-presentation';
import {
getSeriesHistoryResultLabel,
shouldDisplaySeriesHistoryScore,
} from '../components/competition/competition-series-history';
import { import {
Btn, Btn,
Chip, Chip,
@@ -50,7 +45,6 @@ import {
LoadingNote, LoadingNote,
Panel, Panel,
PanelHeader, PanelHeader,
Pill,
PlainPage, PlainPage,
Skeleton, Skeleton,
} from '../ui'; } from '../ui';
@@ -95,122 +89,14 @@ function ChampionChip({
); );
} }
function OfficialMatchResult({
competition,
}: {
competition: CompetitionDetailResponse;
}) {
const { projection, teams } = competition;
const teamName = (id: string) =>
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 (
<span className="flex shrink-0 -space-x-1.5" aria-hidden="true">
{members.slice(0, 5).map((member) => (
<img
key={member.userId}
src={profileIconUrl(manifest, member.profileIconId)}
alt=""
title={member.summonerName}
className="size-6 rounded-full bg-sunken-strong object-cover ring-2 ring-card"
loading="lazy"
/>
))}
</span>
);
}
/** 펼치지 않아도 보이는 결과 요약. 목록 응답에 담긴 값만 쓴다. */
function MatchOutcomeSummary({
match,
recordedGameCount,
manifest,
}: {
match: ApiInternalMatchCard;
recordedGameCount: number;
manifest: Manifest;
}) {
const outcome = getInternalMatchOutcome(match);
if (!outcome) {
return (
<span className="flex items-center gap-2">
{match.status === 'in-progress' && (
<Pill tone="live" dot>
진행 중
</Pill>
)}
<span className="tabular">{recordedGameCount}세트 수집</span>
</span>
);
}
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 (
<span className="flex min-w-0 items-center gap-2">
<span className={nameClass(left)}>{left.name}</span>
<strong className="tabular shrink-0 rounded-full bg-sunken-strong px-2.5 py-0.5 text-content-strong">
{leftWins} : {rightWins}
</strong>
<span className={nameClass(right)}>{right.name}</span>
</span>
);
}
return (
<span className="flex min-w-0 items-center gap-2">
<Pill tone="gold">우승</Pill>
<strong className="min-w-0 truncate font-bold text-content">
{outcome.winner.name}
</strong>
<MemberStack members={outcome.winner.members} manifest={manifest} />
</span>
);
}
function MatchCard({ function MatchCard({
match, match,
communityId, communityId,
manifest,
}: { }: {
match: ApiInternalMatchCard; match: ApiInternalMatchCard;
communityId: string; communityId: string;
manifest: Manifest;
}) { }) {
const [open, setOpen] = useState(false); const result = match.resultPresentation;
const competition = useCompetition(match.matchId, communityId, open);
const location = useLocation(); const location = useLocation();
const backTo = `${location.pathname}${location.search}`; const backTo = `${location.pathname}${location.search}`;
const recordedGames = match.games.filter( const recordedGames = match.games.filter(
@@ -224,10 +110,7 @@ function MatchCard({
return ( return (
<li> <li>
<details <details className="group">
className="group"
onToggle={(event) => setOpen(event.currentTarget.open)}
>
<summary className="grid cursor-pointer list-none grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-2 px-4 py-3.5 hover:bg-sunken focus-visible:-outline-offset-2 sm:grid-cols-[minmax(0,1fr)_minmax(0,18rem)_auto] sm:px-5 [&::-webkit-details-marker]:hidden"> <summary className="grid cursor-pointer list-none grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-2 px-4 py-3.5 hover:bg-sunken focus-visible:-outline-offset-2 sm:grid-cols-[minmax(0,1fr)_minmax(0,18rem)_auto] sm:px-5 [&::-webkit-details-marker]:hidden">
<span className="min-w-0"> <span className="min-w-0">
<span className="tabular block text-xs text-content-muted"> <span className="tabular block text-xs text-content-muted">
@@ -243,76 +126,62 @@ function MatchCard({
</strong> </strong>
</span> </span>
<span className="col-start-1 row-start-2 flex min-w-0 text-sm text-content-muted sm:col-start-2 sm:row-start-1 sm:justify-end"> <span className="col-start-1 row-start-2 flex min-w-0 text-sm text-content-muted sm:col-start-2 sm:row-start-1 sm:justify-end">
{competition.data ? ( <strong className="font-semibold text-content">
<strong className="font-semibold text-content"> {formatOfficialMatchResult(result)}
<OfficialMatchResult competition={competition.data} /> </strong>
</strong>
) : (
<MatchOutcomeSummary
match={match}
recordedGameCount={recordedGames.length}
manifest={manifest}
/>
)}
</span> </span>
<ChevronDown <ChevronDown
className="col-start-2 row-span-2 row-start-1 size-4 text-content-muted transition-transform group-open:rotate-180 sm:col-start-3 sm:row-span-1" className="col-start-2 row-span-2 row-start-1 size-4 text-content-muted transition-transform group-open:rotate-180 sm:col-start-3 sm:row-span-1"
aria-hidden="true" aria-hidden="true"
/> />
</summary> </summary>
{open && ( <div className="border-t border-line bg-sunken px-4 py-3 sm:px-5">
<div className="border-t border-line bg-sunken px-4 py-3 sm:px-5"> <div className="flex flex-wrap items-center justify-between gap-2 text-sm">
<div className="flex flex-wrap items-center justify-between gap-2 text-sm"> <p className="text-content-muted">
<p className="text-content-muted"> {recordedGames.length > 0 ? '수집된 세트 기록' : '수집된 세트 기록 없음'}
{competition.isLoading </p>
? '공식 결과를 확인하는 중' <Link
: competition.data className="font-semibold hover:underline"
? '수집된 세트 기록' to={internalMatchDetailPath(communityId, match.matchId)}
: '공식 시리즈 정보를 확인할 수 없습니다'} state={{ backTo }}
</p> >
<Link 내전 기록 전체 보기 →
className="font-semibold hover:underline" </Link>
to={internalMatchDetailPath(communityId, match.matchId)}
state={{ backTo }}
>
내전 기록 전체 보기 →
</Link>
</div>
{recordedGames.length > 0 && (
<ul className="mt-2 divide-y divide-line text-sm">
{recordedGames.map((game) => {
const winner = match.teams.find(
({ teamIndex }) => teamIndex === game.winnerTeamIndex,
);
return (
<li
key={game.gameNumber}
className="flex flex-wrap items-center justify-between gap-x-3 py-2"
>
<span className="tabular">
전체 {game.gameNumber}세트 ·{' '}
{winner ? `${winner.name} 승` : '팀 미확인'}
</span>
{game.riotMatchId && (
<Link
className="font-semibold hover:underline"
to={internalMatchGamePath(
communityId,
match.matchId,
game.gameNumber,
)}
state={{ backTo, backLabel: '내전 전적으로' }}
>
상세 분석
</Link>
)}
</li>
);
})}
</ul>
)}
</div> </div>
)} {recordedGames.length > 0 && (
<ul className="mt-2 divide-y divide-line text-sm">
{recordedGames.map((game) => {
const winner = match.teams.find(
({ teamIndex }) => teamIndex === game.winnerTeamIndex,
);
return (
<li
key={game.gameNumber}
className="flex flex-wrap items-center justify-between gap-x-3 py-2"
>
<span className="tabular">
전체 {game.gameNumber}세트 ·{' '}
{winner ? `${winner.name} 승` : '팀 미확인'}
</span>
{game.riotMatchId && (
<Link
className="font-semibold hover:underline"
to={internalMatchGamePath(
communityId,
match.matchId,
game.gameNumber,
)}
state={{ backTo, backLabel: '내전 전적으로' }}
>
상세 분석
</Link>
)}
</li>
);
})}
</ul>
)}
</div>
</details> </details>
</li> </li>
); );
@@ -567,7 +436,7 @@ export default function CommunityInternalStatsPage() {
const isRanking = searchParams.get('view') === 'ranking'; const isRanking = searchParams.get('view') === 'ranking';
const seasonId = searchParams.get('seasonId') || 'current'; const seasonId = searchParams.get('seasonId') || 'current';
const query = searchParams.get('q') ?? ''; 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 format = searchParams.get('format');
const playerId = searchParams.get('player'); const playerId = searchParams.get('player');
const sort = parseLeaderboardSort(searchParams.get('sort')); const sort = parseLeaderboardSort(searchParams.get('sort'));
@@ -579,12 +448,18 @@ export default function CommunityInternalStatsPage() {
limit: 12, limit: 12,
}; };
const communityQuery = useCommunity(communityId); const communityQuery = useCommunity(communityId);
const seasonsQuery = useCommunityStatsSeasons(communityId);
const matchesQuery = useCommunityInternalStatsMatches( const matchesQuery = useCommunityInternalStatsMatches(
filters, {
...filters,
query: isRanking ? undefined : keyword,
format: format === 'pair' || format === 'tournament' ? format : undefined,
playerId: playerId ?? undefined,
},
communityId, communityId,
!isRanking, !isRanking,
); );
const leaderboardQuery = useCommunityLeaderboard(filters, communityId); const leaderboardQuery = useCommunityLeaderboard({ ...filters, query: isRanking ? keyword : undefined }, communityId);
const insightsQuery = useTeamInsights(filters, communityId); const insightsQuery = useTeamInsights(filters, communityId);
const { data: ddragon } = useDdragonManifest(); const { data: ddragon } = useDdragonManifest();
const matches = const matches =
@@ -599,24 +474,12 @@ export default function CommunityInternalStatsPage() {
sort, sort,
); );
const player = leaderboardRows.find((row) => row.userId === playerId); const player = leaderboardRows.find((row) => row.userId === playerId);
const visibleMatches = matches.filter((match) => { const matchedUsers = leaderboardQuery.data?.matchedUserIds;
const matchType = match.teams.length === 2 ? 'pair' : 'tournament'; const visiblePlayers = isRanking && keyword
return ( ? leaderboardRows.filter((row) => matchedUsers?.includes(row.userId))
((format !== 'pair' && format !== 'tournament') || : leaderboardRows;
matchType === format) && const hasMatchFilters = Boolean(keyword || format || playerId);
(!playerId || const confirmedSideWinRate = insights?.sideWinRate.confirmed;
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 title = isRanking ? '선수 순위' : '최근 내전'; const title = isRanking ? '선수 순위' : '최근 내전';
if (!communityId) { if (!communityId) {
@@ -673,7 +536,11 @@ export default function CommunityInternalStatsPage() {
> >
<option value="current">현재 시즌</option> <option value="current">현재 시즌</option>
<option value="all">전체 시즌</option> <option value="all">전체 시즌</option>
{seasonId !== 'current' && seasonId !== 'all' && ( {seasonsQuery.data?.seasons
.filter(({ id }) => id !== 'current' && id !== 'all')
.map(({ id, label }) => <option key={id} value={id}>{label}</option>)}
{seasonId !== 'current' && seasonId !== 'all' &&
!seasonsQuery.data?.seasons.some(({ id }) => id === seasonId) && (
<option value={seasonId}>{season?.label ?? seasonId}</option> <option value={seasonId}>{season?.label ?? seasonId}</option>
)} )}
</select> </select>
@@ -703,6 +570,7 @@ export default function CommunityInternalStatsPage() {
<input <input
type="search" type="search"
aria-label={isRanking ? '선수 검색' : '내전명 검색'} aria-label={isRanking ? '선수 검색' : '내전명 검색'}
maxLength={100}
placeholder={isRanking ? '선수 이름 검색' : '내전명 검색'} placeholder={isRanking ? '선수 이름 검색' : '내전명 검색'}
value={query} value={query}
onChange={(event) => updateParam('q', event.target.value)} onChange={(event) => updateParam('q', event.target.value)}
@@ -716,7 +584,7 @@ export default function CommunityInternalStatsPage() {
<h2 id="internal-stats-heading" className="text-base font-bold"> <h2 id="internal-stats-heading" className="text-base font-bold">
{title}{' '} {title}{' '}
<span className="tabular ml-1 text-sm font-medium text-content-muted"> <span className="tabular ml-1 text-sm font-medium text-content-muted">
{isRanking ? visiblePlayers.length : visibleMatches.length} {isRanking ? visiblePlayers.length : matches.length}
</span> </span>
</h2> </h2>
{isRanking ? ( {isRanking ? (
@@ -841,34 +709,28 @@ export default function CommunityInternalStatsPage() {
} }
/> />
</div> </div>
) : visibleMatches.length === 0 ? ( ) : matches.length === 0 ? (
<EmptyNote <EmptyNote
size="sm" size="sm"
title={ title={
hasMatchFilters hasMatchFilters
? '불러온 기록에 일치하는 내전이 없습니다' ? '조건에 일치하는 내전이 없습니다'
: '아직 수집된 내전 결과가 없습니다' : '아직 수집된 내전 결과가 없습니다'
} }
/> />
) : ( ) : (
<ul className="divide-y divide-line"> <ul className="divide-y divide-line">
{visibleMatches.map((match) => ( {matches.map((match) => (
<MatchCard <MatchCard
key={match.matchId} key={match.matchId}
match={match} match={match}
communityId={communityId} communityId={communityId}
manifest={ddragon}
/> />
))} ))}
</ul> </ul>
)} )}
{matchesQuery.hasNextPage && ( {matchesQuery.hasNextPage && (
<div className="space-y-2 border-t border-line p-3"> <div className="space-y-2 border-t border-line p-3">
{hasMatchFilters && (
<p className="text-center text-xs text-content-muted">
필터는 불러온 {matches.length}건에 적용됩니다.
</p>
)}
{matchesQuery.isFetchNextPageError && ( {matchesQuery.isFetchNextPageError && (
<p <p
role="status" role="status"
@@ -901,12 +763,10 @@ export default function CommunityInternalStatsPage() {
<div className="p-4"> <div className="p-4">
{insightsQuery.isLoading ? ( {insightsQuery.isLoading ? (
<Skeleton width="100%" height={52} /> <Skeleton width="100%" height={52} />
) : confirmedSideWinRate ? (
<SideWinRate {...confirmedSideWinRate} />
) : insights ? ( ) : insights ? (
<SideWinRate <p className="text-sm text-content-muted">확정 세트 표본을 확인할 수 없습니다.</p>
blue={insights.sideWinRate.blue}
red={insights.sideWinRate.red}
sampleSize={insights.sideWinRate.bluePicks}
/>
) : ( ) : (
<ErrorNote <ErrorNote
title="시즌 요약을 불러오지 못했습니다" title="시즌 요약을 불러오지 못했습니다"
+78 -30
View File
@@ -1,4 +1,4 @@
import { useEffect, useState, type CSSProperties } from 'react'; import { useEffect, useState, type CSSProperties, type ReactNode } from 'react';
import type { import type {
MatchDetailResponse, MatchDetailResponse,
MatchEventType, MatchEventType,
@@ -24,6 +24,7 @@ import {
Button, Button,
EmptyNote, EmptyNote,
ErrorNote, ErrorNote,
LoadingNote,
Panel, Panel,
PanelHeader, PanelHeader,
Pill, Pill,
@@ -36,11 +37,11 @@ import {
getHomeMatchEnrollment, getHomeMatchEnrollment,
getHomeMatchSchedule, getHomeMatchSchedule,
getNextMatchBanner, getNextMatchBanner,
HOME_MATCH_STATUS, getMatchStageLabel,
} from './home-match-presentation'; } from './home-match-presentation';
const UPCOMING_MATCH_LIST_LIMIT = 4; const UPCOMING_MATCH_LIST_LIMIT = 4;
const HISTORY_MATCH_PAGE_SIZE = 10; const MATCH_ARCHIVE_PAGE_SIZE = 10;
const HOME_HISTORY_LIMIT = 4; const HOME_HISTORY_LIMIT = 4;
const HOME_RANKING_LIMIT = 5; const HOME_RANKING_LIMIT = 5;
const DEFAULT_MAP_ID = 11; const DEFAULT_MAP_ID = 11;
@@ -127,9 +128,11 @@ function NextMatch({ match }: { match: MatchDetailResponse }) {
function UpcomingMatches({ function UpcomingMatches({
matches, matches,
title = '이어지는 내전', title = '이어지는 내전',
footer,
}: { }: {
matches: MatchDetailResponse[]; matches: MatchDetailResponse[];
title?: string; title?: string;
footer?: ReactNode;
}) { }) {
return ( return (
<Panel> <Panel>
@@ -156,7 +159,7 @@ function UpcomingMatches({
<p className="tabular col-start-1 mt-1 text-[13px] text-content-muted sm:col-start-3 sm:row-start-1 sm:mt-0"> <p className="tabular col-start-1 mt-1 text-[13px] text-content-muted sm:col-start-3 sm:row-start-1 sm:mt-0">
{match.status === 'recruiting' {match.status === 'recruiting'
? label ? label
: HOME_MATCH_STATUS[match.status]}{' '} : getMatchStageLabel(match)}{' '}
· {capacity} · {capacity}
</p> </p>
<ChevronRight <ChevronRight
@@ -168,6 +171,10 @@ function UpcomingMatches({
); );
})} })}
</ul> </ul>
{matches.length === 0 && (
<EmptyNote size="sm" title="이 페이지에 표시할 일정이 없습니다." />
)}
{footer}
</Panel> </Panel>
); );
} }
@@ -238,13 +245,13 @@ function HistoryResult({ match }: { match: MatchSummaryResponse }) {
tone={match.status === 'in-progress' ? 'live' : 'neutral'} tone={match.status === 'in-progress' ? 'live' : 'neutral'}
dot={match.status === 'in-progress'} dot={match.status === 'in-progress'}
> >
{HOME_MATCH_STATUS[match.status]} {getMatchStageLabel(match)}
</Pill> </Pill>
); );
} }
return ( return (
<span className="text-content-muted"> <span className="text-content-muted">
{HOME_MATCH_STATUS[match.status]} {getMatchStageLabel(match)}
</span> </span>
); );
} }
@@ -764,7 +771,7 @@ function RankingPreview({ statsPath }: { statsPath: string }) {
); );
} }
interface HistoryPaginationProps { interface MatchPaginationProps {
page: number; page: number;
pageCount: number; pageCount: number;
total: number; total: number;
@@ -773,14 +780,14 @@ interface HistoryPaginationProps {
onNext: () => void; onNext: () => void;
} }
function HistoryPagination({ function MatchPagination({
page, page,
pageCount, pageCount,
total, total,
isFetching, isFetching,
onPrevious, onPrevious,
onNext, onNext,
}: HistoryPaginationProps) { }: MatchPaginationProps) {
return ( return (
<div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1 border-t border-line px-4 py-2.5 sm:px-5"> <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1 border-t border-line px-4 py-2.5 sm:px-5">
<span className="tabular text-xs text-content-muted"> <span className="tabular text-xs text-content-muted">
@@ -814,32 +821,43 @@ export default function HomePage({ eventType }: { eventType?: MatchEventType })
const eventLabel = MATCH_EVENT_LABEL[selectedEventType]; const eventLabel = MATCH_EVENT_LABEL[selectedEventType];
const [timelineNow] = useState(() => new Date().toISOString()); const [timelineNow] = useState(() => new Date().toISOString());
const [searchParams, setSearchParams] = useSearchParams(); const [searchParams, setSearchParams] = useSearchParams();
const requestedPage = Number(searchParams.get('page')); function getPage(key: 'page' | 'activePage') {
const historyPage = const page = Number(searchParams.get(key));
showArchive && Number.isSafeInteger(requestedPage) && requestedPage > 0 return showArchive && Number.isSafeInteger(page) && page > 0 ? page : 1;
? requestedPage }
: 1; const historyPage = getPage('page');
const historyLimit = showArchive const activePage = getPage('activePage');
? HISTORY_MATCH_PAGE_SIZE const historyLimit = showArchive ? MATCH_ARCHIVE_PAGE_SIZE : HOME_HISTORY_LIMIT;
: HOME_HISTORY_LIMIT; const activeLimit = showArchive ? MATCH_ARCHIVE_PAGE_SIZE : UPCOMING_MATCH_LIST_LIMIT;
function setHistoryPage(page: number) { function setPage(key: 'page' | 'activePage', page: number) {
const params = new URLSearchParams(searchParams); setSearchParams((previous) => {
if (page > 1) params.set('page', String(page)); const params = new URLSearchParams(previous);
else params.delete('page'); if (page > 1) params.set(key, String(page));
setSearchParams(params, { preventScrollReset: true }); else params.delete(key);
return params;
}, { preventScrollReset: true });
} }
const upcomingMatchesQuery = useMatches({ const upcomingMatchesQuery = useMatches({
eventType: selectedEventType, eventType: selectedEventType,
view: 'upcoming',
asOf: timelineNow,
limit: UPCOMING_MATCH_LIST_LIMIT, limit: UPCOMING_MATCH_LIST_LIMIT,
scheduledFrom: timelineNow,
sort: 'asc', sort: 'asc',
}); });
const activeMatchesQuery = useMatchesPage({
eventType: selectedEventType,
view: 'active',
asOf: timelineNow,
limit: activeLimit,
page: activePage,
sort: 'desc',
});
const historyMatchesQuery = useMatchesPage({ const historyMatchesQuery = useMatchesPage({
eventType: selectedEventType, eventType: selectedEventType,
view: 'history',
asOf: timelineNow,
limit: historyLimit, limit: historyLimit,
page: historyPage, page: historyPage,
status: showArchive ? undefined : 'finished',
scheduledTo: showArchive ? timelineNow : undefined,
sort: 'desc', sort: 'desc',
includeResults: true, includeResults: true,
}); });
@@ -860,6 +878,11 @@ export default function HomePage({ eventType }: { eventType?: MatchEventType })
const bannerMatch = showArchive ? undefined : nextMatch; const bannerMatch = showArchive ? undefined : nextMatch;
const visibleUpcomingMatches = showArchive ? allUpcomingMatches : upcomingMatches; const visibleUpcomingMatches = showArchive ? allUpcomingMatches : upcomingMatches;
const historyTotal = historyMatchesQuery.data?.total ?? 0; 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( const historyPageCount = Math.max(
1, 1,
Math.ceil(historyTotal / (historyMatchesQuery.data?.limit ?? historyLimit)), Math.ceil(historyTotal / (historyMatchesQuery.data?.limit ?? historyLimit)),
@@ -882,6 +905,31 @@ export default function HomePage({ eventType }: { eventType?: MatchEventType })
<h1 className="text-2xl font-bold">{eventLabel} 일정</h1> <h1 className="text-2xl font-bold">{eventLabel} 일정</h1>
</header> </header>
)} )}
{activeMatchesQuery.isError && !activeMatchesQuery.data ? (
<ErrorNote title="진행 중인 일정을 불러오지 못했습니다"
action={<Button size="sm" label="다시 시도" onClick={() => void activeMatchesQuery.refetch()} />} />
) : activeMatchesQuery.isPlaceholderData ? (
<Panel aria-busy="true">
<PanelHeader title="진행 중인 일정" />
<LoadingNote label="일정을 불러오는 중" />
</Panel>
) : activeMatchesQuery.data &&
(activeMatchesQuery.data.matches.length > 0 || activePage > 1) ? (
<UpcomingMatches
matches={activeMatchesQuery.data.matches}
title="진행 중인 일정"
footer={showArchive && (activePageCount > 1 || activePage > 1) && (
<MatchPagination
page={activePage}
pageCount={activePageCount}
total={activeTotal}
isFetching={activeMatchesQuery.isFetching}
onPrevious={() => setPage('activePage', Math.min(activePage - 1, activePageCount))}
onNext={() => setPage('activePage', activePage + 1)}
/>
)}
/>
) : null}
{upcomingMatchesQuery.isLoading ? ( {upcomingMatchesQuery.isLoading ? (
<UpcomingStatusHeading className="text-sm text-content-muted" aria-busy="true"> <UpcomingStatusHeading className="text-sm text-content-muted" aria-busy="true">
{eventLabel} 일정을 불러오는 중 {eventLabel} 일정을 불러오는 중
@@ -921,7 +969,7 @@ export default function HomePage({ eventType }: { eventType?: MatchEventType })
> >
<HistorySection aria-busy={isHistoryPageLoading} aria-live="polite"> <HistorySection aria-busy={isHistoryPageLoading} aria-live="polite">
<PanelHeader <PanelHeader
title={showArchive ? '지난 일정과 결과' : '최근 내전 결과'} title={showArchive ? '종료된 일정과 결과' : '최근 내전 결과'}
variant={showArchive ? 'panel' : 'section'} variant={showArchive ? 'panel' : 'section'}
actions={ actions={
<Link <Link
@@ -961,14 +1009,14 @@ export default function HomePage({ eventType }: { eventType?: MatchEventType })
) : ( ) : (
<RecentMatchResults matches={historyMatchesQuery.data?.matches ?? []} /> <RecentMatchResults matches={historyMatchesQuery.data?.matches ?? []} />
)} )}
{showArchive && !hasHistoryError && historyTotal > 0 && ( {showArchive && !hasHistoryError && (historyTotal > 0 || historyPage > 1) && (
<HistoryPagination <MatchPagination
page={historyPage} page={historyPage}
pageCount={historyPageCount} pageCount={historyPageCount}
total={historyTotal} total={historyTotal}
isFetching={historyMatchesQuery.isFetching} isFetching={historyMatchesQuery.isFetching}
onPrevious={() => setHistoryPage(Math.max(1, historyPage - 1))} onPrevious={() => setPage('page', Math.min(historyPage - 1, historyPageCount))}
onNext={() => setHistoryPage(historyPage + 1)} onNext={() => setPage('page', historyPage + 1)}
/> />
)} )}
</HistorySection> </HistorySection>
+54 -12
View File
@@ -1,7 +1,8 @@
import { Link, useLocation, useParams } from "react-router"; 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 type { ApiInternalMatchDetailResponse, TeamSide } from "../api/types";
import { DEFAULT_COMMUNITY_ID } from "../config"; import { DEFAULT_COMMUNITY_ID } from "../config";
import { ApiError } from "../lib/api";
import { import {
championDisplayName, championDisplayName,
championIconUrl, championIconUrl,
@@ -12,12 +13,16 @@ import {
} from "../lib/league"; } from "../lib/league";
import { internalMatchGamePath } from "../lib/internal-match-routes"; import { internalMatchGamePath } from "../lib/internal-match-routes";
import { groupRecordedSets } from "../lib/internal-match-series"; 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 { LANE_LABELS } from "../lib/riot-history";
import { ItemIcon } from "../components/ItemTooltip"; import { ItemIcon } from "../components/ItemTooltip";
import { BasicGameScoreboard } from "../components/BasicGameScoreboard";
import { import {
Btn, Btn,
EmptyNote, EmptyNote,
ErrorNote,
LoadingNote, LoadingNote,
MetaDot, MetaDot,
PageBody, PageBody,
@@ -101,17 +106,22 @@ function GamePanel({
communityId, communityId,
matchId, matchId,
game, game,
teams,
ordinal, ordinal,
riotMatchId,
manifest, manifest,
}: { }: {
communityId: string; communityId: string;
matchId: string; matchId: string;
game: ApiInternalMatchDetailResponse["games"][number]; game: ApiInternalMatchDetailResponse["games"][number];
teams: ApiInternalMatchDetailResponse["match"]["teams"];
ordinal?: number; ordinal?: number;
riotMatchId: string | null;
manifest: ReturnType<typeof useDdragonManifest>["data"]; manifest: ReturnType<typeof useDdragonManifest>["data"];
}) { }) {
const location = useLocation(); const location = useLocation();
const historyBackTo = `${location.pathname}${location.search}${location.hash}`; const historyBackTo = `${location.pathname}${location.search}${location.hash}`;
const hasAnalysis = !game.analysisAvailability || game.analysisAvailability === "available";
return ( return (
<section className="lts-panel overflow-hidden"> <section className="lts-panel overflow-hidden">
@@ -125,8 +135,10 @@ function GamePanel({
</h3> </h3>
<p className="mt-1 text-xs text-base-content/35"> <p className="mt-1 text-xs text-base-content/35">
{formatDateTime(game.gameCreation)} ·{" "} {formatDateTime(game.gameCreation)} ·{" "}
{formatDuration(game.gameDuration)} ·{" "} {formatDuration(game.gameDuration)}
<span className="font-mono">{game.riotMatchId}</span> {riotMatchId && (
<> · <span className="font-mono">{riotMatchId}</span></>
)}
</p> </p>
</div> </div>
<div className="flex gap-2"> <div className="flex gap-2">
@@ -135,7 +147,7 @@ function GamePanel({
state={{ backTo: historyBackTo }} 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" 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 ? "상세 분석" : "경기 기록"}
</Link> </Link>
{game.teams.map((team) => ( {game.teams.map((team) => (
<span <span
@@ -155,7 +167,7 @@ function GamePanel({
</div> </div>
</div> </div>
{game.teams.map((team) => ( {hasAnalysis ? game.teams.map((team) => (
<div <div
key={team.side} key={team.side}
className="border-b border-base-content/8 last:border-b-0" className="border-b border-base-content/8 last:border-b-0"
@@ -246,7 +258,7 @@ function GamePanel({
</table> </table>
</div> </div>
</div> </div>
))} )) : <BasicGameScoreboard game={game} teams={teams} manifest={manifest} />}
</section> </section>
); );
} }
@@ -260,7 +272,6 @@ export default function InternalMatchDetailPage() {
? requestedBack ? requestedBack
: `/communities/${communityId}/internal-stats`; : `/communities/${communityId}/internal-stats`;
const detailQuery = useInternalMatchDetail(matchId, communityId); const detailQuery = useInternalMatchDetail(matchId, communityId);
const competition = useCompetition(matchId, communityId);
const { data: ddragon } = useDdragonManifest(); const { data: ddragon } = useDdragonManifest();
const detail = detailQuery.data; 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 (
<PlainPage>
<ErrorNote title="내전 기록을 불러오지 못했습니다"
action={<Btn onClick={() => void detailQuery.refetch()}>다시 시도</Btn>} />
</PlainPage>
);
}
if (!detail) {
return ( return (
<PlainPage> <PlainPage>
<EmptyNote <EmptyNote
@@ -287,7 +306,11 @@ export default function InternalMatchDetailPage() {
); );
} }
const groups = groupRecordedSets(detail, competition.data); const groups = groupRecordedSets(detail);
const competition = detail.competition;
const unanalysedGames = competition?.projection.games.filter(
(game) => !detail.games.some((record) => record.gameId === game.id),
) ?? [];
return ( return (
<> <>
@@ -305,6 +328,12 @@ export default function InternalMatchDetailPage() {
<span>{detail.match.teams.length}팀</span> <span>{detail.match.teams.length}팀</span>
<MetaDot /> <MetaDot />
<span>{detail.games.length}세트 수집</span> <span>{detail.games.length}세트 수집</span>
{competition && (
<>
<MetaDot />
<span>{formatOfficialMatchResult(detail.match.resultPresentation)}</span>
</>
)}
</> </>
} }
actions={ actions={
@@ -314,7 +343,7 @@ export default function InternalMatchDetailPage() {
} }
/> />
<PageBody width="xl" className="space-y-4"> <PageBody width="xl" className="space-y-4">
{detail.games.length === 0 && ( {detail.games.length === 0 && unanalysedGames.length === 0 && (
<Panel> <Panel>
<EmptyNote title="수집된 경기 기록이 없습니다" /> <EmptyNote title="수집된 경기 기록이 없습니다" />
</Panel> </Panel>
@@ -324,14 +353,27 @@ export default function InternalMatchDetailPage() {
<h2 className="flex flex-wrap items-baseline gap-x-2 px-1 text-base font-bold"> <h2 className="flex flex-wrap items-baseline gap-x-2 px-1 text-base font-bold">
{group.label} {group.label}
<span className="text-xs font-medium text-content-muted"> <span className="text-xs font-medium text-content-muted">
{group.series ? "시리즈" : "대진"} · {group.sets.length}세트 수집 {group.series ? "시리즈" : "공식 시리즈 정보 없음"} · {group.sets.length}세트 수집
</span> </span>
</h2> </h2>
{group.sets.map(({ game, official }) => ( {group.sets.map(({ game, official }) => (
<GamePanel key={game.riotMatchId} communityId={communityId} matchId={detail.match.matchId} game={game} ordinal={official?.ordinal} manifest={ddragon} /> <GamePanel key={game.riotMatchId} communityId={communityId} matchId={detail.match.matchId} game={game} teams={detail.match.teams} ordinal={official?.ordinal} riotMatchId={riotMatchIdForDisplay(game, official)} manifest={ddragon} />
))} ))}
</section> </section>
))} ))}
{unanalysedGames.length > 0 && (
<Panel className="space-y-2 p-4">
<h2 className="font-semibold">공식 세트 결과</h2>
<ul className="space-y-1 text-sm">
{unanalysedGames.map((game) => (
<li key={game.id}>
전체 {game.displayNumber}세트 · {competition?.teams.find((team) => team.teamId === game.winnerTeamId)?.name ?? "팀 미확인"} 승리
{" · "}{game.evidence.type === "legacy" ? "Riot 원본 없음" : "상세 분석 준비 중"}
</li>
))}
</ul>
</Panel>
)}
</PageBody> </PageBody>
</> </>
); );
+44 -11
View File
@@ -61,6 +61,7 @@ import {
} from "../components/competition/match-detail-tabs"; } from "../components/competition/match-detail-tabs";
import { DEFAULT_COMMUNITY_ID, useAuthUserId } from "../config"; import { DEFAULT_COMMUNITY_ID, useAuthUserId } from "../config";
import { apiFetch, ApiError } from "../lib/api"; import { apiFetch, ApiError } from "../lib/api";
import { getMatchStageLabel } from "./home-match-presentation";
import { profileIconUrl } from "../lib/ddragon"; import { profileIconUrl } from "../lib/ddragon";
import { import {
POSITION_ORDER, POSITION_ORDER,
@@ -1000,6 +1001,9 @@ function MatchRegistration({
joining, joining,
error, error,
onJoin, onJoin,
cancelling,
cancelError,
onCancel,
}: { }: {
match: MatchDetailView; match: MatchDetailView;
canJoin: boolean; canJoin: boolean;
@@ -1008,6 +1012,9 @@ function MatchRegistration({
joining: boolean; joining: boolean;
error: Error | null; error: Error | null;
onJoin: (position: Position) => void; onJoin: (position: Position) => void;
cancelling: boolean;
cancelError: Error | null;
onCancel: () => void;
}) { }) {
const [selectedPosition, setSelectedPosition] = useState<Position>(); const [selectedPosition, setSelectedPosition] = useState<Position>();
const position = selectedPosition ?? initialPosition; const position = selectedPosition ?? initialPosition;
@@ -1059,6 +1066,13 @@ function MatchRegistration({
) )
)} )}
{error && <ErrorNote className="mt-4" title="참가 신청을 완료하지 못했습니다" description={error.message} />} {error && <ErrorNote className="mt-4" title="참가 신청을 완료하지 못했습니다" description={error.message} />}
{match.joined && canJoin && (
<Btn className="mt-4" variant="secondary" loading={cancelling}
disabled={cancelling} onClick={onCancel}>
참가 신청 취소
</Btn>
)}
{cancelError && <ErrorNote className="mt-4" title="참가 신청을 취소하지 못했습니다" description={cancelError.message} />}
</Panel> </Panel>
); );
} }
@@ -1452,6 +1466,12 @@ export default function MatchDetailPage() {
const navigate = useNavigate(); const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams(); const [searchParams, setSearchParams] = useSearchParams();
const queryClient = useQueryClient(); 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 authUserId = useAuthUserId();
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
const competitionEnabled = Boolean( const competitionEnabled = Boolean(
@@ -1527,9 +1547,7 @@ export default function MatchDetailPage() {
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null], queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null],
}), }),
queryClient.invalidateQueries({ invalidateMatchLists(),
queryKey: ["matches", DEFAULT_COMMUNITY_ID],
}),
]); ]);
}, },
onError: () => { onError: () => {
@@ -1537,6 +1555,19 @@ export default function MatchDetailPage() {
}, },
}); });
const cancelJoinMutation = useMutation({
mutationFn: () => apiFetch<MatchDetailResponse>(
`/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({ const addParticipantMutation = useMutation({
mutationFn: ({ mutationFn: ({
userId, userId,
@@ -1557,9 +1588,7 @@ export default function MatchDetailPage() {
onSuccess: async () => { onSuccess: async () => {
await Promise.all([ await Promise.all([
queryClient.invalidateQueries({ queryKey: matchQueryKey }), queryClient.invalidateQueries({ queryKey: matchQueryKey }),
queryClient.invalidateQueries({ invalidateMatchLists(),
queryKey: ["matches", DEFAULT_COMMUNITY_ID],
}),
]); ]);
}, },
}); });
@@ -1591,9 +1620,7 @@ export default function MatchDetailPage() {
}, },
onSettled: () => { onSettled: () => {
void queryClient.invalidateQueries({ queryKey: matchQueryKey }); void queryClient.invalidateQueries({ queryKey: matchQueryKey });
void queryClient.invalidateQueries({ void invalidateMatchLists();
queryKey: ["matches", DEFAULT_COMMUNITY_ID],
});
}, },
}); });
@@ -1686,6 +1713,7 @@ export default function MatchDetailPage() {
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ["auction", DEFAULT_COMMUNITY_ID, id ?? null], queryKey: ["auction", DEFAULT_COMMUNITY_ID, id ?? null],
}), }),
invalidateMatchLists(),
]); ]);
navigate(`/match/${id}/auction`); navigate(`/match/${id}/auction`);
}, },
@@ -1845,13 +1873,15 @@ export default function MatchDetailPage() {
} }
const match = mapApiMatchToMatchDetail(matchQuery.data); const match = mapApiMatchToMatchDetail(matchQuery.data);
const si = statusBadge(match.status); const si = { ...statusBadge(match.status), label: getMatchStageLabel(matchQuery.data) };
const auctionNotStarted = const auctionNotStarted =
auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404; auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404;
const activeAuction = auctionNotStarted ? null : auctionQuery.data; const activeAuction = auctionNotStarted ? null : auctionQuery.data;
const showAuctionLink = Boolean(activeAuction); const showAuctionLink = Boolean(activeAuction);
const hasTeamProgress = Boolean(competitionQuery.data?.teams.length) && 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( const auctionParticipantPool = buildAuctionParticipantPool(
matchQuery.data.participants, matchQuery.data.participants,
); );
@@ -2010,6 +2040,9 @@ export default function MatchDetailPage() {
joining={joinMatchMutation.isPending} joining={joinMatchMutation.isPending}
error={joinMatchMutation.error} error={joinMatchMutation.error}
onJoin={joinMatchMutation.mutate} onJoin={joinMatchMutation.mutate}
cancelling={cancelJoinMutation.isPending}
cancelError={cancelJoinMutation.error}
onCancel={() => cancelJoinMutation.mutate()}
/> />
)} )}
+83 -52
View File
@@ -13,7 +13,7 @@ import {
XAxis, XAxis,
YAxis, YAxis,
} from "recharts"; } from "recharts";
import { useCompetition, useDdragonManifest, useInternalMatchDetail } from "../api/hooks"; import { useDdragonManifest, useInternalMatchDetail } from "../api/hooks";
import type { ApiInternalMatchDetailResponse, TeamSide } from "../api/types"; import type { ApiInternalMatchDetailResponse, TeamSide } from "../api/types";
import { DEFAULT_COMMUNITY_ID } from "../config"; import { DEFAULT_COMMUNITY_ID } from "../config";
import { import {
@@ -30,7 +30,10 @@ import {
internalMatchGamePath, internalMatchGamePath,
} from "../lib/internal-match-routes"; } from "../lib/internal-match-routes";
import { selectInternalMatchGame } from "../lib/internal-match-game-selection"; 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 { 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 { getSeriesHistoryResultLabel, shouldDisplaySeriesHistoryScore } from "../components/competition/competition-series-history";
import { LANE_LABELS } from "../lib/riot-history"; import { LANE_LABELS } from "../lib/riot-history";
import { import {
@@ -58,6 +61,7 @@ import {
import { import {
Btn, Btn,
EmptyNote, EmptyNote,
ErrorNote,
LoadingNote, LoadingNote,
MetaDot, MetaDot,
PageBody, PageBody,
@@ -1626,15 +1630,16 @@ function MatchScoreHero({
}) { }) {
const selectedSeries = group.series; const selectedSeries = group.series;
const officialGame = group.sets.find(({ game }) => game === selectedGame)?.official; const officialGame = group.sets.find(({ game }) => game === selectedGame)?.official;
const riotMatchId = riotMatchIdForDisplay(selectedGame, officialGame);
const setLabel = officialGame ? `${officialGame.ordinal}세트` : `전체 ${selectedGame.gameNumber}세트`; const setLabel = officialGame ? `${officialGame.ordinal}세트` : `전체 ${selectedGame.gameNumber}세트`;
const [leftTeam, rightTeam] = selectedGame.teams; const [leftTeam, rightTeam] = selectedGame.teams;
const getScore = (side: TeamSide) => selectedSeries?.entries.find( const teamName = (teamId: string | null) =>
(entry) => entry.teamId === officialGame?.teams[side].teamId, detail.competition?.teams.find((team) => team.teamId === teamId)?.name ?? "팀 미확인";
)?.gameWins; const seriesSummary = selectedSeries && shouldDisplaySeriesHistoryScore(selectedSeries)
const leftScore = leftTeam && getScore(leftTeam.side); ? `${selectedSeries.status === "in-progress" ? "시리즈 현재" : "시리즈 최종"} · ${selectedSeries.entries.map(
const rightScore = rightTeam && getScore(rightTeam.side); ({ teamId, gameWins }) => `${teamName(teamId)} ${gameWins}`,
const showSeriesScore = selectedSeries && shouldDisplaySeriesHistoryScore(selectedSeries) && leftScore !== undefined && rightScore !== undefined; ).join(" : ")}`
const decision = selectedSeries?.status === "completed" ? getSeriesHistoryResultLabel(selectedSeries) : null; : selectedSeries?.status === "completed" ? getSeriesHistoryResultLabel(selectedSeries) : null;
const sideTone = (side: TeamSide) => const sideTone = (side: TeamSide) =>
side === "blue" ? "text-win" : "text-loss"; side === "blue" ? "text-win" : "text-loss";
@@ -1666,8 +1671,18 @@ function MatchScoreHero({
<span className="tabular"> <span className="tabular">
{formatDuration(selectedGame.gameDuration)} {formatDuration(selectedGame.gameDuration)}
</span> </span>
<MetaDot /> {riotMatchId && (
<span className="font-mono text-xs">{selectedGame.riotMatchId}</span> <>
<MetaDot />
<span className="font-mono text-xs">{riotMatchId}</span>
</>
)}
{seriesSummary && (
<>
<MetaDot />
<span>{seriesSummary}</span>
</>
)}
</> </>
} }
actions={ actions={
@@ -1687,16 +1702,7 @@ function MatchScoreHero({
</div> </div>
</div> </div>
<div className="text-center"> <div className="text-center">
{showSeriesScore ? ( <div className="text-sm font-semibold text-on-ink-muted">세트 결과</div>
<>
<div className="tabular text-4xl font-extrabold">{leftScore} : {rightScore}</div>
<div className="mt-0.5 text-xs font-semibold text-on-ink-muted">
{selectedSeries.status === "in-progress" ? "시리즈 진행 스코어" : "시리즈 스코어"}
</div>
</>
) : (
<div className="text-sm font-semibold text-on-ink-muted">{decision ?? "세트 결과"}</div>
)}
</div> </div>
<div className="min-w-0"> <div className="min-w-0">
<div <div
@@ -1727,10 +1733,11 @@ export default function MatchGameDetailPage() {
const resolvedMatchId = matchId ?? id; const resolvedMatchId = matchId ?? id;
const requestedGameNumber = Number(gameNumber); const requestedGameNumber = Number(gameNumber);
const detailQuery = useInternalMatchDetail(resolvedMatchId, communityId); const detailQuery = useInternalMatchDetail(resolvedMatchId, communityId);
const competition = useCompetition(resolvedMatchId, communityId);
const { data: ddragon } = useDdragonManifest(); const { data: ddragon } = useDdragonManifest();
const detail = detailQuery.data; const detail = detailQuery.data;
const fallbackBackTo = resolvedMatchId const fallbackBackTo = id
? `/match/${id}?tab=games`
: resolvedMatchId
? internalMatchDetailPath(communityId, resolvedMatchId) ? internalMatchDetailPath(communityId, resolvedMatchId)
: `/communities/${communityId}/internal-stats`; : `/communities/${communityId}/internal-stats`;
const backTarget = resolveBackTarget(location.state, fallbackBackTo); const backTarget = resolveBackTarget(location.state, fallbackBackTo);
@@ -1744,7 +1751,15 @@ export default function MatchGameDetailPage() {
); );
} }
if (detailQuery.error || !detail) { if (detailQuery.isError && !(detailQuery.error instanceof ApiError && detailQuery.error.status === 404)) {
return (
<PlainPage>
<ErrorNote title="세트 기록을 불러오지 못했습니다"
action={<Btn onClick={() => void detailQuery.refetch()}>다시 시도</Btn>} />
</PlainPage>
);
}
if (!detail) {
return ( return (
<PlainPage> <PlainPage>
<EmptyNote <EmptyNote
@@ -1760,9 +1775,24 @@ export default function MatchGameDetailPage() {
requestedGameNumber, requestedGameNumber,
); );
const groups = groupRecordedSets(detail, competition.data); const groups = groupRecordedSets(detail);
const group = groups.find(({ sets }) => sets.some(({ game }) => game === selectedGame)); const group = groups.find(({ sets }) => sets.some(({ game }) => game === selectedGame));
if (!selectedGame || !group) { 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 (
<PlainPage>
<EmptyNote
title={officialGame.evidence.type === "legacy" ? "Riot 원본이 없는 과거 기록" : "상세 분석 준비 중"}
description={`${officialGame.ordinal}세트 · ${winner?.name ?? "팀 미확인"} 승리`}
action={<Btn to={backTarget.to}>{backTarget.label}</Btn>}
/>
</PlainPage>
);
}
const hasRecordedGames = detail.games.length > 0; const hasRecordedGames = detail.games.length > 0;
const requestedGameLabel = const requestedGameLabel =
Number.isSafeInteger(requestedGameNumber) && requestedGameNumber > 0 Number.isSafeInteger(requestedGameNumber) && requestedGameNumber > 0
@@ -1805,38 +1835,39 @@ export default function MatchGameDetailPage() {
navigationState={navigationState} navigationState={navigationState}
/> />
<PostgameBreakdown {!selectedGame.analysisAvailability || selectedGame.analysisAvailability === "available" ? (
selectedGame={selectedGame} <>
detail={detail} <PostgameBreakdown
manifest={ddragon}
/>
<TimelineGraph
key={selectedGame.riotMatchId}
selectedGame={selectedGame}
detail={detail}
manifest={ddragon}
/>
<div className="mt-5 space-y-4">
<InternalGameDetailTabBar
activeTab={activeTab}
onChange={setActiveTab}
/>
<InternalGameAnalysisPanel
activeTab={activeTab}
selectedGame={selectedGame}
detail={detail}
manifest={ddragon}
scoreboard={
<ScoreboardTables
selectedGame={selectedGame} selectedGame={selectedGame}
detail={detail} detail={detail}
manifest={ddragon} manifest={ddragon}
/> />
} <TimelineGraph
/> key={selectedGame.riotMatchId}
</div> selectedGame={selectedGame}
detail={detail}
manifest={ddragon}
/>
<div className="mt-5 space-y-4">
<InternalGameDetailTabBar activeTab={activeTab} onChange={setActiveTab} />
<InternalGameAnalysisPanel
activeTab={activeTab}
selectedGame={selectedGame}
detail={detail}
manifest={ddragon}
scoreboard={
<ScoreboardTables
selectedGame={selectedGame}
detail={detail}
manifest={ddragon}
/>
}
/>
</div>
</>
) : (
<BasicGameScoreboard game={selectedGame} teams={detail.match.teams} manifest={ddragon} />
)}
</PageBody> </PageBody>
</> </>
); );
+11 -16
View File
@@ -52,11 +52,11 @@ import {
RANK_FILTER_TABS, RANK_FILTER_TABS,
} from "../lib/riot-history"; } from "../lib/riot-history";
import { import {
mockLargestMultiKill,
multiKillLabel, multiKillLabel,
rankPositionRates, rankPositionRates,
} from "../lib/multi-kill"; } from "../lib/multi-kill";
import { ResponsiveTierLabel } from "../components/RankBadge"; import { ResponsiveTierLabel } from "../components/RankBadge";
import { formatRankDetail } from "../components/rankBadgeUtils";
import { import {
InternalGameAnalysisPanel, InternalGameAnalysisPanel,
InternalGameDetailTabBar, InternalGameDetailTabBar,
@@ -647,8 +647,12 @@ function ParticipantRow({
> >
{participantName} {participantName}
</div> </div>
{/* 티어 (임시: 백엔드 연동 전까지 비움 — 라인은 행 순서로 식별) */} {participant.tier && (
<div className="truncate text-xs text-base-content/30">—</div> <div className="truncate text-xs text-content-muted"
title={`저장된 티어 · ${formatLastFetched(participant.tier.fetchedAt)}`}>
{formatRankDetail(participant.tier)}
</div>
)}
</div> </div>
</div> </div>
@@ -782,10 +786,9 @@ function resolveInternalDetailGame(
match: ApiRecentMatchView, match: ApiRecentMatchView,
) { ) {
if (!detail) return undefined; if (!detail) return undefined;
return ( return detail.games.find(
detail.games.find((game) => game.gameNumber === match.gameNumber) ?? (game) => game.riotMatchId === match.matchId &&
detail.games.find((game) => game.riotMatchId === match.matchId) ?? (match.gameNumber === undefined || game.gameNumber === match.gameNumber),
detail.games[0]
); );
} }
@@ -914,14 +917,7 @@ function RecentMatchCard({
ownerParticipantId: string; ownerParticipantId: string;
}) { }) {
const [expanded, setExpanded] = useState(false); const [expanded, setExpanded] = useState(false);
// 응답에 값이 없을 때 개발 화면에서만 목업으로 배지 모양을 확인한다. const multiKill = multiKillLabel(match.largestMultiKill);
const isMockMultiKill =
match.largestMultiKill === undefined && import.meta.env.DEV;
const multiKill = multiKillLabel(
isMockMultiKill
? mockLargestMultiKill(match.kills)
: match.largestMultiKill,
);
const championName = const championName =
championDisplayName(manifest, match.championId) ?? String(match.championId); championDisplayName(manifest, match.championId) ?? String(match.championId);
const outcome = match.remake ? "remake" : match.win ? "win" : "loss"; const outcome = match.remake ? "remake" : match.win ? "win" : "loss";
@@ -964,7 +960,6 @@ function RecentMatchCard({
{multiKill && ( {multiKill && (
<span <span
className="mt-1 inline-flex h-5 items-center rounded-full border border-leaf px-2 text-[11px] font-semibold text-leaf" className="mt-1 inline-flex h-5 items-center rounded-full border border-leaf px-2 text-[11px] font-semibold text-leaf"
title={isMockMultiKill ? "목업 데이터 (API 미지원)" : undefined}
> >
{multiKill} {multiKill}
</span> </span>
+15 -7
View File
@@ -1,4 +1,4 @@
import type { MatchDetailResponse } from '@lolympus/contracts'; import type { MatchDetailResponse, MatchEventStage } from '@lolympus/contracts';
const scheduleFormatter = new Intl.DateTimeFormat('ko-KR', { const scheduleFormatter = new Intl.DateTimeFormat('ko-KR', {
timeZone: 'Asia/Seoul', timeZone: 'Asia/Seoul',
@@ -10,16 +10,25 @@ const scheduleFormatter = new Intl.DateTimeFormat('ko-KR', {
hourCycle: 'h23', hourCycle: 'h23',
}); });
export const HOME_MATCH_STATUS = { const MATCH_STAGE_LABEL: Record<MatchEventStage, string> = {
recruiting: '모집 중', recruiting: '모집 중',
'team-built': '팀빌딩', auction: '경매 중',
'team-ready': '팀 편성 완료',
'team-check': '팀빌딩 상태 확인 필요',
'in-progress': '진행 중', 'in-progress': '진행 중',
finished: '종료', finished: '종료',
} as const; };
export function getMatchStageLabel(
match: Pick<MatchDetailResponse, 'status' | 'eventProgress'>,
) {
return MATCH_STAGE_LABEL[match.eventProgress?.stage ??
(match.status === 'team-built' ? 'team-check' : match.status)];
}
type HomeMatchEnrollment = Pick< type HomeMatchEnrollment = Pick<
MatchDetailResponse, MatchDetailResponse,
'status' | 'joined' | 'participants' | 'maxParticipants' 'status' | 'eventProgress' | 'joined' | 'participants' | 'maxParticipants'
>; >;
export function getHomeMatchSchedule(scheduledAt: string) { export function getHomeMatchSchedule(scheduledAt: string) {
@@ -92,8 +101,7 @@ export function getNextMatchBanner(
const regularTitle = /^(?:[월화수목금토일]요일\s*(?:정기\s*)?|정기\s*)내전$/u; const regularTitle = /^(?:[월화수목금토일]요일\s*(?:정기\s*)?|정기\s*)내전$/u;
const title = regularTitle.test(match.title.trim()) ? '정기 내전' : match.title; const title = regularTitle.test(match.title.trim()) ? '정기 내전' : match.title;
let status: string = HOME_MATCH_STATUS[match.status]; let status = getMatchStageLabel(match);
if (match.status === 'team-built') status = '팀 편성';
if (match.status === 'recruiting') { if (match.status === 'recruiting') {
if (match.joined) status = '신청 완료'; if (match.joined) status = '신청 완료';
else if (!canApply) status = match.maxParticipants > 0 ? '정원 마감' : '모집 마감'; else if (!canApply) status = match.maxParticipants > 0 ? '정원 마감' : '모집 마감';
@@ -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 (
<span className="flex flex-wrap items-center gap-x-2 text-sm">
{result.series.teams[0]}
<strong className="tabular rounded-field bg-sunken px-2 py-0.5 text-base">
{result.series.score.join(' : ')}
</strong>
{result.series.teams[1]}
</span>
);
case 'tournament':
return (
<span className="text-sm font-semibold">
<span className="mr-2 text-xs font-medium text-content-muted">
우승
</span>
{result.champion}
</span>
);
case 'collecting':
return (
<span className="text-sm font-semibold text-content">
결과 수집 중{' '}
<span className="ml-1 font-normal text-content-muted">
{result.recordedGames}세트
</span>
</span>
);
case 'unavailable':
return <span className="text-sm text-content-muted">공식 결과 없음</span>;
}
}
function MatchDetails({ result }: { result: PreviewMatch['result'] }) {
if (result.kind === 'collecting') {
return (
<p>
수집된 {result.recordedGames}세트를 확인 중입니다. 순위와 우승팀은 대회
결과가 확정되면 표시됩니다.
</p>
);
}
if (result.kind === 'unavailable') {
return <p>내전 일정은 종료됐고 공식 결과가 등록되지 않았습니다.</p>;
}
const series = result.kind === 'tournament' ? result.final : result.series;
return (
<>
<p className="font-semibold text-content">
{result.kind === 'tournament' ? '결승 시리즈' : '시리즈 결과'}
<span className="tabular ml-2">
{series.teams[0]} {series.score.join(' : ')} {series.teams[1]}
</span>
</p>
<ol className="mt-2 divide-y divide-line">
{series.games.map((game, index) => (
<li
key={index}
className="tabular flex flex-wrap justify-between gap-x-4 py-2"
>
<span>
{index + 1}세트 ·{' '}
<strong className="font-semibold text-content">
{game.winner} 승리
</strong>
</span>
<span>{game.duration}</span>
</li>
))}
</ol>
</>
);
}
function MatchRow({ match }: { match: PreviewMatch }) {
const schedule = getHomeMatchSchedule(match.scheduledAt);
return (
<li>
<details className="group">
<summary className="grid cursor-pointer list-none grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-2 px-4 py-3.5 hover:bg-sunken focus-visible:-outline-offset-2 sm:grid-cols-[minmax(0,1fr)_minmax(0,auto)_auto] sm:px-5 [&::-webkit-details-marker]:hidden">
<span className="min-w-0">
<span className="tabular block text-xs text-content-muted">
<time dateTime={match.scheduledAt}>{schedule?.compact}</time> ·{' '}
{match.teamCount}팀
</span>
<strong className="mt-1 block break-words text-base font-semibold leading-snug">
{match.title}
</strong>
</span>
<span className="col-start-1 row-start-2 min-w-0 sm:col-start-2 sm:row-start-1">
<MatchResult result={match.result} />
</span>
<ChevronDown
className="col-start-2 row-span-2 row-start-1 size-4 text-content-muted transition-transform group-open:rotate-180 sm:col-start-3 sm:row-span-1"
aria-hidden="true"
/>
</summary>
<div className="border-t border-line bg-sunken px-4 py-3 text-sm text-content-muted sm:px-5">
<MatchDetails result={match.result} />
</div>
</details>
</li>
);
}
function Ranking({
players,
season,
}: {
players: (PreviewPlayer & { rank: number })[];
season: string;
}) {
return (
<table className="w-full table-fixed text-left text-sm">
<colgroup>
<col className="w-12" />
<col />
<col className="w-14" />
<col className="w-18" />
</colgroup>
<thead className="bg-sunken text-xs text-content-muted">
<tr>
<th scope="col" className="py-2 pl-4 font-semibold">
순위
</th>
<th scope="col" className="px-2 py-2 font-semibold">
선수
</th>
<th scope="col" className="py-2 text-right font-semibold">
세트
</th>
<th scope="col" className="py-2 pr-4 text-right font-semibold">
승률
</th>
</tr>
</thead>
<tbody className="divide-y divide-line">
{players.map((player) => {
const total = player.wins + player.losses;
const search = new URLSearchParams({ season, player: player.id });
return (
<tr key={player.id} className="hover:bg-sunken">
<td className="tabular py-3 pl-4 text-content-muted">
{player.rank}
</td>
<td className="px-2 py-3">
<Link
to={`?${search}`}
className="break-words font-semibold hover:underline"
aria-label={`${player.name}#${player.tag} 참가 내전 보기`}
>
{player.name}
<span className="font-normal text-content-muted">
#{player.tag}
</span>
</Link>
<p className="text-xs text-content-muted">{player.position}</p>
</td>
<td className="tabular py-3 text-right">{total}</td>
<td className="tabular py-3 pr-4 text-right font-semibold">
{Math.round((player.wins / total) * 100)}%
</td>
</tr>
);
})}
</tbody>
</table>
);
}
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 (
<aside
className="self-start rounded-xl border border-line bg-card p-5"
aria-labelledby="preview-season-heading"
>
<h2 id="preview-season-heading" className="text-base font-bold">
시즌 요약
</h2>
<p className="mt-1 text-xs text-content-muted">{season} 시즌 전체</p>
<dl className="tabular my-4 flex gap-6 border-b border-line pb-4 text-sm">
<div>
<dt className="text-xs text-content-muted">기록된 세트</dt>
<dd className="text-xl font-bold">{total}</dd>
</div>
<div>
<dt className="text-xs text-content-muted">집계 선수</dt>
<dd className="text-xl font-bold">{playerCount}</dd>
</div>
</dl>
<p className="text-sm font-semibold">진영 승률</p>
<div className="tabular mt-2 flex justify-between gap-2 text-xs font-semibold">
<span>블루 {blueShare}%</span>
<span>레드 {100 - blueShare}%</span>
</div>
<div
aria-hidden="true"
className="mt-2 flex h-1.5 gap-0.5 overflow-hidden rounded-full"
>
<div className="bg-win" style={{ width: `${blueShare}%` }} />
<div className="flex-1 bg-loss" />
</div>
<p className="tabular mt-2 text-xs text-content-muted">
승패가 기록된 {total}세트 기준
</p>
</aside>
);
}
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 (
<div className="min-h-[calc(100vh-var(--app-header-height))] bg-body">
<main className={`${pageWidthClass()} pb-12 pt-6 sm:pt-8`}>
<header className="flex flex-wrap items-end justify-between gap-4">
<div>
<div className="flex flex-wrap items-center gap-2 text-xs font-semibold text-content-muted">
<span className="rounded-full border border-line-strong bg-card px-2 py-0.5">
목업 데이터
</span>
<Link
to={`/communities/${DEFAULT_COMMUNITY_ID}/internal-stats`}
className="hover:underline"
>
현재 전적 화면 보기
</Link>
</div>
<h1 className="mt-2 text-2xl font-bold tracking-tight sm:text-[30px]">
내전 전적
</h1>
<p className="mt-1 text-sm text-content-muted">
최근 내전 결과와 시즌별 선수 순위
</p>
</div>
<label className="flex items-center gap-2 text-sm font-semibold">
시즌
<select
className="lts-select !w-auto"
value={season}
onChange={(event) => updateParam('season', event.target.value)}
>
<option value="2026">2026 시즌</option>
<option value="2025">2025 시즌</option>
</select>
</label>
</header>
<div className="mt-6 grid gap-5 lg:grid-cols-[minmax(0,1fr)_16rem]">
<section
aria-labelledby="preview-results-heading"
className="min-w-0"
>
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex gap-1.5" role="group" aria-label="전적 보기">
<Chip
selected={!isRanking}
onClick={() => updateParam('view', '')}
>
최근 내전
</Chip>
<Chip
selected={isRanking}
onClick={() => updateParam('view', 'ranking')}
>
선수 순위
</Chip>
</div>
<label className="flex h-10 w-full items-center gap-2 rounded-full border border-line-strong bg-card px-3 text-content-muted focus-within:border-content-muted sm:w-60">
<Search className="size-4 shrink-0" aria-hidden="true" />
<input
type="search"
aria-label={isRanking ? '선수 검색' : '내전명 검색'}
placeholder={
isRanking ? '선수 이름 또는 이름#태그' : '내전명 검색'
}
value={query}
onChange={(event) => updateParam('q', event.target.value)}
className="min-w-0 flex-1 text-sm text-content focus-visible:outline-none"
/>
</label>
</div>
<div className="mt-4 overflow-hidden rounded-xl border border-line bg-card">
<div className="flex flex-wrap items-center justify-between gap-2 border-b border-line px-4 py-3 sm:px-5">
<h2
id="preview-results-heading"
className="text-base font-bold"
>
{sectionTitle}{' '}
<span className="tabular ml-1 text-sm font-medium text-content-muted">
{count}
</span>
</h2>
{isRanking ? (
<span className="text-xs text-content-muted">승률 순</span>
) : (
<div
className="flex flex-wrap gap-1.5"
role="group"
aria-label="내전 유형"
>
{formats.map(({ value, label }) => (
<Chip
key={value}
selected={format === value}
onClick={() => updateParam('format', value)}
>
{label}
</Chip>
))}
</div>
)}
</div>
{!isRanking && player && (
<div className="border-b border-line px-4 py-2 sm:px-5">
<Chip
selected
onClick={() => updateParam('player', '')}
aria-label={`${player.name} 참가 내전 필터 해제`}
>
{player.name} 참가 내전{' '}
<X className="size-3.5" aria-hidden="true" />
</Chip>
</div>
)}
{count === 0 ? (
<EmptyNote size="sm" title="조건에 맞는 기록이 없습니다" />
) : isRanking ? (
<Ranking players={players} season={season} />
) : (
<ul className="divide-y divide-line">
{matches.map((match) => (
<MatchRow key={match.id} match={match} />
))}
</ul>
)}
</div>
</section>
<SeasonSummary
season={season}
playerCount={data.players.length}
sideWins={data.sideWins}
/>
</div>
</main>
</div>
);
}
-292
View File
@@ -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 (
<section className="match-flows-panel min-w-0 border border-line bg-card">
<h2 className="border-b border-line px-4 py-3.5 text-base font-bold sm:px-5">{title}</h2>
<div className="px-4 py-4 sm:px-5">{children}</div>
</section>
);
}
function PreviewControl({ label, children }: { label: string; children: ReactNode }) {
return (
<label className="flex flex-wrap items-center gap-2 text-sm font-medium text-content-muted">
{label}
{children}
</label>
);
}
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 (
<>
<PreviewControl label="예시 모집 상태">
<select className={selectClass} value={full ? "full" : "open"} onChange={(event) => {
setFull(event.target.value === "full");
setEntry(null);
setPosition("");
}}>
<option value="open">자리 있음</option>
<option value="full">정원 마감</option>
</select>
</PreviewControl>
<div className="match-flows-grid grid gap-4">
<Panel title="내 참가 상태">
<div className="flex flex-wrap items-center justify-between gap-2">
<p role="status" className="text-lg font-bold">
{entry === "joined" ? "참가 확정" : entry === "waiting" ? "대기 신청 완료" : full ? "현재 정원이 찼습니다" : "2자리 남았어요"}
</p>
<Pill tone={full ? "gold" : "live"}>{enrolled}/20명</Pill>
</div>
<progress className="match-flows-capacity mt-3 h-2 w-full" value={enrolled} max={20} aria-label="참가 정원" />
{entry ? (
<div className="mt-4 grid gap-3">
<p className="text-sm text-content-muted">
{entry === "joined" ? `희망 포지션은 ${position}입니다. 20:50까지 디스코드 대기실에 입장해 주세요.` : `희망 포지션은 ${position}입니다. 현재 대기 1번이며 빈자리가 생기면 순서대로 안내합니다.`}
</p>
<div><Btn variant="ghost" onClick={() => setEntry(null)}>신청 취소</Btn></div>
</div>
) : (
<form className="mt-4 grid gap-4" onSubmit={(event) => {
event.preventDefault();
setEntry(full ? "waiting" : "joined");
}}>
<fieldset>
<legend className="mb-2 text-sm font-semibold">희망 포지션</legend>
<div className="flex flex-wrap gap-2">
{positions.map((role) => (
<label key={role} className="cursor-pointer">
<input className="peer sr-only" type="radio" name="position" value={role} checked={position === role} onChange={() => setPosition(role)} />
<span className="inline-flex min-h-9 items-center rounded-full border border-line-strong px-3 text-sm peer-checked:border-transparent peer-checked:bg-secondary peer-checked:text-secondary-content peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2">{role}</span>
</label>
))}
</div>
</fieldset>
<div><Btn type="submit" variant="primary" disabled={!position} className="min-h-11">{full ? "대기 신청" : "참가 신청"}</Btn></div>
</form>
)}
</Panel>
<Panel title="일정 안내">
<dl className="space-y-3 text-sm">
<div className="flex justify-between gap-4"><dt className="text-content-muted">신청 마감</dt><dd className="font-semibold">20:30</dd></div>
<div className="flex justify-between gap-4"><dt className="text-content-muted">디스코드 집결</dt><dd className="font-semibold">20:50</dd></div>
<div className="flex justify-between gap-4"><dt className="text-content-muted">내전 시작</dt><dd className="font-semibold">21:00</dd></div>
</dl>
<details className="mt-4 border-t border-line pt-3 text-sm">
<summary className="cursor-pointer font-semibold">참가 규칙</summary>
<p className="mt-2 text-content-muted">희망 포지션과 실제 배정은 다를 수 있습니다. 불참 시 모집 마감 전 신청을 취소해 주세요.</p>
</details>
</Panel>
</div>
</>
);
}
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 (
<>
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<PreviewControl label="예시 역할">
<select className={selectClass} value={spectator ? "spectator" : "captain"} onChange={(event) => setSpectator(event.target.value === "spectator")}>
<option value="captain">별무리 팀장</option>
<option value="spectator">관전자</option>
</select>
</PreviewControl>
<Chip selected={closed} onClick={() => setClosed(!closed)}>입찰 마감 상태</Chip>
</div>
<div className="match-flows-grid grid gap-4">
<Panel title="현재 선수 · 7/16">
<div className="flex flex-wrap items-start justify-between gap-3">
<div><p className="text-xl font-bold">초승달 <span className="text-sm font-medium text-content-muted">#MOON</span></p><p className="mt-1 text-sm text-content-muted">다이아몬드 2 · 정글 / 서포터</p></div>
<Pill tone={closed ? "neutral" : "live"}>{closed ? "입찰 마감" : "입찰 중"}</Pill>
</div>
<div className="mt-5 grid grid-cols-2 gap-3 rounded-lg bg-sunken px-3 py-3.5 sm:px-4" role="status">
<div><p className="text-sm text-content-muted">{closed ? "최종 낙찰가" : "현재 최고가"}</p><p className="tabular text-xl font-bold">{current.points}P</p><p className="text-sm text-content-muted">{current.team}</p></div>
{!spectator && <div><p className="text-sm text-content-muted">별무리 잔여</p><p className="tabular text-xl font-bold">{closed && current.team === "별무리" ? teams[0].points - current.points : teams[0].points}P</p></div>}
</div>
{!spectator && !closed && (
<div className="mt-4 flex flex-wrap items-center gap-2">
<Btn variant="primary" className="min-h-11" disabled={current.team === "별무리"} onClick={() => setBids([{ team: "별무리", points: nextBid }, ...bids])}>{current.team === "별무리" ? "현재 최고 입찰" : `${nextBid}P 입찰`}</Btn>
<p className="text-sm text-content-muted">낙찰될 때 포인트가 차감됩니다.</p>
</div>
)}
<div className="mt-5 space-y-3 border-t border-line pt-3 text-sm">
<details><summary className="cursor-pointer font-semibold">최근 내전 전적</summary><p className="mt-2 text-content-muted">최근 8세트 · 5승 3패 · KDA 3.6</p></details>
<details><summary className="cursor-pointer font-semibold">현재 선수 입찰 기록 · {bids.length}건</summary><ol className="mt-2 divide-y divide-line">{bids.map((bid) => <li key={bid.points} className="flex justify-between py-2"><span>{bid.team}</span><strong>{bid.points}P</strong></li>)}</ol></details>
</div>
</Panel>
<Panel title="팀 현황">
<ul className="divide-y divide-line">
{teams.map((team) => {
const won = closed && current.team === team.name;
return (
<li key={team.name} className="flex justify-between gap-3 py-3 first:pt-0 last:pb-0">
<div><p className="font-semibold">{team.name}</p><p className="mt-1 text-xs text-content-muted">{won ? "선수 1명 낙찰" : `빈 포지션 · ${team.open}`}</p></div>
<div className="tabular text-right"><p className="font-bold">{team.points - (won ? current.points : 0)}P</p><p className="mt-1 text-xs text-content-muted">{team.players + Number(won)}/5명</p></div>
</li>
);
})}
</ul>
</Panel>
</div>
</>
);
}
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 (
<>
<div><Chip selected={issued} onClick={() => { setIssued(!issued); setCodeStatus(""); }}>코드 발급 상태</Chip></div>
<div className="match-flows-grid grid gap-4">
<Panel title="다음 경기">
<p className="text-sm text-content-muted">준결승 · 3전 2선승 · 21:30</p>
<p className="mt-2 text-xl font-bold">별무리 <span className="mx-1 text-sm font-medium text-content-muted">vs</span> 여울</p>
<div className="mt-5 grid gap-3 rounded-lg bg-sunken p-3.5 sm:p-4">
<div className="flex flex-wrap items-center justify-between gap-2"><p className="text-sm font-semibold">1세트 토너먼트 코드</p><Pill tone={issued ? "live" : "gold"}>{issued ? "발급됨" : "발급 대기"}</Pill></div>
{issued ? (
<div className="flex flex-wrap items-center justify-between gap-2"><code className="text-sm font-semibold">{code}</code><Btn onClick={() => void copyCode()}>코드 복사</Btn></div>
) : <p className="text-sm text-content-muted">운영자가 코드를 발급하면 이곳에서 복사할 수 있습니다.</p>}
<p role="status" className={codeStatus ? "text-sm text-content-muted" : "sr-only"}>{codeStatus}</p>
</div>
<details className="mt-4 border-t border-line pt-3 text-sm">
<summary className="cursor-pointer font-semibold">다른 세트 상태</summary>
<p className="mt-2 text-content-muted">2세트 · 발급 대기</p><p className="mt-1 text-content-muted">3세트 · 필요 시 진행</p>
</details>
</Panel>
<Panel title="라운드별 일정·결과">
<ul className="space-y-3 text-sm">
<li><details><summary className="cursor-pointer font-semibold">1라운드 · 종료</summary><p className="mt-2 text-content-muted">별무리 2 : 0 밤편지</p></details></li>
<li className="border-t border-line pt-3"><details><summary className="cursor-pointer font-semibold">준결승 · 2대진</summary><p className="mt-2 text-content-muted">별무리 vs 여울 · 21:30</p><p className="mt-1 text-content-muted">서릿길 vs 파도 · 21:30</p></details></li>
<li className="border-t border-line pt-3 text-content-muted">결승 · 대진 미정</li>
</ul>
</Panel>
</div>
</>
);
}
function Operations() {
const [filter, setFilter] = useState("전체");
const [done, setDone] = useState<string[]>([]);
const [message, setMessage] = useState("");
const shown = opsItems.filter((item) => filter === "전체" || filter === item.type);
return (
<>
<div className="flex flex-wrap gap-2" role="group" aria-label="작업 유형">
{["전체", ...opsItems.map((item) => item.type)].map((type) => (
<Chip key={type} selected={type === filter} onClick={() => setFilter(type)}>{type}</Chip>
))}
</div>
<Panel title={`남은 작업 ${opsItems.length - done.length}건`}>
<ul className="divide-y divide-line">
{shown.map((item) => {
const completed = done.includes(item.id);
return (
<li key={item.id} className="py-3 first:pt-0 last:pb-0">
<details>
<summary className="cursor-pointer rounded-field py-1 focus-visible:outline-2 focus-visible:outline-offset-2">
<span className="match-flows-task inline-flex flex-wrap items-center gap-x-3 gap-y-1 align-middle"><strong className="text-sm">{item.title}</strong><Pill tone={completed ? "live" : "gold"}>{completed ? item.done : "확인 필요"}</Pill><span className="match-flows-task-context text-sm text-content-muted">{item.context}</span></span>
</summary>
<div className="mt-2 space-y-3 rounded-lg bg-sunken p-3 text-sm text-content-muted">
<p>{item.detail}</p>
{!completed && <Btn onClick={() => { setDone([...done, item.id]); setMessage(`${item.title} · ${item.done}`); }}>{item.action}</Btn>}
</div>
</details>
</li>
);
})}
</ul>
<p role="status" className="sr-only">{message}</p>
</Panel>
</>
);
}
export default function MatchFlowsPreview() {
const [params] = useSearchParams();
const active = flows.find((flow) => flow.id === params.get("flow"))?.id ?? "signup";
const heading = headings[active];
return (
<main className={`${pageWidthClass("lg")} pb-12 pt-6 text-content sm:pt-9`}>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-content-muted">
<Pill>UX 목업</Pill><span>샘플 데이터로 보는 내전 흐름</span>
</div>
<nav aria-label="목업 흐름" className="mt-4 flex flex-wrap gap-2 border-b border-line pb-4">
{flows.map((flow) => (
<Link key={flow.id} to={`?flow=${flow.id}`} aria-current={active === flow.id ? "page" : undefined} className="match-flows-link inline-flex min-h-9 items-center rounded-full border border-line-strong bg-card px-3.5 text-sm font-semibold text-content-muted hover:text-content">{flow.name}</Link>
))}
</nav>
<div className="pb-5 pt-5 sm:pt-7">
<p className="text-sm font-semibold text-content-muted">{heading.label}</p>
<h1 className="match-flows-title mt-1 font-bold leading-tight">{heading.title}</h1>
<p className="mt-1.5 text-sm text-content-muted">{heading.detail}</p>
</div>
<div className="space-y-3">
{active === "signup" && <Signup />}
{active === "auction" && <Auction />}
{active === "team" && <TeamProgress />}
{active === "ops" && <Operations />}
</div>
</main>
);
}
@@ -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,
},
],
},
};
@@ -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;
}
}
@@ -78,6 +78,6 @@ test('uses neutral titles and distinguishes registration states on the next matc
assert.equal(getNextMatchBanner({ ...match, maxParticipants: 0 }).status, '모집 마감'); assert.equal(getNextMatchBanner({ ...match, maxParticipants: 0 }).status, '모집 마감');
assert.deepEqual( assert.deepEqual(
getNextMatchBanner({ ...fullMatch, title: '토요일 시즌 결승 내전', status: 'team-built' }), getNextMatchBanner({ ...fullMatch, title: '토요일 시즌 결승 내전', status: 'team-built' }),
{ title: '토요일 시즌 결승 내전', status: '팀 편성', capacity: '1/1명', canApply: false }, { title: '토요일 시즌 결승 내전', status: '팀빌딩 상태 확인 필요', capacity: '1/1명', canApply: false },
); );
}); });
@@ -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,
);
});
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import test from 'node:test'; import test from 'node:test';
import { import {
getInternalMatchOutcome, formatOfficialMatchResult,
getMainLane, getMainLane,
parseLeaderboardSort, parseLeaderboardSort,
rankLeaderboardByLane, rankLeaderboardByLane,
@@ -74,32 +74,23 @@ test('picks the most played lane', () => {
assert.equal(getMainLane({}), undefined); assert.equal(getMainLane({}), undefined);
}); });
test('shows a score for a single two-team series and a winner otherwise', () => { test('displays official tournament winners by ID and keeps older records neutral', () => {
const team = (teamIndex: number) => ({ const champion = 'winner' as import('@lolympus/contracts').TeamId;
teamIndex, assert.equal(formatOfficialMatchResult({
name: `${teamIndex + 1}팀`, type: 'official',
members: [], competitionId: 'tournament' as import('@lolympus/contracts').CompetitionId,
}); sourceRevision: 10,
const pair = getInternalMatchOutcome({ phase: 'completed',
winnerTeamIndex: 1, formatType: 'double-elimination',
teams: [team(0), team(1)], completedSeriesCount: 2,
seriesResults: [ teams: [{ teamId: champion, name: '별무리' }],
{ teamAIndex: 0, teamBIndex: 1, teamAWins: 1, teamBWins: 2 }, outcome: {
], type: 'double-elimination',
}); championTeamId: champion,
assert.equal(pair?.type, 'score'); placements: [{ rank: 1, teamId: champion }],
assert.equal(pair?.type === 'score' && pair.rightWins, 2); completedAt: '2026-11-10T00:00:00Z',
assert.equal(pair?.winner?.name, '2팀'); },
}), '우승 · 별무리');
const tournament = getInternalMatchOutcome({ assert.equal(formatOfficialMatchResult({ type: 'legacy' }), '과거 기록');
winnerTeamIndex: 2, assert.equal(formatOfficialMatchResult(undefined), '공식 결과 확인 불가');
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,
);
}); });
+53 -1
View File
@@ -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 { CompetitionFormatType } from "./format.js";
import type { import type {
CommunityId, CommunityId,
@@ -23,6 +23,14 @@ export type MatchGameMode =
| "double-elimination"; | "double-elimination";
export type MatchEventType = "inhouse" | "tournament"; 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 GrandFinalGameCount = 1 | 3 | 5;
export type MatchPosition = "TOP" | "JGL" | "MID" | "ADC" | "SUP"; export type MatchPosition = "TOP" | "JGL" | "MID" | "ADC" | "SUP";
@@ -48,6 +56,13 @@ export interface MatchTierView {
fetchedAt: IsoDateTime; fetchedAt: IsoDateTime;
} }
export interface RecentMatchParticipantRank {
tier: string;
rank?: string;
leaguePoints?: number;
fetchedAt: IsoDateTime;
}
export interface MatchParticipantView { export interface MatchParticipantView {
userId: UserId; userId: UserId;
gameName?: string; gameName?: string;
@@ -88,6 +103,7 @@ export interface MatchDetailResponse {
description: string; description: string;
mapId: number; mapId: number;
status: MatchLifecycleStatus; status: MatchLifecycleStatus;
eventProgress?: { stage: MatchEventStage };
scheduledAt: IsoDateTime; scheduledAt: IsoDateTime;
maxParticipants: number; maxParticipants: number;
gameCount: number; gameCount: number;
@@ -126,6 +142,42 @@ export interface MatchSummaryResponse extends MatchDetailResponse {
historyResult?: MatchHistoryResult; 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 { export interface TeamTournamentCodeView {
gameSlotId: GameSlotId; gameSlotId: GameSlotId;
seriesId: SeriesId; seriesId: SeriesId;