.
This commit is contained in:
1 parent
a197185ad0
commit
30dfb7ce58
27 files changed
+1584
-45
No files matched your search
@@ -0,0 +1,134 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Param,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
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()
|
||||
public async getAuction(
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
) {
|
||||
return this.auctionService.getByMatchId(matchId);
|
||||
}
|
||||
|
||||
// 공개 — 팀장 2명만 쓸 엔드포인트(트러스트 기반, 10명 동시 관전).
|
||||
@Post('open-bidding')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
public async openBidding(
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
) {
|
||||
return this.auctionService.openBidding(matchId);
|
||||
}
|
||||
|
||||
@Post('bids')
|
||||
@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')
|
||||
@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')
|
||||
@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,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuctionController } from './auction.controller';
|
||||
import { AuctionService } from './auction.service';
|
||||
|
||||
@Module({
|
||||
controllers: [AuctionController],
|
||||
providers: [AuctionService],
|
||||
exports: [AuctionService],
|
||||
})
|
||||
export class AuctionModule {}
|
||||
@@ -0,0 +1,265 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
AuctionDocument,
|
||||
AuctionPlayerSnapshot,
|
||||
Position,
|
||||
TeamSide,
|
||||
} from '../global/database/schema';
|
||||
|
||||
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) {}
|
||||
|
||||
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 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.',
|
||||
);
|
||||
}
|
||||
|
||||
const nonCaptainPuuids = new Set<string>();
|
||||
const playerUsers = await UserModel.find({
|
||||
_id: {
|
||||
$in: match.participants
|
||||
.filter((p) => !captainUserIds.some((cid) => cid.equals(p.userId)))
|
||||
.map((p) => p.userId),
|
||||
},
|
||||
});
|
||||
const userById = new Map(playerUsers.map((u) => [u._id.toString(), u]));
|
||||
|
||||
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';
|
||||
await match.save();
|
||||
|
||||
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;
|
||||
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.');
|
||||
}
|
||||
|
||||
auction.currentBid = params.amount;
|
||||
auction.currentBidder = params.side;
|
||||
auction.bids.push({
|
||||
side: params.side,
|
||||
amount: params.amount,
|
||||
bidderUserId: params.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.');
|
||||
|
||||
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';
|
||||
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;
|
||||
}
|
||||
await auction.save();
|
||||
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') {
|
||||
match.status = 'recruiting';
|
||||
await match.save({ session });
|
||||
}
|
||||
await session.commitTransaction();
|
||||
} catch (err) {
|
||||
await session.abortTransaction();
|
||||
throw err;
|
||||
} finally {
|
||||
await session.endSession();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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';
|
||||
}
|
||||
Reference in new issue
Block a user