.
This commit is contained in:
1 parent
4baea89f89
commit
fd386ed202
32 files changed
+1128
-601
No files matched your search
@@ -39,8 +39,7 @@ export class AuctionController {
|
||||
matchId,
|
||||
communityId,
|
||||
captains: body.captains.map((c) => ({
|
||||
side: c.side,
|
||||
groupIndex: c.groupIndex ?? 1,
|
||||
teamIndex: c.teamIndex,
|
||||
userId: new mongoose.Types.ObjectId(c.userId),
|
||||
})),
|
||||
initialPoints: body.initialPoints ?? 1000,
|
||||
@@ -76,8 +75,7 @@ export class AuctionController {
|
||||
) {
|
||||
return this.auctionService.placeBid({
|
||||
matchId,
|
||||
side: body.side,
|
||||
groupIndex: body.groupIndex ?? 1,
|
||||
teamIndex: body.teamIndex,
|
||||
amount: body.amount,
|
||||
bidderUserId: this.resolveBidder(currentUser, body.bidderUserId),
|
||||
});
|
||||
|
||||
@@ -19,7 +19,6 @@ import type {
|
||||
AuctionDocument,
|
||||
IdentityDocument,
|
||||
Position,
|
||||
TeamSide,
|
||||
UserDocument,
|
||||
} from '../global/database/schema';
|
||||
import { AuctionService } from './auction.service';
|
||||
@@ -29,8 +28,7 @@ interface JoinAuctionPayload {
|
||||
}
|
||||
|
||||
interface BidPayload {
|
||||
side: TeamSide;
|
||||
groupIndex?: number;
|
||||
teamIndex: number;
|
||||
amount: number;
|
||||
bidderUserId?: string;
|
||||
}
|
||||
@@ -125,8 +123,7 @@ export class AuctionGateway
|
||||
try {
|
||||
const auction = await this.auctionService.placeBid({
|
||||
matchId: new mongoose.Types.ObjectId(matchId),
|
||||
side: payload.side,
|
||||
groupIndex: payload.groupIndex ?? 1,
|
||||
teamIndex: payload.teamIndex,
|
||||
amount: payload.amount,
|
||||
bidderUserId,
|
||||
});
|
||||
|
||||
@@ -31,10 +31,9 @@ describe('AuctionService', () => {
|
||||
};
|
||||
}
|
||||
|
||||
function createFullTeam(side: 'blue' | 'red') {
|
||||
function createFullTeam(teamIndex: number) {
|
||||
return {
|
||||
side,
|
||||
groupIndex: 1,
|
||||
teamIndex,
|
||||
captainUserId: new mongoose.Types.ObjectId(),
|
||||
points: 100,
|
||||
members: Array.from({ length: 4 }, () => ({
|
||||
@@ -49,7 +48,7 @@ describe('AuctionService', () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const auction = {
|
||||
phase: 'bidding',
|
||||
teams: [createFullTeam('blue'), createFullTeam('red')],
|
||||
teams: [createFullTeam(1), createFullTeam(2)],
|
||||
currentBid: 10,
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
@@ -62,8 +61,7 @@ describe('AuctionService', () => {
|
||||
await expect(
|
||||
service.placeBid({
|
||||
matchId,
|
||||
side: 'blue',
|
||||
groupIndex: 1,
|
||||
teamIndex: 1,
|
||||
amount: 20,
|
||||
}),
|
||||
).rejects.toThrow('Team already has maximum members.');
|
||||
@@ -74,7 +72,7 @@ describe('AuctionService', () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const auction = {
|
||||
phase: 'bidding',
|
||||
currentBidder: 'blue',
|
||||
currentBidderTeamIndex: 1,
|
||||
currentBid: 20,
|
||||
currentIndex: 0,
|
||||
order: [
|
||||
@@ -83,7 +81,7 @@ describe('AuctionService', () => {
|
||||
preferredPositions: [{ position: 'ADC', priority: 1 }],
|
||||
},
|
||||
],
|
||||
teams: [createFullTeam('blue'), createFullTeam('red')],
|
||||
teams: [createFullTeam(1), createFullTeam(2)],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const { service } = createService({
|
||||
@@ -112,7 +110,7 @@ describe('AuctionService', () => {
|
||||
order: [{ userId: blueMemberId }, { userId: redMemberId }],
|
||||
teams: [
|
||||
{
|
||||
side: 'blue',
|
||||
teamIndex: 1,
|
||||
captainUserId: blueCaptainId,
|
||||
points: 970,
|
||||
members: [
|
||||
@@ -124,7 +122,7 @@ describe('AuctionService', () => {
|
||||
],
|
||||
},
|
||||
{
|
||||
side: 'red',
|
||||
teamIndex: 2,
|
||||
captainUserId: redCaptainId,
|
||||
points: 940,
|
||||
members: [
|
||||
@@ -178,9 +176,8 @@ describe('AuctionService', () => {
|
||||
expect(match.save).toHaveBeenCalledTimes(1);
|
||||
expect(match.teams).toEqual([
|
||||
{
|
||||
side: 'blue',
|
||||
groupIndex: 1,
|
||||
name: '블루팀',
|
||||
teamIndex: 1,
|
||||
name: '1팀',
|
||||
captainUserId: blueCaptainId,
|
||||
members: [
|
||||
{
|
||||
@@ -196,9 +193,8 @@ describe('AuctionService', () => {
|
||||
],
|
||||
},
|
||||
{
|
||||
side: 'red',
|
||||
groupIndex: 1,
|
||||
name: '레드팀',
|
||||
teamIndex: 2,
|
||||
name: '2팀',
|
||||
captainUserId: redCaptainId,
|
||||
members: [
|
||||
{
|
||||
@@ -233,9 +229,8 @@ describe('AuctionService', () => {
|
||||
status: 'team-built',
|
||||
teams: [
|
||||
{
|
||||
side: 'blue',
|
||||
groupIndex: 1,
|
||||
name: '블루팀',
|
||||
teamIndex: 1,
|
||||
name: '1팀',
|
||||
members: [],
|
||||
},
|
||||
],
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
MatchTeamMember,
|
||||
Position,
|
||||
RiotAccount,
|
||||
TeamSide,
|
||||
} from '../global/database/schema';
|
||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||
import type { RiotPlatformRoute, RiotRegionalRoute } from '../riot/riot.types';
|
||||
@@ -30,8 +29,7 @@ interface StartAuctionParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
captains: {
|
||||
side: TeamSide;
|
||||
groupIndex: number;
|
||||
teamIndex: number;
|
||||
userId: mongoose.Types.ObjectId;
|
||||
}[];
|
||||
initialPoints: number;
|
||||
@@ -40,8 +38,7 @@ interface StartAuctionParams {
|
||||
|
||||
interface PlaceBidParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
side: TeamSide;
|
||||
groupIndex: number;
|
||||
teamIndex: number;
|
||||
amount: number;
|
||||
bidderUserId?: mongoose.Types.ObjectId;
|
||||
}
|
||||
@@ -90,13 +87,16 @@ export class AuctionService {
|
||||
throw new BadRequestException('Not enough participants (need at least 10).');
|
||||
}
|
||||
const expectedCaptainCount = desiredAuctionCount / AUCTION_MAX_TEAM_SIZE;
|
||||
const groupCount = expectedCaptainCount / 2;
|
||||
if (params.captains.length !== expectedCaptainCount) {
|
||||
throw new BadRequestException(
|
||||
`Expected ${expectedCaptainCount} captains for ${desiredAuctionCount} participants.`,
|
||||
);
|
||||
}
|
||||
this.assertCaptainAssignments(params.captains, activeParticipants, groupCount);
|
||||
this.assertCaptainAssignments(
|
||||
params.captains,
|
||||
activeParticipants,
|
||||
expectedCaptainCount,
|
||||
);
|
||||
const captainUserIds = params.captains.map((c) => c.userId);
|
||||
|
||||
const basePlayerUsers = await UserModel.find({
|
||||
@@ -158,8 +158,7 @@ export class AuctionService {
|
||||
matchId: params.matchId,
|
||||
phase: 'presenting',
|
||||
teams: params.captains.map((c) => ({
|
||||
side: c.side,
|
||||
groupIndex: c.groupIndex,
|
||||
teamIndex: c.teamIndex,
|
||||
captainUserId: c.userId,
|
||||
points: params.initialPoints,
|
||||
members: [],
|
||||
@@ -206,8 +205,7 @@ export class AuctionService {
|
||||
}
|
||||
auction.phase = 'bidding';
|
||||
auction.currentBid = 0;
|
||||
auction.currentBidder = undefined;
|
||||
auction.currentBidderGroupIndex = undefined;
|
||||
auction.currentBidderTeamIndex = undefined;
|
||||
auction.currentDeadline = this.createDeadline(auction.maxTimerSeconds);
|
||||
await auction.save();
|
||||
return auction;
|
||||
@@ -218,7 +216,7 @@ export class AuctionService {
|
||||
if (auction.phase !== 'bidding') {
|
||||
throw new BadRequestException('Auction is not in bidding phase.');
|
||||
}
|
||||
const team = this.findAuctionTeam(auction, params.side, params.groupIndex);
|
||||
const team = this.findAuctionTeamByIndex(auction, params.teamIndex);
|
||||
if (!team) throw new BadRequestException('Unknown team.');
|
||||
if (params.amount <= auction.currentBid) {
|
||||
throw new BadRequestException('Bid must exceed current bid.');
|
||||
@@ -230,14 +228,12 @@ export class AuctionService {
|
||||
// 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다.
|
||||
|
||||
auction.currentBid = params.amount;
|
||||
auction.currentBidder = params.side;
|
||||
auction.currentBidderGroupIndex = params.groupIndex;
|
||||
auction.currentBidderTeamIndex = params.teamIndex;
|
||||
auction.currentDeadline = this.createDeadline(
|
||||
this.resolveBidExtensionSeconds(auction),
|
||||
);
|
||||
auction.bids.push({
|
||||
side: params.side,
|
||||
groupIndex: params.groupIndex,
|
||||
teamIndex: params.teamIndex,
|
||||
amount: params.amount,
|
||||
bidderUserId: team.captainUserId,
|
||||
timestamp: new Date(),
|
||||
@@ -251,13 +247,12 @@ export class AuctionService {
|
||||
if (auction.phase !== 'bidding') {
|
||||
throw new BadRequestException('Auction is not in bidding phase.');
|
||||
}
|
||||
if (!auction.currentBidder || auction.currentBid <= 0) {
|
||||
if (!auction.currentBidderTeamIndex || auction.currentBid <= 0) {
|
||||
throw new BadRequestException('No bid to mark sold.');
|
||||
}
|
||||
const team = this.findAuctionTeam(
|
||||
const team = this.findAuctionTeamByIndex(
|
||||
auction,
|
||||
auction.currentBidder,
|
||||
auction.currentBidderGroupIndex ?? 1,
|
||||
auction.currentBidderTeamIndex,
|
||||
);
|
||||
if (!team) throw new BadRequestException('Winning team not found.');
|
||||
this.assertTeamHasSlot(team);
|
||||
@@ -293,8 +288,7 @@ export class AuctionService {
|
||||
auction.currentIndex = nextIndex;
|
||||
auction.phase = 'presenting';
|
||||
auction.currentBid = 0;
|
||||
auction.currentBidder = undefined;
|
||||
auction.currentBidderGroupIndex = undefined;
|
||||
auction.currentBidderTeamIndex = undefined;
|
||||
}
|
||||
auction.currentDeadline = undefined;
|
||||
await auction.save();
|
||||
@@ -372,18 +366,13 @@ export class AuctionService {
|
||||
private assertCaptainAssignments(
|
||||
captains: StartAuctionParams['captains'],
|
||||
activeParticipants: Array<{ userId: mongoose.Types.ObjectId }>,
|
||||
groupCount: number,
|
||||
expectedCaptainCount: number,
|
||||
): void {
|
||||
const activeUserIds = new Set(
|
||||
activeParticipants.map((participant) => participant.userId.toString()),
|
||||
);
|
||||
const captainUserIds = new Set<string>();
|
||||
const teamKeys = new Set<string>();
|
||||
const requiredKeys = new Set<string>();
|
||||
for (let groupIndex = 1; groupIndex <= groupCount; groupIndex += 1) {
|
||||
requiredKeys.add(`blue:${groupIndex}`);
|
||||
requiredKeys.add(`red:${groupIndex}`);
|
||||
}
|
||||
const teamIndexes = new Set<number>();
|
||||
|
||||
for (const captain of captains) {
|
||||
const userId = captain.userId.toString();
|
||||
@@ -397,31 +386,31 @@ export class AuctionService {
|
||||
}
|
||||
captainUserIds.add(userId);
|
||||
|
||||
if (captain.groupIndex < 1 || captain.groupIndex > groupCount) {
|
||||
throw new BadRequestException('Captain groupIndex is out of range.');
|
||||
if (
|
||||
!Number.isInteger(captain.teamIndex) ||
|
||||
captain.teamIndex < 1 ||
|
||||
captain.teamIndex > expectedCaptainCount
|
||||
) {
|
||||
throw new BadRequestException('Captain teamIndex is out of range.');
|
||||
}
|
||||
const key = `${captain.side}:${captain.groupIndex}`;
|
||||
if (teamKeys.has(key)) {
|
||||
if (teamIndexes.has(captain.teamIndex)) {
|
||||
throw new BadRequestException('Duplicate captain team assignment.');
|
||||
}
|
||||
teamKeys.add(key);
|
||||
teamIndexes.add(captain.teamIndex);
|
||||
}
|
||||
|
||||
for (const key of requiredKeys) {
|
||||
if (!teamKeys.has(key)) {
|
||||
throw new BadRequestException('Each group needs one blue and one red captain.');
|
||||
for (let teamIndex = 1; teamIndex <= expectedCaptainCount; teamIndex += 1) {
|
||||
if (!teamIndexes.has(teamIndex)) {
|
||||
throw new BadRequestException('Each teamIndex needs one captain.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private findAuctionTeam(
|
||||
private findAuctionTeamByIndex(
|
||||
auction: AuctionDocument,
|
||||
side: TeamSide,
|
||||
groupIndex: number,
|
||||
teamIndex: number,
|
||||
): AuctionTeam | undefined {
|
||||
return auction.teams.find(
|
||||
(team) => team.side === side && (team.groupIndex ?? 1) === groupIndex,
|
||||
);
|
||||
return auction.teams.find((team) => team.teamIndex === teamIndex);
|
||||
}
|
||||
|
||||
private createDeadline(secondsFromNow: number): Date {
|
||||
@@ -485,9 +474,8 @@ export class AuctionService {
|
||||
];
|
||||
|
||||
return {
|
||||
side: team.side,
|
||||
groupIndex: team.groupIndex ?? 1,
|
||||
name: this.resolveTeamName(team.side, team.groupIndex ?? 1, auction.teams),
|
||||
teamIndex: team.teamIndex,
|
||||
name: this.resolveTeamName(team.teamIndex),
|
||||
captainUserId: team.captainUserId,
|
||||
members,
|
||||
};
|
||||
@@ -593,14 +581,8 @@ export class AuctionService {
|
||||
}, 0);
|
||||
}
|
||||
|
||||
private resolveTeamName(
|
||||
side: TeamSide,
|
||||
groupIndex: number,
|
||||
teams: AuctionTeam[],
|
||||
): string {
|
||||
const groupCount = new Set(teams.map((team) => team.groupIndex ?? 1)).size;
|
||||
const sideLabel = side === 'blue' ? '블루팀' : '레드팀';
|
||||
return groupCount <= 1 ? sideLabel : `${groupIndex}조 ${sideLabel}`;
|
||||
private resolveTeamName(teamIndex: number): string {
|
||||
return `${teamIndex}팀`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,17 +10,11 @@ import {
|
||||
Min,
|
||||
ValidateNested,
|
||||
} from 'class-validator';
|
||||
import { TEAM_SIDES } from '../../global/database/schema';
|
||||
import type { TeamSide } from '../../global/database/schema';
|
||||
|
||||
class CaptainAssignmentDto {
|
||||
@IsEnum(TEAM_SIDES)
|
||||
side!: TeamSide;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
groupIndex?: number;
|
||||
teamIndex!: number;
|
||||
|
||||
@IsMongoId()
|
||||
userId!: string;
|
||||
@@ -46,13 +40,9 @@ export class StartAuctionDto {
|
||||
}
|
||||
|
||||
export class PlaceBidDto {
|
||||
@IsEnum(TEAM_SIDES)
|
||||
side!: TeamSide;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
groupIndex?: number;
|
||||
teamIndex!: number;
|
||||
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
|
||||
@@ -47,6 +47,7 @@ interface InternalRecord {
|
||||
userId: string;
|
||||
summonerName: string;
|
||||
profileIconId: number;
|
||||
teamIndex: number;
|
||||
side: TeamSide;
|
||||
championId: number;
|
||||
championLevel: number;
|
||||
@@ -81,6 +82,7 @@ interface InternalGameDetail {
|
||||
gameDuration: number;
|
||||
winnerSide: TeamSide;
|
||||
teams: Array<{
|
||||
teamIndex: number;
|
||||
side: TeamSide;
|
||||
win: boolean;
|
||||
objectives: { baron: number; dragon: number; tower: number };
|
||||
@@ -237,12 +239,14 @@ export class CommunityStatsService {
|
||||
gameCreation: game.gameCreation,
|
||||
gameDuration: game.gameDuration,
|
||||
teams: game.teams.map((team) => ({
|
||||
teamIndex: team.teamIndex,
|
||||
side: team.side,
|
||||
win: team.win,
|
||||
objectives: team.objectives,
|
||||
participants: team.participants.map((record) => ({
|
||||
userId: record.userId,
|
||||
summonerName: record.summonerName,
|
||||
teamIndex: record.teamIndex,
|
||||
side: record.side,
|
||||
teamPosition: record.teamPosition,
|
||||
championId: record.championId,
|
||||
@@ -454,17 +458,19 @@ export class CommunityStatsService {
|
||||
scheduledAt: match.scheduledAt.toISOString(),
|
||||
status: match.status === 'finished' ? 'finished' : 'in-progress',
|
||||
gameCount: match.gameCount,
|
||||
blueScore: match.result?.blueScore ?? 0,
|
||||
redScore: match.result?.redScore ?? 0,
|
||||
winnerSide: match.result?.winnerSide,
|
||||
winnerTeamIndex: match.result?.winnerTeamIndex,
|
||||
seriesResults: match.result?.seriesResults ?? [],
|
||||
games: games.map((game) => ({
|
||||
gameNumber: game.gameNumber,
|
||||
riotMatchId: game.riotMatchId ?? null,
|
||||
blueTeamIndex: game.blueTeamIndex,
|
||||
redTeamIndex: game.redTeamIndex,
|
||||
winnerTeamIndex: game.winnerTeamIndex ?? null,
|
||||
winnerSide: game.winnerSide ?? null,
|
||||
gameDuration: game.gameDuration,
|
||||
})),
|
||||
teams: match.teams.map((team) => ({
|
||||
side: team.side,
|
||||
teamIndex: team.teamIndex,
|
||||
name: team.name,
|
||||
members: team.members.map((member) => {
|
||||
const participant = participantById.get(member.userId.toString());
|
||||
@@ -508,6 +514,8 @@ export class CommunityStatsService {
|
||||
gameDuration: game.gameDuration,
|
||||
winnerSide: game.winnerSide,
|
||||
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
|
||||
const teamIndex =
|
||||
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
|
||||
const rawTeamId = rawTeamIdBySide.get(side);
|
||||
const rawTeam = raw.info.teams.find((team) => team.teamId === rawTeamId);
|
||||
const teamRawParticipants = raw.info.participants.filter(
|
||||
@@ -522,6 +530,7 @@ export class CommunityStatsService {
|
||||
0,
|
||||
);
|
||||
return {
|
||||
teamIndex,
|
||||
side,
|
||||
win: game.winnerSide === side,
|
||||
objectives: {
|
||||
@@ -559,6 +568,7 @@ export class CommunityStatsService {
|
||||
gameDuration: game.gameDuration,
|
||||
winnerSide: game.winnerSide,
|
||||
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
|
||||
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
|
||||
side,
|
||||
win: game.winnerSide === side,
|
||||
objectives: { baron: 0, dragon: 0, tower: 0 },
|
||||
@@ -621,6 +631,7 @@ export class CommunityStatsService {
|
||||
rawParticipant?.summonerName ??
|
||||
'Unknown',
|
||||
profileIconId: snapshot?.profileIconId ?? 0,
|
||||
teamIndex: participant.teamIndex,
|
||||
side: participant.side,
|
||||
championId: participant.championId,
|
||||
championLevel: rawParticipant?.champLevel ?? 0,
|
||||
|
||||
@@ -22,17 +22,25 @@ export interface InternalMatchCardView {
|
||||
scheduledAt: string;
|
||||
status: 'finished' | 'in-progress';
|
||||
gameCount: number;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
winnerSide?: TeamSide;
|
||||
winnerTeamIndex?: number;
|
||||
seriesResults: Array<{
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
teamBWins: number;
|
||||
winnerTeamIndex?: number;
|
||||
}>;
|
||||
games: Array<{
|
||||
gameNumber: number;
|
||||
riotMatchId: string | null;
|
||||
blueTeamIndex: number;
|
||||
redTeamIndex: number;
|
||||
winnerTeamIndex: number | null;
|
||||
winnerSide: TeamSide | null;
|
||||
gameDuration: number;
|
||||
}>;
|
||||
teams: Array<{
|
||||
side: TeamSide;
|
||||
teamIndex: number;
|
||||
name: string;
|
||||
members: Array<{
|
||||
userId: string;
|
||||
@@ -101,12 +109,14 @@ export interface InternalMatchDetailResponse {
|
||||
gameCreation: number;
|
||||
gameDuration: number;
|
||||
teams: Array<{
|
||||
teamIndex: number;
|
||||
side: TeamSide;
|
||||
win: boolean;
|
||||
objectives: { baron: number; dragon: number; tower: number };
|
||||
participants: Array<{
|
||||
userId: string | null;
|
||||
summonerName: string;
|
||||
teamIndex: number;
|
||||
side: TeamSide;
|
||||
teamPosition: string;
|
||||
championId: number;
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import { migrateTeamIndex } from './20260502-team-index';
|
||||
|
||||
function createDb(params: {
|
||||
auctions?: Array<Record<string, unknown>>;
|
||||
matches?: Array<Record<string, unknown>>;
|
||||
}) {
|
||||
const collections = {
|
||||
auction: params.auctions ?? [],
|
||||
match: params.matches ?? [],
|
||||
};
|
||||
|
||||
return {
|
||||
collections,
|
||||
db: {
|
||||
collection(name: string) {
|
||||
const key = name === 'auction' ? 'auction' : 'match';
|
||||
const docs = collections[key];
|
||||
return {
|
||||
find() {
|
||||
return {
|
||||
limit() {
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const doc of docs) yield doc;
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
async bulkWrite(writes: Array<{
|
||||
updateOne: {
|
||||
filter: { _id: unknown };
|
||||
update: {
|
||||
$set: Record<string, unknown>;
|
||||
$unset: Record<string, ''>;
|
||||
};
|
||||
};
|
||||
}>) {
|
||||
for (const write of writes) {
|
||||
const doc = docs.find((item) => item._id === write.updateOne.filter._id);
|
||||
if (!doc) continue;
|
||||
Object.assign(doc, write.updateOne.update.$set);
|
||||
for (const key of Object.keys(write.updateOne.update.$unset)) {
|
||||
delete doc[key];
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('migrateTeamIndex', () => {
|
||||
it('migrates auction and match team identity fields', async () => {
|
||||
const { db, collections } = createDb({
|
||||
auctions: [
|
||||
{
|
||||
_id: 'auction-1',
|
||||
teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }],
|
||||
bids: [{ side: 'red', groupIndex: 1, amount: 100 }],
|
||||
currentBidder: 'red',
|
||||
currentBidderGroupIndex: 1,
|
||||
},
|
||||
],
|
||||
matches: [
|
||||
{
|
||||
_id: 'match-1',
|
||||
teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }],
|
||||
result: {
|
||||
winnerSide: 'blue',
|
||||
blueScore: 1,
|
||||
redScore: 0,
|
||||
games: [
|
||||
{
|
||||
gameNumber: 1,
|
||||
riotMatchId: 'KR_1',
|
||||
winnerSide: 'blue',
|
||||
blueGroupIndex: 1,
|
||||
redGroupIndex: 1,
|
||||
participants: [
|
||||
{ userId: 'u1', side: 'blue' },
|
||||
{ userId: 'u2', side: 'red' },
|
||||
],
|
||||
},
|
||||
],
|
||||
seriesResults: [
|
||||
{
|
||||
blueGroupIndex: 1,
|
||||
redGroupIndex: 1,
|
||||
blueScore: 1,
|
||||
redScore: 0,
|
||||
winnerSide: 'blue',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const stats = await migrateTeamIndex(db, { dryRun: false });
|
||||
|
||||
expect(stats).toEqual({
|
||||
scannedAuctions: 1,
|
||||
changedAuctions: 1,
|
||||
scannedMatches: 1,
|
||||
changedMatches: 1,
|
||||
});
|
||||
expect(collections.auction[0]).toMatchObject({
|
||||
teams: [{ teamIndex: 1 }, { teamIndex: 2 }],
|
||||
bids: [{ teamIndex: 2, amount: 100 }],
|
||||
currentBidderTeamIndex: 2,
|
||||
});
|
||||
expect(collections.match[0]).toMatchObject({
|
||||
teams: [{ teamIndex: 1, name: '1팀' }, { teamIndex: 2, name: '2팀' }],
|
||||
result: {
|
||||
winnerTeamIndex: 1,
|
||||
games: [
|
||||
{
|
||||
blueTeamIndex: 1,
|
||||
redTeamIndex: 2,
|
||||
winnerTeamIndex: 1,
|
||||
participants: [
|
||||
{ teamIndex: 1, side: 'blue' },
|
||||
{ teamIndex: 2, side: 'red' },
|
||||
],
|
||||
},
|
||||
],
|
||||
seriesResults: [
|
||||
{
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
teamAWins: 1,
|
||||
teamBWins: 0,
|
||||
winnerTeamIndex: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(collections.auction[0]).not.toHaveProperty('currentBidder');
|
||||
expect(collections.match[0].result).not.toHaveProperty('blueScore');
|
||||
});
|
||||
|
||||
it('is idempotent after applying updates', async () => {
|
||||
const { db } = createDb({
|
||||
matches: [
|
||||
{
|
||||
_id: 'match-1',
|
||||
teams: [{ side: 'blue', groupIndex: 1 }],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await migrateTeamIndex(db, { dryRun: false });
|
||||
const stats = await migrateTeamIndex(db, { dryRun: false });
|
||||
|
||||
expect(stats.changedMatches).toBe(0);
|
||||
expect(stats.changedAuctions).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,335 @@
|
||||
type LegacySide = 'blue' | 'red';
|
||||
|
||||
interface MigrationCollection {
|
||||
find(filter: Record<string, unknown>): {
|
||||
limit(limit: number): AsyncIterable<AnyDoc>;
|
||||
};
|
||||
bulkWrite(
|
||||
writes: Array<{
|
||||
updateOne: {
|
||||
filter: { _id: unknown };
|
||||
update: { $set: Record<string, unknown>; $unset: Record<string, ''> };
|
||||
};
|
||||
}>,
|
||||
options: { ordered: boolean },
|
||||
): Promise<unknown>;
|
||||
}
|
||||
|
||||
interface MigrationDb {
|
||||
collection(name: string): MigrationCollection;
|
||||
}
|
||||
|
||||
interface MigrationOptions {
|
||||
dryRun?: boolean;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
interface MigrationStats {
|
||||
scannedAuctions: number;
|
||||
changedAuctions: number;
|
||||
scannedMatches: number;
|
||||
changedMatches: number;
|
||||
}
|
||||
|
||||
type AnyDoc = Record<string, unknown> & { _id: unknown };
|
||||
|
||||
export async function migrateTeamIndex(
|
||||
db: MigrationDb,
|
||||
options: MigrationOptions = {},
|
||||
): Promise<MigrationStats> {
|
||||
const dryRun = options.dryRun ?? true;
|
||||
const stats: MigrationStats = {
|
||||
scannedAuctions: 0,
|
||||
changedAuctions: 0,
|
||||
scannedMatches: 0,
|
||||
changedMatches: 0,
|
||||
};
|
||||
|
||||
await migrateCollection(db.collection('auction'), options.limit, dryRun, stats, 'auction');
|
||||
await migrateCollection(db.collection('match'), options.limit, dryRun, stats, 'match');
|
||||
|
||||
return stats;
|
||||
}
|
||||
|
||||
async function migrateCollection(
|
||||
collection: MigrationCollection,
|
||||
limit: number | undefined,
|
||||
dryRun: boolean,
|
||||
stats: MigrationStats,
|
||||
kind: 'auction' | 'match',
|
||||
) {
|
||||
const cursor = collection.find({}).limit(limit ?? 0);
|
||||
const writes: Array<{
|
||||
updateOne: {
|
||||
filter: { _id: unknown };
|
||||
update: { $set: Record<string, unknown>; $unset: Record<string, ''> };
|
||||
};
|
||||
}> = [];
|
||||
|
||||
for await (const doc of cursor) {
|
||||
if (kind === 'auction') stats.scannedAuctions += 1;
|
||||
if (kind === 'match') stats.scannedMatches += 1;
|
||||
|
||||
const update = kind === 'auction' ? migrateAuction(doc) : migrateMatch(doc);
|
||||
if (!update) continue;
|
||||
|
||||
if (kind === 'auction') stats.changedAuctions += 1;
|
||||
if (kind === 'match') stats.changedMatches += 1;
|
||||
writes.push({
|
||||
updateOne: {
|
||||
filter: { _id: doc._id },
|
||||
update,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (!dryRun && writes.length > 0) {
|
||||
await collection.bulkWrite(writes, { ordered: false });
|
||||
}
|
||||
}
|
||||
|
||||
function migrateAuction(doc: AnyDoc) {
|
||||
const set: Record<string, unknown> = {};
|
||||
const unset: Record<string, ''> = {};
|
||||
let changed = false;
|
||||
|
||||
const teams = asArray(doc.teams).map((team) => {
|
||||
const migrated = { ...team };
|
||||
const teamIndex = readTeamIndex(migrated);
|
||||
if (teamIndex !== undefined) migrated.teamIndex = teamIndex;
|
||||
if ('side' in migrated || 'groupIndex' in migrated) changed = true;
|
||||
delete migrated.side;
|
||||
delete migrated.groupIndex;
|
||||
return migrated;
|
||||
});
|
||||
if (changed) set.teams = teams;
|
||||
|
||||
const bids = asArray(doc.bids).map((bid) => {
|
||||
const migrated = { ...bid };
|
||||
const teamIndex = readTeamIndex(migrated);
|
||||
if (teamIndex !== undefined) migrated.teamIndex = teamIndex;
|
||||
if ('side' in migrated || 'groupIndex' in migrated) changed = true;
|
||||
delete migrated.side;
|
||||
delete migrated.groupIndex;
|
||||
return migrated;
|
||||
});
|
||||
if (changed) set.bids = bids;
|
||||
|
||||
if (
|
||||
typeof doc.currentBidderTeamIndex !== 'number' &&
|
||||
isSide(doc.currentBidder)
|
||||
) {
|
||||
set.currentBidderTeamIndex = sideGroupToTeamIndex(
|
||||
doc.currentBidder,
|
||||
numberOrDefault(doc.currentBidderGroupIndex, 1),
|
||||
);
|
||||
changed = true;
|
||||
}
|
||||
if ('currentBidder' in doc || 'currentBidderGroupIndex' in doc) {
|
||||
unset.currentBidder = '';
|
||||
unset.currentBidderGroupIndex = '';
|
||||
changed = true;
|
||||
}
|
||||
|
||||
return changed ? { $set: set, $unset: unset } : null;
|
||||
}
|
||||
|
||||
function migrateMatch(doc: AnyDoc) {
|
||||
const set: Record<string, unknown> = {};
|
||||
const unset: Record<string, ''> = {};
|
||||
let changed = false;
|
||||
|
||||
const teams = asArray(doc.teams).map((team) => {
|
||||
const migrated = { ...team };
|
||||
const teamIndex = readTeamIndex(migrated);
|
||||
if (teamIndex !== undefined) migrated.teamIndex = teamIndex;
|
||||
if (!migrated.name && typeof teamIndex === 'number') migrated.name = `${teamIndex}팀`;
|
||||
if ('side' in migrated || 'groupIndex' in migrated) changed = true;
|
||||
delete migrated.side;
|
||||
delete migrated.groupIndex;
|
||||
return migrated;
|
||||
});
|
||||
if (changed) set.teams = teams;
|
||||
|
||||
const result = isRecord(doc.result) ? migrateResult(doc.result) : null;
|
||||
if (result) {
|
||||
set.result = result;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
return changed ? { $set: set, $unset: unset } : null;
|
||||
}
|
||||
|
||||
function migrateResult(result: Record<string, unknown>) {
|
||||
let changed = false;
|
||||
const migrated = { ...result };
|
||||
|
||||
const games = asArray(result.games).map((game) => {
|
||||
const next = { ...game };
|
||||
const blueTeamIndex =
|
||||
numberOrUndefined(next.blueTeamIndex) ??
|
||||
sideGroupToTeamIndex('blue', numberOrDefault(next.blueGroupIndex, 1));
|
||||
const redTeamIndex =
|
||||
numberOrUndefined(next.redTeamIndex) ??
|
||||
sideGroupToTeamIndex('red', numberOrDefault(next.redGroupIndex, 1));
|
||||
const winnerSide = isSide(next.winnerSide) ? next.winnerSide : undefined;
|
||||
const winnerTeamIndex =
|
||||
numberOrUndefined(next.winnerTeamIndex) ??
|
||||
(winnerSide === 'blue'
|
||||
? blueTeamIndex
|
||||
: winnerSide === 'red'
|
||||
? redTeamIndex
|
||||
: undefined);
|
||||
|
||||
next.blueTeamIndex = blueTeamIndex;
|
||||
next.redTeamIndex = redTeamIndex;
|
||||
if (winnerTeamIndex !== undefined) next.winnerTeamIndex = winnerTeamIndex;
|
||||
next.participants = asArray(next.participants).map((participant) => {
|
||||
const migratedParticipant = { ...participant };
|
||||
if (typeof migratedParticipant.teamIndex !== 'number') {
|
||||
migratedParticipant.teamIndex =
|
||||
migratedParticipant.side === 'blue' ? blueTeamIndex : redTeamIndex;
|
||||
}
|
||||
return migratedParticipant;
|
||||
});
|
||||
if ('blueGroupIndex' in next || 'redGroupIndex' in next) changed = true;
|
||||
delete next.blueGroupIndex;
|
||||
delete next.redGroupIndex;
|
||||
return next;
|
||||
});
|
||||
migrated.games = games;
|
||||
|
||||
const seriesResults = asArray(result.seriesResults).map((series) => {
|
||||
if (typeof series.teamAIndex === 'number' && typeof series.teamBIndex === 'number') {
|
||||
return series;
|
||||
}
|
||||
changed = true;
|
||||
const legacyBlueTeamIndex = sideGroupToTeamIndex(
|
||||
'blue',
|
||||
numberOrDefault(series.blueGroupIndex, 1),
|
||||
);
|
||||
const legacyRedTeamIndex = sideGroupToTeamIndex(
|
||||
'red',
|
||||
numberOrDefault(series.redGroupIndex, 1),
|
||||
);
|
||||
const teamAIndex = Math.min(legacyBlueTeamIndex, legacyRedTeamIndex);
|
||||
const teamBIndex = Math.max(legacyBlueTeamIndex, legacyRedTeamIndex);
|
||||
const blueScore = numberOrDefault(series.blueScore, 0);
|
||||
const redScore = numberOrDefault(series.redScore, 0);
|
||||
const winnerSide = isSide(series.winnerSide) ? series.winnerSide : undefined;
|
||||
const winnerTeamIndex =
|
||||
winnerSide === 'blue'
|
||||
? legacyBlueTeamIndex
|
||||
: winnerSide === 'red'
|
||||
? legacyRedTeamIndex
|
||||
: undefined;
|
||||
return {
|
||||
teamAIndex,
|
||||
teamBIndex,
|
||||
teamAWins: teamAIndex === legacyBlueTeamIndex ? blueScore : redScore,
|
||||
teamBWins: teamBIndex === legacyBlueTeamIndex ? blueScore : redScore,
|
||||
winnerTeamIndex,
|
||||
};
|
||||
});
|
||||
migrated.seriesResults = seriesResults.length > 0 ? seriesResults : buildSeries(games);
|
||||
|
||||
if (typeof migrated.winnerTeamIndex !== 'number') {
|
||||
const migratedSeriesResults = Array.isArray(migrated.seriesResults)
|
||||
? migrated.seriesResults
|
||||
: [];
|
||||
migrated.winnerTeamIndex =
|
||||
resolveWinnerTeamIndex(migratedSeriesResults) ??
|
||||
(isSide(migrated.winnerSide)
|
||||
? sideGroupToTeamIndex(migrated.winnerSide, 1)
|
||||
: undefined);
|
||||
}
|
||||
|
||||
if ('winnerSide' in migrated || 'blueScore' in migrated || 'redScore' in migrated) {
|
||||
changed = true;
|
||||
}
|
||||
delete migrated.winnerSide;
|
||||
delete migrated.blueScore;
|
||||
delete migrated.redScore;
|
||||
|
||||
return changed ? migrated : null;
|
||||
}
|
||||
|
||||
function buildSeries(games: Record<string, unknown>[]) {
|
||||
const bySeries = new Map<
|
||||
string,
|
||||
{
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
teamBWins: number;
|
||||
winnerTeamIndex?: number;
|
||||
}
|
||||
>();
|
||||
for (const game of games) {
|
||||
const blueTeamIndex = numberOrDefault(game.blueTeamIndex, 1);
|
||||
const redTeamIndex = numberOrDefault(game.redTeamIndex, 2);
|
||||
const winnerTeamIndex = numberOrUndefined(game.winnerTeamIndex);
|
||||
const teamAIndex = Math.min(blueTeamIndex, redTeamIndex);
|
||||
const teamBIndex = Math.max(blueTeamIndex, redTeamIndex);
|
||||
const key = `${teamAIndex}:${teamBIndex}`;
|
||||
const current =
|
||||
bySeries.get(key) ?? { teamAIndex, teamBIndex, teamAWins: 0, teamBWins: 0 };
|
||||
if (winnerTeamIndex === teamAIndex) current.teamAWins += 1;
|
||||
if (winnerTeamIndex === teamBIndex) current.teamBWins += 1;
|
||||
current.winnerTeamIndex =
|
||||
current.teamAWins > current.teamBWins
|
||||
? teamAIndex
|
||||
: current.teamBWins > current.teamAWins
|
||||
? teamBIndex
|
||||
: undefined;
|
||||
bySeries.set(key, current);
|
||||
}
|
||||
return [...bySeries.values()];
|
||||
}
|
||||
|
||||
function resolveWinnerTeamIndex(
|
||||
seriesResults: Array<Record<string, unknown>>,
|
||||
): number | undefined {
|
||||
const wins = new Map<number, number>();
|
||||
for (const series of seriesResults) {
|
||||
const winnerTeamIndex = numberOrUndefined(series.winnerTeamIndex);
|
||||
if (!winnerTeamIndex) continue;
|
||||
wins.set(winnerTeamIndex, (wins.get(winnerTeamIndex) ?? 0) + 1);
|
||||
}
|
||||
const sorted = [...wins.entries()].sort((left, right) => right[1] - left[1]);
|
||||
if (sorted.length === 0) return undefined;
|
||||
if (sorted.length > 1 && sorted[0][1] === sorted[1][1]) return undefined;
|
||||
return sorted[0][0];
|
||||
}
|
||||
|
||||
function readTeamIndex(value: Record<string, unknown>): number | undefined {
|
||||
if (typeof value.teamIndex === 'number') return value.teamIndex;
|
||||
if (!isSide(value.side)) return undefined;
|
||||
return sideGroupToTeamIndex(value.side, numberOrDefault(value.groupIndex, 1));
|
||||
}
|
||||
|
||||
function sideGroupToTeamIndex(side: LegacySide, groupIndex: number) {
|
||||
return (Math.max(1, groupIndex) - 1) * 2 + (side === 'blue' ? 1 : 2);
|
||||
}
|
||||
|
||||
function asArray(value: unknown): Record<string, unknown>[] {
|
||||
return Array.isArray(value)
|
||||
? value.filter(isRecord).map((item) => ({ ...item }))
|
||||
: [];
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value && typeof value === 'object' && !Array.isArray(value));
|
||||
}
|
||||
|
||||
function isSide(value: unknown): value is LegacySide {
|
||||
return value === 'blue' || value === 'red';
|
||||
}
|
||||
|
||||
function numberOrDefault(value: unknown, fallback: number) {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : fallback;
|
||||
}
|
||||
|
||||
function numberOrUndefined(value: unknown) {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
@@ -340,8 +340,7 @@ export interface MatchTeamMember {
|
||||
}
|
||||
|
||||
export interface MatchTeam {
|
||||
side: TeamSide;
|
||||
groupIndex: number;
|
||||
teamIndex: number;
|
||||
name: string;
|
||||
captainUserId?: mongoose.Types.ObjectId;
|
||||
members: MatchTeamMember[];
|
||||
@@ -349,6 +348,7 @@ export interface MatchTeam {
|
||||
|
||||
export interface MatchGameResultParticipant {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
teamIndex: number;
|
||||
side: TeamSide;
|
||||
championId: number;
|
||||
kills: number;
|
||||
@@ -360,26 +360,25 @@ export interface MatchGameResultParticipant {
|
||||
export interface MatchGameResult {
|
||||
gameNumber: number;
|
||||
riotMatchId: string;
|
||||
blueTeamIndex: number;
|
||||
redTeamIndex: number;
|
||||
winnerTeamIndex: number;
|
||||
winnerSide: TeamSide;
|
||||
blueGroupIndex: number;
|
||||
redGroupIndex: number;
|
||||
gameCreation: number;
|
||||
gameDuration: number;
|
||||
participants: MatchGameResultParticipant[];
|
||||
}
|
||||
|
||||
export interface MatchSeriesResult {
|
||||
blueGroupIndex: number;
|
||||
redGroupIndex: number;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
winnerSide?: TeamSide;
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
teamBWins: number;
|
||||
winnerTeamIndex?: number;
|
||||
}
|
||||
|
||||
export interface MatchResult {
|
||||
winnerSide?: TeamSide;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
winnerTeamIndex?: number;
|
||||
mvpUserId?: mongoose.Types.ObjectId;
|
||||
riotMatchIds: string[]; // 내전에서 플레이된 Riot matchId들
|
||||
games: MatchGameResult[];
|
||||
@@ -489,16 +488,14 @@ export interface AuctionTeamMember {
|
||||
}
|
||||
|
||||
export interface AuctionTeam {
|
||||
side: TeamSide;
|
||||
groupIndex: number;
|
||||
teamIndex: number;
|
||||
captainUserId: mongoose.Types.ObjectId;
|
||||
points: number;
|
||||
members: AuctionTeamMember[];
|
||||
}
|
||||
|
||||
export interface AuctionBid {
|
||||
side: TeamSide;
|
||||
groupIndex?: number;
|
||||
teamIndex: number;
|
||||
amount: number;
|
||||
bidderUserId: mongoose.Types.ObjectId;
|
||||
timestamp: Date;
|
||||
@@ -512,8 +509,7 @@ export interface Auction extends MongooseTimestamps {
|
||||
currentIndex: number;
|
||||
bids: AuctionBid[];
|
||||
currentBid: number;
|
||||
currentBidder?: TeamSide;
|
||||
currentBidderGroupIndex?: number;
|
||||
currentBidderTeamIndex?: number;
|
||||
maxTimerSeconds: number;
|
||||
currentDeadline?: Date;
|
||||
initialPoints: number;
|
||||
@@ -920,8 +916,7 @@ const MatchTeamMemberSubSchema = new Schema<MatchTeamMember>(
|
||||
|
||||
const MatchTeamSubSchema = new Schema<MatchTeam>(
|
||||
{
|
||||
side: { type: String, enum: TEAM_SIDES, required: true },
|
||||
groupIndex: { type: Number, required: true, default: 1, min: 1 },
|
||||
teamIndex: { type: Number, required: true, min: 1 },
|
||||
name: { type: String, required: true },
|
||||
captainUserId: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
members: { type: [MatchTeamMemberSubSchema], required: true, default: [] },
|
||||
@@ -933,6 +928,7 @@ const MatchGameResultParticipantSubSchema =
|
||||
new Schema<MatchGameResultParticipant>(
|
||||
{
|
||||
userId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
teamIndex: { type: Number, required: true, min: 1 },
|
||||
side: { type: String, enum: TEAM_SIDES, required: true },
|
||||
championId: { type: Number, required: true },
|
||||
kills: { type: Number, required: true, default: 0 },
|
||||
@@ -947,9 +943,10 @@ const MatchGameResultSubSchema = new Schema<MatchGameResult>(
|
||||
{
|
||||
gameNumber: { type: Number, required: true },
|
||||
riotMatchId: { type: String, required: true },
|
||||
blueTeamIndex: { type: Number, required: true, min: 1 },
|
||||
redTeamIndex: { type: Number, required: true, min: 1 },
|
||||
winnerTeamIndex: { type: Number, required: true, min: 1 },
|
||||
winnerSide: { type: String, enum: TEAM_SIDES, required: true },
|
||||
blueGroupIndex: { type: Number, required: true, default: 1, min: 1 },
|
||||
redGroupIndex: { type: Number, required: true, default: 1, min: 1 },
|
||||
gameCreation: { type: Number, required: true },
|
||||
gameDuration: { type: Number, required: true },
|
||||
participants: {
|
||||
@@ -963,20 +960,18 @@ const MatchGameResultSubSchema = new Schema<MatchGameResult>(
|
||||
|
||||
const MatchSeriesResultSubSchema = new Schema<MatchSeriesResult>(
|
||||
{
|
||||
blueGroupIndex: { type: Number, required: true, default: 1, min: 1 },
|
||||
redGroupIndex: { type: Number, required: true, default: 1, min: 1 },
|
||||
blueScore: { type: Number, required: true, default: 0 },
|
||||
redScore: { type: Number, required: true, default: 0 },
|
||||
winnerSide: { type: String, enum: TEAM_SIDES, required: false },
|
||||
teamAIndex: { type: Number, required: true, min: 1 },
|
||||
teamBIndex: { type: Number, required: true, min: 1 },
|
||||
teamAWins: { type: Number, required: true, default: 0 },
|
||||
teamBWins: { type: Number, required: true, default: 0 },
|
||||
winnerTeamIndex: { type: Number, required: false, min: 1 },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const MatchResultSubSchema = new Schema<MatchResult>(
|
||||
{
|
||||
winnerSide: { type: String, enum: TEAM_SIDES, required: false },
|
||||
blueScore: { type: Number, required: true, default: 0 },
|
||||
redScore: { type: Number, required: true, default: 0 },
|
||||
winnerTeamIndex: { type: Number, required: false, min: 1 },
|
||||
mvpUserId: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
riotMatchIds: { type: [String], required: true, default: [] },
|
||||
games: { type: [MatchGameResultSubSchema], required: true, default: [] },
|
||||
@@ -1214,8 +1209,7 @@ const AuctionTeamMemberSubSchema = new Schema<AuctionTeamMember>(
|
||||
|
||||
const AuctionTeamSubSchema = new Schema<AuctionTeam>(
|
||||
{
|
||||
side: { type: String, enum: TEAM_SIDES, required: true },
|
||||
groupIndex: { type: Number, required: true, default: 1, min: 1 },
|
||||
teamIndex: { type: Number, required: true, min: 1 },
|
||||
captainUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
points: { type: Number, required: true, default: 0 },
|
||||
members: {
|
||||
@@ -1229,8 +1223,7 @@ const AuctionTeamSubSchema = new Schema<AuctionTeam>(
|
||||
|
||||
const AuctionBidSubSchema = new Schema<AuctionBid>(
|
||||
{
|
||||
side: { type: String, enum: TEAM_SIDES, required: true },
|
||||
groupIndex: { type: Number, required: true, default: 1, min: 1 },
|
||||
teamIndex: { type: Number, required: true, min: 1 },
|
||||
amount: { type: Number, required: true },
|
||||
bidderUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
timestamp: { type: Date, required: true, default: Date.now },
|
||||
@@ -1261,8 +1254,7 @@ export const AuctionSchema = new Schema<Auction>(
|
||||
currentIndex: { type: Number, required: true, default: 0 },
|
||||
bids: { type: [AuctionBidSubSchema], required: true, default: [] },
|
||||
currentBid: { type: Number, required: true, default: 0 },
|
||||
currentBidder: { type: String, enum: TEAM_SIDES, required: false },
|
||||
currentBidderGroupIndex: { type: Number, required: false },
|
||||
currentBidderTeamIndex: { type: Number, required: false, min: 1 },
|
||||
maxTimerSeconds: { type: Number, required: true, default: 30 },
|
||||
currentDeadline: { type: Date, required: false },
|
||||
initialPoints: { type: Number, required: true, default: 1000 },
|
||||
|
||||
@@ -26,7 +26,6 @@ import {
|
||||
buildUserByPuuidMap,
|
||||
countKnownParticipants,
|
||||
resolveExternalCount,
|
||||
resolveTeam100IsBlue,
|
||||
type UserByPuuidMap,
|
||||
} from './match-builder.util';
|
||||
import {
|
||||
@@ -306,9 +305,11 @@ export class LegacyImportService {
|
||||
externalCount: raw
|
||||
? resolveExternalCount(raw, userByPuuid)
|
||||
: Math.max(0, 10 - memberCount),
|
||||
blueScore: match.result?.blueScore ?? 0,
|
||||
redScore: match.result?.redScore ?? 0,
|
||||
winnerSide: match.result?.winnerSide,
|
||||
teamAIndex: match.result?.seriesResults?.[0]?.teamAIndex ?? 1,
|
||||
teamBIndex: match.result?.seriesResults?.[0]?.teamBIndex ?? 2,
|
||||
teamAWins: match.result?.seriesResults?.[0]?.teamAWins ?? 0,
|
||||
teamBWins: match.result?.seriesResults?.[0]?.teamBWins ?? 0,
|
||||
winnerTeamIndex: match.result?.winnerTeamIndex,
|
||||
};
|
||||
}),
|
||||
nextCursor:
|
||||
@@ -391,9 +392,8 @@ export class LegacyImportService {
|
||||
continue;
|
||||
}
|
||||
|
||||
const team100IsBlue = resolveTeam100IsBlue(raw, userByPuuid);
|
||||
const participants = buildParticipantsSnapshot(raw, userByPuuid);
|
||||
const gameResult = buildGameResult(raw, userByPuuid, team100IsBlue, 1);
|
||||
const gameResult = buildGameResult(raw, userByPuuid, 1);
|
||||
if (!gameResult || participants.length === 0) {
|
||||
result.skippedNoKnownParticipants += 1;
|
||||
if (Object.keys(update).length > 0) {
|
||||
@@ -402,23 +402,21 @@ export class LegacyImportService {
|
||||
continue;
|
||||
}
|
||||
|
||||
const winnerSide = gameResult.winnerSide;
|
||||
const winnerTeamIndex = gameResult.winnerTeamIndex;
|
||||
update.mapId = raw.info.mapId ?? match.mapId;
|
||||
update.participants = participants;
|
||||
update.teams = buildTeams(raw, userByPuuid, team100IsBlue);
|
||||
update.teams = buildTeams(raw, userByPuuid);
|
||||
update.result = {
|
||||
winnerSide,
|
||||
blueScore: winnerSide === 'blue' ? 1 : 0,
|
||||
redScore: winnerSide === 'red' ? 1 : 0,
|
||||
winnerTeamIndex,
|
||||
riotMatchIds: [riotMatchId],
|
||||
games: [gameResult],
|
||||
seriesResults: [
|
||||
{
|
||||
blueGroupIndex: 1,
|
||||
redGroupIndex: 1,
|
||||
blueScore: winnerSide === 'blue' ? 1 : 0,
|
||||
redScore: winnerSide === 'red' ? 1 : 0,
|
||||
winnerSide,
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
teamAWins: winnerTeamIndex === 1 ? 1 : 0,
|
||||
teamBWins: winnerTeamIndex === 2 ? 1 : 0,
|
||||
winnerTeamIndex,
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -485,11 +483,10 @@ export class LegacyImportService {
|
||||
const counts = countKnownParticipants(detail, userByPuuid);
|
||||
if (counts.total === 0) return 'skipped';
|
||||
|
||||
const team100IsBlue = resolveTeam100IsBlue(detail, userByPuuid);
|
||||
const gameResult = buildGameResult(detail, userByPuuid, team100IsBlue, 1);
|
||||
const gameResult = buildGameResult(detail, userByPuuid, 1);
|
||||
if (!gameResult || gameResult.participants.length === 0) return 'skipped';
|
||||
|
||||
const winnerSide = gameResult.winnerSide;
|
||||
const winnerTeamIndex = gameResult.winnerTeamIndex;
|
||||
const matchPayload: Partial<Match> = {
|
||||
communityId: new mongoose.Types.ObjectId(job.communityId),
|
||||
title: this.formatLegacyDate(detail.info.gameCreation),
|
||||
@@ -504,20 +501,18 @@ export class LegacyImportService {
|
||||
teamBuiltAt: new Date(detail.info.gameCreation),
|
||||
hostUserId: new mongoose.Types.ObjectId(job.triggeredBy),
|
||||
participants: buildParticipantsSnapshot(detail, userByPuuid),
|
||||
teams: buildTeams(detail, userByPuuid, team100IsBlue),
|
||||
teams: buildTeams(detail, userByPuuid),
|
||||
result: {
|
||||
winnerSide,
|
||||
blueScore: winnerSide === 'blue' ? 1 : 0,
|
||||
redScore: winnerSide === 'red' ? 1 : 0,
|
||||
winnerTeamIndex,
|
||||
riotMatchIds: [riotMatchId],
|
||||
games: [gameResult],
|
||||
seriesResults: [
|
||||
{
|
||||
blueGroupIndex: 1,
|
||||
redGroupIndex: 1,
|
||||
blueScore: winnerSide === 'blue' ? 1 : 0,
|
||||
redScore: winnerSide === 'red' ? 1 : 0,
|
||||
winnerSide,
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
teamAWins: winnerTeamIndex === 1 ? 1 : 0,
|
||||
teamBWins: winnerTeamIndex === 2 ? 1 : 0,
|
||||
winnerTeamIndex,
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -55,9 +55,11 @@ export interface LegacyMatchListResponse {
|
||||
riotMatchId: string | null;
|
||||
memberCount: number;
|
||||
externalCount: number;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
winnerSide?: 'blue' | 'red';
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
teamBWins: number;
|
||||
winnerTeamIndex?: number;
|
||||
}>;
|
||||
nextCursor: number | null;
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import type {
|
||||
MatchTeam,
|
||||
Position,
|
||||
RiotAccount,
|
||||
TeamSide,
|
||||
UserDocument,
|
||||
} from '../global/database/schema';
|
||||
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
|
||||
@@ -91,10 +90,11 @@ export function buildParticipantsSnapshot(
|
||||
export function buildTeams(
|
||||
detail: RiotMatchDto,
|
||||
userByPuuid: UserByPuuidMap,
|
||||
team100IsBlue: boolean,
|
||||
): MatchTeam[] {
|
||||
return (['blue', 'red'] as TeamSide[]).map((side) => {
|
||||
const teamId = resolveRiotTeamId(side, team100IsBlue);
|
||||
return [
|
||||
{ teamIndex: 1, teamId: RIOT_BLUE_TEAM_ID },
|
||||
{ teamIndex: 2, teamId: RIOT_RED_TEAM_ID },
|
||||
].map(({ teamIndex, teamId }) => {
|
||||
const members = detail.info.participants
|
||||
.filter((participant) => participant.teamId === teamId)
|
||||
.map((participant) => {
|
||||
@@ -107,9 +107,8 @@ export function buildTeams(
|
||||
})
|
||||
.filter((member): member is NonNullable<typeof member> => Boolean(member));
|
||||
return {
|
||||
side,
|
||||
groupIndex: 1,
|
||||
name: side === 'blue' ? '블루팀' : '레드팀',
|
||||
teamIndex,
|
||||
name: `${teamIndex}팀`,
|
||||
members,
|
||||
};
|
||||
});
|
||||
@@ -118,20 +117,21 @@ export function buildTeams(
|
||||
export function buildGameResult(
|
||||
detail: RiotMatchDto,
|
||||
userByPuuid: UserByPuuidMap,
|
||||
team100IsBlue: boolean,
|
||||
gameNumber = 1,
|
||||
): MatchGameResult | null {
|
||||
const winningTeam = detail.info.teams.find((team) => team.win);
|
||||
if (!winningTeam) return null;
|
||||
const winnerSide = resolveSide(winningTeam.teamId, team100IsBlue);
|
||||
const winnerSide = resolveSide(winningTeam.teamId);
|
||||
if (!winnerSide) return null;
|
||||
const winnerTeamIndex = winnerSide === 'blue' ? 1 : 2;
|
||||
const participants = detail.info.participants
|
||||
.map((participant) => {
|
||||
const user = userByPuuid.get(participant.puuid);
|
||||
const side = resolveSide(participant.teamId, team100IsBlue);
|
||||
const side = resolveSide(participant.teamId);
|
||||
if (!user || !side) return null;
|
||||
return {
|
||||
userId: user.userId,
|
||||
teamIndex: side === 'blue' ? 1 : 2,
|
||||
side,
|
||||
championId: participant.championId,
|
||||
kills: participant.kills,
|
||||
@@ -147,9 +147,10 @@ export function buildGameResult(
|
||||
return {
|
||||
gameNumber,
|
||||
riotMatchId: detail.metadata.matchId,
|
||||
blueTeamIndex: 1,
|
||||
redTeamIndex: 2,
|
||||
winnerTeamIndex,
|
||||
winnerSide,
|
||||
blueGroupIndex: 1,
|
||||
redGroupIndex: 1,
|
||||
gameCreation: detail.info.gameCreation,
|
||||
gameDuration: detail.info.gameDuration,
|
||||
participants,
|
||||
@@ -165,16 +166,9 @@ export function resolveExternalCount(
|
||||
).length;
|
||||
}
|
||||
|
||||
function resolveRiotTeamId(side: TeamSide, team100IsBlue: boolean): number {
|
||||
if (side === 'blue') {
|
||||
return team100IsBlue ? RIOT_BLUE_TEAM_ID : RIOT_RED_TEAM_ID;
|
||||
}
|
||||
return team100IsBlue ? RIOT_RED_TEAM_ID : RIOT_BLUE_TEAM_ID;
|
||||
}
|
||||
|
||||
function resolveSide(teamId: number, team100IsBlue: boolean): TeamSide | null {
|
||||
if (teamId === RIOT_BLUE_TEAM_ID) return team100IsBlue ? 'blue' : 'red';
|
||||
if (teamId === RIOT_RED_TEAM_ID) return team100IsBlue ? 'red' : 'blue';
|
||||
function resolveSide(teamId: number): 'blue' | 'red' | null {
|
||||
if (teamId === RIOT_BLUE_TEAM_ID) return 'blue';
|
||||
if (teamId === RIOT_RED_TEAM_ID) return 'red';
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
Match,
|
||||
MatchDocument,
|
||||
MatchSeriesResult,
|
||||
MatchStatus,
|
||||
PositionPreference,
|
||||
TierInfo,
|
||||
@@ -99,15 +100,7 @@ export class MatchService {
|
||||
(left, right) => left.gameNumber - right.gameNumber,
|
||||
);
|
||||
if (!obj.result.seriesResults?.length) {
|
||||
obj.result.seriesResults = [
|
||||
{
|
||||
blueGroupIndex: 1,
|
||||
redGroupIndex: 1,
|
||||
blueScore: obj.result.blueScore ?? 0,
|
||||
redScore: obj.result.redScore ?? 0,
|
||||
winnerSide: obj.result.winnerSide,
|
||||
},
|
||||
];
|
||||
obj.result.seriesResults = this.buildSeriesResults(obj.result.games);
|
||||
}
|
||||
}
|
||||
return {
|
||||
@@ -120,7 +113,6 @@ export class MatchService {
|
||||
})),
|
||||
teams: (obj.teams ?? []).map((team) => ({
|
||||
...team,
|
||||
groupIndex: team.groupIndex ?? 1,
|
||||
})),
|
||||
tournamentCodes: await this.tournamentCodeService.buildSlots(match),
|
||||
};
|
||||
@@ -239,4 +231,33 @@ export class MatchService {
|
||||
fetchedAt: tier.fetchedAt,
|
||||
};
|
||||
}
|
||||
|
||||
private buildSeriesResults(
|
||||
games: NonNullable<Match['result']>['games'],
|
||||
): MatchSeriesResult[] {
|
||||
const bySeries = new Map<string, MatchSeriesResult>();
|
||||
for (const game of games) {
|
||||
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
||||
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
|
||||
const key = `${teamAIndex}:${teamBIndex}`;
|
||||
const current =
|
||||
bySeries.get(key) ??
|
||||
({
|
||||
teamAIndex,
|
||||
teamBIndex,
|
||||
teamAWins: 0,
|
||||
teamBWins: 0,
|
||||
} satisfies MatchSeriesResult);
|
||||
if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1;
|
||||
if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1;
|
||||
current.winnerTeamIndex =
|
||||
current.teamAWins > current.teamBWins
|
||||
? teamAIndex
|
||||
: current.teamBWins > current.teamAWins
|
||||
? teamBIndex
|
||||
: undefined;
|
||||
bySeries.set(key, current);
|
||||
}
|
||||
return [...bySeries.values()];
|
||||
}
|
||||
}
|
||||
@@ -369,23 +369,25 @@ export class TournamentCodeService {
|
||||
|
||||
private resolveRequiredSlots(match: MatchDocument): number {
|
||||
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||
const teamGroups = new Set(
|
||||
(match.teams ?? []).map((team) => team.groupIndex ?? 1),
|
||||
);
|
||||
const teamCount = (match.teams ?? []).length;
|
||||
const activeParticipantCount = (match.participants ?? []).filter(
|
||||
(participant) => !participant.excluded,
|
||||
).length;
|
||||
const participantGroups = Math.floor(activeParticipantCount / 10);
|
||||
const groups = Math.max(1, teamGroups.size, participantGroups);
|
||||
return groups * gameCount;
|
||||
const participantSeriesCount = Math.floor(activeParticipantCount / 10);
|
||||
const teamSeriesCount = Math.ceil(teamCount / 2);
|
||||
const seriesCount = Math.max(1, teamSeriesCount, participantSeriesCount);
|
||||
return seriesCount * gameCount;
|
||||
}
|
||||
|
||||
private resolveSeriesRefForGameNumber(
|
||||
match: MatchDocument,
|
||||
gameNumber: number,
|
||||
): { blueGroupIndex: number; redGroupIndex: number } {
|
||||
): { teamAIndex: number; teamBIndex: number } {
|
||||
const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||
const groupIndex = Math.max(1, Math.ceil(gameNumber / perSeries));
|
||||
return { blueGroupIndex: groupIndex, redGroupIndex: groupIndex };
|
||||
const seriesIndex = Math.max(1, Math.ceil(gameNumber / perSeries));
|
||||
return {
|
||||
teamAIndex: (seriesIndex - 1) * 2 + 1,
|
||||
teamBIndex: (seriesIndex - 1) * 2 + 2,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -24,8 +24,8 @@ export interface BulkUploadTournamentCodesResponse {
|
||||
|
||||
export interface TournamentCodeSlotView {
|
||||
gameNumber: number;
|
||||
blueGroupIndex: number;
|
||||
redGroupIndex: number;
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
code: string | null;
|
||||
expiresAt: string | null;
|
||||
state: TournamentCodeState | 'pending';
|
||||
|
||||
@@ -23,16 +23,16 @@ function makeMatch(): {
|
||||
const match = {
|
||||
teams: [
|
||||
{
|
||||
side: 'blue',
|
||||
name: '블루팀',
|
||||
teamIndex: 1,
|
||||
name: '1팀',
|
||||
members: blueUserIds.map((userId) => ({
|
||||
userId,
|
||||
assignedPosition: 'MID',
|
||||
})),
|
||||
},
|
||||
{
|
||||
side: 'red',
|
||||
name: '레드팀',
|
||||
teamIndex: 2,
|
||||
name: '2팀',
|
||||
members: redUserIds.map((userId) => ({
|
||||
userId,
|
||||
assignedPosition: 'MID',
|
||||
@@ -111,9 +111,16 @@ describe('computeGameResult', () => {
|
||||
gameNumber: 1,
|
||||
riotMatchId: 'KR_1',
|
||||
winnerSide: 'blue',
|
||||
blueTeamIndex: 1,
|
||||
redTeamIndex: 2,
|
||||
winnerTeamIndex: 1,
|
||||
gameDuration: 1800,
|
||||
});
|
||||
expect(result?.participants).toHaveLength(10);
|
||||
expect(result?.participants[0]).toMatchObject({
|
||||
teamIndex: 1,
|
||||
side: 'blue',
|
||||
});
|
||||
});
|
||||
|
||||
it('handles reversed Riot side assignment', () => {
|
||||
@@ -126,7 +133,12 @@ describe('computeGameResult', () => {
|
||||
|
||||
const result = computeGameResult({ match, lookup, detail, gameNumber: 2 });
|
||||
|
||||
expect(result?.winnerSide).toBe('red');
|
||||
expect(result).toMatchObject({
|
||||
blueTeamIndex: 2,
|
||||
redTeamIndex: 1,
|
||||
winnerSide: 'blue',
|
||||
winnerTeamIndex: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects matches with too little overlap', () => {
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import mongoose from 'mongoose';
|
||||
import type {
|
||||
MatchDocument,
|
||||
MatchGameResult,
|
||||
TeamSide,
|
||||
} from '../global/database/schema';
|
||||
import type { MatchDocument, MatchGameResult, TeamSide } from '../global/database/schema';
|
||||
import type { RiotMatchDto } from '../riot/riot.types';
|
||||
|
||||
const RIOT_BLUE_TEAM_ID = 100;
|
||||
@@ -37,13 +33,10 @@ export function collectMatchUserIds(match: MatchDocument): mongoose.Types.Object
|
||||
|
||||
export function collectTeamPuuids(
|
||||
match: MatchDocument,
|
||||
side: TeamSide,
|
||||
teamIndex: number,
|
||||
lookup: MatchPuuidLookup,
|
||||
groupIndex = 1,
|
||||
): string[] {
|
||||
const team = match.teams.find(
|
||||
(item) => item.side === side && (item.groupIndex ?? 1) === groupIndex,
|
||||
);
|
||||
const team = match.teams.find((item) => item.teamIndex === teamIndex);
|
||||
if (!team) return [];
|
||||
const userIds = [
|
||||
...(team.captainUserId ? [team.captainUserId] : []),
|
||||
@@ -59,19 +52,19 @@ export function computeGameResult(params: {
|
||||
detail: RiotMatchDto;
|
||||
gameNumber: number;
|
||||
lookup: MatchPuuidLookup;
|
||||
blueGroupIndex?: number;
|
||||
redGroupIndex?: number;
|
||||
teamAIndex?: number;
|
||||
teamBIndex?: number;
|
||||
}): MatchGameResult | null {
|
||||
const {
|
||||
match,
|
||||
detail,
|
||||
gameNumber,
|
||||
lookup,
|
||||
blueGroupIndex = 1,
|
||||
redGroupIndex = 1,
|
||||
teamAIndex = 1,
|
||||
teamBIndex = 2,
|
||||
} = params;
|
||||
const ourBluePuuids = collectTeamPuuids(match, 'blue', lookup, blueGroupIndex);
|
||||
const ourRedPuuids = collectTeamPuuids(match, 'red', lookup, redGroupIndex);
|
||||
const teamAPuuids = collectTeamPuuids(match, teamAIndex, lookup);
|
||||
const teamBPuuids = collectTeamPuuids(match, teamBIndex, lookup);
|
||||
const team100Puuids = detail.info.participants
|
||||
.filter((participant) => participant.teamId === RIOT_BLUE_TEAM_ID)
|
||||
.map((participant) => participant.puuid);
|
||||
@@ -80,15 +73,21 @@ export function computeGameResult(params: {
|
||||
.map((participant) => participant.puuid);
|
||||
|
||||
const normalOverlap =
|
||||
countOverlap(team100Puuids, ourBluePuuids) +
|
||||
countOverlap(team200Puuids, ourRedPuuids);
|
||||
countOverlap(team100Puuids, teamAPuuids) +
|
||||
countOverlap(team200Puuids, teamBPuuids);
|
||||
const reversedOverlap =
|
||||
countOverlap(team100Puuids, ourRedPuuids) +
|
||||
countOverlap(team200Puuids, ourBluePuuids);
|
||||
const teamMapping: Record<number, TeamSide> =
|
||||
normalOverlap >= reversedOverlap
|
||||
? { [RIOT_BLUE_TEAM_ID]: 'blue', [RIOT_RED_TEAM_ID]: 'red' }
|
||||
: { [RIOT_BLUE_TEAM_ID]: 'red', [RIOT_RED_TEAM_ID]: 'blue' };
|
||||
countOverlap(team100Puuids, teamBPuuids) +
|
||||
countOverlap(team200Puuids, teamAPuuids);
|
||||
const blueTeamIndex = normalOverlap >= reversedOverlap ? teamAIndex : teamBIndex;
|
||||
const redTeamIndex = normalOverlap >= reversedOverlap ? teamBIndex : teamAIndex;
|
||||
const teamIndexByRiotTeamId: Record<number, number> = {
|
||||
[RIOT_BLUE_TEAM_ID]: blueTeamIndex,
|
||||
[RIOT_RED_TEAM_ID]: redTeamIndex,
|
||||
};
|
||||
const sideByRiotTeamId: Record<number, TeamSide> = {
|
||||
[RIOT_BLUE_TEAM_ID]: 'blue',
|
||||
[RIOT_RED_TEAM_ID]: 'red',
|
||||
};
|
||||
|
||||
if (Math.max(normalOverlap, reversedOverlap) < MINIMUM_TRUSTED_OVERLAP) {
|
||||
return null;
|
||||
@@ -96,16 +95,20 @@ export function computeGameResult(params: {
|
||||
|
||||
const winningTeam = detail.info.teams.find((team) => team.win);
|
||||
if (!winningTeam) return null;
|
||||
const winnerSide = teamMapping[winningTeam.teamId];
|
||||
const winnerSide = sideByRiotTeamId[winningTeam.teamId];
|
||||
if (!winnerSide) return null;
|
||||
const winnerTeamIndex = teamIndexByRiotTeamId[winningTeam.teamId];
|
||||
if (!winnerTeamIndex) return null;
|
||||
|
||||
const participants = detail.info.participants
|
||||
.map((participant) => {
|
||||
const userId = lookup.userIdByPuuid.get(participant.puuid);
|
||||
const side = teamMapping[participant.teamId];
|
||||
if (!userId || !side) return null;
|
||||
const side = sideByRiotTeamId[participant.teamId];
|
||||
const teamIndex = teamIndexByRiotTeamId[participant.teamId];
|
||||
if (!userId || !side || !teamIndex) return null;
|
||||
return {
|
||||
userId,
|
||||
teamIndex,
|
||||
side,
|
||||
championId: participant.championId,
|
||||
kills: participant.kills,
|
||||
@@ -121,9 +124,10 @@ export function computeGameResult(params: {
|
||||
return {
|
||||
gameNumber,
|
||||
riotMatchId: detail.metadata.matchId,
|
||||
blueTeamIndex,
|
||||
redTeamIndex,
|
||||
winnerTeamIndex,
|
||||
winnerSide,
|
||||
blueGroupIndex,
|
||||
redGroupIndex,
|
||||
gameCreation: detail.info.gameCreation,
|
||||
gameDuration: detail.info.gameDuration,
|
||||
participants,
|
||||
|
||||
@@ -243,12 +243,9 @@ export class TournamentResultService {
|
||||
|
||||
match.status = 'finished';
|
||||
if (match.result) {
|
||||
match.result.winnerSide =
|
||||
match.result.blueScore > match.result.redScore
|
||||
? 'blue'
|
||||
: match.result.redScore > match.result.blueScore
|
||||
? 'red'
|
||||
: undefined;
|
||||
match.result.winnerTeamIndex = this.resolveMatchWinnerTeamIndex(
|
||||
match.result.seriesResults ?? [],
|
||||
);
|
||||
}
|
||||
match.resultPollState = {
|
||||
startedAt: match.resultPollState?.startedAt ?? new Date(),
|
||||
@@ -392,15 +389,14 @@ export class TournamentResultService {
|
||||
),
|
||||
gameResult,
|
||||
].sort((left, right) => left.gameNumber - right.gameNumber);
|
||||
const seriesResults = this.buildSeriesResults(games);
|
||||
|
||||
match.result = {
|
||||
winnerSide: match.result?.winnerSide,
|
||||
blueScore: games.filter((game) => game.winnerSide === 'blue').length,
|
||||
redScore: games.filter((game) => game.winnerSide === 'red').length,
|
||||
winnerTeamIndex: this.resolveMatchWinnerTeamIndex(seriesResults),
|
||||
mvpUserId: match.result?.mvpUserId,
|
||||
riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))],
|
||||
games,
|
||||
seriesResults: this.buildSeriesResults(games),
|
||||
seriesResults,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -410,59 +406,83 @@ export class TournamentResultService {
|
||||
const bySeries = new Map<
|
||||
string,
|
||||
{
|
||||
blueGroupIndex: number;
|
||||
redGroupIndex: number;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
winnerSide?: 'blue' | 'red';
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
teamBWins: number;
|
||||
winnerTeamIndex?: number;
|
||||
}
|
||||
>();
|
||||
|
||||
for (const game of games) {
|
||||
const blueGroupIndex = game.blueGroupIndex ?? 1;
|
||||
const redGroupIndex = game.redGroupIndex ?? 1;
|
||||
const key = `${blueGroupIndex}:${redGroupIndex}`;
|
||||
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
||||
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
|
||||
const key = `${teamAIndex}:${teamBIndex}`;
|
||||
const current =
|
||||
bySeries.get(key) ??
|
||||
{
|
||||
blueGroupIndex,
|
||||
redGroupIndex,
|
||||
blueScore: 0,
|
||||
redScore: 0,
|
||||
teamAIndex,
|
||||
teamBIndex,
|
||||
teamAWins: 0,
|
||||
teamBWins: 0,
|
||||
};
|
||||
if (game.winnerSide === 'blue') current.blueScore += 1;
|
||||
if (game.winnerSide === 'red') current.redScore += 1;
|
||||
current.winnerSide =
|
||||
current.blueScore > current.redScore
|
||||
? 'blue'
|
||||
: current.redScore > current.blueScore
|
||||
? 'red'
|
||||
if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1;
|
||||
if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1;
|
||||
current.winnerTeamIndex =
|
||||
current.teamAWins > current.teamBWins
|
||||
? teamAIndex
|
||||
: current.teamBWins > current.teamAWins
|
||||
? teamBIndex
|
||||
: undefined;
|
||||
bySeries.set(key, current);
|
||||
}
|
||||
|
||||
return [...bySeries.values()].sort(
|
||||
(left, right) =>
|
||||
left.blueGroupIndex - right.blueGroupIndex ||
|
||||
left.redGroupIndex - right.redGroupIndex,
|
||||
left.teamAIndex - right.teamAIndex ||
|
||||
left.teamBIndex - right.teamBIndex,
|
||||
);
|
||||
}
|
||||
|
||||
private resolveSeriesRefForGameNumber(
|
||||
match: MatchDocument,
|
||||
gameNumber: number,
|
||||
): { blueGroupIndex: number; redGroupIndex: number } {
|
||||
): { teamAIndex: number; teamBIndex: number } {
|
||||
const perSeries = match.gameCount || 1;
|
||||
const groupIndex = Math.max(1, Math.ceil(gameNumber / perSeries));
|
||||
return { blueGroupIndex: groupIndex, redGroupIndex: groupIndex };
|
||||
const seriesIndex = Math.max(1, Math.ceil(gameNumber / perSeries));
|
||||
return {
|
||||
teamAIndex: (seriesIndex - 1) * 2 + 1,
|
||||
teamBIndex: (seriesIndex - 1) * 2 + 2,
|
||||
};
|
||||
}
|
||||
|
||||
private resolveRequiredGameSlots(match: MatchDocument): number {
|
||||
const groups = Math.max(
|
||||
1,
|
||||
new Set(match.teams.map((team) => team.groupIndex ?? 1)).size,
|
||||
const activeParticipantCount = match.participants.filter(
|
||||
(participant) => !participant.excluded,
|
||||
).length;
|
||||
const participantSeriesCount = Math.floor(activeParticipantCount / 10);
|
||||
const teamSeriesCount = Math.ceil(match.teams.length / 2);
|
||||
const seriesCount = Math.max(1, participantSeriesCount, teamSeriesCount);
|
||||
return seriesCount * (match.gameCount || 1);
|
||||
}
|
||||
|
||||
private resolveMatchWinnerTeamIndex(
|
||||
seriesResults: NonNullable<MatchDocument['result']>['seriesResults'],
|
||||
): number | undefined {
|
||||
const winsByTeam = new Map<number, number>();
|
||||
for (const series of seriesResults ?? []) {
|
||||
if (!series.winnerTeamIndex) continue;
|
||||
winsByTeam.set(
|
||||
series.winnerTeamIndex,
|
||||
(winsByTeam.get(series.winnerTeamIndex) ?? 0) + 1,
|
||||
);
|
||||
}
|
||||
const sorted = [...winsByTeam.entries()].sort(
|
||||
(left, right) => right[1] - left[1],
|
||||
);
|
||||
return groups * (match.gameCount || 1);
|
||||
if (sorted.length === 0) return undefined;
|
||||
if (sorted.length > 1 && sorted[0][1] === sorted[1][1]) return undefined;
|
||||
return sorted[0][0];
|
||||
}
|
||||
|
||||
private async updatePollState(
|
||||
|
||||
@@ -21,6 +21,7 @@ export interface EnqueueTournamentResultPollResult {
|
||||
|
||||
export interface ComputedGameParticipant {
|
||||
userId: string;
|
||||
teamIndex: number;
|
||||
side: TeamSide;
|
||||
championId: number;
|
||||
kills: number;
|
||||
|
||||
Reference in new issue
Block a user