Files
lolympus-tournament-support/apps/web/src/api/mappers.ts
T
2026-05-02 11:51:01 -07:00

527 lines
13 KiB
TypeScript

import type {
ApiAuction,
ApiAuctionPlayerSnapshot,
ApiAuctionTeam,
ApiMatch,
ApiMatchParticipant,
ApiPositionPreference,
ApiRiotLaneStats,
ApiRiotRecentStatsSummary,
ApiTierInfo,
MatchStatus,
Position,
RiotLane,
TournamentCodeSlotView,
} from "./types";
import { POSITION_ORDER, teamIndexLabel } from "../lib/league";
export interface ParticipantView {
id: string;
userId: string;
summonerName: string;
tag: string;
tier?: ApiTierInfo;
mainPosition: Position;
subPosition: Position;
profileIconId: number;
excluded?: boolean;
}
export interface TeamParticipantView extends ParticipantView {
assignedPosition: Position;
cost?: number;
}
export interface TeamView {
teamIndex: number;
name: string;
participants: TeamParticipantView[];
}
export interface MatchDetailView {
id: string;
title: string;
date: string;
time: string;
status: MatchStatus;
description: string;
map: string;
maxParticipants: number;
gameCount: number;
gameMode: ApiMatch["gameMode"];
tournamentCodes: TournamentCodeSlotView[];
joined: boolean;
participants: ParticipantView[];
teams: TeamView[];
result?: {
winner?: string;
winnerTeamIndex?: number;
riotMatchIds: string[];
games: Array<{
gameNumber: number;
riotMatchId: string;
blueTeamIndex: number;
redTeamIndex: number;
winnerTeamIndex: number;
winnerSide: "blue" | "red";
gameCreation: number;
gameDuration: number;
participants: Array<{
userId: string;
teamIndex: number;
side: "blue" | "red";
championId: number;
kills: number;
deaths: number;
assists: number;
win: boolean;
}>;
}>;
seriesResults: NonNullable<ApiMatch["result"]>["seriesResults"];
};
prizes: string[];
notices: string[];
schedule: { time: string; label: string }[];
}
export interface AuctionPlayerView extends ParticipantView {
passCount: number;
masteries: {
championId: number;
level: number;
points: number;
}[];
recentStats: {
overall: ApiRiotLaneStats;
byLane: Partial<Record<RiotLane, ApiRiotLaneStats>>;
primary: ApiRiotLaneStats | null;
primarySource: "lane" | "overall" | "none";
};
}
export interface AuctionTeamView {
teamIndex: number;
name: string;
captainUserId: string;
captainName: string;
points: number;
members: (AuctionPlayerView & {
assignedPosition: Position;
cost: number;
})[];
}
export interface AuctionStateView {
matchId: string;
phase: ApiAuction["phase"];
teams: AuctionTeamView[];
currentPlayer: AuctionPlayerView | null;
currentPlayerIndex: number;
totalPlayers: number;
auctionOrder: AuctionPlayerView[];
passedQueue: AuctionPlayerView[];
auctionRound: number;
bids: {
teamIndex: number;
amount: number;
timestamp: string;
}[];
currentBid: number;
currentBidder: { teamIndex: number } | null;
timer: number;
maxTimer: number;
deadline?: string;
}
const MAP_LABELS: Record<number, string> = {
11: "소환사의 협곡",
12: "칼바람 나락",
21: "소환사의 협곡",
22: "전략적 팀 전투",
};
const TIER_NAMES: Record<string, string> = {
IRON: "아이언",
BRONZE: "브론즈",
SILVER: "실버",
GOLD: "골드",
PLATINUM: "플래티넘",
EMERALD: "에메랄드",
DIAMOND: "다이아",
MASTER: "마스터",
GRANDMASTER: "그랜드마스터",
CHALLENGER: "챌린저",
};
const POSITION_TO_RIOT_LANE: Record<Position, RiotLane> = {
TOP: "TOP",
JGL: "JUNGLE",
MID: "MIDDLE",
ADC: "BOTTOM",
SUP: "UTILITY",
};
function createEmptyLaneStats(): ApiRiotLaneStats {
return {
games: 0,
wins: 0,
losses: 0,
avgKills: 0,
avgDeaths: 0,
avgAssists: 0,
avgCs: 0,
avgCsPerMin: 0,
mostPlayedChampionIds: [],
};
}
function createEmptyRecentStatsView(): AuctionPlayerView["recentStats"] {
return {
overall: createEmptyLaneStats(),
byLane: {},
primary: null,
primarySource: "none",
};
}
function sortPreferredPositions(preferredPositions: ApiPositionPreference[]) {
return [...preferredPositions].sort(
(left, right) => left.priority - right.priority,
);
}
function resolveMainAndSubPosition(
preferredPositions: ApiPositionPreference[],
) {
const sorted = sortPreferredPositions(preferredPositions);
return {
mainPosition: sorted[0]?.position ?? "MID",
subPosition: sorted[1]?.position ?? sorted[0]?.position ?? "MID",
};
}
function mapMatchParticipantToView(
participant: ApiMatchParticipant,
): ParticipantView {
const { mainPosition, subPosition } = resolveMainAndSubPosition(
participant.preferredPositions,
);
return {
id: participant.userId,
userId: participant.userId,
summonerName: participant.gameName ?? "알 수 없음",
tag: participant.tagLine ?? "----",
tier: participant.tier,
mainPosition,
subPosition,
profileIconId: participant.profileIconId ?? 0,
excluded: participant.excluded ?? false,
};
}
function mapAuctionPlayerToView(
player: ApiAuctionPlayerSnapshot,
): AuctionPlayerView {
const { mainPosition, subPosition } = resolveMainAndSubPosition(
player.preferredPositions,
);
const summary = player.recentStatsSummary;
const primary = pickPrimary(summary, mainPosition);
return {
id: player.userId,
userId: player.userId,
summonerName: player.gameName,
tag: player.tagLine,
tier: selectPrimaryTier(player.tiers),
mainPosition,
subPosition,
profileIconId: player.profileIconId,
passCount: player.passCount ?? 0,
masteries: player.masteries.slice(0, 5).map((mastery) => ({
championId: mastery.championId,
level: mastery.championLevel,
points: mastery.championPoints,
})),
recentStats: {
overall: summary?.overall ?? createEmptyLaneStats(),
byLane: summary?.byLane ?? {},
primary: primary.stats,
primarySource: primary.source,
},
};
}
function createFallbackParticipant(userId: string): ParticipantView {
return {
id: userId,
userId,
summonerName: `User ${userId.slice(-4)}`,
tag: "----",
mainPosition: "MID",
subPosition: "MID",
profileIconId: 0,
};
}
function mapAuctionTeamToView(
team: ApiAuctionTeam,
playerLookup: Map<string, AuctionPlayerView>,
participantLookup: Map<string, ParticipantView>,
): AuctionTeamView {
return {
teamIndex: team.teamIndex,
name: teamIndexLabel(team.teamIndex),
captainUserId: team.captainUserId,
captainName:
participantLookup.get(team.captainUserId)?.summonerName ??
`User ${team.captainUserId.slice(-4)}`,
points: team.points,
members: team.members.map((member) => {
const participant = participantLookup.get(member.userId);
const player =
playerLookup.get(member.userId) ??
(participant
? {
...participant,
passCount: 0,
masteries: [],
recentStats: createEmptyRecentStatsView(),
}
: {
...createFallbackParticipant(member.userId),
passCount: 0,
masteries: [],
recentStats: createEmptyRecentStatsView(),
});
return {
...player,
assignedPosition: member.assignedPosition,
cost: member.cost,
};
}),
};
}
export function mapIdToLabel(mapId: number) {
return MAP_LABELS[mapId] ?? `맵 #${mapId}`;
}
export function formatKoreanDate(dateLike: string | Date) {
const date = new Date(dateLike);
return {
date: new Intl.DateTimeFormat("ko-KR", {
year: "numeric",
month: "long",
day: "numeric",
weekday: "short",
}).format(date),
time: new Intl.DateTimeFormat("ko-KR", {
hour: "numeric",
minute: "2-digit",
}).format(date),
};
}
function pickPrimary(
summary: ApiRiotRecentStatsSummary | undefined,
mainPosition: Position,
): {
stats: ApiRiotLaneStats | null;
source: "lane" | "overall" | "none";
} {
if (!summary) {
return { stats: null, source: "none" };
}
const laneStats = summary.byLane[POSITION_TO_RIOT_LANE[mainPosition]];
if (laneStats && laneStats.games > 0) {
return { stats: laneStats, source: "lane" };
}
if (summary.overall.games > 0) {
return { stats: summary.overall, source: "overall" };
}
return { stats: null, source: "none" };
}
export function selectPrimaryTier(tiers: ApiTierInfo[]) {
return tiers.find((tier) => tier.queueType === "RANKED_SOLO_5x5") ?? tiers[0];
}
export function formatTierLabel(tier?: ApiTierInfo) {
if (!tier) return "미등록";
const tierName = TIER_NAMES[tier.tier] ?? tier.tier;
const highTier = ["MASTER", "GRANDMASTER", "CHALLENGER"].includes(tier.tier);
if (highTier && tier.leaguePoints > 0) {
return `${tierName} ${tier.leaguePoints}LP`;
}
return tier.rank ? `${tierName} ${tier.rank}` : tierName;
}
export function getTierColorToken(tier?: ApiTierInfo) {
switch (tier?.tier) {
case "CHALLENGER":
return "text-amber-400";
case "GRANDMASTER":
return "text-red-400";
case "MASTER":
return "text-fuchsia-400";
case "DIAMOND":
return "text-cyan-400";
case "EMERALD":
return "text-emerald-400";
case "PLATINUM":
return "text-teal-300";
case "GOLD":
return "text-yellow-400";
case "SILVER":
return "text-gray-300";
case "BRONZE":
return "text-amber-700";
case "IRON":
return "text-stone-400";
default:
return "text-base-content/50";
}
}
export function buildDefaultPreferredPositions() {
return POSITION_ORDER.map((position, index) => ({
position,
priority: index + 1,
}));
}
export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
const formattedDate = formatKoreanDate(match.scheduledAt);
const participants = match.participants.map(mapMatchParticipantToView);
const participantLookup = new Map(
participants.map((participant) => [participant.userId, participant]),
);
const teams = match.teams.map((team) => ({
teamIndex: team.teamIndex,
name: teamIndexLabel(team.teamIndex, team.name),
participants: team.members.map((member) => {
const participant =
participantLookup.get(member.userId) ??
createFallbackParticipant(member.userId);
return {
...participant,
assignedPosition: member.assignedPosition,
cost: member.cost,
};
}),
}));
const winnerTeam = match.result?.winnerTeamIndex
? teams.find((team) => team.teamIndex === match.result?.winnerTeamIndex)
: undefined;
return {
id: match._id,
title: match.title,
date: formattedDate.date,
time: formattedDate.time,
status: match.status,
description: match.description,
map: mapIdToLabel(match.mapId),
maxParticipants: match.maxParticipants,
gameCount: match.gameCount ?? 3,
gameMode: match.gameMode ?? "pair",
tournamentCodes: match.tournamentCodes ?? [],
joined: Boolean(match.joined),
participants,
teams,
result: match.result
? {
winner: match.result.winnerTeamIndex ? winnerTeam?.name : undefined,
winnerTeamIndex: match.result.winnerTeamIndex,
riotMatchIds: match.result.riotMatchIds,
games: [...(match.result.games ?? [])].sort(
(left, right) => left.gameNumber - right.gameNumber,
),
seriesResults: match.result.seriesResults ?? [],
}
: undefined,
prizes: match.prizes,
notices: match.notices,
schedule: match.schedule,
};
}
export function mapApiAuctionToAuctionState(
auction: ApiAuction,
match: ApiMatch,
now = new Date(),
): AuctionStateView {
const participantLookup = new Map(
match.participants
.map(mapMatchParticipantToView)
.map((participant) => [participant.userId, participant]),
);
const auctionOrder = auction.order.map(mapAuctionPlayerToView);
const passedQueue = (auction.passedQueue ?? []).map(mapAuctionPlayerToView);
const auctionPlayerLookup = new Map(
auctionOrder.map((player) => [player.userId, player]),
);
const teams = [...auction.teams].sort(
(left, right) => left.teamIndex - right.teamIndex,
);
const totalPlayers = auctionOrder.length;
const currentPlayer =
auction.phase === "complete"
? null
: (auctionPlayerLookup.get(
auction.order[auction.currentIndex]?.userId ?? "",
) ?? null);
const currentPlayerIndex =
auction.phase === "complete" ? totalPlayers : auction.currentIndex;
const timer = auction.currentDeadline
? Math.max(
0,
Math.ceil(
(new Date(auction.currentDeadline).getTime() - now.getTime()) / 1000,
),
)
: 0;
return {
matchId: auction.matchId,
phase: auction.phase,
teams: teams.map((team) =>
mapAuctionTeamToView(team, auctionPlayerLookup, participantLookup),
),
currentPlayer,
currentPlayerIndex,
totalPlayers,
auctionOrder,
passedQueue,
auctionRound: auction.auctionRound ?? 1,
bids: auction.bids.map((bid) => ({
teamIndex: bid.teamIndex,
amount: bid.amount,
timestamp: bid.timestamp,
})),
currentBid: auction.currentBid,
currentBidder: auction.currentBidderTeamIndex
? {
teamIndex: auction.currentBidderTeamIndex,
}
: null,
timer,
maxTimer: auction.maxTimerSeconds,
deadline: auction.currentDeadline,
};
}