import { TournamentCodeSchema, type MatchDocument, } from '../global/database/schema'; import { Logger } from '@nestjs/common'; import mongoose from 'mongoose'; import { TournamentCodeService } from './tournament-code.service'; import { buildDoubleEliminationBracket } from '../double-elimination/double-elimination.util'; type TournamentCodeServiceInternals = TournamentCodeService & { resolveRequiredSlots(match: MatchDocument): number; resolveSeriesRefForGameNumber( match: MatchDocument, gameNumber: number, ): { teamAIndex: number; teamBIndex: number }; ensureGameSchedule(match: MatchDocument): void; attachPendingMatches(communityId?: mongoose.Types.ObjectId): Promise; }; function createAuctionRedisService() { return { acquireTokenLock: jest.fn().mockResolvedValue(true), releaseTokenLock: jest.fn().mockResolvedValue(true), }; } function createSession() { return { startTransaction: jest.fn(), commitTransaction: jest.fn().mockResolvedValue(undefined), abortTransaction: jest.fn().mockResolvedValue(undefined), endSession: jest.fn().mockResolvedValue(undefined), }; } function mongoQuery(value: T) { const query = { exec: jest.fn().mockResolvedValue(value), lean: jest.fn(), limit: jest.fn(), select: jest.fn(), session: jest.fn(), }; query.lean.mockReturnValue(query); query.limit.mockReturnValue(query); query.select.mockReturnValue(query); query.session.mockReturnValue(query); return query; } function createService() { return new TournamentCodeService( {} as never, createAuctionRedisService() as never, ) as unknown as TournamentCodeServiceInternals; } interface MatchOverrides { gameCount?: number; gameMode?: 'pair' | 'bracket' | 'round-robin' | 'double-elimination'; roundRobinMaxRounds?: number; participants?: Array<{ excluded?: boolean }>; teams?: Array<{ teamIndex: number }>; doubleElimination?: MatchDocument['doubleElimination']; tournamentCodeIds?: mongoose.Types.ObjectId[]; gameSchedule?: Array<{ gameNumber: number; roundNumber?: number; teamAIndex: number; teamBIndex: number; }>; } function createMatch(overrides: MatchOverrides): MatchDocument { return { _id: new mongoose.Types.ObjectId(), status: 'in-progress', gameCount: 1, gameMode: 'pair', participants: [], teams: [], tournamentCodeIds: [], gameSchedule: [], save: jest.fn().mockResolvedValue(undefined), markModified: jest.fn(), ...overrides, } as unknown as MatchDocument; } describe('TournamentCodeService round-robin scheduling', () => { it('keeps pair slot calculation unchanged', () => { const service = createService(); const match = createMatch({ gameCount: 3, teams: Array.from({ length: 6 }, (_, index) => ({ teamIndex: index + 1, })), participants: Array.from({ length: 30 }, () => ({})), }); expect(service.resolveRequiredSlots(match)).toBe(9); expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({ teamAIndex: 1, teamBIndex: 2, }); expect(service.resolveSeriesRefForGameNumber(match, 4)).toEqual({ teamAIndex: 3, teamBIndex: 4, }); expect(service.resolveSeriesRefForGameNumber(match, 7)).toEqual({ teamAIndex: 5, teamBIndex: 6, }); }); it('calculates round-robin slots from team pairs and per-pair game count', () => { const service = createService(); expect( service.resolveRequiredSlots( createMatch({ gameMode: 'round-robin', gameCount: 1, teams: Array.from({ length: 6 }, (_, index) => ({ teamIndex: index + 1, })), }), ), ).toBe(15); expect( service.resolveRequiredSlots( createMatch({ gameMode: 'round-robin', gameCount: 2, teams: Array.from({ length: 6 }, (_, index) => ({ teamIndex: index + 1, })), }), ), ).toBe(30); expect( service.resolveRequiredSlots( createMatch({ gameMode: 'round-robin', gameCount: 1, teams: [], participants: Array.from({ length: 30 }, () => ({})), }), ), ).toBe(15); }); it('calculates limited round-robin slots from max rounds', () => { const service = createService(); expect( service.resolveRequiredSlots( createMatch({ gameMode: 'round-robin', gameCount: 1, roundRobinMaxRounds: 3, teams: Array.from({ length: 8 }, (_, index) => ({ teamIndex: index + 1, })), }), ), ).toBe(12); }); it('uses persisted round-robin game schedule for game refs', () => { const service = createService(); const match = createMatch({ gameMode: 'round-robin', gameCount: 2, gameSchedule: [ { gameNumber: 1, roundNumber: 1, teamAIndex: 2, teamBIndex: 5 }, { gameNumber: 2, roundNumber: 1, teamAIndex: 2, teamBIndex: 5 }, { gameNumber: 3, roundNumber: 2, teamAIndex: 1, teamBIndex: 4 }, ], }); expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({ teamAIndex: 2, teamBIndex: 5, }); expect(service.resolveSeriesRefForGameNumber(match, 3)).toEqual({ teamAIndex: 1, teamBIndex: 4, }); }); it('falls back to round-based pairs before schedule is persisted', () => { const service = createService(); const match = createMatch({ gameMode: 'round-robin', gameCount: 1, teams: Array.from({ length: 4 }, (_, index) => ({ teamIndex: index + 1, })), gameSchedule: [], }); expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({ teamAIndex: 1, teamBIndex: 4, }); expect(service.resolveSeriesRefForGameNumber(match, 2)).toEqual({ teamAIndex: 2, teamBIndex: 3, }); }); it('creates a round-robin schedule once and leaves pair matches empty', () => { const service = createService(); const roundRobin = createMatch({ gameMode: 'round-robin', gameCount: 2, teams: Array.from({ length: 4 }, (_, index) => ({ teamIndex: index + 1, })), gameSchedule: [], }); service.ensureGameSchedule(roundRobin); expect(roundRobin.gameSchedule).toHaveLength(12); const persisted = [...roundRobin.gameSchedule]; service.ensureGameSchedule(roundRobin); expect(roundRobin.gameSchedule).toEqual(persisted); const pair = createMatch({ gameMode: 'pair', teams: Array.from({ length: 4 }, (_, index) => ({ teamIndex: index + 1, })), gameSchedule: [], }); service.ensureGameSchedule(pair); expect(pair.gameSchedule).toEqual([]); }); it('creates a double-elimination bracket from built teams', () => { const service = createService(); const match = createMatch({ gameMode: 'double-elimination', gameCount: 3, teams: Array.from({ length: 4 }, (_, index) => ({ teamIndex: index + 1, })), doubleElimination: { teamCount: 4, resetFinalEnabled: true, resetFinalCreated: false, seeds: [], bracketMatches: [], placements: {}, events: [], }, }); service.ensureGameSchedule(match); expect(match.doubleElimination?.seeds).toHaveLength(4); expect(match.doubleElimination?.bracketMatches).toHaveLength(6); expect( match.doubleElimination?.bracketMatches.filter( (bracketMatch) => bracketMatch.state === 'ready', ), ).toHaveLength(2); expect( match.doubleElimination?.bracketMatches.find( (bracketMatch) => bracketMatch.bracketMatchId === 'WB_R1_M1', ), ).toMatchObject({ gameCount: 3, requiredWins: 2 }); }); it('builds a missing bracket from already-persisted authoritative seeds', () => { const service = createService(); const match = createMatch({ gameMode: 'double-elimination', gameCount: 3, teams: Array.from({ length: 4 }, (_, index) => ({ teamIndex: index + 1, })), doubleElimination: { teamCount: 4, resetFinalEnabled: true, resetFinalCreated: false, seeds: [ { seedNumber: 1, teamIndex: 3 }, { seedNumber: 2, teamIndex: 1 }, { seedNumber: 3, teamIndex: 4 }, { seedNumber: 4, teamIndex: 2 }, ], bracketMatches: [], placements: {}, events: [], }, }); const random = jest.spyOn(Math, 'random').mockReturnValue(0); service.ensureGameSchedule(match); expect(match.doubleElimination?.seeds).toEqual([ { seedNumber: 1, teamIndex: 3 }, { seedNumber: 2, teamIndex: 1 }, { seedNumber: 3, teamIndex: 4 }, { seedNumber: 4, teamIndex: 2 }, ]); expect(random).not.toHaveBeenCalled(); random.mockRestore(); }); it('expands double-elimination winner bracket series into code slots', async () => { const TournamentCodeModel = { find: jest.fn().mockReturnValue({ exec: jest.fn().mockResolvedValue([]), }), }; const service = new TournamentCodeService( { getModel: jest.fn().mockResolvedValue(TournamentCodeModel) } as never, createAuctionRedisService() as never, ) as unknown as TournamentCodeServiceInternals; const match = createMatch({ gameMode: 'double-elimination', gameCount: 3, teams: Array.from({ length: 4 }, (_, index) => ({ teamIndex: index + 1, })), doubleElimination: buildDoubleEliminationBracket([1, 2, 3, 4], { resetFinalEnabled: true, }), }); const slots = await service.buildSlots(match); expect(slots.slice(0, 6)).toEqual([ expect.objectContaining({ gameNumber: 1, seriesGameNumber: 1, seriesGameCount: 3, seriesRequiredWins: 2, bracketMatchId: 'WB_R1_M1', }), expect.objectContaining({ gameNumber: 2, seriesGameNumber: 2, bracketMatchId: 'WB_R1_M1', }), expect.objectContaining({ gameNumber: 3, seriesGameNumber: 3, bracketMatchId: 'WB_R1_M1', }), expect.objectContaining({ gameNumber: 4, seriesGameNumber: 1, bracketMatchId: 'WB_R1_M2', }), expect.objectContaining({ gameNumber: 5, seriesGameNumber: 2, bracketMatchId: 'WB_R1_M2', }), expect.objectContaining({ gameNumber: 6, seriesGameNumber: 3, bracketMatchId: 'WB_R1_M2', }), ]); }); it('creates a limited round-robin schedule grouped by playable rounds', () => { const service = createService(); const roundRobin = createMatch({ gameMode: 'round-robin', gameCount: 1, roundRobinMaxRounds: 3, teams: Array.from({ length: 8 }, (_, index) => ({ teamIndex: index + 1, })), gameSchedule: [], }); service.ensureGameSchedule(roundRobin); expect(roundRobin.gameSchedule).toHaveLength(12); for (const roundNumber of [1, 2, 3]) { const round = roundRobin.gameSchedule.filter( (game) => game.roundNumber === roundNumber, ); expect(round).toHaveLength(4); expect( new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex])) .size, ).toBe(8); } }); it('leaves legacy round-robin schedules without round numbers unchanged', () => { const service = createService(); const roundRobin = createMatch({ gameMode: 'round-robin', gameCount: 1, teams: Array.from({ length: 6 }, (_, index) => ({ teamIndex: index + 1, })), gameSchedule: [ { gameNumber: 1, teamAIndex: 2, teamBIndex: 5 }, { gameNumber: 2, teamAIndex: 1, teamBIndex: 2 }, { gameNumber: 3, teamAIndex: 4, teamBIndex: 5 }, { gameNumber: 4, teamAIndex: 1, teamBIndex: 6 }, { gameNumber: 5, teamAIndex: 5, teamBIndex: 6 }, { gameNumber: 6, teamAIndex: 4, teamBIndex: 6 }, ], }); const persisted = [...roundRobin.gameSchedule]; service.ensureGameSchedule(roundRobin); expect(roundRobin.gameSchedule).toEqual(persisted); }); it('does not expose round numbers for legacy round-robin slots', async () => { const codeFindExec = jest.fn().mockResolvedValue([]); const connectionService = { getModel: jest.fn().mockResolvedValue({ find: jest.fn().mockReturnValue({ exec: codeFindExec }), }), }; const service = new TournamentCodeService( connectionService as never, createAuctionRedisService() as never, ) as unknown as TournamentCodeServiceInternals; const slots = await service.buildSlots( createMatch({ gameMode: 'round-robin', gameCount: 1, teams: Array.from({ length: 6 }, (_, index) => ({ teamIndex: index + 1, })), gameSchedule: [ { gameNumber: 1, teamAIndex: 2, teamBIndex: 5 }, { gameNumber: 2, teamAIndex: 1, teamBIndex: 2 }, { gameNumber: 3, teamAIndex: 4, teamBIndex: 5 }, { gameNumber: 4, teamAIndex: 1, teamBIndex: 6 }, { gameNumber: 5, teamAIndex: 5, teamBIndex: 6 }, { gameNumber: 6, teamAIndex: 4, teamBIndex: 6 }, { gameNumber: 7, teamAIndex: 2, teamBIndex: 6 }, { gameNumber: 8, teamAIndex: 3, teamBIndex: 5 }, { gameNumber: 9, teamAIndex: 2, teamBIndex: 3 }, { gameNumber: 10, teamAIndex: 1, teamBIndex: 4 }, { gameNumber: 11, teamAIndex: 3, teamBIndex: 6 }, { gameNumber: 12, teamAIndex: 1, teamBIndex: 3 }, { gameNumber: 13, teamAIndex: 3, teamBIndex: 4 }, { gameNumber: 14, teamAIndex: 1, teamBIndex: 5 }, { gameNumber: 15, teamAIndex: 2, teamBIndex: 4 }, ], }), ); expect(slots).toHaveLength(15); expect(slots[0]).toEqual( expect.objectContaining({ gameNumber: 1, roundNumber: undefined, teamAIndex: 2, teamBIndex: 5, }), ); expect(slots.every((slot) => slot.roundNumber === undefined)).toBe(true); }); it('does not expose fallback round-robin slots before the schedule is persisted', async () => { const service = createService(); const slots = await service.buildSlots( createMatch({ gameMode: 'round-robin', gameCount: 1, teams: Array.from({ length: 6 }, (_, index) => ({ teamIndex: index + 1, })), gameSchedule: [], }), ); expect(slots).toEqual([]); }); it('shows the active replacement when a reversed terminal code shares its game number', async () => { const oldCodeId = new mongoose.Types.ObjectId(); const replacementCodeId = new mongoose.Types.ObjectId(); const TournamentCodeModel = { find: jest.fn().mockReturnValue({ exec: jest.fn().mockResolvedValue([ { _id: replacementCodeId, code: 'NEW-CODE', gameNumber: 1, state: 'reserved', expiresAt: new Date('2026-07-13T00:00:00.000Z'), }, { _id: oldCodeId, code: 'OLD-CODE', gameNumber: 1, state: 'released', expiresAt: new Date('2026-07-13T00:00:00.000Z'), }, ]), }), }; const service = new TournamentCodeService( { getModel: jest.fn().mockResolvedValue(TournamentCodeModel) } as never, createAuctionRedisService() as never, ) as unknown as TournamentCodeServiceInternals; const match = createMatch({ gameCount: 1, teams: [{ teamIndex: 1 }, { teamIndex: 2 }], tournamentCodeIds: [oldCodeId, replacementCodeId], }); const slots = await service.buildSlots(match); expect(slots[0]).toEqual( expect.objectContaining({ gameNumber: 1, code: 'NEW-CODE', state: 'reserved', }), ); }); }); describe('TournamentCodeService bulk upload', () => { it('defines slot and riot match indexes for multi-instance safety', () => { const indexes = TournamentCodeSchema.indexes(); expect(indexes).toContainEqual([ { matchId: 1, gameNumber: 1 }, expect.objectContaining({ unique: true, partialFilterExpression: { matchId: { $exists: true }, gameNumber: { $exists: true }, state: { $in: ['reserved', 'used'] }, }, }), ]); expect(indexes).toContainEqual([ { matchId: 1, bracketMatchId: 1 }, expect.objectContaining({ partialFilterExpression: { matchId: { $exists: true }, bracketMatchId: { $exists: true }, state: { $in: ['reserved', 'used'] }, }, }), ]); expect(indexes).toContainEqual([ { riotMatchId: 1 }, expect.objectContaining({ unique: true, partialFilterExpression: { riotMatchId: { $type: 'string' } }, }), ]); }); it('preserves tournament code casing at the schema layer', async () => { const connection = mongoose.createConnection(); try { const TournamentCodeModel = connection.model( 'TournamentCodeCasingSpec', TournamentCodeSchema, ); const code = new TournamentCodeModel({ code: ' AbC-12345 ', expiresAt: new Date(Date.now() + 60 * 60 * 1000), uploadedBy: new mongoose.Types.ObjectId(), }); expect(code.code).toBe('AbC-12345'); } finally { await connection.close(); } }); it('stores tournament codes with the exact casing from input', async () => { const insertMany = jest.fn().mockResolvedValue(undefined); const TournamentCodeModel = { find: jest.fn().mockReturnValue({ select: jest.fn().mockReturnValue({ lean: jest.fn().mockReturnValue({ exec: jest.fn().mockResolvedValue([]), }), }), }), insertMany, }; const connectionService = { getModel: jest.fn().mockResolvedValue(TournamentCodeModel), }; const service = new TournamentCodeService( connectionService as never, createAuctionRedisService() as never, ) as unknown as TournamentCodeServiceInternals; service.attachPendingMatches = jest.fn().mockResolvedValue(0); await service.bulkUpload({ communityId: new mongoose.Types.ObjectId(), uploadedBy: new mongoose.Types.ObjectId(), codes: [ { code: ' AbC-12345 ', expiresAt: new Date(Date.now() + 60 * 60 * 1000).toISOString(), }, ], }); expect(insertMany).toHaveBeenCalledWith( [ expect.objectContaining({ code: 'AbC-12345', }), ], { ordered: false }, ); }); }); describe('TournamentCodeService pool stats', () => { it('counts only available codes that are usable beyond the expiry margin', async () => { const countDocuments = jest.fn().mockReturnValue({ exec: jest.fn().mockResolvedValue(12), }); const connectionService = { getModel: jest.fn().mockResolvedValue({ countDocuments }), }; const service = new TournamentCodeService( connectionService as never, createAuctionRedisService() as never, ); await expect(service.countUsableAvailable()).resolves.toBe(12); expect(countDocuments).toHaveBeenCalledWith({ state: 'available', expiresAt: { $gt: expect.any(Date), }, }); }); }); describe('TournamentCodeService pending match attachment', () => { it('does not attach tournament codes before match teams are built', async () => { const invalidMatch = { ...createMatch({ status: 'team-built', teams: [], tournamentCodeIds: [], } as unknown as MatchOverrides), isModified: jest.fn().mockReturnValue(false), }; const validMatch = { ...createMatch({ status: 'team-built', teams: [ { teamIndex: 1, members: [{ userId: new mongoose.Types.ObjectId() }], }, { teamIndex: 2, members: [{ userId: new mongoose.Types.ObjectId() }], }, ], tournamentCodeIds: [], } as unknown as MatchOverrides), isModified: jest.fn().mockReturnValue(false), }; const codeId = new mongoose.Types.ObjectId(); const MatchModel = { find: jest.fn().mockReturnValue({ exec: jest.fn().mockResolvedValue([invalidMatch, validMatch]), }), findById: jest.fn().mockResolvedValue(validMatch), }; const TournamentCodeModel = { findOneAndUpdate: jest.fn().mockReturnValue({ exec: jest.fn().mockResolvedValue({ _id: codeId }), }), }; const session = createSession(); const connectionService = { createSession: jest.fn().mockResolvedValue(session), getModel: jest.fn().mockImplementation((modelName: string) => { if (modelName === 'match') return Promise.resolve(MatchModel); if (modelName === 'tournamentCode') { return Promise.resolve(TournamentCodeModel); } throw new Error(`Unexpected model: ${modelName}`); }), }; const auctionRedisService = createAuctionRedisService(); const service = new TournamentCodeService( connectionService as never, auctionRedisService as never, ); const matches = await service.attachPendingMatchDocuments(); expect(matches).toEqual([validMatch]); expect(MatchModel.findById).toHaveBeenCalledTimes(1); expect(MatchModel.findById).toHaveBeenCalledWith(validMatch._id); expect(TournamentCodeModel.findOneAndUpdate).toHaveBeenCalledTimes(1); expect(auctionRedisService.acquireTokenLock).toHaveBeenCalledWith( `tournament-code:match:${validMatch._id.toString()}:lock`, expect.any(String), expect.any(Number), ); expect(session.startTransaction).toHaveBeenCalledTimes(1); expect(session.commitTransaction).toHaveBeenCalledTimes(1); expect(auctionRedisService.releaseTokenLock).toHaveBeenCalledWith( `tournament-code:match:${validMatch._id.toString()}:lock`, expect.any(String), ); expect(validMatch.tournamentCodeIds.map((id) => id.toString())).toEqual([ codeId.toString(), ]); expect(invalidMatch.tournamentCodeIds).toEqual([]); }); }); describe('TournamentCodeService Competition assignment safety', () => { it('does not restore an actively reserved code outside Competition commands', async () => { const code = { _id: new mongoose.Types.ObjectId(), state: 'reserved', save: jest.fn(), }; const connectionService = { getModel: jest.fn().mockImplementation((name: string) => { if (name === 'tournamentCode') { return Promise.resolve({ findById: jest.fn().mockResolvedValue(code), }); } if (name === 'match') return Promise.resolve({}); throw new Error(`Unexpected model ${name}`); }), }; const service = new TournamentCodeService( connectionService as never, createAuctionRedisService() as never, ); await expect(service.restoreToAvailable(code._id)).rejects.toThrow( 'Active Competition assignments', ); expect(code.save).not.toHaveBeenCalled(); }); it('expires a reserved code and releases its assignment and Match binding atomically', async () => { const codeId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId(); const competitionId = new mongoose.Types.ObjectId(); const assignmentId = new mongoose.Types.ObjectId(); const session = createSession(); const code = { _id: codeId, state: 'reserved', matchId }; const codeUpdate = jest.fn().mockReturnValue(mongoQuery(code)); const assignmentUpdate = jest .fn() .mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 })); const matchUpdate = jest .fn() .mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 })); const models = { tournamentCode: { find: jest.fn().mockReturnValue(mongoQuery([{ _id: codeId }])), findOne: jest.fn().mockReturnValue(mongoQuery(code)), findOneAndUpdate: codeUpdate, }, tournamentCodeAssignment: { find: jest.fn().mockReturnValue( mongoQuery([ { _id: assignmentId, competitionId, state: 'reserved', }, ]), ), updateOne: assignmentUpdate, }, competition: { findById: jest.fn().mockReturnValue(mongoQuery({ matchId })), }, match: { updateOne: matchUpdate }, }; const service = new TournamentCodeService( { createSession: jest.fn().mockResolvedValue(session), getModel: jest.fn((name: keyof typeof models) => Promise.resolve(models[name]), ), } as never, createAuctionRedisService() as never, ); await expect(service.markExpired()).resolves.toEqual({ affectedMatchIds: [matchId], expiredCount: 1, failedCount: 0, }); expect(codeUpdate).toHaveBeenCalledWith( { _id: codeId, expiresAt: { $lte: expect.any(Date) as Date }, state: 'reserved', }, { $set: { state: 'expired' }, $unset: { bracketMatchId: 1, gameNumber: 1, matchId: 1, reservedAt: 1, }, }, { returnDocument: 'before', session }, ); expect(assignmentUpdate).toHaveBeenCalledWith( { _id: assignmentId, state: 'reserved' }, { $set: { releasedAt: expect.any(Date) as Date, state: 'released' }, }, { session }, ); expect(matchUpdate).toHaveBeenCalledWith( { _id: matchId }, { $pull: { tournamentCodeIds: codeId } }, { session }, ); expect(session.commitTransaction).toHaveBeenCalledTimes(1); }); it('isolates a used-assignment corruption and still expires the next valid candidate', async () => { const corruptCodeId = new mongoose.Types.ObjectId(); const validCodeId = new mongoose.Types.ObjectId(); const corruptMatchId = new mongoose.Types.ObjectId(); const validMatchId = new mongoose.Types.ObjectId(); const competitionId = new mongoose.Types.ObjectId(); const validAssignmentId = new mongoose.Types.ObjectId(); const sessions = [createSession(), createSession()]; const codeById = new Map([ [ corruptCodeId.toString(), { _id: corruptCodeId, state: 'reserved', matchId: corruptMatchId }, ], [ validCodeId.toString(), { _id: validCodeId, state: 'reserved', matchId: validMatchId }, ], ]); const codeUpdate = jest.fn((filter: { _id: mongoose.Types.ObjectId }) => mongoQuery(codeById.get(filter._id.toString())), ); const assignmentUpdate = jest .fn() .mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 })); const matchUpdate = jest .fn() .mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 })); const models = { tournamentCode: { find: jest .fn() .mockReturnValue( mongoQuery([{ _id: corruptCodeId }, { _id: validCodeId }]), ), findOne: jest.fn((filter: { _id: mongoose.Types.ObjectId }) => mongoQuery(codeById.get(filter._id.toString())), ), findOneAndUpdate: codeUpdate, }, tournamentCodeAssignment: { find: jest.fn((filter: { tournamentCodeId: mongoose.Types.ObjectId }) => mongoQuery( filter.tournamentCodeId.equals(corruptCodeId) ? [ { _id: new mongoose.Types.ObjectId(), competitionId, state: 'used', }, ] : [ { _id: validAssignmentId, competitionId, state: 'reserved', }, ], ), ), updateOne: assignmentUpdate, }, competition: { findById: jest .fn() .mockReturnValue(mongoQuery({ matchId: validMatchId })), }, match: { updateOne: matchUpdate }, }; const errorLog = jest .spyOn(Logger.prototype, 'error') .mockImplementation(() => undefined); const service = new TournamentCodeService( { createSession: jest .fn() .mockImplementation(() => Promise.resolve(sessions.shift())), getModel: jest.fn((name: keyof typeof models) => Promise.resolve(models[name]), ), } as never, createAuctionRedisService() as never, ); await expect(service.markExpired()).resolves.toEqual({ affectedMatchIds: [validMatchId], expiredCount: 1, failedCount: 1, }); expect(codeUpdate).toHaveBeenCalledTimes(1); expect(codeUpdate.mock.calls[0][0]).toMatchObject({ _id: validCodeId }); expect(assignmentUpdate).toHaveBeenCalledWith( { _id: validAssignmentId, state: 'reserved' }, expect.any(Object), expect.any(Object), ); expect(errorLog).toHaveBeenCalledWith( expect.stringContaining('used Competition assignment'), ); errorLog.mockRestore(); }); it('leaves a foreign Competition assignment unchanged and reports the candidate failure', async () => { const codeId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId(); const foreignMatchId = new mongoose.Types.ObjectId(); const competitionId = new mongoose.Types.ObjectId(); const code = { _id: codeId, state: 'reserved', matchId }; const codeUpdate = jest.fn(); const session = createSession(); const models = { tournamentCode: { find: jest.fn().mockReturnValue(mongoQuery([{ _id: codeId }])), findOne: jest.fn().mockReturnValue(mongoQuery(code)), findOneAndUpdate: codeUpdate, }, tournamentCodeAssignment: { find: jest.fn().mockReturnValue( mongoQuery([ { _id: new mongoose.Types.ObjectId(), competitionId, state: 'reserved', }, ]), ), updateOne: jest.fn(), }, competition: { findById: jest .fn() .mockReturnValue(mongoQuery({ matchId: foreignMatchId })), }, match: { updateOne: jest.fn() }, }; const errorLog = jest .spyOn(Logger.prototype, 'error') .mockImplementation(() => undefined); const service = new TournamentCodeService( { createSession: jest.fn().mockResolvedValue(session), getModel: jest.fn((name: keyof typeof models) => Promise.resolve(models[name]), ), } as never, createAuctionRedisService() as never, ); await expect(service.markExpired()).resolves.toEqual({ affectedMatchIds: [], expiredCount: 0, failedCount: 1, }); expect(codeUpdate).not.toHaveBeenCalled(); expect(session.abortTransaction).toHaveBeenCalledTimes(1); expect(errorLog).toHaveBeenCalledWith( expect.stringContaining('ownership does not match'), ); errorLog.mockRestore(); }); });