diff --git a/apps/api/src/modules/auction/auction.controller.ts b/apps/api/src/modules/auction/auction.controller.ts new file mode 100644 index 00000000..86acec54 --- /dev/null +++ b/apps/api/src/modules/auction/auction.controller.ts @@ -0,0 +1,189 @@ +import { + BadRequestException, + Body, + Controller, + Delete, + Get, + HttpCode, + HttpStatus, + Param, + Post, + UseGuards, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { Roles } from '../auth/roles.decorator'; +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 { 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, + private readonly auctionGateway: AuctionGateway, + ) {} + + @Post() + @Roles('admin', 'owner') + @UseGuards(RolesGuard) + public async startAuction( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Body() body: StartAuctionDto, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.auctionService.start({ + matchId, + communityId, + 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, + bidExtensionSeconds: body.bidExtensionSeconds ?? 5, + topTierThreshold: body.topTierThreshold ?? 'NONE', + manualTopTierUserIds: (body.manualTopTierUserIds ?? []).map( + (userId) => new mongoose.Types.ObjectId(userId), + ), + }); + } + + @Get() + @AllowPublicAccess() + public async getAuction( + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + ) { + return this.auctionService.getByMatchId(matchId); + } + + // 공개 — 팀장 2명만 쓸 엔드포인트(트러스트 기반, 10명 동시 관전). + @Post('open-bidding') + @AllowPublicAccess() + @HttpCode(HttpStatus.OK) + public async openBidding( + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + ) { + return this.auctionService.openBidding(matchId); + } + + @Post('bids') + @AllowPublicAccess() + @HttpCode(HttpStatus.OK) + public async placeBid( + @CurrentUser() currentUser: UserDocument | undefined, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Body() body: PlaceBidDto, + ) { + return this.auctionService.placeBid({ + matchId, + teamIndex: body.teamIndex, + amount: body.amount, + bidderUserId: this.resolveBidder(currentUser, body.bidderUserId), + }); + } + + @Post('sold') + @AllowPublicAccess() + @HttpCode(HttpStatus.OK) + public async markSold( + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Body() body: SoldDto, + ) { + return this.auctionService.markSold({ + matchId, + assignedPosition: body.assignedPosition, + }); + } + + @Post('next') + @AllowPublicAccess() + @HttpCode(HttpStatus.OK) + public async next( + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + ) { + 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) + @HttpCode(HttpStatus.NO_CONTENT) + public async resetAuction( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + ) { + this.assertSameCommunity(currentUser, communityId); + await this.auctionService.reset({ matchId, communityId }); + } + + private resolveBidder( + currentUser: UserDocument | undefined, + bodyBidder?: string, + ): mongoose.Types.ObjectId | undefined { + if (currentUser) return currentUser._id; + if (!bodyBidder) return undefined; + if (!mongoose.isValidObjectId(bodyBidder)) { + throw new BadRequestException('Invalid bidderUserId.'); + } + return new mongoose.Types.ObjectId(bodyBidder); + } + + private assertSameCommunity( + user: UserDocument, + communityId: mongoose.Types.ObjectId, + ): void { + if (!user.communityId.equals(communityId)) { + throw new BadRequestException('Different community.'); + } + } +} diff --git a/apps/api/src/modules/auction/auction.gateway.ts b/apps/api/src/modules/auction/auction.gateway.ts new file mode 100644 index 00000000..b868285b --- /dev/null +++ b/apps/api/src/modules/auction/auction.gateway.ts @@ -0,0 +1,385 @@ +import { Logger } from '@nestjs/common'; +import { + ConnectedSocket, + MessageBody, + OnGatewayConnection, + OnGatewayDisconnect, + SubscribeMessage, + WebSocketGateway, + WebSocketServer, +} from '@nestjs/websockets'; +import mongoose from 'mongoose'; +import type { JWTPayload } from 'jose'; +import { Namespace, Socket } from 'socket.io'; +import { AuthService } from '../auth/auth.service'; +import { IdentityService } from '../auth/identity.service'; +import { JwtService } from '../auth/jwt.service'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + AuctionDocument, + IdentityDocument, + Position, + UserDocument, +} from '../global/database/schema'; +import { AuctionService } from './auction.service'; + +interface JoinAuctionPayload { + matchId: string; +} + +interface BidPayload { + teamIndex: number; + amount: number; + bidderUserId?: string; +} + +interface SoldPayload { + assignedPosition?: Position; +} + +@WebSocketGateway({ + namespace: '/auction', + cors: { + origin: true, + credentials: true, + allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'], + }, +}) +export class AuctionGateway + implements OnGatewayConnection, OnGatewayDisconnect +{ + @WebSocketServer() + private server!: Namespace; + + private readonly logger = new Logger(AuctionGateway.name); + private readonly roomTimers = new Map(); + + constructor( + private readonly auctionService: AuctionService, + private readonly authService: AuthService, + private readonly jwtService: JwtService, + private readonly identityService: IdentityService, + private readonly connectionService: ConnectionService, + ) {} + + public async handleConnection(socket: Socket) { + try { + await this.authenticateSocket(socket); + this.logger.debug(`Auction client connected: ${socket.id}`); + } catch (err) { + this.logger.warn( + `Auction client authentication failed: ${ + err instanceof Error ? err.message : err + }`, + ); + socket.disconnect(true); + } + } + + public handleDisconnect(socket: Socket) { + const matchId = this.getSocketMatchId(socket); + if (!matchId) return; + this.maybeClearRoomTimer(matchId); + } + + @SubscribeMessage('join') + public async handleJoin( + @ConnectedSocket() socket: Socket, + @MessageBody() payload: JoinAuctionPayload, + ) { + if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) { + this.emitError(socket, 'Invalid matchId.'); + return; + } + + await socket.join(payload.matchId); + socket.data.matchId = payload.matchId; + + try { + await this.resolveSocketUserForMatch(socket, payload.matchId); + const auction = await this.auctionService.getByMatchId( + new mongoose.Types.ObjectId(payload.matchId), + ); + this.broadcastState(payload.matchId, auction); + } catch (error) { + this.emitKnownError(socket, error); + } + } + + @SubscribeMessage('bid') + public async handleBid( + @ConnectedSocket() socket: Socket, + @MessageBody() payload: BidPayload, + ) { + const matchId = this.requireJoinedMatchId(socket); + if (!matchId) return; + + const bidderUserId = this.resolveBidderUserId(socket, payload?.bidderUserId); + if (payload?.bidderUserId && !bidderUserId) { + this.emitError(socket, 'Invalid bidderUserId.'); + return; + } + + try { + const auction = await this.auctionService.placeBid({ + matchId: new mongoose.Types.ObjectId(matchId), + teamIndex: payload.teamIndex, + amount: payload.amount, + bidderUserId, + }); + this.broadcastState(matchId, auction); + } catch (error) { + this.emitKnownError(socket, error); + } + } + + @SubscribeMessage('open-bidding') + public async handleOpenBidding(@ConnectedSocket() socket: Socket) { + const matchId = this.requireJoinedMatchId(socket); + if (!matchId) return; + + try { + const auction = await this.auctionService.openBidding( + new mongoose.Types.ObjectId(matchId), + ); + this.broadcastState(matchId, auction); + } catch (error) { + this.emitKnownError(socket, error); + } + } + + @SubscribeMessage('sold') + public async handleSold( + @ConnectedSocket() socket: Socket, + @MessageBody() payload: SoldPayload, + ) { + const matchId = this.requireJoinedMatchId(socket); + if (!matchId) return; + + try { + const auction = await this.auctionService.markSold({ + matchId: new mongoose.Types.ObjectId(matchId), + assignedPosition: payload?.assignedPosition, + }); + this.broadcastState(matchId, auction); + } catch (error) { + this.emitKnownError(socket, error); + } + } + + @SubscribeMessage('next') + public async handleNext(@ConnectedSocket() socket: Socket) { + const matchId = this.requireJoinedMatchId(socket); + if (!matchId) return; + + try { + const auction = await this.auctionService.next( + new mongoose.Types.ObjectId(matchId), + ); + this.broadcastState(matchId, auction); + } catch (error) { + this.emitKnownError(socket, error); + } + } + + private requireJoinedMatchId(socket: Socket): string | null { + const matchId = this.getSocketMatchId(socket); + if (!matchId) { + this.emitError(socket, 'Join a match room before sending events.'); + return null; + } + return matchId; + } + + private getSocketMatchId(socket: Socket): string | undefined { + return typeof socket.data.matchId === 'string' + ? socket.data.matchId + : undefined; + } + + private resolveBidderUserId( + socket: Socket, + payloadBidderUserId?: string, + ): mongoose.Types.ObjectId | undefined { + const candidate = + payloadBidderUserId ?? + (socket.data.user as UserDocument | undefined)?._id.toString() ?? + this.readHandshakeUserId(socket); + if (!candidate || !mongoose.isValidObjectId(candidate)) { + return undefined; + } + return new mongoose.Types.ObjectId(candidate); + } + + private readHandshakeUserId(socket: Socket): string | undefined { + const authUserId = socket.handshake.auth['x-auth-user-id']; + if (typeof authUserId === 'string') return authUserId; + + const header = socket.handshake.headers['x-auth-user-id']; + return Array.isArray(header) ? header[0] : header; + } + + private async authenticateSocket(socket: Socket): Promise { + const fallback = await this.authService.resolveDevUserById( + this.readHandshakeUserId(socket), + ); + if (fallback) { + socket.data.user = fallback.user; + socket.data.identity = fallback.identity; + return; + } + + const token = this.readHandshakeToken(socket); + if (!token) { + // 임시 운영용: 경매 진행 중에는 로그인 없이도 관전/팀장 모드 선택/입찰을 허용한다. + return; + } + + const { payload } = await this.jwtService.verify( + token, + 'MICROSOFT_ENTRAID', + ); + socket.data.identity = await this.identityService.findOrCreateByOid({ + entraOid: this.requireStringClaim(payload, 'oid'), + tenantId: this.stringClaim(payload.tid), + email: + this.stringClaim(payload.preferred_username) ?? + this.stringClaim(payload.email), + displayName: this.stringClaim(payload.name), + }); + } + + private readHandshakeToken(socket: Socket): string | undefined { + const authToken = socket.handshake.auth.token; + if (typeof authToken === 'string' && authToken.trim()) { + return authToken.trim().replace(/^Bearer\s+/i, ''); + } + + const header = socket.handshake.headers.authorization; + const authorization = Array.isArray(header) ? header[0] : header; + if (authorization?.startsWith('Bearer ')) { + return authorization.slice('Bearer '.length).trim(); + } + return undefined; + } + + private async resolveSocketUserForMatch( + socket: Socket, + matchId: string, + ): Promise { + if (socket.data.user || !socket.data.identity) return; + + const MatchModel = await this.connectionService.getModel('match'); + const match = await MatchModel.findById(matchId).select({ + communityId: 1, + }); + if (!match) return; + + const UserModel = await this.connectionService.getModel('user'); + socket.data.user = await UserModel.findOne({ + communityId: match.communityId, + identityId: (socket.data.identity as IdentityDocument)._id, + }).exec(); + } + + private requireStringClaim(payload: JWTPayload, key: string): string { + const value = payload[key]; + if (typeof value !== 'string' || value.length === 0) { + throw new Error(`Token is missing ${key} claim.`); + } + return value; + } + + private stringClaim(value: unknown): string | undefined { + return typeof value === 'string' && value.length > 0 ? value : undefined; + } + + public broadcastState(matchId: string, auction: AuctionDocument) { + this.server.to(matchId).emit('state', this.serializeAuction(auction)); + this.syncRoomTimer(matchId, auction); + } + + private syncRoomTimer(matchId: string, auction: AuctionDocument) { + this.clearRoomTimer(matchId); + if (!auction.currentDeadline) return; + + 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(), + }); + + const timer = setInterval(() => { + this.server.to(matchId).emit('tick', { + deadline: deadlineIso, + serverTime: new Date().toISOString(), + }); + + 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; + this.clearRoomTimer(matchId); + } + + private clearRoomTimer(matchId: string) { + const timer = this.roomTimers.get(matchId); + if (!timer) return; + clearInterval(timer); + this.roomTimers.delete(matchId); + } + + private emitKnownError(socket: Socket, error: unknown) { + const message = + error instanceof Error ? error.message : 'Unexpected auction gateway error.'; + 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 }); + } + + private serializeAuction(auction: AuctionDocument) { + return JSON.parse(JSON.stringify(auction)); + } +} diff --git a/apps/api/src/modules/auction/auction.module.ts b/apps/api/src/modules/auction/auction.module.ts new file mode 100644 index 00000000..fbbb1ccd --- /dev/null +++ b/apps/api/src/modules/auction/auction.module.ts @@ -0,0 +1,15 @@ +import { Module } from '@nestjs/common'; +import { RiotModule } from '../riot/riot.module'; +import { TournamentCodeModule } from '../tournament-code/tournament-code.module'; +import { TournamentResultModule } from '../tournament-result/tournament-result.module'; +import { AuctionGateway } from './auction.gateway'; +import { AuctionController } from './auction.controller'; +import { AuctionService } from './auction.service'; + +@Module({ + imports: [RiotModule, TournamentCodeModule, TournamentResultModule], + controllers: [AuctionController], + providers: [AuctionService, AuctionGateway], + exports: [AuctionService], +}) +export class AuctionModule {} diff --git a/apps/api/src/modules/auction/auction.service.spec.ts b/apps/api/src/modules/auction/auction.service.spec.ts new file mode 100644 index 00000000..b423e7cf --- /dev/null +++ b/apps/api/src/modules/auction/auction.service.spec.ts @@ -0,0 +1,631 @@ +import mongoose from 'mongoose'; +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) => allModels[name]), + createSession: jest.fn(), + }; + const enrichmentService = { + enrichRiotAccount: jest.fn(), + }; + const tournamentCodeService = { + reserveForMatch: jest.fn().mockResolvedValue(undefined), + releaseFromMatch: jest.fn().mockResolvedValue(undefined), + }; + const tournamentResultService = { + scheduleInitialPoll: jest.fn().mockResolvedValue(null), + cancelPolling: jest.fn().mockResolvedValue(undefined), + }; + + return { + service: new AuctionService( + connectionService as never, + enrichmentService as never, + tournamentCodeService as never, + tournamentResultService as never, + ), + connectionService, + tournamentCodeService, + tournamentResultService, + auctionHistoryModel, + }; + } + + function createFullTeam(teamIndex: number) { + return { + teamIndex, + captainUserId: new mongoose.Types.ObjectId(), + points: 100, + members: Array.from({ length: 4 }, () => ({ + userId: new mongoose.Types.ObjectId(), + assignedPosition: 'MID', + cost: 10, + })), + }; + } + + afterEach(() => { + jest.useRealTimers(); + }); + + it('starts an auction without reserving tournament codes before teams are complete', async () => { + const matchId = new mongoose.Types.ObjectId(); + const communityId = new mongoose.Types.ObjectId(); + const userIds = Array.from( + { length: 10 }, + () => new mongoose.Types.ObjectId(), + ); + const participants = userIds.map((userId, index) => ({ + userId, + preferredPositions: [{ position: 'MID', priority: 1 }], + joinedAt: new Date(index), + excluded: false, + })); + const match = { + _id: matchId, + communityId, + participants, + status: 'recruiting', + teamBuiltAt: undefined, + save: jest.fn().mockResolvedValue(undefined), + }; + const users = userIds.slice(2).map((userId, index) => ({ + _id: userId, + riotAccounts: [ + { + puuid: `puuid-${index}`, + gameName: `Player${index}`, + tagLine: 'KR1', + profileIconId: index, + tiers: [], + championMasteries: [], + recentStatsSummary: undefined, + lastRefreshRequestedAt: new Date(), + isPrimary: true, + }, + ], + })); + const auction = { + _id: new mongoose.Types.ObjectId(), + matchId, + toObject: jest.fn().mockReturnValue({ matchId }), + }; + const { service, tournamentCodeService, tournamentResultService } = + createService({ + match: { + findById: jest.fn().mockResolvedValue(match), + }, + user: { + find: jest.fn().mockResolvedValue(users), + }, + auction: { + findOne: jest.fn().mockResolvedValue(null), + create: jest.fn().mockResolvedValue(auction), + }, + community: { + findById: jest.fn().mockReturnValue({ + select: jest.fn().mockReturnValue({ + lean: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ + riotPlatform: 'kr', + riotRegion: 'asia', + }), + }), + }), + }), + }, + }); + + await service.start({ + matchId, + communityId, + captains: [ + { teamIndex: 1, userId: userIds[0] }, + { teamIndex: 2, userId: userIds[1] }, + ], + initialPoints: 1000, + maxTimerSeconds: 30, + bidExtensionSeconds: 5, + topTierThreshold: 'NONE', + manualTopTierUserIds: [], + }); + + expect(match.status).toBe('team-built'); + expect(match.teamBuiltAt).toBeInstanceOf(Date); + expect(match.save).toHaveBeenCalledTimes(1); + expect(tournamentCodeService.reserveForMatch).not.toHaveBeenCalled(); + expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled(); + }); + + it('rejects bids when the team already has 5 members including captain', async () => { + const matchId = new mongoose.Types.ObjectId(); + const auction = { + phase: 'bidding', + teams: [createFullTeam(1), createFullTeam(2)], + currentBid: 10, + save: jest.fn().mockResolvedValue(undefined), + }; + const { service } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + }); + + await expect( + service.placeBid({ + matchId, + teamIndex: 1, + amount: 20, + }), + ).rejects.toThrow('Team already has maximum members.'); + expect(auction.save).not.toHaveBeenCalled(); + }); + + it('extends a short bid deadline using the configured bid extension seconds', async () => { + const now = new Date('2026-05-02T00:00:00.000Z'); + jest.useFakeTimers().setSystemTime(now); + + const matchId = new mongoose.Types.ObjectId(); + const captainUserId = new mongoose.Types.ObjectId(); + const auction = { + _id: new mongoose.Types.ObjectId(), + matchId, + phase: 'bidding', + teams: [ + { + teamIndex: 1, + captainUserId, + points: 1000, + members: [], + }, + ], + currentBid: 10, + currentDeadline: new Date(now.getTime() + 2000), + maxTimerSeconds: 30, + bidExtensionSeconds: 12, + bids: [], + save: jest.fn().mockResolvedValue(undefined), + toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }), + }; + const { service } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + }); + + await service.placeBid({ + matchId, + teamIndex: 1, + amount: 20, + }); + + expect(auction.currentDeadline).toEqual( + new Date(now.getTime() + 12000), + ); + expect(auction.save).toHaveBeenCalledTimes(1); + }); + + it('rejects sold confirmation when the winning team is already full', async () => { + const matchId = new mongoose.Types.ObjectId(); + const auction = { + phase: 'bidding', + currentBidderTeamIndex: 1, + currentBid: 20, + currentIndex: 0, + order: [ + { + userId: new mongoose.Types.ObjectId(), + preferredPositions: [{ position: 'ADC', priority: 1 }], + }, + ], + teams: [createFullTeam(1), createFullTeam(2)], + save: jest.fn().mockResolvedValue(undefined), + }; + const { service } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + }); + + await expect(service.markSold({ matchId })).rejects.toThrow( + 'Team already has maximum members.', + ); + 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(); + const redCaptainId = new mongoose.Types.ObjectId(); + const blueMemberId = new mongoose.Types.ObjectId(); + const redMemberId = new mongoose.Types.ObjectId(); + + const auction = { + matchId, + phase: 'sold', + currentIndex: 1, + order: [{ userId: blueMemberId }, { userId: redMemberId }], + teams: [ + { + teamIndex: 1, + captainUserId: blueCaptainId, + points: 970, + members: [ + { + userId: blueMemberId, + assignedPosition: 'ADC', + cost: 30, + }, + ], + }, + { + teamIndex: 2, + captainUserId: redCaptainId, + points: 940, + members: [ + { + userId: redMemberId, + assignedPosition: 'JGL', + cost: 60, + }, + ], + }, + ], + save: jest.fn().mockResolvedValue(undefined), + }; + const match = { + participants: [ + { + userId: blueCaptainId, + preferredPositions: [{ position: 'TOP', priority: 1 }], + }, + { + userId: redCaptainId, + preferredPositions: [{ position: 'MID', priority: 1 }], + }, + { + userId: blueMemberId, + preferredPositions: [{ position: 'ADC', priority: 1 }], + }, + { + userId: redMemberId, + preferredPositions: [{ position: 'JGL', priority: 1 }], + }, + ], + status: 'team-built', + teams: [], + save: jest.fn().mockResolvedValue(undefined), + }; + const { service, tournamentCodeService, tournamentResultService } = + createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + match: { + findById: jest.fn().mockResolvedValue(match), + }, + }); + + await service.next(matchId); + + expect(auction.phase).toBe('complete'); + expect(auction.completedAt).toBeInstanceOf(Date); + expect(auction.save).toHaveBeenCalledTimes(1); + expect(match.save).toHaveBeenCalledTimes(1); + expect(match.teams).toEqual([ + { + teamIndex: 1, + name: '1팀', + captainUserId: blueCaptainId, + members: [ + { + userId: blueCaptainId, + assignedPosition: 'TOP', + cost: 0, + }, + { + userId: blueMemberId, + assignedPosition: 'ADC', + cost: 30, + }, + ], + }, + { + teamIndex: 2, + name: '2팀', + captainUserId: redCaptainId, + members: [ + { + userId: redCaptainId, + assignedPosition: 'MID', + cost: 0, + }, + { + userId: redMemberId, + assignedPosition: 'JGL', + cost: 60, + }, + ], + }, + ]); + expect(tournamentCodeService.reserveForMatch).toHaveBeenCalledWith(match); + expect(tournamentResultService.scheduleInitialPoll).toHaveBeenCalledWith( + match, + ); + }); + + it('clears match teams when resetting an auction', async () => { + const matchId = new mongoose.Types.ObjectId(); + const communityId = 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 = { + deleteOne: jest.fn().mockResolvedValue(undefined), + }; + const match = { + communityId, + status: 'team-built', + teams: [ + { + teamIndex: 1, + name: '1팀', + members: [], + }, + ], + tournamentCodeIds: [new mongoose.Types.ObjectId()], + gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 2 }], + participants: [], + save: jest.fn().mockResolvedValue(undefined), + }; + const auctionFindOneQuery = { + session: jest.fn().mockResolvedValue(auction), + }; + const matchFindByIdQuery = { + session: jest.fn().mockResolvedValue(match), + }; + const { service, connectionService } = createService({ + auction: { + findOne: jest.fn().mockReturnValue(auctionFindOneQuery), + }, + match: { + findById: jest.fn().mockReturnValue(matchFindByIdQuery), + }, + }); + connectionService.createSession.mockResolvedValue(session); + + await service.reset({ matchId, communityId }); + + expect(match.status).toBe('recruiting'); + expect(match.teams).toEqual([]); + expect(match.tournamentCodeIds).toEqual([]); + expect(match.gameSchedule).toEqual([]); + 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 new file mode 100644 index 00000000..b4e587f1 --- /dev/null +++ b/apps/api/src/modules/auction/auction.service.ts @@ -0,0 +1,949 @@ +import { + BadRequestException, + Injectable, + InternalServerErrorException, + Logger, + NotFoundException, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { + AuctionActionType, + AuctionDocument, + AuctionPlayerSnapshot, + AuctionTeam, + AuctionTopTierThreshold, + MatchParticipant, + MatchTeamMember, + Position, + RiotAccount, +} from '../global/database/schema'; +import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; +import type { RiotPlatformRoute, RiotRegionalRoute } from '../riot/riot.types'; +import { TournamentCodeService } from '../tournament-code/tournament-code.service'; +import { TournamentResultService } from '../tournament-result/tournament-result.service'; + +const AUCTION_MAX_TEAM_SIZE = 5; +const AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY = 1; +const AUCTION_ENRICHMENT_COOLDOWN_MS = 3 * 60 * 60 * 1000; + +interface StartAuctionParams { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + captains: { + teamIndex: number; + userId: mongoose.Types.ObjectId; + initialPoints?: number; + }[]; + initialPoints: number; + maxTimerSeconds: number; + bidExtensionSeconds: number; + topTierThreshold: AuctionTopTierThreshold; + manualTopTierUserIds: mongoose.Types.ObjectId[]; +} + +interface PlaceBidParams { + matchId: mongoose.Types.ObjectId; + teamIndex: number; + amount: number; + bidderUserId?: mongoose.Types.ObjectId; +} + +interface MarkSoldParams { + matchId: mongoose.Types.ObjectId; + assignedPosition?: Position; +} + +export interface AuctionHistoryView { + sequence: number; + action: AuctionActionType; + actionLabel: string; + takenAt: Date; +} + +interface AuctionEnrichmentTarget { + userId: mongoose.Types.ObjectId; + puuid: string; +} + +@Injectable() +export class AuctionService { + private readonly logger = new Logger(AuctionService.name); + + constructor( + private readonly connectionService: ConnectionService, + private readonly enrichmentService: RiotAccountEnrichmentService, + private readonly tournamentCodeService: TournamentCodeService, + private readonly tournamentResultService: TournamentResultService, + ) {} + + public async start(params: StartAuctionParams): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const UserModel = await this.connectionService.getModel('user'); + const AuctionModel = await this.connectionService.getModel('auction'); + const CommunityModel = await this.connectionService.getModel('community'); + + const match = await MatchModel.findById(params.matchId); + 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 existing = await AuctionModel.findOne({ matchId: params.matchId }); + if (existing) { + 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; + if (params.captains.length !== expectedCaptainCount) { + throw new BadRequestException( + `Expected ${expectedCaptainCount} captains for ${desiredAuctionCount} participants.`, + ); + } + this.assertCaptainAssignments( + params.captains, + activeParticipants, + expectedCaptainCount, + ); + const captainUserIds = params.captains.map((c) => c.userId); + + const basePlayerUsers = await UserModel.find({ + _id: { + $in: activeParticipants + .filter((p) => !captainUserIds.some((cid) => cid.equals(p.userId))) + .map((p) => p.userId), + }, + }); + const community = await CommunityModel.findById(match.communityId) + .select({ riotPlatform: 1, riotRegion: 1 }) + .lean() + .exec(); + const platform = community?.riotPlatform ?? 'kr'; + const region = community?.riotRegion ?? 'asia'; + + const enrichCooldownCutoff = Date.now() - AUCTION_ENRICHMENT_COOLDOWN_MS; + const enrichTargets = basePlayerUsers.flatMap((user) => { + const account = + user.riotAccounts.find((entry) => entry.isPrimary) ?? user.riotAccounts[0]; + if (!account?.puuid) return []; + if (this.wasRecentlyRefreshed(account, enrichCooldownCutoff)) return []; + return [{ userId: user._id, puuid: account.puuid }]; + }); + + const userById = new Map(basePlayerUsers.map((u) => [u._id.toString(), u])); + + const nonCaptainPuuids = new Set(); + const order: AuctionPlayerSnapshot[] = []; + for (const participant of activeParticipants) { + if (captainUserIds.some((cid) => cid.equals(participant.userId))) { + continue; + } + const user = userById.get(participant.userId.toString()); + if (!user) continue; + const primary = + user.riotAccounts.find((a) => a.isPrimary) ?? user.riotAccounts[0]; + if (!primary) { + throw new BadRequestException( + `Participant ${user._id.toString()} has no Riot account.`, + ); + } + if (nonCaptainPuuids.has(primary.puuid)) continue; + nonCaptainPuuids.add(primary.puuid); + order.push({ + userId: user._id, + puuid: primary.puuid, + gameName: primary.gameName, + tagLine: primary.tagLine, + profileIconId: primary.profileIconId, + preferredPositions: participant.preferredPositions, + tiers: primary.tiers, + masteries: primary.championMasteries, + recentStatsSummary: primary.recentStatsSummary, + passCount: 0, + }); + } + const prioritizedOrder = this.applyTopTierPriority( + order, + params.topTierThreshold, + params.manualTopTierUserIds, + ); + + const auction = await AuctionModel.create({ + matchId: params.matchId, + phase: 'presenting', + teams: params.captains.map((c) => ({ + teamIndex: c.teamIndex, + captainUserId: c.userId, + points: c.initialPoints ?? params.initialPoints, + members: [], + })), + order: prioritizedOrder, + passedQueue: [], + auctionRound: 1, + currentIndex: 0, + bids: [], + currentBid: 0, + maxTimerSeconds: params.maxTimerSeconds, + bidExtensionSeconds: params.bidExtensionSeconds, + initialPoints: params.initialPoints, + topTierThreshold: params.topTierThreshold, + manualTopTierUserIds: + params.topTierThreshold === 'MANUAL' ? params.manualTopTierUserIds : [], + startedAt: new Date(), + }); + await this.recordSnapshot(auction, 'start'); + + match.status = 'team-built'; + match.teamBuiltAt = match.teamBuiltAt ?? new Date(); + await match.save(); + this.enqueueBackgroundOrderEnrichment({ + auctionId: auction._id, + targets: enrichTargets, + platform, + region, + }); + + return auction; + } + + public async getByMatchId( + matchId: mongoose.Types.ObjectId, + ): Promise { + const AuctionModel = await this.connectionService.getModel('auction'); + const auction = await AuctionModel.findOne({ matchId }); + if (!auction) throw new NotFoundException('Auction not found.'); + 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 { + const auction = await this.getByMatchId(matchId); + 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; + auction.currentDeadline = this.createDeadline(auction.maxTimerSeconds); + await auction.save(); + return auction; + } + + public async placeBid(params: PlaceBidParams): Promise { + const auction = await this.getByMatchId(params.matchId); + if (auction.phase !== 'bidding') { + throw new BadRequestException('Auction is not in bidding phase.'); + } + const team = this.findAuctionTeamByIndex(auction, params.teamIndex); + if (!team) throw new BadRequestException('Unknown team.'); + if (params.amount <= auction.currentBid) { + throw new BadRequestException('Bid must exceed current bid.'); + } + if (params.amount > team.points) { + throw new BadRequestException('Bid exceeds team points.'); + } + this.assertTeamHasSlot(team); + // 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다. + + await this.recordSnapshot(auction, 'bid', params.bidderUserId); + auction.currentBid = params.amount; + auction.currentBidderTeamIndex = params.teamIndex; + auction.currentDeadline = this.createDeadline( + this.resolveBidExtensionSeconds(auction), + ); + auction.bids.push({ + teamIndex: params.teamIndex, + amount: params.amount, + bidderUserId: team.captainUserId, + timestamp: new Date(), + }); + await auction.save(); + return auction; + } + + public async markSold(params: MarkSoldParams): Promise { + const auction = await this.getByMatchId(params.matchId); + if (auction.phase !== 'bidding') { + throw new BadRequestException('Auction is not in bidding phase.'); + } + if (!auction.currentBidderTeamIndex || auction.currentBid <= 0) { + throw new BadRequestException('No bid to mark sold.'); + } + const team = this.findAuctionTeamByIndex( + auction, + auction.currentBidderTeamIndex, + ); + if (!team) throw new BadRequestException('Winning team not found.'); + this.assertTeamHasSlot(team); + + 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, + assignedPosition: params.assignedPosition ?? preferredPrimary ?? 'MID', + cost: auction.currentBid, + }); + team.points -= auction.currentBid; + auction.phase = 'sold'; + auction.currentDeadline = undefined; + await auction.save(); + 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' && + 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) { + 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'; + auction.currentBid = 0; + auction.currentBidderTeamIndex = undefined; + } + auction.currentDeadline = undefined; + await auction.save(); + if (auction.phase === 'complete') { + await this.syncMatchTeamsFromAuction(auction); + } + return auction; + } + + public async reset(params: { + matchId: mongoose.Types.ObjectId; + 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(); + 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.'); + } + + 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'; + match.teams = []; + match.tournamentCodeIds = []; + match.gameSchedule = []; + match.participants.forEach((participant) => { + participant.excluded = false; + }); + match.teamBuiltAt = undefined; + match.result = undefined; + match.resultPollState = undefined; + await match.save({ session }); + } + await session.commitTransaction(); + } catch (err) { + await session.abortTransaction(); + throw err; + } finally { + await session.endSession(); + } + } + + 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, + manualTopTierUserIds: mongoose.Types.ObjectId[], + ): AuctionPlayerSnapshot[] { + if (threshold === 'NONE') return order; + if (threshold === 'MANUAL') { + const manualIds = new Set( + manualTopTierUserIds.map((userId) => userId.toString()), + ); + if (manualIds.size === 0) return order; + const selected = order.filter((snap) => + manualIds.has(snap.userId.toString()), + ); + const rest = order.filter( + (snap) => !manualIds.has(snap.userId.toString()), + ); + return [...selected, ...rest]; + } + + 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[] { + 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 }>, + expectedCaptainCount: number, + ): void { + const activeUserIds = new Set( + activeParticipants.map((participant) => participant.userId.toString()), + ); + const captainUserIds = new Set(); + const teamIndexes = new Set(); + + 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 ( + !Number.isInteger(captain.teamIndex) || + captain.teamIndex < 1 || + captain.teamIndex > expectedCaptainCount + ) { + throw new BadRequestException('Captain teamIndex is out of range.'); + } + if (teamIndexes.has(captain.teamIndex)) { + throw new BadRequestException('Duplicate captain team assignment.'); + } + teamIndexes.add(captain.teamIndex); + } + + for (let teamIndex = 1; teamIndex <= expectedCaptainCount; teamIndex += 1) { + if (!teamIndexes.has(teamIndex)) { + throw new BadRequestException('Each teamIndex needs one captain.'); + } + } + } + + private findAuctionTeamByIndex( + auction: AuctionDocument, + teamIndex: number, + ): AuctionTeam | undefined { + return auction.teams.find((team) => team.teamIndex === teamIndex); + } + + private createDeadline(secondsFromNow: number): Date { + return new Date(Date.now() + secondsFromNow * 1000); + } + + private resolveBidExtensionSeconds(auction: AuctionDocument): number { + const maxTimerSeconds = Math.max(5, auction.maxTimerSeconds ?? 30); + const bidExtensionSeconds = Math.max(0, auction.bidExtensionSeconds ?? 5); + const minimumRemainingSeconds = Math.min( + maxTimerSeconds, + bidExtensionSeconds, + ); + + if (!auction.currentDeadline) { + return maxTimerSeconds; + } + + const remainingSeconds = Math.ceil( + (auction.currentDeadline.getTime() - Date.now()) / 1000, + ); + return Math.min( + maxTimerSeconds, + Math.max(minimumRemainingSeconds, remainingSeconds), + ); + } + + private assertTeamHasSlot(team: AuctionTeam): void { + if (this.countTeamMembersIncludingCaptain(team) >= AUCTION_MAX_TEAM_SIZE) { + throw new BadRequestException('Team already has maximum members.'); + } + } + + private countTeamMembersIncludingCaptain(team: AuctionTeam): number { + const userIds = new Set([team.captainUserId.toString()]); + for (const member of team.members) { + userIds.add(member.userId.toString()); + } + return userIds.size; + } + + private async syncMatchTeamsFromAuction( + auction: AuctionDocument, + ): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const match = await MatchModel.findById(auction.matchId); + if (!match) throw new NotFoundException('Match not found.'); + + const participantByUserId = new Map( + match.participants.map((participant) => [ + participant.userId.toString(), + participant, + ]), + ); + + match.teams = auction.teams.map((team) => { + const captain = participantByUserId.get(team.captainUserId.toString()); + const members: MatchTeamMember[] = [ + { + userId: team.captainUserId, + assignedPosition: captain?.preferredPositions[0]?.position ?? 'MID', + cost: 0, + }, + ...team.members + .filter((member) => !member.userId.equals(team.captainUserId)) + .map((member) => ({ + userId: member.userId, + assignedPosition: member.assignedPosition, + cost: member.cost, + })), + ]; + + return { + teamIndex: team.teamIndex, + name: this.resolveTeamName(team.teamIndex), + captainUserId: team.captainUserId, + members, + }; + }); + match.status = 'team-built'; + match.teamBuiltAt = match.teamBuiltAt ?? new Date(); + await match.save(); + await this.tournamentCodeService.reserveForMatch(match); + await this.tournamentResultService.scheduleInitialPoll(match); + } + + private enqueueBackgroundOrderEnrichment(params: { + auctionId: mongoose.Types.ObjectId; + targets: AuctionEnrichmentTarget[]; + platform: RiotPlatformRoute; + region: RiotRegionalRoute; + }): void { + if (params.targets.length === 0) return; + + // 경매 시작 UX를 막지 않도록 Riot 최신화는 뒤에서 1명씩 천천히 수행한다. + void this.refreshOrderSnapshotsFromRiot(params).catch((error: unknown) => { + this.logger.warn( + `Auction background Riot refresh failed for ${params.auctionId.toString()}: ${ + error instanceof Error ? error.message : error + }`, + ); + }); + } + + private async refreshOrderSnapshotsFromRiot(params: { + auctionId: mongoose.Types.ObjectId; + targets: AuctionEnrichmentTarget[]; + platform: RiotPlatformRoute; + region: RiotRegionalRoute; + }): Promise { + const AuctionModel = await this.connectionService.getModel('auction'); + + this.logger.debug( + `Refreshing Riot snapshots for ${params.targets.length} auction players in background.`, + ); + + await runWithConcurrency( + params.targets, + AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY, + async (target) => { + try { + const result = await this.enrichmentService.enrichRiotAccount({ + userId: target.userId, + puuid: target.puuid, + options: { + force: false, + platform: params.platform, + region: params.region, + }, + }); + const account = result.account; + if (!account) return; + + await AuctionModel.updateOne( + { + _id: params.auctionId, + 'order.userId': target.userId, + }, + { + $set: { + 'order.$.gameName': account.gameName, + 'order.$.tagLine': account.tagLine, + 'order.$.profileIconId': account.profileIconId, + 'order.$.tiers': account.tiers, + 'order.$.masteries': account.championMasteries, + 'order.$.recentStatsSummary': account.recentStatsSummary, + updatedAt: new Date(), + }, + }, + ).exec(); + } catch (error: unknown) { + this.logger.warn( + `Failed to refresh auction Riot snapshot for ${target.puuid}: ${ + error instanceof Error ? error.message : error + }`, + ); + } + }, + ); + } + + private wasRecentlyRefreshed(account: RiotAccount, cutoff: number): boolean { + return this.getLatestRefreshAt(account) >= cutoff; + } + + private getLatestRefreshAt(account: RiotAccount): number { + const timestamps = [ + account.lastRefreshRequestedAt, + account.recentStatsFetchedAt, + account.championMasteriesFetchedAt, + account.matchIdsFetchedAt, + ...account.tiers.map((tier) => tier.fetchedAt), + ]; + + return timestamps.reduce((latest, value) => { + const timestamp = value instanceof Date ? value.getTime() : 0; + return Math.max(latest, timestamp); + }, 0); + } + + private resolveTeamName(teamIndex: number): string { + return `${teamIndex}팀`; + } +} + +async function runWithConcurrency( + items: T[], + concurrency: number, + worker: (item: T) => Promise, +): Promise { + if (items.length === 0) return; + + const queue = [...items]; + const runners = Array.from({ length: Math.min(concurrency, queue.length) }, async () => { + while (queue.length > 0) { + const item = queue.shift(); + if (item === undefined) return; + await worker(item); + } + }); + + await Promise.allSettled(runners); +} diff --git a/apps/api/src/modules/auction/dto/auction.dto.ts b/apps/api/src/modules/auction/dto/auction.dto.ts new file mode 100644 index 00000000..9c4e4b8e --- /dev/null +++ b/apps/api/src/modules/auction/dto/auction.dto.ts @@ -0,0 +1,93 @@ +import { Type } from 'class-transformer'; +import { + ArrayMaxSize, + ArrayMinSize, + IsArray, + IsEnum, + 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() + @Min(1) + teamIndex!: number; + + @IsMongoId() + userId!: string; + + @IsOptional() + @IsInt() + @Min(100) + @Max(100000) + initialPoints?: number; +} + +export class StartAuctionDto { + @IsArray() + @ArrayMinSize(2) + @ArrayMaxSize(16) + @ValidateNested({ each: true }) + @Type(() => CaptainAssignmentDto) + captains!: CaptainAssignmentDto[]; + + @IsOptional() + @IsInt() + @Min(100) + @Max(100000) + initialPoints?: number; + + @IsOptional() + @IsEnum(AUCTION_TOP_TIER_THRESHOLDS) + topTierThreshold?: AuctionTopTierThreshold; + + @IsOptional() + @IsArray() + @ArrayMaxSize(100) + @IsMongoId({ each: true }) + manualTopTierUserIds?: string[]; + + @IsOptional() + @IsInt() + @Min(5) + maxTimerSeconds?: number; + + @IsOptional() + @IsInt() + @Min(0) + bidExtensionSeconds?: number; +} + +export class PlaceBidDto { + @IsInt() + @Min(1) + teamIndex!: number; + + @IsInt() + @Min(1) + amount!: number; + + @IsOptional() + @IsMongoId() + bidderUserId?: string; +} + +export class SoldDto { + @IsOptional() + @IsEnum(['TOP', 'JGL', 'MID', 'ADC', 'SUP']) + assignedPosition?: 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP'; +} + +export class UndoAuctionDto { + @IsInt() + @Min(1) + sequence!: number; +}