275 lines
8.1 KiB
TypeScript
275 lines
8.1 KiB
TypeScript
import type {
|
|
BracketRoundView,
|
|
CompetitionTeamMemberView,
|
|
SeriesProjection,
|
|
TeamTournamentCodeView,
|
|
} from "@lolympus/contracts";
|
|
import { bracketRoundLabel } from "../components/competition/double-elimination-bracket-layout.ts";
|
|
|
|
export interface TeamSeriesGroup {
|
|
series: SeriesProjection;
|
|
codes: TeamTournamentCodeView[];
|
|
}
|
|
|
|
export type TeamSeriesTone =
|
|
| "muted"
|
|
| "ready"
|
|
| "live"
|
|
| "completed"
|
|
| "adjudicated";
|
|
|
|
export interface TeamSeriesPresentation {
|
|
label: string;
|
|
tone: TeamSeriesTone;
|
|
showScore: boolean;
|
|
}
|
|
|
|
export type TournamentCodeTone =
|
|
| "pending"
|
|
| "available"
|
|
| "expired"
|
|
| "used";
|
|
|
|
export interface TournamentCodePresentation {
|
|
label: string;
|
|
tone: TournamentCodeTone;
|
|
canCopy: boolean;
|
|
}
|
|
|
|
export type TournamentCodeCopyFeedback =
|
|
| { kind: "success"; message: string }
|
|
| { kind: "error"; message: string };
|
|
|
|
type ClipboardWriter = ((value: string) => Promise<void>) | undefined;
|
|
|
|
const POSITION_RANK = new Map(
|
|
(["TOP", "JGL", "MID", "ADC", "SUP"] as const).map(
|
|
(position, index) => [position, index],
|
|
),
|
|
);
|
|
|
|
export function createTeamSeriesGroups(
|
|
activeSeries: readonly SeriesProjection[],
|
|
tournamentCodes: readonly TeamTournamentCodeView[],
|
|
): TeamSeriesGroup[] {
|
|
const codesBySeriesId = new Map<string, TeamTournamentCodeView[]>();
|
|
for (const assignment of tournamentCodes) {
|
|
const seriesId = String(assignment.seriesId);
|
|
const existing = codesBySeriesId.get(seriesId) ?? [];
|
|
existing.push(assignment);
|
|
codesBySeriesId.set(seriesId, existing);
|
|
}
|
|
|
|
return [...activeSeries]
|
|
.sort(compareSeriesDisplayOrder)
|
|
.map((series) => ({
|
|
series,
|
|
codes: [...(codesBySeriesId.get(String(series.seriesId)) ?? [])].sort(
|
|
compareTournamentCodes,
|
|
),
|
|
}));
|
|
}
|
|
|
|
export function getTeamSeriesDisplayLabel(
|
|
series: SeriesProjection,
|
|
rounds: readonly BracketRoundView[],
|
|
): string {
|
|
const round = rounds.find(({ seriesIds }) =>
|
|
seriesIds.some((seriesId) => seriesId === series.seriesId),
|
|
);
|
|
const stage = round?.stage ?? series.stage.type;
|
|
const roundNumber = round?.roundNumber ?? series.stage.roundNumber ?? 1;
|
|
const baseLabel = bracketRoundLabel(stage, roundNumber);
|
|
|
|
if (!round || round.seriesIds.length <= 1) return baseLabel;
|
|
const matchIndex = round.seriesIds.findIndex(
|
|
(seriesId) => seriesId === series.seriesId,
|
|
);
|
|
return matchIndex >= 0
|
|
? `${baseLabel} · ${matchIndex + 1}경기`
|
|
: baseLabel;
|
|
}
|
|
|
|
export function getTeamSeriesPresentation(
|
|
series: SeriesProjection,
|
|
): TeamSeriesPresentation {
|
|
switch (series.status) {
|
|
case "inactive":
|
|
return { label: "비활성", tone: "muted", showScore: false };
|
|
case "waiting":
|
|
return { label: "대진 대기", tone: "muted", showScore: false };
|
|
case "ready":
|
|
return { label: "경기 가능", tone: "ready", showScore: false };
|
|
case "in-progress":
|
|
return { label: "진행 중", tone: "live", showScore: true };
|
|
case "completed":
|
|
switch (series.outcome.type) {
|
|
case "played":
|
|
return { label: "종료", tone: "completed", showScore: true };
|
|
case "draw":
|
|
return {
|
|
label: "무승부",
|
|
tone:
|
|
series.outcome.basis.type === "played"
|
|
? "completed"
|
|
: "adjudicated",
|
|
showScore: series.outcome.basis.type === "played",
|
|
};
|
|
case "walkover":
|
|
return { label: "부전승", tone: "adjudicated", showScore: false };
|
|
case "forfeit":
|
|
return { label: "기권승", tone: "adjudicated", showScore: false };
|
|
case "administrative":
|
|
return { label: "판정승", tone: "adjudicated", showScore: false };
|
|
}
|
|
}
|
|
}
|
|
|
|
export function getTournamentCodePresentation(
|
|
assignment: TeamTournamentCodeView,
|
|
now = Date.now(),
|
|
): TournamentCodePresentation {
|
|
if (assignment.state === "used") {
|
|
return { label: "사용 완료", tone: "used", canCopy: false };
|
|
}
|
|
if (assignment.state === "pending" || !assignment.code) {
|
|
return { label: "발급 대기", tone: "pending", canCopy: false };
|
|
}
|
|
if (
|
|
assignment.expiresAt &&
|
|
!Number.isFinite(Date.parse(assignment.expiresAt))
|
|
) {
|
|
return { label: "만료 정보 오류", tone: "expired", canCopy: false };
|
|
}
|
|
if (isExpired(assignment.expiresAt, now)) {
|
|
return { label: "만료", tone: "expired", canCopy: false };
|
|
}
|
|
return { label: "사용 가능", tone: "available", canCopy: true };
|
|
}
|
|
|
|
export function getTournamentCodeExpiryLabel(
|
|
expiresAt: string,
|
|
now: number,
|
|
): string {
|
|
const date = new Date(expiresAt);
|
|
if (Number.isNaN(date.getTime())) return "만료 시각 정보 없음";
|
|
|
|
const formatted = new Intl.DateTimeFormat("ko-KR", {
|
|
year: "numeric",
|
|
month: "long",
|
|
day: "numeric",
|
|
hour: "2-digit",
|
|
minute: "2-digit",
|
|
timeZone: "Asia/Seoul",
|
|
timeZoneName: "short",
|
|
}).format(date);
|
|
return date.getTime() <= now
|
|
? `${formatted}에 만료됨`
|
|
: `${formatted}까지 사용 가능`;
|
|
}
|
|
|
|
export function getNextTournamentCodeExpiryDelay(
|
|
assignments: readonly TeamTournamentCodeView[],
|
|
now: number,
|
|
): number | null {
|
|
let nearestExpiry = Number.POSITIVE_INFINITY;
|
|
for (const assignment of assignments) {
|
|
if (assignment.state !== "reserved" || !assignment.code) continue;
|
|
const expiry = assignment.expiresAt
|
|
? Date.parse(assignment.expiresAt)
|
|
: Number.NaN;
|
|
if (Number.isFinite(expiry) && expiry > now) {
|
|
nearestExpiry = Math.min(nearestExpiry, expiry);
|
|
}
|
|
}
|
|
|
|
if (!Number.isFinite(nearestExpiry)) return null;
|
|
return Math.min(nearestExpiry - now, 2_147_483_647);
|
|
}
|
|
|
|
export function getTournamentCodeCopyLabel(
|
|
assignment: TeamTournamentCodeView,
|
|
seriesLabel: string,
|
|
): string {
|
|
return `${seriesLabel} ${assignment.ordinal}세트 토너먼트 코드 복사 (전체 ${assignment.displayNumber}번 게임)`;
|
|
}
|
|
|
|
export async function copyTournamentCode(
|
|
writeText: ClipboardWriter,
|
|
code: string,
|
|
gameLabel: string,
|
|
): Promise<TournamentCodeCopyFeedback> {
|
|
try {
|
|
if (!writeText) throw new Error("Clipboard API unavailable");
|
|
await writeText(code);
|
|
return {
|
|
kind: "success",
|
|
message: `${gameLabel} 코드를 복사했습니다.`,
|
|
};
|
|
} catch {
|
|
return {
|
|
kind: "error",
|
|
message: `${gameLabel} 코드를 복사하지 못했습니다. 코드를 직접 선택해 복사해 주세요.`,
|
|
};
|
|
}
|
|
}
|
|
|
|
export function sortCompletedTeamSeries(
|
|
series: readonly Extract<SeriesProjection, { status: "completed" }>[],
|
|
): Array<Extract<SeriesProjection, { status: "completed" }>> {
|
|
return [...series].sort(
|
|
(left, right) =>
|
|
timestampValue(right.outcome.completedAt) -
|
|
timestampValue(left.outcome.completedAt) ||
|
|
right.stage.displayOrder - left.stage.displayOrder ||
|
|
String(left.seriesId).localeCompare(String(right.seriesId)),
|
|
);
|
|
}
|
|
|
|
export function sortTeamMembersForRoster(
|
|
members: readonly CompetitionTeamMemberView[],
|
|
): CompetitionTeamMemberView[] {
|
|
return [...members].sort(
|
|
(left, right) =>
|
|
(left.assignedPosition
|
|
? (POSITION_RANK.get(left.assignedPosition) ?? POSITION_RANK.size)
|
|
: POSITION_RANK.size) -
|
|
(right.assignedPosition
|
|
? (POSITION_RANK.get(right.assignedPosition) ?? POSITION_RANK.size)
|
|
: POSITION_RANK.size) ||
|
|
left.displayName.localeCompare(right.displayName, "ko"),
|
|
);
|
|
}
|
|
|
|
function compareSeriesDisplayOrder(
|
|
left: SeriesProjection,
|
|
right: SeriesProjection,
|
|
): number {
|
|
return (
|
|
left.stage.displayOrder - right.stage.displayOrder ||
|
|
String(left.seriesId).localeCompare(String(right.seriesId))
|
|
);
|
|
}
|
|
|
|
function compareTournamentCodes(
|
|
left: TeamTournamentCodeView,
|
|
right: TeamTournamentCodeView,
|
|
): number {
|
|
return (
|
|
left.ordinal - right.ordinal ||
|
|
left.displayNumber - right.displayNumber ||
|
|
String(left.gameSlotId).localeCompare(String(right.gameSlotId))
|
|
);
|
|
}
|
|
|
|
function isExpired(expiresAt: string | null, now: number): boolean {
|
|
if (!expiresAt) return false;
|
|
const timestamp = Date.parse(expiresAt);
|
|
return Number.isFinite(timestamp) && timestamp <= now;
|
|
}
|
|
|
|
function timestampValue(value: string): number {
|
|
const timestamp = Date.parse(value);
|
|
return Number.isFinite(timestamp) ? timestamp : Number.NEGATIVE_INFINITY;
|
|
}
|