feat(api): implement auction workflows

This commit is contained in:
dahyeon committed 2026-04-16 03:28:00 +09:00
1 parent b62a3d5edb
commit 7c4e968c5d
6 files changed
+1267

No files matched your search

@@ -0,0 +1,140 @@
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 { PlaceBidDto, SoldDto, StartAuctionDto } from './dto/auction.dto';
@Controller('communities/:communityId/matches/:matchId/auction')
export class AuctionController {
constructor(private readonly auctionService: AuctionService) {}
@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) => ({
side: c.side,
userId: new mongoose.Types.ObjectId(c.userId),
})),
initialPoints: body.initialPoints ?? 1000,
maxTimerSeconds: body.maxTimerSeconds ?? 30,
});
}
@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,
side: body.side,
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);
}
@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.');
}
}
}
@@ -0,0 +1,354 @@
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,
TeamSide,
UserDocument,
} from '../global/database/schema';
import { AuctionService } from './auction.service';
interface JoinAuctionPayload {
matchId: string;
}
interface BidPayload {
side: TeamSide;
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<string, NodeJS.Timeout>();
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),
side: payload.side,
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<void> {
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<void> {
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;
}
private 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();
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);
}
}, 1000);
this.roomTimers.set(matchId, timer);
}
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 emitError(socket: Socket, message: string) {
socket.emit('error', { message });
}
private serializeAuction(auction: AuctionDocument) {
return JSON.parse(JSON.stringify(auction));
}
}
@@ -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 {}
@@ -0,0 +1,262 @@
import mongoose from 'mongoose';
import { AuctionService } from './auction.service';
describe('AuctionService', () => {
function createService(models: Record<string, unknown>) {
const connectionService = {
getModel: jest.fn((name: string) => models[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),
};
return {
service: new AuctionService(
connectionService as never,
enrichmentService as never,
tournamentCodeService as never,
tournamentResultService as never,
),
connectionService,
tournamentCodeService,
tournamentResultService,
};
}
function createFullTeam(side: 'blue' | 'red') {
return {
side,
captainUserId: new mongoose.Types.ObjectId(),
points: 100,
members: Array.from({ length: 4 }, () => ({
userId: new mongoose.Types.ObjectId(),
assignedPosition: 'MID',
cost: 10,
})),
};
}
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('blue'), createFullTeam('red')],
currentBid: 10,
save: jest.fn().mockResolvedValue(undefined),
};
const { service } = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
await expect(
service.placeBid({
matchId,
side: 'blue',
amount: 20,
}),
).rejects.toThrow('Team already has maximum members.');
expect(auction.save).not.toHaveBeenCalled();
});
it('rejects sold confirmation when the winning team is already full', async () => {
const matchId = new mongoose.Types.ObjectId();
const auction = {
phase: 'bidding',
currentBidder: 'blue',
currentBid: 20,
currentIndex: 0,
order: [
{
userId: new mongoose.Types.ObjectId(),
preferredPositions: [{ position: 'ADC', priority: 1 }],
},
],
teams: [createFullTeam('blue'), createFullTeam('red')],
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('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: [
{
side: 'blue',
captainUserId: blueCaptainId,
points: 970,
members: [
{
userId: blueMemberId,
assignedPosition: 'ADC',
cost: 30,
},
],
},
{
side: 'red',
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 } = 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([
{
side: 'blue',
name: '블루팀',
captainUserId: blueCaptainId,
members: [
{
userId: blueCaptainId,
assignedPosition: 'TOP',
cost: 0,
},
{
userId: blueMemberId,
assignedPosition: 'ADC',
cost: 30,
},
],
},
{
side: 'red',
name: '레드팀',
captainUserId: redCaptainId,
members: [
{
userId: redCaptainId,
assignedPosition: 'MID',
cost: 0,
},
{
userId: redMemberId,
assignedPosition: 'JGL',
cost: 60,
},
],
},
]);
});
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: [
{
side: 'blue',
name: '블루팀',
members: [],
},
],
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.save).toHaveBeenCalledWith({ session });
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,436 @@
import {
BadRequestException,
Injectable,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import {
AuctionDocument,
AuctionPlayerSnapshot,
AuctionTeam,
MatchTeamMember,
Position,
TeamSide,
} from '../global/database/schema';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
import { TournamentResultService } from '../tournament-result/tournament-result.service';
const AUCTION_MAX_TEAM_SIZE = 5;
interface StartAuctionParams {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
captains: { side: TeamSide; userId: mongoose.Types.ObjectId }[];
initialPoints: number;
maxTimerSeconds: number;
}
interface PlaceBidParams {
matchId: mongoose.Types.ObjectId;
side: TeamSide;
amount: number;
bidderUserId?: mongoose.Types.ObjectId;
}
interface MarkSoldParams {
matchId: mongoose.Types.ObjectId;
assignedPosition?: Position;
}
@Injectable()
export class AuctionService {
constructor(
private readonly connectionService: ConnectionService,
private readonly enrichmentService: RiotAccountEnrichmentService,
private readonly tournamentCodeService: TournamentCodeService,
private readonly tournamentResultService: TournamentResultService,
) {}
public async start(params: StartAuctionParams): Promise<AuctionDocument> {
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 captainUserIds = params.captains.map((c) => c.userId);
if (captainUserIds[0].equals(captainUserIds[1])) {
throw new BadRequestException('Captains must be different users.');
}
const captainParticipants = match.participants.filter((p) =>
captainUserIds.some((cid) => cid.equals(p.userId)),
);
if (captainParticipants.length !== 2) {
throw new BadRequestException(
'Both captains must be participants of the match.',
);
}
if (
match.participants.length >
params.captains.length * AUCTION_MAX_TEAM_SIZE
) {
throw new BadRequestException(
'Auction supports up to 5 members per team including captains.',
);
}
const basePlayerUsers = await UserModel.find({
_id: {
$in: match.participants
.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 enrichTargets = basePlayerUsers
.map((user) => ({
userId: user._id,
puuid: (user.riotAccounts.find((account) => account.isPrimary) ?? user.riotAccounts[0])
?.puuid,
}))
.filter((target): target is { userId: mongoose.Types.ObjectId; puuid: string } =>
typeof target.puuid === 'string' && target.puuid.length > 0,
);
await runWithConcurrency(enrichTargets, 3, async (target) => {
await this.enrichmentService.enrichRiotAccount({
userId: target.userId,
puuid: target.puuid,
options: {
force: false,
platform,
region,
},
});
});
const playerUsers = await UserModel.find({
_id: { $in: basePlayerUsers.map((user) => user._id) },
});
const userById = new Map(playerUsers.map((u) => [u._id.toString(), u]));
const nonCaptainPuuids = new Set<string>();
const order: AuctionPlayerSnapshot[] = [];
for (const participant of match.participants) {
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,
});
}
const auction = await AuctionModel.create({
matchId: params.matchId,
phase: 'presenting',
teams: params.captains.map((c) => ({
side: c.side,
captainUserId: c.userId,
points: params.initialPoints,
members: [],
})),
order,
currentIndex: 0,
bids: [],
currentBid: 0,
maxTimerSeconds: params.maxTimerSeconds,
initialPoints: params.initialPoints,
startedAt: new Date(),
});
match.status = 'team-built';
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
await match.save();
await this.tournamentCodeService.reserveForMatch(match);
await this.tournamentResultService.scheduleInitialPoll(match);
return auction;
}
public async getByMatchId(
matchId: mongoose.Types.ObjectId,
): Promise<AuctionDocument> {
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 openBidding(
matchId: mongoose.Types.ObjectId,
): Promise<AuctionDocument> {
const auction = await this.getByMatchId(matchId);
if (auction.phase !== 'presenting') {
throw new BadRequestException('Auction is not in presenting phase.');
}
auction.phase = 'bidding';
auction.currentBid = 0;
auction.currentBidder = undefined;
auction.currentDeadline = this.createDeadline(auction.maxTimerSeconds);
await auction.save();
return auction;
}
public async placeBid(params: PlaceBidParams): Promise<AuctionDocument> {
const auction = await this.getByMatchId(params.matchId);
if (auction.phase !== 'bidding') {
throw new BadRequestException('Auction is not in bidding phase.');
}
const team = auction.teams.find((t) => t.side === params.side);
if (!team) throw new BadRequestException('Unknown team side.');
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);
// 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다.
auction.currentBid = params.amount;
auction.currentBidder = params.side;
auction.currentDeadline = this.createDeadline(
this.resolveBidExtensionSeconds(auction),
);
auction.bids.push({
side: params.side,
amount: params.amount,
bidderUserId: team.captainUserId,
timestamp: new Date(),
});
await auction.save();
return auction;
}
public async markSold(params: MarkSoldParams): Promise<AuctionDocument> {
const auction = await this.getByMatchId(params.matchId);
if (auction.phase !== 'bidding') {
throw new BadRequestException('Auction is not in bidding phase.');
}
if (!auction.currentBidder || auction.currentBid <= 0) {
throw new BadRequestException('No bid to mark sold.');
}
const team = auction.teams.find((t) => t.side === auction.currentBidder);
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.');
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 next(
matchId: mongoose.Types.ObjectId,
): Promise<AuctionDocument> {
const auction = await this.getByMatchId(matchId);
if (auction.phase !== 'sold' && auction.phase !== 'presenting') {
throw new BadRequestException('Cannot advance from current phase.');
}
const nextIndex = auction.currentIndex + 1;
if (nextIndex >= auction.order.length) {
auction.phase = 'complete';
auction.completedAt = new Date();
} else {
auction.currentIndex = nextIndex;
auction.phase = 'presenting';
auction.currentBid = 0;
auction.currentBidder = 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<void> {
const AuctionModel = await this.connectionService.getModel('auction');
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 });
if (match.status === 'team-built') {
await this.tournamentCodeService.releaseFromMatch(match);
match.status = 'recruiting';
match.teams = [];
match.tournamentCodeIds = [];
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();
}
}
private createDeadline(secondsFromNow: number): Date {
return new Date(Date.now() + secondsFromNow * 1000);
}
private resolveBidExtensionSeconds(auction: AuctionDocument): number {
if (!auction.currentDeadline) {
return auction.maxTimerSeconds;
}
const remainingSeconds = Math.ceil(
(auction.currentDeadline.getTime() - Date.now()) / 1000,
);
return Math.max(5, 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<string>([team.captainUserId.toString()]);
for (const member of team.members) {
userIds.add(member.userId.toString());
}
return userIds.size;
}
private async syncMatchTeamsFromAuction(
auction: AuctionDocument,
): Promise<void> {
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 {
side: team.side,
name: this.resolveTeamName(team.side),
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 resolveTeamName(side: TeamSide): string {
return side === 'blue' ? '블루팀' : '레드팀';
}
}
async function runWithConcurrency<T>(
items: T[],
concurrency: number,
worker: (item: T) => Promise<void>,
): Promise<void> {
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);
}
@@ -0,0 +1,60 @@
import { Type } from 'class-transformer';
import {
ArrayMaxSize,
ArrayMinSize,
IsArray,
IsEnum,
IsInt,
IsMongoId,
IsOptional,
Min,
ValidateNested,
} from 'class-validator';
import { TEAM_SIDES } from '../../global/database/schema';
import type { TeamSide } from '../../global/database/schema';
class CaptainAssignmentDto {
@IsEnum(TEAM_SIDES)
side!: TeamSide;
@IsMongoId()
userId!: string;
}
export class StartAuctionDto {
@IsArray()
@ArrayMinSize(2)
@ArrayMaxSize(2)
@ValidateNested({ each: true })
@Type(() => CaptainAssignmentDto)
captains!: CaptainAssignmentDto[];
@IsOptional()
@IsInt()
@Min(1)
initialPoints?: number;
@IsOptional()
@IsInt()
@Min(5)
maxTimerSeconds?: number;
}
export class PlaceBidDto {
@IsEnum(TEAM_SIDES)
side!: TeamSide;
@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';
}