.
This commit is contained in:
1 parent
fedca82c81
commit
3607e3a99c
13 files changed
+1828
-783
No files matched your search
@@ -18,11 +18,20 @@ import { RolesGuard } from '../auth/roles.guard';
|
|||||||
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||||
import type { UserDocument } from '../global/database/schema';
|
import type { UserDocument } from '../global/database/schema';
|
||||||
import { AuctionService } from './auction.service';
|
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')
|
@Controller('communities/:communityId/matches/:matchId/auction')
|
||||||
export class AuctionController {
|
export class AuctionController {
|
||||||
constructor(private readonly auctionService: AuctionService) {}
|
constructor(
|
||||||
|
private readonly auctionService: AuctionService,
|
||||||
|
private readonly auctionGateway: AuctionGateway,
|
||||||
|
) {}
|
||||||
|
|
||||||
@Post()
|
@Post()
|
||||||
@Roles('admin', 'owner')
|
@Roles('admin', 'owner')
|
||||||
@@ -41,9 +50,11 @@ export class AuctionController {
|
|||||||
captains: body.captains.map((c) => ({
|
captains: body.captains.map((c) => ({
|
||||||
teamIndex: c.teamIndex,
|
teamIndex: c.teamIndex,
|
||||||
userId: new mongoose.Types.ObjectId(c.userId),
|
userId: new mongoose.Types.ObjectId(c.userId),
|
||||||
|
initialPoints: c.initialPoints,
|
||||||
})),
|
})),
|
||||||
initialPoints: body.initialPoints ?? 1000,
|
initialPoints: body.initialPoints ?? 1000,
|
||||||
maxTimerSeconds: body.maxTimerSeconds ?? 30,
|
maxTimerSeconds: body.maxTimerSeconds ?? 30,
|
||||||
|
topTierThreshold: body.topTierThreshold ?? 'NONE',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,6 +114,40 @@ export class AuctionController {
|
|||||||
return this.auctionService.next(matchId);
|
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()
|
@Delete()
|
||||||
@Roles('admin', 'owner')
|
@Roles('admin', 'owner')
|
||||||
@UseGuards(RolesGuard)
|
@UseGuards(RolesGuard)
|
||||||
|
|||||||
@@ -294,7 +294,7 @@ export class AuctionGateway
|
|||||||
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
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.server.to(matchId).emit('state', this.serializeAuction(auction));
|
||||||
this.syncRoomTimer(matchId, auction);
|
this.syncRoomTimer(matchId, auction);
|
||||||
}
|
}
|
||||||
@@ -305,6 +305,10 @@ export class AuctionGateway
|
|||||||
|
|
||||||
const deadline = auction.currentDeadline;
|
const deadline = auction.currentDeadline;
|
||||||
const deadlineIso = deadline.toISOString();
|
const deadlineIso = deadline.toISOString();
|
||||||
|
if (Date.now() >= deadline.getTime()) {
|
||||||
|
void this.handleDeadlineExpiry(matchId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
this.server.to(matchId).emit('tick', {
|
this.server.to(matchId).emit('tick', {
|
||||||
deadline: deadlineIso,
|
deadline: deadlineIso,
|
||||||
serverTime: new Date().toISOString(),
|
serverTime: new Date().toISOString(),
|
||||||
@@ -318,12 +322,34 @@ export class AuctionGateway
|
|||||||
|
|
||||||
if (Date.now() >= deadline.getTime()) {
|
if (Date.now() >= deadline.getTime()) {
|
||||||
this.clearRoomTimer(matchId);
|
this.clearRoomTimer(matchId);
|
||||||
|
void this.handleDeadlineExpiry(matchId);
|
||||||
}
|
}
|
||||||
}, 1000);
|
}, 1000);
|
||||||
|
|
||||||
this.roomTimers.set(matchId, timer);
|
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) {
|
private maybeClearRoomTimer(matchId: string) {
|
||||||
const room = this.server.adapter.rooms.get(matchId);
|
const room = this.server.adapter.rooms.get(matchId);
|
||||||
if (room && room.size > 0) return;
|
if (room && room.size > 0) return;
|
||||||
@@ -343,6 +369,12 @@ export class AuctionGateway
|
|||||||
this.emitError(socket, message);
|
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) {
|
private emitError(socket: Socket, message: string) {
|
||||||
socket.emit('error', { message });
|
socket.emit('error', { message });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,27 @@ import { AuctionService } from './auction.service';
|
|||||||
|
|
||||||
describe('AuctionService', () => {
|
describe('AuctionService', () => {
|
||||||
function createService(models: Record<string, unknown>) {
|
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 = {
|
const connectionService = {
|
||||||
getModel: jest.fn((name: string) => models[name]),
|
getModel: jest.fn((name: string) => allModels[name]),
|
||||||
createSession: jest.fn(),
|
createSession: jest.fn(),
|
||||||
};
|
};
|
||||||
const enrichmentService = {
|
const enrichmentService = {
|
||||||
@@ -16,6 +35,7 @@ describe('AuctionService', () => {
|
|||||||
};
|
};
|
||||||
const tournamentResultService = {
|
const tournamentResultService = {
|
||||||
scheduleInitialPoll: jest.fn().mockResolvedValue(null),
|
scheduleInitialPoll: jest.fn().mockResolvedValue(null),
|
||||||
|
cancelPolling: jest.fn().mockResolvedValue(undefined),
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -28,6 +48,7 @@ describe('AuctionService', () => {
|
|||||||
connectionService,
|
connectionService,
|
||||||
tournamentCodeService,
|
tournamentCodeService,
|
||||||
tournamentResultService,
|
tournamentResultService,
|
||||||
|
auctionHistoryModel,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,6 +117,119 @@ describe('AuctionService', () => {
|
|||||||
expect(auction.save).not.toHaveBeenCalled();
|
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 () => {
|
it('syncs completed auction teams into the match document', async () => {
|
||||||
const matchId = new mongoose.Types.ObjectId();
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
const blueCaptainId = new mongoose.Types.ObjectId();
|
const blueCaptainId = new mongoose.Types.ObjectId();
|
||||||
@@ -260,4 +394,92 @@ describe('AuctionService', () => {
|
|||||||
expect(match.save).toHaveBeenCalledWith({ session });
|
expect(match.save).toHaveBeenCalledWith({ session });
|
||||||
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
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 mongoose from 'mongoose';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
import {
|
import {
|
||||||
|
AuctionActionType,
|
||||||
AuctionDocument,
|
AuctionDocument,
|
||||||
AuctionPlayerSnapshot,
|
AuctionPlayerSnapshot,
|
||||||
AuctionTeam,
|
AuctionTeam,
|
||||||
|
AuctionTopTierThreshold,
|
||||||
MatchParticipant,
|
MatchParticipant,
|
||||||
MatchTeamMember,
|
MatchTeamMember,
|
||||||
Position,
|
Position,
|
||||||
@@ -31,9 +33,11 @@ interface StartAuctionParams {
|
|||||||
captains: {
|
captains: {
|
||||||
teamIndex: number;
|
teamIndex: number;
|
||||||
userId: mongoose.Types.ObjectId;
|
userId: mongoose.Types.ObjectId;
|
||||||
|
initialPoints?: number;
|
||||||
}[];
|
}[];
|
||||||
initialPoints: number;
|
initialPoints: number;
|
||||||
maxTimerSeconds: number;
|
maxTimerSeconds: number;
|
||||||
|
topTierThreshold: AuctionTopTierThreshold;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface PlaceBidParams {
|
interface PlaceBidParams {
|
||||||
@@ -48,6 +52,13 @@ interface MarkSoldParams {
|
|||||||
assignedPosition?: Position;
|
assignedPosition?: Position;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface AuctionHistoryView {
|
||||||
|
sequence: number;
|
||||||
|
action: AuctionActionType;
|
||||||
|
actionLabel: string;
|
||||||
|
takenAt: Date;
|
||||||
|
}
|
||||||
|
|
||||||
interface AuctionEnrichmentTarget {
|
interface AuctionEnrichmentTarget {
|
||||||
userId: mongoose.Types.ObjectId;
|
userId: mongoose.Types.ObjectId;
|
||||||
puuid: string;
|
puuid: string;
|
||||||
@@ -151,8 +162,13 @@ export class AuctionService {
|
|||||||
tiers: primary.tiers,
|
tiers: primary.tiers,
|
||||||
masteries: primary.championMasteries,
|
masteries: primary.championMasteries,
|
||||||
recentStatsSummary: primary.recentStatsSummary,
|
recentStatsSummary: primary.recentStatsSummary,
|
||||||
|
passCount: 0,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
const prioritizedOrder = this.applyTopTierPriority(
|
||||||
|
order,
|
||||||
|
params.topTierThreshold,
|
||||||
|
);
|
||||||
|
|
||||||
const auction = await AuctionModel.create({
|
const auction = await AuctionModel.create({
|
||||||
matchId: params.matchId,
|
matchId: params.matchId,
|
||||||
@@ -160,17 +176,21 @@ export class AuctionService {
|
|||||||
teams: params.captains.map((c) => ({
|
teams: params.captains.map((c) => ({
|
||||||
teamIndex: c.teamIndex,
|
teamIndex: c.teamIndex,
|
||||||
captainUserId: c.userId,
|
captainUserId: c.userId,
|
||||||
points: params.initialPoints,
|
points: c.initialPoints ?? params.initialPoints,
|
||||||
members: [],
|
members: [],
|
||||||
})),
|
})),
|
||||||
order,
|
order: prioritizedOrder,
|
||||||
|
passedQueue: [],
|
||||||
|
auctionRound: 1,
|
||||||
currentIndex: 0,
|
currentIndex: 0,
|
||||||
bids: [],
|
bids: [],
|
||||||
currentBid: 0,
|
currentBid: 0,
|
||||||
maxTimerSeconds: params.maxTimerSeconds,
|
maxTimerSeconds: params.maxTimerSeconds,
|
||||||
initialPoints: params.initialPoints,
|
initialPoints: params.initialPoints,
|
||||||
|
topTierThreshold: params.topTierThreshold,
|
||||||
startedAt: new Date(),
|
startedAt: new Date(),
|
||||||
});
|
});
|
||||||
|
await this.recordSnapshot(auction, 'start');
|
||||||
|
|
||||||
match.status = 'team-built';
|
match.status = 'team-built';
|
||||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||||
@@ -196,6 +216,35 @@ export class AuctionService {
|
|||||||
return auction;
|
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(
|
public async openBidding(
|
||||||
matchId: mongoose.Types.ObjectId,
|
matchId: mongoose.Types.ObjectId,
|
||||||
): Promise<AuctionDocument> {
|
): Promise<AuctionDocument> {
|
||||||
@@ -203,6 +252,7 @@ export class AuctionService {
|
|||||||
if (auction.phase !== 'presenting') {
|
if (auction.phase !== 'presenting') {
|
||||||
throw new BadRequestException('Auction is not in presenting phase.');
|
throw new BadRequestException('Auction is not in presenting phase.');
|
||||||
}
|
}
|
||||||
|
await this.recordSnapshot(auction, 'open-bidding');
|
||||||
auction.phase = 'bidding';
|
auction.phase = 'bidding';
|
||||||
auction.currentBid = 0;
|
auction.currentBid = 0;
|
||||||
auction.currentBidderTeamIndex = undefined;
|
auction.currentBidderTeamIndex = undefined;
|
||||||
@@ -227,6 +277,7 @@ export class AuctionService {
|
|||||||
this.assertTeamHasSlot(team);
|
this.assertTeamHasSlot(team);
|
||||||
// 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다.
|
// 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다.
|
||||||
|
|
||||||
|
await this.recordSnapshot(auction, 'bid', params.bidderUserId);
|
||||||
auction.currentBid = params.amount;
|
auction.currentBid = params.amount;
|
||||||
auction.currentBidderTeamIndex = params.teamIndex;
|
auction.currentBidderTeamIndex = params.teamIndex;
|
||||||
auction.currentDeadline = this.createDeadline(
|
auction.currentDeadline = this.createDeadline(
|
||||||
@@ -260,6 +311,7 @@ export class AuctionService {
|
|||||||
const current = auction.order[auction.currentIndex];
|
const current = auction.order[auction.currentIndex];
|
||||||
if (!current) throw new BadRequestException('No current player.');
|
if (!current) throw new BadRequestException('No current player.');
|
||||||
|
|
||||||
|
await this.recordSnapshot(auction, 'sold');
|
||||||
const preferredPrimary = current.preferredPositions[0]?.position;
|
const preferredPrimary = current.preferredPositions[0]?.position;
|
||||||
team.members.push({
|
team.members.push({
|
||||||
userId: current.userId,
|
userId: current.userId,
|
||||||
@@ -273,17 +325,70 @@ export class AuctionService {
|
|||||||
return auction;
|
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(
|
public async next(
|
||||||
matchId: mongoose.Types.ObjectId,
|
matchId: mongoose.Types.ObjectId,
|
||||||
): Promise<AuctionDocument> {
|
): Promise<AuctionDocument> {
|
||||||
const auction = await this.getByMatchId(matchId);
|
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.');
|
throw new BadRequestException('Cannot advance from current phase.');
|
||||||
}
|
}
|
||||||
const nextIndex = auction.currentIndex + 1;
|
const nextIndex = auction.currentIndex + 1;
|
||||||
|
const completesAuction =
|
||||||
|
nextIndex >= auction.order.length &&
|
||||||
|
!(
|
||||||
|
(auction.auctionRound ?? 1) === 1 &&
|
||||||
|
(auction.passedQueue?.length ?? 0) > 0
|
||||||
|
);
|
||||||
|
await this.recordSnapshot(auction, completesAuction ? 'complete' : 'next');
|
||||||
if (nextIndex >= auction.order.length) {
|
if (nextIndex >= auction.order.length) {
|
||||||
|
if (
|
||||||
|
(auction.auctionRound ?? 1) === 1 &&
|
||||||
|
(auction.passedQueue?.length ?? 0) > 0
|
||||||
|
) {
|
||||||
|
auction.order.push(
|
||||||
|
...auction.passedQueue.map((player) =>
|
||||||
|
this.cloneAuctionPlayerSnapshot(player),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
auction.passedQueue = [];
|
||||||
|
auction.auctionRound = 2;
|
||||||
|
auction.currentIndex = nextIndex;
|
||||||
|
auction.phase = 'presenting';
|
||||||
|
auction.currentBid = 0;
|
||||||
|
auction.currentBidderTeamIndex = undefined;
|
||||||
|
} else {
|
||||||
|
this.forceAssignRemainingPasses(auction);
|
||||||
auction.phase = 'complete';
|
auction.phase = 'complete';
|
||||||
auction.completedAt = new Date();
|
auction.completedAt = new Date();
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
auction.currentIndex = nextIndex;
|
auction.currentIndex = nextIndex;
|
||||||
auction.phase = 'presenting';
|
auction.phase = 'presenting';
|
||||||
@@ -303,6 +408,8 @@ export class AuctionService {
|
|||||||
communityId: mongoose.Types.ObjectId;
|
communityId: mongoose.Types.ObjectId;
|
||||||
}): Promise<void> {
|
}): Promise<void> {
|
||||||
const AuctionModel = await this.connectionService.getModel('auction');
|
const AuctionModel = await this.connectionService.getModel('auction');
|
||||||
|
const AuctionHistoryModel =
|
||||||
|
await this.connectionService.getModel('auctionHistory');
|
||||||
const MatchModel = await this.connectionService.getModel('match');
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
|
|
||||||
const session = await this.connectionService.createSession();
|
const session = await this.connectionService.createSession();
|
||||||
@@ -323,6 +430,9 @@ export class AuctionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await auction.deleteOne({ session });
|
await auction.deleteOne({ session });
|
||||||
|
await AuctionHistoryModel.deleteMany({ auctionId: auction._id }).session(
|
||||||
|
session,
|
||||||
|
);
|
||||||
if (match.status === 'team-built') {
|
if (match.status === 'team-built') {
|
||||||
await this.tournamentCodeService.releaseFromMatch(match);
|
await this.tournamentCodeService.releaseFromMatch(match);
|
||||||
match.status = 'recruiting';
|
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: {
|
private applyAuctionCut(match: {
|
||||||
participants: MatchParticipant[];
|
participants: MatchParticipant[];
|
||||||
}): MatchParticipant[] {
|
}): MatchParticipant[] {
|
||||||
|
|||||||
@@ -7,9 +7,14 @@ import {
|
|||||||
IsInt,
|
IsInt,
|
||||||
IsMongoId,
|
IsMongoId,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
|
Max,
|
||||||
Min,
|
Min,
|
||||||
ValidateNested,
|
ValidateNested,
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
|
import { AUCTION_TOP_TIER_THRESHOLDS } from '../../global/database/schema';
|
||||||
|
|
||||||
|
export type AuctionTopTierThreshold =
|
||||||
|
(typeof AUCTION_TOP_TIER_THRESHOLDS)[number];
|
||||||
|
|
||||||
class CaptainAssignmentDto {
|
class CaptainAssignmentDto {
|
||||||
@IsInt()
|
@IsInt()
|
||||||
@@ -18,6 +23,12 @@ class CaptainAssignmentDto {
|
|||||||
|
|
||||||
@IsMongoId()
|
@IsMongoId()
|
||||||
userId!: string;
|
userId!: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(100)
|
||||||
|
@Max(100000)
|
||||||
|
initialPoints?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class StartAuctionDto {
|
export class StartAuctionDto {
|
||||||
@@ -30,9 +41,14 @@ export class StartAuctionDto {
|
|||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsInt()
|
@IsInt()
|
||||||
@Min(1)
|
@Min(100)
|
||||||
|
@Max(100000)
|
||||||
initialPoints?: number;
|
initialPoints?: number;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsEnum(AUCTION_TOP_TIER_THRESHOLDS)
|
||||||
|
topTierThreshold?: AuctionTopTierThreshold;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsInt()
|
@IsInt()
|
||||||
@Min(5)
|
@Min(5)
|
||||||
@@ -58,3 +74,9 @@ export class SoldDto {
|
|||||||
@IsEnum(['TOP', 'JGL', 'MID', 'ADC', 'SUP'])
|
@IsEnum(['TOP', 'JGL', 'MID', 'ADC', 'SUP'])
|
||||||
assignedPosition?: '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'
|
| 'presenting'
|
||||||
| 'bidding'
|
| 'bidding'
|
||||||
| 'sold'
|
| 'sold'
|
||||||
|
| 'passed'
|
||||||
| 'complete';
|
| 'complete';
|
||||||
export const AUCTION_PHASES: AuctionPhase[] = [
|
export const AUCTION_PHASES: AuctionPhase[] = [
|
||||||
'waiting',
|
'waiting',
|
||||||
'presenting',
|
'presenting',
|
||||||
'bidding',
|
'bidding',
|
||||||
'sold',
|
'sold',
|
||||||
|
'passed',
|
||||||
'complete',
|
'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 {
|
export interface MongooseTimestamps {
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
@@ -479,6 +497,7 @@ export interface AuctionPlayerSnapshot {
|
|||||||
tiers: TierInfo[];
|
tiers: TierInfo[];
|
||||||
masteries: ChampionMasteryEntry[];
|
masteries: ChampionMasteryEntry[];
|
||||||
recentStatsSummary?: RiotRecentStatsSummary;
|
recentStatsSummary?: RiotRecentStatsSummary;
|
||||||
|
passCount: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AuctionTeamMember {
|
export interface AuctionTeamMember {
|
||||||
@@ -506,6 +525,8 @@ export interface Auction extends MongooseTimestamps {
|
|||||||
phase: AuctionPhase;
|
phase: AuctionPhase;
|
||||||
teams: AuctionTeam[];
|
teams: AuctionTeam[];
|
||||||
order: AuctionPlayerSnapshot[];
|
order: AuctionPlayerSnapshot[];
|
||||||
|
passedQueue: AuctionPlayerSnapshot[];
|
||||||
|
auctionRound: number;
|
||||||
currentIndex: number;
|
currentIndex: number;
|
||||||
bids: AuctionBid[];
|
bids: AuctionBid[];
|
||||||
currentBid: number;
|
currentBid: number;
|
||||||
@@ -513,12 +534,26 @@ export interface Auction extends MongooseTimestamps {
|
|||||||
maxTimerSeconds: number;
|
maxTimerSeconds: number;
|
||||||
currentDeadline?: Date;
|
currentDeadline?: Date;
|
||||||
initialPoints: number;
|
initialPoints: number;
|
||||||
|
topTierThreshold: AuctionTopTierThreshold;
|
||||||
startedAt?: Date;
|
startedAt?: Date;
|
||||||
completedAt?: Date;
|
completedAt?: Date;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AuctionDocument = HydratedDocument<Auction>;
|
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 =====
|
// ===== Sub-schemas =====
|
||||||
const PositionPreferenceSubSchema = new Schema<PositionPreference>(
|
const PositionPreferenceSubSchema = new Schema<PositionPreference>(
|
||||||
{
|
{
|
||||||
@@ -1194,6 +1229,7 @@ const AuctionPlayerSnapshotSubSchema = new Schema<AuctionPlayerSnapshot>(
|
|||||||
default: [],
|
default: [],
|
||||||
},
|
},
|
||||||
recentStatsSummary: { type: RiotRecentStatsSummarySubSchema },
|
recentStatsSummary: { type: RiotRecentStatsSummarySubSchema },
|
||||||
|
passCount: { type: Number, required: true, default: 0 },
|
||||||
},
|
},
|
||||||
{ _id: false },
|
{ _id: false },
|
||||||
);
|
);
|
||||||
@@ -1251,6 +1287,12 @@ export const AuctionSchema = new Schema<Auction>(
|
|||||||
required: true,
|
required: true,
|
||||||
default: [],
|
default: [],
|
||||||
},
|
},
|
||||||
|
passedQueue: {
|
||||||
|
type: [AuctionPlayerSnapshotSubSchema],
|
||||||
|
required: true,
|
||||||
|
default: [],
|
||||||
|
},
|
||||||
|
auctionRound: { type: Number, required: true, default: 1, min: 1 },
|
||||||
currentIndex: { type: Number, required: true, default: 0 },
|
currentIndex: { type: Number, required: true, default: 0 },
|
||||||
bids: { type: [AuctionBidSubSchema], required: true, default: [] },
|
bids: { type: [AuctionBidSubSchema], required: true, default: [] },
|
||||||
currentBid: { type: Number, required: true, default: 0 },
|
currentBid: { type: Number, required: true, default: 0 },
|
||||||
@@ -1258,6 +1300,12 @@ export const AuctionSchema = new Schema<Auction>(
|
|||||||
maxTimerSeconds: { type: Number, required: true, default: 30 },
|
maxTimerSeconds: { type: Number, required: true, default: 30 },
|
||||||
currentDeadline: { type: Date, required: false },
|
currentDeadline: { type: Date, required: false },
|
||||||
initialPoints: { type: Number, required: true, default: 1000 },
|
initialPoints: { type: Number, required: true, default: 1000 },
|
||||||
|
topTierThreshold: {
|
||||||
|
type: String,
|
||||||
|
enum: AUCTION_TOP_TIER_THRESHOLDS,
|
||||||
|
required: true,
|
||||||
|
default: 'NONE',
|
||||||
|
},
|
||||||
startedAt: { type: Date, required: false },
|
startedAt: { type: Date, required: false },
|
||||||
completedAt: { 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[] = [
|
export const tournamentModelDefinitions: ModelDefinition[] = [
|
||||||
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
|
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
|
||||||
{ name: 'community', schema: CommunitySchema, schemaName: 'community' },
|
{ name: 'community', schema: CommunitySchema, schemaName: 'community' },
|
||||||
@@ -1284,6 +1364,11 @@ export const tournamentModelDefinitions: ModelDefinition[] = [
|
|||||||
},
|
},
|
||||||
{ name: 'match', schema: MatchSchema, schemaName: 'match' },
|
{ name: 'match', schema: MatchSchema, schemaName: 'match' },
|
||||||
{ name: 'auction', schema: AuctionSchema, schemaName: 'auction' },
|
{ name: 'auction', schema: AuctionSchema, schemaName: 'auction' },
|
||||||
|
{
|
||||||
|
name: 'auctionHistory',
|
||||||
|
schema: AuctionHistoryEntrySchema,
|
||||||
|
schemaName: 'auctionHistory',
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
export interface TournamentModelTypes {
|
export interface TournamentModelTypes {
|
||||||
@@ -1295,4 +1380,5 @@ export interface TournamentModelTypes {
|
|||||||
legacyImportJob: LegacyImportJob;
|
legacyImportJob: LegacyImportJob;
|
||||||
match: Match;
|
match: Match;
|
||||||
auction: Auction;
|
auction: Auction;
|
||||||
|
auctionHistory: AuctionHistoryEntry;
|
||||||
}
|
}
|
||||||
@@ -91,6 +91,14 @@ export class TournamentResultService {
|
|||||||
return result;
|
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> {
|
public async processPollJob(job: PollTournamentResultJob): Promise<void> {
|
||||||
const MatchModel = await this.connectionService.getModel('match');
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
const TournamentCodeModel =
|
const TournamentCodeModel =
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
} from '../lib/auth/msal.config';
|
} from '../lib/auth/msal.config';
|
||||||
import type {
|
import type {
|
||||||
ApiAuction,
|
ApiAuction,
|
||||||
|
ApiAuctionHistoryEntry,
|
||||||
ApiChampionStatsResponse,
|
ApiChampionStatsResponse,
|
||||||
ApiCommunity,
|
ApiCommunity,
|
||||||
ApiEnqueueRefreshResult,
|
ApiEnqueueRefreshResult,
|
||||||
@@ -133,6 +134,42 @@ export function useAuction(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useAuctionHistory(
|
||||||
|
matchId: string | undefined,
|
||||||
|
communityId = DEFAULT_COMMUNITY_ID,
|
||||||
|
options: { enabled?: boolean; refetchInterval?: number | false } = {},
|
||||||
|
) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['auction-history', communityId, matchId ?? null],
|
||||||
|
queryFn: () =>
|
||||||
|
apiFetch<ApiAuctionHistoryEntry[]>(
|
||||||
|
`/communities/${communityId}/matches/${matchId}/auction/history`,
|
||||||
|
),
|
||||||
|
enabled: Boolean(communityId && matchId && (options.enabled ?? true)),
|
||||||
|
retry: false,
|
||||||
|
refetchInterval: options.refetchInterval,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUndoAuction(communityId = DEFAULT_COMMUNITY_ID) {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: ({
|
||||||
|
matchId,
|
||||||
|
sequence,
|
||||||
|
}: {
|
||||||
|
matchId: string;
|
||||||
|
sequence: number;
|
||||||
|
}) =>
|
||||||
|
apiFetch<ApiAuction>(
|
||||||
|
`/communities/${communityId}/matches/${matchId}/auction/undo`,
|
||||||
|
{
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ sequence }),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export function useCreateMatch(communityId = DEFAULT_COMMUNITY_ID) {
|
export function useCreateMatch(communityId = DEFAULT_COMMUNITY_ID) {
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (body: MatchMutationRequest) =>
|
mutationFn: (body: MatchMutationRequest) =>
|
||||||
|
|||||||
@@ -85,6 +85,7 @@ export interface MatchDetailView {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface AuctionPlayerView extends ParticipantView {
|
export interface AuctionPlayerView extends ParticipantView {
|
||||||
|
passCount: number;
|
||||||
masteries: {
|
masteries: {
|
||||||
championId: number;
|
championId: number;
|
||||||
level: number;
|
level: number;
|
||||||
@@ -118,6 +119,8 @@ export interface AuctionStateView {
|
|||||||
currentPlayerIndex: number;
|
currentPlayerIndex: number;
|
||||||
totalPlayers: number;
|
totalPlayers: number;
|
||||||
auctionOrder: AuctionPlayerView[];
|
auctionOrder: AuctionPlayerView[];
|
||||||
|
passedQueue: AuctionPlayerView[];
|
||||||
|
auctionRound: number;
|
||||||
bids: {
|
bids: {
|
||||||
teamIndex: number;
|
teamIndex: number;
|
||||||
amount: number;
|
amount: number;
|
||||||
@@ -235,6 +238,7 @@ function mapAuctionPlayerToView(
|
|||||||
mainPosition,
|
mainPosition,
|
||||||
subPosition,
|
subPosition,
|
||||||
profileIconId: player.profileIconId,
|
profileIconId: player.profileIconId,
|
||||||
|
passCount: player.passCount ?? 0,
|
||||||
masteries: player.masteries.slice(0, 5).map((mastery) => ({
|
masteries: player.masteries.slice(0, 5).map((mastery) => ({
|
||||||
championId: mastery.championId,
|
championId: mastery.championId,
|
||||||
level: mastery.championLevel,
|
level: mastery.championLevel,
|
||||||
@@ -281,11 +285,13 @@ function mapAuctionTeamToView(
|
|||||||
(participant
|
(participant
|
||||||
? {
|
? {
|
||||||
...participant,
|
...participant,
|
||||||
|
passCount: 0,
|
||||||
masteries: [],
|
masteries: [],
|
||||||
recentStats: createEmptyRecentStatsView(),
|
recentStats: createEmptyRecentStatsView(),
|
||||||
}
|
}
|
||||||
: {
|
: {
|
||||||
...createFallbackParticipant(member.userId),
|
...createFallbackParticipant(member.userId),
|
||||||
|
passCount: 0,
|
||||||
masteries: [],
|
masteries: [],
|
||||||
recentStats: createEmptyRecentStatsView(),
|
recentStats: createEmptyRecentStatsView(),
|
||||||
});
|
});
|
||||||
@@ -464,6 +470,7 @@ export function mapApiAuctionToAuctionState(
|
|||||||
.map((participant) => [participant.userId, participant]),
|
.map((participant) => [participant.userId, participant]),
|
||||||
);
|
);
|
||||||
const auctionOrder = auction.order.map(mapAuctionPlayerToView);
|
const auctionOrder = auction.order.map(mapAuctionPlayerToView);
|
||||||
|
const passedQueue = (auction.passedQueue ?? []).map(mapAuctionPlayerToView);
|
||||||
const auctionPlayerLookup = new Map(
|
const auctionPlayerLookup = new Map(
|
||||||
auctionOrder.map((player) => [player.userId, player]),
|
auctionOrder.map((player) => [player.userId, player]),
|
||||||
);
|
);
|
||||||
@@ -499,6 +506,8 @@ export function mapApiAuctionToAuctionState(
|
|||||||
currentPlayerIndex,
|
currentPlayerIndex,
|
||||||
totalPlayers,
|
totalPlayers,
|
||||||
auctionOrder,
|
auctionOrder,
|
||||||
|
passedQueue,
|
||||||
|
auctionRound: auction.auctionRound ?? 1,
|
||||||
bids: auction.bids.map((bid) => ({
|
bids: auction.bids.map((bid) => ({
|
||||||
teamIndex: bid.teamIndex,
|
teamIndex: bid.teamIndex,
|
||||||
amount: bid.amount,
|
amount: bid.amount,
|
||||||
|
|||||||
@@ -12,7 +12,13 @@ export type AuctionPhase =
|
|||||||
| 'presenting'
|
| 'presenting'
|
||||||
| 'bidding'
|
| 'bidding'
|
||||||
| 'sold'
|
| 'sold'
|
||||||
|
| 'passed'
|
||||||
| 'complete';
|
| 'complete';
|
||||||
|
export type AuctionTopTierThreshold =
|
||||||
|
| 'NONE'
|
||||||
|
| 'EMERALD'
|
||||||
|
| 'DIAMOND'
|
||||||
|
| 'MASTER';
|
||||||
export type CommunityRole = 'owner' | 'admin' | 'member';
|
export type CommunityRole = 'owner' | 'admin' | 'member';
|
||||||
|
|
||||||
export interface ApiPositionPreference {
|
export interface ApiPositionPreference {
|
||||||
@@ -226,6 +232,7 @@ export interface ApiAuctionPlayerSnapshot {
|
|||||||
tiers: ApiTierInfo[];
|
tiers: ApiTierInfo[];
|
||||||
masteries: ApiChampionMasteryEntry[];
|
masteries: ApiChampionMasteryEntry[];
|
||||||
recentStatsSummary?: ApiRiotRecentStatsSummary;
|
recentStatsSummary?: ApiRiotRecentStatsSummary;
|
||||||
|
passCount: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ApiAuctionTeamMember {
|
export interface ApiAuctionTeamMember {
|
||||||
@@ -254,6 +261,8 @@ export interface ApiAuction {
|
|||||||
phase: AuctionPhase;
|
phase: AuctionPhase;
|
||||||
teams: ApiAuctionTeam[];
|
teams: ApiAuctionTeam[];
|
||||||
order: ApiAuctionPlayerSnapshot[];
|
order: ApiAuctionPlayerSnapshot[];
|
||||||
|
passedQueue: ApiAuctionPlayerSnapshot[];
|
||||||
|
auctionRound: number;
|
||||||
currentIndex: number;
|
currentIndex: number;
|
||||||
bids: ApiAuctionBid[];
|
bids: ApiAuctionBid[];
|
||||||
currentBid: number;
|
currentBid: number;
|
||||||
@@ -261,12 +270,27 @@ export interface ApiAuction {
|
|||||||
maxTimerSeconds: number;
|
maxTimerSeconds: number;
|
||||||
currentDeadline?: string;
|
currentDeadline?: string;
|
||||||
initialPoints: number;
|
initialPoints: number;
|
||||||
|
topTierThreshold: AuctionTopTierThreshold;
|
||||||
startedAt?: string;
|
startedAt?: string;
|
||||||
completedAt?: string;
|
completedAt?: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ApiAuctionHistoryEntry {
|
||||||
|
sequence: number;
|
||||||
|
action:
|
||||||
|
| 'start'
|
||||||
|
| 'open-bidding'
|
||||||
|
| 'bid'
|
||||||
|
| 'sold'
|
||||||
|
| 'passed'
|
||||||
|
| 'next'
|
||||||
|
| 'complete';
|
||||||
|
actionLabel: string;
|
||||||
|
takenAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ApiIdentity {
|
export interface ApiIdentity {
|
||||||
id: string;
|
id: string;
|
||||||
entraOid: string;
|
entraOid: string;
|
||||||
|
|||||||
+852
-762
File diff suppressed because it is too large.
Load diff
@@ -29,6 +29,7 @@ import {
|
|||||||
teamIndexLabel,
|
teamIndexLabel,
|
||||||
} from '../lib/league';
|
} from '../lib/league';
|
||||||
import type {
|
import type {
|
||||||
|
AuctionTopTierThreshold,
|
||||||
ApiMatchParticipant,
|
ApiMatchParticipant,
|
||||||
Position,
|
Position,
|
||||||
TeamSide,
|
TeamSide,
|
||||||
@@ -839,9 +840,11 @@ export default function MatchDetailPage() {
|
|||||||
)?.user ?? null;
|
)?.user ?? null;
|
||||||
const canUseMemberActions = Boolean(currentUser || authUserId);
|
const canUseMemberActions = Boolean(currentUser || authUserId);
|
||||||
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID);
|
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID);
|
||||||
const [captainSelections, setCaptainSelections] = useState<Record<string, string>>(
|
const [captainSelections, setCaptainSelections] = useState<
|
||||||
{},
|
Record<string, { userId: string; initialPoints: number }>
|
||||||
);
|
>({});
|
||||||
|
const [topTierThreshold, setTopTierThreshold] =
|
||||||
|
useState<AuctionTopTierThreshold>('NONE');
|
||||||
const pollTournamentResultMutation = usePollTournamentResult(
|
const pollTournamentResultMutation = usePollTournamentResult(
|
||||||
DEFAULT_COMMUNITY_ID,
|
DEFAULT_COMMUNITY_ID,
|
||||||
);
|
);
|
||||||
@@ -877,10 +880,13 @@ export default function MatchDetailPage() {
|
|||||||
captains: buildCaptainSlots(matchQuery.data?.participants ?? []).map(
|
captains: buildCaptainSlots(matchQuery.data?.participants ?? []).map(
|
||||||
(slot) => ({
|
(slot) => ({
|
||||||
teamIndex: slot.teamIndex,
|
teamIndex: slot.teamIndex,
|
||||||
userId: captainSelections[captainSlotKey(slot)],
|
userId: captainSelections[captainSlotKey(slot)]?.userId,
|
||||||
|
initialPoints:
|
||||||
|
captainSelections[captainSlotKey(slot)]?.initialPoints ?? 1000,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
initialPoints: 1000,
|
initialPoints: 1000,
|
||||||
|
topTierThreshold,
|
||||||
maxTimerSeconds: 30,
|
maxTimerSeconds: 30,
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
@@ -919,19 +925,23 @@ export default function MatchDetailPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setCaptainSelections((current) => {
|
setCaptainSelections((current) => {
|
||||||
const next: Record<string, string> = {};
|
const next: Record<string, { userId: string; initialPoints: number }> = {};
|
||||||
const usedUserIds = new Set<string>();
|
const usedUserIds = new Set<string>();
|
||||||
|
|
||||||
for (const slot of slots) {
|
for (const slot of slots) {
|
||||||
const key = captainSlotKey(slot);
|
const key = captainSlotKey(slot);
|
||||||
const currentUserId = current[key];
|
const currentSelection = current[key];
|
||||||
|
const currentUserId = currentSelection?.userId;
|
||||||
const currentIsValid =
|
const currentIsValid =
|
||||||
currentUserId &&
|
currentUserId &&
|
||||||
participants.some((participant) => participant.userId === currentUserId) &&
|
participants.some((participant) => participant.userId === currentUserId) &&
|
||||||
!usedUserIds.has(currentUserId);
|
!usedUserIds.has(currentUserId);
|
||||||
|
|
||||||
if (currentIsValid) {
|
if (currentIsValid) {
|
||||||
next[key] = currentUserId;
|
next[key] = {
|
||||||
|
userId: currentUserId,
|
||||||
|
initialPoints: currentSelection?.initialPoints ?? 1000,
|
||||||
|
};
|
||||||
usedUserIds.add(currentUserId);
|
usedUserIds.add(currentUserId);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -939,7 +949,10 @@ export default function MatchDetailPage() {
|
|||||||
const fallback = participants.find(
|
const fallback = participants.find(
|
||||||
(participant) => !usedUserIds.has(participant.userId),
|
(participant) => !usedUserIds.has(participant.userId),
|
||||||
);
|
);
|
||||||
next[key] = fallback?.userId ?? '';
|
next[key] = {
|
||||||
|
userId: fallback?.userId ?? '',
|
||||||
|
initialPoints: currentSelection?.initialPoints ?? 1000,
|
||||||
|
};
|
||||||
if (fallback) usedUserIds.add(fallback.userId);
|
if (fallback) usedUserIds.add(fallback.userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -990,8 +1003,8 @@ export default function MatchDetailPage() {
|
|||||||
);
|
);
|
||||||
const captainSlots = buildCaptainSlots(matchQuery.data.participants);
|
const captainSlots = buildCaptainSlots(matchQuery.data.participants);
|
||||||
const selectedCaptainIds = captainSlots
|
const selectedCaptainIds = captainSlots
|
||||||
.map((slot) => captainSelections[captainSlotKey(slot)])
|
.map((slot) => captainSelections[captainSlotKey(slot)]?.userId)
|
||||||
.filter(Boolean);
|
.filter((userId): userId is string => Boolean(userId));
|
||||||
const hasUniqueCaptainSelections =
|
const hasUniqueCaptainSelections =
|
||||||
selectedCaptainIds.length === captainSlots.length &&
|
selectedCaptainIds.length === captainSlots.length &&
|
||||||
new Set(selectedCaptainIds).size === selectedCaptainIds.length;
|
new Set(selectedCaptainIds).size === selectedCaptainIds.length;
|
||||||
@@ -1120,20 +1133,26 @@ export default function MatchDetailPage() {
|
|||||||
<div className="grid sm:grid-cols-2 gap-3">
|
<div className="grid sm:grid-cols-2 gap-3">
|
||||||
{captainSlots.map((slot) => {
|
{captainSlots.map((slot) => {
|
||||||
const key = captainSlotKey(slot);
|
const key = captainSlotKey(slot);
|
||||||
const currentValue = captainSelections[key] ?? '';
|
const currentSelection = captainSelections[key];
|
||||||
|
const currentValue = currentSelection?.userId ?? '';
|
||||||
return (
|
return (
|
||||||
<label
|
<label
|
||||||
key={key}
|
key={key}
|
||||||
className="text-xs text-base-content/45"
|
className="text-xs text-base-content/45"
|
||||||
>
|
>
|
||||||
{teamIndexLabel(slot.teamIndex)} 팀장
|
{teamIndexLabel(slot.teamIndex)} 팀장
|
||||||
|
<div className="mt-1 grid grid-cols-[minmax(0,1fr)_96px] gap-2">
|
||||||
<select
|
<select
|
||||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-2 py-2 text-sm"
|
className="w-full border border-base-content/10 bg-transparent px-2 py-2 text-sm"
|
||||||
value={currentValue}
|
value={currentValue}
|
||||||
onChange={(event) =>
|
onChange={(event) =>
|
||||||
setCaptainSelections((current) => ({
|
setCaptainSelections((current) => ({
|
||||||
...current,
|
...current,
|
||||||
[key]: event.target.value,
|
[key]: {
|
||||||
|
userId: event.target.value,
|
||||||
|
initialPoints:
|
||||||
|
current[key]?.initialPoints ?? 1000,
|
||||||
|
},
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
@@ -1155,6 +1174,30 @@ export default function MatchDetailPage() {
|
|||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</select>
|
</select>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min={100}
|
||||||
|
max={100000}
|
||||||
|
step={50}
|
||||||
|
className="w-full border border-base-content/10 bg-transparent px-2 py-2 text-sm tabular-nums"
|
||||||
|
value={currentSelection?.initialPoints ?? 1000}
|
||||||
|
onChange={(event) =>
|
||||||
|
setCaptainSelections((current) => ({
|
||||||
|
...current,
|
||||||
|
[key]: {
|
||||||
|
userId: current[key]?.userId ?? '',
|
||||||
|
initialPoints: Math.min(
|
||||||
|
100000,
|
||||||
|
Math.max(
|
||||||
|
100,
|
||||||
|
Number(event.target.value) || 100,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</label>
|
</label>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
@@ -1164,6 +1207,23 @@ export default function MatchDetailPage() {
|
|||||||
경매를 시작하려면 최소 10명이 필요합니다.
|
경매를 시작하려면 최소 10명이 필요합니다.
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
<label className="block text-xs text-base-content/45">
|
||||||
|
상위 티어 우선 등장
|
||||||
|
<select
|
||||||
|
className="mt-1 w-full max-w-xs border border-base-content/10 bg-transparent px-2 py-2 text-sm"
|
||||||
|
value={topTierThreshold}
|
||||||
|
onChange={(event) =>
|
||||||
|
setTopTierThreshold(
|
||||||
|
event.target.value as AuctionTopTierThreshold,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="NONE">없음</option>
|
||||||
|
<option value="EMERALD">EMERALD+</option>
|
||||||
|
<option value="DIAMOND">DIAMOND+</option>
|
||||||
|
<option value="MASTER">MASTER+</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
<div className="sm:col-span-2 flex items-center gap-3">
|
<div className="sm:col-span-2 flex items-center gap-3">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
Reference in new issue
Block a user