From fd386ed202d388a679cc7b27a07df67d2fbcc300 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sat, 2 May 2026 04:05:35 -0700 Subject: [PATCH] . --- .../src/modules/auction/auction.controller.ts | 6 +- .../src/modules/auction/auction.gateway.ts | 7 +- .../modules/auction/auction.service.spec.ts | 33 +- .../src/modules/auction/auction.service.ts | 90 ++--- .../src/modules/auction/dto/auction.dto.ts | 14 +- .../community-stats.service.ts | 19 +- .../community-stats/community-stats.types.ts | 18 +- .../migrations/20260502-team-index.spec.ts | 160 +++++++++ .../migrations/20260502-team-index.ts | 335 ++++++++++++++++++ .../api/src/modules/global/database/schema.ts | 64 ++-- .../legacy-import/legacy-import.service.ts | 51 ++- .../legacy-import/legacy-import.types.ts | 8 +- .../legacy-import/match-builder.util.ts | 38 +- apps/api/src/modules/match/match.service.ts | 41 ++- .../tournament-code.service.ts | 20 +- .../tournament-code/tournament-code.types.ts | 4 +- .../team-mapping.util.spec.ts | 22 +- .../tournament-result/team-mapping.util.ts | 62 ++-- .../tournament-result.service.ts | 96 +++-- .../tournament-result.types.ts | 1 + apps/api/src/seed.ts | 33 +- apps/web/src/App.tsx | 2 +- apps/web/src/api/mappers.ts | 68 ++-- apps/web/src/api/types.ts | 62 ++-- apps/web/src/api/useAuctionSocket.ts | 5 +- apps/web/src/config.ts | 43 ++- apps/web/src/pages/AuctionPage.tsx | 145 +++----- .../src/pages/CommunityInternalStatsPage.tsx | 46 ++- .../web/src/pages/InternalMatchDetailPage.tsx | 41 ++- apps/web/src/pages/MatchDetailPage.tsx | 142 ++++---- apps/web/src/pages/MatchTeamProgressPage.tsx | 38 +- .../web/src/pages/admin/LegacyMatchesPage.tsx | 15 +- 32 files changed, 1128 insertions(+), 601 deletions(-) create mode 100644 apps/api/src/modules/global/database/migrations/20260502-team-index.spec.ts create mode 100644 apps/api/src/modules/global/database/migrations/20260502-team-index.ts diff --git a/apps/api/src/modules/auction/auction.controller.ts b/apps/api/src/modules/auction/auction.controller.ts index eb2a32b9..f58b8eaa 100644 --- a/apps/api/src/modules/auction/auction.controller.ts +++ b/apps/api/src/modules/auction/auction.controller.ts @@ -39,8 +39,7 @@ export class AuctionController { matchId, communityId, captains: body.captains.map((c) => ({ - side: c.side, - groupIndex: c.groupIndex ?? 1, + teamIndex: c.teamIndex, userId: new mongoose.Types.ObjectId(c.userId), })), initialPoints: body.initialPoints ?? 1000, @@ -76,8 +75,7 @@ export class AuctionController { ) { return this.auctionService.placeBid({ matchId, - side: body.side, - groupIndex: body.groupIndex ?? 1, + teamIndex: body.teamIndex, amount: body.amount, bidderUserId: this.resolveBidder(currentUser, body.bidderUserId), }); diff --git a/apps/api/src/modules/auction/auction.gateway.ts b/apps/api/src/modules/auction/auction.gateway.ts index 8ba0bd1f..ce187e01 100644 --- a/apps/api/src/modules/auction/auction.gateway.ts +++ b/apps/api/src/modules/auction/auction.gateway.ts @@ -19,7 +19,6 @@ import type { AuctionDocument, IdentityDocument, Position, - TeamSide, UserDocument, } from '../global/database/schema'; import { AuctionService } from './auction.service'; @@ -29,8 +28,7 @@ interface JoinAuctionPayload { } interface BidPayload { - side: TeamSide; - groupIndex?: number; + teamIndex: number; amount: number; bidderUserId?: string; } @@ -125,8 +123,7 @@ export class AuctionGateway try { const auction = await this.auctionService.placeBid({ matchId: new mongoose.Types.ObjectId(matchId), - side: payload.side, - groupIndex: payload.groupIndex ?? 1, + teamIndex: payload.teamIndex, amount: payload.amount, bidderUserId, }); diff --git a/apps/api/src/modules/auction/auction.service.spec.ts b/apps/api/src/modules/auction/auction.service.spec.ts index ad4ff096..89b6c5f9 100644 --- a/apps/api/src/modules/auction/auction.service.spec.ts +++ b/apps/api/src/modules/auction/auction.service.spec.ts @@ -31,10 +31,9 @@ describe('AuctionService', () => { }; } - function createFullTeam(side: 'blue' | 'red') { + function createFullTeam(teamIndex: number) { return { - side, - groupIndex: 1, + teamIndex, captainUserId: new mongoose.Types.ObjectId(), points: 100, members: Array.from({ length: 4 }, () => ({ @@ -49,7 +48,7 @@ describe('AuctionService', () => { const matchId = new mongoose.Types.ObjectId(); const auction = { phase: 'bidding', - teams: [createFullTeam('blue'), createFullTeam('red')], + teams: [createFullTeam(1), createFullTeam(2)], currentBid: 10, save: jest.fn().mockResolvedValue(undefined), }; @@ -62,8 +61,7 @@ describe('AuctionService', () => { await expect( service.placeBid({ matchId, - side: 'blue', - groupIndex: 1, + teamIndex: 1, amount: 20, }), ).rejects.toThrow('Team already has maximum members.'); @@ -74,7 +72,7 @@ describe('AuctionService', () => { const matchId = new mongoose.Types.ObjectId(); const auction = { phase: 'bidding', - currentBidder: 'blue', + currentBidderTeamIndex: 1, currentBid: 20, currentIndex: 0, order: [ @@ -83,7 +81,7 @@ describe('AuctionService', () => { preferredPositions: [{ position: 'ADC', priority: 1 }], }, ], - teams: [createFullTeam('blue'), createFullTeam('red')], + teams: [createFullTeam(1), createFullTeam(2)], save: jest.fn().mockResolvedValue(undefined), }; const { service } = createService({ @@ -112,7 +110,7 @@ describe('AuctionService', () => { order: [{ userId: blueMemberId }, { userId: redMemberId }], teams: [ { - side: 'blue', + teamIndex: 1, captainUserId: blueCaptainId, points: 970, members: [ @@ -124,7 +122,7 @@ describe('AuctionService', () => { ], }, { - side: 'red', + teamIndex: 2, captainUserId: redCaptainId, points: 940, members: [ @@ -178,9 +176,8 @@ describe('AuctionService', () => { expect(match.save).toHaveBeenCalledTimes(1); expect(match.teams).toEqual([ { - side: 'blue', - groupIndex: 1, - name: '블루팀', + teamIndex: 1, + name: '1팀', captainUserId: blueCaptainId, members: [ { @@ -196,9 +193,8 @@ describe('AuctionService', () => { ], }, { - side: 'red', - groupIndex: 1, - name: '레드팀', + teamIndex: 2, + name: '2팀', captainUserId: redCaptainId, members: [ { @@ -233,9 +229,8 @@ describe('AuctionService', () => { status: 'team-built', teams: [ { - side: 'blue', - groupIndex: 1, - name: '블루팀', + teamIndex: 1, + name: '1팀', members: [], }, ], diff --git a/apps/api/src/modules/auction/auction.service.ts b/apps/api/src/modules/auction/auction.service.ts index f9907e20..7bf6a143 100644 --- a/apps/api/src/modules/auction/auction.service.ts +++ b/apps/api/src/modules/auction/auction.service.ts @@ -15,7 +15,6 @@ import { MatchTeamMember, Position, RiotAccount, - TeamSide, } from '../global/database/schema'; import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; import type { RiotPlatformRoute, RiotRegionalRoute } from '../riot/riot.types'; @@ -30,8 +29,7 @@ interface StartAuctionParams { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; captains: { - side: TeamSide; - groupIndex: number; + teamIndex: number; userId: mongoose.Types.ObjectId; }[]; initialPoints: number; @@ -40,8 +38,7 @@ interface StartAuctionParams { interface PlaceBidParams { matchId: mongoose.Types.ObjectId; - side: TeamSide; - groupIndex: number; + teamIndex: number; amount: number; bidderUserId?: mongoose.Types.ObjectId; } @@ -90,13 +87,16 @@ export class AuctionService { throw new BadRequestException('Not enough participants (need at least 10).'); } const expectedCaptainCount = desiredAuctionCount / AUCTION_MAX_TEAM_SIZE; - const groupCount = expectedCaptainCount / 2; if (params.captains.length !== expectedCaptainCount) { throw new BadRequestException( `Expected ${expectedCaptainCount} captains for ${desiredAuctionCount} participants.`, ); } - this.assertCaptainAssignments(params.captains, activeParticipants, groupCount); + this.assertCaptainAssignments( + params.captains, + activeParticipants, + expectedCaptainCount, + ); const captainUserIds = params.captains.map((c) => c.userId); const basePlayerUsers = await UserModel.find({ @@ -158,8 +158,7 @@ export class AuctionService { matchId: params.matchId, phase: 'presenting', teams: params.captains.map((c) => ({ - side: c.side, - groupIndex: c.groupIndex, + teamIndex: c.teamIndex, captainUserId: c.userId, points: params.initialPoints, members: [], @@ -206,8 +205,7 @@ export class AuctionService { } auction.phase = 'bidding'; auction.currentBid = 0; - auction.currentBidder = undefined; - auction.currentBidderGroupIndex = undefined; + auction.currentBidderTeamIndex = undefined; auction.currentDeadline = this.createDeadline(auction.maxTimerSeconds); await auction.save(); return auction; @@ -218,7 +216,7 @@ export class AuctionService { if (auction.phase !== 'bidding') { throw new BadRequestException('Auction is not in bidding phase.'); } - const team = this.findAuctionTeam(auction, params.side, params.groupIndex); + const team = this.findAuctionTeamByIndex(auction, params.teamIndex); if (!team) throw new BadRequestException('Unknown team.'); if (params.amount <= auction.currentBid) { throw new BadRequestException('Bid must exceed current bid.'); @@ -230,14 +228,12 @@ export class AuctionService { // 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다. auction.currentBid = params.amount; - auction.currentBidder = params.side; - auction.currentBidderGroupIndex = params.groupIndex; + auction.currentBidderTeamIndex = params.teamIndex; auction.currentDeadline = this.createDeadline( this.resolveBidExtensionSeconds(auction), ); auction.bids.push({ - side: params.side, - groupIndex: params.groupIndex, + teamIndex: params.teamIndex, amount: params.amount, bidderUserId: team.captainUserId, timestamp: new Date(), @@ -251,13 +247,12 @@ export class AuctionService { if (auction.phase !== 'bidding') { throw new BadRequestException('Auction is not in bidding phase.'); } - if (!auction.currentBidder || auction.currentBid <= 0) { + if (!auction.currentBidderTeamIndex || auction.currentBid <= 0) { throw new BadRequestException('No bid to mark sold.'); } - const team = this.findAuctionTeam( + const team = this.findAuctionTeamByIndex( auction, - auction.currentBidder, - auction.currentBidderGroupIndex ?? 1, + auction.currentBidderTeamIndex, ); if (!team) throw new BadRequestException('Winning team not found.'); this.assertTeamHasSlot(team); @@ -293,8 +288,7 @@ export class AuctionService { auction.currentIndex = nextIndex; auction.phase = 'presenting'; auction.currentBid = 0; - auction.currentBidder = undefined; - auction.currentBidderGroupIndex = undefined; + auction.currentBidderTeamIndex = undefined; } auction.currentDeadline = undefined; await auction.save(); @@ -372,18 +366,13 @@ export class AuctionService { private assertCaptainAssignments( captains: StartAuctionParams['captains'], activeParticipants: Array<{ userId: mongoose.Types.ObjectId }>, - groupCount: number, + expectedCaptainCount: number, ): void { const activeUserIds = new Set( activeParticipants.map((participant) => participant.userId.toString()), ); const captainUserIds = new Set(); - const teamKeys = new Set(); - const requiredKeys = new Set(); - for (let groupIndex = 1; groupIndex <= groupCount; groupIndex += 1) { - requiredKeys.add(`blue:${groupIndex}`); - requiredKeys.add(`red:${groupIndex}`); - } + const teamIndexes = new Set(); for (const captain of captains) { const userId = captain.userId.toString(); @@ -397,31 +386,31 @@ export class AuctionService { } captainUserIds.add(userId); - if (captain.groupIndex < 1 || captain.groupIndex > groupCount) { - throw new BadRequestException('Captain groupIndex is out of range.'); + if ( + !Number.isInteger(captain.teamIndex) || + captain.teamIndex < 1 || + captain.teamIndex > expectedCaptainCount + ) { + throw new BadRequestException('Captain teamIndex is out of range.'); } - const key = `${captain.side}:${captain.groupIndex}`; - if (teamKeys.has(key)) { + if (teamIndexes.has(captain.teamIndex)) { throw new BadRequestException('Duplicate captain team assignment.'); } - teamKeys.add(key); + teamIndexes.add(captain.teamIndex); } - for (const key of requiredKeys) { - if (!teamKeys.has(key)) { - throw new BadRequestException('Each group needs one blue and one red captain.'); + for (let teamIndex = 1; teamIndex <= expectedCaptainCount; teamIndex += 1) { + if (!teamIndexes.has(teamIndex)) { + throw new BadRequestException('Each teamIndex needs one captain.'); } } } - private findAuctionTeam( + private findAuctionTeamByIndex( auction: AuctionDocument, - side: TeamSide, - groupIndex: number, + teamIndex: number, ): AuctionTeam | undefined { - return auction.teams.find( - (team) => team.side === side && (team.groupIndex ?? 1) === groupIndex, - ); + return auction.teams.find((team) => team.teamIndex === teamIndex); } private createDeadline(secondsFromNow: number): Date { @@ -485,9 +474,8 @@ export class AuctionService { ]; return { - side: team.side, - groupIndex: team.groupIndex ?? 1, - name: this.resolveTeamName(team.side, team.groupIndex ?? 1, auction.teams), + teamIndex: team.teamIndex, + name: this.resolveTeamName(team.teamIndex), captainUserId: team.captainUserId, members, }; @@ -593,14 +581,8 @@ export class AuctionService { }, 0); } - private resolveTeamName( - side: TeamSide, - groupIndex: number, - teams: AuctionTeam[], - ): string { - const groupCount = new Set(teams.map((team) => team.groupIndex ?? 1)).size; - const sideLabel = side === 'blue' ? '블루팀' : '레드팀'; - return groupCount <= 1 ? sideLabel : `${groupIndex}조 ${sideLabel}`; + private resolveTeamName(teamIndex: number): string { + return `${teamIndex}팀`; } } diff --git a/apps/api/src/modules/auction/dto/auction.dto.ts b/apps/api/src/modules/auction/dto/auction.dto.ts index d84c6929..73123c1b 100644 --- a/apps/api/src/modules/auction/dto/auction.dto.ts +++ b/apps/api/src/modules/auction/dto/auction.dto.ts @@ -10,17 +10,11 @@ import { Min, ValidateNested, } from 'class-validator'; -import { TEAM_SIDES } from '../../global/database/schema'; -import type { TeamSide } from '../../global/database/schema'; class CaptainAssignmentDto { - @IsEnum(TEAM_SIDES) - side!: TeamSide; - - @IsOptional() @IsInt() @Min(1) - groupIndex?: number; + teamIndex!: number; @IsMongoId() userId!: string; @@ -46,13 +40,9 @@ export class StartAuctionDto { } export class PlaceBidDto { - @IsEnum(TEAM_SIDES) - side!: TeamSide; - - @IsOptional() @IsInt() @Min(1) - groupIndex?: number; + teamIndex!: number; @IsInt() @Min(1) diff --git a/apps/api/src/modules/community-stats/community-stats.service.ts b/apps/api/src/modules/community-stats/community-stats.service.ts index c9e76511..1595e806 100644 --- a/apps/api/src/modules/community-stats/community-stats.service.ts +++ b/apps/api/src/modules/community-stats/community-stats.service.ts @@ -47,6 +47,7 @@ interface InternalRecord { userId: string; summonerName: string; profileIconId: number; + teamIndex: number; side: TeamSide; championId: number; championLevel: number; @@ -81,6 +82,7 @@ interface InternalGameDetail { gameDuration: number; winnerSide: TeamSide; teams: Array<{ + teamIndex: number; side: TeamSide; win: boolean; objectives: { baron: number; dragon: number; tower: number }; @@ -237,12 +239,14 @@ export class CommunityStatsService { gameCreation: game.gameCreation, gameDuration: game.gameDuration, teams: game.teams.map((team) => ({ + teamIndex: team.teamIndex, side: team.side, win: team.win, objectives: team.objectives, participants: team.participants.map((record) => ({ userId: record.userId, summonerName: record.summonerName, + teamIndex: record.teamIndex, side: record.side, teamPosition: record.teamPosition, championId: record.championId, @@ -454,17 +458,19 @@ export class CommunityStatsService { scheduledAt: match.scheduledAt.toISOString(), status: match.status === 'finished' ? 'finished' : 'in-progress', gameCount: match.gameCount, - blueScore: match.result?.blueScore ?? 0, - redScore: match.result?.redScore ?? 0, - winnerSide: match.result?.winnerSide, + winnerTeamIndex: match.result?.winnerTeamIndex, + seriesResults: match.result?.seriesResults ?? [], games: games.map((game) => ({ gameNumber: game.gameNumber, riotMatchId: game.riotMatchId ?? null, + blueTeamIndex: game.blueTeamIndex, + redTeamIndex: game.redTeamIndex, + winnerTeamIndex: game.winnerTeamIndex ?? null, winnerSide: game.winnerSide ?? null, gameDuration: game.gameDuration, })), teams: match.teams.map((team) => ({ - side: team.side, + teamIndex: team.teamIndex, name: team.name, members: team.members.map((member) => { const participant = participantById.get(member.userId.toString()); @@ -508,6 +514,8 @@ export class CommunityStatsService { gameDuration: game.gameDuration, winnerSide: game.winnerSide, teams: (['blue', 'red'] as TeamSide[]).map((side) => { + const teamIndex = + side === 'blue' ? game.blueTeamIndex : game.redTeamIndex; const rawTeamId = rawTeamIdBySide.get(side); const rawTeam = raw.info.teams.find((team) => team.teamId === rawTeamId); const teamRawParticipants = raw.info.participants.filter( @@ -522,6 +530,7 @@ export class CommunityStatsService { 0, ); return { + teamIndex, side, win: game.winnerSide === side, objectives: { @@ -559,6 +568,7 @@ export class CommunityStatsService { gameDuration: game.gameDuration, winnerSide: game.winnerSide, teams: (['blue', 'red'] as TeamSide[]).map((side) => ({ + teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex, side, win: game.winnerSide === side, objectives: { baron: 0, dragon: 0, tower: 0 }, @@ -621,6 +631,7 @@ export class CommunityStatsService { rawParticipant?.summonerName ?? 'Unknown', profileIconId: snapshot?.profileIconId ?? 0, + teamIndex: participant.teamIndex, side: participant.side, championId: participant.championId, championLevel: rawParticipant?.champLevel ?? 0, diff --git a/apps/api/src/modules/community-stats/community-stats.types.ts b/apps/api/src/modules/community-stats/community-stats.types.ts index 4696f1cb..ec381dea 100644 --- a/apps/api/src/modules/community-stats/community-stats.types.ts +++ b/apps/api/src/modules/community-stats/community-stats.types.ts @@ -22,17 +22,25 @@ export interface InternalMatchCardView { scheduledAt: string; status: 'finished' | 'in-progress'; gameCount: number; - blueScore: number; - redScore: number; - winnerSide?: TeamSide; + winnerTeamIndex?: number; + seriesResults: Array<{ + teamAIndex: number; + teamBIndex: number; + teamAWins: number; + teamBWins: number; + winnerTeamIndex?: number; + }>; games: Array<{ gameNumber: number; riotMatchId: string | null; + blueTeamIndex: number; + redTeamIndex: number; + winnerTeamIndex: number | null; winnerSide: TeamSide | null; gameDuration: number; }>; teams: Array<{ - side: TeamSide; + teamIndex: number; name: string; members: Array<{ userId: string; @@ -101,12 +109,14 @@ export interface InternalMatchDetailResponse { gameCreation: number; gameDuration: number; teams: Array<{ + teamIndex: number; side: TeamSide; win: boolean; objectives: { baron: number; dragon: number; tower: number }; participants: Array<{ userId: string | null; summonerName: string; + teamIndex: number; side: TeamSide; teamPosition: string; championId: number; diff --git a/apps/api/src/modules/global/database/migrations/20260502-team-index.spec.ts b/apps/api/src/modules/global/database/migrations/20260502-team-index.spec.ts new file mode 100644 index 00000000..deb3168f --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/20260502-team-index.spec.ts @@ -0,0 +1,160 @@ +import { migrateTeamIndex } from './20260502-team-index'; + +function createDb(params: { + auctions?: Array>; + matches?: Array>; +}) { + const collections = { + auction: params.auctions ?? [], + match: params.matches ?? [], + }; + + return { + collections, + db: { + collection(name: string) { + const key = name === 'auction' ? 'auction' : 'match'; + const docs = collections[key]; + return { + find() { + return { + limit() { + return { + async *[Symbol.asyncIterator]() { + for (const doc of docs) yield doc; + }, + }; + }, + }; + }, + async bulkWrite(writes: Array<{ + updateOne: { + filter: { _id: unknown }; + update: { + $set: Record; + $unset: Record; + }; + }; + }>) { + for (const write of writes) { + const doc = docs.find((item) => item._id === write.updateOne.filter._id); + if (!doc) continue; + Object.assign(doc, write.updateOne.update.$set); + for (const key of Object.keys(write.updateOne.update.$unset)) { + delete doc[key]; + } + } + }, + }; + }, + }, + }; +} + +describe('migrateTeamIndex', () => { + it('migrates auction and match team identity fields', async () => { + const { db, collections } = createDb({ + auctions: [ + { + _id: 'auction-1', + teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }], + bids: [{ side: 'red', groupIndex: 1, amount: 100 }], + currentBidder: 'red', + currentBidderGroupIndex: 1, + }, + ], + matches: [ + { + _id: 'match-1', + teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }], + result: { + winnerSide: 'blue', + blueScore: 1, + redScore: 0, + games: [ + { + gameNumber: 1, + riotMatchId: 'KR_1', + winnerSide: 'blue', + blueGroupIndex: 1, + redGroupIndex: 1, + participants: [ + { userId: 'u1', side: 'blue' }, + { userId: 'u2', side: 'red' }, + ], + }, + ], + seriesResults: [ + { + blueGroupIndex: 1, + redGroupIndex: 1, + blueScore: 1, + redScore: 0, + winnerSide: 'blue', + }, + ], + }, + }, + ], + }); + + const stats = await migrateTeamIndex(db, { dryRun: false }); + + expect(stats).toEqual({ + scannedAuctions: 1, + changedAuctions: 1, + scannedMatches: 1, + changedMatches: 1, + }); + expect(collections.auction[0]).toMatchObject({ + teams: [{ teamIndex: 1 }, { teamIndex: 2 }], + bids: [{ teamIndex: 2, amount: 100 }], + currentBidderTeamIndex: 2, + }); + expect(collections.match[0]).toMatchObject({ + teams: [{ teamIndex: 1, name: '1팀' }, { teamIndex: 2, name: '2팀' }], + result: { + winnerTeamIndex: 1, + games: [ + { + blueTeamIndex: 1, + redTeamIndex: 2, + winnerTeamIndex: 1, + participants: [ + { teamIndex: 1, side: 'blue' }, + { teamIndex: 2, side: 'red' }, + ], + }, + ], + seriesResults: [ + { + teamAIndex: 1, + teamBIndex: 2, + teamAWins: 1, + teamBWins: 0, + winnerTeamIndex: 1, + }, + ], + }, + }); + expect(collections.auction[0]).not.toHaveProperty('currentBidder'); + expect(collections.match[0].result).not.toHaveProperty('blueScore'); + }); + + it('is idempotent after applying updates', async () => { + const { db } = createDb({ + matches: [ + { + _id: 'match-1', + teams: [{ side: 'blue', groupIndex: 1 }], + }, + ], + }); + + await migrateTeamIndex(db, { dryRun: false }); + const stats = await migrateTeamIndex(db, { dryRun: false }); + + expect(stats.changedMatches).toBe(0); + expect(stats.changedAuctions).toBe(0); + }); +}); diff --git a/apps/api/src/modules/global/database/migrations/20260502-team-index.ts b/apps/api/src/modules/global/database/migrations/20260502-team-index.ts new file mode 100644 index 00000000..cbbf21c2 --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/20260502-team-index.ts @@ -0,0 +1,335 @@ +type LegacySide = 'blue' | 'red'; + +interface MigrationCollection { + find(filter: Record): { + limit(limit: number): AsyncIterable; + }; + bulkWrite( + writes: Array<{ + updateOne: { + filter: { _id: unknown }; + update: { $set: Record; $unset: Record }; + }; + }>, + options: { ordered: boolean }, + ): Promise; +} + +interface MigrationDb { + collection(name: string): MigrationCollection; +} + +interface MigrationOptions { + dryRun?: boolean; + limit?: number; +} + +interface MigrationStats { + scannedAuctions: number; + changedAuctions: number; + scannedMatches: number; + changedMatches: number; +} + +type AnyDoc = Record & { _id: unknown }; + +export async function migrateTeamIndex( + db: MigrationDb, + options: MigrationOptions = {}, +): Promise { + const dryRun = options.dryRun ?? true; + const stats: MigrationStats = { + scannedAuctions: 0, + changedAuctions: 0, + scannedMatches: 0, + changedMatches: 0, + }; + + await migrateCollection(db.collection('auction'), options.limit, dryRun, stats, 'auction'); + await migrateCollection(db.collection('match'), options.limit, dryRun, stats, 'match'); + + return stats; +} + +async function migrateCollection( + collection: MigrationCollection, + limit: number | undefined, + dryRun: boolean, + stats: MigrationStats, + kind: 'auction' | 'match', +) { + const cursor = collection.find({}).limit(limit ?? 0); + const writes: Array<{ + updateOne: { + filter: { _id: unknown }; + update: { $set: Record; $unset: Record }; + }; + }> = []; + + for await (const doc of cursor) { + if (kind === 'auction') stats.scannedAuctions += 1; + if (kind === 'match') stats.scannedMatches += 1; + + const update = kind === 'auction' ? migrateAuction(doc) : migrateMatch(doc); + if (!update) continue; + + if (kind === 'auction') stats.changedAuctions += 1; + if (kind === 'match') stats.changedMatches += 1; + writes.push({ + updateOne: { + filter: { _id: doc._id }, + update, + }, + }); + } + + if (!dryRun && writes.length > 0) { + await collection.bulkWrite(writes, { ordered: false }); + } +} + +function migrateAuction(doc: AnyDoc) { + const set: Record = {}; + const unset: Record = {}; + let changed = false; + + const teams = asArray(doc.teams).map((team) => { + const migrated = { ...team }; + const teamIndex = readTeamIndex(migrated); + if (teamIndex !== undefined) migrated.teamIndex = teamIndex; + if ('side' in migrated || 'groupIndex' in migrated) changed = true; + delete migrated.side; + delete migrated.groupIndex; + return migrated; + }); + if (changed) set.teams = teams; + + const bids = asArray(doc.bids).map((bid) => { + const migrated = { ...bid }; + const teamIndex = readTeamIndex(migrated); + if (teamIndex !== undefined) migrated.teamIndex = teamIndex; + if ('side' in migrated || 'groupIndex' in migrated) changed = true; + delete migrated.side; + delete migrated.groupIndex; + return migrated; + }); + if (changed) set.bids = bids; + + if ( + typeof doc.currentBidderTeamIndex !== 'number' && + isSide(doc.currentBidder) + ) { + set.currentBidderTeamIndex = sideGroupToTeamIndex( + doc.currentBidder, + numberOrDefault(doc.currentBidderGroupIndex, 1), + ); + changed = true; + } + if ('currentBidder' in doc || 'currentBidderGroupIndex' in doc) { + unset.currentBidder = ''; + unset.currentBidderGroupIndex = ''; + changed = true; + } + + return changed ? { $set: set, $unset: unset } : null; +} + +function migrateMatch(doc: AnyDoc) { + const set: Record = {}; + const unset: Record = {}; + let changed = false; + + const teams = asArray(doc.teams).map((team) => { + const migrated = { ...team }; + const teamIndex = readTeamIndex(migrated); + if (teamIndex !== undefined) migrated.teamIndex = teamIndex; + if (!migrated.name && typeof teamIndex === 'number') migrated.name = `${teamIndex}팀`; + if ('side' in migrated || 'groupIndex' in migrated) changed = true; + delete migrated.side; + delete migrated.groupIndex; + return migrated; + }); + if (changed) set.teams = teams; + + const result = isRecord(doc.result) ? migrateResult(doc.result) : null; + if (result) { + set.result = result; + changed = true; + } + + return changed ? { $set: set, $unset: unset } : null; +} + +function migrateResult(result: Record) { + let changed = false; + const migrated = { ...result }; + + const games = asArray(result.games).map((game) => { + const next = { ...game }; + const blueTeamIndex = + numberOrUndefined(next.blueTeamIndex) ?? + sideGroupToTeamIndex('blue', numberOrDefault(next.blueGroupIndex, 1)); + const redTeamIndex = + numberOrUndefined(next.redTeamIndex) ?? + sideGroupToTeamIndex('red', numberOrDefault(next.redGroupIndex, 1)); + const winnerSide = isSide(next.winnerSide) ? next.winnerSide : undefined; + const winnerTeamIndex = + numberOrUndefined(next.winnerTeamIndex) ?? + (winnerSide === 'blue' + ? blueTeamIndex + : winnerSide === 'red' + ? redTeamIndex + : undefined); + + next.blueTeamIndex = blueTeamIndex; + next.redTeamIndex = redTeamIndex; + if (winnerTeamIndex !== undefined) next.winnerTeamIndex = winnerTeamIndex; + next.participants = asArray(next.participants).map((participant) => { + const migratedParticipant = { ...participant }; + if (typeof migratedParticipant.teamIndex !== 'number') { + migratedParticipant.teamIndex = + migratedParticipant.side === 'blue' ? blueTeamIndex : redTeamIndex; + } + return migratedParticipant; + }); + if ('blueGroupIndex' in next || 'redGroupIndex' in next) changed = true; + delete next.blueGroupIndex; + delete next.redGroupIndex; + return next; + }); + migrated.games = games; + + const seriesResults = asArray(result.seriesResults).map((series) => { + if (typeof series.teamAIndex === 'number' && typeof series.teamBIndex === 'number') { + return series; + } + changed = true; + const legacyBlueTeamIndex = sideGroupToTeamIndex( + 'blue', + numberOrDefault(series.blueGroupIndex, 1), + ); + const legacyRedTeamIndex = sideGroupToTeamIndex( + 'red', + numberOrDefault(series.redGroupIndex, 1), + ); + const teamAIndex = Math.min(legacyBlueTeamIndex, legacyRedTeamIndex); + const teamBIndex = Math.max(legacyBlueTeamIndex, legacyRedTeamIndex); + const blueScore = numberOrDefault(series.blueScore, 0); + const redScore = numberOrDefault(series.redScore, 0); + const winnerSide = isSide(series.winnerSide) ? series.winnerSide : undefined; + const winnerTeamIndex = + winnerSide === 'blue' + ? legacyBlueTeamIndex + : winnerSide === 'red' + ? legacyRedTeamIndex + : undefined; + return { + teamAIndex, + teamBIndex, + teamAWins: teamAIndex === legacyBlueTeamIndex ? blueScore : redScore, + teamBWins: teamBIndex === legacyBlueTeamIndex ? blueScore : redScore, + winnerTeamIndex, + }; + }); + migrated.seriesResults = seriesResults.length > 0 ? seriesResults : buildSeries(games); + + if (typeof migrated.winnerTeamIndex !== 'number') { + const migratedSeriesResults = Array.isArray(migrated.seriesResults) + ? migrated.seriesResults + : []; + migrated.winnerTeamIndex = + resolveWinnerTeamIndex(migratedSeriesResults) ?? + (isSide(migrated.winnerSide) + ? sideGroupToTeamIndex(migrated.winnerSide, 1) + : undefined); + } + + if ('winnerSide' in migrated || 'blueScore' in migrated || 'redScore' in migrated) { + changed = true; + } + delete migrated.winnerSide; + delete migrated.blueScore; + delete migrated.redScore; + + return changed ? migrated : null; +} + +function buildSeries(games: Record[]) { + const bySeries = new Map< + string, + { + teamAIndex: number; + teamBIndex: number; + teamAWins: number; + teamBWins: number; + winnerTeamIndex?: number; + } + >(); + for (const game of games) { + const blueTeamIndex = numberOrDefault(game.blueTeamIndex, 1); + const redTeamIndex = numberOrDefault(game.redTeamIndex, 2); + const winnerTeamIndex = numberOrUndefined(game.winnerTeamIndex); + const teamAIndex = Math.min(blueTeamIndex, redTeamIndex); + const teamBIndex = Math.max(blueTeamIndex, redTeamIndex); + const key = `${teamAIndex}:${teamBIndex}`; + const current = + bySeries.get(key) ?? { teamAIndex, teamBIndex, teamAWins: 0, teamBWins: 0 }; + if (winnerTeamIndex === teamAIndex) current.teamAWins += 1; + if (winnerTeamIndex === teamBIndex) current.teamBWins += 1; + current.winnerTeamIndex = + current.teamAWins > current.teamBWins + ? teamAIndex + : current.teamBWins > current.teamAWins + ? teamBIndex + : undefined; + bySeries.set(key, current); + } + return [...bySeries.values()]; +} + +function resolveWinnerTeamIndex( + seriesResults: Array>, +): number | undefined { + const wins = new Map(); + for (const series of seriesResults) { + const winnerTeamIndex = numberOrUndefined(series.winnerTeamIndex); + if (!winnerTeamIndex) continue; + wins.set(winnerTeamIndex, (wins.get(winnerTeamIndex) ?? 0) + 1); + } + const sorted = [...wins.entries()].sort((left, right) => right[1] - left[1]); + if (sorted.length === 0) return undefined; + if (sorted.length > 1 && sorted[0][1] === sorted[1][1]) return undefined; + return sorted[0][0]; +} + +function readTeamIndex(value: Record): number | undefined { + if (typeof value.teamIndex === 'number') return value.teamIndex; + if (!isSide(value.side)) return undefined; + return sideGroupToTeamIndex(value.side, numberOrDefault(value.groupIndex, 1)); +} + +function sideGroupToTeamIndex(side: LegacySide, groupIndex: number) { + return (Math.max(1, groupIndex) - 1) * 2 + (side === 'blue' ? 1 : 2); +} + +function asArray(value: unknown): Record[] { + return Array.isArray(value) + ? value.filter(isRecord).map((item) => ({ ...item })) + : []; +} + +function isRecord(value: unknown): value is Record { + return Boolean(value && typeof value === 'object' && !Array.isArray(value)); +} + +function isSide(value: unknown): value is LegacySide { + return value === 'blue' || value === 'red'; +} + +function numberOrDefault(value: unknown, fallback: number) { + return typeof value === 'number' && Number.isFinite(value) ? value : fallback; +} + +function numberOrUndefined(value: unknown) { + return typeof value === 'number' && Number.isFinite(value) ? value : undefined; +} diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index 0625c7f9..fa19e17f 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -340,8 +340,7 @@ export interface MatchTeamMember { } export interface MatchTeam { - side: TeamSide; - groupIndex: number; + teamIndex: number; name: string; captainUserId?: mongoose.Types.ObjectId; members: MatchTeamMember[]; @@ -349,6 +348,7 @@ export interface MatchTeam { export interface MatchGameResultParticipant { userId: mongoose.Types.ObjectId; + teamIndex: number; side: TeamSide; championId: number; kills: number; @@ -360,26 +360,25 @@ export interface MatchGameResultParticipant { export interface MatchGameResult { gameNumber: number; riotMatchId: string; + blueTeamIndex: number; + redTeamIndex: number; + winnerTeamIndex: number; winnerSide: TeamSide; - blueGroupIndex: number; - redGroupIndex: number; gameCreation: number; gameDuration: number; participants: MatchGameResultParticipant[]; } export interface MatchSeriesResult { - blueGroupIndex: number; - redGroupIndex: number; - blueScore: number; - redScore: number; - winnerSide?: TeamSide; + teamAIndex: number; + teamBIndex: number; + teamAWins: number; + teamBWins: number; + winnerTeamIndex?: number; } export interface MatchResult { - winnerSide?: TeamSide; - blueScore: number; - redScore: number; + winnerTeamIndex?: number; mvpUserId?: mongoose.Types.ObjectId; riotMatchIds: string[]; // 내전에서 플레이된 Riot matchId들 games: MatchGameResult[]; @@ -489,16 +488,14 @@ export interface AuctionTeamMember { } export interface AuctionTeam { - side: TeamSide; - groupIndex: number; + teamIndex: number; captainUserId: mongoose.Types.ObjectId; points: number; members: AuctionTeamMember[]; } export interface AuctionBid { - side: TeamSide; - groupIndex?: number; + teamIndex: number; amount: number; bidderUserId: mongoose.Types.ObjectId; timestamp: Date; @@ -512,8 +509,7 @@ export interface Auction extends MongooseTimestamps { currentIndex: number; bids: AuctionBid[]; currentBid: number; - currentBidder?: TeamSide; - currentBidderGroupIndex?: number; + currentBidderTeamIndex?: number; maxTimerSeconds: number; currentDeadline?: Date; initialPoints: number; @@ -920,8 +916,7 @@ const MatchTeamMemberSubSchema = new Schema( const MatchTeamSubSchema = new Schema( { - side: { type: String, enum: TEAM_SIDES, required: true }, - groupIndex: { type: Number, required: true, default: 1, min: 1 }, + teamIndex: { type: Number, required: true, min: 1 }, name: { type: String, required: true }, captainUserId: { type: Schema.Types.ObjectId, ref: 'user' }, members: { type: [MatchTeamMemberSubSchema], required: true, default: [] }, @@ -933,6 +928,7 @@ const MatchGameResultParticipantSubSchema = new Schema( { userId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, + teamIndex: { type: Number, required: true, min: 1 }, side: { type: String, enum: TEAM_SIDES, required: true }, championId: { type: Number, required: true }, kills: { type: Number, required: true, default: 0 }, @@ -947,9 +943,10 @@ const MatchGameResultSubSchema = new Schema( { gameNumber: { type: Number, required: true }, riotMatchId: { type: String, required: true }, + blueTeamIndex: { type: Number, required: true, min: 1 }, + redTeamIndex: { type: Number, required: true, min: 1 }, + winnerTeamIndex: { type: Number, required: true, min: 1 }, winnerSide: { type: String, enum: TEAM_SIDES, required: true }, - blueGroupIndex: { type: Number, required: true, default: 1, min: 1 }, - redGroupIndex: { type: Number, required: true, default: 1, min: 1 }, gameCreation: { type: Number, required: true }, gameDuration: { type: Number, required: true }, participants: { @@ -963,20 +960,18 @@ const MatchGameResultSubSchema = new Schema( const MatchSeriesResultSubSchema = new Schema( { - blueGroupIndex: { type: Number, required: true, default: 1, min: 1 }, - redGroupIndex: { type: Number, required: true, default: 1, min: 1 }, - blueScore: { type: Number, required: true, default: 0 }, - redScore: { type: Number, required: true, default: 0 }, - winnerSide: { type: String, enum: TEAM_SIDES, required: false }, + teamAIndex: { type: Number, required: true, min: 1 }, + teamBIndex: { type: Number, required: true, min: 1 }, + teamAWins: { type: Number, required: true, default: 0 }, + teamBWins: { type: Number, required: true, default: 0 }, + winnerTeamIndex: { type: Number, required: false, min: 1 }, }, { _id: false }, ); const MatchResultSubSchema = new Schema( { - winnerSide: { type: String, enum: TEAM_SIDES, required: false }, - blueScore: { type: Number, required: true, default: 0 }, - redScore: { type: Number, required: true, default: 0 }, + winnerTeamIndex: { type: Number, required: false, min: 1 }, mvpUserId: { type: Schema.Types.ObjectId, ref: 'user' }, riotMatchIds: { type: [String], required: true, default: [] }, games: { type: [MatchGameResultSubSchema], required: true, default: [] }, @@ -1214,8 +1209,7 @@ const AuctionTeamMemberSubSchema = new Schema( const AuctionTeamSubSchema = new Schema( { - side: { type: String, enum: TEAM_SIDES, required: true }, - groupIndex: { type: Number, required: true, default: 1, min: 1 }, + teamIndex: { type: Number, required: true, min: 1 }, captainUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, points: { type: Number, required: true, default: 0 }, members: { @@ -1229,8 +1223,7 @@ const AuctionTeamSubSchema = new Schema( const AuctionBidSubSchema = new Schema( { - side: { type: String, enum: TEAM_SIDES, required: true }, - groupIndex: { type: Number, required: true, default: 1, min: 1 }, + teamIndex: { type: Number, required: true, min: 1 }, amount: { type: Number, required: true }, bidderUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, timestamp: { type: Date, required: true, default: Date.now }, @@ -1261,8 +1254,7 @@ export const AuctionSchema = new Schema( currentIndex: { type: Number, required: true, default: 0 }, bids: { type: [AuctionBidSubSchema], required: true, default: [] }, currentBid: { type: Number, required: true, default: 0 }, - currentBidder: { type: String, enum: TEAM_SIDES, required: false }, - currentBidderGroupIndex: { type: Number, required: false }, + currentBidderTeamIndex: { type: Number, required: false, min: 1 }, maxTimerSeconds: { type: Number, required: true, default: 30 }, currentDeadline: { type: Date, required: false }, initialPoints: { type: Number, required: true, default: 1000 }, diff --git a/apps/api/src/modules/legacy-import/legacy-import.service.ts b/apps/api/src/modules/legacy-import/legacy-import.service.ts index a773f00d..f8b2da80 100644 --- a/apps/api/src/modules/legacy-import/legacy-import.service.ts +++ b/apps/api/src/modules/legacy-import/legacy-import.service.ts @@ -26,7 +26,6 @@ import { buildUserByPuuidMap, countKnownParticipants, resolveExternalCount, - resolveTeam100IsBlue, type UserByPuuidMap, } from './match-builder.util'; import { @@ -306,9 +305,11 @@ export class LegacyImportService { externalCount: raw ? resolveExternalCount(raw, userByPuuid) : Math.max(0, 10 - memberCount), - blueScore: match.result?.blueScore ?? 0, - redScore: match.result?.redScore ?? 0, - winnerSide: match.result?.winnerSide, + teamAIndex: match.result?.seriesResults?.[0]?.teamAIndex ?? 1, + teamBIndex: match.result?.seriesResults?.[0]?.teamBIndex ?? 2, + teamAWins: match.result?.seriesResults?.[0]?.teamAWins ?? 0, + teamBWins: match.result?.seriesResults?.[0]?.teamBWins ?? 0, + winnerTeamIndex: match.result?.winnerTeamIndex, }; }), nextCursor: @@ -391,9 +392,8 @@ export class LegacyImportService { continue; } - const team100IsBlue = resolveTeam100IsBlue(raw, userByPuuid); const participants = buildParticipantsSnapshot(raw, userByPuuid); - const gameResult = buildGameResult(raw, userByPuuid, team100IsBlue, 1); + const gameResult = buildGameResult(raw, userByPuuid, 1); if (!gameResult || participants.length === 0) { result.skippedNoKnownParticipants += 1; if (Object.keys(update).length > 0) { @@ -402,23 +402,21 @@ export class LegacyImportService { continue; } - const winnerSide = gameResult.winnerSide; + const winnerTeamIndex = gameResult.winnerTeamIndex; update.mapId = raw.info.mapId ?? match.mapId; update.participants = participants; - update.teams = buildTeams(raw, userByPuuid, team100IsBlue); + update.teams = buildTeams(raw, userByPuuid); update.result = { - winnerSide, - blueScore: winnerSide === 'blue' ? 1 : 0, - redScore: winnerSide === 'red' ? 1 : 0, + winnerTeamIndex, riotMatchIds: [riotMatchId], games: [gameResult], seriesResults: [ { - blueGroupIndex: 1, - redGroupIndex: 1, - blueScore: winnerSide === 'blue' ? 1 : 0, - redScore: winnerSide === 'red' ? 1 : 0, - winnerSide, + teamAIndex: 1, + teamBIndex: 2, + teamAWins: winnerTeamIndex === 1 ? 1 : 0, + teamBWins: winnerTeamIndex === 2 ? 1 : 0, + winnerTeamIndex, }, ], }; @@ -485,11 +483,10 @@ export class LegacyImportService { const counts = countKnownParticipants(detail, userByPuuid); if (counts.total === 0) return 'skipped'; - const team100IsBlue = resolveTeam100IsBlue(detail, userByPuuid); - const gameResult = buildGameResult(detail, userByPuuid, team100IsBlue, 1); + const gameResult = buildGameResult(detail, userByPuuid, 1); if (!gameResult || gameResult.participants.length === 0) return 'skipped'; - const winnerSide = gameResult.winnerSide; + const winnerTeamIndex = gameResult.winnerTeamIndex; const matchPayload: Partial = { communityId: new mongoose.Types.ObjectId(job.communityId), title: this.formatLegacyDate(detail.info.gameCreation), @@ -504,20 +501,18 @@ export class LegacyImportService { teamBuiltAt: new Date(detail.info.gameCreation), hostUserId: new mongoose.Types.ObjectId(job.triggeredBy), participants: buildParticipantsSnapshot(detail, userByPuuid), - teams: buildTeams(detail, userByPuuid, team100IsBlue), + teams: buildTeams(detail, userByPuuid), result: { - winnerSide, - blueScore: winnerSide === 'blue' ? 1 : 0, - redScore: winnerSide === 'red' ? 1 : 0, + winnerTeamIndex, riotMatchIds: [riotMatchId], games: [gameResult], seriesResults: [ { - blueGroupIndex: 1, - redGroupIndex: 1, - blueScore: winnerSide === 'blue' ? 1 : 0, - redScore: winnerSide === 'red' ? 1 : 0, - winnerSide, + teamAIndex: 1, + teamBIndex: 2, + teamAWins: winnerTeamIndex === 1 ? 1 : 0, + teamBWins: winnerTeamIndex === 2 ? 1 : 0, + winnerTeamIndex, }, ], }, diff --git a/apps/api/src/modules/legacy-import/legacy-import.types.ts b/apps/api/src/modules/legacy-import/legacy-import.types.ts index e1559b30..bc2d2205 100644 --- a/apps/api/src/modules/legacy-import/legacy-import.types.ts +++ b/apps/api/src/modules/legacy-import/legacy-import.types.ts @@ -55,9 +55,11 @@ export interface LegacyMatchListResponse { riotMatchId: string | null; memberCount: number; externalCount: number; - blueScore: number; - redScore: number; - winnerSide?: 'blue' | 'red'; + teamAIndex: number; + teamBIndex: number; + teamAWins: number; + teamBWins: number; + winnerTeamIndex?: number; }>; nextCursor: number | null; } diff --git a/apps/api/src/modules/legacy-import/match-builder.util.ts b/apps/api/src/modules/legacy-import/match-builder.util.ts index def1f901..6915ecc4 100644 --- a/apps/api/src/modules/legacy-import/match-builder.util.ts +++ b/apps/api/src/modules/legacy-import/match-builder.util.ts @@ -5,7 +5,6 @@ import type { MatchTeam, Position, RiotAccount, - TeamSide, UserDocument, } from '../global/database/schema'; import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types'; @@ -91,10 +90,11 @@ export function buildParticipantsSnapshot( export function buildTeams( detail: RiotMatchDto, userByPuuid: UserByPuuidMap, - team100IsBlue: boolean, ): MatchTeam[] { - return (['blue', 'red'] as TeamSide[]).map((side) => { - const teamId = resolveRiotTeamId(side, team100IsBlue); + return [ + { teamIndex: 1, teamId: RIOT_BLUE_TEAM_ID }, + { teamIndex: 2, teamId: RIOT_RED_TEAM_ID }, + ].map(({ teamIndex, teamId }) => { const members = detail.info.participants .filter((participant) => participant.teamId === teamId) .map((participant) => { @@ -107,9 +107,8 @@ export function buildTeams( }) .filter((member): member is NonNullable => Boolean(member)); return { - side, - groupIndex: 1, - name: side === 'blue' ? '블루팀' : '레드팀', + teamIndex, + name: `${teamIndex}팀`, members, }; }); @@ -118,20 +117,21 @@ export function buildTeams( export function buildGameResult( detail: RiotMatchDto, userByPuuid: UserByPuuidMap, - team100IsBlue: boolean, gameNumber = 1, ): MatchGameResult | null { const winningTeam = detail.info.teams.find((team) => team.win); if (!winningTeam) return null; - const winnerSide = resolveSide(winningTeam.teamId, team100IsBlue); + const winnerSide = resolveSide(winningTeam.teamId); if (!winnerSide) return null; + const winnerTeamIndex = winnerSide === 'blue' ? 1 : 2; const participants = detail.info.participants .map((participant) => { const user = userByPuuid.get(participant.puuid); - const side = resolveSide(participant.teamId, team100IsBlue); + const side = resolveSide(participant.teamId); if (!user || !side) return null; return { userId: user.userId, + teamIndex: side === 'blue' ? 1 : 2, side, championId: participant.championId, kills: participant.kills, @@ -147,9 +147,10 @@ export function buildGameResult( return { gameNumber, riotMatchId: detail.metadata.matchId, + blueTeamIndex: 1, + redTeamIndex: 2, + winnerTeamIndex, winnerSide, - blueGroupIndex: 1, - redGroupIndex: 1, gameCreation: detail.info.gameCreation, gameDuration: detail.info.gameDuration, participants, @@ -165,16 +166,9 @@ export function resolveExternalCount( ).length; } -function resolveRiotTeamId(side: TeamSide, team100IsBlue: boolean): number { - if (side === 'blue') { - return team100IsBlue ? RIOT_BLUE_TEAM_ID : RIOT_RED_TEAM_ID; - } - return team100IsBlue ? RIOT_RED_TEAM_ID : RIOT_BLUE_TEAM_ID; -} - -function resolveSide(teamId: number, team100IsBlue: boolean): TeamSide | null { - if (teamId === RIOT_BLUE_TEAM_ID) return team100IsBlue ? 'blue' : 'red'; - if (teamId === RIOT_RED_TEAM_ID) return team100IsBlue ? 'red' : 'blue'; +function resolveSide(teamId: number): 'blue' | 'red' | null { + if (teamId === RIOT_BLUE_TEAM_ID) return 'blue'; + if (teamId === RIOT_RED_TEAM_ID) return 'red'; return null; } diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts index 4fd29633..8062a6f5 100644 --- a/apps/api/src/modules/match/match.service.ts +++ b/apps/api/src/modules/match/match.service.ts @@ -9,6 +9,7 @@ import { ConnectionService } from '../global/database/connection.service'; import { Match, MatchDocument, + MatchSeriesResult, MatchStatus, PositionPreference, TierInfo, @@ -99,15 +100,7 @@ export class MatchService { (left, right) => left.gameNumber - right.gameNumber, ); if (!obj.result.seriesResults?.length) { - obj.result.seriesResults = [ - { - blueGroupIndex: 1, - redGroupIndex: 1, - blueScore: obj.result.blueScore ?? 0, - redScore: obj.result.redScore ?? 0, - winnerSide: obj.result.winnerSide, - }, - ]; + obj.result.seriesResults = this.buildSeriesResults(obj.result.games); } } return { @@ -120,7 +113,6 @@ export class MatchService { })), teams: (obj.teams ?? []).map((team) => ({ ...team, - groupIndex: team.groupIndex ?? 1, })), tournamentCodes: await this.tournamentCodeService.buildSlots(match), }; @@ -239,4 +231,33 @@ export class MatchService { fetchedAt: tier.fetchedAt, }; } + + private buildSeriesResults( + games: NonNullable['games'], + ): MatchSeriesResult[] { + const bySeries = new Map(); + for (const game of games) { + const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex); + const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex); + const key = `${teamAIndex}:${teamBIndex}`; + const current = + bySeries.get(key) ?? + ({ + teamAIndex, + teamBIndex, + teamAWins: 0, + teamBWins: 0, + } satisfies MatchSeriesResult); + if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1; + if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1; + current.winnerTeamIndex = + current.teamAWins > current.teamBWins + ? teamAIndex + : current.teamBWins > current.teamAWins + ? teamBIndex + : undefined; + bySeries.set(key, current); + } + return [...bySeries.values()]; + } } diff --git a/apps/api/src/modules/tournament-code/tournament-code.service.ts b/apps/api/src/modules/tournament-code/tournament-code.service.ts index 6d39a09f..42b66084 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.service.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.service.ts @@ -369,23 +369,25 @@ export class TournamentCodeService { private resolveRequiredSlots(match: MatchDocument): number { const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; - const teamGroups = new Set( - (match.teams ?? []).map((team) => team.groupIndex ?? 1), - ); + const teamCount = (match.teams ?? []).length; const activeParticipantCount = (match.participants ?? []).filter( (participant) => !participant.excluded, ).length; - const participantGroups = Math.floor(activeParticipantCount / 10); - const groups = Math.max(1, teamGroups.size, participantGroups); - return groups * gameCount; + const participantSeriesCount = Math.floor(activeParticipantCount / 10); + const teamSeriesCount = Math.ceil(teamCount / 2); + const seriesCount = Math.max(1, teamSeriesCount, participantSeriesCount); + return seriesCount * gameCount; } private resolveSeriesRefForGameNumber( match: MatchDocument, gameNumber: number, - ): { blueGroupIndex: number; redGroupIndex: number } { + ): { teamAIndex: number; teamBIndex: number } { const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; - const groupIndex = Math.max(1, Math.ceil(gameNumber / perSeries)); - return { blueGroupIndex: groupIndex, redGroupIndex: groupIndex }; + const seriesIndex = Math.max(1, Math.ceil(gameNumber / perSeries)); + return { + teamAIndex: (seriesIndex - 1) * 2 + 1, + teamBIndex: (seriesIndex - 1) * 2 + 2, + }; } } diff --git a/apps/api/src/modules/tournament-code/tournament-code.types.ts b/apps/api/src/modules/tournament-code/tournament-code.types.ts index 50c7d127..207f5b0c 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.types.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.types.ts @@ -24,8 +24,8 @@ export interface BulkUploadTournamentCodesResponse { export interface TournamentCodeSlotView { gameNumber: number; - blueGroupIndex: number; - redGroupIndex: number; + teamAIndex: number; + teamBIndex: number; code: string | null; expiresAt: string | null; state: TournamentCodeState | 'pending'; diff --git a/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts b/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts index a0e72be8..4a254382 100644 --- a/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts +++ b/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts @@ -23,16 +23,16 @@ function makeMatch(): { const match = { teams: [ { - side: 'blue', - name: '블루팀', + teamIndex: 1, + name: '1팀', members: blueUserIds.map((userId) => ({ userId, assignedPosition: 'MID', })), }, { - side: 'red', - name: '레드팀', + teamIndex: 2, + name: '2팀', members: redUserIds.map((userId) => ({ userId, assignedPosition: 'MID', @@ -111,9 +111,16 @@ describe('computeGameResult', () => { gameNumber: 1, riotMatchId: 'KR_1', winnerSide: 'blue', + blueTeamIndex: 1, + redTeamIndex: 2, + winnerTeamIndex: 1, gameDuration: 1800, }); expect(result?.participants).toHaveLength(10); + expect(result?.participants[0]).toMatchObject({ + teamIndex: 1, + side: 'blue', + }); }); it('handles reversed Riot side assignment', () => { @@ -126,7 +133,12 @@ describe('computeGameResult', () => { const result = computeGameResult({ match, lookup, detail, gameNumber: 2 }); - expect(result?.winnerSide).toBe('red'); + expect(result).toMatchObject({ + blueTeamIndex: 2, + redTeamIndex: 1, + winnerSide: 'blue', + winnerTeamIndex: 2, + }); }); it('rejects matches with too little overlap', () => { diff --git a/apps/api/src/modules/tournament-result/team-mapping.util.ts b/apps/api/src/modules/tournament-result/team-mapping.util.ts index 0f47cd1a..8f463365 100644 --- a/apps/api/src/modules/tournament-result/team-mapping.util.ts +++ b/apps/api/src/modules/tournament-result/team-mapping.util.ts @@ -1,9 +1,5 @@ import mongoose from 'mongoose'; -import type { - MatchDocument, - MatchGameResult, - TeamSide, -} from '../global/database/schema'; +import type { MatchDocument, MatchGameResult, TeamSide } from '../global/database/schema'; import type { RiotMatchDto } from '../riot/riot.types'; const RIOT_BLUE_TEAM_ID = 100; @@ -37,13 +33,10 @@ export function collectMatchUserIds(match: MatchDocument): mongoose.Types.Object export function collectTeamPuuids( match: MatchDocument, - side: TeamSide, + teamIndex: number, lookup: MatchPuuidLookup, - groupIndex = 1, ): string[] { - const team = match.teams.find( - (item) => item.side === side && (item.groupIndex ?? 1) === groupIndex, - ); + const team = match.teams.find((item) => item.teamIndex === teamIndex); if (!team) return []; const userIds = [ ...(team.captainUserId ? [team.captainUserId] : []), @@ -59,19 +52,19 @@ export function computeGameResult(params: { detail: RiotMatchDto; gameNumber: number; lookup: MatchPuuidLookup; - blueGroupIndex?: number; - redGroupIndex?: number; + teamAIndex?: number; + teamBIndex?: number; }): MatchGameResult | null { const { match, detail, gameNumber, lookup, - blueGroupIndex = 1, - redGroupIndex = 1, + teamAIndex = 1, + teamBIndex = 2, } = params; - const ourBluePuuids = collectTeamPuuids(match, 'blue', lookup, blueGroupIndex); - const ourRedPuuids = collectTeamPuuids(match, 'red', lookup, redGroupIndex); + const teamAPuuids = collectTeamPuuids(match, teamAIndex, lookup); + const teamBPuuids = collectTeamPuuids(match, teamBIndex, lookup); const team100Puuids = detail.info.participants .filter((participant) => participant.teamId === RIOT_BLUE_TEAM_ID) .map((participant) => participant.puuid); @@ -80,15 +73,21 @@ export function computeGameResult(params: { .map((participant) => participant.puuid); const normalOverlap = - countOverlap(team100Puuids, ourBluePuuids) + - countOverlap(team200Puuids, ourRedPuuids); + countOverlap(team100Puuids, teamAPuuids) + + countOverlap(team200Puuids, teamBPuuids); const reversedOverlap = - countOverlap(team100Puuids, ourRedPuuids) + - countOverlap(team200Puuids, ourBluePuuids); - const teamMapping: Record = - normalOverlap >= reversedOverlap - ? { [RIOT_BLUE_TEAM_ID]: 'blue', [RIOT_RED_TEAM_ID]: 'red' } - : { [RIOT_BLUE_TEAM_ID]: 'red', [RIOT_RED_TEAM_ID]: 'blue' }; + countOverlap(team100Puuids, teamBPuuids) + + countOverlap(team200Puuids, teamAPuuids); + const blueTeamIndex = normalOverlap >= reversedOverlap ? teamAIndex : teamBIndex; + const redTeamIndex = normalOverlap >= reversedOverlap ? teamBIndex : teamAIndex; + const teamIndexByRiotTeamId: Record = { + [RIOT_BLUE_TEAM_ID]: blueTeamIndex, + [RIOT_RED_TEAM_ID]: redTeamIndex, + }; + const sideByRiotTeamId: Record = { + [RIOT_BLUE_TEAM_ID]: 'blue', + [RIOT_RED_TEAM_ID]: 'red', + }; if (Math.max(normalOverlap, reversedOverlap) < MINIMUM_TRUSTED_OVERLAP) { return null; @@ -96,16 +95,20 @@ export function computeGameResult(params: { const winningTeam = detail.info.teams.find((team) => team.win); if (!winningTeam) return null; - const winnerSide = teamMapping[winningTeam.teamId]; + const winnerSide = sideByRiotTeamId[winningTeam.teamId]; if (!winnerSide) return null; + const winnerTeamIndex = teamIndexByRiotTeamId[winningTeam.teamId]; + if (!winnerTeamIndex) return null; const participants = detail.info.participants .map((participant) => { const userId = lookup.userIdByPuuid.get(participant.puuid); - const side = teamMapping[participant.teamId]; - if (!userId || !side) return null; + const side = sideByRiotTeamId[participant.teamId]; + const teamIndex = teamIndexByRiotTeamId[participant.teamId]; + if (!userId || !side || !teamIndex) return null; return { userId, + teamIndex, side, championId: participant.championId, kills: participant.kills, @@ -121,9 +124,10 @@ export function computeGameResult(params: { return { gameNumber, riotMatchId: detail.metadata.matchId, + blueTeamIndex, + redTeamIndex, + winnerTeamIndex, winnerSide, - blueGroupIndex, - redGroupIndex, gameCreation: detail.info.gameCreation, gameDuration: detail.info.gameDuration, participants, diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.ts b/apps/api/src/modules/tournament-result/tournament-result.service.ts index 477ac9da..3ee99897 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.ts @@ -243,12 +243,9 @@ export class TournamentResultService { match.status = 'finished'; if (match.result) { - match.result.winnerSide = - match.result.blueScore > match.result.redScore - ? 'blue' - : match.result.redScore > match.result.blueScore - ? 'red' - : undefined; + match.result.winnerTeamIndex = this.resolveMatchWinnerTeamIndex( + match.result.seriesResults ?? [], + ); } match.resultPollState = { startedAt: match.resultPollState?.startedAt ?? new Date(), @@ -392,15 +389,14 @@ export class TournamentResultService { ), gameResult, ].sort((left, right) => left.gameNumber - right.gameNumber); + const seriesResults = this.buildSeriesResults(games); match.result = { - winnerSide: match.result?.winnerSide, - blueScore: games.filter((game) => game.winnerSide === 'blue').length, - redScore: games.filter((game) => game.winnerSide === 'red').length, + winnerTeamIndex: this.resolveMatchWinnerTeamIndex(seriesResults), mvpUserId: match.result?.mvpUserId, riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))], games, - seriesResults: this.buildSeriesResults(games), + seriesResults, }; } @@ -410,59 +406,83 @@ export class TournamentResultService { const bySeries = new Map< string, { - blueGroupIndex: number; - redGroupIndex: number; - blueScore: number; - redScore: number; - winnerSide?: 'blue' | 'red'; + teamAIndex: number; + teamBIndex: number; + teamAWins: number; + teamBWins: number; + winnerTeamIndex?: number; } >(); for (const game of games) { - const blueGroupIndex = game.blueGroupIndex ?? 1; - const redGroupIndex = game.redGroupIndex ?? 1; - const key = `${blueGroupIndex}:${redGroupIndex}`; + const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex); + const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex); + const key = `${teamAIndex}:${teamBIndex}`; const current = bySeries.get(key) ?? { - blueGroupIndex, - redGroupIndex, - blueScore: 0, - redScore: 0, + teamAIndex, + teamBIndex, + teamAWins: 0, + teamBWins: 0, }; - if (game.winnerSide === 'blue') current.blueScore += 1; - if (game.winnerSide === 'red') current.redScore += 1; - current.winnerSide = - current.blueScore > current.redScore - ? 'blue' - : current.redScore > current.blueScore - ? 'red' + if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1; + if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1; + current.winnerTeamIndex = + current.teamAWins > current.teamBWins + ? teamAIndex + : current.teamBWins > current.teamAWins + ? teamBIndex : undefined; bySeries.set(key, current); } return [...bySeries.values()].sort( (left, right) => - left.blueGroupIndex - right.blueGroupIndex || - left.redGroupIndex - right.redGroupIndex, + left.teamAIndex - right.teamAIndex || + left.teamBIndex - right.teamBIndex, ); } private resolveSeriesRefForGameNumber( match: MatchDocument, gameNumber: number, - ): { blueGroupIndex: number; redGroupIndex: number } { + ): { teamAIndex: number; teamBIndex: number } { const perSeries = match.gameCount || 1; - const groupIndex = Math.max(1, Math.ceil(gameNumber / perSeries)); - return { blueGroupIndex: groupIndex, redGroupIndex: groupIndex }; + const seriesIndex = Math.max(1, Math.ceil(gameNumber / perSeries)); + return { + teamAIndex: (seriesIndex - 1) * 2 + 1, + teamBIndex: (seriesIndex - 1) * 2 + 2, + }; } private resolveRequiredGameSlots(match: MatchDocument): number { - const groups = Math.max( - 1, - new Set(match.teams.map((team) => team.groupIndex ?? 1)).size, + const activeParticipantCount = match.participants.filter( + (participant) => !participant.excluded, + ).length; + const participantSeriesCount = Math.floor(activeParticipantCount / 10); + const teamSeriesCount = Math.ceil(match.teams.length / 2); + const seriesCount = Math.max(1, participantSeriesCount, teamSeriesCount); + return seriesCount * (match.gameCount || 1); + } + + private resolveMatchWinnerTeamIndex( + seriesResults: NonNullable['seriesResults'], + ): number | undefined { + const winsByTeam = new Map(); + for (const series of seriesResults ?? []) { + if (!series.winnerTeamIndex) continue; + winsByTeam.set( + series.winnerTeamIndex, + (winsByTeam.get(series.winnerTeamIndex) ?? 0) + 1, + ); + } + const sorted = [...winsByTeam.entries()].sort( + (left, right) => right[1] - left[1], ); - return groups * (match.gameCount || 1); + if (sorted.length === 0) return undefined; + if (sorted.length > 1 && sorted[0][1] === sorted[1][1]) return undefined; + return sorted[0][0]; } private async updatePollState( diff --git a/apps/api/src/modules/tournament-result/tournament-result.types.ts b/apps/api/src/modules/tournament-result/tournament-result.types.ts index 25e265b7..cd9fc0d7 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.types.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.types.ts @@ -21,6 +21,7 @@ export interface EnqueueTournamentResultPollResult { export interface ComputedGameParticipant { userId: string; + teamIndex: number; side: TeamSide; championId: number; kills: number; diff --git a/apps/api/src/seed.ts b/apps/api/src/seed.ts index 458935b0..458e8cf6 100644 --- a/apps/api/src/seed.ts +++ b/apps/api/src/seed.ts @@ -938,8 +938,8 @@ async function main() { participants: auctionPlayers.map(toMatchParticipant), teams: [ { - side: 'blue', - name: '블루팀', + teamIndex: 1, + name: '1팀', captainUserId: players[0]._id, members: [ { @@ -950,8 +950,8 @@ async function main() { ], }, { - side: 'red', - name: '레드팀', + teamIndex: 2, + name: '2팀', captainUserId: players[1]._id, members: [ { @@ -982,8 +982,8 @@ async function main() { participants: players.map(toMatchParticipant), teams: [ { - side: 'blue', - name: '블루팀', + teamIndex: 1, + name: '1팀', captainUserId: players[0]._id, members: finishedBlue.map((member) => ({ userId: member.user._id, @@ -992,8 +992,8 @@ async function main() { })), }, { - side: 'red', - name: '레드팀', + teamIndex: 2, + name: '2팀', captainUserId: players[1]._id, members: finishedRed.map((member) => ({ userId: member.user._id, @@ -1003,11 +1003,18 @@ async function main() { }, ], result: { - winnerSide: 'blue', - blueScore: 2, - redScore: 1, + winnerTeamIndex: 1, mvpUserId: players[0]._id, riotMatchIds: ['KR_DEV_0001', 'KR_DEV_0002', 'KR_DEV_0003'], + seriesResults: [ + { + teamAIndex: 1, + teamBIndex: 2, + teamAWins: 2, + teamBWins: 1, + winnerTeamIndex: 1, + }, + ], }, prizes: ['1등 팀: RP 10,000 지급', 'MVP: 프리리'], notices: [], @@ -1036,13 +1043,13 @@ async function main() { phase: 'presenting', teams: [ { - side: 'blue', + teamIndex: 1, captainUserId: players[0]._id, points: 1000, members: [], }, { - side: 'red', + teamIndex: 2, captainUserId: players[1]._id, points: 1000, members: [], diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index a70eb93a..c5c84037 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -77,7 +77,7 @@ function App() { } /> } /> } /> } /> diff --git a/apps/web/src/api/mappers.ts b/apps/web/src/api/mappers.ts index 8f98c05e..64f69af7 100644 --- a/apps/web/src/api/mappers.ts +++ b/apps/web/src/api/mappers.ts @@ -11,10 +11,9 @@ import type { MatchStatus, Position, RiotLane, - TeamSide, TournamentCodeSlotView, } from "./types"; -import { POSITION_ORDER, sideLabel } from "../lib/league"; +import { POSITION_ORDER, teamIndexLabel } from "../lib/league"; export interface ParticipantView { id: string; @@ -34,8 +33,7 @@ export interface TeamParticipantView extends ParticipantView { } export interface TeamView { - side: TeamSide; - groupIndex: number; + teamIndex: number; name: string; participants: TeamParticipantView[]; } @@ -57,21 +55,21 @@ export interface MatchDetailView { teams: TeamView[]; result?: { winner?: string; - winnerSide?: TeamSide; - blueScore: number; - redScore: number; + winnerTeamIndex?: number; riotMatchIds: string[]; games: Array<{ gameNumber: number; riotMatchId: string; - winnerSide: TeamSide; - blueGroupIndex: number; - redGroupIndex: number; + blueTeamIndex: number; + redTeamIndex: number; + winnerTeamIndex: number; + winnerSide: "blue" | "red"; gameCreation: number; gameDuration: number; participants: Array<{ userId: string; - side: TeamSide; + teamIndex: number; + side: "blue" | "red"; championId: number; kills: number; deaths: number; @@ -101,8 +99,8 @@ export interface AuctionPlayerView extends ParticipantView { } export interface AuctionTeamView { - side: TeamSide; - groupIndex: number; + teamIndex: number; + name: string; captainUserId: string; captainName: string; points: number; @@ -121,13 +119,12 @@ export interface AuctionStateView { totalPlayers: number; auctionOrder: AuctionPlayerView[]; bids: { - side: TeamSide; - groupIndex: number; + teamIndex: number; amount: number; timestamp: string; }[]; currentBid: number; - currentBidder: { side: TeamSide; groupIndex: number } | null; + currentBidder: { teamIndex: number } | null; timer: number; maxTimer: number; deadline?: string; @@ -270,8 +267,8 @@ function mapAuctionTeamToView( participantLookup: Map, ): AuctionTeamView { return { - side: team.side, - groupIndex: team.groupIndex ?? 1, + teamIndex: team.teamIndex, + name: teamIndexLabel(team.teamIndex), captainUserId: team.captainUserId, captainName: participantLookup.get(team.captainUserId)?.summonerName ?? @@ -405,9 +402,8 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView { ); const teams = match.teams.map((team) => ({ - side: team.side, - groupIndex: team.groupIndex ?? 1, - name: team.name || sideLabel(team.side), + teamIndex: team.teamIndex, + name: teamIndexLabel(team.teamIndex, team.name), participants: team.members.map((member) => { const participant = participantLookup.get(member.userId) ?? @@ -421,8 +417,8 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView { }), })); - const winnerTeam = match.result?.winnerSide - ? teams.find((team) => team.side === match.result?.winnerSide) + const winnerTeam = match.result?.winnerTeamIndex + ? teams.find((team) => team.teamIndex === match.result?.winnerTeamIndex) : undefined; return { @@ -434,20 +430,16 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView { description: match.description, map: mapIdToLabel(match.mapId), maxParticipants: match.maxParticipants, - gameCount: match.gameCount ?? 3, - gameMode: match.gameMode ?? "pair", + gameCount: match.gameCount ?? 3, + gameMode: match.gameMode ?? "pair", tournamentCodes: match.tournamentCodes ?? [], joined: Boolean(match.joined), participants, teams, result: match.result - ? { - winner: match.result.winnerSide - ? winnerTeam?.name ?? sideLabel(match.result.winnerSide) - : undefined, - winnerSide: match.result.winnerSide, - blueScore: match.result.blueScore, - redScore: match.result.redScore, + ? { + winner: match.result.winnerTeamIndex ? winnerTeam?.name : undefined, + winnerTeamIndex: match.result.winnerTeamIndex, riotMatchIds: match.result.riotMatchIds, games: [...(match.result.games ?? [])].sort( (left, right) => left.gameNumber - right.gameNumber, @@ -476,9 +468,7 @@ export function mapApiAuctionToAuctionState( auctionOrder.map((player) => [player.userId, player]), ); const teams = [...auction.teams].sort( - (left, right) => - (left.groupIndex ?? 1) - (right.groupIndex ?? 1) || - (left.side === "blue" ? -1 : 1), + (left, right) => left.teamIndex - right.teamIndex, ); const totalPlayers = auctionOrder.length; @@ -510,16 +500,14 @@ export function mapApiAuctionToAuctionState( totalPlayers, auctionOrder, bids: auction.bids.map((bid) => ({ - side: bid.side, - groupIndex: bid.groupIndex ?? 1, + teamIndex: bid.teamIndex, amount: bid.amount, timestamp: bid.timestamp, })), currentBid: auction.currentBid, - currentBidder: auction.currentBidder + currentBidder: auction.currentBidderTeamIndex ? { - side: auction.currentBidder, - groupIndex: auction.currentBidderGroupIndex ?? 1, + teamIndex: auction.currentBidderTeamIndex, } : null, timer, diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index 13d1f91f..1ae5d95a 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -117,8 +117,8 @@ export type TournamentCodeSlotState = TournamentCodeState | 'pending'; export interface TournamentCodeSlotView { gameNumber: number; - blueGroupIndex: number; - redGroupIndex: number; + teamAIndex: number; + teamBIndex: number; code: string | null; expiresAt: string | null; state: TournamentCodeSlotState; @@ -144,8 +144,7 @@ export interface ApiMatchTeamMember { } export interface ApiMatchTeam { - side: TeamSide; - groupIndex: number; + teamIndex: number; name: string; captainUserId?: string; members: ApiMatchTeamMember[]; @@ -153,6 +152,7 @@ export interface ApiMatchTeam { export interface ApiMatchGameResultParticipant { userId: string; + teamIndex: number; side: TeamSide; championId: number; kills: number; @@ -164,27 +164,26 @@ export interface ApiMatchGameResultParticipant { export interface ApiMatchGameResult { gameNumber: number; riotMatchId: string; + blueTeamIndex: number; + redTeamIndex: number; + winnerTeamIndex: number; winnerSide: TeamSide; - blueGroupIndex: number; - redGroupIndex: number; gameCreation: number; gameDuration: number; participants: ApiMatchGameResultParticipant[]; } export interface ApiMatchResult { - winnerSide?: TeamSide; - blueScore: number; - redScore: number; + winnerTeamIndex?: number; mvpUserId?: string; riotMatchIds: string[]; games: ApiMatchGameResult[]; seriesResults?: Array<{ - blueGroupIndex: number; - redGroupIndex: number; - blueScore: number; - redScore: number; - winnerSide?: TeamSide; + teamAIndex: number; + teamBIndex: number; + teamAWins: number; + teamBWins: number; + winnerTeamIndex?: number; }>; } @@ -236,16 +235,14 @@ export interface ApiAuctionTeamMember { } export interface ApiAuctionTeam { - side: TeamSide; - groupIndex: number; + teamIndex: number; captainUserId: string; points: number; members: ApiAuctionTeamMember[]; } export interface ApiAuctionBid { - side: TeamSide; - groupIndex?: number; + teamIndex: number; amount: number; bidderUserId: string; timestamp: string; @@ -260,8 +257,7 @@ export interface ApiAuction { currentIndex: number; bids: ApiAuctionBid[]; currentBid: number; - currentBidder?: TeamSide; - currentBidderGroupIndex?: number; + currentBidderTeamIndex?: number; maxTimerSeconds: number; currentDeadline?: string; initialPoints: number; @@ -520,17 +516,25 @@ export interface ApiInternalMatchCard { scheduledAt: string; status: 'finished' | 'in-progress'; gameCount: number; - blueScore: number; - redScore: number; - winnerSide?: TeamSide; + winnerTeamIndex?: number; + seriesResults: Array<{ + teamAIndex: number; + teamBIndex: number; + teamAWins: number; + teamBWins: number; + winnerTeamIndex?: number; + }>; games: Array<{ gameNumber: number; riotMatchId: string | null; + blueTeamIndex: number; + redTeamIndex: number; + winnerTeamIndex: number | null; winnerSide: TeamSide | null; gameDuration: number; }>; teams: Array<{ - side: TeamSide; + teamIndex: number; name: string; members: Array<{ userId: string; @@ -605,12 +609,14 @@ export interface ApiInternalMatchDetailResponse { gameCreation: number; gameDuration: number; teams: Array<{ + teamIndex: number; side: TeamSide; win: boolean; objectives: { baron: number; dragon: number; tower: number }; participants: Array<{ userId: string | null; summonerName: string; + teamIndex: number; side: TeamSide; teamPosition: string; championId: number; @@ -725,9 +731,11 @@ export interface LegacyMatchListItem { riotMatchId: string | null; memberCount: number; externalCount: number; - blueScore: number; - redScore: number; - winnerSide?: TeamSide; + teamAIndex: number; + teamBIndex: number; + teamAWins: number; + teamBWins: number; + winnerTeamIndex?: number; } export interface LegacyMatchListResponse { diff --git a/apps/web/src/api/useAuctionSocket.ts b/apps/web/src/api/useAuctionSocket.ts index 1a846078..49cef7ed 100644 --- a/apps/web/src/api/useAuctionSocket.ts +++ b/apps/web/src/api/useAuctionSocket.ts @@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'; import { io, type Socket } from 'socket.io-client'; import { API_BASE_URL, useAuthUserId } from '../config'; import { acquireAccessToken } from '../lib/auth/token-provider'; -import type { ApiAuction, Position, TeamSide } from './types'; +import type { ApiAuction, Position } from './types'; type ConnectionStatus = | 'idle' @@ -12,8 +12,7 @@ type ConnectionStatus = | 'error'; interface BidPayload { - side: TeamSide; - groupIndex?: number; + teamIndex: number; amount: number; bidderUserId?: string; } diff --git a/apps/web/src/config.ts b/apps/web/src/config.ts index 978b884b..2e0381ca 100644 --- a/apps/web/src/config.ts +++ b/apps/web/src/config.ts @@ -1,9 +1,8 @@ import { useSyncExternalStore } from 'react'; -export type DevCaptainSide = 'spectator' | 'blue' | 'red'; - const AUTH_USER_ID_STORAGE_KEY = 'lolympus.authUserId'; -const DEV_CAPTAIN_SIDE_STORAGE_KEY = 'lolympus.devCaptainSide'; +const DEV_CAPTAIN_TEAM_INDEX_STORAGE_KEY = 'lolympus.devCaptainTeamIndex'; +const LEGACY_DEV_CAPTAIN_SIDE_STORAGE_KEY = 'lolympus.devCaptainSide'; const AUTH_USER_CHANGED_EVENT = 'lolympus:auth-user-changed'; const CAPTAIN_SIDE_CHANGED_EVENT = 'lolympus:captain-side-changed'; @@ -55,23 +54,29 @@ export function setAuthUserId(userId: string | null) { dispatchWindowEvent(AUTH_USER_CHANGED_EVENT); } -export function getDevCaptainSide(): DevCaptainSide { - if (typeof window === 'undefined') return 'spectator'; +export function getDevCaptainTeamIndex(): number | null { + if (typeof window === 'undefined') return null; - const value = window.localStorage.getItem( - DEV_CAPTAIN_SIDE_STORAGE_KEY, - ) as DevCaptainSide | null; + const value = window.localStorage.getItem(DEV_CAPTAIN_TEAM_INDEX_STORAGE_KEY); + const parsed = Number(value); + if (Number.isInteger(parsed) && parsed > 0) return parsed; - if (value === 'blue' || value === 'red' || value === 'spectator') { - return value; - } - - return 'spectator'; + 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 setDevCaptainSide(side: DevCaptainSide) { +export function setDevCaptainTeamIndex(teamIndex: number | null) { if (typeof window === 'undefined') return; - window.localStorage.setItem(DEV_CAPTAIN_SIDE_STORAGE_KEY, side); + 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); } @@ -83,10 +88,10 @@ export function useAuthUserId(): string | null { ); } -export function useDevCaptainSide(): DevCaptainSide { - return useSyncExternalStore( +export function useDevCaptainTeamIndex(): number | null { + return useSyncExternalStore( (callback) => subscribeToWindowChanges(CAPTAIN_SIDE_CHANGED_EVENT, callback), - getDevCaptainSide, - () => 'spectator', + getDevCaptainTeamIndex, + () => null, ); } diff --git a/apps/web/src/pages/AuctionPage.tsx b/apps/web/src/pages/AuctionPage.tsx index 94d9d0db..0de47220 100644 --- a/apps/web/src/pages/AuctionPage.tsx +++ b/apps/web/src/pages/AuctionPage.tsx @@ -10,8 +10,8 @@ import { import { useAuctionSocket } from '../api/useAuctionSocket'; import { DEFAULT_COMMUNITY_ID, - setDevCaptainSide, - useDevCaptainSide, + setDevCaptainTeamIndex, + useDevCaptainTeamIndex, } from '../config'; import { ApiError } from '../lib/api'; import { @@ -19,36 +19,31 @@ import { championIconUrl, profileIconUrl, } from '../lib/ddragon'; -import { positionIcon, positionLabel } from '../lib/league'; +import { + positionIcon, + positionLabel, + teamIndexColorClasses, + teamIndexLabel, +} from '../lib/league'; import type { ApiAuction, ApiRiotLaneStats, Position, - TeamSide, } from '../api/types'; type CaptainRole = { - side: TeamSide; - groupIndex: number; + teamIndex: number; }; function formatPoints(value: number) { return value.toLocaleString(); } -function teamLabel(side: 'blue' | 'red', groupIndex = 1) { - const sideLabel = side === 'blue' ? '블루팀' : '레드팀'; - return groupIndex === 1 ? sideLabel : `${groupIndex}조 ${sideLabel}`; -} - function isCurrentBidder( currentBidder: AuctionStateView['currentBidder'], - team: Pick, + team: Pick, ) { - return ( - currentBidder?.side === team.side && - currentBidder.groupIndex === team.groupIndex - ); + return currentBidder?.teamIndex === team.teamIndex; } function getAuctionUpdatedAt(auction: ApiAuction | null | undefined) { @@ -231,26 +226,22 @@ function TeamPanel({ isLeft: boolean; }) { const { data: ddragon } = useDdragonManifest(); - const borderColor = - team.side === 'blue' ? 'border-blue-500/25' : 'border-red-500/25'; - const accentBar = team.side === 'blue' ? 'bg-blue-500' : 'bg-red-500'; - const sideColor = team.side === 'blue' ? 'text-blue-400' : 'text-red-400'; - const headerBg = team.side === 'blue' ? 'bg-blue-500/8' : 'bg-red-500/8'; + const tone = teamIndexColorClasses(team.teamIndex); const teamSize = team.members.length + 1; const isFull = teamSize >= AUCTION_MAX_TEAM_SIZE; return (
-
+
- - {teamLabel(team.side, team.groupIndex)} + + {teamIndexLabel(team.teamIndex, team.name)} 팀장: {team.captainName} @@ -306,7 +297,7 @@ function TeamPanel({ length: Math.max(0, AUCTION_MAX_TEAM_SIZE - 1 - team.members.length), }).map((_, index) => (
@@ -426,12 +417,9 @@ function PlayerSpotlight({
{state.currentBidder && ( - {teamLabel( - state.currentBidder.side, - state.currentBidder.groupIndex, - )} + {teamIndexLabel(state.currentBidder.teamIndex)} )} @@ -452,16 +440,12 @@ function BidControls({ }: { state: AuctionStateView; captainRole: CaptainRole | null; - onBid: (side: TeamSide, groupIndex: number, amount: number) => void; + onBid: (teamIndex: number, amount: number) => void; }) { const [bidAmount, setBidAmount] = useState(100); const minBid = state.currentBid + 10; const activeTeam = captainRole - ? state.teams.find( - (team) => - team.side === captainRole.side && - team.groupIndex === captainRole.groupIndex, - ) + ? state.teams.find((team) => team.teamIndex === captainRole.teamIndex) : null; const activeTeamSize = activeTeam ? activeTeam.members.length + 1 : 0; const isActiveTeamFull = activeTeamSize >= AUCTION_MAX_TEAM_SIZE; @@ -511,21 +495,19 @@ function BidControls({ />
); @@ -549,11 +531,11 @@ function BidLog({ bids }: { bids: AuctionStateView['bids'] }) {
{bids.map((bid, index) => ( -
+
- {teamLabel(bid.side, bid.groupIndex)} + {teamIndexLabel(bid.teamIndex)} → @@ -579,8 +561,7 @@ export default function AuctionPage() { refetchInterval: 5000, }); const socket = useAuctionSocket(id); - const captainSide = useDevCaptainSide(); - const [captainGroupIndex, setCaptainGroupIndex] = useState(1); + const captainTeamIndex = useDevCaptainTeamIndex(); const [now, setNow] = useState(() => Date.now()); const [assignedPosition, setAssignedPosition] = useState('MID'); @@ -594,16 +575,15 @@ export default function AuctionPage() { liveAuction && matchQuery.data ? mapApiAuctionToAuctionState(liveAuction, matchQuery.data, new Date(now)) : null; - const availableGroups = useMemo(() => { - const groups = new Set((auctionState?.teams ?? []).map((team) => team.groupIndex)); - return [...groups].sort((left, right) => left - right); + const availableTeamIndexes = useMemo(() => { + const indexes = new Set((auctionState?.teams ?? []).map((team) => team.teamIndex)); + return [...indexes].sort((left, right) => left - right); }, [auctionState?.teams]); const captainRole: CaptainRole | null = - captainSide === 'spectator' + captainTeamIndex === null ? null : { - side: captainSide, - groupIndex: captainGroupIndex, + teamIndex: captainTeamIndex, }; useEffect(() => { @@ -613,11 +593,11 @@ export default function AuctionPage() { }, [auctionState?.currentPlayer?.id]); useEffect(() => { - if (availableGroups.length === 0) return; - if (!availableGroups.includes(captainGroupIndex)) { - setCaptainGroupIndex(availableGroups[0]); + if (availableTeamIndexes.length === 0) return; + if (captainTeamIndex !== null && !availableTeamIndexes.includes(captainTeamIndex)) { + setDevCaptainTeamIndex(availableTeamIndexes[0]); } - }, [availableGroups, captainGroupIndex]); + }, [availableTeamIndexes, captainTeamIndex]); if (!DEFAULT_COMMUNITY_ID) { return ( @@ -737,31 +717,23 @@ export default function AuctionPage() { 소켓: {socket.connectionStatus} {/* 임시 운영용: 로그인/권한 확인 없이 조작자 역할을 선택할 수 있게 열어둔다. */} - {captainSide !== 'spectator' && availableGroups.length > 1 && ( - - )}
@@ -774,10 +746,10 @@ export default function AuctionPage() {
{auctionState.teams.map((team) => ( ))}
@@ -805,15 +777,10 @@ export default function AuctionPage() { {auctionState.phase === 'sold' && auctionState.currentBidder && (
- {teamLabel( - auctionState.currentBidder.side, - auctionState.currentBidder.groupIndex, - )} 낙찰 + {teamIndexLabel(auctionState.currentBidder.teamIndex)} 낙찰 {' '}— {formatPoints(auctionState.currentBid)}P
)} @@ -821,8 +788,8 @@ export default function AuctionPage() { - socket.placeBid({ side, groupIndex, amount }) + onBid={(teamIndex, amount) => + socket.placeBid({ teamIndex, amount }) } /> diff --git a/apps/web/src/pages/CommunityInternalStatsPage.tsx b/apps/web/src/pages/CommunityInternalStatsPage.tsx index 65a84da6..7b2790c8 100644 --- a/apps/web/src/pages/CommunityInternalStatsPage.tsx +++ b/apps/web/src/pages/CommunityInternalStatsPage.tsx @@ -14,6 +14,7 @@ import type { } from '../api/types'; import { DEFAULT_COMMUNITY_ID } from '../config'; import { championDisplayName, championIconUrl, profileIconUrl } from '../lib/ddragon'; +import { sideShortLabel, teamIndexColorClasses, teamIndexLabel } from '../lib/league'; function formatDateTime(value: string) { return new Intl.DateTimeFormat('ko-KR', { @@ -31,7 +32,7 @@ function formatDuration(seconds: number) { } function sideLabel(side: TeamSide) { - return side === 'blue' ? '블루팀' : '레드팀'; + return sideShortLabel(side); } function sideText(side: TeamSide) { @@ -70,6 +71,13 @@ function MatchCard({ match: ApiInternalMatchCard; manifest: ReturnType['data']; }) { + const primarySeries = match.seriesResults[0]; + const teamName = (teamIndex: number) => + teamIndexLabel( + teamIndex, + match.teams.find((team) => team.teamIndex === teamIndex)?.name, + ); + return ( {game.gameNumber}경기 - {game.winnerSide ? ( + {game.winnerSide && game.winnerTeamIndex ? ( - {sideLabel(game.winnerSide)} 승 + {teamName(game.winnerTeamIndex)} 승 ({sideLabel(game.winnerSide)}) ) : ( '대기' @@ -105,26 +113,32 @@ function MatchCard({
-
-
-
{match.blueScore}
-
BLUE
+ {primarySeries && ( +
+
+
{primarySeries.teamAWins}
+
+ {teamName(primarySeries.teamAIndex)} +
+
+
VS
+
+
{primarySeries.teamBWins}
+
+ {teamName(primarySeries.teamBIndex)} +
+
-
VS
-
-
{match.redScore}
-
RED
-
-
+ )}
{match.teams.map((team) => (
-
+
{team.name}
diff --git a/apps/web/src/pages/InternalMatchDetailPage.tsx b/apps/web/src/pages/InternalMatchDetailPage.tsx index 86197eac..562770f6 100644 --- a/apps/web/src/pages/InternalMatchDetailPage.tsx +++ b/apps/web/src/pages/InternalMatchDetailPage.tsx @@ -3,6 +3,7 @@ import { useDdragonManifest, useInternalMatchDetail } from '../api/hooks'; import type { ApiInternalMatchDetailResponse, TeamSide } from '../api/types'; import { DEFAULT_COMMUNITY_ID } from '../config'; import { championDisplayName, championIconUrl, itemIconUrl } from '../lib/ddragon'; +import { sideShortLabel, teamIndexColorClasses, teamIndexLabel } from '../lib/league'; import { LANE_LABELS } from '../lib/riot-history'; function formatDateTime(value: string | number) { @@ -21,7 +22,7 @@ function formatDuration(seconds: number) { } function sideLabel(side: TeamSide) { - return side === 'blue' ? '블루팀' : '레드팀'; + return sideShortLabel(side); } function sideClass(side: TeamSide) { @@ -100,7 +101,8 @@ function GamePanel({ team.win ? 'bg-base-content/5' : 'opacity-40' }`} > - {sideLabel(team.side)} {team.win ? '승' : '패'} + {teamIndexLabel(team.teamIndex)} ({sideLabel(team.side)}){' '} + {team.win ? '승' : '패'} ))}
@@ -109,7 +111,7 @@ function GamePanel({ {game.teams.map((team) => (
- {sideLabel(team.side)} · 바론 {team.objectives.baron} · 드래곤{' '} + {teamIndexLabel(team.teamIndex)} ({sideLabel(team.side)}) · 바론 {team.objectives.baron} · 드래곤{' '} {team.objectives.dragon} · 타워 {team.objectives.tower}
@@ -219,6 +221,13 @@ export default function InternalMatchDetailPage() { ); } + const primarySeries = detail.match.seriesResults[0]; + const teamName = (teamIndex: number) => + teamIndexLabel( + teamIndex, + detail.match.teams.find((team) => team.teamIndex === teamIndex)?.name, + ); + return (
-
-
-
{detail.match.blueScore}
-
BLUE
+ {primarySeries && ( +
+
+
{primarySeries.teamAWins}
+
+ {teamName(primarySeries.teamAIndex)} +
+
+
VS
+
+
{primarySeries.teamBWins}
+
+ {teamName(primarySeries.teamBIndex)} +
+
-
VS
-
-
{detail.match.redScore}
-
RED
-
-
+ )}
diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index be7932f1..2f79169a 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -21,7 +21,13 @@ import { import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config'; import { apiFetch, ApiError } from '../lib/api'; import { profileIconUrl } from '../lib/ddragon'; -import { positionIcon, positionLabel } from '../lib/league'; +import { + positionIcon, + positionLabel, + sideShortLabel, + teamIndexColorClasses, + teamIndexLabel, +} from '../lib/league'; import type { ApiMatchParticipant, Position, @@ -30,17 +36,11 @@ import type { } from '../api/types'; type CaptainSelectionSlot = { - side: TeamSide; - groupIndex: number; + teamIndex: number; }; function captainSlotKey(slot: CaptainSelectionSlot) { - return `${slot.side}:${slot.groupIndex}`; -} - -function teamLabel(side: TeamSide, groupIndex = 1) { - const sideText = side === 'blue' ? '블루팀' : '레드팀'; - return groupIndex === 1 ? sideText : `${groupIndex}조 ${sideText}`; + return String(slot.teamIndex); } function buildAuctionParticipantPool(participants: ApiMatchParticipant[]) { @@ -55,13 +55,10 @@ function buildAuctionParticipantPool(participants: ApiMatchParticipant[]) { function buildCaptainSlots( participants: ApiMatchParticipant[], ): CaptainSelectionSlot[] { - const groupCount = Math.floor(buildAuctionParticipantPool(participants).length / 10); - return Array.from({ length: groupCount }, (_, index) => index + 1).flatMap( - (groupIndex) => [ - { side: 'blue' as const, groupIndex }, - { side: 'red' as const, groupIndex }, - ], - ); + const teamCount = Math.floor(buildAuctionParticipantPool(participants).length / 5); + return Array.from({ length: teamCount }, (_, index) => ({ + teamIndex: index + 1, + })); } function PosBadge({ pos, sub }: { pos: Position; sub?: boolean }) { @@ -267,20 +264,16 @@ function TeamCard({ matchId: string; isWinner?: boolean; }) { - const borderColor = - team.side === 'blue' ? 'border-blue-500/25' : 'border-red-500/25'; - const headerBg = team.side === 'blue' ? 'bg-blue-500/8' : 'bg-red-500/8'; - const sideColor = team.side === 'blue' ? 'text-blue-400' : 'text-red-400'; - const accentBar = team.side === 'blue' ? 'bg-blue-500' : 'bg-red-500'; + const tone = teamIndexColorClasses(team.teamIndex); return ( -
-
+
+
- + {team.name} {isWinner && ( @@ -290,7 +283,7 @@ function TeamCard({ )}
진행 페이지 @@ -414,9 +407,9 @@ function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) {
{slot.gameNumber}경기 - {(slot.blueGroupIndex > 1 || slot.redGroupIndex > 1) && ( + {(slot.teamAIndex > 1 || slot.teamBIndex > 2) && ( - {slot.blueGroupIndex}조 + {teamIndexLabel(slot.teamAIndex)} vs {teamIndexLabel(slot.teamBIndex)} )} @@ -461,14 +454,19 @@ function formatGameDuration(seconds: number) { return `${minutes}:${String(rest).padStart(2, '0')}`; } -function resultSideLabel(side: 'blue' | 'red', groupIndex = 1) { - return teamLabel(side, groupIndex); -} - function resultSideClass(side: 'blue' | 'red') { return side === 'blue' ? 'text-blue-400' : 'text-red-400'; } +function resultSideLabel(side: TeamSide) { + return sideShortLabel(side); +} + +function resolveMatchTeamName(match: MatchDetailView, teamIndex: number) { + const team = match.teams.find((item) => item.teamIndex === teamIndex); + return teamIndexLabel(teamIndex, team?.name); +} + function MatchResultPanel({ match }: { match: MatchDetailView }) { if (!match.result) return null; @@ -485,34 +483,37 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) { (_, index) => index + 1, ); const seriesResults = match.result.seriesResults ?? []; + const primarySeries = seriesResults[0]; return (
-
-
-
- {match.result.blueScore} + {primarySeries && ( +
+
+
+ {primarySeries.teamAWins} +
+
+ {resolveMatchTeamName(match, primarySeries.teamAIndex)} +
-
- 블루팀 +
+ VS +
+
+
+ {primarySeries.teamBWins} +
+
+ {resolveMatchTeamName(match, primarySeries.teamBIndex)} +
-
- VS -
-
-
- {match.result.redScore} -
-
- 레드팀 -
-
-
+ )}
{match.result.winner ? `${match.result.winner} 승리` @@ -522,16 +523,21 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) {
{seriesResults.map((series) => (
- {series.blueGroupIndex}조 + {resolveMatchTeamName(match, series.teamAIndex)} vs{' '} + {resolveMatchTeamName(match, series.teamBIndex)}
- 블루 {series.blueScore} + + {series.teamAWins} + : - 레드 {series.redScore} + + {series.teamBWins} +
))} @@ -540,10 +546,6 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) {
{gameNumbers.map((gameNumber) => { const game = gamesByNumber.get(gameNumber); - const winnerGroupIndex = - game?.winnerSide === 'blue' - ? game.blueGroupIndex - : game?.redGroupIndex; return (
- {resultSideLabel(game.winnerSide, winnerGroupIndex)} 승 + {resolveMatchTeamName(match, game.winnerTeamIndex)} 승 + + + ({resultSideLabel(game.winnerSide)} 진영) {game.riotMatchId} @@ -625,8 +630,7 @@ export default function MatchDetailPage() { body: JSON.stringify({ captains: buildCaptainSlots(matchQuery.data?.participants ?? []).map( (slot) => ({ - side: slot.side, - groupIndex: slot.groupIndex, + teamIndex: slot.teamIndex, userId: captainSelections[captainSlotKey(slot)], }), ), @@ -851,7 +855,7 @@ export default function MatchDetailPage() { 경매 시작

- 참가 신청 순서 기준 10명당 1개 조가 만들어지고, 각 조에 블루/레드 팀장을 지정합니다. + 참가 신청 순서 기준 5명당 1개 팀이 만들어지고, 각 팀의 팀장을 지정합니다.

{waitingParticipantCount > 0 && (

@@ -876,7 +880,7 @@ export default function MatchDetailPage() { key={key} className="text-xs text-base-content/45" > - {teamLabel(slot.side, slot.groupIndex)} 팀장 + {teamIndexLabel(slot.teamIndex)} 팀장