.
This commit is contained in:
1 parent
feeb30c6a9
commit
5286e4d1ed
13 files changed
+341
-79
No files matched your search
@@ -12,6 +12,7 @@ function makeHandler(overrides?: {
|
|||||||
}): MatchCancelHandler {
|
}): MatchCancelHandler {
|
||||||
const matchService = {
|
const matchService = {
|
||||||
cancelJoin: jest.fn(),
|
cancelJoin: jest.fn(),
|
||||||
|
list: jest.fn(),
|
||||||
...overrides?.matchService,
|
...overrides?.matchService,
|
||||||
} as unknown as MatchService;
|
} as unknown as MatchService;
|
||||||
const dakaoUserService = {
|
const dakaoUserService = {
|
||||||
@@ -29,13 +30,17 @@ const baseParams = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
describe('MatchCancelHandler', () => {
|
describe('MatchCancelHandler', () => {
|
||||||
it('rejects invalid match id without touching services', async () => {
|
it('rejects unknown match reference without cancelling', async () => {
|
||||||
const findUserByKakaoTalkId = jest.fn();
|
|
||||||
const cancelJoin = jest.fn();
|
const cancelJoin = jest.fn();
|
||||||
const handler = makeHandler({
|
const handler = makeHandler({
|
||||||
matchService: { cancelJoin } as Partial<MatchService>,
|
matchService: {
|
||||||
|
cancelJoin,
|
||||||
|
list: jest.fn().mockResolvedValue([]),
|
||||||
|
} as Partial<MatchService>,
|
||||||
dakaoUserService: {
|
dakaoUserService: {
|
||||||
findUserByKakaoTalkId,
|
findUserByKakaoTalkId: jest.fn().mockResolvedValue({
|
||||||
|
_id: objectId('222222222222222222222222'),
|
||||||
|
}),
|
||||||
} as Partial<DakaoUserService>,
|
} as Partial<DakaoUserService>,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -44,13 +49,12 @@ describe('MatchCancelHandler', () => {
|
|||||||
matchId: 'not-an-id',
|
matchId: 'not-an-id',
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(findUserByKakaoTalkId).not.toHaveBeenCalled();
|
|
||||||
expect(cancelJoin).not.toHaveBeenCalled();
|
expect(cancelJoin).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('모집 중인 내전이 없습니다'),
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
@@ -87,6 +91,39 @@ describe('MatchCancelHandler', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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 () => {
|
it('asks unregistered user to register first', async () => {
|
||||||
const cancelJoin = jest.fn();
|
const cancelJoin = jest.fn();
|
||||||
const handler = makeHandler({
|
const handler = makeHandler({
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import mongoose from 'mongoose';
|
|||||||
import { MatchService } from '../../match/match.service';
|
import { MatchService } from '../../match/match.service';
|
||||||
import { DakaoSegment } from '../dakao.types';
|
import { DakaoSegment } from '../dakao.types';
|
||||||
import { DakaoUserService } from '../dakao-user.service';
|
import { DakaoUserService } from '../dakao-user.service';
|
||||||
|
import { resolveRecruitingMatchReference } from './match-reference.util';
|
||||||
|
|
||||||
interface CancelHandlerParams {
|
interface CancelHandlerParams {
|
||||||
communityId: mongoose.Types.ObjectId;
|
communityId: mongoose.Types.ObjectId;
|
||||||
@@ -23,11 +24,6 @@ export class MatchCancelHandler {
|
|||||||
) {}
|
) {}
|
||||||
|
|
||||||
public async handle(params: CancelHandlerParams): Promise<DakaoSegment[]> {
|
public async handle(params: CancelHandlerParams): Promise<DakaoSegment[]> {
|
||||||
if (!mongoose.isValidObjectId(params.matchId)) {
|
|
||||||
return this.errorReply(params, '유효하지 않은 내전 ID 입니다.');
|
|
||||||
}
|
|
||||||
const matchObjectId = new mongoose.Types.ObjectId(params.matchId);
|
|
||||||
|
|
||||||
const user = await this.dakaoUserService.findUserByKakaoTalkId({
|
const user = await this.dakaoUserService.findUserByKakaoTalkId({
|
||||||
communityId: params.communityId,
|
communityId: params.communityId,
|
||||||
kakaoTalkId: params.senderUserId,
|
kakaoTalkId: params.senderUserId,
|
||||||
@@ -39,9 +35,14 @@ export class MatchCancelHandler {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const matchTarget = await this.resolveCancelTarget(params);
|
||||||
|
if (typeof matchTarget === 'string') {
|
||||||
|
return this.errorReply(params, matchTarget);
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const match = await this.matchService.cancelJoin({
|
const match = await this.matchService.cancelJoin({
|
||||||
matchId: matchObjectId,
|
matchId: matchTarget,
|
||||||
userId: user._id,
|
userId: user._id,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -69,6 +70,35 @@ export class MatchCancelHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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(
|
private errorReply(
|
||||||
params: CancelHandlerParams,
|
params: CancelHandlerParams,
|
||||||
message: string,
|
message: string,
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ describe('MatchJoinHandler', () => {
|
|||||||
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('코드 또는 제목'),
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
@@ -178,6 +178,46 @@ describe('MatchJoinHandler', () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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('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({
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
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';
|
import { normalizeRiotIdPart } from '../riot-id.util';
|
||||||
|
import { resolveRecruitingMatchReference } from './match-reference.util';
|
||||||
|
|
||||||
interface JoinHandlerParams {
|
interface JoinHandlerParams {
|
||||||
communityId: mongoose.Types.ObjectId;
|
communityId: mongoose.Types.ObjectId;
|
||||||
@@ -145,10 +146,10 @@ export class MatchJoinHandler {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (titleTarget.kind === 'ambiguous') {
|
if (titleTarget.kind === 'ambiguous') {
|
||||||
return `내전 제목이 여러 개와 겹칩니다 (${titleTarget.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`;
|
return `내전 코드 또는 제목이 여러 개와 겹칩니다 (${titleTarget.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`;
|
||||||
}
|
}
|
||||||
|
|
||||||
return '모집 중인 내전을 찾을 수 없습니다. !내전 리스트에서 ID 또는 제목을 확인해주세요.';
|
return '모집 중인 내전을 찾을 수 없습니다. !내전 리스트에서 코드 또는 제목을 확인해주세요.';
|
||||||
}
|
}
|
||||||
|
|
||||||
private parseRiotId(
|
private parseRiotId(
|
||||||
@@ -183,7 +184,10 @@ export class MatchJoinHandler {
|
|||||||
const gameName = normalizeRiotIdPart(value.slice(splitAt + 1));
|
const gameName = normalizeRiotIdPart(value.slice(splitAt + 1));
|
||||||
if (!matchTitlePrefix || !gameName) continue;
|
if (!matchTitlePrefix || !gameName) continue;
|
||||||
|
|
||||||
const result = this.findByTitlePrefix(matches, matchTitlePrefix);
|
const result = resolveRecruitingMatchReference(
|
||||||
|
matchTitlePrefix,
|
||||||
|
matches,
|
||||||
|
);
|
||||||
if (result.kind === 'matched') {
|
if (result.kind === 'matched') {
|
||||||
return { kind: 'matched', match: result.match, gameName };
|
return { kind: 'matched', match: result.match, gameName };
|
||||||
}
|
}
|
||||||
@@ -197,42 +201,6 @@ export class MatchJoinHandler {
|
|||||||
: { kind: 'not-found' };
|
: { 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,
|
||||||
@@ -281,7 +249,3 @@ function splitPositionsFromRight(value: string): number[] {
|
|||||||
}
|
}
|
||||||
return positions;
|
return positions;
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeLookup(value: string): string {
|
|
||||||
return value.normalize('NFC').trim().replace(/\s+/g, ' ').toLowerCase();
|
|
||||||
}
|
|
||||||
@@ -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:'),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -29,12 +29,15 @@ export class MatchListHandler {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
const lines = matches.map((m, i) => {
|
const matchesWithCodes = await Promise.all(
|
||||||
const id = (m._id as mongoose.Types.ObjectId).toString();
|
matches.map((match) => this.matchService.ensureShortCode(match)),
|
||||||
|
);
|
||||||
|
|
||||||
|
const lines = matchesWithCodes.map((m, i) => {
|
||||||
const filled = m.participants.length;
|
const filled = m.participants.length;
|
||||||
const cap = m.maxParticipants;
|
const cap = m.maxParticipants;
|
||||||
const time = formatScheduledAt(m.scheduledAt);
|
const time = formatScheduledAt(m.scheduledAt);
|
||||||
return `\n${i + 1}. ${m.title} (${filled}/${cap}) ${time}\n ID: ${id}`;
|
return `\n${i + 1}. ${m.title} (${filled}/${cap}) ${time}\n 코드: ${m.shortCode}`;
|
||||||
});
|
});
|
||||||
|
|
||||||
return [
|
return [
|
||||||
@@ -45,19 +48,18 @@ export class MatchListHandler {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
kind: 'text',
|
kind: 'text',
|
||||||
text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n신청: !내전 신청 [ID 또는 제목] <닉네임>#<태그> <포지션1>,<포지션2>\n취소: !내전 취소 <ID> 또는 !내전 참가취소 <ID>\n모집 중 내전이 1개면 신청 ID/제목은 생략할 수 있습니다.`,
|
text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n신청: !내전 신청 [코드 또는 제목] <닉네임>#<태그> <포지션1>,<포지션2>\n취소: !내전 취소 <코드 또는 제목>\n모집 중 내전이 1개면 신청 코드/제목은 생략할 수 있습니다.`,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatScheduledAt(date: Date): string {
|
function formatScheduledAt(date: Date): string {
|
||||||
// YYYY-MM-DD HH:mm (KST 표기)
|
// M/D HH:mm (KST 표기)
|
||||||
const kst = new Date(date.getTime() + 9 * 60 * 60 * 1000);
|
const kst = new Date(date.getTime() + 9 * 60 * 60 * 1000);
|
||||||
const yyyy = kst.getUTCFullYear();
|
const month = kst.getUTCMonth() + 1;
|
||||||
const mm = String(kst.getUTCMonth() + 1).padStart(2, '0');
|
const day = kst.getUTCDate();
|
||||||
const dd = String(kst.getUTCDate()).padStart(2, '0');
|
|
||||||
const hh = String(kst.getUTCHours()).padStart(2, '0');
|
const hh = String(kst.getUTCHours()).padStart(2, '0');
|
||||||
const mi = String(kst.getUTCMinutes()).padStart(2, '0');
|
const mi = String(kst.getUTCMinutes()).padStart(2, '0');
|
||||||
return `${yyyy}-${mm}-${dd} ${hh}:${mi}`;
|
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();
|
||||||
|
}
|
||||||
@@ -74,6 +74,13 @@ describe('parseCommand', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('parses match-cancel command with short code', () => {
|
||||||
|
expect(parseCommand('!내전 취소 AB12')).toEqual({
|
||||||
|
kind: 'match-cancel',
|
||||||
|
matchId: 'AB12',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it('parses account register command', () => {
|
it('parses account register command', () => {
|
||||||
expect(parseCommand('!내전 계정등록 hello world#KR1')).toEqual({
|
expect(parseCommand('!내전 계정등록 hello world#KR1')).toEqual({
|
||||||
kind: 'account-register',
|
kind: 'account-register',
|
||||||
@@ -110,12 +117,6 @@ describe('parseCommand', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('throws invalid_match_id for non-objectid cancel match', () => {
|
|
||||||
expect(() => parseCommand('!내전 취소 not-an-id')).toThrow(
|
|
||||||
/invalid_match_id/,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws invalid_riot_id when # missing', () => {
|
it('throws invalid_riot_id when # missing', () => {
|
||||||
expect(() =>
|
expect(() =>
|
||||||
parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 프리리 미드,탑'),
|
parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 프리리 미드,탑'),
|
||||||
|
|||||||
@@ -94,9 +94,6 @@ function parseCancelArgs(args: string): DakaoCommand {
|
|||||||
if (matchId.length === 0) {
|
if (matchId.length === 0) {
|
||||||
throw new CommandParseError('usage');
|
throw new CommandParseError('usage');
|
||||||
}
|
}
|
||||||
if (!isObjectIdHex(matchId)) {
|
|
||||||
throw new CommandParseError('invalid_match_id', matchId);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
kind: 'match-cancel',
|
kind: 'match-cancel',
|
||||||
@@ -143,7 +140,3 @@ function parseJoinArgs(args: string): DakaoCommand {
|
|||||||
positions,
|
positions,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function isObjectIdHex(value: string): boolean {
|
|
||||||
return /^[a-f0-9]{24}$/i.test(value);
|
|
||||||
}
|
|
||||||
@@ -420,6 +420,7 @@ export interface MatchScheduleItem {
|
|||||||
|
|
||||||
export interface Match extends MongooseTimestamps {
|
export interface Match extends MongooseTimestamps {
|
||||||
communityId: mongoose.Types.ObjectId;
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
shortCode?: string;
|
||||||
title: string;
|
title: string;
|
||||||
description: string;
|
description: string;
|
||||||
mapId: number; // Riot Match-V5 mapId (11=소환사의 협곡, 12=ARAM 등)
|
mapId: number; // Riot Match-V5 mapId (11=소환사의 협곡, 12=ARAM 등)
|
||||||
@@ -1068,6 +1069,14 @@ export const MatchSchema = new Schema<Match>(
|
|||||||
ref: 'community',
|
ref: 'community',
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
|
shortCode: {
|
||||||
|
type: String,
|
||||||
|
required: false,
|
||||||
|
trim: true,
|
||||||
|
uppercase: true,
|
||||||
|
minlength: 4,
|
||||||
|
maxlength: 6,
|
||||||
|
},
|
||||||
title: { type: String, required: true },
|
title: { type: String, required: true },
|
||||||
description: { type: String, required: true, default: '' },
|
description: { type: String, required: true, default: '' },
|
||||||
mapId: { type: Number, required: true, default: 11 },
|
mapId: { type: Number, required: true, default: 11 },
|
||||||
@@ -1141,6 +1150,13 @@ export const MatchSchema = new Schema<Match>(
|
|||||||
|
|
||||||
MatchSchema.index({ communityId: 1, scheduledAt: -1 });
|
MatchSchema.index({ communityId: 1, scheduledAt: -1 });
|
||||||
MatchSchema.index({ communityId: 1, status: 1, scheduledAt: -1 });
|
MatchSchema.index({ communityId: 1, status: 1, scheduledAt: -1 });
|
||||||
|
MatchSchema.index(
|
||||||
|
{ communityId: 1, shortCode: 1 },
|
||||||
|
{
|
||||||
|
unique: true,
|
||||||
|
partialFilterExpression: { shortCode: { $type: 'string' } },
|
||||||
|
},
|
||||||
|
);
|
||||||
MatchSchema.index({ legacyImported: 1, scheduledAt: -1 });
|
MatchSchema.index({ legacyImported: 1, scheduledAt: -1 });
|
||||||
MatchSchema.index({ 'result.games.riotMatchId': 1 }, { sparse: true });
|
MatchSchema.index({ 'result.games.riotMatchId': 1 }, { sparse: true });
|
||||||
MatchSchema.index({ title: 'text', description: 'text' });
|
MatchSchema.index({ title: 'text', description: 'text' });
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import {
|
import {
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
Injectable,
|
Injectable,
|
||||||
|
InternalServerErrorException,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
@@ -17,6 +18,10 @@ import {
|
|||||||
import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants';
|
import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants';
|
||||||
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
|
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
|
||||||
|
|
||||||
|
const MATCH_SHORT_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||||
|
const MATCH_SHORT_CODE_LENGTH = 4;
|
||||||
|
const MATCH_SHORT_CODE_GENERATION_ATTEMPTS = 20;
|
||||||
|
|
||||||
interface CreateMatchParams {
|
interface CreateMatchParams {
|
||||||
communityId: mongoose.Types.ObjectId;
|
communityId: mongoose.Types.ObjectId;
|
||||||
hostUserId?: mongoose.Types.ObjectId;
|
hostUserId?: mongoose.Types.ObjectId;
|
||||||
@@ -65,6 +70,9 @@ export class MatchService {
|
|||||||
.exec();
|
.exec();
|
||||||
return MatchModel.create({
|
return MatchModel.create({
|
||||||
...params.data,
|
...params.data,
|
||||||
|
shortCode:
|
||||||
|
params.data.shortCode ??
|
||||||
|
(await this.generateUniqueShortCode(MatchModel, params.communityId)),
|
||||||
gameCount:
|
gameCount:
|
||||||
params.data.gameCount ??
|
params.data.gameCount ??
|
||||||
community?.matchGameCount ??
|
community?.matchGameCount ??
|
||||||
@@ -89,6 +97,18 @@ export class MatchService {
|
|||||||
.exec();
|
.exec();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async ensureShortCode(match: MatchDocument): Promise<MatchDocument> {
|
||||||
|
if (match.shortCode) return match;
|
||||||
|
|
||||||
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
|
match.shortCode = await this.generateUniqueShortCode(
|
||||||
|
MatchModel,
|
||||||
|
match.communityId,
|
||||||
|
);
|
||||||
|
await match.save();
|
||||||
|
return match;
|
||||||
|
}
|
||||||
|
|
||||||
public async getById(
|
public async getById(
|
||||||
matchId: mongoose.Types.ObjectId,
|
matchId: mongoose.Types.ObjectId,
|
||||||
): Promise<MatchDocument> {
|
): Promise<MatchDocument> {
|
||||||
@@ -269,6 +289,36 @@ export class MatchService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async generateUniqueShortCode(
|
||||||
|
MatchModel: mongoose.Model<Match>,
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
): Promise<string> {
|
||||||
|
for (
|
||||||
|
let attempt = 0;
|
||||||
|
attempt < MATCH_SHORT_CODE_GENERATION_ATTEMPTS;
|
||||||
|
attempt += 1
|
||||||
|
) {
|
||||||
|
const shortCode = this.generateShortCode();
|
||||||
|
const exists = await MatchModel.exists({ communityId, shortCode });
|
||||||
|
if (!exists) return shortCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new InternalServerErrorException(
|
||||||
|
'Failed to generate unique match short code.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private generateShortCode(): string {
|
||||||
|
let code = '';
|
||||||
|
for (let index = 0; index < MATCH_SHORT_CODE_LENGTH; index += 1) {
|
||||||
|
const alphabetIndex = Math.floor(
|
||||||
|
Math.random() * MATCH_SHORT_CODE_ALPHABET.length,
|
||||||
|
);
|
||||||
|
code += MATCH_SHORT_CODE_ALPHABET[alphabetIndex];
|
||||||
|
}
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
private buildSeriesResults(
|
private buildSeriesResults(
|
||||||
games: NonNullable<Match['result']>['games'],
|
games: NonNullable<Match['result']>['games'],
|
||||||
): MatchSeriesResult[] {
|
): MatchSeriesResult[] {
|
||||||
|
|||||||
@@ -202,6 +202,7 @@ export interface ApiMatchScheduleItem {
|
|||||||
export interface ApiMatch {
|
export interface ApiMatch {
|
||||||
_id: string;
|
_id: string;
|
||||||
communityId: string;
|
communityId: string;
|
||||||
|
shortCode?: string;
|
||||||
title: string;
|
title: string;
|
||||||
description: string;
|
description: string;
|
||||||
mapId: number;
|
mapId: number;
|
||||||
|
|||||||
@@ -212,6 +212,15 @@ function QueueRankCell({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function SoloRankPrefix({ tier }: { tier?: ApiTierInfo }) {
|
||||||
|
return (
|
||||||
|
<span className="inline-flex shrink-0 items-center gap-1 text-[10px] font-black text-base-content/35">
|
||||||
|
{/* <span>SOLO</span> */}
|
||||||
|
<RankBadge tier={tier} />
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function TierCell({ participant }: { participant: ParticipantView }) {
|
function TierCell({ participant }: { participant: ParticipantView }) {
|
||||||
const profileQuery = useUserHistoryProfile(
|
const profileQuery = useUserHistoryProfile(
|
||||||
participant.userId,
|
participant.userId,
|
||||||
@@ -1516,17 +1525,26 @@ export default function MatchDetailPage() {
|
|||||||
selectedManualTopTierUserIds.includes(
|
selectedManualTopTierUserIds.includes(
|
||||||
participant.userId,
|
participant.userId,
|
||||||
);
|
);
|
||||||
|
const soloTier =
|
||||||
|
participant.tier?.queueType ===
|
||||||
|
"RANKED_SOLO_5x5"
|
||||||
|
? participant.tier
|
||||||
|
: undefined;
|
||||||
return (
|
return (
|
||||||
<label
|
<label
|
||||||
key={participant.userId}
|
key={participant.userId}
|
||||||
className="flex cursor-pointer items-center justify-between gap-3 border border-base-content/8 px-2 py-1.5 text-xs text-base-content/55 transition-colors hover:border-primary/25 hover:bg-primary/5"
|
className="flex cursor-pointer items-center justify-between gap-3 border border-base-content/8 px-2 py-1.5 text-xs text-base-content/55 transition-colors hover:border-primary/25 hover:bg-primary/5"
|
||||||
>
|
>
|
||||||
|
<span className="flex min-w-0 items-center gap-2">
|
||||||
|
<SoloRankPrefix tier={soloTier} />
|
||||||
<span className="min-w-0 truncate">
|
<span className="min-w-0 truncate">
|
||||||
{participant.gameName ?? participant.userId}
|
{participant.gameName ??
|
||||||
|
participant.userId}
|
||||||
<span className="ml-1 text-base-content/25">
|
<span className="ml-1 text-base-content/25">
|
||||||
#{participant.tagLine ?? "----"}
|
#{participant.tagLine ?? "----"}
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
|
</span>
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
className="checkbox checkbox-primary checkbox-xs"
|
className="checkbox checkbox-primary checkbox-xs"
|
||||||
|
|||||||
Reference in new issue
Block a user