feat: improve tournament workflows and prune outdated docs

This commit is contained in:
dahyeon committed 2026-11-10 15:31:19 +09:00
1 parent da7b502936
commit 38a89b5374
53 files changed
+3308 -3276

No files matched your search

@@ -1,80 +0,0 @@
# Spec: API Performance Observability And Full Route Report
## Objective
Add Phase 1 and Phase 2 support for API performance work:
- Phase 1 records request latency and Mongoose document-return metrics.
- Phase 2 generates a report for every API route, not only the slowest routes.
- New Relic Transaction or custom event data is the preferred production source.
- Local NDJSON files provide a staging/local fallback with query-level detail.
Success means an engineer can run representative traffic against the API and produce
a route-complete report that includes routes with no samples.
## Tech Stack
- NestJS API in `apps/api`
- Mongoose models created through `ConnectionService`
- New Relic Node agent, already configured by `apps/api/newrelic.cjs`
- Jest for unit tests
- `ts-node` for API maintenance scripts
## Commands
- Build: `pnpm --filter api build`
- Test: `pnpm --filter api test`
- Generate local/New Relic report: `pnpm --filter api perf:report`
- Generate route manifest only: `pnpm --filter api perf:routes`
## Project Structure
- `apps/api/src/modules/global/observability/` contains request/query instrumentation.
- `apps/api/src/scripts/api-performance-report.ts` generates full API reports.
- `docs/specs/api-performance-observability.md` defines this behavior.
## Code Style
Instrumentation must be opt-in and defensive:
```ts
if (!isPerformanceObservabilityEnabled()) return;
recordApiPerformanceEvent({
type: 'api-request',
method,
route,
durationMs,
});
```
Do not record raw request bodies, authorization headers, cookies, raw Mongo filters,
or raw query results.
## Testing Strategy
- Unit test pure metric aggregation and route discovery logic.
- Unit test request context aggregation without a database.
- Build the API to catch Nest and TypeScript integration issues.
- Production/staging validation uses New Relic Transaction data and optional local
NDJSON from representative traffic.
## Boundaries
- Always: keep instrumentation disabled unless explicitly enabled.
- Always: include all discovered controller routes in the report.
- Always: report `no-samples` for routes that did not receive traffic.
- Ask first: adding external load-test dependencies or CI performance gates.
- Never: log secrets, request bodies, auth headers, cookies, or raw Mongo filters.
## Success Criteria
- API request events include duration, status, route, query count, Mongoose duration,
returned document count, and hydrated document count.
- Mongoose query events include model, collection, operation, duration, returned
documents, hydrated documents, and lean status.
- New Relic receives route-level custom events when instrumentation is enabled.
- New Relic Transaction traces can be grouped by route through custom transaction names
and attributes.
- The report generator can use local NDJSON, New Relic custom events, or New Relic
Transaction duration data.
- The report lists every API route from controller source files.
-67
View File
@@ -1,67 +0,0 @@
# Spec: Dakao Upcoming Internal Match List
## Objective
When a user sends `!내전 일정`, return only recruiting matches whose scheduled
start is not earlier than the command processing time. Matches that have already
started must not consume the ten-result query limit or appear in the response.
## Approved Product Decisions
- Capture the command processing time once before querying matches.
- Exclude `scheduledAt < now`.
- Include `scheduledAt === now` and future matches.
- Apply the boundary only to the Dakao `!내전 일정` command.
- Preserve the existing recruiting status, result limit, ordering, formatting,
short-code generation, and short-link behavior.
## Commands
- Focused test:
`pnpm --filter api exec jest src/modules/dakao/handlers/match-list.handler.spec.ts --runInBand`
- API lint:
`pnpm --filter api exec eslint "{src,apps,libs,test}/**/*.ts" --max-warnings=0`
- API build: `pnpm --filter api build`
## Project Structure
- `apps/api/src/modules/dakao/handlers/match-list.handler.ts` owns the command
query and response formatting.
- `apps/api/src/modules/dakao/handlers/match-list.handler.spec.ts` verifies the
command boundary and presentation.
- `apps/api/src/modules/match/match.service.ts` translates `scheduledFrom` into a
MongoDB `$gte` filter.
## Code Style
Pass the captured boundary through the existing list contract:
```ts
const scheduledFrom = new Date();
await matchService.list({ communityId, scheduledFrom });
```
## Testing Strategy
- Freeze the system clock in the handler unit test.
- Assert that the exact frozen time is passed as `scheduledFrom`.
- Rely on the existing `MatchService` test that verifies `scheduledFrom` becomes
`{ scheduledAt: { $gte: scheduledFrom } }`.
- Run the focused handler test, full API lint, and API build.
## Boundaries
- Always: filter before applying the result limit and use one captured time.
- Ask first: change ordering, statuses, limit, or response wording.
- Never: hide the requirement with an ESLint exception or filter only after the
limited database query.
## Success Criteria
- A match scheduled before command processing time is not queried.
- A match scheduled exactly at command processing time remains eligible.
- Existing command formatting and link tests continue to pass.
## Open Questions
None.
@@ -1,134 +0,0 @@
# Spec: Double-Elimination Connector Routing
## Objective
Make winner advancement lines in the desktop double-elimination bracket bend at a
consistent horizontal position. Two winner lines entering the same match should
read as one visual pair when their vertical spans can share a rail: use the center
of the 40px inter-column corridor when it is safe, and move the pair together only
when another connector would interfere. If an accepted A/B mapping reverses the
source order and makes those spans overlap, preserve separate deterministic,
stroke-clear rails instead of creating a collinear overlap.
The primary user is a participant or organizer tracing advancement through a busy
eight-team bracket. Success means the solid coral winner paths are visually
aligned without degrading the existing dashed loser paths, card placement, or
keyboard-driven connector highlighting.
## Approved Product Decisions
- Treat the two `winner` connectors entering one Series as a semantic bundle.
- Prefer `target.x - columnGap / 2` for a winner bundle.
- If the preferred rail causes crossings, collinear overlap, or less than 5px of
clearance from an overlapping parallel route, move a shareable bundle to the
nearest safe rail. Retain separate rails only when the pair's own vertical spans
overlap and therefore cannot safely share any rail; move those rails to the
nearest deterministic positions needed to preserve the same 5px clearance.
- Preserve the current loser/reset rail ordering unless moving one is required to
maintain valid geometry.
- Keep every connector as a separate `H-V-H` SVG path so focus highlighting and
accessible labels remain independent.
- Keep long-distance bends inside the corridor immediately before the target
column; do not use the midpoint between source and target cards.
## Tech Stack
- React 19, TypeScript 6, Vite 8, Tailwind CSS 4, and daisyUI under `apps/web`
- Node's built-in test runner for the pure bracket layout calculation
## Commands
- Focused layout tests: `pnpm --filter web exec node --test --experimental-strip-types test/double-elimination-bracket-layout.test.ts`
- Full web tests: `pnpm --filter web test`
- Web lint: `pnpm --filter web lint`
- Web production build: `pnpm --filter web build:prod`
- Development server: `pnpm --filter web start:dev`
## Project Structure
- `apps/web/src/components/competition/double-elimination-bracket-layout.ts`
validates the bracket graph, positions cards, assigns connector rails, and emits
SVG path geometry.
- `apps/web/src/components/competition/DoubleEliminationBracket.tsx` renders the
computed paths and must not need routing-specific changes.
- `apps/web/test/double-elimination-bracket-layout.test.ts` contains canonical
four-team, eight-team, and reset-final fixtures plus geometry assertions.
## Code Style
Keep routing deterministic and express geometry through small named helpers:
```ts
const preferredX = target.x - geometry.columnGap / 2;
const verticalX = nearestSafeRail(preferredX, bundle, occupiedRoutes);
```
Use existing layout types and semantic connector kinds. Do not add a dependency,
DOM measurement, mutable global state, or renderer-specific routing behavior.
## Testing Strategy
- Add regression tests before implementation and confirm they fail against the
current per-edge rail allocator.
- Assert observable geometry: safe winner pairs share a rail, quiet corridors use
their exact midpoint, busy corridors keep a pair aligned, and mixed
winner/loser entries remain distinguishable.
- Cover reversed A/B winner input explicitly: it remains deterministic and uses
separate rails without collinear overlap or focused-stroke clearance conflicts
because no shared H-V-H rail is safe.
- Replace the obsolete "all rails in a target column are unique" assertion with
interval-aware overlap and 5px focused-stroke clearance protection.
- Preserve deterministic output for shuffled input, finite path coordinates,
target-corridor bounds, card avoidance, endpoint alignment, and canonical graph
validation.
- Verify four-team, eight-team, and reset-final layouts; run the complete web test,
lint, and production build commands.
## Boundaries
### Always
- Keep winner, loser, and reset connectors visually distinguishable by the existing
solid/dashed patterns and brand tokens.
- Keep connector rails strictly inside the target corridor.
- Avoid strict segment crossings and collinear overlaps whenever a safe candidate
exists.
- Keep overlapping parallel winner and loser rails at least 5px apart, matching
the widest focused connector underlay.
- Produce the same layout regardless of projection input ordering.
### Ask First
- Add dependencies or change the public projection contract.
- Change bracket card dimensions, round columns, or the 40px column gap.
- Redesign mobile bracket presentation or connector interaction behavior.
### Never
- Route a connector through a match card.
- Infer routing from Series codes; use canonical graph identity and topology.
- Merge two logical connectors into one SVG path.
- Modify unrelated competition or score-card behavior.
## Success Criteria
- The two winner paths into `LB_R3_M1` bend at the corridor midpoint and share the
same `verticalX`.
- The winner paths into the grand final share the corridor midpoint when safe.
- Every same-target winner pair whose vertical spans do not overlap shares one
`verticalX`, using the nearest collision-safe rail when the midpoint is busy.
- A reversed A/B pair with overlapping vertical spans retains deterministic
separate rails, produces no collinear segment overlap, and remains at least 5px
from every overlapping vertical route.
- Loser/reset paths retain their baseline rails, and winner bundles remain at least
5px away where their vertical runs overlap.
- All rails remain inside their target corridors without card penetration or
collinear overlap.
- Canonical four-team, eight-team, reset-final, and shuffled-input tests pass.
- Full web tests and production build pass; changed-file lint passes, and any
unrelated full-lint baseline failures are documented.
## Open Questions
None. The user reviewed the proposed bundle-aware routing behavior and requested
implementation.
-170
View File
@@ -1,170 +0,0 @@
# Spec: Internal Match Game Analysis P0/P1
## Objective
Make an internal-match game result explain both the final numbers and how the game
reached them. P0 exposes data already present in the detail response: objective
events, complete team objectives, participant gold/GPM, and explicitly labelled
kill participation. P1 projects Riot Match-V5 timeline frames into real 10- and
15-minute lane checkpoints and a unified event stream for kills and structures.
The primary user is a tournament participant or organizer reviewing a completed
game on desktop or mobile. Success means the user can identify the major objective
sequence before reading ten player cards, compare lane state at 10/15 minutes, and
trace kills and building events without mistaking unavailable data for zero.
## Approved Product Decisions
- Place game flow immediately after the game summary and before detail tabs.
- Render chart events as both visual markers and a keyboard-readable text list.
- Keep the existing gold/XP toggle and runes/build experience.
- Show tower, dragon, inhibitor, Baron, Rift Herald, Void Grub, and Elder Dragon
totals; derive dragon type labels only when objective events are available.
- Combine participant CS and economy instead of adding another wide table column.
- Label kill participation explicitly as `KP`.
- Replace final-state values in the lane tab with 10/15-minute checkpoints; default
to 15 minutes and pair players by `teamPosition`, never array position.
- Keep `objectiveEvents` for compatibility and add `timelineEvents` for the unified
P1 stream.
- Treat missing checkpoints and events as unavailable, not zero.
- Do not add an opaque MVP/rating or new external data feed in this scope.
## Tech Stack
- React 19, TypeScript 6, Recharts 3, Tailwind CSS 4, and daisyUI under `apps/web`
- NestJS 11, TypeScript 5, Mongoose 9, and Jest under `apps/api`
- Riot Match-V5 match and timeline payloads already cached in `RiotMatchModel`
- Node's built-in test runner for pure web transformations
## Commands
- Focused web tests: `pnpm --filter web test`
- Web lint: `pnpm --filter web lint`
- Web production build: `pnpm --filter web build:prod`
- Focused API tests: `pnpm --filter api test -- --runInBand riot-match.service.spec.ts match-stats-fragment.builder.spec.ts community-stats.service.spec.ts`
- API build: `pnpm --filter api build`
- Development web server: `pnpm --filter web start:dev`
## Project Structure
- `apps/web/src/pages/MatchGameDetailPage.tsx` owns the result summary,
participant scoreboard, flow chart, and accessible event list.
- `apps/web/src/components/InternalGameAnalysisTabs.tsx` owns the lane and build
tabs.
- `apps/web/src/lib/internal-match-timeline.ts` owns pure event normalization,
labels, filtering, and chart projection.
- `apps/web/src/lib/internal-game-matchups.ts` owns pure role pairing and checkpoint
comparisons.
- `apps/web/test/` contains Node unit tests for the pure web transformations.
- `apps/api/src/modules/riot/` parses trusted fields from Riot match timelines.
- `apps/api/src/modules/community-stats/match-stats-fragment.builder.ts` projects
stored Riot payloads into cached internal-match records.
- `apps/api/src/modules/community-stats/community-stats.service.ts` maps persisted
records into the public detail response and versions response caches.
- `apps/api/src/modules/global/database/schema.ts` defines persisted TypeScript
shapes; nested `gameDetails` remains a Mongoose Mixed array.
## Data Contract
Participant checkpoint data is additive and optional for legacy/fallback games:
```ts
interface MatchStatsCheckpoint {
timestamp: number;
gold: number;
cs: number;
xp: number;
kills: number;
deaths: number;
assists: number;
}
interface MatchStatsParticipantCheckpoints {
at10?: MatchStatsCheckpoint;
at15?: MatchStatsCheckpoint;
}
```
Each detailed participant gains optional `participantId` and `checkpoints`. Each
game gains optional `timelineEvents`, whose `type` is an existing objective type or
`championKill`, `tower`, or `inhibitor`. Actor IDs, assists, monster subtype, and
tower subtype are optional fields appropriate to the event type.
For a 10/15-minute target, use the latest frame at or before the target only when it
is less than one `frameInterval` old. Persist the actual selected timestamp. CS is
`minionsKilled + jungleMinionsKilled`; checkpoint K/D/A includes champion-kill
events through the selected timestamp. A game ending before a target has no value
for that checkpoint.
## Code Style
Keep timeline calculations independent from React and use discriminated event
types with conservative fallbacks:
```ts
const events = game.timelineEvents?.length
? game.timelineEvents
: game.objectiveEvents;
const checkpoint = participant.checkpoints?.at15;
if (!checkpoint) return { kind: "unavailable" };
```
Use existing semantic color tokens and square bordered panels. Dynamic chart
coordinates may use numeric props; spacing, colors, and typography remain in the
existing Tailwind/daisyUI system.
## Testing Strategy
- Develop pure event normalization, checkpoint selection, role pairing, and metric
comparison test-first.
- Builder tests cover exact and missing checkpoints, jungle CS, cumulative K/D/A,
executes, objective fallback, building ownership, and deterministic event order.
- Service tests reject stale cached response shapes and verify additive mapping.
- Browser verification covers 320px, 390px, 768px, 1024px, and 1440px; the event
text list is the accessible equivalent of decorative chart markers.
- Verify the supplied production-like game as well as a short game and a game with
no timeline.
## Boundaries
### Always
- Preserve existing `objectiveEvents`, runes/builds, and match-detail routes.
- Derive participant checkpoint values from stored Riot timeline frames.
- Pair lanes by normalized `teamPosition` and show unavailable states explicitly.
- Communicate team/event meaning with text as well as color.
- Increment the match-stats builder and detail-response cache versions whenever a
persisted or cached response shape changes.
### Ask First
- Add a frontend or backend dependency.
- Change the public route or remove compatibility fields.
- Add a database migration or make a bulk external Riot API fetch.
- Deploy, push, or alter CI configuration.
### Never
- Infer absent checkpoint data as zero.
- Pair opponents by array order.
- Claim that a nearby objective caused a gold swing.
- Expose unparsed arbitrary Riot event fields.
- Modify unrelated Competition/bracket work already present in the worktree.
## Success Criteria
- Game flow appears before player details and includes objective markers plus an
equivalent textual sequence on desktop and mobile.
- Summary shows all currently projected objective totals and available dragon types.
- Every participant shows labelled KP, gold, GPM, CS, and CS/min without breaking
the responsive scoreboard.
- The lane tab defaults to 15 minutes, can switch to 10 minutes, and presents
GD/CSD/XPD and checkpoint K/D/A for correctly paired roles.
- The unified timeline can filter and display objectives, champion kills, towers,
and inhibitors, while falling back to objective-only data during rolling updates.
- Focused API/web tests, lint, and production builds pass.
## Open Questions
None. The user reviewed the P0/P1 task plan and requested implementation.
-93
View File
@@ -1,93 +0,0 @@
# Spec: 카카오톡 방 이동 후 사용자 데이터 이관
## Objective
`!내전 데이터이관 <예전 kakaoTalkNickname>` 명령으로 기존 user의
`kakaoTalkId`를 명령 발신자의 현재 ID로 변경한다. 기존 user의 `_id`,
`riotAccounts`, 참가 기록, 권한과 기타 데이터는 유지한다.
## Proposed Success Criteria
- 현재 명령이 연결된 community 안에서만 조회한다.
- 인자 전체를 예전 닉네임으로 취급하여 공백이 포함된 닉네임을 지원한다.
- 닉네임은 앞뒤 인자 공백을 제거한 후 정확히 일치하는 값으로 조회한다.
- `riotAccounts`가 있는 기존 user를 이관 대상으로 삼는다.
- 대상 없음, 중복 닉네임, 다른 user의 현재 카카오 ID 점유는 변경 없이 안내한다.
- 성공 시 기존 user의 `kakaoTalkId`만 변경하고 발신자에게 완료를 안내한다.
- 동일 ID로 재시도하면 이미 연결된 상태로 안내한다.
- 동시 변경과 DB 중복 키 오류를 처리하며 새 user를 생성하거나 병합하지 않는다.
## Tech Stack / Project Structure
NestJS 11, TypeScript, Mongoose 9, Jest 30, pnpm workspace.
`apps/api/src/modules/dakao/`의 parser, handler, service, module 및 명령 라우팅을 사용한다.
테스트는 구현 옆 `*.spec.ts`, 명세는 `docs/specs/`에 둔다.
## Commands
- 관련 테스트: `pnpm --filter api test --runInBand dakao`
- 전체 API 테스트: `pnpm --filter api test --runInBand`
- 빌드: `pnpm --filter api build`
- 변경 파일 lint: `pnpm --filter api exec eslint <changed-files>`
- 개발 실행: `pnpm --filter api start:debug`
## Code Style
기존 Injectable handler/service와 discriminated command union 패턴을 따른다.
```typescript
return { kind: 'data-transfer', previousNickname: args };
```
## Testing Strategy
구현 전 실패 테스트를 작성한다. 파싱, 커뮤니티 범위, 성공 후 기존 데이터 보존,
대상 없음/중복, ID 충돌, 재시도, 동시 갱신 실패 및 라우팅/응답을 검증한다.
관련 테스트 후 전체 API 테스트와 빌드를 수행한다.
## Boundaries
- Always: 커뮤니티 범위 제한, 입력 검증, 기존 user 식별자 및 연결 데이터 보존.
- Ask first: 스키마 변경, 의존성 추가, 기존 user 병합/삭제.
- Never: 운영 DB 직접 수정, 비밀값 커밋, 실패 테스트 제거.
## Confirmed Policy
사용자 확인: `riotAccounts`가 등록된 user를 뜻한다. Riot 계정 검증 및 소유권
확인은 하지 않으며 운영으로 통제한다. 예전 닉네임으로 조회하여 ID만 변경한다.
## Implementation Plan and Tasks
1. 이관 서비스: `dakao-user.service.ts` 및 전용 테스트 파일.
- 수락 조건: 기존 데이터 보존, 대상/충돌/재시도/동시 변경 처리.
- 검증: 실패 테스트 확인 후 서비스 테스트 통과.
2. 명령 parser 및 handler: 구현과 각각의 테스트 4개 파일.
- 수락 조건: 공백 포함 닉네임 파싱, 빈 입력 사용법, 결과별 한국어 응답.
- 검증: parser/handler 테스트 통과. 작업 1에 의존.
3. subscriber 및 module 연결: 구현 2개와 subscriber 테스트.
- 수락 조건: 현재 커뮤니티/발신자 ID 전달, 도움말 노출.
- 검증: Dakao 테스트, 전체 API 테스트, 빌드, 변경 파일 lint. 작업 2에 의존.
위험: 동시에 이관되는 user는 기존 ID를 조건으로 갱신하여 덮어쓰기를 막고,
새 ID 동시 점유는 기존 unique 인덱스 오류를 충돌 응답으로 변환한다.
각 단계에서 테스트를 확인하고 다음 단계로 진행한다.
## Verification Results
- 서비스, parser/handler, subscriber 테스트는 기능 미구현 상태의 실패를 확인한 후 통과.
- Dakao: 16 suites / 92 tests 통과.
- API 전체: 99 suites / 634 tests 통과, 기존 테스트 2개 실패.
- `api-performance-report.spec.ts`: Windows `path.relative`의 역슬래시와 기대값 불일치.
- `secret.service.spec.ts`: 환경변수에 의존해 누락된 bootstrap secret의 기대 키 불일치.
- 두 테스트는 변경하지 않은 파일이며 별도 실행에서도 같은 실패 재현.
- API 빌드, 변경 TypeScript 파일 ESLint, `git diff --check` 통과.
- 로컬 실행 환경 Node 24.15.0; 저장소 엔진 요구사항은 Node 26.
- 실제 카카오톡 메시지 전송 및 운영 DB 이관은 실행하지 않음.
- 코드 검토: 커뮤니티 제한, 정확한 닉네임 조회, 등록 계정 필터,
ID만 갱신하는 조건부 업데이트, 충돌 응답, DI 및 명령 라우팅 확인.
## Usage
새 방에서 `!내전 데이터이관 예전 닉네임`을 실행한다. 따옴표 없이 공백을 포함한
닉네임 전체를 입력할 수 있다. 새 ID로 이미 user가 생성되어 있으면 자동 병합하지
않고 운영자 문의를 안내한다. 소유권 확인은 운영 정책으로 통제한다.
@@ -75,7 +75,7 @@
세트의 기본 헤더에는 `2:0`도, 세트 승패를 숫자로 바꾼 `1:0`도 넣지 않는다. 필요하면 별도 `시리즈 최종 2:0` 또는 `시리즈 현재 1:0`을 함께 표시한다. `현재/최종`은 공식 시리즈 상태가 결정한다. 동일 두 팀이 승자조와 결승에서 다시 만나면 별개의 `seriesId`와 세트 목록을 가진다.
표의 라운드 이름은 설명용 예시다. 화면에서는 기존 공식 대진의 라운드 이름을 공용 함수로 재사용하고 내전 상세, 전적, 팀 진행 사이에서 같은 이름을 쓴다. [기존 팀 진행 명세](team-progress-page-ux-refresh.md)
표의 라운드 이름은 설명용 예시다. 화면에서는 기존 공식 대진의 라운드 이름을 공용 함수로 재사용하고 내전 상세, 전적, 팀 진행 사이에서 같은 이름을 쓴다. [라운드 이름 공용 함수](../../apps/web/src/components/competition/double-elimination-bracket-layout.ts#L202)
| 시리즈/슬롯 상태 | 화면 문구와 점수 |
| --- | --- |
-175
View File
@@ -1,175 +0,0 @@
# Spec: Refresh Riot ID by PUUID
## Objective
Whenever an account is refreshed manually from the personal match-history page
or automatically by the stale-account background scheduler, resolve its current
Riot ID through Riot Account-V1 using the stored PUUID. If the player changed
either their game name or tag line, persist the latest values on the same embedded
Riot account so the profile displays the new Riot ID.
The existing refresh job remains the single user-facing operation. It continues
to refresh matches and ranked data, and additionally refreshes identity before
emitting its completion event.
## Approved Product Decisions
- Use the stored PUUID as the stable identity key; never look up the account by
the possibly stale game name and tag line.
- Query Riot Account-V1 on every manually queued user-history refresh job and
every selected stale-account background refresh rather than applying a name TTL.
- Update `gameName` and `tagLine` together only when Riot returns a matching PUUID
and both values are non-empty.
- Preserve the previous Riot ID if the Account-V1 lookup fails or returns an
incomplete or mismatched response.
- Treat identity refresh as best effort, matching the existing ranked-data refresh
policy: log a failure but allow successful match refresh work to complete.
- When a caller does not already know the Riot regional route, resolve it from the
user's community and fall back to `asia` only when the community has no route.
- Do not increment the background failure counter or enter backoff solely because
the identity lookup failed; background statistics enrichment retains its
existing success and failure semantics.
- Reuse the existing refresh completion event and profile-query invalidation; do
not add a new endpoint, response field, socket event, or frontend state path.
- Update only the embedded Riot account used by the personal profile. Historical
match snapshots retain the names recorded by Riot for those games.
## Tech Stack
- NestJS 11, TypeScript 5, Mongoose 9, and Jest under `apps/api`
- Riot Account-V1 through the existing `RiotAccountService`
- Redis stream jobs through the existing `RiotJobWorkerService`
- Scheduled stale-account refresh through `BackgroundRefreshScheduler`
- React Query profile invalidation already present in `UserHistoryPage`
## Commands
- Focused tests:
`pnpm --filter api exec jest --runInBand riot-account-enrichment.service.spec.ts riot-job-worker.service.spec.ts background-refresh.scheduler.spec.ts`
- API lint: `pnpm --filter api lint`
- API build: `pnpm --filter api build`
- Web lint: `pnpm --filter web lint`
- Web production build: `pnpm --filter web build:prod`
## Project Structure
- `apps/api/src/modules/riot/riot-account.service.ts` owns the validated
Account-V1 PUUID lookup.
- `apps/api/src/modules/riot/riot-account-enrichment.service.ts` owns the
persistence boundary for the embedded Riot account.
- `apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts` verifies
update, no-op, and failure behavior.
- `apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts` orchestrates
identity, match, and ranked refresh work before completion.
- `apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts` verifies
that a personal-history refresh job requests the PUUID-based identity refresh.
- `apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts`
orchestrates best-effort identity refresh for stale accounts before statistics
enrichment.
- `apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.spec.ts`
verifies background invocation, ordering, and failure isolation.
- `apps/web/src/pages/UserHistoryPage.tsx` already invalidates the profile query
when the refresh socket reports completion and is not modified in this scope.
## Internal Contract
Add one focused method to `RiotAccountEnrichmentService`:
```ts
type RefreshRiotIdentityResult = "updated" | "unchanged" | "failed";
refreshRiotIdentity(params: {
userId: mongoose.Types.ObjectId;
puuid: string;
region?: RiotRegionalRoute;
}): Promise<RefreshRiotIdentityResult>;
```
`updated` means both persisted Riot ID fields now match Account-V1. `unchanged`
means the validated response matched the stored values and no database write was
needed. `failed` means no stored account could be resolved or the external lookup
could not safely provide a complete identity; stored values remain unchanged. If
`region` is omitted, the service resolves the user's community and uses its
configured `riotRegion`, falling back to `asia` only when unavailable.
## Code Style
Keep the external validation and persistence decision explicit:
```ts
const identity = await this.accountService.getByPuuid(puuid, { region });
if (identity.puuid !== puuid || !identity.gameName || !identity.tagLine) {
return "failed";
}
```
Use existing single quotes, NestJS logging, Mongoose document mutation, and
Prettier formatting. Do not add a generic identity abstraction or new dependency.
## Testing Strategy
- Write the enrichment-service tests first and confirm they fail before adding
the new method.
- Verify a changed game name and tag line are persisted together.
- Verify identical values return `unchanged` without saving.
- Verify missing values, PUUID mismatch, and Riot lookup errors return `failed`
without overwriting or saving the stored identity.
- Write the worker orchestration expectation before calling the new method.
- Verify a region-less identity refresh uses the user's configured community
region.
- Write background scheduler expectations before adding identity refresh to the
stale-account loop.
- Verify identity refresh happens before statistics enrichment and that a rejected
identity lookup does not increment background failure counters.
- Run focused API tests after each slice, then API lint/build and web lint/build
to verify the existing client integration remains valid.
## Boundaries
### Always
- Use the stored PUUID for Account-V1 lookup and verify the returned PUUID.
- Validate both Riot ID fields before mutating the database.
- Preserve the current Riot ID on any unsafe or failed response.
- Keep the existing refresh route, enqueue response, and socket event compatible.
- Keep background identity failures independent from enrichment failure counters.
- Run focused tests before broader lint and build verification.
### Ask First
- Add a database field or migration.
- Change refresh failure semantics so an identity lookup failure fails the whole
user-history job.
- Update historical match snapshots or active match participant display names.
- Add a new API response field, endpoint, dependency, or Redis job type.
- Commit, push, deploy, or alter CI configuration.
### Never
- Resolve identity from the stale stored Riot ID.
- Partially update only the game name or only the tag line.
- Replace a valid stored identity with empty or mismatched Account-V1 data.
- Expose Riot API errors or credentials to the browser.
- Mix the change with the separate past-history result-column PR.
## Success Criteria
- Clicking `정보 갱신` causes the queued worker to call Account-V1 by the stored
PUUID.
- Selecting a stale account for background refresh also calls Account-V1 by the
stored PUUID before statistics enrichment.
- A changed Riot game name or tag line is persisted on the matching embedded
account before the completion event is broadcast.
- The completion event triggers the existing profile-query invalidation, so the
personal history header displays the latest `gameName#tagLine`.
- Failed, incomplete, or mismatched Riot identity responses do not overwrite the
existing Riot ID and do not prevent otherwise successful match refresh work.
- Background identity lookup failures do not increment the account failure counter
or prevent otherwise successful background enrichment.
- Focused tests, API lint/build, and web lint/production build pass.
## Open Questions
None. The user approved this specification and requested implementation. The
existing queue and UI invalidation paths support the behavior without a public
contract change.
-162
View File
@@ -1,162 +0,0 @@
# Spec: Series Result History UI
## Objective
Replace the compact `Game N - winner` cards below Competition brackets with a
chronological, Series-centric result history. Users should be able to scan when a
Series was played, its round, participants, official result, and current score,
then expand the row to inspect the accepted Games that produced that record.
This first version is a truthful activity/result history, not a future schedule.
It uses only recorded Competition projection data and does not invent scheduled
times, venues, replay links, or team logos.
## Approved Product Decisions
- Keep the bracket first as the topology view and place the chronological history
below it.
- Render one primary row per Series, never one primary row per Game.
- Include a started `in-progress` Series when it has at least one accepted Game, so
completed Games do not disappear while a best-of Series is still running.
- Include every completed Series, including draw, walkover, forfeit, and
administrative outcomes with no accepted Game.
- Exclude inactive, waiting, ready, and game-less in-progress Series because they do
not have a truthful result timestamp.
- Use the earliest accepted Game `startedAt` as the Series activity time. For a
game-less decision, group by `outcome.completedAt` but display no fake start time.
- Group and format dates explicitly in `Asia/Seoul`.
- Keep individual Games in a native, keyboard-accessible disclosure below the Series
row.
- Make each disclosed Game row a real link to its internal-stat Game detail. Keep the
visible Series-local `ordinal`, but build the route from the globally unique
`displayNumber`.
- Preserve the current Competition page path in router state so the detail page can
return users to the same result view.
- Use the coral semantic primary token as an interaction cue on Game links (leading
edge, focus ring, subtle state background, and arrow), not as a winner or score
color.
- Scope that primary override to the result-history section so the exact coral remains
consistent in light and dark themes without changing unrelated dark-theme actions.
## Tech Stack
- React 19 and TypeScript 6 under `apps/web`
- Tailwind CSS 4 and daisyUI semantic tokens
- Shared Competition contracts from `@lolympus/contracts`
- Node's built-in test runner with TypeScript type stripping for pure model tests
## Commands
- Focused RED/GREEN test:
`pnpm --filter web exec node --test --experimental-strip-types test/competition-series-history.test.ts`
- Full web tests: `pnpm --filter web test`
- Web lint: `pnpm --filter web lint`
- Web build: `pnpm --filter web build`
## Project Structure
- `apps/web/src/components/competition/competition-series-history.ts` derives the
stable, timezone-aware history view model without React.
- `apps/web/src/components/competition/CompetitionSeriesHistory.tsx` renders the
semantic date sections and responsive Series rows.
- `apps/web/src/components/competition/CompetitionGameHistory.tsx` renders the
disclosed, navigable Game rows and their responsive interaction states.
- `apps/web/src/components/competition/CompetitionResults.tsx` replaces the existing
completed-Game card grid with the new component and supplies the route context.
- `apps/web/src/lib/internal-match-game-selection.ts` keeps explicit Game-detail
routes from silently falling back to a different recorded Game.
- `apps/web/test/competition-series-history.test.ts` specifies aggregation, ordering,
outcome, and formatting behavior.
## Code Style
Use contract discriminators and team IDs as the source of truth:
```ts
const shouldInclude =
(series.status === "in-progress" && games.length > 0) ||
series.status === "completed";
const winnerTeamId =
series.status === "completed" && series.outcome.type !== "draw"
? series.outcome.winnerTeamId
: undefined;
```
The UI uses flat, full-width rows and existing semantic tokens. It does not reuse
the bordered bracket card layout or introduce new dependencies.
## Testing Strategy
Develop the pure model test-first. Cover:
- Games aggregated by `seriesId` and ordered by Series-local `ordinal`;
- Series score preserved from A/B entries even when blue/red sides change;
- chronological ordering independent of projection graph order;
- `Asia/Seoul` grouping across the UTC day boundary;
- started in-progress Series and game-less completed decisions;
- exclusion of unstarted and orphan data;
- played, draw, walkover, forfeit, and administrative status semantics;
- deterministic tie-breaking and legacy zero-duration formatting.
- Game-detail route generation from `displayNumber`, including rejection of invalid
legacy display numbers.
- Exact internal Game selection, including a missing-result case when the requested
display number is absent from a stale or legacy detail payload.
After unit tests, run full web tests, changed-file lint, and the TypeScript/Vite build.
Review the markup for native keyboard interaction, heading order, visible status text,
and mobile layouts down to 320px.
## Boundaries
### Always
- Use `series.entries` for A/B score and `outcome.winnerTeamId` for the official
winner; never infer identity from score, array position, or blue/red side.
- Keep game-less adjudications visible without presenting `0 : 0` as a played score.
- Omit `durationSeconds === 0` because it represents missing legacy data.
- Use `displayNumber`, never Series-local `ordinal`, for the internal Game URL.
- Keep each Game row as one semantic anchor with no nested interactive control.
- Keep link text readable in both themes; coral may indicate interaction but must not
be the only visible cue.
- Never substitute another Game when the Game number explicitly requested by the URL
is not present in the internal-stat payload.
- Preserve all unrelated working-tree changes.
### Ask First
- Change the public Competition contract, database schema, or projector.
- Add Series scheduling or external replay/venue data.
- Add a frontend dependency or test framework.
### Never
- Present `completedAt` as a scheduled or actual start time.
- Reuse free-text `match.schedule` as official Series scheduling data.
- Parse `series.code` for identity, winner, or ordering.
- Make status or winner understandable only through color.
## Success Criteria
- A completed `2 : 1` Series appears as one chronological row with both teams, the
official score, round label, status, and an expandable three-Game history.
- In-progress Series retain already accepted Games and display `진행 중`.
- No-game decisions appear with the correct decision label and no misleading score
or start time.
- Date grouping and time display are stable in `Asia/Seoul` regardless of runtime
timezone.
- The layout is readable without horizontal scrolling at 320px and uses the wider
double-elimination page naturally on desktop.
- Each recorded Game can be opened by pointer or keyboard, lands on its matching
internal-stat Game, and provides a return link to the Competition result page.
- A temporarily stale or inconsistent detail payload shows an explicit missing-Game
state rather than silently rendering the first Game.
- Game rows expose an always-visible detail cue and coral hover, active, and focus
affordances without changing winner semantics.
- Focused/full tests, changed-file lint, and web build pass without modifying
unrelated work.
## Open Questions
None. The user approved the Series-centric, result-history-first direction and
requested implementation.
-150
View File
@@ -1,150 +0,0 @@
# Spec: Team Progress Page UX Refresh
## Objective
Reorganize the team progress page around the participant's primary task: identify
the next opponent, understand the Series state, and copy the correct tournament
code without cross-referencing separate sections. Keep the existing Competition
API and visual language while making status, adjudicated results, copy feedback,
the roster, and past results clearer on desktop and mobile.
The primary user is a team participant preparing to join an official internal-match
game. Success means every active Series and its codes form one understandable work
area, human-facing Korean labels lead internal identifiers, and the copy flow is
accessible and explicit.
## Approved Product Decisions
- Group tournament codes under their matching active Series using `seriesId`.
- Label a Series-local game as `1세트`, `2세트`, and so on; retain global
`Game 19`-style numbers only as secondary metadata.
- Use the bracket's canonical visible round names from Competition round metadata:
upper round 1 is `브래킷 1R`, later upper rounds are `브래킷 상위 nR`, and
lower rounds are `브래킷 하위 nR`. Retain raw Series codes such as `WB_FINAL`
as secondary diagnostic text.
- Show pre-start and adjudicated Series without misleading `0–0` scores.
- Distinguish `부전승`, `기권승`, `판정승`, and `무승부` using the existing
outcome discriminator. Do not invent a free-form reason that is not public data.
- Make copy targets at least 44 CSS pixels high, uniquely label each button, keep
the complete code visible/selectable, and announce copy success or failure.
- Order the page as header, next matches with codes, compact roster, then recent
results. Show two recent results and collapse older entries.
- Preserve existing loading, selection, empty, error, revision-consistency, and
authorization behavior.
## Tech Stack
- React 19 and TypeScript 6 under `apps/web`
- Tailwind CSS 4 and daisyUI 5 using the repository's square bordered surfaces
- Node's built-in test runner for pure view-model behavior
- Existing `lucide-react` icon set; no new dependency
## Commands
- Focused tests: `pnpm --filter web exec node --test --experimental-strip-types test/match-team-progress-view.test.ts`
- Full web tests: `pnpm --filter web test`
- Web lint: `pnpm --filter web lint`
- Web build: `pnpm --filter web build`
- Development server: `pnpm --filter web start:dev`
## Project Structure
- `apps/web/src/pages/MatchTeamProgressPage.tsx` owns queries, snapshot guards,
page ordering, and top-level team navigation.
- `apps/web/src/pages/match-team-progress-view.ts` owns pure grouping, ordering,
labels, code state, and copy-result behavior.
- `apps/web/src/components/competition/double-elimination-bracket-layout.ts`
remains the canonical source for visible bracket round names.
- `apps/web/src/components/competition/TeamTournamentCodes.tsx` owns code rows and
clipboard feedback.
- `apps/web/src/components/competition/TeamSeriesCard.tsx` owns the page-specific
Series summary, leaving bracket/history card geometry and behavior unchanged.
- `apps/web/test/match-team-progress-view.test.ts` specifies the new pure behavior.
## Code Style
Keep data transformation outside React and render semantic native controls:
```ts
const seriesCodes = tournamentCodesForSeries(
teamView.tournamentCodes,
series.seriesId,
);
<button aria-label={`${setLabel} 토너먼트 코드 복사`}>
복사
</button>
```
Use `text-content-subtle` and `text-content-muted` for secondary text. Semantic
colors may provide a border or background accent, while normal-size text remains a
high-contrast base-content color.
## Testing Strategy
- Test code-to-Series association by exact `seriesId` and deterministic ordinal
ordering before adding the UI.
- Test bracket-aligned round labels, code availability/expiry state, unique copy
labels, and explicit clipboard success/failure results as pure functions.
- Test every page-specific Series lifecycle/outcome branch, including played and
administrative draws, so the local summary cannot drift silently.
- Run the complete web suite, lint, and build after the focused tests pass.
- When the in-app browser is available, runtime verification covers 320px, 768px,
1024px, and 1440px; keyboard focus, copy announcements, long-code reflow, and
console output are checked manually.
## Boundaries
### Always
- Join assignments to active Series only by the contract's `seriesId`.
- Keep the full tournament code selectable and copy the unmodified string.
- Preserve native link, button, list, table, heading, and disclosure semantics.
- Use the existing design tokens and icon dependency.
### Ask First
- Change the API or public contract.
- Add a dependency or browser-test framework.
- Change tournament-code authorization or visibility policy.
- Deploy, push, or alter CI.
### Never
- Infer a Series association from global game numbers.
- Display an adjudicated `0–0` as if it were a played result.
- Expose private facts or fabricate an adjudication reason.
- Hide copy failure or rely on color alone for state.
- Modify unrelated Competition, bracket, or theme behavior.
## Success Criteria
- Each active Series appears as a full-width next-match panel containing only its
own ordered code rows.
- Bracket-aligned labels lead raw Series codes, and Series-local set numbers lead
global game numbers.
- Ready Series show a pending score, while adjudicated results show their result
category instead of a numeric score.
- Copy buttons have unique accessible names, 44px targets, visible/live feedback,
and an explicit failure path.
- The roster uses Korean position labels in canonical role order, with the captain
marker close to the player name.
- At most two recent results are expanded by default; older results are available
through a keyboard-accessible disclosure.
- Focused and full tests, scoped lint, and build pass. Responsive runtime review is
recorded separately when the in-app browser is available.
## Verification Record
- Focused view-model tests: 9 passed.
- Full web suite: 88 passed without skips.
- Scoped ESLint for all team-progress files: passed.
- Production TypeScript/Vite build: passed; only the existing large-chunk warning
remains.
- Full repository lint remains blocked by pre-existing errors in unrelated files.
- Runtime screenshot/keyboard verification was not claimed because the required
in-app browser was unavailable in this session.
## Open Questions
None. The user approved the audit recommendations and requested implementation.