diff --git a/apps/api/src/modules/match/dto/create-match.dto.ts b/apps/api/src/modules/match/dto/create-match.dto.ts index 04dd92e4..886ef1d5 100644 --- a/apps/api/src/modules/match/dto/create-match.dto.ts +++ b/apps/api/src/modules/match/dto/create-match.dto.ts @@ -236,21 +236,3 @@ export class SwapDoubleEliminationSeedsDto { @Min(1) rightSeedNumber!: number; } - -export class ApplyDoubleEliminationWalkoverDto { - @IsInt() - @Min(1) - winnerTeamIndex!: number; - - @IsOptional() - @IsString() - @MaxLength(512) - reason?: string; -} - -export class CancelDoubleEliminationActionDto { - @IsOptional() - @IsString() - @MaxLength(512) - reason?: string; -} diff --git a/apps/api/src/modules/match/match-result-cutover.spec.ts b/apps/api/src/modules/match/match-result-cutover.spec.ts new file mode 100644 index 00000000..7c6385e9 --- /dev/null +++ b/apps/api/src/modules/match/match-result-cutover.spec.ts @@ -0,0 +1,42 @@ +import { PATH_METADATA } from '@nestjs/common/constants'; +import { MatchController } from './match.controller'; +import { MatchService } from './match.service'; + +const LEGACY_RESULT_METHODS = [ + 'applyDoubleEliminationWalkover', + 'cancelDoubleEliminationWalkover', + 'cancelDoubleEliminationRiotResult', +] as const; + +describe('Match result ownership cutover', () => { + it('does not expose legacy Match result mutation routes', () => { + const routes = Object.getOwnPropertyNames(MatchController.prototype) + .map((name) => { + const handler = Object.getOwnPropertyDescriptor( + MatchController.prototype, + name, + )?.value as unknown; + return typeof handler === 'function' + ? (Reflect.getMetadata(PATH_METADATA, handler) as unknown) + : undefined; + }) + .filter((path): path is string => typeof path === 'string'); + + expect(routes).not.toEqual( + expect.arrayContaining([ + ':matchId/double-elimination/bracket-matches/:bracketMatchId/walkover', + ':matchId/double-elimination/bracket-matches/:bracketMatchId/walkover/cancel', + ':matchId/double-elimination/bracket-matches/:bracketMatchId/result/cancel', + ]), + ); + }); + + it.each(LEGACY_RESULT_METHODS)( + 'removes the legacy MatchService.%s result writer', + (methodName) => { + expect(Object.getOwnPropertyNames(MatchService.prototype)).not.toContain( + methodName, + ); + }, + ); +}); diff --git a/apps/api/src/modules/match/match.controller.ts b/apps/api/src/modules/match/match.controller.ts index ad0a7bd9..64ffc95b 100644 --- a/apps/api/src/modules/match/match.controller.ts +++ b/apps/api/src/modules/match/match.controller.ts @@ -21,8 +21,6 @@ import { ParseObjectIdPipe } from '../common/parse-object-id.pipe'; import type { MatchStatus, UserDocument } from '../global/database/schema'; import { AddParticipantDto, - ApplyDoubleEliminationWalkoverDto, - CancelDoubleEliminationActionDto, CreateMatchDto, JoinMatchDto, SwapDoubleEliminationSeedsDto, @@ -169,77 +167,6 @@ export class MatchController { return this.matchService.serialize(match); } - @Post(':matchId/double-elimination/bracket-matches/:bracketMatchId/walkover') - @Roles('admin', 'owner') - @UseGuards(RolesGuard) - public async applyDoubleEliminationWalkover( - @CurrentUser() currentUser: UserDocument, - @Param('communityId', ParseObjectIdPipe) - communityId: mongoose.Types.ObjectId, - @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, - @Param('bracketMatchId') bracketMatchId: string, - @Body() body: ApplyDoubleEliminationWalkoverDto, - ) { - this.assertSameCommunity(currentUser, communityId); - const match = await this.matchService.applyDoubleEliminationWalkover({ - matchId, - communityId, - actorUserId: currentUser._id, - bracketMatchId, - winnerTeamIndex: body.winnerTeamIndex, - reason: body.reason, - }); - return this.matchService.serialize(match); - } - - @Post( - ':matchId/double-elimination/bracket-matches/:bracketMatchId/walkover/cancel', - ) - @Roles('admin', 'owner') - @UseGuards(RolesGuard) - public async cancelDoubleEliminationWalkover( - @CurrentUser() currentUser: UserDocument, - @Param('communityId', ParseObjectIdPipe) - communityId: mongoose.Types.ObjectId, - @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, - @Param('bracketMatchId') bracketMatchId: string, - @Body() body: CancelDoubleEliminationActionDto, - ) { - this.assertSameCommunity(currentUser, communityId); - const match = await this.matchService.cancelDoubleEliminationWalkover({ - matchId, - communityId, - actorUserId: currentUser._id, - bracketMatchId, - reason: body.reason, - }); - return this.matchService.serialize(match); - } - - @Post( - ':matchId/double-elimination/bracket-matches/:bracketMatchId/result/cancel', - ) - @Roles('admin', 'owner') - @UseGuards(RolesGuard) - public async cancelDoubleEliminationRiotResult( - @CurrentUser() currentUser: UserDocument, - @Param('communityId', ParseObjectIdPipe) - communityId: mongoose.Types.ObjectId, - @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, - @Param('bracketMatchId') bracketMatchId: string, - @Body() body: CancelDoubleEliminationActionDto, - ) { - this.assertSameCommunity(currentUser, communityId); - const match = await this.matchService.cancelDoubleEliminationRiotResult({ - matchId, - communityId, - actorUserId: currentUser._id, - bracketMatchId, - reason: body.reason, - }); - return this.matchService.serialize(match); - } - @Delete(':matchId') @Roles('admin', 'owner') @UseGuards(RolesGuard) diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts index 20fb5e3c..9061cba8 100644 --- a/apps/api/src/modules/match/match.service.ts +++ b/apps/api/src/modules/match/match.service.ts @@ -6,8 +6,6 @@ import { } from '@nestjs/common'; import mongoose from 'mongoose'; import { - cancelDoubleEliminationBracketMatch, - completeDoubleEliminationBracketMatch, reshuffleDoubleEliminationSeeds, swapDoubleEliminationSeeds, } from '../double-elimination/double-elimination.util'; @@ -17,8 +15,6 @@ import { ConnectionService } from '../global/database/connection.service'; import { Match, MatchDocument, - MatchGameMode, - MatchSeriesResult, MatchStatus, POSITIONS, Position, @@ -116,17 +112,6 @@ interface SwapDoubleEliminationSeedsParams extends DoubleEliminationAdminParams rightSeedNumber: number; } -interface ApplyDoubleEliminationWalkoverParams extends DoubleEliminationAdminParams { - bracketMatchId: string; - winnerTeamIndex: number; - reason?: string; -} - -interface CancelDoubleEliminationActionParams extends DoubleEliminationAdminParams { - bracketMatchId: string; - reason?: string; -} - @Injectable() export class MatchService { constructor( @@ -313,7 +298,7 @@ export class MatchService { match.doubleElimination = reshuffleDoubleEliminationSeeds( match.doubleElimination as NonNullable, ); - match.doubleElimination!.events.push({ + match.doubleElimination.events.push({ type: 'seeds-reshuffled', actorUserId: params.actorUserId, createdAt: new Date(), @@ -337,7 +322,7 @@ export class MatchService { rightSeedNumber: params.rightSeedNumber, }, ); - match.doubleElimination!.events.push({ + match.doubleElimination.events.push({ type: 'seeds-swapped', actorUserId: params.actorUserId, createdAt: new Date(), @@ -348,130 +333,6 @@ export class MatchService { return match; } - public async applyDoubleEliminationWalkover( - params: ApplyDoubleEliminationWalkoverParams, - ): Promise { - const match = await this.loadDoubleEliminationMatch(params); - const bracketMatch = this.requireDoubleEliminationBracketMatch( - match, - params.bracketMatchId, - ); - if (bracketMatch.state !== 'ready') { - throw new BadRequestException('Bracket match is not ready.'); - } - if ( - bracketMatch.teamAIndex !== params.winnerTeamIndex && - bracketMatch.teamBIndex !== params.winnerTeamIndex - ) { - throw new BadRequestException( - 'Winner team is not assigned to this bracket match.', - ); - } - - await this.releaseReservedDoubleEliminationCodes(match, [ - params.bracketMatchId, - ]); - match.doubleElimination = completeDoubleEliminationBracketMatch( - match.doubleElimination as NonNullable, - { - bracketMatchId: params.bracketMatchId, - winnerTeamIndex: params.winnerTeamIndex, - completedBy: 'walkover', - completedAt: new Date(), - walkover: { - winnerTeamIndex: params.winnerTeamIndex, - reason: params.reason, - awardedBy: params.actorUserId, - awardedAt: new Date(), - active: true, - }, - }, - ); - match.markModified('doubleElimination'); - this.syncDoubleEliminationWinner(match); - await match.save(); - await this.tournamentCodeService.reserveForMatch(match); - await this.communityStatsService.invalidateCommunity(params.communityId); - return match; - } - - public async cancelDoubleEliminationWalkover( - params: CancelDoubleEliminationActionParams, - ): Promise { - const match = await this.loadDoubleEliminationMatch(params); - const bracketMatch = this.requireDoubleEliminationBracketMatch( - match, - params.bracketMatchId, - ); - if ( - bracketMatch.completedBy !== 'walkover' || - !bracketMatch.walkover?.active - ) { - throw new BadRequestException('Active walkover was not found.'); - } - await this.releaseReservedDoubleEliminationCodes(match); - match.doubleElimination = cancelDoubleEliminationBracketMatch( - match.doubleElimination as NonNullable, - { - bracketMatchId: params.bracketMatchId, - cancelledBy: params.actorUserId, - cancelReason: params.reason, - }, - ); - match.markModified('doubleElimination'); - this.syncDoubleEliminationWinner(match); - await match.save(); - await this.tournamentCodeService.reserveForMatch(match); - await this.communityStatsService.invalidateCommunity(params.communityId); - return match; - } - - public async cancelDoubleEliminationRiotResult( - params: CancelDoubleEliminationActionParams, - ): Promise { - const match = await this.loadDoubleEliminationMatch(params); - const game = match.result?.games?.find( - (entry) => entry.bracketMatchId === params.bracketMatchId, - ); - if (!game) throw new NotFoundException('Collected result not found.'); - await this.releaseReservedDoubleEliminationCodes(match); - match.doubleElimination = cancelDoubleEliminationBracketMatch( - match.doubleElimination as NonNullable, - { - bracketMatchId: params.bracketMatchId, - cancelledBy: params.actorUserId, - cancelReason: params.reason, - }, - ); - match.doubleElimination!.events.push({ - type: 'riot-result-cancelled', - bracketMatchId: params.bracketMatchId, - actorUserId: params.actorUserId, - reason: params.reason, - createdAt: new Date(), - }); - const games = (match.result?.games ?? []).filter( - (entry) => entry.bracketMatchId !== params.bracketMatchId, - ); - match.result = { - winnerTeamIndex: undefined, - mvpUserId: match.result?.mvpUserId, - riotMatchIds: (match.result?.riotMatchIds ?? []).filter( - (riotMatchId) => riotMatchId !== game.riotMatchId, - ), - games, - seriesResults: this.buildSeriesResults(games), - }; - await this.voidDoubleEliminationCode(match, params.bracketMatchId); - if (match.status === 'finished') match.status = 'in-progress'; - match.markModified('doubleElimination'); - await match.save(); - await this.tournamentCodeService.reserveForMatch(match); - await this.matchStatsService.buildAndUpsert(match._id); - await this.communityStatsService.invalidateCommunity(params.communityId); - return match; - } - public async join(params: JoinMatchParams): Promise { const MatchModel = await this.connectionService.getModel('match'); const UserModel = await this.connectionService.getModel('user'); @@ -518,7 +379,7 @@ export class MatchService { T extends Partial & DoubleEliminationConfigInput, >(input: T): Partial { const patch = this.stripMatchConfigInput(input); - const gameMode = (patch.gameMode ?? 'pair') as MatchGameMode; + const gameMode = patch.gameMode ?? 'pair'; const maxParticipants = patch.maxParticipants ?? 10; if (gameMode === 'double-elimination') { @@ -565,7 +426,8 @@ export class MatchService { private stripMatchConfigInput< T extends Partial & DoubleEliminationConfigInput, >(input: T): Partial { - const { doubleEliminationResetFinalEnabled: _ignored, ...patch } = input; + const patch = { ...input }; + delete patch.doubleEliminationResetFinalEnabled; return patch; } @@ -623,20 +485,8 @@ export class MatchService { } } - private requireDoubleEliminationBracketMatch( - match: MatchDocument, - bracketMatchId: string, - ) { - const bracketMatch = match.doubleElimination?.bracketMatches.find( - (entry) => entry.bracketMatchId === bracketMatchId, - ); - if (!bracketMatch) throw new NotFoundException('Bracket match not found.'); - return bracketMatch; - } - private async releaseReservedDoubleEliminationCodes( match: MatchDocument, - bracketMatchIds?: string[], ): Promise { const ids = match.tournamentCodeIds ?? []; if (ids.length === 0) return; @@ -646,9 +496,7 @@ export class MatchService { _id: { $in: ids }, matchId: match._id, state: 'reserved', - ...(bracketMatchIds - ? { bracketMatchId: { $in: bracketMatchIds } } - : { bracketMatchId: { $exists: true } }), + bracketMatchId: { $exists: true }, }).exec(); if (codes.length === 0) return; const releasedIds = codes.map((code) => code._id.toString()); @@ -669,46 +517,6 @@ export class MatchService { ); } - private async voidDoubleEliminationCode( - match: MatchDocument, - bracketMatchId: string, - ): Promise { - const TournamentCodeModel = - await this.connectionService.getModel('tournamentCode'); - await TournamentCodeModel.updateOne( - { - _id: { $in: match.tournamentCodeIds ?? [] }, - matchId: match._id, - bracketMatchId, - state: 'used', - }, - { - $set: { state: 'voided' }, - }, - ).exec(); - } - - private syncDoubleEliminationWinner(match: MatchDocument): void { - if ((match.gameMode ?? 'pair') !== 'double-elimination') return; - const firstTeamIndex = match.doubleElimination?.placements.firstTeamIndex; - if (firstTeamIndex) { - match.status = 'finished'; - match.result = match.result ?? { - riotMatchIds: [], - games: [], - seriesResults: [], - }; - match.result.winnerTeamIndex = firstTeamIndex; - return; - } - if (match.status === 'finished') { - match.status = 'in-progress'; - } - if (match.result) { - match.result.winnerTeamIndex = undefined; - } - } - public async cancelJoin( params: CancelMatchJoinParams, ): Promise { @@ -1029,34 +837,4 @@ export class MatchService { } return code; } - - private buildSeriesResults( - games: NonNullable['games'], - ): MatchSeriesResult[] { - const bySeries = new Map(); - for (const game of games) { - const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex); - const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex); - const key = game.bracketMatchId ?? `${teamAIndex}:${teamBIndex}`; - const current = - bySeries.get(key) ?? - ({ - bracketMatchId: game.bracketMatchId, - teamAIndex, - teamBIndex, - teamAWins: 0, - teamBWins: 0, - } satisfies MatchSeriesResult); - if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1; - if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1; - current.winnerTeamIndex = - current.teamAWins > current.teamBWins - ? teamAIndex - : current.teamBWins > current.teamAWins - ? teamBIndex - : undefined; - bySeries.set(key, current); - } - return [...bySeries.values()]; - } }