This commit is contained in:
dahyeon committed 2026-04-24 13:40:39 -07:00
1 parent a197185ad0
commit 30dfb7ce58
27 files changed
+1584 -45

No files matched your search

@@ -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();
}
}
}