.
This commit is contained in:
1 parent
b152a5b0fa
commit
2379051196
32 files changed
+1682
-383
No files matched your search
+3
-1
@@ -21,4 +21,6 @@ website/LICENSE
|
||||
|
||||
!.claude/settings.json
|
||||
|
||||
*.temp.MD
|
||||
*.temp.MD
|
||||
|
||||
*.md
|
||||
+1
-2
@@ -43,8 +43,7 @@ COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/package.json ./apps/
|
||||
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/node_modules ./apps/api/node_modules
|
||||
COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist
|
||||
COPY --chown=nonroot:nonroot apps/project.env ./project.env
|
||||
COPY --chown=nonroot:nonroot apps/api/docker-entrypoint.js ./apps/api/docker-entrypoint.js
|
||||
|
||||
EXPOSE 10712
|
||||
|
||||
CMD ["apps/api/docker-entrypoint.js"]
|
||||
CMD ["apps/api/dist/main.js"]
|
||||
@@ -1,72 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const MACHINE_ENV_PATHS = [
|
||||
process.env.MachineEnvFile,
|
||||
process.env.MACHINE_ENV_FILE,
|
||||
'/source/global-env-vars.txt',
|
||||
process.env.HOME
|
||||
? path.join(process.env.HOME, 'source/global-env-vars.txt')
|
||||
: '',
|
||||
].filter(Boolean);
|
||||
|
||||
const PROJECT_ENV_PATHS = [
|
||||
'project.env',
|
||||
'/app/project.env',
|
||||
'apps/project.env',
|
||||
];
|
||||
|
||||
function stripQuotes(value) {
|
||||
const trimmed = value.trim();
|
||||
if (
|
||||
(trimmed.startsWith('"') && trimmed.endsWith('"')) ||
|
||||
(trimmed.startsWith("'") && trimmed.endsWith("'"))
|
||||
) {
|
||||
return trimmed.slice(1, -1);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function loadEnvFile(filePath, options = {}) {
|
||||
const { override = false } = options;
|
||||
const content = fs.readFileSync(filePath, 'utf8');
|
||||
for (const line of content.split(/\r?\n/u)) {
|
||||
if (!line.trim() || /^\s*#/u.test(line)) continue;
|
||||
|
||||
const match = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/u);
|
||||
if (!match) continue;
|
||||
|
||||
if (!override && process.env[match[1]] !== undefined) continue;
|
||||
process.env[match[1]] = stripQuotes(match[2]);
|
||||
}
|
||||
}
|
||||
|
||||
const machineEnvFile = MACHINE_ENV_PATHS.find((candidate) =>
|
||||
fs.existsSync(candidate),
|
||||
);
|
||||
if (machineEnvFile) {
|
||||
loadEnvFile(machineEnvFile, { override: true });
|
||||
}
|
||||
|
||||
for (const projectEnvFile of PROJECT_ENV_PATHS) {
|
||||
if (fs.existsSync(projectEnvFile)) {
|
||||
loadEnvFile(projectEnvFile);
|
||||
}
|
||||
}
|
||||
|
||||
const missing = [
|
||||
'INFISICAL_CLIENT_ID',
|
||||
'INFISICAL_CLIENT_SECRET',
|
||||
'INFISICAL_PROJECT_ID',
|
||||
].filter((key) => !process.env[key]);
|
||||
|
||||
if (missing.length > 0) {
|
||||
console.error(
|
||||
`Missing required environment variables: ${missing.join(', ')}`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
require('./dist/main.js');
|
||||
@@ -10,12 +10,12 @@
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"seed:dev": "ts-node src/seed.ts",
|
||||
"seed:dakao-participant": "ts-node src/seed-dakao-participant.ts",
|
||||
"start:dev": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'dev'); \"./start.ps1\"\"",
|
||||
"start:test": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'test'); \"./start.ps1\"\"",
|
||||
"start:prod": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'prod'); \"./start.ps1\"\"",
|
||||
"pm2:dev": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'dev'); ./start.ps1 -UsePm2\"",
|
||||
"pm2:test": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'test'); ./start.ps1 -UsePm2\"",
|
||||
"pm2:prod": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'prod'); ./start.ps1 -UsePm2\"",
|
||||
"start:dev": "node -e \"process.env.NODE_ENV='dev'; require('./dist/main.js')\"",
|
||||
"start:test": "node -e \"process.env.NODE_ENV='test'; require('./dist/main.js')\"",
|
||||
"start:prod": "node -e \"process.env.NODE_ENV='prod'; require('./dist/main.js')\"",
|
||||
"pm2:dev": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:dev",
|
||||
"pm2:test": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:test",
|
||||
"pm2:prod": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:prod",
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"test": "jest",
|
||||
|
||||
@@ -40,6 +40,7 @@ export class AuctionController {
|
||||
communityId,
|
||||
captains: body.captains.map((c) => ({
|
||||
side: c.side,
|
||||
groupIndex: c.groupIndex ?? 1,
|
||||
userId: new mongoose.Types.ObjectId(c.userId),
|
||||
})),
|
||||
initialPoints: body.initialPoints ?? 1000,
|
||||
@@ -76,6 +77,7 @@ export class AuctionController {
|
||||
return this.auctionService.placeBid({
|
||||
matchId,
|
||||
side: body.side,
|
||||
groupIndex: body.groupIndex ?? 1,
|
||||
amount: body.amount,
|
||||
bidderUserId: this.resolveBidder(currentUser, body.bidderUserId),
|
||||
});
|
||||
|
||||
@@ -30,6 +30,7 @@ interface JoinAuctionPayload {
|
||||
|
||||
interface BidPayload {
|
||||
side: TeamSide;
|
||||
groupIndex?: number;
|
||||
amount: number;
|
||||
bidderUserId?: string;
|
||||
}
|
||||
@@ -125,6 +126,7 @@ export class AuctionGateway
|
||||
const auction = await this.auctionService.placeBid({
|
||||
matchId: new mongoose.Types.ObjectId(matchId),
|
||||
side: payload.side,
|
||||
groupIndex: payload.groupIndex ?? 1,
|
||||
amount: payload.amount,
|
||||
bidderUserId,
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
AuctionDocument,
|
||||
AuctionPlayerSnapshot,
|
||||
AuctionTeam,
|
||||
MatchParticipant,
|
||||
MatchTeamMember,
|
||||
Position,
|
||||
TeamSide,
|
||||
@@ -23,7 +24,11 @@ const AUCTION_MAX_TEAM_SIZE = 5;
|
||||
interface StartAuctionParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
captains: { side: TeamSide; userId: mongoose.Types.ObjectId }[];
|
||||
captains: {
|
||||
side: TeamSide;
|
||||
groupIndex: number;
|
||||
userId: mongoose.Types.ObjectId;
|
||||
}[];
|
||||
initialPoints: number;
|
||||
maxTimerSeconds: number;
|
||||
}
|
||||
@@ -31,6 +36,7 @@ interface StartAuctionParams {
|
||||
interface PlaceBidParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
side: TeamSide;
|
||||
groupIndex: number;
|
||||
amount: number;
|
||||
bidderUserId?: mongoose.Types.ObjectId;
|
||||
}
|
||||
@@ -66,30 +72,24 @@ export class AuctionService {
|
||||
throw new BadRequestException('Auction already exists for this match.');
|
||||
}
|
||||
|
||||
const activeParticipants = this.applyAuctionCut(match);
|
||||
const desiredAuctionCount = activeParticipants.length;
|
||||
if (desiredAuctionCount < 10) {
|
||||
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);
|
||||
const captainUserIds = params.captains.map((c) => c.userId);
|
||||
if (captainUserIds[0].equals(captainUserIds[1])) {
|
||||
throw new BadRequestException('Captains must be different users.');
|
||||
}
|
||||
const captainParticipants = match.participants.filter((p) =>
|
||||
captainUserIds.some((cid) => cid.equals(p.userId)),
|
||||
);
|
||||
if (captainParticipants.length !== 2) {
|
||||
throw new BadRequestException(
|
||||
'Both captains must be participants of the match.',
|
||||
);
|
||||
}
|
||||
if (
|
||||
match.participants.length >
|
||||
params.captains.length * AUCTION_MAX_TEAM_SIZE
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'Auction supports up to 5 members per team including captains.',
|
||||
);
|
||||
}
|
||||
|
||||
const basePlayerUsers = await UserModel.find({
|
||||
_id: {
|
||||
$in: match.participants
|
||||
$in: activeParticipants
|
||||
.filter((p) => !captainUserIds.some((cid) => cid.equals(p.userId)))
|
||||
.map((p) => p.userId),
|
||||
},
|
||||
@@ -130,7 +130,7 @@ export class AuctionService {
|
||||
|
||||
const nonCaptainPuuids = new Set<string>();
|
||||
const order: AuctionPlayerSnapshot[] = [];
|
||||
for (const participant of match.participants) {
|
||||
for (const participant of activeParticipants) {
|
||||
if (captainUserIds.some((cid) => cid.equals(participant.userId))) {
|
||||
continue;
|
||||
}
|
||||
@@ -163,6 +163,7 @@ export class AuctionService {
|
||||
phase: 'presenting',
|
||||
teams: params.captains.map((c) => ({
|
||||
side: c.side,
|
||||
groupIndex: c.groupIndex,
|
||||
captainUserId: c.userId,
|
||||
points: params.initialPoints,
|
||||
members: [],
|
||||
@@ -204,6 +205,7 @@ export class AuctionService {
|
||||
auction.phase = 'bidding';
|
||||
auction.currentBid = 0;
|
||||
auction.currentBidder = undefined;
|
||||
auction.currentBidderGroupIndex = undefined;
|
||||
auction.currentDeadline = this.createDeadline(auction.maxTimerSeconds);
|
||||
await auction.save();
|
||||
return auction;
|
||||
@@ -214,8 +216,8 @@ export class AuctionService {
|
||||
if (auction.phase !== 'bidding') {
|
||||
throw new BadRequestException('Auction is not in bidding phase.');
|
||||
}
|
||||
const team = auction.teams.find((t) => t.side === params.side);
|
||||
if (!team) throw new BadRequestException('Unknown team side.');
|
||||
const team = this.findAuctionTeam(auction, params.side, params.groupIndex);
|
||||
if (!team) throw new BadRequestException('Unknown team.');
|
||||
if (params.amount <= auction.currentBid) {
|
||||
throw new BadRequestException('Bid must exceed current bid.');
|
||||
}
|
||||
@@ -227,11 +229,13 @@ export class AuctionService {
|
||||
|
||||
auction.currentBid = params.amount;
|
||||
auction.currentBidder = params.side;
|
||||
auction.currentBidderGroupIndex = params.groupIndex;
|
||||
auction.currentDeadline = this.createDeadline(
|
||||
this.resolveBidExtensionSeconds(auction),
|
||||
);
|
||||
auction.bids.push({
|
||||
side: params.side,
|
||||
groupIndex: params.groupIndex,
|
||||
amount: params.amount,
|
||||
bidderUserId: team.captainUserId,
|
||||
timestamp: new Date(),
|
||||
@@ -248,7 +252,11 @@ export class AuctionService {
|
||||
if (!auction.currentBidder || auction.currentBid <= 0) {
|
||||
throw new BadRequestException('No bid to mark sold.');
|
||||
}
|
||||
const team = auction.teams.find((t) => t.side === auction.currentBidder);
|
||||
const team = this.findAuctionTeam(
|
||||
auction,
|
||||
auction.currentBidder,
|
||||
auction.currentBidderGroupIndex ?? 1,
|
||||
);
|
||||
if (!team) throw new BadRequestException('Winning team not found.');
|
||||
this.assertTeamHasSlot(team);
|
||||
|
||||
@@ -284,6 +292,7 @@ export class AuctionService {
|
||||
auction.phase = 'presenting';
|
||||
auction.currentBid = 0;
|
||||
auction.currentBidder = undefined;
|
||||
auction.currentBidderGroupIndex = undefined;
|
||||
}
|
||||
auction.currentDeadline = undefined;
|
||||
await auction.save();
|
||||
@@ -323,6 +332,9 @@ export class AuctionService {
|
||||
match.status = 'recruiting';
|
||||
match.teams = [];
|
||||
match.tournamentCodeIds = [];
|
||||
match.participants.forEach((participant) => {
|
||||
participant.excluded = false;
|
||||
});
|
||||
match.teamBuiltAt = undefined;
|
||||
match.result = undefined;
|
||||
match.resultPollState = undefined;
|
||||
@@ -337,6 +349,79 @@ export class AuctionService {
|
||||
}
|
||||
}
|
||||
|
||||
private applyAuctionCut(match: {
|
||||
participants: MatchParticipant[];
|
||||
}): MatchParticipant[] {
|
||||
const ordered = [...match.participants].sort(
|
||||
(left, right) => left.joinedAt.getTime() - right.joinedAt.getTime(),
|
||||
);
|
||||
const desiredAuctionCount = Math.floor(ordered.length / 10) * 10;
|
||||
const activeIds = new Set(
|
||||
ordered
|
||||
.slice(0, desiredAuctionCount)
|
||||
.map((participant) => participant.userId.toString()),
|
||||
);
|
||||
match.participants.forEach((participant) => {
|
||||
participant.excluded = !activeIds.has(participant.userId.toString());
|
||||
});
|
||||
return ordered.slice(0, desiredAuctionCount);
|
||||
}
|
||||
|
||||
private assertCaptainAssignments(
|
||||
captains: StartAuctionParams['captains'],
|
||||
activeParticipants: Array<{ userId: mongoose.Types.ObjectId }>,
|
||||
groupCount: 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}`);
|
||||
}
|
||||
|
||||
for (const captain of captains) {
|
||||
const userId = captain.userId.toString();
|
||||
if (!activeUserIds.has(userId)) {
|
||||
throw new BadRequestException(
|
||||
'All captains must be active participants of the match.',
|
||||
);
|
||||
}
|
||||
if (captainUserIds.has(userId)) {
|
||||
throw new BadRequestException('Captains must be different users.');
|
||||
}
|
||||
captainUserIds.add(userId);
|
||||
|
||||
if (captain.groupIndex < 1 || captain.groupIndex > groupCount) {
|
||||
throw new BadRequestException('Captain groupIndex is out of range.');
|
||||
}
|
||||
const key = `${captain.side}:${captain.groupIndex}`;
|
||||
if (teamKeys.has(key)) {
|
||||
throw new BadRequestException('Duplicate captain team assignment.');
|
||||
}
|
||||
teamKeys.add(key);
|
||||
}
|
||||
|
||||
for (const key of requiredKeys) {
|
||||
if (!teamKeys.has(key)) {
|
||||
throw new BadRequestException('Each group needs one blue and one red captain.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private findAuctionTeam(
|
||||
auction: AuctionDocument,
|
||||
side: TeamSide,
|
||||
groupIndex: number,
|
||||
): AuctionTeam | undefined {
|
||||
return auction.teams.find(
|
||||
(team) => team.side === side && (team.groupIndex ?? 1) === groupIndex,
|
||||
);
|
||||
}
|
||||
|
||||
private createDeadline(secondsFromNow: number): Date {
|
||||
return new Date(Date.now() + secondsFromNow * 1000);
|
||||
}
|
||||
@@ -399,7 +484,8 @@ export class AuctionService {
|
||||
|
||||
return {
|
||||
side: team.side,
|
||||
name: this.resolveTeamName(team.side),
|
||||
groupIndex: team.groupIndex ?? 1,
|
||||
name: this.resolveTeamName(team.side, team.groupIndex ?? 1, auction.teams),
|
||||
captainUserId: team.captainUserId,
|
||||
members,
|
||||
};
|
||||
@@ -411,8 +497,14 @@ export class AuctionService {
|
||||
await this.tournamentResultService.scheduleInitialPoll(match);
|
||||
}
|
||||
|
||||
private resolveTeamName(side: TeamSide): string {
|
||||
return side === 'blue' ? '블루팀' : '레드팀';
|
||||
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}`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,11 @@ class CaptainAssignmentDto {
|
||||
@IsEnum(TEAM_SIDES)
|
||||
side!: TeamSide;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
groupIndex?: number;
|
||||
|
||||
@IsMongoId()
|
||||
userId!: string;
|
||||
}
|
||||
@@ -24,7 +29,7 @@ class CaptainAssignmentDto {
|
||||
export class StartAuctionDto {
|
||||
@IsArray()
|
||||
@ArrayMinSize(2)
|
||||
@ArrayMaxSize(2)
|
||||
@ArrayMaxSize(16)
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => CaptainAssignmentDto)
|
||||
captains!: CaptainAssignmentDto[];
|
||||
@@ -44,6 +49,11 @@ export class PlaceBidDto {
|
||||
@IsEnum(TEAM_SIDES)
|
||||
side!: TeamSide;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
groupIndex?: number;
|
||||
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
amount!: number;
|
||||
|
||||
@@ -32,6 +32,13 @@ export const MATCH_STATUSES: MatchStatus[] = [
|
||||
export type TeamSide = 'blue' | 'red';
|
||||
export const TEAM_SIDES: TeamSide[] = ['blue', 'red'];
|
||||
|
||||
export type MatchGameMode = 'pair' | 'bracket' | 'round-robin';
|
||||
export const MATCH_GAME_MODES: MatchGameMode[] = [
|
||||
'pair',
|
||||
'bracket',
|
||||
'round-robin',
|
||||
];
|
||||
|
||||
export type CommunityRole = 'owner' | 'admin' | 'member';
|
||||
export const COMMUNITY_ROLES: CommunityRole[] = ['owner', 'admin', 'member'];
|
||||
|
||||
@@ -323,6 +330,7 @@ export interface MatchParticipant {
|
||||
tier?: TierInfo;
|
||||
preferredPositions: PositionPreference[];
|
||||
joinedAt: Date;
|
||||
excluded?: boolean;
|
||||
}
|
||||
|
||||
export interface MatchTeamMember {
|
||||
@@ -333,6 +341,7 @@ export interface MatchTeamMember {
|
||||
|
||||
export interface MatchTeam {
|
||||
side: TeamSide;
|
||||
groupIndex: number;
|
||||
name: string;
|
||||
captainUserId?: mongoose.Types.ObjectId;
|
||||
members: MatchTeamMember[];
|
||||
@@ -352,11 +361,21 @@ export interface MatchGameResult {
|
||||
gameNumber: number;
|
||||
riotMatchId: string;
|
||||
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;
|
||||
}
|
||||
|
||||
export interface MatchResult {
|
||||
winnerSide?: TeamSide;
|
||||
blueScore: number;
|
||||
@@ -364,6 +383,7 @@ export interface MatchResult {
|
||||
mvpUserId?: mongoose.Types.ObjectId;
|
||||
riotMatchIds: string[]; // 내전에서 플레이된 Riot matchId들
|
||||
games: MatchGameResult[];
|
||||
seriesResults?: MatchSeriesResult[];
|
||||
}
|
||||
|
||||
export interface MatchResultPollState {
|
||||
@@ -389,6 +409,7 @@ export interface Match extends MongooseTimestamps {
|
||||
scheduledAt: Date;
|
||||
maxParticipants: number;
|
||||
gameCount: number;
|
||||
gameMode: MatchGameMode;
|
||||
tournamentCodeIds: mongoose.Types.ObjectId[];
|
||||
teamBuiltAt?: Date;
|
||||
hostUserId?: mongoose.Types.ObjectId;
|
||||
@@ -469,6 +490,7 @@ export interface AuctionTeamMember {
|
||||
|
||||
export interface AuctionTeam {
|
||||
side: TeamSide;
|
||||
groupIndex: number;
|
||||
captainUserId: mongoose.Types.ObjectId;
|
||||
points: number;
|
||||
members: AuctionTeamMember[];
|
||||
@@ -476,6 +498,7 @@ export interface AuctionTeam {
|
||||
|
||||
export interface AuctionBid {
|
||||
side: TeamSide;
|
||||
groupIndex?: number;
|
||||
amount: number;
|
||||
bidderUserId: mongoose.Types.ObjectId;
|
||||
timestamp: Date;
|
||||
@@ -490,6 +513,7 @@ export interface Auction extends MongooseTimestamps {
|
||||
bids: AuctionBid[];
|
||||
currentBid: number;
|
||||
currentBidder?: TeamSide;
|
||||
currentBidderGroupIndex?: number;
|
||||
maxTimerSeconds: number;
|
||||
currentDeadline?: Date;
|
||||
initialPoints: number;
|
||||
@@ -880,6 +904,7 @@ const MatchParticipantSubSchema = new Schema<MatchParticipant>(
|
||||
default: [],
|
||||
},
|
||||
joinedAt: { type: Date, required: true, default: Date.now },
|
||||
excluded: { type: Boolean, required: true, default: false },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
@@ -896,6 +921,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 },
|
||||
name: { type: String, required: true },
|
||||
captainUserId: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
members: { type: [MatchTeamMemberSubSchema], required: true, default: [] },
|
||||
@@ -922,6 +948,8 @@ const MatchGameResultSubSchema = new Schema<MatchGameResult>(
|
||||
gameNumber: { type: Number, required: true },
|
||||
riotMatchId: { type: String, required: true },
|
||||
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: {
|
||||
@@ -933,6 +961,17 @@ const MatchGameResultSubSchema = new Schema<MatchGameResult>(
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
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 },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const MatchResultSubSchema = new Schema<MatchResult>(
|
||||
{
|
||||
winnerSide: { type: String, enum: TEAM_SIDES, required: false },
|
||||
@@ -941,6 +980,11 @@ const MatchResultSubSchema = new Schema<MatchResult>(
|
||||
mvpUserId: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
riotMatchIds: { type: [String], required: true, default: [] },
|
||||
games: { type: [MatchGameResultSubSchema], required: true, default: [] },
|
||||
seriesResults: {
|
||||
type: [MatchSeriesResultSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
@@ -1001,8 +1045,23 @@ export const MatchSchema = new Schema<Match>(
|
||||
default: 'recruiting',
|
||||
},
|
||||
scheduledAt: { type: Date, required: true },
|
||||
maxParticipants: { type: Number, required: true, default: 10 },
|
||||
maxParticipants: {
|
||||
type: Number,
|
||||
required: true,
|
||||
default: 10,
|
||||
min: 10,
|
||||
validate: {
|
||||
validator: (value: number) => Number.isInteger(value) && value % 10 === 0,
|
||||
message: 'maxParticipants must be a multiple of 10.',
|
||||
},
|
||||
},
|
||||
gameCount: { type: Number, required: true, default: 3 },
|
||||
gameMode: {
|
||||
type: String,
|
||||
enum: MATCH_GAME_MODES,
|
||||
required: true,
|
||||
default: 'pair',
|
||||
},
|
||||
tournamentCodeIds: {
|
||||
type: [{ type: Schema.Types.ObjectId, ref: 'tournamentCode' }],
|
||||
required: true,
|
||||
@@ -1156,6 +1215,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 },
|
||||
captainUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
points: { type: Number, required: true, default: 0 },
|
||||
members: {
|
||||
@@ -1170,6 +1230,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 },
|
||||
amount: { type: Number, required: true },
|
||||
bidderUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
timestamp: { type: Date, required: true, default: Date.now },
|
||||
@@ -1201,6 +1262,7 @@ export const AuctionSchema = new Schema<Auction>(
|
||||
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 },
|
||||
maxTimerSeconds: { type: Number, required: true, default: 30 },
|
||||
currentDeadline: { type: Date, required: false },
|
||||
initialPoints: { type: Number, required: true, default: 1000 },
|
||||
|
||||
@@ -2,7 +2,22 @@ import { Injectable, Logger } from '@nestjs/common';
|
||||
import { InfisicalSDK } from '@infisical/sdk';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
type SecretMap = Record<string, string | boolean | undefined>;
|
||||
type SecretMap = Record<string, string | undefined>;
|
||||
|
||||
const DEFAULT_INFISICAL_SITE_URL = 'https://secret-manager.dahyeon.us/';
|
||||
const IMDS_TOKEN_TTL_SECONDS = 60;
|
||||
const IMDS_REQUEST_TIMEOUT_MS = 1500;
|
||||
const FALLBACK_IMDS_BASE_URLS = [
|
||||
'http://169.254.169.254',
|
||||
'http://host.docker.internal:8675',
|
||||
];
|
||||
|
||||
interface InfisicalBootstrapConfig {
|
||||
siteUrl: string;
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
projectId: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SecretService {
|
||||
@@ -10,57 +25,8 @@ export class SecretService {
|
||||
|
||||
private secrets: SecretMap | null = null; // null = 아직 로드 전
|
||||
private loading?: Promise<void>; // 진행 중인 로드(중복 호출 방지)
|
||||
private infisicalClient: InfisicalSDK;
|
||||
|
||||
private readonly siteUrl: string;
|
||||
private readonly clientSecret: string;
|
||||
private readonly clientId: string;
|
||||
private readonly projectId: string;
|
||||
|
||||
private readonly PROCESS_ENVS = [
|
||||
'COSMOSDB_ENDPOINT',
|
||||
'COSMOSDB_KEY',
|
||||
'NATS_ENDPOINT',
|
||||
'NATS_TOKEN',
|
||||
'NATS_URL',
|
||||
'DAKAO_INBOUND_SUBJECT',
|
||||
'DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT',
|
||||
'DAKAO_REPLY_SUBJECT_PREFIX',
|
||||
'DAKAO_COMMAND_SOURCE',
|
||||
'DAKAO_BOT_USER_ID',
|
||||
'DAKAO_INSTANCE_ID',
|
||||
'JWT_CLAIM_AUDIENCE',
|
||||
'MICROSOFT_ENTRAID_TENANT_ID',
|
||||
'MICROSOFT_ENTRAID_ALLOWED_ALGS',
|
||||
'AUTH_DEV_HEADER_ENABLED',
|
||||
// 필요시 추가
|
||||
] as const;
|
||||
|
||||
constructor(private readonly config: ConfigService) {
|
||||
this.siteUrl =
|
||||
this.config.get<string>('INFISICAL_SITE_URL') ??
|
||||
'https://secret-manager.dahyeon.us/';
|
||||
this.clientSecret = this.config.get<string>(
|
||||
'INFISICAL_CLIENT_SECRET',
|
||||
) as string;
|
||||
this.clientId = this.config.get<string>('INFISICAL_CLIENT_ID') as string;
|
||||
this.projectId = this.config.get<string>('INFISICAL_PROJECT_ID') as string;
|
||||
// console.log(this.siteUrl, this.clientSecret, this.clientId, this.projectId)
|
||||
|
||||
const missing = [
|
||||
!this.siteUrl && 'INFISICAL_SITE_URL',
|
||||
!this.clientId && 'INFISICAL_CLIENT_ID',
|
||||
!this.clientSecret && 'INFISICAL_CLIENT_SECRET',
|
||||
!this.projectId && 'INFISICAL_PROJECT_ID',
|
||||
].filter(Boolean);
|
||||
if (missing.length > 0) {
|
||||
throw new Error(
|
||||
`Missing required Infisical configuration: ${missing.join(', ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
this.infisicalClient = new InfisicalSDK({ siteUrl: this.siteUrl });
|
||||
}
|
||||
constructor(private readonly config: ConfigService) {}
|
||||
|
||||
/** 한 번만 로그인/페치. 동시에 여러 번 호출돼도 같은 Promise를 공유 */
|
||||
private async fetchSecrets(): Promise<void> {
|
||||
@@ -68,20 +34,24 @@ export class SecretService {
|
||||
if (this.loading) return this.loading; // 로드 중이면 그거 기다리기
|
||||
|
||||
this.loading = (async () => {
|
||||
await this.infisicalClient.auth().universalAuth.login({
|
||||
clientId: this.clientId,
|
||||
clientSecret: this.clientSecret,
|
||||
const bootstrapConfig = await this.resolveInfisicalBootstrapConfig();
|
||||
const infisicalClient = new InfisicalSDK({
|
||||
siteUrl: bootstrapConfig.siteUrl,
|
||||
});
|
||||
// console.log(this.infisicalClient)
|
||||
|
||||
const res = await this.infisicalClient.secrets().listSecrets({
|
||||
await infisicalClient.auth().universalAuth.login({
|
||||
clientId: bootstrapConfig.clientId,
|
||||
clientSecret: bootstrapConfig.clientSecret,
|
||||
});
|
||||
|
||||
const res = await infisicalClient.secrets().listSecrets({
|
||||
environment:
|
||||
process.env.NODE_ENV === 'prod'
|
||||
? 'prod'
|
||||
: process.env.NODE_ENV === 'test'
|
||||
? 'staging'
|
||||
: 'dev',
|
||||
projectId: this.projectId,
|
||||
projectId: bootstrapConfig.projectId,
|
||||
});
|
||||
|
||||
// 임시 객체에 채운 뒤 한 번에 교체(일관성 보장)
|
||||
@@ -90,11 +60,10 @@ export class SecretService {
|
||||
map[s.secretKey] = s.secretValue;
|
||||
}
|
||||
|
||||
// 필요한 값은 process.env에 반영
|
||||
for (const k of this.PROCESS_ENVS) {
|
||||
const v = map[k as string];
|
||||
// 앱 생명주기에서 필요한 env는 모두 SecretService가 process.env에 반영한다.
|
||||
for (const [k, v] of Object.entries(map)) {
|
||||
if (typeof v === 'string' && v.length > 0) {
|
||||
process.env[k as string] = v;
|
||||
process.env[k] = v;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,6 +80,128 @@ export class SecretService {
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveInfisicalBootstrapConfig(): Promise<InfisicalBootstrapConfig> {
|
||||
const [clientId, clientSecret, projectId] = await Promise.all([
|
||||
this.resolveBootstrapValue('INFISICAL_CLIENT_ID'),
|
||||
this.resolveBootstrapValue('INFISICAL_CLIENT_SECRET'),
|
||||
this.resolveBootstrapValue('INFISICAL_PROJECT_ID'),
|
||||
]);
|
||||
const siteUrl =
|
||||
(await this.resolveBootstrapValue('INFISICAL_SITE_URL', false)) ??
|
||||
DEFAULT_INFISICAL_SITE_URL;
|
||||
|
||||
const missing = [
|
||||
!siteUrl && 'INFISICAL_SITE_URL',
|
||||
!clientId && 'INFISICAL_CLIENT_ID',
|
||||
!clientSecret && 'INFISICAL_CLIENT_SECRET',
|
||||
!projectId && 'INFISICAL_PROJECT_ID',
|
||||
].filter(Boolean);
|
||||
if (missing.length > 0) {
|
||||
throw new Error(
|
||||
`Missing required Infisical bootstrap configuration: ${missing.join(', ')}`,
|
||||
);
|
||||
}
|
||||
if (!clientId || !clientSecret || !projectId) {
|
||||
throw new Error('Missing required Infisical bootstrap configuration.');
|
||||
}
|
||||
|
||||
return {
|
||||
siteUrl,
|
||||
clientId,
|
||||
clientSecret,
|
||||
projectId,
|
||||
};
|
||||
}
|
||||
|
||||
private async resolveBootstrapValue(
|
||||
key: string,
|
||||
required = true,
|
||||
): Promise<string | undefined> {
|
||||
const configured = this.config.get<string>(key)?.trim();
|
||||
if (configured) return configured;
|
||||
|
||||
const fromImds = await this.getImdsSecret(key);
|
||||
if (fromImds) {
|
||||
process.env[key] = fromImds;
|
||||
return fromImds;
|
||||
}
|
||||
|
||||
if (required) {
|
||||
throw new Error(`Missing required bootstrap secret: ${key}`);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private async getImdsSecret(key: string): Promise<string | undefined> {
|
||||
let lastError: Error | undefined;
|
||||
for (const baseUrl of this.resolveImdsBaseUrls()) {
|
||||
try {
|
||||
const token = await this.issueImdsToken(baseUrl);
|
||||
const secret = await this.fetchImdsText(
|
||||
`${baseUrl.replace(/\/$/u, '')}/latest/meta-data/secrets/${encodeURIComponent(key)}`,
|
||||
{
|
||||
'X-aws-ec2-metadata-token': token,
|
||||
},
|
||||
);
|
||||
return secret.trim() || undefined;
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error : new Error(String(error));
|
||||
}
|
||||
}
|
||||
|
||||
if (lastError) {
|
||||
this.logger.debug(
|
||||
`IMDS secret lookup failed for ${key}: ${lastError.message}`,
|
||||
);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private resolveImdsBaseUrls(): string[] {
|
||||
return [
|
||||
this.config.get<string>('IMDS_BASE_URL'),
|
||||
this.config.get<string>('MACHINE_METADATA_BASE_URL'),
|
||||
...FALLBACK_IMDS_BASE_URLS,
|
||||
]
|
||||
.map((value) => value?.trim())
|
||||
.filter((value): value is string => Boolean(value));
|
||||
}
|
||||
|
||||
private async issueImdsToken(baseUrl: string): Promise<string> {
|
||||
return this.fetchImdsText(
|
||||
`${baseUrl.replace(/\/$/u, '')}/latest/api/token`,
|
||||
{
|
||||
'X-aws-ec2-metadata-token-ttl-seconds': String(IMDS_TOKEN_TTL_SECONDS),
|
||||
},
|
||||
'PUT',
|
||||
);
|
||||
}
|
||||
|
||||
private async fetchImdsText(
|
||||
url: string,
|
||||
headers: Record<string, string>,
|
||||
method = 'GET',
|
||||
): Promise<string> {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(
|
||||
() => controller.abort(),
|
||||
IMDS_REQUEST_TIMEOUT_MS,
|
||||
);
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method,
|
||||
headers,
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`IMDS ${method} ${url} failed with ${response.status}`);
|
||||
}
|
||||
return response.text();
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
/** lazy get: 필요할 때 처음 한번만 로드 */
|
||||
public async get<T = string>(key: string, fallback?: T): Promise<T> {
|
||||
if (!this.secrets) {
|
||||
|
||||
@@ -412,6 +412,15 @@ export class LegacyImportService {
|
||||
redScore: winnerSide === 'red' ? 1 : 0,
|
||||
riotMatchIds: [riotMatchId],
|
||||
games: [gameResult],
|
||||
seriesResults: [
|
||||
{
|
||||
blueGroupIndex: 1,
|
||||
redGroupIndex: 1,
|
||||
blueScore: winnerSide === 'blue' ? 1 : 0,
|
||||
redScore: winnerSide === 'red' ? 1 : 0,
|
||||
winnerSide,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
await MatchModel.updateOne(
|
||||
@@ -490,6 +499,7 @@ export class LegacyImportService {
|
||||
scheduledAt: new Date(detail.info.gameCreation),
|
||||
maxParticipants: 10,
|
||||
gameCount: 1,
|
||||
gameMode: 'pair',
|
||||
tournamentCodeIds: [],
|
||||
teamBuiltAt: new Date(detail.info.gameCreation),
|
||||
hostUserId: new mongoose.Types.ObjectId(job.triggeredBy),
|
||||
@@ -501,6 +511,15 @@ export class LegacyImportService {
|
||||
redScore: winnerSide === 'red' ? 1 : 0,
|
||||
riotMatchIds: [riotMatchId],
|
||||
games: [gameResult],
|
||||
seriesResults: [
|
||||
{
|
||||
blueGroupIndex: 1,
|
||||
redGroupIndex: 1,
|
||||
blueScore: winnerSide === 'blue' ? 1 : 0,
|
||||
redScore: winnerSide === 'red' ? 1 : 0,
|
||||
winnerSide,
|
||||
},
|
||||
],
|
||||
},
|
||||
legacyImported: true,
|
||||
legacyImportSource: {
|
||||
|
||||
@@ -108,6 +108,7 @@ export function buildTeams(
|
||||
.filter((member): member is NonNullable<typeof member> => Boolean(member));
|
||||
return {
|
||||
side,
|
||||
groupIndex: 1,
|
||||
name: side === 'blue' ? '블루팀' : '레드팀',
|
||||
members,
|
||||
};
|
||||
@@ -147,6 +148,8 @@ export function buildGameResult(
|
||||
gameNumber,
|
||||
riotMatchId: detail.metadata.matchId,
|
||||
winnerSide,
|
||||
blueGroupIndex: 1,
|
||||
redGroupIndex: 1,
|
||||
gameCreation: detail.info.gameCreation,
|
||||
gameDuration: detail.info.gameDuration,
|
||||
participants,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Type } from 'class-transformer';
|
||||
import {
|
||||
ArrayMaxSize,
|
||||
ArrayMinSize,
|
||||
registerDecorator,
|
||||
IsArray,
|
||||
IsDate,
|
||||
IsEnum,
|
||||
@@ -12,9 +13,40 @@ import {
|
||||
Min,
|
||||
MinLength,
|
||||
ValidateNested,
|
||||
ValidationArguments,
|
||||
ValidationOptions,
|
||||
} from 'class-validator';
|
||||
import { POSITIONS } from '../../global/database/schema';
|
||||
import type { Position } from '../../global/database/schema';
|
||||
import { MATCH_GAME_MODES, POSITIONS } from '../../global/database/schema';
|
||||
import type { MatchGameMode, Position } from '../../global/database/schema';
|
||||
|
||||
function IsMultipleOf(
|
||||
multiple: number,
|
||||
validationOptions?: ValidationOptions,
|
||||
): PropertyDecorator {
|
||||
return (object, propertyName) => {
|
||||
registerDecorator({
|
||||
name: 'isMultipleOf',
|
||||
target: object.constructor,
|
||||
propertyName: String(propertyName),
|
||||
constraints: [multiple],
|
||||
options: validationOptions,
|
||||
validator: {
|
||||
validate(value: unknown, args: ValidationArguments) {
|
||||
const [divisor] = args.constraints as [number];
|
||||
return (
|
||||
typeof value === 'number' &&
|
||||
Number.isInteger(value) &&
|
||||
value % divisor === 0
|
||||
);
|
||||
},
|
||||
defaultMessage(args: ValidationArguments) {
|
||||
const [divisor] = args.constraints as [number];
|
||||
return `${args.property} must be a multiple of ${divisor}.`;
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export class PositionPreferenceDto {
|
||||
@IsEnum(POSITIONS)
|
||||
@@ -56,7 +88,8 @@ export class CreateMatchDto {
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(2)
|
||||
@Min(10)
|
||||
@IsMultipleOf(10)
|
||||
maxParticipants?: number;
|
||||
|
||||
@IsOptional()
|
||||
@@ -64,6 +97,10 @@ export class CreateMatchDto {
|
||||
@Min(1)
|
||||
gameCount?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(MATCH_GAME_MODES)
|
||||
gameMode?: MatchGameMode;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@@ -106,7 +143,8 @@ export class UpdateMatchDto {
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(2)
|
||||
@Min(10)
|
||||
@IsMultipleOf(10)
|
||||
maxParticipants?: number;
|
||||
|
||||
@IsOptional()
|
||||
@@ -114,6 +152,10 @@ export class UpdateMatchDto {
|
||||
@Min(1)
|
||||
gameCount?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(MATCH_GAME_MODES)
|
||||
gameMode?: MatchGameMode;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
|
||||
@@ -54,6 +54,7 @@ export class MatchController {
|
||||
scheduledAt: body.scheduledAt,
|
||||
maxParticipants: body.maxParticipants ?? 10,
|
||||
gameCount: body.gameCount,
|
||||
gameMode: body.gameMode ?? 'pair',
|
||||
prizes: body.prizes ?? [],
|
||||
notices: body.notices ?? [],
|
||||
schedule: body.schedule ?? [],
|
||||
|
||||
@@ -98,10 +98,30 @@ export class MatchService {
|
||||
obj.result.games = [...obj.result.games].sort(
|
||||
(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,
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
return {
|
||||
...obj,
|
||||
gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
|
||||
gameMode: match.gameMode ?? 'pair',
|
||||
participants: (obj.participants ?? []).map((participant) => ({
|
||||
...participant,
|
||||
excluded: participant.excluded ?? false,
|
||||
})),
|
||||
teams: (obj.teams ?? []).map((team) => ({
|
||||
...team,
|
||||
groupIndex: team.groupIndex ?? 1,
|
||||
})),
|
||||
tournamentCodes: await this.tournamentCodeService.buildSlots(match),
|
||||
};
|
||||
}
|
||||
@@ -114,6 +134,14 @@ export class MatchService {
|
||||
throw new BadRequestException('Match does not belong to this community.');
|
||||
}
|
||||
const previousStatus = match.status;
|
||||
if (
|
||||
previousStatus !== 'recruiting' &&
|
||||
('maxParticipants' in params.patch || 'gameMode' in params.patch)
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'maxParticipants and gameMode can only be changed while recruiting.',
|
||||
);
|
||||
}
|
||||
match.set(params.patch);
|
||||
if (
|
||||
previousStatus !== 'recruiting' &&
|
||||
@@ -183,6 +211,7 @@ export class MatchService {
|
||||
tier: selectedTier,
|
||||
preferredPositions: params.preferredPositions,
|
||||
joinedAt: new Date(),
|
||||
excluded: false,
|
||||
});
|
||||
await match.save();
|
||||
return match;
|
||||
|
||||
@@ -220,7 +220,8 @@ export class TournamentCodeService {
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
|
||||
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||
const need = match.gameCount - match.tournamentCodeIds.length;
|
||||
const requiredSlots = this.resolveRequiredSlots(match);
|
||||
const need = requiredSlots - match.tournamentCodeIds.length;
|
||||
if (need <= 0) return match;
|
||||
|
||||
const reservedIds: mongoose.Types.ObjectId[] = [];
|
||||
@@ -311,7 +312,7 @@ export class TournamentCodeService {
|
||||
const matches = await MatchModel.find(filter).exec();
|
||||
let touched = 0;
|
||||
for (const match of matches) {
|
||||
if ((match.tournamentCodeIds?.length ?? 0) >= (match.gameCount || 0)) {
|
||||
if ((match.tournamentCodeIds?.length ?? 0) >= this.resolveRequiredSlots(match)) {
|
||||
continue;
|
||||
}
|
||||
const before = match.tournamentCodeIds?.length ?? 0;
|
||||
@@ -325,7 +326,7 @@ export class TournamentCodeService {
|
||||
public async buildSlots(match: MatchDocument): Promise<TournamentCodeSlotView[]> {
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||
const gameCount = this.resolveRequiredSlots(match);
|
||||
const ids = match.tournamentCodeIds ?? [];
|
||||
const codes =
|
||||
ids.length > 0
|
||||
@@ -341,8 +342,10 @@ export class TournamentCodeService {
|
||||
const gameNumber = index + 1;
|
||||
const code = byGameNumber.get(gameNumber);
|
||||
if (!code) {
|
||||
const seriesRef = this.resolveSeriesRefForGameNumber(match, gameNumber);
|
||||
return {
|
||||
gameNumber,
|
||||
...seriesRef,
|
||||
code: null,
|
||||
expiresAt: null,
|
||||
state: 'pending',
|
||||
@@ -351,6 +354,7 @@ export class TournamentCodeService {
|
||||
}
|
||||
return {
|
||||
gameNumber,
|
||||
...this.resolveSeriesRefForGameNumber(match, gameNumber),
|
||||
code: code.code,
|
||||
expiresAt: code.expiresAt.toISOString(),
|
||||
state: code.state,
|
||||
@@ -362,4 +366,26 @@ export class TournamentCodeService {
|
||||
private normalizeCode(code: string | undefined): string {
|
||||
return (code ?? '').trim().toUpperCase();
|
||||
}
|
||||
|
||||
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 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;
|
||||
}
|
||||
|
||||
private resolveSeriesRefForGameNumber(
|
||||
match: MatchDocument,
|
||||
gameNumber: number,
|
||||
): { blueGroupIndex: number; redGroupIndex: number } {
|
||||
const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||
const groupIndex = Math.max(1, Math.ceil(gameNumber / perSeries));
|
||||
return { blueGroupIndex: groupIndex, redGroupIndex: groupIndex };
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,8 @@ export interface BulkUploadTournamentCodesResponse {
|
||||
|
||||
export interface TournamentCodeSlotView {
|
||||
gameNumber: number;
|
||||
blueGroupIndex: number;
|
||||
redGroupIndex: number;
|
||||
code: string | null;
|
||||
expiresAt: string | null;
|
||||
state: TournamentCodeState | 'pending';
|
||||
|
||||
@@ -39,11 +39,18 @@ export function collectTeamPuuids(
|
||||
match: MatchDocument,
|
||||
side: TeamSide,
|
||||
lookup: MatchPuuidLookup,
|
||||
groupIndex = 1,
|
||||
): string[] {
|
||||
const team = match.teams.find((item) => item.side === side);
|
||||
const team = match.teams.find(
|
||||
(item) => item.side === side && (item.groupIndex ?? 1) === groupIndex,
|
||||
);
|
||||
if (!team) return [];
|
||||
return team.members
|
||||
.map((member) => lookup.puuidByUserId.get(member.userId.toString()))
|
||||
const userIds = [
|
||||
...(team.captainUserId ? [team.captainUserId] : []),
|
||||
...team.members.map((member) => member.userId),
|
||||
];
|
||||
return userIds
|
||||
.map((userId) => lookup.puuidByUserId.get(userId.toString()))
|
||||
.filter((puuid): puuid is string => Boolean(puuid));
|
||||
}
|
||||
|
||||
@@ -52,10 +59,19 @@ export function computeGameResult(params: {
|
||||
detail: RiotMatchDto;
|
||||
gameNumber: number;
|
||||
lookup: MatchPuuidLookup;
|
||||
blueGroupIndex?: number;
|
||||
redGroupIndex?: number;
|
||||
}): MatchGameResult | null {
|
||||
const { match, detail, gameNumber, lookup } = params;
|
||||
const ourBluePuuids = collectTeamPuuids(match, 'blue', lookup);
|
||||
const ourRedPuuids = collectTeamPuuids(match, 'red', lookup);
|
||||
const {
|
||||
match,
|
||||
detail,
|
||||
gameNumber,
|
||||
lookup,
|
||||
blueGroupIndex = 1,
|
||||
redGroupIndex = 1,
|
||||
} = params;
|
||||
const ourBluePuuids = collectTeamPuuids(match, 'blue', lookup, blueGroupIndex);
|
||||
const ourRedPuuids = collectTeamPuuids(match, 'red', lookup, redGroupIndex);
|
||||
const team100Puuids = detail.info.participants
|
||||
.filter((participant) => participant.teamId === RIOT_BLUE_TEAM_ID)
|
||||
.map((participant) => participant.puuid);
|
||||
@@ -106,6 +122,8 @@ export function computeGameResult(params: {
|
||||
gameNumber,
|
||||
riotMatchId: detail.metadata.matchId,
|
||||
winnerSide,
|
||||
blueGroupIndex,
|
||||
redGroupIndex,
|
||||
gameCreation: detail.info.gameCreation,
|
||||
gameDuration: detail.info.gameDuration,
|
||||
participants,
|
||||
|
||||
@@ -210,6 +210,7 @@ export class TournamentResultService {
|
||||
detail,
|
||||
gameNumber: code.gameNumber,
|
||||
lookup,
|
||||
...this.resolveSeriesRefForGameNumber(match, code.gameNumber),
|
||||
});
|
||||
if (!gameResult) {
|
||||
this.logger.warn(
|
||||
@@ -235,7 +236,7 @@ export class TournamentResultService {
|
||||
match: MatchDocument,
|
||||
codes: TournamentCodeDocument[],
|
||||
): Promise<boolean> {
|
||||
if (codes.length < match.gameCount) return false;
|
||||
if (codes.length < this.resolveRequiredGameSlots(match)) return false;
|
||||
if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) {
|
||||
return false;
|
||||
}
|
||||
@@ -399,9 +400,71 @@ export class TournamentResultService {
|
||||
mvpUserId: match.result?.mvpUserId,
|
||||
riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))],
|
||||
games,
|
||||
seriesResults: this.buildSeriesResults(games),
|
||||
};
|
||||
}
|
||||
|
||||
private buildSeriesResults(
|
||||
games: MatchGameResult[],
|
||||
): NonNullable<MatchDocument['result']>['seriesResults'] {
|
||||
const bySeries = new Map<
|
||||
string,
|
||||
{
|
||||
blueGroupIndex: number;
|
||||
redGroupIndex: number;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
winnerSide?: 'blue' | 'red';
|
||||
}
|
||||
>();
|
||||
|
||||
for (const game of games) {
|
||||
const blueGroupIndex = game.blueGroupIndex ?? 1;
|
||||
const redGroupIndex = game.redGroupIndex ?? 1;
|
||||
const key = `${blueGroupIndex}:${redGroupIndex}`;
|
||||
const current =
|
||||
bySeries.get(key) ??
|
||||
{
|
||||
blueGroupIndex,
|
||||
redGroupIndex,
|
||||
blueScore: 0,
|
||||
redScore: 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'
|
||||
: undefined;
|
||||
bySeries.set(key, current);
|
||||
}
|
||||
|
||||
return [...bySeries.values()].sort(
|
||||
(left, right) =>
|
||||
left.blueGroupIndex - right.blueGroupIndex ||
|
||||
left.redGroupIndex - right.redGroupIndex,
|
||||
);
|
||||
}
|
||||
|
||||
private resolveSeriesRefForGameNumber(
|
||||
match: MatchDocument,
|
||||
gameNumber: number,
|
||||
): { blueGroupIndex: number; redGroupIndex: number } {
|
||||
const perSeries = match.gameCount || 1;
|
||||
const groupIndex = Math.max(1, Math.ceil(gameNumber / perSeries));
|
||||
return { blueGroupIndex: groupIndex, redGroupIndex: groupIndex };
|
||||
}
|
||||
|
||||
private resolveRequiredGameSlots(match: MatchDocument): number {
|
||||
const groups = Math.max(
|
||||
1,
|
||||
new Set(match.teams.map((team) => team.groupIndex ?? 1)).size,
|
||||
);
|
||||
return groups * (match.gameCount || 1);
|
||||
}
|
||||
|
||||
private async updatePollState(
|
||||
match: MatchDocument,
|
||||
outcome: 'matched' | 'not-found' | 'failed',
|
||||
|
||||
@@ -74,7 +74,7 @@ async function loadMachineEnvFile() {
|
||||
process.env[key] = rawValue.replace(/^["']|["']$/g, '');
|
||||
}
|
||||
} catch {
|
||||
// start.ps1과 동일하게 로컬 machine env 파일이 없으면 무시한다.
|
||||
// 로컬 machine env 파일이 없으면 무시한다.
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ async function loadMachineEnvFile() {
|
||||
process.env[key] = value;
|
||||
}
|
||||
} catch {
|
||||
// start.ps1도 파일이 없으면 그냥 지나간다.
|
||||
// 로컬 machine env 파일이 없으면 그냥 지나간다.
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
param(
|
||||
[switch]$UsePm2,
|
||||
[string]$Pm2Name = "lolympus-tournament-support"
|
||||
)
|
||||
|
||||
if (-not $env:NODE_ENV) {
|
||||
$env:NODE_ENV = "dev"
|
||||
}
|
||||
|
||||
$MainScript = Join-Path $PSScriptRoot "dist/main.js"
|
||||
|
||||
if ($isMacOS -or $isLinux) {
|
||||
$env:MachineEnvFile = "$env:HOME/source/global-env-vars.txt"
|
||||
} elseif ($isWindows) {
|
||||
$env:MachineEnvFile = "$env:USERPROFILE/source/global-env-vars.txt"
|
||||
}
|
||||
|
||||
function Set-EnvFromFile {
|
||||
param([string]$Path)
|
||||
|
||||
if (-not (Test-Path $Path)) {
|
||||
throw "File not found: $Path"
|
||||
}
|
||||
|
||||
foreach ($line in Get-Content $Path) {
|
||||
if ([string]::IsNullOrWhiteSpace($line)) { continue }
|
||||
if ($line -match '^\s*#') { continue }
|
||||
|
||||
if ($line -match '^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$') {
|
||||
$key = $matches[1]
|
||||
$value = $matches[2].Trim()
|
||||
|
||||
if (
|
||||
($value.StartsWith('"') -and $value.EndsWith('"')) -or
|
||||
($value.StartsWith("'") -and $value.EndsWith("'"))
|
||||
) {
|
||||
$value = $value.Substring(1, $value.Length - 2)
|
||||
}
|
||||
|
||||
[System.Environment]::SetEnvironmentVariable($key, $value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Test-Path $env:MachineEnvFile) {
|
||||
Set-EnvFromFile $env:MachineEnvFile
|
||||
}
|
||||
|
||||
if (-not $env:INFISICAL_CLIENT_ID) {
|
||||
Write-Error "INFISICAL_CLIENT_ID is not set."
|
||||
exit 1
|
||||
}
|
||||
|
||||
if (-not $env:INFISICAL_CLIENT_SECRET) {
|
||||
Write-Error "INFISICAL_CLIENT_SECRET is not set."
|
||||
exit 1
|
||||
}
|
||||
|
||||
if (-not $env:INFISICAL_PROJECT_ID) {
|
||||
Write-Error "INFISICAL_PROJECT_ID is not set."
|
||||
exit 1
|
||||
}
|
||||
|
||||
if ($UsePm2) {
|
||||
pm2 start $MainScript --name $Pm2Name --update-env
|
||||
} else {
|
||||
node $MainScript
|
||||
}
|
||||
@@ -8,12 +8,14 @@ import AuthCallbackPage from './pages/AuthCallback';
|
||||
import HomePage from './pages/HomePage';
|
||||
import LoginPage from './pages/Login';
|
||||
import MatchDetailPage from './pages/MatchDetailPage';
|
||||
import MatchTeamProgressPage from './pages/MatchTeamProgressPage';
|
||||
import AuctionPage from './pages/AuctionPage';
|
||||
import UserHistoryPage from './pages/UserHistoryPage';
|
||||
import CommunityInternalStatsPage from './pages/CommunityInternalStatsPage';
|
||||
import InternalMatchDetailPage from './pages/InternalMatchDetailPage';
|
||||
import LegacyImportPage from './pages/admin/LegacyImportPage';
|
||||
import LegacyMatchesPage from './pages/admin/LegacyMatchesPage';
|
||||
import MatchAdminPage from './pages/admin/MatchAdminPage';
|
||||
import TournamentCodesPage from './pages/admin/TournamentCodesPage';
|
||||
|
||||
function MsalHeaderActions() {
|
||||
@@ -74,6 +76,10 @@ function App() {
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/auth/callback" element={<AuthCallbackPage />} />
|
||||
<Route path="/match/:id" element={<MatchDetailPage />} />
|
||||
<Route
|
||||
path="/match/:id/team/:side/:groupIndex"
|
||||
element={<MatchTeamProgressPage />}
|
||||
/>
|
||||
<Route path="/match/:id/auction" element={<AuctionPage />} />
|
||||
<Route path="/users/:userId/history" element={<UserHistoryPage />} />
|
||||
<Route
|
||||
@@ -84,6 +90,10 @@ function App() {
|
||||
path="/communities/:cid/internal-stats/match/:matchId"
|
||||
element={<InternalMatchDetailPage />}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/communities/:cid/matches"
|
||||
element={<MatchAdminPage />}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/communities/:cid/tournament-codes"
|
||||
element={<TournamentCodesPage />}
|
||||
|
||||
@@ -30,6 +30,7 @@ import type {
|
||||
StartLegacyImportRequest,
|
||||
StartLegacyImportResponse,
|
||||
MatchStatus,
|
||||
MatchMutationRequest,
|
||||
MatchesResponse,
|
||||
MeResponse,
|
||||
RiotQueueGroup,
|
||||
@@ -130,6 +131,26 @@ export function useAuction(
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateMatch(communityId = DEFAULT_COMMUNITY_ID) {
|
||||
return useMutation({
|
||||
mutationFn: (body: MatchMutationRequest) =>
|
||||
apiFetch<ApiMatch>(`/communities/${communityId}/matches`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateMatch(communityId = DEFAULT_COMMUNITY_ID) {
|
||||
return useMutation({
|
||||
mutationFn: ({ matchId, body }: { matchId: string; body: Partial<MatchMutationRequest> }) =>
|
||||
apiFetch<ApiMatch>(`/communities/${communityId}/matches/${matchId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
function createUserHistoryPath(
|
||||
communityId: string,
|
||||
userId: string,
|
||||
|
||||
+31
-24
@@ -25,6 +25,7 @@ export interface ParticipantView {
|
||||
mainPosition: Position;
|
||||
subPosition: Position;
|
||||
profileIconId: number;
|
||||
excluded?: boolean;
|
||||
}
|
||||
|
||||
export interface TeamParticipantView extends ParticipantView {
|
||||
@@ -34,6 +35,7 @@ export interface TeamParticipantView extends ParticipantView {
|
||||
|
||||
export interface TeamView {
|
||||
side: TeamSide;
|
||||
groupIndex: number;
|
||||
name: string;
|
||||
participants: TeamParticipantView[];
|
||||
}
|
||||
@@ -48,6 +50,7 @@ export interface MatchDetailView {
|
||||
map: string;
|
||||
maxParticipants: number;
|
||||
gameCount: number;
|
||||
gameMode: ApiMatch["gameMode"];
|
||||
tournamentCodes: TournamentCodeSlotView[];
|
||||
joined: boolean;
|
||||
participants: ParticipantView[];
|
||||
@@ -62,6 +65,8 @@ export interface MatchDetailView {
|
||||
gameNumber: number;
|
||||
riotMatchId: string;
|
||||
winnerSide: TeamSide;
|
||||
blueGroupIndex: number;
|
||||
redGroupIndex: number;
|
||||
gameCreation: number;
|
||||
gameDuration: number;
|
||||
participants: Array<{
|
||||
@@ -74,6 +79,7 @@ export interface MatchDetailView {
|
||||
win: boolean;
|
||||
}>;
|
||||
}>;
|
||||
seriesResults: NonNullable<ApiMatch["result"]>["seriesResults"];
|
||||
};
|
||||
prizes: string[];
|
||||
notices: string[];
|
||||
@@ -96,6 +102,7 @@ export interface AuctionPlayerView extends ParticipantView {
|
||||
|
||||
export interface AuctionTeamView {
|
||||
side: TeamSide;
|
||||
groupIndex: number;
|
||||
captainUserId: string;
|
||||
captainName: string;
|
||||
points: number;
|
||||
@@ -108,18 +115,19 @@ export interface AuctionTeamView {
|
||||
export interface AuctionStateView {
|
||||
matchId: string;
|
||||
phase: ApiAuction["phase"];
|
||||
teams: [AuctionTeamView, AuctionTeamView];
|
||||
teams: AuctionTeamView[];
|
||||
currentPlayer: AuctionPlayerView | null;
|
||||
currentPlayerIndex: number;
|
||||
totalPlayers: number;
|
||||
auctionOrder: AuctionPlayerView[];
|
||||
bids: {
|
||||
side: TeamSide;
|
||||
groupIndex: number;
|
||||
amount: number;
|
||||
timestamp: string;
|
||||
}[];
|
||||
currentBid: number;
|
||||
currentBidder: TeamSide | null;
|
||||
currentBidder: { side: TeamSide; groupIndex: number } | null;
|
||||
timer: number;
|
||||
maxTimer: number;
|
||||
deadline?: string;
|
||||
@@ -208,6 +216,7 @@ function mapMatchParticipantToView(
|
||||
mainPosition,
|
||||
subPosition,
|
||||
profileIconId: participant.profileIconId ?? 0,
|
||||
excluded: participant.excluded ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -262,6 +271,7 @@ function mapAuctionTeamToView(
|
||||
): AuctionTeamView {
|
||||
return {
|
||||
side: team.side,
|
||||
groupIndex: team.groupIndex ?? 1,
|
||||
captainUserId: team.captainUserId,
|
||||
captainName:
|
||||
participantLookup.get(team.captainUserId)?.summonerName ??
|
||||
@@ -396,6 +406,7 @@ 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),
|
||||
participants: team.members.map((member) => {
|
||||
const participant =
|
||||
@@ -423,7 +434,8 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
|
||||
description: match.description,
|
||||
map: mapIdToLabel(match.mapId),
|
||||
maxParticipants: match.maxParticipants,
|
||||
gameCount: match.gameCount ?? 3,
|
||||
gameCount: match.gameCount ?? 3,
|
||||
gameMode: match.gameMode ?? "pair",
|
||||
tournamentCodes: match.tournamentCodes ?? [],
|
||||
joined: Boolean(match.joined),
|
||||
participants,
|
||||
@@ -440,6 +452,7 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
|
||||
games: [...(match.result.games ?? [])].sort(
|
||||
(left, right) => left.gameNumber - right.gameNumber,
|
||||
),
|
||||
seriesResults: match.result.seriesResults ?? [],
|
||||
}
|
||||
: undefined,
|
||||
prizes: match.prizes,
|
||||
@@ -462,22 +475,11 @@ export function mapApiAuctionToAuctionState(
|
||||
const auctionPlayerLookup = new Map(
|
||||
auctionOrder.map((player) => [player.userId, player]),
|
||||
);
|
||||
const blueTeam =
|
||||
auction.teams.find((team) => team.side === "blue") ??
|
||||
({
|
||||
side: "blue",
|
||||
captainUserId: "",
|
||||
points: 0,
|
||||
members: [],
|
||||
} satisfies ApiAuctionTeam);
|
||||
const redTeam =
|
||||
auction.teams.find((team) => team.side === "red") ??
|
||||
({
|
||||
side: "red",
|
||||
captainUserId: "",
|
||||
points: 0,
|
||||
members: [],
|
||||
} satisfies ApiAuctionTeam);
|
||||
const teams = [...auction.teams].sort(
|
||||
(left, right) =>
|
||||
(left.groupIndex ?? 1) - (right.groupIndex ?? 1) ||
|
||||
(left.side === "blue" ? -1 : 1),
|
||||
);
|
||||
|
||||
const totalPlayers = auctionOrder.length;
|
||||
const currentPlayer =
|
||||
@@ -500,21 +502,26 @@ export function mapApiAuctionToAuctionState(
|
||||
return {
|
||||
matchId: auction.matchId,
|
||||
phase: auction.phase,
|
||||
teams: [
|
||||
mapAuctionTeamToView(blueTeam, auctionPlayerLookup, participantLookup),
|
||||
mapAuctionTeamToView(redTeam, auctionPlayerLookup, participantLookup),
|
||||
],
|
||||
teams: teams.map((team) =>
|
||||
mapAuctionTeamToView(team, auctionPlayerLookup, participantLookup),
|
||||
),
|
||||
currentPlayer,
|
||||
currentPlayerIndex,
|
||||
totalPlayers,
|
||||
auctionOrder,
|
||||
bids: auction.bids.map((bid) => ({
|
||||
side: bid.side,
|
||||
groupIndex: bid.groupIndex ?? 1,
|
||||
amount: bid.amount,
|
||||
timestamp: bid.timestamp,
|
||||
})),
|
||||
currentBid: auction.currentBid,
|
||||
currentBidder: auction.currentBidder ?? null,
|
||||
currentBidder: auction.currentBidder
|
||||
? {
|
||||
side: auction.currentBidder,
|
||||
groupIndex: auction.currentBidderGroupIndex ?? 1,
|
||||
}
|
||||
: null,
|
||||
timer,
|
||||
maxTimer: auction.maxTimerSeconds,
|
||||
deadline: auction.currentDeadline,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
|
||||
export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';
|
||||
export type TeamSide = 'blue' | 'red';
|
||||
export type MatchGameMode = 'pair' | 'bracket' | 'round-robin';
|
||||
export type MatchStatus =
|
||||
| 'recruiting'
|
||||
| 'team-built'
|
||||
@@ -116,6 +117,8 @@ export type TournamentCodeSlotState = TournamentCodeState | 'pending';
|
||||
|
||||
export interface TournamentCodeSlotView {
|
||||
gameNumber: number;
|
||||
blueGroupIndex: number;
|
||||
redGroupIndex: number;
|
||||
code: string | null;
|
||||
expiresAt: string | null;
|
||||
state: TournamentCodeSlotState;
|
||||
@@ -131,6 +134,7 @@ export interface ApiMatchParticipant {
|
||||
tier?: ApiTierInfo;
|
||||
preferredPositions: ApiPositionPreference[];
|
||||
joinedAt: string;
|
||||
excluded?: boolean;
|
||||
}
|
||||
|
||||
export interface ApiMatchTeamMember {
|
||||
@@ -141,6 +145,7 @@ export interface ApiMatchTeamMember {
|
||||
|
||||
export interface ApiMatchTeam {
|
||||
side: TeamSide;
|
||||
groupIndex: number;
|
||||
name: string;
|
||||
captainUserId?: string;
|
||||
members: ApiMatchTeamMember[];
|
||||
@@ -160,6 +165,8 @@ export interface ApiMatchGameResult {
|
||||
gameNumber: number;
|
||||
riotMatchId: string;
|
||||
winnerSide: TeamSide;
|
||||
blueGroupIndex: number;
|
||||
redGroupIndex: number;
|
||||
gameCreation: number;
|
||||
gameDuration: number;
|
||||
participants: ApiMatchGameResultParticipant[];
|
||||
@@ -172,6 +179,13 @@ export interface ApiMatchResult {
|
||||
mvpUserId?: string;
|
||||
riotMatchIds: string[];
|
||||
games: ApiMatchGameResult[];
|
||||
seriesResults?: Array<{
|
||||
blueGroupIndex: number;
|
||||
redGroupIndex: number;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
winnerSide?: TeamSide;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface ApiMatchScheduleItem {
|
||||
@@ -189,6 +203,7 @@ export interface ApiMatch {
|
||||
scheduledAt: string;
|
||||
maxParticipants: number;
|
||||
gameCount: number;
|
||||
gameMode: MatchGameMode;
|
||||
tournamentCodes?: TournamentCodeSlotView[];
|
||||
hostUserId?: string;
|
||||
participants: ApiMatchParticipant[];
|
||||
@@ -222,6 +237,7 @@ export interface ApiAuctionTeamMember {
|
||||
|
||||
export interface ApiAuctionTeam {
|
||||
side: TeamSide;
|
||||
groupIndex: number;
|
||||
captainUserId: string;
|
||||
points: number;
|
||||
members: ApiAuctionTeamMember[];
|
||||
@@ -229,6 +245,7 @@ export interface ApiAuctionTeam {
|
||||
|
||||
export interface ApiAuctionBid {
|
||||
side: TeamSide;
|
||||
groupIndex?: number;
|
||||
amount: number;
|
||||
bidderUserId: string;
|
||||
timestamp: string;
|
||||
@@ -244,6 +261,7 @@ export interface ApiAuction {
|
||||
bids: ApiAuctionBid[];
|
||||
currentBid: number;
|
||||
currentBidder?: TeamSide;
|
||||
currentBidderGroupIndex?: number;
|
||||
maxTimerSeconds: number;
|
||||
currentDeadline?: string;
|
||||
initialPoints: number;
|
||||
@@ -275,6 +293,19 @@ export interface MatchesResponse {
|
||||
matches: ApiMatch[];
|
||||
}
|
||||
|
||||
export interface MatchMutationRequest {
|
||||
title: string;
|
||||
description?: string;
|
||||
mapId?: number;
|
||||
scheduledAt: string;
|
||||
maxParticipants?: number;
|
||||
gameCount?: number;
|
||||
gameMode?: MatchGameMode;
|
||||
prizes?: string[];
|
||||
notices?: string[];
|
||||
schedule?: ApiMatchScheduleItem[];
|
||||
}
|
||||
|
||||
export interface DdragonChampionEntry {
|
||||
key: string;
|
||||
name: string;
|
||||
|
||||
@@ -13,6 +13,7 @@ type ConnectionStatus =
|
||||
|
||||
interface BidPayload {
|
||||
side: TeamSide;
|
||||
groupIndex?: number;
|
||||
amount: number;
|
||||
bidderUserId?: string;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Link, useParams } from 'react-router';
|
||||
import { useAuction, useDdragonManifest, useMatch, useMe } from '../api/hooks';
|
||||
import {
|
||||
@@ -20,12 +20,32 @@ import {
|
||||
profileIconUrl,
|
||||
} from '../lib/ddragon';
|
||||
import { positionIcon, positionLabel } from '../lib/league';
|
||||
import type { ApiRiotLaneStats, Position } from '../api/types';
|
||||
import type { ApiRiotLaneStats, Position, TeamSide } from '../api/types';
|
||||
|
||||
type CaptainRole = {
|
||||
side: TeamSide;
|
||||
groupIndex: 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'>,
|
||||
) {
|
||||
return (
|
||||
currentBidder?.side === team.side &&
|
||||
currentBidder.groupIndex === team.groupIndex
|
||||
);
|
||||
}
|
||||
|
||||
const AUCTION_MAX_TEAM_SIZE = 5;
|
||||
const LANE_ROWS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
|
||||
const POSITION_TO_RIOT_LANE = {
|
||||
@@ -209,7 +229,7 @@ function TeamPanel({
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`text-[11px] font-bold uppercase tracking-wide ${sideColor}`}>
|
||||
{team.side === 'blue' ? '블루팀' : '레드팀'}
|
||||
{teamLabel(team.side, team.groupIndex)}
|
||||
</span>
|
||||
<span className="text-[10px] text-base-content/30">
|
||||
팀장: {team.captainName}
|
||||
@@ -265,7 +285,7 @@ function TeamPanel({
|
||||
length: Math.max(0, AUCTION_MAX_TEAM_SIZE - 1 - team.members.length),
|
||||
}).map((_, index) => (
|
||||
<div
|
||||
key={`empty-${team.side}-${index}`}
|
||||
key={`empty-${team.side}-${team.groupIndex}-${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" />
|
||||
@@ -385,9 +405,12 @@ function PlayerSpotlight({
|
||||
<div className="flex items-center gap-2">
|
||||
{state.currentBidder && (
|
||||
<span
|
||||
className={`text-[10px] font-bold uppercase ${state.currentBidder === 'blue' ? 'text-blue-400' : 'text-red-400'}`}
|
||||
className={`text-[10px] font-bold uppercase ${state.currentBidder.side === 'blue' ? 'text-blue-400' : 'text-red-400'}`}
|
||||
>
|
||||
{state.currentBidder === 'blue' ? '블루' : '레드'}
|
||||
{teamLabel(
|
||||
state.currentBidder.side,
|
||||
state.currentBidder.groupIndex,
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<span className="text-lg font-black text-amber-400 tabular-nums">
|
||||
@@ -403,21 +426,22 @@ function PlayerSpotlight({
|
||||
|
||||
function BidControls({
|
||||
state,
|
||||
captainSide,
|
||||
captainRole,
|
||||
onBid,
|
||||
}: {
|
||||
state: AuctionStateView;
|
||||
captainSide: 'spectator' | 'blue' | 'red';
|
||||
onBid: (side: 'blue' | 'red', amount: number) => void;
|
||||
captainRole: CaptainRole | null;
|
||||
onBid: (side: TeamSide, groupIndex: number, amount: number) => void;
|
||||
}) {
|
||||
const [bidAmount, setBidAmount] = useState(100);
|
||||
const minBid = state.currentBid + 10;
|
||||
const activeTeam =
|
||||
captainSide === 'blue'
|
||||
? state.teams[0]
|
||||
: captainSide === 'red'
|
||||
? state.teams[1]
|
||||
: null;
|
||||
const activeTeam = captainRole
|
||||
? state.teams.find(
|
||||
(team) =>
|
||||
team.side === captainRole.side &&
|
||||
team.groupIndex === captainRole.groupIndex,
|
||||
)
|
||||
: null;
|
||||
const activeTeamSize = activeTeam ? activeTeam.members.length + 1 : 0;
|
||||
const isActiveTeamFull = activeTeamSize >= AUCTION_MAX_TEAM_SIZE;
|
||||
|
||||
@@ -466,7 +490,7 @@ function BidControls({
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => onBid(activeTeam.side, bidAmount)}
|
||||
onClick={() => onBid(activeTeam.side, activeTeam.groupIndex, bidAmount)}
|
||||
disabled={
|
||||
isActiveTeamFull ||
|
||||
bidAmount > activeTeam.points ||
|
||||
@@ -479,8 +503,8 @@ function BidControls({
|
||||
}`}
|
||||
>
|
||||
{isActiveTeamFull
|
||||
? `${activeTeam.side === 'blue' ? '블루팀' : '레드팀'} 정원 완료 (${activeTeamSize}/${AUCTION_MAX_TEAM_SIZE})`
|
||||
: `${activeTeam.side === 'blue' ? '블루팀' : '레드팀'} 입찰 (${formatPoints(bidAmount)}P)`}
|
||||
? `${teamLabel(activeTeam.side, activeTeam.groupIndex)} 정원 완료 (${activeTeamSize}/${AUCTION_MAX_TEAM_SIZE})`
|
||||
: `${teamLabel(activeTeam.side, activeTeam.groupIndex)} 입찰 (${formatPoints(bidAmount)}P)`}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
@@ -508,7 +532,7 @@ function BidLog({ bids }: { bids: AuctionStateView['bids'] }) {
|
||||
<span
|
||||
className={`font-bold uppercase ${bid.side === 'blue' ? 'text-blue-400' : 'text-red-400'}`}
|
||||
>
|
||||
{bid.side === 'blue' ? '블루' : '레드'}
|
||||
{teamLabel(bid.side, bid.groupIndex)}
|
||||
</span>
|
||||
<span className="text-base-content/30">→</span>
|
||||
<span className="text-amber-400 tabular-nums font-semibold">
|
||||
@@ -533,6 +557,7 @@ export default function AuctionPage() {
|
||||
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID);
|
||||
const socket = useAuctionSocket(id);
|
||||
const captainSide = useDevCaptainSide();
|
||||
const [captainGroupIndex, setCaptainGroupIndex] = useState(1);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
const [assignedPosition, setAssignedPosition] = useState<Position>('MID');
|
||||
|
||||
@@ -546,6 +571,17 @@ 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);
|
||||
}, [auctionState?.teams]);
|
||||
const captainRole: CaptainRole | null =
|
||||
captainSide === 'spectator'
|
||||
? null
|
||||
: {
|
||||
side: captainSide,
|
||||
groupIndex: captainGroupIndex,
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (auctionState?.currentPlayer) {
|
||||
@@ -553,6 +589,13 @@ export default function AuctionPage() {
|
||||
}
|
||||
}, [auctionState?.currentPlayer?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (availableGroups.length === 0) return;
|
||||
if (!availableGroups.includes(captainGroupIndex)) {
|
||||
setCaptainGroupIndex(availableGroups[0]);
|
||||
}
|
||||
}, [availableGroups, captainGroupIndex]);
|
||||
|
||||
if (!DEFAULT_COMMUNITY_ID) {
|
||||
return (
|
||||
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
|
||||
@@ -681,6 +724,21 @@ export default function AuctionPage() {
|
||||
<option value="blue">블루팀장</option>
|
||||
<option value="red">레드팀장</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>
|
||||
@@ -689,13 +747,16 @@ export default function AuctionPage() {
|
||||
<TimerBar timer={auctionState.timer} maxTimer={auctionState.maxTimer} />
|
||||
)}
|
||||
|
||||
<div className="flex flex-col lg:flex-row gap-4 mt-4">
|
||||
<div className="w-full lg:w-56 shrink-0">
|
||||
<TeamPanel
|
||||
team={auctionState.teams[0]}
|
||||
isActive={auctionState.currentBidder === 'blue'}
|
||||
isLeft
|
||||
/>
|
||||
<div className="grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_minmax(340px,440px)] gap-4 mt-4">
|
||||
<div className="grid sm:grid-cols-2 gap-4 content-start">
|
||||
{auctionState.teams.map((team) => (
|
||||
<TeamPanel
|
||||
key={`${team.side}-${team.groupIndex}`}
|
||||
team={team}
|
||||
isActive={isCurrentBidder(auctionState.currentBidder, team)}
|
||||
isLeft={team.side === 'blue'}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-w-0 space-y-4">
|
||||
@@ -721,20 +782,25 @@ export default function AuctionPage() {
|
||||
{auctionState.phase === 'sold' && auctionState.currentBidder && (
|
||||
<div
|
||||
className={`text-center py-3 border text-sm font-bold ${
|
||||
auctionState.currentBidder === 'blue'
|
||||
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'
|
||||
}`}
|
||||
>
|
||||
{auctionState.currentBidder === 'blue' ? '블루팀' : '레드팀'} 낙찰
|
||||
{teamLabel(
|
||||
auctionState.currentBidder.side,
|
||||
auctionState.currentBidder.groupIndex,
|
||||
)} 낙찰
|
||||
{' '}— {formatPoints(auctionState.currentBid)}P
|
||||
</div>
|
||||
)}
|
||||
|
||||
<BidControls
|
||||
state={auctionState}
|
||||
captainSide={captainSide}
|
||||
onBid={(side, amount) => socket.placeBid({ side, amount })}
|
||||
captainRole={captainRole}
|
||||
onBid={(side, groupIndex, amount) =>
|
||||
socket.placeBid({ side, groupIndex, amount })
|
||||
}
|
||||
/>
|
||||
<BidLog bids={auctionState.bids} />
|
||||
|
||||
@@ -788,14 +854,6 @@ export default function AuctionPage() {
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="w-full lg:w-56 shrink-0">
|
||||
<TeamPanel
|
||||
team={auctionState.teams[1]}
|
||||
isActive={auctionState.currentBidder === 'red'}
|
||||
isLeft={false}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Link } from 'react-router';
|
||||
import { mapApiMatchToMatchDetail } from '../api/mappers';
|
||||
import { useMatches } from '../api/hooks';
|
||||
import { useMatches, useMe } from '../api/hooks';
|
||||
import { DEFAULT_COMMUNITY_ID } from '../config';
|
||||
|
||||
function StatusBadge({ status }: { status: string }) {
|
||||
@@ -49,6 +49,7 @@ export default function HomePage() {
|
||||
{ status: 'finished', limit: 10 },
|
||||
DEFAULT_COMMUNITY_ID,
|
||||
);
|
||||
const meQuery = useMe();
|
||||
|
||||
if (!DEFAULT_COMMUNITY_ID) {
|
||||
return (
|
||||
@@ -84,6 +85,11 @@ export default function HomePage() {
|
||||
finishedMatchesQuery.data?.map(mapApiMatchToMatchDetail) ?? [];
|
||||
const nextMatch = upcomingMatches[0];
|
||||
const upcomingCards = nextMatch ? upcomingMatches.slice(1) : upcomingMatches;
|
||||
const currentUser =
|
||||
meQuery.data?.memberships.find(
|
||||
(membership) => membership.community?._id === DEFAULT_COMMUNITY_ID,
|
||||
)?.user ?? null;
|
||||
const canManage = currentUser?.role === 'owner' || currentUser?.role === 'admin';
|
||||
|
||||
return (
|
||||
<main className="max-w-5xl mx-auto px-4 sm:px-6">
|
||||
@@ -92,12 +98,22 @@ export default function HomePage() {
|
||||
<h2 className="text-xs font-bold text-base-content/40 uppercase tracking-widest">
|
||||
다음 내전
|
||||
</h2>
|
||||
<Link
|
||||
to={`/communities/${DEFAULT_COMMUNITY_ID}/internal-stats`}
|
||||
className="text-xs font-bold text-primary hover:underline"
|
||||
>
|
||||
내전 전적 보기
|
||||
</Link>
|
||||
<div className="flex items-center gap-3">
|
||||
{canManage && (
|
||||
<Link
|
||||
to={`/admin/communities/${DEFAULT_COMMUNITY_ID}/matches`}
|
||||
className="text-xs font-bold text-base-content/35 hover:text-primary"
|
||||
>
|
||||
내전 관리
|
||||
</Link>
|
||||
)}
|
||||
<Link
|
||||
to={`/communities/${DEFAULT_COMMUNITY_ID}/internal-stats`}
|
||||
className="text-xs font-bold text-primary hover:underline"
|
||||
>
|
||||
내전 전적 보기
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{nextMatch ? (
|
||||
|
||||
@@ -22,7 +22,47 @@ 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 type { Position, TournamentCodeSlotView } from '../api/types';
|
||||
import type {
|
||||
ApiMatchParticipant,
|
||||
Position,
|
||||
TeamSide,
|
||||
TournamentCodeSlotView,
|
||||
} from '../api/types';
|
||||
|
||||
type CaptainSelectionSlot = {
|
||||
side: TeamSide;
|
||||
groupIndex: 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}`;
|
||||
}
|
||||
|
||||
function buildAuctionParticipantPool(participants: ApiMatchParticipant[]) {
|
||||
const ordered = [...participants].sort(
|
||||
(left, right) =>
|
||||
new Date(left.joinedAt).getTime() - new Date(right.joinedAt).getTime(),
|
||||
);
|
||||
const auctionParticipantCount = Math.floor(ordered.length / 10) * 10;
|
||||
return ordered.slice(0, auctionParticipantCount);
|
||||
}
|
||||
|
||||
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 },
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
function PosBadge({ pos, sub }: { pos: Position; sub?: boolean }) {
|
||||
return (
|
||||
@@ -123,8 +163,13 @@ function ParticipantRow({
|
||||
<span className="font-medium text-[13px] text-base-content truncate block leading-tight group-hover:text-primary transition-colors">
|
||||
{participant.summonerName}
|
||||
</span>
|
||||
<span className="text-[10px] text-base-content/25 leading-tight">
|
||||
<span className="inline-flex items-center gap-1 text-[10px] text-base-content/25 leading-tight">
|
||||
#{participant.tag}
|
||||
{participant.excluded && (
|
||||
<span className="border border-amber-500/20 bg-amber-500/10 px-1 text-[9px] font-bold text-amber-500">
|
||||
제외
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</Link>
|
||||
@@ -215,9 +260,11 @@ function ParticipantTable({
|
||||
|
||||
function TeamCard({
|
||||
team,
|
||||
matchId,
|
||||
isWinner,
|
||||
}: {
|
||||
team: TeamView;
|
||||
matchId: string;
|
||||
isWinner?: boolean;
|
||||
}) {
|
||||
const borderColor =
|
||||
@@ -242,6 +289,12 @@ function TeamCard({
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Link
|
||||
to={`/match/${matchId}/team/${team.side}/${team.groupIndex}`}
|
||||
className="text-[10px] font-bold text-base-content/35 hover:text-primary"
|
||||
>
|
||||
진행 페이지
|
||||
</Link>
|
||||
</div>
|
||||
<table className="w-full text-left">
|
||||
<thead>
|
||||
@@ -359,8 +412,13 @@ function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) {
|
||||
<div className="space-y-2">
|
||||
{slots.map((slot) => (
|
||||
<div key={slot.gameNumber} className="flex items-start gap-2">
|
||||
<span className="text-[11px] font-bold text-base-content/40 w-11 shrink-0 pt-1.5">
|
||||
<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) && (
|
||||
<span className="block text-[10px] font-normal text-base-content/25">
|
||||
{slot.blueGroupIndex}조
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{slot.code ? (
|
||||
<TournamentCodeDisplay slot={slot} />
|
||||
@@ -403,8 +461,8 @@ function formatGameDuration(seconds: number) {
|
||||
return `${minutes}:${String(rest).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function resultSideLabel(side: 'blue' | 'red') {
|
||||
return side === 'blue' ? '블루팀' : '레드팀';
|
||||
function resultSideLabel(side: 'blue' | 'red', groupIndex = 1) {
|
||||
return teamLabel(side, groupIndex);
|
||||
}
|
||||
|
||||
function resultSideClass(side: 'blue' | 'red') {
|
||||
@@ -417,10 +475,16 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) {
|
||||
const gamesByNumber = new Map(
|
||||
match.result.games.map((game) => [game.gameNumber, game]),
|
||||
);
|
||||
const maxGameNumber = Math.max(
|
||||
match.gameCount,
|
||||
match.tournamentCodes.length,
|
||||
...match.result.games.map((game) => game.gameNumber),
|
||||
);
|
||||
const gameNumbers = Array.from(
|
||||
{ length: match.gameCount },
|
||||
{ length: maxGameNumber },
|
||||
(_, index) => index + 1,
|
||||
);
|
||||
const seriesResults = match.result.seriesResults ?? [];
|
||||
|
||||
return (
|
||||
<div className="mb-6 border border-base-content/10 bg-base-content/[0.02] p-5">
|
||||
@@ -452,11 +516,34 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) {
|
||||
<div className="text-center mt-3 text-[11px] font-bold text-amber-400 uppercase tracking-wide">
|
||||
{match.result.winner
|
||||
? `${match.result.winner} 승리`
|
||||
: `결과 수집 중 · ${match.result.games.length}/${match.gameCount}경기`}
|
||||
: `결과 수집 중 · ${match.result.games.length}/${maxGameNumber}경기`}
|
||||
</div>
|
||||
{seriesResults.length > 1 && (
|
||||
<div className="mt-4 grid sm:grid-cols-2 gap-2">
|
||||
{seriesResults.map((series) => (
|
||||
<div
|
||||
key={`${series.blueGroupIndex}-${series.redGroupIndex}`}
|
||||
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}조
|
||||
</div>
|
||||
<div className="mt-1 flex items-center justify-between">
|
||||
<span className="text-blue-400">블루 {series.blueScore}</span>
|
||||
<span className="text-base-content/20">:</span>
|
||||
<span className="text-red-400">레드 {series.redScore}</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<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}
|
||||
@@ -468,7 +555,7 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) {
|
||||
{game ? (
|
||||
<div>
|
||||
<span className={`font-black ${resultSideClass(game.winnerSide)}`}>
|
||||
{resultSideLabel(game.winnerSide)} 승
|
||||
{resultSideLabel(game.winnerSide, winnerGroupIndex)} 승
|
||||
</span>
|
||||
<span className="ml-2 text-base-content/35 font-mono">
|
||||
{game.riotMatchId}
|
||||
@@ -501,8 +588,9 @@ export default function MatchDetailPage() {
|
||||
)?.user ?? null;
|
||||
const canUseMemberActions = Boolean(currentUser || authUserId);
|
||||
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID);
|
||||
const [blueCaptainUserId, setBlueCaptainUserId] = useState('');
|
||||
const [redCaptainUserId, setRedCaptainUserId] = useState('');
|
||||
const [captainSelections, setCaptainSelections] = useState<Record<string, string>>(
|
||||
{},
|
||||
);
|
||||
const pollTournamentResultMutation = usePollTournamentResult(
|
||||
DEFAULT_COMMUNITY_ID,
|
||||
);
|
||||
@@ -535,10 +623,13 @@ export default function MatchDetailPage() {
|
||||
apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/auction`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
captains: [
|
||||
{ side: 'blue', userId: blueCaptainUserId },
|
||||
{ side: 'red', userId: redCaptainUserId },
|
||||
],
|
||||
captains: buildCaptainSlots(matchQuery.data?.participants ?? []).map(
|
||||
(slot) => ({
|
||||
side: slot.side,
|
||||
groupIndex: slot.groupIndex,
|
||||
userId: captainSelections[captainSlotKey(slot)],
|
||||
}),
|
||||
),
|
||||
initialPoints: 1000,
|
||||
maxTimerSeconds: 30,
|
||||
}),
|
||||
@@ -568,14 +659,43 @@ export default function MatchDetailPage() {
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const participants = matchQuery.data?.participants ?? [];
|
||||
if (!blueCaptainUserId && participants[0]) {
|
||||
setBlueCaptainUserId(participants[0].userId);
|
||||
const participants = buildAuctionParticipantPool(
|
||||
matchQuery.data?.participants ?? [],
|
||||
);
|
||||
const slots = buildCaptainSlots(matchQuery.data?.participants ?? []);
|
||||
if (slots.length === 0) {
|
||||
setCaptainSelections({});
|
||||
return;
|
||||
}
|
||||
if (!redCaptainUserId && participants[1]) {
|
||||
setRedCaptainUserId(participants[1].userId);
|
||||
}
|
||||
}, [blueCaptainUserId, redCaptainUserId, matchQuery.data?.participants]);
|
||||
|
||||
setCaptainSelections((current) => {
|
||||
const next: Record<string, string> = {};
|
||||
const usedUserIds = new Set<string>();
|
||||
|
||||
for (const slot of slots) {
|
||||
const key = captainSlotKey(slot);
|
||||
const currentUserId = current[key];
|
||||
const currentIsValid =
|
||||
currentUserId &&
|
||||
participants.some((participant) => participant.userId === currentUserId) &&
|
||||
!usedUserIds.has(currentUserId);
|
||||
|
||||
if (currentIsValid) {
|
||||
next[key] = currentUserId;
|
||||
usedUserIds.add(currentUserId);
|
||||
continue;
|
||||
}
|
||||
|
||||
const fallback = participants.find(
|
||||
(participant) => !usedUserIds.has(participant.userId),
|
||||
);
|
||||
next[key] = fallback?.userId ?? '';
|
||||
if (fallback) usedUserIds.add(fallback.userId);
|
||||
}
|
||||
|
||||
return next;
|
||||
});
|
||||
}, [matchQuery.data?.participants]);
|
||||
|
||||
if (!DEFAULT_COMMUNITY_ID) {
|
||||
return (
|
||||
@@ -615,14 +735,24 @@ export default function MatchDetailPage() {
|
||||
const auctionNotStarted =
|
||||
auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404;
|
||||
const showAuctionLink = Boolean(auctionQuery.data);
|
||||
const auctionParticipantPool = buildAuctionParticipantPool(
|
||||
matchQuery.data.participants,
|
||||
);
|
||||
const captainSlots = buildCaptainSlots(matchQuery.data.participants);
|
||||
const selectedCaptainIds = captainSlots
|
||||
.map((slot) => captainSelections[captainSlotKey(slot)])
|
||||
.filter(Boolean);
|
||||
const hasUniqueCaptainSelections =
|
||||
selectedCaptainIds.length === captainSlots.length &&
|
||||
new Set(selectedCaptainIds).size === selectedCaptainIds.length;
|
||||
const waitingParticipantCount =
|
||||
matchQuery.data.participants.length - auctionParticipantPool.length;
|
||||
const canStartAuction =
|
||||
canManageAuction &&
|
||||
match.status === 'recruiting' &&
|
||||
matchQuery.data.participants.length >= 2 &&
|
||||
auctionParticipantPool.length >= 10 &&
|
||||
auctionNotStarted &&
|
||||
blueCaptainUserId &&
|
||||
redCaptainUserId &&
|
||||
blueCaptainUserId !== redCaptainUserId;
|
||||
hasUniqueCaptainSelections;
|
||||
|
||||
return (
|
||||
<main className="max-w-5xl mx-auto px-4 sm:px-6 py-6">
|
||||
@@ -721,8 +851,13 @@ export default function MatchDetailPage() {
|
||||
경매 시작
|
||||
</h3>
|
||||
<p className="mt-1 text-xs text-base-content/40">
|
||||
두 팀장을 선택하면 경매를 시작할 수 있습니다.
|
||||
참가 신청 순서 기준 10명당 1개 조가 만들어지고, 각 조에 블루/레드 팀장을 지정합니다.
|
||||
</p>
|
||||
{waitingParticipantCount > 0 && (
|
||||
<p className="mt-1 text-[11px] text-amber-500">
|
||||
{waitingParticipantCount}명은 10명 단위에 맞지 않아 이번 경매에서 제외됩니다.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{showAuctionLink ? (
|
||||
@@ -730,37 +865,55 @@ export default function MatchDetailPage() {
|
||||
경매 페이지 열기
|
||||
</Link>
|
||||
) : (
|
||||
<div className="grid sm:grid-cols-2 gap-3">
|
||||
<label className="text-xs text-base-content/45">
|
||||
블루팀 팀장
|
||||
<select
|
||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-2 py-2 text-sm"
|
||||
value={blueCaptainUserId}
|
||||
onChange={(event) => setBlueCaptainUserId(event.target.value)}
|
||||
>
|
||||
<option value="">선택하세요</option>
|
||||
{matchQuery.data.participants.map((participant) => (
|
||||
<option key={`blue-${participant.userId}`} value={participant.userId}>
|
||||
{participant.gameName ?? participant.userId}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-xs text-base-content/45">
|
||||
레드팀 팀장
|
||||
<select
|
||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-2 py-2 text-sm"
|
||||
value={redCaptainUserId}
|
||||
onChange={(event) => setRedCaptainUserId(event.target.value)}
|
||||
>
|
||||
<option value="">선택하세요</option>
|
||||
{matchQuery.data.participants.map((participant) => (
|
||||
<option key={`red-${participant.userId}`} value={participant.userId}>
|
||||
{participant.gameName ?? participant.userId}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<div className="space-y-3">
|
||||
{captainSlots.length > 0 ? (
|
||||
<div className="grid sm:grid-cols-2 gap-3">
|
||||
{captainSlots.map((slot) => {
|
||||
const key = captainSlotKey(slot);
|
||||
const currentValue = captainSelections[key] ?? '';
|
||||
return (
|
||||
<label
|
||||
key={key}
|
||||
className="text-xs text-base-content/45"
|
||||
>
|
||||
{teamLabel(slot.side, slot.groupIndex)} 팀장
|
||||
<select
|
||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-2 py-2 text-sm"
|
||||
value={currentValue}
|
||||
onChange={(event) =>
|
||||
setCaptainSelections((current) => ({
|
||||
...current,
|
||||
[key]: event.target.value,
|
||||
}))
|
||||
}
|
||||
>
|
||||
<option value="">선택하세요</option>
|
||||
{auctionParticipantPool.map((participant) => {
|
||||
const selectedByOtherSlot =
|
||||
selectedCaptainIds.includes(
|
||||
participant.userId,
|
||||
) && currentValue !== participant.userId;
|
||||
return (
|
||||
<option
|
||||
key={`${key}-${participant.userId}`}
|
||||
value={participant.userId}
|
||||
disabled={selectedByOtherSlot}
|
||||
>
|
||||
{participant.gameName ?? participant.userId}
|
||||
{selectedByOtherSlot ? ' (선택됨)' : ''}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="border border-dashed border-base-content/10 px-3 py-4 text-xs text-base-content/35">
|
||||
경매를 시작하려면 최소 10명이 필요합니다.
|
||||
</div>
|
||||
)}
|
||||
<div className="sm:col-span-2 flex items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
@@ -785,8 +938,9 @@ export default function MatchDetailPage() {
|
||||
<div className="space-y-4">
|
||||
{match.teams.map((team) => (
|
||||
<TeamCard
|
||||
key={team.side}
|
||||
key={`${team.side}-${team.groupIndex}`}
|
||||
team={team}
|
||||
matchId={match.id}
|
||||
isWinner={
|
||||
match.status === 'finished'
|
||||
? match.result?.winner === team.name
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
import { Link, useParams } from 'react-router';
|
||||
import { useDdragonManifest, useMatch } from '../api/hooks';
|
||||
import type { ApiMatchParticipant, Position, TeamSide } 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}`;
|
||||
}
|
||||
|
||||
function formatExpiry(value: string | null) {
|
||||
if (!value) return '-';
|
||||
return new Intl.DateTimeFormat('ko-KR', {
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(new Date(value));
|
||||
}
|
||||
|
||||
function ParticipantLine({
|
||||
participant,
|
||||
assignedPosition,
|
||||
isCaptain,
|
||||
}: {
|
||||
participant?: ApiMatchParticipant;
|
||||
assignedPosition?: Position;
|
||||
isCaptain?: boolean;
|
||||
}) {
|
||||
const { data: ddragon } = useDdragonManifest();
|
||||
const name = participant?.gameName ?? '알 수 없는 참가자';
|
||||
const tag = participant?.tagLine ?? '----';
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-3 border-b border-base-content/5 last:border-b-0 px-3 py-2">
|
||||
<div className="h-8 w-8 shrink-0 overflow-hidden bg-base-content/10">
|
||||
<img
|
||||
src={profileIconUrl(ddragon, participant?.profileIconId ?? 0)}
|
||||
alt=""
|
||||
className="h-full w-full object-cover"
|
||||
loading="lazy"
|
||||
/>
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate text-sm font-bold text-base-content">
|
||||
{name}
|
||||
</span>
|
||||
{isCaptain && (
|
||||
<span className="border border-amber-500/20 bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-bold text-amber-500">
|
||||
팀장
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-[11px] text-base-content/30">#{tag}</div>
|
||||
</div>
|
||||
<div className="text-xs font-semibold text-primary">
|
||||
{assignedPosition ? positionLabel[assignedPosition] : '-'}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function MatchTeamProgressPage() {
|
||||
const { id, side, groupIndex } = useParams();
|
||||
const parsedGroupIndex = Number(groupIndex ?? 1);
|
||||
const teamSide = side === 'blue' || side === 'red' ? side : null;
|
||||
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
|
||||
|
||||
if (!DEFAULT_COMMUNITY_ID) {
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl px-4 py-20 text-center text-sm text-amber-600">
|
||||
`VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다.
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
if (matchQuery.isLoading) {
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl px-4 py-20 text-center text-sm text-base-content/40">
|
||||
팀 진행 정보를 불러오는 중...
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
if (!teamSide || !matchQuery.data) {
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl px-4 py-20 text-center">
|
||||
<h1 className="text-lg font-bold">팀 정보를 찾을 수 없습니다</h1>
|
||||
<Link to={`/match/${id}`} className="btn btn-primary btn-sm mt-4 px-5 text-xs">
|
||||
내전 상세로
|
||||
</Link>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
const match = matchQuery.data;
|
||||
const team = match.teams.find(
|
||||
(item) =>
|
||||
item.side === teamSide && (item.groupIndex ?? 1) === parsedGroupIndex,
|
||||
);
|
||||
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,
|
||||
);
|
||||
const games = (match.result?.games ?? []).filter((game) =>
|
||||
teamSide === 'blue'
|
||||
? game.blueGroupIndex === parsedGroupIndex
|
||||
: game.redGroupIndex === parsedGroupIndex,
|
||||
);
|
||||
|
||||
if (!team) {
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl px-4 py-20 text-center">
|
||||
<h1 className="text-lg font-bold">아직 팀이 생성되지 않았습니다</h1>
|
||||
<p className="mt-2 text-sm text-base-content/40">
|
||||
경매가 완료되면 팀별 진행 페이지를 사용할 수 있습니다.
|
||||
</p>
|
||||
<Link to={`/match/${id}`} className="btn btn-primary btn-sm mt-4 px-5 text-xs">
|
||||
내전 상세로
|
||||
</Link>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl px-4 py-6 sm:px-6">
|
||||
<Link
|
||||
to={`/match/${id}`}
|
||||
className="mb-5 inline-flex text-xs text-base-content/40 hover:text-base-content"
|
||||
>
|
||||
← 내전 상세로
|
||||
</Link>
|
||||
|
||||
<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)}
|
||||
</h1>
|
||||
<p className="mt-1 text-sm text-base-content/45">
|
||||
이 팀에 연결된 토너먼트 코드와 수집된 결과만 보여줍니다.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_320px]">
|
||||
<section className="border border-base-content/10 bg-base-100">
|
||||
<div className="border-b border-base-content/10 bg-base-200/40 px-4 py-2">
|
||||
<h2 className="text-[11px] font-bold uppercase tracking-wider text-base-content/40">
|
||||
팀 구성
|
||||
</h2>
|
||||
</div>
|
||||
<ParticipantLine
|
||||
participant={
|
||||
team.captainUserId
|
||||
? participantByUserId.get(team.captainUserId)
|
||||
: undefined
|
||||
}
|
||||
isCaptain
|
||||
/>
|
||||
{team.members.map((member) => (
|
||||
<ParticipantLine
|
||||
key={member.userId}
|
||||
participant={participantByUserId.get(member.userId)}
|
||||
assignedPosition={member.assignedPosition}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
|
||||
<section className="space-y-4">
|
||||
<div className="border border-base-content/10 bg-base-100">
|
||||
<div className="border-b border-base-content/10 bg-base-200/40 px-4 py-2">
|
||||
<h2 className="text-[11px] font-bold uppercase tracking-wider text-base-content/40">
|
||||
토너먼트 코드
|
||||
</h2>
|
||||
</div>
|
||||
<div className="divide-y divide-base-content/5">
|
||||
{codes.length > 0 ? (
|
||||
codes.map((slot) => (
|
||||
<div key={slot.gameNumber} className="px-4 py-3 text-xs">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="font-bold text-base-content/50">
|
||||
{slot.gameNumber}경기
|
||||
</span>
|
||||
<code className="font-mono font-black text-primary">
|
||||
{slot.code ?? '발급 대기'}
|
||||
</code>
|
||||
</div>
|
||||
<div className="mt-1 text-[11px] text-base-content/30">
|
||||
만료 {formatExpiry(slot.expiresAt)}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div className="px-4 py-6 text-center text-xs text-base-content/30">
|
||||
아직 연결된 코드가 없습니다.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border border-base-content/10 bg-base-100">
|
||||
<div className="border-b border-base-content/10 bg-base-200/40 px-4 py-2">
|
||||
<h2 className="text-[11px] font-bold uppercase tracking-wider text-base-content/40">
|
||||
결과
|
||||
</h2>
|
||||
</div>
|
||||
<div className="divide-y divide-base-content/5">
|
||||
{games.length > 0 ? (
|
||||
games.map((game) => {
|
||||
const won = game.winnerSide === teamSide;
|
||||
return (
|
||||
<div key={game.gameNumber} className="px-4 py-3 text-xs">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="font-bold text-base-content/50">
|
||||
{game.gameNumber}경기
|
||||
</span>
|
||||
<span
|
||||
className={won ? 'font-black text-blue-400' : 'font-black text-red-400'}
|
||||
>
|
||||
{won ? '승리' : '패배'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-1 truncate font-mono text-[11px] text-base-content/30">
|
||||
{game.riotMatchId}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<div className="px-4 py-6 text-center text-xs text-base-content/30">
|
||||
아직 수집된 결과가 없습니다.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Link, useParams } from 'react-router';
|
||||
import {
|
||||
useCreateMatch,
|
||||
useDeleteMatch,
|
||||
useMatches,
|
||||
useMe,
|
||||
useUpdateMatch,
|
||||
} from '../../api/hooks';
|
||||
import type {
|
||||
ApiMatch,
|
||||
ApiMatchScheduleItem,
|
||||
MatchGameMode,
|
||||
MatchMutationRequest,
|
||||
} from '../../api/types';
|
||||
import { DEFAULT_COMMUNITY_ID } from '../../config';
|
||||
|
||||
const DEFAULT_FORM: MatchMutationRequest = {
|
||||
title: '',
|
||||
description: '',
|
||||
mapId: 11,
|
||||
scheduledAt: toInputValue(new Date(Date.now() + 24 * 60 * 60 * 1000)),
|
||||
maxParticipants: 10,
|
||||
gameCount: 3,
|
||||
gameMode: 'pair',
|
||||
prizes: [],
|
||||
notices: [],
|
||||
schedule: [],
|
||||
};
|
||||
|
||||
const GAME_MODE_LABEL: Record<MatchGameMode, string> = {
|
||||
pair: '페어',
|
||||
bracket: '브래킷',
|
||||
'round-robin': '라운드 로빈',
|
||||
};
|
||||
|
||||
function toInputValue(value: string | Date) {
|
||||
const date = value instanceof Date ? value : new Date(value);
|
||||
const offset = date.getTimezoneOffset();
|
||||
return new Date(date.getTime() - offset * 60_000).toISOString().slice(0, 16);
|
||||
}
|
||||
|
||||
function toIsoFromInput(value: string) {
|
||||
return new Date(value).toISOString();
|
||||
}
|
||||
|
||||
function formatDate(value: string) {
|
||||
return new Intl.DateTimeFormat('ko-KR', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(new Date(value));
|
||||
}
|
||||
|
||||
function parseLines(value: string) {
|
||||
return value
|
||||
.split(/\r?\n/u)
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function parseSchedule(value: string): ApiMatchScheduleItem[] {
|
||||
return parseLines(value).map((line) => {
|
||||
const [time, ...labelParts] = line.split('|').map((part) => part.trim());
|
||||
return {
|
||||
time: time || '00:00',
|
||||
label: labelParts.join('|') || '일정',
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function scheduleToText(schedule: ApiMatchScheduleItem[] = []) {
|
||||
return schedule.map((item) => `${item.time}|${item.label}`).join('\n');
|
||||
}
|
||||
|
||||
function makeForm(match?: ApiMatch): MatchMutationRequest & {
|
||||
prizesText: string;
|
||||
noticesText: string;
|
||||
scheduleText: string;
|
||||
} {
|
||||
if (!match) {
|
||||
return {
|
||||
...DEFAULT_FORM,
|
||||
prizesText: '',
|
||||
noticesText: '',
|
||||
scheduleText: '',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
title: match.title,
|
||||
description: match.description,
|
||||
mapId: match.mapId,
|
||||
scheduledAt: toInputValue(match.scheduledAt),
|
||||
maxParticipants: match.maxParticipants,
|
||||
gameCount: match.gameCount,
|
||||
gameMode: match.gameMode ?? 'pair',
|
||||
prizes: match.prizes,
|
||||
notices: match.notices,
|
||||
schedule: match.schedule,
|
||||
prizesText: match.prizes.join('\n'),
|
||||
noticesText: match.notices.join('\n'),
|
||||
scheduleText: scheduleToText(match.schedule),
|
||||
};
|
||||
}
|
||||
|
||||
export default function MatchAdminPage() {
|
||||
const { cid } = useParams();
|
||||
const communityId = cid ?? DEFAULT_COMMUNITY_ID;
|
||||
const queryClient = useQueryClient();
|
||||
const meQuery = useMe();
|
||||
const matchesQuery = useMatches({ limit: 200 }, communityId);
|
||||
const createMutation = useCreateMatch(communityId);
|
||||
const updateMutation = useUpdateMatch(communityId);
|
||||
const deleteMutation = useDeleteMatch(communityId);
|
||||
const [editing, setEditing] = useState<ApiMatch | null>(null);
|
||||
const [showForm, setShowForm] = useState(false);
|
||||
const [form, setForm] = useState(makeForm());
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
const currentUser =
|
||||
meQuery.data?.memberships.find(
|
||||
(membership) => membership.community?._id === communityId,
|
||||
)?.user ?? null;
|
||||
const canManage = currentUser?.role === 'owner' || currentUser?.role === 'admin';
|
||||
const matches = useMemo(
|
||||
() => [...(matchesQuery.data ?? [])].sort((a, b) => new Date(b.scheduledAt).getTime() - new Date(a.scheduledAt).getTime()),
|
||||
[matchesQuery.data],
|
||||
);
|
||||
|
||||
async function invalidate() {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: ['matches', communityId] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['match', communityId] }),
|
||||
]);
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
setEditing(null);
|
||||
setForm(makeForm());
|
||||
setShowForm(true);
|
||||
setMessage(null);
|
||||
}
|
||||
|
||||
function openEdit(match: ApiMatch) {
|
||||
setEditing(match);
|
||||
setForm(makeForm(match));
|
||||
setShowForm(true);
|
||||
setMessage(null);
|
||||
}
|
||||
|
||||
function buildPayload(): MatchMutationRequest {
|
||||
return {
|
||||
title: form.title.trim(),
|
||||
description: form.description?.trim() ?? '',
|
||||
mapId: Number(form.mapId ?? 11),
|
||||
scheduledAt: toIsoFromInput(form.scheduledAt),
|
||||
maxParticipants: Number(form.maxParticipants ?? 10),
|
||||
gameCount: Number(form.gameCount ?? 3),
|
||||
gameMode: form.gameMode,
|
||||
prizes: parseLines(form.prizesText),
|
||||
notices: parseLines(form.noticesText),
|
||||
schedule: parseSchedule(form.scheduleText),
|
||||
};
|
||||
}
|
||||
|
||||
function submit() {
|
||||
setMessage(null);
|
||||
const payload = buildPayload();
|
||||
if (!payload.title) {
|
||||
setMessage('제목을 입력해주세요.');
|
||||
return;
|
||||
}
|
||||
|
||||
const callbacks = {
|
||||
onSuccess: async () => {
|
||||
await invalidate();
|
||||
setShowForm(false);
|
||||
setEditing(null);
|
||||
setMessage(editing ? '내전을 수정했습니다.' : '내전을 만들었습니다.');
|
||||
},
|
||||
onError: (error: Error) => setMessage(error.message),
|
||||
};
|
||||
|
||||
if (editing) {
|
||||
updateMutation.mutate({ matchId: editing._id, body: payload }, callbacks);
|
||||
return;
|
||||
}
|
||||
createMutation.mutate(payload, callbacks);
|
||||
}
|
||||
|
||||
if (!canManage && !meQuery.isPending) {
|
||||
return (
|
||||
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
|
||||
<h1 className="text-lg font-bold">권한이 필요합니다</h1>
|
||||
<p className="mt-2 text-sm text-base-content/40">
|
||||
내전 관리는 owner/admin만 사용할 수 있습니다.
|
||||
</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="max-w-6xl mx-auto px-4 sm:px-6 py-6">
|
||||
<Link to="/" className="inline-flex text-xs text-base-content/40 hover:text-base-content mb-5">
|
||||
← 목록으로
|
||||
</Link>
|
||||
<div className="mb-6 flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-black text-base-content">내전 관리</h1>
|
||||
<p className="mt-1 text-sm text-base-content/45">
|
||||
내전 생성, 모집 정원, 게임 모드와 공지 내용을 관리합니다.
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" className="btn btn-primary btn-sm px-5 text-xs" onClick={openCreate}>
|
||||
새 내전 만들기
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{message && (
|
||||
<div className="mb-4 border border-primary/20 bg-primary/5 px-3 py-2 text-xs text-base-content/60">
|
||||
{message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showForm && (
|
||||
<section className="mb-6 border border-base-content/10 bg-base-100 p-4">
|
||||
<div className="mb-4 flex items-center justify-between gap-3">
|
||||
<h2 className="text-sm font-bold">
|
||||
{editing ? '내전 수정' : '새 내전'}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-base-content/35 hover:text-base-content"
|
||||
onClick={() => setShowForm(false)}
|
||||
>
|
||||
닫기
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-3">
|
||||
<label className="text-xs text-base-content/45 md:col-span-2">
|
||||
제목
|
||||
<input
|
||||
value={form.title}
|
||||
onChange={(event) => setForm((current) => ({ ...current, title: event.target.value }))}
|
||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-base-content/45 md:col-span-2">
|
||||
설명
|
||||
<textarea
|
||||
value={form.description}
|
||||
onChange={(event) => setForm((current) => ({ ...current, description: event.target.value }))}
|
||||
rows={3}
|
||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-base-content/45">
|
||||
시작 시간
|
||||
<input
|
||||
type="datetime-local"
|
||||
value={form.scheduledAt}
|
||||
onChange={(event) => setForm((current) => ({ ...current, scheduledAt: event.target.value }))}
|
||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-base-content/45">
|
||||
정원
|
||||
<select
|
||||
value={form.maxParticipants}
|
||||
onChange={(event) => setForm((current) => ({ ...current, maxParticipants: Number(event.target.value) }))}
|
||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
|
||||
>
|
||||
{[10, 20, 30, 40, 50, 60].map((value) => (
|
||||
<option key={value} value={value}>{value}명</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-xs text-base-content/45">
|
||||
게임 수
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
value={form.gameCount}
|
||||
onChange={(event) => setForm((current) => ({ ...current, gameCount: Number(event.target.value) }))}
|
||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-base-content/45">
|
||||
게임 모드
|
||||
<select
|
||||
value={form.gameMode}
|
||||
onChange={(event) => setForm((current) => ({ ...current, gameMode: event.target.value as MatchGameMode }))}
|
||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
|
||||
>
|
||||
{Object.entries(GAME_MODE_LABEL).map(([value, label]) => (
|
||||
<option key={value} value={value}>{label}</option>
|
||||
))}
|
||||
</select>
|
||||
<span className="mt-1 block text-[10px] text-amber-500/80">
|
||||
현재 경매/코드 연결은 페어 방식 기준으로 동작합니다.
|
||||
</span>
|
||||
</label>
|
||||
<label className="text-xs text-base-content/45">
|
||||
상품 (줄바꿈 구분)
|
||||
<textarea
|
||||
value={form.prizesText}
|
||||
onChange={(event) => setForm((current) => ({ ...current, prizesText: event.target.value }))}
|
||||
rows={4}
|
||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-base-content/45">
|
||||
공지 (줄바꿈 구분)
|
||||
<textarea
|
||||
value={form.noticesText}
|
||||
onChange={(event) => setForm((current) => ({ ...current, noticesText: event.target.value }))}
|
||||
rows={4}
|
||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-base-content/45 md:col-span-2">
|
||||
일정 (`시간|라벨`, 줄바꿈 구분)
|
||||
<textarea
|
||||
value={form.scheduleText}
|
||||
onChange={(event) => setForm((current) => ({ ...current, scheduleText: event.target.value }))}
|
||||
rows={3}
|
||||
placeholder="20:50|로비 오픈"
|
||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm font-mono"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-sm px-5 text-xs"
|
||||
disabled={createMutation.isPending || updateMutation.isPending}
|
||||
onClick={submit}
|
||||
>
|
||||
{editing ? '수정 저장' : '생성'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost btn-sm px-5 text-xs"
|
||||
onClick={() => setShowForm(false)}
|
||||
>
|
||||
취소
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section className="border border-base-content/10 bg-base-100 overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[900px] text-left">
|
||||
<thead>
|
||||
<tr className="bg-base-200/40 border-b border-base-content/10 text-[11px] uppercase tracking-wider text-base-content/35">
|
||||
<th className="px-3 py-2">시간</th>
|
||||
<th className="px-3 py-2">내전</th>
|
||||
<th className="px-3 py-2">상태</th>
|
||||
<th className="px-3 py-2">정원</th>
|
||||
<th className="px-3 py-2">모드</th>
|
||||
<th className="px-3 py-2 text-right">작업</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{matches.map((match) => (
|
||||
<tr key={match._id} className="border-b border-base-content/5">
|
||||
<td className="px-3 py-2 text-xs text-base-content/45">
|
||||
{formatDate(match.scheduledAt)}
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<Link to={`/match/${match._id}`} className="text-sm font-bold hover:text-primary">
|
||||
{match.title}
|
||||
</Link>
|
||||
<div className="mt-0.5 text-[11px] text-base-content/30">
|
||||
{match.description || '-'}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-3 py-2 text-xs">{match.status}</td>
|
||||
<td className="px-3 py-2 text-xs tabular-nums">
|
||||
{match.participants.length}/{match.maxParticipants}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-xs">
|
||||
{GAME_MODE_LABEL[match.gameMode ?? 'pair']}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right">
|
||||
<div className="inline-flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="text-[11px] px-2 py-1 border border-base-content/10 text-base-content/50 hover:text-primary"
|
||||
onClick={() => openEdit(match)}
|
||||
>
|
||||
수정
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="text-[11px] px-2 py-1 border border-red-500/20 text-red-400 hover:bg-red-500/10"
|
||||
disabled={deleteMutation.isPending}
|
||||
onClick={() => {
|
||||
if (!window.confirm('이 내전을 삭제할까요?')) return;
|
||||
deleteMutation.mutate(match._id, {
|
||||
onSuccess: invalidate,
|
||||
onError: (error) =>
|
||||
setMessage(error instanceof Error ? error.message : '삭제 실패'),
|
||||
});
|
||||
}}
|
||||
>
|
||||
삭제
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{matches.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={6} className="px-4 py-10 text-center text-sm text-base-content/35">
|
||||
등록된 내전이 없습니다.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user