From a5654c02a201b9c49538b46d5a8176ac768fc7b4 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sat, 2 May 2026 05:23:56 -0700 Subject: [PATCH] . --- .../api/src/modules/dakao/dakao.subscriber.ts | 8 +- .../dakao/handlers/match-join.handler.spec.ts | 127 ++++++++++++- .../dakao/handlers/match-join.handler.ts | 177 +++++++++++++++++- .../dakao/handlers/match-list.handler.ts | 2 +- .../dakao/parsers/command.parser.spec.ts | 37 ++-- .../modules/dakao/parsers/command.parser.ts | 38 +--- 6 files changed, 327 insertions(+), 62 deletions(-) diff --git a/apps/api/src/modules/dakao/dakao.subscriber.ts b/apps/api/src/modules/dakao/dakao.subscriber.ts index 8a4422f5..cc1b84a6 100644 --- a/apps/api/src/modules/dakao/dakao.subscriber.ts +++ b/apps/api/src/modules/dakao/dakao.subscriber.ts @@ -110,11 +110,9 @@ export class DakaoSubscriber implements OnModuleInit { case 'match-join': segments = await this.matchJoinHandler.handle({ communityId, - matchId: command.matchId, + matchAndRiotId: command.matchAndRiotId, senderUserId: event.userId, senderNickname, - gameName: command.gameName, - tagLine: command.tagLine, positions: command.positions.positions, }); break; @@ -204,9 +202,9 @@ export class DakaoSubscriber implements OnModuleInit { const text = ((): string => { switch (err.code) { case 'unknown_command': - return ` 알 수 없는 명령어입니다. 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <게임명>#<태그> <포지션1>,<포지션2>, !내전 취소 , !내전 참가취소 `; + return ` 알 수 없는 명령어입니다. 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 [ID 또는 제목] <게임명>#<태그> <포지션1>,<포지션2>, !내전 취소 , !내전 참가취소 `; case 'usage': - return ` 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <게임명>#<태그> <포지션1>,<포지션2>, !내전 취소 , !내전 참가취소 `; + return ` 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 [ID 또는 제목] <게임명>#<태그> <포지션1>,<포지션2>, !내전 취소 , !내전 참가취소 `; case 'invalid_match_id': return ` 매치 ID 형식이 올바르지 않습니다 (${err.detail ?? ''}).`; case 'invalid_riot_id': diff --git a/apps/api/src/modules/dakao/handlers/match-join.handler.spec.ts b/apps/api/src/modules/dakao/handlers/match-join.handler.spec.ts index 5ad7235a..5354d71c 100644 --- a/apps/api/src/modules/dakao/handlers/match-join.handler.spec.ts +++ b/apps/api/src/modules/dakao/handlers/match-join.handler.spec.ts @@ -12,6 +12,7 @@ function makeHandler(overrides?: { }): MatchJoinHandler { const matchService = { join: jest.fn(), + list: jest.fn(), ...overrides?.matchService, } as unknown as MatchService; const dakaoUserService = { @@ -23,27 +24,37 @@ function makeHandler(overrides?: { const baseParams = { communityId: objectId('111111111111111111111111'), - matchId: '69b63bc96da18dfdb218ee8c', + matchAndRiotId: '69b63bc96da18dfdb218ee8c 프리리#KR1', senderUserId: 'kakao-user-1', senderNickname: '프리리', - gameName: '프리리', - tagLine: 'KR1', positions: ['MID', 'TOP'] as const, }; describe('MatchJoinHandler', () => { - it('rejects invalid match id without touching services', async () => { - const handler = makeHandler(); + it('rejects missing match reference when multiple matches are recruiting', async () => { + const resolveRiotAccount = jest.fn(); + const handler = makeHandler({ + matchService: { + list: jest.fn().mockResolvedValue([ + { _id: objectId('333333333333333333333333'), title: '저녁 내전' }, + { _id: objectId('444444444444444444444444'), title: '심야 내전' }, + ]), + } as Partial, + dakaoUserService: { + resolveRiotAccount, + } as Partial, + }); const segments = await handler.handle({ ...baseParams, - matchId: 'not-an-id', + matchAndRiotId: '프리리#KR1', positions: [...baseParams.positions], }); + expect(resolveRiotAccount).not.toHaveBeenCalled(); expect(segments).toEqual([ expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }), expect.objectContaining({ kind: 'text', - text: expect.stringContaining('유효하지 않은 내전 ID'), + text: expect.stringContaining('ID 또는 제목'), }), ]); }); @@ -92,6 +103,108 @@ describe('MatchJoinHandler', () => { }); }); + it('uses the only recruiting match when match reference is omitted', async () => { + const matchId = objectId('333333333333333333333333'); + const join = jest.fn().mockResolvedValue({ + title: '저녁 내전', + participants: [{}], + maxParticipants: 10, + }); + const handler = makeHandler({ + matchService: { + list: jest + .fn() + .mockResolvedValue([{ _id: matchId, title: '저녁 내전' }]), + join, + } as Partial, + dakaoUserService: { + resolveRiotAccount: jest.fn().mockResolvedValue({ + user: { _id: objectId('222222222222222222222222') }, + riotAccount: { puuid: 'puuid-1', gameName: '프리리', tagLine: 'KR1' }, + }), + } as Partial, + }); + + const segments = await handler.handle({ + ...baseParams, + matchAndRiotId: '프리리#KR1', + positions: [...baseParams.positions], + }); + + expect(join).toHaveBeenCalledWith( + expect.objectContaining({ + matchId, + }), + ); + expect(segments[1]).toMatchObject({ + kind: 'text', + text: expect.stringContaining('신청 완료 (1/10)'), + }); + }); + + it('resolves a unique recruiting match by title prefix', async () => { + const matchId = objectId('333333333333333333333333'); + const join = jest.fn().mockResolvedValue({ + title: '저녁 내전', + participants: [{}], + maxParticipants: 10, + }); + const handler = makeHandler({ + matchService: { + list: jest.fn().mockResolvedValue([ + { _id: matchId, title: '저녁 내전' }, + { _id: objectId('444444444444444444444444'), title: '심야 내전' }, + ]), + join, + } as Partial, + dakaoUserService: { + resolveRiotAccount: jest.fn().mockResolvedValue({ + user: { _id: objectId('222222222222222222222222') }, + riotAccount: { puuid: 'puuid-1', gameName: '프리리', tagLine: 'KR1' }, + }), + } as Partial, + }); + + await handler.handle({ + ...baseParams, + matchAndRiotId: '저녁 프리리#KR1', + positions: [...baseParams.positions], + }); + + expect(join).toHaveBeenCalledWith( + expect.objectContaining({ + matchId, + }), + ); + }); + + it('rejects ambiguous title prefixes', async () => { + const resolveRiotAccount = jest.fn(); + const handler = makeHandler({ + matchService: { + list: jest.fn().mockResolvedValue([ + { _id: objectId('333333333333333333333333'), title: '저녁 내전 A' }, + { _id: objectId('444444444444444444444444'), title: '저녁 내전 B' }, + ]), + } as Partial, + dakaoUserService: { + resolveRiotAccount, + } as Partial, + }); + + const segments = await handler.handle({ + ...baseParams, + matchAndRiotId: '저녁 프리리#KR1', + positions: [...baseParams.positions], + }); + + expect(resolveRiotAccount).not.toHaveBeenCalled(); + expect(segments[1]).toMatchObject({ + kind: 'text', + text: expect.stringContaining('여러 개와 겹칩니다'), + }); + }); + it('translates riot_account_not_found errors', async () => { const handler = makeHandler({ dakaoUserService: { diff --git a/apps/api/src/modules/dakao/handlers/match-join.handler.ts b/apps/api/src/modules/dakao/handlers/match-join.handler.ts index 08ebb6d9..7ad71e74 100644 --- a/apps/api/src/modules/dakao/handlers/match-join.handler.ts +++ b/apps/api/src/modules/dakao/handlers/match-join.handler.ts @@ -5,18 +5,27 @@ import { } from '@nestjs/common'; import mongoose from 'mongoose'; import { MatchService } from '../../match/match.service'; -import { Position, PositionPreference } from '../../global/database/schema'; +import { + MatchDocument, + Position, + PositionPreference, +} from '../../global/database/schema'; import { DakaoSegment } from '../dakao.types'; import { DakaoUserError, DakaoUserService } from '../dakao-user.service'; +import { normalizeRiotIdPart } from '../riot-id.util'; interface JoinHandlerParams { communityId: mongoose.Types.ObjectId; - matchId: string; + matchAndRiotId: string; senderUserId: string; // kakaoTalkId senderNickname: string; // kakaoTalkNickname + positions: Position[]; +} + +interface ResolvedJoinTarget { + matchId: mongoose.Types.ObjectId; gameName: string; tagLine: string; - positions: Position[]; } @Injectable() @@ -27,10 +36,10 @@ export class MatchJoinHandler { ) {} public async handle(params: JoinHandlerParams): Promise { - if (!mongoose.isValidObjectId(params.matchId)) { - return this.errorReply(params, '유효하지 않은 내전 ID 입니다.'); + const joinTarget = await this.resolveJoinTarget(params); + if (typeof joinTarget === 'string') { + return this.errorReply(params, joinTarget); } - const matchObjectId = new mongoose.Types.ObjectId(params.matchId); let resolved; try { @@ -38,8 +47,8 @@ export class MatchJoinHandler { communityId: params.communityId, kakaoTalkId: params.senderUserId, kakaoTalkNickname: params.senderNickname, - gameName: params.gameName, - tagLine: params.tagLine, + gameName: joinTarget.gameName, + tagLine: joinTarget.tagLine, }); } catch (err) { if (err instanceof DakaoUserError) { @@ -54,7 +63,7 @@ export class MatchJoinHandler { try { const match = await this.matchService.join({ - matchId: matchObjectId, + matchId: joinTarget.matchId, userId: resolved.user._id, preferredPositions, riotPuuid: resolved.riotAccount.puuid, @@ -86,6 +95,144 @@ export class MatchJoinHandler { } } + private async resolveJoinTarget( + params: JoinHandlerParams, + ): Promise { + const riotId = this.parseRiotId(params.matchAndRiotId); + if (typeof riotId === 'string') return riotId; + + const objectIdMatch = riotId.gameNameWithOptionalMatchRef.match( + /^([a-f0-9]{24})(?:\s+(.+))?$/i, + ); + if (objectIdMatch) { + const gameName = normalizeRiotIdPart(objectIdMatch[2] ?? ''); + if (!gameName) { + return '라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).'; + } + return { + matchId: new mongoose.Types.ObjectId(objectIdMatch[1]), + gameName, + tagLine: riotId.tagLine, + }; + } + + const recruitingMatches = await this.matchService.list({ + communityId: params.communityId, + status: 'recruiting', + limit: 50, + }); + if (recruitingMatches.length === 0) { + return '모집 중인 내전이 없습니다.'; + } + + if (recruitingMatches.length === 1) { + return { + matchId: recruitingMatches[0]._id, + gameName: riotId.gameNameWithOptionalMatchRef, + tagLine: riotId.tagLine, + }; + } + + const titleTarget = this.resolveTitleTarget( + riotId.gameNameWithOptionalMatchRef, + recruitingMatches, + ); + if (titleTarget.kind === 'matched') { + return { + matchId: titleTarget.match._id, + gameName: titleTarget.gameName, + tagLine: riotId.tagLine, + }; + } + if (titleTarget.kind === 'ambiguous') { + return `내전 제목이 여러 개와 겹칩니다 (${titleTarget.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`; + } + + return '모집 중인 내전을 찾을 수 없습니다. !내전 리스트에서 ID 또는 제목을 확인해주세요.'; + } + + private parseRiotId( + value: string, + ): { gameNameWithOptionalMatchRef: string; tagLine: string } | string { + const hashIndex = value.lastIndexOf('#'); + if (hashIndex <= 0 || hashIndex === value.length - 1) { + return '라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).'; + } + + const gameNameWithOptionalMatchRef = normalizeRiotIdPart( + value.slice(0, hashIndex), + ); + const tagLine = normalizeRiotIdPart(value.slice(hashIndex + 1)); + if (!gameNameWithOptionalMatchRef || !tagLine) { + return '라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).'; + } + return { gameNameWithOptionalMatchRef, tagLine }; + } + + private resolveTitleTarget( + value: string, + matches: MatchDocument[], + ): + | { kind: 'matched'; match: MatchDocument; gameName: string } + | { kind: 'ambiguous'; titles: string[] } + | { kind: 'not-found' } { + let ambiguousTitles: string[] | null = null; + + for (const splitAt of splitPositionsFromRight(value)) { + const matchTitlePrefix = value.slice(0, splitAt).trim(); + const gameName = normalizeRiotIdPart(value.slice(splitAt + 1)); + if (!matchTitlePrefix || !gameName) continue; + + const result = this.findByTitlePrefix(matches, matchTitlePrefix); + if (result.kind === 'matched') { + return { kind: 'matched', match: result.match, gameName }; + } + if (result.kind === 'ambiguous') { + ambiguousTitles = result.titles; + } + } + + return ambiguousTitles + ? { kind: 'ambiguous', titles: ambiguousTitles } + : { kind: 'not-found' }; + } + + private findByTitlePrefix( + matches: MatchDocument[], + titlePrefix: string, + ): + | { kind: 'matched'; match: MatchDocument } + | { kind: 'ambiguous'; titles: string[] } + | { kind: 'not-found' } { + const normalizedPrefix = normalizeLookup(titlePrefix); + const exactMatches = matches.filter( + (match) => normalizeLookup(match.title) === normalizedPrefix, + ); + if (exactMatches.length === 1) { + return { kind: 'matched', match: exactMatches[0] }; + } + if (exactMatches.length > 1) { + return { + kind: 'ambiguous', + titles: exactMatches.map((match) => match.title), + }; + } + + const prefixMatches = matches.filter((match) => + normalizeLookup(match.title).startsWith(normalizedPrefix), + ); + if (prefixMatches.length === 1) { + return { kind: 'matched', match: prefixMatches[0] }; + } + if (prefixMatches.length > 1) { + return { + kind: 'ambiguous', + titles: prefixMatches.map((match) => match.title), + }; + } + return { kind: 'not-found' }; + } + private errorReply( params: JoinHandlerParams, message: string, @@ -126,3 +273,15 @@ export class MatchJoinHandler { return raw; } } + +function splitPositionsFromRight(value: string): number[] { + const positions: number[] = []; + for (let index = value.length - 1; index >= 0; index -= 1) { + if (/\s/.test(value[index])) positions.push(index); + } + return positions; +} + +function normalizeLookup(value: string): string { + return value.normalize('NFC').trim().replace(/\s+/g, ' ').toLowerCase(); +} diff --git a/apps/api/src/modules/dakao/handlers/match-list.handler.ts b/apps/api/src/modules/dakao/handlers/match-list.handler.ts index db77a45c..1d846bfb 100644 --- a/apps/api/src/modules/dakao/handlers/match-list.handler.ts +++ b/apps/api/src/modules/dakao/handlers/match-list.handler.ts @@ -45,7 +45,7 @@ export class MatchListHandler { }, { kind: 'text', - text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n신청: !내전 신청 <닉네임>#<태그> <포지션1>,<포지션2>\n취소: !내전 취소 또는 !내전 참가취소 `, + text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n신청: !내전 신청 [ID 또는 제목] <닉네임>#<태그> <포지션1>,<포지션2>\n취소: !내전 취소 또는 !내전 참가취소 \n모집 중 내전이 1개면 신청 ID/제목은 생략할 수 있습니다.`, }, ]; } diff --git a/apps/api/src/modules/dakao/parsers/command.parser.spec.ts b/apps/api/src/modules/dakao/parsers/command.parser.spec.ts index 57d89873..a8671bba 100644 --- a/apps/api/src/modules/dakao/parsers/command.parser.spec.ts +++ b/apps/api/src/modules/dakao/parsers/command.parser.spec.ts @@ -15,9 +15,7 @@ describe('parseCommand', () => { ); expect(result).toMatchObject({ kind: 'match-join', - matchId: '69b63bc96da18dfdb218ee8c', - gameName: '프리리', - tagLine: 'KR1', + matchAndRiotId: '69b63bc96da18dfdb218ee8c 프리리#KR1', }); if (result.kind === 'match-join') { expect(result.positions.positions).toEqual(['MID', 'TOP']); @@ -30,12 +28,11 @@ describe('parseCommand', () => { ); expect(result).toMatchObject({ kind: 'match-join', - gameName: 'hello world', - tagLine: 'KR1', + matchAndRiotId: '69b63bc96da18dfdb218ee8c hello world#KR1', }); }); - it('normalizes hidden unicode differences in riot id', () => { + it('parses hidden unicode differences in riot id input', () => { const decomposedGameName = '프리리'.normalize('NFD'); const result = parseCommand( `!내전 신청 69b63bc96da18dfdb218ee8c ${decomposedGameName}\u200B#KR1\uFEFF 미드,탑`, @@ -43,8 +40,23 @@ describe('parseCommand', () => { expect(result).toMatchObject({ kind: 'match-join', - gameName: '프리리', - tagLine: 'KR1', + matchAndRiotId: `69b63bc96da18dfdb218ee8c ${decomposedGameName}\u200B#KR1`, + }); + }); + + it('parses match-join command without explicit match id', () => { + const result = parseCommand('!내전 신청 프리리#KR1 미드,탑'); + expect(result).toMatchObject({ + kind: 'match-join', + matchAndRiotId: '프리리#KR1', + }); + }); + + it('parses match-join command with title prefix', () => { + const result = parseCommand('!내전 신청 저녁 프리리#KR1 미드,탑'); + expect(result).toMatchObject({ + kind: 'match-join', + matchAndRiotId: '저녁 프리리#KR1', }); }); @@ -89,10 +101,13 @@ describe('parseCommand', () => { expect(() => parseCommand('!내전 폭파')).toThrow(/unknown_command/); }); - it('throws invalid_match_id for non-objectid match', () => { - expect(() => + it('allows non-objectid join match reference for title matching', () => { + expect( parseCommand('!내전 신청 not-an-id 프리리#KR1 미드,탑'), - ).toThrow(/invalid_match_id/); + ).toMatchObject({ + kind: 'match-join', + matchAndRiotId: 'not-an-id 프리리#KR1', + }); }); it('throws invalid_match_id for non-objectid cancel match', () => { diff --git a/apps/api/src/modules/dakao/parsers/command.parser.ts b/apps/api/src/modules/dakao/parsers/command.parser.ts index bf3f1d15..1fa837a5 100644 --- a/apps/api/src/modules/dakao/parsers/command.parser.ts +++ b/apps/api/src/modules/dakao/parsers/command.parser.ts @@ -10,9 +10,7 @@ export type DakaoCommand = } | { kind: 'match-join'; - matchId: string; - gameName: string; - tagLine: string; + matchAndRiotId: string; positions: ParsedPositions; } | { @@ -111,38 +109,22 @@ function parseJoinArgs(args: string): DakaoCommand { throw new CommandParseError('usage'); } - // 마지막 토큰이 포지션 리스트(쉼표 포함). 그 앞이 라이엇 ID(공백 포함 가능). 그 앞이 matchId. - // 형식: # ,... + // 마지막 토큰이 포지션 리스트(쉼표 포함). 그 앞은 내전 식별자(선택)와 라이엇 ID. + // 형식: [] # ,... // 끝에서부터 토큰을 분리해 안정적으로 파싱한다. const lastSpace = args.lastIndexOf(' '); if (lastSpace === -1) { throw new CommandParseError('usage'); } const positionPart = args.slice(lastSpace + 1).trim(); - const head = args.slice(0, lastSpace).trim(); - if (positionPart.length === 0 || head.length === 0) { + const matchAndRiotId = args.slice(0, lastSpace).trim(); + if (positionPart.length === 0 || matchAndRiotId.length === 0) { throw new CommandParseError('usage'); } - const headSpace = head.indexOf(' '); - if (headSpace === -1) { - throw new CommandParseError('usage'); - } - const matchId = head.slice(0, headSpace).trim(); - const riotId = head.slice(headSpace + 1).trim(); - - if (!isObjectIdHex(matchId)) { - throw new CommandParseError('invalid_match_id', matchId); - } - - const hashIndex = riotId.lastIndexOf('#'); - if (hashIndex <= 0 || hashIndex === riotId.length - 1) { - throw new CommandParseError('invalid_riot_id', riotId); - } - const gameName = normalizeRiotIdPart(riotId.slice(0, hashIndex)); - const tagLine = normalizeRiotIdPart(riotId.slice(hashIndex + 1)); - if (gameName.length === 0 || tagLine.length === 0) { - throw new CommandParseError('invalid_riot_id', riotId); + const hashIndex = matchAndRiotId.lastIndexOf('#'); + if (hashIndex <= 0 || hashIndex === matchAndRiotId.length - 1) { + throw new CommandParseError('invalid_riot_id', matchAndRiotId); } let positions: ParsedPositions; @@ -157,9 +139,7 @@ function parseJoinArgs(args: string): DakaoCommand { return { kind: 'match-join', - matchId, - gameName, - tagLine, + matchAndRiotId, positions, }; }