From a307780752daf0f135b6dbe6a89b357cdbbaf50b Mon Sep 17 00:00:00 2001 From: Park Dahyeon Date: Mon, 13 Jul 2026 03:56:22 +0000 Subject: [PATCH] fix: preserve legacy competition slot identity --- .../20260712-competition-domain.spec.ts | 261 ++++++++++ .../migrations/20260712-competition-domain.ts | 478 ++++++++++++++++-- 2 files changed, 686 insertions(+), 53 deletions(-) diff --git a/apps/api/src/modules/global/database/migrations/20260712-competition-domain.spec.ts b/apps/api/src/modules/global/database/migrations/20260712-competition-domain.spec.ts index 46758d13..a95a1b00 100644 --- a/apps/api/src/modules/global/database/migrations/20260712-competition-domain.spec.ts +++ b/apps/api/src/modules/global/database/migrations/20260712-competition-domain.spec.ts @@ -139,6 +139,249 @@ describe('planCompetitionMigration', () => { }); }); + it('preserves a persisted non-canonical round-robin schedule', () => { + const schedule = [ + [1, 1, 1, 2], + [2, 1, 3, 4], + [3, 1, 5, 6], + [4, 1, 7, 8], + [5, 2, 1, 3], + [6, 2, 2, 4], + [7, 2, 5, 7], + [8, 2, 6, 8], + [9, 3, 1, 4], + [10, 3, 2, 3], + [11, 3, 5, 8], + [12, 3, 6, 7], + ] as const; + const legacy = pairedMatch({ + _id: 'match-persisted-round-robin-schedule', + gameMode: 'round-robin', + gameCount: 1, + roundRobinMaxRounds: 3, + teams: Array.from({ length: 8 }, (_, index) => + legacyTeam(index + 1, `${index + 1}팀`), + ), + gameSchedule: schedule.map( + ([gameNumber, roundNumber, teamAIndex, teamBIndex]) => ({ + gameNumber, + roundNumber, + teamAIndex, + teamBIndex, + }), + ), + result: { + games: schedule.map(([gameNumber, , teamAIndex, teamBIndex]) => + legacyGame({ + gameNumber, + riotMatchId: `KR_PERSISTED_RR_${gameNumber}`, + blueTeamIndex: teamAIndex, + redTeamIndex: teamBIndex, + winnerTeamIndex: teamAIndex, + riotArchivePresent: true, + }), + ), + seriesResults: [], + }, + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.competition.format).toMatchObject({ + type: 'round-robin', + pairings: expect.arrayContaining([ + expect.objectContaining({ + roundNumber: 3, + matchNumber: 4, + teamAId: plan.competition.teams[5].teamId, + teamBId: plan.competition.teams[6].teamId, + }), + ]), + }); + expect( + plan.facts.filter(({ type }) => type === 'game-accepted'), + ).toHaveLength(12); + }); + + it('maps a result-less reserved TournamentCode by its global game number', () => { + const legacy = pairedMatch({ + _id: 'match-future-reserved-code', + gameCount: 2, + teams: [ + legacyTeam(1, 'One'), + legacyTeam(2, 'Two'), + legacyTeam(3, 'Three'), + legacyTeam(4, 'Four'), + ], + gameSchedule: undefined, + result: { games: [], seriesResults: [] }, + tournamentCodes: [ + { + _id: 'future-code-for-global-game-3', + state: 'reserved', + gameNumber: 3, + }, + ], + }); + + const plan = requireReady(planCompetitionMigration(legacy)); + const expectedSeries = plan.competition.seriesGraph.find( + (series) => series.code === 'PAIR_M2', + ); + + expect(expectedSeries).toBeDefined(); + expect(plan.assignments).toContainEqual( + expect.objectContaining({ + tournamentCodeId: 'future-code-for-global-game-3', + seriesId: expectedSeries!.id, + gameSlotId: expectedSeries!.gameSlots[0].id, + }), + ); + }); + + it('maps persisted WB_FINAL global game numbers to distinct stable slots', () => { + const legacy = loadDataTxtFixture(); + legacy.result = { games: [], seriesResults: [] }; + legacy.doubleElimination!.bracketMatches = dataTxtUpperBracketTopology(); + legacy.tournamentCodes = [19, 20, 21].map((gameNumber, index) => ({ + _id: `wb-final-code-${index + 1}`, + state: 'reserved' as const, + bracketMatchId: 'WB_FINAL', + gameNumber, + })); + + const plan = requireReady(planCompetitionMigration(legacy)); + const wbFinal = plan.competition.seriesGraph.find( + (series) => series.code === 'WB_FINAL', + ); + + expect(wbFinal).toBeDefined(); + expect(wbFinal!.gameSlots).toHaveLength(3); + expect(plan.assignments).toHaveLength(3); + for (const [index, slot] of wbFinal!.gameSlots.entries()) { + expect(plan.assignments).toContainEqual( + expect.objectContaining({ + tournamentCodeId: `wb-final-code-${index + 1}`, + seriesId: wbFinal!.id, + gameSlotId: slot.id, + }), + ); + } + }); + + it('quarantines a TournamentCode whose bracket identity conflicts with its global game number', () => { + const legacy = loadDataTxtFixture(); + legacy.result = { games: [], seriesResults: [] }; + legacy.doubleElimination!.bracketMatches = dataTxtUpperBracketTopology(); + legacy.tournamentCodes = [ + { + _id: 'conflicting-wb-final-code', + state: 'reserved', + bracketMatchId: 'WB_FINAL', + gameNumber: 1, + }, + ]; + + const plan = planCompetitionMigration(legacy); + + expect(plan).toMatchObject({ + status: 'quarantined', + reasons: expect.arrayContaining([ + expect.objectContaining({ + code: 'TOURNAMENT_CODE_ASSIGNMENT_CONFLICT', + }), + ]), + }); + }); + + it('quarantines conflicting Riot evidence and global game number', () => { + const legacy = pairedMatch({ + _id: 'match-conflicting-code-evidence', + gameCount: 2, + gameSchedule: undefined, + result: { + games: [ + legacyGame({ + gameNumber: 1, + riotMatchId: 'KR_CONFLICTING_CODE_EVIDENCE', + blueTeamIndex: 1, + redTeamIndex: 2, + winnerTeamIndex: 1, + riotArchivePresent: true, + }), + ], + seriesResults: [], + }, + tournamentCodes: [ + { + _id: 'code-with-conflicting-evidence', + state: 'used', + gameNumber: 2, + riotMatchId: 'KR_CONFLICTING_CODE_EVIDENCE', + }, + ], + }); + + expect(planCompetitionMigration(legacy)).toMatchObject({ + status: 'quarantined', + reasons: expect.arrayContaining([ + expect.objectContaining({ + code: 'TOURNAMENT_CODE_ASSIGNMENT_CONFLICT', + }), + ]), + }); + }); + + it('quarantines a TournamentCode game number outside the Competition topology', () => { + const legacy = pairedMatch({ + _id: 'match-out-of-range-code', + gameSchedule: undefined, + result: { games: [], seriesResults: [] }, + tournamentCodes: [ + { + _id: 'out-of-range-code', + state: 'reserved', + gameNumber: 99, + }, + ], + }); + + expect(planCompetitionMigration(legacy)).toMatchObject({ + status: 'quarantined', + reasons: expect.arrayContaining([ + expect.objectContaining({ + code: 'TOURNAMENT_CODE_ASSIGNMENT_MAPPING_NOT_FOUND', + }), + ]), + }); + }); + + it('does not guess the first slot of a multi-slot Series without exact slot evidence', () => { + const legacy = pairedMatch({ + _id: 'match-multi-slot-code-without-evidence', + gameCount: 3, + result: { games: [], seriesResults: [] }, + tournamentCodes: [ + { + _id: 'code-with-series-only', + state: 'reserved', + bracketMatchId: 'PAIR_M1', + }, + ], + }); + + const plan = planCompetitionMigration(legacy); + + expect(plan).toMatchObject({ + status: 'quarantined', + reasons: expect.arrayContaining([ + expect.objectContaining({ + code: 'TOURNAMENT_CODE_ASSIGNMENT_MAPPING_NOT_FOUND', + }), + ]), + }); + }); + it('repairs the data.txt WB_R2_M2 positional bug from accepted game evidence', () => { const legacy = loadDataTxtFixture(); @@ -301,3 +544,21 @@ function loadDataTxtFixture(): LegacyMatchInput { updatedAt: '2026-07-12T17:17:00.000Z', }; } + +function dataTxtUpperBracketTopology() { + return [ + 'WB_R1_M1', + 'WB_R1_M2', + 'WB_R1_M3', + 'WB_R1_M4', + 'WB_R2_M1', + 'WB_R2_M2', + 'WB_FINAL', + ].map((bracketMatchId, index) => ({ + bracketMatchId, + gameNumber: index + 1, + gameCount: 3, + requiredWins: 2, + bracketSide: 'winner' as const, + })); +} diff --git a/apps/api/src/modules/global/database/migrations/20260712-competition-domain.ts b/apps/api/src/modules/global/database/migrations/20260712-competition-domain.ts index 4145aecb..c9ba7d56 100644 --- a/apps/api/src/modules/global/database/migrations/20260712-competition-domain.ts +++ b/apps/api/src/modules/global/database/migrations/20260712-competition-domain.ts @@ -3,6 +3,7 @@ import { projectCompetition } from '../../../competition/domain/competition-proj import { generateSeriesGraph, type CompetitionGraphFormat, + type RoundRobinPairing, type SeriesDefinition, } from '../../../competition/domain/series-graph'; @@ -314,7 +315,12 @@ export function planCompetitionMigration( return quarantined(matchId, reasons, warnings); } - const format = buildFormat(input, warnings, reasons); + const format = buildFormat( + input, + teamBuild.teamIdByLegacyIndex, + warnings, + reasons, + ); if (!format) return quarantined(matchId, reasons, warnings); let seriesGraph: SeriesDefinition[]; @@ -396,9 +402,9 @@ export function planCompetitionMigration( const assignments = buildAssignments( input, competitionId, - plannedGames, facts, seriesGraph, + teamBuild.teamIdByLegacyIndex, warnings, reasons, ); @@ -577,6 +583,7 @@ function seedMap( function buildFormat( input: LegacyMatchInput, + teamIds: Map, warnings: CompetitionMigrationIssue[], reasons: CompetitionMigrationIssue[], ): CompetitionGraphFormat | undefined { @@ -602,15 +609,24 @@ function buildFormat( ), ); return fixedFormat('paired-series', gameCount); - case 'round-robin': + case 'round-robin': { + const pairings = normalizeLegacyRoundRobinPairings( + input, + teamIds, + gameCount, + reasons, + ); + if (pairings === null) return undefined; return { type: 'round-robin', rule: fixedRule(gameCount), ...(positiveInteger(input.roundRobinMaxRounds) ? { maxRounds: input.roundRobinMaxRounds } : {}), + ...(pairings ? { pairings } : {}), tieBreakers: ['series-wins', 'game-diff', 'head-to-head'], }; + } case 'double-elimination': { const teamCount = input.teams.length; if (teamCount !== 4 && teamCount !== 8) { @@ -647,6 +663,136 @@ function buildFormat( } } +function normalizeLegacyRoundRobinPairings( + input: LegacyMatchInput, + teamIds: ReadonlyMap, + gameCount: number, + reasons: CompetitionMigrationIssue[], +): RoundRobinPairing[] | undefined | null { + const schedule = input.gameSchedule ?? []; + if (schedule.length === 0) return undefined; + + const seenGameNumbers = new Set(); + const groups = new Map< + string, + { + roundNumber: number; + teamAId: string; + teamBId: string; + gameNumbers: number[]; + } + >(); + const gamesPerRound = Math.floor(teamIds.size / 2) * gameCount; + + for (const assignment of schedule) { + const teamAId = teamIds.get(assignment.teamAIndex); + const teamBId = teamIds.get(assignment.teamBIndex); + const roundNumber = + positiveInteger(assignment.roundNumber) ?? + (gamesPerRound > 0 && positiveInteger(assignment.gameNumber) + ? Math.floor((assignment.gameNumber - 1) / gamesPerRound) + 1 + : undefined); + if ( + !positiveInteger(assignment.gameNumber) || + seenGameNumbers.has(assignment.gameNumber) || + !teamAId || + !teamBId || + teamAId === teamBId || + !roundNumber || + (positiveInteger(input.roundRobinMaxRounds) !== undefined && + roundNumber > input.roundRobinMaxRounds!) + ) { + reasons.push( + issue( + 'INVALID_ROUND_ROBIN_SCHEDULE', + 'The persisted round-robin schedule has an invalid game, round, or team identity.', + { gameNumber: assignment.gameNumber }, + ), + ); + return null; + } + seenGameNumbers.add(assignment.gameNumber); + + const opponents = [teamAId, teamBId].sort(); + const key = opponents.join(':'); + const existing = groups.get(key); + if (existing && existing.roundNumber !== roundNumber) { + reasons.push( + issue( + 'INVALID_ROUND_ROBIN_SCHEDULE', + 'A persisted round-robin opponent pair occurs in multiple rounds.', + { gameNumber: assignment.gameNumber }, + ), + ); + return null; + } + const group = + existing ?? + ({ + roundNumber, + teamAId, + teamBId, + gameNumbers: [], + } satisfies { + roundNumber: number; + teamAId: string; + teamBId: string; + gameNumbers: number[]; + }); + group.gameNumbers.push(assignment.gameNumber); + groups.set(key, group); + } + + const orderedGroups = [...groups.values()].sort( + (left, right) => + left.roundNumber - right.roundNumber || + Math.min(...left.gameNumbers) - Math.min(...right.gameNumbers), + ); + const teamsByRound = new Map>(); + const matchNumberByRound = new Map(); + const pairings: RoundRobinPairing[] = []; + for (const group of orderedGroups) { + if (group.gameNumbers.length !== gameCount) { + reasons.push( + issue( + 'INVALID_ROUND_ROBIN_SCHEDULE', + 'Every persisted round-robin Series must contain exactly gameCount scheduled games.', + { + roundNumber: group.roundNumber, + scheduledGameCount: group.gameNumbers.length, + expectedGameCount: gameCount, + }, + ), + ); + return null; + } + const roundTeams = teamsByRound.get(group.roundNumber) ?? new Set(); + if (roundTeams.has(group.teamAId) || roundTeams.has(group.teamBId)) { + reasons.push( + issue( + 'INVALID_ROUND_ROBIN_SCHEDULE', + 'A team appears in multiple persisted Series in the same round.', + { roundNumber: group.roundNumber }, + ), + ); + return null; + } + roundTeams.add(group.teamAId); + roundTeams.add(group.teamBId); + teamsByRound.set(group.roundNumber, roundTeams); + + const matchNumber = (matchNumberByRound.get(group.roundNumber) ?? 0) + 1; + matchNumberByRound.set(group.roundNumber, matchNumber); + pairings.push({ + roundNumber: group.roundNumber, + matchNumber, + teamAId: group.teamAId, + teamBId: group.teamBId, + }); + } + return pairings; +} + function fixedFormat(type: 'paired-series', gameCount: number) { return { type, rule: fixedRule(gameCount) } as const; } @@ -1246,12 +1392,276 @@ function materializeFacts( }); } +interface TournamentCodeAssignmentTarget { + series: SeriesDefinition; + slot: SeriesDefinition['gameSlots'][number]; +} + +function resolveTournamentCodeAssignmentTarget(params: { + input: LegacyMatchInput; + code: LegacyTournamentCodeInput; + tournamentCodeId: string; + gameFact: MigrationGameAcceptedFact | undefined; + graph: SeriesDefinition[]; + teamIds: ReadonlyMap; +}): TournamentCodeAssignmentTarget | { issue: CompetitionMigrationIssue } { + let target: TournamentCodeAssignmentTarget | undefined; + if (params.gameFact) { + const series = params.graph.find( + (candidate) => candidate.id === params.gameFact!.seriesId, + ); + const slot = series?.gameSlots.find( + (candidate) => candidate.id === params.gameFact!.gameSlotId, + ); + if (!series || !slot) { + return assignmentMappingNotFound( + params, + 'Accepted TournamentCode evidence does not target a stable GameSlot.', + ); + } + target = { series, slot }; + } + + if (params.code.gameNumber !== undefined) { + const numbered = resolveGlobalGameNumberTarget(params); + if ('issue' in numbered) return numbered; + if (target && !sameAssignmentTarget(target, numbered)) { + return assignmentConflict( + params, + [target, numbered], + 'TournamentCode Riot evidence conflicts with its global game number.', + ); + } + target = numbered; + } + + if (params.code.bracketMatchId) { + const bracketSeries = params.graph.find( + (candidate) => candidate.code === params.code.bracketMatchId, + ); + if (!bracketSeries) { + return assignmentMappingNotFound( + params, + 'The TournamentCode bracket identity has no stable Series.', + ); + } + if (target && target.series.id !== bracketSeries.id) { + return assignmentConflict( + params, + [target], + 'TournamentCode bracket identity conflicts with its exact GameSlot evidence.', + ); + } + if (!target) { + if (bracketSeries.gameSlots.length !== 1) { + return assignmentMappingNotFound( + params, + 'A multi-slot TournamentCode Series needs exact GameSlot evidence.', + ); + } + target = { series: bracketSeries, slot: bracketSeries.gameSlots[0] }; + } + } + + return ( + target ?? + assignmentMappingNotFound( + params, + 'A non-available TournamentCode cannot be mapped to a stable GameSlot.', + ) + ); +} + +function resolveGlobalGameNumberTarget(params: { + input: LegacyMatchInput; + code: LegacyTournamentCodeInput; + tournamentCodeId: string; + graph: SeriesDefinition[]; + teamIds: ReadonlyMap; +}): TournamentCodeAssignmentTarget | { issue: CompetitionMigrationIssue } { + const gameNumber = positiveInteger(params.code.gameNumber); + if (!gameNumber) { + return assignmentMappingNotFound( + params, + 'TournamentCode gameNumber must be a positive integer.', + ); + } + + const bracketMatches = params.input.doubleElimination?.bracketMatches ?? []; + if ( + params.input.gameMode === 'double-elimination' && + bracketMatches.length > 0 + ) { + const seenBracketNumbers = new Set(); + const ordered = [...bracketMatches].sort( + (left, right) => + (positiveInteger(left.gameNumber) ?? Number.MAX_SAFE_INTEGER) - + (positiveInteger(right.gameNumber) ?? Number.MAX_SAFE_INTEGER) || + left.bracketMatchId.localeCompare(right.bracketMatchId), + ); + let nextGameNumber = 1; + for (const bracketMatch of ordered) { + const bracketNumber = positiveInteger(bracketMatch.gameNumber); + if ( + !bracketNumber || + seenBracketNumbers.has(bracketNumber) || + bracketNumber !== seenBracketNumbers.size + 1 + ) { + return assignmentMappingNotFound( + params, + 'The persisted double-elimination topology has ambiguous Series numbering.', + ); + } + seenBracketNumbers.add(bracketNumber); + const gameCount = positiveInteger(bracketMatch.gameCount) ?? 1; + if ( + gameNumber >= nextGameNumber && + gameNumber < nextGameNumber + gameCount + ) { + const series = params.graph.find( + (candidate) => candidate.code === bracketMatch.bracketMatchId, + ); + const ordinal = gameNumber - nextGameNumber + 1; + const slot = series?.gameSlots.find( + (candidate) => candidate.ordinal === ordinal, + ); + if (!series || !slot) { + return assignmentMappingNotFound( + params, + 'The persisted double-elimination GameSlot has no Competition target.', + ); + } + return { series, slot }; + } + nextGameNumber += gameCount; + } + return assignmentMappingNotFound( + params, + 'TournamentCode gameNumber is outside the persisted double-elimination topology.', + ); + } + + const schedule = params.input.gameSchedule ?? []; + if (schedule.length > 0) { + const matches = schedule.filter( + (assignment) => assignment.gameNumber === gameNumber, + ); + if (matches.length !== 1) { + return assignmentMappingNotFound( + params, + matches.length > 1 + ? 'TournamentCode gameNumber maps to multiple persisted schedule entries.' + : 'TournamentCode gameNumber is absent from the persisted schedule.', + ); + } + const [assignment] = matches; + const teamAId = params.teamIds.get(assignment.teamAIndex); + const teamBId = params.teamIds.get(assignment.teamBIndex); + if (!teamAId || !teamBId || teamAId === teamBId) { + return assignmentMappingNotFound( + params, + 'TournamentCode schedule entry references an invalid team set.', + ); + } + const candidates = params.graph.filter((series) => + staticSeriesHasTeamSet(series, teamAId, teamBId), + ); + if (candidates.length !== 1) { + return assignmentMappingNotFound( + params, + 'TournamentCode schedule entry does not identify one stable Series.', + ); + } + const samePair = schedule + .filter( + (candidate) => + unorderedNumberPair(candidate.teamAIndex, candidate.teamBIndex) === + unorderedNumberPair(assignment.teamAIndex, assignment.teamBIndex), + ) + .sort((left, right) => left.gameNumber - right.gameNumber); + const ordinal = samePair.findIndex( + (candidate) => candidate.gameNumber === gameNumber, + ); + const series = candidates[0]; + const slot = series.gameSlots.find( + (candidate) => candidate.ordinal === ordinal + 1, + ); + if (!slot) { + return assignmentMappingNotFound( + params, + 'TournamentCode schedule ordinal has no stable GameSlot.', + ); + } + return { series, slot }; + } + + const flattened = params.graph.flatMap((series) => + series.gameSlots.map((slot) => ({ series, slot })), + ); + const target = flattened[gameNumber - 1]; + return ( + target ?? + assignmentMappingNotFound( + params, + 'TournamentCode gameNumber is outside the canonical Competition topology.', + ) + ); +} + +function assignmentMappingNotFound( + params: { + code: LegacyTournamentCodeInput; + tournamentCodeId: string; + }, + message: string, +): { issue: CompetitionMigrationIssue } { + return { + issue: issue('TOURNAMENT_CODE_ASSIGNMENT_MAPPING_NOT_FOUND', message, { + tournamentCodeId: params.tournamentCodeId, + bracketMatchId: params.code.bracketMatchId, + gameNumber: params.code.gameNumber, + }), + }; +} + +function assignmentConflict( + params: { + code: LegacyTournamentCodeInput; + tournamentCodeId: string; + }, + targets: TournamentCodeAssignmentTarget[], + message: string, +): { issue: CompetitionMigrationIssue } { + return { + issue: issue('TOURNAMENT_CODE_ASSIGNMENT_CONFLICT', message, { + tournamentCodeId: params.tournamentCodeId, + bracketMatchId: params.code.bracketMatchId, + gameNumber: params.code.gameNumber, + targets: targets.map(({ series, slot }) => ({ + seriesId: series.id, + gameSlotId: slot.id, + })), + }), + }; +} + +function sameAssignmentTarget( + left: TournamentCodeAssignmentTarget, + right: TournamentCodeAssignmentTarget, +): boolean { + return left.series.id === right.series.id && left.slot.id === right.slot.id; +} + +function unorderedNumberPair(left: number, right: number): string { + return left < right ? `${left}:${right}` : `${right}:${left}`; +} + function buildAssignments( input: LegacyMatchInput, competitionId: string, - plannedGames: PlannedGame[], facts: CompetitionMigrationFact[], graph: SeriesDefinition[], + teamIds: ReadonlyMap, warnings: CompetitionMigrationIssue[], reasons: CompetitionMigrationIssue[], ): CompetitionMigrationAssignment[] { @@ -1275,57 +1685,19 @@ function buildAssignments( (fact.evidence.type === 'legacy' && fact.evidence.legacyReference.endsWith(`:${code.riotMatchId}`))), ); - let series = gameFact - ? graph.find((candidate) => candidate.id === gameFact.seriesId) - : graph.find((candidate) => candidate.code === code.bracketMatchId); - if (!series && code.gameNumber !== undefined) { - const game = plannedGames.find( - (candidate) => candidate.legacy.gameNumber === code.gameNumber, - ); - series = game?.series; - } - if (!series) { - reasons.push( - issue( - 'TOURNAMENT_CODE_ASSIGNMENT_MAPPING_NOT_FOUND', - 'A non-available TournamentCode cannot be mapped to a stable GameSlot.', - { - tournamentCodeId, - bracketMatchId: code.bracketMatchId, - gameNumber: code.gameNumber, - }, - ), - ); - continue; - } - - let slot = gameFact - ? series.gameSlots.find( - (candidate) => candidate.id === gameFact.gameSlotId, - ) - : undefined; - if (!slot && code.gameNumber !== undefined && code.bracketMatchId) { - const legacyBracket = input.doubleElimination?.bracketMatches?.find( - (candidate) => candidate.bracketMatchId === code.bracketMatchId, - ); - const ordinal = legacyBracket?.gameNumber - ? code.gameNumber - legacyBracket.gameNumber + 1 - : undefined; - slot = series.gameSlots.find( - (candidate) => candidate.ordinal === ordinal, - ); - } - slot ??= series.gameSlots[0]; - if (!slot) { - reasons.push( - issue( - 'TOURNAMENT_CODE_ASSIGNMENT_MAPPING_NOT_FOUND', - 'A TournamentCode Series has no stable GameSlot.', - { tournamentCodeId, seriesId: series.id }, - ), - ); + const resolution = resolveTournamentCodeAssignmentTarget({ + input, + code, + tournamentCodeId, + gameFact, + graph, + teamIds, + }); + if ('issue' in resolution) { + reasons.push(resolution.issue); continue; } + const { series, slot } = resolution; if (code.state === 'used' && !gameFact) { warnings.push( issue(