feat: enhance auction interactions and player statistics UI

This commit is contained in:
dahyeon committed 2026-11-11 20:06:22 +09:00
1 parent 6c582ba3cf
commit be4de61bb7
115 files changed
+13292 -2871

No files matched your search

@@ -0,0 +1,9 @@
/**
* 계정 지급 전에는 화면에서 선택한 팀으로 입찰하는 임시 운영 모드가 기본이다.
* 계정 지급 후 AUCTION_REQUIRE_CAPTAIN_AUTH=true로 로그인·팀장 검증을 복구한다.
*/
export function isAuctionCaptainAuthRequired(): boolean {
return (
process.env.AUCTION_REQUIRE_CAPTAIN_AUTH?.trim().toLowerCase() === 'true'
);
}
@@ -0,0 +1,156 @@
import mongoose from 'mongoose';
import { BadRequestException } from '@nestjs/common';
jest.mock('../auth/jwt.service', () => ({ JwtService: class JwtService {} }));
import { AuctionGateway } from './auction.gateway';
function setup() {
const appendChatMessage = jest.fn();
const gateway = new AuctionGateway(
{ appendChatMessage } as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
);
const broadcast = jest.fn();
const to = jest.fn().mockReturnValue({ emit: broadcast });
(gateway as unknown as { server: unknown }).server = {
to,
};
const socket = {
data: {
matchId: new mongoose.Types.ObjectId().toString(),
user: {
_id: new mongoose.Types.ObjectId(),
role: 'admin',
riotAccounts: [],
kakaoTalkNickname: '운영자',
},
},
emit: jest.fn(),
};
return { gateway, appendChatMessage, broadcast, socket, to };
}
describe('Auction chat delivery', () => {
const payload = {
message: '준비해 주세요',
clientMessageId: '0589e8a4-bccd-4ccd-a3ae-28f117401e79',
};
it('acknowledges only after saving and assigns the operator role from the socket user', async () => {
const { gateway, appendChatMessage, broadcast, socket } = setup();
const message = { id: 'saved', ...payload, sentAt: new Date() };
let finish!: (result: unknown) => void;
appendChatMessage.mockReturnValue(
new Promise((resolve) => {
finish = resolve;
}),
);
const ack = jest.fn();
const pending = gateway.handleChatMessage(socket as never, payload, ack);
expect(ack).not.toHaveBeenCalled();
expect(broadcast).not.toHaveBeenCalled();
finish({ message, created: true });
await pending;
expect(appendChatMessage).toHaveBeenCalledWith(
expect.objectContaining({
clientMessageId: payload.clientMessageId,
senderRole: 'operator',
displayName: '운영자',
}),
);
expect(ack).toHaveBeenCalledWith({
ok: true,
message: expect.objectContaining({ id: 'saved' }),
});
expect(broadcast).toHaveBeenCalledTimes(1);
});
it('acknowledges a retry without broadcasting a duplicate', async () => {
const { gateway, appendChatMessage, broadcast, socket } = setup();
appendChatMessage.mockResolvedValue({
message: { id: 'saved' },
created: false,
});
const ack = jest.fn();
await gateway.handleChatMessage(socket as never, payload, ack);
expect(ack).toHaveBeenCalledWith({ ok: true, message: { id: 'saved' } });
expect(broadcast).not.toHaveBeenCalled();
});
it('returns rejection to the requesting composer without reporting success', async () => {
const { gateway, appendChatMessage, broadcast, socket } = setup();
appendChatMessage.mockRejectedValue(
new BadRequestException('Chat message is required.'),
);
const ack = jest.fn();
await gateway.handleChatMessage(socket as never, payload, ack);
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({
ok: false,
message: 'Chat message is required.',
}),
);
expect(broadcast).not.toHaveBeenCalled();
});
});
describe('Auction live reactions', () => {
it('broadcasts to the joined room with the server-resolved name, without saving a chat message', () => {
const { gateway, appendChatMessage, broadcast, socket, to } = setup();
const ack = jest.fn();
gateway.handleChatReaction(socket as never, { kind: 'clap' }, ack);
expect(to).toHaveBeenCalledWith(socket.data.matchId);
expect(broadcast).toHaveBeenCalledWith(
'chat-reaction',
expect.objectContaining({
id: expect.any(String),
kind: 'clap',
displayName: '운영자',
userId: socket.data.user._id.toString(),
}),
);
expect(ack).toHaveBeenCalledWith({
ok: true,
reaction: broadcast.mock.calls[0][1],
});
expect(appendChatMessage).not.toHaveBeenCalled();
});
it('rejects unjoined clients and arbitrary reaction values', () => {
const { gateway, broadcast, socket } = setup();
const ack = jest.fn();
gateway.handleChatReaction({ data: {} } as never, { kind: 'heart' }, ack);
expect(ack).toHaveBeenLastCalledWith({ ok: false, code: 'NOT_JOINED' });
for (const kind of ['__proto__', 'not-supported', 1, null]) {
gateway.handleChatReaction(socket as never, { kind }, ack);
expect(ack).toHaveBeenLastCalledWith({
ok: false,
code: 'INVALID_REACTION',
});
}
expect(broadcast).not.toHaveBeenCalled();
});
it('throttles bursts, then accepts the next reaction after the interval', () => {
const { gateway, broadcast, socket } = setup();
const clock = jest.spyOn(Date, 'now').mockReturnValue(1000);
const ack = jest.fn();
try {
gateway.handleChatReaction(socket as never, { kind: 'heart' }, ack);
gateway.handleChatReaction(socket as never, { kind: 'heart' }, ack);
expect(ack).toHaveBeenLastCalledWith({
ok: false,
code: 'REACTION_RATE_LIMITED',
});
expect(broadcast).toHaveBeenCalledTimes(1);
clock.mockReturnValue(1400);
gateway.handleChatReaction(socket as never, { kind: 'celebrate' }, ack);
expect(broadcast).toHaveBeenCalledTimes(2);
} finally {
clock.mockRestore();
}
});
});
@@ -0,0 +1,101 @@
import 'reflect-metadata';
import mongoose from 'mongoose';
import { GUARDS_METADATA } from '@nestjs/common/constants';
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from '../auth/allow-public-access.decorator';
import type { UserDocument } from '../global/database/schema';
jest.mock('../auth/jwt.service', () => ({
JwtService: class JwtService {},
}));
import { AuctionController } from './auction.controller';
describe('AuctionController bid authentication', () => {
beforeEach(() => {
jest.replaceProperty(process, 'env', { ...process.env });
delete process.env.AUCTION_REQUIRE_CAPTAIN_AUTH;
});
afterEach(() => jest.restoreAllMocks());
it('allows HTTP guests to reach the configurable bid checks', () => {
const handler = AuctionController.prototype.placeBid;
expect(
Reflect.getMetadata(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, handler),
).toBe(true);
expect(Reflect.getMetadata(GUARDS_METADATA, handler)).toBeUndefined();
});
it.each([undefined, 'false', 'true'])(
'handles HTTP guests with captain auth=%s',
async (auth) => {
if (auth !== undefined) process.env.AUCTION_REQUIRE_CAPTAIN_AUTH = auth;
const placeBid = jest.fn().mockResolvedValue({ revision: 2 });
const controller = new AuctionController(
{ placeBid } as never,
{} as never,
{} as never,
);
const matchId = new mongoose.Types.ObjectId();
const result = controller.placeBid(
undefined,
new mongoose.Types.ObjectId(),
matchId,
{
bidderTeamIndex: 2,
bidPointAmount: 20,
},
);
if (auth === 'true') {
await expect(result).rejects.toThrow(
'팀장 계정으로 로그인해야 입찰할 수 있습니다.',
);
expect(placeBid).not.toHaveBeenCalled();
} else {
await expect(result).resolves.toEqual({ revision: 2 });
expect(placeBid).toHaveBeenCalledWith(
expect.objectContaining({
matchId,
teamIndex: 2,
amount: 20,
bidderUserId: undefined,
}),
);
}
},
);
it('passes the signed-in user to service checks and restores community validation in strict mode', async () => {
const placeBid = jest.fn().mockResolvedValue({ revision: 2 });
const controller = new AuctionController(
{ placeBid } as never,
{} as never,
{} as never,
);
const user = {
_id: new mongoose.Types.ObjectId(),
communityId: new mongoose.Types.ObjectId(),
} as UserDocument;
const matchId = new mongoose.Types.ObjectId();
const body = { bidderTeamIndex: 2, bidPointAmount: 20 };
await controller.placeBid(
user,
new mongoose.Types.ObjectId(),
matchId,
body,
);
expect(placeBid).toHaveBeenLastCalledWith(
expect.objectContaining({ bidderUserId: user._id }),
);
process.env.AUCTION_REQUIRE_CAPTAIN_AUTH = 'true';
await expect(
controller.placeBid(user, new mongoose.Types.ObjectId(), matchId, body),
).rejects.toThrow('Different community.');
expect(placeBid).toHaveBeenCalledTimes(1);
await expect(
controller.placeBid(user, user.communityId, matchId, body),
).resolves.toEqual({ revision: 2 });
expect(placeBid).toHaveBeenCalledTimes(2);
});
});
@@ -3,6 +3,7 @@ import {
Body,
Controller,
Delete,
ForbiddenException,
Get,
HttpCode,
HttpStatus,
@@ -19,6 +20,7 @@ import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { UserDocument } from '../global/database/schema';
import { AuctionService } from './auction.service';
import { isAuctionCaptainAuthRequired } from './auction-bid-auth';
import { AuctionGateway } from './auction.gateway';
import { AuctionBidArchiveService } from './auction-bid-archive.service';
import {
@@ -106,20 +108,26 @@ export class AuctionController {
}
@Post('bids')
@Roles('admin', 'owner', 'member')
@UseGuards(RolesGuard)
@AllowPublicAccess()
@HttpCode(HttpStatus.OK)
public async placeBid(
@CurrentUser() currentUser: UserDocument,
@CurrentUser() currentUser: UserDocument | undefined,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: PlaceBidDto,
) {
this.assertSameCommunity(currentUser, communityId);
if (isAuctionCaptainAuthRequired()) {
if (!currentUser) {
throw new ForbiddenException(
'팀장 계정으로 로그인해야 입찰할 수 있습니다.',
);
}
this.assertSameCommunity(currentUser, communityId);
}
return this.auctionService.placeBid({
matchId,
bidderUserId: currentUser._id,
bidderUserId: currentUser?._id,
teamIndex: body.bidderTeamIndex,
amount: body.bidPointAmount,
bidRequestId: body.bidRequestId,
@@ -8,6 +8,15 @@ jest.mock('../auth/jwt.service', () => ({
import { AuctionGateway } from './auction.gateway';
describe('AuctionGateway', () => {
beforeEach(() => {
jest.replaceProperty(process, 'env', { ...process.env });
delete process.env.AUCTION_REQUIRE_CAPTAIN_AUTH;
});
afterEach(() => {
jest.restoreAllMocks();
});
it('signals pending initial state so the client can retry privately after recovery', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const gateway = new AuctionGateway(
@@ -114,7 +123,8 @@ describe('AuctionGateway', () => {
};
}
it('requires an authenticated user before forwarding a bid', async () => {
it('requires an authenticated user when captain authentication is enabled', async () => {
process.env.AUCTION_REQUIRE_CAPTAIN_AUTH = 'true';
const matchId = new mongoose.Types.ObjectId().toString();
const { gateway, auctionService } = createGateway();
const ack = jest.fn();
@@ -131,6 +141,49 @@ describe('AuctionGateway', () => {
);
});
it.each([undefined, bidderUserId])(
'accepts the selected team in temporary mode for user %s',
async (userId) => {
const matchId = new mongoose.Types.ObjectId().toString();
const placeBidDelta = jest.fn().mockResolvedValue({
auctionBidHistoryEntry: {
bidderTeamIndex: 2,
bidderUserId: new mongoose.Types.ObjectId().toString(),
bidPointAmount: 120,
bidPlacedAtTimestampMS: 1780000000000,
},
currentHighestBidderTeamIndex: 2,
currentHighestBidPointAmount: 120,
currentServerTimestampMS: 1780000000000,
revision: 9,
});
const { gateway, emit } = createGateway({ placeBidDelta });
const ack = jest.fn();
await gateway.handleBid(
{
data: { matchId, user: userId ? { _id: userId } : undefined },
emit: jest.fn(),
} as never,
{ bidderTeamIndex: 2, bidPointAmount: 120 },
ack,
);
expect(placeBidDelta).toHaveBeenCalledWith(
expect.objectContaining({
teamIndex: 2,
amount: 120,
bidderUserId: userId,
}),
);
expect(ack).toHaveBeenCalledWith(expect.objectContaining({ ok: true }));
expect(emit).toHaveBeenCalledWith(
'bid',
expect.objectContaining({ currentHighestBidderTeamIndex: 2 }),
);
},
);
it('broadcasts a bid delta and acknowledges the matching bid request', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const auctionBidHistoryEntry = {
@@ -14,6 +14,11 @@ import {
import mongoose from 'mongoose';
import type { JWTPayload } from 'jose';
import type { DefaultEventsMap, Namespace, Socket } from 'socket.io';
import type {
AuctionReactionEvent,
AuctionReactionKind,
AuctionReactionReply,
} from '@lolympus/contracts';
import { AuthService } from '../auth/auth.service';
import { IdentityService } from '../auth/identity.service';
import { JwtService } from '../auth/jwt.service';
@@ -31,6 +36,7 @@ import type {
AuctionStateResponse,
} from './auction.service';
import { AuctionEventBusService } from './auction-event-bus.service';
import { isAuctionCaptainAuthRequired } from './auction-bid-auth';
import {
isAuctionResyncRecommended,
resolveAuctionRejectionReason,
@@ -72,6 +78,7 @@ type AuctionActionPayload = Omit<SoldPayload, 'assignedPosition'>;
interface ChatMessagePayload {
message?: string;
displayName?: string;
clientMessageId?: string;
}
interface BidRateLimitState {
@@ -80,6 +87,7 @@ interface BidRateLimitState {
}
interface AuctionSocketData {
auctionReactionSentAt?: number;
auctionResyncAtTimestampMS?: number;
auctionResyncInProgress?: boolean;
auctionBidRateLimit?: BidRateLimitState;
@@ -97,6 +105,16 @@ type AuctionSocket = Socket<
>;
const BID_RATE_LIMIT_WINDOW_MS = 1000;
const REACTION_KINDS: Record<AuctionReactionKind, true> = {
'thumbs-up': true,
heart: true,
clap: true,
laugh: true,
wow: true,
sad: true,
fire: true,
celebrate: true,
};
const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8;
const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED';
const BID_RATE_LIMIT_REJECTION_MESSAGE =
@@ -250,7 +268,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
try {
const bidderUserId = this.resolveSocketUserId(socket);
if (!bidderUserId)
if (isAuctionCaptainAuthRequired() && !bidderUserId)
throw new ForbiddenException(
'팀장 계정으로 로그인해야 입찰할 수 있습니다.',
);
@@ -466,30 +484,82 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
public async handleChatMessage(
@ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: ChatMessagePayload,
@Ack() ack?: (response: Record<string, unknown>) => void,
) {
const matchId = this.requireJoinedMatchId(socket);
if (!matchId) return;
if (!matchId) {
ack?.({ ok: false, message: 'Join a match room before sending events.' });
return;
}
if (typeof payload?.message !== 'string') {
this.emitError(socket, 'Chat message is required.');
ack?.({ ok: false, message: 'Chat message is required.' });
return;
}
try {
const { message } = await this.auctionService.appendChatMessage({
const { message, created } = await this.auctionService.appendChatMessage({
matchId: new mongoose.Types.ObjectId(matchId),
clientMessageId: payload.clientMessageId,
senderRole: ['owner', 'admin'].includes(socket.data.user?.role ?? '')
? 'operator'
: undefined,
userId: this.resolveSocketUserId(socket),
displayName: this.resolveChatDisplayName(socket, payload.displayName),
message: payload.message,
});
this.server
.to(matchId)
.emit('chat-message', this.serializeChatMessage(message));
const serialized = this.serializeChatMessage(message);
if (created) this.server.to(matchId).emit('chat-message', serialized);
ack?.({ ok: true, message: serialized });
} catch (error) {
this.emitKnownError(socket, error);
if (ack) ack({ ok: false, ...this.resolveErrorPayload(error) });
else this.emitKnownError(socket, error);
}
}
@SubscribeMessage('chat-reaction')
public handleChatReaction(
@ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: { kind?: unknown },
@Ack() ack?: (response: AuctionReactionReply) => void,
) {
const matchId = this.getSocketMatchId(socket);
if (!matchId) {
ack?.({ ok: false, code: 'NOT_JOINED' });
return;
}
if (
typeof payload?.kind !== 'string' ||
!Object.hasOwn(REACTION_KINDS, payload.kind)
) {
ack?.({ ok: false, code: 'INVALID_REACTION' });
return;
}
const now = Date.now();
if (
socket.data.auctionReactionSentAt !== undefined &&
now - socket.data.auctionReactionSentAt < 400
) {
ack?.({ ok: false, code: 'REACTION_RATE_LIMITED' });
return;
}
socket.data.auctionReactionSentAt = now;
const reaction: AuctionReactionEvent = {
id: randomUUID(),
kind: payload.kind as AuctionReactionKind,
displayName: Array.from(this.resolveChatDisplayName(socket))
.slice(0, 40)
.join(''),
userId: this.resolveSocketUserId(socket)?.toString(),
sentAt: now,
};
// The room adapter fans out to all viewers. Reactions never enter the
// persisted message history, so reconnects do not replay old animations.
this.server.to(matchId).emit('chat-reaction', reaction);
ack?.({ ok: true, reaction });
}
private requireJoinedMatchId(socket: AuctionSocket): string | null {
const matchId = this.getSocketMatchId(socket);
if (!matchId) {
@@ -156,6 +156,11 @@ describe('AuctionService', () => {
};
}
beforeEach(() => {
jest.replaceProperty(process, 'env', { ...process.env });
delete process.env.AUCTION_REQUIRE_CAPTAIN_AUTH;
});
afterEach(() => {
jest.restoreAllMocks();
jest.useRealTimers();
@@ -1055,6 +1060,113 @@ describe('AuctionService', () => {
});
});
describe.each(['realtime', 'redis-fallback', 'legacy'] as const)(
'%s bid authorization',
(path) => {
it.each([
[undefined, 'guest'],
[undefined, 'other-user'],
['false', 'other-user'],
['true', 'guest'],
['true', 'other-user'],
['true', 'captain'],
] as const)('checks auth=%s for %s', async (auth, actor) => {
if (auth !== undefined) process.env.AUCTION_REQUIRE_CAPTAIN_AUTH = auth;
const matchId = new mongoose.Types.ObjectId();
const captainUserId = new mongoose.Types.ObjectId();
const playerUserId = new mongoose.Types.ObjectId();
const bidderUserId =
actor === 'guest'
? undefined
: actor === 'captain'
? captainUserId
: new mongoose.Types.ObjectId();
const team = { teamIndex: 2, captainUserId, points: 1000, members: [] };
const auction = {
_id: new mongoose.Types.ObjectId(),
matchId,
auctionEngineVersion: path === 'legacy' ? undefined : 'redis-v1',
phase: 'bidding',
teams: [team],
currentBid: 0,
bidExtensionSeconds: 5,
bids: [],
save: jest.fn().mockResolvedValue(undefined),
toObject: () => ({ matchId, teams: [team], phase: 'bidding' }),
};
const {
service,
auctionRedisCommandService,
auctionRedisStateReaderService,
} = createService({
auction: { findOne: jest.fn().mockResolvedValue(auction) },
});
const state = {
auctionLifecycleId: 'life-1',
currentBidRoundPlayerUserId: playerUserId.toString(),
phase: 'bidding',
revision: 2,
auctionTeams: [
{
teamIndex: 2,
captainUserId: captainUserId.toString(),
remainingBidPointAmount: 1000,
members: [],
},
],
};
auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue(
state,
);
if (path === 'realtime') {
auctionRedisStateReaderService.readBidContext.mockResolvedValue({
...state,
bidderTeamCaptainUserId: captainUserId.toString(),
});
}
const result = service.placeBidDelta({
matchId,
teamIndex: 2,
amount: 20,
bidderUserId,
bidRequestId: 'auth-mode-bid',
});
if (auth === 'true' && actor !== 'captain') {
await expect(result).rejects.toThrow(
actor === 'guest'
? '팀장 계정으로 로그인해야 입찰할 수 있습니다.'
: '해당 팀의 팀장만 입찰할 수 있습니다.',
);
expect(auctionRedisCommandService.placeBid).not.toHaveBeenCalled();
expect(auction.save).not.toHaveBeenCalled();
return;
}
await expect(result).resolves.toBeDefined();
if (path === 'legacy') {
expect(auction.bids).toEqual([
expect.objectContaining({
teamIndex: 2,
amount: 20,
bidderUserId: captainUserId,
}),
]);
expect(auction.save).toHaveBeenCalledTimes(1);
} else {
expect(auctionRedisCommandService.placeBid).toHaveBeenCalledWith(
matchId.toString(),
expect.objectContaining({
bidderTeamIndex: 2,
bidPointAmount: 20,
bidderUserId: captainUserId.toString(),
}),
);
}
});
},
);
it('places bids through Redis for redis-v1 auctions', async () => {
const matchId = new mongoose.Types.ObjectId();
const captainUserId = new mongoose.Types.ObjectId();
@@ -1747,9 +1859,17 @@ describe('AuctionService', () => {
chatMessages: oldMessages,
save: jest.fn().mockResolvedValue(undefined),
};
const findOneAndUpdate = jest.fn().mockImplementation((_filter, update) => {
auction.chatMessages = [
...auction.chatMessages,
...update.$push.chatMessages.$each,
].slice(-200);
return auction;
});
const { service } = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
findOneAndUpdate,
},
});
@@ -1770,7 +1890,54 @@ describe('AuctionService', () => {
expect(auction.chatMessages).toHaveLength(200);
expect(auction.chatMessages[0].id).toBe('old-1');
expect(auction.chatMessages.at(-1)).toBe(appended.message);
expect(auction.save).toHaveBeenCalledTimes(1);
expect(auction.save).not.toHaveBeenCalled();
expect(appended.created).toBe(true);
expect(findOneAndUpdate).toHaveBeenCalledWith(
{ matchId, 'chatMessages.id': { $ne: appended.message.id } },
{ $push: { chatMessages: { $each: [appended.message], $slice: -200 } } },
{ new: true },
);
});
it('returns the saved message on retry without appending or broadcasting it again', async () => {
const matchId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const clientMessageId = '0589e8a4-bccd-4ccd-a3ae-28f117401e79';
const saved = {
id: `${userId.toString()}:${clientMessageId}`,
clientMessageId,
userId,
displayName: '팀장',
message: '확인했습니다',
sentAt: new Date(),
};
const findOneAndUpdate = jest.fn().mockResolvedValue(null);
const auction = { matchId, chatMessages: [saved] };
const { service } = createService({
auction: {
findOneAndUpdate,
findOne: jest.fn().mockResolvedValue(auction),
},
});
await expect(
service.appendChatMessage({
matchId,
userId,
clientMessageId,
message: '확인했습니다',
}),
).resolves.toEqual({ auction, message: saved, created: false });
expect(findOneAndUpdate.mock.calls[0][0]['chatMessages.id']).toEqual({
$ne: saved.id,
});
await expect(
service.appendChatMessage({
matchId,
userId,
clientMessageId,
message: '다른 메시지',
}),
).rejects.toThrow('Chat message conflicts with an earlier request.');
});
it('rejects blank and overly long chat messages', async () => {
+51 -11
View File
@@ -16,6 +16,7 @@ import {
} from './auction-lifecycle-lock';
import { AUCTION_OPTIONAL_PROJECTION_FIELDS } from './auction-projection';
import { AuctionEventBusService } from './auction-event-bus.service';
import { isAuctionCaptainAuthRequired } from './auction-bid-auth';
import { performance } from 'perf_hooks';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
@@ -142,6 +143,8 @@ type RedisActionRequestContext =
interface AppendChatMessageParams {
matchId: mongoose.Types.ObjectId;
clientMessageId?: string;
senderRole?: 'operator';
userId?: mongoose.Types.ObjectId;
displayName?: string;
message: string;
@@ -666,26 +669,57 @@ export class AuctionService {
public async appendChatMessage(params: AppendChatMessageParams): Promise<{
auction: AuctionDocument;
message: AuctionChatMessage;
created: boolean;
}> {
const auction = await this.getByMatchId(params.matchId);
const messageText = this.normalizeChatMessage(params.message);
if (
params.clientMessageId !== undefined &&
!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
params.clientMessageId,
)
) {
throw new BadRequestException('Invalid chat message id.');
}
// A retry keeps its ID. The conditional push is atomic, including when
// the first request is still saving after the client has timed out.
const id = params.clientMessageId
? `${params.userId?.toString() ?? 'guest'}:${params.clientMessageId}`
: randomUUID();
const message: AuctionChatMessage = {
id: randomUUID(),
id,
clientMessageId: params.clientMessageId,
senderRole: params.senderRole,
userId: params.userId,
displayName: this.normalizeChatDisplayName(params.displayName),
message: messageText,
sentAt: new Date(),
};
auction.chatMessages ??= [];
auction.chatMessages.push(message);
const overflow = auction.chatMessages.length - AUCTION_CHAT_MAX_MESSAGES;
if (overflow > 0) {
auction.chatMessages.splice(0, overflow);
}
const AuctionModel = await this.connectionService.getModel('auction');
const auction = await AuctionModel.findOneAndUpdate(
{ matchId: params.matchId, 'chatMessages.id': { $ne: id } },
{
$push: {
chatMessages: {
$each: [message],
$slice: -AUCTION_CHAT_MAX_MESSAGES,
},
},
},
{ new: true },
);
if (auction) return { auction, message, created: true };
await auction.save();
return { auction, message };
const existingAuction = await this.getByMatchId(params.matchId);
const existing = existingAuction.chatMessages.find(
(entry) => entry.id === id,
);
if (!existing || existing.message !== messageText) {
throw new BadRequestException(
'Chat message conflicts with an earlier request.',
);
}
return { auction: existingAuction, message: existing, created: false };
}
public async listHistory(params: {
@@ -2921,7 +2955,13 @@ export class AuctionService {
bidderUserId: mongoose.Types.ObjectId | undefined,
captainUserId: string,
) {
if (bidderUserId && bidderUserId.toString() !== captainUserId) {
if (!isAuctionCaptainAuthRequired()) return;
if (!bidderUserId) {
throw new ForbiddenException(
'팀장 계정으로 로그인해야 입찰할 수 있습니다.',
);
}
if (bidderUserId.toString() !== captainUserId) {
throw new ForbiddenException('해당 팀의 팀장만 입찰할 수 있습니다.');
}
}
@@ -86,10 +86,11 @@ export class CommunityStatsController {
@Query('to') to?: string,
@Query('championId') championId?: string,
@Query('q') query?: string,
@Query('lane') lane?: string,
) {
return this.communityStatsService.getLeaderboard({
communityId,
filters: this.toFilters({ seasonId, from, to, championId, query }),
filters: this.toFilters({ seasonId, from, to, championId, query, lane }),
});
}
@@ -131,18 +132,24 @@ export class CommunityStatsController {
@Query('championId') championId?: string,
@Query('cursor') cursor?: string,
@Query('limit') limit?: string,
@Query('lane') lane?: string,
@Query('includePositionCounts') includePositionCounts?: string,
) {
return this.communityStatsService.getUserInternalHistory({
communityId,
userId,
filters: this.toFilters({
seasonId,
from,
to,
championId,
cursor,
limit,
}),
filters: {
...this.toFilters({
seasonId,
from,
to,
championId,
cursor,
limit,
lane,
}),
includePositionCounts: includePositionCounts === 'true',
},
});
}
@@ -157,7 +164,14 @@ export class CommunityStatsController {
format?: CommunityStatsFilters['format'];
playerId?: string;
cursorMatchId?: string;
lane?: string;
}): CommunityStatsFilters {
if (
params.lane !== undefined &&
!['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'].includes(params.lane)
) {
throw new BadRequestException('Invalid lane.');
}
if (
params.query !== undefined &&
(typeof params.query !== 'string' || params.query.length > 100)
@@ -175,6 +189,7 @@ export class CommunityStatsController {
format: params.format,
playerId: params.playerId,
cursorMatchId: params.cursorMatchId,
lane: params.lane as CommunityStatsFilters['lane'],
};
}
@@ -320,7 +320,7 @@ describe('CommunityStatsService', () => {
expect(set).not.toHaveBeenCalled();
expect(setDetail).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenCalledWith(
expect.objectContaining({ field: expect.stringContaining(':r8:') }),
expect.objectContaining({ field: expect.stringContaining(':r9:') }),
response,
);
},
@@ -530,7 +530,7 @@ describe('CommunityStatsService', () => {
expect(setDetail).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenNthCalledWith(
2,
expect.objectContaining({ field: expect.stringContaining(':r8:') }),
expect.objectContaining({ field: expect.stringContaining(':r9:') }),
invalidCheckpointResponse,
);
});
@@ -637,7 +637,7 @@ describe('CommunityStatsService', () => {
includeTimeline: true,
});
expect(set).toHaveBeenCalledWith(
expect.objectContaining({ field: expect.stringContaining(':r8:') }),
expect.objectContaining({ field: expect.stringContaining(':r9:') }),
fallback,
60,
);
@@ -649,7 +649,7 @@ describe('CommunityStatsService', () => {
expect(buildAndUpsert).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenCalledTimes(1);
expect(setDetail).toHaveBeenCalledWith(
expect.objectContaining({ field: expect.stringContaining(':r8:') }),
expect.objectContaining({ field: expect.stringContaining(':r9:') }),
recovered,
);
});
@@ -820,6 +820,36 @@ describe('CommunityStatsService', () => {
);
});
it('returns independent recent-20 lane windows and counts from records before pagination', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const records = Array.from({ length: 60 }, (_, index) => ({
...record(matchId), userId: userId.toString(), gameNumber: index + 1,
riotMatchId: `KR_${index}`, gameCreation: index * 1000,
teamPosition: index < 25 ? 'MIDDLE' : 'TOP',
}));
const repository = {
findUserRecordFragments: jest.fn().mockResolvedValue([{ matchId, builderVersion: MATCH_STATS_BUILDER_VERSION, records }]),
findDetailsByMatches: jest.fn().mockResolvedValue([]),
} as unknown as jest.Mocked<MatchStatsRepository>;
const cache = { get: jest.fn().mockResolvedValue(null), set: jest.fn().mockResolvedValue(undefined) } as unknown as CommunityStatsCacheService;
const service = new CommunityStatsService({} as ConnectionService, cache, repository, {} as MatchStatsService);
(service as unknown as { resolveContext: jest.Mock }).resolveContext = jest.fn().mockResolvedValue({
community: {}, season: { id: 'all', label: '전체', startedAt: null, endedAt: null }, from: null, to: null,
});
const mid = await service.getUserInternalHistory({ communityId, userId, filters: { limit: 20, lane: 'MIDDLE', includePositionCounts: true } });
expect(mid.matches).toHaveLength(20);
expect(mid.matches[0].matchId).toBe('KR_24');
expect(mid.matches[19].matchId).toBe('KR_5');
expect(mid.matches[0].damageShare).toBe(30);
expect(mid.positionCounts).toEqual({ ALL: 20, TOP: 20, JUNGLE: 0, MIDDLE: 20, BOTTOM: 0, UTILITY: 0 });
expect(repository.findUserRecordFragments).toHaveBeenCalledWith(expect.objectContaining({ limit: 0 }));
const all = await service.getUserInternalHistory({ communityId, userId, filters: { limit: 20, includePositionCounts: true } });
expect(all.matches.every(game => game.teamPosition === 'TOP')).toBe(true);
expect(all.positionCounts).toEqual(mid.positionCounts);
});
it('coalesces concurrent user internal history cache misses', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
@@ -45,6 +45,7 @@ import {
MatchStatsUserRecordFragment,
} from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
import { presentStatsCard, statsDate } from './internal-stats-presentation';
import {
InternalGameDetail,
InternalRecord,
@@ -55,7 +56,7 @@ const DEFAULT_LIST_LIMIT = 20;
const MAX_LIST_LIMIT = 50;
const MAX_MATCH_SCAN = 300;
const MIN_HIGHLIGHT_GAMES = 5;
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 8;
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 9;
const INCOMPLETE_MATCH_DETAIL_TTL_SECONDS = 60;
interface CommunityStatsContext {
@@ -139,6 +140,7 @@ export class CommunityStatsService {
'projection.formatType': 1,
'projection.outcome': 1,
'projection.series': 1,
'projection.games': 1,
})
.lean()
.exec();
@@ -148,6 +150,9 @@ export class CommunityStatsService {
this.presentOfficialResult(competition),
]),
);
const sources = new Map(
competitions.map((source) => [source.matchId.toString(), source]),
);
return {
...pagination,
matches: cards.map(({ card, sourceCompetitionId, sourceRevision }) => {
@@ -161,10 +166,20 @@ export class CommunityStatsService {
(resultPresentation.type === 'official' &&
sourceCompetitionId === resultPresentation.competitionId &&
sourceRevision === resultPresentation.sourceRevision);
return {
const presented = {
...(canUseGames ? card : this.adjustCardForRange(card, [])),
resultPresentation,
};
const source = sources.get(card.matchId);
return source && canUseGames
? presentStatsCard(
presented,
presentCompetitionDetail({
...source,
teams: source.teams.map((team) => ({ ...team, members: [] })),
}),
)
: presented;
}),
};
}
@@ -192,7 +207,24 @@ export class CommunityStatsService {
return {
cards: visible.map((fragment) => ({
card: this.adjustCardForRange(
fragment.matchCard as unknown as InternalMatchCardView,
{
...(fragment.matchCard as unknown as InternalMatchCardView),
games: (
fragment.matchCard as unknown as InternalMatchCardView
).games.map((game) => {
const detail = fragment.gameDetails?.find(
(item) => item.gameNumber === game.gameNumber,
);
return {
...game,
analysisAvailability: !detail
? ('pending' as const)
: detail.rawAvailable === false
? ('missing' as const)
: ('available' as const),
};
}),
},
(fragment.gameDetails ?? []).filter((game) =>
this.isGameInRange(game.gameCreation, context),
),
@@ -226,6 +258,7 @@ export class CommunityStatsService {
const records = this.applyChampionFilter(dataset.records, filters);
response = {
rows: this.buildLeaderboardRows(records),
lane: filters.lane,
season: dataset.season,
};
await this.cacheService.set(key, response);
@@ -275,6 +308,7 @@ export class CommunityStatsService {
const response: TeamInsightsResponse = {
season: dataset.season,
totals: dataset.totals,
sideWinRate: {
blue: this.percent(blueWins, blueGames),
red: this.percent(redWins, redGames),
@@ -464,7 +498,18 @@ export class CommunityStatsService {
}
}
const response: InternalMatchDetailResponse = {
match,
match: presentStatsCard(
{
...match,
games: (match.games ?? []).map((game) => ({
...game,
analysisAvailability:
games.find((linked) => linked.game.gameNumber === game.gameNumber)
?.analysisAvailability ?? 'pending',
})),
},
dataset.competition,
),
competition: dataset.competition,
games: games.map(({ game, official, analysisAvailability }) => ({
gameNumber: game.gameNumber,
@@ -708,11 +753,24 @@ export class CommunityStatsService {
});
const gameDetails: Array<Pick<InternalGameDetail, 'winnerSide'>> = [];
const records: InternalRecord[] = [];
const participants = new Set<string>();
let matches = 0,
analyzedGames = 0;
for (const fragment of fragments) {
const games = fragment.gameDetails.filter((game) =>
this.isGameInRange(game.gameCreation, context),
);
const gameNumbers = new Set(games.map(({ gameNumber }) => gameNumber));
if (games.length) matches += 1;
const gameNumbers = new Set(
games
.filter((game) => game.rawAvailable !== false)
.map(({ gameNumber }) => gameNumber),
);
analyzedGames += gameNumbers.size;
const allNumbers = new Set(games.map((game) => game.gameNumber));
fragment.records
.filter((record) => allNumbers.has(record.gameNumber))
.forEach((record) => participants.add(record.userId));
gameDetails.push(...games);
records.push(
...fragment.records.filter(({ gameNumber }) =>
@@ -720,7 +778,17 @@ export class CommunityStatsService {
),
);
}
return { season: context.season, records, gameDetails };
return {
season: context.season,
records,
gameDetails,
totals: {
matches,
games: gameDetails.length,
analyzedGames,
players: participants.size,
},
};
}
private async buildBaseDataset(
@@ -850,7 +918,8 @@ export class CommunityStatsService {
userId: params.userId,
fromGameCreation: context.from?.getTime(),
toGameCreation: context.to?.getTime(),
limit: MAX_MATCH_SCAN,
// The inspector needs the latest 20 of each lane, even in older events.
limit: params.filters.includePositionCounts ? 0 : MAX_MATCH_SCAN,
};
let fragments =
await this.matchStatsRepository.findUserRecordFragments(fragmentQuery);
@@ -885,8 +954,31 @@ export class CommunityStatsService {
};
const response: UserInternalHistoryResponse = {
season: context.season,
...(params.filters.includePositionCounts
? {
positionCounts: Object.fromEntries(
['ALL', 'TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'].map(
(lane) => [
lane,
Math.min(
20,
this.applyChampionFilter(allUserRecords, {
championId: params.filters.championId,
}).filter(
(record) =>
lane === 'ALL' || record.teamPosition === lane,
).length,
),
],
),
),
}
: {}),
playerStats: records.length
? this.toLeaderboardRow(userId, records)
: null,
championStats: this.buildUserChampionStats(
allUserRecords,
this.applyChampionFilter(allUserRecords, { lane: params.filters.lane }),
context.season,
),
summary: this.buildUserSummary(records, visible.length || limit),
@@ -913,6 +1005,11 @@ export class CommunityStatsService {
fragment.records.filter(
(record) =>
record.userId === userId &&
!fragment.gameDetails?.some(
(game) =>
game.gameNumber === record.gameNumber &&
game.rawAvailable === false,
) &&
this.isGameInRange(record.gameCreation, context),
),
)
@@ -1129,13 +1226,13 @@ export class CommunityStatsService {
const community = await CommunityModel.findById(communityId).exec();
if (!community) throw new NotFoundException('Community not found.');
const season = this.resolveSeason(community, filters.seasonId);
const from = filters.from
? new Date(filters.from)
let from = filters.from
? statsDate(filters.from, false)
: season.startedAt
? new Date(season.startedAt)
: null;
const to = filters.to
? new Date(filters.to)
let to = filters.to
? statsDate(filters.to, true)
: season.endedAt
? new Date(season.endedAt)
: null;
@@ -1148,6 +1245,11 @@ export class CommunityStatsService {
if (from && to && from.getTime() > to.getTime()) {
throw new BadRequestException('Invalid date range.');
}
// A date filter narrows the selected season; it never escapes it.
if (season.startedAt && (!from || from < new Date(season.startedAt)))
from = new Date(season.startedAt);
if (season.endedAt && (!to || to > new Date(season.endedAt)))
to = new Date(season.endedAt);
return { community, season, from, to };
}
@@ -1419,6 +1521,7 @@ export class CommunityStatsService {
return {
matchId: record.riotMatchId,
internalMatchId: record.matchId,
internalMatchTitle: record.title,
gameNumber: record.gameNumber,
queueId: 0,
queueLabel: '내전',
@@ -1443,6 +1546,7 @@ export class CommunityStatsService {
wardsPlaced: record.wardsPlaced,
wardsKilled: record.wardsKilled,
damageDealtToChampions: record.damageDealtToChampions,
damageShare: record.damageShare,
damageTaken: record.damageTaken,
goldEarned: record.gold,
items: record.items,
@@ -1493,8 +1597,11 @@ export class CommunityStatsService {
records: InternalRecord[],
filters: CommunityStatsFilters,
): InternalRecord[] {
if (!filters.championId) return records;
return records.filter((record) => record.championId === filters.championId);
return records.filter(
(record) =>
(!filters.championId || record.championId === filters.championId) &&
(!filters.lane || record.teamPosition === filters.lane),
);
}
private isGameInRange(
@@ -1533,6 +1640,8 @@ export class CommunityStatsService {
summonerName: record.summonerName,
championId: record.championId,
matchId: record.riotMatchId,
internalMatchId: record.matchId,
gameNumber: record.gameNumber,
isSingleGame: true,
};
}
@@ -1621,7 +1730,7 @@ export class CommunityStatsService {
cacheScope,
JSON.stringify([
MATCH_STATS_BUILDER_VERSION,
scope === 'matches' ? 'matches-page-v1' : scope,
`${scope}:presentation-v2`,
filters.seasonId ?? 'current',
filters.from ?? '',
filters.to ?? '',
@@ -1632,6 +1741,8 @@ export class CommunityStatsService {
filters.format ?? '',
filters.playerId ?? '',
filters.cursorMatchId ?? '',
filters.lane ?? '',
...(filters.includePositionCounts ? ['position-windows-v1'] : []),
]),
);
}
@@ -5,6 +5,7 @@ import type {
InternalMatchCompetition,
InternalMatchResultPresentation,
SeriesId,
SeriesProjection,
} from '@lolympus/contracts';
import type {
MatchStatsParticipantCheckpoints,
@@ -21,6 +22,7 @@ import type {
} from '../match-history/match-history.types';
export interface CommunityStatsFilters {
includePositionCounts?: boolean;
seasonId?: string;
from?: string;
to?: string;
@@ -31,6 +33,7 @@ export interface CommunityStatsFilters {
format?: 'pair' | 'tournament';
playerId?: string;
cursorMatchId?: string;
lane?: RiotLane;
}
export interface InternalMatchListResponse {
@@ -48,6 +51,8 @@ export interface InternalMatchCardView {
gameCount: number;
winnerTeamIndex?: number;
resultPresentation?: InternalMatchResultPresentation;
/** Official series only. Historical opponent pairs are not inferred rounds. */
series?: SeriesProjection[];
seriesResults: Array<{
teamAIndex: number;
teamBIndex: number;
@@ -57,6 +62,9 @@ export interface InternalMatchCardView {
}>;
games: Array<{
gameNumber: number;
seriesId?: string;
ordinal?: number;
analysisAvailability?: GameAnalysisAvailability | 'pending';
riotMatchId: string | null;
blueTeamIndex: number;
redTeamIndex: number;
@@ -66,6 +74,7 @@ export interface InternalMatchCardView {
}>;
teams: Array<{
teamIndex: number;
teamId?: string;
name: string;
members: Array<{
userId: string;
@@ -77,6 +86,7 @@ export interface InternalMatchCardView {
export interface LeaderboardResponse {
rows: LeaderboardRow[];
lane?: RiotLane;
season: HistorySeasonDto;
matchedUserIds?: string[];
}
@@ -111,11 +121,19 @@ export interface LeaderHighlight {
summonerName: string;
championId?: number;
matchId?: string;
internalMatchId?: string;
gameNumber?: number;
isSingleGame: boolean;
}
export interface TeamInsightsResponse {
season: HistorySeasonDto;
totals: {
matches: number;
games: number;
analyzedGames: number;
players: number;
};
sideWinRate: {
blue: number;
red: number;
@@ -214,7 +232,9 @@ export interface InternalMatchDetailResponse {
}
export interface UserInternalHistoryResponse {
positionCounts?: Record<string, number>;
season: HistorySeasonDto;
playerStats?: LeaderboardRow | null;
championStats: LeaderboardChampionStats;
summary: {
windowSize: number;
@@ -0,0 +1,378 @@
import { BadRequestException } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import request from 'supertest';
import type { Server } from 'node:http';
import mongoose from 'mongoose';
import { CommunityStatsService } from './community-stats.service';
import { CommunityStatsController } from './community-stats.controller';
import { ConnectionService } from '../global/database/connection.service';
import { CommunityStatsCacheService } from './community-stats-cache.service';
import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
import {
MATCH_STATS_BUILDER_VERSION,
type InternalRecord,
} from './match-stats.types';
import { presentStatsCard, statsDate } from './internal-stats-presentation';
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const start = Date.parse('2026-06-18T12:00:00Z');
function record(
gameNumber: number,
values: Partial<InternalRecord> = {},
): InternalRecord {
return {
matchId: matchId.toString(),
title: '여름 내전',
scheduledAt: new Date(start),
gameNumber,
riotMatchId: `KR_${gameNumber}`,
gameCreation: start + gameNumber * 1800000,
gameDuration: 1800,
userId: userId.toString(),
summonerName: '선수',
tagLine: 'KR1',
profileIconId: 1,
teamIndex: 1,
side: 'blue',
championId: 1,
teamPosition: 'TOP',
kills: 8,
deaths: 2,
assists: 4,
win: true,
cs: 240,
csPerMin: 8,
gold: 12000,
gpm: 400,
killParticipation: 60,
damageShare: 30,
visionScore: 12,
damageDealtToChampions: 18000,
...values,
} as InternalRecord;
}
function fixture() {
const records = [
record(1),
record(2, {
teamPosition: 'JUNGLE',
championId: 2,
kills: 2,
deaths: 4,
assists: 6,
win: false,
csPerMin: 4,
gpm: 300,
killParticipation: 40,
}),
record(3, { kills: 99 }),
record(3, { userId: new mongoose.Types.ObjectId().toString() }),
];
const fragment = {
matchId,
builderVersion: MATCH_STATS_BUILDER_VERSION,
records,
gameDetails: [1, 2, 3].map((gameNumber) => ({
gameNumber,
gameCreation: start + gameNumber * 1800000,
winnerSide: gameNumber === 2 ? 'red' : 'blue',
rawAvailable: gameNumber !== 3,
})),
};
const cache = new Map<string, unknown>();
const repository = {
findSeasonStats: jest.fn().mockResolvedValue([fragment]),
findUserRecordFragments: jest.fn().mockResolvedValue([fragment]),
findDetailsByMatches: jest.fn().mockResolvedValue([]),
};
const service = new CommunityStatsService(
{
getModel: async () => ({
findById: () => ({
exec: async () => ({
seasons: [
{
id: 'june',
label: '6월',
startedAt: new Date('2026-06-01T00:00:00+09:00'),
endedAt: new Date('2026-06-30T23:59:59.999+09:00'),
},
],
}),
}),
}),
} as unknown as ConnectionService,
{
get: async (key: unknown) => cache.get(JSON.stringify(key)),
set: async (key: unknown, value: unknown) => {
cache.set(JSON.stringify(key), value);
},
} as unknown as CommunityStatsCacheService,
repository as unknown as MatchStatsRepository,
{} as MatchStatsService,
);
jest
.spyOn(
service as unknown as { repairCommunityFragments: () => Promise<number> },
'repairCommunityFragments',
)
.mockResolvedValue(0);
return { service, repository };
}
describe('internal stats API contract', () => {
it('serves the scoped player and leaderboard contracts through the HTTP routes', async () => {
const { service } = fixture();
const module = await Test.createTestingModule({
controllers: [CommunityStatsController],
providers: [{ provide: CommunityStatsService, useValue: service }],
}).compile();
const app = module.createNestApplication();
await app.init();
const server: Server = app.getHttpServer();
try {
const base = `/communities/${communityId.toString()}`;
const leaderboard = await request(server)
.get(`${base}/internal-stats/leaderboard?seasonId=all&lane=TOP`)
.expect(200);
expect(leaderboard.body).toMatchObject({
lane: 'TOP',
rows: [{ games: 1, kda: 6 }],
});
const player = await request(server)
.get(
`${base}/users/${userId.toString()}/internal-history?seasonId=all&lane=JUNGLE`,
)
.expect(200);
expect(player.body).toMatchObject({
playerStats: { games: 1, kda: 2 },
matches: [{ gameNumber: 2 }],
});
await request(server)
.get(`${base}/internal-stats/leaderboard?lane=invalid`)
.expect(400);
await request(server)
.get(`${base}/internal-stats/leaderboard?from=2026-02-30`)
.expect(400);
await request(server)
.get('/communities/invalid/internal-stats/leaderboard')
.expect(400);
} finally {
await app.close();
}
});
it('searches escaped text across title, team and player without losing date or cursor constraints', async () => {
const chain = {
select: jest.fn().mockReturnThis(),
sort: jest.fn().mockReturnThis(),
limit: jest.fn().mockReturnThis(),
lean: jest.fn().mockReturnThis(),
exec: jest.fn().mockResolvedValue([]),
};
const find = jest.fn().mockReturnValue(chain);
const repository = new MatchStatsRepository({
getModel: async () => ({ find }),
} as unknown as ConnectionService);
await repository.findMatchPage({
communityId,
query: '팀.*',
from: start,
cursor: start + 1000,
cursorMatchId: matchId.toString(),
limit: 4,
});
expect(find).toHaveBeenCalledWith(
expect.objectContaining({
communityId,
$and: expect.arrayContaining([
{
$or: [
'matchCard.title',
'matchCard.teams.name',
'matchCard.teams.members.summonerName',
].map((field) => ({
[field]: { $regex: '팀\\.\\*', $options: 'i' },
})),
},
]),
}),
);
expect(chain.limit).toHaveBeenCalledWith(4);
expect(chain.select).toHaveBeenCalledWith(
expect.objectContaining({ 'gameDetails.rawAvailable': 1 }),
);
});
it('recalculates every metric per lane, isolates cached scopes and excludes missing raw data', async () => {
const { service } = fixture();
const all = await service.getLeaderboard({
communityId,
filters: { seasonId: 'all' },
});
const top = await service.getLeaderboard({
communityId,
filters: { seasonId: 'all', lane: 'TOP' },
});
const jungle = await service.getLeaderboard({
communityId,
filters: { seasonId: 'all', lane: 'JUNGLE' },
});
expect(all.rows).toHaveLength(1);
expect(all.rows[0]).toMatchObject({
games: 2,
totalKills: 10,
winRate: 50,
avgGoldPerMin: 350,
avgCsPerMin: 6,
avgKillParticipation: 50,
});
expect(top).toMatchObject({
lane: 'TOP',
rows: [
{
games: 1,
kda: 6,
winRate: 100,
avgGoldPerMin: 400,
avgCsPerMin: 8,
avgKillParticipation: 60,
},
],
});
expect(jungle).toMatchObject({
lane: 'JUNGLE',
rows: [{ games: 1, kda: 2, winRate: 0, avgGoldPerMin: 300 }],
});
expect(
await service.getLeaderboard({
communityId,
filters: { seasonId: 'all' },
}),
).toEqual(all);
const insight = await service.getTeamInsights({
communityId,
filters: { seasonId: 'all' },
});
expect(insight.totals).toEqual({
matches: 1,
games: 3,
analyzedGames: 2,
players: 2,
});
expect(insight.topTeamGpm).toMatchObject({
internalMatchId: matchId.toString(),
gameNumber: 1,
metric: 400,
});
});
it('keeps player summary and matches in the same scope while retaining champion choices', async () => {
const { service } = fixture();
const history = await service.getUserInternalHistory({
communityId,
userId,
filters: { seasonId: 'all', championId: 1 },
});
expect(history.playerStats).toMatchObject({ games: 1, kda: 6 });
expect(history.matches).toHaveLength(1);
expect(history.matches[0]).toMatchObject({
internalMatchId: matchId.toString(),
internalMatchTitle: '여름 내전',
gameNumber: 1,
});
expect(history.championStats.champions).toHaveLength(2);
});
it('intersects custom dates with the season and accepts inclusive KST calendar dates', async () => {
const { service, repository } = fixture();
await service.getLeaderboard({
communityId,
filters: { seasonId: 'june', from: '2026-05-01', to: '2026-07-31' },
});
expect(repository.findSeasonStats).toHaveBeenCalledWith({
communityId,
from: Date.parse('2026-05-31T15:00:00Z'),
to: Date.parse('2026-06-30T14:59:59.999Z'),
});
expect(statsDate('2026-06-18', false)?.toISOString()).toBe(
'2026-06-17T15:00:00.000Z',
);
expect(statsDate('2026-06-18', true)?.toISOString()).toBe(
'2026-06-18T14:59:59.999Z',
);
await expect(
service.getLeaderboard({ communityId, filters: { from: '2026-02-30' } }),
).rejects.toBeInstanceOf(BadRequestException);
await expect(
service.getLeaderboard({
communityId,
filters: { from: '2026-06-20', to: '2026-06-19' },
}),
).rejects.toBeInstanceOf(BadRequestException);
});
it('rejects unsupported lanes at the HTTP controller boundary', () => {
const controller = new CommunityStatsController(
{} as CommunityStatsService,
);
expect(() =>
(
controller as unknown as {
toFilters: (params: { lane: string }) => unknown;
}
).toFilters({ lane: 'SUPPORT' }),
).toThrow(BadRequestException);
});
it('uses official evidence to distinguish rematches and does not invent round identities', () => {
type Card = Parameters<typeof presentStatsCard>[0];
type Competition = NonNullable<Parameters<typeof presentStatsCard>[1]>;
const card = {
games: [
{ gameNumber: 1, riotMatchId: 'KR_1' },
{ gameNumber: 2, riotMatchId: 'KR_2' },
{ gameNumber: 3, riotMatchId: 'old' },
],
teams: [{ teamIndex: 1 }],
} as Card;
const competition = {
teams: [{ displayOrder: 1, teamId: 'a' }],
projection: {
games: [
{
displayNumber: 1,
ordinal: 1,
seriesId: 'upper',
evidence: { type: 'riot', riotMatchId: 'KR_1' },
},
{
displayNumber: 2,
ordinal: 1,
seriesId: 'final',
evidence: { type: 'riot', riotMatchId: 'KR_2' },
},
{
displayNumber: 3,
ordinal: 2,
seriesId: 'final',
evidence: { type: 'riot', riotMatchId: 'replacement' },
},
],
series: [
{ seriesId: 'upper' },
{ seriesId: 'final' },
{ seriesId: 'other', status: 'scheduled' },
],
},
} as unknown as Competition;
const result = presentStatsCard(card, competition);
expect(result.games.map((game) => game.seriesId)).toEqual([
'upper',
'final',
undefined,
]);
expect(result.series?.map((series) => series.seriesId)).toEqual([
'upper',
'final',
]);
expect(result.teams[0].teamId).toBe('a');
});
});
@@ -0,0 +1,59 @@
import type { InternalMatchCompetition } from '@lolympus/contracts';
import type { InternalMatchCardView } from './community-stats.types';
/** Attach official identities without merging rematches between the same teams. */
export function presentStatsCard(
card: InternalMatchCardView,
competition?: Pick<InternalMatchCompetition, 'teams' | 'projection'>,
): InternalMatchCardView {
if (!competition) return card;
const officialGames = competition.projection.games ?? [];
const games = card.games.map((game) => {
const official = officialGames.find(
(candidate) =>
candidate.displayNumber === game.gameNumber &&
(candidate.evidence.type === 'riot'
? candidate.evidence.riotMatchId
: candidate.evidence.legacyReference) === game.riotMatchId,
);
return official
? { ...game, seriesId: official.seriesId, ordinal: official.ordinal }
: game;
});
const visible = new Set(games.map((game) => game.seriesId));
return {
...card,
games,
teams: card.teams?.map((team) => ({
...team,
teamId: competition.teams.find((t) => t.displayOrder === team.teamIndex)
?.teamId,
})),
series: (competition.projection.series ?? []).filter(
(series) =>
visible.has(series.seriesId) ||
(series.status === 'completed' && series.outcome.type !== 'played'),
),
};
}
/** Date-only inputs are inclusive Korean calendar days; ISO timestamps remain supported. */
export function statsDate(
value: string | undefined,
end: boolean,
): Date | null {
if (!value) return null;
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
const date = new Date(
`${value}T${end ? '23:59:59.999' : '00:00:00.000'}+09:00`,
);
const midnight = new Date(`${value}T00:00:00.000Z`);
if (
!Number.isFinite(midnight.getTime()) ||
midnight.toISOString().slice(0, 10) !== value
)
return new Date(NaN);
return date;
}
return new Date(value);
}
@@ -6,7 +6,11 @@ import type { MatchStats, MatchStatsDocument } from '../global/database/schema';
export type MatchStatsUserRecordFragment = Pick<
MatchStats,
'matchId' | 'records' | 'builderVersion'
>;
> & {
gameDetails?: Array<
Pick<MatchStats['gameDetails'][number], 'gameNumber' | 'rawAvailable'>
>;
};
export type MatchStatsDetailFragment = Pick<
MatchStats,
@@ -209,10 +213,17 @@ export class MatchStatsRepository {
};
}
if (params.query) {
filter['matchCard.title'] = {
const search = {
$regex: params.query.replace(/[.*+?^$\x7b\x7d()|[\]\\]/g, '\\$&'),
$options: 'i',
};
conditions.push({
$or: [
{ 'matchCard.title': search },
{ 'matchCard.teams.name': search },
{ 'matchCard.teams.members.summonerName': search },
],
});
}
if (params.format) {
filter['matchCard.teams.1'] = { $exists: true };
@@ -250,6 +261,7 @@ export class MatchStatsRepository {
sourceRevision: 1,
'gameDetails.gameNumber': 1,
'gameDetails.gameCreation': 1,
'gameDetails.rawAvailable': 1,
})
.sort({ scheduledAt: -1, matchId: -1 })
.limit(params.limit)
@@ -298,6 +310,8 @@ export class MatchStatsRepository {
})
.select({
_id: 0,
matchId: 1,
scheduledAt: 1,
'records.userId': 1,
'records.summonerName': 1,
'records.tagLine': 1,
@@ -319,6 +333,7 @@ export class MatchStatsRepository {
'gameDetails.gameCreation': 1,
'gameDetails.gameNumber': 1,
'gameDetails.winnerSide': 1,
'gameDetails.rawAvailable': 1,
})
.sort({ scheduledAt: -1 })
.lean()
@@ -352,7 +367,14 @@ export class MatchStatsRepository {
return MatchStatsModel.find(filter)
.sort({ scheduledAt: -1 })
.limit(params.limit ?? 300)
.select({ _id: 0, matchId: 1, records: 1, builderVersion: 1 })
.select({
_id: 0,
matchId: 1,
records: 1,
builderVersion: 1,
'gameDetails.gameNumber': 1,
'gameDetails.rawAvailable': 1,
})
.lean<MatchStatsUserRecordFragment[]>()
.exec();
}
@@ -857,6 +857,8 @@ export const AuctionBidRecordSchema = new Schema<AuctionBidRecord>(
export interface AuctionChatMessage {
id: string;
clientMessageId?: string;
senderRole?: 'operator';
userId?: mongoose.Types.ObjectId;
displayName: string;
message: string;
@@ -2255,6 +2257,8 @@ const AuctionBidHistoryEntrySubSchema = new Schema<AuctionBidHistoryEntry>(
const AuctionChatMessageSubSchema = new Schema<AuctionChatMessage>(
{
id: { type: String, required: true },
clientMessageId: { type: String, required: false },
senderRole: { type: String, enum: ['operator'], required: false },
userId: { type: Schema.Types.ObjectId, ref: 'user', required: false },
displayName: { type: String, required: true },
message: { type: String, required: true },
@@ -56,6 +56,7 @@ export class MatchHistoryController {
@Query('seasonId') seasonId?: string,
@Query('championId') championId?: string,
@Query('limit') limit?: string,
@Query('lane') lane?: string,
) {
return this.matchHistoryService.getRecentSummary({
communityId,
@@ -66,6 +67,7 @@ export class MatchHistoryController {
seasonId,
championId: this.toNumber(championId),
limit: this.toNumber(limit),
lane,
},
});
}
@@ -82,6 +84,8 @@ export class MatchHistoryController {
@Query('championId') championId?: string,
@Query('limit') limit?: string,
@Query('cursor') cursor?: string,
@Query('lane') lane?: string,
@Query('includePositionCounts') includePositionCounts?: string,
) {
return this.matchHistoryService.getRecentMatches({
communityId,
@@ -93,6 +97,8 @@ export class MatchHistoryController {
championId: this.toNumber(championId),
limit: this.toNumber(limit),
cursor: this.toNumber(cursor),
lane,
includePositionCounts: includePositionCounts === 'true',
},
});
}
@@ -5,6 +5,72 @@ import { MatchHistoryService } from './match-history.service';
const SEASON_START = Date.parse('2026-01-01T00:00:00Z');
describe('MatchHistoryService champion filtering', () => {
it('selects a lane before limiting and uses only the requested participant, including legacy individualPosition', async () => {
const { service, scope, find } = createHarness();
const result = await service.getRecentMatches({
...scope,
filters: { rank: 'solo', lane: 'MIDDLE', limit: 20 },
});
expect(result.matches.map((game) => game.matchId)).toEqual([
'KR_3',
'KR_2',
'KR_1',
]);
expect(result.matches.every((game) => game.teamPosition === 'MIDDLE')).toBe(
true,
);
expect(result.matches[0].damageShare).toBe(100);
expect(find.mock.calls[0][0]['raw.info.participants']?.$elemMatch).toEqual({
puuid: 'player',
$or: [
{ teamPosition: 'MIDDLE' },
{ teamPosition: { $in: ['', null] }, individualPosition: 'MIDDLE' },
],
});
});
it('combines champion and lane filtering and rejects invalid lanes', async () => {
const { service, scope } = createHarness();
const result = await service.getRecentMatches({
...scope,
filters: { rank: 'solo', championId: 1, lane: 'MIDDLE', limit: 20 },
});
expect(result.matches).toEqual([]);
await expect(
service.getRecentMatches({ ...scope, filters: { lane: 'unknown' } }),
).rejects.toThrow('Invalid lane');
});
it('counts independent lane windows across the season and caps each at twenty', async () => {
const { service, scope, aggregate } = createHarness();
const result = await service.getRecentMatches({
...scope,
filters: {
rank: 'solo',
lane: 'MIDDLE',
limit: 20,
includePositionCounts: true,
},
});
expect(result.positionCounts).toEqual({
ALL: 20,
TOP: 20,
JUNGLE: 0,
MIDDLE: 3,
BOTTOM: 0,
UTILITY: 0,
});
expect(aggregate.mock.calls[0][0][0]).toEqual({
$match: {
participantPuuids: 'player',
queueId: { $in: [420] },
gameCreation: { $gte: SEASON_START },
},
});
expect(JSON.stringify(aggregate.mock.calls[0][0])).toContain('$$p.puuid');
expect(JSON.stringify(aggregate.mock.calls[0][0])).not.toContain('$limit');
});
it('paginates matching games beyond 120 newer games and excludes opponents using the champion', async () => {
const harness = createHarness();
const filters = { championId: 99, rank: 'solo', limit: 2 };
@@ -77,7 +143,14 @@ interface HistoryQuery {
queueId: { $in: number[] };
gameCreation?: { $gte?: number; $lt?: number };
'raw.info.participants'?: {
$elemMatch: { puuid: string; championId: number };
$elemMatch: {
puuid: string;
championId?: number;
$or?: Array<{
teamPosition: string | { $in: (string | null)[] };
individualPosition?: string;
}>;
};
};
}
@@ -122,7 +195,18 @@ function createHarness() {
row.raw.info.participants.some(
(entry) =>
entry.puuid === participant.puuid &&
entry.championId === participant.championId,
(participant.championId === undefined ||
entry.championId === participant.championId) &&
(!participant.$or ||
participant.$or.some((condition) =>
typeof condition.teamPosition === 'string'
? entry.teamPosition === condition.teamPosition
: condition.teamPosition.$in.includes(
entry.teamPosition ?? null,
) &&
entry.individualPosition ===
condition.individualPosition,
)),
)),
)
.sort((a, b) => b.gameCreation - a.gameCreation)
@@ -133,6 +217,15 @@ function createHarness() {
};
return query;
});
const aggregate = jest.fn<
{ exec: () => Promise<Array<{ _id: string; count: number }>> },
[unknown[]]
>(() => ({
exec: async () => [
{ _id: 'TOP', count: 127 },
{ _id: 'MIDDLE', count: 3 },
],
}));
const models = {
user: {
find: () => ({
@@ -179,7 +272,7 @@ function createHarness() {
}),
}),
},
riotMatch: { find },
riotMatch: { find, aggregate },
};
const connection = {
getModel: async (name: keyof typeof models) => models[name],
@@ -190,6 +283,7 @@ function createHarness() {
find,
select,
returnedCounts,
aggregate,
};
}
@@ -198,6 +292,9 @@ function storedMatch(sequence: number, championId: number, queueId = 420) {
const participant = {
puuid: 'player',
championId,
teamPosition:
sequence === 2 ? undefined : championId === 99 ? 'MIDDLE' : 'TOP',
individualPosition: championId === 99 ? 'MIDDLE' : 'TOP',
teamId: 100,
win: true,
kills: 5,
@@ -229,6 +326,7 @@ function storedMatch(sequence: number, championId: number, queueId = 420) {
puuid: 'opponent',
teamId: 200,
championId: 99,
teamPosition: 'MIDDLE',
win: false,
},
],
@@ -53,6 +53,8 @@ interface MatchFilters {
championId?: number;
limit?: number;
cursor?: number;
lane?: string;
includePositionCounts?: boolean;
}
interface AggregatedChampion {
@@ -183,6 +185,7 @@ export class MatchHistoryService {
context,
queueIds,
championId: params.filters.championId,
lane: params.filters.lane,
limit,
});
const views = docs
@@ -212,6 +215,7 @@ export class MatchHistoryService {
context,
queueIds,
championId: params.filters.championId,
lane: params.filters.lane,
limit: limit + 1,
cursor: params.filters.cursor,
});
@@ -223,6 +227,15 @@ export class MatchHistoryService {
return {
matches: page,
...(params.filters.includePositionCounts
? {
positionCounts: await this.getPositionCounts(
context,
queueIds,
params.filters.championId,
),
}
: {}),
nextCursor:
views.length > limit
? (page[page.length - 1]?.gameCreation ?? null)
@@ -394,7 +407,14 @@ export class MatchHistoryService {
limit: number;
cursor?: number;
championId?: number;
lane?: string;
}): Promise<RiotMatchDocument[]> {
if (
params.lane &&
!['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'].includes(params.lane)
) {
throw new BadRequestException('Invalid lane.');
}
if (params.queueIds.length === 0) return [];
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const gameCreation: Record<string, number> = {};
@@ -408,12 +428,25 @@ export class MatchHistoryService {
queueId: { $in: params.queueIds },
};
if (Object.keys(gameCreation).length > 0) query.gameCreation = gameCreation;
if (params.championId !== undefined) {
if (params.championId !== undefined || params.lane) {
// Both conditions must match the same participant, before pagination.
query['raw.info.participants'] = {
$elemMatch: {
puuid: params.context.account.puuid,
championId: params.championId,
...(params.championId !== undefined
? { championId: params.championId }
: {}),
...(params.lane
? {
$or: [
{ teamPosition: params.lane },
{
teamPosition: { $in: ['', null] },
individualPosition: params.lane,
},
],
}
: {}),
},
};
}
@@ -425,6 +458,74 @@ export class MatchHistoryService {
.exec();
}
/** Counts independent position windows, without transferring full match payloads. */
private async getPositionCounts(
context: HistoryContext,
queueIds: number[],
championId?: number,
): Promise<Record<string, number>> {
const model = await this.connectionService.getModel('riotMatch');
const rows = await model
.aggregate<{ _id: string; count: number }>([
{
$match: {
participantPuuids: context.account.puuid,
queueId: { $in: queueIds },
...(context.seasonStartedAt
? { gameCreation: { $gte: context.seasonStartedAt.getTime() } }
: {}),
},
},
{
$project: {
participant: {
$first: {
$filter: {
input: '$raw.info.participants',
as: 'p',
cond: { $eq: ['$$p.puuid', context.account.puuid] },
},
},
},
},
},
{
$match: {
participant: { $ne: null },
...(championId !== undefined
? { 'participant.championId': championId }
: {}),
},
},
{
$group: {
_id: {
$cond: [
{ $in: [{ $ifNull: ['$participant.teamPosition', ''] }, ['']] },
'$participant.individualPosition',
'$participant.teamPosition',
],
},
count: { $sum: 1 },
},
},
])
.exec();
const counts: Record<string, number> = {
ALL: Math.min(
20,
rows.reduce((sum, row) => sum + row.count, 0),
),
};
for (const lane of ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY']) {
counts[lane] = Math.min(
20,
rows.find((row) => row._id === lane)?.count ?? 0,
);
}
return counts;
}
private async aggregateChampionStats(params: {
context: HistoryContext;
queueIds: number[];
@@ -676,6 +777,7 @@ export class MatchHistoryService {
wardsPlaced: participant.wardsPlaced,
wardsKilled: participant.wardsKilled,
damageDealtToChampions: participant.totalDamageDealtToChampions,
damageShare: damageShare * 100,
damageTaken: participant.totalDamageTaken,
goldEarned: participant.goldEarned,
items: [
@@ -103,6 +103,8 @@ export interface RecentSummaryResponse {
}
export interface RecentMatchesResponse {
/** Available games in each independent recent-20 window. */
positionCounts?: Record<string, number>;
matches: RecentMatchView[];
nextCursor: number | null;
lastFetchedAt: string | null;
@@ -136,8 +138,11 @@ export interface RecentMatchTeamParticipantView {
}
export interface RecentMatchView {
/** Player champion damage / team champion damage, as a percentage. */
damageShare?: number;
matchId: string;
internalMatchId?: string;
internalMatchTitle?: string;
gameNumber?: number;
queueId: number;
queueLabel: string;