Compare commits

..
5 Commits
35 changed files with 2804 additions and 2373 deletions

No files matched your search

+2
View File
@@ -28,6 +28,8 @@ website/LICENSE
!AGENTS.md !AGENTS.md
!docs/specs/internal-match-game-analysis.md !docs/specs/internal-match-game-analysis.md
!docs/plans/internal-match-game-analysis-p0-p1.md !docs/plans/internal-match-game-analysis-p0-p1.md
!docs/specs/double-elimination-connector-routing.md
!docs/plans/double-elimination-connector-routing.md
!agents/**/*.md !agents/**/*.md
!skills/**/*.md !skills/**/*.md
/tmp/ /tmp/
+8 -8
View File
@@ -29,20 +29,20 @@
}, },
"dependencies": { "dependencies": {
"@lolympus/contracts": "workspace:*", "@lolympus/contracts": "workspace:*",
"@nestjs/common": "^11.1.28", "@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.4", "@nestjs/config": "^4.0.4",
"@nestjs/core": "^11.1.28", "@nestjs/core": "^11.0.1",
"@nestjs/platform-express": "^11.1.28", "@nestjs/platform-express": "^11.0.1",
"@nestjs/platform-socket.io": "^11.1.28", "@nestjs/platform-socket.io": "^11.1.19",
"@nestjs/swagger": "^11.4.6", "@nestjs/swagger": "^11.2.7",
"@nestjs/websockets": "^11.1.28", "@nestjs/websockets": "^11.1.19",
"@socket.io/redis-adapter": "^8.3.0", "@socket.io/redis-adapter": "^8.3.0",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
"class-validator": "^0.15.1", "class-validator": "^0.15.1",
"jose": "^6.2.2", "jose": "^6.2.2",
"mongoose": "9.4.1", "mongoose": "^9.4.1",
"nats": "^2.29.3", "nats": "^2.29.3",
"newrelic": "^14.3.3", "newrelic": "^14.3.0",
"redis": "^5.12.1", "redis": "^5.12.1",
"reflect-metadata": "^0.2.2", "reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1", "rxjs": "^7.8.1",
@@ -2,30 +2,6 @@ import mongoose from 'mongoose';
import { AuctionService } from './auction.service'; import { AuctionService } from './auction.service';
describe('AuctionService', () => { describe('AuctionService', () => {
function requireRecord(
value: unknown,
label: string,
): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new Error(`${label} must be an object.`);
}
return value as Record<string, unknown>;
}
function requireArray(value: unknown, label: string): unknown[] {
if (!Array.isArray(value)) {
throw new Error(`${label} must be an array.`);
}
return value as unknown[];
}
function parseJsonRecord(value: unknown, label: string) {
if (typeof value !== 'string') {
throw new Error(`${label} must be a JSON string.`);
}
return requireRecord(JSON.parse(value) as unknown, label);
}
function createService(models: Record<string, unknown>) { function createService(models: Record<string, unknown>) {
const auctionHistoryModel = { const auctionHistoryModel = {
findOne: jest.fn().mockReturnValue({ findOne: jest.fn().mockReturnValue({
@@ -1031,12 +1007,7 @@ describe('AuctionService', () => {
); );
const transitionInput = const transitionInput =
auctionRedisCommandService.applyTransition.mock.calls[0][1]; auctionRedisCommandService.applyTransition.mock.calls[0][1];
expect( expect(JSON.parse(transitionInput.durabilityPayloadJson)).toMatchObject({
parseJsonRecord(
transitionInput.durabilityPayloadJson,
'durabilityPayloadJson',
),
).toMatchObject({
afterAuctionMongoProjection: expect.objectContaining({ afterAuctionMongoProjection: expect.objectContaining({
phase: 'bidding', phase: 'bidding',
revision: 2, revision: 2,
@@ -1207,40 +1178,17 @@ describe('AuctionService', () => {
const transitionInput = const transitionInput =
auctionRedisCommandService.applyTransition.mock.calls[0][1]; auctionRedisCommandService.applyTransition.mock.calls[0][1];
const durabilityPayload = parseJsonRecord( const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
transitionInput.durabilityPayloadJson, expect(durabilityPayload.snapshotBefore).toMatchObject({
'durabilityPayloadJson',
);
const snapshotBefore = requireRecord(
durabilityPayload.snapshotBefore,
'snapshotBefore',
);
const snapshotBeforeTeams = requireArray(
snapshotBefore.auctionTeams,
'snapshotBefore.auctionTeams',
);
const snapshotBeforeTeam = requireRecord(
snapshotBeforeTeams[0],
'snapshotBefore.auctionTeams[0]',
);
const afterAuctionMongoProjection = requireRecord(
durabilityPayload.afterAuctionMongoProjection,
'afterAuctionMongoProjection',
);
const projectedTeams = requireArray(
afterAuctionMongoProjection.auctionTeams,
'afterAuctionMongoProjection.auctionTeams',
);
const projectedTeam = requireRecord(
projectedTeams[0],
'afterAuctionMongoProjection.auctionTeams[0]',
);
expect(snapshotBefore).toMatchObject({
phase: 'bidding', phase: 'bidding',
revision: 4, revision: 4,
}); });
expect(snapshotBeforeTeam.members).toEqual([]); expect(durabilityPayload.snapshotBefore.auctionTeams[0].members).toEqual(
expect(projectedTeam.members).toEqual([ [],
);
expect(
durabilityPayload.afterAuctionMongoProjection.auctionTeams[0].members,
).toEqual([
expect.objectContaining({ expect.objectContaining({
memberAcquisitionBidPointAmount: 120, memberAcquisitionBidPointAmount: 120,
userId: playerUserId.toString(), userId: playerUserId.toString(),
@@ -1448,12 +1396,7 @@ describe('AuctionService', () => {
}); });
const [, transitionInput] = const [, transitionInput] =
auctionRedisCommandService.applyTransition.mock.calls.at(-1) ?? []; auctionRedisCommandService.applyTransition.mock.calls.at(-1) ?? [];
expect( expect(JSON.parse(transitionInput.durabilityPayloadJson)).toMatchObject({
parseJsonRecord(
transitionInput.durabilityPayloadJson,
'durabilityPayloadJson',
),
).toMatchObject({
afterAuctionMongoProjection: { afterAuctionMongoProjection: {
matchSideEffectStatus: 'pending', matchSideEffectStatus: 'pending',
phase: 'complete', phase: 'complete',
@@ -2624,10 +2567,7 @@ describe('AuctionService', () => {
durationSeconds: 30, durationSeconds: 30,
mode: 'set-relative', mode: 'set-relative',
}); });
const durabilityPayload = parseJsonRecord( const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
transitionInput.durabilityPayloadJson,
'durabilityPayloadJson',
);
expect(durabilityPayload).toMatchObject({ expect(durabilityPayload).toMatchObject({
auctionActionType: 'undo', auctionActionType: 'undo',
historyMutation: { historyMutation: {
@@ -429,14 +429,8 @@ export function applyCompetitionDomainInvariantIndexes(
} }
} }
export type CompetitionModelName =
| 'competition'
| 'competitionFact'
| 'competitionOutbox'
| 'tournamentCodeAssignment';
export const competitionModelDefinitions: Array<{ export const competitionModelDefinitions: Array<{
name: CompetitionModelName; name: string;
schema: mongoose.Schema; schema: mongoose.Schema;
schemaName: string; schemaName: string;
}> = [ }> = [
@@ -1,8 +1,4 @@
import { projectCompetition } from './competition-projector'; import { projectCompetition } from './competition-projector';
import {
CompetitionDomainError,
type CompetitionDomainErrorCode,
} from './domain-error';
import { generateSeriesGraph } from './series-graph'; import { generateSeriesGraph } from './series-graph';
describe('projectCompetition', () => { describe('projectCompetition', () => {
@@ -327,8 +323,7 @@ describe('projectCompetition', () => {
'team-1', 'team-1',
); );
expectCompetitionDomainError( expect(() =>
() =>
projectCompetition({ projectCompetition({
competitionId, competitionId,
revision: 1, revision: 1,
@@ -338,7 +333,10 @@ describe('projectCompetition', () => {
seriesGraph, seriesGraph,
facts: [{ ...accepted, seriesId: 'series-does-not-exist' }], facts: [{ ...accepted, seriesId: 'series-does-not-exist' }],
}), }),
'GAME_SERIES_MISMATCH', ).toThrow(
expect.objectContaining({
code: 'GAME_SERIES_MISMATCH',
}),
); );
}); });
@@ -358,8 +356,7 @@ describe('projectCompetition', () => {
'team-1', 'team-1',
); );
expectCompetitionDomainError( expect(() =>
() =>
projectCompetition({ projectCompetition({
competitionId, competitionId,
revision: 1, revision: 1,
@@ -369,7 +366,10 @@ describe('projectCompetition', () => {
seriesGraph, seriesGraph,
facts: [{ ...accepted, gameSlotId: 'slot-does-not-exist' }], facts: [{ ...accepted, gameSlotId: 'slot-does-not-exist' }],
}), }),
'GAME_SLOT_INVALID', ).toThrow(
expect.objectContaining({
code: 'GAME_SLOT_INVALID',
}),
); );
}); });
@@ -382,8 +382,7 @@ describe('projectCompetition', () => {
}; };
const seriesGraph = generateSeriesGraph({ competitionId, teams, format }); const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
expectCompetitionDomainError( expect(() =>
() =>
projectCompetition({ projectCompetition({
competitionId, competitionId,
revision: 1, revision: 1,
@@ -409,7 +408,10 @@ describe('projectCompetition', () => {
}, },
], ],
}), }),
'ADJUDICATION_INVALID', ).toThrow(
expect.objectContaining({
code: 'ADJUDICATION_INVALID',
}),
); );
}); });
@@ -615,23 +617,3 @@ interface GameSlotLike {
id: string; id: string;
ordinal: number; ordinal: number;
} }
function expectCompetitionDomainError(
action: () => unknown,
expectedCode: CompetitionDomainErrorCode,
): void {
let thrown: unknown;
try {
action();
} catch (error: unknown) {
thrown = error;
}
expect(thrown).toBeInstanceOf(CompetitionDomainError);
if (!(thrown instanceof CompetitionDomainError)) {
throw new Error(
`Expected CompetitionDomainError, received ${String(thrown)}`,
);
}
expect(thrown.code).toBe(expectedCode);
}
@@ -1,7 +1,6 @@
import { import {
assertReversalPreview, assertReversalPreview,
buildReversalFacts, buildReversalFacts,
CompetitionReversalError,
previewSeriesReversal, previewSeriesReversal,
} from './competition-reversal'; } from './competition-reversal';
@@ -20,8 +19,7 @@ describe('Competition reversal planning', () => {
]; ];
it('rejects strict reversal when a descendant has result activity', () => { it('rejects strict reversal when a descendant has result activity', () => {
expectCompetitionReversalError( expect(() =>
() =>
previewSeriesReversal({ previewSeriesReversal({
competitionId: 'competition-1', competitionId: 'competition-1',
revision: 2, revision: 2,
@@ -31,7 +29,8 @@ describe('Competition reversal planning', () => {
facts, facts,
assignments, assignments,
}), }),
'REVERSAL_DESCENDANT_ACTIVITY', ).toThrow(
expect.objectContaining({ code: 'REVERSAL_DESCENDANT_ACTIVITY' }),
); );
}); });
@@ -106,8 +105,7 @@ describe('Competition reversal planning', () => {
assignments, assignments,
}); });
expectCompetitionReversalError( expect(() =>
() =>
assertReversalPreview( assertReversalPreview(
{ {
competitionId: 'competition-1', competitionId: 'competition-1',
@@ -120,8 +118,7 @@ describe('Competition reversal planning', () => {
}, },
preview.impactHash, preview.impactHash,
), ),
'REVERSAL_PREVIEW_STALE', ).toThrow(expect.objectContaining({ code: 'REVERSAL_PREVIEW_STALE' }));
);
}); });
it('emits one append-only reversal fact for every active result fact', () => { it('emits one append-only reversal fact for every active result fact', () => {
@@ -163,26 +160,6 @@ describe('Competition reversal planning', () => {
}); });
}); });
function expectCompetitionReversalError(
action: () => unknown,
expectedCode: CompetitionReversalError['code'],
): void {
let thrown: unknown;
try {
action();
} catch (error: unknown) {
thrown = error;
}
expect(thrown).toBeInstanceOf(CompetitionReversalError);
if (!(thrown instanceof CompetitionReversalError)) {
throw new Error(
`Expected CompetitionReversalError, received ${String(thrown)}`,
);
}
expect(thrown.code).toBe(expectedCode);
}
function series(id: string, sources: Array<Record<string, unknown>>) { function series(id: string, sources: Array<Record<string, unknown>>) {
return { return {
id, id,
@@ -22,33 +22,6 @@ function makeHandler(params: {
} }
describe('MatchListHandler', () => { describe('MatchListHandler', () => {
afterEach(() => {
jest.useRealTimers();
});
it('queries only matches scheduled at or after command processing time', async () => {
const now = new Date('2026-07-25T07:30:00.000Z');
jest.useFakeTimers().setSystemTime(now);
const communityId = objectId('111111111111111111111111');
const list = jest.fn().mockResolvedValue([]);
const handler = makeHandler({
matchService: { list },
});
await handler.handle({
communityId,
senderUserId: 'kakao-user-1',
senderNickname: '프리리',
});
expect(list).toHaveBeenCalledWith({
communityId,
status: 'recruiting',
scheduledFrom: now,
limit: 10,
});
});
it('prints short codes, compact KST dates, and short links', async () => { it('prints short codes, compact KST dates, and short links', async () => {
const match = { const match = {
_id: objectId('333333333333333333333333'), _id: objectId('333333333333333333333333'),
@@ -19,11 +19,9 @@ export class MatchListHandler {
senderUserId: string; senderUserId: string;
senderNickname: string; senderNickname: string;
}): Promise<DakaoSegment[]> { }): Promise<DakaoSegment[]> {
const scheduledFrom = new Date();
const matches = await this.matchService.list({ const matches = await this.matchService.list({
communityId: params.communityId, communityId: params.communityId,
status: 'recruiting', status: 'recruiting',
scheduledFrom,
limit: 10, limit: 10,
}); });
@@ -2,10 +2,7 @@ import { Injectable, Logger, Scope, OnModuleInit } from '@nestjs/common';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { applyMongoosePerformancePlugin } from '../observability/mongoose-performance.plugin'; import { applyMongoosePerformancePlugin } from '../observability/mongoose-performance.plugin';
import { SecretService } from '../secret/secret.service'; import { SecretService } from '../secret/secret.service';
import { import { tournamentModelDefinitions, TournamentModelTypes } from './schema';
tournamentModelDefinitions,
type TournamentModelTypes,
} from './schema';
export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string { export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
if (nodeEnv === 'prod') return 'lolympus'; if (nodeEnv === 'prod') return 'lolympus';
@@ -45,8 +42,7 @@ export class ConnectionService implements OnModuleInit {
private connectionPromise: Promise<mongoose.Connection> | null = null; private connectionPromise: Promise<mongoose.Connection> | null = null;
constructor(private readonly secretService: SecretService) {} constructor(private readonly secretService: SecretService) {}
private tournamentModels: Map<keyof TournamentModelTypes, unknown> | null = private tournamentModels: Map<string, mongoose.Model<any>> | null = null;
null;
public async getConnection(): Promise<mongoose.Connection> { public async getConnection(): Promise<mongoose.Connection> {
if ( if (
@@ -93,18 +89,14 @@ export class ConnectionService implements OnModuleInit {
modelKey: K, modelKey: K,
): Promise<mongoose.Model<TournamentModelTypes[K]>> { ): Promise<mongoose.Model<TournamentModelTypes[K]>> {
const connection = await this.getConnection(); const connection = await this.getConnection();
if (this.tournamentModels) { if (this.tournamentModels)
return this.requireTournamentModel(this.tournamentModels, modelKey); return this.tournamentModels.get(modelKey) as mongoose.Model<
} TournamentModelTypes[K]
>;
const models = new Map<keyof TournamentModelTypes, unknown>(); const models = new Map<K, mongoose.Model<TournamentModelTypes[K]>>();
tournamentModelDefinitions.forEach((modelDefinition) => { tournamentModelDefinitions.forEach((modelDefinition) => {
if (!(modelDefinition.schema instanceof mongoose.Schema)) {
throw new Error(
`Invalid Mongoose schema for model ${modelDefinition.name}.`,
);
}
applyMongoosePerformancePlugin(modelDefinition.schema); applyMongoosePerformancePlugin(modelDefinition.schema);
// 이미 생성된 경우 컴파일 스킵. // 이미 생성된 경우 컴파일 스킵.
if ( if (
@@ -114,14 +106,14 @@ export class ConnectionService implements OnModuleInit {
) )
) { ) {
models.set( models.set(
modelDefinition.name, modelDefinition.name as K,
connection.models[modelDefinition.name], connection.models[modelDefinition.name],
); );
return; return;
} else { } else {
models.set( models.set(
modelDefinition.name, modelDefinition.name as K,
connection.model( connection.model<TournamentModelTypes[K]>(
modelDefinition.name, modelDefinition.name,
modelDefinition.schema, modelDefinition.schema,
modelDefinition.schemaName, modelDefinition.schemaName,
@@ -131,18 +123,7 @@ export class ConnectionService implements OnModuleInit {
}); });
this.tournamentModels = models; this.tournamentModels = models;
return this.requireTournamentModel(models, modelKey); return models.get(modelKey) as mongoose.Model<TournamentModelTypes[K]>;
}
private requireTournamentModel<K extends keyof TournamentModelTypes>(
models: ReadonlyMap<keyof TournamentModelTypes, unknown>,
modelKey: K,
): mongoose.Model<TournamentModelTypes[K]> {
const model = models.get(modelKey);
if (model === undefined) {
throw new Error(`Mongoose model ${modelKey} is not registered.`);
}
return model as mongoose.Model<TournamentModelTypes[K]>;
} }
public async createSession( public async createSession(
@@ -253,7 +253,9 @@ function migrateResult(result: Record<string, unknown>) {
seriesResults.length > 0 ? seriesResults : buildSeries(games); seriesResults.length > 0 ? seriesResults : buildSeries(games);
if (typeof migrated.winnerTeamIndex !== 'number') { if (typeof migrated.winnerTeamIndex !== 'number') {
const migratedSeriesResults = asArray(migrated.seriesResults); const migratedSeriesResults = Array.isArray(migrated.seriesResults)
? migrated.seriesResults
: [];
migrated.winnerTeamIndex = migrated.winnerTeamIndex =
resolveWinnerTeamIndex(migratedSeriesResults) ?? resolveWinnerTeamIndex(migratedSeriesResults) ??
(isSide(migrated.winnerSide) (isSide(migrated.winnerSide)
@@ -117,9 +117,7 @@ function createDb(params: {
function matchesFilter(doc: Doc, filter: Record<string, unknown>): boolean { function matchesFilter(doc: Doc, filter: Record<string, unknown>): boolean {
const clauses = filter.$or; const clauses = filter.$or;
if (Array.isArray(clauses)) { if (Array.isArray(clauses)) {
return (clauses as unknown[]).some( return clauses.some((clause) => matchesFilter(doc, clause));
(clause) => isRecord(clause) && matchesFilter(doc, clause),
);
} }
return Object.entries(filter).every(([key, value]) => { return Object.entries(filter).every(([key, value]) => {
@@ -11,11 +11,7 @@ import {
} from '../../../double-elimination/double-elimination.util'; } from '../../../double-elimination/double-elimination.util';
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants'; import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants';
import { ConnectionService } from '../connection.service'; import { ConnectionService } from '../connection.service';
import type { import type { MatchDocument, TournamentCodeDocument } from '../schema';
MatchDocument,
TournamentCode,
TournamentCodeDocument,
} from '../schema';
import { SecretModule } from '../../secret/secret.module'; import { SecretModule } from '../../secret/secret.module';
interface CliOptions { interface CliOptions {
@@ -338,7 +334,7 @@ function printPlan(plan: MatchRepairPlan) {
async function applyPlan( async function applyPlan(
match: MatchDocument, match: MatchDocument,
plan: MatchRepairPlan, plan: MatchRepairPlan,
TournamentCodeModel: mongoose.Model<TournamentCode>, TournamentCodeModel: mongoose.Model<any>,
session: mongoose.ClientSession, session: mongoose.ClientSession,
) { ) {
if (plan.skippedReason) return; if (plan.skippedReason) return;
@@ -2485,9 +2485,7 @@ MatchStatsSchema.index({ communityId: 1, userIds: 1 });
MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 }); MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 });
MatchStatsSchema.index({ communityId: 1, championIds: 1 }); MatchStatsSchema.index({ communityId: 1, championIds: 1 });
export const tournamentModelDefinitions: Array< export const tournamentModelDefinitions: ModelDefinition[] = [
ModelDefinition & { name: keyof TournamentModelTypes }
> = [
...competitionModelDefinitions, ...competitionModelDefinitions,
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' }, { name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
{ name: 'community', schema: CommunitySchema, schemaName: 'community' }, { name: 'community', schema: CommunitySchema, schemaName: 'community' },
+1 -1
View File
@@ -1,5 +1,5 @@
export interface ModelDefinition { export interface ModelDefinition {
name: string; name: string;
schema: unknown; schema: mongoose.Schema<any>;
schemaName?: string; schemaName?: string;
} }
@@ -34,13 +34,10 @@ type SchemaWithPerformanceMarker = mongoose.Schema & {
[PERFORMANCE_PLUGIN_APPLIED]?: boolean; [PERFORMANCE_PLUGIN_APPLIED]?: boolean;
}; };
export function applyMongoosePerformancePlugin(schemaValue: unknown): void { export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void {
if (!(schemaValue instanceof mongoose.Schema)) { const markedSchema = schema as SchemaWithPerformanceMarker;
throw new TypeError('Mongoose performance plugin requires a Schema.'); if (markedSchema[PERFORMANCE_PLUGIN_APPLIED]) return;
} markedSchema[PERFORMANCE_PLUGIN_APPLIED] = true;
const schema = schemaValue as SchemaWithPerformanceMarker;
if (schema[PERFORMANCE_PLUGIN_APPLIED]) return;
schema[PERFORMANCE_PLUGIN_APPLIED] = true;
schema.pre(QUERY_OPERATION_REGEX, function () { schema.pre(QUERY_OPERATION_REGEX, function () {
const query = this as QueryWithPerformanceState; const query = this as QueryWithPerformanceState;
@@ -5,9 +5,7 @@ describe('MatchService', () => {
function createServiceWithCreateModels() { function createServiceWithCreateModels() {
const createdPayloads: Record<string, unknown>[] = []; const createdPayloads: Record<string, unknown>[] = [];
const MatchModel = { const MatchModel = {
create: jest create: jest.fn().mockImplementation(async (payload) => {
.fn()
.mockImplementation(async (payload: Record<string, unknown>) => {
createdPayloads.push(payload); createdPayloads.push(payload);
return payload; return payload;
}), }),
+7 -7
View File
@@ -19,15 +19,15 @@
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
"@lolympus/contracts": "workspace:*",
"@azure/msal-browser": "^5.8.0", "@azure/msal-browser": "^5.8.0",
"@azure/msal-react": "^5.3.1", "@azure/msal-react": "^5.3.1",
"@lolympus/contracts": "workspace:*", "@newrelic/browser-agent": "^1.316.0",
"@newrelic/browser-agent": "^1.318.0",
"@tanstack/react-query": "^5.100.1", "@tanstack/react-query": "^5.100.1",
"lucide-react": "^1.14.0", "lucide-react": "^1.14.0",
"react": "^19.2.8", "react": "^19.2.4",
"react-dom": "^19.2.8", "react-dom": "^19.2.4",
"react-router": "^8.3.0", "react-router": "^7.14.0",
"recharts": "^3.8.1", "recharts": "^3.8.1",
"socket.io-client": "^4.8.3" "socket.io-client": "^4.8.3"
}, },
@@ -46,7 +46,7 @@
"tailwindcss": "^4.2.2", "tailwindcss": "^4.2.2",
"typescript": "~6.0.2", "typescript": "~6.0.2",
"typescript-eslint": "^8.58.0", "typescript-eslint": "^8.58.0",
"vite": "^8.1.5", "vite": "^8.0.4",
"wrangler": "^4.114.0" "wrangler": "^4.85.0"
} }
} }
+62 -100
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { io, type Socket } from 'socket.io-client'; import { io, type Socket } from 'socket.io-client';
import { API_BASE_URL, useAuthUserId } from '../config'; import { API_BASE_URL, useAuthUserId } from '../config';
import { acquireAccessToken } from '../lib/auth/token-provider'; import { acquireAccessToken } from '../lib/auth/token-provider';
@@ -140,9 +140,6 @@ function mergeChatMessages(
export function useAuctionSocket(matchId: string | undefined) { export function useAuctionSocket(matchId: string | undefined) {
const authUserId = useAuthUserId(); const authUserId = useAuthUserId();
const connectionKey = matchId
? JSON.stringify([matchId, authUserId ?? null])
: null;
const socketRef = useRef<Socket | null>(null); const socketRef = useRef<Socket | null>(null);
const pendingBidTimeoutsRef = useRef< const pendingBidTimeoutsRef = useRef<
Record<string, ReturnType<typeof setTimeout>> Record<string, ReturnType<typeof setTimeout>>
@@ -169,14 +166,9 @@ export function useAuctionSocket(matchId: string | undefined) {
Record<string, { action: string }> Record<string, { action: string }>
>({}); >({});
const [resetAt, setResetAt] = useState<number | null>(null); const [resetAt, setResetAt] = useState<number | null>(null);
const [connectionState, setConnectionState] = useState<{ const [connectionStatus, setConnectionStatus] =
key: string; useState<ConnectionStatus>('idle');
status: ConnectionStatus; const [error, setError] = useState<string | null>(null);
}>({ key: '', status: 'idle' });
const [errorState, setErrorState] = useState<{
key: string;
message: string | null;
}>({ key: '', message: null });
const [serverTimeOffsetMs, setServerTimeOffsetMs] = useState(0); const [serverTimeOffsetMs, setServerTimeOffsetMs] = useState(0);
const [serverRoundTripMs, setServerRoundTripMs] = useState<number | null>( const [serverRoundTripMs, setServerRoundTripMs] = useState<number | null>(
null, null,
@@ -184,13 +176,19 @@ export function useAuctionSocket(matchId: string | undefined) {
const [bidLatencyDiagnostics, setBidLatencyDiagnostics] = const [bidLatencyDiagnostics, setBidLatencyDiagnostics] =
useState<BidLatencyDiagnostics | null>(null); useState<BidLatencyDiagnostics | null>(null);
const commitAuctionState = useCallback( function syncLatestConfirmedBidPointAmountFromAuction(
(nextAuction: ApiAuction, source = 'socket-state'): boolean => { nextAuction: ApiAuction,
) {
latestConfirmedBidPointAmountRef.current =
resolveCurrentBidPointAmount(nextAuction);
}
function commitAuctionState(
nextAuction: ApiAuction,
source = 'socket-state',
): boolean {
const currentAuction = latestAuctionRef.current; const currentAuction = latestAuctionRef.current;
const applied = shouldApplyIncomingAuctionState( const applied = shouldApplyIncomingAuctionState(currentAuction, nextAuction);
currentAuction,
nextAuction,
);
const currentRevision = const currentRevision =
typeof currentAuction?.revision === 'number' typeof currentAuction?.revision === 'number'
? currentAuction.revision ? currentAuction.revision
@@ -219,15 +217,12 @@ export function useAuctionSocket(matchId: string | undefined) {
} }
latestAuctionRef.current = nextAuction; latestAuctionRef.current = nextAuction;
latestConfirmedBidPointAmountRef.current = syncLatestConfirmedBidPointAmountFromAuction(nextAuction);
resolveCurrentBidPointAmount(nextAuction);
setAuction(nextAuction); setAuction(nextAuction);
return true; return true;
}, }
[matchId],
);
const commitBidDelta = useCallback((payload: BidDeltaPayload): boolean => { function commitBidDelta(payload: BidDeltaPayload): boolean {
const currentAuction = latestAuctionRef.current; const currentAuction = latestAuctionRef.current;
const nextAuction = applyBidDelta(currentAuction, payload); const nextAuction = applyBidDelta(currentAuction, payload);
if (!nextAuction || nextAuction === currentAuction) { if (!nextAuction || nextAuction === currentAuction) {
@@ -235,18 +230,10 @@ export function useAuctionSocket(matchId: string | undefined) {
} }
latestAuctionRef.current = nextAuction; latestAuctionRef.current = nextAuction;
latestConfirmedBidPointAmountRef.current = syncLatestConfirmedBidPointAmountFromAuction(nextAuction);
resolveCurrentBidPointAmount(nextAuction);
setAuction(nextAuction); setAuction(nextAuction);
return true; return true;
}, []); }
const setError = useCallback(
(message: string | null) => {
setErrorState({ key: connectionKey ?? '', message });
},
[connectionKey],
);
function applyFallbackServerTimestamp(currentServerTimestampMS?: number) { function applyFallbackServerTimestamp(currentServerTimestampMS?: number) {
if (hasSyncedServerTimeRef.current) return; if (hasSyncedServerTimeRef.current) return;
@@ -358,47 +345,14 @@ export function useAuctionSocket(matchId: string | undefined) {
}); });
} }
const clearPendingBidRequest = useCallback((bidRequestId: string) => {
const timeoutId = pendingBidTimeoutsRef.current[bidRequestId];
if (timeoutId) clearTimeout(timeoutId);
delete pendingBidTimeoutsRef.current[bidRequestId];
setPendingBidRequests((current) => {
const next = { ...current };
delete next[bidRequestId];
return next;
});
}, []);
const clearPendingActionRequest = useCallback(
(auctionActionRequestId: string) => {
const timeoutId =
pendingActionTimeoutsRef.current[auctionActionRequestId];
if (timeoutId) clearTimeout(timeoutId);
delete pendingActionTimeoutsRef.current[auctionActionRequestId];
setPendingActionRequests((current) => {
const next = { ...current };
delete next[auctionActionRequestId];
return next;
});
},
[],
);
const clearPendingActionRequests = useCallback(() => {
Object.values(pendingActionTimeoutsRef.current).forEach((timeoutId) =>
clearTimeout(timeoutId),
);
pendingActionTimeoutsRef.current = {};
setPendingActionRequests({});
}, []);
useEffect(() => { useEffect(() => {
if (!matchId || !connectionKey) { if (!matchId) {
return; return;
} }
const activeConnectionKey = connectionKey;
let disposed = false; let disposed = false;
setConnectionStatus('connecting');
setError(null);
void (async () => { void (async () => {
const accessToken = await acquireAccessToken().catch((error) => { const accessToken = await acquireAccessToken().catch((error) => {
@@ -419,11 +373,7 @@ export function useAuctionSocket(matchId: string | undefined) {
socketRef.current = socket; socketRef.current = socket;
socket.on('connect', () => { socket.on('connect', () => {
setConnectionState({ setConnectionStatus('connected');
key: activeConnectionKey,
status: 'connected',
});
setError(null);
socket.emit('join', { matchId }); socket.emit('join', { matchId });
requestServerTimeSync(socket); requestServerTimeSync(socket);
if (timeSyncIntervalRef.current) { if (timeSyncIntervalRef.current) {
@@ -437,10 +387,7 @@ export function useAuctionSocket(matchId: string | undefined) {
socket.on('disconnect', () => { socket.on('disconnect', () => {
clearTimeSyncTimers(); clearTimeSyncTimers();
setConnectionState({ setConnectionStatus('disconnected');
key: activeConnectionKey,
status: 'disconnected',
});
}); });
socket.on('state', (nextAuction: ApiAuction) => { socket.on('state', (nextAuction: ApiAuction) => {
@@ -573,20 +520,42 @@ export function useAuctionSocket(matchId: string | undefined) {
hasSyncedServerTimeRef.current = false; hasSyncedServerTimeRef.current = false;
setPendingBidRequests({}); setPendingBidRequests({});
setPendingActionRequests({}); setPendingActionRequests({});
setConnectionStatus('idle');
setServerTimeOffsetMs(0); setServerTimeOffsetMs(0);
setServerRoundTripMs(null); setServerRoundTripMs(null);
setBidLatencyDiagnostics(null); setBidLatencyDiagnostics(null);
}; };
}, [ }, [authUserId, matchId]);
authUserId,
clearPendingActionRequests, function clearPendingBidRequest(bidRequestId: string) {
clearPendingBidRequest, const timeoutId = pendingBidTimeoutsRef.current[bidRequestId];
commitAuctionState, if (timeoutId) clearTimeout(timeoutId);
commitBidDelta, delete pendingBidTimeoutsRef.current[bidRequestId];
connectionKey, setPendingBidRequests((current) => {
matchId, const next = { ...current };
setError, delete next[bidRequestId];
]); return next;
});
}
function clearPendingActionRequest(auctionActionRequestId: string) {
const timeoutId = pendingActionTimeoutsRef.current[auctionActionRequestId];
if (timeoutId) clearTimeout(timeoutId);
delete pendingActionTimeoutsRef.current[auctionActionRequestId];
setPendingActionRequests((current) => {
const next = { ...current };
delete next[auctionActionRequestId];
return next;
});
}
function clearPendingActionRequests() {
Object.values(pendingActionTimeoutsRef.current).forEach((timeoutId) =>
clearTimeout(timeoutId),
);
pendingActionTimeoutsRef.current = {};
setPendingActionRequests({});
}
function emit(eventName: string, payload?: unknown) { function emit(eventName: string, payload?: unknown) {
const socket = socketRef.current; const socket = socketRef.current;
@@ -768,16 +737,9 @@ export function useAuctionSocket(matchId: string | undefined) {
const currentAuction = auction; const currentAuction = auction;
const visibleAuction = const visibleAuction =
currentAuction && currentAuction.matchId === matchId ? currentAuction : null; currentAuction && currentAuction.matchId === matchId ? currentAuction : null;
const visibleConnectionStatus: ConnectionStatus = const visibleConnectionStatus: ConnectionStatus = matchId
connectionKey === null ? connectionStatus
? 'idle' : 'idle';
: connectionState.key === connectionKey
? connectionState.status
: 'connecting';
const visibleError =
connectionKey !== null && errorState.key === connectionKey
? errorState.message
: null;
return { return {
auction: visibleAuction, auction: visibleAuction,
@@ -788,7 +750,7 @@ export function useAuctionSocket(matchId: string | undefined) {
pendingBidRequests, pendingBidRequests,
resetAt, resetAt,
connectionStatus: visibleConnectionStatus, connectionStatus: visibleConnectionStatus,
error: visibleError, error,
bidLatencyDiagnostics, bidLatencyDiagnostics,
serverRoundTripMs: matchId ? serverRoundTripMs : null, serverRoundTripMs: matchId ? serverRoundTripMs : null,
serverTimeOffsetMs: matchId ? serverTimeOffsetMs : 0, serverTimeOffsetMs: matchId ? serverTimeOffsetMs : 0,
+19 -37
View File
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { io } from 'socket.io-client'; import { io, type Socket } from 'socket.io-client';
import { API_BASE_URL } from '../config'; import { API_BASE_URL } from '../config';
import type { ApiRiotRefreshEvent } from './types'; import type { ApiRiotRefreshEvent } from './types';
@@ -19,43 +19,37 @@ export function useRiotRefreshSocket({
parentJobId?: string; parentJobId?: string;
onEvent: (event: ApiRiotRefreshEvent) => void; onEvent: (event: ApiRiotRefreshEvent) => void;
}) { }) {
const subscriptionKey = const socketRef = useRef<Socket | null>(null);
puuid || parentJobId ? JSON.stringify([puuid, parentJobId]) : null;
const onEventRef = useRef(onEvent); const onEventRef = useRef(onEvent);
const [connectionState, setConnectionState] = useState<{ const [connectionStatus, setConnectionStatus] =
key: string; useState<ConnectionStatus>('idle');
status: ConnectionStatus; const [error, setError] = useState<string | null>(null);
error: string | null;
}>({ key: '', status: 'idle', error: null });
useEffect(() => { useEffect(() => {
onEventRef.current = onEvent; onEventRef.current = onEvent;
}, [onEvent]); }, [onEvent]);
useEffect(() => { useEffect(() => {
if (!subscriptionKey) { if (!puuid && !parentJobId) {
setConnectionStatus('idle');
return; return;
} }
setConnectionStatus('connecting');
setError(null);
const socket = io(`${API_BASE_URL}/riot-refresh`, { const socket = io(`${API_BASE_URL}/riot-refresh`, {
transports: ['websocket'], transports: ['websocket'],
}); });
socketRef.current = socket;
socket.on('connect', () => { socket.on('connect', () => {
setConnectionState({ setConnectionStatus('connected');
key: subscriptionKey,
status: 'connected',
error: null,
});
socket.emit('subscribe', { puuid, parentJobId }); socket.emit('subscribe', { puuid, parentJobId });
}); });
socket.on('disconnect', () => { socket.on('disconnect', () => {
setConnectionState((current) => ({ setConnectionStatus('disconnected');
key: subscriptionKey,
status: 'disconnected',
error: current.key === subscriptionKey ? current.error : null,
}));
}); });
socket.on('riot-refresh', (event: ApiRiotRefreshEvent) => { socket.on('riot-refresh', (event: ApiRiotRefreshEvent) => {
@@ -63,29 +57,17 @@ export function useRiotRefreshSocket({
}); });
socket.on('error', (payload: { message?: string }) => { socket.on('error', (payload: { message?: string }) => {
setConnectionState({ setConnectionStatus('error');
key: subscriptionKey, setError(payload.message ?? '전적 갱신 소켓 연결 중 오류가 발생했습니다.');
status: 'error',
error:
payload.message ?? '전적 갱신 소켓 연결 중 오류가 발생했습니다.',
});
}); });
return () => { return () => {
socket.removeAllListeners(); socket.removeAllListeners();
socket.disconnect(); socket.disconnect();
socketRef.current = null;
setConnectionStatus('idle');
}; };
}, [parentJobId, puuid, subscriptionKey]); }, [parentJobId, puuid]);
const hasCurrentConnection = return { connectionStatus, error };
subscriptionKey !== null && connectionState.key === subscriptionKey;
return {
connectionStatus:
subscriptionKey === null
? 'idle'
: hasCurrentConnection
? connectionState.status
: 'connecting',
error: hasCurrentConnection ? connectionState.error : null,
};
} }
+7 -17
View File
@@ -1,30 +1,20 @@
import { useState } from 'react'; import { useEffect, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query'; import { useQueryClient } from '@tanstack/react-query';
import { setAuthUserId, useAuthUserId } from '../config'; import { setAuthUserId, useAuthUserId } from '../config';
export default function DevAuthSwitcher() { export default function DevAuthSwitcher() {
const authUserId = useAuthUserId(); const authUserId = useAuthUserId();
const queryClient = useQueryClient();
const [inputValue, setInputValue] = useState(authUserId ?? '');
useEffect(() => {
setInputValue(authUserId ?? '');
}, [authUserId]);
if (!import.meta.env.DEV) { if (!import.meta.env.DEV) {
return null; return null;
} }
return (
<DevAuthSwitcherForm
key={authUserId ?? 'no-auth-user'}
authUserId={authUserId}
/>
);
}
function DevAuthSwitcherForm({
authUserId,
}: {
authUserId: string | null;
}) {
const queryClient = useQueryClient();
const [inputValue, setInputValue] = useState(authUserId ?? '');
function updateAuthUserId(nextValue: string | null) { function updateAuthUserId(nextValue: string | null) {
setAuthUserId(nextValue); setAuthUserId(nextValue);
void queryClient.invalidateQueries(); void queryClient.invalidateQueries();
+44 -1
View File
@@ -1,9 +1,21 @@
import type { ApiTierInfo } from "../api/types"; import type { ApiTierInfo } from "../api/types";
import { formatRankBadge, formatRankDetail } from "./rankBadgeUtils";
type RankBadgeSize = "sm" | "md"; type RankBadgeSize = "sm" | "md";
type RankBadgeTooltipPlacement = "left" | "bottom"; type RankBadgeTooltipPlacement = "left" | "bottom";
const TIER_NAMES: Record<string, string> = {
IRON: "아이언",
BRONZE: "브론즈",
SILVER: "실버",
GOLD: "골드",
PLATINUM: "플래티넘",
EMERALD: "에메랄드",
DIAMOND: "다이아몬드",
MASTER: "마스터",
GRANDMASTER: "그랜드마스터",
CHALLENGER: "챌린저",
};
const SIZE_CLASSES: Record<RankBadgeSize, string> = { const SIZE_CLASSES: Record<RankBadgeSize, string> = {
sm: "h-[17px] min-w-[18px]", sm: "h-[17px] min-w-[18px]",
md: "h-[18px] min-w-[20px]", md: "h-[18px] min-w-[20px]",
@@ -14,6 +26,21 @@ const TOOLTIP_CLASSES: Record<RankBadgeTooltipPlacement, string> = {
bottom: "tooltip-bottom", bottom: "tooltip-bottom",
}; };
function normalizeRank(rank: string | undefined) {
switch (rank) {
case "I":
return "1";
case "II":
return "2";
case "III":
return "3";
case "IV":
return "4";
default:
return rank;
}
}
function rankBadgeClass(tier: ApiTierInfo | undefined) { function rankBadgeClass(tier: ApiTierInfo | undefined) {
switch (tier?.tier) { switch (tier?.tier) {
case "CHALLENGER": case "CHALLENGER":
@@ -41,6 +68,22 @@ function rankBadgeClass(tier: ApiTierInfo | undefined) {
} }
} }
export function formatRankBadge(tier: ApiTierInfo | undefined) {
if (!tier) return "U";
const tierInitial =
tier.tier === "GRANDMASTER" ? "GM" : tier.tier.slice(0, 1);
const rank = normalizeRank(tier.rank);
return rank ? `${tierInitial}${rank}` : tierInitial;
}
export function formatRankDetail(tier: ApiTierInfo | undefined) {
if (!tier) return "랭크 정보 없음";
const tierName = TIER_NAMES[tier.tier] ?? tier.tier;
const rank = normalizeRank(tier.rank);
const label = rank ? `${tierName} ${rank}` : tierName;
return `${label} - ${tier.leaguePoints} LP`;
}
export function RankBadge({ export function RankBadge({
tier, tier,
size = "md", size = "md",
+9 -21
View File
@@ -67,7 +67,6 @@ const TIER_COMPACT_NAMES: Record<string, string> = {
}; };
type PeriodKey = "30" | "90" | "all"; type PeriodKey = "30" | "90" | "all";
type PeriodFilter = { key: PeriodKey; cutoffTimestamp: number };
type SummaryVariant = "footer" | "inline"; type SummaryVariant = "footer" | "inline";
type SummaryDirection = "up" | "down" | "flat"; type SummaryDirection = "up" | "down" | "flat";
@@ -315,17 +314,18 @@ export default function TierHistoryChart({
const [queue, setQueue] = useState( const [queue, setQueue] = useState(
availableQueues[0] ?? "RANKED_SOLO_5x5", availableQueues[0] ?? "RANKED_SOLO_5x5",
); );
const [periodFilter, setPeriodFilter] = useState<PeriodFilter>({ const [period, setPeriod] = useState<PeriodKey>("all");
key: "all",
cutoffTimestamp: 0,
});
const period = periodFilter.key;
const activeQueue = availableQueues.includes(queue) const activeQueue = availableQueues.includes(queue)
? queue ? queue
: (availableQueues[0] ?? "RANKED_SOLO_5x5"); : (availableQueues[0] ?? "RANKED_SOLO_5x5");
const points = useMemo<ChartPoint[]>(() => { const points = useMemo<ChartPoint[]>(() => {
const periodDays =
PERIOD_OPTIONS.find((option) => option.key === period)?.days ?? null;
const cutoff =
periodDays === null ? 0 : Date.now() - periodDays * 24 * 60 * 60 * 1000;
return entries return entries
.filter((entry) => entry.queueType === activeQueue) .filter((entry) => entry.queueType === activeQueue)
.map((entry) => ({ .map((entry) => ({
@@ -337,9 +337,9 @@ export default function TierHistoryChart({
wins: entry.wins, wins: entry.wins,
losses: entry.losses, losses: entry.losses,
})) }))
.filter((point) => point.ts >= periodFilter.cutoffTimestamp) .filter((point) => point.ts >= cutoff)
.sort((left, right) => left.ts - right.ts); .sort((left, right) => left.ts - right.ts);
}, [entries, activeQueue, periodFilter.cutoffTimestamp]); }, [entries, activeQueue, period]);
// 티어 경계(가로 점선) 후보 — 데이터 범위 안에 드는 티어 floor만. // 티어 경계(가로 점선) 후보 — 데이터 범위 안에 드는 티어 floor만.
const tierLines = useMemo(() => { const tierLines = useMemo(() => {
@@ -408,19 +408,7 @@ export default function TierHistoryChart({
<select <select
className="h-7 border border-base-content/10 bg-base-100 px-2 text-xs text-base-content focus:border-primary/30 focus:outline-none" className="h-7 border border-base-content/10 bg-base-100 px-2 text-xs text-base-content focus:border-primary/30 focus:outline-none"
value={period} value={period}
onChange={(event) => { onChange={(event) => setPeriod(event.target.value as PeriodKey)}
const nextPeriod = event.target.value as PeriodKey;
const days =
PERIOD_OPTIONS.find((option) => option.key === nextPeriod)
?.days ?? null;
setPeriodFilter({
key: nextPeriod,
cutoffTimestamp:
days === null
? 0
: Date.now() - days * 24 * 60 * 60 * 1000,
});
}}
> >
{PERIOD_OPTIONS.map((option) => ( {PERIOD_OPTIONS.map((option) => (
<option key={option.key} value={option.key}> <option key={option.key} value={option.key}>
@@ -104,7 +104,11 @@ export function SeriesScoreCard({
{presentation.label} {presentation.label}
</span> </span>
</header> </header>
<div className="divide-y divide-base-content/8"> <div
className={
isBracket ? "relative" : "divide-y divide-base-content/8"
}
>
{series.entries.map((entry) => { {series.entries.map((entry) => {
const team = entry.teamId ? teamById.get(entry.teamId) : undefined; const team = entry.teamId ? teamById.get(entry.teamId) : undefined;
const isWinner = isSeriesEntryWinner(series, entry.teamId); const isWinner = isSeriesEntryWinner(series, entry.teamId);
@@ -129,6 +133,13 @@ export function SeriesScoreCard({
/> />
); );
})} })}
{isBracket && (
<span
className="pointer-events-none absolute inset-x-0 border-t border-base-content/8"
style={{ top: SERIES_SCORE_CARD_GEOMETRY.entryHeight }}
aria-hidden="true"
/>
)}
</div> </div>
</article> </article>
); );
@@ -17,6 +17,8 @@ export const DOUBLE_ELIMINATION_BRACKET_GEOMETRY = {
boardPadding: 12, boardPadding: 12,
columnWidth: 228, columnWidth: 228,
columnGap: 40, columnGap: 40,
// Matches the widest focused connector underlay so parallel routes stay legible.
connectorRailClearance: 5,
cardBorderWidth: SERIES_SCORE_CARD_GEOMETRY.borderWidth, cardBorderWidth: SERIES_SCORE_CARD_GEOMETRY.borderWidth,
cardHeight: SERIES_SCORE_CARD_GEOMETRY.height, cardHeight: SERIES_SCORE_CARD_GEOMETRY.height,
cardHeaderHeight: SERIES_SCORE_CARD_GEOMETRY.headerHeight, cardHeaderHeight: SERIES_SCORE_CARD_GEOMETRY.headerHeight,
@@ -109,6 +111,29 @@ interface NormalizedRound {
seriesIds: SeriesId[]; seriesIds: SeriesId[];
} }
interface ConnectorRoute {
connector: SeriesConnectorView;
key: string;
kind: BracketConnectorKind;
targetColumn: number;
targetNodeY: number;
sourceX: number;
sourceY: number;
targetX: number;
targetY: number;
}
interface SeparateWinnerRailChoice {
verticalXs: [number, number];
crossings: number;
distanceFromBaseline: number;
distanceFromCenter: number;
}
type OrthogonalSegment =
| { orientation: "horizontal"; fixed: number; start: number; end: number }
| { orientation: "vertical"; fixed: number; start: number; end: number };
const STAGE_ORDER: Record<BracketStage, number> = { const STAGE_ORDER: Record<BracketStage, number> = {
upper: 0, upper: 0,
lower: 1, lower: 1,
@@ -126,6 +151,9 @@ const CONNECTOR_SELECTION_ORDER: Record<
"slot-b": 3, "slot-b": 3,
}; };
// A focused 5px underlay extends 2.5px from its centerline.
const CONNECTOR_RAIL_EDGE_INSET = 3;
export function createDoubleEliminationBracketLayout( export function createDoubleEliminationBracketLayout(
projection: DoubleEliminationCompetitionProjection, projection: DoubleEliminationCompetitionProjection,
configuration: DoubleEliminationBracketConfiguration, configuration: DoubleEliminationBracketConfiguration,
@@ -540,56 +568,53 @@ function buildConnectors(
nodeById: Map<SeriesId, BracketNodeLayout>, nodeById: Map<SeriesId, BracketNodeLayout>,
): BracketConnectorLayout[] | null { ): BracketConnectorLayout[] | null {
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY; const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
const connectorsByTargetColumn = new Map< const routes: ConnectorRoute[] = [];
number, const routesByTargetColumn = new Map<number, ConnectorRoute[]>();
Array<{
connector: SeriesConnectorView;
source: BracketNodeLayout;
target: BracketNodeLayout;
}>
>();
for (const connector of projection.connectors) { for (const connector of projection.connectors) {
const source = nodeById.get(connector.from.seriesId); const source = nodeById.get(connector.from.seriesId);
const target = nodeById.get(connector.to.seriesId); const target = nodeById.get(connector.to.seriesId);
if (!source || !target || target.column <= source.column) return null; if (!source || !target || target.column <= source.column) return null;
const routes = connectorsByTargetColumn.get(target.column) ?? []; const route = {
routes.push({ connector, source, target }); connector,
connectorsByTargetColumn.set(target.column, routes); key: connectorKey(connector),
kind: connectorKind(connector.from.select),
targetColumn: target.column,
targetNodeY: target.y,
sourceX: source.x + source.width,
sourceY: connectorAnchorY(source, connector.from.select),
targetX: target.x,
targetY: targetSlotY(target, connector.to.slot),
} satisfies ConnectorRoute;
routes.push(route);
const columnRoutes = routesByTargetColumn.get(target.column) ?? [];
columnRoutes.push(route);
routesByTargetColumn.set(target.column, columnRoutes);
} }
const verticalXByConnector = new Map<string, number>(); const verticalXByConnector = new Map<string, number>();
for (const routes of connectorsByTargetColumn.values()) { for (const columnRoutes of routesByTargetColumn.values()) {
routes.sort( columnRoutes.sort(
(left, right) => (left, right) =>
connectorAnchorY(right.source, right.connector.from.select) - right.sourceY - left.sourceY ||
connectorAnchorY(left.source, left.connector.from.select) || right.targetY - left.targetY ||
targetSlotY(right.target, right.connector.to.slot) - left.key.localeCompare(right.key),
targetSlotY(left.target, left.connector.to.slot) ||
connectorKey(left.connector).localeCompare(connectorKey(right.connector)),
); );
routes.forEach(({ connector, target }, index) => { columnRoutes.forEach(({ key, targetX }, index) => {
verticalXByConnector.set( verticalXByConnector.set(
connectorKey(connector), key,
target.x - targetX -
geometry.columnGap + geometry.columnGap +
(geometry.columnGap * (index + 1)) / (routes.length + 1), (geometry.columnGap * (index + 1)) / (columnRoutes.length + 1),
); );
}); });
} }
if (!alignWinnerBundleRails(routes, verticalXByConnector)) return null;
const result: BracketConnectorLayout[] = []; const result: BracketConnectorLayout[] = [];
for (const connector of projection.connectors) { for (const route of routes) {
const source = nodeById.get(connector.from.seriesId); const { connector, key, kind, sourceX, sourceY, targetX, targetY } = route;
const target = nodeById.get(connector.to.seriesId); const verticalX = verticalXByConnector.get(key);
if (!source || !target || target.column <= source.column) return null;
const sourceX = source.x + source.width;
const targetX = target.x;
const sourceY = connectorAnchorY(source, connector.from.select);
const targetY = targetSlotY(target, connector.to.slot);
const verticalX = verticalXByConnector.get(connectorKey(connector));
if (verticalX === undefined) return null; if (verticalX === undefined) return null;
const kind = connectorKind(connector.from.select);
result.push({ result.push({
fromSeriesId: connector.from.seriesId, fromSeriesId: connector.from.seriesId,
select: connector.from.select, select: connector.from.select,
@@ -622,6 +647,324 @@ function buildConnectors(
); );
} }
function alignWinnerBundleRails(
routes: readonly ConnectorRoute[],
verticalXByConnector: Map<string, number>,
): boolean {
const winnersByTarget = new Map<SeriesId, ConnectorRoute[]>();
for (const route of routes) {
if (route.kind !== "winner") continue;
const winners = winnersByTarget.get(route.connector.to.seriesId) ?? [];
winners.push(route);
winnersByTarget.set(route.connector.to.seriesId, winners);
}
const bundles = [...winnersByTarget.values()]
.filter(
(winners) =>
winners.length === 2 &&
winners[0].connector.to.slot !== winners[1].connector.to.slot,
)
.sort(
(left, right) =>
left[0].targetColumn - right[0].targetColumn ||
left[0].targetNodeY - right[0].targetNodeY ||
left[0].key.localeCompare(right[0].key),
);
for (const bundle of bundles) {
const preferredX =
bundle[0].targetX - DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2;
if (
intervalsOverlap(
bundle[0].sourceY,
bundle[0].targetY,
bundle[1].sourceY,
bundle[1].targetY,
)
) {
const assignment = chooseSeparateWinnerRails(
bundle,
routes,
verticalXByConnector,
preferredX,
);
if (!assignment) return false;
for (const [key, verticalX] of assignment) {
verticalXByConnector.set(key, verticalX);
}
continue;
}
const verticalX = chooseWinnerBundleRail(
bundle,
routes,
verticalXByConnector,
preferredX,
);
if (verticalX === null) return false;
for (const route of bundle) verticalXByConnector.set(route.key, verticalX);
}
return true;
}
function chooseWinnerBundleRail(
bundle: readonly ConnectorRoute[],
routes: readonly ConnectorRoute[],
verticalXByConnector: Map<string, number>,
preferredX: number,
): number | null {
const previousRails = bundle.map((route) =>
verticalXByConnector.get(route.key),
);
if (previousRails.some((verticalX) => verticalX === undefined)) return null;
const previousScore = connectorConflictScore(routes, verticalXByConnector);
// Keep the existing crossing budget, then favor stroke-clear rails nearest center.
let best:
| {
verticalX: number;
crossings: number;
clearanceConflicts: number;
distanceFromCenter: number;
}
| null = null;
for (const candidateX of winnerRailCandidates(preferredX)) {
for (const route of bundle) {
verticalXByConnector.set(route.key, candidateX);
}
const score = connectorConflictScore(routes, verticalXByConnector);
if (
score.overlaps !== 0 ||
score.crossings > previousScore.crossings ||
score.clearanceConflicts > previousScore.clearanceConflicts
) {
continue;
}
const distanceFromCenter = Math.abs(candidateX - preferredX);
if (
!best ||
score.clearanceConflicts < best.clearanceConflicts ||
(score.clearanceConflicts === best.clearanceConflicts &&
(score.crossings < best.crossings ||
(score.crossings === best.crossings &&
distanceFromCenter < best.distanceFromCenter)))
) {
best = {
verticalX: candidateX,
crossings: score.crossings,
clearanceConflicts: score.clearanceConflicts,
distanceFromCenter,
};
}
}
if (best) return best.verticalX;
bundle.forEach((route, index) => {
const previousX = previousRails[index];
if (previousX !== undefined) {
verticalXByConnector.set(route.key, previousX);
}
});
return null;
}
function winnerRailCandidates(preferredX: number): number[] {
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
const maximumOffset =
geometry.columnGap / 2 - CONNECTOR_RAIL_EDGE_INSET;
const candidates = [preferredX];
for (let offset = 1; offset <= maximumOffset; offset += 1) {
candidates.push(preferredX - offset, preferredX + offset);
}
return candidates;
}
function chooseSeparateWinnerRails(
bundle: readonly ConnectorRoute[],
routes: readonly ConnectorRoute[],
verticalXByConnector: Map<string, number>,
preferredX: number,
): Map<string, number> | null {
const orderedBundle = [...bundle].sort(
(left, right) =>
left.sourceY - right.sourceY ||
left.targetY - right.targetY ||
left.key.localeCompare(right.key),
);
const previousRails: number[] = [];
for (const route of orderedBundle) {
const previousX = verticalXByConnector.get(route.key);
if (previousX === undefined) return null;
previousRails.push(previousX);
}
const previousScore = connectorConflictScore(routes, verticalXByConnector);
const bundleKeys = new Set(orderedBundle.map(({ key }) => key));
const candidates = [
...new Set([...previousRails, ...winnerRailCandidates(preferredX)]),
];
let best: SeparateWinnerRailChoice | null = null;
for (const firstX of candidates) {
for (const secondX of candidates) {
if (firstX === secondX) continue;
verticalXByConnector.set(orderedBundle[0].key, firstX);
verticalXByConnector.set(orderedBundle[1].key, secondX);
const bundleScore = connectorConflictScore(
routes,
verticalXByConnector,
bundleKeys,
);
const score = connectorConflictScore(routes, verticalXByConnector);
if (
bundleScore.overlaps !== 0 ||
bundleScore.clearanceConflicts !== 0 ||
score.overlaps !== 0 ||
score.crossings > previousScore.crossings
) {
continue;
}
const distanceFromBaseline =
Math.abs(firstX - previousRails[0]) +
Math.abs(secondX - previousRails[1]);
const distanceFromCenter =
Math.abs(firstX - preferredX) + Math.abs(secondX - preferredX);
const candidate: SeparateWinnerRailChoice = {
verticalXs: [firstX, secondX],
crossings: score.crossings,
distanceFromBaseline,
distanceFromCenter,
};
if (!best || compareSeparateWinnerRailChoices(candidate, best) < 0) {
best = candidate;
}
}
}
orderedBundle.forEach((route, index) => {
verticalXByConnector.set(route.key, previousRails[index]);
});
if (!best) return null;
return new Map(
orderedBundle.map((route, index) => [route.key, best.verticalXs[index]]),
);
}
function compareSeparateWinnerRailChoices(
left: SeparateWinnerRailChoice,
right: SeparateWinnerRailChoice,
): number {
return (
left.crossings - right.crossings ||
left.distanceFromBaseline - right.distanceFromBaseline ||
left.distanceFromCenter - right.distanceFromCenter ||
left.verticalXs[0] - right.verticalXs[0] ||
left.verticalXs[1] - right.verticalXs[1]
);
}
function connectorConflictScore(
routes: readonly ConnectorRoute[],
verticalXByConnector: ReadonlyMap<string, number>,
focusedRouteKeys?: ReadonlySet<string>,
): { crossings: number; overlaps: number; clearanceConflicts: number } {
let crossings = 0;
let overlaps = 0;
let clearanceConflicts = 0;
for (let leftIndex = 0; leftIndex < routes.length; leftIndex += 1) {
const leftX = verticalXByConnector.get(routes[leftIndex].key);
if (leftX === undefined) continue;
const leftSegments = connectorRouteSegments(routes[leftIndex], leftX);
for (
let rightIndex = leftIndex + 1;
rightIndex < routes.length;
rightIndex += 1
) {
if (
focusedRouteKeys &&
!focusedRouteKeys.has(routes[leftIndex].key) &&
!focusedRouteKeys.has(routes[rightIndex].key)
) {
continue;
}
const rightX = verticalXByConnector.get(routes[rightIndex].key);
if (rightX === undefined) continue;
const rightSegments = connectorRouteSegments(routes[rightIndex], rightX);
for (const left of leftSegments) {
for (const right of rightSegments) {
if (left.orientation === right.orientation) {
const overlapLength =
Math.min(left.end, right.end) - Math.max(left.start, right.start);
if (left.fixed === right.fixed && overlapLength > 0) {
overlaps += 1;
} else if (
left.orientation === "vertical" &&
overlapLength > 0 &&
Math.abs(left.fixed - right.fixed) <
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.connectorRailClearance
) {
clearanceConflicts += 1;
}
continue;
}
const horizontal =
left.orientation === "horizontal" ? left : right;
const vertical = left.orientation === "vertical" ? left : right;
if (
vertical.fixed > horizontal.start &&
vertical.fixed < horizontal.end &&
horizontal.fixed > vertical.start &&
horizontal.fixed < vertical.end
) {
crossings += 1;
}
}
}
}
}
return { crossings, overlaps, clearanceConflicts };
}
function connectorRouteSegments(
route: ConnectorRoute,
verticalX: number,
): OrthogonalSegment[] {
return [
orthogonalSegment("horizontal", route.sourceY, route.sourceX, verticalX),
orthogonalSegment("vertical", verticalX, route.sourceY, route.targetY),
orthogonalSegment("horizontal", route.targetY, verticalX, route.targetX),
];
}
function orthogonalSegment(
orientation: OrthogonalSegment["orientation"],
fixed: number,
first: number,
second: number,
): OrthogonalSegment {
return {
orientation,
fixed,
start: Math.min(first, second),
end: Math.max(first, second),
};
}
function intervalsOverlap(
firstStart: number,
firstEnd: number,
secondStart: number,
secondEnd: number,
): boolean {
return (
Math.min(firstStart, firstEnd) < Math.max(secondStart, secondEnd) &&
Math.min(secondStart, secondEnd) < Math.max(firstStart, firstEnd)
);
}
function connectorLabel( function connectorLabel(
connector: SeriesConnectorView, connector: SeriesConnectorView,
graph: ValidatedGraph, graph: ValidatedGraph,
-45
View File
@@ -1,45 +0,0 @@
import type { ApiTierInfo } from "../api/types";
const TIER_NAMES: Record<string, string> = {
IRON: "아이언",
BRONZE: "브론즈",
SILVER: "실버",
GOLD: "골드",
PLATINUM: "플래티넘",
EMERALD: "에메랄드",
DIAMOND: "다이아몬드",
MASTER: "마스터",
GRANDMASTER: "그랜드마스터",
CHALLENGER: "챌린저",
};
function normalizeRank(rank: string | undefined) {
switch (rank) {
case "I":
return "1";
case "II":
return "2";
case "III":
return "3";
case "IV":
return "4";
default:
return rank;
}
}
export function formatRankBadge(tier: ApiTierInfo | undefined) {
if (!tier) return "U";
const tierInitial =
tier.tier === "GRANDMASTER" ? "GM" : tier.tier.slice(0, 1);
const rank = normalizeRank(tier.rank);
return rank ? `${tierInitial}${rank}` : tierInitial;
}
export function formatRankDetail(tier: ApiTierInfo | undefined) {
if (!tier) return "랭크 정보 없음";
const tierName = TIER_NAMES[tier.tier] ?? tier.tier;
const rank = normalizeRank(tier.rank);
const label = rank ? `${tierName} ${rank}` : tierName;
return `${label} - ${tier.leaguePoints} LP`;
}
+17 -35
View File
@@ -2,7 +2,6 @@ import {
lazy, lazy,
memo, memo,
Suspense, Suspense,
useCallback,
useEffect, useEffect,
useLayoutEffect, useLayoutEffect,
useMemo, useMemo,
@@ -52,8 +51,7 @@ import {
teamIndexLabel, teamIndexLabel,
} from "../lib/league"; } from "../lib/league";
import { internalMatchGamePath } from "../lib/internal-match-routes"; import { internalMatchGamePath } from "../lib/internal-match-routes";
import { RankBadge } from "../components/RankBadge"; import { formatRankDetail, RankBadge } from "../components/RankBadge";
import { formatRankDetail } from "../components/rankBadgeUtils";
import type { import type {
ApiAuction, ApiAuction,
ApiAuctionChatMessage, ApiAuctionChatMessage,
@@ -1618,6 +1616,7 @@ function BidControls({
serverTimeOffsetMs: number; serverTimeOffsetMs: number;
onBid: (teamIndex: number, amount: number) => void; onBid: (teamIndex: number, amount: number) => void;
}) { }) {
const [bidAmount, setBidAmount] = useState(100);
const minBid = state.currentBid + AUCTION_MIN_BID_POINTS; const minBid = state.currentBid + AUCTION_MIN_BID_POINTS;
const activeTeam = captainRole const activeTeam = captainRole
? state.teams.find((team) => team.teamIndex === captainRole.teamIndex) ? state.teams.find((team) => team.teamIndex === captainRole.teamIndex)
@@ -1628,23 +1627,6 @@ function BidControls({
? getReservedPointsAfterCurrentBid(activeTeam) ? getReservedPointsAfterCurrentBid(activeTeam)
: 0; : 0;
const maxBid = activeTeam ? getMaxBidForTeam(activeTeam) : 0; const maxBid = activeTeam ? getMaxBidForTeam(activeTeam) : 0;
const defaultBidAmount = Math.max(minBid, Math.ceil(minBid / 10) * 10);
const bidContextKey = `${activeTeam?.teamIndex ?? "spectator"}:${maxBid}:${minBid}`;
const [bidDraft, setBidDraft] = useState({
contextKey: bidContextKey,
amount: activeTeam
? Math.min(maxBid, defaultBidAmount)
: defaultBidAmount,
});
const bidAmount =
bidDraft.contextKey === bidContextKey
? bidDraft.amount
: activeTeam
? Math.min(maxBid, defaultBidAmount)
: defaultBidAmount;
const setBidAmount = (amount: number) => {
setBidDraft({ contextKey: bidContextKey, amount });
};
const canAffordNextBid = !isActiveTeamFull && maxBid >= minBid; const canAffordNextBid = !isActiveTeamFull && maxBid >= minBid;
const isBidExpired = useIsDeadlineExpired( const isBidExpired = useIsDeadlineExpired(
state.deadline, state.deadline,
@@ -1655,6 +1637,11 @@ function BidControls({
? Math.min(maxBid, Math.max(minBid, bidAmount)) ? Math.min(maxBid, Math.max(minBid, bidAmount))
: Math.max(minBid, bidAmount); : Math.max(minBid, bidAmount);
useEffect(() => {
const nextBid = Math.max(minBid, Math.ceil(minBid / 10) * 10);
setBidAmount(activeTeam ? Math.min(maxBid, nextBid) : nextBid);
}, [activeTeam, maxBid, minBid]);
if (state.phase !== "bidding") return null; if (state.phase !== "bidding") return null;
if (!activeTeam) { if (!activeTeam) {
@@ -1856,10 +1843,7 @@ export default function AuctionPage() {
const resetAuctionMutation = useResetAuction(DEFAULT_COMMUNITY_ID); const resetAuctionMutation = useResetAuction(DEFAULT_COMMUNITY_ID);
const socket = useAuctionSocket(id); const socket = useAuctionSocket(id);
const captainTeamIndex = useDevCaptainTeamIndex(); const captainTeamIndex = useDevCaptainTeamIndex();
const [assignedPositionDraft, setAssignedPositionDraft] = useState<{ const [assignedPosition, setAssignedPosition] = useState<Position>("MID");
playerId: string | null;
position: Position;
}>({ playerId: null, position: "MID" });
const [showCancelModal, setShowCancelModal] = useState(false); const [showCancelModal, setShowCancelModal] = useState(false);
const [cancelConfirmText, setCancelConfirmText] = useState(""); const [cancelConfirmText, setCancelConfirmText] = useState("");
const [undoTargetSequence, setUndoTargetSequence] = useState<number | null>( const [undoTargetSequence, setUndoTargetSequence] = useState<number | null>(
@@ -1869,7 +1853,7 @@ export default function AuctionPage() {
const historyBackTo = `${location.pathname}${location.search}${location.hash}`; const historyBackTo = `${location.pathname}${location.search}${location.hash}`;
const canConfirmAuctionCancel = cancelConfirmText.trim() === "예"; const canConfirmAuctionCancel = cancelConfirmText.trim() === "예";
const clearAuctionDataAfterCancel = useCallback(async () => { async function clearAuctionDataAfterCancel() {
if (!id) return; if (!id) return;
const auctionQueryKey = ["auction", DEFAULT_COMMUNITY_ID, id] as const; const auctionQueryKey = ["auction", DEFAULT_COMMUNITY_ID, id] as const;
const auctionHistoryQueryKey = [ const auctionHistoryQueryKey = [
@@ -1894,7 +1878,7 @@ export default function AuctionPage() {
queryKey: ["match", DEFAULT_COMMUNITY_ID, id], queryKey: ["match", DEFAULT_COMMUNITY_ID, id],
exact: true, exact: true,
}); });
}, [id, queryClient]); }
useEffect(() => { useEffect(() => {
if (!showCancelModal) return; if (!showCancelModal) return;
@@ -1909,14 +1893,6 @@ export default function AuctionPage() {
: null, : null,
[liveAuction, matchQuery.data], [liveAuction, matchQuery.data],
); );
const currentPlayerId = auctionState?.currentPlayer?.id ?? null;
const assignedPosition =
assignedPositionDraft.playerId === currentPlayerId
? assignedPositionDraft.position
: (auctionState?.currentPlayer?.mainPosition ?? "MID");
const setAssignedPosition = (position: Position) => {
setAssignedPositionDraft({ playerId: currentPlayerId, position });
};
const availableTeamIndexes = useMemo(() => { const availableTeamIndexes = useMemo(() => {
const indexes = new Set( const indexes = new Set(
(auctionState?.teams ?? []).map((team) => team.teamIndex), (auctionState?.teams ?? []).map((team) => team.teamIndex),
@@ -1931,6 +1907,12 @@ export default function AuctionPage() {
}; };
const chatSenderLabel = resolveChatSenderLabel(currentUser, captainRole); const chatSenderLabel = resolveChatSenderLabel(currentUser, captainRole);
useEffect(() => {
if (auctionState?.currentPlayer) {
setAssignedPosition(auctionState.currentPlayer.mainPosition);
}
}, [auctionState?.currentPlayer?.id]);
useEffect(() => { useEffect(() => {
if (availableTeamIndexes.length === 0) return; if (availableTeamIndexes.length === 0) return;
if ( if (
@@ -1946,7 +1928,7 @@ export default function AuctionPage() {
void clearAuctionDataAfterCancel().finally(() => { void clearAuctionDataAfterCancel().finally(() => {
navigate(`/match/${id}`, { replace: true }); navigate(`/match/${id}`, { replace: true });
}); });
}, [clearAuctionDataAfterCancel, id, navigate, socket.resetAt]); }, [id, navigate, socket.resetAt]);
if (!DEFAULT_COMMUNITY_ID) { if (!DEFAULT_COMMUNITY_ID) {
return ( return (
+34 -54
View File
@@ -1,4 +1,4 @@
import { useMemo, useState } from 'react'; import { useEffect, useMemo, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query'; import { useQueryClient } from '@tanstack/react-query';
import { Link, useParams } from 'react-router'; import { Link, useParams } from 'react-router';
import { import {
@@ -8,17 +8,11 @@ import {
useMe, useMe,
useStartLegacyImport, useStartLegacyImport,
} from '../../api/hooks'; } from '../../api/hooks';
import type { import type { LegacyImportJob, StartLegacyImportRequest } from '../../api/types';
LegacyImportJob,
LegacyImportMemberWindow,
StartLegacyImportRequest,
} from '../../api/types';
import { DEFAULT_COMMUNITY_ID } from '../../config'; import { DEFAULT_COMMUNITY_ID } from '../../config';
const DEFAULT_START = '2024-05-01T00:00:00.000Z'; const DEFAULT_START = '2024-05-01T00:00:00.000Z';
type MemberWindowOverride = { startTime: string; endTime: string };
function toInputValue(value: string) { function toInputValue(value: string) {
const date = new Date(value); const date = new Date(value);
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60_000); const local = new Date(date.getTime() - date.getTimezoneOffset() * 60_000);
@@ -50,15 +44,6 @@ function progress(job: LegacyImportJob) {
return Math.round((job.processedMembers / job.totalMembers) * 100); return Math.round((job.processedMembers / job.totalMembers) * 100);
} }
function defaultMemberOverride(
member: LegacyImportMemberWindow,
): MemberWindowOverride {
return {
startTime: toInputValue(member.startTime),
endTime: toInputValue(member.endTime),
};
}
function JobCard({ function JobCard({
job, job,
onCancel, onCancel,
@@ -126,7 +111,7 @@ export default function LegacyImportPage() {
const [windowEnd, setWindowEnd] = useState(''); const [windowEnd, setWindowEnd] = useState('');
const [message, setMessage] = useState<string | null>(null); const [message, setMessage] = useState<string | null>(null);
const [overrides, setOverrides] = useState< const [overrides, setOverrides] = useState<
Record<string, MemberWindowOverride> Record<string, { startTime: string; endTime: string }>
>({}); >({});
const currentUser = const currentUser =
meQuery.data?.memberships.find( meQuery.data?.memberships.find(
@@ -146,6 +131,20 @@ export default function LegacyImportPage() {
const cancelMutation = useCancelLegacyImport(communityId); const cancelMutation = useCancelLegacyImport(communityId);
const members = membersQuery.data?.members ?? []; const members = membersQuery.data?.members ?? [];
useEffect(() => {
setOverrides(
Object.fromEntries(
members.map((member) => [
member.userId,
{
startTime: toInputValue(member.startTime),
endTime: toInputValue(member.endTime),
},
]),
),
);
}, [members]);
const manageableMemberships = const manageableMemberships =
meQuery.data?.memberships.filter((membership) => { meQuery.data?.memberships.filter((membership) => {
const role = membership.user.role; const role = membership.user.role;
@@ -181,15 +180,11 @@ export default function LegacyImportPage() {
const payload: StartLegacyImportRequest = { const payload: StartLegacyImportRequest = {
windowStart: fromInputValue(windowStart), windowStart: fromInputValue(windowStart),
windowEnd: fromInputValue(windowEnd), windowEnd: fromInputValue(windowEnd),
memberOverrides: members.map((member) => { memberOverrides: members.map((member) => ({
const override =
overrides[member.userId] ?? defaultMemberOverride(member);
return {
userId: member.userId, userId: member.userId,
startTime: fromInputValue(override.startTime), startTime: fromInputValue(overrides[member.userId]?.startTime ?? ''),
endTime: fromInputValue(override.endTime), endTime: fromInputValue(overrides[member.userId]?.endTime ?? ''),
}; })),
}),
}; };
startMutation.mutate(payload, { startMutation.mutate(payload, {
onSuccess: async (result) => { onSuccess: async (result) => {
@@ -328,14 +323,8 @@ export default function LegacyImportPage() {
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{members.map((member) => { {members.map((member) => (
const override = <tr key={member.userId} className="border-b border-base-content/5">
overrides[member.userId] ?? defaultMemberOverride(member);
return (
<tr
key={member.userId}
className="border-b border-base-content/5"
>
<td className="px-3 py-2 text-sm font-bold"> <td className="px-3 py-2 text-sm font-bold">
{member.displayName} {member.displayName}
</td> </td>
@@ -348,20 +337,16 @@ export default function LegacyImportPage() {
<td className="px-3 py-2"> <td className="px-3 py-2">
<input <input
type="datetime-local" type="datetime-local"
value={override.startTime} value={overrides[member.userId]?.startTime ?? ''}
onChange={(event) => onChange={(event) =>
setOverrides((current) => { setOverrides((current) => ({
const currentOverride =
current[member.userId] ??
defaultMemberOverride(member);
return {
...current, ...current,
[member.userId]: { [member.userId]: {
...currentOverride, ...current[member.userId],
startTime: event.target.value, startTime: event.target.value,
endTime: current[member.userId]?.endTime ?? '',
}, },
}; }))
})
} }
className="border border-base-content/10 bg-transparent px-2 py-1 text-xs" className="border border-base-content/10 bg-transparent px-2 py-1 text-xs"
/> />
@@ -369,27 +354,22 @@ export default function LegacyImportPage() {
<td className="px-3 py-2"> <td className="px-3 py-2">
<input <input
type="datetime-local" type="datetime-local"
value={override.endTime} value={overrides[member.userId]?.endTime ?? ''}
onChange={(event) => onChange={(event) =>
setOverrides((current) => { setOverrides((current) => ({
const currentOverride =
current[member.userId] ??
defaultMemberOverride(member);
return {
...current, ...current,
[member.userId]: { [member.userId]: {
...currentOverride, ...current[member.userId],
startTime: current[member.userId]?.startTime ?? '',
endTime: event.target.value, endTime: event.target.value,
}, },
}; }))
})
} }
className="border border-base-content/10 bg-transparent px-2 py-1 text-xs" className="border border-base-content/10 bg-transparent px-2 py-1 text-xs"
/> />
</td> </td>
</tr> </tr>
); ))}
})}
{members.length === 0 && ( {members.length === 0 && (
<tr> <tr>
<td colSpan={5} className="px-4 py-8 text-center text-sm text-base-content/35"> <td colSpan={5} className="px-4 py-8 text-center text-sm text-base-content/35">
@@ -367,6 +367,7 @@ test("orders mobile groups as winners, losers, grand final, then reset final", (
shuffledLayout.mobileGroups.map((group) => group.seriesIds), shuffledLayout.mobileGroups.map((group) => group.seriesIds),
orderedLayout.mobileGroups.map((group) => group.seriesIds), orderedLayout.mobileGroups.map((group) => group.seriesIds),
); );
assert.deepEqual(shuffledLayout.connectors, orderedLayout.connectors);
assert.deepEqual( assert.deepEqual(
shuffledLayout.mobileGroups.flatMap((group) => group.seriesIds).sort(), shuffledLayout.mobileGroups.flatMap((group) => group.seriesIds).sort(),
shuffled.projection.series.map((series) => series.seriesId).sort(), shuffled.projection.series.map((series) => series.seriesId).sort(),
@@ -474,11 +475,10 @@ test("returns null instead of throwing for an unknown connector discriminator",
); );
}); });
test("keeps connector rails distinct and outside intervening card rectangles", () => { test("keeps connector rails finite and outside intervening card rectangles", () => {
const { projection } = eightTeamProjection(); const { projection } = eightTeamProjection();
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT); const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
const nodes = new Map(layout.nodes.map((node) => [node.seriesId, node])); const nodes = new Map(layout.nodes.map((node) => [node.seriesId, node]));
const routesByTargetColumn = new Map<number, number[]>();
for (const route of layout.connectors) { for (const route of layout.connectors) {
const source = nodes.get(route.fromSeriesId); const source = nodes.get(route.fromSeriesId);
@@ -511,23 +511,256 @@ test("keeps connector rails distinct and outside intervening card rectangles", (
false, false,
); );
} }
}
});
const rails = routesByTargetColumn.get(target.column) ?? []; test("aligns paired winner bends on one shared rail", () => {
rails.push(route.verticalX); const fourTeam = fourTeamProjection();
routesByTargetColumn.set(target.column, rails); const fourTeamLayout = requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT);
for (const targetSeriesId of [fourTeam.ids.WB_FINAL, fourTeam.ids.GF]) {
const routes = winnerRoutesTo(fourTeamLayout, targetSeriesId);
assert.equal(routes.length, 2);
assert.equal(routes[0].verticalX, routes[1].verticalX);
} }
for (const rails of routesByTargetColumn.values()) { const { projection, ids } = eightTeamProjection();
assert.equal(new Set(rails).size, rails.length); const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
for (const targetSeriesId of [
ids.WB_R2_M1,
ids.WB_R2_M2,
ids.WB_FINAL,
ids.LB_R3_M1,
ids.GF,
]) {
const routes = winnerRoutesTo(layout, targetSeriesId);
assert.equal(routes.length, 2);
assert.equal(
routes[0].verticalX,
routes[1].verticalX,
`${targetSeriesId} winner routes must share one bend rail`,
);
}
});
test("keeps reversed winner slots on deterministic non-overlapping rails", () => {
const { projection, ids } = fourTeamProjection();
const reversed = cloneProjection(projection);
const firstWinner = reversed.connectors.find(
({ from, to }) =>
from.seriesId === ids.WB_R1_M1 &&
from.select === "winner" &&
to.seriesId === ids.WB_FINAL,
);
const secondWinner = reversed.connectors.find(
({ from, to }) =>
from.seriesId === ids.WB_R1_M2 &&
from.select === "winner" &&
to.seriesId === ids.WB_FINAL,
);
assert.ok(firstWinner);
assert.ok(secondWinner);
firstWinner.to = { seriesId: ids.WB_FINAL, slot: "B" };
secondWinner.to = { seriesId: ids.WB_FINAL, slot: "A" };
const orderedLayout = requireLayout(reversed, FOUR_TEAM_LAYOUT);
const shuffled = cloneProjection(reversed);
shuffled.connectors = shuffledCopy(shuffled.connectors);
const shuffledLayout = requireLayout(shuffled, FOUR_TEAM_LAYOUT);
const routes = winnerRoutesTo(orderedLayout, ids.WB_FINAL);
assert.equal(routes.length, 2);
assert.equal(new Set(routes.map(({ verticalX }) => verticalX)).size, 2);
assert.equal(countCollinearConnectorOverlaps(orderedLayout.connectors), 0);
assert.deepEqual(shuffledLayout.connectors, orderedLayout.connectors);
});
test("moves reversed winner rails clear of overlapping connector underlays", () => {
const { projection, ids } = eightTeamProjection();
const reversed = cloneProjection(projection);
const firstWinner = reversed.connectors.find(
({ from, to }) =>
from.seriesId === ids.WB_R1_M1 &&
from.select === "winner" &&
to.seriesId === ids.WB_R2_M1,
);
const secondWinner = reversed.connectors.find(
({ from, to }) =>
from.seriesId === ids.WB_R1_M2 &&
from.select === "winner" &&
to.seriesId === ids.WB_R2_M1,
);
assert.ok(firstWinner);
assert.ok(secondWinner);
firstWinner.to = { seriesId: ids.WB_R2_M1, slot: "B" };
secondWinner.to = { seriesId: ids.WB_R2_M1, slot: "A" };
const layout = requireLayout(reversed, EIGHT_TEAM_LAYOUT);
const shuffled = cloneProjection(reversed);
shuffled.connectors = shuffledCopy(shuffled.connectors);
const shuffledLayout = requireLayout(shuffled, EIGHT_TEAM_LAYOUT);
const winners = winnerRoutesTo(layout, ids.WB_R2_M1);
assert.equal(winners.length, 2);
for (const winner of winners) {
for (const route of layout.connectors) {
if (
route === winner ||
!intervalsStrictlyOverlap(
winner.sourceY,
winner.targetY,
route.sourceY,
route.targetY,
)
) {
continue;
}
assert.ok(
Math.abs(winner.verticalX - route.verticalX) >=
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.connectorRailClearance,
`${winner.fromSeriesId} winner rail ${winner.verticalX} is too close to ${route.fromSeriesId} ${route.kind} rail ${route.verticalX}`,
);
}
}
assert.deepEqual(shuffledLayout.connectors, layout.connectors);
});
test("centers conflict-free paired winner bends in the routing gap", () => {
const fourTeam = fourTeamProjection();
const fourTeamLayout = requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT);
const fourTeamGrandFinal = nodeFor(fourTeamLayout, fourTeam.ids.GF);
assert.deepEqual(
winnerRoutesTo(fourTeamLayout, fourTeam.ids.GF).map(
({ verticalX }) => verticalX,
),
[
fourTeamGrandFinal.x -
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2,
fourTeamGrandFinal.x -
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2,
],
);
const { projection, ids } = eightTeamProjection();
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
for (const targetSeriesId of [ids.LB_R3_M1, ids.GF]) {
const target = nodeFor(layout, targetSeriesId);
const expectedVerticalX =
target.x - DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2;
const routes = winnerRoutesTo(layout, targetSeriesId);
assert.equal(routes.length, 2);
assert.deepEqual(
routes.map(({ verticalX }) => verticalX),
[expectedVerticalX, expectedVerticalX],
);
}
});
test("preserves baseline rails for loser and reset paths", () => {
const { projection } = eightTeamProjection({ resetFinal: true });
const layout = requireLayout(projection, EIGHT_TEAM_RESET_LAYOUT);
const nodes = new Map(layout.nodes.map((node) => [node.seriesId, node]));
const routesByTargetColumn = new Map<number, ConnectorLayout[]>();
for (const route of layout.connectors) {
const target = nodes.get(route.toSeriesId);
assert.ok(target);
const routes = routesByTargetColumn.get(target.column) ?? [];
routes.push(route);
routesByTargetColumn.set(target.column, routes);
}
for (const routes of routesByTargetColumn.values()) {
routes.sort(
(left, right) =>
right.sourceY - left.sourceY ||
right.targetY - left.targetY ||
connectorLayoutKey(left).localeCompare(connectorLayoutKey(right)),
);
routes.forEach((route, index) => {
if (route.kind === "winner") return;
assert.equal(
route.verticalX,
route.targetX -
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap +
(DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap * (index + 1)) /
(routes.length + 1),
);
});
}
});
test("keeps paired winner rails clear of overlapping loser paths", () => {
const fourTeam = fourTeamProjection();
const eightTeam = eightTeamProjection();
const fixtures = [
{
layout: requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT),
pairedWinnerTargets: new Set<SeriesId>([
fourTeam.ids.WB_FINAL,
fourTeam.ids.GF,
]),
},
{
layout: requireLayout(eightTeam.projection, EIGHT_TEAM_LAYOUT),
pairedWinnerTargets: new Set<SeriesId>([
eightTeam.ids.WB_R2_M1,
eightTeam.ids.WB_R2_M2,
eightTeam.ids.WB_FINAL,
eightTeam.ids.LB_R3_M1,
eightTeam.ids.GF,
]),
},
];
for (const { layout, pairedWinnerTargets } of fixtures) {
for (const winner of layout.connectors) {
if (
winner.kind !== "winner" ||
!pairedWinnerTargets.has(winner.toSeriesId)
) {
continue;
}
for (const loser of layout.connectors) {
if (
loser.kind !== "loser" ||
!intervalsStrictlyOverlap(
winner.sourceY,
winner.targetY,
loser.sourceY,
loser.targetY,
)
) {
continue;
}
assert.ok(
Math.abs(winner.verticalX - loser.verticalX) >=
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.connectorRailClearance,
`${winner.fromSeriesId} winner rail ${winner.verticalX} is too close to ${loser.fromSeriesId} loser rail ${loser.verticalX}`,
);
}
}
} }
}); });
test("minimizes connector crossings without introducing segment overlaps", () => { test("minimizes connector crossings without introducing segment overlaps", () => {
const { projection } = eightTeamProjection(); const fourTeam = fourTeamProjection();
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT); const fourTeamReset = fourTeamProjection({ resetFinal: true });
const eightTeam = eightTeamProjection();
const eightTeamReset = eightTeamProjection({ resetFinal: true });
const layouts = [
requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT),
requireLayout(fourTeamReset.projection, FOUR_TEAM_RESET_LAYOUT),
requireLayout(eightTeam.projection, EIGHT_TEAM_LAYOUT),
requireLayout(eightTeamReset.projection, EIGHT_TEAM_RESET_LAYOUT),
];
assert.equal(countStrictConnectorCrossings(layout.connectors), 12); assert.ok(countStrictConnectorCrossings(layouts[2].connectors) <= 12);
for (const layout of layouts) {
assert.equal(countCollinearConnectorOverlaps(layout.connectors), 0); assert.equal(countCollinearConnectorOverlaps(layout.connectors), 0);
}
}); });
test("aligns connector endpoints with the A and B entry row centers", () => { test("aligns connector endpoints with the A and B entry row centers", () => {
@@ -921,6 +1154,18 @@ function segment(
}; };
} }
function intervalsStrictlyOverlap(
firstStart: number,
firstEnd: number,
secondStart: number,
secondEnd: number,
): boolean {
return (
Math.min(firstStart, firstEnd) < Math.max(secondStart, secondEnd) &&
Math.min(secondStart, secondEnd) < Math.max(firstStart, firstEnd)
);
}
function countStrictConnectorCrossings(routes: readonly ConnectorLayout[]): number { function countStrictConnectorCrossings(routes: readonly ConnectorLayout[]): number {
let crossings = 0; let crossings = 0;
for (let leftIndex = 0; leftIndex < routes.length; leftIndex += 1) { for (let leftIndex = 0; leftIndex < routes.length; leftIndex += 1) {
@@ -1009,6 +1254,16 @@ function nodeFor(
return node; return node;
} }
function winnerRoutesTo(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
targetSeriesId: SeriesId,
) {
return layout.connectors.filter(
(route) =>
route.kind === "winner" && route.toSeriesId === targetSeriesId,
);
}
function routeFrom( function routeFrom(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>, layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
id: SeriesId, id: SeriesId,
@@ -1036,6 +1291,10 @@ function connectorIdentity(
}; };
} }
function connectorLayoutKey(connector: ConnectorLayout): string {
return `${connector.fromSeriesId}:${connector.select}:${connector.toSeriesId}:${connector.toSlot}`;
}
function mobileGroupKeys( function mobileGroupKeys(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>, layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
) { ) {
@@ -0,0 +1,33 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
import { SERIES_SCORE_CARD_GEOMETRY } from "../src/components/competition/series-score-card-geometry.ts";
const component = await readFile(
new URL(
"../src/components/competition/SeriesScoreCard.tsx",
import.meta.url,
),
"utf8",
);
test("keeps bracket entry rows equal by overlaying their divider", () => {
assert.equal(
SERIES_SCORE_CARD_GEOMETRY.height -
SERIES_SCORE_CARD_GEOMETRY.borderWidth * 2 -
SERIES_SCORE_CARD_GEOMETRY.headerHeight,
SERIES_SCORE_CARD_GEOMETRY.entryHeight * 2,
);
assert.match(
component,
/className=\{\s*isBracket\s*\?\s*"relative"\s*:\s*"divide-y divide-base-content\/8"\s*\}/,
);
assert.match(
component,
/className="pointer-events-none absolute inset-x-0 border-t border-base-content\/8"/,
);
assert.match(
component,
/style=\{\{ top: SERIES_SCORE_CARD_GEOMETRY\.entryHeight \}\}/,
);
});
@@ -0,0 +1,84 @@
# Implementation Plan: Double-Elimination Connector Routing
## Overview
Replace per-edge winner rail staggering with deterministic, collision-aware winner
bundles while retaining the existing target-corridor `H-V-H` path model and the
current loser/reset routing behavior.
## Architecture Decisions
- Keep routing as a pure layout calculation; the React renderer consumes unchanged
`BracketConnectorLayout` paths.
- Allocate baseline rails first, then choose one rail for each same-target winner
bundle while leaving loser/reset coordinates unchanged.
- Score complete candidate paths by parallel-stroke clearance, strict crossings,
and distance from the corridor midpoint.
- Permit shared `verticalX` only when the participating vertical intervals do not
overlap; otherwise search the same corridor for the nearest deterministic pair
of separate rails with focused-stroke clearance.
## Task List
### Phase 1: Regression Contract
- [x] Add tests proving quiet winner bundles use the corridor midpoint and all
shareable same-target winner paths remain aligned.
- [x] Replace target-column rail uniqueness with interval-aware segment assertions.
- [x] Cover reversed A/B input where overlapping vertical spans require the
deterministic separate-rail fallback.
- [x] Confirm the focused test fails with the current allocator.
### Checkpoint: RED
- [x] The new behavioral assertion fails for the expected unequal `verticalX`.
- [x] Existing tests remain unchanged except where their invariant is obsolete.
### Phase 2: Bundle-Aware Allocator
- [x] Represent connector routing inputs with precomputed source/target anchors.
- [x] Retain stable independent rails for loser/reset routes.
- [x] Group the two winners entering each target and select the nearest safe shared
rail without card penetration, forbidden overlap, or avoidable added crossings.
- [x] Fall back to the nearest deterministic, stroke-clear separate rails only
when the pair's own vertical intervals overlap and cannot safely share a rail.
### Checkpoint: GREEN
- [x] Focused layout tests pass for four-team, eight-team, reset-final, and shuffled
input fixtures.
- [x] Strict crossing, collinear-overlap, and 5px parallel-clearance safeguards pass.
### Phase 3: Verification and Review
- [x] Run the full web suite, lint, and production build; document the unrelated
pre-existing full-lint failures while verifying changed files separately.
- [x] Inspect the diff for correctness, simplicity, security, performance, and
adherence to the approved spec.
- [x] Perform an independent review and address all required findings.
### Checkpoint: Complete
- [x] All success criteria in the spec are verified.
- [x] No unrelated files are modified.
## Risks and Mitigations
| Risk | Impact | Mitigation |
|---|---|---|
| Blind midpoint alignment adds crossings in busy upper rounds | High | Score complete candidate paths and move the winner bundle together to the nearest safe rail. |
| Shared rails create overlapping vertical segments | High | Check interval overlap before allowing a shared `verticalX`; search deterministic fallback rails with 5px clearance otherwise. |
| Visually parallel rails pass exact-coordinate tests but overlap at stroke width | High | Require 5px clearance across overlapping vertical runs and cover it for 4/8-team fixtures. |
| Routing changes depend on input array order | Medium | Sort routes and bundles by graph display order and retain shuffled-fixture equality tests. |
| A long connector bends through an intermediate card | High | Restrict every candidate to the target corridor and retain card-penetration assertions. |
| Reset-final slot carry-over is accidentally treated as a winner pair | Medium | Bundle only connectors whose computed kind is `winner`; keep reset paths independent. |
## Dependencies
```text
Regression contract -> bundle-aware rail allocator -> full verification -> review
```
## Open Questions
None.
-32
View File
@@ -1,32 +0,0 @@
# Dependency Audit Exceptions
## GHSA-mh99-v99m-4gvg
- Package: `brace-expansion`
- Scope: development tooling only (`eslint`, `jest`, and `@nestjs/cli` through
`minimatch`/`glob`)
- Production exposure: none; `pnpm audit --prod --audit-level high` reports no
high or critical findings
- Reason: the only patched release is `brace-expansion@5.0.8`, whose CommonJS
API is incompatible with the affected `minimatch@3` and `minimatch@9`
consumers
- Mitigation: repository-controlled glob patterns are trusted; no
attacker-controlled input is passed to these development tools
- Review date: 2026-08-25
- Removal condition: remove the audit exception once the upstream toolchain
supports `brace-expansion@5.0.8` or publishes compatible patched releases
## Tracked remediation
### GHSA-664h-wqgq-64gw
- Package: `mongoose@9.4.1`
- Severity: moderate
- Patched version: `>=9.7.2`
- Status: not ignored; it remains visible in a full audit and does not fail the
high-severity CI gate
- Upgrade blocker: Mongoose 9.7.x tightens create and query types and currently
causes API compilation failures across the model layer
- Next action: migrate the affected model create/query types, then upgrade
Mongoose in a dedicated change
- Review date: 2026-08-25
-67
View File
@@ -1,67 +0,0 @@
# Spec: Dakao Upcoming Internal Match List
## Objective
When a user sends `!내전 일정`, return only recruiting matches whose scheduled
start is not earlier than the command processing time. Matches that have already
started must not consume the ten-result query limit or appear in the response.
## Approved Product Decisions
- Capture the command processing time once before querying matches.
- Exclude `scheduledAt < now`.
- Include `scheduledAt === now` and future matches.
- Apply the boundary only to the Dakao `!내전 일정` command.
- Preserve the existing recruiting status, result limit, ordering, formatting,
short-code generation, and short-link behavior.
## Commands
- Focused test:
`pnpm --filter api exec jest src/modules/dakao/handlers/match-list.handler.spec.ts --runInBand`
- API lint:
`pnpm --filter api exec eslint "{src,apps,libs,test}/**/*.ts" --max-warnings=0`
- API build: `pnpm --filter api build`
## Project Structure
- `apps/api/src/modules/dakao/handlers/match-list.handler.ts` owns the command
query and response formatting.
- `apps/api/src/modules/dakao/handlers/match-list.handler.spec.ts` verifies the
command boundary and presentation.
- `apps/api/src/modules/match/match.service.ts` translates `scheduledFrom` into a
MongoDB `$gte` filter.
## Code Style
Pass the captured boundary through the existing list contract:
```ts
const scheduledFrom = new Date();
await matchService.list({ communityId, scheduledFrom });
```
## Testing Strategy
- Freeze the system clock in the handler unit test.
- Assert that the exact frozen time is passed as `scheduledFrom`.
- Rely on the existing `MatchService` test that verifies `scheduledFrom` becomes
`{ scheduledAt: { $gte: scheduledFrom } }`.
- Run the focused handler test, full API lint, and API build.
## Boundaries
- Always: filter before applying the result limit and use one captured time.
- Ask first: change ordering, statuses, limit, or response wording.
- Never: hide the requirement with an ESLint exception or filter only after the
limited database query.
## Success Criteria
- A match scheduled before command processing time is not queried.
- A match scheduled exactly at command processing time remains eligible.
- Existing command formatting and link tests continue to pass.
## Open Questions
None.
@@ -0,0 +1,134 @@
# Spec: Double-Elimination Connector Routing
## Objective
Make winner advancement lines in the desktop double-elimination bracket bend at a
consistent horizontal position. Two winner lines entering the same match should
read as one visual pair when their vertical spans can share a rail: use the center
of the 40px inter-column corridor when it is safe, and move the pair together only
when another connector would interfere. If an accepted A/B mapping reverses the
source order and makes those spans overlap, preserve separate deterministic,
stroke-clear rails instead of creating a collinear overlap.
The primary user is a participant or organizer tracing advancement through a busy
eight-team bracket. Success means the solid coral winner paths are visually
aligned without degrading the existing dashed loser paths, card placement, or
keyboard-driven connector highlighting.
## Approved Product Decisions
- Treat the two `winner` connectors entering one Series as a semantic bundle.
- Prefer `target.x - columnGap / 2` for a winner bundle.
- If the preferred rail causes crossings, collinear overlap, or less than 5px of
clearance from an overlapping parallel route, move a shareable bundle to the
nearest safe rail. Retain separate rails only when the pair's own vertical spans
overlap and therefore cannot safely share any rail; move those rails to the
nearest deterministic positions needed to preserve the same 5px clearance.
- Preserve the current loser/reset rail ordering unless moving one is required to
maintain valid geometry.
- Keep every connector as a separate `H-V-H` SVG path so focus highlighting and
accessible labels remain independent.
- Keep long-distance bends inside the corridor immediately before the target
column; do not use the midpoint between source and target cards.
## Tech Stack
- React 19, TypeScript 6, Vite 8, Tailwind CSS 4, and daisyUI under `apps/web`
- Node's built-in test runner for the pure bracket layout calculation
## Commands
- Focused layout tests: `pnpm --filter web exec node --test --experimental-strip-types test/double-elimination-bracket-layout.test.ts`
- Full web tests: `pnpm --filter web test`
- Web lint: `pnpm --filter web lint`
- Web production build: `pnpm --filter web build:prod`
- Development server: `pnpm --filter web start:dev`
## Project Structure
- `apps/web/src/components/competition/double-elimination-bracket-layout.ts`
validates the bracket graph, positions cards, assigns connector rails, and emits
SVG path geometry.
- `apps/web/src/components/competition/DoubleEliminationBracket.tsx` renders the
computed paths and must not need routing-specific changes.
- `apps/web/test/double-elimination-bracket-layout.test.ts` contains canonical
four-team, eight-team, and reset-final fixtures plus geometry assertions.
## Code Style
Keep routing deterministic and express geometry through small named helpers:
```ts
const preferredX = target.x - geometry.columnGap / 2;
const verticalX = nearestSafeRail(preferredX, bundle, occupiedRoutes);
```
Use existing layout types and semantic connector kinds. Do not add a dependency,
DOM measurement, mutable global state, or renderer-specific routing behavior.
## Testing Strategy
- Add regression tests before implementation and confirm they fail against the
current per-edge rail allocator.
- Assert observable geometry: safe winner pairs share a rail, quiet corridors use
their exact midpoint, busy corridors keep a pair aligned, and mixed
winner/loser entries remain distinguishable.
- Cover reversed A/B winner input explicitly: it remains deterministic and uses
separate rails without collinear overlap or focused-stroke clearance conflicts
because no shared H-V-H rail is safe.
- Replace the obsolete "all rails in a target column are unique" assertion with
interval-aware overlap and 5px focused-stroke clearance protection.
- Preserve deterministic output for shuffled input, finite path coordinates,
target-corridor bounds, card avoidance, endpoint alignment, and canonical graph
validation.
- Verify four-team, eight-team, and reset-final layouts; run the complete web test,
lint, and production build commands.
## Boundaries
### Always
- Keep winner, loser, and reset connectors visually distinguishable by the existing
solid/dashed patterns and brand tokens.
- Keep connector rails strictly inside the target corridor.
- Avoid strict segment crossings and collinear overlaps whenever a safe candidate
exists.
- Keep overlapping parallel winner and loser rails at least 5px apart, matching
the widest focused connector underlay.
- Produce the same layout regardless of projection input ordering.
### Ask First
- Add dependencies or change the public projection contract.
- Change bracket card dimensions, round columns, or the 40px column gap.
- Redesign mobile bracket presentation or connector interaction behavior.
### Never
- Route a connector through a match card.
- Infer routing from Series codes; use canonical graph identity and topology.
- Merge two logical connectors into one SVG path.
- Modify unrelated competition or score-card behavior.
## Success Criteria
- The two winner paths into `LB_R3_M1` bend at the corridor midpoint and share the
same `verticalX`.
- The winner paths into the grand final share the corridor midpoint when safe.
- Every same-target winner pair whose vertical spans do not overlap shares one
`verticalX`, using the nearest collision-safe rail when the midpoint is busy.
- A reversed A/B pair with overlapping vertical spans retains deterministic
separate rails, produces no collinear segment overlap, and remains at least 5px
from every overlapping vertical route.
- Loser/reset paths retain their baseline rails, and winner bundles remain at least
5px away where their vertical runs overlap.
- All rails remain inside their target corridors without card penetration or
collinear overlap.
- Canonical four-team, eight-team, reset-final, and shuffled-input tests pass.
- Full web tests and production build pass; changed-file lint passes, and any
unrelated full-lint baseline failures are documented.
## Open Questions
None. The user reviewed the proposed bundle-aware routing behavior and requested
implementation.
+1 -21
View File
@@ -26,26 +26,6 @@
}, },
"packageManager": "pnpm@10.4.1", "packageManager": "pnpm@10.4.1",
"dependencies": { "dependencies": {
"@infisical/sdk": "^5.0.2" "@infisical/sdk": "^5.0.0"
},
"pnpm": {
"auditConfig": {
"ignoreGhsas": [
"GHSA-mh99-v99m-4gvg"
]
},
"overrides": {
"@babel/core@7.29.0": "7.29.6",
"brace-expansion@1.1.13": "1.1.16",
"brace-expansion@2.0.3": "2.1.2",
"brace-expansion@5.0.5": "5.0.8",
"engine.io@6.6.6": "6.6.7",
"fast-uri@3.1.0": "3.1.4",
"form-data@4.0.5": "4.0.6",
"js-yaml@4.1.1": "4.3.0",
"js-yaml@5.2.1": "5.2.2",
"qs@6.15.1": "6.15.2",
"ws@8.18.3": "8.21.0"
}
} }
} }
+1630 -1662
View File
File diff suppressed because it is too large. Load diff