feat(api): handle Dakao match commands
This commit is contained in:
1 parent
3b2ac601a0
commit
b5aa58dde8
7 files changed
+1210
No files matched your search
@@ -0,0 +1,168 @@
|
|||||||
|
import { BadRequestException } from '@nestjs/common';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { MatchService } from '../../match/match.service';
|
||||||
|
import { DakaoUserService } from '../dakao-user.service';
|
||||||
|
import { MatchCancelHandler } from './match-cancel.handler';
|
||||||
|
|
||||||
|
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
|
||||||
|
|
||||||
|
function makeHandler(overrides?: {
|
||||||
|
matchService?: Partial<MatchService>;
|
||||||
|
dakaoUserService?: Partial<DakaoUserService>;
|
||||||
|
}): MatchCancelHandler {
|
||||||
|
const matchService = {
|
||||||
|
cancelJoin: jest.fn(),
|
||||||
|
list: jest.fn(),
|
||||||
|
...overrides?.matchService,
|
||||||
|
} as unknown as MatchService;
|
||||||
|
const dakaoUserService = {
|
||||||
|
findUserByKakaoTalkId: jest.fn(),
|
||||||
|
...overrides?.dakaoUserService,
|
||||||
|
} as unknown as DakaoUserService;
|
||||||
|
return new MatchCancelHandler(matchService, dakaoUserService);
|
||||||
|
}
|
||||||
|
|
||||||
|
const baseParams = {
|
||||||
|
communityId: objectId('111111111111111111111111'),
|
||||||
|
matchId: '69b63bc96da18dfdb218ee8c',
|
||||||
|
senderUserId: 'kakao-user-1',
|
||||||
|
senderNickname: '프리리',
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('MatchCancelHandler', () => {
|
||||||
|
it('rejects unknown match reference without cancelling', async () => {
|
||||||
|
const cancelJoin = jest.fn();
|
||||||
|
const handler = makeHandler({
|
||||||
|
matchService: {
|
||||||
|
cancelJoin,
|
||||||
|
list: jest.fn().mockResolvedValue([]),
|
||||||
|
} as Partial<MatchService>,
|
||||||
|
dakaoUserService: {
|
||||||
|
findUserByKakaoTalkId: jest.fn().mockResolvedValue({
|
||||||
|
_id: objectId('222222222222222222222222'),
|
||||||
|
}),
|
||||||
|
} as Partial<DakaoUserService>,
|
||||||
|
});
|
||||||
|
|
||||||
|
const segments = await handler.handle({
|
||||||
|
...baseParams,
|
||||||
|
matchId: 'not-an-id',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(cancelJoin).not.toHaveBeenCalled();
|
||||||
|
expect(segments).toEqual([
|
||||||
|
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
|
||||||
|
expect.objectContaining({
|
||||||
|
kind: 'text',
|
||||||
|
text: expect.stringContaining('모집 중인 내전이 없습니다'),
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('replies with success for registered user cancellation', async () => {
|
||||||
|
const cancelJoin = jest.fn().mockResolvedValue({
|
||||||
|
title: '저녁 내전',
|
||||||
|
participants: [{}, {}],
|
||||||
|
maxParticipants: 10,
|
||||||
|
});
|
||||||
|
const findUserByKakaoTalkId = jest.fn().mockResolvedValue({
|
||||||
|
_id: objectId('222222222222222222222222'),
|
||||||
|
});
|
||||||
|
const handler = makeHandler({
|
||||||
|
matchService: { cancelJoin } as Partial<MatchService>,
|
||||||
|
dakaoUserService: {
|
||||||
|
findUserByKakaoTalkId,
|
||||||
|
} as Partial<DakaoUserService>,
|
||||||
|
});
|
||||||
|
|
||||||
|
const segments = await handler.handle(baseParams);
|
||||||
|
|
||||||
|
expect(findUserByKakaoTalkId).toHaveBeenCalledWith({
|
||||||
|
communityId: baseParams.communityId,
|
||||||
|
kakaoTalkId: 'kakao-user-1',
|
||||||
|
});
|
||||||
|
expect(cancelJoin).toHaveBeenCalledWith({
|
||||||
|
matchId: expect.any(mongoose.Types.ObjectId),
|
||||||
|
userId: expect.any(mongoose.Types.ObjectId),
|
||||||
|
});
|
||||||
|
expect(segments[1]).toMatchObject({
|
||||||
|
kind: 'text',
|
||||||
|
text: expect.stringContaining('참가 취소 완료 (2/10)'),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolves cancellation by short code', async () => {
|
||||||
|
const matchId = objectId('333333333333333333333333');
|
||||||
|
const cancelJoin = jest.fn().mockResolvedValue({
|
||||||
|
title: '저녁 내전',
|
||||||
|
participants: [{}, {}],
|
||||||
|
maxParticipants: 10,
|
||||||
|
});
|
||||||
|
const findUserByKakaoTalkId = jest.fn().mockResolvedValue({
|
||||||
|
_id: objectId('222222222222222222222222'),
|
||||||
|
});
|
||||||
|
const handler = makeHandler({
|
||||||
|
matchService: {
|
||||||
|
cancelJoin,
|
||||||
|
list: jest.fn().mockResolvedValue([
|
||||||
|
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
||||||
|
]),
|
||||||
|
} as Partial<MatchService>,
|
||||||
|
dakaoUserService: {
|
||||||
|
findUserByKakaoTalkId,
|
||||||
|
} as Partial<DakaoUserService>,
|
||||||
|
});
|
||||||
|
|
||||||
|
await handler.handle({
|
||||||
|
...baseParams,
|
||||||
|
matchId: 'AB12',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(cancelJoin).toHaveBeenCalledWith({
|
||||||
|
matchId,
|
||||||
|
userId: expect.any(mongoose.Types.ObjectId),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('asks unregistered user to register first', async () => {
|
||||||
|
const cancelJoin = jest.fn();
|
||||||
|
const handler = makeHandler({
|
||||||
|
matchService: { cancelJoin } as Partial<MatchService>,
|
||||||
|
dakaoUserService: {
|
||||||
|
findUserByKakaoTalkId: jest.fn().mockResolvedValue(null),
|
||||||
|
} as Partial<DakaoUserService>,
|
||||||
|
});
|
||||||
|
|
||||||
|
const segments = await handler.handle(baseParams);
|
||||||
|
|
||||||
|
expect(cancelJoin).not.toHaveBeenCalled();
|
||||||
|
expect(segments[1]).toMatchObject({
|
||||||
|
kind: 'text',
|
||||||
|
text: expect.stringContaining('계정을 등록'),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('translates not-joined cancellation errors', async () => {
|
||||||
|
const handler = makeHandler({
|
||||||
|
matchService: {
|
||||||
|
cancelJoin: jest
|
||||||
|
.fn()
|
||||||
|
.mockRejectedValue(
|
||||||
|
new BadRequestException('User has not joined this match.'),
|
||||||
|
),
|
||||||
|
} as Partial<MatchService>,
|
||||||
|
dakaoUserService: {
|
||||||
|
findUserByKakaoTalkId: jest.fn().mockResolvedValue({
|
||||||
|
_id: objectId('222222222222222222222222'),
|
||||||
|
}),
|
||||||
|
} as Partial<DakaoUserService>,
|
||||||
|
});
|
||||||
|
|
||||||
|
const segments = await handler.handle(baseParams);
|
||||||
|
|
||||||
|
expect(segments[1]).toMatchObject({
|
||||||
|
kind: 'text',
|
||||||
|
text: expect.stringContaining('신청한 내전이 아닙니다'),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { MatchService } from '../../match/match.service';
|
||||||
|
import { DakaoSegment } from '../dakao.types';
|
||||||
|
import { DakaoUserService } from '../dakao-user.service';
|
||||||
|
import { resolveRecruitingMatchReference } from './match-reference.util';
|
||||||
|
|
||||||
|
interface CancelHandlerParams {
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
matchId: string;
|
||||||
|
senderUserId: string; // kakaoTalkId
|
||||||
|
senderNickname: string; // kakaoTalkNickname
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MatchCancelHandler {
|
||||||
|
constructor(
|
||||||
|
private readonly matchService: MatchService,
|
||||||
|
private readonly dakaoUserService: DakaoUserService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public async handle(params: CancelHandlerParams): Promise<DakaoSegment[]> {
|
||||||
|
const user = await this.dakaoUserService.findUserByKakaoTalkId({
|
||||||
|
communityId: params.communityId,
|
||||||
|
kakaoTalkId: params.senderUserId,
|
||||||
|
});
|
||||||
|
if (!user) {
|
||||||
|
return this.errorReply(
|
||||||
|
params,
|
||||||
|
'먼저 !내전 계정등록 <닉네임>#<태그> 로 계정을 등록해주세요.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const matchTarget = await this.resolveCancelTarget(params);
|
||||||
|
if (typeof matchTarget === 'string') {
|
||||||
|
return this.errorReply(params, matchTarget);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const match = await this.matchService.cancelJoin({
|
||||||
|
matchId: matchTarget,
|
||||||
|
userId: user._id,
|
||||||
|
});
|
||||||
|
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
kind: 'mention',
|
||||||
|
userId: params.senderUserId,
|
||||||
|
displayText: params.senderNickname,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: 'text',
|
||||||
|
text:
|
||||||
|
` 참가 취소 완료 (${match.participants.length}/${match.maxParticipants})` +
|
||||||
|
`\n내전: ${match.title}`,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof NotFoundException) {
|
||||||
|
return this.errorReply(params, '내전을 찾을 수 없습니다.');
|
||||||
|
}
|
||||||
|
if (err instanceof BadRequestException) {
|
||||||
|
return this.errorReply(params, this.translateBadRequest(err.message));
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async resolveCancelTarget(
|
||||||
|
params: CancelHandlerParams,
|
||||||
|
): Promise<mongoose.Types.ObjectId | string> {
|
||||||
|
if (mongoose.isValidObjectId(params.matchId)) {
|
||||||
|
return new mongoose.Types.ObjectId(params.matchId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const recruitingMatches = await this.matchService.list({
|
||||||
|
communityId: params.communityId,
|
||||||
|
status: 'recruiting',
|
||||||
|
limit: 50,
|
||||||
|
});
|
||||||
|
if (recruitingMatches.length === 0) {
|
||||||
|
return '모집 중인 내전이 없습니다.';
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = resolveRecruitingMatchReference(
|
||||||
|
params.matchId,
|
||||||
|
recruitingMatches,
|
||||||
|
);
|
||||||
|
if (result.kind === 'matched') {
|
||||||
|
return result.match._id;
|
||||||
|
}
|
||||||
|
if (result.kind === 'ambiguous') {
|
||||||
|
return `내전 코드 또는 제목이 여러 개와 겹칩니다 (${result.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`;
|
||||||
|
}
|
||||||
|
return '모집 중인 내전을 찾을 수 없습니다. !내전 리스트에서 코드 또는 제목을 확인해주세요.';
|
||||||
|
}
|
||||||
|
|
||||||
|
private errorReply(
|
||||||
|
params: CancelHandlerParams,
|
||||||
|
message: string,
|
||||||
|
): DakaoSegment[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
kind: 'mention',
|
||||||
|
userId: params.senderUserId,
|
||||||
|
displayText: params.senderNickname,
|
||||||
|
},
|
||||||
|
{ kind: 'text', text: ` ${message}` },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private translateBadRequest(raw: string): string {
|
||||||
|
if (raw.includes('different communities')) {
|
||||||
|
return '이 내전은 현재 채팅방의 커뮤니티 소속이 아닙니다.';
|
||||||
|
}
|
||||||
|
if (raw.includes('not recruiting')) {
|
||||||
|
return '모집 중인 내전만 참가 취소할 수 있습니다.';
|
||||||
|
}
|
||||||
|
if (raw.includes('has not joined')) return '신청한 내전이 아닙니다.';
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,389 @@
|
|||||||
|
import { BadRequestException } from '@nestjs/common';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { MatchService } from '../../match/match.service';
|
||||||
|
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
|
||||||
|
import { MatchJoinHandler } from './match-join.handler';
|
||||||
|
|
||||||
|
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
|
||||||
|
|
||||||
|
function makeHandler(overrides?: {
|
||||||
|
matchService?: Partial<MatchService>;
|
||||||
|
dakaoUserService?: Partial<DakaoUserService>;
|
||||||
|
}): MatchJoinHandler {
|
||||||
|
const matchService = {
|
||||||
|
join: jest.fn(),
|
||||||
|
list: jest.fn(),
|
||||||
|
...overrides?.matchService,
|
||||||
|
} as unknown as MatchService;
|
||||||
|
const dakaoUserService = {
|
||||||
|
resolveRiotAccount: jest.fn(),
|
||||||
|
findUserByKakaoTalkId: jest.fn(),
|
||||||
|
...overrides?.dakaoUserService,
|
||||||
|
} as unknown as DakaoUserService;
|
||||||
|
return new MatchJoinHandler(matchService, dakaoUserService);
|
||||||
|
}
|
||||||
|
|
||||||
|
const baseParams = {
|
||||||
|
communityId: objectId('111111111111111111111111'),
|
||||||
|
matchAndRiotId: '69b63bc96da18dfdb218ee8c 프리리#KR1',
|
||||||
|
senderUserId: 'kakao-user-1',
|
||||||
|
senderNickname: '프리리',
|
||||||
|
positions: ['MID', 'TOP'] as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('MatchJoinHandler', () => {
|
||||||
|
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<MatchService>,
|
||||||
|
dakaoUserService: {
|
||||||
|
resolveRiotAccount,
|
||||||
|
} as Partial<DakaoUserService>,
|
||||||
|
});
|
||||||
|
const segments = await handler.handle({
|
||||||
|
...baseParams,
|
||||||
|
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('코드 또는 제목'),
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('replies with success and uses input position priority', async () => {
|
||||||
|
const join = jest.fn().mockResolvedValue({
|
||||||
|
title: '저녁 내전',
|
||||||
|
participants: [{}, {}, {}],
|
||||||
|
maxParticipants: 10,
|
||||||
|
});
|
||||||
|
const resolveRiotAccount = jest.fn().mockResolvedValue({
|
||||||
|
user: { _id: objectId('222222222222222222222222') },
|
||||||
|
riotAccount: { puuid: 'puuid-1', gameName: '프리리', tagLine: 'KR1' },
|
||||||
|
});
|
||||||
|
const handler = makeHandler({
|
||||||
|
matchService: { join } as Partial<MatchService>,
|
||||||
|
dakaoUserService: {
|
||||||
|
resolveRiotAccount,
|
||||||
|
} as Partial<DakaoUserService>,
|
||||||
|
});
|
||||||
|
|
||||||
|
const segments = await handler.handle({
|
||||||
|
...baseParams,
|
||||||
|
positions: [...baseParams.positions],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(resolveRiotAccount).toHaveBeenCalledWith({
|
||||||
|
communityId: baseParams.communityId,
|
||||||
|
kakaoTalkId: 'kakao-user-1',
|
||||||
|
kakaoTalkNickname: '프리리',
|
||||||
|
gameName: '프리리',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
});
|
||||||
|
expect(join).toHaveBeenCalledWith({
|
||||||
|
matchId: expect.any(mongoose.Types.ObjectId),
|
||||||
|
userId: expect.any(mongoose.Types.ObjectId),
|
||||||
|
preferredPositions: [
|
||||||
|
{ position: 'MID', priority: 1 },
|
||||||
|
{ position: 'TOP', priority: 2 },
|
||||||
|
],
|
||||||
|
riotPuuid: 'puuid-1',
|
||||||
|
});
|
||||||
|
expect(segments[1]).toMatchObject({
|
||||||
|
kind: 'text',
|
||||||
|
text: expect.stringContaining('신청 완료 (3/10)'),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
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('resolves a recruiting match by short code', 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: '저녁 내전', shortCode: 'AB12' },
|
||||||
|
{
|
||||||
|
_id: objectId('444444444444444444444444'),
|
||||||
|
title: '심야 내전',
|
||||||
|
shortCode: 'CD34',
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
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: 'AB12 프리리#KR1',
|
||||||
|
positions: [...baseParams.positions],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(join).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
matchId,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
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 () => {
|
||||||
|
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 () => {
|
||||||
|
const handler = makeHandler({
|
||||||
|
dakaoUserService: {
|
||||||
|
resolveRiotAccount: jest
|
||||||
|
.fn()
|
||||||
|
.mockRejectedValue(
|
||||||
|
new DakaoUserError('riot_account_not_found', '프리리#KR1'),
|
||||||
|
),
|
||||||
|
} as Partial<DakaoUserService>,
|
||||||
|
});
|
||||||
|
const segments = await handler.handle({
|
||||||
|
...baseParams,
|
||||||
|
positions: [...baseParams.positions],
|
||||||
|
});
|
||||||
|
expect(segments[1]).toMatchObject({
|
||||||
|
kind: 'text',
|
||||||
|
text: expect.stringContaining('라이엇 계정을 찾을 수 없습니다'),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('translates match BadRequest into korean', async () => {
|
||||||
|
const handler = makeHandler({
|
||||||
|
matchService: {
|
||||||
|
join: jest
|
||||||
|
.fn()
|
||||||
|
.mockRejectedValue(new BadRequestException('Match is full.')),
|
||||||
|
} as Partial<MatchService>,
|
||||||
|
dakaoUserService: {
|
||||||
|
resolveRiotAccount: jest.fn().mockResolvedValue({
|
||||||
|
user: { _id: objectId('222222222222222222222222') },
|
||||||
|
riotAccount: { puuid: 'p', gameName: 'g', tagLine: 't' },
|
||||||
|
}),
|
||||||
|
} as Partial<DakaoUserService>,
|
||||||
|
});
|
||||||
|
const segments = await handler.handle({
|
||||||
|
...baseParams,
|
||||||
|
positions: [...baseParams.positions],
|
||||||
|
});
|
||||||
|
expect(segments[1]).toMatchObject({
|
||||||
|
kind: 'text',
|
||||||
|
text: expect.stringContaining('정원이 가득'),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,352 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { MatchService } from '../../match/match.service';
|
||||||
|
import {
|
||||||
|
MatchDocument,
|
||||||
|
Position,
|
||||||
|
PositionPreference,
|
||||||
|
RiotAccount,
|
||||||
|
UserDocument,
|
||||||
|
} from '../../global/database/schema';
|
||||||
|
import { DakaoSegment } from '../dakao.types';
|
||||||
|
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
|
||||||
|
import { normalizeRiotIdPart } from '../riot-id.util';
|
||||||
|
import { resolveRecruitingMatchReference } from './match-reference.util';
|
||||||
|
|
||||||
|
interface JoinHandlerParams {
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
matchAndRiotId: string;
|
||||||
|
senderUserId: string; // kakaoTalkId
|
||||||
|
senderNickname: string; // kakaoTalkNickname
|
||||||
|
positions?: Position[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ResolvedJoinTarget {
|
||||||
|
matchId: mongoose.Types.ObjectId;
|
||||||
|
gameName?: string;
|
||||||
|
tagLine?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MatchJoinHandler {
|
||||||
|
constructor(
|
||||||
|
private readonly matchService: MatchService,
|
||||||
|
private readonly dakaoUserService: DakaoUserService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public async handle(params: JoinHandlerParams): Promise<DakaoSegment[]> {
|
||||||
|
const joinTarget = await this.resolveJoinTarget(params);
|
||||||
|
if (typeof joinTarget === 'string') {
|
||||||
|
return this.errorReply(params, joinTarget);
|
||||||
|
}
|
||||||
|
|
||||||
|
let resolved:
|
||||||
|
| { user: UserDocument; riotAccount: RiotAccount }
|
||||||
|
| string;
|
||||||
|
try {
|
||||||
|
resolved =
|
||||||
|
joinTarget.gameName && joinTarget.tagLine
|
||||||
|
? await this.dakaoUserService.resolveRiotAccount({
|
||||||
|
communityId: params.communityId,
|
||||||
|
kakaoTalkId: params.senderUserId,
|
||||||
|
kakaoTalkNickname: params.senderNickname,
|
||||||
|
gameName: joinTarget.gameName,
|
||||||
|
tagLine: joinTarget.tagLine,
|
||||||
|
})
|
||||||
|
: await this.resolveRegisteredRiotAccount(params);
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof DakaoUserError) {
|
||||||
|
return this.errorReply(params, this.translateUserError(err));
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
if (typeof resolved === 'string') {
|
||||||
|
return this.errorReply(params, resolved);
|
||||||
|
}
|
||||||
|
|
||||||
|
const preferredPositions = this.resolvePreferredPositions(
|
||||||
|
params.positions,
|
||||||
|
resolved.user.preferredPositions,
|
||||||
|
);
|
||||||
|
if (typeof preferredPositions === 'string') {
|
||||||
|
return this.errorReply(params, preferredPositions);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const match = await this.matchService.join({
|
||||||
|
matchId: joinTarget.matchId,
|
||||||
|
userId: resolved.user._id,
|
||||||
|
preferredPositions,
|
||||||
|
riotPuuid: resolved.riotAccount.puuid,
|
||||||
|
});
|
||||||
|
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
kind: 'mention',
|
||||||
|
userId: params.senderUserId,
|
||||||
|
displayText: params.senderNickname,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: 'text',
|
||||||
|
text:
|
||||||
|
` 신청 완료 (${match.participants.length}/${match.maxParticipants})` +
|
||||||
|
`\n내전: ${match.title}` +
|
||||||
|
`\n계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}` +
|
||||||
|
`\n포지션: ${preferredPositions
|
||||||
|
.map((entry) => entry.position)
|
||||||
|
.join(', ')}`,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof NotFoundException) {
|
||||||
|
return this.errorReply(params, '내전을 찾을 수 없습니다.');
|
||||||
|
}
|
||||||
|
if (err instanceof BadRequestException) {
|
||||||
|
return this.errorReply(params, this.translateBadRequest(err.message));
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async resolveJoinTarget(
|
||||||
|
params: JoinHandlerParams,
|
||||||
|
): Promise<ResolvedJoinTarget | string> {
|
||||||
|
if (!params.matchAndRiotId.includes('#')) {
|
||||||
|
return this.resolveJoinTargetWithoutRiotId(params);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 '모집 중인 내전이 없습니다.';
|
||||||
|
}
|
||||||
|
|
||||||
|
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를 사용해주세요.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (recruitingMatches.length === 1) {
|
||||||
|
return {
|
||||||
|
matchId: recruitingMatches[0]._id,
|
||||||
|
gameName: riotId.gameNameWithOptionalMatchRef,
|
||||||
|
tagLine: riotId.tagLine,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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(
|
||||||
|
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 = resolveRecruitingMatchReference(
|
||||||
|
matchTitlePrefix,
|
||||||
|
matches,
|
||||||
|
);
|
||||||
|
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 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(
|
||||||
|
params: JoinHandlerParams,
|
||||||
|
message: string,
|
||||||
|
): DakaoSegment[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
kind: 'mention',
|
||||||
|
userId: params.senderUserId,
|
||||||
|
displayText: params.senderNickname,
|
||||||
|
},
|
||||||
|
{ kind: 'text', text: ` ${message}` },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private translateUserError(err: DakaoUserError): string {
|
||||||
|
switch (err.code) {
|
||||||
|
case 'invalid_project_id':
|
||||||
|
return '커뮤니티 식별자가 올바르지 않습니다.';
|
||||||
|
case 'community_not_found':
|
||||||
|
return '연결된 커뮤니티를 찾을 수 없습니다.';
|
||||||
|
case 'riot_account_not_found':
|
||||||
|
return `라이엇 계정을 찾을 수 없습니다 (${err.detail ?? ''}).`;
|
||||||
|
case 'riot_account_already_registered':
|
||||||
|
return `이미 등록된 라이엇 계정이 있습니다 (${err.detail ?? ''}).`;
|
||||||
|
case 'riot_account_conflict':
|
||||||
|
return `이미 다른 사용자가 등록한 라이엇 계정입니다 (${err.detail ?? ''}).`;
|
||||||
|
case 'riot_account_lookup_failed':
|
||||||
|
return '라이엇 계정 조회 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private translateBadRequest(raw: string): string {
|
||||||
|
if (raw.includes('different communities'))
|
||||||
|
return '이 내전은 현재 채팅방의 커뮤니티 소속이 아닙니다.';
|
||||||
|
if (raw.includes('not recruiting')) return '모집 중인 내전이 아닙니다.';
|
||||||
|
if (raw.includes('full')) return '정원이 가득 찼습니다.';
|
||||||
|
if (raw.includes('already joined')) return '이미 신청한 내전입니다.';
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { MatchService } from '../../match/match.service';
|
||||||
|
import { MatchListHandler } from './match-list.handler';
|
||||||
|
|
||||||
|
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
|
||||||
|
|
||||||
|
describe('MatchListHandler', () => {
|
||||||
|
it('prints short codes and compact KST dates', async () => {
|
||||||
|
const match = {
|
||||||
|
_id: objectId('333333333333333333333333'),
|
||||||
|
title: '토요 내전',
|
||||||
|
shortCode: 'AB12',
|
||||||
|
participants: [{}, {}],
|
||||||
|
maxParticipants: 10,
|
||||||
|
scheduledAt: new Date('2026-05-02T10:30:00.000Z'),
|
||||||
|
};
|
||||||
|
const matchService = {
|
||||||
|
list: jest.fn().mockResolvedValue([match]),
|
||||||
|
ensureShortCode: jest.fn().mockResolvedValue(match),
|
||||||
|
} as unknown as MatchService;
|
||||||
|
const handler = new MatchListHandler(matchService);
|
||||||
|
|
||||||
|
const segments = await handler.handle({
|
||||||
|
communityId: objectId('111111111111111111111111'),
|
||||||
|
senderUserId: 'kakao-user-1',
|
||||||
|
senderNickname: '프리리',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(matchService.ensureShortCode).toHaveBeenCalledWith(match);
|
||||||
|
expect(segments[1]).toMatchObject({
|
||||||
|
kind: 'text',
|
||||||
|
text: expect.stringContaining('토요 내전 (2/10) 5/2 19:30'),
|
||||||
|
});
|
||||||
|
expect(segments[1]).toMatchObject({
|
||||||
|
kind: 'text',
|
||||||
|
text: expect.stringContaining('코드: AB12'),
|
||||||
|
});
|
||||||
|
expect(segments[1]).toMatchObject({
|
||||||
|
kind: 'text',
|
||||||
|
text: expect.not.stringContaining('2026-05-02'),
|
||||||
|
});
|
||||||
|
expect(segments[1]).toMatchObject({
|
||||||
|
kind: 'text',
|
||||||
|
text: expect.not.stringContaining('ID:'),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { MatchService } from '../../match/match.service';
|
||||||
|
import { DakaoSegment } from '../dakao.types';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MatchListHandler {
|
||||||
|
constructor(private readonly matchService: MatchService) {}
|
||||||
|
|
||||||
|
public async handle(params: {
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
senderUserId: string;
|
||||||
|
senderNickname: string;
|
||||||
|
}): Promise<DakaoSegment[]> {
|
||||||
|
const matches = await this.matchService.list({
|
||||||
|
communityId: params.communityId,
|
||||||
|
status: 'recruiting',
|
||||||
|
limit: 10,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (matches.length === 0) {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
kind: 'mention',
|
||||||
|
userId: params.senderUserId,
|
||||||
|
displayText: params.senderNickname,
|
||||||
|
},
|
||||||
|
{ kind: 'text', text: ' 모집 중인 내전이 없습니다.' },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
const matchesWithCodes = await Promise.all(
|
||||||
|
matches.map((match) => this.matchService.ensureShortCode(match)),
|
||||||
|
);
|
||||||
|
|
||||||
|
const lines = matchesWithCodes.map((m, i) => {
|
||||||
|
const filled = m.participants.length;
|
||||||
|
const cap = m.maxParticipants;
|
||||||
|
const time = formatScheduledAt(m.scheduledAt);
|
||||||
|
return `\n${i + 1}. ${m.title} (${filled}/${cap}) ${time}\n 코드: ${m.shortCode}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
kind: 'mention',
|
||||||
|
userId: params.senderUserId,
|
||||||
|
displayText: params.senderNickname,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: 'text',
|
||||||
|
text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n선호포지션등록: !내전 선호포지션등록 미드,정글\n신청: !내전 신청 <코드> [닉네임#태그] [포지션1,포지션2]\n취소: !내전 취소 <코드>\n계정/선호포지션을 등록해두면 !내전 신청 <코드> 로 신청할 수 있습니다.`,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatScheduledAt(date: Date): string {
|
||||||
|
// M/D HH:mm (KST 표기)
|
||||||
|
const kst = new Date(date.getTime() + 9 * 60 * 60 * 1000);
|
||||||
|
const month = kst.getUTCMonth() + 1;
|
||||||
|
const day = kst.getUTCDate();
|
||||||
|
const hh = String(kst.getUTCHours()).padStart(2, '0');
|
||||||
|
const mi = String(kst.getUTCMinutes()).padStart(2, '0');
|
||||||
|
return `${month}/${day} ${hh}:${mi}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import type { MatchDocument } from '../../global/database/schema';
|
||||||
|
|
||||||
|
export type MatchReferenceResult =
|
||||||
|
| { kind: 'matched'; match: MatchDocument }
|
||||||
|
| { kind: 'ambiguous'; titles: string[] }
|
||||||
|
| { kind: 'not-found' };
|
||||||
|
|
||||||
|
export function resolveRecruitingMatchReference(
|
||||||
|
reference: string,
|
||||||
|
matches: MatchDocument[],
|
||||||
|
): MatchReferenceResult {
|
||||||
|
const normalizedCode = normalizeShortCode(reference);
|
||||||
|
const codeMatches = matches.filter(
|
||||||
|
(match) =>
|
||||||
|
match.shortCode && normalizeShortCode(match.shortCode) === normalizedCode,
|
||||||
|
);
|
||||||
|
if (codeMatches.length === 1) {
|
||||||
|
return { kind: 'matched', match: codeMatches[0] };
|
||||||
|
}
|
||||||
|
if (codeMatches.length > 1) {
|
||||||
|
return {
|
||||||
|
kind: 'ambiguous',
|
||||||
|
titles: codeMatches.map((match) => match.title),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedReference = normalizeLookup(reference);
|
||||||
|
const exactMatches = matches.filter(
|
||||||
|
(match) => normalizeLookup(match.title) === normalizedReference,
|
||||||
|
);
|
||||||
|
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(normalizedReference),
|
||||||
|
);
|
||||||
|
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' };
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLookup(value: string): string {
|
||||||
|
return value.normalize('NFC').trim().replace(/\s+/g, ' ').toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeShortCode(value: string): string {
|
||||||
|
return value.normalize('NFC').trim().replace(/\s+/g, '').toUpperCase();
|
||||||
|
}
|
||||||
Reference in new issue
Block a user