From 5ad0f8a1c2d61f6b9b395d92c3bff37611010bdb Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sun, 7 Jun 2026 07:20:35 -0700 Subject: [PATCH] feat: add auction chat --- .../src/modules/auction/auction.gateway.ts | 77 ++++++++ .../modules/auction/auction.service.spec.ts | 70 +++++++ .../src/modules/auction/auction.service.ts | 59 ++++++ .../api/src/modules/global/database/schema.ts | 25 +++ apps/web/src/api/types.ts | 9 + apps/web/src/api/useAuctionSocket.ts | 54 +++++- apps/web/src/pages/AuctionPage.tsx | 175 ++++++++++++++++-- 7 files changed, 449 insertions(+), 20 deletions(-) diff --git a/apps/api/src/modules/auction/auction.gateway.ts b/apps/api/src/modules/auction/auction.gateway.ts index b868285b..aad113e4 100644 --- a/apps/api/src/modules/auction/auction.gateway.ts +++ b/apps/api/src/modules/auction/auction.gateway.ts @@ -16,6 +16,7 @@ import { IdentityService } from '../auth/identity.service'; import { JwtService } from '../auth/jwt.service'; import { ConnectionService } from '../global/database/connection.service'; import type { + AuctionChatMessage, AuctionDocument, IdentityDocument, Position, @@ -37,6 +38,11 @@ interface SoldPayload { assignedPosition?: Position; } +interface ChatMessagePayload { + message?: string; + displayName?: string; +} + @WebSocketGateway({ namespace: '/auction', cors: { @@ -100,6 +106,7 @@ export class AuctionGateway const auction = await this.auctionService.getByMatchId( new mongoose.Types.ObjectId(payload.matchId), ); + this.emitChatHistory(socket, auction); this.broadcastState(payload.matchId, auction); } catch (error) { this.emitKnownError(socket, error); @@ -182,6 +189,34 @@ export class AuctionGateway } } + @SubscribeMessage('chat-message') + public async handleChatMessage( + @ConnectedSocket() socket: Socket, + @MessageBody() payload: ChatMessagePayload, + ) { + const matchId = this.requireJoinedMatchId(socket); + if (!matchId) return; + + if (typeof payload?.message !== 'string') { + this.emitError(socket, 'Chat message is required.'); + return; + } + + try { + const { message } = await this.auctionService.appendChatMessage({ + matchId: new mongoose.Types.ObjectId(matchId), + userId: this.resolveSocketUserId(socket), + displayName: this.resolveChatDisplayName(socket, payload.displayName), + message: payload.message, + }); + this.server + .to(matchId) + .emit('chat-message', this.serializeChatMessage(message)); + } catch (error) { + this.emitKnownError(socket, error); + } + } + private requireJoinedMatchId(socket: Socket): string | null { const matchId = this.getSocketMatchId(socket); if (!matchId) { @@ -219,6 +254,36 @@ export class AuctionGateway return Array.isArray(header) ? header[0] : header; } + private resolveSocketUserId( + socket: Socket, + ): mongoose.Types.ObjectId | undefined { + return (socket.data.user as UserDocument | undefined)?._id; + } + + private resolveChatDisplayName( + socket: Socket, + fallbackDisplayName?: string, + ): string { + const user = socket.data.user as UserDocument | undefined; + const primaryRiotAccount = + user?.riotAccounts.find((entry) => entry.isPrimary) ?? + user?.riotAccounts[0]; + if (primaryRiotAccount?.gameName) { + return primaryRiotAccount.tagLine + ? `${primaryRiotAccount.gameName}#${primaryRiotAccount.tagLine}` + : primaryRiotAccount.gameName; + } + + if (user?.kakaoTalkNickname) return user.kakaoTalkNickname; + if (user?.discordNickname) return user.discordNickname; + + const identity = socket.data.identity as IdentityDocument | undefined; + if (identity?.displayName) return identity.displayName; + if (identity?.email) return identity.email; + + return fallbackDisplayName ?? '관전자'; + } + private async authenticateSocket(socket: Socket): Promise { const fallback = await this.authService.resolveDevUserById( this.readHandshakeUserId(socket), @@ -299,6 +364,14 @@ export class AuctionGateway this.syncRoomTimer(matchId, auction); } + private emitChatHistory(socket: Socket, auction: AuctionDocument) { + socket.emit('chat-history', { + messages: (auction.chatMessages ?? []).map((message) => + this.serializeChatMessage(message), + ), + }); + } + private syncRoomTimer(matchId: string, auction: AuctionDocument) { this.clearRoomTimer(matchId); if (!auction.currentDeadline) return; @@ -382,4 +455,8 @@ export class AuctionGateway private serializeAuction(auction: AuctionDocument) { return JSON.parse(JSON.stringify(auction)); } + + private serializeChatMessage(message: AuctionChatMessage) { + return JSON.parse(JSON.stringify(message)); + } } diff --git a/apps/api/src/modules/auction/auction.service.spec.ts b/apps/api/src/modules/auction/auction.service.spec.ts index 7cdeecf0..e5c41945 100644 --- a/apps/api/src/modules/auction/auction.service.spec.ts +++ b/apps/api/src/modules/auction/auction.service.spec.ts @@ -159,6 +159,76 @@ describe('AuctionService', () => { expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled(); }); + it('appends a chat message and keeps only the latest 200 messages', async () => { + const matchId = new mongoose.Types.ObjectId(); + const userId = new mongoose.Types.ObjectId(); + const oldMessages = Array.from({ length: 200 }, (_, index) => ({ + id: `old-${index}`, + displayName: 'Old', + message: `old message ${index}`, + sentAt: new Date(index), + })); + const auction = { + matchId, + chatMessages: oldMessages, + save: jest.fn().mockResolvedValue(undefined), + }; + const { service } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + }); + + const appended = await service.appendChatMessage({ + matchId, + userId, + displayName: ' Captain One ', + message: ' 좋은 픽입니다 ', + }); + + expect(appended.message).toMatchObject({ + userId, + displayName: 'Captain One', + message: '좋은 픽입니다', + }); + expect(appended.message.id).toHaveLength(36); + expect(appended.message.sentAt).toBeInstanceOf(Date); + 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); + }); + + it('rejects blank and overly long chat messages', async () => { + const matchId = new mongoose.Types.ObjectId(); + const auction = { + matchId, + chatMessages: [], + save: jest.fn().mockResolvedValue(undefined), + }; + const { service } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + }); + + await expect( + service.appendChatMessage({ + matchId, + displayName: 'Spectator', + message: ' ', + }), + ).rejects.toThrow('Chat message is required.'); + await expect( + service.appendChatMessage({ + matchId, + displayName: 'Spectator', + message: 'a'.repeat(301), + }), + ).rejects.toThrow('Chat message must be 300 characters or less.'); + expect(auction.save).not.toHaveBeenCalled(); + }); + it('randomizes the non-captain player order when starting an auction', async () => { const randomSpy = jest.spyOn(Math, 'random').mockReturnValue(0); const matchId = new mongoose.Types.ObjectId(); diff --git a/apps/api/src/modules/auction/auction.service.ts b/apps/api/src/modules/auction/auction.service.ts index e3bc218d..434e6e21 100644 --- a/apps/api/src/modules/auction/auction.service.ts +++ b/apps/api/src/modules/auction/auction.service.ts @@ -5,10 +5,12 @@ import { Logger, NotFoundException, } from '@nestjs/common'; +import { randomUUID } from 'crypto'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import { AuctionActionType, + AuctionChatMessage, AuctionDocument, AuctionPlayerSnapshot, AuctionTeam, @@ -26,6 +28,9 @@ import { TournamentResultService } from '../tournament-result/tournament-result. const AUCTION_MAX_TEAM_SIZE = 5; const AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY = 1; const AUCTION_ENRICHMENT_COOLDOWN_MS = 3 * 60 * 60 * 1000; +const AUCTION_CHAT_MAX_MESSAGES = 200; +const AUCTION_CHAT_MAX_MESSAGE_LENGTH = 300; +const AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH = 24; interface StartAuctionParams { matchId: mongoose.Types.ObjectId; @@ -54,6 +59,13 @@ interface MarkSoldParams { assignedPosition?: Position; } +interface AppendChatMessageParams { + matchId: mongoose.Types.ObjectId; + userId?: mongoose.Types.ObjectId; + displayName?: string; + message: string; +} + export interface AuctionHistoryView { sequence: number; action: AuctionActionType; @@ -221,6 +233,31 @@ export class AuctionService { return auction; } + public async appendChatMessage(params: AppendChatMessageParams): Promise<{ + auction: AuctionDocument; + message: AuctionChatMessage; + }> { + const auction = await this.getByMatchId(params.matchId); + const messageText = this.normalizeChatMessage(params.message); + const message: AuctionChatMessage = { + id: randomUUID(), + 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); + } + + await auction.save(); + return { auction, message }; + } + public async listHistory(params: { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; @@ -601,6 +638,28 @@ export class AuctionService { return JSON.parse(JSON.stringify(player)) as AuctionPlayerSnapshot; } + private normalizeChatMessage(message: string): string { + const normalized = message.trim(); + if (!normalized) { + throw new BadRequestException('Chat message is required.'); + } + if (Array.from(normalized).length > AUCTION_CHAT_MAX_MESSAGE_LENGTH) { + throw new BadRequestException( + `Chat message must be ${AUCTION_CHAT_MAX_MESSAGE_LENGTH} characters or less.`, + ); + } + return normalized; + } + + private normalizeChatDisplayName(displayName: string | undefined): string { + const normalized = displayName?.trim() || '관전자'; + const chars = Array.from(normalized); + if (chars.length <= AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH) { + return normalized; + } + return chars.slice(0, AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH).join(''); + } + private async recordSnapshot( auction: AuctionDocument, action: AuctionActionType, diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index e7f41494..ece1dbff 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -618,6 +618,14 @@ export interface AuctionBid { timestamp: Date; } +export interface AuctionChatMessage { + id: string; + userId?: mongoose.Types.ObjectId; + displayName: string; + message: string; + sentAt: Date; +} + export interface Auction extends MongooseTimestamps { matchId: mongoose.Types.ObjectId; phase: AuctionPhase; @@ -635,6 +643,7 @@ export interface Auction extends MongooseTimestamps { initialPoints: number; topTierThreshold: AuctionTopTierThreshold; manualTopTierUserIds: mongoose.Types.ObjectId[]; + chatMessages: AuctionChatMessage[]; startedAt?: Date; completedAt?: Date; } @@ -1566,6 +1575,17 @@ const AuctionBidSubSchema = new Schema( { _id: false }, ); +const AuctionChatMessageSubSchema = new Schema( + { + id: { type: String, required: true }, + userId: { type: Schema.Types.ObjectId, ref: 'user', required: false }, + displayName: { type: String, required: true }, + message: { type: String, required: true }, + sentAt: { type: Date, required: true, default: Date.now }, + }, + { _id: false }, +); + export const AuctionSchema = new Schema( { matchId: { @@ -1612,6 +1632,11 @@ export const AuctionSchema = new Schema( required: true, default: [], }, + chatMessages: { + type: [AuctionChatMessageSubSchema], + required: true, + default: [], + }, startedAt: { type: Date, required: false }, completedAt: { type: Date, required: false }, }, diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index e349c1c9..c872f1fe 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -272,6 +272,14 @@ export interface ApiAuctionBid { timestamp: string; } +export interface ApiAuctionChatMessage { + id: string; + userId?: string; + displayName: string; + message: string; + sentAt: string; +} + export interface ApiAuction { _id: string; matchId: string; @@ -290,6 +298,7 @@ export interface ApiAuction { initialPoints: number; topTierThreshold: AuctionTopTierThreshold; manualTopTierUserIds: string[]; + chatMessages?: ApiAuctionChatMessage[]; startedAt?: string; completedAt?: string; createdAt: string; diff --git a/apps/web/src/api/useAuctionSocket.ts b/apps/web/src/api/useAuctionSocket.ts index 49cef7ed..e6fa1af0 100644 --- a/apps/web/src/api/useAuctionSocket.ts +++ b/apps/web/src/api/useAuctionSocket.ts @@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'; import { io, type Socket } from 'socket.io-client'; import { API_BASE_URL, useAuthUserId } from '../config'; import { acquireAccessToken } from '../lib/auth/token-provider'; -import type { ApiAuction, Position } from './types'; +import type { ApiAuction, ApiAuctionChatMessage, Position } from './types'; type ConnectionStatus = | 'idle' @@ -17,18 +17,42 @@ interface BidPayload { bidderUserId?: string; } +interface ChatMessagePayload { + displayName?: string; + message: string; +} + +interface ChatHistoryPayload { + messages?: ApiAuctionChatMessage[]; +} + +const MAX_CHAT_MESSAGES = 200; + +function mergeChatMessages( + current: ApiAuctionChatMessage[], + incoming: ApiAuctionChatMessage[], +) { + const byId = new Map(current.map((message) => [message.id, message])); + for (const message of incoming) { + byId.set(message.id, message); + } + + return [...byId.values()] + .sort((left, right) => Date.parse(left.sentAt) - Date.parse(right.sentAt)) + .slice(-MAX_CHAT_MESSAGES); +} + export function useAuctionSocket(matchId: string | undefined) { const authUserId = useAuthUserId(); const socketRef = useRef(null); const [auction, setAuction] = useState(null); + const [chatMessages, setChatMessages] = useState([]); const [connectionStatus, setConnectionStatus] = useState('idle'); const [error, setError] = useState(null); useEffect(() => { if (!matchId) { - setAuction(null); - setConnectionStatus('idle'); return; } @@ -65,9 +89,20 @@ export function useAuctionSocket(matchId: string | undefined) { socket.on('state', (nextAuction: ApiAuction) => { setAuction(nextAuction); + if (nextAuction.chatMessages) { + setChatMessages(mergeChatMessages([], nextAuction.chatMessages)); + } setError(null); }); + socket.on('chat-history', (payload: ChatHistoryPayload) => { + setChatMessages(mergeChatMessages([], payload.messages ?? [])); + }); + + socket.on('chat-message', (message: ApiAuctionChatMessage) => { + setChatMessages((current) => mergeChatMessages(current, [message])); + }); + socket.on('error', (payload: { message?: string }) => { setConnectionStatus('error'); setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.'); @@ -101,9 +136,15 @@ export function useAuctionSocket(matchId: string | undefined) { socket.emit(eventName, payload); } + const visibleAuction = auction?.matchId === matchId ? auction : null; + const visibleConnectionStatus: ConnectionStatus = matchId + ? connectionStatus + : 'idle'; + return { - auction, - connectionStatus, + auction: visibleAuction, + chatMessages: visibleAuction ? chatMessages : [], + connectionStatus: visibleConnectionStatus, error, placeBid(payload: BidPayload) { emit('bid', payload); @@ -117,5 +158,8 @@ export function useAuctionSocket(matchId: string | undefined) { next() { emit('next', {}); }, + sendChatMessage(payload: ChatMessagePayload) { + emit('chat-message', payload); + }, }; } diff --git a/apps/web/src/pages/AuctionPage.tsx b/apps/web/src/pages/AuctionPage.tsx index 8a65828f..a42f8955 100644 --- a/apps/web/src/pages/AuctionPage.tsx +++ b/apps/web/src/pages/AuctionPage.tsx @@ -1,5 +1,13 @@ -import { useEffect, useMemo, useRef, useState } from 'react'; +import { + useEffect, + useMemo, + useRef, + useState, + type FormEvent, + type KeyboardEvent, +} from 'react'; import { useQueryClient } from '@tanstack/react-query'; +import { SendHorizontal } from 'lucide-react'; import { Link, useLocation, useParams } from 'react-router'; import { useAuction, @@ -34,8 +42,10 @@ import { } from '../lib/league'; import type { ApiAuction, + ApiAuctionChatMessage, ApiRiotLaneStats, ApiTierInfo, + ApiUser, Position, } from '../api/types'; @@ -73,6 +83,31 @@ function relativeTime(dateLike: string) { return `${Math.floor(hours / 24)}일 전`; } +function formatChatTime(dateLike: string) { + return new Intl.DateTimeFormat('ko-KR', { + hour: '2-digit', + minute: '2-digit', + }).format(new Date(dateLike)); +} + +function resolveChatSenderLabel( + currentUser: ApiUser | null, + captainRole: CaptainRole | null, +) { + const primaryRiotAccount = + currentUser?.riotAccounts.find((entry) => entry.isPrimary) ?? + currentUser?.riotAccounts[0]; + if (primaryRiotAccount?.gameName) { + return primaryRiotAccount.tagLine + ? `${primaryRiotAccount.gameName}#${primaryRiotAccount.tagLine}` + : primaryRiotAccount.gameName; + } + if (currentUser?.kakaoTalkNickname) return currentUser.kakaoTalkNickname; + if (currentUser?.discordNickname) return currentUser.discordNickname; + if (captainRole) return `${teamIndexLabel(captainRole.teamIndex)} 팀장`; + return '관전자'; +} + function normalizeRank(rank: string | undefined) { switch (rank) { case 'I': @@ -738,6 +773,7 @@ export default function AuctionPage() { : { teamIndex: captainTeamIndex, }; + const chatSenderLabel = resolveChatSenderLabel(currentUser, captainRole); useEffect(() => { if (auctionState?.currentPlayer) { @@ -1073,9 +1109,35 @@ export default function AuctionPage() { + +
+ + socket.sendChatMessage({ + displayName: chatSenderLabel, + message, + }) + } + className="h-[420px]" + /> +
); } @@ -1231,37 +1293,120 @@ function PoolListItem({ ); } -function ChatPanel() { +function ChatPanel({ + messages, + connectionStatus, + senderLabel, + onSend, + className = '', +}: { + messages: ApiAuctionChatMessage[]; + connectionStatus: ReturnType['connectionStatus']; + senderLabel: string; + onSend: (message: string) => void; + className?: string; +}) { + const [draft, setDraft] = useState(''); + const messagesEndRef = useRef(null); + const trimmedDraft = draft.trim(); + const isConnected = connectionStatus === 'connected'; + const canSend = isConnected && trimmedDraft.length > 0; + + useEffect(() => { + messagesEndRef.current?.scrollIntoView({ block: 'end' }); + }, [messages.length]); + + function handleSubmit(event: FormEvent) { + event.preventDefault(); + if (!canSend) return; + onSend(trimmedDraft); + setDraft(''); + } + + function handleKeyDown(event: KeyboardEvent) { + if (event.key !== 'Enter' || event.shiftKey) return; + event.preventDefault(); + if (!canSend) return; + onSend(trimmedDraft); + setDraft(''); + } + + const statusLabel = + connectionStatus === 'connected' + ? '실시간' + : connectionStatus === 'connecting' + ? '연결 중' + : '오프라인'; + return ( -
+
채팅
- - 곧 활성화됩니다 + + {statusLabel}
-
- 아직 메시지가 없습니다 +
+ {messages.length === 0 ? ( +
+ 아직 메시지가 없습니다 +
+ ) : ( +
    + {messages.map((message) => ( +
  1. +
    + + {message.displayName} + + +
    +

    + {message.message} +

    +
  2. + ))} +
+ )} +
-
+
+
+ {senderLabel} + {draft.length}/300 +