diff --git a/apps/api/src/modules/auction/auction.controller.ts b/apps/api/src/modules/auction/auction.controller.ts index f58b8eaa..a72e9fc8 100644 --- a/apps/api/src/modules/auction/auction.controller.ts +++ b/apps/api/src/modules/auction/auction.controller.ts @@ -18,11 +18,20 @@ import { RolesGuard } from '../auth/roles.guard'; import { ParseObjectIdPipe } from '../common/parse-object-id.pipe'; import type { UserDocument } from '../global/database/schema'; import { AuctionService } from './auction.service'; -import { PlaceBidDto, SoldDto, StartAuctionDto } from './dto/auction.dto'; +import { AuctionGateway } from './auction.gateway'; +import { + PlaceBidDto, + SoldDto, + StartAuctionDto, + UndoAuctionDto, +} from './dto/auction.dto'; @Controller('communities/:communityId/matches/:matchId/auction') export class AuctionController { - constructor(private readonly auctionService: AuctionService) {} + constructor( + private readonly auctionService: AuctionService, + private readonly auctionGateway: AuctionGateway, + ) {} @Post() @Roles('admin', 'owner') @@ -41,9 +50,11 @@ export class AuctionController { captains: body.captains.map((c) => ({ teamIndex: c.teamIndex, userId: new mongoose.Types.ObjectId(c.userId), + initialPoints: c.initialPoints, })), initialPoints: body.initialPoints ?? 1000, maxTimerSeconds: body.maxTimerSeconds ?? 30, + topTierThreshold: body.topTierThreshold ?? 'NONE', }); } @@ -103,6 +114,40 @@ export class AuctionController { return this.auctionService.next(matchId); } + @Get('history') + @Roles('admin', 'owner') + @UseGuards(RolesGuard) + public async listHistory( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.auctionService.listHistory({ matchId, communityId }); + } + + @Post('undo') + @Roles('admin', 'owner') + @UseGuards(RolesGuard) + @HttpCode(HttpStatus.OK) + public async undo( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Body() body: UndoAuctionDto, + ) { + this.assertSameCommunity(currentUser, communityId); + const auction = await this.auctionService.undoTo({ + matchId, + communityId, + sequence: body.sequence, + }); + this.auctionGateway.broadcastState(matchId.toString(), auction); + return auction; + } + @Delete() @Roles('admin', 'owner') @UseGuards(RolesGuard) diff --git a/apps/api/src/modules/auction/auction.gateway.ts b/apps/api/src/modules/auction/auction.gateway.ts index ce187e01..b868285b 100644 --- a/apps/api/src/modules/auction/auction.gateway.ts +++ b/apps/api/src/modules/auction/auction.gateway.ts @@ -294,7 +294,7 @@ export class AuctionGateway return typeof value === 'string' && value.length > 0 ? value : undefined; } - private broadcastState(matchId: string, auction: AuctionDocument) { + public broadcastState(matchId: string, auction: AuctionDocument) { this.server.to(matchId).emit('state', this.serializeAuction(auction)); this.syncRoomTimer(matchId, auction); } @@ -305,6 +305,10 @@ export class AuctionGateway const deadline = auction.currentDeadline; const deadlineIso = deadline.toISOString(); + if (Date.now() >= deadline.getTime()) { + void this.handleDeadlineExpiry(matchId); + return; + } this.server.to(matchId).emit('tick', { deadline: deadlineIso, serverTime: new Date().toISOString(), @@ -318,12 +322,34 @@ export class AuctionGateway if (Date.now() >= deadline.getTime()) { this.clearRoomTimer(matchId); + void this.handleDeadlineExpiry(matchId); } }, 1000); this.roomTimers.set(matchId, timer); } + private async handleDeadlineExpiry(matchIdStr: string) { + const matchId = new mongoose.Types.ObjectId(matchIdStr); + const auction = await this.auctionService + .getByMatchId(matchId) + .catch(() => null); + if (!auction || auction.phase !== 'bidding') return; + if (!auction.currentDeadline || auction.currentDeadline.getTime() > Date.now()) { + return; + } + + try { + const nextAuction = + auction.currentBid > 0 + ? await this.auctionService.markSold({ matchId }) + : await this.auctionService.markPassed(matchId); + this.broadcastState(matchIdStr, nextAuction); + } catch (error) { + this.emitKnownErrorToRoom(matchIdStr, error); + } + } + private maybeClearRoomTimer(matchId: string) { const room = this.server.adapter.rooms.get(matchId); if (room && room.size > 0) return; @@ -343,6 +369,12 @@ export class AuctionGateway this.emitError(socket, message); } + private emitKnownErrorToRoom(matchId: string, error: unknown) { + const message = + error instanceof Error ? error.message : 'Unexpected auction gateway error.'; + this.server.to(matchId).emit('error', { message }); + } + private emitError(socket: Socket, message: string) { socket.emit('error', { message }); } diff --git a/apps/api/src/modules/auction/auction.service.spec.ts b/apps/api/src/modules/auction/auction.service.spec.ts index 89b6c5f9..054536af 100644 --- a/apps/api/src/modules/auction/auction.service.spec.ts +++ b/apps/api/src/modules/auction/auction.service.spec.ts @@ -3,8 +3,27 @@ import { AuctionService } from './auction.service'; describe('AuctionService', () => { function createService(models: Record) { + const auctionHistoryModel = { + findOne: jest.fn().mockReturnValue({ + sort: jest.fn().mockReturnValue({ + select: jest.fn().mockReturnValue({ + lean: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue(null), + }), + }), + }), + }), + create: jest.fn().mockResolvedValue(undefined), + deleteMany: jest.fn().mockReturnValue({ + session: jest.fn().mockResolvedValue(undefined), + }), + }; + const allModels = { + auctionHistory: auctionHistoryModel, + ...models, + }; const connectionService = { - getModel: jest.fn((name: string) => models[name]), + getModel: jest.fn((name: string) => allModels[name]), createSession: jest.fn(), }; const enrichmentService = { @@ -16,6 +35,7 @@ describe('AuctionService', () => { }; const tournamentResultService = { scheduleInitialPoll: jest.fn().mockResolvedValue(null), + cancelPolling: jest.fn().mockResolvedValue(undefined), }; return { @@ -28,6 +48,7 @@ describe('AuctionService', () => { connectionService, tournamentCodeService, tournamentResultService, + auctionHistoryModel, }; } @@ -96,6 +117,119 @@ describe('AuctionService', () => { expect(auction.save).not.toHaveBeenCalled(); }); + it('marks a zero-bid player as passed and queues them for round two', async () => { + const matchId = new mongoose.Types.ObjectId(); + const playerId = new mongoose.Types.ObjectId(); + const auction = { + _id: new mongoose.Types.ObjectId(), + matchId, + phase: 'bidding', + currentBid: 0, + currentIndex: 0, + auctionRound: 1, + order: [ + { + userId: playerId, + preferredPositions: [{ position: 'MID', priority: 1 }], + passCount: 0, + }, + ], + passedQueue: [], + save: jest.fn().mockResolvedValue(undefined), + toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }), + }; + const { service } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + }); + + await service.markPassed(matchId); + + expect(auction.phase).toBe('passed'); + expect(auction.order[0].passCount).toBe(1); + expect(auction.passedQueue).toHaveLength(1); + expect(auction.save).toHaveBeenCalledTimes(1); + }); + + it('force-assigns second-pass players to the open team with most points', async () => { + const matchId = new mongoose.Types.ObjectId(); + const captainOneId = new mongoose.Types.ObjectId(); + const captainTwoId = new mongoose.Types.ObjectId(); + const passedPlayerId = new mongoose.Types.ObjectId(); + const auction = { + _id: new mongoose.Types.ObjectId(), + matchId, + phase: 'passed', + currentIndex: 0, + auctionRound: 2, + order: [ + { + userId: passedPlayerId, + preferredPositions: [{ position: 'SUP', priority: 1 }], + passCount: 2, + }, + ], + passedQueue: [], + teams: [ + { + teamIndex: 1, + captainUserId: captainOneId, + points: 10, + members: [], + }, + { + teamIndex: 2, + captainUserId: captainTwoId, + points: 50, + members: [], + }, + ], + save: jest.fn().mockResolvedValue(undefined), + toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }), + }; + const match = { + participants: [ + { + userId: captainOneId, + preferredPositions: [{ position: 'TOP', priority: 1 }], + }, + { + userId: captainTwoId, + preferredPositions: [{ position: 'JGL', priority: 1 }], + }, + { + userId: passedPlayerId, + preferredPositions: [{ position: 'SUP', priority: 1 }], + }, + ], + status: 'team-built', + teams: [], + teamBuiltAt: undefined, + save: jest.fn().mockResolvedValue(undefined), + }; + const { service } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + match: { + findById: jest.fn().mockResolvedValue(match), + }, + }); + + await service.next(matchId); + + expect(auction.phase).toBe('complete'); + expect(auction.teams[1].members).toEqual([ + { + userId: passedPlayerId, + assignedPosition: 'SUP', + cost: 1, + }, + ]); + expect(auction.teams[1].points).toBe(49); + }); + it('syncs completed auction teams into the match document', async () => { const matchId = new mongoose.Types.ObjectId(); const blueCaptainId = new mongoose.Types.ObjectId(); @@ -260,4 +394,92 @@ describe('AuctionService', () => { expect(match.save).toHaveBeenCalledWith({ session }); expect(session.commitTransaction).toHaveBeenCalledTimes(1); }); + + it('undoes to a history snapshot and releases resources when leaving complete', async () => { + const matchId = new mongoose.Types.ObjectId(); + const communityId = new mongoose.Types.ObjectId(); + const auctionId = new mongoose.Types.ObjectId(); + const session = { + startTransaction: jest.fn(), + commitTransaction: jest.fn().mockResolvedValue(undefined), + abortTransaction: jest.fn().mockResolvedValue(undefined), + endSession: jest.fn().mockResolvedValue(undefined), + }; + const auction = { + _id: auctionId, + matchId, + completedAt: new Date(), + }; + const snapshot = { + _id: auctionId.toString(), + matchId: matchId.toString(), + phase: 'bidding', + order: [], + teams: [], + }; + const restored = { _id: auctionId, phase: 'bidding' }; + const match = { + communityId, + status: 'finished', + result: { games: [] }, + save: jest.fn().mockResolvedValue(undefined), + }; + const auctionFindOneQuery = { + session: jest.fn().mockResolvedValue(auction), + }; + const matchFindByIdQuery = { + session: jest.fn().mockResolvedValue(match), + }; + const historyFindOneQuery = { + session: jest.fn().mockReturnValue({ + lean: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ + auctionId, + matchId, + sequence: 3, + snapshotBefore: snapshot, + }), + }), + }), + }; + const historyDeleteManyQuery = { + session: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue(undefined), + }), + }; + const auctionReplaceOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue(undefined), + }); + const { service, connectionService, tournamentCodeService, tournamentResultService } = + createService({ + auction: { + findOne: jest.fn().mockReturnValue(auctionFindOneQuery), + replaceOne: auctionReplaceOne, + findById: jest.fn().mockResolvedValue(restored), + }, + auctionHistory: { + findOne: jest.fn().mockReturnValue(historyFindOneQuery), + deleteMany: jest.fn().mockReturnValue(historyDeleteManyQuery), + }, + match: { + findById: jest.fn().mockReturnValue(matchFindByIdQuery), + }, + }); + connectionService.createSession.mockResolvedValue(session); + + await expect( + service.undoTo({ matchId, communityId, sequence: 3 }), + ).resolves.toBe(restored); + + expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(match); + expect(tournamentResultService.cancelPolling).toHaveBeenCalledWith(match); + expect(match.status).toBe('team-built'); + expect(match.result).toBeUndefined(); + expect(auctionReplaceOne).toHaveBeenCalledWith( + { _id: auctionId }, + snapshot, + { session }, + ); + expect(session.commitTransaction).toHaveBeenCalledTimes(1); + }); }); diff --git a/apps/api/src/modules/auction/auction.service.ts b/apps/api/src/modules/auction/auction.service.ts index 7bf6a143..c459d6d6 100644 --- a/apps/api/src/modules/auction/auction.service.ts +++ b/apps/api/src/modules/auction/auction.service.ts @@ -8,9 +8,11 @@ import { import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import { + AuctionActionType, AuctionDocument, AuctionPlayerSnapshot, AuctionTeam, + AuctionTopTierThreshold, MatchParticipant, MatchTeamMember, Position, @@ -31,9 +33,11 @@ interface StartAuctionParams { captains: { teamIndex: number; userId: mongoose.Types.ObjectId; + initialPoints?: number; }[]; initialPoints: number; maxTimerSeconds: number; + topTierThreshold: AuctionTopTierThreshold; } interface PlaceBidParams { @@ -48,6 +52,13 @@ interface MarkSoldParams { assignedPosition?: Position; } +export interface AuctionHistoryView { + sequence: number; + action: AuctionActionType; + actionLabel: string; + takenAt: Date; +} + interface AuctionEnrichmentTarget { userId: mongoose.Types.ObjectId; puuid: string; @@ -151,8 +162,13 @@ export class AuctionService { tiers: primary.tiers, masteries: primary.championMasteries, recentStatsSummary: primary.recentStatsSummary, + passCount: 0, }); } + const prioritizedOrder = this.applyTopTierPriority( + order, + params.topTierThreshold, + ); const auction = await AuctionModel.create({ matchId: params.matchId, @@ -160,17 +176,21 @@ export class AuctionService { teams: params.captains.map((c) => ({ teamIndex: c.teamIndex, captainUserId: c.userId, - points: params.initialPoints, + points: c.initialPoints ?? params.initialPoints, members: [], })), - order, + order: prioritizedOrder, + passedQueue: [], + auctionRound: 1, currentIndex: 0, bids: [], currentBid: 0, maxTimerSeconds: params.maxTimerSeconds, initialPoints: params.initialPoints, + topTierThreshold: params.topTierThreshold, startedAt: new Date(), }); + await this.recordSnapshot(auction, 'start'); match.status = 'team-built'; match.teamBuiltAt = match.teamBuiltAt ?? new Date(); @@ -196,6 +216,35 @@ export class AuctionService { return auction; } + public async listHistory(params: { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + }): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const AuctionHistoryModel = + await this.connectionService.getModel('auctionHistory'); + const match = await MatchModel.findById(params.matchId).select({ + communityId: 1, + }); + if (!match) throw new NotFoundException('Match not found.'); + if (!match.communityId.equals(params.communityId)) { + throw new BadRequestException('Match does not belong to this community.'); + } + + const entries = await AuctionHistoryModel.find({ matchId: params.matchId }) + .sort({ sequence: -1 }) + .limit(100) + .lean() + .exec(); + + return entries.map((entry) => ({ + sequence: entry.sequence, + action: entry.action, + actionLabel: this.formatHistoryActionLabel(entry.action), + takenAt: entry.takenAt, + })); + } + public async openBidding( matchId: mongoose.Types.ObjectId, ): Promise { @@ -203,6 +252,7 @@ export class AuctionService { if (auction.phase !== 'presenting') { throw new BadRequestException('Auction is not in presenting phase.'); } + await this.recordSnapshot(auction, 'open-bidding'); auction.phase = 'bidding'; auction.currentBid = 0; auction.currentBidderTeamIndex = undefined; @@ -227,6 +277,7 @@ export class AuctionService { this.assertTeamHasSlot(team); // 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다. + await this.recordSnapshot(auction, 'bid', params.bidderUserId); auction.currentBid = params.amount; auction.currentBidderTeamIndex = params.teamIndex; auction.currentDeadline = this.createDeadline( @@ -260,6 +311,7 @@ export class AuctionService { const current = auction.order[auction.currentIndex]; if (!current) throw new BadRequestException('No current player.'); + await this.recordSnapshot(auction, 'sold'); const preferredPrimary = current.preferredPositions[0]?.position; team.members.push({ userId: current.userId, @@ -273,17 +325,70 @@ export class AuctionService { return auction; } + public async markPassed( + matchId: mongoose.Types.ObjectId, + ): Promise { + const auction = await this.getByMatchId(matchId); + if (auction.phase !== 'bidding') { + throw new BadRequestException('Auction is not in bidding phase.'); + } + if (auction.currentBid > 0) { + throw new BadRequestException('Cannot pass a player with an active bid.'); + } + const current = auction.order[auction.currentIndex]; + if (!current) throw new BadRequestException('No current player.'); + + await this.recordSnapshot(auction, 'passed'); + current.passCount = (current.passCount ?? 0) + 1; + if ((auction.auctionRound ?? 1) === 1) { + auction.passedQueue.push(this.cloneAuctionPlayerSnapshot(current)); + } + auction.phase = 'passed'; + auction.currentDeadline = undefined; + await auction.save(); + return auction; + } + public async next( matchId: mongoose.Types.ObjectId, ): Promise { const auction = await this.getByMatchId(matchId); - if (auction.phase !== 'sold' && auction.phase !== 'presenting') { + if ( + auction.phase !== 'sold' && + auction.phase !== 'presenting' && + auction.phase !== 'passed' + ) { throw new BadRequestException('Cannot advance from current phase.'); } const nextIndex = auction.currentIndex + 1; + const completesAuction = + nextIndex >= auction.order.length && + !( + (auction.auctionRound ?? 1) === 1 && + (auction.passedQueue?.length ?? 0) > 0 + ); + await this.recordSnapshot(auction, completesAuction ? 'complete' : 'next'); if (nextIndex >= auction.order.length) { - auction.phase = 'complete'; - auction.completedAt = new Date(); + if ( + (auction.auctionRound ?? 1) === 1 && + (auction.passedQueue?.length ?? 0) > 0 + ) { + auction.order.push( + ...auction.passedQueue.map((player) => + this.cloneAuctionPlayerSnapshot(player), + ), + ); + auction.passedQueue = []; + auction.auctionRound = 2; + auction.currentIndex = nextIndex; + auction.phase = 'presenting'; + auction.currentBid = 0; + auction.currentBidderTeamIndex = undefined; + } else { + this.forceAssignRemainingPasses(auction); + auction.phase = 'complete'; + auction.completedAt = new Date(); + } } else { auction.currentIndex = nextIndex; auction.phase = 'presenting'; @@ -303,6 +408,8 @@ export class AuctionService { communityId: mongoose.Types.ObjectId; }): Promise { const AuctionModel = await this.connectionService.getModel('auction'); + const AuctionHistoryModel = + await this.connectionService.getModel('auctionHistory'); const MatchModel = await this.connectionService.getModel('match'); const session = await this.connectionService.createSession(); @@ -323,6 +430,9 @@ export class AuctionService { } await auction.deleteOne({ session }); + await AuctionHistoryModel.deleteMany({ auctionId: auction._id }).session( + session, + ); if (match.status === 'team-built') { await this.tournamentCodeService.releaseFromMatch(match); match.status = 'recruiting'; @@ -345,6 +455,210 @@ export class AuctionService { } } + public async undoTo(params: { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + sequence: number; + }): Promise { + const AuctionModel = await this.connectionService.getModel('auction'); + const AuctionHistoryModel = + await this.connectionService.getModel('auctionHistory'); + const MatchModel = await this.connectionService.getModel('match'); + + const session = await this.connectionService.createSession(); + if (!session) { + throw new InternalServerErrorException('Failed to start DB session.'); + } + + try { + session.startTransaction(); + const auction = await AuctionModel.findOne({ + matchId: params.matchId, + }).session(session); + if (!auction) throw new NotFoundException('Auction not found.'); + + const match = await MatchModel.findById(params.matchId).session(session); + if (!match) throw new NotFoundException('Match not found.'); + if (!match.communityId.equals(params.communityId)) { + throw new BadRequestException('Community mismatch.'); + } + + const history = await AuctionHistoryModel.findOne({ + auctionId: auction._id, + sequence: params.sequence, + }) + .session(session) + .lean() + .exec(); + if (!history) throw new NotFoundException('Auction history not found.'); + + const snapshot = history.snapshotBefore; + if (!snapshot || typeof snapshot !== 'object') { + throw new BadRequestException('Auction history snapshot is invalid.'); + } + + const undoingCompletedAuction = + Boolean(auction.completedAt) && !('completedAt' in snapshot); + if (undoingCompletedAuction) { + await this.tournamentCodeService.releaseFromMatch(match); + await this.tournamentResultService.cancelPolling(match); + match.status = 'team-built'; + match.result = undefined; + await match.save({ session }); + } + + await AuctionModel.replaceOne({ _id: auction._id }, snapshot, { + session, + }).exec(); + await AuctionHistoryModel.deleteMany({ + auctionId: auction._id, + sequence: { $gt: params.sequence }, + }) + .session(session) + .exec(); + + await session.commitTransaction(); + const restored = await AuctionModel.findById(auction._id); + if (!restored) throw new NotFoundException('Auction not found.'); + return restored; + } catch (err) { + await session.abortTransaction(); + throw err; + } finally { + await session.endSession(); + } + } + + private applyTopTierPriority( + order: AuctionPlayerSnapshot[], + threshold: AuctionTopTierThreshold, + ): AuctionPlayerSnapshot[] { + if (threshold === 'NONE') return order; + + const ranks = [ + 'IRON', + 'BRONZE', + 'SILVER', + 'GOLD', + 'PLATINUM', + 'EMERALD', + 'DIAMOND', + 'MASTER', + 'GRANDMASTER', + 'CHALLENGER', + ]; + const cutoff = ranks.indexOf(threshold); + const score = (snap: AuctionPlayerSnapshot) => { + const solo = snap.tiers.find( + (tier) => tier.queueType === 'RANKED_SOLO_5x5', + ); + if (!solo) return -1; + const tierIdx = ranks.indexOf(solo.tier); + if (tierIdx < cutoff) return -1; + const rankBonus = + ({ I: 4, II: 3, III: 2, IV: 1, '': 0 } as Record)[ + solo.rank + ] ?? 0; + return tierIdx * 1000 + rankBonus * 100 + (solo.leaguePoints ?? 0) * 0.001; + }; + + const top = order + .filter((snap) => score(snap) >= 0) + .sort((left, right) => score(right) - score(left)); + const rest = order.filter((snap) => score(snap) < 0); + return [...top, ...rest]; + } + + private forceAssignRemainingPasses(auction: AuctionDocument): void { + const forcedPlayers = auction.order.filter( + (player) => + (player.passCount ?? 0) >= 2 && + !this.isAuctionPlayerAssigned(auction, player.userId), + ); + + for (const player of forcedPlayers) { + const targetTeam = [...auction.teams] + .filter( + (team) => this.countTeamMembersIncludingCaptain(team) < AUCTION_MAX_TEAM_SIZE, + ) + .sort((left, right) => right.points - left.points)[0]; + if (!targetTeam) return; + + const preferredPrimary = player.preferredPositions[0]?.position; + targetTeam.members.push({ + userId: player.userId, + assignedPosition: preferredPrimary ?? 'MID', + cost: 1, + }); + targetTeam.points = Math.max(0, targetTeam.points - 1); + } + } + + private isAuctionPlayerAssigned( + auction: AuctionDocument, + userId: mongoose.Types.ObjectId, + ): boolean { + const userIdText = userId.toString(); + return auction.teams.some((team) => + team.members.some((member) => member.userId.toString() === userIdText), + ); + } + + private cloneAuctionPlayerSnapshot( + player: AuctionPlayerSnapshot, + ): AuctionPlayerSnapshot { + return JSON.parse(JSON.stringify(player)) as AuctionPlayerSnapshot; + } + + private async recordSnapshot( + auction: AuctionDocument, + action: AuctionActionType, + actorUserId?: mongoose.Types.ObjectId, + ): Promise { + const AuctionHistoryModel = + await this.connectionService.getModel('auctionHistory'); + const latest = await AuctionHistoryModel.findOne({ auctionId: auction._id }) + .sort({ sequence: -1 }) + .select({ sequence: 1 }) + .lean() + .exec(); + const snapshotBefore = + typeof auction.toObject === 'function' + ? auction.toObject({ depopulate: true }) + : auction; + + await AuctionHistoryModel.create({ + auctionId: auction._id, + matchId: auction.matchId, + sequence: (latest?.sequence ?? 0) + 1, + action, + actorUserId, + snapshotBefore: JSON.parse(JSON.stringify(snapshotBefore)), + takenAt: new Date(), + }); + } + + private formatHistoryActionLabel(action: AuctionActionType): string { + switch (action) { + case 'start': + return '경매 시작'; + case 'open-bidding': + return '입찰 열기'; + case 'bid': + return '입찰'; + case 'sold': + return '낙찰 처리'; + case 'passed': + return '유찰'; + case 'next': + return '다음 선수'; + case 'complete': + return '경매 완료'; + default: + return action; + } + } + private applyAuctionCut(match: { participants: MatchParticipant[]; }): MatchParticipant[] { diff --git a/apps/api/src/modules/auction/dto/auction.dto.ts b/apps/api/src/modules/auction/dto/auction.dto.ts index 73123c1b..82422bdb 100644 --- a/apps/api/src/modules/auction/dto/auction.dto.ts +++ b/apps/api/src/modules/auction/dto/auction.dto.ts @@ -7,9 +7,14 @@ import { IsInt, IsMongoId, IsOptional, + Max, Min, ValidateNested, } from 'class-validator'; +import { AUCTION_TOP_TIER_THRESHOLDS } from '../../global/database/schema'; + +export type AuctionTopTierThreshold = + (typeof AUCTION_TOP_TIER_THRESHOLDS)[number]; class CaptainAssignmentDto { @IsInt() @@ -18,6 +23,12 @@ class CaptainAssignmentDto { @IsMongoId() userId!: string; + + @IsOptional() + @IsInt() + @Min(100) + @Max(100000) + initialPoints?: number; } export class StartAuctionDto { @@ -30,9 +41,14 @@ export class StartAuctionDto { @IsOptional() @IsInt() - @Min(1) + @Min(100) + @Max(100000) initialPoints?: number; + @IsOptional() + @IsEnum(AUCTION_TOP_TIER_THRESHOLDS) + topTierThreshold?: AuctionTopTierThreshold; + @IsOptional() @IsInt() @Min(5) @@ -58,3 +74,9 @@ export class SoldDto { @IsEnum(['TOP', 'JGL', 'MID', 'ADC', 'SUP']) assignedPosition?: 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP'; } + +export class UndoAuctionDto { + @IsInt() + @Min(1) + sequence!: number; +} diff --git a/apps/api/src/modules/global/database/migrations/20260502-auction-pass-history.ts b/apps/api/src/modules/global/database/migrations/20260502-auction-pass-history.ts new file mode 100644 index 00000000..4560ce95 --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/20260502-auction-pass-history.ts @@ -0,0 +1,96 @@ +interface MigrationCollection { + find(filter: Record): { + limit(limit: number): AsyncIterable; + }; + bulkWrite( + writes: Array<{ + updateOne: { + filter: { _id: unknown }; + update: { $set: Record }; + }; + }>, + options: { ordered: boolean }, + ): Promise; +} + +interface MigrationDb { + collection(name: string): MigrationCollection; +} + +interface MigrationOptions { + dryRun?: boolean; + limit?: number; +} + +interface MigrationStats { + scannedAuctions: number; + changedAuctions: number; +} + +type AnyDoc = Record & { _id: unknown }; + +export async function migrateAuctionPassHistory( + db: MigrationDb, + options: MigrationOptions = {}, +): Promise { + const dryRun = options.dryRun ?? true; + const stats: MigrationStats = { + scannedAuctions: 0, + changedAuctions: 0, + }; + const writes: Array<{ + updateOne: { + filter: { _id: unknown }; + update: { $set: Record }; + }; + }> = []; + + for await (const doc of db.collection('auction').find({}).limit(options.limit ?? 0)) { + stats.scannedAuctions += 1; + const set: Record = {}; + let changed = false; + + if (!Array.isArray(doc.passedQueue)) { + set.passedQueue = []; + changed = true; + } + if (typeof doc.auctionRound !== 'number') { + set.auctionRound = 1; + changed = true; + } + if (typeof doc.topTierThreshold !== 'string') { + set.topTierThreshold = 'NONE'; + changed = true; + } + + const order = Array.isArray(doc.order) + ? doc.order.map((player) => { + if (!isRecord(player) || typeof player.passCount === 'number') { + return player; + } + changed = true; + return { ...player, passCount: 0 }; + }) + : []; + if (changed && order.length > 0) set.order = order; + if (!changed) continue; + + stats.changedAuctions += 1; + writes.push({ + updateOne: { + filter: { _id: doc._id }, + update: { $set: set }, + }, + }); + } + + if (!dryRun && writes.length > 0) { + await db.collection('auction').bulkWrite(writes, { ordered: false }); + } + + return stats; +} + +function isRecord(value: unknown): value is Record { + return Boolean(value && typeof value === 'object' && !Array.isArray(value)); +} diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index fa19e17f..ef2781e6 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -97,14 +97,32 @@ export type AuctionPhase = | 'presenting' | 'bidding' | 'sold' + | 'passed' | 'complete'; export const AUCTION_PHASES: AuctionPhase[] = [ 'waiting', 'presenting', 'bidding', 'sold', + 'passed', 'complete', ]; +export const AUCTION_TOP_TIER_THRESHOLDS = [ + 'NONE', + 'EMERALD', + 'DIAMOND', + 'MASTER', +] as const; +export type AuctionTopTierThreshold = + (typeof AUCTION_TOP_TIER_THRESHOLDS)[number]; +export type AuctionActionType = + | 'start' + | 'open-bidding' + | 'bid' + | 'sold' + | 'passed' + | 'next' + | 'complete'; export interface MongooseTimestamps { createdAt: Date; @@ -479,6 +497,7 @@ export interface AuctionPlayerSnapshot { tiers: TierInfo[]; masteries: ChampionMasteryEntry[]; recentStatsSummary?: RiotRecentStatsSummary; + passCount: number; } export interface AuctionTeamMember { @@ -506,6 +525,8 @@ export interface Auction extends MongooseTimestamps { phase: AuctionPhase; teams: AuctionTeam[]; order: AuctionPlayerSnapshot[]; + passedQueue: AuctionPlayerSnapshot[]; + auctionRound: number; currentIndex: number; bids: AuctionBid[]; currentBid: number; @@ -513,12 +534,26 @@ export interface Auction extends MongooseTimestamps { maxTimerSeconds: number; currentDeadline?: Date; initialPoints: number; + topTierThreshold: AuctionTopTierThreshold; startedAt?: Date; completedAt?: Date; } export type AuctionDocument = HydratedDocument; +export interface AuctionHistoryEntry extends MongooseTimestamps { + auctionId: mongoose.Types.ObjectId; + matchId: mongoose.Types.ObjectId; + sequence: number; + action: AuctionActionType; + actorUserId?: mongoose.Types.ObjectId; + snapshotBefore: Record; + takenAt: Date; +} + +export type AuctionHistoryEntryDocument = + HydratedDocument; + // ===== Sub-schemas ===== const PositionPreferenceSubSchema = new Schema( { @@ -1194,6 +1229,7 @@ const AuctionPlayerSnapshotSubSchema = new Schema( default: [], }, recentStatsSummary: { type: RiotRecentStatsSummarySubSchema }, + passCount: { type: Number, required: true, default: 0 }, }, { _id: false }, ); @@ -1251,6 +1287,12 @@ export const AuctionSchema = new Schema( required: true, default: [], }, + passedQueue: { + type: [AuctionPlayerSnapshotSubSchema], + required: true, + default: [], + }, + auctionRound: { type: Number, required: true, default: 1, min: 1 }, currentIndex: { type: Number, required: true, default: 0 }, bids: { type: [AuctionBidSubSchema], required: true, default: [] }, currentBid: { type: Number, required: true, default: 0 }, @@ -1258,6 +1300,12 @@ export const AuctionSchema = new Schema( maxTimerSeconds: { type: Number, required: true, default: 30 }, currentDeadline: { type: Date, required: false }, initialPoints: { type: Number, required: true, default: 1000 }, + topTierThreshold: { + type: String, + enum: AUCTION_TOP_TIER_THRESHOLDS, + required: true, + default: 'NONE', + }, startedAt: { type: Date, required: false }, completedAt: { type: Date, required: false }, }, @@ -1267,6 +1315,38 @@ export const AuctionSchema = new Schema( }, ); +const AuctionHistoryEntrySchema = new Schema( + { + auctionId: { + type: Schema.Types.ObjectId, + ref: 'auction', + required: true, + index: true, + }, + matchId: { + type: Schema.Types.ObjectId, + ref: 'match', + required: true, + index: true, + }, + sequence: { type: Number, required: true, min: 1 }, + action: { + type: String, + enum: ['start', 'open-bidding', 'bid', 'sold', 'passed', 'next', 'complete'], + required: true, + }, + actorUserId: { type: Schema.Types.ObjectId, ref: 'user', required: false }, + snapshotBefore: { type: Schema.Types.Mixed, required: true }, + takenAt: { type: Date, required: true, default: Date.now }, + }, + { + timestamps: true, + collection: 'auctionHistory', + }, +); + +AuctionHistoryEntrySchema.index({ auctionId: 1, sequence: -1 }); + export const tournamentModelDefinitions: ModelDefinition[] = [ { name: 'identity', schema: IdentitySchema, schemaName: 'identity' }, { name: 'community', schema: CommunitySchema, schemaName: 'community' }, @@ -1284,6 +1364,11 @@ export const tournamentModelDefinitions: ModelDefinition[] = [ }, { name: 'match', schema: MatchSchema, schemaName: 'match' }, { name: 'auction', schema: AuctionSchema, schemaName: 'auction' }, + { + name: 'auctionHistory', + schema: AuctionHistoryEntrySchema, + schemaName: 'auctionHistory', + }, ]; export interface TournamentModelTypes { @@ -1295,4 +1380,5 @@ export interface TournamentModelTypes { legacyImportJob: LegacyImportJob; match: Match; auction: Auction; + auctionHistory: AuctionHistoryEntry; } 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 3ee99897..425d81da 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.ts @@ -91,6 +91,14 @@ export class TournamentResultService { return result; } + public async cancelPolling( + matchOrId: MatchDocument | mongoose.Types.ObjectId, + ): Promise { + const match = await this.loadMatch(matchOrId); + match.resultPollState = undefined; + await match.save(); + } + public async processPollJob(job: PollTournamentResultJob): Promise { const MatchModel = await this.connectionService.getModel('match'); const TournamentCodeModel = diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts index 7f4ab7e1..5847a73c 100644 --- a/apps/web/src/api/hooks.ts +++ b/apps/web/src/api/hooks.ts @@ -10,6 +10,7 @@ import { } from '../lib/auth/msal.config'; import type { ApiAuction, + ApiAuctionHistoryEntry, ApiChampionStatsResponse, ApiCommunity, ApiEnqueueRefreshResult, @@ -133,6 +134,42 @@ export function useAuction( }); } +export function useAuctionHistory( + matchId: string | undefined, + communityId = DEFAULT_COMMUNITY_ID, + options: { enabled?: boolean; refetchInterval?: number | false } = {}, +) { + return useQuery({ + queryKey: ['auction-history', communityId, matchId ?? null], + queryFn: () => + apiFetch( + `/communities/${communityId}/matches/${matchId}/auction/history`, + ), + enabled: Boolean(communityId && matchId && (options.enabled ?? true)), + retry: false, + refetchInterval: options.refetchInterval, + }); +} + +export function useUndoAuction(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: ({ + matchId, + sequence, + }: { + matchId: string; + sequence: number; + }) => + apiFetch( + `/communities/${communityId}/matches/${matchId}/auction/undo`, + { + method: 'POST', + body: JSON.stringify({ sequence }), + }, + ), + }); +} + export function useCreateMatch(communityId = DEFAULT_COMMUNITY_ID) { return useMutation({ mutationFn: (body: MatchMutationRequest) => diff --git a/apps/web/src/api/mappers.ts b/apps/web/src/api/mappers.ts index 64f69af7..90e81a23 100644 --- a/apps/web/src/api/mappers.ts +++ b/apps/web/src/api/mappers.ts @@ -85,6 +85,7 @@ export interface MatchDetailView { } export interface AuctionPlayerView extends ParticipantView { + passCount: number; masteries: { championId: number; level: number; @@ -118,6 +119,8 @@ export interface AuctionStateView { currentPlayerIndex: number; totalPlayers: number; auctionOrder: AuctionPlayerView[]; + passedQueue: AuctionPlayerView[]; + auctionRound: number; bids: { teamIndex: number; amount: number; @@ -235,6 +238,7 @@ function mapAuctionPlayerToView( mainPosition, subPosition, profileIconId: player.profileIconId, + passCount: player.passCount ?? 0, masteries: player.masteries.slice(0, 5).map((mastery) => ({ championId: mastery.championId, level: mastery.championLevel, @@ -281,11 +285,13 @@ function mapAuctionTeamToView( (participant ? { ...participant, + passCount: 0, masteries: [], recentStats: createEmptyRecentStatsView(), } : { ...createFallbackParticipant(member.userId), + passCount: 0, masteries: [], recentStats: createEmptyRecentStatsView(), }); @@ -464,6 +470,7 @@ export function mapApiAuctionToAuctionState( .map((participant) => [participant.userId, participant]), ); const auctionOrder = auction.order.map(mapAuctionPlayerToView); + const passedQueue = (auction.passedQueue ?? []).map(mapAuctionPlayerToView); const auctionPlayerLookup = new Map( auctionOrder.map((player) => [player.userId, player]), ); @@ -499,6 +506,8 @@ export function mapApiAuctionToAuctionState( currentPlayerIndex, totalPlayers, auctionOrder, + passedQueue, + auctionRound: auction.auctionRound ?? 1, bids: auction.bids.map((bid) => ({ teamIndex: bid.teamIndex, amount: bid.amount, diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index 1ae5d95a..4adafc49 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -12,7 +12,13 @@ export type AuctionPhase = | 'presenting' | 'bidding' | 'sold' + | 'passed' | 'complete'; +export type AuctionTopTierThreshold = + | 'NONE' + | 'EMERALD' + | 'DIAMOND' + | 'MASTER'; export type CommunityRole = 'owner' | 'admin' | 'member'; export interface ApiPositionPreference { @@ -226,6 +232,7 @@ export interface ApiAuctionPlayerSnapshot { tiers: ApiTierInfo[]; masteries: ApiChampionMasteryEntry[]; recentStatsSummary?: ApiRiotRecentStatsSummary; + passCount: number; } export interface ApiAuctionTeamMember { @@ -254,6 +261,8 @@ export interface ApiAuction { phase: AuctionPhase; teams: ApiAuctionTeam[]; order: ApiAuctionPlayerSnapshot[]; + passedQueue: ApiAuctionPlayerSnapshot[]; + auctionRound: number; currentIndex: number; bids: ApiAuctionBid[]; currentBid: number; @@ -261,12 +270,27 @@ export interface ApiAuction { maxTimerSeconds: number; currentDeadline?: string; initialPoints: number; + topTierThreshold: AuctionTopTierThreshold; startedAt?: string; completedAt?: string; createdAt: string; updatedAt: string; } +export interface ApiAuctionHistoryEntry { + sequence: number; + action: + | 'start' + | 'open-bidding' + | 'bid' + | 'sold' + | 'passed' + | 'next' + | 'complete'; + actionLabel: string; + takenAt: string; +} + export interface ApiIdentity { id: string; entraOid: string; diff --git a/apps/web/src/pages/AuctionPage.tsx b/apps/web/src/pages/AuctionPage.tsx index b80c418e..81885208 100644 --- a/apps/web/src/pages/AuctionPage.tsx +++ b/apps/web/src/pages/AuctionPage.tsx @@ -1,867 +1,957 @@ -import { useState } from "react"; -import { ChevronDown, ChevronUp, ClipboardCheck, Copy } from "lucide-react"; -import { Link, useParams } from "react-router"; +import { useEffect, useMemo, useRef, useState } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { Link, useParams } from 'react-router'; import { + useAuction, + useAuctionHistory, useDdragonManifest, useMatch, - useUserHistoryProfile, -} from "../api/hooks"; -import { formatKoreanDate, formatTierLabel } from "../api/mappers"; + useMe, + useUndoAuction, +} from '../api/hooks'; +import { + formatTierLabel, + getTierColorToken, + mapApiAuctionToAuctionState, + type AuctionStateView, +} from '../api/mappers'; +import { useAuctionSocket } from '../api/useAuctionSocket'; +import { + DEFAULT_COMMUNITY_ID, + setDevCaptainTeamIndex, + useDevCaptainTeamIndex, +} from '../config'; +import { ApiError } from '../lib/api'; +import { + championDisplayName, + championIconUrl, + profileIconUrl, +} from '../lib/ddragon'; +import { + positionIcon, + positionLabel, + teamIndexColorClasses, + teamIndexLabel, +} from '../lib/league'; import type { - ApiMatch, - ApiMatchGameResult, - ApiMatchParticipant, - ApiTierInfo, - MatchGameMode, + ApiAuction, + ApiRiotLaneStats, Position, - TeamSide, - TournamentCodeSlotView, -} from "../api/types"; -import { DEFAULT_COMMUNITY_ID } from "../config"; -import { profileIconUrl } from "../lib/ddragon"; -import { positionLabel, sideShortLabel, teamIndexLabel } from "../lib/league"; +} from '../api/types'; -const GAME_MODE_LABEL: Record = { - pair: "페어 매치", - bracket: "토너먼트", - "round-robin": "리그전", +type CaptainRole = { + teamIndex: number; }; -function cn(...classes: Array) { - return classes.filter(Boolean).join(" "); +function formatPoints(value: number) { + return value.toLocaleString(); } -function resultBadgeClass(won: boolean) { - return won - ? "border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-300" - : "border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-300"; +function relativeTime(dateLike: string) { + const seconds = Math.max( + 0, + Math.floor((Date.now() - new Date(dateLike).getTime()) / 1000), + ); + if (seconds < 60) return `${seconds}초 전`; + const minutes = Math.floor(seconds / 60); + if (minutes < 60) return `${minutes}분 전`; + const hours = Math.floor(minutes / 60); + if (hours < 24) return `${hours}시간 전`; + return `${Math.floor(hours / 24)}일 전`; } -function sideBadgeClass(side: TeamSide) { - return side === "blue" - ? "border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300" - : "border-rose-500/30 bg-rose-500/10 text-rose-700 dark:text-rose-300"; -} - -function captainName( - team: ApiMatch["teams"][number] | undefined, - participantByUserId: Map, +function isCurrentBidder( + currentBidder: AuctionStateView['currentBidder'], + team: Pick, ) { - if (!team?.captainUserId) return undefined; - return participantByUserId.get(team.captainUserId)?.gameName; + return currentBidder?.teamIndex === team.teamIndex; } -function tierByQueue(tiers: ApiTierInfo[], queueType: string) { - return tiers.find((tier) => tier.queueType === queueType); +function getAuctionUpdatedAt(auction: ApiAuction | null | undefined) { + if (!auction) return 0; + return Date.parse(auction.updatedAt ?? auction.createdAt ?? '') || 0; } -function normalizeRank(rank: string | undefined) { - switch (rank) { - case "I": - return "1"; - case "II": - return "2"; - case "III": - return "3"; - case "IV": - return "4"; - default: - return rank; - } +function pickLatestAuction( + socketAuction: ApiAuction | null, + queryAuction: ApiAuction | undefined, +) { + if (!socketAuction) return queryAuction ?? null; + if (!queryAuction) return socketAuction; + return getAuctionUpdatedAt(queryAuction) > getAuctionUpdatedAt(socketAuction) + ? queryAuction + : socketAuction; } -function formatRankTooltip(tier: ApiTierInfo | undefined) { - if (!tier) return "언랭크"; - - const highTier = ["MASTER", "GRANDMASTER", "CHALLENGER"].includes(tier.tier); - const normalizedTier = { - ...tier, - rank: normalizeRank(tier.rank) ?? tier.rank, - }; - - const label = highTier - ? formatTierLabel({ ...normalizedTier, leaguePoints: 0 }) - : formatTierLabel(normalizedTier); - - return `${label} - ${tier.leaguePoints}LP`; -} - -function formatRankBadge(tier: ApiTierInfo | undefined) { - if (!tier) return "U"; - - const tierInitial = - tier.tier === "GRANDMASTER" ? "GM" : tier.tier.slice(0, 1); - const rank = normalizeRank(tier.rank); - - return rank ? `${tierInitial}${rank}` : tierInitial; -} - -function rankBadgeClass(tier: ApiTierInfo | undefined) { - switch (tier?.tier) { - case "CHALLENGER": - return "border-amber-500/60 bg-amber-100 text-amber-900 dark:border-amber-400/40 dark:bg-amber-400/20 dark:text-amber-200"; - case "GRANDMASTER": - return "border-red-500/60 bg-red-100 text-red-800 dark:border-red-400/40 dark:bg-red-400/20 dark:text-red-200"; - case "MASTER": - return "border-fuchsia-500/60 bg-fuchsia-100 text-fuchsia-800 dark:border-fuchsia-400/40 dark:bg-fuchsia-400/20 dark:text-fuchsia-200"; - case "DIAMOND": - return "border-cyan-500/60 bg-cyan-100 text-cyan-800 dark:border-cyan-400/40 dark:bg-cyan-400/20 dark:text-cyan-200"; - case "EMERALD": - return "border-emerald-500/60 bg-emerald-100 text-emerald-800 dark:border-emerald-400/40 dark:bg-emerald-400/20 dark:text-emerald-200"; - case "PLATINUM": - return "border-teal-500/60 bg-teal-100 text-teal-800 dark:border-teal-400/40 dark:bg-teal-400/20 dark:text-teal-200"; - case "GOLD": - return "border-amber-500/70 bg-amber-100 text-amber-900 dark:border-yellow-400/40 dark:bg-yellow-400/20 dark:text-yellow-200"; - case "SILVER": - return "border-slate-400/60 bg-slate-100 text-slate-700 dark:border-slate-300/40 dark:bg-slate-300/15 dark:text-slate-200"; - case "BRONZE": - return "border-orange-600/60 bg-orange-100 text-orange-800 dark:border-orange-500/40 dark:bg-orange-500/20 dark:text-orange-200"; - case "IRON": - return "border-stone-500/60 bg-stone-100 text-stone-700 dark:border-stone-400/40 dark:bg-stone-400/15 dark:text-stone-300"; - default: - return "border-base-content/25 bg-base-content/5 text-base-content/55"; - } -} - -function RankBadge({ tier }: { tier?: ApiTierInfo }) { - const tooltip = formatRankTooltip(tier); +const AUCTION_MAX_TEAM_SIZE = 5; +const LANE_ROWS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP']; +const POSITION_TO_RIOT_LANE = { + TOP: 'TOP', + JGL: 'JUNGLE', + MID: 'MIDDLE', + ADC: 'BOTTOM', + SUP: 'UTILITY', +} as const; +function PosBadge({ pos }: { pos: Position }) { return ( - - - {formatRankBadge(tier)} - + + + {positionLabel[pos]} ); } -function QueueRankCell({ - label, - tier, -}: { - label: "SOLO" | "FLEX"; - tier?: ApiTierInfo; -}) { +function TimerBar({ timer, maxTimer }: { timer: number; maxTimer: number }) { + const pct = maxTimer > 0 ? (timer / maxTimer) * 100 : 0; + const urgent = timer <= 5; + return ( - - - {label} - - - +
+
+
); } -function ParticipantLine({ - participant, - assignedPosition, - isCaptain, +function getWinRate(stats: ApiRiotLaneStats) { + return stats.games > 0 ? Math.round((stats.wins / stats.games) * 100) : 0; +} + +function getWinRateClass(winRate: number) { + if (winRate >= 55) return 'text-blue-400'; + if (winRate >= 50) return 'text-base-content'; + return 'text-red-400'; +} + +function formatKdaRatio(stats: ApiRiotLaneStats) { + if (stats.avgDeaths === 0) return 'Perfect'; + return ((stats.avgKills + stats.avgAssists) / stats.avgDeaths).toFixed(2); +} + +function RecentSoloStats({ + player, }: { - participant?: ApiMatchParticipant; - assignedPosition?: Position; - isCaptain?: boolean; + player: NonNullable; }) { - const { data: ddragon } = useDdragonManifest(); - const profileQuery = useUserHistoryProfile( - participant?.userId, - DEFAULT_COMMUNITY_ID, - ); + const primaryStats = player.recentStats.primary; - const name = participant?.gameName ?? "알 수 없는 참가자"; - const tag = participant?.tagLine ?? "----"; - const tiers = profileQuery.data?.tiers ?? []; - - const soloTier = - tierByQueue(tiers, "RANKED_SOLO_5x5") ?? - (participant?.tier?.queueType === "RANKED_SOLO_5x5" - ? participant.tier - : undefined); - const flexTier = tierByQueue(tiers, "RANKED_FLEX_SR"); - const positionText = assignedPosition ? positionLabel[assignedPosition] : "-"; - - const content = ( - <> -
- -
- -
-
- - {name} - - {isCaptain && ( - - 팀장 - - )} -
- -
- #{tag} -
- -
- - {positionText} - - - -
-
- -
- {positionText} -
- -
- -
- -
- -
- - ); - - const className = - "grid grid-cols-[auto_minmax(0,1fr)] items-center gap-3 border-b border-base-content/5 px-3 py-2.5 last:border-b-0 sm:grid-cols-[auto_minmax(0,1fr)_56px_86px_86px]"; - - if (participant?.userId) { + if (!primaryStats) { return ( - - {content} - +
+

+ 최근 솔로랭크 +

+
+ 최근 솔로랭크 기록이 없습니다 +
+
); } - return
{content}
; -} + const primaryWinRate = getWinRate(primaryStats); + const primaryKdaRatio = formatKdaRatio(primaryStats); -function TeamMemberScoutLine({ - isCaptain, - member, - participant, -}: { - isCaptain?: boolean; - member: ApiMatch["teams"][number]["members"][number]; - participant?: ApiMatchParticipant; -}) { return ( - - ); -} - -function MemberListHeader({ - title, - subtitle, - trailing, -}: { - title: string; - subtitle?: string; - trailing?: string; -}) { - return ( -
-
+
+
-
- {title} +

+ 최근 솔로랭크 +

+
+ + {positionLabel[player.mainPosition]} + + {player.recentStats.primarySource === 'overall' ? ( + + 전체 기준 + + ) : null}
- {subtitle && ( -
- {subtitle} -
- )}
- - {trailing && ( -
- {trailing} -
- )} +
+ {primaryWinRate}% +
-
-
-
소환사
-
라인
-
솔로
-
자유
+
+
+ 전적 + + {primaryStats.wins}W{' '} + {primaryStats.losses}L + +
+
+ KDA + + {primaryStats.avgKills}/{primaryStats.avgDeaths}/{primaryStats.avgAssists} + = 3 ? 'text-emerald-400' : 'text-base-content/50'}`} + > + ({primaryKdaRatio}) + + +
+
+ 분당 CS + + {primaryStats.avgCsPerMin} + +
+
+ +
+ {LANE_ROWS.map((position) => { + const laneStats = + player.recentStats.byLane[POSITION_TO_RIOT_LANE[position]]; + const isMainLane = position === player.mainPosition; + + return ( +
+ + {positionLabel[position]} + + {laneStats && laneStats.games > 0 ? ( + + {laneStats.wins}W {laneStats.losses}L · {laneStats.avgKills}/ + {laneStats.avgDeaths}/{laneStats.avgAssists} ·{' '} + {laneStats.avgCsPerMin} CS/min + + ) : ( + — + )} +
+ ); + })}
); } -function TeamVersusPanel({ - align = "left", - captain, - label, - name, - tone = "normal", +function TeamPanel({ + team, + isActive, + isLeft, }: { - align?: "left" | "right"; - captain?: string; - label: string; - name: string; - tone?: "primary" | "normal"; + team: AuctionStateView['teams'][number]; + isActive: boolean; + isLeft: boolean; }) { + const { data: ddragon } = useDdragonManifest(); + const tone = teamIndexColorClasses(team.teamIndex); + const teamSize = team.members.length + 1; + const isFull = teamSize >= AUCTION_MAX_TEAM_SIZE; + return (
-
- {label} -
- {name} + className={`absolute ${isLeft ? 'left-0' : 'right-0'} top-0 bottom-0 w-0.5 ${tone.bar}`} + /> +
+
+
+ + {teamIndexLabel(team.teamIndex, team.name)} + + + 팀장: {team.captainName} + +
+ + {formatPoints(team.points)}P + +
+
+ + 팀장 포함 {teamSize}/{AUCTION_MAX_TEAM_SIZE} + + {isFull && 정원 완료} +
- {captain && ( -
- 팀장 {captain} + +
+ {team.members.length === 0 ? ( +
+ 아직 멤버가 없습니다 +
+ ) : ( + team.members.map((member) => ( +
+ +
+ +
+
+ + {member.summonerName} + +
+ + + + {member.cost} + +
+ )) + )} + + {Array.from({ + length: Math.max(0, AUCTION_MAX_TEAM_SIZE - 1 - team.members.length), + }).map((_, index) => ( +
+
+ — +
+ ))} +
+
+ ); +} + +function PlayerSpotlight({ + state, +}: { + state: AuctionStateView; +}) { + const { data: ddragon } = useDdragonManifest(); + const player = state.currentPlayer; + if (!player) return null; + + return ( +
+
+
+ + + +
+
+ + {player.summonerName} + + + #{player.tag} + +
+
+ {formatTierLabel(player.tier)} +
+
+ + + {' '} + {positionLabel[player.subPosition]} + +
+
+
+
+ +
+
+

+ 숙련도 높은 챔피언 +

+
+ {player.masteries.length > 0 ? ( + player.masteries.map((mastery) => { + const iconUrl = championIconUrl(ddragon, mastery.championId); + const displayName = + championDisplayName(ddragon, mastery.championId) ?? + String(mastery.championId); + return ( +
+
+ {iconUrl ? ( + {displayName} + ) : null} +
+
+
+ {displayName} +
+
+ Lv.{mastery.level} · {(mastery.points / 1000).toFixed(0)}K +
+
+
+ ); + }) + ) : ( +
+ 숙련도 데이터가 없습니다. +
+ )} +
+
+ + +
+ + {(state.phase === 'bidding' || state.phase === 'sold') && ( +
+
+ + {state.phase === 'sold' ? '낙찰가' : '현재 입찰가'} + +
+ {state.currentBidder && ( + + {teamIndexLabel(state.currentBidder.teamIndex)} + + )} + + {state.currentBid > 0 ? formatPoints(state.currentBid) : '—'} + +
+
+
+ )} + {state.phase === 'passed' && ( +
+ + 유찰{' '} + {state.auctionRound === 1 + ? '— 마지막에 다시 등장합니다' + : '— 강제 배정 대상'} +
)}
); } -function UpcomingGameCard({ - expanded, - game, - isNext, - onToggle, - participantByUserId, - parsedTeamIndex, - slot, - teamByIndex, +function BidControls({ + state, + captainRole, + onBid, }: { - expanded: boolean; - game?: ApiMatchGameResult; - isNext?: boolean; - onToggle: () => void; - participantByUserId: Map; - parsedTeamIndex: number; - slot: TournamentCodeSlotView; - teamByIndex: Map; + state: AuctionStateView; + captainRole: CaptainRole | null; + onBid: (teamIndex: number, amount: number) => void; }) { - const [copied, setCopied] = useState(false); + const [bidAmount, setBidAmount] = useState(100); + const minBid = state.currentBid + 10; + const activeTeam = captainRole + ? state.teams.find((team) => team.teamIndex === captainRole.teamIndex) + : null; + const activeTeamSize = activeTeam ? activeTeam.members.length + 1 : 0; + const isActiveTeamFull = activeTeamSize >= AUCTION_MAX_TEAM_SIZE; - const opponentIndex = - slot.teamAIndex === parsedTeamIndex ? slot.teamBIndex : slot.teamAIndex; + useEffect(() => { + setBidAmount(Math.max(minBid, Math.ceil(minBid / 10) * 10)); + }, [state.currentBid, minBid]); - const ourTeam = teamByIndex.get(parsedTeamIndex); - const opponentTeam = teamByIndex.get(opponentIndex); + if (state.phase !== 'bidding') return null; - const ourTeamName = teamIndexLabel(parsedTeamIndex, ourTeam?.name); - const opponentTeamName = teamIndexLabel(opponentIndex, opponentTeam?.name); - - const ourCaptainName = captainName(ourTeam, participantByUserId); - const opponentCaptainName = captainName(opponentTeam, participantByUserId); - - const opponentMembers = opponentTeam?.members ?? []; - const finished = Boolean(game?.winnerTeamIndex); - const won = finished && game?.winnerTeamIndex === parsedTeamIndex; - - const ourSide: TeamSide = - slot.teamAIndex === parsedTeamIndex ? "blue" : "red"; - - async function handleCopy() { - if (!slot.code) return; - - try { - await navigator.clipboard.writeText(slot.code); - setCopied(true); - window.setTimeout(() => setCopied(false), 1500); - } catch { - setCopied(false); - } + if (!activeTeam) { + return ( +
+ 관전자 모드입니다. 우측 상단에서 조작자 역할을 선택하면 입찰할 수 있습니다. +
+ ); } + const presets = [50, 100, 150, 200, 300, 500]; + return ( -
  • -
    -
    - +
    + {presets.map((preset) => ( + + ))} + + setBidAmount(Math.max(minBid, Number(event.target.value))) + } + min={minBid} + disabled={isActiveTeamFull} + className="w-24 text-xs px-2 py-1 border border-base-content/10 bg-transparent text-base-content tabular-nums text-right focus:outline-none focus:border-primary/30" + /> +
    + +
    + ); +} - - {sideShortLabel(ourSide)} - +function BidLog({ bids }: { bids: AuctionStateView['bids'] }) { + const endRef = useRef(null); - {finished && ( + useEffect(() => { + endRef.current?.scrollIntoView({ behavior: 'smooth' }); + }, [bids.length]); + + if (bids.length === 0) return null; + + return ( +
    +
    + + 입찰 기록 + +
    +
    + {bids.map((bid, index) => ( +
    - {won ? "승리" : "패배"} + {teamIndexLabel(bid.teamIndex)} + + → + + {formatPoints(bid.amount)}P - )} -
    - - -
    - -
    - - -
    - - VS - -
    - - -
    - -
    -
    -
    -
    - 토너먼트 코드 -
    -
    - 클라이언트에 붙여넣어 게임에 입장하세요. -
    - - {slot.code && ( - - )} -
    - - {slot.code ? ( - - {slot.code} - - ) : ( -
    - 발급 대기 -
    - )} + ))} +
    - - {expanded && ( -
    - - - {opponentMembers.length > 0 ? ( -
    - {opponentMembers.map((member) => ( - - ))} -
    - ) : ( -
    - 상대팀 멤버 정보가 아직 없습니다. -
    - )} -
    - )} - - {finished && game?.riotMatchId && ( -
    - {game.riotMatchId} -
    - )} -
  • +
    ); } -function TeamGameCardsSection({ - defaultExpandedGameNumber, - emptyMessage, - gameByNumber, - isPreTeamBuilt, - match, - participantByUserId, - parsedTeamIndex, - teamByIndex, - slots, - title, -}: { - defaultExpandedGameNumber?: number | null; - emptyMessage: string; - gameByNumber: Map; - isPreTeamBuilt?: boolean; - match: ApiMatch; - participantByUserId: Map; - parsedTeamIndex: number; - teamByIndex: Map; - slots: TournamentCodeSlotView[]; - title: string; -}) { - const formatted = formatKoreanDate(match.scheduledAt); - const [expandedGameNumber, setExpandedGameNumber] = useState( - defaultExpandedGameNumber ?? null, - ); - const nextGameNumber = defaultExpandedGameNumber ?? null; - - return ( -
    -
    -
    -

    - {title} -

    -

    - 팀별 경기 진행 상황과 입장 정보를 확인합니다. -

    -
    - -
    -
    - {formatted.date} {formatted.time} -
    -
    - {GAME_MODE_LABEL[match.gameMode]} -
    -
    -
    - -
    - {isPreTeamBuilt ? ( -
    - 팀 빌딩이 끝나면 일정이 표시됩니다. -
    - ) : slots.length === 0 ? ( -
    - {emptyMessage} -
    - ) : ( -
      - {slots.map((slot) => ( - - setExpandedGameNumber((current) => - current === slot.gameNumber ? null : slot.gameNumber, - ) - } - participantByUserId={participantByUserId} - parsedTeamIndex={parsedTeamIndex} - slot={slot} - teamByIndex={teamByIndex} - /> - ))} -
    - )} -
    -
    - ); -} - -function buildFinishedSlot( - game: ApiMatchGameResult, - slotByGameNumber: Map, -): TournamentCodeSlotView { - const slot = slotByGameNumber.get(game.gameNumber); - - return { - gameNumber: game.gameNumber, - teamAIndex: game.blueTeamIndex, - teamBIndex: game.redTeamIndex, - code: slot?.code ?? null, - expiresAt: slot?.expiresAt ?? null, - state: slot?.state ?? "used", - riotMatchId: slot?.riotMatchId ?? game.riotMatchId, - }; -} - -export default function MatchTeamProgressPage() { - const { id, teamIndex } = useParams(); - const parsedTeamIndex = Number(teamIndex); +export default function AuctionPage() { + const { id } = useParams(); + const queryClient = useQueryClient(); + const meQuery = useMe(); + const currentUser = + meQuery.data?.memberships.find( + (membership) => membership.community?._id === DEFAULT_COMMUNITY_ID, + )?.user ?? null; + const canManageAuction = + import.meta.env.DEV || + currentUser?.role === 'owner' || + currentUser?.role === 'admin'; const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); + const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID, { + refetchInterval: 5000, + }); + const historyQuery = useAuctionHistory(id, DEFAULT_COMMUNITY_ID, { + enabled: canManageAuction, + refetchInterval: 3000, + }); + const undoMutation = useUndoAuction(DEFAULT_COMMUNITY_ID); + const socket = useAuctionSocket(id); + const captainTeamIndex = useDevCaptainTeamIndex(); + const [now, setNow] = useState(() => Date.now()); + const [assignedPosition, setAssignedPosition] = useState('MID'); + + useEffect(() => { + const timer = window.setInterval(() => setNow(Date.now()), 1000); + return () => window.clearInterval(timer); + }, []); + + const liveAuction = pickLatestAuction(socket.auction, auctionQuery.data); + const auctionState = + liveAuction && matchQuery.data + ? mapApiAuctionToAuctionState(liveAuction, matchQuery.data, new Date(now)) + : null; + const availableTeamIndexes = useMemo(() => { + const indexes = new Set((auctionState?.teams ?? []).map((team) => team.teamIndex)); + return [...indexes].sort((left, right) => left - right); + }, [auctionState?.teams]); + const captainRole: CaptainRole | null = + captainTeamIndex === null + ? null + : { + teamIndex: captainTeamIndex, + }; + + useEffect(() => { + if (auctionState?.currentPlayer) { + setAssignedPosition(auctionState.currentPlayer.mainPosition); + } + }, [auctionState?.currentPlayer?.id]); + + useEffect(() => { + if (availableTeamIndexes.length === 0) return; + if (captainTeamIndex !== null && !availableTeamIndexes.includes(captainTeamIndex)) { + setDevCaptainTeamIndex(availableTeamIndexes[0]); + } + }, [availableTeamIndexes, captainTeamIndex]); if (!DEFAULT_COMMUNITY_ID) { return ( -
    - `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. +
    + + `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. +
    ); } - if (matchQuery.isLoading) { + if (matchQuery.isLoading || (auctionQuery.isLoading && !socket.auction)) { return ( -
    - 팀 진행 정보를 불러오는 중... +
    + 경매를 연결하는 중...
    ); } - if ( - !Number.isInteger(parsedTeamIndex) || - parsedTeamIndex < 1 || - !matchQuery.data - ) { + if (auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404 && !socket.auction) { return ( -
    -

    팀 정보를 찾을 수 없습니다

    - - 내전 상세로 +
    +

    경매가 아직 시작되지 않았습니다

    + + 내전 상세로 돌아가기
    ); } - const match = matchQuery.data; - const team = match.teams.find((item) => item.teamIndex === parsedTeamIndex); - - const participantByUserId = new Map( - match.participants.map((participant) => [participant.userId, participant]), - ); - - const slotByGameNumber = new Map( - (match.tournamentCodes ?? []).map((slot) => [slot.gameNumber, slot]), - ); - - const codes = (match.tournamentCodes ?? []).filter( - (slot) => - slot.teamAIndex === parsedTeamIndex || - slot.teamBIndex === parsedTeamIndex, - ); - - const upcomingSlots = [...codes].sort( - (left, right) => left.gameNumber - right.gameNumber, - ); - - const teamByIndex = new Map( - match.teams.map((item) => [item.teamIndex, item]), - ); - - const gameByNumber = new Map( - (match.result?.games ?? []).map((game) => [game.gameNumber, game]), - ); - - const isPreTeamBuilt = - match.status === "recruiting" || (match.teams ?? []).length === 0; - - const teamGames = (match.result?.games ?? []).filter( - (game) => - game.blueTeamIndex === parsedTeamIndex || - game.redTeamIndex === parsedTeamIndex, - ); - - const finishedSlots = teamGames - .filter((game) => Boolean(game.winnerTeamIndex)) - .map((game) => buildFinishedSlot(game, slotByGameNumber)) - .sort((left, right) => left.gameNumber - right.gameNumber); - - const activeSlots = upcomingSlots.filter( - (slot) => !gameByNumber.get(slot.gameNumber)?.winnerTeamIndex, - ); - - if (!team) { + if (!auctionState || !matchQuery.data) { return ( -
    -

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

    -

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

    - - 내전 상세로 - +
    + + 경매 상태를 불러오지 못했습니다. +
    ); } - const captainIsInMembers = team.members.some( - (member) => member.userId === team.captainUserId, - ); + const phaseLabel: Record = { + waiting: '경매 준비 중...', + presenting: '다음 선수 등장', + bidding: '입찰 진행 중', + sold: '낙찰!', + passed: '유찰 — 다음 선수로', + complete: '경매 완료', + }; + const errorMessage = + socket.error ?? + (auctionQuery.error instanceof Error ? auctionQuery.error.message : null); + + function handleUndo(sequence: number) { + if (!id) return; + if (!window.confirm(`${sequence}번 액션 직전으로 되돌릴까요?`)) return; + undoMutation.mutate( + { matchId: id, sequence }, + { + onSuccess: async () => { + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: ['auction', DEFAULT_COMMUNITY_ID, id], + }), + queryClient.invalidateQueries({ + queryKey: ['auction-history', DEFAULT_COMMUNITY_ID, id], + }), + queryClient.invalidateQueries({ + queryKey: ['match', DEFAULT_COMMUNITY_ID, id], + }), + ]); + }, + }, + ); + } + + const undoPanel = canManageAuction ? ( +
    +
    + 되돌리기 (Undo) +
    +
    + {historyQuery.data?.length ? ( + historyQuery.data.map((entry) => ( + + )) + ) : ( +
    + 기록이 없습니다 +
    + )} +
    +
    + ) : null; return ( -
    +
    - ← 내전 상세로 + + + + 내전 상세로 -
    -
    -
    -
    - 팀 진행 페이지 -
    -

    - {teamIndexLabel(team.teamIndex, team.name)} -

    -

    - 다가오는 경기 일정, 토너먼트 코드, 상대팀 정보를 한곳에서 - 확인합니다. -

    -
    + {errorMessage && ( +
    + {errorMessage} +
    + )} -
    -
    - 다음 경기 -
    -
    - {activeSlots[0] - ? `${activeSlots[0].gameNumber}경기` - : "남은 경기 없음"} -
    + {undoMutation.error instanceof Error && ( +
    + {undoMutation.error.message} +
    + )} + +
    +
    +

    + 경매 팀빌딩 +

    +

    + {Math.min(auctionState.currentPlayerIndex + 1, Math.max(auctionState.totalPlayers, 1))} /{' '} + {auctionState.totalPlayers} 선수 +

    +
    +
    +
    + + {phaseLabel[auctionState.phase]} + + {auctionState.phase === 'bidding' && ( + + {auctionState.timer}s + + )} +
    +
    + 소켓: {socket.connectionStatus} + {/* 임시 운영용: 로그인/권한 확인 없이 조작자 역할을 선택할 수 있게 열어둔다. */} +
    - + {auctionState.phase === 'bidding' && ( + + )} - +
    +
    + {auctionState.teams.map((team) => ( + + ))} +
    -
    - +
    + {auctionState.phase === 'complete' ? ( + <> +
    +
    + 경매 완료 +
    +
    + 모든 선수가 팀에 배정되었습니다. +
    + + 결과 확인 + +
    + {undoPanel} + + ) : ( + <> + - {!captainIsInMembers && team.captainUserId && ( - - )} + {auctionState.phase === 'sold' && auctionState.currentBidder && ( +
    + {teamIndexLabel(auctionState.currentBidder.teamIndex)} 낙찰 + {' '}— {formatPoints(auctionState.currentBid)}P +
    + )} - {team.members.map((member) => ( - - ))} -
    + + socket.placeBid({ teamIndex, amount }) + } + /> + + + {canManageAuction && ( +
    +
    + Auction Controls +
    + {auctionState.phase === 'presenting' && ( + + )} + {auctionState.phase === 'bidding' && ( +
    + + +
    + )} + {(auctionState.phase === 'sold' || + auctionState.phase === 'passed') && ( + + )} +
    + )} + {undoPanel} + + )} +
    +
    ); } diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index 40cf88c4..aaa337fb 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -29,6 +29,7 @@ import { teamIndexLabel, } from '../lib/league'; import type { + AuctionTopTierThreshold, ApiMatchParticipant, Position, TeamSide, @@ -839,9 +840,11 @@ export default function MatchDetailPage() { )?.user ?? null; const canUseMemberActions = Boolean(currentUser || authUserId); const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID); - const [captainSelections, setCaptainSelections] = useState>( - {}, - ); + const [captainSelections, setCaptainSelections] = useState< + Record + >({}); + const [topTierThreshold, setTopTierThreshold] = + useState('NONE'); const pollTournamentResultMutation = usePollTournamentResult( DEFAULT_COMMUNITY_ID, ); @@ -877,10 +880,13 @@ export default function MatchDetailPage() { captains: buildCaptainSlots(matchQuery.data?.participants ?? []).map( (slot) => ({ teamIndex: slot.teamIndex, - userId: captainSelections[captainSlotKey(slot)], + userId: captainSelections[captainSlotKey(slot)]?.userId, + initialPoints: + captainSelections[captainSlotKey(slot)]?.initialPoints ?? 1000, }), ), initialPoints: 1000, + topTierThreshold, maxTimerSeconds: 30, }), }), @@ -919,19 +925,23 @@ export default function MatchDetailPage() { } setCaptainSelections((current) => { - const next: Record = {}; + const next: Record = {}; const usedUserIds = new Set(); for (const slot of slots) { const key = captainSlotKey(slot); - const currentUserId = current[key]; + const currentSelection = current[key]; + const currentUserId = currentSelection?.userId; const currentIsValid = currentUserId && participants.some((participant) => participant.userId === currentUserId) && !usedUserIds.has(currentUserId); if (currentIsValid) { - next[key] = currentUserId; + next[key] = { + userId: currentUserId, + initialPoints: currentSelection?.initialPoints ?? 1000, + }; usedUserIds.add(currentUserId); continue; } @@ -939,7 +949,10 @@ export default function MatchDetailPage() { const fallback = participants.find( (participant) => !usedUserIds.has(participant.userId), ); - next[key] = fallback?.userId ?? ''; + next[key] = { + userId: fallback?.userId ?? '', + initialPoints: currentSelection?.initialPoints ?? 1000, + }; if (fallback) usedUserIds.add(fallback.userId); } @@ -990,8 +1003,8 @@ export default function MatchDetailPage() { ); const captainSlots = buildCaptainSlots(matchQuery.data.participants); const selectedCaptainIds = captainSlots - .map((slot) => captainSelections[captainSlotKey(slot)]) - .filter(Boolean); + .map((slot) => captainSelections[captainSlotKey(slot)]?.userId) + .filter((userId): userId is string => Boolean(userId)); const hasUniqueCaptainSelections = selectedCaptainIds.length === captainSlots.length && new Set(selectedCaptainIds).size === selectedCaptainIds.length; @@ -1120,41 +1133,71 @@ export default function MatchDetailPage() {
    {captainSlots.map((slot) => { const key = captainSlotKey(slot); - const currentValue = captainSelections[key] ?? ''; + const currentSelection = captainSelections[key]; + const currentValue = currentSelection?.userId ?? ''; return ( ); })} @@ -1164,6 +1207,23 @@ export default function MatchDetailPage() { 경매를 시작하려면 최소 10명이 필요합니다.
    )} +