From 4475a2d86be7639c7e6bf978a390a348329ebb5a Mon Sep 17 00:00:00 2001 From: dahyeon Date: Mon, 27 Apr 2026 19:56:10 -0700 Subject: [PATCH] . --- .../src/modules/dakao/dakao-user.service.ts | 149 ++++++++++++++---- apps/api/src/modules/dakao/dakao.module.ts | 2 + .../api/src/modules/dakao/dakao.subscriber.ts | 15 +- .../handlers/account-register.handler.ts | 79 ++++++++++ .../dakao/handlers/match-list.handler.ts | 2 +- .../dakao/parsers/command.parser.spec.ts | 19 +++ .../modules/dakao/parsers/command.parser.ts | 30 ++++ 7 files changed, 262 insertions(+), 34 deletions(-) create mode 100644 apps/api/src/modules/dakao/handlers/account-register.handler.ts diff --git a/apps/api/src/modules/dakao/dakao-user.service.ts b/apps/api/src/modules/dakao/dakao-user.service.ts index 19e9061e..21a0ccc2 100644 --- a/apps/api/src/modules/dakao/dakao-user.service.ts +++ b/apps/api/src/modules/dakao/dakao-user.service.ts @@ -45,6 +45,12 @@ interface RiotRouting { region: RiotRegionalRoute; } +interface ResolvedRiotIdentity { + requestedGameName: string; + requestedTagLine: string; + dto: { puuid: string; gameName: string | null; tagLine: string | null }; +} + const DEFAULT_RIOT_PLATFORM: RiotPlatformRoute = 'kr'; const DEFAULT_RIOT_REGION: RiotRegionalRoute = 'asia'; @@ -109,9 +115,8 @@ export class DakaoUserService { ): Promise { const user = await this.upsertUser(context); const routing = await this.resolveRiotRouting(context.communityId); - const requestedGameName = normalizeRiotIdPart(context.gameName); - const requestedTagLine = normalizeRiotIdPart(context.tagLine); - this.logRiotIdNormalization(context, requestedGameName, requestedTagLine); + const { requestedGameName, requestedTagLine, dto } = + await this.lookupRiotIdentity(context, routing); const existing = user.riotAccounts.find( (a) => @@ -124,34 +129,6 @@ export class DakaoUserService { ); } - let dto: { puuid: string; gameName: string | null; tagLine: string | null }; - try { - dto = await this.riotAccountService.getByRiotId( - requestedGameName, - requestedTagLine, - { region: routing.region }, - ); - this.logger.log( - `Resolved Riot ID ${requestedGameName}#${requestedTagLine} via ${routing.region}: puuid=${dto.puuid} canonical=${dto.gameName ?? '-'}#${dto.tagLine ?? '-'}`, - ); - } catch (err) { - if (err instanceof RiotApiError && err.status === 404) { - throw new DakaoUserError( - 'riot_account_not_found', - `${requestedGameName}#${requestedTagLine}`, - ); - } - this.logger.error( - `Riot account lookup failed for ${requestedGameName}#${requestedTagLine}: ${ - (err as Error)?.message ?? err - }`, - ); - throw new DakaoUserError( - 'riot_account_lookup_failed', - (err as Error)?.message, - ); - } - if (existing) { const nextGameName = dto.gameName ?? requestedGameName; const nextTagLine = dto.tagLine ?? requestedTagLine; @@ -193,6 +170,116 @@ export class DakaoUserService { }); } + public async registerPrimaryRiotAccount( + context: ResolveContext, + ): Promise { + const user = await this.upsertUser(context); + const routing = await this.resolveRiotRouting(context.communityId); + const { requestedGameName, requestedTagLine, dto } = + await this.lookupRiotIdentity(context, routing); + const nextGameName = dto.gameName ?? requestedGameName; + const nextTagLine = dto.tagLine ?? requestedTagLine; + + let targetIndex = user.riotAccounts.findIndex( + (account) => account.puuid === dto.puuid, + ); + if (targetIndex === -1) { + targetIndex = user.riotAccounts.findIndex( + (account) => + account.gameName.toLowerCase() === requestedGameName.toLowerCase() && + account.tagLine.toLowerCase() === requestedTagLine.toLowerCase(), + ); + } + + if (targetIndex >= 0) { + const target = user.riotAccounts[targetIndex]; + const puuidChanged = target.puuid !== dto.puuid; + target.puuid = dto.puuid; + target.gameName = nextGameName; + target.tagLine = nextTagLine; + if (puuidChanged) this.clearRiotCache(target); + user.riotAccounts.forEach((account, index) => { + account.isPrimary = index === targetIndex; + }); + await this.saveUserHandlingDuplicate(user, nextGameName, nextTagLine); + return this.enrichAttachedAccount({ + user, + riotAccount: target, + platform: routing.platform, + region: routing.region, + }); + } + + user.riotAccounts.forEach((account) => { + account.isPrimary = false; + }); + user.riotAccounts.push({ + puuid: dto.puuid, + gameName: nextGameName, + tagLine: nextTagLine, + profileIconId: 0, + revisionDate: 0, + summonerLevel: 0, + isPrimary: true, + tiers: [], + tierHistory: [], + matchIds: [], + championMasteries: [], + championRecords: {}, + } as unknown as RiotAccount); + + await this.saveUserHandlingDuplicate(user, nextGameName, nextTagLine); + const attached = user.riotAccounts.find( + (account) => account.puuid === dto.puuid, + ); + if (!attached) { + throw new DakaoUserError('riot_account_lookup_failed', 'attach failed'); + } + return this.enrichAttachedAccount({ + user, + riotAccount: attached, + platform: routing.platform, + region: routing.region, + }); + } + + private async lookupRiotIdentity( + context: ResolveContext, + routing: RiotRouting, + ): Promise { + const requestedGameName = normalizeRiotIdPart(context.gameName); + const requestedTagLine = normalizeRiotIdPart(context.tagLine); + this.logRiotIdNormalization(context, requestedGameName, requestedTagLine); + + try { + const dto = await this.riotAccountService.getByRiotId( + requestedGameName, + requestedTagLine, + { region: routing.region }, + ); + this.logger.log( + `Resolved Riot ID ${requestedGameName}#${requestedTagLine} via ${routing.region}: puuid=${dto.puuid} canonical=${dto.gameName ?? '-'}#${dto.tagLine ?? '-'}`, + ); + return { requestedGameName, requestedTagLine, dto }; + } catch (err) { + if (err instanceof RiotApiError && err.status === 404) { + throw new DakaoUserError( + 'riot_account_not_found', + `${requestedGameName}#${requestedTagLine}`, + ); + } + this.logger.error( + `Riot account lookup failed for ${requestedGameName}#${requestedTagLine}: ${ + (err as Error)?.message ?? err + }`, + ); + throw new DakaoUserError( + 'riot_account_lookup_failed', + (err as Error)?.message, + ); + } + } + private logRiotIdNormalization( context: ResolveContext, normalizedGameName: string, diff --git a/apps/api/src/modules/dakao/dakao.module.ts b/apps/api/src/modules/dakao/dakao.module.ts index 86f52e29..5626b745 100644 --- a/apps/api/src/modules/dakao/dakao.module.ts +++ b/apps/api/src/modules/dakao/dakao.module.ts @@ -9,6 +9,7 @@ import { DakaoPublisher } from './dakao.publisher'; import { DakaoSubscriber } from './dakao.subscriber'; import { DakaoUserService } from './dakao-user.service'; import { IdempotencyCache } from './idempotency.cache'; +import { AccountRegisterHandler } from './handlers/account-register.handler'; import { MatchJoinHandler } from './handlers/match-join.handler'; import { MatchListHandler } from './handlers/match-list.handler'; @@ -23,6 +24,7 @@ import { MatchListHandler } from './handlers/match-list.handler'; DakaoSubscriber, DakaoUserService, IdempotencyCache, + AccountRegisterHandler, MatchListHandler, MatchJoinHandler, ], diff --git a/apps/api/src/modules/dakao/dakao.subscriber.ts b/apps/api/src/modules/dakao/dakao.subscriber.ts index f1197b0f..9a42d8e5 100644 --- a/apps/api/src/modules/dakao/dakao.subscriber.ts +++ b/apps/api/src/modules/dakao/dakao.subscriber.ts @@ -7,6 +7,7 @@ import { DakaoInboundEvent, DakaoLong, DakaoSegment } from './dakao.types'; import { DakaoPublisher } from './dakao.publisher'; import { DakaoUserError, DakaoUserService } from './dakao-user.service'; import { IdempotencyCache } from './idempotency.cache'; +import { AccountRegisterHandler } from './handlers/account-register.handler'; import { MatchJoinHandler } from './handlers/match-join.handler'; import { MatchListHandler } from './handlers/match-list.handler'; @@ -24,6 +25,7 @@ export class DakaoSubscriber implements OnModuleInit { private readonly dakaoUserService: DakaoUserService, private readonly publisher: DakaoPublisher, private readonly idempotency: IdempotencyCache, + private readonly accountRegisterHandler: AccountRegisterHandler, private readonly matchListHandler: MatchListHandler, private readonly matchJoinHandler: MatchJoinHandler, ) {} @@ -94,6 +96,15 @@ export class DakaoSubscriber implements OnModuleInit { senderNickname, }); break; + case 'account-register': + segments = await this.accountRegisterHandler.handle({ + communityId, + senderUserId: event.userId, + senderNickname, + gameName: command.gameName, + tagLine: command.tagLine, + }); + break; case 'match-join': segments = await this.matchJoinHandler.handle({ communityId, @@ -183,9 +194,9 @@ export class DakaoSubscriber implements OnModuleInit { const text = ((): string => { switch (err.code) { case 'unknown_command': - return ` 알 수 없는 명령어입니다. 사용법: !내전 목록 또는 !내전 신청 <게임명>#<태그> <포지션1>,<포지션2>`; + return ` 알 수 없는 명령어입니다. 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <게임명>#<태그> <포지션1>,<포지션2>`; case 'usage': - return ` 사용법: !내전 목록 또는 !내전 신청 <게임명>#<태그> <포지션1>,<포지션2>`; + return ` 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <게임명>#<태그> <포지션1>,<포지션2>`; case 'invalid_match_id': return ` 매치 ID 형식이 올바르지 않습니다 (${err.detail ?? ''}).`; case 'invalid_riot_id': diff --git a/apps/api/src/modules/dakao/handlers/account-register.handler.ts b/apps/api/src/modules/dakao/handlers/account-register.handler.ts new file mode 100644 index 00000000..6dec9c57 --- /dev/null +++ b/apps/api/src/modules/dakao/handlers/account-register.handler.ts @@ -0,0 +1,79 @@ +import { Injectable } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { DakaoSegment } from '../dakao.types'; +import { DakaoUserError, DakaoUserService } from '../dakao-user.service'; + +interface AccountRegisterHandlerParams { + communityId: mongoose.Types.ObjectId; + senderUserId: string; + senderNickname: string; + gameName: string; + tagLine: string; +} + +@Injectable() +export class AccountRegisterHandler { + constructor(private readonly dakaoUserService: DakaoUserService) {} + + public async handle( + params: AccountRegisterHandlerParams, + ): Promise { + try { + const resolved = await this.dakaoUserService.registerPrimaryRiotAccount({ + communityId: params.communityId, + kakaoTalkId: params.senderUserId, + kakaoTalkNickname: params.senderNickname, + gameName: params.gameName, + tagLine: params.tagLine, + }); + + return [ + { + kind: 'mention', + userId: params.senderUserId, + displayText: params.senderNickname, + }, + { + kind: 'text', + text: + ` 계정 등록 완료` + + `\n대표 계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}`, + }, + ]; + } catch (err) { + if (err instanceof DakaoUserError) { + return this.errorReply(params, this.translateUserError(err)); + } + throw err; + } + } + + private errorReply( + params: AccountRegisterHandlerParams, + 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_conflict': + return `이미 다른 사용자가 등록한 라이엇 계정입니다 (${err.detail ?? ''}).`; + case 'riot_account_lookup_failed': + return '라이엇 계정 조회 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.'; + } + } +} diff --git a/apps/api/src/modules/dakao/handlers/match-list.handler.ts b/apps/api/src/modules/dakao/handlers/match-list.handler.ts index 6bf6ad9b..23746ed6 100644 --- a/apps/api/src/modules/dakao/handlers/match-list.handler.ts +++ b/apps/api/src/modules/dakao/handlers/match-list.handler.ts @@ -45,7 +45,7 @@ export class MatchListHandler { }, { kind: 'text', - text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n신청: !내전 신청 <닉네임>#<태그> <포지션1>,<포지션2>`, + text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n신청: !내전 신청 <닉네임>#<태그> <포지션1>,<포지션2>`, }, ]; } diff --git a/apps/api/src/modules/dakao/parsers/command.parser.spec.ts b/apps/api/src/modules/dakao/parsers/command.parser.spec.ts index 43628e46..2b11818c 100644 --- a/apps/api/src/modules/dakao/parsers/command.parser.spec.ts +++ b/apps/api/src/modules/dakao/parsers/command.parser.spec.ts @@ -48,6 +48,25 @@ describe('parseCommand', () => { }); }); + it('parses account register command', () => { + expect(parseCommand('!내전 계정등록 hello world#KR1')).toEqual({ + kind: 'account-register', + gameName: 'hello world', + tagLine: 'KR1', + }); + }); + + it('normalizes account register riot id', () => { + const decomposedGameName = '프리리'.normalize('NFD'); + expect( + parseCommand(`!내전 계정등록 ${decomposedGameName}\u200B#KR1\uFEFF`), + ).toEqual({ + kind: 'account-register', + gameName: '프리리', + tagLine: 'KR1', + }); + }); + it('throws not_a_command for non-prefix messages', () => { expect(() => parseCommand('안녕하세요')).toThrow(/not_a_command/); }); diff --git a/apps/api/src/modules/dakao/parsers/command.parser.ts b/apps/api/src/modules/dakao/parsers/command.parser.ts index f7874f08..5bc9bd04 100644 --- a/apps/api/src/modules/dakao/parsers/command.parser.ts +++ b/apps/api/src/modules/dakao/parsers/command.parser.ts @@ -3,6 +3,11 @@ import { normalizeRiotIdPart } from '../riot-id.util'; export type DakaoCommand = | { kind: 'match-list' } + | { + kind: 'account-register'; + gameName: string; + tagLine: string; + } | { kind: 'match-join'; matchId: string; @@ -49,11 +54,36 @@ export function parseCommand(rawMessage: string): DakaoCommand { return { kind: 'match-list' }; case '신청': return parseJoinArgs(args); + case '계정등록': + return parseAccountRegisterArgs(args); default: throw new CommandParseError('unknown_command', subCommand); } } +function parseAccountRegisterArgs(args: string): DakaoCommand { + if (args.length === 0) { + throw new CommandParseError('usage'); + } + + const hashIndex = args.lastIndexOf('#'); + if (hashIndex <= 0 || hashIndex === args.length - 1) { + throw new CommandParseError('invalid_riot_id', args); + } + + const gameName = normalizeRiotIdPart(args.slice(0, hashIndex)); + const tagLine = normalizeRiotIdPart(args.slice(hashIndex + 1)); + if (gameName.length === 0 || tagLine.length === 0) { + throw new CommandParseError('invalid_riot_id', args); + } + + return { + kind: 'account-register', + gameName, + tagLine, + }; +} + function parseJoinArgs(args: string): DakaoCommand { if (args.length === 0) { throw new CommandParseError('usage');