From e63fba0286b33583c91d1a67325fbb5682669b14 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sun, 7 Jun 2026 05:30:53 -0700 Subject: [PATCH 01/57] feat: include dakao send result subjects --- apps/api/src/modules/dakao/dakao.publisher.spec.ts | 4 ++++ apps/api/src/modules/dakao/dakao.publisher.ts | 13 ++++++++++++- apps/api/src/modules/dakao/dakao.types.ts | 6 ++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/apps/api/src/modules/dakao/dakao.publisher.spec.ts b/apps/api/src/modules/dakao/dakao.publisher.spec.ts index 84a382b7..c61575f9 100644 --- a/apps/api/src/modules/dakao/dakao.publisher.spec.ts +++ b/apps/api/src/modules/dakao/dakao.publisher.spec.ts @@ -97,6 +97,10 @@ describe('DakaoPublisher', () => { eventSource: 'lolympus', type: 'chat.send-message', correlationId: 'chat-log-1', + resultSubjects: { + succeeded: 'staging.lolympus.dakao.chat.send-message.succeeded.v1', + failed: 'staging.lolympus.dakao.chat.send-message.failed.v1', + }, }); expect(getPublishedEnvelope(outboxService)).not.toHaveProperty( 'replySubject', diff --git a/apps/api/src/modules/dakao/dakao.publisher.ts b/apps/api/src/modules/dakao/dakao.publisher.ts index 0d788af4..44ea636a 100644 --- a/apps/api/src/modules/dakao/dakao.publisher.ts +++ b/apps/api/src/modules/dakao/dakao.publisher.ts @@ -3,6 +3,7 @@ import { randomUUID } from 'crypto'; import { SecretService } from '../global/secret/secret.service'; import { DakaoCommandEnvelope, + DakaoResultSubjects, DakaoSegment, DakaoSendMessagePayload, } from './dakao.types'; @@ -16,7 +17,12 @@ const EVENT_SOURCE_DEFAULT = 'lolympus'; @Injectable() export class DakaoPublisher implements OnModuleInit { private readonly logger = new Logger(DakaoPublisher.name); - private sendMessageSubject = resolveDakaoNatsNames().subjects.chatSendMessage; + private readonly names = resolveDakaoNatsNames(); + private sendMessageSubject = this.names.subjects.chatSendMessage; + private resultSubjects: DakaoResultSubjects = { + succeeded: this.names.subjects.chatSendMessageSucceeded, + failed: this.names.subjects.chatSendMessageFailed, + }; private eventSource = EVENT_SOURCE_DEFAULT; constructor( @@ -35,6 +41,10 @@ export class DakaoPublisher implements OnModuleInit { this.sendMessageSubject = sendOverride || resolveDakaoNatsNames().subjects.chatSendMessage; + this.resultSubjects = { + succeeded: this.names.subjects.chatSendMessageSucceeded, + failed: this.names.subjects.chatSendMessageFailed, + }; this.eventSource = sourceOverride || EVENT_SOURCE_DEFAULT; this.logger.log( @@ -63,6 +73,7 @@ export class DakaoPublisher implements OnModuleInit { type: 'chat.send-message', eventSource: this.eventSource, correlationId: params.correlationId, + resultSubjects: this.resultSubjects, payload, }; await this.outboxService.enqueueAndPublish({ diff --git a/apps/api/src/modules/dakao/dakao.types.ts b/apps/api/src/modules/dakao/dakao.types.ts index 251d5c5f..ee634807 100644 --- a/apps/api/src/modules/dakao/dakao.types.ts +++ b/apps/api/src/modules/dakao/dakao.types.ts @@ -75,12 +75,18 @@ export interface DakaoSendMessagePayload { silence?: boolean; } +export interface DakaoResultSubjects { + succeeded: string; + failed: string; +} + export interface DakaoCommandEnvelope { schema: 'dakao.command.v1'; eventId: string; type: string; eventSource: string; correlationId?: string; + resultSubjects?: DakaoResultSubjects; payload: TPayload; } -- 2.54.0 From 7b636ee7932a18d693cd0c6aa9c9a06ba34b7de6 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sun, 7 Jun 2026 05:57:44 -0700 Subject: [PATCH 02/57] fix: preserve dakao result subjects on outbox retry --- .../dakao/dakao-outbox.service.spec.ts | 116 ++++++++++++++++++ .../src/modules/dakao/dakao-outbox.service.ts | 22 +++- .../api/src/modules/global/database/schema.ts | 8 ++ 3 files changed, 145 insertions(+), 1 deletion(-) create mode 100644 apps/api/src/modules/dakao/dakao-outbox.service.spec.ts diff --git a/apps/api/src/modules/dakao/dakao-outbox.service.spec.ts b/apps/api/src/modules/dakao/dakao-outbox.service.spec.ts new file mode 100644 index 00000000..97b6c264 --- /dev/null +++ b/apps/api/src/modules/dakao/dakao-outbox.service.spec.ts @@ -0,0 +1,116 @@ +import { ConnectionService } from '../global/database/connection.service'; +import { NatsService } from '../global/nats/nats.service'; +import { DakaoOutboxService } from './dakao-outbox.service'; +import { DakaoResultSubjects } from './dakao.types'; + +function execResult(value: T) { + return { exec: jest.fn().mockResolvedValue(value) }; +} + +function makeService(outboxModel: Record) { + const connectionService = { + getModel: jest.fn().mockResolvedValue(outboxModel), + } as unknown as ConnectionService; + const natsService = { + publishJetStream: jest.fn().mockResolvedValue(undefined), + } as unknown as NatsService; + + return { + service: new DakaoOutboxService(connectionService, natsService), + connectionService, + natsService, + }; +} + +describe('DakaoOutboxService', () => { + it('persists result subjects when enqueuing send-message commands', async () => { + const outboxModel = { + findOneAndUpdate: jest.fn().mockReturnValue(execResult({})), + updateOne: jest.fn().mockReturnValue(execResult({})), + }; + const { service, natsService } = makeService(outboxModel); + const resultSubjects: DakaoResultSubjects = { + succeeded: 'staging.lolympus.dakao.chat.send-message.succeeded.v1', + failed: 'staging.lolympus.dakao.chat.send-message.failed.v1', + }; + + await service.enqueueAndPublish({ + subject: 'staging.dakao.chat.send-message.v1', + eventId: 'lolympus:chat.send-message:chat-log-1', + envelope: { + schema: 'dakao.command.v1', + eventId: 'lolympus:chat.send-message:chat-log-1', + type: 'chat.send-message', + eventSource: 'lolympus', + correlationId: 'chat-log-1', + resultSubjects, + payload: { + chatroomId: '18474390111480678', + segments: [{ kind: 'text', text: 'done' }], + }, + }, + }); + + expect(outboxModel.findOneAndUpdate).toHaveBeenCalledWith( + { eventId: 'lolympus:chat.send-message:chat-log-1' }, + expect.objectContaining({ + $setOnInsert: expect.objectContaining({ resultSubjects }), + }), + expect.any(Object), + ); + expect(natsService.publishJetStream).toHaveBeenCalledWith( + 'staging.dakao.chat.send-message.v1', + expect.objectContaining({ resultSubjects }), + { messageId: 'lolympus:chat.send-message:chat-log-1' }, + ); + }); + + it('restores send-message result subjects when sweeping legacy stale rows', async () => { + const previousNodeEnv = process.env.NODE_ENV; + process.env.NODE_ENV = 'staging'; + + try { + const exec = jest.fn().mockResolvedValue([ + { + eventId: 'lolympus:chat.send-message:chat-log-1', + type: 'chat.send-message', + eventSource: 'lolympus', + subject: 'staging.dakao.chat.send-message.v1', + correlationId: 'chat-log-1', + payload: { + chatroomId: '18474390111480678', + segments: [{ kind: 'text', text: 'done' }], + }, + }, + ]); + const lean = jest.fn().mockReturnValue({ exec }); + const limit = jest.fn().mockReturnValue({ lean }); + const sort = jest.fn().mockReturnValue({ limit }); + const outboxModel = { + find: jest.fn().mockReturnValue({ sort }), + }; + const { service } = makeService(outboxModel); + const enqueue = jest + .spyOn(service, 'enqueueAndPublish') + .mockResolvedValue(undefined); + + await expect(service.sweepStale({ staleMs: 1, limit: 1 })).resolves.toBe( + 1, + ); + + expect(enqueue).toHaveBeenCalledWith( + expect.objectContaining({ + envelope: expect.objectContaining({ + resultSubjects: { + succeeded: + 'staging.lolympus.dakao.chat.send-message.succeeded.v1', + failed: 'staging.lolympus.dakao.chat.send-message.failed.v1', + }, + }), + }), + ); + } finally { + process.env.NODE_ENV = previousNodeEnv; + } + }); +}); diff --git a/apps/api/src/modules/dakao/dakao-outbox.service.ts b/apps/api/src/modules/dakao/dakao-outbox.service.ts index ca58d2cd..21fb7cda 100644 --- a/apps/api/src/modules/dakao/dakao-outbox.service.ts +++ b/apps/api/src/modules/dakao/dakao-outbox.service.ts @@ -1,13 +1,23 @@ import { Injectable, Logger } from '@nestjs/common'; import { ConnectionService } from '../global/database/connection.service'; import { NatsService } from '../global/nats/nats.service'; -import { DakaoCommandEnvelope, DakaoResultEnvelope } from './dakao.types'; +import { resolveDakaoNatsNames } from './dakao.nats-names'; +import { + DakaoCommandEnvelope, + DakaoResultEnvelope, + DakaoResultSubjects, +} from './dakao.types'; +const CHAT_SEND_MESSAGE_TYPE = 'chat.send-message'; const TERMINAL_STATES = ['sent', 'failed'] as const; @Injectable() export class DakaoOutboxService { private readonly logger = new Logger(DakaoOutboxService.name); + private readonly chatSendMessageResultSubjects = { + succeeded: resolveDakaoNatsNames().subjects.chatSendMessageSucceeded, + failed: resolveDakaoNatsNames().subjects.chatSendMessageFailed, + }; constructor( private readonly connectionService: ConnectionService, @@ -30,6 +40,7 @@ export class DakaoOutboxService { type: params.envelope.type, subject: params.subject, correlationId: params.envelope.correlationId, + resultSubjects: params.envelope.resultSubjects, payload: params.envelope.payload as Record, state: 'pending', publishAttempts: 0, @@ -161,6 +172,8 @@ export class DakaoOutboxService { type: row.type, eventSource: row.eventSource, correlationId: row.correlationId, + resultSubjects: + row.resultSubjects ?? this.resolveDefaultResultSubjects(row.type), payload: row.payload, }, }); @@ -168,4 +181,11 @@ export class DakaoOutboxService { return rows.length; } + + private resolveDefaultResultSubjects( + type: string, + ): DakaoResultSubjects | undefined { + if (type !== CHAT_SEND_MESSAGE_TYPE) return undefined; + return this.chatSendMessageResultSubjects; + } } diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index 9aef3702..e7f41494 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -350,6 +350,10 @@ export interface DakaoOutboxMessage extends MongooseTimestamps { type: string; subject: string; correlationId?: string; + resultSubjects?: { + succeeded: string; + failed: string; + }; payload: Record; state: DakaoOutboxMessageState; publishAttempts: number; @@ -960,6 +964,10 @@ export const DakaoOutboxMessageSchema = new Schema( type: { type: String, required: true }, subject: { type: String, required: true }, correlationId: { type: String }, + resultSubjects: { + succeeded: { type: String }, + failed: { type: String }, + }, payload: { type: Schema.Types.Mixed, required: true }, state: { type: String, -- 2.54.0 From a8963424290c3aecc3dfb787c5e1d2b6c2d0372c Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sun, 7 Jun 2026 06:03:30 -0700 Subject: [PATCH 03/57] chore(web): limit upcoming match cards --- apps/web/src/pages/HomePage.tsx | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/apps/web/src/pages/HomePage.tsx b/apps/web/src/pages/HomePage.tsx index e7d8874a..bb2c45a2 100644 --- a/apps/web/src/pages/HomePage.tsx +++ b/apps/web/src/pages/HomePage.tsx @@ -3,6 +3,9 @@ import { mapApiMatchToMatchDetail } from '../api/mappers'; import { useMatches, useMe } from '../api/hooks'; import { DEFAULT_COMMUNITY_ID } from '../config'; +const UPCOMING_GRID_MATCH_LIMIT = 3; +const UPCOMING_MATCH_LIST_LIMIT = UPCOMING_GRID_MATCH_LIMIT + 1; + function StatusBadge({ status }: { status: string }) { const styles: Record = { 모집중: 'bg-green-500/15 text-green-500 border-green-500/20', @@ -44,7 +47,10 @@ function getStatusLabel(status: string) { } export default function HomePage() { - const upcomingMatchesQuery = useMatches({ limit: 20 }, DEFAULT_COMMUNITY_ID); + const upcomingMatchesQuery = useMatches( + { limit: UPCOMING_MATCH_LIST_LIMIT }, + DEFAULT_COMMUNITY_ID, + ); const finishedMatchesQuery = useMatches( { status: 'finished', limit: 10 }, DEFAULT_COMMUNITY_ID, @@ -84,7 +90,10 @@ export default function HomePage() { const finishedMatches = finishedMatchesQuery.data?.map(mapApiMatchToMatchDetail) ?? []; const nextMatch = upcomingMatches[0]; - const upcomingCards = nextMatch ? upcomingMatches.slice(1) : upcomingMatches; + const upcomingCards = (nextMatch + ? upcomingMatches.slice(1) + : upcomingMatches + ).slice(0, UPCOMING_GRID_MATCH_LIMIT); const currentUser = meQuery.data?.memberships.find( (membership) => membership.community?._id === DEFAULT_COMMUNITY_ID, -- 2.54.0 From 2dae3c7caebe6da9dc8766ee6f7c75385401bc6f Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sun, 7 Jun 2026 06:27:51 -0700 Subject: [PATCH 04/57] chore(web): add start scripts for modes --- apps/web/package.json | 2 ++ package.json | 2 ++ 2 files changed, 4 insertions(+) diff --git a/apps/web/package.json b/apps/web/package.json index 09296fec..80e50309 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -5,6 +5,8 @@ "type": "module", "scripts": { "dev": "vite", + "start:dev": "vite --mode development", + "start:staging": "vite --mode staging", "build": "tsc -b && vite build", "build:staging": "tsc -b && vite build --mode staging", "build:prod": "tsc -b && vite build --mode production", diff --git a/package.json b/package.json index 4de702f5..66077104 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,8 @@ "start:api:staging": "pnpm --filter api start:staging", "start:api:prod": "pnpm --filter api start:prod", "start:api": "pnpm --filter api start:prod", + "start:web:dev": "pnpm --filter web start:dev", + "start:web:staging": "pnpm --filter web start:staging", "build:api": "pnpm --filter api build", "dev:web": "pnpm --filter web dev", "build:web:staging": "pnpm --filter web build:staging", -- 2.54.0 From 994a9fcad07d660e1579bf3ec468fecc191eea5f Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sun, 7 Jun 2026 06:28:11 -0700 Subject: [PATCH 05/57] feat(web): filter match participants --- apps/web/src/pages/MatchDetailPage.tsx | 190 ++++++++++++++++++++++++- 1 file changed, 183 insertions(+), 7 deletions(-) diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index cf330b08..9d76a0c2 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -24,6 +24,7 @@ import { DEFAULT_COMMUNITY_ID, useAuthUserId } from "../config"; import { apiFetch, ApiError } from "../lib/api"; import { profileIconUrl } from "../lib/ddragon"; import { + POSITION_ORDER, positionIcon, positionLabel, sideShortLabel, @@ -52,6 +53,38 @@ type CaptainSelection = { const DEFAULT_AUCTION_MAX_TIMER_SECONDS = 30; const DEFAULT_AUCTION_BID_EXTENSION_SECONDS = 5; const MAX_AUCTION_TIMER_SECONDS = 3600; +const ALL_PARTICIPANT_FILTER = "all"; + +type ParticipantPositionFilter = Position | typeof ALL_PARTICIPANT_FILTER; +type ParticipantTierFilter = string | typeof ALL_PARTICIPANT_FILTER; + +const PARTICIPANT_TIER_FILTERS = [ + "CHALLENGER", + "GRANDMASTER", + "MASTER", + "DIAMOND", + "EMERALD", + "PLATINUM", + "GOLD", + "SILVER", + "BRONZE", + "IRON", + "UNRANKED", +] as const; + +const PARTICIPANT_TIER_LABELS: Record = { + CHALLENGER: "챌린저", + GRANDMASTER: "그랜드마스터", + MASTER: "마스터", + DIAMOND: "다이아몬드", + EMERALD: "에메랄드", + PLATINUM: "플래티넘", + GOLD: "골드", + SILVER: "실버", + BRONZE: "브론즈", + IRON: "아이언", + UNRANKED: "언랭크", +}; function captainSlotKey(slot: CaptainSelectionSlot) { return String(slot.teamIndex); @@ -270,6 +303,19 @@ function statusBadge(status: MatchDetailView["status"]) { } } +function participantTierFilterValue(participant: ParticipantView) { + return participant.tier?.tier ?? "UNRANKED"; +} + +// PARTICIPANT_TIER_FILTERS는 높은 티어 → 낮은 티어 순서이므로 +// 인덱스가 작을수록 상위 티어. (없는 값은 최하위로 취급) +function tierRank(tier: string) { + const index = PARTICIPANT_TIER_FILTERS.indexOf( + tier as (typeof PARTICIPANT_TIER_FILTERS)[number], + ); + return index === -1 ? PARTICIPANT_TIER_FILTERS.length : index; +} + function ParticipantRow({ participant, index, @@ -353,6 +399,47 @@ function ParticipantTable({ onJoin: () => void; isJoining: boolean; }) { + const [positionFilter, setPositionFilter] = + useState(ALL_PARTICIPANT_FILTER); + const [tierFilter, setTierFilter] = useState( + ALL_PARTICIPANT_FILTER, + ); + const filteredParticipants = participants.filter((participant) => { + const matchesPosition = + positionFilter === ALL_PARTICIPANT_FILTER || + participant.mainPosition === positionFilter; + const matchesTier = + tierFilter === ALL_PARTICIPANT_FILTER || + tierRank(participantTierFilterValue(participant)) <= tierRank(tierFilter); + + return matchesPosition && matchesTier; + }); + const isFiltered = + positionFilter !== ALL_PARTICIPANT_FILTER || + tierFilter !== ALL_PARTICIPANT_FILTER; + const positionFilteredParticipants = participants.filter( + (participant) => + positionFilter === ALL_PARTICIPANT_FILTER || + participant.mainPosition === positionFilter, + ); + // "이상" 임계값으로 쓸 수 있는 티어 = 참가자 중 실제 존재하는 티어. + // 언랭크는 "이상" 기준으로 전체와 동일하므로 임계값 후보에서 제외한다. + const presentTiers = new Set( + positionFilteredParticipants.map(participantTierFilterValue), + ); + const availableTiers = PARTICIPANT_TIER_FILTERS.filter( + (tier) => tier !== "UNRANKED" && presentTiers.has(tier), + ); + const tierAtOrAboveCounts = new Map( + availableTiers.map((tier) => [ + tier, + positionFilteredParticipants.filter( + (participant) => + tierRank(participantTierFilterValue(participant)) <= tierRank(tier), + ).length, + ]), + ); + return (
@@ -368,6 +455,84 @@ function ParticipantTable({ {joined ? "참가 완료" : isJoining ? "신청 중..." : "참가 신청"}
+
+
+
+ + {POSITION_ORDER.map((position) => { + const active = positionFilter === position; + return ( + + ); + })} +
+ +
+ + {filteredParticipants.length}/{participants.length}명 + + {isFiltered && ( + + )} +
+
+
@@ -380,13 +545,24 @@ function ParticipantTable({ - {participants.map((participant, index) => ( - - ))} + {filteredParticipants.length > 0 ? ( + filteredParticipants.map((participant, index) => ( + + )) + ) : ( + + + + )}
+ 조건에 맞는 참가자가 없습니다. +
-- 2.54.0 From 6a192276e8f28f1df27e0ef0bbcd8658c985a4d1 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sun, 7 Jun 2026 06:51:35 -0700 Subject: [PATCH 06/57] feat(admin): manage match participants --- .../src/modules/match/dto/create-match.dto.ts | 8 + .../api/src/modules/match/match.controller.ts | 44 +++ apps/api/src/modules/match/match.service.ts | 95 ++++++ apps/web/src/pages/MatchDetailPage.tsx | 291 +++++++++++++++++- 4 files changed, 437 insertions(+), 1 deletion(-) diff --git a/apps/api/src/modules/match/dto/create-match.dto.ts b/apps/api/src/modules/match/dto/create-match.dto.ts index a2757c73..7fe6ee55 100644 --- a/apps/api/src/modules/match/dto/create-match.dto.ts +++ b/apps/api/src/modules/match/dto/create-match.dto.ts @@ -173,6 +173,14 @@ export class UpdateMatchDto { schedule?: MatchScheduleItemDto[]; } +export class UpdateParticipantDto { + @IsEnum(POSITIONS) + mainPosition!: Position; + + @IsEnum(POSITIONS) + subPosition!: Position; +} + export class JoinMatchDto { @IsArray() @ArrayMinSize(1) diff --git a/apps/api/src/modules/match/match.controller.ts b/apps/api/src/modules/match/match.controller.ts index c581dbdc..74b448a2 100644 --- a/apps/api/src/modules/match/match.controller.ts +++ b/apps/api/src/modules/match/match.controller.ts @@ -27,6 +27,7 @@ import { CreateMatchDto, JoinMatchDto, UpdateMatchDto, + UpdateParticipantDto, } from './dto/create-match.dto'; import { MatchService } from './match.service'; @@ -137,6 +138,49 @@ export class MatchController { }); } + // 관리자 전용 — 참가자 주/부 포지션 변경. + @Patch(':matchId/participants/:userId') + @Roles('admin', 'owner') + @UseGuards(RolesGuard) + public async updateParticipant( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, + @Body() body: UpdateParticipantDto, + ) { + this.assertSameCommunity(currentUser, communityId); + const match = await this.matchService.updateParticipantPositions({ + matchId, + communityId, + targetUserId: userId, + mainPosition: body.mainPosition, + subPosition: body.subPosition, + }); + return this.matchService.serialize(match); + } + + // 관리자 전용 — 참가자 강제 제외. + @Delete(':matchId/participants/:userId') + @Roles('admin', 'owner') + @UseGuards(RolesGuard) + @HttpCode(HttpStatus.NO_CONTENT) + public async removeParticipant( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, + ) { + this.assertSameCommunity(currentUser, communityId); + await this.matchService.removeParticipant({ + matchId, + communityId, + targetUserId: userId, + }); + } + private resolveJoinerUserId( currentUser: UserDocument | undefined, bodyUserId?: string, diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts index 1bf6b3b6..d1a1f184 100644 --- a/apps/api/src/modules/match/match.service.ts +++ b/apps/api/src/modules/match/match.service.ts @@ -13,6 +13,7 @@ import { MatchDocument, MatchSeriesResult, MatchStatus, + Position, PositionPreference, TierInfo, } from '../global/database/schema'; @@ -54,6 +55,20 @@ interface CancelMatchJoinParams { userId: mongoose.Types.ObjectId; } +interface RemoveParticipantParams { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + targetUserId: mongoose.Types.ObjectId; +} + +interface UpdateParticipantPositionsParams { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + targetUserId: mongoose.Types.ObjectId; + mainPosition: Position; + subPosition: Position; +} + @Injectable() export class MatchService { constructor( @@ -276,6 +291,86 @@ export class MatchService { return match; } + // 관리자 전용 — 특정 참가자를 강제로 제외한다. + public async removeParticipant( + params: RemoveParticipantParams, + ): Promise { + const match = await this.loadRecruitingMatch( + params.matchId, + params.communityId, + ); + const participantIndex = match.participants.findIndex((participant) => + participant.userId.equals(params.targetUserId), + ); + if (participantIndex === -1) { + throw new NotFoundException('Participant not found.'); + } + match.participants.splice(participantIndex, 1); + await match.save(); + return match; + } + + // 관리자 전용 — 참가자의 주/부 포지션(선호 우선순위 1·2)을 교체한다. + public async updateParticipantPositions( + params: UpdateParticipantPositionsParams, + ): Promise { + const match = await this.loadRecruitingMatch( + params.matchId, + params.communityId, + ); + const participant = match.participants.find((entry) => + entry.userId.equals(params.targetUserId), + ); + if (!participant) { + throw new NotFoundException('Participant not found.'); + } + participant.preferredPositions = this.reorderPreferredPositions( + params.mainPosition, + params.subPosition, + participant.preferredPositions, + ); + match.markModified('participants'); + await match.save(); + return match; + } + + private async loadRecruitingMatch( + matchId: mongoose.Types.ObjectId, + communityId: mongoose.Types.ObjectId, + ): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const match = await MatchModel.findById(matchId); + if (!match) throw new NotFoundException('Match not found.'); + if (!match.communityId.equals(communityId)) { + throw new BadRequestException('Different community.'); + } + if (match.status !== 'recruiting') { + throw new BadRequestException('Match is not recruiting.'); + } + return match; + } + + // 주/부 포지션을 priority 1·2로 올리고 기존 나머지 선호는 뒤로 보존한다. + private reorderPreferredPositions( + mainPosition: Position, + subPosition: Position, + current: PositionPreference[], + ): PositionPreference[] { + const ordered: Position[] = [mainPosition]; + if (subPosition !== mainPosition) ordered.push(subPosition); + for (const preference of [...current].sort( + (left, right) => left.priority - right.priority, + )) { + if (!ordered.includes(preference.position)) { + ordered.push(preference.position); + } + } + return ordered.map((position, index) => ({ + position, + priority: index + 1, + })); + } + private selectParticipantTier(tiers: TierInfo[]): TierInfo | undefined { const tier = tiers.find((entry) => entry.queueType === 'RANKED_SOLO_5x5') ?? tiers[0]; diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index 9d76a0c2..e5caf73f 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -33,7 +33,9 @@ import { } from "../lib/league"; import type { AuctionTopTierThreshold, + ApiMatch, ApiMatchParticipant, + ApiPositionPreference, ApiTierInfo, ManualTournamentResultCollectResponse, Position, @@ -90,6 +92,25 @@ function captainSlotKey(slot: CaptainSelectionSlot) { return String(slot.teamIndex); } +// 백엔드 reorderPreferredPositions와 동일 규칙. 낙관적 업데이트에서 +// 캐시된 preferredPositions를 즉시 갱신하는 데 사용한다. +function reorderPreferredPositions( + mainPosition: Position, + subPosition: Position, + current: ApiPositionPreference[], +): ApiPositionPreference[] { + const ordered: Position[] = [mainPosition]; + if (subPosition !== mainPosition) ordered.push(subPosition); + for (const preference of [...current].sort( + (left, right) => left.priority - right.priority, + )) { + if (!ordered.includes(preference.position)) { + ordered.push(preference.position); + } + } + return ordered.map((position, index) => ({ position, priority: index + 1 })); +} + function parseInitialPointsInput(value: string) { if (!value.trim()) return null; const points = Number(value); @@ -316,18 +337,81 @@ function tierRank(tier: string) { return index === -1 ? PARTICIPANT_TIER_FILTERS.length : index; } +type ParticipantRowAdmin = { + onRemove: (userId: string) => void; + onChangePositions: ( + userId: string, + mainPosition: Position, + subPosition: Position, + ) => void; + isRemoving: boolean; + isUpdating: boolean; +}; + +function PositionSelect({ + value, + sub, + disabled, + onChange, +}: { + value: Position; + sub?: boolean; + disabled?: boolean; + onChange: (next: Position) => void; +}) { + return ( + + ); +} + function ParticipantRow({ participant, index, assignedPos, + admin, }: { participant: ParticipantView; index: number; assignedPos?: Position; + admin?: ParticipantRowAdmin; }) { const { data: ddragon } = useDdragonManifest(); const location = useLocation(); const historyBackTo = `${location.pathname}${location.search}${location.hash}`; + const [confirmingRemove, setConfirmingRemove] = useState(false); + + // 주/부 포지션이 겹치면 두 값을 맞바꿔 항상 서로 다르게 유지한다. + const handleMainChange = (next: Position) => { + if (!admin) return; + const sub = + next === participant.subPosition + ? participant.mainPosition + : participant.subPosition; + admin.onChangePositions(participant.userId, next, sub); + }; + const handleSubChange = (next: Position) => { + if (!admin) return; + const main = + next === participant.mainPosition + ? participant.subPosition + : participant.mainPosition; + admin.onChangePositions(participant.userId, main, next); + }; return ( @@ -370,6 +454,68 @@ function ParticipantRow({ + ) : admin ? ( + <> + + + + + + + + {confirmingRemove ? ( + + + + + ) : ( + + )} + + ) : ( <> @@ -391,6 +537,11 @@ function ParticipantTable({ canJoin, onJoin, isJoining, + canManage, + onRemoveParticipant, + onUpdatePositions, + removingUserId, + updatingUserId, }: { participants: ParticipantView[]; maxParticipants: number; @@ -398,6 +549,15 @@ function ParticipantTable({ canJoin: boolean; onJoin: () => void; isJoining: boolean; + canManage: boolean; + onRemoveParticipant: (userId: string) => void; + onUpdatePositions: ( + userId: string, + mainPosition: Position, + subPosition: Position, + ) => void; + removingUserId: string | null; + updatingUserId: string | null; }) { const [positionFilter, setPositionFilter] = useState(ALL_PARTICIPANT_FILTER); @@ -542,6 +702,9 @@ function ParticipantTable({ 현재 티어 주 포지션 부 포지션 + {canManage && ( + 관리 + )} @@ -551,12 +714,22 @@ function ParticipantTable({ key={participant.id} participant={participant} index={index} + admin={ + canManage + ? { + onRemove: onRemoveParticipant, + onChangePositions: onUpdatePositions, + isRemoving: removingUserId === participant.userId, + isUpdating: updatingUserId === participant.userId, + } + : undefined + } /> )) ) : ( 조건에 맞는 참가자가 없습니다. @@ -1241,6 +1414,89 @@ export default function MatchDetailPage() { }, }); + const matchQueryKey = ["match", DEFAULT_COMMUNITY_ID, id ?? null]; + + const removeParticipantMutation = useMutation({ + mutationFn: (userId: string) => + apiFetch( + `/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants/${userId}`, + { method: "DELETE" }, + ), + onMutate: async (userId: string) => { + await queryClient.cancelQueries({ queryKey: matchQueryKey }); + const previous = queryClient.getQueryData(matchQueryKey); + if (previous) { + queryClient.setQueryData(matchQueryKey, { + ...previous, + participants: previous.participants.filter( + (participant) => participant.userId !== userId, + ), + }); + } + return { previous }; + }, + onError: (_error, _userId, context) => { + if (context?.previous) { + queryClient.setQueryData(matchQueryKey, context.previous); + } + }, + onSettled: () => { + void queryClient.invalidateQueries({ queryKey: matchQueryKey }); + void queryClient.invalidateQueries({ + queryKey: ["matches", DEFAULT_COMMUNITY_ID], + }); + }, + }); + + const updateParticipantMutation = useMutation({ + mutationFn: ({ + userId, + mainPosition, + subPosition, + }: { + userId: string; + mainPosition: Position; + subPosition: Position; + }) => + apiFetch( + `/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants/${userId}`, + { + method: "PATCH", + body: JSON.stringify({ mainPosition, subPosition }), + }, + ), + onMutate: async ({ userId, mainPosition, subPosition }) => { + await queryClient.cancelQueries({ queryKey: matchQueryKey }); + const previous = queryClient.getQueryData(matchQueryKey); + if (previous) { + queryClient.setQueryData(matchQueryKey, { + ...previous, + participants: previous.participants.map((participant) => + participant.userId === userId + ? { + ...participant, + preferredPositions: reorderPreferredPositions( + mainPosition, + subPosition, + participant.preferredPositions, + ), + } + : participant, + ), + }); + } + return { previous }; + }, + onError: (_error, _variables, context) => { + if (context?.previous) { + queryClient.setQueryData(matchQueryKey, context.previous); + } + }, + onSettled: () => { + void queryClient.invalidateQueries({ queryKey: matchQueryKey }); + }, + }); + const startAuctionMutation = useMutation({ mutationFn: () => apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/auction`, { @@ -1511,6 +1767,18 @@ export default function MatchDetailPage() {
)} + {removeParticipantMutation.error instanceof Error && ( +
+ {removeParticipantMutation.error.message} +
+ )} + + {updateParticipantMutation.error instanceof Error && ( +
+ {updateParticipantMutation.error.message} +
+ )} + {pollTournamentResultMutation.error instanceof Error && (
{pollTournamentResultMutation.error.message} @@ -1542,6 +1810,27 @@ export default function MatchDetailPage() { canJoin={canUseMemberActions} onJoin={() => joinMatchMutation.mutate()} isJoining={joinMatchMutation.isPending} + canManage={canManageAuction} + onRemoveParticipant={(userId) => + removeParticipantMutation.mutate(userId) + } + onUpdatePositions={(userId, mainPosition, subPosition) => + updateParticipantMutation.mutate({ + userId, + mainPosition, + subPosition, + }) + } + removingUserId={ + removeParticipantMutation.isPending + ? (removeParticipantMutation.variables ?? null) + : null + } + updatingUserId={ + updateParticipantMutation.isPending + ? (updateParticipantMutation.variables?.userId ?? null) + : null + } /> {isCheckingPermissions ? ( -- 2.54.0 From b711c63dcd7403f9887458905ca0b0761763d3f1 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sun, 7 Jun 2026 07:01:01 -0700 Subject: [PATCH 07/57] fix(api): keep zero-bid auction passes open --- .../modules/auction/auction.service.spec.ts | 104 +++++++++++------- .../src/modules/auction/auction.service.ts | 53 +-------- 2 files changed, 67 insertions(+), 90 deletions(-) diff --git a/apps/api/src/modules/auction/auction.service.spec.ts b/apps/api/src/modules/auction/auction.service.spec.ts index ff5cfc6f..7cdeecf0 100644 --- a/apps/api/src/modules/auction/auction.service.spec.ts +++ b/apps/api/src/modules/auction/auction.service.spec.ts @@ -348,7 +348,7 @@ describe('AuctionService', () => { expect(auction.save).not.toHaveBeenCalled(); }); - it('marks a zero-bid player as passed and queues them for round two', async () => { + it('marks a zero-bid player as passed and queues them for another round', async () => { const matchId = new mongoose.Types.ObjectId(); const playerId = new mongoose.Types.ObjectId(); const auction = { @@ -383,25 +383,63 @@ describe('AuctionService', () => { expect(auction.save).toHaveBeenCalledTimes(1); }); - it('force-assigns second-pass players to the open team with most points', async () => { + it('queues zero-bid passes after the first auction round', async () => { + const matchId = new mongoose.Types.ObjectId(); + const playerId = new mongoose.Types.ObjectId(); + const auction = { + _id: new mongoose.Types.ObjectId(), + matchId, + phase: 'bidding', + currentBid: 0, + currentIndex: 0, + auctionRound: 2, + order: [ + { + userId: playerId, + preferredPositions: [{ position: 'MID', priority: 1 }], + passCount: 1, + }, + ], + passedQueue: [], + save: jest.fn().mockResolvedValue(undefined), + toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }), + }; + const { service } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + }); + + await service.markPassed(matchId); + + expect(auction.phase).toBe('passed'); + expect(auction.order[0].passCount).toBe(2); + expect(auction.passedQueue).toHaveLength(1); + expect(auction.passedQueue[0]).toMatchObject({ + userId: playerId.toString(), + preferredPositions: [{ position: 'MID', priority: 1 }], + passCount: 2, + }); + }); + + it('requeues second-pass players instead of force-assigning them', async () => { const matchId = new mongoose.Types.ObjectId(); const captainOneId = new mongoose.Types.ObjectId(); const captainTwoId = new mongoose.Types.ObjectId(); const passedPlayerId = new mongoose.Types.ObjectId(); + const passedPlayer = { + userId: passedPlayerId, + preferredPositions: [{ position: 'SUP', priority: 1 }], + passCount: 2, + }; const auction = { _id: new mongoose.Types.ObjectId(), matchId, phase: 'passed', currentIndex: 0, auctionRound: 2, - order: [ - { - userId: passedPlayerId, - preferredPositions: [{ position: 'SUP', priority: 1 }], - passCount: 2, - }, - ], - passedQueue: [], + order: [passedPlayer], + passedQueue: [passedPlayer], teams: [ { teamIndex: 1, @@ -419,46 +457,28 @@ describe('AuctionService', () => { save: jest.fn().mockResolvedValue(undefined), toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }), }; - const match = { - participants: [ - { - userId: captainOneId, - preferredPositions: [{ position: 'TOP', priority: 1 }], - }, - { - userId: captainTwoId, - preferredPositions: [{ position: 'JGL', priority: 1 }], - }, - { - userId: passedPlayerId, - preferredPositions: [{ position: 'SUP', priority: 1 }], - }, - ], - status: 'team-built', - teams: [], - teamBuiltAt: undefined, - save: jest.fn().mockResolvedValue(undefined), - }; const { service } = createService({ auction: { findOne: jest.fn().mockResolvedValue(auction), }, - match: { - findById: jest.fn().mockResolvedValue(match), - }, }); await service.next(matchId); - expect(auction.phase).toBe('complete'); - expect(auction.teams[1].members).toEqual([ - { - userId: passedPlayerId, - assignedPosition: 'SUP', - cost: 1, - }, - ]); - expect(auction.teams[1].points).toBe(49); + expect(auction.phase).toBe('presenting'); + expect(auction.auctionRound).toBe(3); + expect(auction.currentIndex).toBe(1); + expect(auction.order).toHaveLength(2); + expect(auction.order[1]).toMatchObject({ + userId: passedPlayerId.toString(), + preferredPositions: [{ position: 'SUP', priority: 1 }], + passCount: 2, + }); + expect(auction.passedQueue).toEqual([]); + expect(auction.teams[0].members).toEqual([]); + expect(auction.teams[1].members).toEqual([]); + expect(auction.teams[0].points).toBe(10); + expect(auction.teams[1].points).toBe(50); }); it('syncs completed auction teams into the match document', async () => { diff --git a/apps/api/src/modules/auction/auction.service.ts b/apps/api/src/modules/auction/auction.service.ts index b93d66b8..e3bc218d 100644 --- a/apps/api/src/modules/auction/auction.service.ts +++ b/apps/api/src/modules/auction/auction.service.ts @@ -345,9 +345,8 @@ export class AuctionService { await this.recordSnapshot(auction, 'passed'); current.passCount = (current.passCount ?? 0) + 1; - if ((auction.auctionRound ?? 1) === 1) { - auction.passedQueue.push(this.cloneAuctionPlayerSnapshot(current)); - } + auction.passedQueue ??= []; + auction.passedQueue.push(this.cloneAuctionPlayerSnapshot(current)); auction.phase = 'passed'; auction.currentDeadline = undefined; await auction.save(); @@ -368,29 +367,22 @@ export class AuctionService { const nextIndex = auction.currentIndex + 1; const completesAuction = nextIndex >= auction.order.length && - !( - (auction.auctionRound ?? 1) === 1 && - (auction.passedQueue?.length ?? 0) > 0 - ); + (auction.passedQueue?.length ?? 0) === 0; await this.recordSnapshot(auction, completesAuction ? 'complete' : 'next'); if (nextIndex >= auction.order.length) { - if ( - (auction.auctionRound ?? 1) === 1 && - (auction.passedQueue?.length ?? 0) > 0 - ) { + if ((auction.passedQueue?.length ?? 0) > 0) { auction.order.push( ...auction.passedQueue.map((player) => this.cloneAuctionPlayerSnapshot(player), ), ); auction.passedQueue = []; - auction.auctionRound = 2; + auction.auctionRound = (auction.auctionRound ?? 1) + 1; auction.currentIndex = nextIndex; auction.phase = 'presenting'; auction.currentBid = 0; auction.currentBidderTeamIndex = undefined; } else { - this.forceAssignRemainingPasses(auction); auction.phase = 'complete'; auction.completedAt = new Date(); } @@ -603,41 +595,6 @@ export class AuctionService { return shuffled; } - private forceAssignRemainingPasses(auction: AuctionDocument): void { - const forcedPlayers = auction.order.filter( - (player) => - (player.passCount ?? 0) >= 2 && - !this.isAuctionPlayerAssigned(auction, player.userId), - ); - - for (const player of forcedPlayers) { - const targetTeam = [...auction.teams] - .filter( - (team) => this.countTeamMembersIncludingCaptain(team) < AUCTION_MAX_TEAM_SIZE, - ) - .sort((left, right) => right.points - left.points)[0]; - if (!targetTeam) return; - - const preferredPrimary = player.preferredPositions[0]?.position; - targetTeam.members.push({ - userId: player.userId, - assignedPosition: preferredPrimary ?? 'MID', - cost: 1, - }); - targetTeam.points = Math.max(0, targetTeam.points - 1); - } - } - - private isAuctionPlayerAssigned( - auction: AuctionDocument, - userId: mongoose.Types.ObjectId, - ): boolean { - const userIdText = userId.toString(); - return auction.teams.some((team) => - team.members.some((member) => member.userId.toString() === userIdText), - ); - } - private cloneAuctionPlayerSnapshot( player: AuctionPlayerSnapshot, ): AuctionPlayerSnapshot { -- 2.54.0 From ad84bf1f89535aea5f4fdf69ea81f3a9c7c907d2 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sun, 7 Jun 2026 07:07:48 -0700 Subject: [PATCH 08/57] feat(web): show participant position counts --- apps/web/src/pages/MatchDetailPage.tsx | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index e5caf73f..30d98575 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -471,9 +471,9 @@ function ParticipantRow({ onChange={handleSubChange} /> - + {confirmingRemove ? ( - + {POSITION_ORDER.map((position) => { const active = positionFilter === position; + const count = positionCounts.get(position) ?? 0; return ( ); })} @@ -703,7 +713,9 @@ function ParticipantTable({ 주 포지션 부 포지션 {canManage && ( - 관리 + + 관리 + )} -- 2.54.0 From c4f19d256d363ac0aaf4a4603fd596c2d681a5ce Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sun, 7 Jun 2026 07:16:31 -0700 Subject: [PATCH 09/57] fix: refresh riot tiers from history jobs --- .../riot-job-worker.service.spec.ts | 116 ++++++++++++++++++ .../riot-job-queue/riot-job-worker.service.ts | 27 +++- .../riot-account-enrichment.service.spec.ts | 67 ++++++++++ .../riot/riot-account-enrichment.service.ts | 25 ++++ 4 files changed, 233 insertions(+), 2 deletions(-) create mode 100644 apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts diff --git a/apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts new file mode 100644 index 00000000..a35c8462 --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts @@ -0,0 +1,116 @@ +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { GarnetService } from '../global/garnet/garnet.service'; +import { LegacyImportService } from '../legacy-import/legacy-import.service'; +import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; +import { RiotRecentMatchesService } from '../riot/riot-recent-matches.service'; +import { TournamentResultService } from '../tournament-result/tournament-result.service'; +import { RIOT_JOB_GROUP, RiotRefreshSubJob } from './riot-job-queue.types'; +import { RiotJobQueueService } from './riot-job-queue.service'; +import { RiotJobWorkerService } from './riot-job-worker.service'; +import { RiotRefreshGateway } from './riot-refresh.gateway'; + +function execResult(value: T) { + return { exec: jest.fn().mockResolvedValue(value) }; +} + +function makeWorker() { + const garnetService = { + acknowledgeStream: jest.fn().mockResolvedValue(undefined), + } as unknown as jest.Mocked; + const jobQueueService = { + markProcessing: jest.fn().mockResolvedValue(undefined), + markCompleted: jest.fn().mockResolvedValue({ + parentJobId: 'parent-1', + jobId: 'job-1', + queueGroup: 'summoners-rift', + puuid: 'puuid-1', + state: 'completed', + }), + markFailed: jest.fn(), + } as unknown as jest.Mocked; + const recentMatchesService = { + ensureFreshForQueue: jest.fn().mockResolvedValue(undefined), + } as unknown as jest.Mocked; + const userModel = { + updateOne: jest.fn().mockReturnValue(execResult({ modifiedCount: 1 })), + }; + const connectionService = { + getModel: jest.fn().mockResolvedValue(userModel), + } as unknown as jest.Mocked; + const refreshGateway = { + broadcastRefreshEvent: jest.fn(), + } as unknown as jest.Mocked; + const tournamentResultService = { + processPollJob: jest.fn(), + } as unknown as jest.Mocked; + const legacyImportService = { + processMemberJob: jest.fn(), + } as unknown as jest.Mocked; + const enrichmentService = { + refreshLeagueEntries: jest.fn().mockResolvedValue('updated'), + } as unknown as jest.Mocked; + + const worker = new RiotJobWorkerService( + garnetService, + jobQueueService, + recentMatchesService, + connectionService, + refreshGateway, + tournamentResultService, + legacyImportService, + enrichmentService, + ); + + return { + worker, + garnetService, + jobQueueService, + recentMatchesService, + connectionService, + refreshGateway, + enrichmentService, + }; +} + +describe('RiotJobWorkerService', () => { + it('refreshes league entries while processing user history refresh jobs', async () => { + const { worker, enrichmentService, recentMatchesService, garnetService } = + makeWorker(); + const userId = new mongoose.Types.ObjectId().toString(); + const job: RiotRefreshSubJob = { + jobId: 'job-1', + parentJobId: 'parent-1', + userId, + puuid: 'puuid-1', + region: 'asia', + platform: 'kr', + queueGroup: 'summoners-rift', + queueIds: [420, 430], + requestedAt: Date.now(), + priority: 'high', + }; + + await (worker as unknown as { + processEntry: ( + stream: string, + entry: { id: string; message: Record }, + ) => Promise; + }).processEntry('riot:queue:high', { + id: '1-0', + message: { job: JSON.stringify(job) }, + }); + + expect(recentMatchesService.ensureFreshForQueue).toHaveBeenCalledTimes(2); + expect(enrichmentService.refreshLeagueEntries).toHaveBeenCalledWith({ + userId: expect.any(mongoose.Types.ObjectId), + puuid: 'puuid-1', + platform: 'kr', + }); + expect(garnetService.acknowledgeStream).toHaveBeenCalledWith( + 'riot:queue:high', + RIOT_JOB_GROUP, + '1-0', + ); + }); +}); diff --git a/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts index a543d8cb..0c7b6e44 100644 --- a/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts +++ b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts @@ -9,7 +9,10 @@ import { ConnectionService } from '../global/database/connection.service'; import { GarnetService, StreamEntry } from '../global/garnet/garnet.service'; import { LegacyImportService } from '../legacy-import/legacy-import.service'; import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types'; +import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; import { RiotRecentMatchesService } from '../riot/riot-recent-matches.service'; +import { TournamentResultService } from '../tournament-result/tournament-result.service'; +import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types'; import { RIOT_JOB_GROUP, RIOT_JOB_HIGH_STREAM, @@ -19,8 +22,6 @@ import { } from './riot-job-queue.types'; import { RiotJobQueueService } from './riot-job-queue.service'; import { RiotRefreshGateway } from './riot-refresh.gateway'; -import { TournamentResultService } from '../tournament-result/tournament-result.service'; -import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types'; const LEADER_KEY = 'riot:worker:leader'; const LEADER_TTL_SECONDS = 60; @@ -39,6 +40,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy { private readonly refreshGateway: RiotRefreshGateway, private readonly tournamentResultService: TournamentResultService, private readonly legacyImportService: LegacyImportService, + private readonly enrichmentService: RiotAccountEnrichmentService, ) {} public async onModuleInit() { @@ -102,6 +104,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy { queueId, }); } + await this.refreshLeagueEntries(job); await this.markUserFetchedAt(job); const event = await this.jobQueueService.markCompleted(job); this.refreshGateway.broadcastRefreshEvent(event); @@ -135,6 +138,26 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy { } } + private async refreshLeagueEntries(job: RiotRefreshSubJob): Promise { + try { + const result = await this.enrichmentService.refreshLeagueEntries({ + userId: new mongoose.Types.ObjectId(job.userId), + puuid: job.puuid, + platform: job.platform, + }); + if (result !== 'failed') return; + this.logger.warn( + `Riot league refresh failed ${job.jobId}: puuid=${job.puuid}`, + ); + } catch (error) { + this.logger.warn( + `Riot league refresh failed ${job.jobId}: ${ + error instanceof Error ? error.message : error + }`, + ); + } + } + private async markUserFetchedAt(job: RiotRefreshSubJob): Promise { const UserModel = await this.connectionService.getModel('user'); const now = new Date(); diff --git a/apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts b/apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts index 7dc5035e..39df54b8 100644 --- a/apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts +++ b/apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts @@ -370,6 +370,73 @@ describe('RiotAccountEnrichmentService', () => { expect(user.save).not.toHaveBeenCalled(); }); + it('refreshes league entries without refreshing recent matches', async () => { + const recent = new Date(Date.now() - 60_000); + const account = makeAccount({ + revisionDate: Date.now() - 60_000, + tiers: [ + { + leagueId: 'L1', + queueType: 'RANKED_SOLO_5x5', + tier: 'GOLD', + rank: 'II', + puuid: 'puuid-1', + leaguePoints: 1, + wins: 1, + losses: 1, + fetchedAt: recent, + }, + ], + recentStatsFetchedAt: recent, + recentStatsSummary: createEmptyRiotRecentStatsSummary(), + }); + const user = makeUser(account); + const { service, leagueService, recentMatchesService } = makeService({ + user, + league: { + getEntriesByPuuid: jest.fn().mockResolvedValue([ + { + leagueId: 'L2', + queueType: 'RANKED_SOLO_5x5', + tier: 'PLATINUM', + rank: 'IV', + puuid: 'puuid-1', + leaguePoints: 20, + wins: 10, + losses: 8, + }, + ]), + } as Partial, + }); + + const result = await service.refreshLeagueEntries({ + userId: user._id, + puuid: 'puuid-1', + platform: 'kr', + }); + + expect(result).toBe('updated'); + expect(leagueService.getEntriesByPuuid).toHaveBeenCalledWith('puuid-1', { + platform: 'kr', + }); + expect(recentMatchesService.syncRecentMatches).not.toHaveBeenCalled(); + expect(account.tiers).toHaveLength(1); + expect(account.tiers[0]).toMatchObject({ + leagueId: 'L2', + queueType: 'RANKED_SOLO_5x5', + tier: 'PLATINUM', + rank: 'IV', + leaguePoints: 20, + }); + expect(account.tierHistory.at(-1)).toMatchObject({ + queueType: 'RANKED_SOLO_5x5', + tier: 'PLATINUM', + rank: 'IV', + leaguePoints: 20, + }); + expect(user.save).toHaveBeenCalledTimes(1); + }); + it('records failed for individual failing fetches but updates the rest', async () => { const account = makeAccount(); const user = makeUser(account); diff --git a/apps/api/src/modules/riot/riot-account-enrichment.service.ts b/apps/api/src/modules/riot/riot-account-enrichment.service.ts index 1f9ac2a8..65bd3840 100644 --- a/apps/api/src/modules/riot/riot-account-enrichment.service.ts +++ b/apps/api/src/modules/riot/riot-account-enrichment.service.ts @@ -52,6 +52,8 @@ export interface EnrichResult { account: RiotAccount | null; } +export type RefreshLeagueEntriesResult = 'updated' | 'failed'; + @Injectable() export class RiotAccountEnrichmentService { private readonly logger = new Logger(RiotAccountEnrichmentService.name); @@ -95,6 +97,29 @@ export class RiotAccountEnrichmentService { return promise; } + public async refreshLeagueEntries(params: { + userId: mongoose.Types.ObjectId; + puuid: string; + platform?: RiotPlatformRoute; + }): Promise { + const UserModel = await this.connectionService.getModel('user'); + const user = await UserModel.findById(params.userId).exec(); + if (!user) return 'failed'; + + const account = user.riotAccounts.find((a) => a.puuid === params.puuid); + if (!account) return 'failed'; + + const outcome = await this.fetchLeagueSafe( + params.puuid, + params.platform ?? DEFAULT_PLATFORM, + ); + if (outcome.status !== 'updated' || !outcome.dto) return 'failed'; + + this.applyLeagueEntries(account, outcome.dto); + await user.save(); + return 'updated'; + } + private async doEnrichRiotAccount(params: { userId: mongoose.Types.ObjectId; puuid: string; -- 2.54.0 From 5ad0f8a1c2d61f6b9b395d92c3bff37611010bdb Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sun, 7 Jun 2026 07:20:35 -0700 Subject: [PATCH 10/57] 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 +