From 2379051196a53fb120039be6cc4f66fd60729eae Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sat, 2 May 2026 02:59:33 -0700 Subject: [PATCH] . --- .gitignore | 4 +- Dockerfile | 3 +- apps/api/docker-entrypoint.js | 72 --- apps/api/package.json | 12 +- .../src/modules/auction/auction.controller.ts | 2 + .../src/modules/auction/auction.gateway.ts | 2 + .../src/modules/auction/auction.service.ts | 148 ++++-- .../src/modules/auction/dto/auction.dto.ts | 12 +- .../api/src/modules/global/database/schema.ts | 64 ++- .../modules/global/secret/secret.service.ts | 213 ++++++--- .../legacy-import/legacy-import.service.ts | 19 + .../legacy-import/match-builder.util.ts | 3 + .../src/modules/match/dto/create-match.dto.ts | 50 +- .../api/src/modules/match/match.controller.ts | 1 + apps/api/src/modules/match/match.service.ts | 29 ++ .../tournament-code.service.ts | 32 +- .../tournament-code/tournament-code.types.ts | 2 + .../tournament-result/team-mapping.util.ts | 30 +- .../tournament-result.service.ts | 65 ++- apps/api/src/seed-dakao-participant.ts | 2 +- apps/api/src/seed.ts | 2 +- apps/api/start.ps1 | 68 --- apps/web/src/App.tsx | 10 + apps/web/src/api/hooks.ts | 21 + apps/web/src/api/mappers.ts | 55 ++- apps/web/src/api/types.ts | 31 ++ apps/web/src/api/useAuctionSocket.ts | 1 + apps/web/src/pages/AuctionPage.tsx | 134 ++++-- apps/web/src/pages/HomePage.tsx | 30 +- apps/web/src/pages/MatchDetailPage.tsx | 270 ++++++++--- apps/web/src/pages/MatchTeamProgressPage.tsx | 245 ++++++++++ apps/web/src/pages/admin/MatchAdminPage.tsx | 433 ++++++++++++++++++ 32 files changed, 1682 insertions(+), 383 deletions(-) delete mode 100644 apps/api/docker-entrypoint.js delete mode 100644 apps/api/start.ps1 create mode 100644 apps/web/src/pages/MatchTeamProgressPage.tsx create mode 100644 apps/web/src/pages/admin/MatchAdminPage.tsx diff --git a/.gitignore b/.gitignore index 692837a7..cd075144 100644 --- a/.gitignore +++ b/.gitignore @@ -21,4 +21,6 @@ website/LICENSE !.claude/settings.json -*.temp.MD \ No newline at end of file +*.temp.MD + +*.md \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index cb7fab03..a9e4d021 100644 --- a/Dockerfile +++ b/Dockerfile @@ -43,8 +43,7 @@ COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/package.json ./apps/ COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/node_modules ./apps/api/node_modules COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist COPY --chown=nonroot:nonroot apps/project.env ./project.env -COPY --chown=nonroot:nonroot apps/api/docker-entrypoint.js ./apps/api/docker-entrypoint.js EXPOSE 10712 -CMD ["apps/api/docker-entrypoint.js"] +CMD ["apps/api/dist/main.js"] diff --git a/apps/api/docker-entrypoint.js b/apps/api/docker-entrypoint.js deleted file mode 100644 index 267e7b42..00000000 --- a/apps/api/docker-entrypoint.js +++ /dev/null @@ -1,72 +0,0 @@ -'use strict'; - -const fs = require('node:fs'); -const path = require('node:path'); - -const MACHINE_ENV_PATHS = [ - process.env.MachineEnvFile, - process.env.MACHINE_ENV_FILE, - '/source/global-env-vars.txt', - process.env.HOME - ? path.join(process.env.HOME, 'source/global-env-vars.txt') - : '', -].filter(Boolean); - -const PROJECT_ENV_PATHS = [ - 'project.env', - '/app/project.env', - 'apps/project.env', -]; - -function stripQuotes(value) { - const trimmed = value.trim(); - if ( - (trimmed.startsWith('"') && trimmed.endsWith('"')) || - (trimmed.startsWith("'") && trimmed.endsWith("'")) - ) { - return trimmed.slice(1, -1); - } - return trimmed; -} - -function loadEnvFile(filePath, options = {}) { - const { override = false } = options; - const content = fs.readFileSync(filePath, 'utf8'); - for (const line of content.split(/\r?\n/u)) { - if (!line.trim() || /^\s*#/u.test(line)) continue; - - const match = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/u); - if (!match) continue; - - if (!override && process.env[match[1]] !== undefined) continue; - process.env[match[1]] = stripQuotes(match[2]); - } -} - -const machineEnvFile = MACHINE_ENV_PATHS.find((candidate) => - fs.existsSync(candidate), -); -if (machineEnvFile) { - loadEnvFile(machineEnvFile, { override: true }); -} - -for (const projectEnvFile of PROJECT_ENV_PATHS) { - if (fs.existsSync(projectEnvFile)) { - loadEnvFile(projectEnvFile); - } -} - -const missing = [ - 'INFISICAL_CLIENT_ID', - 'INFISICAL_CLIENT_SECRET', - 'INFISICAL_PROJECT_ID', -].filter((key) => !process.env[key]); - -if (missing.length > 0) { - console.error( - `Missing required environment variables: ${missing.join(', ')}`, - ); - process.exit(1); -} - -require('./dist/main.js'); diff --git a/apps/api/package.json b/apps/api/package.json index a45ff898..3d24a047 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -10,12 +10,12 @@ "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", "seed:dev": "ts-node src/seed.ts", "seed:dakao-participant": "ts-node src/seed-dakao-participant.ts", - "start:dev": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'dev'); \"./start.ps1\"\"", - "start:test": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'test'); \"./start.ps1\"\"", - "start:prod": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'prod'); \"./start.ps1\"\"", - "pm2:dev": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'dev'); ./start.ps1 -UsePm2\"", - "pm2:test": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'test'); ./start.ps1 -UsePm2\"", - "pm2:prod": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'prod'); ./start.ps1 -UsePm2\"", + "start:dev": "node -e \"process.env.NODE_ENV='dev'; require('./dist/main.js')\"", + "start:test": "node -e \"process.env.NODE_ENV='test'; require('./dist/main.js')\"", + "start:prod": "node -e \"process.env.NODE_ENV='prod'; require('./dist/main.js')\"", + "pm2:dev": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:dev", + "pm2:test": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:test", + "pm2:prod": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:prod", "start:debug": "nest start --debug --watch", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "test": "jest", diff --git a/apps/api/src/modules/auction/auction.controller.ts b/apps/api/src/modules/auction/auction.controller.ts index 49efe3ee..eb2a32b9 100644 --- a/apps/api/src/modules/auction/auction.controller.ts +++ b/apps/api/src/modules/auction/auction.controller.ts @@ -40,6 +40,7 @@ export class AuctionController { communityId, captains: body.captains.map((c) => ({ side: c.side, + groupIndex: c.groupIndex ?? 1, userId: new mongoose.Types.ObjectId(c.userId), })), initialPoints: body.initialPoints ?? 1000, @@ -76,6 +77,7 @@ export class AuctionController { return this.auctionService.placeBid({ matchId, side: body.side, + groupIndex: body.groupIndex ?? 1, 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 c0c94a26..8ba0bd1f 100644 --- a/apps/api/src/modules/auction/auction.gateway.ts +++ b/apps/api/src/modules/auction/auction.gateway.ts @@ -30,6 +30,7 @@ interface JoinAuctionPayload { interface BidPayload { side: TeamSide; + groupIndex?: number; amount: number; bidderUserId?: string; } @@ -125,6 +126,7 @@ export class AuctionGateway const auction = await this.auctionService.placeBid({ matchId: new mongoose.Types.ObjectId(matchId), side: payload.side, + groupIndex: payload.groupIndex ?? 1, amount: payload.amount, bidderUserId, }); diff --git a/apps/api/src/modules/auction/auction.service.ts b/apps/api/src/modules/auction/auction.service.ts index b940e7b9..0a163521 100644 --- a/apps/api/src/modules/auction/auction.service.ts +++ b/apps/api/src/modules/auction/auction.service.ts @@ -10,6 +10,7 @@ import { AuctionDocument, AuctionPlayerSnapshot, AuctionTeam, + MatchParticipant, MatchTeamMember, Position, TeamSide, @@ -23,7 +24,11 @@ const AUCTION_MAX_TEAM_SIZE = 5; interface StartAuctionParams { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; - captains: { side: TeamSide; userId: mongoose.Types.ObjectId }[]; + captains: { + side: TeamSide; + groupIndex: number; + userId: mongoose.Types.ObjectId; + }[]; initialPoints: number; maxTimerSeconds: number; } @@ -31,6 +36,7 @@ interface StartAuctionParams { interface PlaceBidParams { matchId: mongoose.Types.ObjectId; side: TeamSide; + groupIndex: number; amount: number; bidderUserId?: mongoose.Types.ObjectId; } @@ -66,30 +72,24 @@ export class AuctionService { throw new BadRequestException('Auction already exists for this match.'); } + const activeParticipants = this.applyAuctionCut(match); + const desiredAuctionCount = activeParticipants.length; + if (desiredAuctionCount < 10) { + 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); const captainUserIds = params.captains.map((c) => c.userId); - if (captainUserIds[0].equals(captainUserIds[1])) { - throw new BadRequestException('Captains must be different users.'); - } - const captainParticipants = match.participants.filter((p) => - captainUserIds.some((cid) => cid.equals(p.userId)), - ); - if (captainParticipants.length !== 2) { - throw new BadRequestException( - 'Both captains must be participants of the match.', - ); - } - if ( - match.participants.length > - params.captains.length * AUCTION_MAX_TEAM_SIZE - ) { - throw new BadRequestException( - 'Auction supports up to 5 members per team including captains.', - ); - } const basePlayerUsers = await UserModel.find({ _id: { - $in: match.participants + $in: activeParticipants .filter((p) => !captainUserIds.some((cid) => cid.equals(p.userId))) .map((p) => p.userId), }, @@ -130,7 +130,7 @@ export class AuctionService { const nonCaptainPuuids = new Set(); const order: AuctionPlayerSnapshot[] = []; - for (const participant of match.participants) { + for (const participant of activeParticipants) { if (captainUserIds.some((cid) => cid.equals(participant.userId))) { continue; } @@ -163,6 +163,7 @@ export class AuctionService { phase: 'presenting', teams: params.captains.map((c) => ({ side: c.side, + groupIndex: c.groupIndex, captainUserId: c.userId, points: params.initialPoints, members: [], @@ -204,6 +205,7 @@ export class AuctionService { auction.phase = 'bidding'; auction.currentBid = 0; auction.currentBidder = undefined; + auction.currentBidderGroupIndex = undefined; auction.currentDeadline = this.createDeadline(auction.maxTimerSeconds); await auction.save(); return auction; @@ -214,8 +216,8 @@ export class AuctionService { if (auction.phase !== 'bidding') { throw new BadRequestException('Auction is not in bidding phase.'); } - const team = auction.teams.find((t) => t.side === params.side); - if (!team) throw new BadRequestException('Unknown team side.'); + const team = this.findAuctionTeam(auction, params.side, params.groupIndex); + if (!team) throw new BadRequestException('Unknown team.'); if (params.amount <= auction.currentBid) { throw new BadRequestException('Bid must exceed current bid.'); } @@ -227,11 +229,13 @@ export class AuctionService { auction.currentBid = params.amount; auction.currentBidder = params.side; + auction.currentBidderGroupIndex = params.groupIndex; auction.currentDeadline = this.createDeadline( this.resolveBidExtensionSeconds(auction), ); auction.bids.push({ side: params.side, + groupIndex: params.groupIndex, amount: params.amount, bidderUserId: team.captainUserId, timestamp: new Date(), @@ -248,7 +252,11 @@ export class AuctionService { if (!auction.currentBidder || auction.currentBid <= 0) { throw new BadRequestException('No bid to mark sold.'); } - const team = auction.teams.find((t) => t.side === auction.currentBidder); + const team = this.findAuctionTeam( + auction, + auction.currentBidder, + auction.currentBidderGroupIndex ?? 1, + ); if (!team) throw new BadRequestException('Winning team not found.'); this.assertTeamHasSlot(team); @@ -284,6 +292,7 @@ export class AuctionService { auction.phase = 'presenting'; auction.currentBid = 0; auction.currentBidder = undefined; + auction.currentBidderGroupIndex = undefined; } auction.currentDeadline = undefined; await auction.save(); @@ -323,6 +332,9 @@ export class AuctionService { match.status = 'recruiting'; match.teams = []; match.tournamentCodeIds = []; + match.participants.forEach((participant) => { + participant.excluded = false; + }); match.teamBuiltAt = undefined; match.result = undefined; match.resultPollState = undefined; @@ -337,6 +349,79 @@ export class AuctionService { } } + private applyAuctionCut(match: { + participants: MatchParticipant[]; + }): MatchParticipant[] { + const ordered = [...match.participants].sort( + (left, right) => left.joinedAt.getTime() - right.joinedAt.getTime(), + ); + const desiredAuctionCount = Math.floor(ordered.length / 10) * 10; + const activeIds = new Set( + ordered + .slice(0, desiredAuctionCount) + .map((participant) => participant.userId.toString()), + ); + match.participants.forEach((participant) => { + participant.excluded = !activeIds.has(participant.userId.toString()); + }); + return ordered.slice(0, desiredAuctionCount); + } + + private assertCaptainAssignments( + captains: StartAuctionParams['captains'], + activeParticipants: Array<{ userId: mongoose.Types.ObjectId }>, + groupCount: 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}`); + } + + for (const captain of captains) { + const userId = captain.userId.toString(); + if (!activeUserIds.has(userId)) { + throw new BadRequestException( + 'All captains must be active participants of the match.', + ); + } + if (captainUserIds.has(userId)) { + throw new BadRequestException('Captains must be different users.'); + } + captainUserIds.add(userId); + + if (captain.groupIndex < 1 || captain.groupIndex > groupCount) { + throw new BadRequestException('Captain groupIndex is out of range.'); + } + const key = `${captain.side}:${captain.groupIndex}`; + if (teamKeys.has(key)) { + throw new BadRequestException('Duplicate captain team assignment.'); + } + teamKeys.add(key); + } + + for (const key of requiredKeys) { + if (!teamKeys.has(key)) { + throw new BadRequestException('Each group needs one blue and one red captain.'); + } + } + } + + private findAuctionTeam( + auction: AuctionDocument, + side: TeamSide, + groupIndex: number, + ): AuctionTeam | undefined { + return auction.teams.find( + (team) => team.side === side && (team.groupIndex ?? 1) === groupIndex, + ); + } + private createDeadline(secondsFromNow: number): Date { return new Date(Date.now() + secondsFromNow * 1000); } @@ -399,7 +484,8 @@ export class AuctionService { return { side: team.side, - name: this.resolveTeamName(team.side), + groupIndex: team.groupIndex ?? 1, + name: this.resolveTeamName(team.side, team.groupIndex ?? 1, auction.teams), captainUserId: team.captainUserId, members, }; @@ -411,8 +497,14 @@ export class AuctionService { await this.tournamentResultService.scheduleInitialPoll(match); } - private resolveTeamName(side: TeamSide): string { - return side === 'blue' ? '블루팀' : '레드팀'; + 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}`; } } diff --git a/apps/api/src/modules/auction/dto/auction.dto.ts b/apps/api/src/modules/auction/dto/auction.dto.ts index 9fee333d..d84c6929 100644 --- a/apps/api/src/modules/auction/dto/auction.dto.ts +++ b/apps/api/src/modules/auction/dto/auction.dto.ts @@ -17,6 +17,11 @@ class CaptainAssignmentDto { @IsEnum(TEAM_SIDES) side!: TeamSide; + @IsOptional() + @IsInt() + @Min(1) + groupIndex?: number; + @IsMongoId() userId!: string; } @@ -24,7 +29,7 @@ class CaptainAssignmentDto { export class StartAuctionDto { @IsArray() @ArrayMinSize(2) - @ArrayMaxSize(2) + @ArrayMaxSize(16) @ValidateNested({ each: true }) @Type(() => CaptainAssignmentDto) captains!: CaptainAssignmentDto[]; @@ -44,6 +49,11 @@ export class PlaceBidDto { @IsEnum(TEAM_SIDES) side!: TeamSide; + @IsOptional() + @IsInt() + @Min(1) + groupIndex?: number; + @IsInt() @Min(1) amount!: number; diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index bf7ef38b..0625c7f9 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -32,6 +32,13 @@ export const MATCH_STATUSES: MatchStatus[] = [ export type TeamSide = 'blue' | 'red'; export const TEAM_SIDES: TeamSide[] = ['blue', 'red']; +export type MatchGameMode = 'pair' | 'bracket' | 'round-robin'; +export const MATCH_GAME_MODES: MatchGameMode[] = [ + 'pair', + 'bracket', + 'round-robin', +]; + export type CommunityRole = 'owner' | 'admin' | 'member'; export const COMMUNITY_ROLES: CommunityRole[] = ['owner', 'admin', 'member']; @@ -323,6 +330,7 @@ export interface MatchParticipant { tier?: TierInfo; preferredPositions: PositionPreference[]; joinedAt: Date; + excluded?: boolean; } export interface MatchTeamMember { @@ -333,6 +341,7 @@ export interface MatchTeamMember { export interface MatchTeam { side: TeamSide; + groupIndex: number; name: string; captainUserId?: mongoose.Types.ObjectId; members: MatchTeamMember[]; @@ -352,11 +361,21 @@ export interface MatchGameResult { gameNumber: number; riotMatchId: string; 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; +} + export interface MatchResult { winnerSide?: TeamSide; blueScore: number; @@ -364,6 +383,7 @@ export interface MatchResult { mvpUserId?: mongoose.Types.ObjectId; riotMatchIds: string[]; // 내전에서 플레이된 Riot matchId들 games: MatchGameResult[]; + seriesResults?: MatchSeriesResult[]; } export interface MatchResultPollState { @@ -389,6 +409,7 @@ export interface Match extends MongooseTimestamps { scheduledAt: Date; maxParticipants: number; gameCount: number; + gameMode: MatchGameMode; tournamentCodeIds: mongoose.Types.ObjectId[]; teamBuiltAt?: Date; hostUserId?: mongoose.Types.ObjectId; @@ -469,6 +490,7 @@ export interface AuctionTeamMember { export interface AuctionTeam { side: TeamSide; + groupIndex: number; captainUserId: mongoose.Types.ObjectId; points: number; members: AuctionTeamMember[]; @@ -476,6 +498,7 @@ export interface AuctionTeam { export interface AuctionBid { side: TeamSide; + groupIndex?: number; amount: number; bidderUserId: mongoose.Types.ObjectId; timestamp: Date; @@ -490,6 +513,7 @@ export interface Auction extends MongooseTimestamps { bids: AuctionBid[]; currentBid: number; currentBidder?: TeamSide; + currentBidderGroupIndex?: number; maxTimerSeconds: number; currentDeadline?: Date; initialPoints: number; @@ -880,6 +904,7 @@ const MatchParticipantSubSchema = new Schema( default: [], }, joinedAt: { type: Date, required: true, default: Date.now }, + excluded: { type: Boolean, required: true, default: false }, }, { _id: false }, ); @@ -896,6 +921,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 }, name: { type: String, required: true }, captainUserId: { type: Schema.Types.ObjectId, ref: 'user' }, members: { type: [MatchTeamMemberSubSchema], required: true, default: [] }, @@ -922,6 +948,8 @@ const MatchGameResultSubSchema = new Schema( gameNumber: { type: Number, required: true }, riotMatchId: { type: String, required: true }, 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: { @@ -933,6 +961,17 @@ const MatchGameResultSubSchema = new Schema( { _id: false }, ); +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 }, + }, + { _id: false }, +); + const MatchResultSubSchema = new Schema( { winnerSide: { type: String, enum: TEAM_SIDES, required: false }, @@ -941,6 +980,11 @@ const MatchResultSubSchema = new Schema( mvpUserId: { type: Schema.Types.ObjectId, ref: 'user' }, riotMatchIds: { type: [String], required: true, default: [] }, games: { type: [MatchGameResultSubSchema], required: true, default: [] }, + seriesResults: { + type: [MatchSeriesResultSubSchema], + required: true, + default: [], + }, }, { _id: false }, ); @@ -1001,8 +1045,23 @@ export const MatchSchema = new Schema( default: 'recruiting', }, scheduledAt: { type: Date, required: true }, - maxParticipants: { type: Number, required: true, default: 10 }, + maxParticipants: { + type: Number, + required: true, + default: 10, + min: 10, + validate: { + validator: (value: number) => Number.isInteger(value) && value % 10 === 0, + message: 'maxParticipants must be a multiple of 10.', + }, + }, gameCount: { type: Number, required: true, default: 3 }, + gameMode: { + type: String, + enum: MATCH_GAME_MODES, + required: true, + default: 'pair', + }, tournamentCodeIds: { type: [{ type: Schema.Types.ObjectId, ref: 'tournamentCode' }], required: true, @@ -1156,6 +1215,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 }, captainUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, points: { type: Number, required: true, default: 0 }, members: { @@ -1170,6 +1230,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 }, amount: { type: Number, required: true }, bidderUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, timestamp: { type: Date, required: true, default: Date.now }, @@ -1201,6 +1262,7 @@ export const AuctionSchema = new Schema( 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 }, 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/global/secret/secret.service.ts b/apps/api/src/modules/global/secret/secret.service.ts index bfa6c3c7..a6c28034 100644 --- a/apps/api/src/modules/global/secret/secret.service.ts +++ b/apps/api/src/modules/global/secret/secret.service.ts @@ -2,7 +2,22 @@ import { Injectable, Logger } from '@nestjs/common'; import { InfisicalSDK } from '@infisical/sdk'; import { ConfigService } from '@nestjs/config'; -type SecretMap = Record; +type SecretMap = Record; + +const DEFAULT_INFISICAL_SITE_URL = 'https://secret-manager.dahyeon.us/'; +const IMDS_TOKEN_TTL_SECONDS = 60; +const IMDS_REQUEST_TIMEOUT_MS = 1500; +const FALLBACK_IMDS_BASE_URLS = [ + 'http://169.254.169.254', + 'http://host.docker.internal:8675', +]; + +interface InfisicalBootstrapConfig { + siteUrl: string; + clientId: string; + clientSecret: string; + projectId: string; +} @Injectable() export class SecretService { @@ -10,57 +25,8 @@ export class SecretService { private secrets: SecretMap | null = null; // null = 아직 로드 전 private loading?: Promise; // 진행 중인 로드(중복 호출 방지) - private infisicalClient: InfisicalSDK; - private readonly siteUrl: string; - private readonly clientSecret: string; - private readonly clientId: string; - private readonly projectId: string; - - private readonly PROCESS_ENVS = [ - 'COSMOSDB_ENDPOINT', - 'COSMOSDB_KEY', - 'NATS_ENDPOINT', - 'NATS_TOKEN', - 'NATS_URL', - 'DAKAO_INBOUND_SUBJECT', - 'DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT', - 'DAKAO_REPLY_SUBJECT_PREFIX', - 'DAKAO_COMMAND_SOURCE', - 'DAKAO_BOT_USER_ID', - 'DAKAO_INSTANCE_ID', - 'JWT_CLAIM_AUDIENCE', - 'MICROSOFT_ENTRAID_TENANT_ID', - 'MICROSOFT_ENTRAID_ALLOWED_ALGS', - 'AUTH_DEV_HEADER_ENABLED', - // 필요시 추가 - ] as const; - - constructor(private readonly config: ConfigService) { - this.siteUrl = - this.config.get('INFISICAL_SITE_URL') ?? - 'https://secret-manager.dahyeon.us/'; - this.clientSecret = this.config.get( - 'INFISICAL_CLIENT_SECRET', - ) as string; - this.clientId = this.config.get('INFISICAL_CLIENT_ID') as string; - this.projectId = this.config.get('INFISICAL_PROJECT_ID') as string; - // console.log(this.siteUrl, this.clientSecret, this.clientId, this.projectId) - - const missing = [ - !this.siteUrl && 'INFISICAL_SITE_URL', - !this.clientId && 'INFISICAL_CLIENT_ID', - !this.clientSecret && 'INFISICAL_CLIENT_SECRET', - !this.projectId && 'INFISICAL_PROJECT_ID', - ].filter(Boolean); - if (missing.length > 0) { - throw new Error( - `Missing required Infisical configuration: ${missing.join(', ')}`, - ); - } - - this.infisicalClient = new InfisicalSDK({ siteUrl: this.siteUrl }); - } + constructor(private readonly config: ConfigService) {} /** 한 번만 로그인/페치. 동시에 여러 번 호출돼도 같은 Promise를 공유 */ private async fetchSecrets(): Promise { @@ -68,20 +34,24 @@ export class SecretService { if (this.loading) return this.loading; // 로드 중이면 그거 기다리기 this.loading = (async () => { - await this.infisicalClient.auth().universalAuth.login({ - clientId: this.clientId, - clientSecret: this.clientSecret, + const bootstrapConfig = await this.resolveInfisicalBootstrapConfig(); + const infisicalClient = new InfisicalSDK({ + siteUrl: bootstrapConfig.siteUrl, }); - // console.log(this.infisicalClient) - const res = await this.infisicalClient.secrets().listSecrets({ + await infisicalClient.auth().universalAuth.login({ + clientId: bootstrapConfig.clientId, + clientSecret: bootstrapConfig.clientSecret, + }); + + const res = await infisicalClient.secrets().listSecrets({ environment: process.env.NODE_ENV === 'prod' ? 'prod' : process.env.NODE_ENV === 'test' ? 'staging' : 'dev', - projectId: this.projectId, + projectId: bootstrapConfig.projectId, }); // 임시 객체에 채운 뒤 한 번에 교체(일관성 보장) @@ -90,11 +60,10 @@ export class SecretService { map[s.secretKey] = s.secretValue; } - // 필요한 값은 process.env에 반영 - for (const k of this.PROCESS_ENVS) { - const v = map[k as string]; + // 앱 생명주기에서 필요한 env는 모두 SecretService가 process.env에 반영한다. + for (const [k, v] of Object.entries(map)) { if (typeof v === 'string' && v.length > 0) { - process.env[k as string] = v; + process.env[k] = v; } } @@ -111,6 +80,128 @@ export class SecretService { } } + private async resolveInfisicalBootstrapConfig(): Promise { + const [clientId, clientSecret, projectId] = await Promise.all([ + this.resolveBootstrapValue('INFISICAL_CLIENT_ID'), + this.resolveBootstrapValue('INFISICAL_CLIENT_SECRET'), + this.resolveBootstrapValue('INFISICAL_PROJECT_ID'), + ]); + const siteUrl = + (await this.resolveBootstrapValue('INFISICAL_SITE_URL', false)) ?? + DEFAULT_INFISICAL_SITE_URL; + + const missing = [ + !siteUrl && 'INFISICAL_SITE_URL', + !clientId && 'INFISICAL_CLIENT_ID', + !clientSecret && 'INFISICAL_CLIENT_SECRET', + !projectId && 'INFISICAL_PROJECT_ID', + ].filter(Boolean); + if (missing.length > 0) { + throw new Error( + `Missing required Infisical bootstrap configuration: ${missing.join(', ')}`, + ); + } + if (!clientId || !clientSecret || !projectId) { + throw new Error('Missing required Infisical bootstrap configuration.'); + } + + return { + siteUrl, + clientId, + clientSecret, + projectId, + }; + } + + private async resolveBootstrapValue( + key: string, + required = true, + ): Promise { + const configured = this.config.get(key)?.trim(); + if (configured) return configured; + + const fromImds = await this.getImdsSecret(key); + if (fromImds) { + process.env[key] = fromImds; + return fromImds; + } + + if (required) { + throw new Error(`Missing required bootstrap secret: ${key}`); + } + return undefined; + } + + private async getImdsSecret(key: string): Promise { + let lastError: Error | undefined; + for (const baseUrl of this.resolveImdsBaseUrls()) { + try { + const token = await this.issueImdsToken(baseUrl); + const secret = await this.fetchImdsText( + `${baseUrl.replace(/\/$/u, '')}/latest/meta-data/secrets/${encodeURIComponent(key)}`, + { + 'X-aws-ec2-metadata-token': token, + }, + ); + return secret.trim() || undefined; + } catch (error) { + lastError = error instanceof Error ? error : new Error(String(error)); + } + } + + if (lastError) { + this.logger.debug( + `IMDS secret lookup failed for ${key}: ${lastError.message}`, + ); + } + return undefined; + } + + private resolveImdsBaseUrls(): string[] { + return [ + this.config.get('IMDS_BASE_URL'), + this.config.get('MACHINE_METADATA_BASE_URL'), + ...FALLBACK_IMDS_BASE_URLS, + ] + .map((value) => value?.trim()) + .filter((value): value is string => Boolean(value)); + } + + private async issueImdsToken(baseUrl: string): Promise { + return this.fetchImdsText( + `${baseUrl.replace(/\/$/u, '')}/latest/api/token`, + { + 'X-aws-ec2-metadata-token-ttl-seconds': String(IMDS_TOKEN_TTL_SECONDS), + }, + 'PUT', + ); + } + + private async fetchImdsText( + url: string, + headers: Record, + method = 'GET', + ): Promise { + const controller = new AbortController(); + const timeout = setTimeout( + () => controller.abort(), + IMDS_REQUEST_TIMEOUT_MS, + ); + try { + const response = await fetch(url, { + method, + headers, + signal: controller.signal, + }); + if (!response.ok) { + throw new Error(`IMDS ${method} ${url} failed with ${response.status}`); + } + return response.text(); + } finally { + clearTimeout(timeout); + } + } + /** lazy get: 필요할 때 처음 한번만 로드 */ public async get(key: string, fallback?: T): Promise { if (!this.secrets) { 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 a56c3210..a773f00d 100644 --- a/apps/api/src/modules/legacy-import/legacy-import.service.ts +++ b/apps/api/src/modules/legacy-import/legacy-import.service.ts @@ -412,6 +412,15 @@ export class LegacyImportService { redScore: winnerSide === 'red' ? 1 : 0, riotMatchIds: [riotMatchId], games: [gameResult], + seriesResults: [ + { + blueGroupIndex: 1, + redGroupIndex: 1, + blueScore: winnerSide === 'blue' ? 1 : 0, + redScore: winnerSide === 'red' ? 1 : 0, + winnerSide, + }, + ], }; await MatchModel.updateOne( @@ -490,6 +499,7 @@ export class LegacyImportService { scheduledAt: new Date(detail.info.gameCreation), maxParticipants: 10, gameCount: 1, + gameMode: 'pair', tournamentCodeIds: [], teamBuiltAt: new Date(detail.info.gameCreation), hostUserId: new mongoose.Types.ObjectId(job.triggeredBy), @@ -501,6 +511,15 @@ export class LegacyImportService { redScore: winnerSide === 'red' ? 1 : 0, riotMatchIds: [riotMatchId], games: [gameResult], + seriesResults: [ + { + blueGroupIndex: 1, + redGroupIndex: 1, + blueScore: winnerSide === 'blue' ? 1 : 0, + redScore: winnerSide === 'red' ? 1 : 0, + winnerSide, + }, + ], }, legacyImported: true, legacyImportSource: { 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 e60d67d6..def1f901 100644 --- a/apps/api/src/modules/legacy-import/match-builder.util.ts +++ b/apps/api/src/modules/legacy-import/match-builder.util.ts @@ -108,6 +108,7 @@ export function buildTeams( .filter((member): member is NonNullable => Boolean(member)); return { side, + groupIndex: 1, name: side === 'blue' ? '블루팀' : '레드팀', members, }; @@ -147,6 +148,8 @@ export function buildGameResult( gameNumber, riotMatchId: detail.metadata.matchId, winnerSide, + blueGroupIndex: 1, + redGroupIndex: 1, gameCreation: detail.info.gameCreation, gameDuration: detail.info.gameDuration, participants, diff --git a/apps/api/src/modules/match/dto/create-match.dto.ts b/apps/api/src/modules/match/dto/create-match.dto.ts index 63989d96..a2757c73 100644 --- a/apps/api/src/modules/match/dto/create-match.dto.ts +++ b/apps/api/src/modules/match/dto/create-match.dto.ts @@ -2,6 +2,7 @@ import { Type } from 'class-transformer'; import { ArrayMaxSize, ArrayMinSize, + registerDecorator, IsArray, IsDate, IsEnum, @@ -12,9 +13,40 @@ import { Min, MinLength, ValidateNested, + ValidationArguments, + ValidationOptions, } from 'class-validator'; -import { POSITIONS } from '../../global/database/schema'; -import type { Position } from '../../global/database/schema'; +import { MATCH_GAME_MODES, POSITIONS } from '../../global/database/schema'; +import type { MatchGameMode, Position } from '../../global/database/schema'; + +function IsMultipleOf( + multiple: number, + validationOptions?: ValidationOptions, +): PropertyDecorator { + return (object, propertyName) => { + registerDecorator({ + name: 'isMultipleOf', + target: object.constructor, + propertyName: String(propertyName), + constraints: [multiple], + options: validationOptions, + validator: { + validate(value: unknown, args: ValidationArguments) { + const [divisor] = args.constraints as [number]; + return ( + typeof value === 'number' && + Number.isInteger(value) && + value % divisor === 0 + ); + }, + defaultMessage(args: ValidationArguments) { + const [divisor] = args.constraints as [number]; + return `${args.property} must be a multiple of ${divisor}.`; + }, + }, + }); + }; +} export class PositionPreferenceDto { @IsEnum(POSITIONS) @@ -56,7 +88,8 @@ export class CreateMatchDto { @IsOptional() @IsInt() - @Min(2) + @Min(10) + @IsMultipleOf(10) maxParticipants?: number; @IsOptional() @@ -64,6 +97,10 @@ export class CreateMatchDto { @Min(1) gameCount?: number; + @IsOptional() + @IsEnum(MATCH_GAME_MODES) + gameMode?: MatchGameMode; + @IsOptional() @IsArray() @IsString({ each: true }) @@ -106,7 +143,8 @@ export class UpdateMatchDto { @IsOptional() @IsInt() - @Min(2) + @Min(10) + @IsMultipleOf(10) maxParticipants?: number; @IsOptional() @@ -114,6 +152,10 @@ export class UpdateMatchDto { @Min(1) gameCount?: number; + @IsOptional() + @IsEnum(MATCH_GAME_MODES) + gameMode?: MatchGameMode; + @IsOptional() @IsArray() @IsString({ each: true }) diff --git a/apps/api/src/modules/match/match.controller.ts b/apps/api/src/modules/match/match.controller.ts index d3c71af0..c581dbdc 100644 --- a/apps/api/src/modules/match/match.controller.ts +++ b/apps/api/src/modules/match/match.controller.ts @@ -54,6 +54,7 @@ export class MatchController { scheduledAt: body.scheduledAt, maxParticipants: body.maxParticipants ?? 10, gameCount: body.gameCount, + gameMode: body.gameMode ?? 'pair', prizes: body.prizes ?? [], notices: body.notices ?? [], schedule: body.schedule ?? [], diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts index 6bdce5cf..4fd29633 100644 --- a/apps/api/src/modules/match/match.service.ts +++ b/apps/api/src/modules/match/match.service.ts @@ -98,10 +98,30 @@ export class MatchService { obj.result.games = [...obj.result.games].sort( (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, + }, + ]; + } } return { ...obj, gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT, + gameMode: match.gameMode ?? 'pair', + participants: (obj.participants ?? []).map((participant) => ({ + ...participant, + excluded: participant.excluded ?? false, + })), + teams: (obj.teams ?? []).map((team) => ({ + ...team, + groupIndex: team.groupIndex ?? 1, + })), tournamentCodes: await this.tournamentCodeService.buildSlots(match), }; } @@ -114,6 +134,14 @@ export class MatchService { throw new BadRequestException('Match does not belong to this community.'); } const previousStatus = match.status; + if ( + previousStatus !== 'recruiting' && + ('maxParticipants' in params.patch || 'gameMode' in params.patch) + ) { + throw new BadRequestException( + 'maxParticipants and gameMode can only be changed while recruiting.', + ); + } match.set(params.patch); if ( previousStatus !== 'recruiting' && @@ -183,6 +211,7 @@ export class MatchService { tier: selectedTier, preferredPositions: params.preferredPositions, joinedAt: new Date(), + excluded: false, }); await match.save(); return match; 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 c5305abc..6d39a09f 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.service.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.service.ts @@ -220,7 +220,8 @@ export class TournamentCodeService { if (!match) throw new NotFoundException('Match not found.'); match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; - const need = match.gameCount - match.tournamentCodeIds.length; + const requiredSlots = this.resolveRequiredSlots(match); + const need = requiredSlots - match.tournamentCodeIds.length; if (need <= 0) return match; const reservedIds: mongoose.Types.ObjectId[] = []; @@ -311,7 +312,7 @@ export class TournamentCodeService { const matches = await MatchModel.find(filter).exec(); let touched = 0; for (const match of matches) { - if ((match.tournamentCodeIds?.length ?? 0) >= (match.gameCount || 0)) { + if ((match.tournamentCodeIds?.length ?? 0) >= this.resolveRequiredSlots(match)) { continue; } const before = match.tournamentCodeIds?.length ?? 0; @@ -325,7 +326,7 @@ export class TournamentCodeService { public async buildSlots(match: MatchDocument): Promise { const TournamentCodeModel = await this.connectionService.getModel('tournamentCode'); - const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; + const gameCount = this.resolveRequiredSlots(match); const ids = match.tournamentCodeIds ?? []; const codes = ids.length > 0 @@ -341,8 +342,10 @@ export class TournamentCodeService { const gameNumber = index + 1; const code = byGameNumber.get(gameNumber); if (!code) { + const seriesRef = this.resolveSeriesRefForGameNumber(match, gameNumber); return { gameNumber, + ...seriesRef, code: null, expiresAt: null, state: 'pending', @@ -351,6 +354,7 @@ export class TournamentCodeService { } return { gameNumber, + ...this.resolveSeriesRefForGameNumber(match, gameNumber), code: code.code, expiresAt: code.expiresAt.toISOString(), state: code.state, @@ -362,4 +366,26 @@ export class TournamentCodeService { private normalizeCode(code: string | undefined): string { return (code ?? '').trim().toUpperCase(); } + + 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 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; + } + + private resolveSeriesRefForGameNumber( + match: MatchDocument, + gameNumber: number, + ): { blueGroupIndex: number; redGroupIndex: number } { + const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; + const groupIndex = Math.max(1, Math.ceil(gameNumber / perSeries)); + return { blueGroupIndex: groupIndex, redGroupIndex: groupIndex }; + } } 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 c841da3f..50c7d127 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.types.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.types.ts @@ -24,6 +24,8 @@ export interface BulkUploadTournamentCodesResponse { export interface TournamentCodeSlotView { gameNumber: number; + blueGroupIndex: number; + redGroupIndex: number; code: string | null; expiresAt: string | null; state: TournamentCodeState | 'pending'; 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 a617b78f..0f47cd1a 100644 --- a/apps/api/src/modules/tournament-result/team-mapping.util.ts +++ b/apps/api/src/modules/tournament-result/team-mapping.util.ts @@ -39,11 +39,18 @@ export function collectTeamPuuids( match: MatchDocument, side: TeamSide, lookup: MatchPuuidLookup, + groupIndex = 1, ): string[] { - const team = match.teams.find((item) => item.side === side); + const team = match.teams.find( + (item) => item.side === side && (item.groupIndex ?? 1) === groupIndex, + ); if (!team) return []; - return team.members - .map((member) => lookup.puuidByUserId.get(member.userId.toString())) + const userIds = [ + ...(team.captainUserId ? [team.captainUserId] : []), + ...team.members.map((member) => member.userId), + ]; + return userIds + .map((userId) => lookup.puuidByUserId.get(userId.toString())) .filter((puuid): puuid is string => Boolean(puuid)); } @@ -52,10 +59,19 @@ export function computeGameResult(params: { detail: RiotMatchDto; gameNumber: number; lookup: MatchPuuidLookup; + blueGroupIndex?: number; + redGroupIndex?: number; }): MatchGameResult | null { - const { match, detail, gameNumber, lookup } = params; - const ourBluePuuids = collectTeamPuuids(match, 'blue', lookup); - const ourRedPuuids = collectTeamPuuids(match, 'red', lookup); + const { + match, + detail, + gameNumber, + lookup, + blueGroupIndex = 1, + redGroupIndex = 1, + } = params; + const ourBluePuuids = collectTeamPuuids(match, 'blue', lookup, blueGroupIndex); + const ourRedPuuids = collectTeamPuuids(match, 'red', lookup, redGroupIndex); const team100Puuids = detail.info.participants .filter((participant) => participant.teamId === RIOT_BLUE_TEAM_ID) .map((participant) => participant.puuid); @@ -106,6 +122,8 @@ export function computeGameResult(params: { gameNumber, riotMatchId: detail.metadata.matchId, 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 2ce0be98..477ac9da 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.ts @@ -210,6 +210,7 @@ export class TournamentResultService { detail, gameNumber: code.gameNumber, lookup, + ...this.resolveSeriesRefForGameNumber(match, code.gameNumber), }); if (!gameResult) { this.logger.warn( @@ -235,7 +236,7 @@ export class TournamentResultService { match: MatchDocument, codes: TournamentCodeDocument[], ): Promise { - if (codes.length < match.gameCount) return false; + if (codes.length < this.resolveRequiredGameSlots(match)) return false; if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) { return false; } @@ -399,9 +400,71 @@ export class TournamentResultService { mvpUserId: match.result?.mvpUserId, riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))], games, + seriesResults: this.buildSeriesResults(games), }; } + private buildSeriesResults( + games: MatchGameResult[], + ): NonNullable['seriesResults'] { + const bySeries = new Map< + string, + { + blueGroupIndex: number; + redGroupIndex: number; + blueScore: number; + redScore: number; + winnerSide?: 'blue' | 'red'; + } + >(); + + for (const game of games) { + const blueGroupIndex = game.blueGroupIndex ?? 1; + const redGroupIndex = game.redGroupIndex ?? 1; + const key = `${blueGroupIndex}:${redGroupIndex}`; + const current = + bySeries.get(key) ?? + { + blueGroupIndex, + redGroupIndex, + blueScore: 0, + redScore: 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' + : undefined; + bySeries.set(key, current); + } + + return [...bySeries.values()].sort( + (left, right) => + left.blueGroupIndex - right.blueGroupIndex || + left.redGroupIndex - right.redGroupIndex, + ); + } + + private resolveSeriesRefForGameNumber( + match: MatchDocument, + gameNumber: number, + ): { blueGroupIndex: number; redGroupIndex: number } { + const perSeries = match.gameCount || 1; + const groupIndex = Math.max(1, Math.ceil(gameNumber / perSeries)); + return { blueGroupIndex: groupIndex, redGroupIndex: groupIndex }; + } + + private resolveRequiredGameSlots(match: MatchDocument): number { + const groups = Math.max( + 1, + new Set(match.teams.map((team) => team.groupIndex ?? 1)).size, + ); + return groups * (match.gameCount || 1); + } + private async updatePollState( match: MatchDocument, outcome: 'matched' | 'not-found' | 'failed', diff --git a/apps/api/src/seed-dakao-participant.ts b/apps/api/src/seed-dakao-participant.ts index f66befa7..fe0d669e 100644 --- a/apps/api/src/seed-dakao-participant.ts +++ b/apps/api/src/seed-dakao-participant.ts @@ -74,7 +74,7 @@ async function loadMachineEnvFile() { process.env[key] = rawValue.replace(/^["']|["']$/g, ''); } } catch { - // start.ps1과 동일하게 로컬 machine env 파일이 없으면 무시한다. + // 로컬 machine env 파일이 없으면 무시한다. } } diff --git a/apps/api/src/seed.ts b/apps/api/src/seed.ts index 8fe23f8c..458935b0 100644 --- a/apps/api/src/seed.ts +++ b/apps/api/src/seed.ts @@ -40,7 +40,7 @@ async function loadMachineEnvFile() { process.env[key] = value; } } catch { - // start.ps1도 파일이 없으면 그냥 지나간다. + // 로컬 machine env 파일이 없으면 그냥 지나간다. } } diff --git a/apps/api/start.ps1 b/apps/api/start.ps1 deleted file mode 100644 index 20e3329c..00000000 --- a/apps/api/start.ps1 +++ /dev/null @@ -1,68 +0,0 @@ -param( - [switch]$UsePm2, - [string]$Pm2Name = "lolympus-tournament-support" -) - -if (-not $env:NODE_ENV) { - $env:NODE_ENV = "dev" -} - -$MainScript = Join-Path $PSScriptRoot "dist/main.js" - -if ($isMacOS -or $isLinux) { - $env:MachineEnvFile = "$env:HOME/source/global-env-vars.txt" -} elseif ($isWindows) { - $env:MachineEnvFile = "$env:USERPROFILE/source/global-env-vars.txt" -} - -function Set-EnvFromFile { - param([string]$Path) - - if (-not (Test-Path $Path)) { - throw "File not found: $Path" - } - - foreach ($line in Get-Content $Path) { - if ([string]::IsNullOrWhiteSpace($line)) { continue } - if ($line -match '^\s*#') { continue } - - if ($line -match '^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$') { - $key = $matches[1] - $value = $matches[2].Trim() - - if ( - ($value.StartsWith('"') -and $value.EndsWith('"')) -or - ($value.StartsWith("'") -and $value.EndsWith("'")) - ) { - $value = $value.Substring(1, $value.Length - 2) - } - - [System.Environment]::SetEnvironmentVariable($key, $value) - } - } -} - -if (Test-Path $env:MachineEnvFile) { - Set-EnvFromFile $env:MachineEnvFile -} - -if (-not $env:INFISICAL_CLIENT_ID) { - Write-Error "INFISICAL_CLIENT_ID is not set." - exit 1 -} - -if (-not $env:INFISICAL_CLIENT_SECRET) { - Write-Error "INFISICAL_CLIENT_SECRET is not set." - exit 1 -} - -if (-not $env:INFISICAL_PROJECT_ID) { - Write-Error "INFISICAL_PROJECT_ID is not set." - exit 1 -} - -if ($UsePm2) { - pm2 start $MainScript --name $Pm2Name --update-env -} else { - node $MainScript -} diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 2cfd3c0e..a70eb93a 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -8,12 +8,14 @@ import AuthCallbackPage from './pages/AuthCallback'; import HomePage from './pages/HomePage'; import LoginPage from './pages/Login'; import MatchDetailPage from './pages/MatchDetailPage'; +import MatchTeamProgressPage from './pages/MatchTeamProgressPage'; import AuctionPage from './pages/AuctionPage'; import UserHistoryPage from './pages/UserHistoryPage'; import CommunityInternalStatsPage from './pages/CommunityInternalStatsPage'; import InternalMatchDetailPage from './pages/InternalMatchDetailPage'; import LegacyImportPage from './pages/admin/LegacyImportPage'; import LegacyMatchesPage from './pages/admin/LegacyMatchesPage'; +import MatchAdminPage from './pages/admin/MatchAdminPage'; import TournamentCodesPage from './pages/admin/TournamentCodesPage'; function MsalHeaderActions() { @@ -74,6 +76,10 @@ function App() { } /> } /> } /> + } + /> } /> } /> } /> + } + /> } diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts index 5853d8e6..24342cc0 100644 --- a/apps/web/src/api/hooks.ts +++ b/apps/web/src/api/hooks.ts @@ -30,6 +30,7 @@ import type { StartLegacyImportRequest, StartLegacyImportResponse, MatchStatus, + MatchMutationRequest, MatchesResponse, MeResponse, RiotQueueGroup, @@ -130,6 +131,26 @@ export function useAuction( }); } +export function useCreateMatch(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (body: MatchMutationRequest) => + apiFetch(`/communities/${communityId}/matches`, { + method: 'POST', + body: JSON.stringify(body), + }), + }); +} + +export function useUpdateMatch(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: ({ matchId, body }: { matchId: string; body: Partial }) => + apiFetch(`/communities/${communityId}/matches/${matchId}`, { + method: 'PATCH', + body: JSON.stringify(body), + }), + }); +} + function createUserHistoryPath( communityId: string, userId: string, diff --git a/apps/web/src/api/mappers.ts b/apps/web/src/api/mappers.ts index 9ea5036b..8f98c05e 100644 --- a/apps/web/src/api/mappers.ts +++ b/apps/web/src/api/mappers.ts @@ -25,6 +25,7 @@ export interface ParticipantView { mainPosition: Position; subPosition: Position; profileIconId: number; + excluded?: boolean; } export interface TeamParticipantView extends ParticipantView { @@ -34,6 +35,7 @@ export interface TeamParticipantView extends ParticipantView { export interface TeamView { side: TeamSide; + groupIndex: number; name: string; participants: TeamParticipantView[]; } @@ -48,6 +50,7 @@ export interface MatchDetailView { map: string; maxParticipants: number; gameCount: number; + gameMode: ApiMatch["gameMode"]; tournamentCodes: TournamentCodeSlotView[]; joined: boolean; participants: ParticipantView[]; @@ -62,6 +65,8 @@ export interface MatchDetailView { gameNumber: number; riotMatchId: string; winnerSide: TeamSide; + blueGroupIndex: number; + redGroupIndex: number; gameCreation: number; gameDuration: number; participants: Array<{ @@ -74,6 +79,7 @@ export interface MatchDetailView { win: boolean; }>; }>; + seriesResults: NonNullable["seriesResults"]; }; prizes: string[]; notices: string[]; @@ -96,6 +102,7 @@ export interface AuctionPlayerView extends ParticipantView { export interface AuctionTeamView { side: TeamSide; + groupIndex: number; captainUserId: string; captainName: string; points: number; @@ -108,18 +115,19 @@ export interface AuctionTeamView { export interface AuctionStateView { matchId: string; phase: ApiAuction["phase"]; - teams: [AuctionTeamView, AuctionTeamView]; + teams: AuctionTeamView[]; currentPlayer: AuctionPlayerView | null; currentPlayerIndex: number; totalPlayers: number; auctionOrder: AuctionPlayerView[]; bids: { side: TeamSide; + groupIndex: number; amount: number; timestamp: string; }[]; currentBid: number; - currentBidder: TeamSide | null; + currentBidder: { side: TeamSide; groupIndex: number } | null; timer: number; maxTimer: number; deadline?: string; @@ -208,6 +216,7 @@ function mapMatchParticipantToView( mainPosition, subPosition, profileIconId: participant.profileIconId ?? 0, + excluded: participant.excluded ?? false, }; } @@ -262,6 +271,7 @@ function mapAuctionTeamToView( ): AuctionTeamView { return { side: team.side, + groupIndex: team.groupIndex ?? 1, captainUserId: team.captainUserId, captainName: participantLookup.get(team.captainUserId)?.summonerName ?? @@ -396,6 +406,7 @@ 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), participants: team.members.map((member) => { const participant = @@ -423,7 +434,8 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView { description: match.description, map: mapIdToLabel(match.mapId), maxParticipants: match.maxParticipants, - gameCount: match.gameCount ?? 3, + gameCount: match.gameCount ?? 3, + gameMode: match.gameMode ?? "pair", tournamentCodes: match.tournamentCodes ?? [], joined: Boolean(match.joined), participants, @@ -440,6 +452,7 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView { games: [...(match.result.games ?? [])].sort( (left, right) => left.gameNumber - right.gameNumber, ), + seriesResults: match.result.seriesResults ?? [], } : undefined, prizes: match.prizes, @@ -462,22 +475,11 @@ export function mapApiAuctionToAuctionState( const auctionPlayerLookup = new Map( auctionOrder.map((player) => [player.userId, player]), ); - const blueTeam = - auction.teams.find((team) => team.side === "blue") ?? - ({ - side: "blue", - captainUserId: "", - points: 0, - members: [], - } satisfies ApiAuctionTeam); - const redTeam = - auction.teams.find((team) => team.side === "red") ?? - ({ - side: "red", - captainUserId: "", - points: 0, - members: [], - } satisfies ApiAuctionTeam); + const teams = [...auction.teams].sort( + (left, right) => + (left.groupIndex ?? 1) - (right.groupIndex ?? 1) || + (left.side === "blue" ? -1 : 1), + ); const totalPlayers = auctionOrder.length; const currentPlayer = @@ -500,21 +502,26 @@ export function mapApiAuctionToAuctionState( return { matchId: auction.matchId, phase: auction.phase, - teams: [ - mapAuctionTeamToView(blueTeam, auctionPlayerLookup, participantLookup), - mapAuctionTeamToView(redTeam, auctionPlayerLookup, participantLookup), - ], + teams: teams.map((team) => + mapAuctionTeamToView(team, auctionPlayerLookup, participantLookup), + ), currentPlayer, currentPlayerIndex, totalPlayers, auctionOrder, bids: auction.bids.map((bid) => ({ side: bid.side, + groupIndex: bid.groupIndex ?? 1, amount: bid.amount, timestamp: bid.timestamp, })), currentBid: auction.currentBid, - currentBidder: auction.currentBidder ?? null, + currentBidder: auction.currentBidder + ? { + side: auction.currentBidder, + groupIndex: auction.currentBidderGroupIndex ?? 1, + } + : null, timer, maxTimer: auction.maxTimerSeconds, deadline: auction.currentDeadline, diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index 0a431f5b..13d1f91f 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -1,6 +1,7 @@ export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP'; export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY'; export type TeamSide = 'blue' | 'red'; +export type MatchGameMode = 'pair' | 'bracket' | 'round-robin'; export type MatchStatus = | 'recruiting' | 'team-built' @@ -116,6 +117,8 @@ export type TournamentCodeSlotState = TournamentCodeState | 'pending'; export interface TournamentCodeSlotView { gameNumber: number; + blueGroupIndex: number; + redGroupIndex: number; code: string | null; expiresAt: string | null; state: TournamentCodeSlotState; @@ -131,6 +134,7 @@ export interface ApiMatchParticipant { tier?: ApiTierInfo; preferredPositions: ApiPositionPreference[]; joinedAt: string; + excluded?: boolean; } export interface ApiMatchTeamMember { @@ -141,6 +145,7 @@ export interface ApiMatchTeamMember { export interface ApiMatchTeam { side: TeamSide; + groupIndex: number; name: string; captainUserId?: string; members: ApiMatchTeamMember[]; @@ -160,6 +165,8 @@ export interface ApiMatchGameResult { gameNumber: number; riotMatchId: string; winnerSide: TeamSide; + blueGroupIndex: number; + redGroupIndex: number; gameCreation: number; gameDuration: number; participants: ApiMatchGameResultParticipant[]; @@ -172,6 +179,13 @@ export interface ApiMatchResult { mvpUserId?: string; riotMatchIds: string[]; games: ApiMatchGameResult[]; + seriesResults?: Array<{ + blueGroupIndex: number; + redGroupIndex: number; + blueScore: number; + redScore: number; + winnerSide?: TeamSide; + }>; } export interface ApiMatchScheduleItem { @@ -189,6 +203,7 @@ export interface ApiMatch { scheduledAt: string; maxParticipants: number; gameCount: number; + gameMode: MatchGameMode; tournamentCodes?: TournamentCodeSlotView[]; hostUserId?: string; participants: ApiMatchParticipant[]; @@ -222,6 +237,7 @@ export interface ApiAuctionTeamMember { export interface ApiAuctionTeam { side: TeamSide; + groupIndex: number; captainUserId: string; points: number; members: ApiAuctionTeamMember[]; @@ -229,6 +245,7 @@ export interface ApiAuctionTeam { export interface ApiAuctionBid { side: TeamSide; + groupIndex?: number; amount: number; bidderUserId: string; timestamp: string; @@ -244,6 +261,7 @@ export interface ApiAuction { bids: ApiAuctionBid[]; currentBid: number; currentBidder?: TeamSide; + currentBidderGroupIndex?: number; maxTimerSeconds: number; currentDeadline?: string; initialPoints: number; @@ -275,6 +293,19 @@ export interface MatchesResponse { matches: ApiMatch[]; } +export interface MatchMutationRequest { + title: string; + description?: string; + mapId?: number; + scheduledAt: string; + maxParticipants?: number; + gameCount?: number; + gameMode?: MatchGameMode; + prizes?: string[]; + notices?: string[]; + schedule?: ApiMatchScheduleItem[]; +} + export interface DdragonChampionEntry { key: string; name: string; diff --git a/apps/web/src/api/useAuctionSocket.ts b/apps/web/src/api/useAuctionSocket.ts index a9e16146..1a846078 100644 --- a/apps/web/src/api/useAuctionSocket.ts +++ b/apps/web/src/api/useAuctionSocket.ts @@ -13,6 +13,7 @@ type ConnectionStatus = interface BidPayload { side: TeamSide; + groupIndex?: number; amount: number; bidderUserId?: string; } diff --git a/apps/web/src/pages/AuctionPage.tsx b/apps/web/src/pages/AuctionPage.tsx index e4317e7a..dc4abba0 100644 --- a/apps/web/src/pages/AuctionPage.tsx +++ b/apps/web/src/pages/AuctionPage.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from 'react'; +import { useEffect, useMemo, useRef, useState } from 'react'; import { Link, useParams } from 'react-router'; import { useAuction, useDdragonManifest, useMatch, useMe } from '../api/hooks'; import { @@ -20,12 +20,32 @@ import { profileIconUrl, } from '../lib/ddragon'; import { positionIcon, positionLabel } from '../lib/league'; -import type { ApiRiotLaneStats, Position } from '../api/types'; +import type { ApiRiotLaneStats, Position, TeamSide } from '../api/types'; + +type CaptainRole = { + side: TeamSide; + groupIndex: 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, +) { + return ( + currentBidder?.side === team.side && + currentBidder.groupIndex === team.groupIndex + ); +} + const AUCTION_MAX_TEAM_SIZE = 5; const LANE_ROWS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP']; const POSITION_TO_RIOT_LANE = { @@ -209,7 +229,7 @@ function TeamPanel({
- {team.side === 'blue' ? '블루팀' : '레드팀'} + {teamLabel(team.side, team.groupIndex)} 팀장: {team.captainName} @@ -265,7 +285,7 @@ function TeamPanel({ length: Math.max(0, AUCTION_MAX_TEAM_SIZE - 1 - team.members.length), }).map((_, index) => (
@@ -385,9 +405,12 @@ function PlayerSpotlight({
{state.currentBidder && ( - {state.currentBidder === 'blue' ? '블루' : '레드'} + {teamLabel( + state.currentBidder.side, + state.currentBidder.groupIndex, + )} )} @@ -403,21 +426,22 @@ function PlayerSpotlight({ function BidControls({ state, - captainSide, + captainRole, onBid, }: { state: AuctionStateView; - captainSide: 'spectator' | 'blue' | 'red'; - onBid: (side: 'blue' | 'red', amount: number) => void; + captainRole: CaptainRole | null; + onBid: (side: TeamSide, groupIndex: number, amount: number) => void; }) { const [bidAmount, setBidAmount] = useState(100); const minBid = state.currentBid + 10; - const activeTeam = - captainSide === 'blue' - ? state.teams[0] - : captainSide === 'red' - ? state.teams[1] - : null; + const activeTeam = captainRole + ? state.teams.find( + (team) => + team.side === captainRole.side && + team.groupIndex === captainRole.groupIndex, + ) + : null; const activeTeamSize = activeTeam ? activeTeam.members.length + 1 : 0; const isActiveTeamFull = activeTeamSize >= AUCTION_MAX_TEAM_SIZE; @@ -466,7 +490,7 @@ function BidControls({ />
); @@ -508,7 +532,7 @@ function BidLog({ bids }: { bids: AuctionStateView['bids'] }) { - {bid.side === 'blue' ? '블루' : '레드'} + {teamLabel(bid.side, bid.groupIndex)} → @@ -533,6 +557,7 @@ export default function AuctionPage() { const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID); const socket = useAuctionSocket(id); const captainSide = useDevCaptainSide(); + const [captainGroupIndex, setCaptainGroupIndex] = useState(1); const [now, setNow] = useState(() => Date.now()); const [assignedPosition, setAssignedPosition] = useState('MID'); @@ -546,6 +571,17 @@ 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); + }, [auctionState?.teams]); + const captainRole: CaptainRole | null = + captainSide === 'spectator' + ? null + : { + side: captainSide, + groupIndex: captainGroupIndex, + }; useEffect(() => { if (auctionState?.currentPlayer) { @@ -553,6 +589,13 @@ export default function AuctionPage() { } }, [auctionState?.currentPlayer?.id]); + useEffect(() => { + if (availableGroups.length === 0) return; + if (!availableGroups.includes(captainGroupIndex)) { + setCaptainGroupIndex(availableGroups[0]); + } + }, [availableGroups, captainGroupIndex]); + if (!DEFAULT_COMMUNITY_ID) { return (
@@ -681,6 +724,21 @@ export default function AuctionPage() { + {captainSide !== 'spectator' && availableGroups.length > 1 && ( + + )}
@@ -689,13 +747,16 @@ export default function AuctionPage() { )} -
-
- +
+
+ {auctionState.teams.map((team) => ( + + ))}
@@ -721,20 +782,25 @@ export default function AuctionPage() { {auctionState.phase === 'sold' && auctionState.currentBidder && (
- {auctionState.currentBidder === 'blue' ? '블루팀' : '레드팀'} 낙찰 + {teamLabel( + auctionState.currentBidder.side, + auctionState.currentBidder.groupIndex, + )} 낙찰 {' '}— {formatPoints(auctionState.currentBid)}P
)} socket.placeBid({ side, amount })} + captainRole={captainRole} + onBid={(side, groupIndex, amount) => + socket.placeBid({ side, groupIndex, amount }) + } /> @@ -788,14 +854,6 @@ export default function AuctionPage() { )}
- -
- -
); diff --git a/apps/web/src/pages/HomePage.tsx b/apps/web/src/pages/HomePage.tsx index 5b2737b5..e7d8874a 100644 --- a/apps/web/src/pages/HomePage.tsx +++ b/apps/web/src/pages/HomePage.tsx @@ -1,6 +1,6 @@ import { Link } from 'react-router'; import { mapApiMatchToMatchDetail } from '../api/mappers'; -import { useMatches } from '../api/hooks'; +import { useMatches, useMe } from '../api/hooks'; import { DEFAULT_COMMUNITY_ID } from '../config'; function StatusBadge({ status }: { status: string }) { @@ -49,6 +49,7 @@ export default function HomePage() { { status: 'finished', limit: 10 }, DEFAULT_COMMUNITY_ID, ); + const meQuery = useMe(); if (!DEFAULT_COMMUNITY_ID) { return ( @@ -84,6 +85,11 @@ export default function HomePage() { finishedMatchesQuery.data?.map(mapApiMatchToMatchDetail) ?? []; const nextMatch = upcomingMatches[0]; const upcomingCards = nextMatch ? upcomingMatches.slice(1) : upcomingMatches; + const currentUser = + meQuery.data?.memberships.find( + (membership) => membership.community?._id === DEFAULT_COMMUNITY_ID, + )?.user ?? null; + const canManage = currentUser?.role === 'owner' || currentUser?.role === 'admin'; return (
@@ -92,12 +98,22 @@ export default function HomePage() {

다음 내전

- - 내전 전적 보기 - +
+ {canManage && ( + + 내전 관리 + + )} + + 내전 전적 보기 + +
{nextMatch ? ( diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index 4cb92c48..be7932f1 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -22,7 +22,47 @@ 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 type { Position, TournamentCodeSlotView } from '../api/types'; +import type { + ApiMatchParticipant, + Position, + TeamSide, + TournamentCodeSlotView, +} from '../api/types'; + +type CaptainSelectionSlot = { + side: TeamSide; + groupIndex: 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}`; +} + +function buildAuctionParticipantPool(participants: ApiMatchParticipant[]) { + const ordered = [...participants].sort( + (left, right) => + new Date(left.joinedAt).getTime() - new Date(right.joinedAt).getTime(), + ); + const auctionParticipantCount = Math.floor(ordered.length / 10) * 10; + return ordered.slice(0, auctionParticipantCount); +} + +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 }, + ], + ); +} function PosBadge({ pos, sub }: { pos: Position; sub?: boolean }) { return ( @@ -123,8 +163,13 @@ function ParticipantRow({ {participant.summonerName} - + #{participant.tag} + {participant.excluded && ( + + 제외 + + )}
@@ -215,9 +260,11 @@ function ParticipantTable({ function TeamCard({ team, + matchId, isWinner, }: { team: TeamView; + matchId: string; isWinner?: boolean; }) { const borderColor = @@ -242,6 +289,12 @@ function TeamCard({ )} + + 진행 페이지 + @@ -359,8 +412,13 @@ function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) {
{slots.map((slot) => (
- + {slot.gameNumber}경기 + {(slot.blueGroupIndex > 1 || slot.redGroupIndex > 1) && ( + + {slot.blueGroupIndex}조 + + )} {slot.code ? ( @@ -403,8 +461,8 @@ function formatGameDuration(seconds: number) { return `${minutes}:${String(rest).padStart(2, '0')}`; } -function resultSideLabel(side: 'blue' | 'red') { - return side === 'blue' ? '블루팀' : '레드팀'; +function resultSideLabel(side: 'blue' | 'red', groupIndex = 1) { + return teamLabel(side, groupIndex); } function resultSideClass(side: 'blue' | 'red') { @@ -417,10 +475,16 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) { const gamesByNumber = new Map( match.result.games.map((game) => [game.gameNumber, game]), ); + const maxGameNumber = Math.max( + match.gameCount, + match.tournamentCodes.length, + ...match.result.games.map((game) => game.gameNumber), + ); const gameNumbers = Array.from( - { length: match.gameCount }, + { length: maxGameNumber }, (_, index) => index + 1, ); + const seriesResults = match.result.seriesResults ?? []; return (
@@ -452,11 +516,34 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) {
{match.result.winner ? `${match.result.winner} 승리` - : `결과 수집 중 · ${match.result.games.length}/${match.gameCount}경기`} + : `결과 수집 중 · ${match.result.games.length}/${maxGameNumber}경기`}
+ {seriesResults.length > 1 && ( +
+ {seriesResults.map((series) => ( +
+
+ {series.blueGroupIndex}조 +
+
+ 블루 {series.blueScore} + : + 레드 {series.redScore} +
+
+ ))} +
+ )}
{gameNumbers.map((gameNumber) => { const game = gamesByNumber.get(gameNumber); + const winnerGroupIndex = + game?.winnerSide === 'blue' + ? game.blueGroupIndex + : game?.redGroupIndex; return (
- {resultSideLabel(game.winnerSide)} 승 + {resultSideLabel(game.winnerSide, winnerGroupIndex)} 승 {game.riotMatchId} @@ -501,8 +588,9 @@ export default function MatchDetailPage() { )?.user ?? null; const canUseMemberActions = Boolean(currentUser || authUserId); const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID); - const [blueCaptainUserId, setBlueCaptainUserId] = useState(''); - const [redCaptainUserId, setRedCaptainUserId] = useState(''); + const [captainSelections, setCaptainSelections] = useState>( + {}, + ); const pollTournamentResultMutation = usePollTournamentResult( DEFAULT_COMMUNITY_ID, ); @@ -535,10 +623,13 @@ export default function MatchDetailPage() { apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/auction`, { method: 'POST', body: JSON.stringify({ - captains: [ - { side: 'blue', userId: blueCaptainUserId }, - { side: 'red', userId: redCaptainUserId }, - ], + captains: buildCaptainSlots(matchQuery.data?.participants ?? []).map( + (slot) => ({ + side: slot.side, + groupIndex: slot.groupIndex, + userId: captainSelections[captainSlotKey(slot)], + }), + ), initialPoints: 1000, maxTimerSeconds: 30, }), @@ -568,14 +659,43 @@ export default function MatchDetailPage() { } useEffect(() => { - const participants = matchQuery.data?.participants ?? []; - if (!blueCaptainUserId && participants[0]) { - setBlueCaptainUserId(participants[0].userId); + const participants = buildAuctionParticipantPool( + matchQuery.data?.participants ?? [], + ); + const slots = buildCaptainSlots(matchQuery.data?.participants ?? []); + if (slots.length === 0) { + setCaptainSelections({}); + return; } - if (!redCaptainUserId && participants[1]) { - setRedCaptainUserId(participants[1].userId); - } - }, [blueCaptainUserId, redCaptainUserId, matchQuery.data?.participants]); + + setCaptainSelections((current) => { + const next: Record = {}; + const usedUserIds = new Set(); + + for (const slot of slots) { + const key = captainSlotKey(slot); + const currentUserId = current[key]; + const currentIsValid = + currentUserId && + participants.some((participant) => participant.userId === currentUserId) && + !usedUserIds.has(currentUserId); + + if (currentIsValid) { + next[key] = currentUserId; + usedUserIds.add(currentUserId); + continue; + } + + const fallback = participants.find( + (participant) => !usedUserIds.has(participant.userId), + ); + next[key] = fallback?.userId ?? ''; + if (fallback) usedUserIds.add(fallback.userId); + } + + return next; + }); + }, [matchQuery.data?.participants]); if (!DEFAULT_COMMUNITY_ID) { return ( @@ -615,14 +735,24 @@ export default function MatchDetailPage() { const auctionNotStarted = auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404; const showAuctionLink = Boolean(auctionQuery.data); + const auctionParticipantPool = buildAuctionParticipantPool( + matchQuery.data.participants, + ); + const captainSlots = buildCaptainSlots(matchQuery.data.participants); + const selectedCaptainIds = captainSlots + .map((slot) => captainSelections[captainSlotKey(slot)]) + .filter(Boolean); + const hasUniqueCaptainSelections = + selectedCaptainIds.length === captainSlots.length && + new Set(selectedCaptainIds).size === selectedCaptainIds.length; + const waitingParticipantCount = + matchQuery.data.participants.length - auctionParticipantPool.length; const canStartAuction = canManageAuction && match.status === 'recruiting' && - matchQuery.data.participants.length >= 2 && + auctionParticipantPool.length >= 10 && auctionNotStarted && - blueCaptainUserId && - redCaptainUserId && - blueCaptainUserId !== redCaptainUserId; + hasUniqueCaptainSelections; return (
@@ -721,8 +851,13 @@ export default function MatchDetailPage() { 경매 시작

- 두 팀장을 선택하면 경매를 시작할 수 있습니다. + 참가 신청 순서 기준 10명당 1개 조가 만들어지고, 각 조에 블루/레드 팀장을 지정합니다.

+ {waitingParticipantCount > 0 && ( +

+ {waitingParticipantCount}명은 10명 단위에 맞지 않아 이번 경매에서 제외됩니다. +

+ )}
{showAuctionLink ? ( @@ -730,37 +865,55 @@ export default function MatchDetailPage() { 경매 페이지 열기 ) : ( -
- - +
+ {captainSlots.length > 0 ? ( +
+ {captainSlots.map((slot) => { + const key = captainSlotKey(slot); + const currentValue = captainSelections[key] ?? ''; + return ( + + ); + })} +
+ ) : ( +
+ 경매를 시작하려면 최소 10명이 필요합니다. +
+ )}
+ ); +} + +export default function MatchTeamProgressPage() { + const { id, side, groupIndex } = useParams(); + const parsedGroupIndex = Number(groupIndex ?? 1); + const teamSide = side === 'blue' || side === 'red' ? side : null; + const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); + + if (!DEFAULT_COMMUNITY_ID) { + return ( +
+ `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. +
+ ); + } + + if (matchQuery.isLoading) { + return ( +
+ 팀 진행 정보를 불러오는 중... +
+ ); + } + + if (!teamSide || !matchQuery.data) { + return ( +
+

팀 정보를 찾을 수 없습니다

+ + 내전 상세로 + +
+ ); + } + + const match = matchQuery.data; + const team = match.teams.find( + (item) => + item.side === teamSide && (item.groupIndex ?? 1) === parsedGroupIndex, + ); + const participantByUserId = new Map( + match.participants.map((participant) => [participant.userId, participant]), + ); + const codes = (match.tournamentCodes ?? []).filter((slot) => + teamSide === 'blue' + ? slot.blueGroupIndex === parsedGroupIndex + : slot.redGroupIndex === parsedGroupIndex, + ); + const games = (match.result?.games ?? []).filter((game) => + teamSide === 'blue' + ? game.blueGroupIndex === parsedGroupIndex + : game.redGroupIndex === parsedGroupIndex, + ); + + if (!team) { + return ( +
+

아직 팀이 생성되지 않았습니다

+

+ 경매가 완료되면 팀별 진행 페이지를 사용할 수 있습니다. +

+ + 내전 상세로 + +
+ ); + } + + return ( +
+ + ← 내전 상세로 + + +
+

+ {team.name || teamLabel(team.side, team.groupIndex)} +

+

+ 이 팀에 연결된 토너먼트 코드와 수집된 결과만 보여줍니다. +

+
+ +
+
+
+

+ 팀 구성 +

+
+ + {team.members.map((member) => ( + + ))} +
+ +
+
+
+

+ 토너먼트 코드 +

+
+
+ {codes.length > 0 ? ( + codes.map((slot) => ( +
+
+ + {slot.gameNumber}경기 + + + {slot.code ?? '발급 대기'} + +
+
+ 만료 {formatExpiry(slot.expiresAt)} +
+
+ )) + ) : ( +
+ 아직 연결된 코드가 없습니다. +
+ )} +
+
+ +
+
+

+ 결과 +

+
+
+ {games.length > 0 ? ( + games.map((game) => { + const won = game.winnerSide === teamSide; + return ( +
+
+ + {game.gameNumber}경기 + + + {won ? '승리' : '패배'} + +
+
+ {game.riotMatchId} +
+
+ ); + }) + ) : ( +
+ 아직 수집된 결과가 없습니다. +
+ )} +
+
+
+
+
+ ); +} diff --git a/apps/web/src/pages/admin/MatchAdminPage.tsx b/apps/web/src/pages/admin/MatchAdminPage.tsx new file mode 100644 index 00000000..5e134004 --- /dev/null +++ b/apps/web/src/pages/admin/MatchAdminPage.tsx @@ -0,0 +1,433 @@ +import { useMemo, useState } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { Link, useParams } from 'react-router'; +import { + useCreateMatch, + useDeleteMatch, + useMatches, + useMe, + useUpdateMatch, +} from '../../api/hooks'; +import type { + ApiMatch, + ApiMatchScheduleItem, + MatchGameMode, + MatchMutationRequest, +} from '../../api/types'; +import { DEFAULT_COMMUNITY_ID } from '../../config'; + +const DEFAULT_FORM: MatchMutationRequest = { + title: '', + description: '', + mapId: 11, + scheduledAt: toInputValue(new Date(Date.now() + 24 * 60 * 60 * 1000)), + maxParticipants: 10, + gameCount: 3, + gameMode: 'pair', + prizes: [], + notices: [], + schedule: [], +}; + +const GAME_MODE_LABEL: Record = { + pair: '페어', + bracket: '브래킷', + 'round-robin': '라운드 로빈', +}; + +function toInputValue(value: string | Date) { + const date = value instanceof Date ? value : new Date(value); + const offset = date.getTimezoneOffset(); + return new Date(date.getTime() - offset * 60_000).toISOString().slice(0, 16); +} + +function toIsoFromInput(value: string) { + return new Date(value).toISOString(); +} + +function formatDate(value: string) { + return new Intl.DateTimeFormat('ko-KR', { + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + }).format(new Date(value)); +} + +function parseLines(value: string) { + return value + .split(/\r?\n/u) + .map((line) => line.trim()) + .filter(Boolean); +} + +function parseSchedule(value: string): ApiMatchScheduleItem[] { + return parseLines(value).map((line) => { + const [time, ...labelParts] = line.split('|').map((part) => part.trim()); + return { + time: time || '00:00', + label: labelParts.join('|') || '일정', + }; + }); +} + +function scheduleToText(schedule: ApiMatchScheduleItem[] = []) { + return schedule.map((item) => `${item.time}|${item.label}`).join('\n'); +} + +function makeForm(match?: ApiMatch): MatchMutationRequest & { + prizesText: string; + noticesText: string; + scheduleText: string; +} { + if (!match) { + return { + ...DEFAULT_FORM, + prizesText: '', + noticesText: '', + scheduleText: '', + }; + } + + return { + title: match.title, + description: match.description, + mapId: match.mapId, + scheduledAt: toInputValue(match.scheduledAt), + maxParticipants: match.maxParticipants, + gameCount: match.gameCount, + gameMode: match.gameMode ?? 'pair', + prizes: match.prizes, + notices: match.notices, + schedule: match.schedule, + prizesText: match.prizes.join('\n'), + noticesText: match.notices.join('\n'), + scheduleText: scheduleToText(match.schedule), + }; +} + +export default function MatchAdminPage() { + const { cid } = useParams(); + const communityId = cid ?? DEFAULT_COMMUNITY_ID; + const queryClient = useQueryClient(); + const meQuery = useMe(); + const matchesQuery = useMatches({ limit: 200 }, communityId); + const createMutation = useCreateMatch(communityId); + const updateMutation = useUpdateMatch(communityId); + const deleteMutation = useDeleteMatch(communityId); + const [editing, setEditing] = useState(null); + const [showForm, setShowForm] = useState(false); + const [form, setForm] = useState(makeForm()); + const [message, setMessage] = useState(null); + + const currentUser = + meQuery.data?.memberships.find( + (membership) => membership.community?._id === communityId, + )?.user ?? null; + const canManage = currentUser?.role === 'owner' || currentUser?.role === 'admin'; + const matches = useMemo( + () => [...(matchesQuery.data ?? [])].sort((a, b) => new Date(b.scheduledAt).getTime() - new Date(a.scheduledAt).getTime()), + [matchesQuery.data], + ); + + async function invalidate() { + await Promise.all([ + queryClient.invalidateQueries({ queryKey: ['matches', communityId] }), + queryClient.invalidateQueries({ queryKey: ['match', communityId] }), + ]); + } + + function openCreate() { + setEditing(null); + setForm(makeForm()); + setShowForm(true); + setMessage(null); + } + + function openEdit(match: ApiMatch) { + setEditing(match); + setForm(makeForm(match)); + setShowForm(true); + setMessage(null); + } + + function buildPayload(): MatchMutationRequest { + return { + title: form.title.trim(), + description: form.description?.trim() ?? '', + mapId: Number(form.mapId ?? 11), + scheduledAt: toIsoFromInput(form.scheduledAt), + maxParticipants: Number(form.maxParticipants ?? 10), + gameCount: Number(form.gameCount ?? 3), + gameMode: form.gameMode, + prizes: parseLines(form.prizesText), + notices: parseLines(form.noticesText), + schedule: parseSchedule(form.scheduleText), + }; + } + + function submit() { + setMessage(null); + const payload = buildPayload(); + if (!payload.title) { + setMessage('제목을 입력해주세요.'); + return; + } + + const callbacks = { + onSuccess: async () => { + await invalidate(); + setShowForm(false); + setEditing(null); + setMessage(editing ? '내전을 수정했습니다.' : '내전을 만들었습니다.'); + }, + onError: (error: Error) => setMessage(error.message), + }; + + if (editing) { + updateMutation.mutate({ matchId: editing._id, body: payload }, callbacks); + return; + } + createMutation.mutate(payload, callbacks); + } + + if (!canManage && !meQuery.isPending) { + return ( +
+

권한이 필요합니다

+

+ 내전 관리는 owner/admin만 사용할 수 있습니다. +

+
+ ); + } + + return ( +
+ + ← 목록으로 + +
+
+

내전 관리

+

+ 내전 생성, 모집 정원, 게임 모드와 공지 내용을 관리합니다. +

+
+ +
+ + {message && ( +
+ {message} +
+ )} + + {showForm && ( +
+
+

+ {editing ? '내전 수정' : '새 내전'} +

+ +
+ +
+ +