From be4de61bb7b33a53c5742e44ccfd29755336497b Mon Sep 17 00:00:00 2001 From: Park Dahyeon Date: Wed, 11 Nov 2026 20:06:22 +0900 Subject: [PATCH] feat: enhance auction interactions and player statistics UI --- .gitignore | 1 + apps/api/README.md | 13 + .../src/modules/auction/auction-bid-auth.ts | 9 + .../auction/auction-chat.gateway.spec.ts | 156 ++ .../auction/auction.controller.spec.ts | 101 + .../src/modules/auction/auction.controller.ts | 18 +- .../modules/auction/auction.gateway.spec.ts | 55 +- .../src/modules/auction/auction.gateway.ts | 84 +- .../modules/auction/auction.service.spec.ts | 169 +- .../src/modules/auction/auction.service.ts | 62 +- .../community-stats.controller.ts | 33 +- .../community-stats.service.spec.ts | 38 +- .../community-stats.service.ts | 141 +- .../community-stats/community-stats.types.ts | 20 + .../internal-stats-api.spec.ts | 378 +++ .../internal-stats-presentation.ts | 59 + .../community-stats/match-stats.repository.ts | 28 +- .../api/src/modules/global/database/schema.ts | 4 + .../match-history/match-history.controller.ts | 6 + .../match-history/match-history.query.spec.ts | 104 +- .../match-history/match-history.service.ts | 106 +- .../match-history/match-history.types.ts | 5 + apps/web/design-previews/internal-stats.html | 12 + .../player-information-v2.html | 12 + .../design-previews/player-information.html | 12 + apps/web/eslint.config.js | 10 + apps/web/src/App.tsx | 148 +- apps/web/src/api/auction-chat.ts | 31 + apps/web/src/api/auction-reactions.ts | 73 + apps/web/src/api/hooks.ts | 10 +- apps/web/src/api/mappers.ts | 10 +- apps/web/src/api/types.ts | 18 + apps/web/src/api/useAuctionSocket.ts | 73 +- apps/web/src/components/AuctionChatPanel.tsx | 497 ++++ .../src/components/AuctionReactionLayer.tsx | 59 + .../src/components/AuctionReactionPicker.tsx | 109 + apps/web/src/components/HomeHallOfFame.css | 138 +- apps/web/src/components/HomeHallOfFame.tsx | 60 +- apps/web/src/components/SummonerAvatar.tsx | 59 + apps/web/src/components/app-header.css | 186 ++ apps/web/src/components/auction-chat.css | 227 ++ .../AuctionPlayerProfile.tsx | 598 ++++ .../auction-player-profile/design-qa.md | 92 + .../auction-player-profile/history.ts | 84 + .../auction-player-profile/profile.css | 653 +++++ .../auction-player-profile/stats.ts | 113 + .../useProfileHistory.ts | 79 + .../useProfileManifest.ts | 52 + apps/web/src/components/auction-reactions.css | 132 + .../competition/CompetitionSeriesHistory.tsx | 42 +- .../DoubleEliminationMobileBracket.tsx | 18 +- .../competition/TeamMemberSummary.tsx | 34 + .../src/components/competition/TeamRoster.tsx | 32 + .../components/competition/TeamSeriesCard.tsx | 60 +- .../competition/TeamTournamentCodes.tsx | 190 +- .../competition/competition-series-history.ts | 3 +- .../components/internal-stats/StatsEvent.tsx | 288 ++ .../internal-stats/StatsLeaderboard.tsx | 200 ++ .../components/internal-stats/StatsShared.tsx | 181 ++ .../internal-stats/StatsSummary.tsx | 140 + .../components/internal-stats/design-qa.md | 50 + .../internal-stats/internal-stats.css | 2487 +++++++++++++++++ .../components/internal-stats/stats-model.ts | 54 + .../internal-stats/stats-navigation.ts | 137 + apps/web/src/config.ts | 42 + .../internal-stats/Preview.tsx | 240 ++ .../design-previews/internal-stats/data.ts | 123 + .../internal-stats/design-qa.md | 57 + .../design-previews/internal-stats/main.tsx | 13 + .../design-previews/internal-stats/model.ts | 51 + .../internal-stats/preview.css | 20 + .../player-information-v2/Preview.tsx | 148 + .../player-information-v2/data.ts | 90 + .../player-information-v2/design-qa.md | 184 ++ .../player-information-v2/main.tsx | 12 + .../player-information-v2/preview.css | 91 + .../player-information-v2/stats.ts | 58 + .../player-information/Preview.tsx | 207 ++ .../player-information/data.ts | 105 + .../player-information/design-qa.md | 128 + .../player-information/main.tsx | 16 + .../player-information/preview.css | 116 + apps/web/src/index.css | 8 +- apps/web/src/pages/AuctionPage.tsx | 1183 ++------ .../src/pages/CommunityInternalPlayerPage.tsx | 310 ++ .../src/pages/CommunityInternalStatsPage.tsx | 1362 ++++----- apps/web/src/pages/HomePage.tsx | 189 +- .../web/src/pages/InternalMatchDetailPage.tsx | 470 +--- apps/web/src/pages/Login.tsx | 35 +- apps/web/src/pages/MatchGameDetailPage.tsx | 508 ++-- apps/web/src/pages/MatchTeamProgressPage.tsx | 48 +- apps/web/src/pages/UserHistoryPage.tsx | 21 +- apps/web/src/pages/admin/LegacyImportPage.tsx | 8 +- apps/web/src/pages/admin/MatchAdminPage.tsx | 6 +- .../src/pages/admin/TournamentCodesPage.tsx | 6 +- apps/web/src/pages/auction.css | 26 + apps/web/src/pages/login.css | 70 + apps/web/test/auction-chat.test.ts | 47 + apps/web/test/auction-player-profile.test.ts | 168 ++ apps/web/test/auction-reactions.test.ts | 88 + .../test/competition-series-history.test.ts | 7 +- apps/web/test/internal-stats-preview.test.ts | 84 + .../test/internal-stats-production.test.ts | 95 + .../player-information-preview-v2.test.ts | 63 + design-qa.md | 269 ++ docs/specs/information-visible-ui.md | 83 + .../07-visual-design-review.md | 2 + .../README.md | 228 ++ .../evidence/00-user-reference.png | Bin 0 -> 360353 bytes .../evidence/01-auction.png | Bin 0 -> 63001 bytes .../evidence/02-history-navigation.png | Bin 0 -> 56539 bytes .../evidence/03-internal-match-detail.png | Bin 0 -> 105662 bytes .../evidence/04-auction-return.png | Bin 0 -> 62731 bytes packages/contracts/src/auction.ts | 24 + packages/contracts/src/index.ts | 1 + 115 files changed, 13292 insertions(+), 2871 deletions(-) create mode 100644 apps/api/src/modules/auction/auction-bid-auth.ts create mode 100644 apps/api/src/modules/auction/auction-chat.gateway.spec.ts create mode 100644 apps/api/src/modules/auction/auction.controller.spec.ts create mode 100644 apps/api/src/modules/community-stats/internal-stats-api.spec.ts create mode 100644 apps/api/src/modules/community-stats/internal-stats-presentation.ts create mode 100644 apps/web/design-previews/internal-stats.html create mode 100644 apps/web/design-previews/player-information-v2.html create mode 100644 apps/web/design-previews/player-information.html create mode 100644 apps/web/src/api/auction-chat.ts create mode 100644 apps/web/src/api/auction-reactions.ts create mode 100644 apps/web/src/components/AuctionChatPanel.tsx create mode 100644 apps/web/src/components/AuctionReactionLayer.tsx create mode 100644 apps/web/src/components/AuctionReactionPicker.tsx create mode 100644 apps/web/src/components/SummonerAvatar.tsx create mode 100644 apps/web/src/components/app-header.css create mode 100644 apps/web/src/components/auction-chat.css create mode 100644 apps/web/src/components/auction-player-profile/AuctionPlayerProfile.tsx create mode 100644 apps/web/src/components/auction-player-profile/design-qa.md create mode 100644 apps/web/src/components/auction-player-profile/history.ts create mode 100644 apps/web/src/components/auction-player-profile/profile.css create mode 100644 apps/web/src/components/auction-player-profile/stats.ts create mode 100644 apps/web/src/components/auction-player-profile/useProfileHistory.ts create mode 100644 apps/web/src/components/auction-player-profile/useProfileManifest.ts create mode 100644 apps/web/src/components/auction-reactions.css create mode 100644 apps/web/src/components/competition/TeamMemberSummary.tsx create mode 100644 apps/web/src/components/competition/TeamRoster.tsx create mode 100644 apps/web/src/components/internal-stats/StatsEvent.tsx create mode 100644 apps/web/src/components/internal-stats/StatsLeaderboard.tsx create mode 100644 apps/web/src/components/internal-stats/StatsShared.tsx create mode 100644 apps/web/src/components/internal-stats/StatsSummary.tsx create mode 100644 apps/web/src/components/internal-stats/design-qa.md create mode 100644 apps/web/src/components/internal-stats/internal-stats.css create mode 100644 apps/web/src/components/internal-stats/stats-model.ts create mode 100644 apps/web/src/components/internal-stats/stats-navigation.ts create mode 100644 apps/web/src/design-previews/internal-stats/Preview.tsx create mode 100644 apps/web/src/design-previews/internal-stats/data.ts create mode 100644 apps/web/src/design-previews/internal-stats/design-qa.md create mode 100644 apps/web/src/design-previews/internal-stats/main.tsx create mode 100644 apps/web/src/design-previews/internal-stats/model.ts create mode 100644 apps/web/src/design-previews/internal-stats/preview.css create mode 100644 apps/web/src/design-previews/player-information-v2/Preview.tsx create mode 100644 apps/web/src/design-previews/player-information-v2/data.ts create mode 100644 apps/web/src/design-previews/player-information-v2/design-qa.md create mode 100644 apps/web/src/design-previews/player-information-v2/main.tsx create mode 100644 apps/web/src/design-previews/player-information-v2/preview.css create mode 100644 apps/web/src/design-previews/player-information-v2/stats.ts create mode 100644 apps/web/src/design-previews/player-information/Preview.tsx create mode 100644 apps/web/src/design-previews/player-information/data.ts create mode 100644 apps/web/src/design-previews/player-information/design-qa.md create mode 100644 apps/web/src/design-previews/player-information/main.tsx create mode 100644 apps/web/src/design-previews/player-information/preview.css create mode 100644 apps/web/src/pages/CommunityInternalPlayerPage.tsx create mode 100644 apps/web/src/pages/login.css create mode 100644 apps/web/test/auction-chat.test.ts create mode 100644 apps/web/test/auction-player-profile.test.ts create mode 100644 apps/web/test/auction-reactions.test.ts create mode 100644 apps/web/test/internal-stats-preview.test.ts create mode 100644 apps/web/test/internal-stats-production.test.ts create mode 100644 apps/web/test/player-information-preview-v2.test.ts create mode 100644 docs/specs/information-visible-ui.md create mode 100644 docs/ux-audit-2026-11-11-auction-inspector/README.md create mode 100644 docs/ux-audit-2026-11-11-auction-inspector/evidence/00-user-reference.png create mode 100644 docs/ux-audit-2026-11-11-auction-inspector/evidence/01-auction.png create mode 100644 docs/ux-audit-2026-11-11-auction-inspector/evidence/02-history-navigation.png create mode 100644 docs/ux-audit-2026-11-11-auction-inspector/evidence/03-internal-match-detail.png create mode 100644 docs/ux-audit-2026-11-11-auction-inspector/evidence/04-auction-return.png create mode 100644 packages/contracts/src/auction.ts diff --git a/.gitignore b/.gitignore index a5c55162..bfe8196f 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,7 @@ website/LICENSE !design-qa.md !docs/specs/home-banner-production.md !docs/specs/match-status-and-result-presentation.md +!docs/specs/information-visible-ui.md !docs/ux-audit-2026-11-10/06-ui-improvement-review.md !docs/ux-audit-2026-11-10/07-visual-design-review.md /tmp/ diff --git a/apps/api/README.md b/apps/api/README.md index 099517c5..ed92ee3d 100644 --- a/apps/api/README.md +++ b/apps/api/README.md @@ -72,6 +72,19 @@ executable path. The runner starts an isolated replica set on a random loopback port, uses a temporary database directory, and removes it after the tests. It does not use the application's database connection settings. +## Temporary auction role selection + +Until captain accounts are issued, bids use the team selected in the auction UI. +By default, both WebSocket and HTTP bids accept guests and signed-in users without +checking whether the user is that team's captain. Team existence, bid amounts, +remaining points, roster limits, deadlines and round consistency are still checked. +Bid history continues to identify the selected team's captain, so it is not proof +of the account that submitted a bid in this temporary mode. + +After issuing accounts, set `AUCTION_REQUIRE_CAPTAIN_AUTH=true` in the API +environment (or `project.env`) and restart the API to require a signed-in captain +for the selected team on all bid paths. Unset or `false` keeps temporary mode. + ## Auction durability Accepted Redis bids now enter `auction:bidArchivePayloads` and diff --git a/apps/api/src/modules/auction/auction-bid-auth.ts b/apps/api/src/modules/auction/auction-bid-auth.ts new file mode 100644 index 00000000..a52a1b93 --- /dev/null +++ b/apps/api/src/modules/auction/auction-bid-auth.ts @@ -0,0 +1,9 @@ +/** + * 계정 지급 전에는 화면에서 선택한 팀으로 입찰하는 임시 운영 모드가 기본이다. + * 계정 지급 후 AUCTION_REQUIRE_CAPTAIN_AUTH=true로 로그인·팀장 검증을 복구한다. + */ +export function isAuctionCaptainAuthRequired(): boolean { + return ( + process.env.AUCTION_REQUIRE_CAPTAIN_AUTH?.trim().toLowerCase() === 'true' + ); +} diff --git a/apps/api/src/modules/auction/auction-chat.gateway.spec.ts b/apps/api/src/modules/auction/auction-chat.gateway.spec.ts new file mode 100644 index 00000000..dd8c7738 --- /dev/null +++ b/apps/api/src/modules/auction/auction-chat.gateway.spec.ts @@ -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(); + } + }); +}); diff --git a/apps/api/src/modules/auction/auction.controller.spec.ts b/apps/api/src/modules/auction/auction.controller.spec.ts new file mode 100644 index 00000000..40a8aacf --- /dev/null +++ b/apps/api/src/modules/auction/auction.controller.spec.ts @@ -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); + }); +}); diff --git a/apps/api/src/modules/auction/auction.controller.ts b/apps/api/src/modules/auction/auction.controller.ts index b15a6c35..36faedee 100644 --- a/apps/api/src/modules/auction/auction.controller.ts +++ b/apps/api/src/modules/auction/auction.controller.ts @@ -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, diff --git a/apps/api/src/modules/auction/auction.gateway.spec.ts b/apps/api/src/modules/auction/auction.gateway.spec.ts index 673cea6c..d3aa0f67 100644 --- a/apps/api/src/modules/auction/auction.gateway.spec.ts +++ b/apps/api/src/modules/auction/auction.gateway.spec.ts @@ -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 = { diff --git a/apps/api/src/modules/auction/auction.gateway.ts b/apps/api/src/modules/auction/auction.gateway.ts index 7b5493ad..8215a9f5 100644 --- a/apps/api/src/modules/auction/auction.gateway.ts +++ b/apps/api/src/modules/auction/auction.gateway.ts @@ -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; 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 = { + '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) => 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) { diff --git a/apps/api/src/modules/auction/auction.service.spec.ts b/apps/api/src/modules/auction/auction.service.spec.ts index 80368dc2..33067038 100644 --- a/apps/api/src/modules/auction/auction.service.spec.ts +++ b/apps/api/src/modules/auction/auction.service.spec.ts @@ -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 () => { diff --git a/apps/api/src/modules/auction/auction.service.ts b/apps/api/src/modules/auction/auction.service.ts index 7e58b37a..ea00d57d 100644 --- a/apps/api/src/modules/auction/auction.service.ts +++ b/apps/api/src/modules/auction/auction.service.ts @@ -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('해당 팀의 팀장만 입찰할 수 있습니다.'); } } diff --git a/apps/api/src/modules/community-stats/community-stats.controller.ts b/apps/api/src/modules/community-stats/community-stats.controller.ts index c7936637..45d41dad 100644 --- a/apps/api/src/modules/community-stats/community-stats.controller.ts +++ b/apps/api/src/modules/community-stats/community-stats.controller.ts @@ -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'], }; } diff --git a/apps/api/src/modules/community-stats/community-stats.service.spec.ts b/apps/api/src/modules/community-stats/community-stats.service.spec.ts index d49eacb5..9a28b3df 100644 --- a/apps/api/src/modules/community-stats/community-stats.service.spec.ts +++ b/apps/api/src/modules/community-stats/community-stats.service.spec.ts @@ -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; + 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(); diff --git a/apps/api/src/modules/community-stats/community-stats.service.ts b/apps/api/src/modules/community-stats/community-stats.service.ts index 6c62fa1d..1ad35ed8 100644 --- a/apps/api/src/modules/community-stats/community-stats.service.ts +++ b/apps/api/src/modules/community-stats/community-stats.service.ts @@ -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> = []; const records: InternalRecord[] = []; + const participants = new Set(); + 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'] : []), ]), ); } diff --git a/apps/api/src/modules/community-stats/community-stats.types.ts b/apps/api/src/modules/community-stats/community-stats.types.ts index d86fafc2..8bac3179 100644 --- a/apps/api/src/modules/community-stats/community-stats.types.ts +++ b/apps/api/src/modules/community-stats/community-stats.types.ts @@ -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; season: HistorySeasonDto; + playerStats?: LeaderboardRow | null; championStats: LeaderboardChampionStats; summary: { windowSize: number; diff --git a/apps/api/src/modules/community-stats/internal-stats-api.spec.ts b/apps/api/src/modules/community-stats/internal-stats-api.spec.ts new file mode 100644 index 00000000..9295a5c6 --- /dev/null +++ b/apps/api/src/modules/community-stats/internal-stats-api.spec.ts @@ -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 { + 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(); + 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 }, + '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[0]; + type Competition = NonNullable[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'); + }); +}); diff --git a/apps/api/src/modules/community-stats/internal-stats-presentation.ts b/apps/api/src/modules/community-stats/internal-stats-presentation.ts new file mode 100644 index 00000000..23b68e67 --- /dev/null +++ b/apps/api/src/modules/community-stats/internal-stats-presentation.ts @@ -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, +): 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); +} diff --git a/apps/api/src/modules/community-stats/match-stats.repository.ts b/apps/api/src/modules/community-stats/match-stats.repository.ts index e42c517a..46ec5f8f 100644 --- a/apps/api/src/modules/community-stats/match-stats.repository.ts +++ b/apps/api/src/modules/community-stats/match-stats.repository.ts @@ -6,7 +6,11 @@ import type { MatchStats, MatchStatsDocument } from '../global/database/schema'; export type MatchStatsUserRecordFragment = Pick< MatchStats, 'matchId' | 'records' | 'builderVersion' ->; +> & { + gameDetails?: Array< + Pick + >; +}; 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() .exec(); } diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index 83e785ba..59c516a0 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -857,6 +857,8 @@ export const AuctionBidRecordSchema = new Schema( 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( const AuctionChatMessageSubSchema = new Schema( { 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 }, diff --git a/apps/api/src/modules/match-history/match-history.controller.ts b/apps/api/src/modules/match-history/match-history.controller.ts index 866a5957..b93fd517 100644 --- a/apps/api/src/modules/match-history/match-history.controller.ts +++ b/apps/api/src/modules/match-history/match-history.controller.ts @@ -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', }, }); } diff --git a/apps/api/src/modules/match-history/match-history.query.spec.ts b/apps/api/src/modules/match-history/match-history.query.spec.ts index f5e35b0b..9c3559b6 100644 --- a/apps/api/src/modules/match-history/match-history.query.spec.ts +++ b/apps/api/src/modules/match-history/match-history.query.spec.ts @@ -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> }, + [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, }, ], diff --git a/apps/api/src/modules/match-history/match-history.service.ts b/apps/api/src/modules/match-history/match-history.service.ts index a4eb0cd4..15d7e1d6 100644 --- a/apps/api/src/modules/match-history/match-history.service.ts +++ b/apps/api/src/modules/match-history/match-history.service.ts @@ -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 { + 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 = {}; @@ -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> { + 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 = { + 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: [ diff --git a/apps/api/src/modules/match-history/match-history.types.ts b/apps/api/src/modules/match-history/match-history.types.ts index a0e4aae1..d954e106 100644 --- a/apps/api/src/modules/match-history/match-history.types.ts +++ b/apps/api/src/modules/match-history/match-history.types.ts @@ -103,6 +103,8 @@ export interface RecentSummaryResponse { } export interface RecentMatchesResponse { + /** Available games in each independent recent-20 window. */ + positionCounts?: Record; 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; diff --git a/apps/web/design-previews/internal-stats.html b/apps/web/design-previews/internal-stats.html new file mode 100644 index 00000000..e4375053 --- /dev/null +++ b/apps/web/design-previews/internal-stats.html @@ -0,0 +1,12 @@ + + + + + + 내전 전적 개선 시안 · LOLYMPUS + + +
+ + + diff --git a/apps/web/design-previews/player-information-v2.html b/apps/web/design-previews/player-information-v2.html new file mode 100644 index 00000000..d625ec30 --- /dev/null +++ b/apps/web/design-previews/player-information-v2.html @@ -0,0 +1,12 @@ + + + + + + 선수 정보 시안 02 · LOLYMPUS + + +
+ + + diff --git a/apps/web/design-previews/player-information.html b/apps/web/design-previews/player-information.html new file mode 100644 index 00000000..8d863c5b --- /dev/null +++ b/apps/web/design-previews/player-information.html @@ -0,0 +1,12 @@ + + + + + + 선수 정보 개선 시안 · LOLYMPUS + + +
+ + + diff --git a/apps/web/eslint.config.js b/apps/web/eslint.config.js index 5e6b472f..cedf0b14 100644 --- a/apps/web/eslint.config.js +++ b/apps/web/eslint.config.js @@ -19,5 +19,15 @@ export default defineConfig([ ecmaVersion: 2020, globals: globals.browser, }, + rules: { + // Product policy: information stays visible; use sections, links and pagination. + 'no-restricted-syntax': [ + 'error', + { + selector: 'JSXOpeningElement[name.name="details"], JSXOpeningElement[name.name="summary"]', + message: 'LOLYMPUS does not use disclosure/accordion UI. Keep content visible in a section, or use a dedicated route for a separate task.', + }, + ], + }, }, ]) diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index f95bf881..4a2d4943 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -23,16 +23,18 @@ import MatchTeamProgressPage from "./pages/MatchTeamProgressPage"; import AuctionPage from "./pages/AuctionPage"; import UserHistoryPage from "./pages/UserHistoryPage"; import CommunityInternalStatsPage from "./pages/CommunityInternalStatsPage"; +import CommunityInternalPlayerPage from "./pages/CommunityInternalPlayerPage"; import InternalMatchDetailPage from "./pages/InternalMatchDetailPage"; import LegacyImportPage from "./pages/admin/LegacyImportPage"; import LegacyMatchesPage from "./pages/admin/LegacyMatchesPage"; import MatchAdminPage from "./pages/admin/MatchAdminPage"; import TournamentCodesPage from "./pages/admin/TournamentCodesPage"; import { PlainPage, Tooltip, pageWidthClass } from "./ui"; +import "./components/app-header.css"; const NAV_ICON_BUTTON_CLASS = - "grid size-10 shrink-0 place-items-center rounded-field text-content-muted transition-colors hover:bg-sunken-strong hover:text-content md:size-11"; + "lts-header-icon-button"; function MsalHeaderActions() { const { accounts, instance } = useMsal(); @@ -41,7 +43,7 @@ function MsalHeaderActions() { if (!account) { return ( 로그인 @@ -63,7 +65,7 @@ function MsalHeaderActions() { aria-label={`${name} 로그아웃`} onClick={() => void instance.logoutRedirect()} > -