This commit is contained in:
dahyeon committed 2026-05-02 04:05:35 -07:00
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: [],
},
],
+36 -54
View File
@@ -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;
}
+28 -36
View File
@@ -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;
}
+31 -10
View File
@@ -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;
+20 -13
View File
@@ -938,8 +938,8 @@ async function main() {
participants: auctionPlayers.map(toMatchParticipant),
teams: [
{
side: 'blue',
name: '블루팀',
teamIndex: 1,
name: '1팀',
captainUserId: players[0]._id,
members: [
{
@@ -950,8 +950,8 @@ async function main() {
],
},
{
side: 'red',
name: '레드팀',
teamIndex: 2,
name: '2팀',
captainUserId: players[1]._id,
members: [
{
@@ -982,8 +982,8 @@ async function main() {
participants: players.map(toMatchParticipant),
teams: [
{
side: 'blue',
name: '블루팀',
teamIndex: 1,
name: '1팀',
captainUserId: players[0]._id,
members: finishedBlue.map((member) => ({
userId: member.user._id,
@@ -992,8 +992,8 @@ async function main() {
})),
},
{
side: 'red',
name: '레드팀',
teamIndex: 2,
name: '2팀',
captainUserId: players[1]._id,
members: finishedRed.map((member) => ({
userId: member.user._id,
@@ -1003,11 +1003,18 @@ async function main() {
},
],
result: {
winnerSide: 'blue',
blueScore: 2,
redScore: 1,
winnerTeamIndex: 1,
mvpUserId: players[0]._id,
riotMatchIds: ['KR_DEV_0001', 'KR_DEV_0002', 'KR_DEV_0003'],
seriesResults: [
{
teamAIndex: 1,
teamBIndex: 2,
teamAWins: 2,
teamBWins: 1,
winnerTeamIndex: 1,
},
],
},
prizes: ['1등 팀: RP 10,000 지급', 'MVP: 프리리'],
notices: [],
@@ -1036,13 +1043,13 @@ async function main() {
phase: 'presenting',
teams: [
{
side: 'blue',
teamIndex: 1,
captainUserId: players[0]._id,
points: 1000,
members: [],
},
{
side: 'red',
teamIndex: 2,
captainUserId: players[1]._id,
points: 1000,
members: [],
+1 -1
View File
@@ -77,7 +77,7 @@ function App() {
<Route path="/auth/callback" element={<AuthCallbackPage />} />
<Route path="/match/:id" element={<MatchDetailPage />} />
<Route
path="/match/:id/team/:side/:groupIndex"
path="/match/:id/team/:teamIndex"
element={<MatchTeamProgressPage />}
/>
<Route path="/match/:id/auction" element={<AuctionPage />} />
+28 -40
View File
@@ -11,10 +11,9 @@ import type {
MatchStatus,
Position,
RiotLane,
TeamSide,
TournamentCodeSlotView,
} from "./types";
import { POSITION_ORDER, sideLabel } from "../lib/league";
import { POSITION_ORDER, teamIndexLabel } from "../lib/league";
export interface ParticipantView {
id: string;
@@ -34,8 +33,7 @@ export interface TeamParticipantView extends ParticipantView {
}
export interface TeamView {
side: TeamSide;
groupIndex: number;
teamIndex: number;
name: string;
participants: TeamParticipantView[];
}
@@ -57,21 +55,21 @@ export interface MatchDetailView {
teams: TeamView[];
result?: {
winner?: string;
winnerSide?: TeamSide;
blueScore: number;
redScore: number;
winnerTeamIndex?: number;
riotMatchIds: string[];
games: Array<{
gameNumber: number;
riotMatchId: string;
winnerSide: TeamSide;
blueGroupIndex: number;
redGroupIndex: number;
blueTeamIndex: number;
redTeamIndex: number;
winnerTeamIndex: number;
winnerSide: "blue" | "red";
gameCreation: number;
gameDuration: number;
participants: Array<{
userId: string;
side: TeamSide;
teamIndex: number;
side: "blue" | "red";
championId: number;
kills: number;
deaths: number;
@@ -101,8 +99,8 @@ export interface AuctionPlayerView extends ParticipantView {
}
export interface AuctionTeamView {
side: TeamSide;
groupIndex: number;
teamIndex: number;
name: string;
captainUserId: string;
captainName: string;
points: number;
@@ -121,13 +119,12 @@ export interface AuctionStateView {
totalPlayers: number;
auctionOrder: AuctionPlayerView[];
bids: {
side: TeamSide;
groupIndex: number;
teamIndex: number;
amount: number;
timestamp: string;
}[];
currentBid: number;
currentBidder: { side: TeamSide; groupIndex: number } | null;
currentBidder: { teamIndex: number } | null;
timer: number;
maxTimer: number;
deadline?: string;
@@ -270,8 +267,8 @@ function mapAuctionTeamToView(
participantLookup: Map<string, ParticipantView>,
): AuctionTeamView {
return {
side: team.side,
groupIndex: team.groupIndex ?? 1,
teamIndex: team.teamIndex,
name: teamIndexLabel(team.teamIndex),
captainUserId: team.captainUserId,
captainName:
participantLookup.get(team.captainUserId)?.summonerName ??
@@ -405,9 +402,8 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
);
const teams = match.teams.map((team) => ({
side: team.side,
groupIndex: team.groupIndex ?? 1,
name: team.name || sideLabel(team.side),
teamIndex: team.teamIndex,
name: teamIndexLabel(team.teamIndex, team.name),
participants: team.members.map((member) => {
const participant =
participantLookup.get(member.userId) ??
@@ -421,8 +417,8 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
}),
}));
const winnerTeam = match.result?.winnerSide
? teams.find((team) => team.side === match.result?.winnerSide)
const winnerTeam = match.result?.winnerTeamIndex
? teams.find((team) => team.teamIndex === match.result?.winnerTeamIndex)
: undefined;
return {
@@ -434,20 +430,16 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
description: match.description,
map: mapIdToLabel(match.mapId),
maxParticipants: match.maxParticipants,
gameCount: match.gameCount ?? 3,
gameMode: match.gameMode ?? "pair",
gameCount: match.gameCount ?? 3,
gameMode: match.gameMode ?? "pair",
tournamentCodes: match.tournamentCodes ?? [],
joined: Boolean(match.joined),
participants,
teams,
result: match.result
? {
winner: match.result.winnerSide
? winnerTeam?.name ?? sideLabel(match.result.winnerSide)
: undefined,
winnerSide: match.result.winnerSide,
blueScore: match.result.blueScore,
redScore: match.result.redScore,
? {
winner: match.result.winnerTeamIndex ? winnerTeam?.name : undefined,
winnerTeamIndex: match.result.winnerTeamIndex,
riotMatchIds: match.result.riotMatchIds,
games: [...(match.result.games ?? [])].sort(
(left, right) => left.gameNumber - right.gameNumber,
@@ -476,9 +468,7 @@ export function mapApiAuctionToAuctionState(
auctionOrder.map((player) => [player.userId, player]),
);
const teams = [...auction.teams].sort(
(left, right) =>
(left.groupIndex ?? 1) - (right.groupIndex ?? 1) ||
(left.side === "blue" ? -1 : 1),
(left, right) => left.teamIndex - right.teamIndex,
);
const totalPlayers = auctionOrder.length;
@@ -510,16 +500,14 @@ export function mapApiAuctionToAuctionState(
totalPlayers,
auctionOrder,
bids: auction.bids.map((bid) => ({
side: bid.side,
groupIndex: bid.groupIndex ?? 1,
teamIndex: bid.teamIndex,
amount: bid.amount,
timestamp: bid.timestamp,
})),
currentBid: auction.currentBid,
currentBidder: auction.currentBidder
currentBidder: auction.currentBidderTeamIndex
? {
side: auction.currentBidder,
groupIndex: auction.currentBidderGroupIndex ?? 1,
teamIndex: auction.currentBidderTeamIndex,
}
: null,
timer,
+35 -27
View File
@@ -117,8 +117,8 @@ export type TournamentCodeSlotState = TournamentCodeState | 'pending';
export interface TournamentCodeSlotView {
gameNumber: number;
blueGroupIndex: number;
redGroupIndex: number;
teamAIndex: number;
teamBIndex: number;
code: string | null;
expiresAt: string | null;
state: TournamentCodeSlotState;
@@ -144,8 +144,7 @@ export interface ApiMatchTeamMember {
}
export interface ApiMatchTeam {
side: TeamSide;
groupIndex: number;
teamIndex: number;
name: string;
captainUserId?: string;
members: ApiMatchTeamMember[];
@@ -153,6 +152,7 @@ export interface ApiMatchTeam {
export interface ApiMatchGameResultParticipant {
userId: string;
teamIndex: number;
side: TeamSide;
championId: number;
kills: number;
@@ -164,27 +164,26 @@ export interface ApiMatchGameResultParticipant {
export interface ApiMatchGameResult {
gameNumber: number;
riotMatchId: string;
blueTeamIndex: number;
redTeamIndex: number;
winnerTeamIndex: number;
winnerSide: TeamSide;
blueGroupIndex: number;
redGroupIndex: number;
gameCreation: number;
gameDuration: number;
participants: ApiMatchGameResultParticipant[];
}
export interface ApiMatchResult {
winnerSide?: TeamSide;
blueScore: number;
redScore: number;
winnerTeamIndex?: number;
mvpUserId?: string;
riotMatchIds: string[];
games: ApiMatchGameResult[];
seriesResults?: Array<{
blueGroupIndex: number;
redGroupIndex: number;
blueScore: number;
redScore: number;
winnerSide?: TeamSide;
teamAIndex: number;
teamBIndex: number;
teamAWins: number;
teamBWins: number;
winnerTeamIndex?: number;
}>;
}
@@ -236,16 +235,14 @@ export interface ApiAuctionTeamMember {
}
export interface ApiAuctionTeam {
side: TeamSide;
groupIndex: number;
teamIndex: number;
captainUserId: string;
points: number;
members: ApiAuctionTeamMember[];
}
export interface ApiAuctionBid {
side: TeamSide;
groupIndex?: number;
teamIndex: number;
amount: number;
bidderUserId: string;
timestamp: string;
@@ -260,8 +257,7 @@ export interface ApiAuction {
currentIndex: number;
bids: ApiAuctionBid[];
currentBid: number;
currentBidder?: TeamSide;
currentBidderGroupIndex?: number;
currentBidderTeamIndex?: number;
maxTimerSeconds: number;
currentDeadline?: string;
initialPoints: number;
@@ -520,17 +516,25 @@ export interface ApiInternalMatchCard {
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;
@@ -605,12 +609,14 @@ export interface ApiInternalMatchDetailResponse {
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;
@@ -725,9 +731,11 @@ export interface LegacyMatchListItem {
riotMatchId: string | null;
memberCount: number;
externalCount: number;
blueScore: number;
redScore: number;
winnerSide?: TeamSide;
teamAIndex: number;
teamBIndex: number;
teamAWins: number;
teamBWins: number;
winnerTeamIndex?: number;
}
export interface LegacyMatchListResponse {
+2 -3
View File
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react';
import { io, type Socket } from 'socket.io-client';
import { API_BASE_URL, useAuthUserId } from '../config';
import { acquireAccessToken } from '../lib/auth/token-provider';
import type { ApiAuction, Position, TeamSide } from './types';
import type { ApiAuction, Position } from './types';
type ConnectionStatus =
| 'idle'
@@ -12,8 +12,7 @@ type ConnectionStatus =
| 'error';
interface BidPayload {
side: TeamSide;
groupIndex?: number;
teamIndex: number;
amount: number;
bidderUserId?: string;
}
+24 -19
View File
@@ -1,9 +1,8 @@
import { useSyncExternalStore } from 'react';
export type DevCaptainSide = 'spectator' | 'blue' | 'red';
const AUTH_USER_ID_STORAGE_KEY = 'lolympus.authUserId';
const DEV_CAPTAIN_SIDE_STORAGE_KEY = 'lolympus.devCaptainSide';
const DEV_CAPTAIN_TEAM_INDEX_STORAGE_KEY = 'lolympus.devCaptainTeamIndex';
const LEGACY_DEV_CAPTAIN_SIDE_STORAGE_KEY = 'lolympus.devCaptainSide';
const AUTH_USER_CHANGED_EVENT = 'lolympus:auth-user-changed';
const CAPTAIN_SIDE_CHANGED_EVENT = 'lolympus:captain-side-changed';
@@ -55,23 +54,29 @@ export function setAuthUserId(userId: string | null) {
dispatchWindowEvent(AUTH_USER_CHANGED_EVENT);
}
export function getDevCaptainSide(): DevCaptainSide {
if (typeof window === 'undefined') return 'spectator';
export function getDevCaptainTeamIndex(): number | null {
if (typeof window === 'undefined') return null;
const value = window.localStorage.getItem(
DEV_CAPTAIN_SIDE_STORAGE_KEY,
) as DevCaptainSide | null;
const value = window.localStorage.getItem(DEV_CAPTAIN_TEAM_INDEX_STORAGE_KEY);
const parsed = Number(value);
if (Number.isInteger(parsed) && parsed > 0) return parsed;
if (value === 'blue' || value === 'red' || value === 'spectator') {
return value;
}
return 'spectator';
const legacy = window.localStorage.getItem(LEGACY_DEV_CAPTAIN_SIDE_STORAGE_KEY);
if (legacy === 'blue') return 1;
if (legacy === 'red') return 2;
return null;
}
export function setDevCaptainSide(side: DevCaptainSide) {
export function setDevCaptainTeamIndex(teamIndex: number | null) {
if (typeof window === 'undefined') return;
window.localStorage.setItem(DEV_CAPTAIN_SIDE_STORAGE_KEY, side);
if (teamIndex && Number.isInteger(teamIndex) && teamIndex > 0) {
window.localStorage.setItem(
DEV_CAPTAIN_TEAM_INDEX_STORAGE_KEY,
String(teamIndex),
);
} else {
window.localStorage.removeItem(DEV_CAPTAIN_TEAM_INDEX_STORAGE_KEY);
}
dispatchWindowEvent(CAPTAIN_SIDE_CHANGED_EVENT);
}
@@ -83,10 +88,10 @@ export function useAuthUserId(): string | null {
);
}
export function useDevCaptainSide(): DevCaptainSide {
return useSyncExternalStore<DevCaptainSide>(
export function useDevCaptainTeamIndex(): number | null {
return useSyncExternalStore<number | null>(
(callback) => subscribeToWindowChanges(CAPTAIN_SIDE_CHANGED_EVENT, callback),
getDevCaptainSide,
() => 'spectator',
getDevCaptainTeamIndex,
() => null,
);
}
+56 -89
View File
@@ -10,8 +10,8 @@ import {
import { useAuctionSocket } from '../api/useAuctionSocket';
import {
DEFAULT_COMMUNITY_ID,
setDevCaptainSide,
useDevCaptainSide,
setDevCaptainTeamIndex,
useDevCaptainTeamIndex,
} from '../config';
import { ApiError } from '../lib/api';
import {
@@ -19,36 +19,31 @@ import {
championIconUrl,
profileIconUrl,
} from '../lib/ddragon';
import { positionIcon, positionLabel } from '../lib/league';
import {
positionIcon,
positionLabel,
teamIndexColorClasses,
teamIndexLabel,
} from '../lib/league';
import type {
ApiAuction,
ApiRiotLaneStats,
Position,
TeamSide,
} from '../api/types';
type CaptainRole = {
side: TeamSide;
groupIndex: number;
teamIndex: number;
};
function formatPoints(value: number) {
return value.toLocaleString();
}
function teamLabel(side: 'blue' | 'red', groupIndex = 1) {
const sideLabel = side === 'blue' ? '블루팀' : '레드팀';
return groupIndex === 1 ? sideLabel : `${groupIndex}조 ${sideLabel}`;
}
function isCurrentBidder(
currentBidder: AuctionStateView['currentBidder'],
team: Pick<AuctionStateView['teams'][number], 'side' | 'groupIndex'>,
team: Pick<AuctionStateView['teams'][number], 'teamIndex'>,
) {
return (
currentBidder?.side === team.side &&
currentBidder.groupIndex === team.groupIndex
);
return currentBidder?.teamIndex === team.teamIndex;
}
function getAuctionUpdatedAt(auction: ApiAuction | null | undefined) {
@@ -231,26 +226,22 @@ function TeamPanel({
isLeft: boolean;
}) {
const { data: ddragon } = useDdragonManifest();
const borderColor =
team.side === 'blue' ? 'border-blue-500/25' : 'border-red-500/25';
const accentBar = team.side === 'blue' ? 'bg-blue-500' : 'bg-red-500';
const sideColor = team.side === 'blue' ? 'text-blue-400' : 'text-red-400';
const headerBg = team.side === 'blue' ? 'bg-blue-500/8' : 'bg-red-500/8';
const tone = teamIndexColorClasses(team.teamIndex);
const teamSize = team.members.length + 1;
const isFull = teamSize >= AUCTION_MAX_TEAM_SIZE;
return (
<div
className={`border ${borderColor} bg-base-100 relative ${isActive ? 'ring-1 ring-primary/30' : ''}`}
className={`border ${tone.border} bg-base-100 relative ${isActive ? 'ring-1 ring-primary/30' : ''}`}
>
<div
className={`absolute ${isLeft ? 'left-0' : 'right-0'} top-0 bottom-0 w-0.5 ${accentBar}`}
className={`absolute ${isLeft ? 'left-0' : 'right-0'} top-0 bottom-0 w-0.5 ${tone.bar}`}
/>
<div className={`${headerBg} px-3 py-2 border-b ${borderColor}`}>
<div className={`${tone.bg} px-3 py-2 border-b ${tone.border}`}>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<span className={`text-[11px] font-bold uppercase tracking-wide ${sideColor}`}>
{teamLabel(team.side, team.groupIndex)}
<span className={`text-[11px] font-bold uppercase tracking-wide ${tone.text}`}>
{teamIndexLabel(team.teamIndex, team.name)}
</span>
<span className="text-[10px] text-base-content/30">
팀장: {team.captainName}
@@ -306,7 +297,7 @@ function TeamPanel({
length: Math.max(0, AUCTION_MAX_TEAM_SIZE - 1 - team.members.length),
}).map((_, index) => (
<div
key={`empty-${team.side}-${team.groupIndex}-${index}`}
key={`empty-${team.teamIndex}-${index}`}
className="px-3 py-1.5 h-[34px] flex items-center"
>
<div className="w-6 h-6 border border-dashed border-base-content/8 shrink-0" />
@@ -426,12 +417,9 @@ function PlayerSpotlight({
<div className="flex items-center gap-2">
{state.currentBidder && (
<span
className={`text-[10px] font-bold uppercase ${state.currentBidder.side === 'blue' ? 'text-blue-400' : 'text-red-400'}`}
className={`text-[10px] font-bold uppercase ${teamIndexColorClasses(state.currentBidder.teamIndex).text}`}
>
{teamLabel(
state.currentBidder.side,
state.currentBidder.groupIndex,
)}
{teamIndexLabel(state.currentBidder.teamIndex)}
</span>
)}
<span className="text-lg font-black text-amber-400 tabular-nums">
@@ -452,16 +440,12 @@ function BidControls({
}: {
state: AuctionStateView;
captainRole: CaptainRole | null;
onBid: (side: TeamSide, groupIndex: number, amount: number) => void;
onBid: (teamIndex: number, amount: number) => void;
}) {
const [bidAmount, setBidAmount] = useState(100);
const minBid = state.currentBid + 10;
const activeTeam = captainRole
? state.teams.find(
(team) =>
team.side === captainRole.side &&
team.groupIndex === captainRole.groupIndex,
)
? state.teams.find((team) => team.teamIndex === captainRole.teamIndex)
: null;
const activeTeamSize = activeTeam ? activeTeam.members.length + 1 : 0;
const isActiveTeamFull = activeTeamSize >= AUCTION_MAX_TEAM_SIZE;
@@ -511,21 +495,19 @@ function BidControls({
/>
</div>
<button
onClick={() => onBid(activeTeam.side, activeTeam.groupIndex, bidAmount)}
onClick={() => onBid(activeTeam.teamIndex, bidAmount)}
disabled={
isActiveTeamFull ||
bidAmount > activeTeam.points ||
bidAmount <= state.currentBid
}
className={`w-full py-2 text-xs font-bold uppercase tracking-wide border transition-colors disabled:opacity-30 disabled:cursor-not-allowed ${
activeTeam.side === 'blue'
? 'border-blue-500/30 bg-blue-500/10 text-blue-400 hover:bg-blue-500/20'
: 'border-red-500/30 bg-red-500/10 text-red-400 hover:bg-red-500/20'
`${teamIndexColorClasses(activeTeam.teamIndex).border} ${teamIndexColorClasses(activeTeam.teamIndex).bg} ${teamIndexColorClasses(activeTeam.teamIndex).text} hover:bg-base-content/5`
}`}
>
{isActiveTeamFull
? `${teamLabel(activeTeam.side, activeTeam.groupIndex)} 정원 완료 (${activeTeamSize}/${AUCTION_MAX_TEAM_SIZE})`
: `${teamLabel(activeTeam.side, activeTeam.groupIndex)} 입찰 (${formatPoints(bidAmount)}P)`}
? `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 정원 완료 (${activeTeamSize}/${AUCTION_MAX_TEAM_SIZE})`
: `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 입찰 (${formatPoints(bidAmount)}P)`}
</button>
</div>
);
@@ -549,11 +531,11 @@ function BidLog({ bids }: { bids: AuctionStateView['bids'] }) {
</div>
<div className="max-h-28 overflow-y-auto p-2 space-y-0.5">
{bids.map((bid, index) => (
<div key={`${bid.side}-${bid.timestamp}-${index}`} className="flex items-center gap-2 text-[11px]">
<div key={`${bid.teamIndex}-${bid.timestamp}-${index}`} className="flex items-center gap-2 text-[11px]">
<span
className={`font-bold uppercase ${bid.side === 'blue' ? 'text-blue-400' : 'text-red-400'}`}
className={`font-bold uppercase ${teamIndexColorClasses(bid.teamIndex).text}`}
>
{teamLabel(bid.side, bid.groupIndex)}
{teamIndexLabel(bid.teamIndex)}
</span>
<span className="text-base-content/30">→</span>
<span className="text-amber-400 tabular-nums font-semibold">
@@ -579,8 +561,7 @@ export default function AuctionPage() {
refetchInterval: 5000,
});
const socket = useAuctionSocket(id);
const captainSide = useDevCaptainSide();
const [captainGroupIndex, setCaptainGroupIndex] = useState(1);
const captainTeamIndex = useDevCaptainTeamIndex();
const [now, setNow] = useState(() => Date.now());
const [assignedPosition, setAssignedPosition] = useState<Position>('MID');
@@ -594,16 +575,15 @@ export default function AuctionPage() {
liveAuction && matchQuery.data
? mapApiAuctionToAuctionState(liveAuction, matchQuery.data, new Date(now))
: null;
const availableGroups = useMemo(() => {
const groups = new Set((auctionState?.teams ?? []).map((team) => team.groupIndex));
return [...groups].sort((left, right) => left - right);
const availableTeamIndexes = useMemo(() => {
const indexes = new Set((auctionState?.teams ?? []).map((team) => team.teamIndex));
return [...indexes].sort((left, right) => left - right);
}, [auctionState?.teams]);
const captainRole: CaptainRole | null =
captainSide === 'spectator'
captainTeamIndex === null
? null
: {
side: captainSide,
groupIndex: captainGroupIndex,
teamIndex: captainTeamIndex,
};
useEffect(() => {
@@ -613,11 +593,11 @@ export default function AuctionPage() {
}, [auctionState?.currentPlayer?.id]);
useEffect(() => {
if (availableGroups.length === 0) return;
if (!availableGroups.includes(captainGroupIndex)) {
setCaptainGroupIndex(availableGroups[0]);
if (availableTeamIndexes.length === 0) return;
if (captainTeamIndex !== null && !availableTeamIndexes.includes(captainTeamIndex)) {
setDevCaptainTeamIndex(availableTeamIndexes[0]);
}
}, [availableGroups, captainGroupIndex]);
}, [availableTeamIndexes, captainTeamIndex]);
if (!DEFAULT_COMMUNITY_ID) {
return (
@@ -737,31 +717,23 @@ export default function AuctionPage() {
<span>소켓: {socket.connectionStatus}</span>
{/* 임시 운영용: 로그인/권한 확인 없이 조작자 역할을 선택할 수 있게 열어둔다. */}
<select
value={captainSide}
value={captainTeamIndex ?? 'spectator'}
onChange={(event) =>
setDevCaptainSide(event.target.value as 'spectator' | 'blue' | 'red')
setDevCaptainTeamIndex(
event.target.value === 'spectator'
? null
: Number(event.target.value),
)
}
className="border border-base-content/10 bg-transparent px-2 py-1 text-xs"
>
<option value="spectator">관전자</option>
<option value="blue">블루팀장</option>
<option value="red">레드팀장</option>
{availableTeamIndexes.map((teamIndex) => (
<option key={teamIndex} value={teamIndex}>
{teamIndexLabel(teamIndex)} 팀장
</option>
))}
</select>
{captainSide !== 'spectator' && availableGroups.length > 1 && (
<select
value={captainGroupIndex}
onChange={(event) =>
setCaptainGroupIndex(Number(event.target.value))
}
className="border border-base-content/10 bg-transparent px-2 py-1 text-xs"
>
{availableGroups.map((groupIndex) => (
<option key={groupIndex} value={groupIndex}>
{groupIndex}조
</option>
))}
</select>
)}
</div>
</div>
</div>
@@ -774,10 +746,10 @@ export default function AuctionPage() {
<div className="grid sm:grid-cols-2 gap-4 content-start">
{auctionState.teams.map((team) => (
<TeamPanel
key={`${team.side}-${team.groupIndex}`}
key={team.teamIndex}
team={team}
isActive={isCurrentBidder(auctionState.currentBidder, team)}
isLeft={team.side === 'blue'}
isLeft={team.teamIndex % 2 === 1}
/>
))}
</div>
@@ -805,15 +777,10 @@ export default function AuctionPage() {
{auctionState.phase === 'sold' && auctionState.currentBidder && (
<div
className={`text-center py-3 border text-sm font-bold ${
auctionState.currentBidder.side === 'blue'
? 'border-blue-500/20 bg-blue-500/8 text-blue-400'
: 'border-red-500/20 bg-red-500/8 text-red-400'
`${teamIndexColorClasses(auctionState.currentBidder.teamIndex).border} ${teamIndexColorClasses(auctionState.currentBidder.teamIndex).bg} ${teamIndexColorClasses(auctionState.currentBidder.teamIndex).text}`
}`}
>
{teamLabel(
auctionState.currentBidder.side,
auctionState.currentBidder.groupIndex,
)} 낙찰
{teamIndexLabel(auctionState.currentBidder.teamIndex)} 낙찰
{' '}— {formatPoints(auctionState.currentBid)}P
</div>
)}
@@ -821,8 +788,8 @@ export default function AuctionPage() {
<BidControls
state={auctionState}
captainRole={captainRole}
onBid={(side, groupIndex, amount) =>
socket.placeBid({ side, groupIndex, amount })
onBid={(teamIndex, amount) =>
socket.placeBid({ teamIndex, amount })
}
/>
<BidLog bids={auctionState.bids} />
@@ -14,6 +14,7 @@ import type {
} from '../api/types';
import { DEFAULT_COMMUNITY_ID } from '../config';
import { championDisplayName, championIconUrl, profileIconUrl } from '../lib/ddragon';
import { sideShortLabel, teamIndexColorClasses, teamIndexLabel } from '../lib/league';
function formatDateTime(value: string) {
return new Intl.DateTimeFormat('ko-KR', {
@@ -31,7 +32,7 @@ function formatDuration(seconds: number) {
}
function sideLabel(side: TeamSide) {
return side === 'blue' ? '블루팀' : '레드팀';
return sideShortLabel(side);
}
function sideText(side: TeamSide) {
@@ -70,6 +71,13 @@ function MatchCard({
match: ApiInternalMatchCard;
manifest: ReturnType<typeof useDdragonManifest>['data'];
}) {
const primarySeries = match.seriesResults[0];
const teamName = (teamIndex: number) =>
teamIndexLabel(
teamIndex,
match.teams.find((team) => team.teamIndex === teamIndex)?.name,
);
return (
<Link
to={`/communities/${DEFAULT_COMMUNITY_ID}/internal-stats/match/${match.matchId}`}
@@ -91,9 +99,9 @@ function MatchCard({
className="inline-flex items-center gap-1 border border-base-content/10 px-2 py-1 text-[10px] text-base-content/45"
>
{game.gameNumber}경기
{game.winnerSide ? (
{game.winnerSide && game.winnerTeamIndex ? (
<span className={sideText(game.winnerSide)}>
{sideLabel(game.winnerSide)} 승
{teamName(game.winnerTeamIndex)} 승 ({sideLabel(game.winnerSide)})
</span>
) : (
'대기'
@@ -105,26 +113,32 @@ function MatchCard({
</div>
<div className="text-center px-8">
<div className="flex items-center justify-center gap-5">
<div className={match.winnerSide === 'blue' ? 'text-blue-400' : 'text-blue-400/30'}>
<div className="text-4xl font-black tabular-nums">{match.blueScore}</div>
<div className="text-[10px] font-bold uppercase tracking-wider">BLUE</div>
{primarySeries && (
<div className="flex items-center justify-center gap-5">
<div className={primarySeries.winnerTeamIndex === primarySeries.teamAIndex ? teamIndexColorClasses(primarySeries.teamAIndex).text : 'text-base-content/30'}>
<div className="text-4xl font-black tabular-nums">{primarySeries.teamAWins}</div>
<div className="text-[10px] font-bold uppercase tracking-wider">
{teamName(primarySeries.teamAIndex)}
</div>
</div>
<div className="text-base-content/15 text-xs font-black">VS</div>
<div className={primarySeries.winnerTeamIndex === primarySeries.teamBIndex ? teamIndexColorClasses(primarySeries.teamBIndex).text : 'text-base-content/30'}>
<div className="text-4xl font-black tabular-nums">{primarySeries.teamBWins}</div>
<div className="text-[10px] font-bold uppercase tracking-wider">
{teamName(primarySeries.teamBIndex)}
</div>
</div>
</div>
<div className="text-base-content/15 text-xs font-black">VS</div>
<div className={match.winnerSide === 'red' ? 'text-red-400' : 'text-red-400/30'}>
<div className="text-4xl font-black tabular-nums">{match.redScore}</div>
<div className="text-[10px] font-bold uppercase tracking-wider">RED</div>
</div>
</div>
)}
</div>
<div className="grid sm:grid-cols-2 gap-2">
{match.teams.map((team) => (
<div
key={team.side}
className={`border ${team.side === 'blue' ? 'border-blue-500/15' : 'border-red-500/15'} p-2`}
key={team.teamIndex}
className={`border ${teamIndexColorClasses(team.teamIndex).border} p-2`}
>
<div className={`text-[10px] font-black uppercase tracking-wider ${sideText(team.side)}`}>
<div className={`text-[10px] font-black uppercase tracking-wider ${teamIndexColorClasses(team.teamIndex).text}`}>
{team.name}
</div>
<div className="mt-2 space-y-1">
+28 -13
View File
@@ -3,6 +3,7 @@ import { useDdragonManifest, useInternalMatchDetail } from '../api/hooks';
import type { ApiInternalMatchDetailResponse, TeamSide } from '../api/types';
import { DEFAULT_COMMUNITY_ID } from '../config';
import { championDisplayName, championIconUrl, itemIconUrl } from '../lib/ddragon';
import { sideShortLabel, teamIndexColorClasses, teamIndexLabel } from '../lib/league';
import { LANE_LABELS } from '../lib/riot-history';
function formatDateTime(value: string | number) {
@@ -21,7 +22,7 @@ function formatDuration(seconds: number) {
}
function sideLabel(side: TeamSide) {
return side === 'blue' ? '블루팀' : '레드팀';
return sideShortLabel(side);
}
function sideClass(side: TeamSide) {
@@ -100,7 +101,8 @@ function GamePanel({
team.win ? 'bg-base-content/5' : 'opacity-40'
}`}
>
{sideLabel(team.side)} {team.win ? '승' : '패'}
{teamIndexLabel(team.teamIndex)} ({sideLabel(team.side)}){' '}
{team.win ? '승' : '패'}
</span>
))}
</div>
@@ -109,7 +111,7 @@ function GamePanel({
{game.teams.map((team) => (
<div key={team.side} className="border-b border-base-content/8 last:border-b-0">
<div className={`px-4 py-2 text-[11px] font-black uppercase tracking-wider ${sideClass(team.side)}`}>
{sideLabel(team.side)} · 바론 {team.objectives.baron} · 드래곤{' '}
{teamIndexLabel(team.teamIndex)} ({sideLabel(team.side)}) · 바론 {team.objectives.baron} · 드래곤{' '}
{team.objectives.dragon} · 타워 {team.objectives.tower}
</div>
<div className="overflow-x-auto">
@@ -219,6 +221,13 @@ export default function InternalMatchDetailPage() {
);
}
const primarySeries = detail.match.seriesResults[0];
const teamName = (teamIndex: number) =>
teamIndexLabel(
teamIndex,
detail.match.teams.find((team) => team.teamIndex === teamIndex)?.name,
);
return (
<main className="max-w-6xl mx-auto px-4 sm:px-6 py-6">
<Link
@@ -238,17 +247,23 @@ export default function InternalMatchDetailPage() {
{formatDateTime(detail.match.scheduledAt)} · {detail.match.gameCount}전제
</p>
</div>
<div className="flex items-center gap-6">
<div className={detail.match.winnerSide === 'blue' ? 'text-blue-400' : 'text-blue-400/30'}>
<div className="text-4xl font-black tabular-nums">{detail.match.blueScore}</div>
<div className="text-[10px] font-bold uppercase tracking-wider">BLUE</div>
{primarySeries && (
<div className="flex items-center gap-6">
<div className={primarySeries.winnerTeamIndex === primarySeries.teamAIndex ? teamIndexColorClasses(primarySeries.teamAIndex).text : 'text-base-content/30'}>
<div className="text-4xl font-black tabular-nums">{primarySeries.teamAWins}</div>
<div className="text-[10px] font-bold uppercase tracking-wider">
{teamName(primarySeries.teamAIndex)}
</div>
</div>
<div className="text-base-content/15 text-xs font-black">VS</div>
<div className={primarySeries.winnerTeamIndex === primarySeries.teamBIndex ? teamIndexColorClasses(primarySeries.teamBIndex).text : 'text-base-content/30'}>
<div className="text-4xl font-black tabular-nums">{primarySeries.teamBWins}</div>
<div className="text-[10px] font-bold uppercase tracking-wider">
{teamName(primarySeries.teamBIndex)}
</div>
</div>
</div>
<div className="text-base-content/15 text-xs font-black">VS</div>
<div className={detail.match.winnerSide === 'red' ? 'text-red-400' : 'text-red-400/30'}>
<div className="text-4xl font-black tabular-nums">{detail.match.redScore}</div>
<div className="text-[10px] font-bold uppercase tracking-wider">RED</div>
</div>
</div>
)}
</div>
</section>
+73 -69
View File
@@ -21,7 +21,13 @@ import {
import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config';
import { apiFetch, ApiError } from '../lib/api';
import { profileIconUrl } from '../lib/ddragon';
import { positionIcon, positionLabel } from '../lib/league';
import {
positionIcon,
positionLabel,
sideShortLabel,
teamIndexColorClasses,
teamIndexLabel,
} from '../lib/league';
import type {
ApiMatchParticipant,
Position,
@@ -30,17 +36,11 @@ import type {
} from '../api/types';
type CaptainSelectionSlot = {
side: TeamSide;
groupIndex: number;
teamIndex: number;
};
function captainSlotKey(slot: CaptainSelectionSlot) {
return `${slot.side}:${slot.groupIndex}`;
}
function teamLabel(side: TeamSide, groupIndex = 1) {
const sideText = side === 'blue' ? '블루팀' : '레드팀';
return groupIndex === 1 ? sideText : `${groupIndex}조 ${sideText}`;
return String(slot.teamIndex);
}
function buildAuctionParticipantPool(participants: ApiMatchParticipant[]) {
@@ -55,13 +55,10 @@ function buildAuctionParticipantPool(participants: ApiMatchParticipant[]) {
function buildCaptainSlots(
participants: ApiMatchParticipant[],
): CaptainSelectionSlot[] {
const groupCount = Math.floor(buildAuctionParticipantPool(participants).length / 10);
return Array.from({ length: groupCount }, (_, index) => index + 1).flatMap(
(groupIndex) => [
{ side: 'blue' as const, groupIndex },
{ side: 'red' as const, groupIndex },
],
);
const teamCount = Math.floor(buildAuctionParticipantPool(participants).length / 5);
return Array.from({ length: teamCount }, (_, index) => ({
teamIndex: index + 1,
}));
}
function PosBadge({ pos, sub }: { pos: Position; sub?: boolean }) {
@@ -267,20 +264,16 @@ function TeamCard({
matchId: string;
isWinner?: boolean;
}) {
const borderColor =
team.side === 'blue' ? 'border-blue-500/25' : 'border-red-500/25';
const headerBg = team.side === 'blue' ? 'bg-blue-500/8' : 'bg-red-500/8';
const sideColor = team.side === 'blue' ? 'text-blue-400' : 'text-red-400';
const accentBar = team.side === 'blue' ? 'bg-blue-500' : 'bg-red-500';
const tone = teamIndexColorClasses(team.teamIndex);
return (
<div className={`border ${borderColor} overflow-hidden bg-base-100 relative`}>
<div className={`absolute left-0 top-0 bottom-0 w-0.5 ${accentBar}`} />
<div className={`border ${tone.border} overflow-hidden bg-base-100 relative`}>
<div className={`absolute left-0 top-0 bottom-0 w-0.5 ${tone.bar}`} />
<div
className={`${headerBg} px-4 py-2 flex items-center justify-between border-b ${borderColor}`}
className={`${tone.bg} px-4 py-2 flex items-center justify-between border-b ${tone.border}`}
>
<div className="flex items-center gap-2">
<span className={`text-xs font-bold uppercase tracking-wide ${sideColor}`}>
<span className={`text-xs font-bold uppercase tracking-wide ${tone.text}`}>
{team.name}
</span>
{isWinner && (
@@ -290,7 +283,7 @@ function TeamCard({
)}
</div>
<Link
to={`/match/${matchId}/team/${team.side}/${team.groupIndex}`}
to={`/match/${matchId}/team/${team.teamIndex}`}
className="text-[10px] font-bold text-base-content/35 hover:text-primary"
>
진행 페이지
@@ -414,9 +407,9 @@ function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) {
<div key={slot.gameNumber} className="flex items-start gap-2">
<span className="text-[11px] font-bold text-base-content/40 w-20 shrink-0 pt-1.5">
{slot.gameNumber}경기
{(slot.blueGroupIndex > 1 || slot.redGroupIndex > 1) && (
{(slot.teamAIndex > 1 || slot.teamBIndex > 2) && (
<span className="block text-[10px] font-normal text-base-content/25">
{slot.blueGroupIndex}조
{teamIndexLabel(slot.teamAIndex)} vs {teamIndexLabel(slot.teamBIndex)}
</span>
)}
</span>
@@ -461,14 +454,19 @@ function formatGameDuration(seconds: number) {
return `${minutes}:${String(rest).padStart(2, '0')}`;
}
function resultSideLabel(side: 'blue' | 'red', groupIndex = 1) {
return teamLabel(side, groupIndex);
}
function resultSideClass(side: 'blue' | 'red') {
return side === 'blue' ? 'text-blue-400' : 'text-red-400';
}
function resultSideLabel(side: TeamSide) {
return sideShortLabel(side);
}
function resolveMatchTeamName(match: MatchDetailView, teamIndex: number) {
const team = match.teams.find((item) => item.teamIndex === teamIndex);
return teamIndexLabel(teamIndex, team?.name);
}
function MatchResultPanel({ match }: { match: MatchDetailView }) {
if (!match.result) return null;
@@ -485,34 +483,37 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) {
(_, index) => index + 1,
);
const seriesResults = match.result.seriesResults ?? [];
const primarySeries = seriesResults[0];
return (
<div className="mb-6 border border-base-content/10 bg-base-content/[0.02] p-5">
<div className="flex items-center justify-center gap-8">
<div
className={`text-center ${match.result.winnerSide === 'blue' ? 'text-blue-400' : 'text-blue-400/30'}`}
>
<div className="text-3xl font-black tabular-nums">
{match.result.blueScore}
{primarySeries && (
<div className="flex items-center justify-center gap-8">
<div
className={`text-center ${primarySeries.winnerTeamIndex === primarySeries.teamAIndex ? teamIndexColorClasses(primarySeries.teamAIndex).text : 'text-base-content/30'}`}
>
<div className="text-3xl font-black tabular-nums">
{primarySeries.teamAWins}
</div>
<div className="text-[10px] uppercase tracking-wider mt-0.5 font-semibold">
{resolveMatchTeamName(match, primarySeries.teamAIndex)}
</div>
</div>
<div className="text-[10px] uppercase tracking-wider mt-0.5 font-semibold">
블루팀
<div className="text-base-content/20 text-xs font-bold uppercase tracking-widest">
VS
</div>
<div
className={`text-center ${primarySeries.winnerTeamIndex === primarySeries.teamBIndex ? teamIndexColorClasses(primarySeries.teamBIndex).text : 'text-base-content/30'}`}
>
<div className="text-3xl font-black tabular-nums">
{primarySeries.teamBWins}
</div>
<div className="text-[10px] uppercase tracking-wider mt-0.5 font-semibold">
{resolveMatchTeamName(match, primarySeries.teamBIndex)}
</div>
</div>
</div>
<div className="text-base-content/20 text-xs font-bold uppercase tracking-widest">
VS
</div>
<div
className={`text-center ${match.result.winnerSide === 'red' ? 'text-red-400' : 'text-red-400/30'}`}
>
<div className="text-3xl font-black tabular-nums">
{match.result.redScore}
</div>
<div className="text-[10px] uppercase tracking-wider mt-0.5 font-semibold">
레드팀
</div>
</div>
</div>
)}
<div className="text-center mt-3 text-[11px] font-bold text-amber-400 uppercase tracking-wide">
{match.result.winner
? `${match.result.winner} 승리`
@@ -522,16 +523,21 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) {
<div className="mt-4 grid sm:grid-cols-2 gap-2">
{seriesResults.map((series) => (
<div
key={`${series.blueGroupIndex}-${series.redGroupIndex}`}
key={`${series.teamAIndex}-${series.teamBIndex}`}
className="border border-base-content/8 bg-base-100 px-3 py-2 text-xs"
>
<div className="font-bold text-base-content/55">
{series.blueGroupIndex}조
{resolveMatchTeamName(match, series.teamAIndex)} vs{' '}
{resolveMatchTeamName(match, series.teamBIndex)}
</div>
<div className="mt-1 flex items-center justify-between">
<span className="text-blue-400">블루 {series.blueScore}</span>
<span className={teamIndexColorClasses(series.teamAIndex).text}>
{series.teamAWins}
</span>
<span className="text-base-content/20">:</span>
<span className="text-red-400">레드 {series.redScore}</span>
<span className={teamIndexColorClasses(series.teamBIndex).text}>
{series.teamBWins}
</span>
</div>
</div>
))}
@@ -540,10 +546,6 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) {
<div className="mt-5 border border-base-content/8 divide-y divide-base-content/8">
{gameNumbers.map((gameNumber) => {
const game = gamesByNumber.get(gameNumber);
const winnerGroupIndex =
game?.winnerSide === 'blue'
? game.blueGroupIndex
: game?.redGroupIndex;
return (
<div
key={gameNumber}
@@ -555,7 +557,10 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) {
{game ? (
<div>
<span className={`font-black ${resultSideClass(game.winnerSide)}`}>
{resultSideLabel(game.winnerSide, winnerGroupIndex)} 승
{resolveMatchTeamName(match, game.winnerTeamIndex)} 승
</span>
<span className="ml-1 text-base-content/35">
({resultSideLabel(game.winnerSide)} 진영)
</span>
<span className="ml-2 text-base-content/35 font-mono">
{game.riotMatchId}
@@ -625,8 +630,7 @@ export default function MatchDetailPage() {
body: JSON.stringify({
captains: buildCaptainSlots(matchQuery.data?.participants ?? []).map(
(slot) => ({
side: slot.side,
groupIndex: slot.groupIndex,
teamIndex: slot.teamIndex,
userId: captainSelections[captainSlotKey(slot)],
}),
),
@@ -851,7 +855,7 @@ export default function MatchDetailPage() {
경매 시작
</h3>
<p className="mt-1 text-xs text-base-content/40">
참가 신청 순서 기준 10명당 1개 조가 만들어지고, 각 조에 블루/레드 팀장을 지정합니다.
참가 신청 순서 기준 5명당 1개 팀이 만들어지고, 각 팀의 팀장을 지정합니다.
</p>
{waitingParticipantCount > 0 && (
<p className="mt-1 text-[11px] text-amber-500">
@@ -876,7 +880,7 @@ export default function MatchDetailPage() {
key={key}
className="text-xs text-base-content/45"
>
{teamLabel(slot.side, slot.groupIndex)} 팀장
{teamIndexLabel(slot.teamIndex)} 팀장
<select
className="mt-1 w-full border border-base-content/10 bg-transparent px-2 py-2 text-sm"
value={currentValue}
@@ -938,12 +942,12 @@ export default function MatchDetailPage() {
<div className="space-y-4">
{match.teams.map((team) => (
<TeamCard
key={`${team.side}-${team.groupIndex}`}
key={team.teamIndex}
team={team}
matchId={match.id}
isWinner={
match.status === 'finished'
? match.result?.winner === team.name
? match.result?.winnerTeamIndex === team.teamIndex
: undefined
}
/>
+15 -23
View File
@@ -1,14 +1,9 @@
import { Link, useParams } from 'react-router';
import { useDdragonManifest, useMatch } from '../api/hooks';
import type { ApiMatchParticipant, Position, TeamSide } from '../api/types';
import type { ApiMatchParticipant, Position } from '../api/types';
import { DEFAULT_COMMUNITY_ID } from '../config';
import { profileIconUrl } from '../lib/ddragon';
import { positionLabel } from '../lib/league';
function teamLabel(side: TeamSide, groupIndex = 1) {
const sideText = side === 'blue' ? '블루팀' : '레드팀';
return groupIndex === 1 ? sideText : `${groupIndex}조 ${sideText}`;
}
import { positionLabel, sideShortLabel, teamIndexLabel } from '../lib/league';
function formatExpiry(value: string | null) {
if (!value) return '-';
@@ -64,9 +59,8 @@ function ParticipantLine({
}
export default function MatchTeamProgressPage() {
const { id, side, groupIndex } = useParams();
const parsedGroupIndex = Number(groupIndex ?? 1);
const teamSide = side === 'blue' || side === 'red' ? side : null;
const { id, teamIndex } = useParams();
const parsedTeamIndex = Number(teamIndex);
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
if (!DEFAULT_COMMUNITY_ID) {
@@ -85,7 +79,7 @@ export default function MatchTeamProgressPage() {
);
}
if (!teamSide || !matchQuery.data) {
if (!Number.isInteger(parsedTeamIndex) || parsedTeamIndex < 1 || !matchQuery.data) {
return (
<main className="mx-auto max-w-5xl px-4 py-20 text-center">
<h1 className="text-lg font-bold">팀 정보를 찾을 수 없습니다</h1>
@@ -97,22 +91,15 @@ export default function MatchTeamProgressPage() {
}
const match = matchQuery.data;
const team = match.teams.find(
(item) =>
item.side === teamSide && (item.groupIndex ?? 1) === parsedGroupIndex,
);
const team = match.teams.find((item) => item.teamIndex === parsedTeamIndex);
const participantByUserId = new Map(
match.participants.map((participant) => [participant.userId, participant]),
);
const codes = (match.tournamentCodes ?? []).filter((slot) =>
teamSide === 'blue'
? slot.blueGroupIndex === parsedGroupIndex
: slot.redGroupIndex === parsedGroupIndex,
slot.teamAIndex === parsedTeamIndex || slot.teamBIndex === parsedTeamIndex,
);
const games = (match.result?.games ?? []).filter((game) =>
teamSide === 'blue'
? game.blueGroupIndex === parsedGroupIndex
: game.redGroupIndex === parsedGroupIndex,
game.blueTeamIndex === parsedTeamIndex || game.redTeamIndex === parsedTeamIndex,
);
if (!team) {
@@ -140,7 +127,7 @@ export default function MatchTeamProgressPage() {
<div className="mb-6 border-b border-base-content/8 pb-5">
<h1 className="text-2xl font-black text-base-content">
{team.name || teamLabel(team.side, team.groupIndex)}
{teamIndexLabel(team.teamIndex, team.name)}
</h1>
<p className="mt-1 text-sm text-base-content/45">
이 팀에 연결된 토너먼트 코드와 수집된 결과만 보여줍니다.
@@ -212,7 +199,9 @@ export default function MatchTeamProgressPage() {
<div className="divide-y divide-base-content/5">
{games.length > 0 ? (
games.map((game) => {
const won = game.winnerSide === teamSide;
const won = game.winnerTeamIndex === parsedTeamIndex;
const side =
game.blueTeamIndex === parsedTeamIndex ? 'blue' : 'red';
return (
<div key={game.gameNumber} className="px-4 py-3 text-xs">
<div className="flex items-center justify-between gap-2">
@@ -225,6 +214,9 @@ export default function MatchTeamProgressPage() {
{won ? '승리' : '패배'}
</span>
</div>
<div className="mt-1 text-[11px] text-base-content/35">
{sideShortLabel(side)} 진영
</div>
<div className="mt-1 truncate font-mono text-[11px] text-base-content/30">
{game.riotMatchId}
</div>
+11 -4
View File
@@ -10,6 +10,7 @@ import {
} from '../../api/hooks';
import type { LegacyMatchListItem } from '../../api/types';
import { DEFAULT_COMMUNITY_ID } from '../../config';
import { teamIndexLabel } from '../../lib/league';
function formatDate(value: string) {
return new Intl.DateTimeFormat('ko-KR', {
@@ -22,10 +23,16 @@ function formatDate(value: string) {
}
function resultLabel(match: LegacyMatchListItem) {
if (!match.winnerSide) return '-';
return match.winnerSide === 'blue'
? `블루 ${match.blueScore}:${match.redScore}`
: `레드 ${match.redScore}:${match.blueScore}`;
if (!match.winnerTeamIndex) return '-';
const winnerScore =
match.winnerTeamIndex === match.teamAIndex
? match.teamAWins
: match.teamBWins;
const loserScore =
match.winnerTeamIndex === match.teamAIndex
? match.teamBWins
: match.teamAWins;
return `${teamIndexLabel(match.winnerTeamIndex)} ${winnerScore}:${loserScore}`;
}
export default function LegacyMatchesPage() {