This commit is contained in:
dahyeon committed 2026-05-02 05:23:56 -07:00
1 parent bd3cd4fa5f
commit a5654c02a2
6 files changed
+327 -62

No files matched your search

@@ -110,11 +110,9 @@ export class DakaoSubscriber implements OnModuleInit {
case 'match-join': case 'match-join':
segments = await this.matchJoinHandler.handle({ segments = await this.matchJoinHandler.handle({
communityId, communityId,
matchId: command.matchId, matchAndRiotId: command.matchAndRiotId,
senderUserId: event.userId, senderUserId: event.userId,
senderNickname, senderNickname,
gameName: command.gameName,
tagLine: command.tagLine,
positions: command.positions.positions, positions: command.positions.positions,
}); });
break; break;
@@ -204,9 +202,9 @@ export class DakaoSubscriber implements OnModuleInit {
const text = ((): string => { const text = ((): string => {
switch (err.code) { switch (err.code) {
case 'unknown_command': case 'unknown_command':
return ` 알 수 없는 명령어입니다. 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>, !내전 취소 <ID>, !내전 참가취소 <ID>`; return ` 알 수 없는 명령어입니다. 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 [ID 또는 제목] <게임명>#<태그> <포지션1>,<포지션2>, !내전 취소 <ID>, !내전 참가취소 <ID>`;
case 'usage': case 'usage':
return ` 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>, !내전 취소 <ID>, !내전 참가취소 <ID>`; return ` 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 [ID 또는 제목] <게임명>#<태그> <포지션1>,<포지션2>, !내전 취소 <ID>, !내전 참가취소 <ID>`;
case 'invalid_match_id': case 'invalid_match_id':
return ` 매치 ID 형식이 올바르지 않습니다 (${err.detail ?? ''}).`; return ` 매치 ID 형식이 올바르지 않습니다 (${err.detail ?? ''}).`;
case 'invalid_riot_id': case 'invalid_riot_id':
@@ -12,6 +12,7 @@ function makeHandler(overrides?: {
}): MatchJoinHandler { }): MatchJoinHandler {
const matchService = { const matchService = {
join: jest.fn(), join: jest.fn(),
list: jest.fn(),
...overrides?.matchService, ...overrides?.matchService,
} as unknown as MatchService; } as unknown as MatchService;
const dakaoUserService = { const dakaoUserService = {
@@ -23,27 +24,37 @@ function makeHandler(overrides?: {
const baseParams = { const baseParams = {
communityId: objectId('111111111111111111111111'), communityId: objectId('111111111111111111111111'),
matchId: '69b63bc96da18dfdb218ee8c', matchAndRiotId: '69b63bc96da18dfdb218ee8c 프리리#KR1',
senderUserId: 'kakao-user-1', senderUserId: 'kakao-user-1',
senderNickname: '프리리', senderNickname: '프리리',
gameName: '프리리',
tagLine: 'KR1',
positions: ['MID', 'TOP'] as const, positions: ['MID', 'TOP'] as const,
}; };
describe('MatchJoinHandler', () => { describe('MatchJoinHandler', () => {
it('rejects invalid match id without touching services', async () => { it('rejects missing match reference when multiple matches are recruiting', async () => {
const handler = makeHandler(); const resolveRiotAccount = jest.fn();
const handler = makeHandler({
matchService: {
list: jest.fn().mockResolvedValue([
{ _id: objectId('333333333333333333333333'), title: '저녁 내전' },
{ _id: objectId('444444444444444444444444'), title: '심야 내전' },
]),
} as Partial<MatchService>,
dakaoUserService: {
resolveRiotAccount,
} as Partial<DakaoUserService>,
});
const segments = await handler.handle({ const segments = await handler.handle({
...baseParams, ...baseParams,
matchId: 'not-an-id', matchAndRiotId: '프리리#KR1',
positions: [...baseParams.positions], positions: [...baseParams.positions],
}); });
expect(resolveRiotAccount).not.toHaveBeenCalled();
expect(segments).toEqual([ expect(segments).toEqual([
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }), expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
expect.objectContaining({ expect.objectContaining({
kind: 'text', 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<MatchService>,
dakaoUserService: {
resolveRiotAccount: jest.fn().mockResolvedValue({
user: { _id: objectId('222222222222222222222222') },
riotAccount: { puuid: 'puuid-1', gameName: '프리리', tagLine: 'KR1' },
}),
} as Partial<DakaoUserService>,
});
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<MatchService>,
dakaoUserService: {
resolveRiotAccount: jest.fn().mockResolvedValue({
user: { _id: objectId('222222222222222222222222') },
riotAccount: { puuid: 'puuid-1', gameName: '프리리', tagLine: 'KR1' },
}),
} as Partial<DakaoUserService>,
});
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<MatchService>,
dakaoUserService: {
resolveRiotAccount,
} as Partial<DakaoUserService>,
});
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 () => { it('translates riot_account_not_found errors', async () => {
const handler = makeHandler({ const handler = makeHandler({
dakaoUserService: { dakaoUserService: {
@@ -5,18 +5,27 @@ import {
} from '@nestjs/common'; } from '@nestjs/common';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { MatchService } from '../../match/match.service'; 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 { DakaoSegment } from '../dakao.types';
import { DakaoUserError, DakaoUserService } from '../dakao-user.service'; import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
import { normalizeRiotIdPart } from '../riot-id.util';
interface JoinHandlerParams { interface JoinHandlerParams {
communityId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId;
matchId: string; matchAndRiotId: string;
senderUserId: string; // kakaoTalkId senderUserId: string; // kakaoTalkId
senderNickname: string; // kakaoTalkNickname senderNickname: string; // kakaoTalkNickname
positions: Position[];
}
interface ResolvedJoinTarget {
matchId: mongoose.Types.ObjectId;
gameName: string; gameName: string;
tagLine: string; tagLine: string;
positions: Position[];
} }
@Injectable() @Injectable()
@@ -27,10 +36,10 @@ export class MatchJoinHandler {
) {} ) {}
public async handle(params: JoinHandlerParams): Promise<DakaoSegment[]> { public async handle(params: JoinHandlerParams): Promise<DakaoSegment[]> {
if (!mongoose.isValidObjectId(params.matchId)) { const joinTarget = await this.resolveJoinTarget(params);
return this.errorReply(params, '유효하지 않은 내전 ID 입니다.'); if (typeof joinTarget === 'string') {
return this.errorReply(params, joinTarget);
} }
const matchObjectId = new mongoose.Types.ObjectId(params.matchId);
let resolved; let resolved;
try { try {
@@ -38,8 +47,8 @@ export class MatchJoinHandler {
communityId: params.communityId, communityId: params.communityId,
kakaoTalkId: params.senderUserId, kakaoTalkId: params.senderUserId,
kakaoTalkNickname: params.senderNickname, kakaoTalkNickname: params.senderNickname,
gameName: params.gameName, gameName: joinTarget.gameName,
tagLine: params.tagLine, tagLine: joinTarget.tagLine,
}); });
} catch (err) { } catch (err) {
if (err instanceof DakaoUserError) { if (err instanceof DakaoUserError) {
@@ -54,7 +63,7 @@ export class MatchJoinHandler {
try { try {
const match = await this.matchService.join({ const match = await this.matchService.join({
matchId: matchObjectId, matchId: joinTarget.matchId,
userId: resolved.user._id, userId: resolved.user._id,
preferredPositions, preferredPositions,
riotPuuid: resolved.riotAccount.puuid, riotPuuid: resolved.riotAccount.puuid,
@@ -86,6 +95,144 @@ export class MatchJoinHandler {
} }
} }
private async resolveJoinTarget(
params: JoinHandlerParams,
): Promise<ResolvedJoinTarget | string> {
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( private errorReply(
params: JoinHandlerParams, params: JoinHandlerParams,
message: string, message: string,
@@ -126,3 +273,15 @@ export class MatchJoinHandler {
return raw; 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();
}
@@ -45,7 +45,7 @@ export class MatchListHandler {
}, },
{ {
kind: 'text', kind: 'text',
text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n신청: !내전 신청 <ID> <닉네임>#<태그> <포지션1>,<포지션2>\n취소: !내전 취소 <ID> 또는 !내전 참가취소 <ID>`, text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n신청: !내전 신청 [ID 또는 제목] <닉네임>#<태그> <포지션1>,<포지션2>\n취소: !내전 취소 <ID> 또는 !내전 참가취소 <ID>\n모집 중 내전이 1개면 신청 ID/제목은 생략할 수 있습니다.`,
}, },
]; ];
} }
@@ -15,9 +15,7 @@ describe('parseCommand', () => {
); );
expect(result).toMatchObject({ expect(result).toMatchObject({
kind: 'match-join', kind: 'match-join',
matchId: '69b63bc96da18dfdb218ee8c', matchAndRiotId: '69b63bc96da18dfdb218ee8c 프리리#KR1',
gameName: '프리리',
tagLine: 'KR1',
}); });
if (result.kind === 'match-join') { if (result.kind === 'match-join') {
expect(result.positions.positions).toEqual(['MID', 'TOP']); expect(result.positions.positions).toEqual(['MID', 'TOP']);
@@ -30,12 +28,11 @@ describe('parseCommand', () => {
); );
expect(result).toMatchObject({ expect(result).toMatchObject({
kind: 'match-join', kind: 'match-join',
gameName: 'hello world', matchAndRiotId: '69b63bc96da18dfdb218ee8c hello world#KR1',
tagLine: 'KR1',
}); });
}); });
it('normalizes hidden unicode differences in riot id', () => { it('parses hidden unicode differences in riot id input', () => {
const decomposedGameName = '프리리'.normalize('NFD'); const decomposedGameName = '프리리'.normalize('NFD');
const result = parseCommand( const result = parseCommand(
`!내전 신청 69b63bc96da18dfdb218ee8c ${decomposedGameName}\u200B#KR1\uFEFF 미드,탑`, `!내전 신청 69b63bc96da18dfdb218ee8c ${decomposedGameName}\u200B#KR1\uFEFF 미드,탑`,
@@ -43,8 +40,23 @@ describe('parseCommand', () => {
expect(result).toMatchObject({ expect(result).toMatchObject({
kind: 'match-join', kind: 'match-join',
gameName: '프리리', matchAndRiotId: `69b63bc96da18dfdb218ee8c ${decomposedGameName}\u200B#KR1`,
tagLine: '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/); expect(() => parseCommand('!내전 폭파')).toThrow(/unknown_command/);
}); });
it('throws invalid_match_id for non-objectid match', () => { it('allows non-objectid join match reference for title matching', () => {
expect(() => expect(
parseCommand('!내전 신청 not-an-id 프리리#KR1 미드,탑'), 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', () => { it('throws invalid_match_id for non-objectid cancel match', () => {
@@ -10,9 +10,7 @@ export type DakaoCommand =
} }
| { | {
kind: 'match-join'; kind: 'match-join';
matchId: string; matchAndRiotId: string;
gameName: string;
tagLine: string;
positions: ParsedPositions; positions: ParsedPositions;
} }
| { | {
@@ -111,38 +109,22 @@ function parseJoinArgs(args: string): DakaoCommand {
throw new CommandParseError('usage'); throw new CommandParseError('usage');
} }
// 마지막 토큰이 포지션 리스트(쉼표 포함). 그 앞이 라이엇 ID(공백 포함 가능). 그 앞이 matchId. // 마지막 토큰이 포지션 리스트(쉼표 포함). 그 앞은 내전 식별자(선택)와 라이엇 ID.
// 형식: <matchId> <gameName...>#<tagLine> <pos1>,<pos2>... // 형식: [<matchId|title...>] <gameName...>#<tagLine> <pos1>,<pos2>...
// 끝에서부터 토큰을 분리해 안정적으로 파싱한다. // 끝에서부터 토큰을 분리해 안정적으로 파싱한다.
const lastSpace = args.lastIndexOf(' '); const lastSpace = args.lastIndexOf(' ');
if (lastSpace === -1) { if (lastSpace === -1) {
throw new CommandParseError('usage'); throw new CommandParseError('usage');
} }
const positionPart = args.slice(lastSpace + 1).trim(); const positionPart = args.slice(lastSpace + 1).trim();
const head = args.slice(0, lastSpace).trim(); const matchAndRiotId = args.slice(0, lastSpace).trim();
if (positionPart.length === 0 || head.length === 0) { if (positionPart.length === 0 || matchAndRiotId.length === 0) {
throw new CommandParseError('usage'); throw new CommandParseError('usage');
} }
const headSpace = head.indexOf(' '); const hashIndex = matchAndRiotId.lastIndexOf('#');
if (headSpace === -1) { if (hashIndex <= 0 || hashIndex === matchAndRiotId.length - 1) {
throw new CommandParseError('usage'); throw new CommandParseError('invalid_riot_id', matchAndRiotId);
}
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);
} }
let positions: ParsedPositions; let positions: ParsedPositions;
@@ -157,9 +139,7 @@ function parseJoinArgs(args: string): DakaoCommand {
return { return {
kind: 'match-join', kind: 'match-join',
matchId, matchAndRiotId,
gameName,
tagLine,
positions, positions,
}; };
} }