.
This commit is contained in:
1 parent
fedca82c81
commit
3607e3a99c
13 files changed
+1838
-793
No files matched your search
@@ -18,11 +18,20 @@ import { RolesGuard } from '../auth/roles.guard';
|
||||
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||
import type { UserDocument } from '../global/database/schema';
|
||||
import { AuctionService } from './auction.service';
|
||||
import { PlaceBidDto, SoldDto, StartAuctionDto } from './dto/auction.dto';
|
||||
import { AuctionGateway } from './auction.gateway';
|
||||
import {
|
||||
PlaceBidDto,
|
||||
SoldDto,
|
||||
StartAuctionDto,
|
||||
UndoAuctionDto,
|
||||
} from './dto/auction.dto';
|
||||
|
||||
@Controller('communities/:communityId/matches/:matchId/auction')
|
||||
export class AuctionController {
|
||||
constructor(private readonly auctionService: AuctionService) {}
|
||||
constructor(
|
||||
private readonly auctionService: AuctionService,
|
||||
private readonly auctionGateway: AuctionGateway,
|
||||
) {}
|
||||
|
||||
@Post()
|
||||
@Roles('admin', 'owner')
|
||||
@@ -41,9 +50,11 @@ export class AuctionController {
|
||||
captains: body.captains.map((c) => ({
|
||||
teamIndex: c.teamIndex,
|
||||
userId: new mongoose.Types.ObjectId(c.userId),
|
||||
initialPoints: c.initialPoints,
|
||||
})),
|
||||
initialPoints: body.initialPoints ?? 1000,
|
||||
maxTimerSeconds: body.maxTimerSeconds ?? 30,
|
||||
topTierThreshold: body.topTierThreshold ?? 'NONE',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -103,6 +114,40 @@ export class AuctionController {
|
||||
return this.auctionService.next(matchId);
|
||||
}
|
||||
|
||||
@Get('history')
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
public async listHistory(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
return this.auctionService.listHistory({ matchId, communityId });
|
||||
}
|
||||
|
||||
@Post('undo')
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
public async undo(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@Body() body: UndoAuctionDto,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
const auction = await this.auctionService.undoTo({
|
||||
matchId,
|
||||
communityId,
|
||||
sequence: body.sequence,
|
||||
});
|
||||
this.auctionGateway.broadcastState(matchId.toString(), auction);
|
||||
return auction;
|
||||
}
|
||||
|
||||
@Delete()
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
|
||||
@@ -294,7 +294,7 @@ export class AuctionGateway
|
||||
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
||||
}
|
||||
|
||||
private broadcastState(matchId: string, auction: AuctionDocument) {
|
||||
public broadcastState(matchId: string, auction: AuctionDocument) {
|
||||
this.server.to(matchId).emit('state', this.serializeAuction(auction));
|
||||
this.syncRoomTimer(matchId, auction);
|
||||
}
|
||||
@@ -305,6 +305,10 @@ export class AuctionGateway
|
||||
|
||||
const deadline = auction.currentDeadline;
|
||||
const deadlineIso = deadline.toISOString();
|
||||
if (Date.now() >= deadline.getTime()) {
|
||||
void this.handleDeadlineExpiry(matchId);
|
||||
return;
|
||||
}
|
||||
this.server.to(matchId).emit('tick', {
|
||||
deadline: deadlineIso,
|
||||
serverTime: new Date().toISOString(),
|
||||
@@ -318,12 +322,34 @@ export class AuctionGateway
|
||||
|
||||
if (Date.now() >= deadline.getTime()) {
|
||||
this.clearRoomTimer(matchId);
|
||||
void this.handleDeadlineExpiry(matchId);
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
this.roomTimers.set(matchId, timer);
|
||||
}
|
||||
|
||||
private async handleDeadlineExpiry(matchIdStr: string) {
|
||||
const matchId = new mongoose.Types.ObjectId(matchIdStr);
|
||||
const auction = await this.auctionService
|
||||
.getByMatchId(matchId)
|
||||
.catch(() => null);
|
||||
if (!auction || auction.phase !== 'bidding') return;
|
||||
if (!auction.currentDeadline || auction.currentDeadline.getTime() > Date.now()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const nextAuction =
|
||||
auction.currentBid > 0
|
||||
? await this.auctionService.markSold({ matchId })
|
||||
: await this.auctionService.markPassed(matchId);
|
||||
this.broadcastState(matchIdStr, nextAuction);
|
||||
} catch (error) {
|
||||
this.emitKnownErrorToRoom(matchIdStr, error);
|
||||
}
|
||||
}
|
||||
|
||||
private maybeClearRoomTimer(matchId: string) {
|
||||
const room = this.server.adapter.rooms.get(matchId);
|
||||
if (room && room.size > 0) return;
|
||||
@@ -343,6 +369,12 @@ export class AuctionGateway
|
||||
this.emitError(socket, message);
|
||||
}
|
||||
|
||||
private emitKnownErrorToRoom(matchId: string, error: unknown) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : 'Unexpected auction gateway error.';
|
||||
this.server.to(matchId).emit('error', { message });
|
||||
}
|
||||
|
||||
private emitError(socket: Socket, message: string) {
|
||||
socket.emit('error', { message });
|
||||
}
|
||||
|
||||
@@ -3,8 +3,27 @@ import { AuctionService } from './auction.service';
|
||||
|
||||
describe('AuctionService', () => {
|
||||
function createService(models: Record<string, unknown>) {
|
||||
const auctionHistoryModel = {
|
||||
findOne: jest.fn().mockReturnValue({
|
||||
sort: jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue(null),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
create: jest.fn().mockResolvedValue(undefined),
|
||||
deleteMany: jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockResolvedValue(undefined),
|
||||
}),
|
||||
};
|
||||
const allModels = {
|
||||
auctionHistory: auctionHistoryModel,
|
||||
...models,
|
||||
};
|
||||
const connectionService = {
|
||||
getModel: jest.fn((name: string) => models[name]),
|
||||
getModel: jest.fn((name: string) => allModels[name]),
|
||||
createSession: jest.fn(),
|
||||
};
|
||||
const enrichmentService = {
|
||||
@@ -16,6 +35,7 @@ describe('AuctionService', () => {
|
||||
};
|
||||
const tournamentResultService = {
|
||||
scheduleInitialPoll: jest.fn().mockResolvedValue(null),
|
||||
cancelPolling: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -28,6 +48,7 @@ describe('AuctionService', () => {
|
||||
connectionService,
|
||||
tournamentCodeService,
|
||||
tournamentResultService,
|
||||
auctionHistoryModel,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -96,6 +117,119 @@ describe('AuctionService', () => {
|
||||
expect(auction.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('marks a zero-bid player as passed and queues them for round two', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const playerId = new mongoose.Types.ObjectId();
|
||||
const auction = {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
matchId,
|
||||
phase: 'bidding',
|
||||
currentBid: 0,
|
||||
currentIndex: 0,
|
||||
auctionRound: 1,
|
||||
order: [
|
||||
{
|
||||
userId: playerId,
|
||||
preferredPositions: [{ position: 'MID', priority: 1 }],
|
||||
passCount: 0,
|
||||
},
|
||||
],
|
||||
passedQueue: [],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }),
|
||||
};
|
||||
const { service } = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
});
|
||||
|
||||
await service.markPassed(matchId);
|
||||
|
||||
expect(auction.phase).toBe('passed');
|
||||
expect(auction.order[0].passCount).toBe(1);
|
||||
expect(auction.passedQueue).toHaveLength(1);
|
||||
expect(auction.save).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('force-assigns second-pass players to the open team with most points', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const captainOneId = new mongoose.Types.ObjectId();
|
||||
const captainTwoId = new mongoose.Types.ObjectId();
|
||||
const passedPlayerId = new mongoose.Types.ObjectId();
|
||||
const auction = {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
matchId,
|
||||
phase: 'passed',
|
||||
currentIndex: 0,
|
||||
auctionRound: 2,
|
||||
order: [
|
||||
{
|
||||
userId: passedPlayerId,
|
||||
preferredPositions: [{ position: 'SUP', priority: 1 }],
|
||||
passCount: 2,
|
||||
},
|
||||
],
|
||||
passedQueue: [],
|
||||
teams: [
|
||||
{
|
||||
teamIndex: 1,
|
||||
captainUserId: captainOneId,
|
||||
points: 10,
|
||||
members: [],
|
||||
},
|
||||
{
|
||||
teamIndex: 2,
|
||||
captainUserId: captainTwoId,
|
||||
points: 50,
|
||||
members: [],
|
||||
},
|
||||
],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }),
|
||||
};
|
||||
const match = {
|
||||
participants: [
|
||||
{
|
||||
userId: captainOneId,
|
||||
preferredPositions: [{ position: 'TOP', priority: 1 }],
|
||||
},
|
||||
{
|
||||
userId: captainTwoId,
|
||||
preferredPositions: [{ position: 'JGL', priority: 1 }],
|
||||
},
|
||||
{
|
||||
userId: passedPlayerId,
|
||||
preferredPositions: [{ position: 'SUP', priority: 1 }],
|
||||
},
|
||||
],
|
||||
status: 'team-built',
|
||||
teams: [],
|
||||
teamBuiltAt: undefined,
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const { service } = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
match: {
|
||||
findById: jest.fn().mockResolvedValue(match),
|
||||
},
|
||||
});
|
||||
|
||||
await service.next(matchId);
|
||||
|
||||
expect(auction.phase).toBe('complete');
|
||||
expect(auction.teams[1].members).toEqual([
|
||||
{
|
||||
userId: passedPlayerId,
|
||||
assignedPosition: 'SUP',
|
||||
cost: 1,
|
||||
},
|
||||
]);
|
||||
expect(auction.teams[1].points).toBe(49);
|
||||
});
|
||||
|
||||
it('syncs completed auction teams into the match document', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const blueCaptainId = new mongoose.Types.ObjectId();
|
||||
@@ -260,4 +394,92 @@ describe('AuctionService', () => {
|
||||
expect(match.save).toHaveBeenCalledWith({ session });
|
||||
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('undoes to a history snapshot and releases resources when leaving complete', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const auctionId = new mongoose.Types.ObjectId();
|
||||
const session = {
|
||||
startTransaction: jest.fn(),
|
||||
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
endSession: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const auction = {
|
||||
_id: auctionId,
|
||||
matchId,
|
||||
completedAt: new Date(),
|
||||
};
|
||||
const snapshot = {
|
||||
_id: auctionId.toString(),
|
||||
matchId: matchId.toString(),
|
||||
phase: 'bidding',
|
||||
order: [],
|
||||
teams: [],
|
||||
};
|
||||
const restored = { _id: auctionId, phase: 'bidding' };
|
||||
const match = {
|
||||
communityId,
|
||||
status: 'finished',
|
||||
result: { games: [] },
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const auctionFindOneQuery = {
|
||||
session: jest.fn().mockResolvedValue(auction),
|
||||
};
|
||||
const matchFindByIdQuery = {
|
||||
session: jest.fn().mockResolvedValue(match),
|
||||
};
|
||||
const historyFindOneQuery = {
|
||||
session: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({
|
||||
auctionId,
|
||||
matchId,
|
||||
sequence: 3,
|
||||
snapshotBefore: snapshot,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
};
|
||||
const historyDeleteManyQuery = {
|
||||
session: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue(undefined),
|
||||
}),
|
||||
};
|
||||
const auctionReplaceOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
const { service, connectionService, tournamentCodeService, tournamentResultService } =
|
||||
createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockReturnValue(auctionFindOneQuery),
|
||||
replaceOne: auctionReplaceOne,
|
||||
findById: jest.fn().mockResolvedValue(restored),
|
||||
},
|
||||
auctionHistory: {
|
||||
findOne: jest.fn().mockReturnValue(historyFindOneQuery),
|
||||
deleteMany: jest.fn().mockReturnValue(historyDeleteManyQuery),
|
||||
},
|
||||
match: {
|
||||
findById: jest.fn().mockReturnValue(matchFindByIdQuery),
|
||||
},
|
||||
});
|
||||
connectionService.createSession.mockResolvedValue(session);
|
||||
|
||||
await expect(
|
||||
service.undoTo({ matchId, communityId, sequence: 3 }),
|
||||
).resolves.toBe(restored);
|
||||
|
||||
expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(match);
|
||||
expect(tournamentResultService.cancelPolling).toHaveBeenCalledWith(match);
|
||||
expect(match.status).toBe('team-built');
|
||||
expect(match.result).toBeUndefined();
|
||||
expect(auctionReplaceOne).toHaveBeenCalledWith(
|
||||
{ _id: auctionId },
|
||||
snapshot,
|
||||
{ session },
|
||||
);
|
||||
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -8,9 +8,11 @@ import {
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
AuctionActionType,
|
||||
AuctionDocument,
|
||||
AuctionPlayerSnapshot,
|
||||
AuctionTeam,
|
||||
AuctionTopTierThreshold,
|
||||
MatchParticipant,
|
||||
MatchTeamMember,
|
||||
Position,
|
||||
@@ -31,9 +33,11 @@ interface StartAuctionParams {
|
||||
captains: {
|
||||
teamIndex: number;
|
||||
userId: mongoose.Types.ObjectId;
|
||||
initialPoints?: number;
|
||||
}[];
|
||||
initialPoints: number;
|
||||
maxTimerSeconds: number;
|
||||
topTierThreshold: AuctionTopTierThreshold;
|
||||
}
|
||||
|
||||
interface PlaceBidParams {
|
||||
@@ -48,6 +52,13 @@ interface MarkSoldParams {
|
||||
assignedPosition?: Position;
|
||||
}
|
||||
|
||||
export interface AuctionHistoryView {
|
||||
sequence: number;
|
||||
action: AuctionActionType;
|
||||
actionLabel: string;
|
||||
takenAt: Date;
|
||||
}
|
||||
|
||||
interface AuctionEnrichmentTarget {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
puuid: string;
|
||||
@@ -151,8 +162,13 @@ export class AuctionService {
|
||||
tiers: primary.tiers,
|
||||
masteries: primary.championMasteries,
|
||||
recentStatsSummary: primary.recentStatsSummary,
|
||||
passCount: 0,
|
||||
});
|
||||
}
|
||||
const prioritizedOrder = this.applyTopTierPriority(
|
||||
order,
|
||||
params.topTierThreshold,
|
||||
);
|
||||
|
||||
const auction = await AuctionModel.create({
|
||||
matchId: params.matchId,
|
||||
@@ -160,17 +176,21 @@ export class AuctionService {
|
||||
teams: params.captains.map((c) => ({
|
||||
teamIndex: c.teamIndex,
|
||||
captainUserId: c.userId,
|
||||
points: params.initialPoints,
|
||||
points: c.initialPoints ?? params.initialPoints,
|
||||
members: [],
|
||||
})),
|
||||
order,
|
||||
order: prioritizedOrder,
|
||||
passedQueue: [],
|
||||
auctionRound: 1,
|
||||
currentIndex: 0,
|
||||
bids: [],
|
||||
currentBid: 0,
|
||||
maxTimerSeconds: params.maxTimerSeconds,
|
||||
initialPoints: params.initialPoints,
|
||||
topTierThreshold: params.topTierThreshold,
|
||||
startedAt: new Date(),
|
||||
});
|
||||
await this.recordSnapshot(auction, 'start');
|
||||
|
||||
match.status = 'team-built';
|
||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||
@@ -196,6 +216,35 @@ export class AuctionService {
|
||||
return auction;
|
||||
}
|
||||
|
||||
public async listHistory(params: {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
}): Promise<AuctionHistoryView[]> {
|
||||
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<AuctionDocument> {
|
||||
@@ -203,6 +252,7 @@ export class AuctionService {
|
||||
if (auction.phase !== 'presenting') {
|
||||
throw new BadRequestException('Auction is not in presenting phase.');
|
||||
}
|
||||
await this.recordSnapshot(auction, 'open-bidding');
|
||||
auction.phase = 'bidding';
|
||||
auction.currentBid = 0;
|
||||
auction.currentBidderTeamIndex = undefined;
|
||||
@@ -227,6 +277,7 @@ export class AuctionService {
|
||||
this.assertTeamHasSlot(team);
|
||||
// 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다.
|
||||
|
||||
await this.recordSnapshot(auction, 'bid', params.bidderUserId);
|
||||
auction.currentBid = params.amount;
|
||||
auction.currentBidderTeamIndex = params.teamIndex;
|
||||
auction.currentDeadline = this.createDeadline(
|
||||
@@ -260,6 +311,7 @@ export class AuctionService {
|
||||
const current = auction.order[auction.currentIndex];
|
||||
if (!current) throw new BadRequestException('No current player.');
|
||||
|
||||
await this.recordSnapshot(auction, 'sold');
|
||||
const preferredPrimary = current.preferredPositions[0]?.position;
|
||||
team.members.push({
|
||||
userId: current.userId,
|
||||
@@ -273,17 +325,70 @@ export class AuctionService {
|
||||
return auction;
|
||||
}
|
||||
|
||||
public async markPassed(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
): Promise<AuctionDocument> {
|
||||
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<AuctionDocument> {
|
||||
const auction = await this.getByMatchId(matchId);
|
||||
if (auction.phase !== 'sold' && auction.phase !== 'presenting') {
|
||||
if (
|
||||
auction.phase !== 'sold' &&
|
||||
auction.phase !== 'presenting' &&
|
||||
auction.phase !== 'passed'
|
||||
) {
|
||||
throw new BadRequestException('Cannot advance from current phase.');
|
||||
}
|
||||
const nextIndex = auction.currentIndex + 1;
|
||||
const completesAuction =
|
||||
nextIndex >= auction.order.length &&
|
||||
!(
|
||||
(auction.auctionRound ?? 1) === 1 &&
|
||||
(auction.passedQueue?.length ?? 0) > 0
|
||||
);
|
||||
await this.recordSnapshot(auction, completesAuction ? 'complete' : 'next');
|
||||
if (nextIndex >= auction.order.length) {
|
||||
auction.phase = 'complete';
|
||||
auction.completedAt = new Date();
|
||||
if (
|
||||
(auction.auctionRound ?? 1) === 1 &&
|
||||
(auction.passedQueue?.length ?? 0) > 0
|
||||
) {
|
||||
auction.order.push(
|
||||
...auction.passedQueue.map((player) =>
|
||||
this.cloneAuctionPlayerSnapshot(player),
|
||||
),
|
||||
);
|
||||
auction.passedQueue = [];
|
||||
auction.auctionRound = 2;
|
||||
auction.currentIndex = nextIndex;
|
||||
auction.phase = 'presenting';
|
||||
auction.currentBid = 0;
|
||||
auction.currentBidderTeamIndex = undefined;
|
||||
} else {
|
||||
this.forceAssignRemainingPasses(auction);
|
||||
auction.phase = 'complete';
|
||||
auction.completedAt = new Date();
|
||||
}
|
||||
} else {
|
||||
auction.currentIndex = nextIndex;
|
||||
auction.phase = 'presenting';
|
||||
@@ -303,6 +408,8 @@ export class AuctionService {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
}): Promise<void> {
|
||||
const AuctionModel = await this.connectionService.getModel('auction');
|
||||
const AuctionHistoryModel =
|
||||
await this.connectionService.getModel('auctionHistory');
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
|
||||
const session = await this.connectionService.createSession();
|
||||
@@ -323,6 +430,9 @@ export class AuctionService {
|
||||
}
|
||||
|
||||
await auction.deleteOne({ session });
|
||||
await AuctionHistoryModel.deleteMany({ auctionId: auction._id }).session(
|
||||
session,
|
||||
);
|
||||
if (match.status === 'team-built') {
|
||||
await this.tournamentCodeService.releaseFromMatch(match);
|
||||
match.status = 'recruiting';
|
||||
@@ -345,6 +455,210 @@ export class AuctionService {
|
||||
}
|
||||
}
|
||||
|
||||
public async undoTo(params: {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
sequence: number;
|
||||
}): Promise<AuctionDocument> {
|
||||
const AuctionModel = await this.connectionService.getModel('auction');
|
||||
const AuctionHistoryModel =
|
||||
await this.connectionService.getModel('auctionHistory');
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
|
||||
const session = await this.connectionService.createSession();
|
||||
if (!session) {
|
||||
throw new InternalServerErrorException('Failed to start DB session.');
|
||||
}
|
||||
|
||||
try {
|
||||
session.startTransaction();
|
||||
const auction = await AuctionModel.findOne({
|
||||
matchId: params.matchId,
|
||||
}).session(session);
|
||||
if (!auction) throw new NotFoundException('Auction not found.');
|
||||
|
||||
const match = await MatchModel.findById(params.matchId).session(session);
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
if (!match.communityId.equals(params.communityId)) {
|
||||
throw new BadRequestException('Community mismatch.');
|
||||
}
|
||||
|
||||
const history = await AuctionHistoryModel.findOne({
|
||||
auctionId: auction._id,
|
||||
sequence: params.sequence,
|
||||
})
|
||||
.session(session)
|
||||
.lean()
|
||||
.exec();
|
||||
if (!history) throw new NotFoundException('Auction history not found.');
|
||||
|
||||
const snapshot = history.snapshotBefore;
|
||||
if (!snapshot || typeof snapshot !== 'object') {
|
||||
throw new BadRequestException('Auction history snapshot is invalid.');
|
||||
}
|
||||
|
||||
const undoingCompletedAuction =
|
||||
Boolean(auction.completedAt) && !('completedAt' in snapshot);
|
||||
if (undoingCompletedAuction) {
|
||||
await this.tournamentCodeService.releaseFromMatch(match);
|
||||
await this.tournamentResultService.cancelPolling(match);
|
||||
match.status = 'team-built';
|
||||
match.result = undefined;
|
||||
await match.save({ session });
|
||||
}
|
||||
|
||||
await AuctionModel.replaceOne({ _id: auction._id }, snapshot, {
|
||||
session,
|
||||
}).exec();
|
||||
await AuctionHistoryModel.deleteMany({
|
||||
auctionId: auction._id,
|
||||
sequence: { $gt: params.sequence },
|
||||
})
|
||||
.session(session)
|
||||
.exec();
|
||||
|
||||
await session.commitTransaction();
|
||||
const restored = await AuctionModel.findById(auction._id);
|
||||
if (!restored) throw new NotFoundException('Auction not found.');
|
||||
return restored;
|
||||
} catch (err) {
|
||||
await session.abortTransaction();
|
||||
throw err;
|
||||
} finally {
|
||||
await session.endSession();
|
||||
}
|
||||
}
|
||||
|
||||
private applyTopTierPriority(
|
||||
order: AuctionPlayerSnapshot[],
|
||||
threshold: AuctionTopTierThreshold,
|
||||
): AuctionPlayerSnapshot[] {
|
||||
if (threshold === 'NONE') return order;
|
||||
|
||||
const ranks = [
|
||||
'IRON',
|
||||
'BRONZE',
|
||||
'SILVER',
|
||||
'GOLD',
|
||||
'PLATINUM',
|
||||
'EMERALD',
|
||||
'DIAMOND',
|
||||
'MASTER',
|
||||
'GRANDMASTER',
|
||||
'CHALLENGER',
|
||||
];
|
||||
const cutoff = ranks.indexOf(threshold);
|
||||
const score = (snap: AuctionPlayerSnapshot) => {
|
||||
const solo = snap.tiers.find(
|
||||
(tier) => tier.queueType === 'RANKED_SOLO_5x5',
|
||||
);
|
||||
if (!solo) return -1;
|
||||
const tierIdx = ranks.indexOf(solo.tier);
|
||||
if (tierIdx < cutoff) return -1;
|
||||
const rankBonus =
|
||||
({ I: 4, II: 3, III: 2, IV: 1, '': 0 } as Record<string, number>)[
|
||||
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<void> {
|
||||
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[] {
|
||||
|
||||
@@ -7,9 +7,14 @@ import {
|
||||
IsInt,
|
||||
IsMongoId,
|
||||
IsOptional,
|
||||
Max,
|
||||
Min,
|
||||
ValidateNested,
|
||||
} from 'class-validator';
|
||||
import { AUCTION_TOP_TIER_THRESHOLDS } from '../../global/database/schema';
|
||||
|
||||
export type AuctionTopTierThreshold =
|
||||
(typeof AUCTION_TOP_TIER_THRESHOLDS)[number];
|
||||
|
||||
class CaptainAssignmentDto {
|
||||
@IsInt()
|
||||
@@ -18,6 +23,12 @@ class CaptainAssignmentDto {
|
||||
|
||||
@IsMongoId()
|
||||
userId!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(100)
|
||||
@Max(100000)
|
||||
initialPoints?: number;
|
||||
}
|
||||
|
||||
export class StartAuctionDto {
|
||||
@@ -30,9 +41,14 @@ export class StartAuctionDto {
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Min(100)
|
||||
@Max(100000)
|
||||
initialPoints?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(AUCTION_TOP_TIER_THRESHOLDS)
|
||||
topTierThreshold?: AuctionTopTierThreshold;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(5)
|
||||
@@ -58,3 +74,9 @@ export class SoldDto {
|
||||
@IsEnum(['TOP', 'JGL', 'MID', 'ADC', 'SUP'])
|
||||
assignedPosition?: 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
|
||||
}
|
||||
|
||||
export class UndoAuctionDto {
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
sequence!: number;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
interface MigrationCollection {
|
||||
find(filter: Record<string, unknown>): {
|
||||
limit(limit: number): AsyncIterable<AnyDoc>;
|
||||
};
|
||||
bulkWrite(
|
||||
writes: Array<{
|
||||
updateOne: {
|
||||
filter: { _id: unknown };
|
||||
update: { $set: Record<string, unknown> };
|
||||
};
|
||||
}>,
|
||||
options: { ordered: boolean },
|
||||
): Promise<unknown>;
|
||||
}
|
||||
|
||||
interface MigrationDb {
|
||||
collection(name: string): MigrationCollection;
|
||||
}
|
||||
|
||||
interface MigrationOptions {
|
||||
dryRun?: boolean;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
interface MigrationStats {
|
||||
scannedAuctions: number;
|
||||
changedAuctions: number;
|
||||
}
|
||||
|
||||
type AnyDoc = Record<string, unknown> & { _id: unknown };
|
||||
|
||||
export async function migrateAuctionPassHistory(
|
||||
db: MigrationDb,
|
||||
options: MigrationOptions = {},
|
||||
): Promise<MigrationStats> {
|
||||
const dryRun = options.dryRun ?? true;
|
||||
const stats: MigrationStats = {
|
||||
scannedAuctions: 0,
|
||||
changedAuctions: 0,
|
||||
};
|
||||
const writes: Array<{
|
||||
updateOne: {
|
||||
filter: { _id: unknown };
|
||||
update: { $set: Record<string, unknown> };
|
||||
};
|
||||
}> = [];
|
||||
|
||||
for await (const doc of db.collection('auction').find({}).limit(options.limit ?? 0)) {
|
||||
stats.scannedAuctions += 1;
|
||||
const set: Record<string, unknown> = {};
|
||||
let changed = false;
|
||||
|
||||
if (!Array.isArray(doc.passedQueue)) {
|
||||
set.passedQueue = [];
|
||||
changed = true;
|
||||
}
|
||||
if (typeof doc.auctionRound !== 'number') {
|
||||
set.auctionRound = 1;
|
||||
changed = true;
|
||||
}
|
||||
if (typeof doc.topTierThreshold !== 'string') {
|
||||
set.topTierThreshold = 'NONE';
|
||||
changed = true;
|
||||
}
|
||||
|
||||
const order = Array.isArray(doc.order)
|
||||
? doc.order.map((player) => {
|
||||
if (!isRecord(player) || typeof player.passCount === 'number') {
|
||||
return player;
|
||||
}
|
||||
changed = true;
|
||||
return { ...player, passCount: 0 };
|
||||
})
|
||||
: [];
|
||||
if (changed && order.length > 0) set.order = order;
|
||||
if (!changed) continue;
|
||||
|
||||
stats.changedAuctions += 1;
|
||||
writes.push({
|
||||
updateOne: {
|
||||
filter: { _id: doc._id },
|
||||
update: { $set: set },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (!dryRun && writes.length > 0) {
|
||||
await db.collection('auction').bulkWrite(writes, { ordered: false });
|
||||
}
|
||||
|
||||
return stats;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value && typeof value === 'object' && !Array.isArray(value));
|
||||
}
|
||||
@@ -97,14 +97,32 @@ export type AuctionPhase =
|
||||
| 'presenting'
|
||||
| 'bidding'
|
||||
| 'sold'
|
||||
| 'passed'
|
||||
| 'complete';
|
||||
export const AUCTION_PHASES: AuctionPhase[] = [
|
||||
'waiting',
|
||||
'presenting',
|
||||
'bidding',
|
||||
'sold',
|
||||
'passed',
|
||||
'complete',
|
||||
];
|
||||
export const AUCTION_TOP_TIER_THRESHOLDS = [
|
||||
'NONE',
|
||||
'EMERALD',
|
||||
'DIAMOND',
|
||||
'MASTER',
|
||||
] as const;
|
||||
export type AuctionTopTierThreshold =
|
||||
(typeof AUCTION_TOP_TIER_THRESHOLDS)[number];
|
||||
export type AuctionActionType =
|
||||
| 'start'
|
||||
| 'open-bidding'
|
||||
| 'bid'
|
||||
| 'sold'
|
||||
| 'passed'
|
||||
| 'next'
|
||||
| 'complete';
|
||||
|
||||
export interface MongooseTimestamps {
|
||||
createdAt: Date;
|
||||
@@ -479,6 +497,7 @@ export interface AuctionPlayerSnapshot {
|
||||
tiers: TierInfo[];
|
||||
masteries: ChampionMasteryEntry[];
|
||||
recentStatsSummary?: RiotRecentStatsSummary;
|
||||
passCount: number;
|
||||
}
|
||||
|
||||
export interface AuctionTeamMember {
|
||||
@@ -506,6 +525,8 @@ export interface Auction extends MongooseTimestamps {
|
||||
phase: AuctionPhase;
|
||||
teams: AuctionTeam[];
|
||||
order: AuctionPlayerSnapshot[];
|
||||
passedQueue: AuctionPlayerSnapshot[];
|
||||
auctionRound: number;
|
||||
currentIndex: number;
|
||||
bids: AuctionBid[];
|
||||
currentBid: number;
|
||||
@@ -513,12 +534,26 @@ export interface Auction extends MongooseTimestamps {
|
||||
maxTimerSeconds: number;
|
||||
currentDeadline?: Date;
|
||||
initialPoints: number;
|
||||
topTierThreshold: AuctionTopTierThreshold;
|
||||
startedAt?: Date;
|
||||
completedAt?: Date;
|
||||
}
|
||||
|
||||
export type AuctionDocument = HydratedDocument<Auction>;
|
||||
|
||||
export interface AuctionHistoryEntry extends MongooseTimestamps {
|
||||
auctionId: mongoose.Types.ObjectId;
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
sequence: number;
|
||||
action: AuctionActionType;
|
||||
actorUserId?: mongoose.Types.ObjectId;
|
||||
snapshotBefore: Record<string, unknown>;
|
||||
takenAt: Date;
|
||||
}
|
||||
|
||||
export type AuctionHistoryEntryDocument =
|
||||
HydratedDocument<AuctionHistoryEntry>;
|
||||
|
||||
// ===== Sub-schemas =====
|
||||
const PositionPreferenceSubSchema = new Schema<PositionPreference>(
|
||||
{
|
||||
@@ -1194,6 +1229,7 @@ const AuctionPlayerSnapshotSubSchema = new Schema<AuctionPlayerSnapshot>(
|
||||
default: [],
|
||||
},
|
||||
recentStatsSummary: { type: RiotRecentStatsSummarySubSchema },
|
||||
passCount: { type: Number, required: true, default: 0 },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
@@ -1251,6 +1287,12 @@ export const AuctionSchema = new Schema<Auction>(
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
passedQueue: {
|
||||
type: [AuctionPlayerSnapshotSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
auctionRound: { type: Number, required: true, default: 1, min: 1 },
|
||||
currentIndex: { type: Number, required: true, default: 0 },
|
||||
bids: { type: [AuctionBidSubSchema], required: true, default: [] },
|
||||
currentBid: { type: Number, required: true, default: 0 },
|
||||
@@ -1258,6 +1300,12 @@ export const AuctionSchema = new Schema<Auction>(
|
||||
maxTimerSeconds: { type: Number, required: true, default: 30 },
|
||||
currentDeadline: { type: Date, required: false },
|
||||
initialPoints: { type: Number, required: true, default: 1000 },
|
||||
topTierThreshold: {
|
||||
type: String,
|
||||
enum: AUCTION_TOP_TIER_THRESHOLDS,
|
||||
required: true,
|
||||
default: 'NONE',
|
||||
},
|
||||
startedAt: { type: Date, required: false },
|
||||
completedAt: { type: Date, required: false },
|
||||
},
|
||||
@@ -1267,6 +1315,38 @@ export const AuctionSchema = new Schema<Auction>(
|
||||
},
|
||||
);
|
||||
|
||||
const AuctionHistoryEntrySchema = new Schema<AuctionHistoryEntry>(
|
||||
{
|
||||
auctionId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'auction',
|
||||
required: true,
|
||||
index: true,
|
||||
},
|
||||
matchId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'match',
|
||||
required: true,
|
||||
index: true,
|
||||
},
|
||||
sequence: { type: Number, required: true, min: 1 },
|
||||
action: {
|
||||
type: String,
|
||||
enum: ['start', 'open-bidding', 'bid', 'sold', 'passed', 'next', 'complete'],
|
||||
required: true,
|
||||
},
|
||||
actorUserId: { type: Schema.Types.ObjectId, ref: 'user', required: false },
|
||||
snapshotBefore: { type: Schema.Types.Mixed, required: true },
|
||||
takenAt: { type: Date, required: true, default: Date.now },
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
collection: 'auctionHistory',
|
||||
},
|
||||
);
|
||||
|
||||
AuctionHistoryEntrySchema.index({ auctionId: 1, sequence: -1 });
|
||||
|
||||
export const tournamentModelDefinitions: ModelDefinition[] = [
|
||||
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
|
||||
{ name: 'community', schema: CommunitySchema, schemaName: 'community' },
|
||||
@@ -1284,6 +1364,11 @@ export const tournamentModelDefinitions: ModelDefinition[] = [
|
||||
},
|
||||
{ name: 'match', schema: MatchSchema, schemaName: 'match' },
|
||||
{ name: 'auction', schema: AuctionSchema, schemaName: 'auction' },
|
||||
{
|
||||
name: 'auctionHistory',
|
||||
schema: AuctionHistoryEntrySchema,
|
||||
schemaName: 'auctionHistory',
|
||||
},
|
||||
];
|
||||
|
||||
export interface TournamentModelTypes {
|
||||
@@ -1295,4 +1380,5 @@ export interface TournamentModelTypes {
|
||||
legacyImportJob: LegacyImportJob;
|
||||
match: Match;
|
||||
auction: Auction;
|
||||
auctionHistory: AuctionHistoryEntry;
|
||||
}
|
||||
@@ -91,6 +91,14 @@ export class TournamentResultService {
|
||||
return result;
|
||||
}
|
||||
|
||||
public async cancelPolling(
|
||||
matchOrId: MatchDocument | mongoose.Types.ObjectId,
|
||||
): Promise<void> {
|
||||
const match = await this.loadMatch(matchOrId);
|
||||
match.resultPollState = undefined;
|
||||
await match.save();
|
||||
}
|
||||
|
||||
public async processPollJob(job: PollTournamentResultJob): Promise<void> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const TournamentCodeModel =
|
||||
|
||||
Reference in new issue
Block a user