feat: expose revision-safe competition API
This commit is contained in:
1 parent
f3286e7fd1
commit
55e5b8df70
11 files changed
+2443
-19
No files matched your search
@@ -8,6 +8,7 @@ import { AuctionModule } from './modules/auction/auction.module';
|
|||||||
import { AuthModule } from './modules/auth/auth.module';
|
import { AuthModule } from './modules/auth/auth.module';
|
||||||
import { CommunityModule } from './modules/community/community.module';
|
import { CommunityModule } from './modules/community/community.module';
|
||||||
import { CommunityStatsModule } from './modules/community-stats/community-stats.module';
|
import { CommunityStatsModule } from './modules/community-stats/community-stats.module';
|
||||||
|
import { CompetitionModule } from './modules/competition/competition.module';
|
||||||
import { DakaoModule } from './modules/dakao/dakao.module';
|
import { DakaoModule } from './modules/dakao/dakao.module';
|
||||||
import { GlobalModule } from './modules/global/global.module';
|
import { GlobalModule } from './modules/global/global.module';
|
||||||
import { LegacyImportModule } from './modules/legacy-import/legacy-import.module';
|
import { LegacyImportModule } from './modules/legacy-import/legacy-import.module';
|
||||||
@@ -31,6 +32,7 @@ import { UserModule } from './modules/user/user.module';
|
|||||||
BackgroundRefreshModule,
|
BackgroundRefreshModule,
|
||||||
CommunityModule,
|
CommunityModule,
|
||||||
CommunityStatsModule,
|
CommunityStatsModule,
|
||||||
|
CompetitionModule,
|
||||||
MatchModule,
|
MatchModule,
|
||||||
MatchHistoryModule,
|
MatchHistoryModule,
|
||||||
LegacyImportModule,
|
LegacyImportModule,
|
||||||
|
|||||||
@@ -18,7 +18,14 @@ async function bootstrap() {
|
|||||||
app.enableCors({
|
app.enableCors({
|
||||||
origin: createCorsOrigin(nodeEnv),
|
origin: createCorsOrigin(nodeEnv),
|
||||||
credentials: true,
|
credentials: true,
|
||||||
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
|
allowedHeaders: [
|
||||||
|
'Authorization',
|
||||||
|
'Content-Type',
|
||||||
|
'X-Auth-User-Id',
|
||||||
|
'If-Match',
|
||||||
|
'Idempotency-Key',
|
||||||
|
],
|
||||||
|
exposedHeaders: ['ETag'],
|
||||||
});
|
});
|
||||||
app.useGlobalPipes(
|
app.useGlobalPipes(
|
||||||
new ValidationPipe({
|
new ValidationPipe({
|
||||||
|
|||||||
@@ -162,6 +162,15 @@ describe('CompetitionCommandService', () => {
|
|||||||
gameId: GAME_ID,
|
gameId: GAME_ID,
|
||||||
seriesId: SERIES_ID,
|
seriesId: SERIES_ID,
|
||||||
gameSlotId: GAME_SLOT_ID,
|
gameSlotId: GAME_SLOT_ID,
|
||||||
|
startedAt: new Date('2026-07-12T09:30:00.000Z'),
|
||||||
|
durationSeconds: 1_800,
|
||||||
|
participants: [
|
||||||
|
{
|
||||||
|
userId: USER_ID.toHexString(),
|
||||||
|
teamId: TEAM_A_ID.toHexString(),
|
||||||
|
side: 'blue',
|
||||||
|
},
|
||||||
|
],
|
||||||
});
|
});
|
||||||
expect(factOptions).toEqual({ session: harness.session });
|
expect(factOptions).toEqual({ session: harness.session });
|
||||||
|
|
||||||
@@ -253,6 +262,134 @@ describe('CompetitionCommandService', () => {
|
|||||||
expect(harness.assignmentModel.updateOne).not.toHaveBeenCalled();
|
expect(harness.assignmentModel.updateOne).not.toHaveBeenCalled();
|
||||||
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
|
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('previews a strict or cascade reversal against the requested revision', async () => {
|
||||||
|
const reversal = reversalFixture();
|
||||||
|
const harness = createHarness({
|
||||||
|
competition: reversal.competition,
|
||||||
|
facts: reversal.facts,
|
||||||
|
assignments: reversal.assignments,
|
||||||
|
});
|
||||||
|
const service = new CompetitionCommandService(
|
||||||
|
harness.connectionService as ConnectionService,
|
||||||
|
);
|
||||||
|
|
||||||
|
const preview = await service.previewSeriesReversal({
|
||||||
|
competitionId: COMPETITION_ID,
|
||||||
|
expectedRevision: 7,
|
||||||
|
seriesId: reversal.parentSeriesId,
|
||||||
|
mode: 'cascade',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(preview).toMatchObject({
|
||||||
|
sourceRevision: 7,
|
||||||
|
impactHash: expect.stringMatching(/^[a-f0-9]{64}$/),
|
||||||
|
impact: {
|
||||||
|
seriesIds: [
|
||||||
|
reversal.parentSeriesId.toHexString(),
|
||||||
|
reversal.childSeriesId.toHexString(),
|
||||||
|
],
|
||||||
|
factIds: [
|
||||||
|
reversal.parentFactId.toHexString(),
|
||||||
|
reversal.childFactId.toHexString(),
|
||||||
|
],
|
||||||
|
releasesReservedCodes: 1,
|
||||||
|
voidsUsedCodes: 1,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a reversal preview at a stale revision', async () => {
|
||||||
|
const reversal = reversalFixture();
|
||||||
|
const harness = createHarness({ competition: reversal.competition });
|
||||||
|
const service = new CompetitionCommandService(
|
||||||
|
harness.connectionService as ConnectionService,
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.previewSeriesReversal({
|
||||||
|
competitionId: COMPETITION_ID,
|
||||||
|
expectedRevision: 6,
|
||||||
|
seriesId: reversal.parentSeriesId,
|
||||||
|
mode: 'strict',
|
||||||
|
}),
|
||||||
|
).rejects.toMatchObject({
|
||||||
|
code: 'STALE_COMPETITION_REVISION',
|
||||||
|
httpStatus: 412,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hash-confirms and atomically appends cascade reversal facts', async () => {
|
||||||
|
const reversal = reversalFixture();
|
||||||
|
const harness = createHarness({
|
||||||
|
competition: reversal.competition,
|
||||||
|
facts: reversal.facts,
|
||||||
|
assignments: reversal.assignments,
|
||||||
|
});
|
||||||
|
const service = new CompetitionCommandService(
|
||||||
|
harness.connectionService as ConnectionService,
|
||||||
|
);
|
||||||
|
const preview = await service.previewSeriesReversal({
|
||||||
|
competitionId: COMPETITION_ID,
|
||||||
|
expectedRevision: 7,
|
||||||
|
seriesId: reversal.parentSeriesId,
|
||||||
|
mode: 'cascade',
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.reverseSeries({
|
||||||
|
competitionId: COMPETITION_ID,
|
||||||
|
expectedRevision: 7,
|
||||||
|
idempotencyKey: 'admin:reverse:1',
|
||||||
|
actor: { type: 'user', userId: USER_ID },
|
||||||
|
seriesId: reversal.parentSeriesId,
|
||||||
|
mode: 'cascade',
|
||||||
|
reason: 'Wrong result ingestion',
|
||||||
|
impactHash: preview.impactHash,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toMatchObject({ revision: 8, replayed: false });
|
||||||
|
expect(harness.factModel.insertMany).toHaveBeenCalledWith(
|
||||||
|
[
|
||||||
|
expect.objectContaining({
|
||||||
|
_id: expect.any(Types.ObjectId),
|
||||||
|
type: 'game-voided',
|
||||||
|
gameAcceptedFactId: reversal.parentFactId,
|
||||||
|
revision: 8,
|
||||||
|
ordinalWithinRevision: 1,
|
||||||
|
reason: 'Wrong result ingestion',
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
_id: expect.any(Types.ObjectId),
|
||||||
|
type: 'game-voided',
|
||||||
|
gameAcceptedFactId: reversal.childFactId,
|
||||||
|
revision: 8,
|
||||||
|
ordinalWithinRevision: 2,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
{ session: harness.session },
|
||||||
|
);
|
||||||
|
expect(harness.assignmentModel.updateMany).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
competitionId: COMPETITION_ID,
|
||||||
|
gameSlotId: {
|
||||||
|
$in: expect.arrayContaining([
|
||||||
|
reversal.parentGameSlotId,
|
||||||
|
reversal.childGameSlotId,
|
||||||
|
]),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
expect.any(Array),
|
||||||
|
{ session: harness.session },
|
||||||
|
);
|
||||||
|
expect(harness.tournamentCodeModel.updateMany).toHaveBeenCalled();
|
||||||
|
expect(harness.competitionModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||||
|
{ _id: COMPETITION_ID, revision: 7 },
|
||||||
|
expect.objectContaining({ $inc: { revision: 1 } }),
|
||||||
|
expect.objectContaining({ session: harness.session }),
|
||||||
|
);
|
||||||
|
expect(harness.outboxModel.insertMany).toHaveBeenCalledTimes(1);
|
||||||
|
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const COMPETITION_ID = new Types.ObjectId('64b000000000000000000001');
|
const COMPETITION_ID = new Types.ObjectId('64b000000000000000000001');
|
||||||
@@ -300,6 +437,15 @@ function acceptGameCommand() {
|
|||||||
winnerTeamId: TEAM_A_ID,
|
winnerTeamId: TEAM_A_ID,
|
||||||
participantAssignments: [],
|
participantAssignments: [],
|
||||||
},
|
},
|
||||||
|
startedAt: new Date('2026-07-12T09:30:00.000Z'),
|
||||||
|
durationSeconds: 1_800,
|
||||||
|
participants: [
|
||||||
|
{
|
||||||
|
userId: USER_ID.toHexString(),
|
||||||
|
teamId: TEAM_A_ID.toHexString(),
|
||||||
|
side: 'blue',
|
||||||
|
},
|
||||||
|
],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -307,6 +453,9 @@ function createHarness(
|
|||||||
options: {
|
options: {
|
||||||
competitionRevision?: number;
|
competitionRevision?: number;
|
||||||
casResult?: Record<string, unknown> | null;
|
casResult?: Record<string, unknown> | null;
|
||||||
|
competition?: Record<string, unknown>;
|
||||||
|
facts?: Array<Record<string, unknown>>;
|
||||||
|
assignments?: Array<Record<string, unknown>>;
|
||||||
} = {},
|
} = {},
|
||||||
) {
|
) {
|
||||||
const session = {
|
const session = {
|
||||||
@@ -315,7 +464,9 @@ function createHarness(
|
|||||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||||
endSession: jest.fn().mockResolvedValue(undefined),
|
endSession: jest.fn().mockResolvedValue(undefined),
|
||||||
};
|
};
|
||||||
const competition = competitionDocument(options.competitionRevision ?? 7);
|
const competition =
|
||||||
|
options.competition ??
|
||||||
|
competitionDocument(options.competitionRevision ?? 7);
|
||||||
const competitionModel = {
|
const competitionModel = {
|
||||||
findById: jest.fn().mockReturnValue(queryResult(competition)),
|
findById: jest.fn().mockReturnValue(queryResult(competition)),
|
||||||
findOneAndUpdate: jest
|
findOneAndUpdate: jest
|
||||||
@@ -329,7 +480,7 @@ function createHarness(
|
|||||||
),
|
),
|
||||||
};
|
};
|
||||||
const factModel = {
|
const factModel = {
|
||||||
find: jest.fn().mockReturnValue(queryResult([])),
|
find: jest.fn().mockReturnValue(queryResult(options.facts ?? [])),
|
||||||
insertMany: jest.fn().mockResolvedValue([]),
|
insertMany: jest.fn().mockResolvedValue([]),
|
||||||
};
|
};
|
||||||
const outboxModel = {
|
const outboxModel = {
|
||||||
@@ -337,10 +488,13 @@ function createHarness(
|
|||||||
insertMany: jest.fn().mockResolvedValue([]),
|
insertMany: jest.fn().mockResolvedValue([]),
|
||||||
};
|
};
|
||||||
const assignmentModel = {
|
const assignmentModel = {
|
||||||
|
find: jest.fn().mockReturnValue(queryResult(options.assignments ?? [])),
|
||||||
updateOne: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
|
updateOne: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
|
||||||
|
updateMany: jest.fn().mockResolvedValue({ modifiedCount: 2 }),
|
||||||
};
|
};
|
||||||
const tournamentCodeModel = {
|
const tournamentCodeModel = {
|
||||||
updateOne: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
|
updateOne: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
|
||||||
|
updateMany: jest.fn().mockResolvedValue({ modifiedCount: 2 }),
|
||||||
};
|
};
|
||||||
const models: Record<string, unknown> = {
|
const models: Record<string, unknown> = {
|
||||||
competition: competitionModel,
|
competition: competitionModel,
|
||||||
@@ -399,3 +553,103 @@ function queryResult<T>(value: T) {
|
|||||||
query.lean.mockReturnValue(query);
|
query.lean.mockReturnValue(query);
|
||||||
return query;
|
return query;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function reversalFixture() {
|
||||||
|
const parentSeriesId = new Types.ObjectId('64b000000000000000000021');
|
||||||
|
const childSeriesId = new Types.ObjectId('64b000000000000000000022');
|
||||||
|
const parentFactId = new Types.ObjectId('64b000000000000000000023');
|
||||||
|
const childFactId = new Types.ObjectId('64b000000000000000000024');
|
||||||
|
const parentGameSlotId = new Types.ObjectId('64b000000000000000000025');
|
||||||
|
const childGameSlotId = new Types.ObjectId('64b000000000000000000026');
|
||||||
|
const parentCodeId = new Types.ObjectId('64b000000000000000000027');
|
||||||
|
const childCodeId = new Types.ObjectId('64b000000000000000000028');
|
||||||
|
const series = (
|
||||||
|
id: Types.ObjectId,
|
||||||
|
sourceA: Record<string, unknown>,
|
||||||
|
sourceB: Record<string, unknown>,
|
||||||
|
) => ({
|
||||||
|
id: id.toHexString(),
|
||||||
|
stage: { type: 'upper', displayOrder: 1 },
|
||||||
|
slots: [
|
||||||
|
{ position: 'A', source: sourceA },
|
||||||
|
{ position: 'B', source: sourceB },
|
||||||
|
],
|
||||||
|
rule: { type: 'first-to', winsRequired: 1, maxGames: 1 },
|
||||||
|
gameSlots: [],
|
||||||
|
});
|
||||||
|
const accepted = (
|
||||||
|
_id: Types.ObjectId,
|
||||||
|
seriesId: Types.ObjectId,
|
||||||
|
gameSlotId: Types.ObjectId,
|
||||||
|
) => ({
|
||||||
|
_id,
|
||||||
|
competitionId: COMPETITION_ID,
|
||||||
|
type: 'game-accepted',
|
||||||
|
revision: 1,
|
||||||
|
ordinalWithinRevision: 1,
|
||||||
|
commandId: `command-${_id.toHexString()}`,
|
||||||
|
idempotencyKey: `key-${_id.toHexString()}`,
|
||||||
|
requestHash: `hash-${_id.toHexString()}`,
|
||||||
|
schemaVersion: 1,
|
||||||
|
actor: { type: 'system' },
|
||||||
|
occurredAt: new Date('2026-07-12T00:00:00.000Z'),
|
||||||
|
recordedAt: new Date('2026-07-12T00:00:00.000Z'),
|
||||||
|
gameId: new Types.ObjectId(),
|
||||||
|
seriesId,
|
||||||
|
gameSlotId,
|
||||||
|
ordinal: 1,
|
||||||
|
evidence: { type: 'legacy', legacyReference: 'legacy' },
|
||||||
|
mapping: {
|
||||||
|
blueTeamId: TEAM_A_ID,
|
||||||
|
redTeamId: TEAM_B_ID,
|
||||||
|
winnerTeamId: TEAM_A_ID,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
parentSeriesId,
|
||||||
|
childSeriesId,
|
||||||
|
parentFactId,
|
||||||
|
childFactId,
|
||||||
|
parentGameSlotId,
|
||||||
|
childGameSlotId,
|
||||||
|
competition: {
|
||||||
|
...competitionDocument(7),
|
||||||
|
seriesGraph: [
|
||||||
|
series(
|
||||||
|
parentSeriesId,
|
||||||
|
{ type: 'team', teamId: TEAM_A_ID.toHexString() },
|
||||||
|
{ type: 'team', teamId: TEAM_B_ID.toHexString() },
|
||||||
|
),
|
||||||
|
series(
|
||||||
|
childSeriesId,
|
||||||
|
{
|
||||||
|
type: 'series-outcome',
|
||||||
|
seriesId: parentSeriesId.toHexString(),
|
||||||
|
select: 'winner',
|
||||||
|
},
|
||||||
|
{ type: 'team', teamId: TEAM_B_ID.toHexString() },
|
||||||
|
),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
facts: [
|
||||||
|
accepted(parentFactId, parentSeriesId, parentGameSlotId),
|
||||||
|
accepted(childFactId, childSeriesId, childGameSlotId),
|
||||||
|
],
|
||||||
|
assignments: [
|
||||||
|
{
|
||||||
|
competitionId: COMPETITION_ID,
|
||||||
|
seriesId: parentSeriesId,
|
||||||
|
gameSlotId: parentGameSlotId,
|
||||||
|
tournamentCodeId: parentCodeId,
|
||||||
|
state: 'used',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
competitionId: COMPETITION_ID,
|
||||||
|
seriesId: childSeriesId,
|
||||||
|
gameSlotId: childGameSlotId,
|
||||||
|
tournamentCodeId: childCodeId,
|
||||||
|
state: 'reserved',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -5,6 +5,13 @@ import { ConnectionService } from '../global/database/connection.service';
|
|||||||
import type { Competition, CompetitionOutbox } from './competition.schema';
|
import type { Competition, CompetitionOutbox } from './competition.schema';
|
||||||
import { CompetitionCommandError } from './competition.errors';
|
import { CompetitionCommandError } from './competition.errors';
|
||||||
import { projectCompetition } from './domain/competition-projector';
|
import { projectCompetition } from './domain/competition-projector';
|
||||||
|
import {
|
||||||
|
assertReversalPreview,
|
||||||
|
buildReversalFacts,
|
||||||
|
previewSeriesReversal as planSeriesReversal,
|
||||||
|
type SeriesReversalMode,
|
||||||
|
type SeriesReversalPreview,
|
||||||
|
} from './domain/competition-reversal';
|
||||||
|
|
||||||
type PersistenceId = string | mongoose.Types.ObjectId;
|
type PersistenceId = string | mongoose.Types.ObjectId;
|
||||||
|
|
||||||
@@ -25,6 +32,9 @@ export interface AcceptGameCommand {
|
|||||||
ordinal: number;
|
ordinal: number;
|
||||||
evidence: Readonly<Record<string, unknown>>;
|
evidence: Readonly<Record<string, unknown>>;
|
||||||
mapping: Readonly<Record<string, unknown>>;
|
mapping: Readonly<Record<string, unknown>>;
|
||||||
|
startedAt?: Date;
|
||||||
|
durationSeconds?: number;
|
||||||
|
participants?: readonly Readonly<Record<string, unknown>>[];
|
||||||
tournamentCode?: {
|
tournamentCode?: {
|
||||||
tournamentCodeId: PersistenceId;
|
tournamentCodeId: PersistenceId;
|
||||||
riotMatchId: string;
|
riotMatchId: string;
|
||||||
@@ -49,6 +59,21 @@ export interface AdjudicateSeriesCommand {
|
|||||||
reason: string;
|
reason: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface PreviewSeriesReversalCommand {
|
||||||
|
competitionId: PersistenceId;
|
||||||
|
expectedRevision: number;
|
||||||
|
seriesId: PersistenceId;
|
||||||
|
mode: SeriesReversalMode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReverseSeriesCommand extends PreviewSeriesReversalCommand {
|
||||||
|
idempotencyKey: string;
|
||||||
|
actor: CompetitionCommandActor;
|
||||||
|
occurredAt?: Date;
|
||||||
|
reason: string;
|
||||||
|
impactHash: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface CompetitionCommandResult {
|
export interface CompetitionCommandResult {
|
||||||
competition: unknown;
|
competition: unknown;
|
||||||
commandId: string;
|
commandId: string;
|
||||||
@@ -57,7 +82,7 @@ export interface CompetitionCommandResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface CommandEnvelope {
|
interface CommandEnvelope {
|
||||||
type: 'accept-game' | 'adjudicate-series';
|
type: 'accept-game' | 'adjudicate-series' | 'reverse-series';
|
||||||
competitionId: PersistenceId;
|
competitionId: PersistenceId;
|
||||||
expectedRevision: number;
|
expectedRevision: number;
|
||||||
idempotencyKey: string;
|
idempotencyKey: string;
|
||||||
@@ -87,6 +112,11 @@ export class CompetitionCommandService {
|
|||||||
ordinal: command.ordinal,
|
ordinal: command.ordinal,
|
||||||
evidence: command.evidence,
|
evidence: command.evidence,
|
||||||
mapping: command.mapping,
|
mapping: command.mapping,
|
||||||
|
...(command.startedAt ? { startedAt: command.startedAt } : {}),
|
||||||
|
...(command.durationSeconds === undefined
|
||||||
|
? {}
|
||||||
|
: { durationSeconds: command.durationSeconds }),
|
||||||
|
...(command.participants ? { participants: command.participants } : {}),
|
||||||
...(command.tournamentCode
|
...(command.tournamentCode
|
||||||
? { tournamentCode: command.tournamentCode }
|
? { tournamentCode: command.tournamentCode }
|
||||||
: {}),
|
: {}),
|
||||||
@@ -112,6 +142,214 @@ export class CompetitionCommandService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async previewSeriesReversal(
|
||||||
|
command: PreviewSeriesReversalCommand,
|
||||||
|
): Promise<SeriesReversalPreview> {
|
||||||
|
if (
|
||||||
|
!Number.isInteger(command.expectedRevision) ||
|
||||||
|
command.expectedRevision < 0
|
||||||
|
) {
|
||||||
|
throw invalidCommandError();
|
||||||
|
}
|
||||||
|
const CompetitionModel =
|
||||||
|
await this.connectionService.getModel('competition');
|
||||||
|
const competition = await CompetitionModel.findById(command.competitionId)
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
if (!competition) throw competitionNotFound(command.competitionId);
|
||||||
|
assertExpectedRevision(competition.revision, command.expectedRevision);
|
||||||
|
|
||||||
|
const [FactModel, AssignmentModel] = await Promise.all([
|
||||||
|
this.connectionService.getModel('competitionFact'),
|
||||||
|
this.connectionService.getModel('tournamentCodeAssignment'),
|
||||||
|
]);
|
||||||
|
const [facts, assignments] = await Promise.all([
|
||||||
|
FactModel.find({ competitionId: command.competitionId })
|
||||||
|
.sort({ revision: 1, ordinalWithinRevision: 1 })
|
||||||
|
.lean()
|
||||||
|
.exec(),
|
||||||
|
AssignmentModel.find({ competitionId: command.competitionId })
|
||||||
|
.lean()
|
||||||
|
.exec(),
|
||||||
|
]);
|
||||||
|
const revisionCheck = await CompetitionModel.findById(command.competitionId)
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
if (!revisionCheck) throw competitionNotFound(command.competitionId);
|
||||||
|
assertExpectedRevision(revisionCheck.revision, command.expectedRevision);
|
||||||
|
return planSeriesReversal(
|
||||||
|
reversalInput(competition, command, facts, assignments),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async reverseSeries(
|
||||||
|
command: ReverseSeriesCommand,
|
||||||
|
): Promise<CompetitionCommandResult> {
|
||||||
|
const envelope: CommandEnvelope = {
|
||||||
|
type: 'reverse-series',
|
||||||
|
competitionId: command.competitionId,
|
||||||
|
expectedRevision: command.expectedRevision,
|
||||||
|
idempotencyKey: command.idempotencyKey,
|
||||||
|
actor: command.actor,
|
||||||
|
occurredAt: command.occurredAt,
|
||||||
|
payload: {
|
||||||
|
seriesId: command.seriesId,
|
||||||
|
mode: command.mode,
|
||||||
|
reason: command.reason.trim(),
|
||||||
|
impactHash: command.impactHash,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
validateEnvelope(envelope);
|
||||||
|
if (!/^[a-f0-9]{64}$/.test(command.impactHash)) {
|
||||||
|
throw invalidCommandError();
|
||||||
|
}
|
||||||
|
|
||||||
|
const session = await this.connectionService.createSession();
|
||||||
|
if (!session) {
|
||||||
|
throw new CompetitionCommandError(
|
||||||
|
'COMPETITION_TRANSACTION_UNAVAILABLE',
|
||||||
|
'A MongoDB transaction is required for Competition commands.',
|
||||||
|
500,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
session.startTransaction();
|
||||||
|
const [CompetitionModel, FactModel, OutboxModel, AssignmentModel] =
|
||||||
|
await Promise.all([
|
||||||
|
this.connectionService.getModel('competition'),
|
||||||
|
this.connectionService.getModel('competitionFact'),
|
||||||
|
this.connectionService.getModel('competitionOutbox'),
|
||||||
|
this.connectionService.getModel('tournamentCodeAssignment'),
|
||||||
|
]);
|
||||||
|
const requestHash = requestHashFor(envelope);
|
||||||
|
const commandId = commandIdFor(envelope);
|
||||||
|
const receipt = await OutboxModel.findOne({
|
||||||
|
competitionId: command.competitionId,
|
||||||
|
idempotencyKey: command.idempotencyKey,
|
||||||
|
})
|
||||||
|
.session(session)
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
if (receipt) {
|
||||||
|
const replay = await this.replay(
|
||||||
|
CompetitionModel,
|
||||||
|
command.competitionId,
|
||||||
|
requestHash,
|
||||||
|
receipt,
|
||||||
|
session,
|
||||||
|
);
|
||||||
|
await session.commitTransaction();
|
||||||
|
return replay;
|
||||||
|
}
|
||||||
|
|
||||||
|
const competition = await CompetitionModel.findById(command.competitionId)
|
||||||
|
.session(session)
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
if (!competition) throw competitionNotFound(command.competitionId);
|
||||||
|
assertExpectedRevision(competition.revision, command.expectedRevision);
|
||||||
|
|
||||||
|
const [existingFacts, assignments] = await Promise.all([
|
||||||
|
FactModel.find({ competitionId: command.competitionId })
|
||||||
|
.sort({ revision: 1, ordinalWithinRevision: 1 })
|
||||||
|
.session(session)
|
||||||
|
.lean()
|
||||||
|
.exec(),
|
||||||
|
AssignmentModel.find({ competitionId: command.competitionId })
|
||||||
|
.session(session)
|
||||||
|
.lean()
|
||||||
|
.exec(),
|
||||||
|
]);
|
||||||
|
const input = reversalInput(
|
||||||
|
competition,
|
||||||
|
command,
|
||||||
|
existingFacts,
|
||||||
|
assignments,
|
||||||
|
);
|
||||||
|
const preview = assertReversalPreview(input, command.impactHash);
|
||||||
|
const nextRevision = command.expectedRevision + 1;
|
||||||
|
const recordedAt = new Date();
|
||||||
|
const occurredAt = command.occurredAt ?? recordedAt;
|
||||||
|
const rawFacts = buildReversalFacts({
|
||||||
|
preview,
|
||||||
|
facts: input.facts,
|
||||||
|
competitionId: idString(command.competitionId),
|
||||||
|
commandId,
|
||||||
|
nextRevision,
|
||||||
|
actor: toPlain(command.actor) as Readonly<Record<string, unknown>>,
|
||||||
|
reason: command.reason.trim(),
|
||||||
|
occurredAt,
|
||||||
|
});
|
||||||
|
const reversalFacts = rawFacts.map((rawFact) =>
|
||||||
|
persistenceReversalFact(rawFact, command, commandId, requestHash),
|
||||||
|
);
|
||||||
|
const projection = projectCompetition({
|
||||||
|
competitionId: idString(command.competitionId),
|
||||||
|
revision: nextRevision,
|
||||||
|
projectorVersion: competition.projectorVersion,
|
||||||
|
teams: toPlain(competition.teams) as never,
|
||||||
|
format: toPlain(competition.format) as never,
|
||||||
|
seriesGraph: toPlain(competition.seriesGraph) as never,
|
||||||
|
facts: [...existingFacts, ...reversalFacts].map(factForProjection),
|
||||||
|
});
|
||||||
|
|
||||||
|
await FactModel.insertMany(reversalFacts, { session });
|
||||||
|
const updated = await CompetitionModel.findOneAndUpdate(
|
||||||
|
{ _id: command.competitionId, revision: command.expectedRevision },
|
||||||
|
{
|
||||||
|
$inc: { revision: 1 },
|
||||||
|
$set: {
|
||||||
|
projection,
|
||||||
|
projectorVersion: competition.projectorVersion,
|
||||||
|
phase: projection.phase,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ new: true, runValidators: true, session },
|
||||||
|
)
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
if (!updated) throw staleRevisionError(command.expectedRevision);
|
||||||
|
|
||||||
|
await this.applyReversalAssignments(
|
||||||
|
command.competitionId,
|
||||||
|
preview,
|
||||||
|
assignments,
|
||||||
|
commandId,
|
||||||
|
recordedAt,
|
||||||
|
session,
|
||||||
|
);
|
||||||
|
await OutboxModel.insertMany(
|
||||||
|
[
|
||||||
|
buildOutbox(
|
||||||
|
command.competitionId,
|
||||||
|
envelope,
|
||||||
|
commandId,
|
||||||
|
requestHash,
|
||||||
|
nextRevision,
|
||||||
|
reversalFacts,
|
||||||
|
projection,
|
||||||
|
updated,
|
||||||
|
recordedAt,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
{ session },
|
||||||
|
);
|
||||||
|
await session.commitTransaction();
|
||||||
|
return {
|
||||||
|
competition: updated,
|
||||||
|
commandId,
|
||||||
|
revision: nextRevision,
|
||||||
|
replayed: false,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
await session.abortTransaction().catch(() => undefined);
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
await session.endSession();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async runCommand(
|
private async runCommand(
|
||||||
command: CommandEnvelope,
|
command: CommandEnvelope,
|
||||||
): Promise<CompetitionCommandResult> {
|
): Promise<CompetitionCommandResult> {
|
||||||
@@ -347,6 +585,53 @@ export class CompetitionCommandService {
|
|||||||
throw tournamentCodeConflict(command, tournamentCode.tournamentCodeId);
|
throw tournamentCodeConflict(command, tournamentCode.tournamentCodeId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async applyReversalAssignments(
|
||||||
|
competitionId: PersistenceId,
|
||||||
|
preview: SeriesReversalPreview,
|
||||||
|
assignments: Array<Record<string, any>>,
|
||||||
|
commandId: string,
|
||||||
|
recordedAt: Date,
|
||||||
|
session: mongoose.ClientSession,
|
||||||
|
): Promise<void> {
|
||||||
|
const impactedSlotIds = new Set(preview.impact.gameSlotIds);
|
||||||
|
const impacted = assignments.filter(
|
||||||
|
(assignment) =>
|
||||||
|
impactedSlotIds.has(idString(assignment.gameSlotId)) &&
|
||||||
|
(assignment.state === 'reserved' || assignment.state === 'used'),
|
||||||
|
);
|
||||||
|
if (impacted.length === 0) return;
|
||||||
|
|
||||||
|
const gameSlotIds = impacted.map(({ gameSlotId }) =>
|
||||||
|
persistenceObjectId(gameSlotId),
|
||||||
|
);
|
||||||
|
const codeIds = impacted.map(({ tournamentCodeId }) =>
|
||||||
|
persistenceObjectId(tournamentCodeId),
|
||||||
|
);
|
||||||
|
const AssignmentModel = (await this.connectionService.getModel(
|
||||||
|
'tournamentCodeAssignment',
|
||||||
|
)) as mongoose.Model<any>;
|
||||||
|
await AssignmentModel.updateMany(
|
||||||
|
{
|
||||||
|
competitionId,
|
||||||
|
gameSlotId: { $in: gameSlotIds },
|
||||||
|
state: { $in: ['reserved', 'used'] },
|
||||||
|
},
|
||||||
|
reversalStatePipeline(recordedAt, commandId),
|
||||||
|
{ session },
|
||||||
|
);
|
||||||
|
const TournamentCodeModel = (await this.connectionService.getModel(
|
||||||
|
'tournamentCode',
|
||||||
|
)) as mongoose.Model<any>;
|
||||||
|
await TournamentCodeModel.updateMany(
|
||||||
|
{
|
||||||
|
_id: { $in: codeIds },
|
||||||
|
state: { $in: ['reserved', 'used'] },
|
||||||
|
},
|
||||||
|
tournamentCodeReversalStatePipeline(recordedAt),
|
||||||
|
{ session },
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function validateEnvelope(command: CommandEnvelope): void {
|
function validateEnvelope(command: CommandEnvelope): void {
|
||||||
@@ -355,14 +640,11 @@ function validateEnvelope(command: CommandEnvelope): void {
|
|||||||
command.expectedRevision < 0 ||
|
command.expectedRevision < 0 ||
|
||||||
command.idempotencyKey.trim().length === 0 ||
|
command.idempotencyKey.trim().length === 0 ||
|
||||||
command.idempotencyKey.length > 200 ||
|
command.idempotencyKey.length > 200 ||
|
||||||
(command.type === 'adjudicate-series' &&
|
((command.type === 'adjudicate-series' ||
|
||||||
|
command.type === 'reverse-series') &&
|
||||||
String(command.payload.reason).trim().length === 0)
|
String(command.payload.reason).trim().length === 0)
|
||||||
) {
|
) {
|
||||||
throw new CompetitionCommandError(
|
throw invalidCommandError();
|
||||||
'INVALID_COMPETITION_COMMAND',
|
|
||||||
'Expected revision and a non-empty Idempotency-Key are required.',
|
|
||||||
422,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -419,16 +701,29 @@ function buildFact(
|
|||||||
ordinal: command.payload.ordinal,
|
ordinal: command.payload.ordinal,
|
||||||
evidence: command.payload.evidence,
|
evidence: command.payload.evidence,
|
||||||
mapping: command.payload.mapping,
|
mapping: command.payload.mapping,
|
||||||
|
...(command.payload.startedAt === undefined
|
||||||
|
? {}
|
||||||
|
: { startedAt: command.payload.startedAt }),
|
||||||
|
...(command.payload.durationSeconds === undefined
|
||||||
|
? {}
|
||||||
|
: { durationSeconds: command.payload.durationSeconds }),
|
||||||
|
...(command.payload.participants === undefined
|
||||||
|
? {}
|
||||||
|
: { participants: command.payload.participants }),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
if (command.type === 'adjudicate-series') {
|
||||||
...common,
|
return {
|
||||||
type: 'series-adjudicated',
|
...common,
|
||||||
seriesId: command.payload.seriesId,
|
type: 'series-adjudicated',
|
||||||
decision: command.payload.decision,
|
seriesId: command.payload.seriesId,
|
||||||
reason: command.payload.reason,
|
decision: command.payload.decision,
|
||||||
};
|
reason: command.payload.reason,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
throw invalidCommandError();
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildOutbox(
|
function buildOutbox(
|
||||||
@@ -437,11 +732,14 @@ function buildOutbox(
|
|||||||
commandId: string,
|
commandId: string,
|
||||||
requestHash: string,
|
requestHash: string,
|
||||||
revision: number,
|
revision: number,
|
||||||
fact: Readonly<Record<string, unknown>>,
|
fact:
|
||||||
|
| Readonly<Record<string, unknown>>
|
||||||
|
| readonly Readonly<Record<string, unknown>>[],
|
||||||
projection: unknown,
|
projection: unknown,
|
||||||
updatedCompetition: unknown,
|
updatedCompetition: unknown,
|
||||||
recordedAt: Date,
|
recordedAt: Date,
|
||||||
): Readonly<Record<string, unknown>> {
|
): Readonly<Record<string, unknown>> {
|
||||||
|
const facts = Array.isArray(fact) ? fact : [fact];
|
||||||
return {
|
return {
|
||||||
eventId: `${commandId}:competition-projected`,
|
eventId: `${commandId}:competition-projected`,
|
||||||
competitionId,
|
competitionId,
|
||||||
@@ -453,7 +751,7 @@ function buildOutbox(
|
|||||||
payload: {
|
payload: {
|
||||||
competitionId: idString(competitionId),
|
competitionId: idString(competitionId),
|
||||||
sourceRevision: revision,
|
sourceRevision: revision,
|
||||||
factIds: [idString(fact._id as PersistenceId)],
|
factIds: facts.map((entry) => idString(entry._id as PersistenceId)),
|
||||||
projection,
|
projection,
|
||||||
phase:
|
phase:
|
||||||
isRecord(projection) && typeof projection.phase === 'string'
|
isRecord(projection) && typeof projection.phase === 'string'
|
||||||
@@ -558,3 +856,122 @@ function tournamentCodeConflict(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function reversalInput(
|
||||||
|
competition: Pick<Competition, 'revision' | 'seriesGraph'>,
|
||||||
|
command: PreviewSeriesReversalCommand,
|
||||||
|
facts: readonly unknown[],
|
||||||
|
assignments: readonly Record<string, any>[],
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
competitionId: idString(command.competitionId),
|
||||||
|
revision: competition.revision,
|
||||||
|
seriesId: idString(command.seriesId),
|
||||||
|
mode: command.mode,
|
||||||
|
graph: toPlain(competition.seriesGraph) as never,
|
||||||
|
facts: facts.map((fact) =>
|
||||||
|
factForProjection(fact as Readonly<Record<string, unknown>>),
|
||||||
|
),
|
||||||
|
assignments: assignments.map((assignment) => ({
|
||||||
|
seriesId: idString(assignment.seriesId),
|
||||||
|
gameSlotId: idString(assignment.gameSlotId),
|
||||||
|
state: String(assignment.state),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function persistenceReversalFact(
|
||||||
|
rawFact: Record<string, unknown>,
|
||||||
|
command: ReverseSeriesCommand,
|
||||||
|
commandId: string,
|
||||||
|
requestHash: string,
|
||||||
|
): Readonly<Record<string, unknown>> {
|
||||||
|
const { id, ...fields } = rawFact;
|
||||||
|
return {
|
||||||
|
...fields,
|
||||||
|
_id: persistenceObjectId(id as PersistenceId),
|
||||||
|
competitionId: command.competitionId,
|
||||||
|
commandId,
|
||||||
|
idempotencyKey: command.idempotencyKey,
|
||||||
|
requestHash,
|
||||||
|
...(fields.gameAcceptedFactId === undefined
|
||||||
|
? {}
|
||||||
|
: {
|
||||||
|
gameAcceptedFactId: persistenceObjectId(
|
||||||
|
fields.gameAcceptedFactId as PersistenceId,
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
...(fields.adjudicationFactId === undefined
|
||||||
|
? {}
|
||||||
|
: {
|
||||||
|
adjudicationFactId: persistenceObjectId(
|
||||||
|
fields.adjudicationFactId as PersistenceId,
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function reversalStatePipeline(
|
||||||
|
recordedAt: Date,
|
||||||
|
commandId?: string,
|
||||||
|
): mongoose.PipelineStage[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
state: {
|
||||||
|
$cond: [{ $eq: ['$state', 'reserved'] }, 'released', 'voided'],
|
||||||
|
},
|
||||||
|
releasedAt: {
|
||||||
|
$cond: [{ $eq: ['$state', 'reserved'] }, recordedAt, '$$REMOVE'],
|
||||||
|
},
|
||||||
|
voidedAt: {
|
||||||
|
$cond: [{ $eq: ['$state', 'used'] }, recordedAt, '$$REMOVE'],
|
||||||
|
},
|
||||||
|
...(commandId ? { commandId } : {}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function tournamentCodeReversalStatePipeline(
|
||||||
|
recordedAt: Date,
|
||||||
|
): mongoose.PipelineStage[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
state: {
|
||||||
|
$cond: [{ $eq: ['$state', 'reserved'] }, 'released', 'voided'],
|
||||||
|
},
|
||||||
|
releasedAt: {
|
||||||
|
$cond: [{ $eq: ['$state', 'reserved'] }, recordedAt, '$releasedAt'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function persistenceObjectId(value: PersistenceId): PersistenceId {
|
||||||
|
if (value instanceof mongoose.Types.ObjectId) return value;
|
||||||
|
return mongoose.isValidObjectId(value)
|
||||||
|
? new mongoose.Types.ObjectId(value)
|
||||||
|
: value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function competitionNotFound(
|
||||||
|
competitionId: PersistenceId,
|
||||||
|
): CompetitionCommandError {
|
||||||
|
return new CompetitionCommandError(
|
||||||
|
'COMPETITION_NOT_FOUND',
|
||||||
|
'Competition not found.',
|
||||||
|
404,
|
||||||
|
{ competitionId: idString(competitionId) },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function invalidCommandError(): CompetitionCommandError {
|
||||||
|
return new CompetitionCommandError(
|
||||||
|
'INVALID_COMPETITION_COMMAND',
|
||||||
|
'Expected revision, valid payload, and a non-empty Idempotency-Key are required.',
|
||||||
|
422,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,319 @@
|
|||||||
|
import { ForbiddenException } from '@nestjs/common';
|
||||||
|
import { Types } from 'mongoose';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import { CompetitionBootstrapService } from './competition-bootstrap.service';
|
||||||
|
import { CompetitionQueryService } from './competition-query.service';
|
||||||
|
|
||||||
|
describe('CompetitionQueryService', () => {
|
||||||
|
it('bootstraps a built Match once when its Competition is first read', async () => {
|
||||||
|
const harness = createHarness({ competition: null });
|
||||||
|
const bootstrapped = competitionDocument();
|
||||||
|
harness.bootstrapService.bootstrap.mockResolvedValue(bootstrapped);
|
||||||
|
const service = createService(harness);
|
||||||
|
|
||||||
|
const result = await service.getCompetition({
|
||||||
|
communityId: COMMUNITY_ID,
|
||||||
|
matchId: MATCH_ID,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(harness.matchModel.findOne).toHaveBeenCalledWith({
|
||||||
|
_id: MATCH_ID,
|
||||||
|
communityId: COMMUNITY_ID,
|
||||||
|
});
|
||||||
|
expect(harness.bootstrapService.bootstrap).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ _id: MATCH_ID, status: 'team-built' }),
|
||||||
|
);
|
||||||
|
expect(result).toBe(bootstrapped);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns an explicit team view with codes only for the callers team', async () => {
|
||||||
|
const harness = createHarness();
|
||||||
|
const service = createService(harness);
|
||||||
|
|
||||||
|
const result = await service.getTeamView({
|
||||||
|
communityId: COMMUNITY_ID,
|
||||||
|
matchId: MATCH_ID,
|
||||||
|
userId: TEAM_A_USER_ID,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toMatchObject({
|
||||||
|
competitionId: COMPETITION_ID.toHexString(),
|
||||||
|
revision: 4,
|
||||||
|
teamId: TEAM_A_ID.toHexString(),
|
||||||
|
activeSeries: [expect.objectContaining({ seriesId: SERIES_ID })],
|
||||||
|
tournamentCodes: [
|
||||||
|
{
|
||||||
|
gameSlotId: GAME_SLOT_ID,
|
||||||
|
seriesId: SERIES_ID,
|
||||||
|
ordinal: 1,
|
||||||
|
displayNumber: 1,
|
||||||
|
state: 'reserved',
|
||||||
|
code: 'TEAM-A-SECRET-CODE',
|
||||||
|
expiresAt: '2026-07-13T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(JSON.stringify(result)).not.toContain('OPPONENT-SECRET-CODE');
|
||||||
|
expect(harness.tournamentCodeModel.find).toHaveBeenCalledWith({
|
||||||
|
_id: { $in: [TEAM_A_CODE_ID] },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not reveal a team view to an authenticated non-participant', async () => {
|
||||||
|
const service = createService(createHarness());
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.getTeamView({
|
||||||
|
communityId: COMMUNITY_ID,
|
||||||
|
matchId: MATCH_ID,
|
||||||
|
userId: new Types.ObjectId('64c000000000000000000099'),
|
||||||
|
}),
|
||||||
|
).rejects.toBeInstanceOf(ForbiddenException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('pages facts in immutable revision order using an opaque cursor', async () => {
|
||||||
|
const harness = createHarness();
|
||||||
|
harness.factModel.find.mockReturnValueOnce(
|
||||||
|
queryResult([
|
||||||
|
factDocument('64c000000000000000000031', 1, 1),
|
||||||
|
factDocument('64c000000000000000000032', 2, 1),
|
||||||
|
factDocument('64c000000000000000000033', 3, 1),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
const service = createService(harness);
|
||||||
|
|
||||||
|
const first = await service.listFacts({
|
||||||
|
communityId: COMMUNITY_ID,
|
||||||
|
matchId: MATCH_ID,
|
||||||
|
limit: 2,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(first.facts).toHaveLength(2);
|
||||||
|
expect(first.nextCursor).toEqual(expect.any(String));
|
||||||
|
expect(first.facts[0]).toMatchObject({
|
||||||
|
id: '64c000000000000000000031',
|
||||||
|
competitionId: COMPETITION_ID.toHexString(),
|
||||||
|
type: 'game-accepted',
|
||||||
|
revision: 1,
|
||||||
|
});
|
||||||
|
expect(first.facts[0]).not.toHaveProperty('requestHash');
|
||||||
|
expect(first.facts[0]).not.toHaveProperty('idempotencyKey');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const COMMUNITY_ID = new Types.ObjectId('64c000000000000000000001');
|
||||||
|
const MATCH_ID = new Types.ObjectId('64c000000000000000000002');
|
||||||
|
const COMPETITION_ID = new Types.ObjectId('64c000000000000000000003');
|
||||||
|
const TEAM_A_ID = new Types.ObjectId('64c000000000000000000004');
|
||||||
|
const TEAM_B_ID = new Types.ObjectId('64c000000000000000000005');
|
||||||
|
const TEAM_A_USER_ID = new Types.ObjectId('64c000000000000000000006');
|
||||||
|
const TEAM_B_USER_ID = new Types.ObjectId('64c000000000000000000007');
|
||||||
|
const TEAM_A_CODE_ID = new Types.ObjectId('64c000000000000000000008');
|
||||||
|
const TEAM_B_CODE_ID = new Types.ObjectId('64c000000000000000000009');
|
||||||
|
const SERIES_ID = 'series-1';
|
||||||
|
const GAME_SLOT_ID = 'slot-1';
|
||||||
|
|
||||||
|
function createService(harness: ReturnType<typeof createHarness>) {
|
||||||
|
return new CompetitionQueryService(
|
||||||
|
harness.connectionService as ConnectionService,
|
||||||
|
harness.bootstrapService as unknown as CompetitionBootstrapService,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function createHarness(options: { competition?: unknown } = {}) {
|
||||||
|
const competition =
|
||||||
|
options.competition === undefined
|
||||||
|
? competitionDocument()
|
||||||
|
: options.competition;
|
||||||
|
const competitionModel = {
|
||||||
|
findOne: jest.fn().mockReturnValue(queryResult(competition)),
|
||||||
|
};
|
||||||
|
const matchModel = {
|
||||||
|
findOne: jest.fn().mockReturnValue(
|
||||||
|
queryResult({
|
||||||
|
_id: MATCH_ID,
|
||||||
|
communityId: COMMUNITY_ID,
|
||||||
|
status: 'team-built',
|
||||||
|
teams: [{ teamIndex: 1 }, { teamIndex: 2 }],
|
||||||
|
participants: [],
|
||||||
|
gameMode: 'pair',
|
||||||
|
gameCount: 3,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
const assignmentModel = {
|
||||||
|
find: jest.fn().mockReturnValue(
|
||||||
|
queryResult([
|
||||||
|
{
|
||||||
|
competitionId: COMPETITION_ID,
|
||||||
|
seriesId: SERIES_ID,
|
||||||
|
gameSlotId: GAME_SLOT_ID,
|
||||||
|
tournamentCodeId: TEAM_A_CODE_ID,
|
||||||
|
state: 'reserved',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
competitionId: COMPETITION_ID,
|
||||||
|
seriesId: 'series-opponent-only',
|
||||||
|
gameSlotId: 'slot-opponent-only',
|
||||||
|
tournamentCodeId: TEAM_B_CODE_ID,
|
||||||
|
state: 'reserved',
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
const tournamentCodeModel = {
|
||||||
|
find: jest.fn().mockReturnValue(
|
||||||
|
queryResult([
|
||||||
|
{
|
||||||
|
_id: TEAM_A_CODE_ID,
|
||||||
|
code: 'TEAM-A-SECRET-CODE',
|
||||||
|
expiresAt: new Date('2026-07-13T00:00:00.000Z'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
_id: TEAM_B_CODE_ID,
|
||||||
|
code: 'OPPONENT-SECRET-CODE',
|
||||||
|
expiresAt: new Date('2026-07-13T00:00:00.000Z'),
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
const factModel = {
|
||||||
|
find: jest.fn().mockReturnValue(queryResult([])),
|
||||||
|
};
|
||||||
|
const models: Record<string, unknown> = {
|
||||||
|
competition: competitionModel,
|
||||||
|
match: matchModel,
|
||||||
|
tournamentCodeAssignment: assignmentModel,
|
||||||
|
tournamentCode: tournamentCodeModel,
|
||||||
|
competitionFact: factModel,
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
competitionModel,
|
||||||
|
matchModel,
|
||||||
|
assignmentModel,
|
||||||
|
tournamentCodeModel,
|
||||||
|
factModel,
|
||||||
|
connectionService: {
|
||||||
|
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
|
||||||
|
},
|
||||||
|
bootstrapService: { bootstrap: jest.fn() },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function competitionDocument() {
|
||||||
|
return {
|
||||||
|
_id: COMPETITION_ID,
|
||||||
|
matchId: MATCH_ID,
|
||||||
|
communityId: COMMUNITY_ID,
|
||||||
|
schemaVersion: 1,
|
||||||
|
projectorVersion: 1,
|
||||||
|
revision: 4,
|
||||||
|
phase: 'running',
|
||||||
|
teams: [
|
||||||
|
{
|
||||||
|
teamId: TEAM_A_ID,
|
||||||
|
displayOrder: 1,
|
||||||
|
seedNumber: 1,
|
||||||
|
name: 'Team A',
|
||||||
|
members: [{ userId: TEAM_A_USER_ID, displayName: 'A' }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
teamId: TEAM_B_ID,
|
||||||
|
displayOrder: 2,
|
||||||
|
seedNumber: 2,
|
||||||
|
name: 'Team B',
|
||||||
|
members: [{ userId: TEAM_B_USER_ID, displayName: 'B' }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
format: {
|
||||||
|
type: 'paired-series',
|
||||||
|
rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' },
|
||||||
|
},
|
||||||
|
seriesGraph: [],
|
||||||
|
projection: {
|
||||||
|
sourceRevision: 4,
|
||||||
|
projectorVersion: 1,
|
||||||
|
phase: 'running',
|
||||||
|
formatType: 'paired-series',
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
seriesId: SERIES_ID,
|
||||||
|
status: 'in-progress',
|
||||||
|
stage: { type: 'pair', displayOrder: 1 },
|
||||||
|
rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' },
|
||||||
|
entries: [
|
||||||
|
{ slot: 'A', teamId: TEAM_A_ID.toHexString(), gameWins: 1 },
|
||||||
|
{ slot: 'B', teamId: TEAM_B_ID.toHexString(), gameWins: 0 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
seriesId: 'series-opponent-only',
|
||||||
|
status: 'in-progress',
|
||||||
|
stage: { type: 'pair', displayOrder: 2 },
|
||||||
|
rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' },
|
||||||
|
entries: [
|
||||||
|
{ slot: 'A', teamId: TEAM_B_ID.toHexString(), gameWins: 0 },
|
||||||
|
{ slot: 'B', teamId: 'other-team', gameWins: 1 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
games: [],
|
||||||
|
gameSlots: [
|
||||||
|
{
|
||||||
|
id: GAME_SLOT_ID,
|
||||||
|
seriesId: SERIES_ID,
|
||||||
|
ordinal: 1,
|
||||||
|
displayNumber: 1,
|
||||||
|
status: 'reserved',
|
||||||
|
entries: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
rounds: [],
|
||||||
|
connectors: [],
|
||||||
|
},
|
||||||
|
createdAt: new Date('2026-07-11T00:00:00.000Z'),
|
||||||
|
updatedAt: new Date('2026-07-12T00:00:00.000Z'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function factDocument(id: string, revision: number, ordinal: number) {
|
||||||
|
return {
|
||||||
|
_id: new Types.ObjectId(id),
|
||||||
|
competitionId: COMPETITION_ID,
|
||||||
|
type: 'game-accepted',
|
||||||
|
revision,
|
||||||
|
ordinalWithinRevision: ordinal,
|
||||||
|
commandId: `command-${revision}`,
|
||||||
|
idempotencyKey: `secret-${revision}`,
|
||||||
|
requestHash: `hash-${revision}`,
|
||||||
|
schemaVersion: 1,
|
||||||
|
actor: { type: 'system' },
|
||||||
|
occurredAt: new Date('2026-07-12T00:00:00.000Z'),
|
||||||
|
recordedAt: new Date('2026-07-12T00:00:01.000Z'),
|
||||||
|
gameId: new Types.ObjectId('64c000000000000000000041'),
|
||||||
|
seriesId: new Types.ObjectId('64c000000000000000000042'),
|
||||||
|
gameSlotId: new Types.ObjectId('64c000000000000000000043'),
|
||||||
|
ordinal: 1,
|
||||||
|
evidence: { type: 'legacy', legacyReference: 'legacy-1' },
|
||||||
|
mapping: {
|
||||||
|
mappingVersion: 1,
|
||||||
|
confidence: 1,
|
||||||
|
blueTeamId: TEAM_A_ID,
|
||||||
|
redTeamId: TEAM_B_ID,
|
||||||
|
winnerTeamId: TEAM_A_ID,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function queryResult<T>(value: T) {
|
||||||
|
const query = {
|
||||||
|
sort: jest.fn(),
|
||||||
|
limit: jest.fn(),
|
||||||
|
lean: jest.fn(),
|
||||||
|
exec: jest.fn().mockResolvedValue(value),
|
||||||
|
};
|
||||||
|
query.sort.mockReturnValue(query);
|
||||||
|
query.limit.mockReturnValue(query);
|
||||||
|
query.lean.mockReturnValue(query);
|
||||||
|
return query;
|
||||||
|
}
|
||||||
@@ -0,0 +1,340 @@
|
|||||||
|
import type {
|
||||||
|
CompetitionFactView,
|
||||||
|
CompetitionFactsResponse,
|
||||||
|
TeamCompetitionViewResponse,
|
||||||
|
} from '@lolympus/contracts';
|
||||||
|
import {
|
||||||
|
ConflictException,
|
||||||
|
ForbiddenException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
UnprocessableEntityException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import type { Competition } from './competition.schema';
|
||||||
|
import { CompetitionBootstrapService } from './competition-bootstrap.service';
|
||||||
|
|
||||||
|
type PersistenceId = string | mongoose.Types.ObjectId;
|
||||||
|
|
||||||
|
export interface CompetitionScope {
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
matchId: mongoose.Types.ObjectId;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CompetitionProjectionSource {
|
||||||
|
series?: Array<Record<string, unknown>>;
|
||||||
|
gameSlots?: Array<Record<string, unknown>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CompetitionQueryService {
|
||||||
|
constructor(
|
||||||
|
private readonly connectionService: ConnectionService,
|
||||||
|
private readonly bootstrapService: CompetitionBootstrapService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** Resolve the one-to-one aggregate, lazily freezing a completed team build. */
|
||||||
|
public async getCompetition(scope: CompetitionScope): Promise<any> {
|
||||||
|
const CompetitionModel =
|
||||||
|
await this.connectionService.getModel('competition');
|
||||||
|
const existing = await CompetitionModel.findOne({
|
||||||
|
matchId: scope.matchId,
|
||||||
|
communityId: scope.communityId,
|
||||||
|
})
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
if (existing) return existing;
|
||||||
|
|
||||||
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
|
const match = await MatchModel.findOne({
|
||||||
|
_id: scope.matchId,
|
||||||
|
communityId: scope.communityId,
|
||||||
|
})
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
if (!match) throw new NotFoundException('Match not found.');
|
||||||
|
if (
|
||||||
|
match.status === 'recruiting' ||
|
||||||
|
!Array.isArray(match.teams) ||
|
||||||
|
match.teams.length < 2
|
||||||
|
) {
|
||||||
|
throw new ConflictException(
|
||||||
|
'Competition is unavailable until team building is complete.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return this.bootstrapService.bootstrap(match as never);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getTeamView(
|
||||||
|
scope: CompetitionScope & { userId: mongoose.Types.ObjectId },
|
||||||
|
): Promise<TeamCompetitionViewResponse> {
|
||||||
|
const competition = (await this.getCompetition(scope)) as Competition & {
|
||||||
|
_id: PersistenceId;
|
||||||
|
};
|
||||||
|
const team = competition.teams.find(({ members }) =>
|
||||||
|
members.some(({ userId }) => sameId(userId, scope.userId)),
|
||||||
|
);
|
||||||
|
if (!team) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Only a Competition team member may access the team view.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const projection = competition.projection as CompetitionProjectionSource;
|
||||||
|
const allSeries = Array.isArray(projection.series) ? projection.series : [];
|
||||||
|
const teamId = idString(team.teamId);
|
||||||
|
const activeSeries = allSeries.filter(
|
||||||
|
(series) =>
|
||||||
|
series.status !== 'completed' &&
|
||||||
|
series.status !== 'inactive' &&
|
||||||
|
Array.isArray(series.entries) &&
|
||||||
|
series.entries.some(
|
||||||
|
(entry) =>
|
||||||
|
isRecord(entry) &&
|
||||||
|
idString(entry.teamId as PersistenceId) === teamId,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const activeSeriesIds = new Set(
|
||||||
|
activeSeries.map((series) => idString(series.seriesId as PersistenceId)),
|
||||||
|
);
|
||||||
|
const gameSlots = (
|
||||||
|
Array.isArray(projection.gameSlots) ? projection.gameSlots : []
|
||||||
|
).filter((slot) =>
|
||||||
|
activeSeriesIds.has(idString(slot.seriesId as PersistenceId)),
|
||||||
|
);
|
||||||
|
|
||||||
|
const AssignmentModel = await this.connectionService.getModel(
|
||||||
|
'tournamentCodeAssignment',
|
||||||
|
);
|
||||||
|
const queriedAssignments = await AssignmentModel.find({
|
||||||
|
competitionId: competition._id,
|
||||||
|
seriesId: { $in: [...activeSeriesIds] },
|
||||||
|
state: { $in: ['reserved', 'used'] },
|
||||||
|
})
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
// Keep this defensive filter even when the persistence query is mocked or
|
||||||
|
// changed: an opponent-only assignment must never cross this boundary.
|
||||||
|
const assignments = queriedAssignments.filter((assignment) =>
|
||||||
|
activeSeriesIds.has(idString(assignment.seriesId)),
|
||||||
|
);
|
||||||
|
const codeIds = assignments.map(({ tournamentCodeId }) => tournamentCodeId);
|
||||||
|
const TournamentCodeModel =
|
||||||
|
await this.connectionService.getModel('tournamentCode');
|
||||||
|
const codes = codeIds.length
|
||||||
|
? await TournamentCodeModel.find({ _id: { $in: codeIds } })
|
||||||
|
.lean()
|
||||||
|
.exec()
|
||||||
|
: [];
|
||||||
|
const codeById = new Map(codes.map((code) => [idString(code._id), code]));
|
||||||
|
const assignmentBySlot = new Map(
|
||||||
|
assignments.map((assignment) => [
|
||||||
|
idString(assignment.gameSlotId),
|
||||||
|
assignment,
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
competitionId: idString(competition._id) as never,
|
||||||
|
revision: competition.revision,
|
||||||
|
phase: competition.phase,
|
||||||
|
teamId: teamId as never,
|
||||||
|
activeSeries: toWire(activeSeries) as never,
|
||||||
|
tournamentCodes: gameSlots.map((slot) => {
|
||||||
|
const gameSlotId = idString(slot.id as PersistenceId);
|
||||||
|
const assignment = assignmentBySlot.get(gameSlotId);
|
||||||
|
const code = assignment
|
||||||
|
? codeById.get(idString(assignment.tournamentCodeId))
|
||||||
|
: undefined;
|
||||||
|
return {
|
||||||
|
gameSlotId: gameSlotId as never,
|
||||||
|
seriesId: idString(slot.seriesId as PersistenceId) as never,
|
||||||
|
ordinal: numberValue(slot.ordinal),
|
||||||
|
displayNumber: numberValue(slot.displayNumber),
|
||||||
|
state:
|
||||||
|
assignment?.state === 'reserved' || assignment?.state === 'used'
|
||||||
|
? assignment.state
|
||||||
|
: 'pending',
|
||||||
|
code: typeof code?.code === 'string' ? code.code : null,
|
||||||
|
expiresAt: code?.expiresAt ? isoDate(code.expiresAt) : null,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public async listFacts(
|
||||||
|
scope: CompetitionScope & { cursor?: string; limit?: number },
|
||||||
|
): Promise<CompetitionFactsResponse> {
|
||||||
|
const competition = (await this.getCompetition(scope)) as Competition & {
|
||||||
|
_id: PersistenceId;
|
||||||
|
};
|
||||||
|
const limit = normalizeLimit(scope.limit);
|
||||||
|
const cursor = scope.cursor ? decodeCursor(scope.cursor) : undefined;
|
||||||
|
const cursorFilter = cursor
|
||||||
|
? {
|
||||||
|
$or: [
|
||||||
|
{ revision: { $gt: cursor.revision } },
|
||||||
|
{
|
||||||
|
revision: cursor.revision,
|
||||||
|
ordinalWithinRevision: { $gt: cursor.ordinalWithinRevision },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
revision: cursor.revision,
|
||||||
|
ordinalWithinRevision: cursor.ordinalWithinRevision,
|
||||||
|
_id: { $gt: new mongoose.Types.ObjectId(cursor.id) },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
: {};
|
||||||
|
const FactModel = await this.connectionService.getModel('competitionFact');
|
||||||
|
const rows = await FactModel.find({
|
||||||
|
competitionId: competition._id,
|
||||||
|
...cursorFilter,
|
||||||
|
})
|
||||||
|
.sort({ revision: 1, ordinalWithinRevision: 1, _id: 1 })
|
||||||
|
.limit(limit + 1)
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
const page = rows.slice(0, limit);
|
||||||
|
const last = page.at(-1);
|
||||||
|
return {
|
||||||
|
facts: page.map(presentFact),
|
||||||
|
nextCursor:
|
||||||
|
rows.length > limit && last
|
||||||
|
? encodeCursor({
|
||||||
|
revision: last.revision,
|
||||||
|
ordinalWithinRevision: last.ordinalWithinRevision,
|
||||||
|
id: idString(last._id),
|
||||||
|
})
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function presentFact(source: Record<string, any>): CompetitionFactView {
|
||||||
|
const common = {
|
||||||
|
id: idString(source._id) as never,
|
||||||
|
competitionId: idString(source.competitionId) as never,
|
||||||
|
revision: source.revision,
|
||||||
|
ordinalWithinRevision: source.ordinalWithinRevision,
|
||||||
|
commandId: String(source.commandId) as never,
|
||||||
|
schemaVersion: source.schemaVersion,
|
||||||
|
actor: toWire(source.actor) as never,
|
||||||
|
occurredAt: isoDate(source.occurredAt),
|
||||||
|
recordedAt: isoDate(source.recordedAt),
|
||||||
|
...(source.causationId ? { causationId: String(source.causationId) } : {}),
|
||||||
|
};
|
||||||
|
switch (source.type) {
|
||||||
|
case 'game-accepted':
|
||||||
|
return {
|
||||||
|
...common,
|
||||||
|
type: 'game-accepted',
|
||||||
|
gameId: idString(source.gameId) as never,
|
||||||
|
seriesId: idString(source.seriesId) as never,
|
||||||
|
gameSlotId: idString(source.gameSlotId) as never,
|
||||||
|
ordinal: source.ordinal,
|
||||||
|
startedAt: isoDate(source.startedAt ?? source.occurredAt),
|
||||||
|
durationSeconds: numberValue(source.durationSeconds ?? 0),
|
||||||
|
participants: toWire(source.participants ?? []) as never,
|
||||||
|
evidence: toWire(source.evidence) as never,
|
||||||
|
mapping: toWire(source.mapping) as never,
|
||||||
|
};
|
||||||
|
case 'game-voided':
|
||||||
|
return {
|
||||||
|
...common,
|
||||||
|
type: 'game-voided',
|
||||||
|
gameAcceptedFactId: idString(source.gameAcceptedFactId) as never,
|
||||||
|
reason: String(source.reason),
|
||||||
|
};
|
||||||
|
case 'series-adjudicated':
|
||||||
|
return {
|
||||||
|
...common,
|
||||||
|
type: 'series-adjudicated',
|
||||||
|
seriesId: idString(source.seriesId) as never,
|
||||||
|
decision: toWire(source.decision) as never,
|
||||||
|
reason: String(source.reason),
|
||||||
|
};
|
||||||
|
case 'adjudication-reversed':
|
||||||
|
return {
|
||||||
|
...common,
|
||||||
|
type: 'adjudication-reversed',
|
||||||
|
adjudicationFactId: idString(source.adjudicationFactId) as never,
|
||||||
|
reason: String(source.reason),
|
||||||
|
};
|
||||||
|
default:
|
||||||
|
throw new Error(`Unsupported Competition fact type: ${source.type}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FactCursor {
|
||||||
|
revision: number;
|
||||||
|
ordinalWithinRevision: number;
|
||||||
|
id: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeCursor(cursor: FactCursor): string {
|
||||||
|
return Buffer.from(JSON.stringify(cursor)).toString('base64url');
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeCursor(value: string): FactCursor {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(Buffer.from(value, 'base64url').toString('utf8'));
|
||||||
|
if (
|
||||||
|
!isRecord(parsed) ||
|
||||||
|
!Number.isInteger(parsed.revision) ||
|
||||||
|
!Number.isInteger(parsed.ordinalWithinRevision) ||
|
||||||
|
typeof parsed.id !== 'string' ||
|
||||||
|
!mongoose.isValidObjectId(parsed.id)
|
||||||
|
) {
|
||||||
|
throw new Error('malformed cursor');
|
||||||
|
}
|
||||||
|
return parsed as unknown as FactCursor;
|
||||||
|
} catch {
|
||||||
|
throw new UnprocessableEntityException('Invalid facts cursor.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLimit(value: number | undefined): number {
|
||||||
|
if (value === undefined) return 50;
|
||||||
|
if (!Number.isInteger(value) || value < 1 || value > 100) {
|
||||||
|
throw new UnprocessableEntityException(
|
||||||
|
'Facts page limit must be an integer from 1 through 100.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sameId(left: PersistenceId, right: PersistenceId): boolean {
|
||||||
|
return idString(left) === idString(right);
|
||||||
|
}
|
||||||
|
|
||||||
|
function idString(value: PersistenceId): string {
|
||||||
|
return value instanceof mongoose.Types.ObjectId
|
||||||
|
? value.toHexString()
|
||||||
|
: String(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isoDate(value: Date | string): string {
|
||||||
|
return value instanceof Date ? value.toISOString() : String(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function numberValue(value: unknown): number {
|
||||||
|
return typeof value === 'number' ? value : Number(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toWire(value: unknown): unknown {
|
||||||
|
if (value instanceof mongoose.Types.ObjectId) return value.toHexString();
|
||||||
|
if (value instanceof Date) return value.toISOString();
|
||||||
|
if (Array.isArray(value)) return value.map(toWire);
|
||||||
|
if (isRecord(value)) {
|
||||||
|
return Object.fromEntries(
|
||||||
|
Object.entries(value).map(([key, child]) => [key, toWire(child)]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||||
|
}
|
||||||
@@ -0,0 +1,356 @@
|
|||||||
|
import { HttpException } from '@nestjs/common';
|
||||||
|
import { Types } from 'mongoose';
|
||||||
|
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from '../auth/allow-public-access.decorator';
|
||||||
|
import { ROLES_KEY } from '../auth/roles.decorator';
|
||||||
|
import { CompetitionCommandService } from './competition-command.service';
|
||||||
|
import { CompetitionController } from './competition.controller';
|
||||||
|
import { CompetitionQueryService } from './competition-query.service';
|
||||||
|
|
||||||
|
describe('CompetitionController', () => {
|
||||||
|
it('marks only the detail endpoint public and writes a revision ETag', async () => {
|
||||||
|
const { controller, queryService } = createHarness();
|
||||||
|
const response = { setHeader: jest.fn() };
|
||||||
|
|
||||||
|
const result = await controller.getDetail(
|
||||||
|
COMMUNITY_ID,
|
||||||
|
MATCH_ID,
|
||||||
|
response as never,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
Reflect.getMetadata(
|
||||||
|
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
|
||||||
|
CompetitionController.prototype.getDetail,
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
expect(
|
||||||
|
Reflect.getMetadata(
|
||||||
|
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
|
||||||
|
CompetitionController.prototype.getTeamView,
|
||||||
|
),
|
||||||
|
).not.toBe(true);
|
||||||
|
expect(response.setHeader).toHaveBeenCalledWith('ETag', '"7"');
|
||||||
|
expect(result).toMatchObject({ revision: 7 });
|
||||||
|
expect(queryService.getCompetition).toHaveBeenCalledWith({
|
||||||
|
communityId: COMMUNITY_ID,
|
||||||
|
matchId: MATCH_ID,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('protects audit and mutation endpoints with admin roles', () => {
|
||||||
|
for (const method of [
|
||||||
|
'listFacts',
|
||||||
|
'acceptGame',
|
||||||
|
'adjudicateSeries',
|
||||||
|
'previewReversal',
|
||||||
|
'reverseSeries',
|
||||||
|
] as const) {
|
||||||
|
expect(
|
||||||
|
Reflect.getMetadata(ROLES_KEY, CompetitionController.prototype[method]),
|
||||||
|
).toEqual(['owner', 'admin']);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires If-Match and Idempotency-Key for a mutation', async () => {
|
||||||
|
const { controller } = createHarness();
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
controller.acceptGame(
|
||||||
|
adminUser(),
|
||||||
|
COMMUNITY_ID,
|
||||||
|
MATCH_ID,
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
acceptGameBody(),
|
||||||
|
),
|
||||||
|
).rejects.toMatchObject({
|
||||||
|
status: 422,
|
||||||
|
response: {
|
||||||
|
error: { code: 'INVALID_COMPETITION_COMMAND_HEADERS' },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes revision, idempotency and the authenticated actor to accept-game', async () => {
|
||||||
|
const { controller, commandService } = createHarness();
|
||||||
|
|
||||||
|
await controller.acceptGame(
|
||||||
|
adminUser(),
|
||||||
|
COMMUNITY_ID,
|
||||||
|
MATCH_ID,
|
||||||
|
'W/"7"',
|
||||||
|
'operator:accept:1',
|
||||||
|
acceptGameBody(),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(commandService.acceptGame).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
expectedRevision: 7,
|
||||||
|
idempotencyKey: 'operator:accept:1',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const accepted = commandService.acceptGame.mock.calls[0][0];
|
||||||
|
expect(accepted.competitionId.toHexString()).toBe(
|
||||||
|
COMPETITION_ID.toHexString(),
|
||||||
|
);
|
||||||
|
expect(accepted.actor.userId.toHexString()).toBe(ADMIN_ID.toHexString());
|
||||||
|
expect(accepted.gameId.toHexString()).toBe(GAME_ID.toHexString());
|
||||||
|
expect(accepted.seriesId.toHexString()).toBe(SERIES_ID);
|
||||||
|
expect(accepted.gameSlotId.toHexString()).toBe(GAME_SLOT_ID.toHexString());
|
||||||
|
});
|
||||||
|
|
||||||
|
it('maps command conflicts to the explicit error envelope', async () => {
|
||||||
|
const { controller, commandService } = createHarness();
|
||||||
|
commandService.adjudicateSeries.mockRejectedValue({
|
||||||
|
code: 'IDEMPOTENCY_KEY_CONFLICT',
|
||||||
|
message: 'duplicate key with another payload',
|
||||||
|
httpStatus: 409,
|
||||||
|
details: { idempotencyKey: 'same-key' },
|
||||||
|
});
|
||||||
|
|
||||||
|
let thrown: unknown;
|
||||||
|
try {
|
||||||
|
await controller.adjudicateSeries(
|
||||||
|
adminUser(),
|
||||||
|
COMMUNITY_ID,
|
||||||
|
MATCH_ID,
|
||||||
|
new Types.ObjectId(SERIES_ID),
|
||||||
|
'"7"',
|
||||||
|
'same-key',
|
||||||
|
{
|
||||||
|
decision: { type: 'administrative-draw' },
|
||||||
|
reason: '운영 판단',
|
||||||
|
},
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
thrown = error;
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(thrown).toBeInstanceOf(HttpException);
|
||||||
|
expect(thrown).toMatchObject({
|
||||||
|
status: 409,
|
||||||
|
response: {
|
||||||
|
error: {
|
||||||
|
code: 'IDEMPOTENCY_KEY_CONFLICT',
|
||||||
|
details: { idempotencyKey: 'same-key' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
{
|
||||||
|
source: {
|
||||||
|
code: 'STALE_COMPETITION_REVISION',
|
||||||
|
message: 'stale',
|
||||||
|
httpStatus: 412,
|
||||||
|
},
|
||||||
|
status: 412,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
source: {
|
||||||
|
code: 'GAME_TEAM_MISMATCH',
|
||||||
|
message: 'invalid evidence mapping',
|
||||||
|
},
|
||||||
|
status: 422,
|
||||||
|
},
|
||||||
|
])('maps $source.code to HTTP $status', async ({ source, status }) => {
|
||||||
|
const { controller, commandService } = createHarness();
|
||||||
|
commandService.acceptGame.mockRejectedValue(source);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
controller.acceptGame(
|
||||||
|
adminUser(),
|
||||||
|
COMMUNITY_ID,
|
||||||
|
MATCH_ID,
|
||||||
|
'"7"',
|
||||||
|
`operator:error:${status}`,
|
||||||
|
acceptGameBody(),
|
||||||
|
),
|
||||||
|
).rejects.toMatchObject({
|
||||||
|
status,
|
||||||
|
response: { error: { code: source.code } },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns an explicit 422 envelope for an invalid command body', async () => {
|
||||||
|
const { controller, commandService } = createHarness();
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
controller.adjudicateSeries(
|
||||||
|
adminUser(),
|
||||||
|
COMMUNITY_ID,
|
||||||
|
MATCH_ID,
|
||||||
|
new Types.ObjectId(SERIES_ID),
|
||||||
|
'"7"',
|
||||||
|
'operator:invalid-body:1',
|
||||||
|
{
|
||||||
|
decision: { type: 'walkover' },
|
||||||
|
reason: '',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
).rejects.toMatchObject({
|
||||||
|
status: 422,
|
||||||
|
response: {
|
||||||
|
error: { code: 'INVALID_COMPETITION_REQUEST' },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(commandService.adjudicateSeries).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects malformed game evidence before it reaches the ledger', async () => {
|
||||||
|
const { controller, commandService } = createHarness();
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
controller.acceptGame(
|
||||||
|
adminUser(),
|
||||||
|
COMMUNITY_ID,
|
||||||
|
MATCH_ID,
|
||||||
|
'"7"',
|
||||||
|
'operator:bad-evidence:1',
|
||||||
|
{
|
||||||
|
...acceptGameBody(),
|
||||||
|
evidence: { type: 'invented-evidence' },
|
||||||
|
},
|
||||||
|
),
|
||||||
|
).rejects.toMatchObject({
|
||||||
|
status: 422,
|
||||||
|
response: {
|
||||||
|
error: { code: 'INVALID_COMPETITION_REQUEST' },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(commandService.acceptGame).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires the same revision for preview and hash-confirmed reversal', async () => {
|
||||||
|
const { controller, commandService } = createHarness();
|
||||||
|
|
||||||
|
await controller.previewReversal(
|
||||||
|
adminUser(),
|
||||||
|
COMMUNITY_ID,
|
||||||
|
MATCH_ID,
|
||||||
|
new Types.ObjectId(SERIES_ID),
|
||||||
|
'"7"',
|
||||||
|
{ mode: 'cascade', reason: '잘못 수집됨' },
|
||||||
|
);
|
||||||
|
await controller.reverseSeries(
|
||||||
|
adminUser(),
|
||||||
|
COMMUNITY_ID,
|
||||||
|
MATCH_ID,
|
||||||
|
new Types.ObjectId(SERIES_ID),
|
||||||
|
'"7"',
|
||||||
|
'operator:reverse:1',
|
||||||
|
{
|
||||||
|
mode: 'cascade',
|
||||||
|
reason: '잘못 수집됨',
|
||||||
|
impactHash: 'a'.repeat(64),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(commandService.previewSeriesReversal).toHaveBeenCalledWith({
|
||||||
|
competitionId: COMPETITION_ID,
|
||||||
|
expectedRevision: 7,
|
||||||
|
seriesId: new Types.ObjectId(SERIES_ID),
|
||||||
|
mode: 'cascade',
|
||||||
|
});
|
||||||
|
expect(commandService.reverseSeries).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
competitionId: COMPETITION_ID,
|
||||||
|
expectedRevision: 7,
|
||||||
|
idempotencyKey: 'operator:reverse:1',
|
||||||
|
impactHash: 'a'.repeat(64),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const COMMUNITY_ID = new Types.ObjectId('64d000000000000000000001');
|
||||||
|
const MATCH_ID = new Types.ObjectId('64d000000000000000000002');
|
||||||
|
const COMPETITION_ID = new Types.ObjectId('64d000000000000000000003');
|
||||||
|
const ADMIN_ID = new Types.ObjectId('64d000000000000000000004');
|
||||||
|
const GAME_ID = new Types.ObjectId('64d000000000000000000005');
|
||||||
|
const SERIES_ID = '64d000000000000000000006';
|
||||||
|
const GAME_SLOT_ID = new Types.ObjectId('64d000000000000000000007');
|
||||||
|
const TEAM_A_ID = new Types.ObjectId('64d000000000000000000008');
|
||||||
|
const TEAM_B_ID = new Types.ObjectId('64d000000000000000000009');
|
||||||
|
|
||||||
|
function createHarness() {
|
||||||
|
const competition = {
|
||||||
|
_id: COMPETITION_ID,
|
||||||
|
matchId: MATCH_ID,
|
||||||
|
communityId: COMMUNITY_ID,
|
||||||
|
schemaVersion: 1,
|
||||||
|
revision: 7,
|
||||||
|
phase: 'running',
|
||||||
|
teams: [],
|
||||||
|
format: {
|
||||||
|
type: 'paired-series',
|
||||||
|
rule: { type: 'fixed-games', gameCount: 3, drawPolicy: 'allow' },
|
||||||
|
},
|
||||||
|
projection: {
|
||||||
|
sourceRevision: 7,
|
||||||
|
projectorVersion: 1,
|
||||||
|
phase: 'running',
|
||||||
|
formatType: 'paired-series',
|
||||||
|
series: [],
|
||||||
|
games: [],
|
||||||
|
gameSlots: [],
|
||||||
|
rounds: [],
|
||||||
|
connectors: [],
|
||||||
|
},
|
||||||
|
createdAt: new Date('2026-07-11T00:00:00.000Z'),
|
||||||
|
updatedAt: new Date('2026-07-12T00:00:00.000Z'),
|
||||||
|
};
|
||||||
|
const queryService = {
|
||||||
|
getCompetition: jest.fn().mockResolvedValue(competition),
|
||||||
|
getTeamView: jest.fn(),
|
||||||
|
listFacts: jest.fn(),
|
||||||
|
};
|
||||||
|
const commandService = {
|
||||||
|
acceptGame: jest.fn().mockResolvedValue({ competition, revision: 8 }),
|
||||||
|
adjudicateSeries: jest.fn().mockResolvedValue({ competition, revision: 8 }),
|
||||||
|
previewSeriesReversal: jest.fn().mockResolvedValue({
|
||||||
|
sourceRevision: 7,
|
||||||
|
impactHash: 'a'.repeat(64),
|
||||||
|
impact: {},
|
||||||
|
}),
|
||||||
|
reverseSeries: jest.fn().mockResolvedValue({ competition, revision: 8 }),
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
queryService,
|
||||||
|
commandService,
|
||||||
|
controller: new CompetitionController(
|
||||||
|
queryService as unknown as CompetitionQueryService,
|
||||||
|
commandService as unknown as CompetitionCommandService,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function adminUser() {
|
||||||
|
return {
|
||||||
|
_id: ADMIN_ID,
|
||||||
|
communityId: COMMUNITY_ID,
|
||||||
|
role: 'admin',
|
||||||
|
} as never;
|
||||||
|
}
|
||||||
|
|
||||||
|
function acceptGameBody() {
|
||||||
|
return {
|
||||||
|
gameId: GAME_ID.toHexString(),
|
||||||
|
seriesId: SERIES_ID,
|
||||||
|
gameSlotId: GAME_SLOT_ID.toHexString(),
|
||||||
|
ordinal: 1,
|
||||||
|
evidence: {
|
||||||
|
type: 'riot',
|
||||||
|
riotMatchId: 'KR_1',
|
||||||
|
payloadHash: 'sha256:value',
|
||||||
|
},
|
||||||
|
mapping: {
|
||||||
|
mappingVersion: 1,
|
||||||
|
confidence: 1,
|
||||||
|
blueTeamId: TEAM_A_ID.toHexString(),
|
||||||
|
redTeamId: TEAM_B_ID.toHexString(),
|
||||||
|
winnerTeamId: TEAM_A_ID.toHexString(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,499 @@
|
|||||||
|
import type {
|
||||||
|
CompetitionCommandResponse,
|
||||||
|
CompetitionDetailResponse,
|
||||||
|
CompetitionFactsResponse,
|
||||||
|
SeriesReversalPreviewResponse,
|
||||||
|
TeamCompetitionViewResponse,
|
||||||
|
} from '@lolympus/contracts';
|
||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Headers,
|
||||||
|
HttpException,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
Res,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import type { Response } from 'express';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { plainToInstance } from 'class-transformer';
|
||||||
|
import { validateSync, type ValidationError } from 'class-validator';
|
||||||
|
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
||||||
|
import { CurrentUser } from '../auth/current-user.decorator';
|
||||||
|
import { Roles } from '../auth/roles.decorator';
|
||||||
|
import { RolesGuard } from '../auth/roles.guard';
|
||||||
|
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||||
|
import type { UserDocument } from '../global/database/schema';
|
||||||
|
import { CompetitionCommandService } from './competition-command.service';
|
||||||
|
import { presentCompetitionDetail } from './competition.presenter';
|
||||||
|
import { CompetitionQueryService } from './competition-query.service';
|
||||||
|
import {
|
||||||
|
AcceptCompetitionGameDto,
|
||||||
|
AdjudicateCompetitionSeriesDto,
|
||||||
|
CompetitionFactsQueryDto,
|
||||||
|
PreviewCompetitionSeriesReversalDto,
|
||||||
|
ReverseCompetitionSeriesDto,
|
||||||
|
} from './dto/competition-command.dto';
|
||||||
|
|
||||||
|
@Controller('communities/:communityId/matches/:matchId/competition')
|
||||||
|
export class CompetitionController {
|
||||||
|
constructor(
|
||||||
|
private readonly queryService: CompetitionQueryService,
|
||||||
|
private readonly commandService: CompetitionCommandService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
@AllowPublicAccess()
|
||||||
|
public async getDetail(
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||||
|
@Res({ passthrough: true }) response: Response,
|
||||||
|
): Promise<CompetitionDetailResponse> {
|
||||||
|
return this.translate(async () => {
|
||||||
|
const competition = await this.queryService.getCompetition({
|
||||||
|
communityId,
|
||||||
|
matchId,
|
||||||
|
});
|
||||||
|
response.setHeader('ETag', revisionEtag(competition.revision));
|
||||||
|
return presentCompetitionDetail(competition as never);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('team')
|
||||||
|
public async getTeamView(
|
||||||
|
@CurrentUser() currentUser: UserDocument,
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||||
|
@Res({ passthrough: true }) response?: Response,
|
||||||
|
): Promise<TeamCompetitionViewResponse> {
|
||||||
|
return this.translate(async () => {
|
||||||
|
assertSameCommunity(currentUser, communityId);
|
||||||
|
const result = await this.queryService.getTeamView({
|
||||||
|
communityId,
|
||||||
|
matchId,
|
||||||
|
userId: currentUser._id,
|
||||||
|
});
|
||||||
|
response?.setHeader('ETag', revisionEtag(result.revision));
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('facts')
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
public async listFacts(
|
||||||
|
@CurrentUser() currentUser: UserDocument,
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||||
|
@Query() rawQuery: unknown,
|
||||||
|
): Promise<CompetitionFactsResponse> {
|
||||||
|
return this.translate(async () => {
|
||||||
|
assertSameCommunity(currentUser, communityId);
|
||||||
|
const query = validateDto(CompetitionFactsQueryDto, rawQuery);
|
||||||
|
return this.queryService.listFacts({
|
||||||
|
communityId,
|
||||||
|
matchId,
|
||||||
|
cursor: query.cursor,
|
||||||
|
limit: query.limit,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('games/accept')
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
public async acceptGame(
|
||||||
|
@CurrentUser() currentUser: UserDocument,
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||||
|
@Headers('if-match') ifMatch: string | undefined,
|
||||||
|
@Headers('idempotency-key') idempotencyKey: string | undefined,
|
||||||
|
@Body() rawBody: unknown,
|
||||||
|
): Promise<CompetitionCommandResponse> {
|
||||||
|
return this.translate(async () => {
|
||||||
|
assertSameCommunity(currentUser, communityId);
|
||||||
|
const body = validateDto(AcceptCompetitionGameDto, rawBody);
|
||||||
|
const expectedRevision = requireCommandHeaders(ifMatch, idempotencyKey);
|
||||||
|
const competition = await this.queryService.getCompetition({
|
||||||
|
communityId,
|
||||||
|
matchId,
|
||||||
|
});
|
||||||
|
const result = await this.commandService.acceptGame({
|
||||||
|
competitionId: competition._id,
|
||||||
|
expectedRevision,
|
||||||
|
idempotencyKey: idempotencyKey!,
|
||||||
|
actor: { type: 'user', userId: currentUser._id },
|
||||||
|
gameId: new mongoose.Types.ObjectId(body.gameId),
|
||||||
|
seriesId: new mongoose.Types.ObjectId(body.seriesId),
|
||||||
|
gameSlotId: new mongoose.Types.ObjectId(body.gameSlotId),
|
||||||
|
ordinal: body.ordinal,
|
||||||
|
evidence: { ...body.evidence },
|
||||||
|
mapping: { ...body.mapping },
|
||||||
|
...(body.startedAt ? { startedAt: body.startedAt } : {}),
|
||||||
|
...(body.durationSeconds === undefined
|
||||||
|
? {}
|
||||||
|
: { durationSeconds: body.durationSeconds }),
|
||||||
|
...(body.participants ? { participants: body.participants } : {}),
|
||||||
|
...(body.tournamentCode
|
||||||
|
? {
|
||||||
|
tournamentCode: {
|
||||||
|
tournamentCodeId: new mongoose.Types.ObjectId(
|
||||||
|
body.tournamentCode.tournamentCodeId,
|
||||||
|
),
|
||||||
|
riotMatchId: body.tournamentCode.riotMatchId,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
competition: presentCompetitionDetail(result.competition as never),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('series/:seriesId/adjudications')
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
public async adjudicateSeries(
|
||||||
|
@CurrentUser() currentUser: UserDocument,
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||||
|
@Param('seriesId', ParseObjectIdPipe) seriesId: mongoose.Types.ObjectId,
|
||||||
|
@Headers('if-match') ifMatch: string | undefined,
|
||||||
|
@Headers('idempotency-key') idempotencyKey: string | undefined,
|
||||||
|
@Body() rawBody: unknown,
|
||||||
|
): Promise<CompetitionCommandResponse> {
|
||||||
|
return this.translate(async () => {
|
||||||
|
assertSameCommunity(currentUser, communityId);
|
||||||
|
const body = validateDto(AdjudicateCompetitionSeriesDto, rawBody);
|
||||||
|
const expectedRevision = requireCommandHeaders(ifMatch, idempotencyKey);
|
||||||
|
const competition = await this.queryService.getCompetition({
|
||||||
|
communityId,
|
||||||
|
matchId,
|
||||||
|
});
|
||||||
|
const decision =
|
||||||
|
body.decision.type === 'administrative-draw'
|
||||||
|
? ({ type: 'administrative-draw' } as const)
|
||||||
|
: {
|
||||||
|
type: body.decision.type,
|
||||||
|
winnerTeamId: new mongoose.Types.ObjectId(
|
||||||
|
body.decision.winnerTeamId!,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
const result = await this.commandService.adjudicateSeries({
|
||||||
|
competitionId: competition._id,
|
||||||
|
expectedRevision,
|
||||||
|
idempotencyKey: idempotencyKey!,
|
||||||
|
actor: { type: 'user', userId: currentUser._id },
|
||||||
|
seriesId,
|
||||||
|
decision,
|
||||||
|
reason: body.reason,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
competition: presentCompetitionDetail(result.competition as never),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('series/:seriesId/reversal-preview')
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
public async previewReversal(
|
||||||
|
@CurrentUser() currentUser: UserDocument,
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||||
|
@Param('seriesId', ParseObjectIdPipe) seriesId: mongoose.Types.ObjectId,
|
||||||
|
@Headers('if-match') ifMatch: string | undefined,
|
||||||
|
@Body() rawBody: unknown,
|
||||||
|
): Promise<SeriesReversalPreviewResponse> {
|
||||||
|
return this.translate(async () => {
|
||||||
|
assertSameCommunity(currentUser, communityId);
|
||||||
|
const body = validateDto(PreviewCompetitionSeriesReversalDto, rawBody);
|
||||||
|
const expectedRevision = requireRevisionHeader(ifMatch);
|
||||||
|
const competition = await this.queryService.getCompetition({
|
||||||
|
communityId,
|
||||||
|
matchId,
|
||||||
|
});
|
||||||
|
return (await this.commandService.previewSeriesReversal({
|
||||||
|
competitionId: competition._id,
|
||||||
|
expectedRevision,
|
||||||
|
seriesId,
|
||||||
|
mode: body.mode,
|
||||||
|
})) as SeriesReversalPreviewResponse;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('series/:seriesId/reverse')
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
public async reverseSeries(
|
||||||
|
@CurrentUser() currentUser: UserDocument,
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||||
|
@Param('seriesId', ParseObjectIdPipe) seriesId: mongoose.Types.ObjectId,
|
||||||
|
@Headers('if-match') ifMatch: string | undefined,
|
||||||
|
@Headers('idempotency-key') idempotencyKey: string | undefined,
|
||||||
|
@Body() rawBody: unknown,
|
||||||
|
): Promise<CompetitionCommandResponse> {
|
||||||
|
return this.translate(async () => {
|
||||||
|
assertSameCommunity(currentUser, communityId);
|
||||||
|
const body = validateDto(ReverseCompetitionSeriesDto, rawBody);
|
||||||
|
const expectedRevision = requireCommandHeaders(ifMatch, idempotencyKey);
|
||||||
|
const competition = await this.queryService.getCompetition({
|
||||||
|
communityId,
|
||||||
|
matchId,
|
||||||
|
});
|
||||||
|
const result = await this.commandService.reverseSeries({
|
||||||
|
competitionId: competition._id,
|
||||||
|
expectedRevision,
|
||||||
|
idempotencyKey: idempotencyKey!,
|
||||||
|
actor: { type: 'user', userId: currentUser._id },
|
||||||
|
seriesId,
|
||||||
|
mode: body.mode,
|
||||||
|
reason: body.reason,
|
||||||
|
impactHash: body.impactHash,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
competition: presentCompetitionDetail(result.competition as never),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async translate<T>(operation: () => Promise<T>): Promise<T> {
|
||||||
|
try {
|
||||||
|
return await operation();
|
||||||
|
} catch (error) {
|
||||||
|
throw explicitHttpError(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireCommandHeaders(
|
||||||
|
ifMatch: string | undefined,
|
||||||
|
idempotencyKey: string | undefined,
|
||||||
|
): number {
|
||||||
|
const revision = parseRevision(ifMatch);
|
||||||
|
if (
|
||||||
|
revision === undefined ||
|
||||||
|
typeof idempotencyKey !== 'string' ||
|
||||||
|
idempotencyKey.trim().length === 0 ||
|
||||||
|
idempotencyKey.length > 200
|
||||||
|
) {
|
||||||
|
throw apiHttpError(
|
||||||
|
422,
|
||||||
|
'INVALID_COMPETITION_COMMAND_HEADERS',
|
||||||
|
'A numeric If-Match revision and non-empty Idempotency-Key are required.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return revision;
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireRevisionHeader(ifMatch: string | undefined): number {
|
||||||
|
const revision = parseRevision(ifMatch);
|
||||||
|
if (revision === undefined) {
|
||||||
|
throw apiHttpError(
|
||||||
|
422,
|
||||||
|
'INVALID_COMPETITION_COMMAND_HEADERS',
|
||||||
|
'A numeric If-Match revision is required.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return revision;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseRevision(value: string | undefined): number | undefined {
|
||||||
|
if (!value) return undefined;
|
||||||
|
const match = /^(?:W\/)?"?(\d+)"?$/.exec(value.trim());
|
||||||
|
if (!match) return undefined;
|
||||||
|
const revision = Number(match[1]);
|
||||||
|
return Number.isSafeInteger(revision) ? revision : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function revisionEtag(revision: number): string {
|
||||||
|
return `"${revision}"`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertSameCommunity(
|
||||||
|
user: UserDocument,
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
): void {
|
||||||
|
if (!user?.communityId?.equals(communityId)) {
|
||||||
|
throw apiHttpError(
|
||||||
|
403,
|
||||||
|
'COMPETITION_COMMUNITY_FORBIDDEN',
|
||||||
|
'The authenticated user does not belong to this community.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function explicitHttpError(error: unknown): HttpException {
|
||||||
|
if (error instanceof HttpException) {
|
||||||
|
const response = error.getResponse();
|
||||||
|
if (
|
||||||
|
typeof response === 'object' &&
|
||||||
|
response !== null &&
|
||||||
|
'error' in response
|
||||||
|
) {
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
return apiHttpError(
|
||||||
|
error.getStatus(),
|
||||||
|
statusCodeName(error.getStatus()),
|
||||||
|
typeof response === 'string'
|
||||||
|
? response
|
||||||
|
: error.message || 'Competition request failed.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (isCodedError(error)) {
|
||||||
|
return apiHttpError(
|
||||||
|
error.httpStatus ?? codedErrorStatus(error.code),
|
||||||
|
error.code,
|
||||||
|
error.message,
|
||||||
|
error.details,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return apiHttpError(
|
||||||
|
500,
|
||||||
|
'COMPETITION_INTERNAL_ERROR',
|
||||||
|
'Competition request failed.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function codedErrorStatus(code: string): number {
|
||||||
|
switch (code) {
|
||||||
|
case 'REVERSAL_SERIES_NOT_FOUND':
|
||||||
|
case 'REVERSAL_REASON_REQUIRED':
|
||||||
|
return 422;
|
||||||
|
case 'REVERSAL_DESCENDANT_ACTIVITY':
|
||||||
|
case 'REVERSAL_NO_ACTIVE_RESULT':
|
||||||
|
case 'REVERSAL_PREVIEW_STALE':
|
||||||
|
case 'DUPLICATE_FACT_ID':
|
||||||
|
case 'DUPLICATE_GAME_ID':
|
||||||
|
case 'DUPLICATE_RIOT_MATCH_ID':
|
||||||
|
case 'DUPLICATE_GAME_SLOT':
|
||||||
|
case 'DUPLICATE_GAME_ORDINAL':
|
||||||
|
case 'DUPLICATE_ADJUDICATION':
|
||||||
|
case 'FACT_ALREADY_REVERSED':
|
||||||
|
case 'SERIES_ALREADY_COMPLETED':
|
||||||
|
case 'WALKOVER_HAS_ACTIVE_GAMES':
|
||||||
|
return 409;
|
||||||
|
case 'FACT_REFERENCE_NOT_FOUND':
|
||||||
|
case 'FACT_TYPE_INVALID':
|
||||||
|
case 'GAME_SLOT_INVALID':
|
||||||
|
case 'GAME_ORDINAL_INVALID':
|
||||||
|
case 'GAME_SERIES_MISMATCH':
|
||||||
|
case 'GAME_TEAM_MISMATCH':
|
||||||
|
case 'GAME_WINNER_INVALID':
|
||||||
|
case 'SERIES_DEFINITION_INVALID':
|
||||||
|
case 'SERIES_PARTICIPANTS_INVALID':
|
||||||
|
case 'ADJUDICATION_INVALID':
|
||||||
|
case 'ADJUDICATION_DRAW_NOT_ALLOWED':
|
||||||
|
return 422;
|
||||||
|
default:
|
||||||
|
return 500;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusCodeName(status: number): string {
|
||||||
|
switch (status) {
|
||||||
|
case 403:
|
||||||
|
return 'COMPETITION_FORBIDDEN';
|
||||||
|
case 404:
|
||||||
|
return 'COMPETITION_NOT_FOUND';
|
||||||
|
case 409:
|
||||||
|
return 'COMPETITION_CONFLICT';
|
||||||
|
case 412:
|
||||||
|
return 'STALE_COMPETITION_REVISION';
|
||||||
|
case 422:
|
||||||
|
return 'INVALID_COMPETITION_REQUEST';
|
||||||
|
default:
|
||||||
|
return 'COMPETITION_REQUEST_FAILED';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function apiHttpError(
|
||||||
|
status: number,
|
||||||
|
code: string,
|
||||||
|
message: string,
|
||||||
|
details?: unknown,
|
||||||
|
): HttpException {
|
||||||
|
return new HttpException(
|
||||||
|
{
|
||||||
|
error: {
|
||||||
|
code,
|
||||||
|
message,
|
||||||
|
...(details === undefined ? {} : { details }),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
status,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isCodedError(error: unknown): error is {
|
||||||
|
code: string;
|
||||||
|
message: string;
|
||||||
|
httpStatus?: number;
|
||||||
|
details?: unknown;
|
||||||
|
} {
|
||||||
|
return (
|
||||||
|
typeof error === 'object' &&
|
||||||
|
error !== null &&
|
||||||
|
typeof (error as { code?: unknown }).code === 'string' &&
|
||||||
|
typeof (error as { message?: unknown }).message === 'string'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type DtoConstructor<T extends object> = new () => T;
|
||||||
|
|
||||||
|
function validateDto<T extends object>(
|
||||||
|
constructor: DtoConstructor<T>,
|
||||||
|
value: unknown,
|
||||||
|
): T {
|
||||||
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||||
|
throw apiHttpError(
|
||||||
|
422,
|
||||||
|
'INVALID_COMPETITION_REQUEST',
|
||||||
|
'The Competition request body must be an object.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const instance = plainToInstance(constructor, value);
|
||||||
|
const errors = validateSync(instance, {
|
||||||
|
whitelist: true,
|
||||||
|
forbidNonWhitelisted: true,
|
||||||
|
forbidUnknownValues: true,
|
||||||
|
});
|
||||||
|
if (errors.length > 0) {
|
||||||
|
throw apiHttpError(
|
||||||
|
422,
|
||||||
|
'INVALID_COMPETITION_REQUEST',
|
||||||
|
'The Competition request payload is invalid.',
|
||||||
|
{ fields: flattenValidationErrors(errors) },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
function flattenValidationErrors(
|
||||||
|
errors: readonly ValidationError[],
|
||||||
|
prefix = '',
|
||||||
|
): Array<{ field: string; constraints: string[] }> {
|
||||||
|
return errors.flatMap((error) => {
|
||||||
|
const field = prefix ? `${prefix}.${error.property}` : error.property;
|
||||||
|
const current = error.constraints
|
||||||
|
? [{ field, constraints: Object.values(error.constraints) }]
|
||||||
|
: [];
|
||||||
|
return [
|
||||||
|
...current,
|
||||||
|
...flattenValidationErrors(error.children ?? [], field),
|
||||||
|
];
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { MODULE_METADATA } from '@nestjs/common/constants';
|
||||||
|
import { CompetitionBootstrapService } from './competition-bootstrap.service';
|
||||||
|
import { CompetitionCommandService } from './competition-command.service';
|
||||||
|
import { CompetitionController } from './competition.controller';
|
||||||
|
import { CompetitionModule } from './competition.module';
|
||||||
|
import { CompetitionQueryService } from './competition-query.service';
|
||||||
|
|
||||||
|
describe('CompetitionModule', () => {
|
||||||
|
it('owns and exports the Competition transport and application services', () => {
|
||||||
|
expect(
|
||||||
|
Reflect.getMetadata(MODULE_METADATA.CONTROLLERS, CompetitionModule),
|
||||||
|
).toEqual([CompetitionController]);
|
||||||
|
expect(
|
||||||
|
Reflect.getMetadata(MODULE_METADATA.PROVIDERS, CompetitionModule),
|
||||||
|
).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
CompetitionBootstrapService,
|
||||||
|
CompetitionCommandService,
|
||||||
|
CompetitionQueryService,
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
Reflect.getMetadata(MODULE_METADATA.EXPORTS, CompetitionModule),
|
||||||
|
).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
CompetitionBootstrapService,
|
||||||
|
CompetitionCommandService,
|
||||||
|
CompetitionQueryService,
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { CompetitionBootstrapService } from './competition-bootstrap.service';
|
||||||
|
import { CompetitionCommandService } from './competition-command.service';
|
||||||
|
import { CompetitionController } from './competition.controller';
|
||||||
|
import { CompetitionQueryService } from './competition-query.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
controllers: [CompetitionController],
|
||||||
|
providers: [
|
||||||
|
CompetitionBootstrapService,
|
||||||
|
CompetitionCommandService,
|
||||||
|
CompetitionQueryService,
|
||||||
|
],
|
||||||
|
exports: [
|
||||||
|
CompetitionBootstrapService,
|
||||||
|
CompetitionCommandService,
|
||||||
|
CompetitionQueryService,
|
||||||
|
],
|
||||||
|
})
|
||||||
|
export class CompetitionModule {}
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
import { Type } from 'class-transformer';
|
||||||
|
import {
|
||||||
|
IsEnum,
|
||||||
|
IsArray,
|
||||||
|
IsDate,
|
||||||
|
IsInt,
|
||||||
|
IsMongoId,
|
||||||
|
IsNumber,
|
||||||
|
IsObject,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
Matches,
|
||||||
|
Max,
|
||||||
|
MaxLength,
|
||||||
|
Min,
|
||||||
|
MinLength,
|
||||||
|
ValidateIf,
|
||||||
|
ValidateNested,
|
||||||
|
} from 'class-validator';
|
||||||
|
|
||||||
|
const ADJUDICATION_TYPES = [
|
||||||
|
'walkover',
|
||||||
|
'forfeit',
|
||||||
|
'administrative',
|
||||||
|
'administrative-draw',
|
||||||
|
] as const;
|
||||||
|
const REVERSAL_MODES = ['strict', 'cascade'] as const;
|
||||||
|
const EVIDENCE_TYPES = ['riot', 'legacy'] as const;
|
||||||
|
|
||||||
|
export class CompetitionGameEvidenceDto {
|
||||||
|
@IsEnum(EVIDENCE_TYPES)
|
||||||
|
type!: (typeof EVIDENCE_TYPES)[number];
|
||||||
|
|
||||||
|
@ValidateIf(({ type }) => type === 'riot')
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(128)
|
||||||
|
riotMatchId?: string;
|
||||||
|
|
||||||
|
@ValidateIf(({ type }) => type === 'riot')
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(256)
|
||||||
|
payloadHash?: string;
|
||||||
|
|
||||||
|
@ValidateIf(({ type }) => type === 'legacy')
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(512)
|
||||||
|
legacyReference?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CompetitionGameMappingDto {
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
mappingVersion!: number;
|
||||||
|
|
||||||
|
@IsNumber()
|
||||||
|
@Min(0)
|
||||||
|
@Max(1)
|
||||||
|
confidence!: number;
|
||||||
|
|
||||||
|
@IsMongoId()
|
||||||
|
blueTeamId!: string;
|
||||||
|
|
||||||
|
@IsMongoId()
|
||||||
|
redTeamId!: string;
|
||||||
|
|
||||||
|
@IsMongoId()
|
||||||
|
winnerTeamId!: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsObject({ each: true })
|
||||||
|
participantAssignments?: Array<Record<string, unknown>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TournamentCodeReferenceDto {
|
||||||
|
@IsMongoId()
|
||||||
|
tournamentCodeId!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(128)
|
||||||
|
riotMatchId!: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class AcceptCompetitionGameDto {
|
||||||
|
@IsMongoId()
|
||||||
|
gameId!: string;
|
||||||
|
|
||||||
|
@IsMongoId()
|
||||||
|
seriesId!: string;
|
||||||
|
|
||||||
|
@IsMongoId()
|
||||||
|
gameSlotId!: string;
|
||||||
|
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
ordinal!: number;
|
||||||
|
|
||||||
|
@ValidateNested()
|
||||||
|
@Type(() => CompetitionGameEvidenceDto)
|
||||||
|
evidence!: CompetitionGameEvidenceDto;
|
||||||
|
|
||||||
|
@ValidateNested()
|
||||||
|
@Type(() => CompetitionGameMappingDto)
|
||||||
|
mapping!: CompetitionGameMappingDto;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsDate()
|
||||||
|
@Type(() => Date)
|
||||||
|
startedAt?: Date;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(0)
|
||||||
|
durationSeconds?: number;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsObject({ each: true })
|
||||||
|
participants?: Array<Record<string, unknown>>;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@ValidateNested()
|
||||||
|
@Type(() => TournamentCodeReferenceDto)
|
||||||
|
tournamentCode?: TournamentCodeReferenceDto;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CompetitionAdjudicationDecisionDto {
|
||||||
|
@IsEnum(ADJUDICATION_TYPES)
|
||||||
|
type!: (typeof ADJUDICATION_TYPES)[number];
|
||||||
|
|
||||||
|
@ValidateIf(({ type }) => type !== 'administrative-draw')
|
||||||
|
@IsMongoId()
|
||||||
|
winnerTeamId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class AdjudicateCompetitionSeriesDto {
|
||||||
|
@ValidateNested()
|
||||||
|
@Type(() => CompetitionAdjudicationDecisionDto)
|
||||||
|
decision!: CompetitionAdjudicationDecisionDto;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(2000)
|
||||||
|
reason!: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class PreviewCompetitionSeriesReversalDto {
|
||||||
|
@IsEnum(REVERSAL_MODES)
|
||||||
|
mode!: (typeof REVERSAL_MODES)[number];
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(2000)
|
||||||
|
reason!: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ReverseCompetitionSeriesDto extends PreviewCompetitionSeriesReversalDto {
|
||||||
|
@Matches(/^[a-f0-9]{64}$/)
|
||||||
|
impactHash!: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CompetitionFactsQueryDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(512)
|
||||||
|
cursor?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
@Max(100)
|
||||||
|
@Type(() => Number)
|
||||||
|
limit?: number;
|
||||||
|
}
|
||||||
Reference in new issue
Block a user