This commit is contained in:
dahyeon committed 2026-05-03 00:21:15 -07:00
1 parent 5286e4d1ed
commit 62368c720e
12 files changed
+471 -53

No files matched your search

@@ -1,7 +1,12 @@
import { Injectable, Logger } from '@nestjs/common'; import { Injectable, Logger } from '@nestjs/common';
import mongoose, { isValidObjectId } from 'mongoose'; import mongoose, { isValidObjectId } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import { RiotAccount, UserDocument } from '../global/database/schema'; import {
Position,
PositionPreference,
RiotAccount,
UserDocument,
} from '../global/database/schema';
import { RiotApiError } from '../riot/riot.client.service'; import { RiotApiError } from '../riot/riot.client.service';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
import { RiotAccountService } from '../riot/riot-account.service'; import { RiotAccountService } from '../riot/riot-account.service';
@@ -209,6 +214,29 @@ export class DakaoUserService {
return this.registerRiotAccount(context); return this.registerRiotAccount(context);
} }
public async registerPreferredPositions(params: {
communityId: mongoose.Types.ObjectId;
kakaoTalkId: string;
kakaoTalkNickname: string;
positions: Position[];
}): Promise<UserDocument> {
const user = await this.upsertUser({
communityId: params.communityId,
kakaoTalkId: params.kakaoTalkId,
kakaoTalkNickname: params.kakaoTalkNickname,
});
user.preferredPositions = this.toPositionPreferences(params.positions);
await user.save();
return user;
}
private toPositionPreferences(positions: Position[]): PositionPreference[] {
return positions.map((position, index) => ({
position,
priority: index + 1,
}));
}
private async lookupRiotIdentity( private async lookupRiotIdentity(
context: ResolveContext, context: ResolveContext,
routing: RiotRouting, routing: RiotRouting,
@@ -13,6 +13,7 @@ import { AccountRegisterHandler } from './handlers/account-register.handler';
import { MatchCancelHandler } from './handlers/match-cancel.handler'; import { MatchCancelHandler } from './handlers/match-cancel.handler';
import { MatchJoinHandler } from './handlers/match-join.handler'; import { MatchJoinHandler } from './handlers/match-join.handler';
import { MatchListHandler } from './handlers/match-list.handler'; import { MatchListHandler } from './handlers/match-list.handler';
import { PreferredPositionRegisterHandler } from './handlers/preferred-position-register.handler';
@Module({ @Module({
imports: [RiotModule, MatchModule], imports: [RiotModule, MatchModule],
@@ -29,6 +30,7 @@ import { MatchListHandler } from './handlers/match-list.handler';
MatchListHandler, MatchListHandler,
MatchJoinHandler, MatchJoinHandler,
MatchCancelHandler, MatchCancelHandler,
PreferredPositionRegisterHandler,
], ],
exports: [DakaoPublisher], exports: [DakaoPublisher],
}) })
+13 -3
View File
@@ -11,6 +11,7 @@ import { AccountRegisterHandler } from './handlers/account-register.handler';
import { MatchCancelHandler } from './handlers/match-cancel.handler'; import { MatchCancelHandler } from './handlers/match-cancel.handler';
import { MatchJoinHandler } from './handlers/match-join.handler'; import { MatchJoinHandler } from './handlers/match-join.handler';
import { MatchListHandler } from './handlers/match-list.handler'; import { MatchListHandler } from './handlers/match-list.handler';
import { PreferredPositionRegisterHandler } from './handlers/preferred-position-register.handler';
const INBOUND_SUBJECT_DEFAULT = 'lolympus-tournament-support.kakaotalk.command'; const INBOUND_SUBJECT_DEFAULT = 'lolympus-tournament-support.kakaotalk.command';
@@ -30,6 +31,7 @@ export class DakaoSubscriber implements OnModuleInit {
private readonly matchListHandler: MatchListHandler, private readonly matchListHandler: MatchListHandler,
private readonly matchJoinHandler: MatchJoinHandler, private readonly matchJoinHandler: MatchJoinHandler,
private readonly matchCancelHandler: MatchCancelHandler, private readonly matchCancelHandler: MatchCancelHandler,
private readonly preferredPositionRegisterHandler: PreferredPositionRegisterHandler,
) {} ) {}
async onModuleInit() { async onModuleInit() {
@@ -113,6 +115,14 @@ export class DakaoSubscriber implements OnModuleInit {
matchAndRiotId: command.matchAndRiotId, matchAndRiotId: command.matchAndRiotId,
senderUserId: event.userId, senderUserId: event.userId,
senderNickname, senderNickname,
positions: command.positions?.positions,
});
break;
case 'preferred-position-register':
segments = await this.preferredPositionRegisterHandler.handle({
communityId,
senderUserId: event.userId,
senderNickname,
positions: command.positions.positions, positions: command.positions.positions,
}); });
break; break;
@@ -202,15 +212,15 @@ 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 ` 알 수 없는 명령어입니다. 사용법: !내전 일정, !내전 계정등록 <게임명>#<태그>, !내전 선호포지션등록 미드,정글, !내전 신청 [코드] [게임명#태그] [포지션1,포지션2], !내전 취소 <코드>`;
case 'usage': case 'usage':
return ` 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 [ID 또는 제목] <게임명>#<태그> <포지션1>,<포지션2>, !내전 취소 <ID>, !내전 참가취소 <ID>`; return ` 사용법: !내전 일정, !내전 계정등록 <게임명>#<태그>, !내전 선호포지션등록 미드,정글, !내전 신청 [코드] [게임명#태그] [포지션1,포지션2], !내전 취소 <코드>`;
case 'invalid_match_id': case 'invalid_match_id':
return ` 매치 ID 형식이 올바르지 않습니다 (${err.detail ?? ''}).`; return ` 매치 ID 형식이 올바르지 않습니다 (${err.detail ?? ''}).`;
case 'invalid_riot_id': case 'invalid_riot_id':
return ` 라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).`; return ` 라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).`;
case 'invalid_position': case 'invalid_position':
return ` 포지션 입력이 올바르지 않습니다. 최소 2개, 중복 없이, 인식되는 별칭(탑/정글/미드/원딜/서폿) 사용.`; return ` 포지션 입력이 올바르지 않습니다. 최소 2개, 중복 없이, 인식되는 별칭(탑/정글/미드/원딜/서폿/SUP/SPT) 사용.`;
default: default:
return ` 명령을 처리할 수 없습니다.`; return ` 명령을 처리할 수 없습니다.`;
} }
@@ -17,6 +17,7 @@ function makeHandler(overrides?: {
} as unknown as MatchService; } as unknown as MatchService;
const dakaoUserService = { const dakaoUserService = {
resolveRiotAccount: jest.fn(), resolveRiotAccount: jest.fn(),
findUserByKakaoTalkId: jest.fn(),
...overrides?.dakaoUserService, ...overrides?.dakaoUserService,
} as unknown as DakaoUserService; } as unknown as DakaoUserService;
return new MatchJoinHandler(matchService, dakaoUserService); return new MatchJoinHandler(matchService, dakaoUserService);
@@ -218,6 +219,103 @@ describe('MatchJoinHandler', () => {
); );
}); });
it('uses registered account and preferred positions for abbreviated join', async () => {
const matchId = objectId('333333333333333333333333');
const userId = objectId('222222222222222222222222');
const join = jest.fn().mockResolvedValue({
title: '저녁 내전',
participants: [{}],
maxParticipants: 10,
});
const resolveRiotAccount = jest.fn();
const handler = makeHandler({
matchService: {
list: jest.fn().mockResolvedValue([
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
]),
join,
} as Partial<MatchService>,
dakaoUserService: {
resolveRiotAccount,
findUserByKakaoTalkId: jest.fn().mockResolvedValue({
_id: userId,
riotAccounts: [
{
puuid: 'puuid-1',
gameName: '프리리',
tagLine: 'KR1',
isPrimary: true,
},
],
preferredPositions: [
{ position: 'MID', priority: 1 },
{ position: 'JGL', priority: 2 },
],
}),
} as Partial<DakaoUserService>,
});
const segments = await handler.handle({
...baseParams,
matchAndRiotId: 'AB12',
positions: undefined,
});
expect(resolveRiotAccount).not.toHaveBeenCalled();
expect(join).toHaveBeenCalledWith({
matchId,
userId,
preferredPositions: [
{ position: 'MID', priority: 1 },
{ position: 'JGL', priority: 2 },
],
riotPuuid: 'puuid-1',
});
expect(segments[1]).toMatchObject({
kind: 'text',
text: expect.stringContaining('계정: 프리리#KR1'),
});
});
it('asks abbreviated join users to register missing preferred positions', async () => {
const matchId = objectId('333333333333333333333333');
const join = jest.fn();
const handler = makeHandler({
matchService: {
list: jest.fn().mockResolvedValue([
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
]),
join,
} as Partial<MatchService>,
dakaoUserService: {
findUserByKakaoTalkId: jest.fn().mockResolvedValue({
_id: objectId('222222222222222222222222'),
riotAccounts: [
{
puuid: 'puuid-1',
gameName: '프리리',
tagLine: 'KR1',
isPrimary: true,
},
],
preferredPositions: [],
}),
} as Partial<DakaoUserService>,
});
const segments = await handler.handle({
...baseParams,
matchAndRiotId: 'AB12',
positions: undefined,
});
expect(join).not.toHaveBeenCalled();
expect(segments[1]).toMatchObject({
kind: 'text',
text: expect.stringContaining('선호포지션등록'),
});
});
it('rejects ambiguous title prefixes', async () => { it('rejects ambiguous title prefixes', async () => {
const resolveRiotAccount = jest.fn(); const resolveRiotAccount = jest.fn();
const handler = makeHandler({ const handler = makeHandler({
@@ -9,6 +9,8 @@ import {
MatchDocument, MatchDocument,
Position, Position,
PositionPreference, PositionPreference,
RiotAccount,
UserDocument,
} from '../../global/database/schema'; } 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';
@@ -20,13 +22,13 @@ interface JoinHandlerParams {
matchAndRiotId: string; matchAndRiotId: string;
senderUserId: string; // kakaoTalkId senderUserId: string; // kakaoTalkId
senderNickname: string; // kakaoTalkNickname senderNickname: string; // kakaoTalkNickname
positions: Position[]; positions?: Position[];
} }
interface ResolvedJoinTarget { interface ResolvedJoinTarget {
matchId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId;
gameName: string; gameName?: string;
tagLine: string; tagLine?: string;
} }
@Injectable() @Injectable()
@@ -42,25 +44,37 @@ export class MatchJoinHandler {
return this.errorReply(params, joinTarget); return this.errorReply(params, joinTarget);
} }
let resolved; let resolved:
| { user: UserDocument; riotAccount: RiotAccount }
| string;
try { try {
resolved = await this.dakaoUserService.resolveRiotAccount({ resolved =
joinTarget.gameName && joinTarget.tagLine
? await this.dakaoUserService.resolveRiotAccount({
communityId: params.communityId, communityId: params.communityId,
kakaoTalkId: params.senderUserId, kakaoTalkId: params.senderUserId,
kakaoTalkNickname: params.senderNickname, kakaoTalkNickname: params.senderNickname,
gameName: joinTarget.gameName, gameName: joinTarget.gameName,
tagLine: joinTarget.tagLine, tagLine: joinTarget.tagLine,
}); })
: await this.resolveRegisteredRiotAccount(params);
} catch (err) { } catch (err) {
if (err instanceof DakaoUserError) { if (err instanceof DakaoUserError) {
return this.errorReply(params, this.translateUserError(err)); return this.errorReply(params, this.translateUserError(err));
} }
throw err; throw err;
} }
if (typeof resolved === 'string') {
return this.errorReply(params, resolved);
}
const preferredPositions: PositionPreference[] = params.positions.map( const preferredPositions = this.resolvePreferredPositions(
(position, index) => ({ position, priority: index + 1 }), params.positions,
resolved.user.preferredPositions,
); );
if (typeof preferredPositions === 'string') {
return this.errorReply(params, preferredPositions);
}
try { try {
const match = await this.matchService.join({ const match = await this.matchService.join({
@@ -82,7 +96,9 @@ export class MatchJoinHandler {
` 신청 완료 (${match.participants.length}/${match.maxParticipants})` + ` 신청 완료 (${match.participants.length}/${match.maxParticipants})` +
`\n내전: ${match.title}` + `\n내전: ${match.title}` +
`\n계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}` + `\n계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}` +
`\n포지션: ${params.positions.join(', ')}`, `\n포지션: ${preferredPositions
.map((entry) => entry.position)
.join(', ')}`,
}, },
]; ];
} catch (err) { } catch (err) {
@@ -99,6 +115,10 @@ export class MatchJoinHandler {
private async resolveJoinTarget( private async resolveJoinTarget(
params: JoinHandlerParams, params: JoinHandlerParams,
): Promise<ResolvedJoinTarget | string> { ): Promise<ResolvedJoinTarget | string> {
if (!params.matchAndRiotId.includes('#')) {
return this.resolveJoinTargetWithoutRiotId(params);
}
const riotId = this.parseRiotId(params.matchAndRiotId); const riotId = this.parseRiotId(params.matchAndRiotId);
if (typeof riotId === 'string') return riotId; if (typeof riotId === 'string') return riotId;
@@ -126,14 +146,6 @@ export class MatchJoinHandler {
return '모집 중인 내전이 없습니다.'; return '모집 중인 내전이 없습니다.';
} }
if (recruitingMatches.length === 1) {
return {
matchId: recruitingMatches[0]._id,
gameName: riotId.gameNameWithOptionalMatchRef,
tagLine: riotId.tagLine,
};
}
const titleTarget = this.resolveTitleTarget( const titleTarget = this.resolveTitleTarget(
riotId.gameNameWithOptionalMatchRef, riotId.gameNameWithOptionalMatchRef,
recruitingMatches, recruitingMatches,
@@ -149,9 +161,56 @@ export class MatchJoinHandler {
return `내전 코드 또는 제목이 여러 개와 겹칩니다 (${titleTarget.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`; return `내전 코드 또는 제목이 여러 개와 겹칩니다 (${titleTarget.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`;
} }
if (recruitingMatches.length === 1) {
return {
matchId: recruitingMatches[0]._id,
gameName: riotId.gameNameWithOptionalMatchRef,
tagLine: riotId.tagLine,
};
}
return '모집 중인 내전을 찾을 수 없습니다. !내전 리스트에서 코드 또는 제목을 확인해주세요.'; return '모집 중인 내전을 찾을 수 없습니다. !내전 리스트에서 코드 또는 제목을 확인해주세요.';
} }
private async resolveJoinTargetWithoutRiotId(
params: JoinHandlerParams,
): Promise<ResolvedJoinTarget | string> {
const reference = params.matchAndRiotId.trim();
if (/^[a-f0-9]{24}$/i.test(reference)) {
return {
matchId: new mongoose.Types.ObjectId(reference),
};
}
const recruitingMatches = await this.matchService.list({
communityId: params.communityId,
status: 'recruiting',
limit: 50,
});
if (recruitingMatches.length === 0) {
return '모집 중인 내전이 없습니다.';
}
if (!reference) {
if (recruitingMatches.length === 1) {
return { matchId: recruitingMatches[0]._id };
}
return '모집 중인 내전이 여러 개입니다. !내전 일정에서 코드 또는 제목을 확인해주세요.';
}
const result = resolveRecruitingMatchReference(
reference,
recruitingMatches,
);
if (result.kind === 'matched') {
return { matchId: result.match._id };
}
if (result.kind === 'ambiguous') {
return `내전 코드 또는 제목이 여러 개와 겹칩니다 (${result.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`;
}
return '모집 중인 내전을 찾을 수 없습니다. !내전 일정에서 코드 또는 제목을 확인해주세요.';
}
private parseRiotId( private parseRiotId(
value: string, value: string,
): { gameNameWithOptionalMatchRef: string; tagLine: string } | string { ): { gameNameWithOptionalMatchRef: string; tagLine: string } | string {
@@ -201,6 +260,48 @@ export class MatchJoinHandler {
: { kind: 'not-found' }; : { kind: 'not-found' };
} }
private async resolveRegisteredRiotAccount(
params: JoinHandlerParams,
): Promise<{ user: UserDocument; riotAccount: RiotAccount } | string> {
const user = await this.dakaoUserService.findUserByKakaoTalkId({
communityId: params.communityId,
kakaoTalkId: params.senderUserId,
});
if (!user) {
return '먼저 !내전 계정등록 <닉네임>#<태그> 로 계정을 등록해주세요.';
}
const riotAccount =
user.riotAccounts.find((account) => account.isPrimary) ??
user.riotAccounts[0];
if (!riotAccount) {
return '먼저 !내전 계정등록 <닉네임>#<태그> 로 계정을 등록해주세요.';
}
return { user, riotAccount };
}
private resolvePreferredPositions(
inputPositions: Position[] | undefined,
registeredPositions: PositionPreference[],
): PositionPreference[] | string {
if (inputPositions?.length) {
return inputPositions.map((position, index) => ({
position,
priority: index + 1,
}));
}
const preferredPositions = [...(registeredPositions ?? [])]
.sort((left, right) => left.priority - right.priority)
.filter((entry) => entry.position);
if (preferredPositions.length < 2) {
return '선호포지션을 입력하거나 !내전 선호포지션등록 미드,정글 로 먼저 등록해주세요.';
}
return preferredPositions;
}
private errorReply( private errorReply(
params: JoinHandlerParams, params: JoinHandlerParams,
message: string, message: string,
@@ -48,7 +48,7 @@ export class MatchListHandler {
}, },
{ {
kind: 'text', kind: 'text',
text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n신청: !내전 신청 [코드 또는 제목] <닉네임>#<태그> <포지션1>,<포지션2>\n취소: !내전 취소 <코드 또는 제목>\n모집 중 내전이 1개면 신청 코드/제목은 생략할 수 있습니다.`, text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n선호포지션등록: !내전 선호포지션등록 미드,정글\n신청: !내전 신청 <코드> [닉네임#태그] [포지션1,포지션2]\n취소: !내전 취소 <코드>\n계정/선호포지션을 등록해두면 !내전 신청 <코드> 로 신청할 수 있습니다.`,
}, },
]; ];
} }
@@ -0,0 +1,41 @@
import mongoose from 'mongoose';
import { DakaoUserService } from '../dakao-user.service';
import { PreferredPositionRegisterHandler } from './preferred-position-register.handler';
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
describe('PreferredPositionRegisterHandler', () => {
it('registers preferred positions for abbreviated joins', async () => {
const registerPreferredPositions = jest.fn().mockResolvedValue({
preferredPositions: [
{ position: 'MID', priority: 1 },
{ position: 'JGL', priority: 2 },
],
});
const handler = new PreferredPositionRegisterHandler({
registerPreferredPositions,
} as unknown as DakaoUserService);
const segments = await handler.handle({
communityId: objectId('111111111111111111111111'),
senderUserId: 'kakao-user-1',
senderNickname: '프리리',
positions: ['MID', 'JGL'],
});
expect(registerPreferredPositions).toHaveBeenCalledWith({
communityId: objectId('111111111111111111111111'),
kakaoTalkId: 'kakao-user-1',
kakaoTalkNickname: '프리리',
positions: ['MID', 'JGL'],
});
expect(segments[1]).toMatchObject({
kind: 'text',
text: expect.stringContaining('선호 포지션 등록 완료'),
});
expect(segments[1]).toMatchObject({
kind: 'text',
text: expect.stringContaining('!내전 신청 <내전코드>'),
});
});
});
@@ -0,0 +1,54 @@
import { Injectable } from '@nestjs/common';
import mongoose from 'mongoose';
import { Position } from '../../global/database/schema';
import { DakaoSegment } from '../dakao.types';
import { DakaoUserService } from '../dakao-user.service';
const POSITION_LABELS: Record<Position, string> = {
TOP: '탑',
JGL: '정글',
MID: '미드',
ADC: '원딜',
SUP: '서포터',
};
interface PreferredPositionRegisterHandlerParams {
communityId: mongoose.Types.ObjectId;
senderUserId: string;
senderNickname: string;
positions: Position[];
}
@Injectable()
export class PreferredPositionRegisterHandler {
constructor(private readonly dakaoUserService: DakaoUserService) {}
public async handle(
params: PreferredPositionRegisterHandlerParams,
): Promise<DakaoSegment[]> {
const user = await this.dakaoUserService.registerPreferredPositions({
communityId: params.communityId,
kakaoTalkId: params.senderUserId,
kakaoTalkNickname: params.senderNickname,
positions: params.positions,
});
return [
{
kind: 'mention',
userId: params.senderUserId,
displayText: params.senderNickname,
},
{
kind: 'text',
text:
` 선호 포지션 등록 완료` +
`\n포지션: ${user.preferredPositions
.sort((left, right) => left.priority - right.priority)
.map((entry) => POSITION_LABELS[entry.position])
.join(', ')}` +
`\n이제 !내전 신청 <내전코드> 로 간단히 신청할 수 있습니다.`,
},
];
}
}
@@ -9,6 +9,10 @@ describe('parseCommand', () => {
expect(parseCommand('!내전 리스트')).toEqual({ kind: 'match-list' }); expect(parseCommand('!내전 리스트')).toEqual({ kind: 'match-list' });
}); });
it('parses match-list command (일정)', () => {
expect(parseCommand('!내전 일정')).toEqual({ kind: 'match-list' });
});
it('parses match-join command with simple riot id', () => { it('parses match-join command with simple riot id', () => {
const result = parseCommand( const result = parseCommand(
'!내전 신청 69b63bc96da18dfdb218ee8c 프리리#KR1 미드,탑', '!내전 신청 69b63bc96da18dfdb218ee8c 프리리#KR1 미드,탑',
@@ -60,6 +64,34 @@ describe('parseCommand', () => {
}); });
}); });
it('parses abbreviated match-join command with only match code', () => {
expect(parseCommand('!내전 신청 cab1')).toEqual({
kind: 'match-join',
matchAndRiotId: 'cab1',
});
});
it('parses match-join command with registered account and explicit positions', () => {
const result = parseCommand('!내전 신청 cab1 미드,서포터');
expect(result).toMatchObject({
kind: 'match-join',
matchAndRiotId: 'cab1',
});
if (result.kind === 'match-join') {
expect(result.positions?.positions).toEqual(['MID', 'SUP']);
}
});
it('parses preferred position registration command', () => {
const result = parseCommand('!내전 선호포지션등록 미드,SPT');
expect(result).toMatchObject({
kind: 'preferred-position-register',
});
if (result.kind === 'preferred-position-register') {
expect(result.positions.positions).toEqual(['MID', 'SUP']);
}
});
it('parses match-cancel command (취소)', () => { it('parses match-cancel command (취소)', () => {
expect(parseCommand('!내전 취소 69b63bc96da18dfdb218ee8c')).toEqual({ expect(parseCommand('!내전 취소 69b63bc96da18dfdb218ee8c')).toEqual({
kind: 'match-cancel', kind: 'match-cancel',
@@ -117,10 +149,13 @@ describe('parseCommand', () => {
}); });
}); });
it('throws invalid_riot_id when # missing', () => { it('allows match-join without riot id for registered-account flow', () => {
expect(() => expect(
parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 프리리 미드,탑'), parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 미드,탑'),
).toThrow(/invalid_riot_id/); ).toMatchObject({
kind: 'match-join',
matchAndRiotId: '69b63bc96da18dfdb218ee8c',
});
}); });
it('throws invalid_position for too few positions', () => { it('throws invalid_position for too few positions', () => {
@@ -1,4 +1,8 @@
import { ParsedPositions, parsePositionList } from './position.parser'; import {
ParsedPositions,
isPositionAlias,
parsePositionList,
} from './position.parser';
import { normalizeRiotIdPart } from '../riot-id.util'; import { normalizeRiotIdPart } from '../riot-id.util';
export type DakaoCommand = export type DakaoCommand =
@@ -11,11 +15,15 @@ export type DakaoCommand =
| { | {
kind: 'match-join'; kind: 'match-join';
matchAndRiotId: string; matchAndRiotId: string;
positions: ParsedPositions; positions?: ParsedPositions;
} }
| { | {
kind: 'match-cancel'; kind: 'match-cancel';
matchId: string; matchId: string;
}
| {
kind: 'preferred-position-register';
positions: ParsedPositions;
}; };
export class CommandParseError extends Error { export class CommandParseError extends Error {
@@ -53,6 +61,7 @@ export function parseCommand(rawMessage: string): DakaoCommand {
switch (subCommand) { switch (subCommand) {
case '목록': case '목록':
case '리스트': case '리스트':
case '일정':
return { kind: 'match-list' }; return { kind: 'match-list' };
case '신청': case '신청':
return parseJoinArgs(args); return parseJoinArgs(args);
@@ -61,6 +70,9 @@ export function parseCommand(rawMessage: string): DakaoCommand {
return parseCancelArgs(args); return parseCancelArgs(args);
case '계정등록': case '계정등록':
return parseAccountRegisterArgs(args); return parseAccountRegisterArgs(args);
case '선호포지션등록':
case '포지션등록':
return parsePreferredPositionRegisterArgs(args);
default: default:
throw new CommandParseError('unknown_command', subCommand); throw new CommandParseError('unknown_command', subCommand);
} }
@@ -102,41 +114,68 @@ function parseCancelArgs(args: string): DakaoCommand {
} }
function parseJoinArgs(args: string): DakaoCommand { function parseJoinArgs(args: string): DakaoCommand {
if (args.length === 0) { const trimmed = args.trim();
throw new CommandParseError('usage'); if (trimmed.length === 0) {
return { kind: 'match-join', matchAndRiotId: '' };
} }
// 마지막 토큰이 포지션 리스트(쉼표 포함). 그 앞은 내전 식별자(선택)와 라이엇 ID. // 마지막 토큰이 포지션 리스트(쉼표 포함). 그 앞은 내전 식별자(선택)와 라이엇 ID.
// 형식: [<matchId|title...>] <gameName...>#<tagLine> <pos1>,<pos2>... // 형식: [<matchId|title...>] <gameName...>#<tagLine> <pos1>,<pos2>...
// 끝에서부터 토큰을 분리해 안정적으로 파싱한다. // 끝에서부터 토큰을 분리해 안정적으로 파싱한다.
const lastSpace = args.lastIndexOf(' '); const lastSpace = trimmed.lastIndexOf(' ');
if (lastSpace === -1) { if (lastSpace === -1) {
throw new CommandParseError('usage'); const singlePartPositions = tryParseTrailingPositions(trimmed);
if (singlePartPositions) {
return {
kind: 'match-join',
matchAndRiotId: '',
positions: singlePartPositions,
};
} }
const positionPart = args.slice(lastSpace + 1).trim(); return { kind: 'match-join', matchAndRiotId: trimmed };
const matchAndRiotId = args.slice(0, lastSpace).trim();
if (positionPart.length === 0 || matchAndRiotId.length === 0) {
throw new CommandParseError('usage');
}
const hashIndex = matchAndRiotId.lastIndexOf('#');
if (hashIndex <= 0 || hashIndex === matchAndRiotId.length - 1) {
throw new CommandParseError('invalid_riot_id', matchAndRiotId);
}
let positions: ParsedPositions;
try {
positions = parsePositionList(positionPart);
} catch (err) {
throw new CommandParseError(
'invalid_position',
(err as Error)?.message ?? positionPart,
);
} }
const trailingPart = trimmed.slice(lastSpace + 1).trim();
const matchAndRiotId = trimmed.slice(0, lastSpace).trim();
const positions = tryParseTrailingPositions(trailingPart);
if (positions) {
if (!matchAndRiotId) throw new CommandParseError('usage');
return { return {
kind: 'match-join', kind: 'match-join',
matchAndRiotId, matchAndRiotId,
positions, positions,
}; };
}
return {
kind: 'match-join',
matchAndRiotId: trimmed,
};
}
function parsePreferredPositionRegisterArgs(args: string): DakaoCommand {
if (args.trim().length === 0) {
throw new CommandParseError('usage');
}
return {
kind: 'preferred-position-register',
positions: parsePositionsOrThrow(args),
};
}
function tryParseTrailingPositions(input: string): ParsedPositions | undefined {
if (!input.includes(',') && !isPositionAlias(input)) return undefined;
return parsePositionsOrThrow(input);
}
function parsePositionsOrThrow(input: string): ParsedPositions {
try {
return parsePositionList(input);
} catch (err) {
throw new CommandParseError(
'invalid_position',
(err as Error)?.message ?? input,
);
}
} }
@@ -7,7 +7,7 @@ describe('parsePositionList', () => {
}); });
it('parses english aliases case-insensitively', () => { it('parses english aliases case-insensitively', () => {
const result = parsePositionList('JGL, sup'); const result = parsePositionList('JGL, SPT');
expect(result.positions).toEqual(['JGL', 'SUP']); expect(result.positions).toEqual(['JGL', 'SUP']);
}); });
@@ -26,6 +26,8 @@ const POSITION_ALIASES: Record<string, Position> = {
// SUP // SUP
sup: 'SUP', sup: 'SUP',
supp: 'SUP', supp: 'SUP',
spt: 'SUP',
sp: 'SUP',
support: 'SUP', support: 'SUP',
서폿: 'SUP', 서폿: 'SUP',
서포터: 'SUP', 서포터: 'SUP',
@@ -71,7 +73,7 @@ export function parsePositionList(input: string): ParsedPositions {
const seen = new Set<Position>(); const seen = new Set<Position>();
for (const token of tokens) { for (const token of tokens) {
const key = token.toLowerCase().replace(/\s+/g, ''); const key = normalizePositionAlias(token);
const mapped = POSITION_ALIASES[key]; const mapped = POSITION_ALIASES[key];
if (!mapped) { if (!mapped) {
throw new PositionParseError('unknown', token); throw new PositionParseError('unknown', token);
@@ -85,3 +87,11 @@ export function parsePositionList(input: string): ParsedPositions {
return { positions }; return { positions };
} }
export function isPositionAlias(input: string): boolean {
return Boolean(POSITION_ALIASES[normalizePositionAlias(input)]);
}
function normalizePositionAlias(input: string): string {
return input.toLowerCase().replace(/\s+/g, '');
}