565 lines
15 KiB
TypeScript
565 lines
15 KiB
TypeScript
import type {
|
|
MatchDetailResponse,
|
|
MatchLifecycleStatus,
|
|
MatchParticipantView,
|
|
} from "@lolympus/contracts";
|
|
import type {
|
|
ApiAuction,
|
|
ApiAuctionPlayerSnapshot,
|
|
ApiAuctionTeam,
|
|
ApiPositionPreference,
|
|
ApiRiotLaneStats,
|
|
ApiRiotRecentStatsSummary,
|
|
ApiTierHistoryEntry,
|
|
ApiTierInfo,
|
|
Position,
|
|
RiotLane,
|
|
} 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;
|
|
captainUserId?: string;
|
|
captainName?: string;
|
|
captainTag?: string;
|
|
participants: TeamParticipantView[];
|
|
}
|
|
|
|
export interface MatchDetailView {
|
|
id: string;
|
|
title: string;
|
|
date: string;
|
|
time: string;
|
|
status: MatchLifecycleStatus;
|
|
description: string;
|
|
map: string;
|
|
maxParticipants: number;
|
|
joined: boolean;
|
|
participants: ParticipantView[];
|
|
teams: TeamView[];
|
|
prizes: string[];
|
|
notices: string[];
|
|
schedule: { time: string; label: string }[];
|
|
}
|
|
|
|
export interface AuctionPlayerView extends ParticipantView {
|
|
passCount: number;
|
|
masteries: {
|
|
championId: number;
|
|
level: number;
|
|
points: number;
|
|
}[];
|
|
tierHistory: ApiTierHistoryEntry[];
|
|
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;
|
|
captain?: ParticipantView;
|
|
points: number;
|
|
members: (AuctionPlayerView & {
|
|
assignedPosition: Position;
|
|
cost: number;
|
|
})[];
|
|
}
|
|
|
|
export interface AuctionStateView {
|
|
matchId: string;
|
|
phase: ApiAuction["phase"];
|
|
matchSideEffectRevision?: number;
|
|
matchSideEffectStatus?: ApiAuction["matchSideEffectStatus"];
|
|
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;
|
|
remainingMs: number;
|
|
timer: number;
|
|
maxTimer: number;
|
|
bidExtensionSeconds: 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: MatchParticipantView,
|
|
): 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);
|
|
const masteries = player.masteries ?? [];
|
|
|
|
return {
|
|
id: player.userId,
|
|
userId: player.userId,
|
|
summonerName: player.gameName,
|
|
tag: player.tagLine,
|
|
tier: selectPrimaryTier(player.tiers),
|
|
tierHistory: player.tierHistory ?? [],
|
|
mainPosition,
|
|
subPosition,
|
|
profileIconId: player.profileIconId ?? 0,
|
|
passCount: player.passCount ?? 0,
|
|
masteries: 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: NormalizedApiAuctionTeam,
|
|
playerLookup: Map<string, AuctionPlayerView>,
|
|
participantLookup: Map<string, ParticipantView>,
|
|
): AuctionTeamView {
|
|
const captain =
|
|
participantLookup.get(team.captainUserId) ??
|
|
playerLookup.get(team.captainUserId);
|
|
|
|
return {
|
|
teamIndex: team.teamIndex,
|
|
name: teamIndexLabel(team.teamIndex),
|
|
captainUserId: team.captainUserId,
|
|
captainName: captain?.summonerName ?? `User ${team.captainUserId.slice(-4)}`,
|
|
captain,
|
|
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: [],
|
|
tierHistory: [],
|
|
recentStats: createEmptyRecentStatsView(),
|
|
}
|
|
: {
|
|
...createFallbackParticipant(member.userId),
|
|
passCount: 0,
|
|
masteries: [],
|
|
tierHistory: [],
|
|
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-gold";
|
|
case "GRANDMASTER":
|
|
return "text-loss";
|
|
case "MASTER":
|
|
return "text-fuchsia-400";
|
|
case "DIAMOND":
|
|
return "text-cyan-400";
|
|
case "EMERALD":
|
|
return "text-leaf";
|
|
case "PLATINUM":
|
|
return "text-teal-300";
|
|
case "GOLD":
|
|
return "text-yellow-400";
|
|
case "SILVER":
|
|
return "text-gray-300";
|
|
case "BRONZE":
|
|
return "text-gold";
|
|
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: MatchDetailResponse,
|
|
): 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) => {
|
|
const captain = team.captainUserId
|
|
? participantLookup.get(team.captainUserId)
|
|
: undefined;
|
|
|
|
return {
|
|
teamIndex: team.teamIndex,
|
|
name: teamIndexLabel(team.teamIndex, team.name),
|
|
captainUserId: team.captainUserId,
|
|
captainName:
|
|
captain?.summonerName ??
|
|
(team.captainUserId
|
|
? `User ${team.captainUserId.slice(-4)}`
|
|
: undefined),
|
|
captainTag: captain?.tag,
|
|
participants: team.members.map((member) => {
|
|
const participant =
|
|
participantLookup.get(member.userId) ??
|
|
createFallbackParticipant(member.userId);
|
|
|
|
return {
|
|
...participant,
|
|
assignedPosition: member.assignedPosition,
|
|
cost: member.cost,
|
|
};
|
|
}),
|
|
};
|
|
});
|
|
|
|
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,
|
|
joined: Boolean(match.joined),
|
|
participants,
|
|
teams,
|
|
prizes: match.prizes,
|
|
notices: match.notices,
|
|
schedule: match.schedule,
|
|
};
|
|
}
|
|
|
|
export function mapApiAuctionToAuctionState(
|
|
auction: ApiAuction,
|
|
match: MatchDetailResponse,
|
|
now = new Date(),
|
|
): AuctionStateView {
|
|
const participantLookup = new Map(
|
|
match.participants
|
|
.map(mapMatchParticipantToView)
|
|
.map((participant) => [participant.userId, participant]),
|
|
);
|
|
const rawAuctionOrder = auction.auctionPlayerOrder ?? auction.order ?? [];
|
|
const rawPassedQueue =
|
|
auction.passedAuctionPlayerQueue ?? auction.passedQueue ?? [];
|
|
const rawAuctionTeams = auction.auctionTeams ?? auction.teams ?? [];
|
|
const currentAuctionPlayerOrderIndex =
|
|
auction.currentAuctionPlayerOrderIndex ?? auction.currentIndex ?? 0;
|
|
const currentBid =
|
|
auction.currentHighestBidPointAmount ?? auction.currentBid ?? 0;
|
|
const rawCurrentBidderTeamIndex =
|
|
auction.currentHighestBidderTeamIndex ?? auction.currentBidderTeamIndex;
|
|
const currentBidderTeamIndex =
|
|
rawCurrentBidderTeamIndex !== undefined && rawCurrentBidderTeamIndex > 0
|
|
? rawCurrentBidderTeamIndex
|
|
: undefined;
|
|
const maximumBidRoundDurationSeconds =
|
|
auction.maximumBidRoundDurationSeconds ?? auction.maxTimerSeconds ?? 30;
|
|
const bidRoundExtensionSeconds =
|
|
auction.bidRoundExtensionSeconds ?? auction.bidExtensionSeconds ?? 5;
|
|
const currentBidRoundDeadlineTimestampMS =
|
|
auction.currentBidRoundDeadlineTimestampMS ??
|
|
(auction.currentDeadline ? Date.parse(auction.currentDeadline) : undefined);
|
|
const auctionOrder = rawAuctionOrder.map(mapAuctionPlayerToView);
|
|
const passedQueue = rawPassedQueue.map(mapAuctionPlayerToView);
|
|
const auctionPlayerLookup = new Map(
|
|
auctionOrder.map((player) => [player.userId, player]),
|
|
);
|
|
const teams = rawAuctionTeams
|
|
.map(normalizeApiAuctionTeam)
|
|
.sort((left, right) => left.teamIndex - right.teamIndex);
|
|
|
|
const totalPlayers = auctionOrder.length;
|
|
const currentPlayer =
|
|
auction.phase === "complete"
|
|
? null
|
|
: (auctionPlayerLookup.get(
|
|
rawAuctionOrder[currentAuctionPlayerOrderIndex]?.userId ?? "",
|
|
) ?? null);
|
|
const currentPlayerIndex =
|
|
auction.phase === "complete"
|
|
? totalPlayers
|
|
: currentAuctionPlayerOrderIndex;
|
|
const remainingMs = currentBidRoundDeadlineTimestampMS
|
|
? Math.max(0, currentBidRoundDeadlineTimestampMS - now.getTime())
|
|
: 0;
|
|
const timer = Math.floor(remainingMs / 1000);
|
|
|
|
return {
|
|
matchId: auction.matchId,
|
|
phase: auction.phase,
|
|
matchSideEffectRevision: auction.matchSideEffectRevision,
|
|
matchSideEffectStatus: auction.matchSideEffectStatus,
|
|
teams: teams.map((team) =>
|
|
mapAuctionTeamToView(team, auctionPlayerLookup, participantLookup),
|
|
),
|
|
currentPlayer,
|
|
currentPlayerIndex,
|
|
totalPlayers,
|
|
auctionOrder,
|
|
passedQueue,
|
|
auctionRound: auction.currentAuctionRound ?? auction.auctionRound ?? 1,
|
|
bids: normalizeApiAuctionBids(auction),
|
|
currentBid,
|
|
currentBidder:
|
|
currentBidderTeamIndex !== undefined
|
|
? {
|
|
teamIndex: currentBidderTeamIndex,
|
|
}
|
|
: null,
|
|
remainingMs,
|
|
timer,
|
|
maxTimer: maximumBidRoundDurationSeconds,
|
|
bidExtensionSeconds: bidRoundExtensionSeconds,
|
|
deadline: currentBidRoundDeadlineTimestampMS
|
|
? new Date(currentBidRoundDeadlineTimestampMS).toISOString()
|
|
: undefined,
|
|
};
|
|
}
|
|
|
|
type NormalizedApiAuctionTeam = ApiAuctionTeam & { points: number };
|
|
|
|
function normalizeApiAuctionTeam(
|
|
team: ApiAuctionTeam,
|
|
): NormalizedApiAuctionTeam {
|
|
return {
|
|
...team,
|
|
points: team.points ?? team.remainingBidPointAmount ?? 0,
|
|
members: (team.members ?? []).map((member) => ({
|
|
...member,
|
|
cost: member.cost ?? member.memberAcquisitionBidPointAmount ?? 0,
|
|
})),
|
|
};
|
|
}
|
|
|
|
function normalizeApiAuctionBids(auction: ApiAuction) {
|
|
if (auction.auctionBidHistory) {
|
|
return auction.auctionBidHistory.map((bid) => ({
|
|
amount: bid.bidPointAmount,
|
|
teamIndex: bid.bidderTeamIndex,
|
|
timestamp: new Date(bid.bidPlacedAtTimestampMS).toISOString(),
|
|
}));
|
|
}
|
|
return (auction.bids ?? []).map((bid) => ({
|
|
teamIndex: bid.teamIndex,
|
|
amount: bid.amount,
|
|
timestamp: bid.timestamp,
|
|
}));
|
|
}
|