Compare commits

...

91 Commits

Author SHA1 Message Date
864dbffa6f docs: refresh UI registry contract 2026-08-10 11:18:47 +09:00
0006e91779 docs: adopt AI agent harness 2026-08-07 15:45:05 +09:00
f6441c6a6c Merge pull request '260720_01_ENH: 보유 대수 소수점 2자리까지 풀음, profile(전체) 추가' (#10) from develop into master
Reviewed-on: #10
2026-07-20 14:52:26 +09:00
1da20a1fb6 260720_01_ENH: 보유 대수 소수점 2자리까지 풀음, profile(전체) 추가 2026-07-20 14:38:25 +09:00
d1dc3fe6fa Merge pull request '260511_01_ENH: year가 고정으로 들어가 있던 버그 수정' (#9) from develop into master
Reviewed-on: #9
2026-05-11 17:01:50 +09:00
50e1ea19cc 260511_01_ENH: year가 고정으로 들어가 있던 버그 수정 2026-05-11 16:58:04 +09:00
fc43eab6fc 260402_03_ENH: 워딩 수정 2026-04-02 16:03:32 +09:00
7474d4d3d4 260402_03_ENH: 워딩 수정 2026-04-02 15:56:36 +09:00
01208b5b24 Merge branch 'develop' 2026-04-02 14:49:01 +09:00
d6f4bca06f 260402_02_ENH: LG 보급률, 구매율 워딩을 자사제품 비율(%)로 수정 2026-04-02 14:48:39 +09:00
563f98c6f2 Merge branch 'develop' 2026-04-02 14:35:07 +09:00
20b8547701 260402_01_ENH: LG 보급률, 구매율의 자사제품 비율 공식 워딩 하단으로 이동 및 카테고리 파트 갭에 배경색 추가 2026-04-02 14:34:45 +09:00
b740cc27fa Merge pull request '260401_05_ENH: 전기레인지 화구 수 문항 추가' (#8) from develop into master
Reviewed-on: #8
2026-04-01 17:24:25 +09:00
9b3a21ea39 260401_05_ENH: 전기레인지 화구 수 문항 추가 2026-04-01 17:19:56 +09:00
f4f487ca10 Merge pull request '260401_04_ENH: Total Filter multi-select 가능하게 수정 및 DEBOUNCE_TIME 상수화' (#7) from develop into master
Reviewed-on: #7
2026-04-01 15:24:22 +09:00
3c7865ef60 260401_04_ENH: Total Filter multi-select 가능하게 수정 및 DEBOUNCE_TIME 상수화 2026-04-01 14:39:21 +09:00
849245818c Merge pull request 'develop' (#6) from develop into master
Reviewed-on: #6
2026-04-01 11:26:45 +09:00
26848901cf 260401_03_ENH: fillGreaterThan5 5 초과가 아닌 이상으로 수정 2026-04-01 09:59:29 +09:00
3a42ac867c 260401_02_ENH: 브랜드의 gap 부분 2개 연도 나올수 있도록 수정 2026-04-01 09:49:17 +09:00
ebc72e57c2 260401_01_ENH: 누락 내용 주석 풀고 음영 표시의 경우 Brand 뿐만아니라 다른 페이지에도 적용 2026-04-01 09:30:41 +09:00
f6b5b21cb2 260331_08_ENH: 누락 내용 주석으로 추가(고객사 요청 시 풀것) 2026-03-31 17:57:11 +09:00
59943b2e45 260331_07_ENH: 보급률 변화 페이지 하단에 Gap대문자로 변경 2026-03-31 16:43:35 +09:00
c67971f803 260331_06_ENH: 보급률 변화 페이지 하단에 Gap에 대한 문구 추가 2026-03-31 15:58:58 +09:00
882a5f046a 260331_05_ENH: 차트에 사례수 흘러들어가지 않도록 조치 2026-03-31 14:46:50 +09:00
8540df7274 260331_04_ENH: 일부 헤더 워딩에 줄바꿈 추가2 2026-03-31 11:33:05 +09:00
dc9b2baeb1 260331_03_ENH: 일부 헤더 워딩에 줄바꿈 및 띄어쓰기 추가 2026-03-31 11:29:26 +09:00
d58c0b4dd4 260331_02_ENH: 그룹 헤더 다단도 가능하게 수정 2026-03-31 11:08:30 +09:00
5b2811fd86 Merge pull request '260331_01_ENH: CAGR 셀 색칠 기준 5초과에서 5이상으로 변경' (#5) from develop into master
Reviewed-on: #5
2026-03-31 08:46:50 +09:00
e51c6ba810 260331_01_ENH: CAGR 셀 색칠 기준 5초과에서 5이상으로 변경 2026-03-31 08:19:06 +09:00
3dc735722d Merge pull request '260330_02_ENH: 연도별 사례수 row에서 Column으로 이동' (#4) from develop into master
Reviewed-on: #4
2026-03-30 17:01:29 +09:00
a0ee062899 260330_02_ENH: 연도별 사례수 row에서 Column으로 이동 2026-03-30 16:59:51 +09:00
8fff3ec908 Merge pull request 'develop' (#3) from develop into master
Reviewed-on: #3
2026-03-30 14:07:20 +09:00
7f9465e96f 260330_01_ENH: 26일자 수정사항 반영(라이프스테이지 중분류 제외) 2026-03-30 13:18:08 +09:00
ee8bb13209 260326_02_ENH: 테이블 4종 통합 및 BaseTable 생성 2026-03-26 10:52:31 +09:00
8133ab1ee4 260326_01_ENH: 일부 설정 파일들 리펙토링 2026-03-26 09:55:04 +09:00
2052c84371 260325_02_ENH: 주거형태 필터 원룸 추가 수정 2026-03-25 11:23:12 +09:00
8a6216ef02 260325_01_ENH: 연령대 필터 값 수정 2026-03-25 11:08:00 +09:00
ffeee5bef2 260326_01_ENH: categoryByData 배너 부분 순서 조정 2026-03-24 18:51:41 +09:00
836f756a42 260324_01_ENH: 로그인 response types/auth로 이동 2026-03-24 15:32:02 +09:00
b2cf1b846f 260319_01_ENH: 17일자 수정사항 적용 2026-03-19 14:05:19 +09:00
c66b51ca53 260313_01_ENH: 연도가 있는 문항 내용에 필터 연도 적용 2026-03-13 10:23:18 +09:00
72e18adb03 260312_04_ENH: 카테고리 파트 설문문항 top margin 수정 2026-03-12 16:07:02 +09:00
b39c3e8ef9 260312_03_ENH: 카테고리 파트 설문문항 노출 적용 2026-03-12 16:05:47 +09:00
1751a5071a 260312_02_ENH: 스택차트 색상 11개에서 13개로 수정 2026-03-12 14:18:04 +09:00
41a8e2abb2 260312_01_ENH: API_DECIMAL_POINT, VIEW_DECIMAL_POINT 적용, 스택 차트 색상 변경, 그룹 스택 차트 하단에 연도 레이블 출력, Total 페이지 설명문 수정 2026-03-12 13:28:21 +09:00
75153ff02e 260311_03_ENH: overlay차트에서 비율 바이 비율 제거 제품 순서 틀린것 수정 2026-03-11 17:38:11 +09:00
497301e102 260311_02_ENH: api useCache Const로 일괄 관리 2026-03-11 17:20:07 +09:00
eee25ea68f 260311_01_ENH: Console.log clear 및 구매율 투입변수 수정 2026-03-11 17:14:50 +09:00
1159993c62 260303_02_ENH: CAGR 관련 수정 2026-03-03 16:58:46 +09:00
1c2dcb6fd5 260303_01_ENH: 카테고리 파트 구조 정리 2026-03-03 16:27:05 +09:00
4bdb705720 260226_05_ENH: 카테고리 파트 옵션으로 ChartLegend, ChartTopMargin 추가 2026-02-26 11:56:53 +09:00
9df181e6dc 260226_04_ENH: LG전자 수정사항 적용 2026-02-26 11:35:10 +09:00
11321c483b Merge pull request '260226_03_ENH: 통계 정보 호출 캐시 미사용 api들 캐시 사용으로 변경' (#2) from develop into master
Reviewed-on: #2
2026-02-26 11:10:15 +09:00
011c727cd6 260226_03_ENH: 통계 정보 호출 캐시 미사용 api들 캐시 사용으로 변경 2026-02-26 11:09:28 +09:00
40b6ddb553 Merge pull request '260226_02_ENH: KART API 생성 제거' (#1) from develop into master
Reviewed-on: #1
2026-02-26 11:06:52 +09:00
404e5f7351 260226_02_ENH: KART API 생성 제거 2026-02-26 11:06:10 +09:00
e7688c127c 260226_01_ENH: dev prod api주소 변경 2026-02-26 11:01:26 +09:00
6b118dd7ec 260225_02_ENH: KART 사용 안하기 때문에 API 땜 2026-02-25 17:03:38 +09:00
357d9f2946 260225_01_ENH: 실제 Data 통계 API와 연결 및 일부 페이지 축소 2026-02-25 16:48:12 +09:00
d0e1352739 260210_01_ENH: Reverse StackBar legend 뒤집기 2026-02-10 15:01:31 +09:00
edfecfcea4 260209_04_ENH: 프로필 페이지에서 단위 텍스트 제거 2026-02-09 16:49:14 +09:00
49ae6ff37e 260209_03_ENH: 필터 영역 디자인 통일 2026-02-09 16:44:24 +09:00
0a81c1a748 260209_02_ENH: word break 모드 변경 및 전체파트 table 영역 조정 2026-02-09 16:37:23 +09:00
6e6120f205 260209_01_ENH: 테이블에 단위 텍스트 추가, 하단 설명 추가 2026-02-09 16:28:29 +09:00
b7282bd07d 260206_07_ENH: 필터 아이콘 추가 및 api통신에 캐시 기능 추가, LIFE_STAGE_COLUMNS에 미혼, 독립 시니어 rowspan 적용 2026-02-06 16:30:29 +09:00
17d75e3f3a 260206_06_ENH: LG 보급률 하위 테이블에 설명 영역 확보 2026-02-06 09:53:56 +09:00
6b5454aa59 260206_05_ENH: Chart 색상에서 hsl 함수 제거 2026-02-06 09:21:25 +09:00
b13f508065 260206_04_ENH: Chart 색상 유틸 수정 2026-02-06 09:15:38 +09:00
ea14a230a1 260206_03_BUG: import 버그 수정 2026-02-06 09:08:46 +09:00
0ff202afcc 260206_02_BLD: 로그인 API 롤백 2026-02-06 09:05:28 +09:00
bd9a95b87f 260206_01_ENH: 일부 차트색상 변경, 브랜드별 차트 부분 색상 변경 필요 2026-02-06 09:03:29 +09:00
21989aeeb7 260205_06_ENH: 보유 경로 차트 높이 수정 2026-02-05 16:56:14 +09:00
84675b77b3 260205_05_ENH: 1차 lg 수정 요청사항 반영 2026-02-05 16:54:55 +09:00
8c015bd443 260205_04_ENH: 빠진 아이콘 추가 2026-02-05 12:25:21 +09:00
8de707f8d1 260205_03_ENH: layout color gray + black으로 변경, excel버튼 아이콘으로 변경 2026-02-05 12:22:18 +09:00
5d3de68b05 260205_02_CLN: 안쓰는 import 정리 2026-02-05 10:05:19 +09:00
3e7c2a98df 260205_01_ENH: 페이지 별 엑셀 다운로드 적용 2026-02-05 09:24:19 +09:00
544f3010aa 260204_01_ENH: 카테고리 하위 페이지들 경로명 수정 2026-02-04 12:07:35 +09:00
0b693661f3 260202_04_ENH: Total 하위 페이지들에 useMemo 적용 및 LifeStyle 샘플 데이터 전체 값 조정 2026-02-02 15:21:53 +09:00
84560cef2d 260202_03_ENH: 페이지 깜빡임 최소화 및 카테고리에서 전체로 이동 시 페이지 렌더링 2회 되는 부분 수정 2026-02-02 15:05:11 +09:00
0950679874 260202_02_ENH: 구매 채널에 온/오프라인 네팅 데이터 추가 2026-02-02 12:30:48 +09:00
6f8e09bcf3 260202_01_ENH: route 구조 초창기 기획으로 다시 변경 및 Category 별 하위 페이지에 샘플 데이터 모두 적용 2026-02-02 11:32:50 +09:00
4b40c43962 260129_01_ENH: 카테고리 파트 layout 및 route 구조 변경 2026-01-29 13:42:42 +09:00
d48decab52 260128_04_ENH: 보급률 하단 카드 legend 크기 키우고 border 적용 2026-01-28 17:08:55 +09:00
d7cb9259cd 260128_03_ENH: 샘플데이터 랜덤 적용, lg 보급률 하단 카드 + 게이지 테이블 적용 2026-01-28 17:01:40 +09:00
4c00cfa946 260128_02_TST: 젠킨스 커밋 메시지 테스트 제거 2026-01-28 10:58:02 +09:00
14523e840d 260128_01_TST: 젠킨스 커밋 메시지 테스트 2026-01-28 10:53:37 +09:00
8bfa8fa7c4 260127_01_ENH: 커스텀 컴포넌트들 1차 완성 및 일부페이지에 SampleData 적용 2026-01-27 16:59:24 +09:00
76c2626507 260123_05_BUG: 환경변수 버그 수정 2026-01-23 15:45:34 +09:00
5e43d640a2 260123_04_BUG: 환경변수 버그 수정 2026-01-23 15:05:13 +09:00
6588278e0f 260123_03_BUG: 인증 커스텀 훅 버그 수정 2026-01-23 14:55:05 +09:00
104 changed files with 8937 additions and 531 deletions

18
.agent/profile.yml Normal file
View File

@@ -0,0 +1,18 @@
schema_version: 1
project:
id: lge-cx-dash-front
name: LGE CX Dashboard Frontend
type: requested-project
layer: frontend
legacy: false
stack:
- typescript
- react
- nextjs
shared_contracts:
consumes:
- kri-front-common
- kri-ui-registry

20
.agent/project.md Normal file
View File

@@ -0,0 +1,20 @@
## LGE CX Dashboard Frontend Repository Rules
### Deliverable and User Experience
- This Next.js frontend visualizes LGE appliance penetration, purchase, category, profile, and trend survey statistics.
- Treat approved planning and design material as the scope boundary. Preserve category navigation, filters, labels, chart/table values, comparison context, and Excel export behavior.
- A visual change must not silently alter the represented statistic, denominator, ordering, rounding, tooltip meaning, or empty-data behavior.
- Keep customer survey data, exported workbooks, and internal planning material out of logs, fixtures, screenshots, and external services.
### Frontend Implementation
- Use the consumed KRI frontend common and UI registry contracts. Prefer an existing shadcn/ui or registry component before creating a new foundational component.
- Do not create new TypeScript type or interface names ending in `Dto` or `DTO`.
- Preserve accessibility, responsive layout, loading, empty, error, unauthorized, and export states across every dashboard route.
- Coordinate API request, response, authentication, and error changes with the backend without requiring an unsafe simultaneous deployment.
### Harness and Verification
- `AGENTS.md` and `CLAUDE.md` are generated. Edit `.agent/profile.yml` or `.agent/project.md`, then recompose instead of editing generated files.
- Use the existing npm scripts and focused lint, type-check, test, or production build checks. Do not call production APIs or export real customer data during validation.

View File

@@ -1,7 +1,5 @@
NEXT_PUBLIC_ENV=dev NEXT_PUBLIC_ENV=dev
NEXT_PUBLIC_API_BASE=http://localhost:6100/api NEXT_PUBLIC_API_BASE=https://test-lg-cxdash.kric.com/api
ENV=dev ENV=dev
API_BACK_SERVER=http://localhost:6101/api/v1 API_BACK_SERVER=http://127.0.0.1:6101/api/v1
API_KART_SERVER=https://rapi.kric.com/api/v1
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230

View File

@@ -2,6 +2,4 @@ NEXT_PUBLIC_ENV=local
NEXT_PUBLIC_API_BASE=http://localhost:6100/api NEXT_PUBLIC_API_BASE=http://localhost:6100/api
ENV=local ENV=local
API_CONTACT_SERVER=http://localhost:6101/api/v1 API_BACK_SERVER=http://localhost:6101/api/v1
API_KART_SERVER=https://rapi.kric.com/api/v1
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230

View File

@@ -1,7 +1,5 @@
NEXT_PUBLIC_ENV=prod NEXT_PUBLIC_ENV=prod
NEXT_PUBLIC_API_BASE=http://localhost:6100/api NEXT_PUBLIC_API_BASE=https://lg-cxdash.kric.com/api
ENV=prod ENV=prod
API_CONTACT_SERVER=http://localhost:6101/api/v1 API_BACK_SERVER=http://127.0.0.1:6101/api/v1
API_KART_SERVER=https://rapi.kric.com/api/v1
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230

4
.gitattributes vendored Normal file
View File

@@ -0,0 +1,4 @@
/.gitattributes text eol=lf
/.agent/** text eol=lf
/AGENTS.md text eol=lf
/CLAUDE.md text eol=lf

2
.gitignore vendored
View File

@@ -1,5 +1,7 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
.idea
# dependencies # dependencies
/node_modules /node_modules
/.pnp /.pnp

8
.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# 디폴트 무시된 파일
/shelf/
/workspace.xml
# 에디터 기반 HTTP 클라이언트 요청
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

306
AGENTS.md Normal file
View File

@@ -0,0 +1,306 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Project: lge-cx-dash-front
Schema version: 1
Edit the source fragments or repository .agent files, then recompose.
-->
# KRI Development Base Instructions
This document defines the shared working rules for KRI development repositories.
Keep project-specific facts and commands in the project profile and project rules.
## Instruction Resolution
Apply repository instructions in this order:
1. Base rules
2. Project-type rules
3. Technology-stack rules
4. Shared consumer contracts
5. Project-specific rules
6. The explicitly approved task scope
Later and more specific instructions may override earlier general instructions only within their stated scope.
- Apply a shared consumer contract only when `.agent/profile.yml` declares it.
- Do not silently resolve a material instruction conflict. Report the conflicting rules and request a decision before changing files.
- Rules involving destructive actions, credentials, external systems, production, deployment, databases, or Git publication require explicit authorization even when a later rule is less restrictive.
## Communication
- Respond to the user in Korean unless the user requests another language.
- Keep code identifiers, commands, paths, protocol names, and external API terms in their original form.
- Follow the repository's existing language conventions for code comments and user-facing messages.
- Lead with the result or decision, then provide only the detail needed to verify it.
- Do not create or retain a full session transcript.
## Work Authorization
- The default workflow is discussion first and explicit execution approval second.
- During discussion, perform only read-only investigation needed to understand the task and propose a concrete plan, unless the user prohibits inspection.
- Read-only investigation may include file inspection, code search, encoding checks, `git status`, `git diff`, `git log`, and sanitized official-documentation lookup.
- Before execution approval, do not edit files, install dependencies, run builds or tests, start services, connect to databases, or change local or external state.
- Before requesting approval, describe the intended scope, affected areas, validation plan, and material risks.
- Treat approval as limited to the presented scope. Pause and discuss again if the work materially expands.
- If the user explicitly requests immediate execution without prior discussion, the discussion gate may be skipped for the stated scope.
- Fast-track authorization does not implicitly authorize protected operations such as destructive commands, production changes, deployments, database mutations, Git publication, or external messages.
## Local Development Environment
- Primary OS: Windows 11.
- Primary shell: PowerShell.
- Use Git Bash only when the repository already depends on Bash or POSIX shell behavior.
- Prefer repository-provided wrappers and scripts over globally installed commands.
- Do not assume that GNU utilities, WSL, Docker, or a Unix-compatible shell are available unless the project profile confirms them.
- Detect Java, Node.js, .NET, Python, package-manager, and database-tool versions from repository configuration.
- Do not install or modify global toolchains as part of a project task.
Preferred human-facing tools:
- Classic ASP: Visual Studio Code
- Java and Spring Boot: IntelliJ IDEA
- C# and .NET: JetBrains Rider
- JavaScript, TypeScript, and Next.js: JetBrains WebStorm
- Python: JetBrains PyCharm
- Microsoft SQL Server: SQL Server Management Studio
- Other databases: JetBrains DataGrip
- These preferences do not authorize launching or controlling a GUI application.
- Prefer IDE-independent commands that can also run in CI.
- Do not modify global IDE settings.
- Do not create or modify `.idea`, `.vscode`, workspace, or run-configuration files unless the approved task requires it.
- Preserve existing shared IDE configuration when it is already tracked.
## PowerShell and Path Safety
- Quote paths containing spaces, brackets, parentheses, Korean characters, or PowerShell metacharacters.
- Prefer `-LiteralPath` when operating on an exact filesystem path.
- Use project-relative paths in committed configuration and documentation. Do not commit machine-specific paths such as `D:\_____Dev\...`.
- Do not pass filesystem targets between PowerShell, `cmd.exe`, and Bash for destructive or recursive operations.
- Keep a filesystem operation within one shell from target resolution through execution.
- Before a recursive delete or move, resolve and verify every absolute target.
- Never use a drive root, workspace root, user profile, unresolved variable, wildcard, or broad glob as a recursive delete target.
- Prefer recoverable operations when practical.
## Change Discipline
- Preserve all existing user changes, including uncommitted and untracked work.
- Keep changes minimal but complete for the approved objective.
- Avoid unrelated cleanup, formatting, renaming, dependency upgrades, and architectural refactoring.
- Do not overwrite or revert unrelated changes.
- Stop and report when the requested change overlaps existing work in a way that cannot be handled safely.
- Prefer changing an authoritative source over editing generated output.
- Treat files marked as generated as read-only unless regeneration is part of the approved plan.
- Do not edit vendored dependencies, build outputs, caches, or generated clients unless explicitly required.
- Do not regenerate a broad set of files for a narrow change without first explaining the expected output scope.
## Text Encoding and Korean Content Safety
- Treat the existing file encoding, BOM state, and line-ending style as part of the file's contract.
- Preserve Korean comments, user-facing messages, error messages, identifiers, and documentation exactly unless the task explicitly requires changing them.
- Do not assume that garbled terminal output means the file itself is corrupted. Verify bytes and encoding before modifying suspicious text.
- Before editing an existing text file, determine its current encoding and BOM state when repository configuration does not already guarantee them.
- Do not convert encoding, add or remove a BOM, or normalize line endings as a side effect of an unrelated change.
- Avoid whole-file rewrites for small changes.
- Do not rewrite source files through `Get-Content | Set-Content`, `Out-File`, shell redirection, or another method whose encoding behavior is implicit.
- Do not use a patching or formatting tool on a non-UTF-8 file unless it is known to preserve that file's encoding.
- Treat a console display problem and an on-disk encoding problem as separate issues.
- After editing Korean text, inspect the diff for replacement characters (`<60>`), mojibake, unexpected escapes, BOM changes, and unrelated line-ending changes.
- Run `.agent/tools/check-encoding.ps1` when it is available and the change touches Korean text or a non-default encoding.
- If encoding cannot be identified confidently, stop before writing and report the affected file and evidence.
- For a new text file, follow repository configuration. If no rule exists, use UTF-8 without BOM.
## Git Safety
- Use `git status`, `git diff`, and `git log` for read-only investigation.
- Do not run `commit`, `push`, `pull`, `fetch`, `merge`, `rebase`, `reset`, `checkout`, `switch`, `stash`, `clean`, `tag`, or force operations unless that specific operation is explicitly approved.
- Source-edit approval does not include commit or push approval.
- Never amend an existing commit unless explicitly requested.
- Before an approved commit, show the intended files, validation results, and proposed commit message.
- Never push directly to a protected branch unless the user names the target branch and explicitly authorizes the push.
## Dependencies and External Actions
- Use the package manager, lockfile, and toolchain already selected by the repository.
- Do not install global packages.
- Do not add, remove, or upgrade a dependency unless it was included in the approved plan.
- Pause for approval if an unplanned dependency becomes necessary.
- Keep lockfiles synchronized with approved dependency changes.
- Do not deploy, publish packages, create releases, send messages or email, call business APIs, or modify external services unless explicitly requested.
- Never upload proprietary source code, internal documents, credentials, customer data, or database contents to an external service.
- Remove secrets and unnecessary internal identifiers from external search queries.
## Database Safety
- Treat writing or reviewing SQL as source code separately from executing SQL against a database.
- SQL files, migrations, schema proposals, and query drafts may be created within an approved source-change scope.
- Do not connect to a shared, staging, or production database without explicit authorization for that environment.
- Read-only queries against a non-local database also require authorization because results may contain sensitive data.
- Do not execute DDL, DML, stored procedures, migrations, administrative commands, or data-correction scripts against a non-disposable database without separate authorization for the exact target and operation.
- Source-change approval does not authorize migration execution.
- Use a disposable local or test database for approved validation only after verifying its identity and disposable nature.
- Never place credentials, connection strings, or sensitive query results in source files, logs, generated documents, or chat output.
## Secrets and Sensitive Data
- Never add credentials, tokens, passwords, private keys, connection strings, session identifiers, or production data to source control.
- Read sensitive files only when the approved task requires it and no safer source exists.
- Prefer inspecting configuration keys and schemas without displaying secret values.
- Never echo secrets into terminal output, chat responses, logs, diffs, generated documents, test fixtures, or screenshots.
- Redact sensitive values when reporting errors or command output.
- If a possible secret is discovered, do not repeat it. Report only its location, type, and recommended containment action.
- Do not rotate, revoke, copy, or otherwise modify credentials unless that exact action is explicitly authorized.
## Validation
- Discover supported build, test, lint, type-check, and formatting commands from repository files and project instructions. Do not invent commands.
- Include intended validation in the discussion-phase plan.
- After approved changes, run the narrowest relevant validation first, then broader checks when appropriate.
- Limit formatting to files within the approved scope.
- Do not run tests that require a shared database, production service, paid external API, or sensitive data unless separately authorized.
- Do not claim that a check passed unless it was executed successfully.
- If a check cannot be run, state the exact reason.
- Distinguish a current-change failure from a pre-existing failure or an undetermined failure.
- Do not fix unrelated failures without expanding the approved scope.
- Inspect the worktree after validation for unexpected generated files, formatting churn, encoding changes, or lockfile changes.
## Artifacts and Session Records
- Do not create full-session transcripts, automatic HTML copies, analysis reports, or extra documentation unless explicitly requested.
- Store durable information in the repository's existing documentation structure.
- Do not place generated reports or temporary analysis files in the repository root.
- Remove task-specific temporary files created by the current task after validation when removal is safe.
## Completion Report
When implementation is complete, report in Korean:
- what changed and why;
- the main affected files or components;
- validation commands actually executed and their results;
- checks not executed and the reason;
- remaining risks, assumptions, or follow-up work;
- database, deployment, dependency, encoding, and compatibility impact when applicable.
- Do not report completion while required validation is failing or known encoding corruption is unresolved.
- Keep the report concise and do not include a full session transcript.
## Requested Project Rules
- Treat the approved requirements, acceptance criteria, and recorded decisions as the primary scope boundary.
- Do not infer a requirement solely from a file name, folder date, or apparently newer document.
- When requirements conflict, report the exact sources and request a decision.
- Preserve original customer, partner, and planning documents as read-only evidence unless document editing is explicitly approved.
- Summarize durable implementation requirements inside the repository rather than relying only on files outside the repository.
- Do not expand the deliverable with speculative features, infrastructure, or architectural changes.
- Record material assumptions and unresolved decisions in the project-specific rules or existing project documentation.
- Define observable acceptance criteria before implementation.
- Treat separately managed Frontend and Backend repositories as independent deliverables with a coordinated contract.
- Protect customer, partner, survey, and field data as sensitive information.
- Keep handoff, operation, configuration, and validation instructions usable by the requesting team.
- Report deviations from the requested scope and obtain approval before proceeding.
## TypeScript
- Treat the repository's current TypeScript version, `tsconfig` files, module system, path aliases, and package manager as authoritative.
- Preserve or strengthen existing strictness. Do not weaken compiler options or hide errors with broad `any`, `@ts-ignore`, or unsafe assertions.
- Prefer narrow domain types, discriminated unions, and explicit boundary types over duplicated or overly generic shapes.
- Validate untrusted runtime input even when a compile-time type exists.
- Keep imports, exports, aliases, and generated-code boundaries consistent with the repository.
- Do not introduce a JavaScript-to-TypeScript conversion outside the approved scope.
- Run the repository's focused type-check, lint, test, and build commands as applicable.
## React
- Treat the current React version, component style, state management, routing, styling, and test approach as authoritative.
- Do not perform unrelated class-to-hook, JavaScript-to-TypeScript, state-library, styling-system, or React-to-Next.js migrations.
- Keep components focused and follow the repository's established split between presentation, state, data access, and side effects.
- Keep effects dependency-correct and clean up subscriptions, timers, listeners, and in-flight work where applicable.
- Use stable semantic keys and preserve accessibility, loading, empty, error, disabled, and success states.
- Preserve public component props and shared UI contracts unless a coordinated breaking change is explicitly approved.
- Treat any planned Next.js migration as a separate policy and task; the current React application remains authoritative until that migration slice is approved.
## Next.js
- Treat the repository's current Next.js and React versions, routing model, rendering model, and package manager as authoritative.
- Preserve server and client component boundaries. Add `use client` only when browser APIs, state, effects, or client-only libraries require it.
- Keep secrets, privileged data access, and server-only modules out of client bundles.
- Preserve established route, layout, middleware, authentication, authorization, caching, revalidation, and error-handling conventions.
- Validate request parameters, payloads, headers, cookies, and external responses at runtime.
- Do not create new frontend TypeScript type or interface names ending in `Dto` or `DTO`. Use domain- or purpose-specific names such as `User`, `UserInput`, `UserRequest`, or `UserResponse`; do not rename existing types solely to enforce this rule outside the approved scope.
- Use the approved KRI frontend and UI contracts when the project profile includes them; do not copy shared implementations into an application.
- Avoid incidental routing-model or rendering-strategy migrations.
- Run the repository's focused lint, type-check, test, and production build commands as applicable.
## KriFrontCommon Consumer Contract
### Package Usage
- Consume this contract through the published `@kri/common` package and only through entry points declared in its `package.json` `exports` map.
- Use the package root for runtime-neutral object, URL, date, string, and shared type utilities.
- Use a focused subpath such as `@kri/common/http`, `@kri/common/browser`, `@kri/common/server`, `@kri/common/security`, `@kri/common/hooks`, `@kri/common/query`, `@kri/common/config`, `@kri/common/jotai`, or `@kri/common/noti-hub` for the corresponding capability.
- Do not import from `@kri/common/src/*`, `@kri/common/dist/*`, or another undeclared deep path.
- Do not copy or fork a shared utility locally merely to avoid using an available public entry point. Propose a backward-compatible library addition when the shared contract is genuinely missing.
### Runtime and Optional Integrations
- Keep browser, server, and runtime-neutral imports on their intended side of the application boundary.
- A consumer that uses React hooks, TanStack Query, or Jotai integrations must provide the compatible optional peer dependency required by its selected entry point.
- Preserve the project's established HTTP client, authentication, error-policy, query-client, storage, and environment conventions when adopting a shared helper.
- Validate external data at runtime; a shared TypeScript type alone does not validate an API response or persisted value.
- Prefer named public exports and retain the consumer project's current module system and bundler conventions.
### Change Safety
- Pin or constrain the package version according to the consumer repository's dependency policy and commit its lockfile changes.
- Review release notes and the actual affected API before upgrading. Run the consumer's focused type-check, test, and build commands after an upgrade.
- Do not modify KriFrontCommon or another consumer repository unless it is explicitly included in the approved task scope.
## KriUiRegistry Consumer Contract
### UI Component Selection
When implementing or changing frontend UI, use this order:
1. Reuse an existing shared component in the project when it already meets the requirement.
2. Prefer an approved component from KriUiRegistry.
3. Otherwise, prefer a suitable shadcn/ui component.
4. Create a new custom component only when the preceding options cannot meet the requirement without an unsafe or misleading adaptation.
### Installation and Ownership
- Inspect the registry item and its dependencies before installation. Use the shadcn CLI with the approved registry endpoint under `https://ui-registry.kric.com/r/` instead of copying files from `dist/r` manually.
- `kri-data-table` uses the TanStack Table v8 API. Keep `@tanstack/react-table` within the supported `^8.21.3` range and do not upgrade it to v9 until KriUiRegistry provides an explicitly migrated component contract.
- Respect the consumer project's component aliases, target paths, package manager, styling system, React version, and existing design tokens.
- The shadcn workflow copies component source into the consumer repository. After installation, treat that copy as project-owned code; do not assume registry updates propagate automatically.
- Do not overwrite an existing project component without reviewing the diff and confirming that local behavior and accessibility are preserved.
- Keep package and lockfile changes produced by an installation within the approved scope.
### Adaptation and Verification
- Adapt business data and application behavior outside the shared component when possible. Avoid embedding project-specific API, route, authentication, or environment logic into a reusable component.
- Preserve the installed component's public props, accessibility, keyboard behavior, responsive layout, and loading, empty, error, and disabled states unless the task explicitly changes them.
- If the registry lacks a generally reusable capability, propose it in KriUiRegistry; do not modify that repository unless it is explicitly in scope.
- Run the consumer repository's focused type-check, lint, tests, and build after installation or upgrade.
## LGE CX Dashboard Frontend Repository Rules
### Deliverable and User Experience
- This Next.js frontend visualizes LGE appliance penetration, purchase, category, profile, and trend survey statistics.
- Treat approved planning and design material as the scope boundary. Preserve category navigation, filters, labels, chart/table values, comparison context, and Excel export behavior.
- A visual change must not silently alter the represented statistic, denominator, ordering, rounding, tooltip meaning, or empty-data behavior.
- Keep customer survey data, exported workbooks, and internal planning material out of logs, fixtures, screenshots, and external services.
### Frontend Implementation
- Use the consumed KRI frontend common and UI registry contracts. Prefer an existing shadcn/ui or registry component before creating a new foundational component.
- Do not create new TypeScript type or interface names ending in `Dto` or `DTO`.
- Preserve accessibility, responsive layout, loading, empty, error, unauthorized, and export states across every dashboard route.
- Coordinate API request, response, authentication, and error changes with the backend without requiring an unsafe simultaneous deployment.
### Harness and Verification
- `AGENTS.md` and `CLAUDE.md` are generated. Edit `.agent/profile.yml` or `.agent/project.md`, then recompose instead of editing generated files.
- Use the existing npm scripts and focused lint, type-check, test, or production build checks. Do not call production APIs or export real customer data during validation.

1
CLAUDE.md Normal file
View File

@@ -0,0 +1 @@
@AGENTS.md

View File

@@ -16,7 +16,7 @@ bun dev
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. You can start editing the page by modifying `app/Profile.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.

1051
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -16,11 +16,13 @@
"@radix-ui/react-separator": "^1.1.8", "@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4", "@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-tabs": "^1.1.13", "@radix-ui/react-tabs": "^1.1.13",
"@tanstack/react-query": "^5.90.21",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"crypto-js": "^4.2.0", "crypto-js": "^4.2.0",
"echarts": "^6.0.0", "echarts": "^6.0.0",
"echarts-for-react": "^3.0.5", "echarts-for-react": "^3.0.5",
"exceljs": "^4.4.0",
"jotai": "^2.16.2", "jotai": "^2.16.2",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"lucide-react": "^0.562.0", "lucide-react": "^0.562.0",
@@ -33,6 +35,7 @@
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/postcss": "^4.0.7", "@tailwindcss/postcss": "^4.0.7",
"@tanstack/react-query-devtools": "^5.91.3",
"@types/crypto-js": "^4.2.2", "@types/crypto-js": "^4.2.2",
"@types/lodash": "^4.17.23", "@types/lodash": "^4.17.23",
"@types/node": "^20", "@types/node": "^20",

BIN
public/icon-excel.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

BIN
public/logo_transparent.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

View File

@@ -1,7 +0,0 @@
const AirSolutionPage = () => {
return (
<div>AirSolutionPage</div>
);
}
export default AirSolutionPage;

View File

@@ -0,0 +1,7 @@
import CategoryPage from "../sub-page/CategoryPage";
const ESPage = () => {
return <CategoryPage/>
}
export default ESPage;

View File

@@ -1,7 +0,0 @@
const HAKitchenPage = () => {
return (
<div>HAKitchenPage</div>
);
}
export default HAKitchenPage;

View File

@@ -1,7 +0,0 @@
const HALivingPage = () => {
return (
<div>HALivingPage</div>
);
}
export default HALivingPage;

View File

@@ -0,0 +1,7 @@
import CategoryPage from "../sub-page/CategoryPage";
const KitchenPage = () => {
return <CategoryPage/>
}
export default KitchenPage;

View File

@@ -0,0 +1,7 @@
import CategoryPage from "../sub-page/CategoryPage";
const LivingPage = () => {
return <CategoryPage/>
}
export default LivingPage;

View File

@@ -1,7 +0,0 @@
const MSDigitalPage = () => {
return (
<div>MSDigitalPage</div>
);
}
export default MSDigitalPage;

View File

@@ -0,0 +1,7 @@
import CategoryPage from "../sub-page/CategoryPage";
const MSPage = () => {
return <CategoryPage/>
}
export default MSPage;

View File

@@ -0,0 +1,120 @@
'use client'
import {useMemo} from "react";
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {CategoryTargetData} from "@/types/filter.types";
import {BannerRow, CategoryResolvedField, StatisticsRequest} from "@/types/lg.types";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {CategoryFilterValue} from "@/components/layout/CategoryFilter";
import {buildCategoryFilter, buildGapRow, buildPageModeConfig} from "@/lib/lg-dashboard";
import {BANNER_GROUP_KEY} from "@/const/lg-banner.const";
import {API_DECIMAL_POINT, USE_CACHE} from "@/const/lg-common.const";
import Profile from "./category-page/Profile";
import PenetrationChange from "./category-page/PenetrationChange";
import CategoryDetail from "./category-page/CategoryDetail";
import {useBannerStatisticsQuery} from "@/query/statistics";
export type CategoryPageProps = {
fields: CategoryResolvedField[];
variableIdMap: Record<string, string>;
dataMap:Record<string, BannerRow[]> | undefined;
fillGreaterThan5?: boolean;
isProfileAll?: boolean;
}
const PAGE_COMPONENTS: Partial<Record<CategoryTargetData, React.ComponentType<CategoryPageProps>>> = {
[CategoryTargetData.PROFILE]: Profile,
[CategoryTargetData.PROFILE_ALL]: Profile,
[CategoryTargetData.PENETRATION_CHANGE]: PenetrationChange,
[CategoryTargetData.BRAND]: CategoryDetail,
[CategoryTargetData.TYPE_SPEC]: CategoryDetail,
[CategoryTargetData.BEHAVIOR]: CategoryDetail,
[CategoryTargetData.PURCHASE_CHANNEL]: CategoryDetail,
[CategoryTargetData.PAYMENT_METHOD]: CategoryDetail,
};
const CategoryPage = () => {
const { isTotal, filterValue } = useLayoutFilter();
const debouncedFilterValue = useDebouncedValue<CategoryFilterValue>(filterValue as CategoryFilterValue);
const { fields, variableIdMap } = useMemo(() => {
return buildPageModeConfig(debouncedFilterValue);
}, [debouncedFilterValue]);
const req = useMemo<StatisticsRequest>(() => {
return {
variableIdMap,
bannerIdList: BANNER_GROUP_KEY,
filterCondition: buildCategoryFilter(debouncedFilterValue),
option: { useCache: USE_CACHE, lastYear: false, decimalPoint: 2 },
};
}, [variableIdMap, debouncedFilterValue]);
const { data } = useBannerStatisticsQuery(req);
const dataMap = data?.statisticsDataMap;
const target = debouncedFilterValue.target;
const Comp = PAGE_COMPONENTS[target.value];
const isProfileAll = target.value === CategoryTargetData.PROFILE_ALL;
const fillGreaterThan5 = Comp === CategoryDetail && !!dataMap;
const processedDataMap = useMemo(() => {
if (!dataMap || target.value !== CategoryTargetData.BRAND) {
return dataMap;
}
const nextMap: Record<string, BannerRow[]> = { ...dataMap };
fields.forEach((f) => {
const rows = dataMap[f.requestKeyResolved];
if (!rows?.length) return;
const years = Array.from(new Set(rows.map((row) => Number(row.year))))
.filter((year) => Number.isFinite(year))
.sort((a, b) => b - a)
.slice(0, -1);
if(years.length === 0) {
nextMap[f.requestKeyResolved] = rows;
return;
}
const gapRowsByYear = new Map<number, BannerRow>();
years.forEach((year) => {
const currentYear = year;
const prevYear = year - 1;
const gapRow = buildGapRow(rows, prevYear, currentYear, "LG");
if(gapRow !== null){
gapRowsByYear.set(currentYear, gapRow);
}
});
const nextRows: BannerRow[] = [];
rows.forEach((row) => {
nextRows.push(row);
const gapRow = gapRowsByYear.get(Number(row.year));
if (row.rowLabel === "LG" && gapRow) {
nextRows.push(gapRow);
}
});
nextMap[f.requestKeyResolved] = nextRows;
});
return nextMap;
}, [dataMap, fields, target.value]);
if(isTotal) return null;
return Comp ?
<Comp
fields={fields}
variableIdMap={variableIdMap}
dataMap={processedDataMap}
fillGreaterThan5={fillGreaterThan5}
isProfileAll={isProfileAll}
/>
: null;
}
export default CategoryPage;

View File

@@ -0,0 +1,100 @@
import {CategoryPageProps} from "../../sub-page/CategoryPage";
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {CategoryFilterValue} from "@/components/layout/CategoryFilter";
import {useEffect, useMemo} from "react";
import {BannerRow, PageData} from "@/types/lg.types";
import {buildHeader_Banner, exportDashboardExcel, Section} from "@/lib/lg-export-excel";
import {BANNER_GROUP} from "@/const/lg-banner.const";
import {BANNER_KEY_MAP, PRODUCT_KEY_MAP} from "@/const/lg-schema.const";
import {QID_SURVEY_TITLE} from "@/const/lg-survey.const";
import {SITE_TITLE, YEARS} from "@/const/lg-common.const";
import {CategoryByData} from "@/components/lge-dashboard";
import {wrapSampleRow} from "@/lib/lg-dashboard";
const CategoryDetail = ({
fields,
dataMap,
fillGreaterThan5
}:CategoryPageProps) => {
const {filterValue, registerExcelExporter} = useLayoutFilter();
const debouncedFilterValue = useDebouncedValue<CategoryFilterValue>(filterValue as CategoryFilterValue);
const tableDataArray = useMemo<PageData<BannerRow>[]>(() => {
const tempTableDataArray = fields.map((f) :PageData<BannerRow> => {
const dataLength = dataMap?.[f.requestKeyResolved].filter((row) => row.rowLabel !=`사례수`).length;
const qid = f.qidByMode[debouncedFilterValue.type.value];
let surveyTitle = qid? QID_SURVEY_TITLE[qid] ?? "" : "";
surveyTitle = surveyTitle.replaceAll("[#YEAR#]", debouncedFilterValue.year);
surveyTitle = surveyTitle.replaceAll("[#NEXT_YEAR#]", String(Number(debouncedFilterValue.year) + 1));
return {
title: typeof f.title === "string"? f.title : f.title[debouncedFilterValue.type.value],
surveyTitle: surveyTitle,
chartMode:f.chartMode,
chartLegend:f.chartLegend,
chartTopMargin:f.chartTopMargin,
data: dataLength && dataLength > 0 ? wrapSampleRow(dataMap[f.requestKeyResolved]) : []
};
});
//사례수만 있는 테이블은 아예 제외
return tempTableDataArray.filter((tableData) => tableData.data.length > 0);
}, [debouncedFilterValue, fields, dataMap]);
useEffect(() => {
registerExcelExporter(async () => {
const product = PRODUCT_KEY_MAP[debouncedFilterValue.product];
const type = debouncedFilterValue.type.label;
const target = debouncedFilterValue.target.label.replaceAll('/', '_');
const sheetName = `${product}_${type}_${target}`
const h3 = buildHeader_Banner(BANNER_GROUP, BANNER_KEY_MAP);
const years = [
debouncedFilterValue.year,
String(Number(debouncedFilterValue.year) - 1),
].filter((year) => YEARS.includes(year));
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] = tableDataArray.flatMap((tableData) => {
return years.map((year) => ({
title: `${tableData.title}_${year}년`,
header: h3,
rows: tableData.data.filter((d) => d.year === year) as AnyRow[],
rowGap: 1,
}));
});
await exportDashboardExcel({
fileName: `${SITE_TITLE}(${sheetName}).xlsx`,
sheetName: sheetName,
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter, debouncedFilterValue, tableDataArray]);
return (
<div>
{tableDataArray.map((tableData) => (
<CategoryByData
key={`cbd-${tableData.title.replaceAll(/\s+/g, "_")}`}
selectedYear={debouncedFilterValue.year}
title={tableData.title}
surveyTitle={tableData.surveyTitle}
chartMode={tableData.chartMode}
chartLegend={tableData.chartLegend}
chartTopMargin={tableData.chartTopMargin}
allTableData={tableData.data}
chartHeight={tableData.chartHeight}
chartWidth={tableData.chartWidth}
fillGreaterThan5={fillGreaterThan5}
/>
))}
</div>
);
}
export default CategoryDetail;

View File

@@ -0,0 +1,72 @@
'use client'
import {DataColumn} from "@/components/lge-dashboard";
import BannerSummary from "@/components/lge-dashboard/combo/BannerSummary";
import {useMemo} from "react";
import {parseNumber} from "@/lib/utils";
import {BannerRow} from "@/types/lg.types";
import {CategoryPageProps} from "../../sub-page/CategoryPage";
import {LAST_YEAR} from "@/const/lg-common.const";
const PenetrationChange = ({
dataMap
}:CategoryPageProps) => {
const penetrationChangeData = useMemo<BannerRow[]>(() => {
if (dataMap === undefined) return [];
const tempProfileData: BannerRow[] = [];
Object.keys(dataMap).forEach(requestKey => {
const data = dataMap[requestKey];
tempProfileData.push(
...data.filter((r) => r.rowLabel === `사례수` && r.year === LAST_YEAR),
...data.filter((r) => r.rowLabel === `보유`)
.map((row) => {
return {
...row,
rowLabel: row.year,
}
}));
});
return tempProfileData;
}, [dataMap]);
const getCellClassName = (row: BannerRow, column: DataColumn<BannerRow>, rowIndex: number) => {
if (!("key" in column) || column.key === undefined) return undefined;
const currentYear = Number(row.year);
if (currentYear !== 2024 && currentYear !== 2025) return undefined;
if (column.key === "rowLabel" || column.key === "total") return undefined;
const prevRow = penetrationChangeData[rowIndex - 1];
if (!prevRow || Number(prevRow.year) !== currentYear - 1) return undefined;
const currentValue = parseNumber(row[column.key]);
const prevValue = parseNumber(prevRow[column.key]);
if (currentValue === null || prevValue === null) return undefined;
const gap = currentValue - prevValue;
if (gap >= 3) return "lg-num-pos";
if (gap <= -3) return "lg-num-neg";
return undefined;
};
return(
<>
<BannerSummary
data={penetrationChangeData}
useChart={true}
useYear={false}
getCellClassName={getCellClassName}
/>
<div className="content-text-base font-bold mt-2">
전년 대비 GAP ±3%p 이상 수치 강조 : <span className="lg-num-pos"> 상승</span> / <span className="lg-num-neg">하락</span>
</div>
</>
);
}
export default PenetrationChange

View File

@@ -0,0 +1,88 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import BannerSummary from "@/components/lge-dashboard/combo/BannerSummary";
import {useMemo} from "react";
import {BannerRow} from "@/types/lg.types";
import {CategoryFilterValue} from "@/components/layout/CategoryFilter";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import { calcGapBannerRow } from "@/lib/lg-dashboard";
import {YEARS} from "@/const/lg-common.const";
import {CategoryTargetType} from "@/types/filter.types";
import {CategoryPageProps} from "../../sub-page/CategoryPage";
const Profile = ({
dataMap,
isProfileAll,
}:CategoryPageProps) => {
const { filterValue } = useLayoutFilter();
const debouncedFilterValue = useDebouncedValue<CategoryFilterValue>(filterValue as CategoryFilterValue);
const profileData = useMemo<BannerRow[]>(() => {
if (dataMap === undefined) return [];
const targetMap = {
[CategoryTargetType.PENETRATION]: "보유",
[CategoryTargetType.PURCHASE]: "구매",
[CategoryTargetType.INTENDED]: "향후구매",
}
const tempProfileData: BannerRow[] = [];
Object.keys(dataMap).forEach(requestKey => {
const data = dataMap[requestKey];
if(requestKey.toLowerCase().endsWith("count")){
tempProfileData.push(
...data.filter((r) => r.rowLabel == `MEAN`)
.map((row) => {
return {
...row,
rowLabel: "보유대수",
}
})
);
}
else{
const target = debouncedFilterValue.type.value;
tempProfileData.push(...data.filter((r) => r.rowLabel == `사례수`));
const targetData =
data.filter((r) => r.rowLabel == targetMap[target])
.map((row) => {
return {
...row,
rowLabel: isProfileAll ? `${row.rowLabel}율` : row.year,
}
})
tempProfileData.push(...targetData);
YEARS.forEach((year, idx) => {
const after = targetData.find((r) => r.year == year)
const before = idx == 0? undefined : targetData.find((r) => r.year == YEARS[idx-1]);
if (after && before) {
tempProfileData.push(calcGapBannerRow(after, before));
}
});
}
});
tempProfileData.sort((a, b) => Number(a.rowLabel === "보유대수") - Number(b.rowLabel === "보유대수"));
tempProfileData.sort((a, b) => Number(a.year) - Number(b.year));
return tempProfileData;
}, [debouncedFilterValue, dataMap, isProfileAll]);
return (
<BannerSummary
data={profileData}
useChart={false}
useYear={!isProfileAll}
isProfileAll={isProfileAll}
/>
);
}
export default Profile;

View File

@@ -1,7 +1,271 @@
"use client";
import {
BottomDescription,
GroupedOverlayBar,
type GroupedOverlayBarData,
signStyleGapRow,
TopChartTable,
type TopChartTableRow,
} from "@/components/lge-dashboard";
import {
LIFE_STAGE_COLUMNS,
LIFE_STAGE_GROUPS,
PRODUCT_KEYS,
} from "@/const/lg-product.const";
import { PRODUCT_KEY_MAP } from "@/const/lg-schema.const";
import {
API_DECIMAL_POINT,
SITE_TITLE,
USE_CACHE,
YEARS,
} from "@/const/lg-common.const";
import { CHART_COLOR_BY_YEAR, CHART_FOCUS_COLOR_BY_YEAR } from "@/components/lge-dashboard/chart/chart.config";
import {useEffect, useMemo} from "react";
import LifeStageDiv from "@/components/lge-dashboard/combo/LifeStageDiv";
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {
calcGapProductRow, calcTotalBaseRow,
formatRowLabel,
normalizeFilterCondition,
withGapRow, withTotalBaseRow, wrapSampleRow
} from "@/lib/lg-dashboard";
import {
buildHeader_LifeStageColumns,
buildHeader_ProductKeyMap,
exportDashboardExcel,
Section
} from "@/lib/lg-export-excel";
import {toNumOr0} from "@/lib/utils";
import {LifeStageGroup, LifeStageRow, ProductKey, StatisticsRequest} from "@/types/lg.types";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {SelectedMap} from "@/types/common";
import {useBannerStatisticsQuery, useProductStatisticsQuery} from "@/query/statistics";
const LGPenetrationPage = () => { const LGPenetrationPage = () => {
return ( const {filterValue, registerExcelExporter} = useLayoutFilter();
<div>LGPenetrationPage</div> const debouncedFilterValue = useDebouncedValue<SelectedMap>(filterValue as SelectedMap);
);
const req = useMemo<StatisticsRequest>(() => {
return {
variableIdMap: {penetration: "KQA1", penetration_lg: "KQA3_3_LG"},
bannerIdList: ["product"],
filterCondition: normalizeFilterCondition(debouncedFilterValue),
option: {useCache: USE_CACHE, lastYear: false, decimalPoint: API_DECIMAL_POINT },
};
}, [debouncedFilterValue]);
const req_lifestage = useMemo<StatisticsRequest>(() => {
const filter = {...debouncedFilterValue, "":""}
return {
variableIdMap: {lifestage_lg: "KQA3_3_LG"},
bannerIdList: ["product|lifeStage"],
filterCondition: normalizeFilterCondition(filter),
option: {useCache: USE_CACHE, lastYear: true, decimalPoint: API_DECIMAL_POINT },
};
}, [debouncedFilterValue]);
const {data, isError, error} = useProductStatisticsQuery(req);
const {
data: data_lifestage,
isError: isError_lifestage,
error: error_lifestage
} = useBannerStatisticsQuery(req_lifestage);
if(isError){
console.error(error);
} }
if(isError_lifestage){
console.error(error_lifestage);
}
const penetrationRows =
data?.statisticsDataMap?.penetration
.filter((r) => r.rowLabel == `보유`)
.map((row) => {
const rowSample = data?.statisticsDataMap?.penetration
.find(r => r.rowLabel == '사례수' && r.year == row.year)?.total ?? 0;
return {
...row,
rowLabel: row.year,
sample: `(${rowSample})`,
}
}) ?? [];
const penetrationLGRows =
data?.statisticsDataMap?.penetration_lg
.filter((r) => r.rowLabel == `보유`)
.map((row) => {
const rowSample = data?.statisticsDataMap?.penetration_lg
.find(r => r.rowLabel == '사례수' && r.year == row.year)?.total ?? 0;
return {
...row,
rowLabel: row.year,
sample: `(${rowSample})`,
}
}) ?? [];
const lifeStageRows =
data_lifestage?.statisticsDataMap?.lifestage_lg
.filter((r) => r.rowLabel == `보유`) ?? [];
const { includeProductKeys, productKeyMap, includeProducts } = useMemo(() => {
const included = new Set<ProductKey>();
for (const row of penetrationLGRows) {
for (const k of PRODUCT_KEYS) {
if (!included.has(k) && toNumOr0((row as any)[k]) !== 0) included.add(k);
}
}
const keys = PRODUCT_KEYS.filter((k) => included.has(k));
const map = Object.fromEntries(keys.map((k) => [k, PRODUCT_KEY_MAP[k]])) as Record<string, string>;
const products = keys.map((k) => PRODUCT_KEY_MAP[k]);
return { includeProductKeys: keys, productKeyMap: map, includeProducts: products };
}, [penetrationLGRows]);
const penetrationLGRowsWithGap = useMemo(() => {
const withGap = withGapRow(penetrationLGRows, calcGapProductRow, -1, -2);
return withTotalBaseRow("보급률",penetrationRows, wrapSampleRow(withGap, false), calcTotalBaseRow);
}, [penetrationRows, penetrationLGRows]);
const productTableRows = useMemo<TopChartTableRow[]>(() => {
return penetrationLGRowsWithGap.map((row) => ({
label: formatRowLabel(row.rowLabel),
sample: row.sample,
total: row.total,
values: includeProductKeys.map((k) => (row as any)[k] ?? null),
}));
}, [penetrationLGRowsWithGap, includeProductKeys]);
const productChartData = useMemo<GroupedOverlayBarData>(() => {
const total: Array<Array<number>> = YEARS.map(() => Array(includeProductKeys.length).fill(0));
const focus: Array<Array<number>> = YEARS.map(() => Array(includeProductKeys.length).fill(0));
const yearIndexMap = new Map<string, number>(YEARS.map((y, i) => [y, i]));
penetrationLGRows.forEach((r, ri) => {
const yi = yearIndexMap.get(r.year);
if (yi == null) return;
for (let ci = 0; ci < includeProductKeys.length; ci++) {
const k = includeProductKeys[ci];
const t = (penetrationRows[ri] as any)[k];
const v = (r as any)[k];
total[yi][ci] = Number(t);
focus[yi][ci] = Number(v);
}
});
return {
categories: includeProducts,
years: YEARS,
totalName: "전체",
focusName: "LG",
total,
focus,
};
}, [penetrationRows, penetrationLGRows, includeProductKeys, includeProducts]);
const lifeStageRowsByGroup: LifeStageGroup[] = useMemo(() => {
if(lifeStageRows.length == 0){
return [];
}
const lifeStageData = lifeStageRows[0];
return LIFE_STAGE_GROUPS.map((g) => {
const rows: LifeStageRow[] = g.items.map((key) => {
const label = PRODUCT_KEY_MAP[key];
return {
item: label,
total: lifeStageData[`${key}`] ?? "",
"KLIFEstAGE#1": lifeStageData[`${key}|KLIFEstAGE#1`] ?? "",
"KLIFEstAGE#2": lifeStageData[`${key}|KLIFEstAGE#2`] ?? "",
"KLIFEstAGE#3": lifeStageData[`${key}|KLIFEstAGE#3`] ?? "",
"KLIFEstAGE#4": lifeStageData[`${key}|KLIFEstAGE#4`] ?? "",
"KLIFEstAGE#5": lifeStageData[`${key}|KLIFEstAGE#5`] ?? "",
"KLIFEstAGE#6": lifeStageData[`${key}|KLIFEstAGE#6`] ?? "",
"KLIFEstAGE#7": lifeStageData[`${key}|KLIFEstAGE#7`] ?? "",
"KLIFEstAGE#8": lifeStageData[`${key}|KLIFEstAGE#8`] ?? "",
};
});
return {title: g.title, rows};
});
}, [lifeStageRows]);
const description = useMemo(() => {
return "Q. 다음 중 귀댁에서 보유하고 계신 가전/전자 제품은 무엇입니까? 모두 선택해주세요.<br/>" +
"* 구독/렌탈/선물/경품/아파트 내 빌트인 제품을 모두 포함하여 선택해주세요.<br/>" +
"Q. 보유하고 계신 (제품)의 브랜드는 어떻게 되십니까?<br/>" +
"** 조사 년도 보급률 중 자사제품 비율 = (LG 보급률 ÷ 전체 보급률) × 100";
}, []);
useEffect(() => {
registerExcelExporter(async () => {
const excelHeader = buildHeader_ProductKeyMap(productKeyMap, "sample");
const lifeStageHeader = buildHeader_LifeStageColumns(LIFE_STAGE_COLUMNS);
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] = [
{
title: "LG제품 보급률",
header: excelHeader,
rows: penetrationLGRowsWithGap as AnyRow[],
rowGap: 1,
},
...lifeStageRowsByGroup.map((lifeStageRow) => ({
title: lifeStageRow.title,
header: lifeStageHeader,
rows: lifeStageRow.rows as AnyRow[],
rowGap: 1,
})),
];
await exportDashboardExcel({
fileName: `${SITE_TITLE}(LG제품 보급률).xlsx`,
sheetName: "LG제품 보급률",
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter, penetrationLGRowsWithGap, lifeStageRowsByGroup, productKeyMap]);
return (
<div>
<TopChartTable
title={"LG제품 보급률"}
categories={[...includeProducts]}
rows={productTableRows}
chart={
<GroupedOverlayBar
data={productChartData}
questionText={"보급률"}
yearTotalColor={CHART_COLOR_BY_YEAR}
yearFocusColor={CHART_FOCUS_COLOR_BY_YEAR}
showFocusLabel={"last"}
height={260}
/>
}
signStyle={signStyleGapRow}
/>
<BottomDescription description={description}/>
<LifeStageDiv lifeStageRowsByGroup={lifeStageRowsByGroup}/>
</div>
);
};
export default LGPenetrationPage; export default LGPenetrationPage;

View File

@@ -1,7 +1,194 @@
"use client";
import {useEffect, useMemo} from "react";
import {
PRODUCT_KEYS,
} from "@/const/lg-product.const";
import { PRODUCT_KEY_MAP } from "@/const/lg-schema.const";
import {
API_DECIMAL_POINT,
SITE_TITLE,
USE_CACHE,
YEARS,
} from "@/const/lg-common.const";
import { CHART_COLOR_BY_YEAR, CHART_FOCUS_COLOR_BY_YEAR } from "@/components/lge-dashboard/chart/chart.config";
import {
BottomDescription,
GroupedOverlayBar,
type GroupedOverlayBarData,
signStyleGapRow,
TopChartTable,
type TopChartTableRow,
} from "@/components/lge-dashboard";
import { useLayoutFilter } from "@/components/layout/LayoutFilterContext";
import {
calcGapProductRow, calcTotalBaseRow,
formatRowLabel,
normalizeFilterCondition,
withGapRow, withTotalBaseRow, wrapSampleRow
} from "@/lib/lg-dashboard";
import {buildHeader_ProductKeyMap, exportDashboardExcel} from "@/lib/lg-export-excel";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {SelectedMap} from "@/types/common";
import {ProductKey, StatisticsRequest} from "@/types/lg.types";
import {useProductStatisticsQuery} from "@/query/statistics";
import {toNumOr0} from "@/lib/utils";
const LGPurchasePage = () => { const LGPurchasePage = () => {
return ( const { filterValue, registerExcelExporter } = useLayoutFilter();
<div>LGPurchasePage</div> const debouncedFilterValue = useDebouncedValue<SelectedMap>(filterValue as SelectedMap);
);
const req = useMemo<StatisticsRequest>(() => {
return {
variableIdMap: {purchase: "KQB0", purchase_lg: "KQX3_3_LG"},
bannerIdList: ["product"],
filterCondition: normalizeFilterCondition(debouncedFilterValue),
option: {useCache: USE_CACHE, lastYear: false, decimalPoint: API_DECIMAL_POINT },
};
}, [debouncedFilterValue]);
const {data, isError, error} = useProductStatisticsQuery(req);
if(isError){
console.error(error);
} }
const purchaseRows =
data?.statisticsDataMap?.purchase
.filter((r) => r.rowLabel == `구매`)
.map((row) => {
const rowSample = data?.statisticsDataMap?.purchase
.find(r => r.rowLabel == '사례수' && r.year == row.year)?.total ?? 0;
return {
...row,
rowLabel: row.year,
sample: `(${rowSample})`,
}
}) ?? [];
const purchaseLGRows =
data?.statisticsDataMap?.purchase_lg
.filter((row) => row.rowLabel === `구입`)
.map((row) => {
const rowSample = data?.statisticsDataMap?.purchase_lg
.find(r => r.rowLabel == '사례수' && r.year == row.year)?.total ?? 0;
return {
...row,
rowLabel: row.year,
sample: `(${rowSample})`,
}
}) ?? [];
const purchaseLGRowsWithGap = useMemo(() => {
const withGap = withGapRow(wrapSampleRow(purchaseLGRows, false), calcGapProductRow, -1, -2);
return withTotalBaseRow("구입율",purchaseRows, withGap, calcTotalBaseRow);
}, [purchaseRows, purchaseLGRows]);
const { includeProductKeys, productKeyMap, includeProducts } = useMemo(() => {
const included = new Set<ProductKey>();
for (const row of purchaseLGRows) {
for (const k of PRODUCT_KEYS) {
if (!included.has(k) && toNumOr0((row as any)[k]) !== 0) included.add(k);
}
}
const keys = PRODUCT_KEYS.filter((k) => included.has(k));
const map = Object.fromEntries(keys.map((k) => [k, PRODUCT_KEY_MAP[k]])) as Record<string, string>;
const products = keys.map((k) => PRODUCT_KEY_MAP[k]);
return { includeProductKeys: keys, productKeyMap: map, includeProducts: products };
}, [purchaseLGRows]);
const purchaseTableRows = useMemo<TopChartTableRow[]>(() => {
return purchaseLGRowsWithGap.map((row) => ({
label: formatRowLabel(row.rowLabel),
sample: row.sample,
total: row.total,
values: includeProductKeys.map((k) => (row as any)[k] ?? null),
}));
}, [purchaseLGRowsWithGap, includeProductKeys]);
const purchaseChartData = useMemo<GroupedOverlayBarData>(() => {
const total: Array<Array<number>> = YEARS.map(() => Array(includeProductKeys.length).fill(0));
const focus: Array<Array<number>> = YEARS.map(() => Array(includeProductKeys.length).fill(0));
const yearIndexMap = new Map<string, number>(YEARS.map((y, i) => [y, i]));
purchaseLGRows.forEach((r, ri) => {
const yi = yearIndexMap.get(r.year);
if (yi == null) return;
for (let ci = 0; ci < includeProductKeys.length; ci++) {
const k = includeProductKeys[ci];
const t = (purchaseRows[ri] as any)[k] ?? "";
const v = (r as any)[k] ?? "";
total[yi][ci] = Number(t);
focus[yi][ci] = Number(v);
}
});
return {
categories: includeProducts,
years: YEARS,
totalName: "전체",
focusName: "LG",
total,
focus,
};
}, [purchaseRows, purchaseLGRows, includeProducts, includeProductKeys]);
const description = useMemo(() => {
return "Q. 다음 중 귀댁에서 보유하고 계신 가전/전자 제품은 무엇입니까? 모두 선택해주세요.<br/>" +
"* 구독/렌탈/선물/경품/아파트 내 빌트인 제품을 모두 포함하여 선택해주세요.<br/>" +
"Q. 보유하고 계신 (제품)을 언제 구입하셨습니까?<br/>" +
//"* 새 상품을 선물 받은 경우, 선물 받은 연도로 입력해주세요.<br/>" +
//"** 중고 제품인 경우, 중고 제품을 구입한 연도로 입력해주세요.<br/>" +
//"*** 신규 입주 시 빌트인되어 있던 제품은 입주한 연도를 입력해주세요.<br/>" +
"Q. 보유하고 계신 (제품)의 브랜드는 어떻게 되십니까?<br/>" +
"** 조사 년도 구매율 중 자사제품 비율 = (LG 구매율 ÷ 전체 구매율) × 100";
}, []);
useEffect(() => {
registerExcelExporter(async () => {
const excelHeader = buildHeader_ProductKeyMap(productKeyMap, "sample");
await exportDashboardExcel({
fileName: `${SITE_TITLE}(LG제품 구매율).xlsx`,
sheetName: "LG제품 구매율",
sections: [
{ title: "LG제품 구매율", header: excelHeader, rows: purchaseLGRowsWithGap, rowGap: 1 },
],
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter, purchaseLGRowsWithGap]);
return (
<div>
<TopChartTable
title={"LG제품 구매율"}
categories={[...includeProducts]}
rows={purchaseTableRows}
chart={
<GroupedOverlayBar
data={purchaseChartData}
questionText={"구매율"}
yearTotalColor={CHART_COLOR_BY_YEAR}
yearFocusColor={CHART_FOCUS_COLOR_BY_YEAR}
showFocusLabel={"last"}
height={260}
/>
}
signStyle={signStyleGapRow}
/>
<BottomDescription description={description}/>
</div>
);
};
export default LGPurchasePage; export default LGPurchasePage;

View File

@@ -1,7 +1,224 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import TopChartTable from "@/components/lge-dashboard/combo/TopChartTable";
import VerticalBar from "@/components/lge-dashboard/chart/VerticalBar";
import {
type ChartData,
GroupedStackBar,
signStyleGapRow,
type TopChartTableRow,
type GroupedStackBarData, BottomDescription,
} from "@/components/lge-dashboard";
import { useLayoutFilter } from "@/components/layout/LayoutFilterContext";
import { Button } from "@/components/ui/button";
import {
BRAND_LIST,
YEARS,
SITE_TITLE,
USE_CACHE,
API_DECIMAL_POINT,
} from "@/const/lg-common.const";
import { PRODUCT_KEY_MAP } from "@/const/lg-schema.const";
import { PRODUCT_KEYS, PRODUCTS } from "@/const/lg-product.const";
import { AXIS_HIDE_STYLE, GRID_X_NOT_PADDING } from "@/components/lge-dashboard/chart/chart.config";
import {
calcCagrRow, calcGapProductRow,
formatRowLabel,
normalizeFilterCondition, withCagrRow, withGapRow, wrapSampleRow
} from "@/lib/lg-dashboard";
import {buildHeader_ProductKeyMap, exportDashboardExcel, Section} from "@/lib/lg-export-excel";
import {StatisticsRequest} from "@/types/lg.types";
import {useProductStatisticsQuery} from "@/query/statistics";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {toNumOr0} from "@/lib/utils";
import {SelectedMap} from "@/types/common";
const PenetrationPage = () => { const PenetrationPage = () => {
return ( const { filterValue, registerExcelExporter } = useLayoutFilter();
<div>PenetrationPage</div> const debouncedFilterValue = useDebouncedValue<SelectedMap>(filterValue as SelectedMap);
); const [isBrandShare, setIsBrandShare] = useState(false);
const req = useMemo<StatisticsRequest>(() => {
return {
variableIdMap: { penetration: "KQA1", penetration_brand: "KQA3_3_NET" },
bannerIdList: ["product"],
filterCondition: normalizeFilterCondition(debouncedFilterValue),
option: { useCache: USE_CACHE, lastYear: false, decimalPoint: API_DECIMAL_POINT },
};
}, [debouncedFilterValue]);
const { data, isError, error } = useProductStatisticsQuery(req);
if(isError){
console.error(error);
} }
const penetrationRows =
data?.statisticsDataMap?.penetration
.filter((r) => r.rowLabel == `보유`)
.map((row) => {
const rowSample = data?.statisticsDataMap?.penetration
.find(r => r.rowLabel == '사례수' && r.year == row.year)?.total ?? 0;
return {
...row,
rowLabel: row.year,
sample: `(${rowSample})`,
}
}) ?? [];
const penetrationBrandRows = (
data?.statisticsDataMap?.penetration_brand
?.filter((row) => BRAND_LIST.includes(row.rowLabel)) ?? []
).map((row) => {
PRODUCT_KEYS.forEach((k) => {
(row as any)[k] = Number((row as any)[k]).toFixed(0);
});
return row;
});
const penetrationRowsWithGapCagr = useMemo(() => {
const withGap = withGapRow(penetrationRows, calcGapProductRow, -1, -2);
const withCagr = withCagrRow(withGap, calcCagrRow, -1, 1);
withCagr.forEach((row) => {
if (row.rowLabel !== "CAGR") {
PRODUCT_KEYS.forEach((k) => {
(row as any)[k] = Number((row as any)[k]).toFixed(0);
});
}
});
return wrapSampleRow(withCagr, false);
}, [penetrationRows]);
const productTableRows = useMemo<TopChartTableRow[]>(() => {
return penetrationRowsWithGapCagr.map((row) => ({
label: formatRowLabel(row.rowLabel),
sample: row.sample,
total: row.total,
values: PRODUCT_KEYS.map((k) => (row as any)[k] ?? null),
}))
}, [penetrationRowsWithGapCagr]);
const productChartData = useMemo<ChartData>(() => {
return {
categories: [...PRODUCTS],
series: penetrationRows
.map((row) => ({
name: row.year,
data: PRODUCT_KEYS.map((k) => toNumOr0((row as any)[k])),
})),
};
}, [penetrationRows]);
const brandShareChartData = useMemo<GroupedStackBarData>(() => {
const rowMap = new Map<string, (typeof penetrationBrandRows)[number]>();
for (const r of penetrationBrandRows) {
rowMap.set(`${r.year}__${r.rowLabel}`, r);
}
const values: number[][][] = YEARS.map(() =>
BRAND_LIST.map(() => new Array(PRODUCTS.length).fill(0))
);
YEARS.forEach((year, yi) => {
BRAND_LIST.forEach((brand, bi) => {
PRODUCT_KEYS.forEach((k, ci) => {
const row = rowMap.get(`${year}__${brand}`);
values[yi][bi][ci] = (row as any)?.[k];
});
});
});
return { categories: PRODUCTS, years: YEARS, brands: BRAND_LIST, values };
}, [penetrationBrandRows]);
const description = useMemo(() => {
if(isBrandShare){
return "Q. 보유하고 계신 (제품)의 브랜드는 어떻게 되십니까?";
}
return "Q. 다음 중 귀댁에서 보유하고 계신 가전/전자 제품은 무엇입니까? 모두 선택해주세요.<br/>" +
"* 구독/렌탈/선물/경품/아파트 내 빌트인 제품을 모두 포함하여 선택해주세요.";
}, [isBrandShare]);
useEffect(() => {
registerExcelExporter(async () => {
const excelHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP, "sample");
const brandHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP);
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] = [
{ title: "전체 보급률", header: excelHeader, rows: penetrationRowsWithGapCagr, rowGap: 1 },
...YEARS.map((year) => (
{
title: `브랜드 별 점유율_${year}년`,
header: brandHeader,
rows: penetrationBrandRows.filter((row) => row.year === year),
rowGap: 1,
}
))
];
await exportDashboardExcel({
fileName: `${SITE_TITLE}(보급률).xlsx`,
sheetName: "전체 보급률",
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter, penetrationRowsWithGapCagr, penetrationBrandRows]);
return (
<div>
<div className="flex py-4">
<Button
className="h-8 px-3 text-sm font-semibold content-text-sm"
variant={isBrandShare ? "default" : "secondary"}
onClick={() => setIsBrandShare((v) => !v)}
>
{"브랜드 점유율 변화"}
</Button>
</div>
<TopChartTable
title={isBrandShare ? "브랜드 점유율 변화" : "전체 보급률"}
categories={[...PRODUCTS]}
rows={productTableRows}
chart={
isBrandShare ? (
<GroupedStackBar
data={brandShareChartData}
grid={{...GRID_X_NOT_PADDING, bottom: 20}}
xAxis={{ type: "category", data: PRODUCTS, ...AXIS_HIDE_STYLE }}
yAxis={{ type: "value", ...AXIS_HIDE_STYLE }}
showFocusLabel={"none"}
yearBrandPalette={[ "--chart-etc", "--chart-cbrand","--chart-samsung","--chart-lg"]}
height={260}
/>
) : (
<VerticalBar
data={productChartData}
paletteVarNames={["--chart-3", "--chart-2", "--chart-1"]}
grid={GRID_X_NOT_PADDING}
xAxis={{ type: "category", data: [...PRODUCTS], ...AXIS_HIDE_STYLE }}
yAxis={{ type: "value", ...AXIS_HIDE_STYLE }}
showFocusLabel={"last"}
height={260}
/>
)
}
signStyle={signStyleGapRow}
fillCAGR={true}
/>
<BottomDescription description={"CAGR(%) 5%p 이상 품목에 대해 음영 표시"} />
<BottomDescription description={description} />
</div>
);
};
export default PenetrationPage; export default PenetrationPage;

View File

@@ -1,7 +1,145 @@
"use client";
import {useEffect, useMemo} from "react";
import {
PRODUCT_KEYS,
PRODUCTS,
} from "@/const/lg-product.const";
import { PRODUCT_KEY_MAP } from "@/const/lg-schema.const";
import {
SITE_TITLE,
USE_CACHE,
API_DECIMAL_POINT,
} from "@/const/lg-common.const";
import { AXIS_HIDE_STYLE, GRID_X_NOT_PADDING } from "@/components/lge-dashboard/chart/chart.config";
import {
BottomDescription,
type ChartData,
signStyleGapRow,
TopChartTable,
type TopChartTableRow,
VerticalBar,
} from "@/components/lge-dashboard";
import { useLayoutFilter } from "@/components/layout/LayoutFilterContext";
import {
calcGapProductRow,
formatRowLabel,
normalizeFilterCondition,
withGapRow,
wrapSampleRow
} from "@/lib/lg-dashboard";
import {buildHeader_ProductKeyMap, exportDashboardExcel} from "@/lib/lg-export-excel";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {SelectedMap} from "@/types/common";
import {StatisticsRequest} from "@/types/lg.types";
import {useProductStatisticsQuery} from "@/query/statistics";
const PurchasePage = () => { const PurchasePage = () => {
return ( const { filterValue, registerExcelExporter } = useLayoutFilter();
<div>PurchasePage</div> const debouncedFilterValue = useDebouncedValue<SelectedMap>(filterValue as SelectedMap);
);
const req = useMemo<StatisticsRequest>(() => {
return {
variableIdMap: { purchase: "KQB0"},
bannerIdList: ["product"],
filterCondition: normalizeFilterCondition(debouncedFilterValue),
option: { useCache: USE_CACHE, lastYear: false, decimalPoint: API_DECIMAL_POINT },
};
}, [debouncedFilterValue]);
const { data, isError, error } = useProductStatisticsQuery(req);
if(isError){
console.error(error);
} }
const purchaseRows =
data?.statisticsDataMap?.purchase
.filter((r) => r.rowLabel == `구매`)
.map((row) => {
const rowSample = data?.statisticsDataMap?.purchase
.find(r => r.rowLabel == '사례수' && r.year == row.year)?.total ?? 0;
return {
...row,
rowLabel: row.year,
sample: `(${rowSample})`,
}
}) ?? [];
const purchaseRowsWithGap = useMemo(() => {
return withGapRow(wrapSampleRow(purchaseRows, false), calcGapProductRow, -1, -2);
}, [purchaseRows]);
const purchaseTableRows = useMemo<TopChartTableRow[]>(() => {
return purchaseRowsWithGap.map((row) => ({
label: formatRowLabel(row.rowLabel),
sample: row.sample,
total: row.total,
values: PRODUCT_KEYS.map((k) => (row as any)[k] ?? null),
}));
}, [purchaseRowsWithGap]);
const purchaseChartData = useMemo<ChartData>(() => {
return {
categories: [...PRODUCTS],
series: purchaseRows.filter((r) => !r.rowLabel.includes("사례수"))
.map((r) => ({
name: r.rowLabel,
data: PRODUCT_KEYS.map((k) => (r as any)[k] ?? null),
})),
};
}, [purchaseRows]);
const description = useMemo(() => {
return "Q. 다음 중 귀댁에서 보유하고 계신 가전/전자 제품은 무엇입니까? 모두 선택해주세요.<br/>" +
"* 구독/렌탈/선물/경품/아파트 내 빌트인 제품을 모두 포함하여 선택해주세요.<br/>" +
"Q. 보유하고 계신 (제품)을 언제 구입하셨습니까?<br/>";
/*
"* 새 상품을 선물 받은 경우, 선물 받은 연도로 입력해주세요.<br/>" +
"** 중고 제품인 경우, 중고 제품을 구입한 연도로 입력해주세요.<br/>" +
"*** 신규 입주 시 빌트인되어 있던 제품은 입주한 연도를 입력해주세요.";
*/
}, []);
useEffect(() => {
registerExcelExporter(async () => {
const excelHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP, "sample");
await exportDashboardExcel({
fileName: `${SITE_TITLE}(구매율).xlsx`,
sheetName: "구매율",
sections: [
{ title: "구매율", header: excelHeader, rows: purchaseRowsWithGap, rowGap: 1 },
],
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter, purchaseRowsWithGap]);
return (
<div>
<TopChartTable
title={"전체 구매율"}
categories={[...PRODUCTS]}
rows={purchaseTableRows}
chart={
<VerticalBar
data={purchaseChartData}
paletteVarNames={["--chart-3", "--chart-2", "--chart-1"]}
grid={GRID_X_NOT_PADDING}
xAxis={{ type: "category", data: [...PRODUCTS], ...AXIS_HIDE_STYLE }}
yAxis={{ type: "value", min:0, max:100, ...AXIS_HIDE_STYLE }}
showFocusLabel={"last"}
height={260}
/>
}
signStyle={signStyleGapRow}
/>
<BottomDescription description={description} />
</div>
);
};
export default PurchasePage; export default PurchasePage;

View File

@@ -89,7 +89,7 @@ const LoginPage = () => {
}; };
return ( return (
<div className="min-h-screen flex items-center justify-center p-4 bg-lg-login"> <div className="min-h-screen flex items-center justify-center p-4 bg-lg-login-body">
<Card className="w-full max-w-md shadow-xl"> <Card className="w-full max-w-md shadow-xl">
<CardHeader className="space-y-4"> <CardHeader className="space-y-4">
<div className="flex justify-center"> <div className="flex justify-center">

View File

@@ -1,30 +1,16 @@
import {createBackApi} from "@/lib/server-api"; import {createBackApi} from "@/lib/server-api";
import {LoginRequest, LoginUser} from "@/types/auth"; import {LoginRequest, LoginResponse, LoginUser} from "@/types/auth";
import {NextRequest, NextResponse} from "next/server"; import {NextRequest, NextResponse} from "next/server";
import {serverEnv} from "@/lib/env.server"; import {serverEnv} from "@/lib/env.server";
import {errorToResponse} from "@/lib/http-util"; import {errorToResponse} from "@/lib/http-util";
type LoginResponse = {
accessToken: string;
user: LoginUser;
};
export const POST = async (req: NextRequest) => { export const POST = async (req: NextRequest) => {
try { try {
const backApi = await createBackApi(); const backApi = await createBackApi();
const body = (await req.json()) as LoginRequest; const body = (await req.json()) as LoginRequest;
//const result = await backApi.post<LoginResponse>("/auth/login", body);
const result:LoginResponse = { const result = await backApi.post<LoginResponse>("/auth/login", body);
accessToken: "abcdefghijklmnopqrstuvwxyz0123456789",
user: {
userId: "TEST_USER",
userName: "TEST_USER",
userCmpn: "TEST",
userTeam: "TEST",
userRole: 9999,
}
}
const res = NextResponse.json(result.user, { status: 200 }); const res = NextResponse.json(result.user, { status: 200 });
res.cookies.set("access_token", result.accessToken, { res.cookies.set("access_token", result.accessToken, {

View File

@@ -14,11 +14,15 @@ export async function POST(
const [userId] = slug; const [userId] = slug;
/*
서버 로그아웃 할 필요 없음
const url = userId const url = userId
? `/auth/logout/${encodeURIComponent(userId)}` ? `/auth/logout/${encodeURIComponent(userId)}`
: "/auth/logout/"; : "/auth/logout/";
//await backApi.post<boolean>(url); await backApi.post<boolean>(url);
*/
const res = NextResponse.json({ ok: true }); const res = NextResponse.json({ ok: true });
res.cookies.set("access_token", "", { res.cookies.set("access_token", "", {

View File

@@ -0,0 +1,39 @@
import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common";
import {errorToResponse} from "@/lib/http-util";
import {createBackApi} from "@/lib/server-api";
import {ProductResponse, BannerResponse} from "@/types/lg.types";
export async function POST(
req: NextRequest,
context: RouteContext
) {
try {
const {slug = []} = await context.params;
const backApi = await createBackApi();
const [action] = slug;
if(action === "product" || action === "banner"){
const body = await req.json().catch(() => null);
if (!body) {
return NextResponse.json(
{ message: "요청 바디가 없습니다." },
{ status: 400 }
);
}
if (action === "product") {
const result = await backApi.post<ProductResponse>(`/statistics`, body);
return NextResponse.json(result, { status: 200 });
}
// action === "banner"
const result = await backApi.post<BannerResponse>(`/statistics`, body);
return NextResponse.json(result, { status: 200 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
}

View File

@@ -54,17 +54,6 @@
--color-warning: var(--warning); --color-warning: var(--warning);
--color-info: var(--info); --color-info: var(--info);
/* Chart */
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--color-chart-6: var(--chart-6);
--color-chart-7: var(--chart-7);
--color-chart-8: var(--chart-8);
--color-chart-9: var(--chart-9);
--color-chart-10: var(--chart-10);
--color-chart-border: var(--chart-border); --color-chart-border: var(--chart-border);
/* Sidebar (shadcn sidebar 토큰) */ /* Sidebar (shadcn sidebar 토큰) */
@@ -108,16 +97,24 @@
--lg-gray-400: 0 0% 50%; /* #7F7F7F */ --lg-gray-400: 0 0% 50%; /* #7F7F7F */
--lg-gray-300: 0 0% 75%; /* #BFBFBF */ --lg-gray-300: 0 0% 75%; /* #BFBFBF */
--lg-gray-200: 0 0% 85%; /* #D9D9D9 */ --lg-gray-200: 0 0% 85%; /* #D9D9D9 */
--lg-gray-100: 0 0% 92%; /* #EBEBEB */
--lg-gray-50: 0 0% 96%; /* #F5F5F5 */
--lg-red-600: 341.1 100% 32.4%; /* #A50034 */ --lg-red-600: 341.1 100% 32.4%; /* #A50034 */
--lg-red-500: 341.1 95% 44.0%; /* #DB0649 */ --lg-red-500: 341.1 95% 44.0%; /* #DB0649 */
--lg-red-400: 341.1 85% 56.0%; /* #EE2F6C */ --lg-red-400: 341.1 85% 56.0%; /* #EE2F6C */
--lg-red-300: 341.1 75% 68.0%; /* #EB7097 */ --lg-red-300: 341.1 75% 68.0%; /* #EB7097 */
--lg-red-200: 341.1 65% 82.0%; /* #EFB3C6 */
--lg-red-100: 341.1 55% 90.0%; /* #F4D7E0 */
--lg-red-50: 341.1 45% 96.0%; /* #F9F0F3 */
--lg-pink-600: 324.7 100% 46.3%; /* #EC008B */ --lg-pink-600: 324.7 100% 46.3%; /* #EC008B */
--lg-pink-500: 324.7 95% 56.0%; /* #F924A2 */ --lg-pink-500: 324.7 95% 56.0%; /* #F924A2 */
--lg-pink-400: 324.7 85% 66.0%; /* #F25FB5 */ --lg-pink-400: 324.7 85% 66.0%; /* #F25FB5 */
--lg-pink-300: 324.7 75% 76.0%; /* #F094CA */ --lg-pink-300: 324.7 75% 76.0%; /* #F094CA */
--lg-pink-200: 324.7 65% 86.0%; /* #F3C4DF */
--lg-pink-100: 324.7 55% 92.0%; /* #F6DFED */
--lg-pink-50: 324.7 45% 97.0%; /* #FBF4F8 */
--lg-purple-600: 263.0 65.9% 44.9%; /* #6127BE */ --lg-purple-600: 263.0 65.9% 44.9%; /* #6127BE */
--lg-purple-500: 263.0 60.0% 56.0%; --lg-purple-500: 263.0 60.0% 56.0%;
@@ -128,7 +125,6 @@
--lg-orange-500: 29.6 95% 56.0%; --lg-orange-500: 29.6 95% 56.0%;
--lg-orange-400: 29.6 85% 68.0%; --lg-orange-400: 29.6 85% 68.0%;
--lg-orange-300: 29.6 75% 78.0%; --lg-orange-300: 29.6 75% 78.0%;
/* ============================= /* =============================
Brand Core Brand Core
(semantic은 "실제 색"으로 정의) (semantic은 "실제 색"으로 정의)
@@ -166,16 +162,33 @@
/* ============================= /* =============================
Chart Colors Chart Colors
============================= */ ============================= */
--chart-1: hsl(var(--lg-red-600)); --chart-1: 334 81% 41%;
--chart-2: hsl(var(--lg-red-300)); --chart-2: 0 0% 49%;
--chart-3: hsl(var(--lg-pink-300)); --chart-3: 0 0% 74%;
--chart-4: hsl(var(--lg-pink-400)); --chart-1-t: 334 80% 90%;
--chart-5: hsl(var(--lg-pink-600)); --chart-2-t: 0 0% 70%;
--chart-6: hsl(var(--lg-gray-900)); --chart-3-t: 0 0% 88%;
--chart-7: hsl(var(--lg-gray-800));
--chart-8: hsl(var(--lg-gray-700)); --chart-stack-1: 335 64% 34%;
--chart-9: hsl(var(--lg-gray-600)); --chart-stack-2: 332 65% 57%;
--chart-10: hsl(var(--lg-gray-500)); --chart-stack-3: 334 66% 73%;
--chart-stack-4: 334 28% 49%;
--chart-stack-5: 340 25% 58%;
--chart-stack-6: 0 28% 69%;
--chart-stack-7: 26 37% 70%;
--chart-stack-8: 27 38% 83%;
--chart-stack-9: 30 45% 91%;
--chart-stack-10: 0 0% 50%;
--chart-stack-11: 0 0% 60%;
--chart-stack-12: 0 0% 71%;
--chart-stack-13: 0 0% 82%;
--chart-stack-14: 0 0% 91%;
--chart-lg: var(--chart-1);
--chart-samsung: 218 48% 58%;
--chart-cbrand: var(--chart-2);
--chart-etc: 0 0% 74%;
--chart-border: hsl(0 0% 95%); --chart-border: hsl(0 0% 95%);
/* ============================= /* =============================
@@ -285,6 +298,8 @@
.border-border { border-color: var(--border); } .border-border { border-color: var(--border); }
/* LG gray scale (Tailwind gray override 의도 유지) */ /* LG gray scale (Tailwind gray override 의도 유지) */
.bg-black { background-color: #111111 !important; }
.bg-gray-900 { background-color: hsl(var(--lg-gray-900)) !important; } .bg-gray-900 { background-color: hsl(var(--lg-gray-900)) !important; }
.bg-gray-800 { background-color: hsl(var(--lg-gray-800)) !important; } .bg-gray-800 { background-color: hsl(var(--lg-gray-800)) !important; }
.bg-gray-700 { background-color: hsl(var(--lg-gray-700)) !important; } .bg-gray-700 { background-color: hsl(var(--lg-gray-700)) !important; }
@@ -293,6 +308,8 @@
.bg-gray-400 { background-color: hsl(var(--lg-gray-400)) !important; } .bg-gray-400 { background-color: hsl(var(--lg-gray-400)) !important; }
.bg-gray-300 { background-color: hsl(var(--lg-gray-300)) !important; } .bg-gray-300 { background-color: hsl(var(--lg-gray-300)) !important; }
.bg-gray-200 { background-color: hsl(var(--lg-gray-200)) !important; } .bg-gray-200 { background-color: hsl(var(--lg-gray-200)) !important; }
.bg-gray-100 { background-color: hsl(var(--lg-gray-100)) !important; }
.bg-gray-50 { background-color: hsl(var(--lg-gray-50)) !important; }
.border-gray-900 { border-color: hsl(var(--lg-gray-900)) !important; } .border-gray-900 { border-color: hsl(var(--lg-gray-900)) !important; }
.border-gray-800 { border-color: hsl(var(--lg-gray-800)) !important; } .border-gray-800 { border-color: hsl(var(--lg-gray-800)) !important; }
@@ -302,17 +319,23 @@
.border-gray-400 { border-color: hsl(var(--lg-gray-400)) !important; } .border-gray-400 { border-color: hsl(var(--lg-gray-400)) !important; }
.border-gray-300 { border-color: hsl(var(--lg-gray-300)) !important; } .border-gray-300 { border-color: hsl(var(--lg-gray-300)) !important; }
.border-gray-200 { border-color: hsl(var(--lg-gray-200)) !important; } .border-gray-200 { border-color: hsl(var(--lg-gray-200)) !important; }
.border-gray-100 { border-color: hsl(var(--lg-gray-100)) !important; }
.border-gray-50 { border-color: hsl(var(--lg-gray-50)) !important; }
/* LG Red/Pink/Purple/Orange scale overrides */ /* LG Red/Pink/Purple/Orange scale overrides */
.bg-red-600 { background-color: hsl(var(--lg-red-600)) !important; } .bg-red-600 { background-color: hsl(var(--lg-red-600)) !important; }
.bg-red-500 { background-color: hsl(var(--lg-red-500)) !important; } .bg-red-500 { background-color: hsl(var(--lg-red-500)) !important; }
.bg-red-400 { background-color: hsl(var(--lg-red-400)) !important; } .bg-red-400 { background-color: hsl(var(--lg-red-400)) !important; }
.bg-red-300 { background-color: hsl(var(--lg-red-300)) !important; } .bg-red-300 { background-color: hsl(var(--lg-red-300)) !important; }
.bg-red-200 { background-color: hsl(var(--lg-red-200)) !important; }
.bg-red-100 { background-color: hsl(var(--lg-red-100)) !important; }
.bg-pink-600 { background-color: hsl(var(--lg-pink-600)) !important; } .bg-pink-600 { background-color: hsl(var(--lg-pink-600)) !important; }
.bg-pink-500 { background-color: hsl(var(--lg-pink-500)) !important; } .bg-pink-500 { background-color: hsl(var(--lg-pink-500)) !important; }
.bg-pink-400 { background-color: hsl(var(--lg-pink-400)) !important; } .bg-pink-400 { background-color: hsl(var(--lg-pink-400)) !important; }
.bg-pink-300 { background-color: hsl(var(--lg-pink-300)) !important; } .bg-pink-300 { background-color: hsl(var(--lg-pink-300)) !important; }
.bg-pink-200 { background-color: hsl(var(--lg-pink-200)) !important; }
.bg-pink-100 { background-color: hsl(var(--lg-pink-100)) !important; }
.bg-purple-600 { background-color: hsl(var(--lg-purple-600)) !important; } .bg-purple-600 { background-color: hsl(var(--lg-purple-600)) !important; }
.bg-purple-500 { background-color: hsl(var(--lg-purple-500)) !important; } .bg-purple-500 { background-color: hsl(var(--lg-purple-500)) !important; }
@@ -363,23 +386,57 @@
.placeholder-content-text-3xl::placeholder { font-size: calc(var(--content-font-size) * 1.875); } .placeholder-content-text-3xl::placeholder { font-size: calc(var(--content-font-size) * 1.875); }
.placeholder-content-text-4xl::placeholder { font-size: calc(var(--content-font-size) * 2.25); } .placeholder-content-text-4xl::placeholder { font-size: calc(var(--content-font-size) * 2.25); }
.bg-lg-login { .bg-lg-login-body {
background-color: hsl(var(--background)); background-color: hsl(var(--background));
background-image: linear-gradient( background-image: linear-gradient(
135deg, 135deg,
hsl(var(--lg-red-600) / 0.16) 0%, hsl(var(--lg-gray-900) / 0.5) 0%,
var(--background) 50%, var(--background) 30%,
hsl(var(--lg-pink-600) / 0.14) 100% var(--background) 70%,
hsl(var(--lg-gray-900) / 0.5) 100%
); );
} }
.text-header-color { color: #FFFFFF; }
.text-header-primary {
color: #FFFFFF;
font-weight: 600;
position: relative;
padding-bottom: 4px;
}
.text-header-primary::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 3px;
background: linear-gradient(90deg, #A50034 0%, #E6004C 100%);
border-radius: 2px 2px 0 0;
}
/* 비활성 메뉴 스타일 */
.text-header-secondary-hover {
color: #C0C0C0;
transition: all 0.3s ease;
cursor: pointer;
}
/* 호버 효과 */
.text-header-secondary-hover:hover {
color: rgba(255, 255, 255, 0.9) !important;
}
.bg-lg-main-body { .bg-lg-main-body {
background-color: hsl(var(--background)); background-color: hsl(var(--background));
background-image: linear-gradient( background-image: linear-gradient(
135deg, 135deg,
hsl(var(--lg-red-500) / 0.12) 0%, hsl(var(--lg-gray-900) / 0.2) 0%,
var(--background) 50%, var(--background) 30%,
hsl(var(--lg-pink-500) / 0.10) 100% var(--background) 70%,
hsl(var(--lg-gray-900) / 0.2) 100%
); );
} }
} }
@@ -406,16 +463,28 @@
line-height: 1.15; line-height: 1.15;
text-align: center; text-align: center;
word-wrap: break-word; word-wrap: break-word;
word-break: break-all; word-break: auto-phrase;
}
.lg-table th.lg-table__no-border-r,
.lg-table td.lg-table__no-border-r {
border-right: 0 !important;
}
.lg-table th.lg-table__no-border-l,
.lg-table td.lg-table__no-border-l {
border-left: 0 !important;
} }
.lg-table thead tr.lg-table__group th { .lg-table thead tr.lg-table__group th {
background: hsl(var(--lg-gray-400)); background: hsl(var(--lg-gray-400));
white-space: pre-wrap;
color: #fff; color: #fff;
font-weight: 700; font-weight: 700;
} }
.lg-table thead tr.lg-table__subhead th { .lg-table thead tr.lg-table__subhead th {
background: hsl(var(--lg-gray-600)); background: hsl(var(--lg-gray-600));
white-space: pre-wrap;
color: #fff; color: #fff;
font-weight: 700; font-weight: 700;
} }
@@ -426,7 +495,7 @@
color: var(--foreground); color: var(--foreground);
background: var(--background); background: var(--background);
word-wrap: break-word; word-wrap: break-word;
word-break: break-all; word-break: auto-phrase;
} }
.lg-table .lg-table__sep-l { border-left: 3px solid hsl(var(--lg-gray-200)) !important; } .lg-table .lg-table__sep-l { border-left: 3px solid hsl(var(--lg-gray-200)) !important; }

View File

@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google"; import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css"; import "./globals.css";
import {Toaster} from "sonner"; import {Toaster} from "sonner";
import {AppProvider} from "@/components/providers/AppProvider";
const geistSans = Geist({ const geistSans = Geist({
variable: "--font-geist-sans", variable: "--font-geist-sans",
@@ -26,7 +27,7 @@ const RootLayout = ({
return ( return (
<html lang="en"> <html lang="en">
<body className={`${geistSans.variable} ${geistMono.variable} antialiased`}> <body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
{children} <AppProvider>{children}</AppProvider>
<Toaster /> <Toaster />
</body> </body>
</html> </html>

View File

@@ -0,0 +1,20 @@
"use client";
import { useAtomValue } from "jotai";
import { Loader2Icon } from "lucide-react";
import { loadingAtom } from "@/store/jotai/loading";
export function LoadingOverlay({ force = false }: { force?: boolean }) {
const isLoading = useAtomValue(loadingAtom);
if (!force && !isLoading) return null;
return (
<div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/65">
<div className="flex flex-col items-center gap-3">
<Loader2Icon className="size-20 animate-spin text-white" style={{ animationDuration: "0.7s" }} />
<div className="text-sm font-medium tracking-[0.18em] text-white/90">Loading</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,19 @@
"use client";
import {useIsFetching} from "@tanstack/react-query";
import {useLoading} from "@/hooks/useLoading";
import {useEffect} from "react";
const ReactQueryLoadingSync = () => {
const fetching = useIsFetching();
const { showLoading, hideLoading } = useLoading();
useEffect(() => {
if (fetching > 0) showLoading();
else hideLoading();
}, [fetching, showLoading, hideLoading]);
return null;
};
export default ReactQueryLoadingSync;

View File

@@ -1,19 +1,17 @@
"use client"; "use client";
import { CategoryTargetData, CategoryTargetType } from "@/config/filter.types"; import {
import {categoryTarget, categoryTargetType} from "@/config/filter.data"; CategoryTargetType,
TargetChild,
} from "@/types/filter.types";
import {categoryTarget, categoryTargetType} from "@/const/filter.const";
import { ChevronRight } from "lucide-react"; import { ChevronRight } from "lucide-react";
import { useMemo } from "react"; import {useCallback, useMemo} from "react";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import {ProductKey, ProductsFilterItem} from "@/types/lg.types";
const PRODUCTS = [ import {PRODUCT_KEY_MAP} from "@/const/lg-schema.const";
{ value: "냉장고", label: "냉장고" }, import {YEARS} from "@/const/lg-common.const";
{ value: "세탁기", label: "세탁기" },
{ value: "식기세척기", label: "식기세척기" },
{ value: "건조기", label: "건조기" },
{ value: "에어컨", label: "에어컨" },
] as const;
export type CategoryTypeValue = { export type CategoryTypeValue = {
label: string; label: string;
@@ -21,124 +19,191 @@ export type CategoryTypeValue = {
}; };
export type CategoryFilterValue = { export type CategoryFilterValue = {
product: string; product: ProductKey;
year: string;
type: CategoryTypeValue type: CategoryTypeValue
target: CategoryTargetData; target: TargetChild;
}; };
type CategoryFilterProps = { type CategoryFilterProps = {
filterItems: ProductsFilterItem,
value: CategoryFilterValue; value: CategoryFilterValue;
onChange: (next: CategoryFilterValue) => void; onChange: (next: CategoryFilterValue) => void;
className?: string; className?: string;
}; };
const CategoryFilter = ({ value, onChange, className }: CategoryFilterProps) => { type Option = { key: string; label: string; value: string | CategoryTypeValue | TargetChild };
const currentTargetItem = useMemo(() => { type RowDef = {
return categoryTarget.find((item) => item.type === value.type.value); id: "year" | "product" | "type" | "target";
}, [value.type]); title: string;
options: Option[];
const handlePick = ( isActive: (v: Option["value"]) => boolean;
key: keyof CategoryFilterValue, onSelect: (v: Option["value"]) => void;
v: string | CategoryTypeValue | CategoryTargetData
) => {
if (value[key] === v) return;
const next: CategoryFilterValue = { ...value, [key]: v } as CategoryFilterValue;
if (key === "type") {
const nextItem = categoryTarget.find((item) => item.type === v);
const firstTarget = nextItem?.children?.[0]?.target;
if (firstTarget) next.target = firstTarget;
}
onChange(next);
}; };
function FilterLine({ title, options, isActive, onSelect }: Omit<RowDef, "id">) {
return ( return (
<div className={cn("w-full border border-gray-300 bg-white/70 backdrop-blur-sm", className)}>
{/* 제품 (1줄 나열) */}
<div className="flex min-w-0 border-b border-gray-200">
<div className="flex w-[140px] shrink-0 items-center gap-2 px-3 py-2">
<ChevronRight className="h-4 w-4 text-gray-700" />
<span className="text-sm font-semibold text-gray-900 content-text-sm">제품</span>
</div>
<div className="min-w-0 flex-1 overflow-x-auto px-2 py-2">
<div className="flex w-max items-center gap-1 whitespace-nowrap">
{PRODUCTS.map((p) => {
const active = value.product === p.value;
return (
<Button
key={p.value}
type="button"
variant={active ? "default" : "secondary"}
onClick={() => handlePick("product", p.value)}
className="h-6 shrink-0 rounded-sm px-3 text-sm font-semibold content-text-sm"
>
{p.label}
</Button>
);
})}
</div>
</div>
</div>
{/* 기준 (1줄 나열) */}
<div className="flex min-w-0 border-b border-gray-200">
<div className="flex w-[140px] shrink-0 items-center gap-2 px-3 py-2">
<ChevronRight className="h-4 w-4 text-gray-700" />
<span className="text-sm font-semibold text-gray-900 content-text-sm">기준</span>
</div>
<div className="min-w-0 flex-1 overflow-x-auto px-2 py-2">
<div className="flex w-max items-center gap-1 whitespace-nowrap">
{categoryTargetType.map((item) => {
const active = value.type.label === item.label;
return (
<Button
key={item.label}
type="button"
variant={active ? "default" : "secondary"}
onClick={() => {
handlePick("type", {label:item.label, value:item.value});
}}
className="h-6 shrink-0 rounded-sm px-3 text-sm font-semibold content-text-sm"
>
{item.label}
</Button>
);
})}
</div>
</div>
</div>
{/* 데이터 (1줄 나열) */}
<div className="flex min-w-0"> <div className="flex min-w-0">
<div className="flex w-[140px] shrink-0 items-center gap-2 px-3 py-2"> <div className="flex w-[140px] shrink-0 items-center gap-2 px-3 py-2">
<ChevronRight className="h-4 w-4 text-gray-700" /> <ChevronRight className="h-4 w-4 text-gray-700" />
<span className="text-sm font-semibold text-gray-900 content-text-sm">데이터</span> <span className="text-sm font-semibold text-gray-900 content-text-sm">
{title}
</span>
</div> </div>
<div className="min-w-0 flex-1 overflow-x-auto px-2 py-2"> <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1 px-2 py-2">
<div className="flex w-max items-center gap-1 whitespace-nowrap"> {options.map((opt) => {
{currentTargetItem?.children?.map((child) => { const active = isActive(opt.value);
const active = value.target === child.target;
return ( return (
<Button <Button
key={child.target} key={opt.key}
type="button" type="button"
variant={active ? "default" : "secondary"} variant={active ? "default" : "secondary"}
onClick={() => handlePick("target", child.target)} onClick={() => onSelect(opt.value)}
className="h-6 shrink-0 rounded-sm px-3 text-sm font-semibold content-text-sm" className="h-8 shrink-0 rounded-sm px-3 text-sm font-semibold content-text-base"
> >
{child.label} {opt.label}
</Button> </Button>
); );
})} })}
</div> </div>
</div> </div>
);
}
const CategoryFilter = ({ filterItems, value, onChange, className }: CategoryFilterProps) => {
const currentTargetItem = useMemo(() => {
return categoryTarget.find((item) => item.type.includes(value.type.value));
}, [value.type.value]);
// type 비교는 객체참조가 아니라 value로 비교해야 함
const handlePick = useCallback(
<K extends keyof CategoryFilterValue>(key: K, v: CategoryFilterValue[K]) => {
// 1) type
if (key === "type") {
const nextType = v as CategoryTypeValue;
if (value.type.value === nextType.value) return;
const nextItem = categoryTarget.find((item) =>
item.type.includes(nextType.value)
);
const firstTarget = nextItem?.children?.[0];
onChange({
...value,
type: nextType,
target: firstTarget ?? value.target,
});
return;
}
// 2) target (객체 비교는 value로)
if (key === "target") {
const nextTarget = v as TargetChild;
if (value.target.value === nextTarget.value) return;
onChange({ ...value, target: nextTarget });
return;
}
// 3) year/product (primitive)
if (value[key] === v) return;
onChange({ ...value, [key]: v } as CategoryFilterValue);
},
[value, onChange]
);
const rowDefs = useMemo<RowDef[]>(() => {
const yearRow:RowDef = {
id:"year",
title: "연도",
options:(YEARS).map((y) => ({
key:y,
label:`${y}년`,
value:y,
})),
isActive: (v) => value.year === v,
onSelect: (v) => handlePick("year", v as string),
};
const productRow: RowDef = {
id: "product",
title: "제품",
options: (filterItems.items ?? []).map((p) => ({
key: p,
label: PRODUCT_KEY_MAP[p],
value: p,
})),
isActive: (v) => value.product === v,
onSelect: (v) => handlePick("product", v as ProductKey),
};
const typeRow: RowDef = {
id: "type",
title: "기준",
options: categoryTargetType.map((t) => ({
key: t.label,
label: t.label,
value: { label: t.label, value: t.value },
})),
isActive: (v) => value.type.value === (v as CategoryTypeValue).value,
onSelect: (v) => handlePick("type", v as CategoryTypeValue),
};
const targetRow: RowDef = {
id: "target",
title: "데이터",
options: (currentTargetItem?.children ?? []).map((c) => ({
key: String(c.value),
label: c.label,
value: { label: c.label, value: c.value },
})),
isActive: (v) => value.target.value === (v as TargetChild).value,
onSelect: (v) => handlePick("target", v as TargetChild),
};
// 여기 순서만 바꾸면 배치도 같이 바뀜 (left: 앞쪽 half, right: 뒤쪽 half)
return [yearRow, productRow, typeRow, targetRow];
}, [YEARS, filterItems.items, currentTargetItem, value, handlePick]);
const cells = useMemo(() => {
const half = Math.ceil(rowDefs.length / 2); // 3개면 2개(left) + 1개(right)
const maxRows = half;
return rowDefs.map((def, i) => {
const col = i < half ? 0 : 1; // 0:left, 1:right
const row = i < half ? i : i - half;
return { def, col, row, maxRows };
});
}, [rowDefs]);
return (
<div className={cn("w-full border border-gray-300 bg-white/70 backdrop-blur-sm", className)}>
<div className="grid grid-cols-2">
{cells.map(({ def, col, row, maxRows }) => {
const showRowDivider = row < maxRows - 1; // 같은 rowIndex 기준으로 좌/우 라인 맞춤
return (
<div
key={def.id}
style={{
gridColumnStart: col + 1,
gridRowStart: row + 1,
}}
className={cn(
"min-w-0",
showRowDivider && "border-b border-gray-200",
col === 1 && "border-l-4 border-gray-300"
)}
>
<FilterLine
title={def.title}
options={def.options}
isActive={def.isActive}
onSelect={def.onSelect}
/>
</div>
);
})}
</div> </div>
</div> </div>
); );

View File

@@ -0,0 +1,26 @@
"use client";
import { Button } from "@/components/ui/button";
import { useLayoutFilter } from "./LayoutFilterContext";
import Image from "next/image";
const ExcelDownloadButton = () => {
const { requestExcelExport } = useLayoutFilter();
return (
<div className={"mr-2 pb-1 cursor-pointer"}>
<Image
src="/icon-excel.png"
alt="excel export"
width={27}
height={27}
className="object-contain"
onClick={requestExcelExport}
priority
/>
</div>
);
};
export default ExcelDownloadButton;

View File

@@ -2,11 +2,11 @@ import {useAuth} from "@/hooks/useAuth";
import {useEffect, useState} from "react"; import {useEffect, useState} from "react";
import {LoginUser} from "@/types/auth"; import {LoginUser} from "@/types/auth";
import Image from "next/image"; import Image from "next/image";
import {topMenus} from "@/config/menu.data"; import {topMenus} from "@/const/menu.const";
import {Button} from "@/components/ui/button"; import {Button} from "@/components/ui/button";
import {LogOut} from "lucide-react"; import {LogOut} from "lucide-react";
import {DASHBOARD_YEAR} from "@/const/commonConst";
import {cn} from "@/lib/utils"; import {cn} from "@/lib/utils";
import {SITE_TITLE} from "@/const/lg-common.const";
interface HeaderProps { interface HeaderProps {
activeTopId: string; activeTopId: string;
@@ -30,13 +30,13 @@ const Header = ({
}, [auth.user]) }, [auth.user])
return ( return (
<header className="bg-white border-b border-gray-200 sticky top-0 z-40"> <header className="bg-black border-b border-gray-200 sticky top-0 z-40">
<div className="flex items-center justify-between px-4 h-16"> <div className="flex items-center justify-between px-4 h-16">
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
{/* 로고 */} {/* 로고 */}
<div className="flex items-center gap-2 cursor-pointer w-30 h-15 justify-center"> <div className="flex items-center gap-2 cursor-pointer w-30 h-15 justify-center">
<Image <Image
src="/logo.png" // public/logo.png src="/logo_transparent.png" // public/logo.png
alt="브랜드 로고" alt="브랜드 로고"
width={200} width={200}
height={80} height={80}
@@ -56,32 +56,26 @@ const Header = ({
type="button" type="button"
onClick={() => onNavigate(m.path)} onClick={() => onNavigate(m.path)}
className={cn( className={cn(
"relative h-10 inline-flex items-center font-semibold transition-colors cursor-pointer", "relative h-8 inline-flex items-center font-bold transition-colors cursor-pointer",
"content-text-base bg-transparent px-1", "content-text-lg bg-transparent px-1",
active active
? "text-primary" ? "text-header-primary"
: "text-secondary-hover" : "text-header-secondary-hover"
)} )}
> >
{m.label} {m.label}
{/* 선택 표시(밑줄) */}
{active && (
<span className="absolute left-0 right-0 -bottom-[2px] h-[2px] bg-primary" />
)}
</button> </button>
); );
})} })}
</nav> </nav>
</div> </div>
<div className="flex justify-between items-center"> <div className="flex justify-between items-center">
<h1 className="font-bold content-text-2xl">{DASHBOARD_YEAR}년도 가전보급률 Dashboard</h1> <h1 className="font-bold content-text-2xl text-header-color">{SITE_TITLE}</h1>
</div> </div>
{/* 우측 컨트롤 */} {/* 우측 컨트롤 */}
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<span className="text-sm text-gray-600 hidden sm:inline font-bold">{userInfo?.userName || ""}</span> <span className="content-text-base text-header-color hidden sm:inline font-bold">{userInfo?.userName || ""}</span>
<Button <Button
variant="ghost"
size="sm" size="sm"
className="gap-2" className="gap-2"
onClick={() => onNavigate("/logout")} onClick={() => onNavigate("/logout")}

View File

@@ -0,0 +1,58 @@
"use client";
import React, { createContext, useCallback, useContext, useMemo, useRef } from "react";
import type { SelectedMap } from "@/types/common";
import {CategoryFilterValue} from "@/components/layout/CategoryFilter";
export type ExcelExportContext =
| { isTotal: true; filterValue: SelectedMap }
| { isTotal: false; filterValue: CategoryFilterValue };
type ExcelExporter = (ctx: ExcelExportContext) => void | Promise<void>;
type LayoutFilterContextValue = ExcelExportContext & {
registerExcelExporter: (exporter: ExcelExporter | null) => void;
requestExcelExport: () => Promise<void>;
};
const LayoutFilterContext = createContext<LayoutFilterContextValue | null>(null);
export const LayoutFilterProvider = ({
value,
children,
}: {
value: ExcelExportContext;
children: React.ReactNode;
}) => {
const exporterRef = useRef<ExcelExporter | null>(null);
const registerExcelExporter = useCallback((exporter: ExcelExporter | null) => {
exporterRef.current = exporter;
}, []);
const requestExcelExport = useCallback(async () => {
const exporter = exporterRef.current;
if (!exporter) {
console.warn("Excel exporter is not registered.");
return;
}
await exporter(value);
}, [value]);
const ctxValue = useMemo<LayoutFilterContextValue>(
() => ({
...value,
registerExcelExporter,
requestExcelExport,
}),
[value, registerExcelExporter, requestExcelExport]
);
return <LayoutFilterContext.Provider value={ctxValue}>{children}</LayoutFilterContext.Provider>;
};
export const useLayoutFilter = () => {
const ctx = useContext(LayoutFilterContext);
if (!ctx) throw new Error("useLayoutFilter must be used within LayoutFilterProvider");
return ctx;
};

View File

@@ -1,17 +1,23 @@
"use client"; "use client";
import {ReactNode, useState} from "react"; import {ReactNode, useEffect, useMemo, useRef, useState} from "react";
import {usePathname, useRouter} from "next/navigation"; import {usePathname, useRouter} from "next/navigation";
import {topMenus, totalSubMenus, categorySubMenus} from "@/config/menu.data"; import {cn} from "@/lib/utils";
import {SelectedMap} from "@/types/common";
import {topMenus, totalSubMenus, categorySubMenus} from "@/const/menu.const";
import {categoryTarget, totalFilters} from "@/const/filter.const";
import {CategoryTargetData, CategoryTargetType} from "@/types/filter.types";
import Header from "./Header"; import Header from "./Header";
import SubMenu from "./SubMenu"; import SubMenu from "./SubMenu";
import TotalFilter from "@/components/layout/TotalFilter"; import TotalFilter from "./TotalFilter";
import CategoryFilter, {CategoryFilterValue} from "@/components/layout/CategoryFilter"; import CategoryFilter, {CategoryFilterValue} from "./CategoryFilter";
import {cn} from "@/lib/utils"; import ExcelDownloadButton from "./ExcelDownloadButton";
import {LayoutFilterProvider} from "./LayoutFilterContext";
import {LAST_YEAR} from "@/const/lg-common.const";
import {PRODUCTS_FILTER_ITEM} from "@/const/lg-product.const";
import {ProductsFilterItem} from "@/types/lg.types";
import {ArrowUp, Filter} from "lucide-react";
import {Button} from "@/components/ui/button"; import {Button} from "@/components/ui/button";
import {SelectedMap} from "@/types/common";
import {categoryTarget, totalFilters} from "@/config/filter.data";
import {CategoryTargetData, CategoryTargetType} from "@/config/filter.types";
type MainLayoutProps = { type MainLayoutProps = {
children: ReactNode; children: ReactNode;
@@ -22,38 +28,65 @@ const buildDefaultTotalValue = (): SelectedMap => {
totalFilters.forEach((f) => { totalFilters.forEach((f) => {
// "전체"가 있으면 그 value, 없으면 첫 번째 값 // "전체"가 있으면 그 value, 없으면 첫 번째 값
const all = f.children.find((c) => c.label === "전체"); const all = f.children.find((c) => c.label === "전체");
init[f.variable] = all?.value ?? f.children[0]?.value ?? ""; const initValue = all?.value ?? f.children[0]?.value ?? "";
init[f.variable] = [initValue];
}); });
return init; return init;
}; };
export const buildDefaultCategoryValue = (): CategoryFilterValue => { const buildDefaultCategoryValue = (categoryFilterItems: ProductsFilterItem): CategoryFilterValue => {
const initProduct = categoryFilterItems.items[0];
const initType = {label:"보유", value:CategoryTargetType.PENETRATION} const initType = {label:"보유", value:CategoryTargetType.PENETRATION}
const firstTarget = categoryTarget.find((x) => x.type === initType.value)?.children?.[0]?.target; const firstTarget = categoryTarget.find((x) => x.type.includes(initType.value))?.children[0];
const initTarget = firstTarget ?? { value: CategoryTargetData.PROFILE, label: "Profile"};
return { return {
product: "냉장고", year: LAST_YEAR,
product: initProduct,
type: initType, type: initType,
target: firstTarget ?? CategoryTargetData.PROFILE, target: initTarget,
}; };
}; };
const buildTotalPartDescription = (pathname:string) => {
switch(pathname) {
case "/total/penetration":
return "■ 보급률: 전체 소비자 중, 조사 년도에 해당 제품을 <strong>보유하고 있는 비율</strong>";
case "/total/lg-penetration":
return "■ 보급률: 전체 소비자 중, 조사 년도에 LG 제품을 <strong>보유하고 있는 비율</strong>";
case "/total/purchase":
return "■ 구매율: 전체 소비자 중, 조사 년도에 해당 제품을 <strong>구매한 비율</strong>";
case "/total/lg-purchase":
return "■ 구매율: 전체 소비자 중, 조사 년도에 LG 제품을 <strong>구매한 비율</strong>";
default:
return "";
}
}
const MainLayout = ({ children }: MainLayoutProps) => { const MainLayout = ({ children }: MainLayoutProps) => {
const router = useRouter(); const router = useRouter();
const pathname = usePathname(); const pathname = usePathname();
const scrollRef = useRef<HTMLDivElement | null>(null);
const [showScrollTop, setShowScrollTop] = useState(false);
const isTotal = pathname.startsWith("/total"); const isTotal = pathname.startsWith("/total");
const activeTop = topMenus.find((m) => m.match?.(pathname)) ?? topMenus[0]; const activeTop = topMenus.find((m) => m.match?.(pathname)) ?? topMenus[0];
const subMenus = isTotal ? totalSubMenus : categorySubMenus; const subMenus = isTotal ? totalSubMenus : categorySubMenus;
const activeSub = subMenus.find((m) => m.path.startsWith(pathname)) ?? subMenus[0]; const activeSub = subMenus.find((m) => pathname.startsWith(m.path)) ?? subMenus[0];
const [isTotalFilterOpen, setIsTotalFilterOpen] = useState(true); const [isTotalFilterOpen, setIsTotalFilterOpen] = useState(true);
const [isCategoryFilterOpen, setIsCategoryFilterOpen] = useState(true); const [isCategoryFilterOpen, setIsCategoryFilterOpen] = useState(true);
const isFilterOpen = isTotal ? isTotalFilterOpen : isCategoryFilterOpen; const isFilterOpen = isTotal ? isTotalFilterOpen : isCategoryFilterOpen;
const categoryFilterItems = PRODUCTS_FILTER_ITEM.find((m) => pathname.match?.(m.path)) ?? PRODUCTS_FILTER_ITEM[0];
const totalPartDescription = buildTotalPartDescription(pathname);
const [totalValue, setTotalValue] = useState<SelectedMap>(() => buildDefaultTotalValue()); const [totalValue, setTotalValue] = useState<SelectedMap>(() => buildDefaultTotalValue());
const [categoryValue, setCategoryValue] = useState<CategoryFilterValue>(() => buildDefaultCategoryValue()); const [categoryValue, setCategoryValue] = useState<CategoryFilterValue>(() => buildDefaultCategoryValue(categoryFilterItems));
const prevIsTotalRef = useRef<boolean>(isTotal);
const movePage = (path: string) => { const movePage = (path: string) => {
router.push(path); router.push(path);
@@ -64,13 +97,63 @@ const MainLayout = ({ children }: MainLayoutProps) => {
else setIsCategoryFilterOpen((v) => !v); else setIsCategoryFilterOpen((v) => !v);
}; };
const handleExcelDownload = async () => { const onScrollContent = () => {
// TODO: 다운로드 구현 필요 const el = scrollRef.current;
console.log("Excel download:", { pathname, top: activeTop.id, sub: activeSub.id }); if (!el) return;
setShowScrollTop(el.scrollTop > 120);
}; };
const scrollToTop = () => {
scrollRef.current?.scrollTo({ top: 0, behavior: "smooth" });
};
const isDefaultTotalFilter = useMemo(() => {
if(!isTotal) return false;
return Object.values(totalValue).every(value => value.length === 1 && value[0] === "0");
},[isTotal, totalValue])
const setDefaultTotalFilter = () => {
if(isTotal && !isDefaultTotalFilter){
setTotalValue(prev =>
Object.fromEntries(
Object.keys(prev).map(key => [key, ["0"]])
)
);
}
}
useEffect(() => {
const prevIsTotal = prevIsTotalRef.current;
// 1) category -> total : 아무것도 안 함 (여기서 setCategoryValue 하면 1번 더 렌더됨)
if (isTotal) {
prevIsTotalRef.current = isTotal;
return;
}
// 2) total -> category : 들어오는 순간에만 초기화
if (prevIsTotal) {
setCategoryValue(buildDefaultCategoryValue(categoryFilterItems));
prevIsTotalRef.current = isTotal;
return;
}
// 3) category 내부 이동(카테고리 path 바뀜 등) : product만 동기화
const nextProduct = categoryFilterItems.items[0];
setCategoryValue((prev) => {
if (prev.product === nextProduct) return prev;
return { ...prev, product: nextProduct };
});
prevIsTotalRef.current = isTotal;
}, [isTotal, categoryFilterItems]);
return ( return (
<div className="min-h-screen flex flex-col bg-transparent"> <div className="h-screen flex flex-col bg-transparent overflow-hidden">
<LayoutFilterProvider
value={isTotal? { isTotal: true, filterValue: totalValue } : { isTotal: false, filterValue: categoryValue }}
>
<Header <Header
activeTopId={activeTop.id} activeTopId={activeTop.id}
onNavigate={movePage} onNavigate={movePage}
@@ -82,25 +165,35 @@ const MainLayout = ({ children }: MainLayoutProps) => {
onNavigate={movePage} onNavigate={movePage}
/> />
<div className="flex-1 min-h-0 flex flex-col pr-4"> <div className="flex-1 min-h-0 flex flex-col pr-4">
<div className="bg-card lg-tab-content flex-1 min-h-0"> <div className="bg-card lg-tab-content flex-1 min-h-0 flex flex-col overflow-hidden">
<div className="shrink-0 flex items-center justify-between px-2 py-1"> <div className="shrink-0 flex items-center justify-between px-2 py-1">
<div className="flex">
<button <button
type="button" type="button"
onClick={toggleFilter} onClick={toggleFilter}
className={cn( className={cn(
"inline-flex items-center gap-2 font-semibold text-gray-900 content-text-sm", "inline-flex items-center gap-2 font-semibold text-gray-900 content-text-sm cursor-pointer",
"select-none" "select-none"
)} )}
> >
필터 <span className="text-sm leading-none">{isFilterOpen ? "▲" : "▼"}</span> <Filter className="h-4 w-4 fill-[hsl(var(--lg-gray-500))] stroke-[hsl(var(--lg-gray-500))]" />
필터 <span className="text-sm leading-none mb-1">{isFilterOpen ? "▲" : "▼"}</span>
</button> </button>
{isTotal && (
<>
<Button <Button
variant="excel" variant={isDefaultTotalFilter ? "secondary" : "default"}
className="h-8 px-3 text-sm font-semibold content-text-sm" onClick={setDefaultTotalFilter}
onClick={handleExcelDownload}> className="h-6 rounded-sm px-3 ml-3 text-sm font-semibold content-text-sm"
Excel 다운로드 >
초기화
</Button> </Button>
<div className={"ml-5 content-text-sm"} dangerouslySetInnerHTML={{__html: totalPartDescription}}>
</div>
</>
)}
</div>
<ExcelDownloadButton/>
</div> </div>
{isFilterOpen && ( {isFilterOpen && (
@@ -108,18 +201,42 @@ const MainLayout = ({ children }: MainLayoutProps) => {
{isTotal ? ( {isTotal ? (
<TotalFilter filters={totalFilters} value={totalValue} onChange={setTotalValue} /> <TotalFilter filters={totalFilters} value={totalValue} onChange={setTotalValue} />
) : ( ) : (
<CategoryFilter value={categoryValue} onChange={setCategoryValue} /> <CategoryFilter filterItems={categoryFilterItems} value={categoryValue} onChange={setCategoryValue} />
)} )}
</div> </div>
)} )}
{/* ✅ 실제 콘텐츠만 스크롤 */} <div className="relative flex-1 min-h-0">
<div className="flex-1 min-h-0 overflow-auto"> <div
<div className="p-3">{children}</div> ref={scrollRef}
onScroll={onScrollContent}
className="h-full overflow-auto"
>
<div className="p-3 pb-8">
{children}
</div>
</div>
{showScrollTop && (
<button
type="button"
onClick={scrollToTop}
aria-label="위로 가기"
className={cn(
"absolute -bottom-2 right-4 z-20",
"h-8 w-8 rounded-full",
"bg-gray-900/80 text-white hover:bg-primary",
"flex items-center justify-center"
)}
>
<ArrowUp className="h-5 w-5" />
</button>
)}
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</LayoutFilterProvider>
</div> </div>
); );
} }

View File

@@ -1,4 +1,4 @@
import {SubMenuItem} from "@/config/menu.types"; import {SubMenuItem} from "@/types/menu.types";
import {cn} from "@/lib/utils"; import {cn} from "@/lib/utils";
interface SubMenuProps { interface SubMenuProps {
@@ -29,7 +29,7 @@ const SubMenu = ({
"border border-gray-200", "border border-gray-200",
"-ml-px first:ml-0 rounded-tl-lg rounded-tr-lg cursor-pointer", // 탭이 서로 '붙어' 보이게 "-ml-px first:ml-0 rounded-tl-lg rounded-tr-lg cursor-pointer", // 탭이 서로 '붙어' 보이게
active active
? "bg-primary text-primary-foreground z-40" ? "bg-primary text-primary-foreground z-10"
: "bg-white-hover text-secondary" : "bg-white-hover text-secondary"
)} )}
style={active ? { style={active ? {

View File

@@ -1,4 +1,4 @@
import {TotalFilterItem} from "@/config/filter.types"; import {TotalFilterItem} from "@/types/filter.types";
import {SelectedMap} from "@/types/common"; import {SelectedMap} from "@/types/common";
import {useMemo} from "react"; import {useMemo} from "react";
import {cn} from "@/lib/utils"; import {cn} from "@/lib/utils";
@@ -20,9 +20,32 @@ const TotalFilter = ({
className className
}: TotalFilterProps) => { }: TotalFilterProps) => {
const handlePick = (variable: string, v: string) => { const getSelectableCount = (variable: string) =>
if (value[variable] === v) return; filters.find((filter) => filter.variable === variable)?.children
onChange({ ...value, [variable]: v }); .filter((child) => child.value !== "0").length ?? 0;
const handlePick = (variable: string, selectedValue: string) => {
if (selectedValue === "0") {
onChange({ ...value, [variable]: ["0"] });
return;
}
const currentValues = value[variable] ?? ["0"];
const normalizedValues = currentValues.filter((item) => item !== "0");
const selectableCount = getSelectableCount(variable);
const isAlreadySelected = normalizedValues.includes(selectedValue);
const nextValues = isAlreadySelected
? normalizedValues.filter((item) => item !== selectedValue)
: [...normalizedValues, selectedValue].sort((a, b) => Number(a) - Number(b));
if (nextValues.length === 0 || nextValues.length === selectableCount) {
onChange({ ...value, [variable]: ["0"] });
return;
}
onChange({ ...value, [variable]: nextValues });
}; };
const arranged = useMemo(() => { const arranged = useMemo(() => {
@@ -74,7 +97,7 @@ const TotalFilter = ({
{/* 우측 옵션 */} {/* 우측 옵션 */}
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-1 px-2 py-2"> <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1 px-2 py-2">
{row.children.map((c) => { {row.children.map((c) => {
const active = current === c.value; const active = current.includes(c.value);
return ( return (
<Button <Button

View File

@@ -0,0 +1,43 @@
"use client";
import {bannerType} from "@/components/lge-dashboard/types";
import {Filter} from "lucide-react";
type BannerButtonsProps = {
banners: bannerType[];
selectedBanner: bannerType;
onSelectBanner: (banner: bannerType) => void;
};
const BannerButtons = ({
banners,
selectedBanner,
onSelectBanner
}: BannerButtonsProps) => {
return (
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-center font-bold p-1">
<Filter className="h-4 w-4 -ml-2 mr-1 fill-[hsl(var(--lg-gray-500))] stroke-[hsl(var(--lg-gray-500))]" />
구분 필터
</div>
{banners.map((banner) => (
<button
key={banner.variable}
onClick={() => onSelectBanner(banner)}
className={`
px-4 py-1.5 text-sm font-bold rounded-lg transition-colors cursor-pointer
${
selectedBanner === banner
? "bg-primary text-primary-foreground"
: "bg-gray-100 text-gray-700 hover:bg-primary hover:text-primary-foreground"
}
`}
>
{banner.variableName}
</button>
))}
</div>
);
}
export default BannerButtons;

View File

@@ -0,0 +1,98 @@
"use client";
import dynamic from "next/dynamic";
import type { EChartsOption } from "echarts";
import { CHART_HEIGHTS } from "@/components/lge-dashboard/chart/chart.config";
import {useResizeKey} from "@/hooks/useResize";
import { VIEW_DECIMAL_POINT } from "@/const/lg-common.const";
import { useMemo } from "react";
import {roundNumber} from "@/lib/lg-dashboard";
const ReactECharts = dynamic(() => import("echarts-for-react"), { ssr: false });
type BaseEChartProps = {
option: EChartsOption;
height?: number | string;
className?: string; // wrapper용
contentClassName?: string; // 안쪽 wrapper
chartClassName?: string; // ReactECharts용
/** echarts-for-react의 notMerge/lazyUpdate 옵션 필요 시 */
notMerge?: boolean;
lazyUpdate?: boolean;
/** echarts-for-react 이벤트 바인딩(예: legendselectchanged) */
onEvents?: Record<string, (params: unknown) => void>;
};
const normalizeDataValue = (value: unknown): unknown => {
if (typeof value === "number") {
return roundNumber(value);
}
if (Array.isArray(value)) {
return value.map(normalizeDataValue);
}
if (value && typeof value === "object" && "value" in value) {
const item = value as { value: unknown };
return {
...(value as Record<string, unknown>),
value: normalizeDataValue(item.value),
};
}
return value;
};
const normalizeSeries = (series?: EChartsOption["series"]): EChartsOption["series"] => {
if (!series) return series;
const normalizeOne = (s: any) => {
if (!s || !("data" in s) || !Array.isArray(s.data)) {
return s;
}
return {
...s,
data: s.data.map(normalizeDataValue),
};
};
return Array.isArray(series) ? series.map(normalizeOne) : normalizeOne(series);
};
const BaseEChart = ({
option,
height = CHART_HEIGHTS.DEFAULT,
className,
contentClassName,
chartClassName,
notMerge = true,
lazyUpdate = false, //이거 켜져있으면 오류남 Cannot read properties of undefined (reading 'getRawIndex')
onEvents,
}: BaseEChartProps) => {
const resizeKey = useResizeKey(150);
const normalizedOption = useMemo<EChartsOption>(() => {
return {
...option,
series: normalizeSeries(option.series),
};
}, [option]);
return (
<div className={className} style={{ display: "flex", flexDirection: "column", height: height }}>
<div className={contentClassName} style={{ flex: 1, minHeight: 0 }}>
<ReactECharts
key={resizeKey}
option={normalizedOption}
className={chartClassName}
style={{ width: "100%", height: "100%" }}
notMerge={notMerge}
lazyUpdate={lazyUpdate}
onEvents={onEvents}
/>
</div>
</div>
);
}
export default BaseEChart;

View File

@@ -0,0 +1,8 @@
const BottomDescription = ({description}:{description:string}) => {
return (
<div className="content-text-sm mt-2" dangerouslySetInnerHTML={{__html: description}}>
</div>
);
}
export default BottomDescription;

View File

@@ -0,0 +1,10 @@
const SectionTitle = ({title}:{title:string}) => {
return (
<div className="font-semibold flex items-center gap-2">
<span className="w-3 h-3 bg-primary" />
{title}
</div>
);
}
export default SectionTitle;

View File

@@ -0,0 +1,37 @@
"use client";
import type React from "react";
import { cn } from "@/lib/utils";
type Props = {
label?: string;
title?: string;
rightSlot?: React.ReactNode;
className?: string;
children: React.ReactNode;
};
export const Card = ({
label,
title,
rightSlot,
className,
children }: Props) =>
{
return (
<div className={cn("lg-category-card", className)}>
{label && <div className="lg-category-card__label">{label}</div>}
{(title || rightSlot) && (
<div className="flex items-start justify-between gap-3 pt-2">
{title && <div className="content-text-base font-semibold">{title}</div>}
{rightSlot && <div className="shrink-0">{rightSlot}</div>}
</div>
)}
<div className="pt-3">{children}</div>
</div>
);
}
export default Card;

View File

@@ -0,0 +1,289 @@
"use client";
import React, { useMemo, useState } from "react";
import type {
GridComponentOption,
LegendComponentOption,
TooltipComponentOption,
XAXisComponentOption,
YAXisComponentOption,
SeriesOption, EChartsOption,
} from "echarts";
import BaseEChart from "../BaseEChart";
import { buildLgPalette } from "../color";
import { GroupedOverlayBarData, ShowLabel} from "../types";
import {getIsShowLabel, roundedRectIcon} from "@/components/lge-dashboard/chart/utill";
import {AXIS_HIDE_STYLE, AXIS_HIDE_Y_STYLE, CHART_HEIGHTS, LEGEND_ITEM_SIZE} from "@/components/lge-dashboard/chart/chart.config";
import {makeTotalBasePct} from "@/lib/lg-dashboard";
type Props = {
data: GroupedOverlayBarData;
height?: number | string;
questionText: string;
tooltip?: TooltipComponentOption;
grid?: GridComponentOption;
xAxis?: XAXisComponentOption;
yAxis?: YAXisComponentOption;
legend?: LegendComponentOption;
barMaxWidth?: number;
showFocusLabel?: ShowLabel;
// 연도 legend(좌측)
showYearLegend?: boolean;
yearTotalColor?: Record<string, string>;
yearFocusColor?: Record<string, string>;
};
const GroupedOverlayBar = ({
data,
questionText,
height = CHART_HEIGHTS.DEFAULT,
tooltip,
grid,
xAxis,
yAxis,
showYearLegend = true,
legend,
yearTotalColor,
yearFocusColor,
barMaxWidth,
showFocusLabel = "all",
}: Props) => {
const years = data.years;
const totalName = data.totalName ?? "전체";
const focusName = data.focusName ?? "LG";
const yearLabels = useMemo(() => years.map((y) => `${y}년`), [years]);
const [yearSelected, setYearSelected] = useState<Record<string, boolean>>(() =>
Object.fromEntries(yearLabels.map((yl) => [yl, true]))
);
const option = useMemo(() => {
const defaultGrid: EChartsOption["grid"] = {left: 10, right: 10, top: 40, bottom: 10, containLabel: true};
const defaultYAxis: EChartsOption["yAxis"] = { type: "value", ...AXIS_HIDE_Y_STYLE };
const expandedCategories: string[] = [];
data.categories.forEach((cat, catIdx) => {
years.forEach(year => {
expandedCategories.push(`${year}년 ${cat}`);
});
// 카테고리 사이에 빈 공간 추가 (마지막 제외)
if (catIdx < data.categories.length - 1) {
expandedCategories.push(''); // 빈 항목
}
});
const defaultXAxis: EChartsOption["xAxis"] = {
type: "category",
data: expandedCategories,
...AXIS_HIDE_STYLE
};
// 연도별 색: 없으면 기본값(전체=회색, LG=빨강 계열)
const totalTokens = years.map((y, i) => {
const t = yearTotalColor?.[String(y)];
return t ?? (["--chart-1-t", "--chart-2-t", "--chart-3-t"][i] ?? "--lg-gray-300");
});
const focusTokens = years.map((y, i) => {
const t = yearFocusColor?.[String(y)];
return t ?? (["--chart-1", "--chart-2", "--chart-3"][i] ?? "--lg-red-500");
});
const totalColors = buildLgPalette(totalTokens);
const focusColors = buildLgPalette(focusTokens);
// 연도 legend가 실제로 렌더되려면 "name=24년" series가 있어야 함 (bar가 아닌 line으로)
const yearLegendSeries: SeriesOption[] = showYearLegend
? years.map((y, yi) => ({
id: `__year__|${y}`,
name: `${y}년`,
type: "line",
data: [],
showSymbol: false,
silent: true,
tooltip: { show: false },
emphasis: { disabled: true },
lineStyle: { color: focusColors[yi], width: 6 },
itemStyle: { color: focusColors[yi] },
}))
: [];
const series: SeriesOption[] = [];
for (let yi = 0; yi < years.length; yi++) {
const year = years[yi];
const yearLabel = `${year}년`;
const isOn = yearSelected[yearLabel];
const totalRow = data.total?.[yi] ?? [];
const focusRow = data.focus?.[yi] ?? [];
// 각 카테고리별로 데이터 배치
const totalData: (number | null)[] = [];
const focusData: (number | null)[] = [];
data.categories.forEach((cat, ci) => {
years.forEach((y, yIdx) => {
if (yIdx === yi) {
totalData.push(isOn ? (totalRow[ci] ?? null) : null);
focusData.push(isOn ? (focusRow[ci] ?? null) : null);
} else {
totalData.push(null);
focusData.push(null);
}
});
// 카테고리 사이에 null 추가 (마지막 제외)
if (ci < data.categories.length - 1) {
totalData.push(null);
focusData.push(null);
}
});
// (1) 전체(회색)
series.push({
id: `total|${year}`,
name: `${year}년-${totalName}`,
type: "bar",
z: 1,
barMaxWidth: 42,
emphasis: { disabled: true },
itemStyle: { color: totalColors[yi] },
data: totalData,
});
const showLabel = getIsShowLabel(showFocusLabel, yi, years.length);
// (2) LG(빨강) - 같은 위치에 겹침
series.push({
id: `focus|${year}`,
name: `${year}년-${focusName}`,
type: "bar",
z: 2,
barMaxWidth: 42,
barGap: "-100%",
emphasis: { disabled: true },
itemStyle: { color: focusColors[yi] },
label: showLabel
? ({
show: true,
position: "top",
formatter: (p: any) => (p?.value ?? "") as any,
} as any)
: undefined,
data: focusData,
});
}
const YEAR_ITEM_W = LEGEND_ITEM_SIZE.WIDTH;
const YEAR_ITEM_H = LEGEND_ITEM_SIZE.HEIGHT;
const YEAR_RADIUS = LEGEND_ITEM_SIZE.RADIUS;
let yearLegendOpt: LegendComponentOption | undefined = showYearLegend
? ({
top: 0,
left: "center",
orient: "horizontal",
data: yearLabels,
selected: yearSelected,
icon: roundedRectIcon(YEAR_ITEM_W, YEAR_ITEM_H, YEAR_RADIUS),
itemWidth: YEAR_ITEM_W,
itemHeight: YEAR_ITEM_H,
itemGap: 8,
...legend,
} as LegendComponentOption)
: undefined;
if(yearLegendOpt === undefined && legend !== undefined){
yearLegendOpt = legend;
}
return {
tooltip:
tooltip ??
({
trigger: "axis",
axisPointer: { type: "shadow" },
formatter: (params: any) => {
const arr = Array.isArray(params) ? params : [params];
const header = arr?.[0]?.axisValueLabel ?? "";
//header += ` ${questionText}`;
// bar만
const barItems = arr
.filter((p: any) => p?.seriesType === "bar")
.filter((p: any) => p?.value !== null && p?.value !== undefined);
// year -> {total, focus}
const map = new Map<number, { total?: number; focus?: number }>();
for (const p of barItems) {
const sid = String(p.seriesId ?? ""); // total|24, focus|24
const [kind, yStr] = sid.split("|");
const y = Number(yStr);
const e = map.get(y) ?? {};
if (kind === "total") e.total = Number(p.value);
if (kind === "focus") e.focus = Number(p.value);
map.set(y, e);
}
const lines = [...map.keys()]
.sort((a, b) => a - b)
.map((y) => {
const v = map.get(y)!;
const t = v.total ?? 0;
const f = v.focus ?? 0;
const pct = makeTotalBasePct(t, f);
//const pctStr = pct > 0 ? ` (${pct}%)` : "";
//return `${totalName} ${t} 중 ${focusName} ${f}${pctStr}`;
//return `${totalName} ${t} 중 ${focusName} ${f}`;
return `${questionText} ${totalName} ${t} 중 ${focusName} ${f}`;
});
return [header, ...lines].join("<br/>");
},
} as TooltipComponentOption),
legend: yearLegendOpt ?? undefined,
grid: grid ?? defaultGrid,
xAxis: xAxis ?? defaultXAxis,
yAxis: yAxis ?? defaultYAxis,
series: [...yearLegendSeries, ...series],
};
}, [
years,
data.categories,
data.total,
data.focus,
totalName,
focusName,
tooltip,
grid,
xAxis,
yAxis,
showYearLegend,
legend,
yearTotalColor,
yearFocusColor,
barMaxWidth,
showFocusLabel,
yearLabels,
yearSelected,
]);
const onEvents = useMemo(
() => ({
legendselectchanged: (e: any) => {
const name = String(e?.name ?? "");
if (!yearLabels.includes(name)) return;
const selected = e?.selected as Record<string, boolean>;
setYearSelected((prev) => ({
...prev,
[name]: selected?.[name] ?? true,
}));
},
}),
[yearLabels]
);
return <BaseEChart option={option} height={height} onEvents={onEvents} />;
}
export default GroupedOverlayBar;

View File

@@ -0,0 +1,267 @@
"use client";
import React, { useMemo, useState } from "react";
import type {
GridComponentOption,
LegendComponentOption,
TooltipComponentOption,
XAXisComponentOption,
YAXisComponentOption,
SeriesOption, EChartsOption,
} from "echarts";
import BaseEChart from "../BaseEChart";
import { GroupedStackBarData, ShowLabel} from "../types";
import { buildLgPalette } from "@/components/lge-dashboard/color";
import {getIsShowLabel, roundedRectIcon} from "@/components/lge-dashboard/chart/utill";
import {AXIS_HIDE_STYLE, AXIS_HIDE_Y_STYLE, LEGEND_ITEM_SIZE} from "@/components/lge-dashboard/chart/chart.config";
type Props = {
data: GroupedStackBarData;
height?: number | string;
tooltip?: TooltipComponentOption;
grid?: GridComponentOption;
xAxis?: XAXisComponentOption;
yAxis?: YAXisComponentOption;
legend?: LegendComponentOption;
barMaxWidth?: number;
showFocusLabel?: ShowLabel;
showYearLegend?: boolean;
yearBrandPalette?: string[];
};
const GroupedStackBar = ({
data,
height,
tooltip,
grid,
xAxis,
yAxis,
legend,
barMaxWidth,
showFocusLabel = "all",
showYearLegend = true,
yearBrandPalette,
}: Props) => {
const years = data.years;
const brands = data.brands;
const yearLabels = useMemo(() => years.map((y) => `${y}년`), [years]);
const [yearSelected, setYearSelected] = useState<Record<string, boolean>>(() =>
Object.fromEntries(yearLabels.map((yl) => [yl, true]))
);
const option = useMemo(() => {
const defaultGrid: EChartsOption["grid"] = {left: 10, right: 10, top: 60, bottom: 10, containLabel: true};
const defaultXAxis: EChartsOption["xAxis"] = { type: "category", data: data.categories, ...AXIS_HIDE_STYLE };
const defaultYAxis: EChartsOption["yAxis"] = { type: "value", ...AXIS_HIDE_Y_STYLE };
const latestPalette = buildLgPalette(yearBrandPalette);
const yearLegendTokens = years.map((y) => {
const tokens = yearBrandPalette;
const last = tokens?.[tokens.length - 1];
return last ?? "--lg-gray-500";
});
const yearLegendColors = buildLgPalette(yearLegendTokens);
const yearLegendSeries: SeriesOption[] = showYearLegend
? years.map((y, yi) => ({
id: `__year__|${y}`,
name: `${y}년`,
type: "line",
data: [], // 렌더링 없음(legend만)
showSymbol: false,
silent: true,
tooltip: { show: false },
emphasis: { disabled: true },
lineStyle: { color: yearLegendColors[yi], width: 6 },
itemStyle: { color: yearLegendColors[yi] },
}))
: [];
const brandLegendSeries: SeriesOption[] = brands.map((brand, bi) => ({
id: `__legend__|${brand}`,
name: brand,
type: "line",
data: [], // 렌더링 없음(legend만)
showSymbol: false,
silent: true,
tooltip: { show: false },
emphasis: { disabled: true },
lineStyle: { color: latestPalette[bi], width: 6 },
itemStyle: { color: latestPalette[bi] },
}));
// 2) 실제 bar series (연도 스택 3개) × (브랜드 N개)
const realSeries: SeriesOption[] = [];
for (let yi = 0; yi < years.length; yi++) {
const year = years[yi];
const yearLabel = `${year}년`;
const viewYearLabel = `'${Number(year)-2000}`;
const palette = buildLgPalette(yearBrandPalette);
for (let bi = 0; bi < brands.length; bi++) {
const brand = brands[bi];
const row = data.values?.[yi]?.[bi] ?? [];
const isYearOn = yearSelected[yearLabel];
const showLabel = getIsShowLabel(showFocusLabel, yi, years.length);
const isFirstBrand = bi === 0;
realSeries.push({
id: `${year}|${brand}`,
name: brand,
type: "bar",
stack: `Y${year}`,
emphasis: { disabled: true },
barMaxWidth: barMaxWidth ?? 42,
itemStyle: { color: palette?.[bi] },
label: isFirstBrand
? {
show: true,
position: "bottom",
formatter: () => viewYearLabel,
color: "#666",
fontSize: 12,
}
: showLabel
? {
show: true,
position: "top",
formatter: (p: any) => (p?.value ?? "") as any,
}
: undefined,
data: data.categories.map((_, ci) => (isYearOn ? (row[ci] ?? null) : null)),
});
}
}
// 3) legend 2개: (좌)연도, (우)브랜드
let yearLegendOpt: LegendComponentOption | undefined = showYearLegend
? ({
top: 0,
left: "center",
orient: "horizontal",
data: yearLabels, // yearLegendSeries name과 일치
selected: yearSelected,
icon: roundedRectIcon(LEGEND_ITEM_SIZE.WIDTH, LEGEND_ITEM_SIZE.HEIGHT, LEGEND_ITEM_SIZE.RADIUS),
itemWidth: LEGEND_ITEM_SIZE.WIDTH,
itemHeight: LEGEND_ITEM_SIZE.HEIGHT,
itemGap: 8,
...legend,
} as LegendComponentOption)
: undefined;
if(yearLegendOpt === undefined && legend !== undefined){
yearLegendOpt = legend;
}
const brandLegendOpt: LegendComponentOption = ({
top: 0, //25,
right: "center",
orient: "horizontal",
icon: roundedRectIcon(LEGEND_ITEM_SIZE.WIDTH, LEGEND_ITEM_SIZE.HEIGHT, LEGEND_ITEM_SIZE.RADIUS),
itemWidth: LEGEND_ITEM_SIZE.WIDTH,
itemHeight: LEGEND_ITEM_SIZE.HEIGHT,
itemGap: 8,
...legend,
data: [...brands].reverse(),
} as LegendComponentOption);
//const legends = yearLegendOpt ? [yearLegendOpt, brandLegendOpt] : brandLegendOpt;
const legends = brandLegendOpt;
return {
tooltip:
tooltip ??
({
trigger: "axis",
axisPointer: { type: "shadow" },
formatter: (params: any) => {
const arr = Array.isArray(params) ? params : [params];
const header = arr?.[0]?.axisValueLabel ?? "";
const yearMap = new Map<number, Array<{ brand: string; value: number }>>();
// bar series만 + 값 있는 것만
const barItems = arr
.filter((p: any) => p?.seriesType === "bar")
.filter((p: any) => p?.value !== null && p?.value !== undefined);
barItems.forEach((p: any) => {
const sid = String(p.seriesId ?? "");
const [y, brand] = sid.split("|");
const year = Number(y);
if (!yearMap.has(year)) {
yearMap.set(year, []);
}
yearMap.get(year)!.push({ brand, value: p.value });
});
const lines = Array.from(yearMap.entries())
.sort((a, b) => a[0] - b[0])
.map(([year, brands]) => {
const brandTexts = brands
.toReversed() // 브랜드 역순
.map(item => `${item.brand}: ${item.value}`)
.join(", ");
return `${year}년- ${brandTexts}`;
});
return [header, ...lines].join("<br/>");
},
} as TooltipComponentOption),
legend: legends,
grid: grid ?? defaultGrid,
xAxis: xAxis ?? defaultXAxis,
yAxis: yAxis ?? defaultYAxis,
series: [...yearLegendSeries, ...brandLegendSeries, ...realSeries],
};
}, [
years,
brands,
data.categories,
data.values,
tooltip,
grid,
xAxis,
yAxis,
legend,
showFocusLabel,
showYearLegend,
yearBrandPalette,
yearLabels,
yearSelected,
barMaxWidth,
]);
// 연도 legend 토글 이벤트만 가로채서 yearSelected에 반영
const onEvents = useMemo(
() => ({
legendselectchanged: (e: any) => {
const name = String(e?.name ?? "");
if (!yearLabels.includes(name)) return; // 브랜드 토글은 ECharts 기본 동작 사용
const selected = e?.selected as Record<string, boolean>;
setYearSelected((prev) => ({
...prev,
[name]: selected?.[name] ?? true,
}));
},
}),
[yearLabels]
);
return <BaseEChart option={option} height={height} onEvents={onEvents} />;
};
export default GroupedStackBar;

View File

@@ -0,0 +1,91 @@
"use client";
import { useMemo } from "react";
import type { EChartsOption } from "echarts";
import BaseEChart from "../BaseEChart";
import {ChartData, ShowLabel, ValueFormatter} from "../types";
import { buildLgPalette } from "../color";
import {getIsShowLabel} from "@/components/lge-dashboard/chart/utill";
import {
createDefaultTooltip,
createDefaultLegend,
createDefaultGrid,
createCategoryAxis,
createValueAxis,
} from "@/lib/chart-options";
import { BAR_WIDTHS } from "@/components/lge-dashboard/chart/chart.config";
type Props = {
data: ChartData;
height?: number | string;
className?: string;
paletteVarNames?: string[];
valueFormatter?: ValueFormatter;
tooltip?: EChartsOption["tooltip"];
legend?: EChartsOption["legend"];
grid?: EChartsOption["grid"];
xAxis?: EChartsOption["xAxis"];
yAxis?: EChartsOption["yAxis"];
barMaxWidth?: number;
showFocusLabel?:ShowLabel;
labelOptions?: {
position?: "right" | "insideRight";
color?: string;
distance?: number;
};
};
const HorizontalBar = ({
data,
height,
className,
paletteVarNames,
valueFormatter,
tooltip,
legend,
grid,
xAxis,
yAxis,
barMaxWidth,
showFocusLabel = "all",
labelOptions,
}: Props) => {
const palette = useMemo(() => buildLgPalette(paletteVarNames), [paletteVarNames]);
const option: EChartsOption = useMemo(() => {
const fmt = valueFormatter ?? ((v: number) => String(v));
return {
color: palette,
tooltip: tooltip ?? createDefaultTooltip(fmt),
legend: legend ?? createDefaultLegend(),
grid: grid ?? createDefaultGrid(),
xAxis: xAxis ?? createValueAxis(),
yAxis: yAxis ?? createCategoryAxis(data.categories),
series: data.series.map((s, index) => {
const showLabel = getIsShowLabel(showFocusLabel, index, data.series.length);
return {
name: s.name,
type: "bar",
data: s.data,
emphasis: { disabled: true },
barMaxWidth: barMaxWidth ?? BAR_WIDTHS.DEFAULT,
label: showLabel
? {
show: true,
position: labelOptions?.position ?? "right",
color: labelOptions?.color,
distance: labelOptions?.distance,
formatter: (p: any) => (p?.value ?? "") as any,
}
: undefined,
};
}),
};
}, [data, palette, valueFormatter, tooltip, legend, grid, xAxis, yAxis, barMaxWidth, showFocusLabel, labelOptions]);
return <BaseEChart option={option} height={height} className={className} />;
}
export default HorizontalBar;

View File

@@ -0,0 +1,116 @@
"use client";
import { useMemo } from "react";
import type { EChartsOption } from "echarts";
import BaseEChart from "../BaseEChart";
import type { ChartData, ValueFormatter } from "../types";
import {buildLgPalette, buildLgStackPalette} from "../color";
import {
createDefaultTooltip,
createDefaultLegend,
createDefaultGrid,
createCategoryAxis,
createValueAxis,
createBarSeries,
createReverseTooltip,
createReverseLegend, reverseSeries,
} from "@/lib/chart-options";
type Props = {
data: ChartData;
height?: number | string;
className?: string;
paletteVarNames?: string[];
valueFormatter?: ValueFormatter;
orientation?: "vertical" | "horizontal";
defaultStackKey?: string;
tooltip?: EChartsOption["tooltip"];
legend?: EChartsOption["legend"];
grid?: EChartsOption["grid"];
xAxis?: EChartsOption["xAxis"];
yAxis?: EChartsOption["yAxis"];
barMaxWidth?: number;
isReverse?: boolean;
};
const StackBar = ({
data,
height,
className,
paletteVarNames,
valueFormatter,
orientation = "vertical",
defaultStackKey = "total",
tooltip,
legend,
grid,
xAxis,
yAxis,
barMaxWidth,
isReverse = false,
}: Props) => {
const renderData = useMemo(
() => (isReverse ? reverseSeries(data) : data),
[data, isReverse]
);
const palette = useMemo(() => {
const temp = buildLgStackPalette(paletteVarNames);
const n = data.series.length; // 원본 기준
const base = temp.slice(0, n);
return isReverse ? [...base].reverse() : base;
}, [paletteVarNames, data.series.length, isReverse]);
const option: EChartsOption = useMemo(() => {
const fmt = valueFormatter ?? ((v: number) => String(v));
const isV = orientation === "vertical";
const seriseSum: number[] = new Array(renderData.categories.length).fill(0);
renderData.categories.forEach((c, i) => {
renderData.series.forEach((s) => {
seriseSum[i] += Number(s.data[i]);
})
});
const seriesSumMax = Math.max(...seriseSum);
const valueAxis: { min: number; max?: number } = { min: 0 };
if (seriesSumMax > 100) {
valueAxis.max = Math.ceil(seriesSumMax / 5) * 5;
}
return {
color: palette,
tooltip: tooltip ?? (isReverse ? createReverseTooltip(data, fmt) : createDefaultTooltip(fmt)),
legend: legend ?? (isReverse ? createReverseLegend(data) : createDefaultLegend()),
grid: grid ?? createDefaultGrid(),
xAxis: xAxis ?? (isV ? createCategoryAxis(renderData.categories) : createValueAxis(false, valueAxis)),
yAxis: yAxis ?? (isV ? createValueAxis(false, valueAxis) : createCategoryAxis(renderData.categories)),
series: renderData.series.map((s) =>
createBarSeries(s.name, s.data, {
stack: s.stack ?? defaultStackKey,
barMaxWidth,
})
),
};
}, [
data,
renderData,
palette,
valueFormatter,
orientation,
defaultStackKey,
tooltip,
legend,
grid,
xAxis,
yAxis,
barMaxWidth,
isReverse,
]);
return <BaseEChart option={option} height={height} className={className} />;
};
export default StackBar;

View File

@@ -0,0 +1,84 @@
"use client";
import { useMemo } from "react";
import type { EChartsOption } from "echarts";
import BaseEChart from "../BaseEChart";
import {ChartData, ShowLabel, ValueFormatter} from "../types";
import { buildLgPalette } from "../color";
import {getIsShowLabel} from "@/components/lge-dashboard/chart/utill";
import {
createDefaultTooltip,
createDefaultLegend,
createDefaultGrid,
createCategoryAxis,
createValueAxis,
} from "@/lib/chart-options";
import { BAR_WIDTHS } from "@/components/lge-dashboard/chart/chart.config";
type Props = {
data: ChartData;
height?: number | string;
className?: string;
paletteVarNames?: string[];
valueFormatter?: ValueFormatter;
tooltip?: EChartsOption["tooltip"];
legend?: EChartsOption["legend"];
grid?: EChartsOption["grid"];
xAxis?: EChartsOption["xAxis"];
yAxis?: EChartsOption["yAxis"];
barMaxWidth?: number;
showFocusLabel?:ShowLabel;
};
const VerticalBar = ({
data,
height,
className,
paletteVarNames,
valueFormatter,
tooltip,
legend,
grid,
xAxis,
yAxis,
barMaxWidth,
showFocusLabel = "all",
}: Props) => {
const palette = useMemo(() => buildLgPalette(paletteVarNames), [paletteVarNames]);
const option: EChartsOption = useMemo(() => {
const fmt = valueFormatter ?? ((v: number) => String(v));
return {
color: palette,
tooltip: tooltip ?? createDefaultTooltip(fmt),
legend: legend ?? createDefaultLegend(),
grid: grid ?? createDefaultGrid(),
xAxis: xAxis ?? createCategoryAxis(data.categories, false, { axisTick: { alignWithLabel: true } }),
yAxis: yAxis ?? createValueAxis(),
series: data.series.map((s, index) => {
const showLabel = getIsShowLabel(showFocusLabel, index, data.series.length);
return {
name: s.name,
type: "bar",
data: s.data,
emphasis: { disabled: true },
barMaxWidth: barMaxWidth ?? BAR_WIDTHS.DEFAULT,
label: showLabel
? {
show: true,
position: "top",
formatter: (p: any) => (p?.value ?? "") as any,
}
: undefined,
}
}),
};
}, [data, palette, valueFormatter, tooltip, legend, grid, xAxis, yAxis, barMaxWidth, showFocusLabel]);
return <BaseEChart option={option} height={height} className={className} />;
}
export default VerticalBar;

View File

@@ -0,0 +1,86 @@
/**
* 차트 기본 높이 설정
*/
export const CHART_HEIGHTS = {
DEFAULT: "100%",
COMPACT: 200,
EXPANDED: 320,
} as const;
/**
* Bar 차트의 Bar 너비 설정
*/
export const BAR_WIDTHS = {
DEFAULT: 42,
NARROW: 30,
WIDE: 60,
} as const;
/**
* 차트 Grid 기본 패딩 설정
*/
export const CHART_GRID_DEFAULTS = {
DEFAULT: {
left: 16,
right: 16,
top: 36,
bottom: 12,
containLabel: true,
},
COMPACT: {
left: 10,
right: 10,
top: 20,
bottom: 8,
containLabel: true,
},
} as const;
/**
* Legend 아이템 크기 설정 (GroupedOverlayBar, GroupedStackBar에서 사용)
*/
export const LEGEND_ITEM_SIZE = {
WIDTH: 25,
HEIGHT: 14,
RADIUS: 4,
} as const;
/**
* 테이블 크기 설정
*/
export const TABLE_DIMENSIONS = {
CELL_HEIGHT: {
DEFAULT: 26,
COMPACT: 20,
EXPANDED: 32,
},
MIN_WIDTH: {
STANDARD: 1600,
COMPACT: 1200,
WIDE: 2000,
},
} as const;
import {YEARS} from "@/const/lg-common.const";
/** X 축 패딩 없앤 GridOption*/
export const GRID_X_NOT_PADDING = { left: 0, right: 0, top: 50, bottom: 10, containLabel: false } as const;
/** T 축 패딩 없앤 GridOption*/
export const GRID_Y_NOT_PADDING = { left: 10, right: 10, top: 0, bottom: 0, containLabel: false } as const;
/** 축 스타일 감춤 */
export const AXIS_HIDE_STYLE = { axisLabel: { show: false }, axisTick: { show: false }, axisLine: { show: false }} as const;
export const AXIS_HIDE_Y_STYLE = { min:0, max:100, axisLabel: { show: false }, axisTick: { show: false }, axisLine: { show: false }} as const;
export const CHART_COLOR_BY_YEAR = Object.fromEntries(
YEARS.map((year, i) => [
year,
`--chart-${YEARS.length-i}-t`,
])
) as Record<(typeof YEARS)[number], string>;
export const CHART_FOCUS_COLOR_BY_YEAR = Object.fromEntries(
YEARS.map((year, i) => [
year,
`--chart-${YEARS.length-i}`,
])
) as Record<(typeof YEARS)[number], string>;

View File

@@ -0,0 +1,21 @@
import {ShowLabel} from "@/components/lge-dashboard";
export const roundedRectIcon = (w: number, h: number, r: number) => {
const rr = Math.max(0, Math.min(r, Math.min(w, h) / 2));
// ECharts legend icon은 'path://' 지원
return `path://M${rr},0 H${w - rr} Q${w},0 ${w},${rr} V${h - rr} Q${w},${h} ${w - rr},${h} H${rr} Q0,${h} 0,${h - rr} V${rr} Q0,0 ${rr},0 Z`;
};
export const getIsShowLabel = (showFocusLabel:ShowLabel, i:number, arrayLength: number ):boolean => {
let isShowLabel = false;
if (showFocusLabel === "all") {
isShowLabel = true;
} else if (showFocusLabel === "last") {
isShowLabel = i === arrayLength - 1;
} else if (showFocusLabel === "first") {
isShowLabel = i === 0;
}
return isShowLabel;
}

View File

@@ -0,0 +1,120 @@
type Hsl = { h: number; s: number; l: number };
const MAX_VAR_DEPTH = 10;
const getCssVarRaw = (varName: string) =>
getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
/** var(--a) / var(--a, fallback) 를 실제 값으로 재귀 해석 */
export const resolveCssVarValue = (varName: string, depth = 0): string | null => {
if (typeof window === "undefined") return null;
if (depth > MAX_VAR_DEPTH) return null;
const raw = getCssVarRaw(varName);
if (!raw) return null;
// "var(--x)" 또는 "var(--x, fallback)" 패턴
const m = raw.match(/^var\(\s*(--[^,\s)]+)\s*(?:,\s*([^)]+))?\s*\)$/);
if (m) {
const inner = m[1];
const fallback = m[2]?.trim() ?? null;
return resolveCssVarValue(inner, depth + 1) ?? fallback;
}
return raw;
};
const parseHue = (token: string): number | null => {
const t = token.trim().toLowerCase();
const num = parseFloat(t);
if (!Number.isFinite(num)) return null;
if (t.endsWith("turn")) return num * 360;
if (t.endsWith("rad")) return (num * 180) / Math.PI;
if (t.endsWith("grad")) return num * 0.9;
// deg 또는 단위 없음
return num;
};
const parsePercent = (token: string): number | null => {
const t = token.trim().toLowerCase();
const v = parseFloat(t.replace("%", ""));
if (!Number.isFinite(v)) return null;
// 혹시 "0.81" 같은 값이 들어오면(드물지만) 0~1 범위는 %로 보정
if (!t.includes("%") && v >= 0 && v <= 1) return v * 100;
return v;
};
const parseHslTriplet = (raw: string): Hsl | null => {
// 예: "341.1 100% 32.4%" / "0 0% 85%"
const m = raw.trim().match(/^(-?\d+(\.\d+)?)\s+(\d+(\.\d+)?)%\s+(\d+(\.\d+)?)%$/);
if (!m) return null;
return { h: Number(m[1]), s: Number(m[3]), l: Number(m[5]) };
};
const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
export const resolveHslVar = (varName: string): Hsl | null => {
if (typeof window === "undefined") return null;
const raw = resolveCssVarValue(varName);
return raw ? parseHslTriplet(raw) : null;
};
export const hslCss = (hsl: Hsl, alpha = 1) =>
`hsl(${hsl.h} ${hsl.s}% ${hsl.l}% / ${alpha})`;
export const buildLgPalette = (varNames?: string[]): string[] => {
// globals.css에 정의된 스케일을 직접 참조(중첩 var(--chart-1) 회피)
const defaults = varNames ?? [
"--chart-1",
"--chart-2",
"--chart-3",
];
return defaults.map((v) => {
const hsl = resolveHslVar(v);
return hsl ? hslCss(hsl, 1) : v;
});
};
export const buildLgStackPalette = (varNames?: string[]): string[] => {
// globals.css에 정의된 스케일을 직접 참조(중첩 var(--chart-1) 회피)
const defaults = varNames ?? [
"--chart-stack-1",
"--chart-stack-2",
"--chart-stack-3",
"--chart-stack-4",
"--chart-stack-5",
"--chart-stack-6",
"--chart-stack-7",
"--chart-stack-8",
"--chart-stack-9",
"--chart-stack-10",
"--chart-stack-11",
"--chart-stack-12",
"--chart-stack-13",
];
return defaults.map((v) => {
const hsl = resolveHslVar(v);
return hsl ? hslCss(hsl, 1) : v;
});
};
/** Row 기준 heatmap 배경색: 같은 row 안에서 min~max 상대비율로 칠함 */
export const rowHeatColor = (
value: number,
rowMin: number,
rowMax: number,
low: Hsl,
high: Hsl,
alpha = 0.18
) => {
const t = rowMax === rowMin ? 0.5 : (value - rowMin) / (rowMax - rowMin);
const h: Hsl = {
h: lerp(low.h, high.h, t),
s: lerp(low.s, high.s, t),
l: lerp(low.l, high.l, t),
};
return hslCss(h, alpha);
};

View File

@@ -0,0 +1,266 @@
import { ChartData, DataColumn, DataTable, HorizontalBar, LeftChartTable, MergedTableCell, SignStyle } from "@/components/lge-dashboard";
import { BannerKey, BannerRow } from "@/types/lg.types";
import { buildBannerGroupColumns, formatRowLabel, isGapRow, wrapSampleRow } from "@/lib/lg-dashboard";
import { useEffect, useMemo } from "react";
import { BANNER_GROUP, flattenBannerGroupKeys } from "@/const/lg-banner.const";
import { BANNER_KEY_MAP } from "@/const/lg-schema.const";
import { SITE_TITLE } from "@/const/lg-common.const";
import { GRID_Y_NOT_PADDING } from "@/components/lge-dashboard/chart/chart.config";
import { parseNumber } from "@/lib/utils";
import { buildHeader_DataColumn, exportDashboardExcel, Section } from "@/lib/lg-export-excel";
import { useLayoutFilter } from "@/components/layout/LayoutFilterContext";
import { CategoryFilterValue } from "@/components/layout/CategoryFilter";
import { CategoryTargetData } from "@/types/filter.types";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
type SectionSpec = {
title: string;
groupKeys: Array<keyof typeof BANNER_GROUP>;
};
/** 3개 섹션(테이블)도 여기서만 선언 */
const SECTIONS: SectionSpec[] = [
{ title: "가구 형태", groupKeys: ["lifeStage", "household", "age"] },
{ title: "거주 형태", groupKeys: ["occupancy", "housing", "houseSize"] },
{ title: "거주 지역 및 소득 수준", groupKeys: ["region", "income"] },
];
const SEP_R = "lg-table__sep-r";
const getSectionBannerKeys = (spec: SectionSpec): BannerKey[] =>
spec.groupKeys.flatMap((gk) => flattenBannerGroupKeys(BANNER_GROUP[gk].children));
const buildColumns = (spec: SectionSpec, selectedYear: string, isProfileAll:boolean): DataColumn<BannerRow>[] => {
const columns: DataColumn<BannerRow>[] = [
...(isProfileAll
? [
{
key: "year" as const,
header: "",
rowHead: true,
headerClassName: "lg-table__no-border-r",
width: 60,
},
]
: []),
{
key: "rowLabel",
header: selectedYear ? `${selectedYear}년` : "",
headerClassName: "lg-table__no-border-l",
rowHead: true,
width: 120,
},
{
key: "total",
header: "전체",
numeric: true,
headerClassName: SEP_R,
cellClassName: SEP_R,
width: 80,
},
];
spec.groupKeys.forEach((groupKey) => {
const g = BANNER_GROUP[groupKey];
columns.push({
id: `banner-group-${groupKey}`,
header: g.label,
children: buildBannerGroupColumns<BannerRow>(g, BANNER_KEY_MAP, {
numeric: true,
width: 90,
resolveLeafMeta: (_key, idx, total) => {
const isLast = idx === total - 1;
return {
headerClassName: isLast ? SEP_R : undefined,
cellClassName: isLast ? SEP_R : undefined,
};
},
}),
});
});
return columns;
};
const buildYearMergedCells = (rows: BannerRow[]): MergedTableCell<BannerRow>[] => {
const mergedCells: MergedTableCell<BannerRow>[] = [];
let startRowIndex = 0;
while (startRowIndex < rows.length) {
const year = rows[startRowIndex].year;
let endRowIndex = startRowIndex + 1;
while (endRowIndex < rows.length && rows[endRowIndex].year === year) {
endRowIndex += 1;
}
mergedCells.push({
key: "year",
content: formatRowLabel(year),
startRowIndex,
rowSpan: endRowIndex - startRowIndex,
className: "font-bold text-center",
});
startRowIndex = endRowIndex;
}
return mergedCells;
};
type BannerSummaryProps = {
data: BannerRow[];
useChart: boolean;
useYear: boolean;
isProfileAll?: boolean;
getCellClassName?: (row: BannerRow, column: DataColumn<BannerRow>, rowIndex: number) => string | undefined;
};
const BannerSummary = ({
data,
useChart,
useYear,
isProfileAll = false,
getCellClassName
}: BannerSummaryProps) => {
const { filterValue, registerExcelExporter } = useLayoutFilter();
const debouncedFilterValue = useDebouncedValue<CategoryFilterValue>(filterValue as CategoryFilterValue);
const buildChartData = (rows: BannerRow[]): ChartData => {
const categories = rows
.filter((r) => !r.rowLabel.includes("사례수"))
.map((r) => formatRowLabel(r.rowLabel))
.reverse();
const series = [
{
name: "전체",
data: rows
.filter((r) => !r.rowLabel.includes("사례수"))
.map((r) => parseNumber(r.total) ?? null)
.reverse(),
},
];
return { categories, series };
};
const signStyleGap: SignStyle<BannerRow> = {
rowSelector: (row) => isGapRow(row.rowLabel),
display: "arrow",
arrowWithNumber: true,
paint: "text",
zeroText: "-",
};
const sectionRows = useMemo(() => {
return SECTIONS.map((spec) => {
const specTitle = spec.title;
const bannerKeys = getSectionBannerKeys(spec);
const columns = buildColumns(spec, useYear ? debouncedFilterValue.year : "", isProfileAll);
// rows가 spec마다 다르면 여기서 가져오도록 구성
const rows = wrapSampleRow(useYear ? data.filter((d) => d.year === debouncedFilterValue.year) : data).map((row) => {
row.rowLabel = formatRowLabel(row.rowLabel);
return row;
});
const chartData = buildChartData(rows);
const mergedCells = isProfileAll ? buildYearMergedCells(rows) : undefined;
return {
spec,
specTitle,
bannerKeys,
columns,
rows,
chartData,
mergedCells,
};
});
}, [data, useYear, debouncedFilterValue.year, isProfileAll]);
const getTargetString = (target: CategoryTargetData): string => {
switch (target) {
case CategoryTargetData.PROFILE_ALL:
return "Profile (전체)";
case CategoryTargetData.PROFILE:
return "Profile";
default:
return "보급률 변화"
}
}
useEffect(() => {
registerExcelExporter(async () => {
const product = debouncedFilterValue.product;
const type = debouncedFilterValue.type.label;
const target = getTargetString(debouncedFilterValue.target.value);
const sheetName = `${product}_${type}_${target}`;
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] = sectionRows.map((sectionRow) => ({
title: sectionRow.specTitle,
header: buildHeader_DataColumn(sectionRow.columns),
rows: sectionRow.rows as AnyRow[],
rowGap: 1,
}));
await exportDashboardExcel({
fileName: `${SITE_TITLE}(${sheetName}).xlsx`,
sheetName,
sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter, debouncedFilterValue, sectionRows]);
return (
<div className="flex flex-col gap-6">
{sectionRows.map((sectionRow) => {
return (
<div key={`div_${sectionRow.specTitle}`}>
{useChart ? (
<LeftChartTable<BannerRow>
key={sectionRow.specTitle}
title={sectionRow.specTitle}
columns={sectionRow.columns}
rows={sectionRow.rows}
getCellClassName={getCellClassName}
signStyle={signStyleGap}
chart={
<HorizontalBar
data={sectionRow.chartData}
height="100%"
showFocusLabel="all"
labelOptions={{ position: "insideRight", color: "#fff", distance: 4 }}
legend={{ show: false }}
grid={GRID_Y_NOT_PADDING}
xAxis={{ type: "value", show: false }}
yAxis={{ type: "category", data: sectionRow.chartData.categories, show: false }}
/>
}
chartCell={{ key: "total", startRowIndex: 1 }}
minWidthPx={1200}
starUnder30Sample={true}
/>
) : (
<DataTable<BannerRow>
key={sectionRow.specTitle}
title={sectionRow.specTitle}
columns={sectionRow.columns}
rows={sectionRow.rows}
signStyle={signStyleGap}
unitText={""}
starUnder30Sample={true}
mergedCells={sectionRow.mergedCells}
/>
)}
</div>
);
})}
</div>
);
};
export default BannerSummary;

View File

@@ -0,0 +1,166 @@
import {
bannerType,
BottomDescription, type DataColumn, DataTable, HorizontalBar, SectionTitle, SignStyle, StackBar
} from "@/components/lge-dashboard";
import BannerButtons from "@/components/lge-dashboard/BannerButtons";
import { categoryByDataBanner } from "@/const/filter.const";
import React, { useMemo, useState } from "react";
import { BannerGroupKey, CategoryChartMode, BannerRow, LegendOption } from "@/types/lg.types";
import { buildBannerGroupColumns, buildRowLabelSeriesChartData, buildYearSeriesChartData, formatRowLabel, isBannerGroupKey, isGapRow, wrapSampleRow } from "@/lib/lg-dashboard";
import { BANNER_GROUP } from "@/const/lg-banner.const";
import { BANNER_KEY_MAP } from "@/const/lg-schema.const";
import { createDefaultGrid, reverseCategories } from "@/lib/chart-options";
type CategoryByDataProps = {
selectedYear: string;
title?: string;
surveyTitle?: string;
chartMode: CategoryChartMode;
chartLegend?: LegendOption;
chartTopMargin?: number;
allTableData: BannerRow[];
fillGreaterThan5?: boolean;
chartHeight?: number | string;
chartWidth?: number;
};
const banners: bannerType[] = categoryByDataBanner.map((filter) => {
return { variable: filter.variable, variableName: filter.variableName };
});
const signStyleGap: SignStyle<BannerRow> = {
rowSelector: (row) => isGapRow(row.rowLabel),
display: "arrow",
arrowWithNumber: true,
paint: "text",
zeroText: "-",
};
const CategoryByData = ({
selectedYear,
title,
surveyTitle,
chartMode,
chartLegend,
chartTopMargin,
allTableData,
fillGreaterThan5,
chartHeight,
chartWidth,
}: CategoryByDataProps) => {
const [selectedBanner, setSelectedBanner] = useState<bannerType>(banners[0]);
const buildColumns = (groupKey: BannerGroupKey, year: string): DataColumn<BannerRow>[] => {
const g = BANNER_GROUP[groupKey];
return [
{
key: "rowLabel",
header: `${year}년`,
rowHead: true,
cellClassName: "lg-table__rowhead",
width: 120,
},
{
key: "total",
header: "전체",
numeric: true,
cellClassName: "lg-table__rowhead",
width: 120,
},
{
id: `category-banner-${groupKey}`,
header: g.label,
children: buildBannerGroupColumns<BannerRow>(g, BANNER_KEY_MAP, {
numeric: true,
width: 90,
}),
},
];
};
const chartData = useMemo(() => {
const excludeRowLabels = ["사례수", "gap"];
const chartTargetData = allTableData.filter((row) => row.year === selectedYear || Number(row.year) === Number(selectedYear) - 1);
if (chartMode === "horizontal") {
return reverseCategories(buildYearSeriesChartData(chartTargetData, { excludeRowLabels }));
}
return buildRowLabelSeriesChartData(chartTargetData, { excludeRowLabels });
}, [allTableData, selectedYear, chartMode]);
const tableColumns = useMemo(() => {
const v = selectedBanner.variable;
return isBannerGroupKey(v) ? buildColumns(v, selectedYear) : [];
}, [selectedBanner.variable, selectedYear]);
const tableData = useMemo(
() =>
wrapSampleRow(allTableData)
.filter((row) => row.year === selectedYear)
.map((row) => {
row.rowLabel = formatRowLabel(row.rowLabel);
return row;
}),
[allTableData, selectedYear]
);
return (
<div>
<div className="mb-2 flex items-center pr-6">
{title ? <SectionTitle title={title} /> : <div />}
</div>
<div className="flex gap-6 p-3">
<div className="flex-shrink-0" style={{ width: `${chartWidth ?? 400}px` }}>
{(() => {
switch (chartMode) {
case "horizontal":
return (
<HorizontalBar
data={chartData}
legend={chartLegend}
grid={chartTopMargin ? createDefaultGrid("default", { top: chartTopMargin }) : undefined}
height={chartHeight}
showFocusLabel="none"
paletteVarNames={chartData.series.length === 1 ? ["--chart-1"] : ["--chart-2", "--chart-1"]}
/>
);
case "stack":
case "reverseStack":
return (
<StackBar
data={chartData}
legend={chartLegend}
height={chartHeight}
grid={createDefaultGrid("default", { top: chartTopMargin ? chartTopMargin : 52 })}
isReverse={chartMode === "reverseStack"}
/>
);
default:
return null;
}
})()}
</div>
<div className="flex items-center">
<BannerButtons banners={banners} selectedBanner={selectedBanner} onSelectBanner={setSelectedBanner} />
</div>
<div className="flex-1">
<DataTable
columns={tableColumns}
rows={tableData}
signStyle={signStyleGap}
fillGreaterThan5={fillGreaterThan5}
fillGapRow={true}
starUnder30Sample={true}
/>
<BottomDescription description={"전체 대비 5%p 이상 품목에 대해 음영 표시"} />
</div>
</div>
<div className="ml-5 mb-5 -mt-3 flex content-text-sm">{surveyTitle}</div>
</div>
);
};
export default CategoryByData;

View File

@@ -0,0 +1,58 @@
"use client";
import React from "react";
import { cn } from "@/lib/utils";
import {GaugeColumn, GaugeTable} from "@/components/lge-dashboard";
import Card from "@/components/lge-dashboard/card/Card";
export type GaugeCardTableProps<T> = {
/** 카드 제목 */
title: string;
/** GaugeTable columns */
columns: GaugeColumn<T>[];
/** GaugeTable rows */
rows: T[];
/** GaugeTable 옵션들 (필요한 것만 노출) */
cellHeight?: number;
fillColor?: string;
trackColor?: string;
className?: string;
cardClassName?: string;
tableClassName?: string;
};
const GaugeCardTable = <T extends Record<string, unknown>>(
props: GaugeCardTableProps<T>
) => {
const {
title,
columns,
rows,
cellHeight = 26,
fillColor,
trackColor,
className,
cardClassName,
tableClassName,
} = props;
return (
<div className={cn("w-full", className)}>
<Card label={title} className={cardClassName}>
<div className={cn("w-full", tableClassName)}>
<GaugeTable
columns={columns}
rows={rows}
cellHeight={cellHeight}
fillColor={fillColor}
trackColor={trackColor}
/>
</div>
</Card>
</div>
);
};
export default GaugeCardTable;

View File

@@ -0,0 +1,76 @@
"use client";
import type React from "react";
import { TABLE_DIMENSIONS } from "@/components/lge-dashboard/chart/chart.config";
import { UNIT_TEXT } from "@/const/lg-common.const";
import type { DataColumn, SignStyle } from "../types";
import BaseDataTable from "../table/BaseDataTable";
type MergedChartCell<T> = {
key: keyof T;
startRowIndex?: number;
rowSpan?: number;
className?: string;
};
type Props<T extends Record<string, unknown>> = {
title?: string;
columns: DataColumn<T>[];
rows: T[];
chart: React.ReactNode;
chartCell: MergedChartCell<T>;
signStyle?: SignStyle<T>;
wrapperClassName?: string;
tableClassName?: string;
minWidthPx?: number;
minWidth?: number;
starUnder30Sample?: boolean;
unitText?: string;
getCellClassName?: (row: T, column: DataColumn<T>, rowIndex: number) => string | undefined;
};
export default function LeftChartTable<T extends Record<string, unknown>>({
title,
columns,
rows,
chart,
chartCell,
signStyle,
wrapperClassName,
tableClassName,
minWidthPx = TABLE_DIMENSIONS.MIN_WIDTH.COMPACT,
minWidth,
starUnder30Sample = true,
unitText = UNIT_TEXT,
getCellClassName,
}: Readonly<Props<T>>) {
return (
<BaseDataTable
columns={columns}
rows={rows}
title={title}
wrapperClassName={wrapperClassName}
tableClassName={tableClassName}
minWidth={minWidth ?? minWidthPx}
signStyle={signStyle}
signStyleFallback={{
positiveTextClassName: "lg-num-pos",
negativeTextClassName: "lg-num-neg",
zeroTextClassName: "",
arrowWithNumber: true,
}}
starUnder30Sample={starUnder30Sample}
unitText={unitText}
getCellClassName={getCellClassName}
mergedCells={[
{
key: chartCell.key,
content: chart,
startRowIndex: chartCell.startRowIndex,
rowSpan: chartCell.rowSpan,
className: chartCell.className,
},
]}
/>
);
}

View File

@@ -0,0 +1,52 @@
import GaugeCardTable from "./GaugeCardTable";
import {LIFE_STAGE_COLUMNS} from "@/const/lg-product.const";
import {UNIT_TEXT} from "@/const/lg-common.const";
import {LifeStageGroup} from "@/types/lg.types";
import SectionTitle from "../SectionTitle";
import React from "react";
type lifeStageDivProps = {
lifeStageRowsByGroup:LifeStageGroup[];
}
const LifeStageDiv = ({lifeStageRowsByGroup}:lifeStageDivProps) => {
return (
<div className="mt-6">
<SectionTitle title={"LG 가전 보급률 기준 라이프스테이지별 기회 영역"} />
<div className="flex justify-end text-muted-foreground mb-5">
<div className="flex justify-end gap-4 content-text-xs">
<div className="flex items-center gap-2">
<span className="inline-block h-4 w-8 border bg-gray-200 border-gray-300"/>
<span>제품 보유율</span>
</div>
<div className="flex items-center gap-2">
<span
className="inline-block h-4 w-8 border border-gray-300"
style={{ backgroundColor: "hsl(var(--lg-pink-300) / 0.4)" }}
/>
<span>시장 기회공간</span>
</div>
<div className="flex items-center gap-2">
{UNIT_TEXT}
</div>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
{lifeStageRowsByGroup.map((g) => (
<GaugeCardTable
key={g.title}
title={g.title}
columns={LIFE_STAGE_COLUMNS}
rows={g.rows}
/>
))}
</div>
</div>
);
}
export default LifeStageDiv;

View File

@@ -0,0 +1,147 @@
"use client";
import React, { useMemo } from "react";
import { cn, parseNumber } from "@/lib/utils";
import type { ChartData, SignStyle, TopChartTableRow } from "../types";
import { CHART_HEIGHTS, TABLE_DIMENSIONS } from "@/components/lge-dashboard/chart/chart.config";
import { UNIT_TEXT } from "@/const/lg-common.const";
import {isCagrRow, isSampleRow} from "@/lib/lg-dashboard";
import BaseTableHeader from "../table/core/BaseTableHeader";
import { formatSignedValue, getSignTextClass, resolveSignStyle, toRoundedNumber } from "../table/core/table-core.helpers";
export type TopChartTableProps = {
title?: string;
categories: string[];
rows: TopChartTableRow[];
chart?:
| React.ReactNode
| ((ctx: {
chartData: ChartData;
}) => React.ReactNode);
chartHeight?: number | string;
minWidthPx?: number;
minWidth?: number;
tableClassName?: string;
wrapperClassName?: string;
signStyle?: SignStyle<TopChartTableRow>;
fillCAGR?: boolean;
unitText?: string;
};
export default function TopChartTable({
title,
rows,
categories,
chart,
chartHeight = CHART_HEIGHTS.DEFAULT,
minWidthPx = TABLE_DIMENSIONS.MIN_WIDTH.STANDARD,
minWidth,
tableClassName,
wrapperClassName,
signStyle,
fillCAGR = false,
unitText = UNIT_TEXT,
}: Readonly<TopChartTableProps>) {
const resolvedSignStyle = resolveSignStyle(signStyle, {
positiveTextClassName: "lg-num-pos",
negativeTextClassName: "lg-num-neg",
zeroTextClassName: "",
arrowWithNumber: true,
});
const chartData: ChartData = useMemo(
() => ({
categories,
series: rows.map((row) => ({
name: row.label,
data: row.values.map((value) => parseNumber(value) ?? null),
})),
}),
[categories, rows]
);
const chartNode = useMemo(() => {
if (!chart) {
return null;
}
return typeof chart === "function" ? chart({ chartData }) : chart;
}, [chart, chartData]);
return (
<div className={cn("w-full", wrapperClassName)}>
<BaseTableHeader title={title} unitText={unitText} />
<div className="overflow-x-auto">
<table className={cn("lg-table", tableClassName)} style={{ minWidth: `${minWidth ?? minWidthPx}px` }}>
<thead>
<tr>
<th colSpan={2} className="w-44" style={{ whiteSpace: "nowrap" }} />
<td colSpan={categories.length} style={{ padding: 0, height: chartNode ? chartHeight : 0 }}>
{chartNode ? <div style={{ width: "100%", height: "100%" }}>{chartNode}</div> : null}
</td>
</tr>
<tr className="lg-table__subhead">
<th className="lg-table__sep-r"></th>
<th className="content-text-xs">사례수</th>
{categories.map((category) => (
<th key={category} className="content-text-xs">
{category}
</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row, rowIndex) => {
const signRow = !!signStyle?.rowSelector?.(row, rowIndex);
const sampleRow = isSampleRow(row.label ?? "");
const cagrRow = isCagrRow(row.label ?? "");
const rowTotal = parseNumber(row.total);
return (
<tr key={`${row.label}-${rowIndex}`}>
<th scope="row" className="lg-table__rowhead lg-table__sep-r content-text-sm">
{row.label}
</th>
<td>
{row.sample}
</td>
{categories.map((_, categoryIndex) => {
const rawValue = row.values?.[categoryIndex];
if(sampleRow){
return <td key={categoryIndex}>{rawValue}</td>;
}
const roundedValue = toRoundedNumber(rawValue, cagrRow? 1 : 0);
if (!signRow) {
if (roundedValue === null) {
return <td key={categoryIndex}>-</td>;
}
const shouldFillCell = fillCAGR && cagrRow && rowTotal !== null && roundedValue >= rowTotal + 5;
return <td key={categoryIndex} className={cn(shouldFillCell ? "bg-red-200" : "")}>{roundedValue.toLocaleString()}</td>;
}
if (roundedValue === null) {
return <td key={categoryIndex}>-</td>;
}
return (
<td key={categoryIndex} className={getSignTextClass(roundedValue, resolvedSignStyle)}>
{formatSignedValue(roundedValue, resolvedSignStyle)}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
</div>
</div>
);
}

View File

@@ -0,0 +1,24 @@
export * from "./types";
export { default as BaseEChart } from "./BaseEChart";
export { default as VerticalBar } from "./chart/VerticalBar";
export { default as HorizontalBar } from "./chart/HorizontalBar";
export { default as StackBar } from "./chart/StackBar";
export { default as GroupedStackBar} from "./chart/GroupedStackBar";
export { default as GroupedOverlayBar} from "./chart/GroupedOverlayBar";
export { default as DataTable } from "./table/DataTable";
export type { DataTableProps } from "./table/DataTable";
export type { MergedTableCell } from "./table/BaseDataTable";
export { default as GaugeTable } from "./table/GaugeTable";
export { default as TopChartTable } from "./combo/TopChartTable";
export { default as LeftChartTable } from "./combo/LeftChartTable";
export { default as GaugeCardTable } from "./combo/GaugeCardTable";
export { default as CategoryByData } from "./combo/CategoryByData"
export { default as CardDefault } from "./card/Card";
export { default as SectionTitle } from "./SectionTitle";
export { default as BottomDescription } from "./BottomDescription";

View File

@@ -0,0 +1,176 @@
"use client";
import type React from "react";
import { cn, parseNumber } from "@/lib/utils";
import {isGapRow, isHasCountRow, isSampleRow} from "@/lib/lg-dashboard";
import type { DataColumn, SignStyle } from "../types";
import BaseTableRenderer from "./core/BaseTableRenderer";
import {
appendCellMarker,
formatSignedValue,
getColumnAlign,
getLeafColumns,
getSignCellBackground,
getSignTextClass,
resolveSignStyle,
shouldApplySignToColumn,
toRoundedNumber,
toTableCellContent,
type ResolvedSignStyle,
} from "./core/table-core.helpers";
import {VIEW_DECIMAL_POINT} from "@/const/lg-common.const";
export type MergedTableCell<T> = {
key: keyof T;
content: React.ReactNode;
startRowIndex?: number;
rowSpan?: number;
className?: string;
};
type Props<T extends Record<string, unknown>> = {
columns: DataColumn<T>[];
rows: T[];
title?: string;
wrapperClassName?: string;
tableClassName?: string;
subheadRowClassName?: string;
minWidth?: number;
signStyle?: SignStyle<T>;
signStyleFallback?: Partial<ResolvedSignStyle>;
fillGreaterThan5?: boolean;
fillGapRow?: boolean;
starUnder30Sample?: boolean;
unitText?: string;
mergedCells?: MergedTableCell<T>[];
getCellClassName?: (row: T, column: DataColumn<T>, rowIndex: number) => string | undefined;
};
export default function BaseDataTable<T extends Record<string, unknown>>({
columns,
rows,
title,
wrapperClassName,
tableClassName,
subheadRowClassName,
minWidth,
signStyle,
signStyleFallback,
fillGreaterThan5 = false,
fillGapRow = false,
starUnder30Sample = false,
unitText,
mergedCells,
getCellClassName,
}: Readonly<Props<T>>) {
const resolvedSignStyle = resolveSignStyle(signStyle, signStyleFallback);
const leafColumns = getLeafColumns(columns);
return (
<BaseTableRenderer
columns={columns}
title={title}
unitText={unitText}
showSampleNotice={starUnder30Sample}
wrapperClassName={wrapperClassName}
tableClassName={tableClassName}
subheadRowClassName={subheadRowClassName}
minWidth={minWidth}
>
{rows.map((row, rowIndex) => {
const rowLabel = (row.rowLabel as string) ?? "";
const sampleRow = isSampleRow(rowLabel);
const hasCountRow = isHasCountRow(rowLabel);
const signRow = !!signStyle?.rowSelector?.(row, rowIndex);
const rowTotal = parseNumber(row.total);
const isFillGapRow = fillGapRow && isGapRow(rowLabel)
const fillGapClass = isFillGapRow ? "bg-gray-100" : "";
return (
<tr key={rowIndex}>
{leafColumns.map((column) => {
const dynamicCellClassName = getCellClassName?.(row, column, rowIndex);
const mergedCell = mergedCells?.find((cell) => {
const startRowIndex = cell.startRowIndex ?? 0;
const rowSpan = cell.rowSpan ?? Math.max(0, rows.length - startRowIndex);
return column.key === cell.key && rowIndex >= startRowIndex && rowIndex < startRowIndex + rowSpan;
});
if (mergedCell) {
const mergedCellStart = mergedCell.startRowIndex ?? 0;
const mergedCellSpan = mergedCell.rowSpan ?? Math.max(0, rows.length - mergedCellStart);
if (rowIndex > mergedCellStart) {
return null;
}
return (
<td
key={String(column.key)}
rowSpan={mergedCellSpan}
className={cn(column.cellClassName, mergedCell.className)}
style={{ padding: 0, verticalAlign: "middle" }}
>
{mergedCell.content}
</td>
);
}
const rawValue = row[column.key];
const align = getColumnAlign(column);
const viewDecimalPoint = hasCountRow ? 2 : VIEW_DECIMAL_POINT;
const defaultContent = column.render ? column.render(row) : toTableCellContent(rawValue, viewDecimalPoint);
const numericValue = "numeric" in column && column.numeric ? parseNumber(rawValue ?? defaultContent) ?? 0 : 0;
const applySign = signRow && shouldApplySignToColumn(column, signStyle);
if (column.rowHead) {
return (
<th
key={String(column.key)}
scope="row"
className={cn("lg-table__rowhead", column.cellClassName, dynamicCellClassName, fillGapClass)}
style={{ textAlign: align }}
>
{defaultContent}
</th>
);
}
if (applySign) {
const roundedValue = toRoundedNumber(rawValue);
const displayText = roundedValue === null ? "-" : formatSignedValue(roundedValue, resolvedSignStyle);
const cellStyle: React.CSSProperties =
resolvedSignStyle.paint === "cell"
? { textAlign: align, background: getSignCellBackground(roundedValue ?? 0, resolvedSignStyle) }
: { textAlign: align };
return (
<td key={String(column.key)} className={cn(column.cellClassName, dynamicCellClassName, fillGapClass)} style={cellStyle}>
<span className={cn(roundedValue === null ? "text-gray-500" : getSignTextClass(roundedValue, resolvedSignStyle))}>
{displayText}
</span>
</td>
);
}
const shouldFillCell = fillGreaterThan5 && rowTotal !== null && numericValue >= rowTotal + 5;
const shouldMarkSample = starUnder30Sample && sampleRow && numericValue < 30;
const displayContent = shouldMarkSample ? appendCellMarker(defaultContent, "*") : defaultContent;
return (
<td
key={String(column.key)}
className={cn(column.cellClassName, dynamicCellClassName, fillGapClass, shouldFillCell ? "bg-red-200" : "")}
style={{ textAlign: align }}
>
{displayContent}
</td>
);
})}
</tr>
);
})}
</BaseTableRenderer>
);
}

View File

@@ -0,0 +1,56 @@
"use client";
import type { DataColumn, SignStyle } from "../types";
import { UNIT_TEXT } from "@/const/lg-common.const";
import BaseDataTable, { type MergedTableCell } from "./BaseDataTable";
export type DataTableProps<T extends Record<string, unknown>> = {
columns: DataColumn<T>[];
rows: T[];
title?: string;
className?: string;
tableClassName?: string;
wrapperClassName?: string;
subheadRowClassName?: string;
signStyle?: SignStyle<T>;
fillGreaterThan5?: boolean;
fillGapRow?: boolean;
starUnder30Sample?: boolean;
unitText?: string;
mergedCells?: MergedTableCell<T>[];
};
const DataTable = <T extends Record<string, unknown>>({
columns,
rows,
title,
className,
tableClassName,
wrapperClassName,
subheadRowClassName,
signStyle,
fillGreaterThan5 = false,
fillGapRow = false,
starUnder30Sample = false,
unitText = UNIT_TEXT,
mergedCells,
}: DataTableProps<T>) => {
return (
<BaseDataTable
columns={columns}
rows={rows}
title={title}
tableClassName={tableClassName ?? className}
wrapperClassName={wrapperClassName}
subheadRowClassName={subheadRowClassName}
signStyle={signStyle}
fillGreaterThan5={fillGreaterThan5}
fillGapRow={fillGapRow}
starUnder30Sample={starUnder30Sample}
unitText={unitText}
mergedCells={mergedCells}
/>
);
};
export default DataTable;

View File

@@ -0,0 +1,114 @@
"use client";
import { cn, parseNumber } from "@/lib/utils";
import { roundNumber } from "@/lib/lg-dashboard";
import type { GaugeColumn } from "../types";
import BaseTableRenderer from "./core/BaseTableRenderer";
import { getColumnAlign, getLeafColumns, toTableCellContent } from "./core/table-core.helpers";
type Props<T extends Record<string, unknown>> = {
columns: GaugeColumn<T>[];
rows: T[];
className?: string;
tableClassName?: string;
wrapperClassName?: string;
scale?: number;
fillColor?: string;
trackColor?: string;
cellHeight?: number;
valueFormatter?: (value: number) => string;
};
const GaugeTable = <T extends Record<string, unknown>>({
columns,
rows,
className,
tableClassName,
wrapperClassName,
scale = 1,
fillColor = "hsl(var(--lg-gray-200) / 0.85)",
trackColor = "hsl(var(--lg-pink-300) / 0.2)",
cellHeight = 26,
valueFormatter,
}: Props<T>) => {
const formatValue = valueFormatter ?? ((value: number) => String(roundNumber(value)));
const clampRatio = (value: number) => Math.max(0, Math.min(1, value));
const leafColumns = getLeafColumns(columns);
return (
<BaseTableRenderer
columns={columns}
wrapperClassName={wrapperClassName}
tableClassName={tableClassName ?? className}
minWidth="100%"
colgroup={
<colgroup>
{leafColumns.map((column, index) => (
<col
key={`${String(column.key)}-${index}`}
style={{
width: column.width ?? (column.rowHead ? 50 : 40),
}}
/>
))}
</colgroup>
}
>
{rows.map((row, rowIndex) => (
<tr key={rowIndex}>
{leafColumns.map((column) => {
const align = getColumnAlign(column);
if (column.rowHead) {
const content = column.render ? column.render(row) : toTableCellContent(row[column.key]);
return (
<th
key={String(column.key)}
scope="row"
className={cn("lg-table__rowhead", column.cellClassName)}
style={{ textAlign: align }}
>
{content}
</th>
);
}
const rawValue = row[column.key];
const numericValue = parseNumber(rawValue);
const max = "max" in column ? column.max ?? 100 : 100;
const ratio = numericValue === null ? 0 : clampRatio((numericValue * scale) / max);
const percentage = ratio * 100;
const background =
numericValue === null ? undefined : `linear-gradient(to right, ${fillColor} ${percentage}%, ${trackColor} 0%)`;
if (("cellType" in column ? column.cellType : "gauge") === "number") {
return (
<td key={String(column.key)} className={cn("px-2 content-text-sm", column.cellClassName)} style={{ textAlign: align }}>
{numericValue === null ? "-" : formatValue(numericValue)}
</td>
);
}
return (
<td
key={String(column.key)}
className={cn("px-2 content-text-sm", column.cellClassName)}
style={{
textAlign: "left",
height: cellHeight,
whiteSpace: "nowrap",
background,
backgroundClip: "padding-box",
}}
>
{numericValue === null ? "-" : formatValue(numericValue)}
</td>
);
})}
</tr>
))}
</BaseTableRenderer>
);
};
export default GaugeTable;

View File

@@ -0,0 +1,31 @@
import SectionTitle from "../../SectionTitle";
import { SAMPLE_SIZE_NOTICE } from "@/const/lg-common.const";
type Props = {
title?: string;
unitText?: string;
showSampleNotice?: boolean;
};
export default function BaseTableHeader({ title, unitText, showSampleNotice = false }: Props) {
if (!title && !unitText && !showSampleNotice) {
return null;
}
return (
<div className="mb-2 flex items-center justify-between">
{title ? <SectionTitle title={title} /> : <div />}
{unitText || showSampleNotice ? (
<div className="ml-auto text-right text-gray-500 content-text-xs font-semibold">
{unitText}
{showSampleNotice ? (
<>
<br />
{SAMPLE_SIZE_NOTICE}
</>
) : null}
</div>
) : null}
</div>
);
}

View File

@@ -0,0 +1,71 @@
"use client";
import type React from "react";
import { cn } from "@/lib/utils";
import type { DataColumn, GaugeColumn } from "../../types";
import BaseTableHeader from "./BaseTableHeader";
import { buildHeaderRows } from "./table-core.helpers";
type BaseColumn<T> = DataColumn<T> | GaugeColumn<T>;
type Props<T> = {
columns: BaseColumn<T>[];
title?: string;
unitText?: string;
showSampleNotice?: boolean;
wrapperClassName?: string;
tableClassName?: string;
subheadRowClassName?: string;
minWidth?: number | string;
colgroup?: React.ReactNode;
renderHeaderPrefix?: React.ReactNode;
children: React.ReactNode;
};
export default function BaseTableRenderer<T>({
columns,
title,
unitText,
showSampleNotice = false,
wrapperClassName,
tableClassName,
subheadRowClassName,
minWidth,
colgroup,
renderHeaderPrefix,
children,
}: Readonly<Props<T>>) {
const headerRows = buildHeaderRows(columns);
const lastHeaderRowIndex = headerRows.length - 1;
return (
<div className={cn("w-full", wrapperClassName)}>
<BaseTableHeader title={title} unitText={unitText} showSampleNotice={showSampleNotice} />
<div className="overflow-x-auto">
<table
className={cn("lg-table", tableClassName)}
style={minWidth === undefined ? undefined : { minWidth: typeof minWidth === "number" ? `${minWidth}px` : minWidth }}
>
{colgroup}
<thead>
{renderHeaderPrefix}
{headerRows.map((row, rowIndex) => (
<tr
key={`header-row-${rowIndex}`}
className={cn(rowIndex === lastHeaderRowIndex ? "lg-table__subhead" : "lg-table__group", rowIndex === lastHeaderRowIndex ? subheadRowClassName : undefined)}
>
{row.map((cell) => (
<th key={cell.id} colSpan={cell.colSpan} rowSpan={cell.rowSpan} className={cell.className}>
{cell.label}
</th>
))}
</tr>
))}
</thead>
<tbody>{children}</tbody>
</table>
</div>
</div>
);
}

View File

@@ -0,0 +1,277 @@
import type React from "react";
import { parseNumber } from "@/lib/utils";
import { roundNumber } from "@/lib/lg-dashboard";
import type {
DataColumn,
DataColumnLeaf,
GaugeColumn,
GaugeColumnLeaf,
SignDisplayMode,
SignStyle,
ValueFormatter,
} from "../../types";
export type TableColumnNode<T> = DataColumn<T> | GaugeColumn<T>;
export type TableColumnLeaf<T> = DataColumnLeaf<T> | GaugeColumnLeaf<T>;
export type GroupHeaderCell = {
id: string;
label: string;
colSpan: number;
rowSpan: number;
className?: string;
isLeaf: boolean;
};
export type ResolvedSignStyle = {
paint: "text" | "cell";
display: SignDisplayMode;
showPlus: boolean;
arrowWithNumber: boolean;
zeroText: string;
valueFormatter: ValueFormatter;
positiveTextClassName: string;
negativeTextClassName: string;
zeroTextClassName: string;
positiveCellBg: string;
negativeCellBg: string;
zeroCellBg: string;
};
const defaultValueFormatter: ValueFormatter = (value) =>
Number.isInteger(value) ? String(roundNumber(value)) : value.toLocaleString();
const defaultSignStyle: ResolvedSignStyle = {
paint: "text",
display: "number",
showPlus: true,
arrowWithNumber: false,
zeroText: "-",
valueFormatter: defaultValueFormatter,
positiveTextClassName: "text-primary font-semibold",
negativeTextClassName: "text-info font-semibold",
zeroTextClassName: "text-gray-600",
positiveCellBg: "hsl(var(--primary) / 0.08)",
negativeCellBg: "hsl(var(--info) / 0.08)",
zeroCellBg: "hsl(var(--lg-gray-200) / 0.6)",
};
function isColumnLeaf<T>(column: TableColumnNode<T>): column is TableColumnLeaf<T> {
return !("children" in column) || !column.children?.length;
}
export function getLeafColumns<T>(columns: TableColumnNode<T>[]) {
const leaves: TableColumnLeaf<T>[] = [];
const visit = (nodes: TableColumnNode<T>[]) => {
nodes.forEach((node) => {
if (isColumnLeaf(node)) {
leaves.push(node);
return;
}
visit(node.children);
});
};
visit(columns);
return leaves;
}
function getHeaderDepth<T>(columns: TableColumnNode<T>[]) {
const visit = (nodes: TableColumnNode<T>[], depth: number): number =>
nodes.reduce((maxDepth, node) => {
if (isColumnLeaf(node)) {
return Math.max(maxDepth, depth);
}
return Math.max(maxDepth, visit(node.children, depth + 1));
}, depth);
return columns.length ? visit(columns, 1) : 0;
}
function getLeafCount<T>(column: TableColumnNode<T>): number {
if (isColumnLeaf(column)) {
return 1;
}
return column.children.reduce((sum, child) => sum + getLeafCount(child), 0);
}
function getColSpan<T>(isLeaf: boolean, node: TableColumnNode<T>) {
if(node.colSpan){
return node.colSpan;
}
return isLeaf ? 1 : getLeafCount(node);
}
export function buildHeaderRows<T>(columns: TableColumnNode<T>[]) {
const depth = getHeaderDepth(columns);
if (!depth) {
return [] as GroupHeaderCell[][];
}
const rows = Array.from({ length: depth }, () => [] as GroupHeaderCell[]);
const visit = (nodes: TableColumnNode<T>[], level: number, path: string[]) => {
nodes.forEach((node, index) => {
const nodeId = node.id ?? (isColumnLeaf(node) ? String(node.key) : `${path.join(".") || "root"}:${index}:${node.header}`);
const nextPath = [...path, nodeId];
const isLeaf = isColumnLeaf(node);
const colSpan = getColSpan(isLeaf, node);
rows[level].push({
id: nextPath.join("/"),
label: node.header,
colSpan,
rowSpan: isLeaf ? depth - level : 1,
className: node.headerClassName,
isLeaf,
});
if (!isLeaf) {
visit(node.children, level + 1, nextPath);
}
});
};
visit(columns, 0, []);
return rows;
}
export function hasGroupedHeader<T>(columns: TableColumnNode<T>[]) {
return getHeaderDepth(columns) > 1;
}
export function getColumnAlign<T>(column: TableColumnLeaf<T>, fallback: "left" | "center" | "right" = "center") {
if (column.align) {
return column.align;
}
if ("numeric" in column && column.numeric) {
return "right";
}
if (column.rowHead) {
return "left";
}
return fallback;
}
export function toTableCellContent(raw: unknown, decimalPoint?: number): React.ReactNode {
if (raw == null) {
return "";
}
if (typeof raw === "string") {
const trimmed = raw.trim();
if (!trimmed) {
return raw;
}
const parsed = Number(trimmed);
return Number.isNaN(parsed) ? raw : roundNumber(parsed, decimalPoint);
}
if (typeof raw === "number") {
return String(roundNumber(raw));
}
return String(raw);
}
export function toRoundedNumber(raw: unknown, decimalPoint?: number) {
const parsed = parseNumber(raw);
return parsed === null ? null : roundNumber(parsed, decimalPoint);
}
export function appendCellMarker(content: React.ReactNode, marker: string) {
if (!marker) {
return content;
}
if (typeof content === "string" || typeof content === "number") {
return `${content}${marker}`;
}
return (
<>
{content}
{marker}
</>
);
}
export function resolveSignStyle<T>(signStyle?: SignStyle<T>, fallback?: Partial<ResolvedSignStyle>) {
return {
...defaultSignStyle,
...fallback,
...signStyle,
valueFormatter: signStyle?.valueFormatter ?? fallback?.valueFormatter ?? defaultSignStyle.valueFormatter,
};
}
export function shouldApplySignToColumn<T>(column: TableColumnLeaf<T>, signStyle?: SignStyle<T>) {
if (!signStyle || column.rowHead) {
return false;
}
if (signStyle.keys?.length) {
return signStyle.keys.includes(column.key);
}
return "numeric" in column ? !!column.numeric : false;
}
export function formatSignedValue(
value: number,
options: Pick<ResolvedSignStyle, "arrowWithNumber" | "display" | "showPlus" | "valueFormatter" | "zeroText">
) {
if (options.display === "arrow") {
if (value > 0) {
return options.arrowWithNumber ? `▲${options.valueFormatter(Math.abs(value))}` : "▲";
}
if (value < 0) {
return options.arrowWithNumber ? `▼${options.valueFormatter(Math.abs(value))}` : "▼";
}
return options.zeroText;
}
if (value > 0) {
return options.showPlus ? `+${options.valueFormatter(value)}` : options.valueFormatter(value);
}
if (value < 0) {
return options.valueFormatter(value);
}
return options.zeroText;
}
export function getSignTextClass(
value: number,
options: Pick<ResolvedSignStyle, "negativeTextClassName" | "positiveTextClassName" | "zeroTextClassName">
) {
if (value > 0) {
return options.positiveTextClassName;
}
if (value < 0) {
return options.negativeTextClassName;
}
return options.zeroTextClassName;
}
export function getSignCellBackground(
value: number,
options: Pick<ResolvedSignStyle, "negativeCellBg" | "positiveCellBg" | "zeroCellBg">
) {
if (value > 0) {
return options.positiveCellBg;
}
if (value < 0) {
return options.negativeCellBg;
}
return options.zeroCellBg;
}

View File

@@ -0,0 +1,154 @@
import type React from "react";
import { GAP_WORDING } from "@/const/lg-common.const";
export type NewNumber = number | null | undefined;
export type ChartSeries = {
/** legend에 노출될 이름 */
name: string;
/** categories와 동일 길이 */
data: NewNumber[];
/** stacked bar 용 */
stack?: string; // 같은 stack 값끼리 누적
};
export type ChartData = {
/** x(세로바)/y(가로바) 카테고리 */
categories: string[];
/** 시리즈(막대/스택 등) */
series: ChartSeries[];
};
/**
* (GroupedStackBar)
* - categories: x축 카테고리(예: 제품)
* - years: 그룹(예: 24/25/26)
* - brands: 스택 구성요소(예: LG/SS/C브랜드)
* - values: [yearIndex][brandIndex][categoryIndex]
*/
export type GroupedStackBarData = {
categories: string[];
years: Array<string | number>;
brands: string[];
values: Array<Array<Array<number | null | undefined>>>;
};
export type GroupedOverlayBarData = {
categories: string[]; // 제품
years: string[]; // 예: [24,25,26]
totalName?: string; // default: "전체"
focusName?: string; // default: "LG"
total: Array<Array<number | null>>; // [yearIndex][categoryIndex]
focus: Array<Array<number | null>>; // [yearIndex][categoryIndex]
};
/** (TopChartTable) HTML 테이블용 row (columns=categories) */
export type TopChartTableRow = {
/** 좌측 rowhead 라벨 */
label: string;
total: number | string | null | undefined;
sample: number | string | null | undefined;
/** categories 순서대로 값 */
values: Array<number | string | null | undefined>;
};
export type ValueFormatter = (v: number) => string;
export type TableColumnAlign = "left" | "center" | "right";
type TableColumnShared<T> = {
id?: string;
header: string;
width?: number | string;
align?: TableColumnAlign;
headerClassName?: string;
cellClassName?: string;
render?: (row: T) => React.ReactNode;
colSpan?: number;
};
export type DataColumnLeaf<T> = TableColumnShared<T> & {
key: keyof T;
rowHead?: boolean; // 첫 컬럼 등 row header
numeric?: boolean; // 숫자열(정렬 기본값/색상 타겟 기본값에 사용)
children?: undefined;
};
export type DataColumnGroup<T> = TableColumnShared<T> & {
children: DataColumn<T>[];
key?: undefined;
rowHead?: undefined;
numeric?: undefined;
};
export type DataColumn<T> = DataColumnLeaf<T> | DataColumnGroup<T>;
export type GaugeColumnLeaf<T> = TableColumnShared<T> & {
key: keyof T;
rowHead?: boolean;
/** 게이지 최대값 기준(기본 100) */
max?: number;
render?: (row: T) => React.ReactNode; // rowHead에 쓰기 좋음
cellType?: "gauge" | "number"; // default: "gauge"
children?: undefined;
};
export type GaugeColumnGroup<T> = TableColumnShared<T> & {
children: GaugeColumn<T>[];
key?: undefined;
rowHead?: undefined;
max?: undefined;
cellType?: undefined;
};
export type GaugeColumn<T> = GaugeColumnLeaf<T> | GaugeColumnGroup<T>;
export type SignDisplayMode = "number" | "arrow";
export type SignStyle<T> = {
/** 어떤 row에 +/ -/ 0 색상표기를 적용할지 선택 */
rowSelector: (row: T, rowIndex: number) => boolean;
/** 어떤 컬럼에 적용할지(미지정 시 numeric 컬럼 전체) */
keys?: (keyof T)[];
/** 색상 적용 방식 */
paint?: "text" | "cell"; // 기본 text
/** 표기 방식 */
display?: SignDisplayMode; // 기본 number
showPlus?: boolean; // number 모드에서 + 표시(기본 true)
/** 0 값 표기(기본 "-") */
zeroText?: string;
/** arrow 모드 옵션 */
arrowWithNumber?: boolean; // ▲ 2 처럼 (기본 false)
/** 값 포맷(기본: 정수면 그대로/그 외 toLocaleString) */
valueFormatter?: (v: number) => string;
/** 색상 커스터마이즈(기본: + primary, - info, 0 gray) */
positiveTextClassName?: string; // 기본 "text-primary font-semibold"
negativeTextClassName?: string; // 기본 "text-info font-semibold"
zeroTextClassName?: string; // 기본 "text-gray-600"
positiveCellBg?: string; // ex) "hsl(var(--primary) / 0.08)"
negativeCellBg?: string; // ex) "hsl(var(--info) / 0.08)"
zeroCellBg?: string; // ex) "hsl(var(--lg-gray-200) / 0.6)"
};
export const signStyleGapRow: SignStyle<TopChartTableRow> = {
rowSelector: (row) => row.label === GAP_WORDING,
display: "arrow",
arrowWithNumber: true,
paint: "text",
};
/** ChartLabel 보여지는 옵션 */
export type ShowLabel = "none" | "all" | "last" | "first";
export type bannerType = {
variable: string;
variableName: string;
};

View File

@@ -0,0 +1,33 @@
'use client'
import { Provider as JotaiProvider } from "jotai";
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
import ReactQueryLoadingSync from "@/components/common/ReactQueryLoadingSync";
import {useState} from "react";
import {QueryClient} from "@tanstack/query-core";
import { QueryClientProvider } from "@tanstack/react-query";
export function AppProvider({ children }: { children: React.ReactNode }) {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
retry: 1,
},
},
})
);
return (
<JotaiProvider>
<QueryClientProvider client={queryClient}>
<ReactQueryLoadingSync />
<LoadingOverlay />
{children}
</QueryClientProvider>
</JotaiProvider>
);
}

View File

@@ -1,144 +0,0 @@
import {
CategoryTargetData,
CategoryTargetItem,
CategoryTargetType,
CategoryTargetTypeItem,
TotalFilterItem
} from "./filter.types";
export const totalFilters:TotalFilterItem[] = [
{
variable:"a1",
variableName:"라이프 스테이지",
children:[
{ value: "0", label: "전체"},
{ value: "1", label: "미혼"},
{ value: "2", label: "기혼 무자녀"},
{ value: "3", label: "기혼 미취학자녀"},
{ value: "4", label: "기혼 학령기"},
{ value: "5", label: "기혼 성인자녀"},
{ value: "6", label: "독립 시니어"},
]
},
{
variable:"a2",
variableName:"월 소득 규모",
children:[
{ value: "0", label: "전체"},
{ value: "1", label: "299만원 이하"},
{ value: "2", label: "300~599만원 이하"},
{ value: "3", label: "600~899만원 이하"},
{ value: "4", label: "900만원 이상"},
]
},
{
variable:"a3",
variableName:"거주 형태",
children:[
{ value: "0", label: "전체"},
{ value: "1", label: "자가"},
{ value: "2", label: "전세"},
{ value: "3", label: "전+월세(보증금有)"},
{ value: "4", label: "월세(보증금無)"},
{ value: "5", label: "기타"},
]
},
{
variable:"a4",
variableName:"거주 평형",
children:[
{ value: "0", label: "19평 이하"},
{ value: "1", label: "20평형 대"},
{ value: "2", label: "30평형 대"},
{ value: "3", label: "40평형 대"},
{ value: "4", label: "50평형 이상"},
]
},
{
variable:"a5",
variableName:"주택 형태",
children:[
{ value: "0", label: "전체"},
{ value: "1", label: "아파트"},
{ value: "2", label: "주택"},
{ value: "3", label: "오피스텔"},
{ value: "4", label: "(연립)빌라"},
{ value: "5", label: "기타"},
]
},
{
variable:"a6",
variableName:"지역",
children:[
{ value: "0", label: "전체"},
{ value: "1", label: "서울, 인천, 경기도"},
{ value: "2", label: "경남, 부산, 울산"},
{ value: "3", label: "경북, 대구"},
{ value: "4", label: "전라도, 광주"},
{ value: "5", label: "충청, 대전, 세종"},
{ value: "6", label: "강원, 제주"},
]
},
{
variable:"a7",
variableName:"연령대",
children:[
{ value: "0", label: "20대"},
{ value: "1", label: "30대"},
{ value: "2", label: "40대"},
{ value: "3", label: "50대"},
{ value: "4", label: "60대"},
]
},
{
variable:"a8",
variableName:"가구원 수",
children:[
{ value: "0", label: "전체"},
{ value: "1", label: "1인 가구"},
{ value: "2", label: "2인 가구"},
{ value: "3", label: "3인 가구"},
{ value: "4", label: "4인 이상 가구"},
]
},
]
export const categoryTargetType: CategoryTargetTypeItem[] = [
{
label:"보유",
value: CategoryTargetType.PENETRATION,
},
{
label:"구매",
value: CategoryTargetType.PURCHASE,
},
{
label:"향후 구매",
value: CategoryTargetType.PURCHASE,
},
]
export const categoryTarget: CategoryTargetItem[] = [
{
type: CategoryTargetType.PENETRATION,
children:[
{ target: CategoryTargetData.PROFILE, label: "Profile"},
{ target: CategoryTargetData.PENETRATION_CHANGE, label: "보급률 변화"},
{ target: CategoryTargetData.BRAND, label: "브랜드"},
{ target: CategoryTargetData.TYPE_SPEC, label: "타입/스펙"},
{ target: CategoryTargetData.OWNERSHIP_PATH, label: "보유 경로"},
{ target: CategoryTargetData.PURCHASE_FORMAT, label: "구매 형식"},
]
},
{
type: CategoryTargetType.PURCHASE,
children:[
{ target: CategoryTargetData.PROFILE, label: "Profile"},
{ target: CategoryTargetData.BRAND, label: "브랜드"},
{ target: CategoryTargetData.TYPE_SPEC, label: "타입/스펙"},
{ target: CategoryTargetData.PURCHASE_BEHAVIOR, label: "구입 행태"},
{ target: CategoryTargetData.PURCHASE_CHANNEL, label: "구매 채널"},
{ target: CategoryTargetData.PURCHASE_FORMAT, label: "구매 형식"},
]
},
]

View File

@@ -0,0 +1,266 @@
import {CategoryFieldSpec} from "@/types/lg.types";
import {CategoryTargetData, CategoryTargetType} from "@/types/filter.types";
const profileFieldSpec: CategoryFieldSpec[] = [
{
title: {
[CategoryTargetType.PENETRATION]: "보유율"
, [CategoryTargetType.PURCHASE]: "구매율"
, [CategoryTargetType.INTENDED]: "향후 구매율"
},
requestKey: "category_${keyBase}",
chartMode:"none",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA1"
, [CategoryTargetType.PURCHASE]: "KQB0"
, [CategoryTargetType.INTENDED]: "KQC1"
},
},
{
title: "보유대수",
requestKey: "category_penetration_count",
chartMode:"none",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA2"
},
},
];
export const CATEGORY_PAGE_FIELDS: Record<CategoryTargetData, CategoryFieldSpec[]> = {
[CategoryTargetData.PROFILE_ALL]: profileFieldSpec,
[CategoryTargetData.PROFILE]: profileFieldSpec,
[CategoryTargetData.PENETRATION_CHANGE]: [
{
title: "보급률 변화",
requestKey: "category_${keyBase}",
chartMode:"none",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA1"
},
},
],
[CategoryTargetData.BRAND]: [
{
title: "브랜드",
requestKey: "category_${keyBase}_brand",
chartMode:"reverseStack",
chartTopMargin: 80,
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_3",
[CategoryTargetType.PURCHASE]: "KQX3_3",
},
},
{
title: {
[CategoryTargetType.PENETRATION]: "",
[CategoryTargetType.PURCHASE]: "구매 고려 브랜드",
[CategoryTargetType.INTENDED]: "브랜드",
},
requestKey: "category_${keyBase}_consider_brand",
chartMode:"horizontal",
qidByMode: {
[CategoryTargetType.PURCHASE]: "KQB1",
[CategoryTargetType.INTENDED]: "KQC2",
},
},
],
[CategoryTargetData.TYPE_SPEC]: [
{
title: "타입",
requestKey: "category_${keyBase}_type",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_4",
[CategoryTargetType.PURCHASE]: "KQX3_4",
[CategoryTargetType.INTENDED]: "KQC3_1"
}
},
{
title: "깊이 타입",
requestKey: "category_${keyBase}_depthType",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_5",
[CategoryTargetType.PURCHASE]: "KQX3_5",
[CategoryTargetType.INTENDED]: "KQC3_2"
}
},
{
title: "용량",
requestKey: "category_${keyBase}_capacity",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_6",
[CategoryTargetType.PURCHASE]: "KQX3_6"
}
},
{
title: "설치 형태",
requestKey: "category_${keyBase}_installType",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_7",
[CategoryTargetType.PURCHASE]: "KQX3_7",
[CategoryTargetType.INTENDED]: "KQC3_3"
}
},
{
title: "시공 방식",
requestKey: "category_${keyBase}_installMethod",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.INTENDED]: "KQC3_4"
}
},
{
title: "냉장고 & 김치냉장고 설치 형태",
requestKey: "category_${keyBase}_fridgeInstallType",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.INTENDED]: "KQC3_5"
}
},
{
title: "설치 위치",
requestKey: "category_${keyBase}_installLocation",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.INTENDED]: "KQC3_6"
}
},
{
title: "배치/설치환경",
requestKey: "category_${keyBase}_installEnv",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_8",
[CategoryTargetType.PURCHASE]: "KQX3_8",
[CategoryTargetType.INTENDED]: "KQC3_7"
}
},
{
title: "구입 고려 특징",
requestKey: "category_${keyBase}_buyConsiderations",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.INTENDED]: "KQC3_8"
}
},
{
title: "기능",
requestKey: "category_${keyBase}_features",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_9",
[CategoryTargetType.PURCHASE]: "KQX3_9"
}
},
{
title: "스크린 사이즈",
requestKey: "category_${keyBase}_screenSize",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_10",
[CategoryTargetType.PURCHASE]: "KQX3_10"
}
},
{
title: "용도",
requestKey: "category_${keyBase}_usage",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_11",
[CategoryTargetType.PURCHASE]: "KQX3_11"
}
},
{
title: "스마트 모니터 여부",
requestKey: "category_${keyBase}_isSmartMonitor",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_12",
[CategoryTargetType.PURCHASE]: "KQX3_12"
}
},
{
title: "음식물처리기 구동 방식",
requestKey: "category_${keyBase}_driveMethod",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_13",
[CategoryTargetType.PURCHASE]: "KQX3_13"
}
},
{
title: "전기레인지 화구 수",
requestKey: "category_${keyBase}_burnerCount",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_14",
[CategoryTargetType.PURCHASE]: "KQX3_14"
}
},
],
[CategoryTargetData.BEHAVIOR]: [
{
title: {
[CategoryTargetType.PENETRATION]: "보유 경로"
, [CategoryTargetType.PURCHASE]: "구입 행태"
, [CategoryTargetType.INTENDED]: "구입 행태"
},
requestKey: "category_${keyBase}_behavior",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_1",
[CategoryTargetType.PURCHASE]: "KQB2",
[CategoryTargetType.INTENDED]: "KQC5"
},
},
{
title: "구입 계기",
requestKey: "category_${keyBase}_chance",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PURCHASE]: "KQB3"
},
},
],
[CategoryTargetData.PURCHASE_CHANNEL]: [
{
title: "구매 채널(온/오프라인)",
requestKey: "category_${keyBase}_channel",
chartMode: "reverseStack",
qidByMode: {
[CategoryTargetType.PURCHASE]: "KQB4_NET",
[CategoryTargetType.INTENDED]: "KQC6_NET"
},
},
{
title: "구매 채널(상세)",
requestKey: "category_${keyBase}_channel_detail",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PURCHASE]: "KQB4",
[CategoryTargetType.INTENDED]: "KQC6"
},
},
],
[CategoryTargetData.PAYMENT_METHOD]: [
{
title: "구매형식",
requestKey: "category_${keyBase}_method",
chartMode:"reverseStack",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_2_1",
[CategoryTargetType.PURCHASE]: "KQX3_2_1",
[CategoryTargetType.INTENDED]: "KQC7"
},
},
],
};

View File

@@ -1,3 +1,2 @@
export const UNKNOWN_HTTP_ERROR = 'UNKNOWN_HTTP_ERROR'; export const UNKNOWN_HTTP_ERROR = 'UNKNOWN_HTTP_ERROR';
export const NONE_HTTP_ERROR = 'NONE_HTTP_ERROR'; export const NONE_HTTP_ERROR = 'NONE_HTTP_ERROR';
export const DASHBOARD_YEAR = 2026;

186
src/const/filter.const.ts Normal file
View File

@@ -0,0 +1,186 @@
import {
CategoryTargetData,
CategoryTargetItem,
CategoryTargetType,
CategoryTargetTypeItem, FilterItem,
TotalFilterItem
} from "@/types/filter.types";
export const totalFilters:TotalFilterItem[] = [
{
variable:"lifeStage",
variableName:"라이프 스테이지",
children:[
{ value: "0", label: "전체"},
{ value: "1", label: "미혼"},
{ value: "2", label: "기혼 무자녀"},
{ value: "3", label: "기혼 미취학자녀"},
{ value: "4", label: "기혼 학령기"},
{ value: "5", label: "기혼 성인자녀"},
{ value: "6", label: "독립 시니어"},
{ value: "7", label: "비혼 중년"},
{ value: "8", label: "기타"},
]
},
{
variable:"income",
variableName:"월 소득 규모",
children:[
{ value: "0", label: "전체"},
{ value: "1", label: "299만원 이하"},
{ value: "2", label: "300~599만원 이하"},
{ value: "3", label: "600~899만원 이하"},
{ value: "4", label: "900만원 이상"},
]
},
{
variable:"occupancy",
variableName:"입주 형태",
children:[
{ value: "0", label: "전체"},
{ value: "1", label: "자가"},
{ value: "2", label: "전세"},
{ value: "3", label: "전+월세(보증금有)"},
{ value: "4", label: "월세(보증금無)"},
{ value: "5", label: "기타"},
]
},
{
variable:"houseSize",
variableName:"거주 평형",
children:[
{ value: "0", label: "전체"},
{ value: "1", label: "19평 이하"},
{ value: "2", label: "20평형 대"},
{ value: "3", label: "30평형 대"},
{ value: "4", label: "40평형 대"},
{ value: "5", label: "50평형 이상"},
]
},
{
variable:"housing",
variableName:"주거 형태",
children:[
{ value: "0", label: "전체"},
{ value: "1", label: "아파트"},
{ value: "2", label: "주택"},
{ value: "3", label: "오피스텔"},
{ value: "4", label: "(연립)빌라"},
{ value: "5", label: "원룸"},
{ value: "6", label: "기타"},
]
},
{
variable:"region",
variableName:"지역",
children:[
{ value: "0", label: "전체"},
{ value: "1", label: "서울, 인천, 경기도"},
{ value: "2", label: "경남, 부산, 울산"},
{ value: "3", label: "경북, 대구"},
{ value: "4", label: "전라도, 광주"},
{ value: "5", label: "충청, 대전, 세종"},
{ value: "6", label: "강원, 제주"},
]
},
{
variable:"age",
variableName:"연령대",
children:[
{ value: "0", label: "전체"},
{ value: "1", label: "20대"},
{ value: "2", label: "30대"},
{ value: "3", label: "40대"},
{ value: "4", label: "50대"},
{ value: "5", label: "60대"},
]
},
{
variable:"household",
variableName:"가구원 수",
children:[
{ value: "0", label: "전체"},
{ value: "1", label: "1인 가구"},
{ value: "2", label: "2인 가구"},
{ value: "3", label: "3인 가구"},
{ value: "4", label: "4인 이상 가구"},
]
},
]
export const categoryTargetType: CategoryTargetTypeItem[] = [
{
label:"보유",
value: CategoryTargetType.PENETRATION,
},
{
label:"구매",
value: CategoryTargetType.PURCHASE,
},
{
label:"향후 구매",
value: CategoryTargetType.INTENDED,
},
]
export const categoryTarget: CategoryTargetItem[] = [
{
type: [CategoryTargetType.PENETRATION],
children:[
{ value: CategoryTargetData.PROFILE, label: "Profile"},
{ value: CategoryTargetData.PROFILE_ALL, label: "Profile (전체)"},
{ value: CategoryTargetData.PENETRATION_CHANGE, label: "보급률 변화"},
{ value: CategoryTargetData.BRAND, label: "브랜드"},
{ value: CategoryTargetData.TYPE_SPEC, label: "타입/스펙"},
{ value: CategoryTargetData.BEHAVIOR, label: "보유 경로"},
{ value: CategoryTargetData.PAYMENT_METHOD, label: "구매 형식"},
]
},
{
type: [CategoryTargetType.PURCHASE, CategoryTargetType.INTENDED],
children:[
{ value: CategoryTargetData.PROFILE, label: "Profile"},
{ value: CategoryTargetData.PROFILE_ALL, label: "Profile (전체)"},
{ value: CategoryTargetData.BRAND, label: "브랜드"},
{ value: CategoryTargetData.TYPE_SPEC, label: "타입/스펙"},
{ value: CategoryTargetData.BEHAVIOR, label: "구입 행태"},
{ value: CategoryTargetData.PURCHASE_CHANNEL, label: "구매 채널"},
{ value: CategoryTargetData.PAYMENT_METHOD, label: "구매 형식"},
]
},
]
export const categoryByDataBanner:FilterItem[] = [
{
variable:"lifeStage",
variableName:"라이프 스테이지",
},
{
variable:"age",
variableName:"연령대",
},
{
variable:"household",
variableName:"가구원 수",
},
{
variable:"occupancy",
variableName:"입주 형태",
},
{
variable:"housing",
variableName:"주거 형태",
},
{
variable:"houseSize",
variableName:"거주 평형",
},
{
variable:"income",
variableName:"월 소득 규모",
},
{
variable:"region",
variableName:"지역",
},
]

View File

@@ -0,0 +1,137 @@
import type { BannerKey } from "@/types/lg.types";
import { BANNER_KEY_MAP } from "@/const/lg-schema.const";
export type BannerGroupLeafNode = {
type: "leaf";
key: BannerKey;
};
export type BannerGroupBranchNode = {
type: "group";
id: string;
label: string;
children: readonly BannerGroupNode[];
};
export type BannerGroupNode = BannerGroupLeafNode | BannerGroupBranchNode;
export type BannerGroupDefinition = {
label: string;
children: readonly BannerGroupNode[];
};
export const BANNER_KEYS = Object.keys(BANNER_KEY_MAP) as Array<keyof typeof BANNER_KEY_MAP>;
export const BANNER_KEY = Object.keys(BANNER_KEY_MAP).reduce((acc, k) => {
(acc as any)[k] = k;
return acc;
}, {} as { [K in BannerKey]: K });
const leaf = (key: BannerKey): BannerGroupLeafNode => ({
type: "leaf",
key,
});
const group = (id: string, label: string, children: readonly BannerGroupNode[]): BannerGroupBranchNode => ({
type: "group",
id,
label,
children,
});
export const BANNER_GROUP = {
lifeStage: {
label: "라이프스테이지 별",
children: [
leaf(BANNER_KEY["KLIFEstAGE#1"]),
group("life-stage-married", "기혼", [
leaf(BANNER_KEY["KLIFEstAGE#2"]),
leaf(BANNER_KEY["KLIFEstAGE#3"]),
leaf(BANNER_KEY["KLIFEstAGE#4"]),
leaf(BANNER_KEY["KLIFEstAGE#5"]),
]),
leaf(BANNER_KEY["KLIFEstAGE#6"]),
leaf(BANNER_KEY["KLIFEstAGE#7"]),
leaf(BANNER_KEY["KLIFEstAGE#8"]),
],
},
household: {
label: "가구원수 별",
children: [
leaf(BANNER_KEY["KSQ8_R_DB#1"]),
leaf(BANNER_KEY["KSQ8_R_DB#2"]),
leaf(BANNER_KEY["KSQ8_R_DB#3"]),
leaf(BANNER_KEY["KSQ8_R_DB#4"]),
],
},
age: {
label: "연령",
children: [
leaf(BANNER_KEY["KSQ2_R_R#1"]),
leaf(BANNER_KEY["KSQ2_R_R#2"]),
leaf(BANNER_KEY["KSQ2_R_R#3"]),
leaf(BANNER_KEY["KSQ2_R_R#4"]),
leaf(BANNER_KEY["KSQ2_R_R#5"]),
],
},
occupancy: {
label: "입주 형태",
children: [
leaf(BANNER_KEY["KDQ6#1"]),
leaf(BANNER_KEY["KDQ6#2"]),
leaf(BANNER_KEY["KDQ6#3"]),
leaf(BANNER_KEY["KDQ6#4"]),
leaf(BANNER_KEY["KDQ6#5"]),
],
},
housing: {
label: "주거 형태",
children: [
leaf(BANNER_KEY["KDQ4#1"]),
leaf(BANNER_KEY["KDQ4#2"]),
leaf(BANNER_KEY["KDQ4#3"]),
leaf(BANNER_KEY["KDQ4#4"]),
leaf(BANNER_KEY["KDQ4#5"]),
leaf(BANNER_KEY["KDQ4#6"]),
],
},
houseSize: {
label: "거주 평형",
children: [
leaf(BANNER_KEY["KDQ5#1"]),
leaf(BANNER_KEY["KDQ5#2"]),
leaf(BANNER_KEY["KDQ5#3"]),
leaf(BANNER_KEY["KDQ5#4"]),
leaf(BANNER_KEY["KDQ5#5"]),
],
},
region: {
label: "거주 지역",
children: [
leaf(BANNER_KEY["KSQ4_R_R#1"]),
leaf(BANNER_KEY["KSQ4_R_R#2"]),
leaf(BANNER_KEY["KSQ4_R_R#3"]),
leaf(BANNER_KEY["KSQ4_R_R#4"]),
leaf(BANNER_KEY["KSQ4_R_R#5"]),
leaf(BANNER_KEY["KSQ4_R_R#6"]),
],
},
income: {
label: "소득수준",
children: [
leaf(BANNER_KEY["KDQ3_DB#1"]),
leaf(BANNER_KEY["KDQ3_DB#2"]),
leaf(BANNER_KEY["KDQ3_DB#3"]),
leaf(BANNER_KEY["KDQ3_DB#4"]),
],
},
} as const satisfies Record<string, BannerGroupDefinition>;
export const isBannerGroupBranchNode = (node: BannerGroupNode): node is BannerGroupBranchNode => {
return node.type === "group";
}
export const flattenBannerGroupKeys = (nodes: readonly BannerGroupNode[]): BannerKey[] => {
return nodes.flatMap((node) => (node.type === "leaf" ? [node.key] : flattenBannerGroupKeys(node.children)));
}
export const BANNER_GROUP_KEY = Object.keys(BANNER_GROUP) as string[];

View File

@@ -0,0 +1,15 @@
export const DEBOUNCE_TIME = 500;
export const USE_CACHE = true;
export const API_DECIMAL_POINT = 0;
export const VIEW_DECIMAL_POINT = 0;
export const SITE_TITLE = 'LGE CX Dashboard';
export const YEARS = ["2023", "2024", "2025"];
export const LAST_YEAR = YEARS.at(-1)!;
export const GAP_WORDING = "전년 대비 GAP(%p)";
export const UNIT_TEXT = "(단위 %)"
export const SAMPLE_SIZE_NOTICE = "* 30표본 미만 해석에 주의";
export const BRAND_LIST = ['기타', 'C Brand', '삼성', 'LG'];

View File

@@ -0,0 +1,70 @@
import { GaugeColumn } from "@/components/lge-dashboard";
import { PRODUCT_KEY_MAP } from "@/const/lg-schema.const";
import type { LifeStageRow } from "@/types/lg.types";
export const LIFE_STAGE_COLUMNS: GaugeColumn<LifeStageRow>[] = [
{ key: "item", header: "", rowHead: true, render: (r) => r.item },
{ key: "total", header: "전체", max: 100, align: "left", cellType: "number" },
{ key: "KLIFEstAGE#1", header: "미혼", max: 100, align: "left" },
{
id: "life-stage-married",
header: "기혼",
children: [
{ key: "KLIFEstAGE#2", header: "무자녀", max: 100, align: "left" },
{ key: "KLIFEstAGE#3", header: "미취학", max: 100, align: "left" },
{ key: "KLIFEstAGE#4", header: "취학자녀", max: 100, align: "left" },
{ key: "KLIFEstAGE#5", header: "성인자녀", max: 100, align: "left" },
],
},
{ key: "KLIFEstAGE#6", header: "독립\n시니어", max: 100, align: "left" },
{ key: "KLIFEstAGE#7", header: "비혼 중년", max: 100, align: "left" },
{ key: "KLIFEstAGE#8", header: "기타", max: 100, align: "left" },
];
export const LIFE_STAGE_GROUPS = [
{ title: "대형가전 군", items: ["KPRODUCT#1", "KPRODUCT#7", "KPRODUCT#8", "KPRODUCT#12", "KPRODUCT#14", "KPRODUCT#2", "KPRODUCT#3", "KPRODUCT#11"] },
{ title: "소형가전 군", items: ["KPRODUCT#9", "KPRODUCT#13", "KPRODUCT#4"] },
{ title: "신가전 군", items: ["KPRODUCT#10", "KPRODUCT#6"] },
] as const;
export const PRODUCT_KEYS = Object.keys(PRODUCT_KEY_MAP) as Array<keyof typeof PRODUCT_KEY_MAP>;
export const PRODUCTS = Object.values(PRODUCT_KEY_MAP) as Array<string>;
export const PRODUCTS_FILTER_ITEM = [
{
path: "kitchen",
items: [
"KPRODUCT#1", // 냉장고
"KPRODUCT#2", // 김치 냉장고
"KPRODUCT#3", // 정수기
"KPRODUCT#4", // 전기 레인지
"KPRODUCT#5", // 식기 세척기
"KPRODUCT#6", // 음식물처리기
],
},
{
path: "living",
items: [
"KPRODUCT#7", // 세탁기
"KPRODUCT#9", // 건조기
"KPRODUCT#8", // 청소기
"KPRODUCT#10", // 로봇 청소기
"KPRODUCT#11", // 의류 관리기
],
},
{
path: "es",
items: [
"KPRODUCT#12", // 에어컨
"KPRODUCT#13", // 공기 청정기
],
},
{
path: "ms",
items: [
"KPRODUCT#14", // TV
"KPRODUCT#15", // 노트북
"KPRODUCT#16", // 모니터
],
},
] as const;

View File

@@ -0,0 +1,82 @@
export const PRODUCT_KEY_MAP = {
"KPRODUCT#1": "냉장고",
"KPRODUCT#2": "김치 냉장고",
"KPRODUCT#3": "정수기",
"KPRODUCT#4": "전기 레인지",
"KPRODUCT#5": "식기 세척기",
"KPRODUCT#6": "음식물처리기",
"KPRODUCT#7": "세탁기",
"KPRODUCT#9": "건조기",
"KPRODUCT#8": "청소기",
"KPRODUCT#10": "로봇 청소기",
"KPRODUCT#11": "의류 관리기",
"KPRODUCT#12": "에어컨",
"KPRODUCT#13": "공기 청정기",
"KPRODUCT#14": "TV",
"KPRODUCT#15": "노트북",
"KPRODUCT#16": "모니터",
} as const;
export const BANNER_KEY_MAP = {
// 라이프 스테이지
"KLIFEstAGE#1": "미혼",
"KLIFEstAGE#2": "무자녀",
"KLIFEstAGE#3": "미취학",
"KLIFEstAGE#4": "취학자녀",
"KLIFEstAGE#5": "성인자녀",
"KLIFEstAGE#6": "독립\n시니어",
"KLIFEstAGE#7": "비혼 중년",
"KLIFEstAGE#8": "기타",
// 가구원수
"KSQ8_R_DB#1": "1인 가구",
"KSQ8_R_DB#2": "2인 가구",
"KSQ8_R_DB#3": "3인 가구",
"KSQ8_R_DB#4": "4인 이상 가구",
// 연령
"KSQ2_R_R#1": "20대",
"KSQ2_R_R#2": "30대",
"KSQ2_R_R#3": "40대",
"KSQ2_R_R#4": "50대",
"KSQ2_R_R#5": "60대",
// 점유형태
"KDQ6#1": "자가",
"KDQ6#2": "전세",
"KDQ6#3": "전+월세\n(보증금有)",
"KDQ6#4": "월세\n(보증금無)",
"KDQ6#5": "기타",
// 주거형태
"KDQ4#1": "아파트",
"KDQ4#2": "주택",
"KDQ4#3": "오피스텔",
"KDQ4#4": "(연립)빌라",
"KDQ4#5": "원룸",
"KDQ4#6": "기타",
// 평형
"KDQ5#1": "19평 이하",
"KDQ5#2": "20평형 대",
"KDQ5#3": "30평형 대",
"KDQ5#4": "40평형 대",
"KDQ5#5": "50평형 대 이상",
// 권역
"KSQ4_R_R#1": "서울, 인천, 경기도",
"KSQ4_R_R#2": "경남, 부산, 울산",
"KSQ4_R_R#3": "경북, 대구",
"KSQ4_R_R#4": "전라도, 광주",
"KSQ4_R_R#5": "충청, 대전, 세종",
"KSQ4_R_R#6": "강원, 제주",
// 소득
"KDQ3_DB#1": "299만원 이하",
"KDQ3_DB#2": "300~599만원 이하",
"KDQ3_DB#3": "600~899만원 이하",
"KDQ3_DB#4": "900만원 이상",
} as const;

View File

@@ -0,0 +1,49 @@
export const QID_SURVEY_TITLE: Record<string, string> = {
"KQA3_3": "Q. 보유하고 계신 제품의 브랜드는 어떻게 되십니까?",
"KQA3_4": "Q. 보유하고 계신 제품의 타입은 어떻게 되십니까?",
"KQA3_5": "Q. 보유하고 계신 제품의 깊이 타입은 어떻게 되십니까?",
"KQA3_6": "Q. 보유하고 계신 제품의 용량은 어떻게 되십니까?",
"KQA3_7": "Q. 보유하고 계신 제품의 설치 형태는 어떻게 되십니까?",
"KQA3_8": "Q. 보유하고 계신 제품은 메인 가구와 어떻게 배치되어 있습니까?",
"KQA3_9": "Q. 보유하고 계신 제품에 포함되어 있는 기능이 있으십니까? 모두 선택해 주세요.",
"KQA3_10": "Q. 보유하고 계신 제품의 스크린 사이즈는 어떻게 되십니까?",
"KQA3_11": "Q. 보유하고 계신 제품의 가장 주된 용도는 무엇입니까?",
"KQA3_12": "Q. 보유하고 계신 제품은 스마트 모니터(자체적으로 OS를 가지고 있어, 기타 기기 연결 없이 작동이 가능한 모니터) 입니까?",
"KQA3_13": "Q. 보유하고 계신 제품의 구동 방식은 어떻게 되십니까?",
"KQA3_14": "Q. 보유하고 계신 제품의 화구 수는 어떻게 되십니까?",
"KQA3_1": "Q. 보유하고 계신 제품을 구매 또는 보유하게 된 경로가 어떻게 되십니까? ",
"KQA3_2_1": "Q. 귀하께서는 제품을 어떤 방식으로 구입하셨습니까? ",
"KQX3_3": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 브랜드는 어떻게 되십니까?",
"KQB1": "Q. 귀하께서 [#YEAR#]년에 제품을 구매하실 때 구매를 고려하셨던 브랜드는 무엇입니까? 모두 선택하여 주시기 바랍니다",
"KQX3_4": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 타입은 어떻게 되십니까?",
"KQX3_5": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 깊이 타입은 어떻게 되십니까?",
"KQX3_6": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 용량은 어떻게 되십니까?",
"KQX3_7": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 설치 형태는 어떻게 되십니까?",
"KQX3_8": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품은 메인 가구와 어떻게 배치되어 있습니까?",
"KQX3_9": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품에 포함되어 있는 기능이 있으십니까? 모두 선택해 주세요.",
"KQX3_10": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 스크린 사이즈는 어떻게 되십니까?",
"KQX3_11": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 가장 주된 용도는 무엇입니까?",
"KQX3_12": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품은 스마트 모니터(자체적으로 OS를 가지고 있어, 기타 기기 연결 없이 작동이 가능한 모니터) 입니까?",
"KQX3_13": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 구동 방식은 어떻게 되십니까?",
"KQX3_14": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 화구 수는 어떻게 되십니까?",
"KQB2": "Q. 귀하께서는 [#YEAR#]년에 제품을 신규로 구입하신 건가요? 교체/추가 구입하신 건가요? 한 가지만 선택해주세요",
"KQB3": "Q. 귀하께서 [#YEAR#]년에 제품을 구입하신 이유/계기(상황)는 무엇입니까? 가장 주요한 이유/계기를 한 가지만 선택해주세요",
"KQB4_NET": "Q. 최종적으로 제품을 구매하신 곳은 어디십니까? 한 가지만 선택해주세요",
"KQB4": "Q. 최종적으로 제품을 구매하신 곳은 어디십니까? 한 가지만 선택해주세요",
"KQX3_2_1": "Q. 귀하께서는 제품을 어떤 방식으로 구입하셨습니까? 한가지만 선택해주세요",
"KQC2": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품의 브랜드로 고려하고 계신 것은 무엇입니까? 모두 선택해주세요",
"KQC3_1": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품의 타입으로 고려하고 계신 것은 무엇입니까? 모두 선택해주세요",
"KQC3_2": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품의 깊이 타입으로 고려하고 계신 것은 무엇입니까? 모두 선택해주세요",
"KQC3_3": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품의 설치 형태로 고려하고 계신 것은 무엇입니까? 모두 선택해주세요",
"KQC3_4": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품의 설치 방식을 실제 공간에 구현하기 위해서 다음 중 어떤 방식의 시공이 필요하다고 생각하십니까?",
"KQC3_5": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 <냉장고와 김치냉장고>를 어떤 형태로 설치하실 계획이십니까?",
"KQC3_6": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품은 어디에 설치하실 계획이십니까?",
"KQC3_7": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품은 어떤 환경에 설치하실 계획이십니까?",
"KQC3_8": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품의 특징으로 고려하고 계신 것은 무엇입니까? 모두 선택해주세요",
"KQC5": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품을 신규로 구입하실 건가요? 교체/추가 구입하실 건가요? 한 가지만 선택해주세요",
"KQC6_NET": "Q. [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품을 구매하고 싶으신 곳은 어디십니까? 한 가지만 선택해주세요",
"KQC6": "Q. [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품을 구매하고 싶으신 곳은 어디십니까? 한 가지만 선택해주세요",
"KQC7": "Q. 그렇다면, [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품을 어떤 방식으로 구입하길 원하십니까? 한가지만 선택해주세요",
}

View File

@@ -1,4 +1,4 @@
import {SubMenuItem, TopMenuItem} from "@/config/menu.types"; import {SubMenuItem, TopMenuItem} from "@/types/menu.types";
export const topMenus: TopMenuItem[] = [ export const topMenus: TopMenuItem[] = [
{ {
@@ -10,7 +10,7 @@ export const topMenus: TopMenuItem[] = [
{ {
id: "category", id: "category",
label: "카테고리", label: "카테고리",
path: "/category/ha-kitchen", path: "/category/kitchen",
match: (pathname) => pathname.startsWith("/category"), match: (pathname) => pathname.startsWith("/category"),
}, },
]; ];
@@ -40,23 +40,23 @@ export const totalSubMenus: SubMenuItem[] = [
export const categorySubMenus: SubMenuItem[] = [ export const categorySubMenus: SubMenuItem[] = [
{ {
id: "ha-kitchen", id: "kitchen",
label: "H&A 주방가전(키친)", label: "키친솔루션",
path: "/category/ha-kitchen", path: "/category/kitchen",
}, },
{ {
id: "ha-living", id: "living",
label: "H&A 리빙가전", label: "리빙솔루션",
path: "/category/ha-living", path: "/category/living",
}, },
{ {
id: "air-solution", id: "es",
label: "에어솔루션", label: "ES",
path: "/category/air-solution", path: "/category/es",
}, },
{ {
id: "ms-digital", id: "ms",
label: "MS 디지털가전", label: "MS",
path: "/category/ms-digital", path: "/category/ms",
}, },
] ]

View File

@@ -12,8 +12,7 @@ export const useAuth = () => {
const setFromLoginResponse = useCallback( const setFromLoginResponse = useCallback(
(res: LoginUser, loginSeatNumber:string|null = null) => { (res: LoginUser, loginSeatNumber:string|null = null) => {
setAuth({ setAuth({
user: res, user: res
seatNumber: loginSeatNumber,
}); });
}, },
[setAuth], [setAuth],
@@ -29,7 +28,6 @@ export const useAuth = () => {
const logout = useCallback(() => { const logout = useCallback(() => {
setAuth({ setAuth({
user: null, user: null,
seatNumber: null,
}); });
}, [setAuth]); }, [setAuth]);

View File

@@ -1,6 +1,7 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import {DEBOUNCE_TIME} from "@/const/lg-common.const";
export function useDebouncedValue<T>(value: T, delayMs = 1200) { export function useDebouncedValue<T>(value: T, delayMs = DEBOUNCE_TIME) {
const [debounced, setDebounced] = useState(value); const [debounced, setDebounced] = useState(value);
useEffect(() => { useEffect(() => {

22
src/hooks/useResize.ts Normal file
View File

@@ -0,0 +1,22 @@
import { useEffect, useState } from "react";
export const useResizeKey = (debounceMs = 150) => {
const [key, setKey] = useState(0);
useEffect(() => {
let t: number | undefined;
const onResize = () => {
window.clearTimeout(t);
t = window.setTimeout(() => setKey((k) => k + 1), debounceMs);
};
window.addEventListener("resize", onResize);
return () => {
window.removeEventListener("resize", onResize);
window.clearTimeout(t);
};
}, [debounceMs]);
return key;
}

View File

@@ -14,10 +14,10 @@ import { StorageKey, StorageType } from "@/store/storage/storage-keys";
* 사용법: * 사용법:
* const { set, get, remove } = useStorage(StorageKeys.SeatNumber); * const { set, get, remove } = useStorage(StorageKeys.SeatNumber);
*/ */
export const useStorage = (key: StorageKey) => { export const useStorage = <T>(key: StorageKey) => {
const storageType = StorageType[key]; // "local" | "session" const storageType = StorageType[key]; // "local" | "session"
const set = (value: any): void => { const set = (value: T): void => {
if (storageType === "session") { if (storageType === "session") {
setSessionStorage(key, value); setSessionStorage(key, value);
} else { } else {
@@ -25,7 +25,7 @@ export const useStorage = (key: StorageKey) => {
} }
}; };
const get = (): any => { const get = (): T => {
if (storageType === "session") { if (storageType === "session") {
return getSessionStorage(key); return getSessionStorage(key);
} else { } else {

230
src/lib/chart-options.ts Normal file
View File

@@ -0,0 +1,230 @@
import { AXIS_HIDE_Y_STYLE, BAR_WIDTHS, CHART_GRID_DEFAULTS } from "@/components/lge-dashboard/chart/chart.config";
import {ChartData, NewNumber} from "@/components/lge-dashboard";
export function reverseCategories<T extends ChartData>(data: T): T {
const categories = [...data.categories].reverse();
const series = data.series.map((s) => ({
...s,
data: [...s.data].reverse(),
}));
return { ...data, categories, series };
}
export function reverseSeries<T extends ChartData>(data: T): T {
return {
...data,
series: [...data.series].reverse(),
};
}
/**
* 기본 Tooltip 옵션 생성
* @param valueFormatter - 값 포맷터 함수 (기본값: 정수는 그대로, 소수는 toLocaleString)
* @param overrides - 추가/덮어쓸 옵션
*/
export function createDefaultTooltip(
valueFormatter?: (v: number) => string,
overrides?: any
): any {
const defaultFmt = (v: number) =>
Number.isInteger(v) ? String(v) : v.toLocaleString();
return {
trigger: "axis",
axisPointer: { type: "shadow" },
valueFormatter: (v: unknown) =>
typeof v === "number" ? (valueFormatter ?? defaultFmt)(v) : String(v),
...overrides,
};
}
/**
* 기본 Legend 옵션 생성
* @param overrides - 추가/덮어쓸 옵션
*/
export function createDefaultLegend(
overrides?: any
): any {
return {
...overrides,
top: 0,
};
}
export function createReverseLegend(
originalData: ChartData,
overrides?: any
): any {
const order = originalData.series.map((s) => s.name);
return createDefaultLegend({
...overrides,
data: order,
});
}
export function createReverseTooltip(
originalData: ChartData,
valueFormatter?: (v: number) => string,
overrides?: any
): any {
const order = originalData.series.map((s) => s.name);
// 기본 tooltip 생성(내부 defaultFmt 포함)
const base = createDefaultTooltip(valueFormatter, overrides);
const fmt = base.valueFormatter ?? ((v: unknown) => String(v));
const extractVal = (p: any): unknown => {
const v = p?.value;
if (typeof v === "number") return v;
if (Array.isArray(v)) return v[v.length - 1]; // dataset/encode 케이스 대비
if (typeof p?.data === "number") return p.data;
if (p?.data && typeof p.data.value === "number") return p.data.value;
return v;
};
return {
...base,
formatter: (params: any) => {
const arr = Array.isArray(params) ? params : [params];
if (arr.length === 0) return "";
const title = arr[0]?.axisValueLabel ?? arr[0]?.name ?? "";
const byName = new Map<string, any>();
for (const p of arr) byName.set(p.seriesName, p);
const lines = order
.map((name) => byName.get(name))
.filter(Boolean)
.map((p) => {
const v = extractVal(p);
const printed =
typeof v === "number" ? fmt(v) : v == null ? "-" : String(v);
return `${p.marker ?? ""}${p.seriesName} ${printed}`;
});
return [title, ...lines].join("<br/>");
},
};
}
/**
* 기본 Grid 옵션 생성
* @param preset - 프리셋 타입 (default | compact)
* @param overrides - 추가/덮어쓸 옵션
*/
export function createDefaultGrid(
preset: "default" | "compact" = "default",
overrides?: any
): any {
const base =
preset === "compact"
? CHART_GRID_DEFAULTS.COMPACT
: CHART_GRID_DEFAULTS.DEFAULT;
return {
...base,
...overrides,
};
}
/**
* Category Axis 옵션 생성
* @param data - 카테고리 데이터 배열
* @param hideStyle - 축 스타일 숨김 여부 (라벨, 틱, 라인 등)
* @param overrides - 추가/덮어쓸 옵션
*/
export function createCategoryAxis(
data: string[],
hideStyle?: boolean,
overrides?: any
): any {
const base: any = {
type: "category",
data,
};
if (hideStyle) {
return {
...base,
axisLabel: { show: false },
axisTick: { show: false },
axisLine: { show: false },
splitLine: { show: false },
...overrides,
};
}
return {
...base,
...overrides,
};
}
/**
* Value Axis 옵션 생성
* @param hideStyle - 축 스타일 숨김 여부 (라벨, 틱, 라인 등)
* @param overrides - 추가/덮어쓸 옵션
*/
export function createValueAxis(
hideStyle?: boolean,
overrides?: any
): any {
const base: any = {
type: "value",
};
if (hideStyle) {
return {
...base,
...AXIS_HIDE_Y_STYLE,
splitLine: { show: false },
...overrides,
};
}
return {
...base,
...overrides,
};
}
/**
* Bar 시리즈 기본 옵션 생성
* @param name - 시리즈 이름
* @param data - 데이터 배열
* @param options - 추가 옵션 (stack, barMaxWidth 등)
*/
export function createBarSeries(
name: string,
data: NewNumber[],
options?: {
stack?: string;
barMaxWidth?: number;
emphasis?: boolean;
label?: object;
}
): {
name: string;
type: "bar";
data: NewNumber[];
stack?: string;
barMaxWidth?: number;
emphasis?: { disabled: boolean };
label?: object;
} {
const { stack, barMaxWidth, emphasis = false, label } = options ?? {};
return {
name,
type: "bar",
data,
...(stack && { stack }),
barMaxWidth: barMaxWidth ?? BAR_WIDTHS.DEFAULT,
emphasis: { disabled: !emphasis },
...(label && { label }),
};
}

View File

@@ -7,6 +7,4 @@ const required = (name: string) => {
export const serverEnv = { export const serverEnv = {
ENV: required("ENV"), ENV: required("ENV"),
API_BACK_SERVER: required("API_BACK_SERVER"), API_BACK_SERVER: required("API_BACK_SERVER"),
API_KART_SERVER: required("API_KART_SERVER"),
KART_API_KEY: required("KART_API_KEY"),
}; };

View File

@@ -33,6 +33,11 @@ export type QueryValue = string | string[] | undefined;
export type Query = Record<string, QueryValue>; export type Query = Record<string, QueryValue>;
export type PathParams = Record<string, string | number | boolean>; export type PathParams = Record<string, string | number | boolean>;
export type NextFetchOptions = {
revalidate?: number;
tags?: string[];
};
export type RequestOptions = { export type RequestOptions = {
method?: HttpMethod; method?: HttpMethod;
pathParams?: PathParams; pathParams?: PathParams;
@@ -47,6 +52,8 @@ export type RequestOptions = {
autoLogoutOnAuthError?: boolean; autoLogoutOnAuthError?: boolean;
expectText?: boolean; expectText?: boolean;
expectBinary?: boolean; expectBinary?: boolean;
cache?: RequestCache; // "force-cache" | "no-store" | ...
next?: NextFetchOptions; // Next 서버 fetch 확장 옵션
}; };
export type HttpClientOptions = { export type HttpClientOptions = {
@@ -140,12 +147,17 @@ export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {})
const controller = new AbortController(); const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? defaultTimeoutMs); const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? defaultTimeoutMs);
const isServer = typeof window === "undefined";
const cacheMode: RequestCache = options.cache ?? (isServer && options.next ? "force-cache" : "no-store");
const nextOpt = isServer ? options.next : undefined;
try { try {
const res = await fetch(url.toString(), { const res = await fetch(url.toString(), {
method: options.method ?? (body ? "POST" : "GET"), method: options.method ?? (body ? "POST" : "GET"),
headers, headers,
body, body,
cache: "no-store", cache: cacheMode,
...(nextOpt ? ({ next: nextOpt } as any) : {}),
signal: controller.signal, signal: controller.signal,
}); });

588
src/lib/lg-dashboard.ts Normal file
View File

@@ -0,0 +1,588 @@
import {
BannerGroupKey,
BannerResponse,
BannerRow, BuildPageModeConfigResult,
ProductResponse, ProductRow,
StatisticsRequest
} from "@/types/lg.types";
import {ChartData} from "@/components/lge-dashboard";
import type { DataColumn } from "@/components/lge-dashboard/types";
import {API_DECIMAL_POINT, GAP_WORDING, VIEW_DECIMAL_POINT} from "@/const/lg-common.const";
import {BANNER_GROUP, BANNER_KEYS, type BannerGroupDefinition, type BannerGroupNode, flattenBannerGroupKeys} from "@/const/lg-banner.const";
import {PRODUCT_KEYS} from "@/const/lg-product.const";
import {CATEGORY_PAGE_FIELDS} from "@/config/lg-page.config";
import {formatNumber} from "@/lib/utils";
import {nextApi} from "@/lib/http-client";
import {CategoryFilterValue} from "@/components/layout/CategoryFilter";
export const isSampleRow = (raw: string) => raw.replace(/\s+/g, "").includes("사례수");
export const isHasCountRow = (raw: string) => raw.replace(/\s+/g, "").includes("보유대수");
export const isCagrRow = (raw: string) => raw.replace(/\s+/g, "").toUpperCase().includes("CAGR");
export const isGapRow = (raw: string) => raw.replace(/\s+/g, "").toUpperCase().includes("GAP");
/**
* Row Label을 표시용 텍스트로 포맷팅합니다.
* - "사례수" -> "(사례수)"
* - "gap" -> "전년 대비 GAP(%p)"
* - "CAGR" -> "CAGR(%)"
* - "24" -> "24년"
* - "보급율" -> "보급율(%)"
* - 기타 -> 원본 그대로
*/
export function formatRowLabel(
label: string,
options?: {
convertSample?: boolean; // "사례수" -> "(사례수)" (기본값: true)
convertGap?: boolean; // "gap" -> "전년 대비 GAP(%p)" (기본값: true)
convertCagr?: boolean; // "CAGR" -> "CAGR(%)" (기본값: true)
convertYear?: boolean; // "24" -> "24년" (기본값: true)
convertRate?: boolean; // "~율" -> "~율(%)" (기본값: true)
convertCount?: boolean; // "~대수" -> "~대수(대)" (기본값: true)
}
): string {
const {
convertSample = true,
convertGap = true,
convertCagr = true,
convertYear = true,
convertRate = true,
convertCount = true,
} = options ?? {};
const t = label.trim();
if (convertSample && t === "사례수") return "(사례수)";
if (convertGap && t.toLowerCase() === "gap") return GAP_WORDING;
if (convertCagr && t.toUpperCase() === "CAGR") return "CAGR(%)";
if (convertYear && /^\d{4}$/.test(t)) return `${t.substring(2,4)}년`;
if (convertYear && /^\d{2}$/.test(t)) return `${t}년`;
if (convertRate && t.endsWith("율")) return `${t.replaceAll('(%)','')}(%)`;
if (convertCount && t.includes("대수")) return `${t.replaceAll('(대)','')}(대)`;
return t;
}
export const wrapSampleRow = <T extends Record<string, unknown> & { rowLabel: string }>(
rows: T[], replaceLabel: boolean = true
): T[] => {
return rows.map((r) => {
if (!isSampleRow(r.rowLabel)) return r;
const out: any = { ...r };
Object.entries(r).forEach(([k, v]) => {
if (k == "year" || v == null) return;
if (
typeof v === "number" ||
(typeof v === "string" && v.trim() !== "" && !Number.isNaN(Number(v)))
) {
out[k] = `(${formatNumber(Number(v))})`;
return;
}
if(replaceLabel){
if (typeof v === "string") {
// 이미 괄호면 그대로
out[k] = v.startsWith("(") && v.endsWith(")") ? v : `(${v})`;
return;
}
out[k] = `(${String(v)})`;
}
});
return out as T;
});
};
/**
* 연도 배열로부터 연도 -> 인덱스 맵을 생성합니다.
* @param years - 연도 배열 (예: [2024, 2025, 2026])
* @returns Map<연도, 인덱스>
*/
export function createYearIndexMap(years: number[]): Map<number, number> {
return new Map<number, number>(years.map((y, i) => [y, i]));
}
/**
* 연도 필터링: 지정된 연도 배열에 포함되고 rowLabel이 "년"으로 끝나는 행만 반환
* @param data - 필터링할 데이터 배열
* @param years - 허용할 연도 배열
* @returns 필터링된 데이터 배열
*/
export function filterYearRows<T extends { year: number; rowLabel: string }>(
data: T[],
years: number[]
): T[] {
return data.filter((r) => years.includes(r.year) && r.rowLabel.endsWith("년"));
}
/**
* GroupedOverlayBarData 구조를 생성합니다.
* @param params - 데이터 생성 파라미터
* @returns GroupedOverlayBarData 구조
*/
export function buildOverlayBarData<T extends { year: number; rowLabel: string }>(params: {
totalRows: T[];
focusRows: T[];
productKeys: string[];
years: number[];
totalName?: string;
focusName?: string;
}): {
years: number[];
categories: string[];
totalData: Array<Array<number>>;
focusData: Array<Array<number>>;
totalName: string;
focusName: string;
} {
const {
totalRows,
focusRows,
productKeys,
years,
totalName = "전체",
focusName = "LG",
} = params;
const yearIndexMap = createYearIndexMap(years);
const total: Array<Array<number>> = years.map(() => Array(productKeys.length).fill(0));
const focus: Array<Array<number>> = years.map(() => Array(productKeys.length).fill(0));
// totalRows에서 데이터 매핑
const filteredTotal = filterYearRows(totalRows, years);
for (const row of filteredTotal) {
const yi = yearIndexMap.get(row.year);
if (yi === undefined) continue;
for (let pi = 0; pi < productKeys.length; pi++) {
const key = productKeys[pi];
const val = (row as any)[key];
if (typeof val === "number") {
total[yi][pi] = val;
}
}
}
// focusRows에서 데이터 매핑
const filteredFocus = filterYearRows(focusRows, years);
for (const row of filteredFocus) {
const yi = yearIndexMap.get(row.year);
if (yi === undefined) continue;
for (let pi = 0; pi < productKeys.length; pi++) {
const key = productKeys[pi];
const val = (row as any)[key];
if (typeof val === "number") {
focus[yi][pi] = val;
}
}
}
return {
years,
categories: productKeys,
totalData: total,
focusData: focus,
totalName,
focusName,
};
}
const shouldExcludeLabel = (excludeRowLabels: string[], label: string) =>
excludeRowLabels.some((el) => label.includes(el));
type Opts = {
/** 기본: ["사례수", "gap"] 제외 */
excludeRowLabels?: string[];
/** 기본: (y) => `${y}년` */
yearLabel?: (y: string) => string;
/** StackBar에 넣을 때 "스택 방지"용(연도별 stack 분리) */
splitStackByYear?: boolean;
};
export function buildYearSeriesChartData(rows: BannerRow[], opts: Opts = {}): ChartData {
const {
excludeRowLabels = ["사례수", "gap"],
yearLabel = (y) => `${y}년`,
splitStackByYear = false,
} = opts;
const years = Array.from(new Set(rows.map((r) => r.year))).sort((a, b) => Number(a) - Number(b));
const baseYear = years[0];
const baseLabels = rows
.filter((r) => r.year === baseYear)
.map((r) => r.rowLabel)
.filter((l) => !shouldExcludeLabel(excludeRowLabels, l));
const labels =
baseLabels.length > 0
? baseLabels
: Array.from(new Set(rows.map((r) => r.rowLabel).filter((l) => !shouldExcludeLabel(excludeRowLabels, l))));
const map = new Map<string, Map<string, number>>();
for (const y of years) map.set(y, new Map());
for (const r of rows) {
if (shouldExcludeLabel(excludeRowLabels, r.rowLabel)) continue;
map.get(r.year)?.set(r.rowLabel, Number(r.total ?? 0));
}
return {
categories: labels,
series: years.map((y) => ({
name: yearLabel(y),
data: labels.map((lbl) => map.get(y)?.get(lbl) ?? null),
...(splitStackByYear ? { stack: String(y) } : {}),
})),
};
}
export function buildRowLabelSeriesChartData(
rows: BannerRow[],
opts: Opts = {}
): ChartData {
const {
excludeRowLabels = ["사례수", "gap"],
yearLabel = (y) => `${y}년`,
} = opts;
const years = Array.from(new Set(rows.map((r) => r.year))).sort((a, b) => Number(a) - Number(b));
const categories = years.map(yearLabel);
const baseYear = years[0];
const baseRowLabels = rows
.filter((r) => r.year === baseYear)
.map((r) => r.rowLabel)
.filter((l) => !shouldExcludeLabel(excludeRowLabels, l));
const rowLabels =
baseRowLabels.length > 0
? baseRowLabels
: Array.from(
new Set(rows.map((r) => r.rowLabel).filter((l) => !shouldExcludeLabel(excludeRowLabels, l)))
);
// (year -> (rowLabel -> total)) 맵
const valueMap = new Map<string, Map<string, number>>();
for (const y of years) valueMap.set(y, new Map());
for (const r of rows) {
if (shouldExcludeLabel(excludeRowLabels, r.rowLabel)) continue;
valueMap.get(r.year)!.set(r.rowLabel, Number(r.total ?? 0));
}
return {
categories,
series: rowLabels.map((lbl) => ({
name: lbl,
data: years.map((y) => valueMap.get(y)!.get(lbl) ?? null),
})),
};
}
export const buildGapRow = (
rows: BannerRow[],
prevYear: number,
curYear: number,
baseRowLabel: string,
gapRowLabel = "gap"
): BannerRow | null => {
const prev = rows.find(r => Number(r.year) === prevYear && r.rowLabel === baseRowLabel);
const cur = rows.find(r => Number(r.year) === curYear && r.rowLabel === baseRowLabel);
if (!prev || !cur) return null;
const gap: BannerRow = {
year: String(curYear),
rowLabel: gapRowLabel,
total: String(Number(cur.total) - Number(prev.total)),
};
// cur가 가진 모든 key를 돌면서 "숫자 필드"면 diff 계산
(Object.keys(cur) as Array<keyof BannerRow>).forEach((k) => {
if (k === "year" || k === "rowLabel") return;
const vCur = cur[k];
const vPrev = prev[k];
(gap as any)[k] = String(Number(vCur) - Number(vPrev));
});
return gap;
}
export const isBannerGroupKey = (v: string): v is BannerGroupKey => v in BANNER_GROUP;
export function buildBannerGroupColumns<T extends Record<string, unknown>>(
group: BannerGroupDefinition,
keyLabelMap: Record<string, string>,
options: {
width?: number | string;
numeric?: boolean;
resolveLeafMeta?: (key: string, index: number, total: number) => {
headerClassName?: string;
cellClassName?: string;
};
} = {}
): DataColumn<T>[] {
const leafKeys = flattenBannerGroupKeys(group.children);
let leafIndex = 0;
const visit = (nodes: readonly BannerGroupNode[]): DataColumn<T>[] =>
nodes.map((node) => {
if (node.type === "leaf") {
const currentLeafIndex = leafIndex++;
const meta = options.resolveLeafMeta?.(node.key, currentLeafIndex, leafKeys.length);
return {
key: node.key as keyof T,
header: keyLabelMap[node.key] ?? String(node.key),
numeric: options.numeric,
width: options.width,
headerClassName: meta?.headerClassName,
cellClassName: meta?.cellClassName,
};
}
return {
id: node.id,
header: node.label,
children: visit(node.children),
};
});
return visit(group.children);
}
export const fetchProductStatistics = (req: StatisticsRequest) =>
nextApi.post<ProductResponse>("/statistics/product", req);
export const fetchBannerStatistics = (req: StatisticsRequest) =>
nextApi.post<BannerResponse>("/statistics/banner", req);
type FilterInput =
| Record<string, unknown>
| Map<string, unknown>
| null
| undefined;
export function normalizeFilterCondition(
input: FilterInput,
upToZero: boolean = true
): Record<string, number[]> | undefined {
if (!input) return undefined;
const entries =
input instanceof Map ? Array.from(input.entries()) : Object.entries(input);
const out: Record<string, number[]> = {};
for (const [k, v] of entries) {
if (!k || v == null) continue;
const nums: number[] = [];
const pushNum = (x: unknown) => {
if (x == null) return;
const pushIfValid = (n: number) => {
if (!Number.isFinite(n)) return;
if (upToZero && n === 0) return; // upToZero=true일 때만 0 제외
nums.push(n);
};
if (typeof x === "number") {
pushIfValid(x);
return;
}
if (typeof x === "string") {
const parts = x
.split(/[,\|]/g)
.map((s) => s.trim())
.filter(Boolean);
for (const p of parts) {
pushIfValid(Number(p));
}
}
};
if (Array.isArray(v)) {
for (const item of v) pushNum(item);
} else {
pushNum(v);
}
if (nums.length > 0) out[k] = nums;
}
return Object.keys(out).length ? out : undefined;
}
export const buildCategoryFilter = (
filterValue:CategoryFilterValue
): Record<string, number[]> | undefined => {
const out: Record<string, number[]> = {};
const productCode = filterValue.product.split("#").at(-1);
if (productCode) {
out["product"] = [Number(productCode)];
}
return Object.keys(out).length ? out : undefined;
}
const fixedDecimalPoint = (n: number, decimalPoint?: number): string => {
decimalPoint ??= API_DECIMAL_POINT;
return n.toFixed(decimalPoint);
};
export const roundNumber = (num: number|null, decimalPoint?: number) => {
if(num == null) return null;
decimalPoint ??= VIEW_DECIMAL_POINT;
const factor = 10 ** decimalPoint;
return Math.round(num * factor) / factor;
};
export const calcGapProductRow = (after: ProductRow, before: ProductRow): ProductRow => {
const out: ProductRow = {
year: after?.year ?? "",
rowLabel: "gap",
total: fixedDecimalPoint(Number(after?.total ?? "0") - Number(before?.total ?? "0")),
};
for (const k of PRODUCT_KEYS) {
const a = after? after[k] ?? "0" : "0";
const b = before? before[k] ?? "0" : "0";
out[k] = fixedDecimalPoint(Number(a) - Number(b));
}
return out;
};
export const calcGapBannerRow = (after: BannerRow, before: BannerRow): BannerRow => {
const out: BannerRow = {
year: after?.year ?? "",
rowLabel: "gap",
total: fixedDecimalPoint(Number(after?.total ?? "0") - Number(before?.total ?? "0")),
};
for (const k of BANNER_KEYS) {
const a = after? after[k] ?? "0" : "0";
const b = before? before[k] ?? "0" : "0";
out[k] = fixedDecimalPoint(Number(a) - Number(b));
}
return out;
};
const calcCagr = (after: number, before: number, years:number): number => {
const power = Math.pow(after / before, 1 / years);
const cagr = power - 1;
const cagr100 = cagr * 100;
return cagr100;
};
export const calcCagrRow = (after: ProductRow, before: ProductRow): ProductRow => {
const years = 2; // 24 -> 26
const out: ProductRow = {
year: after?.year ?? "",
rowLabel: "CAGR",
total: "0"
};
// total은 참고용으로만: (26/24) CAGR %
out.total =
fixedDecimalPoint((before?.total ?? "0") > "0" ? calcCagr(Number(after?.total ?? "0"), Number(before?.total ?? "0"), years) : 0, 1);
for (const k of PRODUCT_KEYS) {
const vBefore = before? before[k] ?? "0" : "0";
const vAfter = after? after[k] ?? "0" : "0";
out[k] = fixedDecimalPoint(Number(vBefore) > 0 ? calcCagr(Number(vAfter), Number(vBefore), years) : 0, 1);
}
return out;
};
export const makeTotalBasePct = (t:number|string, f:number|string):number => {
return Number(t) > 0 ? (Number(f) * 100) / Number(t) : 0;
}
export const calcTotalBaseRow = (label:string, totalRow: ProductRow, targetRow: ProductRow): ProductRow => {
const out: ProductRow = {
year: targetRow?.year ?? "",
//rowLabel: `**조사 년도 ${label} 중 자사제품 비율`,
rowLabel: `**자사제품 비율`,
total: fixedDecimalPoint(makeTotalBasePct(totalRow.total, targetRow.total))
};
for (const k of PRODUCT_KEYS) {
const t = totalRow? totalRow[k] ?? "0" : "0";
const f = targetRow? targetRow[k] ?? "0" : "0";
out[k] = fixedDecimalPoint(makeTotalBasePct(t, f));
}
return out;
}
export const withGapRow = <T>(
rows: T[],
calcGapRow: (last: T, secondLast: T) => T,
lastIndex: number,
secondLastIndex: number,
): T[] => {
const last = rows.at(lastIndex);
const secondLast = rows.at(secondLastIndex);
if (!last || !secondLast) return rows;
return [calcGapRow(last, secondLast), ...rows];
}
export const withCagrRow = <T>(
rows: T[],
calcCagrRow: (last: T, first: T) => T,
lastIndex: number,
firstIndex: number,
): T[] => {
const first = rows.at(firstIndex);
const last = rows.at(lastIndex);
if (!first || !last) return rows;
return [...rows, calcCagrRow(last, first)];
}
export const withTotalBaseRow = <T>(
label:string,
totalRows: T[],
targetRows: T[],
calcTotalBaseRow: (label:string, total: T, target: T) => T
): T[] => {
const totalRow = totalRows.at(-1);
const targetRow = targetRows.at(-1);
if (!totalRow || !targetRow) return targetRows;
const totalBaseRow = calcTotalBaseRow(label, totalRow, targetRow);
return targetRows.length === 0 ? [totalBaseRow] : [targetRows[0], totalBaseRow, ...targetRows.slice(1)];
}
const renderKey = (tpl: string, keyBase: string) => tpl.replaceAll("${keyBase}", keyBase.toLowerCase());
export const buildPageModeConfig = (
filterValue: CategoryFilterValue
):BuildPageModeConfigResult => {
const fields = (CATEGORY_PAGE_FIELDS[filterValue.target.value] ?? [])
.filter((f) => !!f.qidByMode[filterValue.type.value])
.map((f) => ({
...f,
requestKeyResolved: renderKey(f.requestKey, filterValue.type.value),
qid: f.qidByMode[filterValue.type.value]!,
}));
const variableIdMap = Object.fromEntries(fields.map((f) => [f.requestKeyResolved, f.qid])) as Record<string, string>;
return { fields, variableIdMap };
};

721
src/lib/lg-export-excel.ts Normal file
View File

@@ -0,0 +1,721 @@
// exportDashboardExcel.ts
"use client";
import { buildBannerGroupColumns, formatRowLabel } from "@/lib/lg-dashboard";
import { DataColumn, GaugeColumn } from "@/components/lge-dashboard";
import { buildHeaderRows, getLeafColumns, type TableColumnNode } from "@/components/lge-dashboard/table/core/table-core.helpers";
import type { BannerGroupDefinition } from "@/const/lg-banner.const";
/**
* 요구사항:
* - 한 파일에 (1) PRODUCT_KEY_MAP 헤더, (2) LIFE_STAGE_COLUMNS 헤더, (3) BANNER_GROUP 헤더를 함께 지원
* - Excel export는 한 시트에 여러 섹션을 순서대로 기록
* - 헤더 스타일:
* group: background = --lg-gray-400
* header: background = --lg-gray-600
* font: #fff, bold
*/
type HeaderStyleKey = "group" | "header";
type HeaderCell = {
text: string;
styleKey: HeaderStyleKey;
rowSpan?: number; // default 1
colSpan?: number; // default 1
align?: "left" | "center" | "right";
};
type HeaderBlock = {
headerRows: HeaderCell[][];
leafKeys: string[]; // 실제 데이터 컬럼 key 순서(좌->우)
totalCols: number;
};
export type Section<T extends Record<string, any>> = {
title?: string;
header: HeaderBlock;
rows: T[];
rowGap?: number; // default 1
// 옵션
colWidthByKey?: Record<string, number>;
numFmtByKey?: Record<string, string>; // 예: "#,##0", "0.0", "0%"
alignByKey?: Record<string, "left" | "center" | "right">;
valueGetter?: (row: T, key: string) => any;
};
type ExportOptions<T extends Record<string, any>> = {
fileName?: string;
sheetName?: string;
sections: Section<T>[];
// CSS 변수(없으면 기본값)
groupBgVar?: string; // default "--lg-gray-400"
headerBgVar?: string; // default "--lg-gray-600"
borderVar?: string; // default "--lg-gray-300"
};
/* =========================================================
* 0) Object.entries 타입 보존
* ========================================================= */
const typedEntries = <T extends Record<string, any>>(obj: T) =>
Object.entries(obj) as Array<[keyof T, T[keyof T]]>;
/* =========================================================
* 1) CSS var -> Excel ARGB (HSL 토큰 "H S% L%" 지원)
* ========================================================= */
type RGB = { r: number; g: number; b: number };
function clamp255(n: number) {
return Math.max(0, Math.min(255, Math.round(n)));
}
function hslTokenToRgb(token: string): RGB | null {
const m = token.trim().match(/^([\d.]+)\s+([\d.]+)%\s+([\d.]+)%$/);
if (!m) return null;
const h = parseFloat(m[1]) % 360;
const s = parseFloat(m[2]) / 100;
const l = parseFloat(m[3]) / 100;
const C = (1 - Math.abs(2 * l - 1)) * s;
const hh = h / 60;
const X = C * (1 - Math.abs((hh % 2) - 1));
let r1 = 0, g1 = 0, b1 = 0;
if (0 <= hh && hh < 1) [r1, g1, b1] = [C, X, 0];
else if (1 <= hh && hh < 2) [r1, g1, b1] = [X, C, 0];
else if (2 <= hh && hh < 3) [r1, g1, b1] = [0, C, X];
else if (3 <= hh && hh < 4) [r1, g1, b1] = [0, X, C];
else if (4 <= hh && hh < 5) [r1, g1, b1] = [X, 0, C];
else if (5 <= hh && hh < 6) [r1, g1, b1] = [C, 0, X];
const m2 = l - C / 2;
return {
r: clamp255((r1 + m2) * 255),
g: clamp255((g1 + m2) * 255),
b: clamp255((b1 + m2) * 255),
};
}
function hexToRgb(hex: string): RGB | null {
const v = hex.trim();
if (!v.startsWith("#")) return null;
const h = v.slice(1);
const full = h.length === 3 ? h.split("").map((c) => c + c).join("") : h;
if (full.length !== 6) return null;
return {
r: parseInt(full.slice(0, 2), 16),
g: parseInt(full.slice(2, 4), 16),
b: parseInt(full.slice(4, 6), 16),
};
}
function rgbToArgb(rgb: RGB) {
const toHex2 = (n: number) => n.toString(16).padStart(2, "0").toUpperCase();
return `FF${toHex2(rgb.r)}${toHex2(rgb.g)}${toHex2(rgb.b)}`;
}
function cssVarToExcelArgb(varName: string, fallbackHex = "#DDDDDD") {
const raw = getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
const rgb = hslTokenToRgb(raw) ?? hexToRgb(raw) ?? hexToRgb(fallbackHex)!;
return rgbToArgb(rgb);
}
/* =========================================================
* 2) 헤더 렌더러 (row/col merge + 스타일)
* ========================================================= */
type StylePack = {
groupBg: string; // ARGB
headerBg: string; // ARGB
headerFont: string; // ARGB (white)
border: string; // ARGB
};
function writeMergedHeader(
ws: any, // ExcelJS.Worksheet
startRow: number,
headerRows: HeaderCell[][],
styles: StylePack
) {
const occupied = new Set<string>(); // "r,c" (0-based within header block)
const isOcc = (r: number, c: number) => occupied.has(`${r},${c}`);
const markOcc = (r: number, c: number) => occupied.add(`${r},${c}`);
const styleOf = (styleKey: HeaderStyleKey) => {
const bg = styleKey === "group" ? styles.groupBg : styles.headerBg;
return {
fill: { type: "pattern", pattern: "solid", fgColor: { argb: bg } },
font: { color: { argb: styles.headerFont }, bold: true },
alignment: { vertical: "middle", wrapText: true },
border: {
top: { style: "thin", color: { argb: styles.border } },
left: { style: "thin", color: { argb: styles.border } },
bottom: { style: "thin", color: { argb: styles.border } },
right: { style: "thin", color: { argb: styles.border } },
},
};
};
const applyStyleRange = (r1: number, c1: number, r2: number, c2: number, st: any) => {
for (let rr = r1; rr <= r2; rr++) {
const row = ws.getRow(rr);
for (let cc = c1; cc <= c2; cc++) {
const cell = row.getCell(cc);
cell.style = { ...(cell.style ?? {}), ...st };
}
}
};
for (let hr = 0; hr < headerRows.length; hr++) {
const rowCells = headerRows[hr];
let colCursor = 0;
for (const hc of rowCells) {
const rs = hc.rowSpan ?? 1;
const cs = hc.colSpan ?? 1;
while (isOcc(hr, colCursor)) colCursor++;
const topRow = startRow + hr;
const leftCol = colCursor + 1; // excel 1-based
const bottomRow = topRow + rs - 1;
const rightCol = leftCol + cs - 1;
const cell = ws.getRow(topRow).getCell(leftCol);
cell.value = hc.text;
const st = styleOf(hc.styleKey);
const horiz = hc.align ?? "center";
cell.alignment = { ...(st.alignment ?? {}), horizontal: horiz };
if (rs > 1 || cs > 1) ws.mergeCells(topRow, leftCol, bottomRow, rightCol);
applyStyleRange(topRow, leftCol, bottomRow, rightCol, {
...st,
alignment: { ...(st.alignment ?? {}), horizontal: horiz },
});
for (let r = hr; r < hr + rs; r++) {
for (let c = colCursor; c < colCursor + cs; c++) {
markOcc(r, c);
}
}
colCursor += cs;
}
ws.getRow(startRow + hr).height = 20;
}
return startRow + headerRows.length;
}
type AutoFitOpt = {
minColWidth?: number; // Excel column width units
maxColWidth?: number;
padding?: number; // width 여유(문자수 기준)
baseRowHeight?: number; // pt
maxRowHeight?: number; // pt
useCanvasMeasure?: boolean; // 브라우저에서 measureText로 더 정확하게
};
function autoFitApprox(ws: any, opt: AutoFitOpt = {}) {
const o: Required<AutoFitOpt> = {
minColWidth: opt.minColWidth ?? 8,
maxColWidth: opt.maxColWidth ?? 60,
padding: opt.padding ?? 2,
baseRowHeight: opt.baseRowHeight ?? 15,
maxRowHeight: opt.maxRowHeight ?? 120,
useCanvasMeasure: opt.useCanvasMeasure ?? true,
};
// 1) 머지 정보(내부 필드 사용: ExcelJS에서 공식 API가 없어서 근사 구현용)
const mergeMap = buildMergeMap(ws);
// 2) 컬럼 폭 먼저 계산
fitColumns(ws, mergeMap, o);
// 3) 그 다음 row height 계산 (wrapText/줄바꿈 고려)
fitRows(ws, mergeMap, o);
}
/* ---------------------------
* Column fit
* --------------------------- */
function fitColumns(ws: any, mergeMap: Map<string, MergeInfo>, o: Required<AutoFitOpt>) {
const colCount = ws.columnCount ?? (ws.columns?.length ?? 0);
const widths = new Array<number>(colCount + 1).fill(o.minColWidth);
ws.eachRow({ includeEmpty: false }, (row: any) => {
row.eachCell({ includeEmpty: false }, (cell: any, colNumber: number) => {
const text = getCellText(cell);
if (!text) return;
// merged cell의 "master"만 처리 (중복 방지)
const masterAddr = getMasterAddress(cell);
const mi = mergeMap.get(masterAddr);
if (mi && cell.address !== masterAddr) return;
const w = estimateWidth(text, cell, o); // width in "excel-char-like units"
if (mi && mi.colSpan > 1) {
// 머지된 텍스트는 span만큼 나눠서 분배(한 컬럼 폭이 과대해지는 현상 방지)
const perCol = w / mi.colSpan;
for (let c = mi.leftCol; c <= mi.rightCol; c++) {
widths[c] = Math.max(widths[c], perCol);
}
} else {
widths[colNumber] = Math.max(widths[colNumber], w);
}
});
});
for (let c = 1; c <= colCount; c++) {
ws.getColumn(c).width = clamp(widths[c] + o.padding, o.minColWidth, o.maxColWidth);
}
}
/* ---------------------------
* Row fit
* --------------------------- */
function fitRows(ws: any, mergeMap: Map<string, MergeInfo>, o: Required<AutoFitOpt>) {
ws.eachRow({ includeEmpty: false }, (row: any) => {
let maxLines = 1;
row.eachCell({ includeEmpty: false }, (cell: any, colNumber: number) => {
const text = getCellText(cell);
if (!text) return;
const masterAddr = getMasterAddress(cell);
const mi = mergeMap.get(masterAddr);
if (mi && cell.address !== masterAddr) return;
const wrap = !!cell.alignment?.wrapText;
const explicitLines = text.split(/\r?\n/);
if (!wrap && explicitLines.length <= 1) return;
// 해당 셀의 사용 가능한 폭(머지면 합산)
const availableWidth = mi
? sumColumnWidth(ws, mi.leftCol, mi.rightCol, o)
: getColumnWidth(ws, colNumber, o);
// 각 라인별로 줄바꿈이 몇 줄로 늘어나는지 근사
let cellLines = 0;
for (const line of explicitLines) {
const lineW = estimateWidth(line, cell, o);
const needed = Math.max(1, Math.ceil(lineW / Math.max(1, availableWidth)));
cellLines += needed;
}
maxLines = Math.max(maxLines, cellLines);
});
const h = clamp(o.baseRowHeight * maxLines, o.baseRowHeight, o.maxRowHeight);
row.height = Math.max(row.height, h);
});
}
/* ---------------------------
* Width estimation
* --------------------------- */
function estimateWidth(text: string, cell: any, o: Required<AutoFitOpt>) {
// 줄바꿈이면 가장 긴 라인 기준(컬럼 폭은 max line)
const lines = text.split(/\r?\n/);
const maxLine = lines.reduce((m, s) => (s.length > m.length ? s : m), "");
if (o.useCanvasMeasure && typeof document !== "undefined") {
const px = measureTextPx(maxLine, cell);
// Excel column width 단위는 폰트마다 다르지만 Calibri 11 기준으로 px/7 정도를 사용
return px / 7;
}
// canvas를 못 쓰는 환경이면 문자 폭 가중치로 근사
return estimateByCharWeight(maxLine);
}
function measureTextPx(text: string, cell: any) {
const canvas = getMeasureCanvas();
const ctx = canvas.getContext("2d")!;
const fontName = cell.font?.name ?? "Calibri";
const size = cell.font?.size ?? 11;
const bold = cell.font?.bold ? "bold " : "";
ctx.font = `${bold}${size}pt ${fontName}`;
return ctx.measureText(text).width;
}
let __canvas: HTMLCanvasElement | null = null;
function getMeasureCanvas() {
if (!__canvas) __canvas = document.createElement("canvas");
return __canvas;
}
// 한글/CJK wide char 가중치 + 숫자/영문 가중치
function estimateByCharWeight(s: string) {
let w = 0;
for (const ch of s) {
if (isWideChar(ch)) w += 1.7; // 한글/한자/가나 등
else if (ch === " ") w += 0.6;
else if (/[A-Z]/.test(ch)) w += 1.1;
else if (/[0-9]/.test(ch)) w += 1.0;
else w += 0.9;
}
return w;
}
function isWideChar(ch: string) {
const code = ch.codePointAt(0) ?? 0;
// 대략적인 CJK 범위
return (
(code >= 0x1100 && code <= 0x11ff) || // Hangul Jamo
(code >= 0x2e80 && code <= 0x9fff) || // CJK, radicals
(code >= 0xac00 && code <= 0xd7af) || // Hangul syllables
(code >= 0x3040 && code <= 0x30ff) || // Hiragana/Katakana
(code >= 0xff00 && code <= 0xffef) // Fullwidth forms
);
}
/* ---------------------------
* Helpers: cell text
* --------------------------- */
function getCellText(cell: any): string {
const v = cell?.value;
if (v === null || v === undefined) return "";
if (typeof v === "string") return v;
if (typeof v === "number" || typeof v === "boolean") return String(v);
if (v instanceof Date) return v.toISOString().slice(0, 10);
// ExcelJS value object types
if (typeof v === "object") {
if (v.richText) return v.richText.map((t: any) => t.text).join("");
if (v.text) return String(v.text);
if (v.formula) return v.result != null ? String(v.result) : "";
if (v.hyperlink) return String(v.text ?? v.hyperlink);
}
return String(v);
}
function getMasterAddress(cell: any) {
// merged cell이면 master가 존재
if (cell?.isMerged && cell?.master?.address) return cell.master.address;
return cell.address;
}
/* ---------------------------
* Helpers: widths
* --------------------------- */
function getColumnWidth(ws: any, col: number, o: Required<AutoFitOpt>) {
const w = ws.getColumn(col)?.width;
return typeof w === "number" ? w : o.minColWidth;
}
function sumColumnWidth(ws: any, left: number, right: number, o: Required<AutoFitOpt>) {
let sum = 0;
for (let c = left; c <= right; c++) sum += getColumnWidth(ws, c, o);
return sum;
}
function clamp(v: number, min: number, max: number) {
return Math.max(min, Math.min(max, v));
}
/* ---------------------------
* Merge map (internal _merges parsing)
* --------------------------- */
type MergeInfo = {
leftCol: number;
rightCol: number;
topRow: number;
bottomRow: number;
colSpan: number;
};
function buildMergeMap(ws: any) {
const map = new Map<string, MergeInfo>();
const merges = ws?._merges;
if (!merges) return map;
// ws._merges: Map<string, any> 형태인 경우가 많고 key는 "A1:C1" 같은 range
const keys: string[] =
merges instanceof Map ? Array.from(merges.keys()) : Object.keys(merges);
for (const range of keys) {
const parsed = parseRange(range);
if (!parsed) continue;
const masterAddr = toA1(parsed.leftCol, parsed.topRow);
map.set(masterAddr, {
...parsed,
colSpan: parsed.rightCol - parsed.leftCol + 1,
});
}
return map;
}
// "A1:C3" -> 醫뚰몴
function parseRange(range: string): Omit<MergeInfo, "colSpan"> | null {
const parts = range.split(":");
if (parts.length !== 2) return null;
const a = parseA1(parts[0]);
const b = parseA1(parts[1]);
if (!a || !b) return null;
return {
leftCol: Math.min(a.col, b.col),
rightCol: Math.max(a.col, b.col),
topRow: Math.min(a.row, b.row),
bottomRow: Math.max(a.row, b.row),
};
}
function parseA1(a1: string): { col: number; row: number } | null {
const m = a1.match(/^([A-Z]+)(\d+)$/i);
if (!m) return null;
const col = lettersToCol(m[1].toUpperCase());
const row = parseInt(m[2], 10);
return { col, row };
}
function lettersToCol(letters: string) {
let n = 0;
for (const ch of letters) {
n = n * 26 + (ch.charCodeAt(0) - 64);
}
return n;
}
function toA1(col: number, row: number) {
return `${colToLetters(col)}${row}`;
}
function colToLetters(col: number) {
let n = col;
let s = "";
while (n > 0) {
const r = (n - 1) % 26;
s = String.fromCharCode(65 + r) + s;
n = Math.floor((n - 1) / 26);
}
return s;
}
/* =========================================================
* 3) 헤더 빌더
* ========================================================= */
/**
* (1) PRODUCT_KEY_MAP:
* - 첫 칸 비움
* - 나머지는 일반 헤더
*/
export function buildHeader_ProductKeyMap(
productKeyMap: Record<string, string>,
sampleHeadKey? :string,
rowHeadKey = "rowLabel"
): HeaderBlock {
const entries = typedEntries(productKeyMap);
const headerRow: HeaderCell[] = [
{ text: "", styleKey: "header", align: "center" },
...(sampleHeadKey
? [{ text: "사례수", styleKey: "header", align: "center" } as const]
: []),
...entries.map(([, label]) => ({
text: String(label),
styleKey: "header" as const,
align: "center" as const,
})),
];
const leafKeys = [rowHeadKey, ...(sampleHeadKey? [sampleHeadKey]: []), ...entries.map(([k]) => String(k))];
return { headerRows: [headerRow], leafKeys, totalCols: headerRow.length };
}
/**
* (2) LIFE_STAGE_COLUMNS:
* - 트리 기반 컬럼에서 header row를 계산
* - HTML 테이블과 동일한 merge 구조를 Excel에 적용
*/
function buildHeaderBlockFromColumns<T>(cols: TableColumnNode<T>[]): HeaderBlock {
const headerRows = buildHeaderRows(cols).map((row) =>
row.map((cell) => ({
text: cell.label,
styleKey: (cell.isLeaf ? "header" : "group") as HeaderStyleKey,
rowSpan: cell.rowSpan,
colSpan: cell.colSpan,
align: "center" as const,
}))
);
const leafKeys = getLeafColumns(cols).map((column) => String(column.key));
return { headerRows, leafKeys, totalCols: leafKeys.length };
}
export function buildHeader_LifeStageColumns<T>(cols: GaugeColumn<T>[]): HeaderBlock {
return buildHeaderBlockFromColumns(cols);
}
export function buildHeader_DataColumn<T>(cols: DataColumn<T>[]): HeaderBlock {
return buildHeaderBlockFromColumns(cols);
}
/**
* (3) BANNER_GROUP + BANNER_KEY_MAP:
* - A1: "" (rowspan2)
* - B1: "전체" (rowspan2) key=total
* - C1~: group(label) (colSpan = keys.ts.length)
* - 2행: 각 key의 라벨(BANNER_KEY_MAP[key])
*/
export function buildHeader_Banner<K extends string>(
bannerGroup: Record<string, BannerGroupDefinition>,
bannerKeyMap: Record<K, string>,
rowHeadKey = "rowLabel",
totalKey = "total"
): HeaderBlock {
const columns: DataColumn<Record<string, unknown>>[] = [
{ key: rowHeadKey, header: "" },
{ key: totalKey, header: "전체" },
...Object.entries(bannerGroup).map(([groupKey, group]) => ({
id: `banner-${groupKey}`,
header: group.label,
children: buildBannerGroupColumns<Record<string, unknown>>(group, bannerKeyMap),
})),
];
return buildHeaderBlockFromColumns(columns);
}
/* =========================================================
* 4) Export (one sheet, 섹션 간 1행 띄움)
* ========================================================= */
export async function exportDashboardExcel<T extends Record<string, any>>(opts: ExportOptions<T>) {
const {
fileName = "export.xlsx",
sheetName = "Export",
sections,
groupBgVar = "--lg-gray-400",
headerBgVar = "--lg-gray-600",
borderVar = "--lg-gray-300",
} = opts;
// ExcelJS import (환경에 따라 min 빌드가 더 잘 동작하는 경우가 있음)
const ExcelJS = await import("exceljs");
const wb = new ExcelJS.Workbook();
const ws = wb.addWorksheet(sheetName);
const stylePack: StylePack = {
groupBg: cssVarToExcelArgb(groupBgVar, "#9CA3AF"),
headerBg: cssVarToExcelArgb(headerBgVar, "#4B5563"),
headerFont: "FFFFFFFF", // #fff
border: cssVarToExcelArgb(borderVar, "#D1D5DB"),
};
let rowCursor = 1;
for (const sec of sections) {
const gap = sec.rowGap ?? 1;
const { header, rows } = sec;
// 섹션 타이틀
if (sec.title) {
const r = ws.getRow(rowCursor);
const c = r.getCell(1);
c.value = sec.title;
c.font = { bold: true, size: 13 };
r.height = 22;
if (header.totalCols > 1) ws.mergeCells(rowCursor, 1, rowCursor, header.totalCols);
rowCursor += 1;
}
// 헤더
rowCursor = writeMergedHeader(ws, rowCursor, header.headerRows, stylePack);
// 컬럼 width
if (sec.colWidthByKey) {
header.leafKeys.forEach((k, idx) => {
const w = sec.colWidthByKey?.[k];
if (w) ws.getColumn(idx + 1).width = w;
});
} else {
// 기본: 첫 컬럼 넓게, 나머지 적당히
header.leafKeys.forEach((_k, idx) => {
ws.getColumn(idx + 1).width = idx === 0 ? 22 : 14;
});
}
const valueGetter = sec.valueGetter ?? ((r: T, k: string) => (r as any)[k]);
// 데이터
for (const row of rows) {
const excelRow = ws.getRow(rowCursor);
//const sampleRow = isSampleRow(valueGetter(row, header.leafKeys.at(0) ?? ""));
header.leafKeys.forEach((key, idx) => {
const cell = excelRow.getCell(idx + 1);
const v = valueGetter(row, key);
const isColHeader = idx === 0;
if (v === null || v === undefined || v === "") cell.value = null;
else if (typeof v === "number") cell.value = v;
else if (isColHeader) cell.value = formatRowLabel(String(v));
//else if (sampleRow) cell.value = `(${String(v)})`;
else cell.value = String(v);
const align =
sec.alignByKey?.[key] ??
(typeof v === "number" ? "right" : "left");
cell.alignment = { vertical: "middle", horizontal: align, wrapText: true };
const numFmt = sec.numFmtByKey?.[key];
if (numFmt) cell.numFmt = numFmt;
cell.border = {
top: { style: "thin", color: { argb: stylePack.border } },
left: { style: "thin", color: { argb: stylePack.border } },
bottom: { style: "thin", color: { argb: stylePack.border } },
right: { style: "thin", color: { argb: stylePack.border } },
};
if(isColHeader){
cell.font = { bold: true };
}
});
excelRow.height = 18;
rowCursor += 1;
}
rowCursor += gap;
}
autoFitApprox(ws, {
minColWidth: 8,
maxColWidth: 55,
baseRowHeight: 15,
maxRowHeight: 120,
useCanvasMeasure: true,
});
// 다운로드
const buf = await wb.xlsx.writeBuffer();
const blob = new Blob([buf], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = fileName;
a.click();
URL.revokeObjectURL(url);
}

View File

@@ -18,9 +18,3 @@ const createServerApi = async (rootUrl: string, defaultHeaders?: Record<string,
export const createBackApi = () => { export const createBackApi = () => {
return createServerApi(serverEnv.API_BACK_SERVER); return createServerApi(serverEnv.API_BACK_SERVER);
} }
export const createKartApi = () => {
return createServerApi(serverEnv.API_KART_SERVER, {
"X-API-Key": serverEnv.KART_API_KEY,
});
};

View File

@@ -100,3 +100,61 @@ export const formatKst = (
}; };
export const isBlank = (v?: string | null) => !v || v.trim().length === 0; export const isBlank = (v?: string | null) => !v || v.trim().length === 0;
export const norm = (s: string) => s.replace(/\s+/g, "").toLowerCase();
export const asNum = (v: unknown): number | null => typeof v === "number" && Number.isFinite(v) ? v : null;
export const formatNumber = (v: number) =>
Number.isInteger(v) ? v.toLocaleString() : v.toLocaleString(undefined, { maximumFractionDigits: 1 });
/**
* 다양한 형식의 값을 숫자로 파싱합니다.
* - 쉼표, 퍼센트, 유니코드 마이너스 자동 처리
* - null/undefined/빈문자열/"−" 등은 null 반환
* - 유한하지 않은 숫자는 null 반환
*/
export function parseNumber(
value: unknown,
options?: {
allowComma?: boolean; // 기본값: true
allowPercent?: boolean; // 기본값: true
allowMinus?: boolean; // 기본값: true (유니코드 마이너스 포함)
}
): number | null {
const { allowComma = true, allowPercent = true, allowMinus = true } = options ?? {};
if (value === null || value === undefined) return null;
if (typeof value === "number") {
return Number.isFinite(value) ? value : null;
}
if (typeof value === "string") {
let s = value.trim();
if (s === "" || s === "-" || s === "−") return null;
s = s.replaceAll("(", "");
s = s.replaceAll(")", "");
if (allowComma) s = s.replaceAll(",", "");
if (allowPercent) s = s.replaceAll("%", "");
if (allowMinus) s = s.replaceAll("−", "-"); // 유니코드 마이너스 -> ASCII 마이너스
const n = Number(s);
return Number.isFinite(n) ? n : null;
}
return null;
}
export const toNumOrNull = (v: unknown) => {
if (v == null) return null;
if (v === "-" || v === "") return null;
const n = Number(v);
return Number.isFinite(n) ? n : null;
};
export const toNumOr0 = (v: unknown) => {
const n = Number(v);
return Number.isFinite(n) ? n : 0;
};

32
src/query/keys.ts Normal file
View File

@@ -0,0 +1,32 @@
import type {StatisticsRequest} from "@/types/lg.types";
const sortRecord = <T,>(obj?: Record<string, T> | null): Record<string, T> => {
if (!obj) return {};
return Object.fromEntries(
Object.keys(obj)
.sort()
.map((k) => [k, obj[k]])
);
};
const sortNumberArrayRecord = (obj?: Record<string, number[]> | null): Record<string, number[]> => {
if (!obj) return {};
return Object.fromEntries(
Object.keys(obj)
.sort()
.map((k) => [k, [...(obj[k] ?? [])].sort((a, b) => a - b)])
);
};
const normalizeReqForKey = (req: StatisticsRequest) => ({
variableIdMap: sortRecord(req.variableIdMap),
bannerIdList: [...(req.bannerIdList ?? [])].sort(),
filterCondition: sortNumberArrayRecord(req.filterCondition as any), // normalizeFilterCondition 결과면 Record<string, number[]>
option: req.option ?? null,
});
export const productStatisticsKey = (req: StatisticsRequest) =>
["statistics", "product", normalizeReqForKey(req)] as const;
export const bannerStatisticsKey = (req: StatisticsRequest) =>
["statistics", "banner", normalizeReqForKey(req)] as const;

28
src/query/statistics.ts Normal file
View File

@@ -0,0 +1,28 @@
import {BannerResponse, ProductResponse, StatisticsRequest} from "@/types/lg.types";
import {useQuery} from "@tanstack/react-query";
import {bannerStatisticsKey, productStatisticsKey} from "@/query/keys";
import {fetchBannerStatistics, fetchProductStatistics} from "@/lib/lg-dashboard";
export function useProductStatisticsQuery(req: StatisticsRequest, enabled = true) {
return useQuery<ProductResponse>({
queryKey: productStatisticsKey(req),
queryFn: () => fetchProductStatistics(req),
enabled,
staleTime: 60_000,
gcTime: 10 * 60_000,
});
}
export function useBannerStatisticsQuery(req: StatisticsRequest, enabled = true) {
return useQuery<BannerResponse>({
queryKey: bannerStatisticsKey(req),
queryFn: () => fetchBannerStatistics(req),
enabled,
/*
refetchOnMount: "always",
staleTime: 0,
*/
staleTime: 60_000,
gcTime: 10 * 60_000,
});
}

View File

@@ -1,11 +1,13 @@
export const StorageKeys = { export const StorageKeys = {
AuthState: "kri:authState", AuthState: "kri:authState",
CategoriFilter: "kri:categoryFilter",
//SidebarCollapsed: "kri:sidebarCollapsed", //SidebarCollapsed: "kri:sidebarCollapsed",
// 필요하면 여기 계속 추가 // 필요하면 여기 계속 추가
} as const; } as const;
export const StorageType: Record<StorageKey, "local" | "session"> = { export const StorageType: Record<StorageKey, "local" | "session"> = {
[StorageKeys.AuthState]: "local", [StorageKeys.AuthState]: "local",
[StorageKeys.CategoriFilter]: "local",
}; };
export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys]; export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys];

View File

@@ -3,6 +3,11 @@ export type LoginRequest = {
userPw: string; userPw: string;
}; };
export type LoginResponse = {
accessToken: string;
user: LoginUser;
};
export type LoginUser = { export type LoginUser = {
userId: string; userId: string;
userName: string; userName: string;

View File

@@ -25,4 +25,4 @@ export type PageResponse<T> = {
empty: boolean; empty: boolean;
} }
export type SelectedMap = Record<string, string>; export type SelectedMap = Record<string, string[]>;

Some files were not shown because too many files have changed in this diff Show More