Compare commits

...

180 Commits

Author SHA1 Message Date
afb9ff8fa8 Merge pull request '261119_01_ENH: 리스트 필터 다이얼로그에 필터 초기화 버튼 추가' (#78) from develop into master
Reviewed-on: #78
2026-11-20 15:50:05 +09:00
904bbd6509 261120_01_FIX: 삭제·권한 없는 프로젝트의 리스트 작업 기록이 남아 403이 반복 조회되는 문제 수정 2026-11-20 15:49:06 +09:00
88b36bf27d 261119_01_ENH: 리스트 필터 다이얼로그에 필터 초기화 버튼 추가 2026-11-19 07:23:14 +09:00
a1835bd63a Merge pull request 'develop' (#77) from develop into master
Reviewed-on: #77
2026-11-19 06:59:29 +09:00
359969c13f 261117_05_ENH: @types/node를 배포 서버 Node 24 기준(^24)으로 변경 2026-11-17 10:15:22 +09:00
02a830f3ee 261117_04_ENH: kri-editor를 KriUiRegistry 최신본으로 재설치(React Compiler lint·SonarQube 지적 사항 반영) 2026-11-17 09:54:37 +09:00
27e41c783b 261117_03_ENH: @kri/common 0.20.0 적용 및 cn 0.5.2 고정 2026-11-17 09:26:39 +09:00
db1f12f9aa 261117_02_FIX: Next.js 16.4.6 업그레이드(보안 취약점 대응)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 08:49:12 +09:00
f955dbaeea 261117_01_ENH: KriColorPalette를 KriUiRegistry(kri-color-palette) 설치본으로 교체
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 08:49:12 +09:00
623615a287 261116_03_ENH: KriColorPalette 중첩 삼항 제거 및 Dice UI 출처 주석 추가 2026-11-16 16:54:42 +09:00
e64a48417b 261116_02_ENH: 여러 줄 텍스트(98) 헤더 타입 추가 및 컨택 진행 화면 textarea 입력 적용 2026-11-16 12:29:47 +09:00
f0cf4a3f71 Merge pull request '261112_02_ENH: CTI 통화 이력 복구·재시도 로직 제거 및 시작·종료 저장 단일 요청으로 간소화' (#76) from develop into master
Reviewed-on: #76
2026-11-12 15:20:09 +09:00
606b6e30d0 261112_02_ENH: CTI 통화 이력 복구·재시도 로직 제거 및 시작·종료 저장 단일 요청으로 간소화 2026-11-12 14:01:28 +09:00
d76176ef5b Merge pull request '261112_01_FIX: CTI 종료 이력 저장 404 시 재시도 중단 및 오류 팝업 미노출' (#75) from develop into master
Reviewed-on: #75
2026-11-12 12:08:09 +09:00
4daf2daf9c 261112_01_FIX: CTI 종료 이력 저장 404 시 재시도 중단 및 오류 팝업 미노출 2026-11-12 12:07:13 +09:00
939a112513 Merge pull request 'develop' (#74) from develop into master
Reviewed-on: #74
2026-11-11 08:29:47 +09:00
2d00f7e490 Merge remote-tracking branch 'origin/develop' into develop 2026-11-10 17:29:02 +09:00
d9c76d6d9c 261105_02_ENH: 문자·이메일·알림톡 예약 발송 시 과거 일시 선택 차단 2026-11-10 17:28:51 +09:00
88233f3a39 261105_02_ENH: 문자·이메일·알림톡 예약 발송 시 과거 일시 선택 차단 2026-11-10 17:28:38 +09:00
679a5f4b19 Merge pull request '261105_02_ENH: 문자·이메일·알림톡 예약 발송 시 과거 일시 선택 차단' (#73) from develop into master
Reviewed-on: #73
2026-11-05 12:37:00 +09:00
d595ea8b8c 261105_02_ENH: 문자·이메일·알림톡 예약 발송 시 과거 일시 선택 차단 2026-11-05 12:36:08 +09:00
2338c991d9 Merge pull request '261105_01_FIX: 리스트 헤더 저장 및 업로드 헤더 비교 시 Trim 적용' (#72) from develop into master
Reviewed-on: #72
2026-11-05 11:51:01 +09:00
986f9bf9a9 261105_01_FIX: 리스트 헤더 저장 및 업로드 헤더 비교 시 Trim 적용
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:03:40 +09:00
052fb97a51 Merge pull request 'develop' (#71) from develop into master
Reviewed-on: #71
2026-11-03 16:57:20 +09:00
dd4fc8f230 261103_03_ENH: 공유 인증 사용자 정보 동기화 및 프로젝트 접근 전환 개선 2026-11-03 15:11:33 +09:00
7f9cbe4f09 261103_02_FIX: 다른 서비스와 도메인 인증 겹치지 않도록 키변경 2026-11-03 10:48:30 +09:00
8ef8de9dae Merge pull request '261103_01_FIX: KriAutoComplete 기본 검색을 contains 방식으로 변경' (#70) from develop into master
Reviewed-on: #70
2026-11-03 09:03:23 +09:00
d91fc8f5a8 261103_01_FIX: KriAutoComplete 기본 검색을 contains 방식으로 변경 2026-11-03 08:37:04 +09:00
3b7377a5ab Merge pull request 'develop' (#69) from develop into master
Reviewed-on: #69
2026-11-02 18:35:31 +09:00
491b5a5e9f 261102_07_FIX: 통화 중 새로고침 시 컨택 페이지 이탈 방지 및 CTI 송수신 로그 추가 2026-11-02 18:28:43 +09:00
72c8cdca37 Merge pull request '261028_01_ENH: CTI 통화 재연결 복원 대응 및 종료 우회 처리 정리' (#68) from feature-tera-ws into develop
Reviewed-on: #68
2026-11-02 18:11:05 +09:00
ff9968db2e 261102_06_ENH: 메시지 템플릿 제목·템플릿명·발신자명에 다국어 입력 허용 (이모지 제외) 2026-11-02 17:10:44 +09:00
bfde326316 261102_05_ENH: 환경변수 public끼리 모음 2026-11-02 16:07:54 +09:00
5a82fe6396 261102_04_ENH: 설문현황 KON·KIWI 바로가기를 환경별 KART 프로젝트 URL로 변경 2026-11-02 16:07:03 +09:00
475204b12b 261102_03_ENH: KART와 JWT 쿠키 처리 방식 통일 및 만료 시간 상수화 2026-11-02 15:53:55 +09:00
d17b7316e7 261102_02_ENH: 공용 JWT 쿠키 Domain 적용 조건을 환경변수 값 기준으로 변경 2026-11-02 15:23:06 +09:00
273caf267d 261102_01_ENH: KART 로그인 연동을 위한 공용 JWT 쿠키 설정 및 로그아웃 처리 통일 2026-11-02 15:12:42 +09:00
c575094aad Merge pull request 'develop' (#67) from develop into master
Reviewed-on: #67
2026-11-02 12:12:55 +09:00
50a0cb1ef5 261029_01_ENH: 이메일·문자·알림톡 템플릿 삭제 기능 추가 및 삭제 2026-11-02 12:07:06 +09:00
07e70d1f44 Merge pull request '261029_01_ENH: 이메일·문자·알림톡 템플릿 삭제 기능 추가 및 삭제' (#66) from master into develop
Reviewed-on: #66
2026-10-29 09:05:04 +09:00
e67d57c51a 261029_01_ENH: 이메일·문자·알림톡 템플릿 삭제 기능 추가 및 삭제 2026-10-29 09:04:06 +09:00
98546a83fd Merge pull request '261028_03_HOT: 헤더관리에서 사용 허용, 외주사, 컨택원, 면접원은 disabled처리' (#65) from master into develop
Reviewed-on: #65
2026-10-28 17:12:29 +09:00
55c988ce20 261028_03_HOT: 헤더관리에서 사용 허용, 외주사, 컨택원, 면접원은 disabled처리 2026-10-28 17:10:18 +09:00
61ac9420c9 Merge pull request 'master' (#64) from master into develop
Reviewed-on: #64
2026-10-28 16:58:52 +09:00
362aca6dbf 261028_02_HOT: 컨택 진행 사용 허용 필드를 단일 선택으로 변경 2026-10-28 16:58:06 +09:00
4fd52bf8fc 261028_01_ENH: CTI 통화 재연결 복원 대응 및 종료 우회 처리 정리
- Talking 재수신 시 기존 통화 세션 복원
- 재로그인 상태 11인 종료 누락 통화를 기존 API로 정리
- 정상 종료 선반영 및 3초 강제 재연결 제거
- 종료 요청 대기·재시도와 중복 이벤트·지연 응답 처리 보완
2026-10-28 16:50:10 +09:00
27b4902a7c Merge pull request '261027_01_ENH: KON·KIWI 프로젝트 목록 및 현황 URL 조회를 backend bypass로 전환하고 연동 403 로그아웃 방지' (#63) from develop into master
Reviewed-on: #63
2026-10-28 08:34:33 +09:00
5a2f30c8b0 261027_01_ENH: KON·KIWI 프로젝트 목록 및 현황 URL 조회를 backend bypass로 전환하고 연동 403 로그아웃 방지 2026-10-27 15:24:52 +09:00
47973ed82d Merge pull request '261026_01_ENH: 문자, 알림톡 발신 번호에 대한 가이드에 KRi 계정 명시' (#62) from develop into master
Reviewed-on: #62
2026-10-26 09:47:43 +09:00
19a5d8b606 261026_01_ENH: 문자, 알림톡 발신 번호에 대한 가이드에 KRi 계정 명시 2026-10-26 09:46:02 +09:00
6c0722f2e5 Merge pull request 'develop' (#61) from develop into master
Reviewed-on: #61
2026-10-26 08:30:58 +09:00
3b552f38cf 261023_02_ENH: 일괄 발송 일부 접수 완료 상태 지원 및 결과 알림·건수 표시 개선 2026-10-23 15:10:46 +09:00
3c27a1fa46 261023_02_ENH: 컨택 진행에서 너무 긴 헤더명은 줄바꿈 2026-10-23 12:34:41 +09:00
2adbba779a Merge branch 'master' into develop
# Conflicts:
#	package-lock.json
#	package.json
#	src/components/dialog/MessageHistoryDialog.tsx
#	src/components/list-contact/ListContactEventPanel.tsx
2026-10-23 12:25:03 +09:00
c2c2eed3b4 Merge branch 'master' into develop 2026-10-23 12:20:22 +09:00
fd4ddb5797 Merge pull request '261023_01_ENH: 문자 SMS·LMS·MMS 유형 분리 및 템플릿·발송 이력·통계 반영' (#58) from hotfix-split-lms-mms into master
Reviewed-on: #58
2026-10-23 12:14:03 +09:00
38ce40c360 261023_01_ENH: 문자 SMS·LMS·MMS 유형 분리 및 템플릿·발송 이력·통계 반영 2026-10-23 12:07:11 +09:00
17ad56939c 261022_05_ENH: 리스트 초기화 범위 세분화 및 설문별 상태이력 초기화 추가 2026-10-22 16:59:04 +09:00
f65dacdec1 261022_03_ENH: 예약 취소 추가 2026-10-22 15:49:14 +09:00
061ef782bc Merge pull request 'hotfix-kkotemplate-ready' (#57) from hotfix-kkotemplate-ready into develop
Reviewed-on: #57
2026-10-22 12:48:07 +09:00
bbaedfc325 Merge pull request 'hotfix-kkotemplate-ready' (#56) from hotfix-kkotemplate-ready into master
Reviewed-on: #56
2026-10-22 12:47:05 +09:00
b087d9527e 261022_02_ENH: 카카오 템플릿 안내문 수정 2026-10-22 12:46:27 +09:00
191c0017a8 261022_01_FIX: kri common 버전업 2026-10-22 12:45:43 +09:00
d2e214696d 261020_02_FIX: 짧은 비동기 작업 종료 시 리스트 및 배정 목록이 갱신되지 않는 오류 수정 2026-10-20 11:57:46 +09:00
8f0de91e93 Merge pull request 'hofix-kkotamplate-alert' (#55) from hofix-kkotamplate-alert into develop
Reviewed-on: #55
2026-10-20 08:36:23 +09:00
361c065ec9 Merge pull request '261020_01_ENH: 카카오 템플릿 리스트 조회 실패시 alert표기하지 않음' (#54) from hofix-kkotamplate-alert into master
Reviewed-on: #54
2026-10-20 08:34:06 +09:00
eb44c57d39 261020_01_ENH: 카카오 템플릿 리스트 조회 실패시 alert표기하지 않음 2026-10-20 08:32:07 +09:00
d4db99337a Merge pull request '261019_01_ENH: 리스트 비동기 작업 동시 실행 제한 및 진행 상태 UI 개선, 미사용 참조 정리' (#53) from feature-async-list-bulk-work into develop
Reviewed-on: #53
2026-10-19 14:29:17 +09:00
d2e826702e 261019_01_ENH: 리스트 비동기 작업 동시 실행 제한 및 진행 상태 UI 개선, 미사용 참조 정리 2026-10-19 14:22:07 +09:00
3d58ffc1b4 Merge pull request '261015_02_ENH: 컨택 진행 화면 발송 현황 모바일 UI 개선' (#52) from develop into master
Reviewed-on: #52
2026-10-15 08:37:09 +09:00
4e51530922 261015_03_ENH: CTI 연결 끊김 자동 복구(최대 15초 간격 재시도)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-15 08:36:20 +09:00
044579c27f 261015_02_ENH: 컨택 진행 화면 발송 현황 모바일 UI 개선
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-15 08:34:49 +09:00
bb641464e2 Merge pull request '261015_01_ENH: 메인 화면·헤더 모바일 UI 개선' (#51) from develop into master
Reviewed-on: #51
2026-10-15 08:26:21 +09:00
ae8f2e6fc5 261015_01_ENH: 메인 화면·헤더 모바일 UI 개선
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-15 08:24:21 +09:00
831f1fac6b Merge pull request 'develop' (#50) from develop into master
Reviewed-on: #50
2026-10-15 07:44:54 +09:00
81dd5165f3 261013_03_ENH: bfcache CTI 재로그인 확인용 임시 로그 제거
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 16:53:25 +09:00
59c9238632 261013_02_ENH: 리스트 관리·컨택 진행 화면 모바일 UI 개선
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 16:53:25 +09:00
dce71d6448 Merge pull request '261013_01_HOT: 리스트 엑셀 업로드·다운로드 및 컨택이력 다운로드 timeout 5분으로 연장' (#49) from develop into master
Reviewed-on: #49
2026-10-13 12:28:49 +09:00
3ce503da18 261013_01_HOT: 리스트 엑셀 업로드·다운로드 및 컨택이력 다운로드 timeout 5분으로 연장
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 11:34:03 +09:00
c13d5e3d79 Merge pull request '261008_02_ENH: 사용가능 변수 리스트 노출 및 경고문 위치 수정, 추가' (#48) from develop into master
Reviewed-on: #48
2026-10-08 12:13:33 +09:00
ea81777a24 261008_02_ENH: 사용가능 변수 리스트 노출 및 경고문 위치 수정, 추가 2026-10-08 12:11:09 +09:00
45d7622961 Merge pull request '261008_01_ENH: 알림톡 템플릿 관련내용 구현 및 발송 구현' (#47) from develop into master
Reviewed-on: #47
2026-10-08 11:35:58 +09:00
264707ac56 261008_01_ENH: 알림톡 템플릿 관련내용 구현 및 발송 구현 2026-10-08 11:20:42 +09:00
f76415f236 Merge pull request '261007_01_ENH: 메시지 API contact-back 경유 전환, 발송 경로 변경 및 발신 이메일 형식 검증 추가' (#46) from develop into master
Reviewed-on: #46
2026-10-07 11:55:57 +09:00
f12c374a84 261007_01_ENH: 메시지 API contact-back 경유 전환, 발송 경로 변경 및 발신 이메일 형식 검증 추가 2026-10-07 11:24:24 +09:00
b6dc4e9d6c Merge pull request 'develop' (#45) from develop into master
Reviewed-on: #45
2026-10-07 08:51:10 +09:00
d088661719 261006_03_ENH: CTI 응답 ErrMsg 포함 시 오류 알림 추가 2026-10-06 14:48:32 +09:00
cf208b7f38 261006_02_ENH: 발신번호 미등록 시 전화걸기 차단 및 CTI 발신 오류(MakeCallError) 처리 2026-10-06 14:33:01 +09:00
746f709e92 261006_01_ENH: 전화를 걸지 않았는데 거는 중으로 남는 CTI 상태 오류 수정 및 AI Agent용 하네스 변경 적용 2026-10-06 13:56:56 +09:00
c4639d6ca2 Merge pull request 'develop' (#44) from develop into master
Reviewed-on: #44
2026-10-02 13:55:29 +09:00
b86ab58767 261001_03_ENH: 페이지 이탈(bfcache) 시 CTI 로그아웃 및 복귀 시 재로그인 2026-10-01 17:02:29 +09:00
825cf5f35f 261001_02_ENH: 발송 다이얼로그 미리보기 통합 및 QR·레이아웃 오류 수정 2026-10-01 16:35:55 +09:00
11f7ec1719 261001_01_ENH: 문자 템플릿 JPG 첨부 및 MMS 이미지 미리보기 추가 2026-10-01 12:13:45 +09:00
35bcc1615c Merge pull request '260929_01_ENH: 리스트 일괄 수정 다이얼로그를 처음 여는 경우 수정행에 아무것도 없게' (#43) from develop into master
Reviewed-on: #43
2026-09-29 11:24:05 +09:00
e8ddcdb88d 260929_01_ENH: 리스트 일괄 수정 다이얼로그를 처음 여는 경우 수정행에 아무것도 없게 2026-09-29 11:21:32 +09:00
be86e2a618 Merge pull request '260922_01_ENH: KON, KIWI 내부적 연동에 따라 url에 대한 경고문 및 전체 url 제거' (#42) from develop into master
Reviewed-on: #42
2026-09-22 15:23:50 +09:00
c92c984def 260922_01_ENH: KON, KIWI 내부적 연동에 따라 url에 대한 경고문 및 전체 url 제거 2026-09-22 15:08:28 +09:00
03a291c0f9 Merge pull request '260921_04_ENH: survey url full도 노출 및 경고문 추가' (#41) from develop into master
Reviewed-on: #41
2026-09-21 17:10:21 +09:00
057f610704 260921_04_ENH: survey url full도 노출 및 경고문 추가 2026-09-21 16:33:46 +09:00
8802f9d22a Merge pull request '260921_03_ENH: survey short url 쓸모가 없어서 폐기' (#40) from develop into master
Reviewed-on: #40
2026-09-21 14:05:41 +09:00
c5e2a3a6db 260921_03_ENH: survey short url 쓸모가 없어서 폐기 2026-09-21 14:04:37 +09:00
ff7791b76d Merge pull request '260921_02_ENH: KON, KIWI 설문 URL 앞부분 수정 못하게 막기' (#39) from develop into master
Reviewed-on: #39
2026-09-21 12:49:05 +09:00
96d9b3baf8 260921_02_ENH: KON, KIWI 설문 URL 앞부분 수정 못하게 막기 2026-09-21 12:48:10 +09:00
afcb15bc98 Merge pull request '260921_01_ENH: 설문번호 노출 및 설문연동에 대한 경고문 추가' (#38) from develop into master
Reviewed-on: #38
2026-09-21 12:07:06 +09:00
3181535e16 260921_01_ENH: 설문번호 노출 및 설문연동에 대한 경고문 추가 2026-09-21 11:58:40 +09:00
10a4bc9ab3 Merge pull request '260917_01_fix: 컨택 목록 복귀 시 필터·정렬·페이지 상태 복원' (#37) from develop into master
Reviewed-on: #37
2026-09-17 07:36:26 +09:00
c4d1a6c998 260917_01_fix: 컨택 목록 복귀 시 필터·정렬·페이지 상태 복원 2026-09-17 07:35:18 +09:00
1e5d27afe2 Merge pull request 'develop' (#36) from develop into master
Reviewed-on: #36
2026-09-16 18:19:17 +09:00
38672c262d 260916_02_ENH: 한글 입력시 툴팁 노출 2026-09-16 17:06:40 +09:00
2464f6b443 260916_01_ENH: SID 검색 시 문자 SID 허용 (틸드 범위는 숫자만 유지) 2026-09-16 15:15:30 +09:00
2ad807b3f9 Merge pull request 'develop' (#35) from develop into master
Reviewed-on: #35
2026-09-15 12:32:57 +09:00
b543d66186 260915_01_ENH: 다운로드 결과값 포함 및 컨택 이력 정렬 옵션 추가 2026-09-15 12:30:52 +09:00
effe279be9 260914_01_ENH: 프로젝트 이동 시 필터 및 검색 초기화 2026-09-14 10:05:08 +09:00
c2f6da0dd5 Merge pull request '260910_02_ENH: 검색 시 1페이지로' (#34) from develop into master
Reviewed-on: #34
2026-09-11 09:28:23 +09:00
73228a2573 260910_02_ENH: 검색 시 1페이지로 2026-09-10 15:47:14 +09:00
cb7b000b08 Merge pull request '260910_01_ENH: 템플릿 작성시 설문 URL에 대한 경고문 추가' (#33) from develop into master
Reviewed-on: #33
2026-09-10 12:32:59 +09:00
5e7199087d 260910_01_ENH: 템플릿 작성시 설문 URL에 대한 경고문 추가 2026-09-10 11:43:54 +09:00
642b0a559f Merge pull request 'develop' (#32) from develop into master
Reviewed-on: #32
2026-09-08 08:40:45 +09:00
3337119459 260908_02_ENH: 반투명 가시화에 대한 안내문 색상 변경 2026-09-08 08:40:11 +09:00
47acc5b4b3 260908_02_ENH: 반투명 가시화에 대한 안내문 색상 변경 2026-09-08 08:39:31 +09:00
5c9ed53b3b Merge pull request 'develop' (#31) from develop into master
Reviewed-on: #31
2026-09-08 07:48:24 +09:00
7bfb1ca987 260908_01_ENH: 이메일 템플릿에서 <area>, <map> 태그 사용 시 반투명 영역으로 가시화 2026-09-08 07:47:32 +09:00
0fbec01f73 260907_02_ENH: 웹소켓 연결 여부 신호등 표기 2026-09-07 15:08:53 +09:00
b6ed23fa88 260907_01_ENH: 에디터 이미지맵 보존 및 SMS 미리보기 문구 지원 2026-09-07 14:28:31 +09:00
050c4ccc6e Merge pull request '260904_01_ENH: 로그인 화면에 ip와 자리번호 노출' (#30) from develop into master
Reviewed-on: #30
2026-09-04 09:34:49 +09:00
b36893610f 260904_01_ENH: 로그인 화면에 ip와 자리번호 노출 2026-09-04 09:23:26 +09:00
4b3100b09c Merge pull request '260826_03_ENH: notihub 수정으로 인한 후속 조치' (#29) from develop into master
Reviewed-on: #29
2026-08-27 08:39:32 +09:00
a48ec34114 260827_01_ENH: 휴대 전화번호 인증은 추후에 작성 가능하도록할 예정 2026-08-27 08:38:43 +09:00
fbb61780ff 260826_03_ENH: notihub 수정으로 인한 후속 조치 2026-08-26 13:55:11 +09:00
d8292b8158 Merge pull request '260826_02_ENH: notihub 수정으로 인한 후속 조치' (#28) from develop into master
Reviewed-on: #28
2026-08-26 13:06:08 +09:00
c324617879 260826_02_ENH: notihub 수정으로 인한 후속 조치 2026-08-26 13:03:56 +09:00
bbc035c778 Merge pull request '260826_01_ENH: notihub 수정으로 인한 후속 조치' (#27) from develop into master
Reviewed-on: #27
2026-08-26 12:47:29 +09:00
a603f6ad6f 260826_01_ENH: notihub 수정으로 인한 후속 조치 2026-08-26 12:46:26 +09:00
de73dbd8db Merge pull request '260818_01_ENH: 리스트 업로드 시 order에 대한 검사 하지 않음' (#26) from develop into master
Reviewed-on: #26
2026-08-18 08:34:13 +09:00
be67eed7e4 260818_01_ENH: 리스트 업로드 시 order에 대한 검사 하지 않음 2026-08-18 08:33:16 +09:00
d674db2232 Merge pull request 'develop' (#25) from develop into master
Reviewed-on: #25
2026-08-12 17:03:49 +09:00
8cd0f5bd53 260812_03_ENH: cti관련 수정 및 리스트 배정 페이지에서 목록에 대한 필터와 건수 위치 뒤집음 2026-08-12 16:38:20 +09:00
e9bb02820c 260812_02_ENH:IP 기반 자리번호 조회 및 헤더 표시, 컨택에서 리스트 관리로 뒤로 가기 했을 경우 캐싱 제거 2026-08-12 15:06:27 +09:00
39ab7996d9 Merge pull request 'develop' (#24) from develop into master
Reviewed-on: #24
2026-08-12 08:43:22 +09:00
081b53945a 260812_01_ENH: 배정·진행 현황 개선 및 예약/이벤트 이력 기능 추가
- 프로젝트별 외주사·필드워커 배정 현황 및 미배정 건수 UI 추가
- 현장 면접 진행 여부와 사용자 권한에 따른 배정 탭·필터·컬럼 노출 제어
- 컨택 마지막 이벤트 일자 필터·정렬 및 결과/일자 컬럼 분리
- 컨택·면접·발송 현황의 날짜 범위 선택 optional 처리
- 진행 현황의 미배정 표시 및 일자별 미사용 결과 제외
- 전역 예약 기간 조회·이동 및 5분 단위 예약 알림 추가
- 내부 관리자용 이벤트 이력 단건 삭제 기능 추가
- 리스트 필터 UI 및 일반 헤더 정렬 기준 개선
- 프로젝트 저장 시 선택 프로젝트 정보 동기화
2026-08-12 08:41:27 +09:00
e8f3308814 260811_01_ENH: 폰트 추가 및 html보기, 프리티어 적용 2026-08-11 08:46:59 +09:00
9b93d45ed0 260810_04_ENH: 컨택 화면 ui 변경 및 개별 발송시 미리보기에 치환 문자열 치환 돼서 보여지도록 수정 2026-08-10 11:57:44 +09:00
ef748142f8 260810_03_ENH: 이메일 템플릿 수정에 폰트 추가 2026-08-10 11:54:41 +09:00
aad991b16b 260810_02_ENH: 직원만 프로젝트 생성 보이게 수정 2026-08-10 11:53:33 +09:00
10ace4fe53 docs: refresh UI registry contract 2026-08-10 11:32:25 +09:00
d9398c5675 260810_01_ENH: sid 필터 복붙, 리스트 배정 화면에서 대상 선택시 필터 자동적용, pw 제한, timepicker 수정 2026-08-10 10:05:10 +09:00
f4a5a04922 Merge pull request '260807_02_ENH: 일부 UI 손봄' (#23) from develop into master
Reviewed-on: #23
2026-08-07 16:16:42 +09:00
3d0c24b2ee 260807_02_ENH: 일부 UI 손봄 2026-08-07 16:16:03 +09:00
511493ab58 Merge pull request 'develop' (#22) from develop into master
Reviewed-on: #22
2026-08-07 14:30:47 +09:00
5eab2e4026 260807_01_ENH: 일부 UI 손봄 2026-08-07 14:30:11 +09:00
257ba6ca83 docs: add agent harness instructions 2026-08-07 11:19:00 +09:00
e4604d9016 Merge pull request '260806_01_ENH: 이메일 첨부파일 등록 추가' (#21) from develop into master
Reviewed-on: #21
2026-08-06 14:56:37 +09:00
86b626b5ea 260806_01_ENH: 이메일 첨부파일 등록 추가 2026-08-06 14:55:27 +09:00
ad5aa5de73 Merge pull request '260805_02_ENH: 외부 설문에서 리스트 관련 기능 사용시 prjctIdx가 아닌 prjctCd로 동작하게 변경' (#20) from develop into master
Reviewed-on: #20
2026-08-05 16:19:43 +09:00
cf94ea21b7 260805_02_ENH: 외부 설문에서 리스트 관련 기능 사용시 prjctIdx가 아닌 prjctCd로 동작하게 변경 2026-08-05 16:18:36 +09:00
ff28925c6e Merge pull request '260805_01_ENH: 이메일 템플릿 저장 시 빈 칸 유지, 외부 설문에서 리스트 단건 조회, 리스트 헤더조회, 리스트 단건 수정 기능 사용할수 있도록 api 라우트 생성 및 cors 완화' (#19) from develop into master
Reviewed-on: #19
2026-08-05 12:20:20 +09:00
6a2265e767 260805_01_ENH: 이메일 템플릿 저장 시 빈 칸 유지, 외부 설문에서 리스트 단건 조회, 리스트 헤더조회, 리스트 단건 수정 기능 사용할수 있도록 api 라우트 생성 및 cors 완화 2026-08-05 12:18:35 +09:00
2d3761f694 Merge pull request '260803_02_ENH: qrcode alt 가리기(사용자 혼동 야기)' (#18) from develop into master
Reviewed-on: #18
2026-08-03 17:07:06 +09:00
618718585c 260803_02_ENH: qrcode alt 가리기(사용자 혼동 야기) 2026-08-03 17:06:19 +09:00
0d17c21b8d Merge pull request '260803_01_ENH: 에디터에 QR 코드 삽입 추가' (#17) from develop into master
Reviewed-on: #17
2026-08-03 15:16:16 +09:00
a28981099f 260803_01_ENH: 에디터에 QR 코드 삽입 추가 2026-08-03 15:15:04 +09:00
c9d0100913 Merge pull request '260728_05_ENH: 에디터 동적 툴바 사용가능하도록 수정' (#16) from develop into master
Reviewed-on: #16
2026-07-28 15:29:41 +09:00
605d2dba49 260728_05_ENH: 에디터 동적 툴바 사용가능하도록 수정 2026-07-28 15:28:00 +09:00
e752a2067d Merge pull request 'develop' (#15) from develop into master
Reviewed-on: #15
2026-07-28 15:16:13 +09:00
65bbabe69b 260728_04_ENH: Wysiwyg 에디터 버그 수정 2026-07-28 14:42:46 +09:00
0285a3fe9d 260728_03_ENH: 시나리오에 치환 문자열 적용, 현황 bar chart에 bar max width 적용, 리스트 업로드 이력에서 만료된 파일은 안나오게 수정 2026-07-28 12:17:54 +09:00
17289bf0e8 Merge pull request '260728_02_ENH: SID String으로 교체' (#14) from feature-sid-convert-varchar into develop
Reviewed-on: #14
2026-07-28 11:48:22 +09:00
d9f53c0c3d 260728_02_ENH: SID String으로 교체 2026-07-28 11:47:33 +09:00
4388b7c048 Merge pull request '260728_01_ENH: 통화중 뒤로가기, 새로고침(단축키) 막기' (#13) from develop into master
Reviewed-on: #13
2026-07-28 08:43:55 +09:00
d97015741a 260728_01_ENH: 통화중 뒤로가기, 새로고침(단축키) 막기 2026-07-28 08:34:01 +09:00
9da39049cc Merge pull request '260727_02_ENH: 통화중 이동 최대한 막기' (#12) from develop into master
Reviewed-on: #12
2026-07-27 17:14:37 +09:00
ce5a402253 260727_02_ENH: 통화중 이동 최대한 막기 2026-07-27 17:13:58 +09:00
72ee21ec65 Merge pull request '260727_01_ENH: 전화 걸기 ws 틀어막기, 선택 항목만인경우 선택된 것이 없으면 오류' (#11) from develop into master
Reviewed-on: #11
2026-07-27 16:38:51 +09:00
157ba6155d 260727_01_ENH: 전화 걸기 ws 틀어막기, 선택 항목만인경우 선택된 것이 없으면 오류 2026-07-27 16:37:26 +09:00
4bfb9ae6ac Merge pull request '260724_02_ENH: 컨택 진행에서 프로젝트 바뀔 시 리스트 화면으로 돌아가게 수정' (#10) from develop into master
Reviewed-on: #10
2026-07-24 14:32:30 +09:00
58e9d0702e 260724_02_ENH: 컨택 진행에서 프로젝트 바뀔 시 리스트 화면으로 돌아가게 수정 2026-07-24 14:31:02 +09:00
22509a892c Merge pull request '260724_01_ENH: 테이블 스타일 통일, 일부 버그 수정' (#9) from develop into master
Reviewed-on: #9
2026-07-24 14:04:07 +09:00
e5e7aed504 260724_01_ENH: 테이블 스타일 통일, 일부 버그 수정 2026-07-24 14:03:03 +09:00
fb37c237b6 Merge pull request '260723_01_ENH: 설문 URL 치환시 모든 헤더 정보에 대해서 치환 가능하게 수정' (#8) from develop into master
Reviewed-on: #8
2026-07-23 16:04:21 +09:00
a7af497542 260723_01_ENH: 설문 URL 치환시 모든 헤더 정보에 대해서 치환 가능하게 수정 2026-07-23 16:03:33 +09:00
199 changed files with 12572 additions and 3154 deletions

View File

@@ -0,0 +1,13 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Contract: kri-front-common
Source: .agent/consumer-references/change-and-verification.md
-->
# KriFrontCommon Change and Verification
- 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.
- Keep `.agent/project.md` near 2-3 KiB as a routing document. Move conditional schemas, endpoint inventories, examples, and issue history to routed `.agent/references/` documents instead of deleting them.
- Do not modify KriFrontCommon or another consumer repository unless it is explicitly included in the approved task scope.

View File

@@ -0,0 +1,15 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Contract: kri-front-common
Source: .agent/consumer-references/package-and-runtime.md
-->
# KriFrontCommon Package and Runtime Contract
- 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.
- 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.

View File

@@ -0,0 +1,13 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Contract: kri-front-common
Source: .agent/consumer-references/react-compiler.md
-->
# React Compiler and Manual Memoization
- `createKriNextConfig` enables `reactCompiler: true` unless the project overrides it; confirm the effective configuration.
- When enabled, rely on React Compiler instead of adding `useMemo`, `useCallback`, or `React.memo` as a routine performance precaution.
- Use manual memoization only for required reference stability, an Effect or third-party contract, compiler-incompatible code, or a measured performance problem.
- Preserve existing memoization unless approved and verified for removal.
- Use `"use memo"` or `"use no memo"` only for a documented compiler boundary.

View File

@@ -0,0 +1,11 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Contract: kri-ui-registry
Source: .agent/consumer-references/editor-html-compatibility.md
-->
# KriEditor HTML Compatibility
- `enableImageMap` opt-in preserves `map`, nested `area`, and `img.usemap` HTML in WYSIWYG mode; consumers remain responsible for sanitizing URLs and attributes according to their server policy.
- Use `htmlSanitizer` when a consumer must apply a stricter HTML policy than the editor's default DOMPurify profile.
- Use `getWysiwygCompatibility` to keep lossy HTML in HTML mode. The callback must return `compatible: false` when WYSIWYG parsing would remove or materially rewrite content.

View File

@@ -0,0 +1,23 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Contract: kri-ui-registry
Source: .agent/consumer-references/installation-and-adaptation.md
-->
# KriUiRegistry Installation and 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.

18
.agent/profile.yml Normal file
View File

@@ -0,0 +1,18 @@
schema_version: 1
project:
id: kri-contact-front
name: KriContact Front
type: internal-service
layer: frontend
legacy: false
stack:
- typescript
- react
- nextjs
shared_contracts:
consumes:
- kri-front-common
- kri-ui-registry

18
.agent/project.md Normal file
View File

@@ -0,0 +1,18 @@
# KriContact Front Project Instruction Router
## Required Project References
Before each related task, read the current contents of every matching reference below, even if it was read earlier in the session.
| Task scope | Required reference |
|---|---|
| Any substantive analysis, planning, implementation, debugging, review, or documentation work in this repository | `.agent/references/repository-rules.md` |
If a task spans multiple scopes, read every matching reference. Do not assume remembered content is current.
## Harness Workflow
- `AGENTS.md` and `CLAUDE.md` are generated outputs. Never edit them directly.
- Edit `.agent/project.md` only when routing changes. Store durable project detail in `.agent/references/`.
- A reference-only content change does not require recomposition when its route is unchanged. Run harness verification to validate routing and UTF-8.
- Recompose and verify after changing `.agent/project.md`, `.agent/profile.yml`, or another composed instruction source.

View File

@@ -0,0 +1,28 @@
## KriContact Front Repository Rules
### Product Purpose and Current Phase
- This is the launched Next.js frontend for KRI contact operations. Preserve first-release behavior while planning and delivering approved follow-up features.
- The primary workflows include project and contact-list management, interviewer and list assignment, call/contact and event history, survey/contact/interview/message progress, SMS and email templates, result codes, users, companies, and roles.
- Prefer product-purpose clarity, workflow consistency, and backward compatibility over broad technical cleanup.
### Domain and Integration Boundaries
- Preserve the selected project context and company, project, role, and user access boundaries across navigation, queries, dialogs, and mutations.
- Treat list headers/items, assignment state, contact history, call state, progress metrics, result codes, templates, uploaded files, and exported files as coordinated API contracts with contact-server.
- Keep server-only credentials and privileged integration logic out of client bundles. Preserve the established Next.js API proxy and server/client boundaries.
- Minimize exposure of names, telephone numbers, contact history, and uploaded list data in UI state, logs, errors, screenshots, and test fixtures.
- Do not send real SMS or email, initiate real calls, or invoke production integrations during development or validation.
### Frontend Implementation
- Use the consumed KRI frontend common and UI registry contracts instead of copying shared utilities, components, or conventions locally.
- Prefer an existing shadcn/ui or approved registry component before creating a new foundational UI component. Compose or extend it locally only for project-specific behavior.
- Do not create new TypeScript type or interface names ending in `Dto` or `DTO`; use domain- or purpose-specific names.
- Preserve accessibility and loading, empty, error, disabled, confirmation, and success states for operational workflows.
- Coordinate request, response, validation, authentication, and error-shape changes with contact-server 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 repository's existing package manager and focused lint, type-check, test, or build commands. Validation must not call real business integrations.

View File

@@ -0,0 +1,41 @@
---
name: attention-aware-communication
description: Shape substantive answers, progress updates, and completion reports for fast, accurate reading without reducing the underlying work.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/attention-aware-communication/SKILL.md
-->
# Attention-Aware Communication
This skill changes presentation only. Investigate, implement, and verify as deeply as the task requires.
## Default: Attention-kind
- Put the bottom line in the first sentence and use plain Korean.
- Say the least that fully answers, then stop. Remove preambles, padding, repetition, and closing restatements.
- Never omit a number, scope condition, risk, prerequisite, uncertainty, or other fact that could cause the user to act incorrectly.
- For genuine breadth, explain the one or two most important points first, name the remaining areas, and let the user choose whether to expand them. Do not use this to defer required caveats or a complete focused answer.
- When the user asks for a detailed explanation, walkthrough, rationale, or full picture, suspend brevity and provide the necessary detail in scannable sections.
- When asked for a deliverable such as a command, message, snippet, or commit text, return the deliverable without unnecessary framing unless safety or correctness requires context.
- Ask one blocking question at a time and put it last. Keep working when a non-blocking assumption is safe.
## Progress and Completion: Rundown
Use Rundown formatting when a task has multiple steps or mixed states:
- Start with a one-line outcome that includes any blocker.
- Distinguish verified completion, work in progress, work not started, and unknown state. Omit empty categories.
- Put each blocker or material risk on its own line.
- Report only observed states. Mark an unknown as unknown and state what check would resolve it.
- End with the next action or a small numbered choice only when the user must decide.
## Explicit-Only: Spartan
Use Spartan style only when the user explicitly asks for it:
- Lead with the complete answer in one sentence.
- Be terse, blunt, and direct; remove warmth, hedging, transitions, narration, and summaries.
- Keep all load-bearing facts, warnings, and conditions even when they make the answer longer.
- If the user also asks for depth, provide the full detail in short, separated blocks.

View File

@@ -0,0 +1,37 @@
---
name: karpathy-guidelines
description: Keep implementation, refactoring, and code review assumption-aware, simple, surgical, and tied to verifiable success criteria.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/karpathy-guidelines/SKILL.md
-->
# Karpathy Guidelines
Use these guidelines while implementing, refactoring, or reviewing code. They refine execution quality but do not expand the approved task scope.
## Think Before Coding
- Inspect the relevant code and repository conventions before choosing a solution.
- Surface an assumption when different choices would materially change behavior, compatibility, data, or scope.
- Ask only when the decision cannot be discovered safely and a reasonable assumption would be risky. Otherwise proceed with the smallest reasonable assumption and report it.
## Simplicity First
- Implement the smallest complete solution that satisfies the observable requirement.
- Do not add speculative abstractions, extension points, configuration, fallback paths, or dependencies for hypothetical future use.
- Prefer an existing repository pattern or standard-library capability over a new local framework.
## Surgical Changes
- Every changed line must trace to the approved objective, required validation, or a necessary compatibility adjustment.
- Preserve existing naming, structure, public behavior, and formatting outside that boundary.
- Do not mix the task with unrelated cleanup. Remove dead code, duplication, or ceremony introduced by the current change before finishing.
## Goal-Driven Execution
- Translate the request into observable success criteria before implementation.
- Choose the narrowest check that can fail for the behavior being changed, then run broader repository checks when appropriate.
- Iterate only within the approved scope until the criteria pass or a concrete blocker is established.
- Before reporting completion, inspect the final diff for unnecessary code and use `verification-before-completion` for fresh evidence.

View File

@@ -0,0 +1,29 @@
---
name: project-reference-loader
description: Load the current project-specific and shared reference documents routed by AGENTS.md before substantive repository analysis, implementation, debugging, review, or planning.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/project-reference-loader/SKILL.md
-->
# Project Reference Loader
Use the repository's generated `AGENTS.md` as the routing entrypoint.
## Workflow
1. Find the `Required Project References` and shared-contract reference routes that match the current task.
2. Read the current contents of every matching file before relying on remembered project behavior, even when the file was read earlier in the session.
3. If the task crosses multiple scopes, read every matching reference. Do not load unrelated references merely because they exist.
4. Treat routed references as binding project instructions within their stated scope. Resolve conflicts using the precedence rules in `AGENTS.md`.
5. If a required reference is missing, unreadable, outside the repository, or internally inconsistent, stop the affected work and report the exact problem instead of guessing.
## Change Handling
- Edit authored project detail under `.agent/references/` when the durable rule belongs only to that repository.
- Edit the provider's `.agent/consumer-references/` when the rule is part of a shared consumer contract.
- Never edit generated `.agent-harness/references/` copies directly.
- Changing `.agent/references/` does not require recomposing `AGENTS.md` when its route is unchanged; changing routing, `project.md`, `consumer.md`, or shared reference sources does.
Before completion, confirm that the references used still exist and that the result does not contradict them. This skill does not expand authorization to edit, commit, push, deploy, connect to external systems, or perform destructive operations.

View File

@@ -0,0 +1,38 @@
---
name: verification-before-completion
description: Require fresh, claim-specific evidence before reporting work complete, fixed, passing, ready, or safe to commit or publish.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/verification-before-completion/SKILL.md
-->
# Verification Before Completion
No completion claim without fresh evidence. This workflow verifies status; it does not authorize a commit, push, deployment, database operation, or other protected action.
## Verification Gate
Before making a success claim:
1. State the exact claim internally and identify which observable check can prove or disprove it.
2. Run the relevant command or inspection fresh after the final change. Use repository-defined commands; do not invent a substitute that proves a different property.
3. Read the complete result needed for the claim, including the exit code, failure count, skipped checks, and generated changes.
4. Compare the evidence with the claim and the approved acceptance criteria.
5. Report only the status supported by that evidence.
## Evidence Rules
- A passing lint does not prove compilation, a passing build does not prove runtime behavior, and a passing narrow test does not prove unrelated requirements.
- For a regression test, establish that it is capable of detecting the defect when practical; do not treat an always-passing test as proof.
- Recheck the worktree or final diff after generators, formatters, tests, or builds that may create or alter files.
- Separate verified results, failures, checks not run, and pre-existing failures. Never quietly merge them into a success statement.
- For delegated work, inspect the returned changes and run the relevant verification yourself before accepting the completion claim.
- For absence or universal claims such as “no occurrences” or “all projects,” use a check whose scope actually covers the claim.
## Reporting
- Cite the commands or inspections actually run and summarize their observed results.
- If a required check cannot run, state the actual incomplete or blocked status and the exact reason.
- Do not use “should work,” “probably passes,” “seems correct,” or similar language as a substitute for verification.
- Do not claim completion while a required check is failing or while known correctness, encoding, security, or generated-output drift remains unresolved.

View File

@@ -0,0 +1,41 @@
---
name: attention-aware-communication
description: Shape substantive answers, progress updates, and completion reports for fast, accurate reading without reducing the underlying work.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/attention-aware-communication/SKILL.md
-->
# Attention-Aware Communication
This skill changes presentation only. Investigate, implement, and verify as deeply as the task requires.
## Default: Attention-kind
- Put the bottom line in the first sentence and use plain Korean.
- Say the least that fully answers, then stop. Remove preambles, padding, repetition, and closing restatements.
- Never omit a number, scope condition, risk, prerequisite, uncertainty, or other fact that could cause the user to act incorrectly.
- For genuine breadth, explain the one or two most important points first, name the remaining areas, and let the user choose whether to expand them. Do not use this to defer required caveats or a complete focused answer.
- When the user asks for a detailed explanation, walkthrough, rationale, or full picture, suspend brevity and provide the necessary detail in scannable sections.
- When asked for a deliverable such as a command, message, snippet, or commit text, return the deliverable without unnecessary framing unless safety or correctness requires context.
- Ask one blocking question at a time and put it last. Keep working when a non-blocking assumption is safe.
## Progress and Completion: Rundown
Use Rundown formatting when a task has multiple steps or mixed states:
- Start with a one-line outcome that includes any blocker.
- Distinguish verified completion, work in progress, work not started, and unknown state. Omit empty categories.
- Put each blocker or material risk on its own line.
- Report only observed states. Mark an unknown as unknown and state what check would resolve it.
- End with the next action or a small numbered choice only when the user must decide.
## Explicit-Only: Spartan
Use Spartan style only when the user explicitly asks for it:
- Lead with the complete answer in one sentence.
- Be terse, blunt, and direct; remove warmth, hedging, transitions, narration, and summaries.
- Keep all load-bearing facts, warnings, and conditions even when they make the answer longer.
- If the user also asks for depth, provide the full detail in short, separated blocks.

View File

@@ -0,0 +1,37 @@
---
name: karpathy-guidelines
description: Keep implementation, refactoring, and code review assumption-aware, simple, surgical, and tied to verifiable success criteria.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/karpathy-guidelines/SKILL.md
-->
# Karpathy Guidelines
Use these guidelines while implementing, refactoring, or reviewing code. They refine execution quality but do not expand the approved task scope.
## Think Before Coding
- Inspect the relevant code and repository conventions before choosing a solution.
- Surface an assumption when different choices would materially change behavior, compatibility, data, or scope.
- Ask only when the decision cannot be discovered safely and a reasonable assumption would be risky. Otherwise proceed with the smallest reasonable assumption and report it.
## Simplicity First
- Implement the smallest complete solution that satisfies the observable requirement.
- Do not add speculative abstractions, extension points, configuration, fallback paths, or dependencies for hypothetical future use.
- Prefer an existing repository pattern or standard-library capability over a new local framework.
## Surgical Changes
- Every changed line must trace to the approved objective, required validation, or a necessary compatibility adjustment.
- Preserve existing naming, structure, public behavior, and formatting outside that boundary.
- Do not mix the task with unrelated cleanup. Remove dead code, duplication, or ceremony introduced by the current change before finishing.
## Goal-Driven Execution
- Translate the request into observable success criteria before implementation.
- Choose the narrowest check that can fail for the behavior being changed, then run broader repository checks when appropriate.
- Iterate only within the approved scope until the criteria pass or a concrete blocker is established.
- Before reporting completion, inspect the final diff for unnecessary code and use `verification-before-completion` for fresh evidence.

View File

@@ -0,0 +1,29 @@
---
name: project-reference-loader
description: Load the current project-specific and shared reference documents routed by AGENTS.md before substantive repository analysis, implementation, debugging, review, or planning.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/project-reference-loader/SKILL.md
-->
# Project Reference Loader
Use the repository's generated `AGENTS.md` as the routing entrypoint.
## Workflow
1. Find the `Required Project References` and shared-contract reference routes that match the current task.
2. Read the current contents of every matching file before relying on remembered project behavior, even when the file was read earlier in the session.
3. If the task crosses multiple scopes, read every matching reference. Do not load unrelated references merely because they exist.
4. Treat routed references as binding project instructions within their stated scope. Resolve conflicts using the precedence rules in `AGENTS.md`.
5. If a required reference is missing, unreadable, outside the repository, or internally inconsistent, stop the affected work and report the exact problem instead of guessing.
## Change Handling
- Edit authored project detail under `.agent/references/` when the durable rule belongs only to that repository.
- Edit the provider's `.agent/consumer-references/` when the rule is part of a shared consumer contract.
- Never edit generated `.agent-harness/references/` copies directly.
- Changing `.agent/references/` does not require recomposing `AGENTS.md` when its route is unchanged; changing routing, `project.md`, `consumer.md`, or shared reference sources does.
Before completion, confirm that the references used still exist and that the result does not contradict them. This skill does not expand authorization to edit, commit, push, deploy, connect to external systems, or perform destructive operations.

View File

@@ -0,0 +1,38 @@
---
name: verification-before-completion
description: Require fresh, claim-specific evidence before reporting work complete, fixed, passing, ready, or safe to commit or publish.
---
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Source: skills/verification-before-completion/SKILL.md
-->
# Verification Before Completion
No completion claim without fresh evidence. This workflow verifies status; it does not authorize a commit, push, deployment, database operation, or other protected action.
## Verification Gate
Before making a success claim:
1. State the exact claim internally and identify which observable check can prove or disprove it.
2. Run the relevant command or inspection fresh after the final change. Use repository-defined commands; do not invent a substitute that proves a different property.
3. Read the complete result needed for the claim, including the exit code, failure count, skipped checks, and generated changes.
4. Compare the evidence with the claim and the approved acceptance criteria.
5. Report only the status supported by that evidence.
## Evidence Rules
- A passing lint does not prove compilation, a passing build does not prove runtime behavior, and a passing narrow test does not prove unrelated requirements.
- For a regression test, establish that it is capable of detecting the defect when practical; do not treat an always-passing test as proof.
- Recheck the worktree or final diff after generators, formatters, tests, or builds that may create or alter files.
- Separate verified results, failures, checks not run, and pre-existing failures. Never quietly merge them into a success statement.
- For delegated work, inspect the returned changes and run the relevant verification yourself before accepting the completion claim.
- For absence or universal claims such as “no occurrences” or “all projects,” use a check whose scope actually covers the claim.
## Reporting
- Cite the commands or inspections actually run and summarize their observed results.
- If a required check cannot run, state the actual incomplete or blocked status and the exact reason.
- Do not use “should work,” “probably passes,” “seems correct,” or similar language as a substitute for verification.
- Do not claim completion while a required check is failing or while known correctness, encoding, security, or generated-output drift remains unresolved.

View File

@@ -1,10 +1,9 @@
NEXT_PUBLIC_ENV=dev NEXT_PUBLIC_ENV=dev
NEXT_PUBLIC_API_BASE=https://test-contact.kric.com/api NEXT_PUBLIC_API_BASE=https://test-contact.kric.com/api
NEXT_PUBLIC_KART_URL=https://test-kart.kric.com
ENV=dev ENV=dev
CONTACT_SERVER=http://127.0.0.1:4001 CONTACT_SERVER=http://127.0.0.1:4001
API_CONTACT_SERVER=http://127.0.0.1:4001/api/v1 API_CONTACT_SERVER=http://127.0.0.1:4001/api/v1
API_NOTIHUB_SERVER=https://noti-hub.kric.com/api/v1
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1 API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
API_KART_SERVER=https://rapi.kric.com/api/v1 AUTH_COOKIE_DOMAIN=kric.com
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230

View File

@@ -1,10 +1,9 @@
NEXT_PUBLIC_ENV=local NEXT_PUBLIC_ENV=local
NEXT_PUBLIC_API_BASE=http://localhost:4000/api NEXT_PUBLIC_API_BASE=http://localhost:4000/api
NEXT_PUBLIC_KART_URL=https://test-kart.kric.com
ENV=local ENV=local
CONTACT_SERVER=http://localhost:4001 CONTACT_SERVER=http://localhost:4001
API_CONTACT_SERVER=http://localhost:4001/api/v1 API_CONTACT_SERVER=http://localhost:4001/api/v1
API_NOTIHUB_SERVER=https://noti-hub.kric.com/api/v1
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1 API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
API_KART_SERVER=https://rapi.kric.com/api/v1 AUTH_COOKIE_DOMAIN=
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230

View File

@@ -1,10 +1,9 @@
NEXT_PUBLIC_ENV=prod NEXT_PUBLIC_ENV=prod
NEXT_PUBLIC_API_BASE=https://contact.kric.com/api NEXT_PUBLIC_API_BASE=https://contact.kric.com/api
NEXT_PUBLIC_KART_URL=https://kart.kric.com
ENV=prod ENV=prod
CONTACT_SERVER=http://127.0.0.1:4001 CONTACT_SERVER=http://127.0.0.1:4001
API_CONTACT_SERVER=http://127.0.0.1:4001/api/v1 API_CONTACT_SERVER=http://127.0.0.1:4001/api/v1
API_NOTIHUB_SERVER=https://noti-hub.kric.com/api/v1
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1 API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
API_KART_SERVER=https://rapi.kric.com/api/v1 AUTH_COOKIE_DOMAIN=kric.com
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

1
.gitignore vendored
View File

@@ -23,6 +23,7 @@
# misc # misc
.DS_Store .DS_Store
*.pem *.pem
/.idea/
# debug # debug
npm-debug.log* npm-debug.log*

8
.idea/.gitignore generated vendored
View File

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

87
.idea/IntelliLang.xml generated
View File

@@ -1,87 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="LanguageInjectionConfiguration">
<injection language="SpEL" injector-id="java">
<display-name>Spring @Cacheable and @CacheEvict</display-name>
<single-file value="true" />
<place><![CDATA[psiMethod().withName("condition").withParameters().definedInClass("org.springframework.cache.annotation.CacheEvict")]]></place>
<place><![CDATA[psiMethod().withName("condition").withParameters().definedInClass("org.springframework.cache.annotation.CachePut")]]></place>
<place><![CDATA[psiMethod().withName("condition").withParameters().definedInClass("org.springframework.cache.annotation.Cacheable")]]></place>
<place><![CDATA[psiMethod().withName("key").withParameters().definedInClass("org.springframework.cache.annotation.CacheEvict")]]></place>
<place><![CDATA[psiMethod().withName("key").withParameters().definedInClass("org.springframework.cache.annotation.CachePut")]]></place>
<place><![CDATA[psiMethod().withName("key").withParameters().definedInClass("org.springframework.cache.annotation.Cacheable")]]></place>
<place><![CDATA[psiMethod().withName("unless").withParameters().definedInClass("org.springframework.cache.annotation.CachePut")]]></place>
<place><![CDATA[psiMethod().withName("unless").withParameters().definedInClass("org.springframework.cache.annotation.Cacheable")]]></place>
</injection>
<injection language="http-header-reference" injector-id="java">
<display-name>Spring HttpHeaders (org.springframework.http)</display-name>
<single-file value="true" />
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("header").definedInClass("org.springframework.http.ResponseEntity.HeadersBuilder"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("header").definedInClass("org.springframework.web.servlet.function.ServerResponse.HeadersBuilder"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("set", "add", "addAll", "getFirst", "containsKey", "get", "put", "getFirstDate", "setDate", "setInstant", "setZonedDateTime").definedInClass("org.springframework.http.HttpHeaders"))]]></place>
</injection>
<injection language="SpEL" injector-id="java">
<display-name>Spring Integration/Messaging</display-name>
<single-file value="true" />
<place><![CDATA[psiMethod().withName("expression").withParameters().definedInClass("org.springframework.messaging.handler.annotation.Payload")]]></place>
<place><![CDATA[psiMethod().withName("value").withParameters().definedInClass("org.springframework.integration.annotation.Payload")]]></place>
<place><![CDATA[psiMethod().withName("value").withParameters().definedInClass("org.springframework.messaging.handler.annotation.Payload")]]></place>
</injection>
<injection language="SQL" injector-id="java">
<display-name>Spring JDBC (org.springframework.jdbc.core.JdbcOperations)</display-name>
<single-file value="true" />
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("batchUpdate").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("execute").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("query").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("queryForInt").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("queryForList").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("queryForLong").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("queryForMap").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("queryForObject").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("queryForRowSet").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("queryForStream").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("sql").definedInClass("org.springframework.jdbc.core.simple.JdbcClient"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("update").definedInClass("org.springframework.jdbc.core.JdbcOperations"))]]></place>
</injection>
<injection language="SQL" injector-id="java">
<display-name>Spring JDBC (org.springframework.jdbc.core.PreparedStatementCreatorFactory)</display-name>
<single-file value="true" />
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("PreparedStatementCreatorFactory").withParameters("java.lang.String").definedInClass("org.springframework.jdbc.core.PreparedStatementCreatorFactory"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("PreparedStatementCreatorFactory").withParameters("java.lang.String", "int[]").definedInClass("org.springframework.jdbc.core.PreparedStatementCreatorFactory"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("PreparedStatementCreatorFactory").withParameters("java.lang.String", "java.util.List").definedInClass("org.springframework.jdbc.core.PreparedStatementCreatorFactory"))]]></place>
</injection>
<injection language="SQL" injector-id="java">
<display-name>Spring JDBC (org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator)</display-name>
<single-file value="true" />
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("createCustomException").withParameters("java.lang.String", "java.lang.String", "java.sql.SQLException", "java.lang.Class").definedInClass("org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("customTranslate").withParameters("java.lang.String", "java.lang.String", "java.sql.SQLException").definedInClass("org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("doTranslate").withParameters("java.lang.String", "java.lang.String", "java.sql.SQLException").definedInClass("org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("logTranslation").withParameters("java.lang.String", "java.lang.String", "java.sql.SQLException", "boolean").definedInClass("org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator"))]]></place>
</injection>
<injection language="SpEL" injector-id="java">
<display-name>Spring Security @PostAuthorize/@PostFilter/@PreAuthorize/@PreFilter/@AuthenticationPrincipal</display-name>
<single-file value="true" />
<place><![CDATA[psiMethod().withName("expression").withParameters().definedInClass("org.springframework.security.core.annotation.AuthenticationPrincipal")]]></place>
<place><![CDATA[psiMethod().withName("expression").withParameters().definedInClass("org.springframework.security.core.annotation.CurrentSecurityContext")]]></place>
<place><![CDATA[psiMethod().withName("value").withParameters().definedInClass("org.springframework.security.access.prepost.PostAuthorize")]]></place>
<place><![CDATA[psiMethod().withName("value").withParameters().definedInClass("org.springframework.security.access.prepost.PostFilter")]]></place>
<place><![CDATA[psiMethod().withName("value").withParameters().definedInClass("org.springframework.security.access.prepost.PreAuthorize")]]></place>
<place><![CDATA[psiMethod().withName("value").withParameters().definedInClass("org.springframework.security.access.prepost.PreFilter")]]></place>
</injection>
<injection language="SpEL" injector-id="java">
<display-name>Spring State Machine</display-name>
<single-file value="true" />
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("event").withParameters("java.lang.String").definedInClass("org.springframework.statemachine.config.configurers.SecurityConfigurer"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("guardExpression").withParameters("java.lang.String").definedInClass("org.springframework.statemachine.config.configurers.TransitionConfigurer"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("secured").withParameters("java.lang.String").definedInClass("org.springframework.statemachine.config.configurers.TransitionConfigurer"))]]></place>
<place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("transition").withParameters("java.lang.String").definedInClass("org.springframework.statemachine.config.configurers.SecurityConfigurer"))]]></place>
</injection>
<injection language="SpEL" injector-id="xml">
<display-name>SpEL for Spring Cache</display-name>
<single-file value="true" />
<place><![CDATA[xmlAttribute().withLocalName("condition").withParent(xmlTag().withNamespace(string().equalTo("http://www.springframework.org/schema/cache")))]]></place>
<place><![CDATA[xmlAttribute().withLocalName("key").withParent(xmlTag().withNamespace(string().equalTo("http://www.springframework.org/schema/cache")))]]></place>
<place><![CDATA[xmlAttribute().withLocalName("unless").withParent(xmlTag().withNamespace(string().equalTo("http://www.springframework.org/schema/cache")))]]></place>
</injection>
</component>
</project>

View File

@@ -1,21 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ClaudeCodeEditorTabs">
<option name="activeSessionId" value="d8691301-ce06-449d-9b1c-6360a510507b" />
<option name="openSessionIds">
<list>
<option value="d8691301-ce06-449d-9b1c-6360a510507b" />
</list>
</option>
<option name="sessionPaths">
<map>
<entry key="d8691301-ce06-449d-9b1c-6360a510507b" value="/sessions/4861f13b-20e7-4229-9754-1933b83c9805" />
</map>
</option>
<option name="sessionTitles">
<map>
<entry key="d8691301-ce06-449d-9b1c-6360a510507b" value="api가 호출될 때 자동으로 loading을 띄우는데 호출 api가 여러개인경우 제일 빠른" />
</map>
</option>
</component>
</project>

View File

@@ -1,5 +0,0 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state>
</component>

View File

@@ -1,8 +0,0 @@
<component name="ProjectDictionaryState">
<dictionary name="project">
<words>
<w>Hder</w>
<w>prjct</w>
</words>
</dictionary>
</component>

View File

@@ -1,15 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GitToolBoxProjectSettings">
<option name="commitMessageIssueKeyValidationOverride">
<BoolValueOverride>
<option name="enabled" value="true" />
</BoolValueOverride>
</option>
<option name="commitMessageValidationEnabledOverride">
<BoolValueOverride>
<option name="enabled" value="true" />
</BoolValueOverride>
</option>
</component>
</project>

View File

@@ -1,9 +0,0 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="CssUnresolvedCustomProperty" enabled="false" level="ERROR" enabled_by_default="false" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="JavaCollectionWithNullableTypeArgument" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="UsePropertyAccessSyntax" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
</profile>
</component>

View File

@@ -1,12 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MaterialThemeProjectNewConfig">
<option name="metadata">
<MTProjectMetadataState>
<option name="migrated" value="true" />
<option name="pristineConfig" value="false" />
<option name="userId" value="4859b8f9:19a516124ff:-7ffa" />
</MTProjectMetadataState>
</option>
</component>
</project>

5
.idea/misc.xml generated
View File

@@ -1,5 +0,0 @@
<project version="4">
<component name="ProjectRootManager">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
.idea/modules.xml generated
View File

@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/contact-front.iml" filepath="$PROJECT_DIR$/contact-front.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated
View File

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

357
AGENTS.md Normal file
View File

@@ -0,0 +1,357 @@
<!--
GENERATED BY KRI AGENT HARNESS. DO NOT EDIT DIRECTLY.
Project: kri-contact-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.
### Attention-Aware Response Style
- Use `attention-aware-communication` for substantive answers, progress updates, and completion reports.
- Default to concise, bottom-line-first Korean without omitting a condition, risk, number, or uncertainty needed for a correct decision.
- Give full detail when the user requests depth. Use Spartan style only when explicitly requested.
- Presentation rules never reduce investigation, implementation, validation, or reporting obligations.
## 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.
## Workflow Skills
- Use `project-reference-loader` before substantive repository analysis, planning, implementation, debugging, or review. Read only the current project and shared references routed for that task, and reread them for each related task even if they were loaded earlier in the session.
- Use `karpathy-guidelines` when implementing, refactoring, or reviewing code. It keeps assumptions visible, changes surgical, and success criteria verifiable.
- Use `verification-before-completion` before claiming that work is complete, fixed, passing, ready, or safe to commit or publish.
- A skill does not expand task scope or authorize Git publication, database execution, deployment, destructive actions, or external communication.
## 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.
## Internal Service Project Rules
- Internal-only usage does not reduce security, privacy, compatibility, or validation requirements.
- Preserve authentication, authorization, role boundaries, auditability, and personal-data protections.
- Identify affected user workflows before changing visible behavior.
- Treat Frontend and Backend repositories as separate deployable systems with an explicit API contract between them.
- Coordinate request, response, authentication, error, and versioning changes across both sides when the approved scope includes both repositories.
- Do not silently require a simultaneous Frontend and Backend deployment.
- Prefer backward-compatible transitions when deployments may occur independently.
- Include migration and rollback considerations for database, API, and configuration changes.
- Do not modernize legacy code as an unrelated side effect.
- Apply Classic ASP text-safety rules only when the project profile declares the `classic-asp` stack.
- Do not access or modify production data merely because the service is internal.
## 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.
- Do not use nested ternary expressions. Use clear `if`/`else` branches, early returns, or well-named intermediate variables instead; a single, non-nested ternary is acceptable only when it remains immediately readable.
- 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
- Consume the published `@kri/common` package only through entry points declared by its `package.json` `exports` map.
- Do not import from `@kri/common/src/*`, `@kri/common/dist/*`, or another undeclared deep path.
- Prefer a public shared helper or an approved backward-compatible library addition over copying or forking shared behavior locally.
- Do not modify KriFrontCommon or another consumer repository unless it is explicitly included in the approved task scope.
### Required Shared References
Before each related task, read the current contents of every matching reference, even if it was read earlier in the session.
| Task scope | Required reference |
|---|---|
| Package entry points, runtime boundaries, HTTP, authentication, state, storage, environment, or optional peer integrations | `.agent-harness/references/kri-front-common/package-and-runtime.md` |
| React rendering performance, memoization, or React Compiler behavior | `.agent-harness/references/kri-front-common/react-compiler.md` |
| Package upgrade, dependency changes, lockfile, or verification | `.agent-harness/references/kri-front-common/change-and-verification.md` |
If a task spans multiple scopes, read every matching reference. Generated files under `.agent-harness/references/` are read-only copies; edit KriFrontCommon's `.agent/consumer.md` or `.agent/consumer-references/` and recompose instead.
## Noti-hub SMS Types
- `MessageType.SMS = 21`, `LMS = 22`, `MMS = 23`; `ChannelType.SMS = 2` is unchanged. `SMS_TYPE_ARRAY` and `SmsType` include all three.
- `LMS_MMS = 22` remains a deprecated source-compatibility alias for LMS only. It does not represent MMS. Enum reverse lookup for 22 returns LMS. Use numeric bulk-list paths; the server no longer accepts LMS_MMS in paths. Numeric 21/22/23 bulk-list requests all return the entire SMS channel, not type-filtered lists.
- Requests retain their existing URLs/body shapes. The server chooses the actual type per recipient after substitution: attachment -> MMS; otherwise title or UTF-8 body >= 90 bytes -> LMS; otherwise SMS.
- Refresh templates from the save response (`tmplatTy`); display actual delivery types from `sendTy`, not the template or result code. A bulk can contain multiple SMS types. LMS/MMS share result codes; use existing server result labels.
- SMS, LMS, MMS and KKO use cancellation code 9998. Verify with `npm run typecheck`, `npm run build`, and `node --test tests/noti-hub-sms.test.mjs`.
## Noti-hub Reservation Cancellation
- Import cancellation types, constants, and helpers from `@kri/common/noti-hub` only. They are runtime-neutral and require no optional peers.
- Individual current cancellation state is determined by resultCode via isReserveCanceledResult; bulk current state is cancellationStatus (NONE/PARTIAL/ALL). These describe current cancellation state, not cancellation eligibility. cancelDt and cancelUser are request history, not current state.
- SendResultInfo, SendInfo, and BulkSendInfo expose optional cancelable. Use isSendCancelable(item), which returns true only for cancelable === true, for cancellation eligibility; missing values from older responses are treated as false. Never infer eligibility from cancelDt, result labels, or result codes.
- cancelable reflects query-time state and may change before cancellation. Determine the final outcome from SendCancelResponse counts.
- sendIdx is the single-cancel identifier, not cmid. It is absent from the latest abbreviated report (/api/v1/report/last/send/...). Request sendIdx must be a positive integer; bulkSendKey is required and at most 32 characters.
- EMAIL_RESERVE_CANCELED_RESULT_CODE is 108 for EMAIL. SMS_KKO_RESERVE_CANCELED_RESULT_CODE is 9998 for SMS, LMS, MMS, and KKO. Unknown message types are not recognized as canceled.
- Display the server's resultViewLabel/resultLabel ("예약 취소"). There is no separate result-code list API.
- HTTP 200 can contain notCancelableCount. parseSendCancelResponse validates nonnegative integer counts and targetCount = canceledCount + alreadyCanceledCount + notCancelableCount, throwing TypeError on invalid data. Bulk targetCount counts currently registered detail rows; response canceledCount counts only cancellations made by that request.
- Existing response fields are unchanged; all added fields on existing types are optional. Verify with npm run typecheck and npm run build.
## HTTP Streaming
- `@kri/common/http` HTTP clients expose streamGet/streamPost/streamPut/streamPatch/streamDel, returning HttpStreamResponse (status, statusText, headers, url, nullable body).
- Streaming shares ordinary authentication, URL, body and HTTP-error policy. Read body incrementally; no automatic JSON/NDJSON/SSE parsing or reconnect is performed.
- Streaming options accept an external AbortSignal. Caller cancellation raises AbortError without an HTTP error notification. Cancel the body when it will not be consumed.
- timeoutMs covers connection/headers (and an HTTP error body); idleTimeoutMs covers inactivity after successful headers and resets on consumed chunks. Both default to the client's defaultTimeoutMs (60 seconds by default), and 0 disables that timer for streaming only.
- Mid-stream transport/time-out errors reach the body reader. HTTP error statuses use existing HttpError handlers before a stream is returned. A 204 response has body=null.
- See HTTP_STREAMING.md for examples and node --test tests/http-stream.test.mjs for focused validation after npm run build.
## KriUiRegistry Consumer Contract
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 custom component only when the preceding options cannot meet the requirement safely.
### KriAutoComplete Search Scroll
- `kri-auto-complete` exposes `resetScrollOnSearch?: boolean` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It defaults to `false`, preserving existing behavior.
- When enabled, a search value change (including clearing it) resets the option list scroll to the top on the next animation frame in both `filter` and `inputOnly` modes. Async result updates alone do not trigger another reset.
### KriAutoComplete Option Tooltip
- `kri-auto-complete` exposes `optionTooltip?: 'singleLine' | 'wrap'` and `optionTooltipClassName?: string` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It is off by default, preserving existing behavior.
- When enabled, hovering an option shows its full `label` in a right-side tooltip. `singleLine` stays on one line until the available viewport width; `wrap` wraps at 28rem. The item depends on the shadcn `tooltip` component and provides its own `TooltipProvider`.
### KriAutoComplete Search Match
- `kri-auto-complete` exposes `searchMatch?: 'fuzzy' | 'contains'` on `KriSingleSelect`, `KriMultiSelect`, and `MultiSelect`. It defaults to `fuzzy` (cmdk's default subsequence scoring), preserving existing behavior.
- `contains` keeps only options whose label or value contains the search text as a case-insensitive substring, in the original option order. It applies only when `searchMode` is `filter`.
### KriEditor SMS Preview
- `changeSmsType` reports `SMS | LMS | MMS`. Update consumer callbacks to handle `MMS`; this widens the previous callback contract.
- Attachment presence (`smsHasAttachment`) takes priority and reports MMS. Otherwise a title or UTF-8 preview size >= `smsMaxBytes` (default 90) reports LMS; the remainder reports SMS. LMS/MMS share `lmsMaxBytes` (default 2000).
- UTF-8 byte counting includes `smsPreviewSuffix` and its separating newline, without storing the suffix in the body.
- This is a preview. Use the template-save response for saved `tmplatTy` and delivery-result `sendTy` for actual per-recipient type after server substitution. Registry updates require updating installed consumer copies.
### Required Shared References
Before each related task, read the current contents of every matching reference, even if it was read earlier in the session.
| Task scope | Required reference |
|---|---|
| Installing, upgrading, adapting, or verifying a registry component | `.agent-harness/references/kri-ui-registry/installation-and-adaptation.md` |
| KriEditor HTML, image-map, sanitizer, or WYSIWYG compatibility | `.agent-harness/references/kri-ui-registry/editor-html-compatibility.md` |
If a task spans multiple scopes, read every matching reference. Generated files under `.agent-harness/references/` are read-only copies; edit KriUiRegistry's `.agent/consumer.md` or `.agent/consumer-references/` and recompose instead.
# KriContact Front Project Instruction Router
## Required Project References
Before each related task, read the current contents of every matching reference below, even if it was read earlier in the session.
| Task scope | Required reference |
|---|---|
| Any substantive analysis, planning, implementation, debugging, review, or documentation work in this repository | `.agent/references/repository-rules.md` |
If a task spans multiple scopes, read every matching reference. Do not assume remembered content is current.
## Harness Workflow
- `AGENTS.md` and `CLAUDE.md` are generated outputs. Never edit them directly.
- Edit `.agent/project.md` only when routing changes. Store durable project detail in `.agent/references/`.
- A reference-only content change does not require recomposition when its route is unchanged. Run harness verification to validate routing and UTF-8.
- Recompose and verify after changing `.agent/project.md`, `.agent/profile.yml`, or another composed instruction source.

1
CLAUDE.md Normal file
View File

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

View File

@@ -29,6 +29,17 @@ const nextConfig = createKriNextConfig({
}, },
], ],
}, },
{
source: "/api/list-external/:path*",
headers: [
{ key: "Access-Control-Allow-Origin", value: "*" },
{ key: "Access-Control-Allow-Methods", value: "GET,POST,PATCH" },
{
key: "Access-Control-Allow-Headers",
value: "Content-Type, X-API-Key",
},
],
},
]; ];
}, },
}) satisfies NextConfig; }) satisfies NextConfig;

1315
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -12,7 +12,7 @@
"@dnd-kit/core": "^6.3.1", "@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0", "@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2", "@dnd-kit/utilities": "^3.2.2",
"@kri/common": "^0.18.0", "@kri/common": "^0.20.0",
"@radix-ui/react-checkbox": "^1.3.3", "@radix-ui/react-checkbox": "^1.3.3",
"@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-dropdown-menu": "^2.1.16",
@@ -26,6 +26,7 @@
"@tanstack/react-query": "^5.90.21", "@tanstack/react-query": "^5.90.21",
"@tanstack/react-table": "^8.21.3", "@tanstack/react-table": "^8.21.3",
"@tiptap/extension-color": "^3.13.0", "@tiptap/extension-color": "^3.13.0",
"@tiptap/extension-font-family": "^3.13.0",
"@tiptap/extension-highlight": "^3.13.0", "@tiptap/extension-highlight": "^3.13.0",
"@tiptap/extension-image": "^3.13.0", "@tiptap/extension-image": "^3.13.0",
"@tiptap/extension-link": "^3.13.0", "@tiptap/extension-link": "^3.13.0",
@@ -41,14 +42,16 @@
"@tiptap/starter-kit": "^3.12.0", "@tiptap/starter-kit": "^3.12.0",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"cmdk": "^1.1.1", "cmdk": "^1.1.1",
"cn": "0.5.2",
"date-fns": "^4.4.0", "date-fns": "^4.4.0",
"dompurify": "^3.4.10", "dompurify": "^3.4.10",
"echarts": "^6.1.0", "echarts": "^6.1.0",
"echarts-for-react": "^3.0.6", "echarts-for-react": "^3.0.6",
"jotai": "^2.15.1", "jotai": "^2.15.1",
"lucide-react": "^0.553.0", "lucide-react": "^0.553.0",
"next": "^16.0.7", "next": "^16.4.6",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"prettier": "^3.9.6",
"qrcode": "^1.5.4", "qrcode": "^1.5.4",
"radix-ui": "^1.6.1", "radix-ui": "^1.6.1",
"react": "^19.2.1", "react": "^19.2.1",
@@ -59,13 +62,13 @@
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/postcss": "^4", "@tailwindcss/postcss": "^4",
"@types/node": "^20", "@types/node": "^24.19.2",
"@types/qrcode": "^1.5.6", "@types/qrcode": "^1.5.6",
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
"babel-plugin-react-compiler": "1.0.0", "babel-plugin-react-compiler": "1.0.0",
"eslint": "^9", "eslint": "^9",
"eslint-config-next": "^16.0.7", "eslint-config-next": "^16.4.6",
"tailwindcss": "^4", "tailwindcss": "^4",
"tw-animate-css": "^1.4.0", "tw-animate-css": "^1.4.0",
"typescript": "^5" "typescript": "^5"

BIN
public/qr_example.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 851 KiB

View File

@@ -1,6 +1,8 @@
'use client' 'use client'
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
import { useAtom } from 'jotai'
import { listJobOpenRequestAtom } from '@/store/jotai/list-job'
import { useMounted } from '@kri/common/hooks' import { useMounted } from '@kri/common/hooks'
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter' import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
import { useAuth } from '@/hooks/useAuth' import { useAuth } from '@/hooks/useAuth'
@@ -13,15 +15,19 @@ import { AssignTargetList, useAssignTargetRows } from '@/components/assign/Assig
import { ListSearchTable } from '@/components/list/ListSearchTable' import { ListSearchTable } from '@/components/list/ListSearchTable'
import { useProjectInfoQuery, useResultCodesQuery } from '@/query/project' import { useProjectInfoQuery, useResultCodesQuery } from '@/query/project'
import { useListHeaderQuery } from '@/query/list' import { useListHeaderQuery } from '@/query/list'
import { useResetListAssignMutation, useUpsertListAssignMutation } from '@/query/assign' import { ListJobPageQueryContext, useSubmitListJob } from '@/query/list-job'
import { ListJobGatePanel } from '@/components/list/ListJobGate'
import { ListJobRefreshNotice } from '@/components/list/ListJobRefreshNotice'
import { useListJobPageMonitor } from '@/hooks/useListJobPageMonitor'
import { ListHeaderAssignConst, LIST_HEADER_TYPE_LABEL } from '@/const/listConst' import { ListHeaderAssignConst, LIST_HEADER_TYPE_LABEL } from '@/const/listConst'
import { createEmptyListFilter, type ListFilter, type ListHeaderAssignType, type listHeader } from '@/types/list' import { createEmptyListFilter, type ListFilter, type ListHeaderAssignType, type listHeader } from '@/types/list'
import type { ResultCode } from '@/types/project' import type { ResultCode } from '@/types/project'
import { isExternalManager } from '@/utils/userRole'
const ASSIGN_TAB_TYPES: ListHeaderAssignType[] = [ const ASSIGN_TAB_TYPES: ListHeaderAssignType[] = [
ListHeaderAssignConst.OUTSOURCE,
ListHeaderAssignConst.CONTACT_INTERVIEWER, ListHeaderAssignConst.CONTACT_INTERVIEWER,
ListHeaderAssignConst.FIELD_INTERVIEWER, ListHeaderAssignConst.FIELD_INTERVIEWER,
ListHeaderAssignConst.OUTSOURCE,
] ]
const ASSIGNED_SENTINEL = '__ASSIGNED__' const ASSIGNED_SENTINEL = '__ASSIGNED__'
@@ -36,8 +42,15 @@ const ListAssignPage = () => {
const prjctIdx = selectedProject?.prjctIdx ?? 0 const prjctIdx = selectedProject?.prjctIdx ?? 0
const enabled = mounted && prjctIdx > 0 const enabled = mounted && prjctIdx > 0
const userRole = auth?.user?.userRole ?? 0 const userRole = auth?.user?.userRole ?? 0
const isExternalUser = isExternalManager(userRole)
const [assignType, setAssignType] = useState<ListHeaderAssignType>(ListHeaderAssignConst.OUTSOURCE) const [assignType, setAssignType] = useState<ListHeaderAssignType>(ListHeaderAssignConst.CONTACT_INTERVIEWER)
const effectiveAssignType =
selectedProject?.ff === false && assignType === ListHeaderAssignConst.FIELD_INTERVIEWER
? ListHeaderAssignConst.CONTACT_INTERVIEWER
: isExternalUser && assignType === ListHeaderAssignConst.OUTSOURCE
? ListHeaderAssignConst.CONTACT_INTERVIEWER
: assignType
const [selectedAssignId, setSelectedAssignId] = useState<string | undefined>(undefined) const [selectedAssignId, setSelectedAssignId] = useState<string | undefined>(undefined)
const [assignFilterIds, setAssignFilterIds] = useState<string[]>([]) const [assignFilterIds, setAssignFilterIds] = useState<string[]>([])
const [transferResve, setTransferResve] = useState(false) const [transferResve, setTransferResve] = useState(false)
@@ -47,24 +60,47 @@ const ListAssignPage = () => {
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled) const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled)
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled) const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled)
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled) const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
const upsertListAssignMutation = useUpsertListAssignMutation(prjctIdx) const assignMutation = useSubmitListJob(prjctIdx)
const resetListAssignMutation = useResetListAssignMutation(prjctIdx) const pageMonitor = useListJobPageMonitor(prjctIdx, 'LIST_ASSIGN', enabled, {
const assignTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType }) hasSelection: !!selectedAssignId,
isSubmitting: assignMutation.isPending,
})
const { gate: assignGate, dataRevision } = pageMonitor
const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom)
const assignTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType: effectiveAssignType })
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data]) const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
const surveyArray = useMemo(() => projectInfoQuery.data?.surveys ?? [], [projectInfoQuery.data]) const surveyArray = useMemo(() => projectInfoQuery.data?.surveys ?? [], [projectInfoQuery.data])
const listHeaders = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data]) const listHeaders = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data])
const assignTabTypes = useMemo(
() =>
ASSIGN_TAB_TYPES.filter((type) => {
if (type === ListHeaderAssignConst.FIELD_INTERVIEWER && selectedProject?.ff === false) return false
if (type === ListHeaderAssignConst.OUTSOURCE && isExternalUser) return false
return true
}),
[selectedProject?.ff, isExternalUser],
)
useEffect(() => {
if (selectedProject?.ff === false && assignType === ListHeaderAssignConst.FIELD_INTERVIEWER) {
setAssignType(ListHeaderAssignConst.CONTACT_INTERVIEWER)
setSelectedAssignId(undefined)
setAssignFilterIds([])
return
}
if (isExternalUser && assignType === ListHeaderAssignConst.OUTSOURCE) {
setAssignType(ListHeaderAssignConst.CONTACT_INTERVIEWER)
setSelectedAssignId(undefined)
setAssignFilterIds([])
}
}, [assignType, selectedProject?.ff, isExternalUser])
const handleTabChange = (value: string) => { const handleTabChange = (value: string) => {
setAssignType(Number(value) as ListHeaderAssignType) setAssignType(Number(value) as ListHeaderAssignType)
setSelectedAssignId(undefined) setSelectedAssignId(undefined)
} }
// 좌측 테이블 선택값이 바뀌면 결과 필터 multiselect도 그 값으로 맞춘다.
useEffect(() => {
setAssignFilterIds(selectedAssignId ? [selectedAssignId] : [])
}, [selectedAssignId])
// "배정됨"/"배정되지 않음"은 실제 대상 선택과 동시에 선택될 수 없다: 새로 클릭된 쪽만 남긴다. // "배정됨"/"배정되지 않음"은 실제 대상 선택과 동시에 선택될 수 없다: 새로 클릭된 쪽만 남긴다.
const handleAssignFilterChange = (next: string[]) => { const handleAssignFilterChange = (next: string[]) => {
const addedSentinel = next.find((value) => isAssignFilterSentinel(value) && !assignFilterIds.includes(value)) const addedSentinel = next.find((value) => isAssignFilterSentinel(value) && !assignFilterIds.includes(value))
@@ -86,17 +122,25 @@ const ListAssignPage = () => {
const externalAssignFilter = useMemo(() => { const externalAssignFilter = useMemo(() => {
if (assignFilterIds[0] === ASSIGNED_SENTINEL) { if (assignFilterIds[0] === ASSIGNED_SENTINEL) {
return { type: assignType, values: [] as string[], condition: 'assigned' as const } return { type: effectiveAssignType, values: [] as string[], condition: 'assigned' as const }
} }
if (assignFilterIds[0] === UNASSIGNED_SENTINEL) { if (assignFilterIds[0] === UNASSIGNED_SENTINEL) {
return { type: assignType, values: [] as string[], condition: 'unassigned' as const } return { type: effectiveAssignType, values: [] as string[], condition: 'unassigned' as const }
} }
return { type: assignType, values: assignFilterIds } return { type: effectiveAssignType, values: assignFilterIds }
}, [assignType, assignFilterIds]) }, [effectiveAssignType, assignFilterIds])
const hasNoAppliedFilter = () => filterSummary.length === 0 && assignFilterIds.length === 0 const hasNoAppliedFilter = () => filterSummary.length === 0 && assignFilterIds.length === 0
useEffect(() => {
if (enabled && openRequest && !openRequest.opened && openRequest.jobType === 'LIST_ASSIGN'
&& openRequest.userId === auth.user?.userId && openRequest.prjctIdx === prjctIdx) {
setOpenRequest({ ...openRequest, opened: true })
}
}, [enabled, openRequest, auth.user?.userId, prjctIdx, setOpenRequest])
const handleAssign = async () => { const handleAssign = async () => {
if (assignGate.submitBlocked || assignMutation.isPending) return
if (!selectedAssignId) { if (!selectedAssignId) {
alert('배정할 대상을 선택해주세요.') alert('배정할 대상을 선택해주세요.')
return return
@@ -105,38 +149,43 @@ const ListAssignPage = () => {
return return
} }
await upsertListAssignMutation.mutateAsync({ await assignMutation.mutateAsync({
assignId: selectedAssignId, jobType: 'LIST_ASSIGN',
request: { path: `mutations/assign/${encodeURIComponent(selectedAssignId)}`,
assignType, body: {
transferResve: assignType === ListHeaderAssignConst.OUTSOURCE? false : transferResve, assignType: effectiveAssignType,
transferResve: effectiveAssignType === ListHeaderAssignConst.OUTSOURCE? false : transferResve,
listFilter: currentListFilter, listFilter: currentListFilter,
}, },
}) })
alert('배정되었습니다.')
} }
const handleResetAssign = async () => { const handleResetAssign = async () => {
if (assignGate.submitBlocked || assignMutation.isPending) return
if (hasNoAppliedFilter() && !confirm('적용된 필터가 없습니다. 전체 리스트를 대상으로 진행 하시겠습니까?')) { if (hasNoAppliedFilter() && !confirm('적용된 필터가 없습니다. 전체 리스트를 대상으로 진행 하시겠습니까?')) {
return return
} }
if (!confirm('정말 배정을 초기화 하시겠습니까?')) return if (!confirm('정말 배정을 초기화 하시겠습니까?')) return
await resetListAssignMutation.mutateAsync({ await assignMutation.mutateAsync({
assignType, jobType: 'LIST_ASSIGN',
path: 'mutations/assign-reset',
body: {
assignType: effectiveAssignType,
listFilter: currentListFilter, listFilter: currentListFilter,
},
}) })
alert('배정이 초기화 되었습니다.')
} }
if (!mounted || !selectedProject) return <LoadingOverlayAdapter force /> if (!mounted || !selectedProject) return <LoadingOverlayAdapter force />
return ( return (
<ListJobPageQueryContext.Provider value="LIST_ASSIGN">
<div className="flex gap-4 text-sm"> <div className="flex gap-4 text-sm">
<div className="w-72 shrink-0 space-y-2"> <div className="w-72 shrink-0 space-y-2">
<Tabs value={String(assignType)} onValueChange={handleTabChange}> <Tabs value={String(effectiveAssignType)} onValueChange={handleTabChange}>
<TabsList className="grid w-full grid-cols-3"> <TabsList className={`grid w-full ${assignTabTypes.length === 2 ? 'grid-cols-2' : assignTabTypes.length === 1 ? 'grid-cols-1' : 'grid-cols-3'}`}>
{ASSIGN_TAB_TYPES.map((type) => ( {assignTabTypes.map((type) => (
<TabsTrigger key={type} value={String(type)}> <TabsTrigger key={type} value={String(type)}>
{LIST_HEADER_TYPE_LABEL[type]} {LIST_HEADER_TYPE_LABEL[type]}
</TabsTrigger> </TabsTrigger>
@@ -147,14 +196,18 @@ const ListAssignPage = () => {
<AssignTargetList <AssignTargetList
prjctIdx={prjctIdx} prjctIdx={prjctIdx}
enabled={enabled} enabled={enabled}
assignType={assignType} assignType={effectiveAssignType}
userRole={userRole}
selectedId={selectedAssignId} selectedId={selectedAssignId}
onSelect={setSelectedAssignId} onSelect={setSelectedAssignId}
/> />
</div> </div>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1 space-y-2">
<ListJobGatePanel gate={assignGate} />
<ListJobRefreshNotice monitor={pageMonitor} />
<ListSearchTable <ListSearchTable
dataRevision={dataRevision}
prjctIdx={prjctIdx} prjctIdx={prjctIdx}
enabled={enabled} enabled={enabled}
userRole={userRole} userRole={userRole}
@@ -163,10 +216,11 @@ const ListAssignPage = () => {
resultCodes={resultCodeArray} resultCodes={resultCodeArray}
surveys={surveyArray} surveys={surveyArray}
listHeaders={listHeaders} listHeaders={listHeaders}
fieldInterviewEnabled={selectedProject.ff !== false}
selectMode="none" selectMode="none"
onCurrentFilterChange={setCurrentListFilter} onCurrentFilterChange={setCurrentListFilter}
onFilterSummaryChange={setFilterSummary} onFilterSummaryChange={setFilterSummary}
excludeFilterHeaderTypes={[assignType]} excludeFilterHeaderTypes={[effectiveAssignType]}
externalAssignFilter={externalAssignFilter} externalAssignFilter={externalAssignFilter}
filterActions={ filterActions={
<KriMultiSelect <KriMultiSelect
@@ -175,14 +229,14 @@ const ListAssignPage = () => {
onChange={handleAssignFilterChange} onChange={handleAssignFilterChange}
getValue={(item) => item.id} getValue={(item) => item.id}
getLabel={(item) => item.name} getLabel={(item) => item.name}
placeholder={`${LIST_HEADER_TYPE_LABEL[assignType]} 필터`} placeholder={`${LIST_HEADER_TYPE_LABEL[effectiveAssignType]} 필터`}
widthClassName="w-56" widthClassName="w-56"
heightClassName="h-9" heightClassName="h-9"
/> />
} }
rightActions={ rightActions={
<> <>
{assignType !== ListHeaderAssignConst.OUTSOURCE && ( {effectiveAssignType === ListHeaderAssignConst.CONTACT_INTERVIEWER && (
<label className="flex items-center gap-2 text-base cursor-pointer"> <label className="flex items-center gap-2 text-base cursor-pointer">
<Checkbox <Checkbox
checked={transferResve} checked={transferResve}
@@ -191,10 +245,10 @@ const ListAssignPage = () => {
예약 이관 예약 이관
</label> </label>
)} )}
<Button type="button" onClick={handleAssign}> <Button type="button" onClick={handleAssign} disabled={assignMutation.isPending || assignGate.submitBlocked}>
배정 배정
</Button> </Button>
<Button type="button" variant="outline" onClick={handleResetAssign}> <Button type="button" variant="outline" onClick={handleResetAssign} disabled={assignMutation.isPending || assignGate.submitBlocked}>
배정 초기화 배정 초기화
</Button> </Button>
</> </>
@@ -202,6 +256,7 @@ const ListAssignPage = () => {
/> />
</div> </div>
</div> </div>
</ListJobPageQueryContext.Provider>
) )
} }

View File

@@ -13,7 +13,7 @@ import { UserInfo } from "@/types/user";
import { useSelectedProject } from "@/hooks/useSelectedProject"; import { useSelectedProject } from "@/hooks/useSelectedProject";
import { KriSelect, KriSelectItem } from "@/components/common/KriSelect"; import { KriSelect, KriSelectItem } from "@/components/common/KriSelect";
import { useAuth } from "@/hooks/useAuth"; import { useAuth } from "@/hooks/useAuth";
import {CONTACT_INTERVIEWER_ROLE} from "@/const/userConst"; import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from "@/const/userConst";
import { import {
useFieldworkUsersQuery, useFieldworkUsersQuery,
@@ -61,8 +61,9 @@ const ProjectAssignPage = () => {
const roles = roleQuery.data ?? []; const roles = roleQuery.data ?? [];
return roles return roles
.filter(r => isFieldWorkUser(r.roleCd)) .filter(r => isFieldWorkUser(r.roleCd))
.filter(r => selectedProject?.ff !== false || r.roleCd !== FIELD_INTERVIEWER_ROLE)
.map(r => ({ value: String(r.roleCd), label: r.roleNm })); .map(r => ({ value: String(r.roleCd), label: r.roleNm }));
}, [roleQuery.data]); }, [roleQuery.data, selectedProject?.ff]);
const [companyFilter, setCompanyFilter] = useState<string>(''); const [companyFilter, setCompanyFilter] = useState<string>('');
const [roleFilter, setRoleFilter] = useState<KriSelectItem | undefined>(undefined); const [roleFilter, setRoleFilter] = useState<KriSelectItem | undefined>(undefined);
@@ -179,11 +180,12 @@ const ProjectAssignPage = () => {
]); ]);
const assignInfoString = useMemo(() => { const assignInfoString = useMemo(() => {
const cmpnAssign = companyFilter ? originAssign.filter(u => u.userCmpn === companyFilter) : originAssign;
return roleArray.map(role => { return roleArray.map(role => {
const cnt = originAssign.filter(u => String(u.userRole) === role.value).length; const cnt = cmpnAssign.filter(u => String(u.userRole) === role.value).length;
return `${role.label} : ${cnt}`; return `${role.label} : ${cnt}`;
}).join(' / '); }).join(' / ');
}, [roleArray, originAssign]); }, [roleArray, originAssign, companyFilter]);
const handleAssign = () => { const handleAssign = () => {
const toAssign = ableView.filter(u => selectedAbleUser.includes(u.userId)); const toAssign = ableView.filter(u => selectedAbleUser.includes(u.userId));
@@ -216,14 +218,14 @@ const ProjectAssignPage = () => {
// 로그인 계정의 소속 회사를 기본 선택하되, 매치되는 게 없으면 자사(ownCmpn) 중 가장 상단 1개로 대체한다. // 로그인 계정의 소속 회사를 기본 선택하되, 매치되는 게 없으면 자사(ownCmpn) 중 가장 상단 1개로 대체한다.
useEffect(() => { useEffect(() => {
const cmpn = auth.user?.userCmpn ?? ""; // 이미 유효한 값이 선택돼 있으면(사용자가 직접 고른 값 포함) 그대로 둔다.
if (cmpn && companyArray.some((company) => company.cmpnId === cmpn)) { if (companyFilter && companyArray.some((company) => company.cmpnId === companyFilter)) {
setCompanyFilter(cmpn);
return; return;
} }
// 이미 유효한 값이 선택돼 있으면(사용자가 직접 고른 값 포함) 그대로 둔다. const cmpn = auth.user?.userCmpn ?? "";
if (companyFilter && companyArray.some((company) => company.cmpnId === companyFilter)) { if (cmpn && companyArray.some((company) => company.cmpnId === cmpn)) {
setCompanyFilter(cmpn);
return; return;
} }
@@ -232,8 +234,8 @@ const ProjectAssignPage = () => {
}, [auth.user?.userCmpn, companyArray, companyFilter]); }, [auth.user?.userCmpn, companyArray, companyFilter]);
useEffect(() => { useEffect(() => {
if (roleFilter) return;
if (roleArray.length === 0) return; if (roleArray.length === 0) return;
if (roleFilter && roleArray.some(role => role.value === roleFilter.value)) return;
const contactRole = roleArray.find(r => r.value === String(CONTACT_INTERVIEWER_ROLE)); const contactRole = roleArray.find(r => r.value === String(CONTACT_INTERVIEWER_ROLE));
setRoleFilter(contactRole ?? roleArray[0]); setRoleFilter(contactRole ?? roleArray[0]);

View File

@@ -1,3 +1,4 @@
import { AuthSessionGate } from "@/components/app-shell/AuthSessionGate";
import AppMainLayout from "@/components/app-shell/AppMainLayout"; import AppMainLayout from "@/components/app-shell/AppMainLayout";
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
@@ -31,8 +32,8 @@ export default async function MainLayoutWrapper({
} }
return ( return (
<AppMainLayout initialFontSize={initialFontSize}> <AuthSessionGate><AppMainLayout initialFontSize={initialFontSize}>
{children} {children}
</AppMainLayout> </AppMainLayout></AuthSessionGate>
); );
} }

View File

@@ -1,23 +1,25 @@
'use client' 'use client'
import { Suspense, useEffect, useMemo, useState } from "react"; import { Suspense, useEffect, useMemo, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation"; import { useRouter, useSearchParams } from "next/navigation";
import { ArrowLeft, CalendarClock, RefreshCw } from "lucide-react"; import { ArrowLeft, RefreshCw } from "lucide-react";
import { useMounted } from "@kri/common/hooks"; import { useMounted } from "@kri/common/hooks";
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter"; import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { useAuth } from "@/hooks/useAuth"; import { useAuth } from "@/hooks/useAuth";
import { useDialog } from "@/hooks/useDialog";
import { useSelectedProject } from "@/hooks/useSelectedProject"; import { useSelectedProject } from "@/hooks/useSelectedProject";
import { useListDetailQuery, useListHeaderQuery, useListReserveByUserQuery, useUpdateListMutation } from "@/query/list"; import { useListDetailQuery, useListHeaderQuery, useUpdateListMutation } from "@/query/list";
import { useProjectInfoQuery, useResultCodesQuery } from "@/query/project"; import { useProjectInfoQuery, useResultCodesQuery } from "@/query/project";
import ListContactInfoPanel, { buildInitialValues } from "@/components/list-contact/ListContactInfoPanel"; import ListContactInfoPanel, { buildInitialValues } from "@/components/list-contact/ListContactInfoPanel";
import ListContactEventPanel from "@/components/list-contact/ListContactEventPanel"; import ListContactEventPanel from "@/components/list-contact/ListContactEventPanel";
import ListUpdateHistoryPanel from "@/components/list-contact/ListUpdateHistoryPanel"; import ListUpdateHistoryPanel from "@/components/list-contact/ListUpdateHistoryPanel";
import ReservationListDialog from "@/components/dialog/ReservationListDialog";
import { createEmptyListFilter, type listHeader } from "@/types/list"; import { createEmptyListFilter, type listHeader } from "@/types/list";
import type { ResultCode } from "@/types/project"; import type { ResultCode } from "@/types/project";
import { isManager } from "@/utils/userRole"; import { isManager } from "@/utils/userRole";
import {useCtiCallPhase} from "@/hooks/useCtiCallPhase";
import {CTI_CALL_PHASE} from "@/const/ctiConst";
const CALL_NAVIGATION_GUARD_KEY = "__listContactCallNavigationGuard";
const ListContactPageContent = () => { const ListContactPageContent = () => {
const router = useRouter(); const router = useRouter();
@@ -27,24 +29,93 @@ const ListContactPageContent = () => {
const mounted = useMounted(); const mounted = useMounted();
const { auth } = useAuth(); const { auth } = useAuth();
const { selectedProject } = useSelectedProject(); const { selectedProject } = useSelectedProject();
const { isDialogOpen, showDialog } = useDialog();
const prjctIdx = selectedProject?.prjctIdx ?? 0; const prjctIdx = selectedProject?.prjctIdx ?? 0;
const prjctCd = selectedProject?.prjctCd ?? ""; const prjctCd = selectedProject?.prjctCd ?? "";
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? ""; const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? "";
const userId = auth?.user?.userId ?? ""; const userId = auth?.user?.userId ?? "";
const userRole = auth?.user?.userRole ?? 0; const userRole = auth?.user?.userRole ?? 0;
const enabled = mounted && prjctIdx > 0 && !!sid; const ctiCallPhase = useCtiCallPhase();
const shouldBlockNavigation = CTI_CALL_PHASE.includes(ctiCallPhase);
const hasObservedCall = useRef(false);
const projectInfoQuery = useProjectInfoQuery(prjctIdx, mounted && prjctIdx > 0); const queriesEnabled = mounted && prjctIdx > 0;
const listHeaderQuery = useListHeaderQuery(prjctIdx, mounted && prjctIdx > 0); const enabled = queriesEnabled && !!sid;
useEffect(() => {
if (!shouldBlockNavigation) return;
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
event.preventDefault();
//구형 브라우저를 커버하기 위함
event.returnValue = true;
};
const handleReloadShortcut = (event: KeyboardEvent) => {
const isReloadShortcut =
event.key === "F5" ||
((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "r");
if (!isReloadShortcut) return;
event.preventDefault();
if (!event.repeat) alert("통화 중에는 새로고침할 수 없습니다.");
};
window.addEventListener("beforeunload", handleBeforeUnload);
window.addEventListener("keydown", handleReloadShortcut, true);
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
window.removeEventListener("keydown", handleReloadShortcut, true);
};
}, [shouldBlockNavigation]);
useEffect(() => {
const hasGuardEntry = window.history.state?.[CALL_NAVIGATION_GUARD_KEY] === true;
if (!shouldBlockNavigation) {
if (hasGuardEntry && hasObservedCall.current) window.history.back();
hasObservedCall.current = false;
return;
}
hasObservedCall.current = true;
let isRestoringHistory = false;
if (!hasGuardEntry) {
window.history.pushState(
{
...window.history.state,
[CALL_NAVIGATION_GUARD_KEY]: true,
},
"",
window.location.href,
);
}
const handlePopState = () => {
if (isRestoringHistory) {
isRestoringHistory = false;
return;
}
alert("통화 중에는 페이지를 이동할 수 없습니다.");
isRestoringHistory = true;
window.history.forward();
};
window.addEventListener("popstate", handlePopState);
return () => window.removeEventListener("popstate", handlePopState);
}, [shouldBlockNavigation]);
const projectInfoQuery = useProjectInfoQuery(prjctIdx, queriesEnabled);
const listHeaderQuery = useListHeaderQuery(prjctIdx, queriesEnabled);
const listDetailQuery = useListDetailQuery(prjctIdx, sid, enabled); const listDetailQuery = useListDetailQuery(prjctIdx, sid, enabled);
const resultCodesQuery = useResultCodesQuery(prjctIdx, mounted && prjctIdx > 0); const resultCodesQuery = useResultCodesQuery(prjctIdx, queriesEnabled);
const updateListMutation = useUpdateListMutation(prjctIdx); const updateListMutation = useUpdateListMutation(prjctIdx);
const reservationDialogOpen = isDialogOpen('reservationListDialog');
const reserveByUserQuery = useListReserveByUserQuery(prjctIdx, userId, reservationDialogOpen);
const listHeaders = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data]); const listHeaders = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data]);
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data]); const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data]);
@@ -62,14 +133,14 @@ const ListContactPageContent = () => {
useEffect(() => { useEffect(() => {
if (sid) return; if (sid) return;
alert("sid가 없으면 진행할 수 없습니다."); alert("sid가 없으면 진행할 수 없습니다.");
router.back(); router.push("/list/manage");
}, [sid, router]); }, [sid, router]);
const handleNavigateToSid = (nextSid: string) => {
router.push(`/list/contact?sid=${encodeURIComponent(nextSid)}`);
};
const handleGoToListManage = () => { const handleGoToListManage = () => {
if(shouldBlockNavigation){
alert("통화 중에는 이동할 수 없습니다.");
return;
}
router.push("/list/manage"); router.push("/list/manage");
}; };
@@ -77,6 +148,11 @@ const ListContactPageContent = () => {
setFormValues((prev) => ({ ...prev, [listHderId]: value })); setFormValues((prev) => ({ ...prev, [listHderId]: value }));
}; };
const handleCancelEdit = () => {
setFormValues(initialFormValues);
setIsEditing(false);
};
const handleToggleEdit = async () => { const handleToggleEdit = async () => {
if (!isEditing) { if (!isEditing) {
setIsEditing(true); setIsEditing(true);
@@ -101,12 +177,13 @@ const ListContactPageContent = () => {
return ( return (
<div className="space-y-6 text-sm"> <div className="space-y-6 text-sm">
<div className="flex items-center gap-3 w-1/2 pr-5"> {/* lg 미만은 아래 패널이 1열이므로 전체 폭을 쓰고, 한 줄에 들어가도록 글자/간격을 줄인다. */}
<div className="flex w-full items-center gap-2 lg:w-1/2 lg:gap-3 lg:pr-5">
<Button type="button" variant="outline" size="icon" onClick={handleGoToListManage} aria-label="목록으로"> <Button type="button" variant="outline" size="icon" onClick={handleGoToListManage} aria-label="목록으로">
<ArrowLeft className="h-4 w-4" /> <ArrowLeft className="h-4 w-4" />
</Button> </Button>
<h1 className="text-2xl font-bold tracking-tight">컨택 진행</h1> <h1 className="text-xl font-bold tracking-tight max-lg:whitespace-nowrap lg:text-2xl">컨택 진행</h1>
<span className="text-2xl font-bold tracking-tight">SID: {sid}</span> <span className="text-xl font-bold tracking-tight max-lg:min-w-0 max-lg:truncate lg:text-2xl">SID: {sid}</span>
<Button <Button
type="button" type="button"
variant="ghost" variant="ghost"
@@ -119,10 +196,11 @@ const ListContactPageContent = () => {
<RefreshCw className={`h-4 w-4 ${listDetailQuery.isFetching ? "animate-spin" : ""}`} /> <RefreshCw className={`h-4 w-4 ${listDetailQuery.isFetching ? "animate-spin" : ""}`} />
</Button> </Button>
<div className="ml-auto flex items-center gap-2"> <div className="ml-auto flex items-center gap-2">
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('reservationListDialog')}> {isEditing ? (
<CalendarClock className="h-4 w-4" /> <Button type="button" variant="outline" disabled={updateListMutation.isPending} onClick={handleCancelEdit}>
예약리스트 조회 취소
</Button> </Button>
) : null}
<Button type="button" disabled={updateListMutation.isPending} onClick={handleToggleEdit}> <Button type="button" disabled={updateListMutation.isPending} onClick={handleToggleEdit}>
{isEditing ? '저장' : '수정'} {isEditing ? '저장' : '수정'}
</Button> </Button>
@@ -162,10 +240,10 @@ const ListContactPageContent = () => {
useFF={projectInfoQuery.data?.ff ?? false} useFF={projectInfoQuery.data?.ff ?? false}
useContactSenario={projectInfoQuery.data?.useContactSenario ?? false} useContactSenario={projectInfoQuery.data?.useContactSenario ?? false}
contactSenario={projectInfoQuery.data?.contactSenario} contactSenario={projectInfoQuery.data?.contactSenario}
listHeaders={listHeaders}
detail={listDetailQuery.data}
/> />
</div> </div>
<ReservationListDialog reservations={reserveByUserQuery.data ?? []} onSelectReservation={handleNavigateToSid} />
</div> </div>
) )
} }

View File

@@ -1,7 +1,11 @@
'use client' 'use client'
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useRef, useState } from 'react'
import { useAtom } from 'jotai'
import { toast } from 'sonner'
import { listJobOpenRequestAtom } from '@/store/jotai/list-job'
import type { PaginationState } from '@tanstack/react-table' import type { PaginationState } from '@tanstack/react-table'
import { useQueryClient } from '@tanstack/react-query'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter' import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
import { useMounted } from "@kri/common/hooks"; import { useMounted } from "@kri/common/hooks";
@@ -10,26 +14,29 @@ import { useDialog } from '@/hooks/useDialog'
import { useSelectedProject } from '@/hooks/useSelectedProject' import { useSelectedProject } from '@/hooks/useSelectedProject'
import { useStorage } from '@/hooks/useStorage' import { useStorage } from '@/hooks/useStorage'
import { StorageKeys } from '@/store/storage/storage-keys' import { StorageKeys } from '@/store/storage/storage-keys'
import { ListManageActions } from '@/components/list/ListManageActions' import { ListManageActions, type ListManageActionKey } from '@/components/list/ListManageActions'
import { ListSearchTable } from '@/components/list/ListSearchTable' import { ListSearchTable } from '@/components/list/ListSearchTable'
import { import {
useDownloadListEventHistoryMutation,
useDownloadListExcelTemplateMutation, useDownloadListExcelTemplateMutation,
useDownloadListItemFileMutation,
useDownloadListMutation,
useDownloadListUpdateHistoryMutation,
useDownloadUploadHistoryFileMutation, useDownloadUploadHistoryFileMutation,
useListHeaderQuery, useListHeaderQuery,
useListUploadHistoryQuery, useListUploadHistoryQuery,
useResetListMutation,
useUpdateListHeaderMutation, useUpdateListHeaderMutation,
useUploadListExcelMutation,
} from '@/query/list' } from '@/query/list'
import { ListJobPageQueryContext, useMyActiveListJobs, useSubmitListJob } from '@/query/list-job'
import { ListJobGatePanel } from '@/components/list/ListJobGate'
import { ListJobRefreshNotice } from '@/components/list/ListJobRefreshNotice'
import { useListJobPageMonitor } from '@/hooks/useListJobPageMonitor'
import { useTrackedListJobs } from '@/store/list-job-tracker'
import { isListPageActionBlocked } from '@/utils/listJobAvailability'
import type { ListJobType } from '@/types/list-job'
import { LIST_DOWNLOAD_JOB_TYPE, LIST_JOB_VIEW, MESSAGE_JOB_TYPE } from '@/const/listJobConst'
import { useProjectInfoQuery, useResultCodesQuery } from '@/query/project' import { useProjectInfoQuery, useResultCodesQuery } from '@/query/project'
import type { ListTableRow } from '@/components/table-column/ListTableColumn' import type { ListTableRow } from '@/components/table-column/ListTableColumn'
import { import {
createEmptyListFilter, createEmptyListFilter,
ListEventHistoryBase, ListEventHistoryBase,
ListEventHistoryOrder,
type LastListVisit, type LastListVisit,
type ListDownloadMode, type ListDownloadMode,
type ListDownloadPayload, type ListDownloadPayload,
@@ -37,8 +44,8 @@ import {
type ListFilterTarget, type ListFilterTarget,
type listHeader, type listHeader,
type ListSearchUiState, type ListSearchUiState,
ListResetMode, type ListResetRequest,
type ListResetScope, type ListResetSelection,
type ListUploadRequest, type ListUploadRequest,
} from '@/types/list' } from '@/types/list'
import { type ResultCode, ResultCodeType } from '@/types/project' import { type ResultCode, ResultCodeType } from '@/types/project'
@@ -48,7 +55,7 @@ import ListHeaderManageDialog from '@/components/dialog/ListHeaderManageDialog'
import ListDownloadDialog from '@/components/dialog/ListDownloadDialog' import ListDownloadDialog from '@/components/dialog/ListDownloadDialog'
import MessageSendDialog, { type MessageSendMode } from '@/components/dialog/MessageSendDialog' import MessageSendDialog, { type MessageSendMode } from '@/components/dialog/MessageSendDialog'
import MessageHistoryDialog from '@/components/dialog/MessageHistoryDialog' import MessageHistoryDialog from '@/components/dialog/MessageHistoryDialog'
import { downloadBase64File, downloadFile, XLSX_MIME_TYPE } from '@kri/common/browser' import { downloadFile } from '@kri/common/browser'
import {CONTACT_INTERVIEWER_ROLE} from "@/const/userConst"; import {CONTACT_INTERVIEWER_ROLE} from "@/const/userConst";
import { isInternalManager, isManager } from "@/utils/userRole"; import { isInternalManager, isManager } from "@/utils/userRole";
import { applyListAccessFilter } from "@/utils/listAccess"; import { applyListAccessFilter } from "@/utils/listAccess";
@@ -68,6 +75,7 @@ const downloadArrayBuffer = (buffer: ArrayBuffer, filename: string, type = 'appl
const createEmptySearchUiState = (): ListSearchUiState => ({ const createEmptySearchUiState = (): ListSearchUiState => ({
searchText: '', searchText: '',
searchContactResult: [], searchContactResult: [],
searchContactDateRange: { from: '', to: '' },
searchInterviewResult: [], searchInterviewResult: [],
surveyResultSelections: {}, surveyResultSelections: {},
filterRows: [], filterRows: [],
@@ -76,10 +84,12 @@ const createEmptySearchUiState = (): ListSearchUiState => ({
const ListManagePage = () => { const ListManagePage = () => {
const router = useRouter() const router = useRouter()
const queryClient = useQueryClient()
const mounted = useMounted() const mounted = useMounted()
const { auth } = useAuth() const { auth } = useAuth()
const { showDialog } = useDialog() const { showDialog } = useDialog()
const { selectedProject, isSelectedProjectHydrated } = useSelectedProject() const { selectedProject, isSelectedProjectHydrated } = useSelectedProject()
const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom)
const [downloadMode, setDownloadMode] = useState<ListDownloadMode>('list') const [downloadMode, setDownloadMode] = useState<ListDownloadMode>('list')
const [messageSendMode, setMessageSendMode] = useState<MessageSendMode>('email') const [messageSendMode, setMessageSendMode] = useState<MessageSendMode>('email')
@@ -91,6 +101,7 @@ const ListManagePage = () => {
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 25 }) const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 25 })
const [restoredVisit, setRestoredVisit] = useState<LastListVisit | null>(null) const [restoredVisit, setRestoredVisit] = useState<LastListVisit | null>(null)
const [restoreResolved, setRestoreResolved] = useState(false) const [restoreResolved, setRestoreResolved] = useState(false)
const previousPrjctIdxRef = useRef(0)
const { get: getLastListVisit, set: setLastListVisit, remove: removeLastListVisit } = useStorage( const { get: getLastListVisit, set: setLastListVisit, remove: removeLastListVisit } = useStorage(
StorageKeys.LastListVisit, StorageKeys.LastListVisit,
@@ -105,19 +116,56 @@ const ListManagePage = () => {
const canManageList = isManager(userRole); const canManageList = isManager(userRole);
// 리스트 초기화/헤더 관리/업로드는 내부 관리자 전용 — 외주사 계정에는 노출되면 안 됨. // 리스트 초기화/헤더 관리/업로드는 내부 관리자 전용 — 외주사 계정에는 노출되면 안 됨.
const isInternal = isInternalManager(userRole); const isInternal = isInternalManager(userRole);
const pageMonitor = useListJobPageMonitor(prjctIdx, 'LIST_RESET', enabled, { hasSelection: selectedRows.length > 0 })
const { gate: pageGate, dataRevision } = pageMonitor
const trackedJobs = useTrackedListJobs()
useEffect(() => {
if (!mounted || !restoreResolved || !enabled || !openRequest || openRequest.opened
|| openRequest.userId !== userId || openRequest.prjctIdx !== prjctIdx) return
const view = LIST_JOB_VIEW[openRequest.jobType]
if (view.path !== '/list/manage' || !view.dialogId) return
if (!canManageList || (!isInternal && (openRequest.jobType === 'LIST_UPLOAD' || openRequest.jobType === 'LIST_RESET'))) {
toast.error('해당 작업 화면을 열 권한이 없습니다.')
setOpenRequest(null)
return
}
if (view.downloadMode) setDownloadMode(view.downloadMode)
if (view.messageMode) setMessageSendMode(view.messageMode)
showDialog(view.dialogId)
setOpenRequest({ ...openRequest, opened: true })
}, [mounted, restoreResolved, enabled, openRequest, userId, prjctIdx, canManageList, isInternal, setOpenRequest, showDialog])
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled) const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled)
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled) const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled)
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled) const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
const uploadHistoryQuery = useListUploadHistoryQuery(prjctIdx, enabled) const uploadHistoryQuery = useListUploadHistoryQuery(prjctIdx, enabled)
const downloadListExcelTemplateMutation = useDownloadListExcelTemplateMutation() const downloadListExcelTemplateMutation = useDownloadListExcelTemplateMutation()
const uploadListExcelMutation = useUploadListExcelMutation(prjctIdx) const submitJob = useSubmitListJob(prjctIdx)
// 전역 ListJobWatcher가 갱신하는 동일 쿼리를 구독하고 별도 폴링은 만들지 않는다.
const myActiveJobsQuery = useMyActiveListJobs(prjctIdx, false)
const myActiveJobTypes = new Set<string>((myActiveJobsQuery.data ?? []).map((job) => job.jobType))
const inspectableJobTypes = new Set([
...trackedJobs.filter(job => job.userId === userId && job.prjctIdx === prjctIdx).map(job => job.jobType),
...myActiveJobTypes,
...(pageGate.availability?.blockers.filter(blocker => blocker.mine && blocker.jobKey).map(blocker => blocker.jobType) ?? []),
])
const isActionDisabled = (jobType: ListJobType) => !inspectableJobTypes.has(jobType) && isListPageActionBlocked(
pageGate.status === 'unsupported' ? undefined : pageGate.availability,
jobType,
pageGate.status === 'checking' || pageGate.status === 'error',
)
const actionJobTypes: Record<ListManageActionKey, ListJobType> = {
reset: 'LIST_RESET', upload: 'LIST_UPLOAD', ...LIST_DOWNLOAD_JOB_TYPE, ...MESSAGE_JOB_TYPE,
}
const disabledActions = new Set((Object.keys(actionJobTypes) as ListManageActionKey[]).filter(action => isActionDisabled(actionJobTypes[action])))
const runningActions = new Set<ListManageActionKey>([
...(myActiveJobTypes.has('LIST_RESET') ? ['reset' as const] : []),
...(myActiveJobTypes.has('LIST_UPLOAD') ? ['upload' as const] : []),
...(Object.keys(LIST_DOWNLOAD_JOB_TYPE) as ListDownloadMode[]).filter((mode) => myActiveJobTypes.has(LIST_DOWNLOAD_JOB_TYPE[mode])),
...(Object.keys(MESSAGE_JOB_TYPE) as MessageSendMode[]).filter((mode) => myActiveJobTypes.has(MESSAGE_JOB_TYPE[mode])),
])
const updateListHeaderMutation = useUpdateListHeaderMutation(prjctIdx) const updateListHeaderMutation = useUpdateListHeaderMutation(prjctIdx)
const resetListMutation = useResetListMutation(prjctIdx)
const downloadListMutation = useDownloadListMutation(prjctIdx)
const downloadListUpdateHistoryMutation = useDownloadListUpdateHistoryMutation(prjctIdx)
const downloadListEventHistoryMutation = useDownloadListEventHistoryMutation(prjctIdx)
const downloadListItemFileMutation = useDownloadListItemFileMutation(prjctIdx)
const downloadUploadHistoryFileMutation = useDownloadUploadHistoryFileMutation(prjctIdx) const downloadUploadHistoryFileMutation = useDownloadUploadHistoryFileMutation(prjctIdx)
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data]) const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
@@ -135,9 +183,34 @@ const ListManagePage = () => {
removeLastListVisit() removeLastListVisit()
} }
setRestoreResolved(true) setRestoreResolved(true)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [mounted, isSelectedProjectHydrated, restoreResolved]) }, [mounted, isSelectedProjectHydrated, restoreResolved])
useEffect(() => {
if (!mounted || !isSelectedProjectHydrated || prjctIdx <= 0) return
const previousPrjctIdx = previousPrjctIdxRef.current
previousPrjctIdxRef.current = prjctIdx
if (previousPrjctIdx === 0 || previousPrjctIdx === prjctIdx) return
setSelectedRows([])
setCurrentListFilter(createEmptyListFilter())
setFilterSummary([])
setSearchUiState(createEmptySearchUiState())
setPagination({ pageIndex: 0, pageSize: 25 })
setRestoredVisit(null)
}, [isSelectedProjectHydrated, mounted, prjctIdx])
// 브라우저 뒤로가기(popstate)는 Next.js가 이 페이지를 재마운트하지 않고 재사용할 수 있어
// refetchOnMount만으로는 최신 데이터를 보장 못한다. popstate는 브라우저 네이티브 이벤트라
// 재마운트 여부와 무관하게 항상 발생하므로, 여기서 명시적으로 무효화한다.
useEffect(() => {
const handlePopState = () => {
void queryClient.invalidateQueries({ queryKey: ['list', 'search-filter'] })
}
window.addEventListener('popstate', handlePopState)
return () => window.removeEventListener('popstate', handlePopState)
}, [queryClient])
const restoredForThisProject = restoredVisit?.prjctIdx === prjctIdx ? restoredVisit : undefined const restoredForThisProject = restoredVisit?.prjctIdx === prjctIdx ? restoredVisit : undefined
const selectedSidSet = useMemo( const selectedSidSet = useMemo(
@@ -191,28 +264,16 @@ const ListManagePage = () => {
showDialog('messageSendDialog') showDialog('messageSendDialog')
} }
const handleResetConfirm = async (payload: { target: ListFilterTarget; scope: ListResetScope }) => { const handleResetConfirm = async (payload: { target: ListFilterTarget; selection: ListResetSelection }) => {
const listFilter = buildTargetFilter(payload.target) const body: ListResetRequest = {
const resetCount = await resetListMutation.mutateAsync({ ...payload.selection,
resetMode: payload.scope === 'result-and-history' ? ListResetMode.HIST : ListResetMode.ALL, listFilter: buildTargetFilter(payload.target),
listFilter, }
}) await submitJob.mutateAsync({ jobType: 'LIST_RESET', path: 'reset', body })
alert(`${resetCount}건 삭제 되었습니다.`)
refreshList()
} }
const handleUploadConfirm = async (file: File, request: ListUploadRequest) => { const handleUploadConfirm = async (file: File, request: ListUploadRequest) => {
const res = await uploadListExcelMutation.mutateAsync({ file, request }) await submitJob.mutateAsync({ jobType: 'LIST_UPLOAD', path: 'upload', file, body: request })
if (res.hasErrorFile && res.errorFileBase64) {
alert("업로드 중 오류가 발생하여 오류 파일을 다운로드합니다.");
downloadBase64File(res.errorFileBase64, res.errorFileName ?? "error.xlsx", XLSX_MIME_TYPE);
}
else{
alert(`${res.successCount}개의 리스트를 업로드했습니다.`);
}
refreshList()
} }
const handleDownloadTemplate = async () => { const handleDownloadTemplate = async () => {
@@ -231,43 +292,47 @@ const ListManagePage = () => {
const handleDownloadConfirm = async (payload: ListDownloadPayload) => { const handleDownloadConfirm = async (payload: ListDownloadPayload) => {
const listFilter = buildTargetFilter(payload.target) const listFilter = buildTargetFilter(payload.target)
const jobType = LIST_DOWNLOAD_JOB_TYPE[payload.mode]
if (payload.mode === 'list') { if (payload.mode === 'list') {
const buffer = await downloadListMutation.mutateAsync(listFilter) await submitJob.mutateAsync({ jobType, path: `downloads/list?includeResult=${payload.includeResult}`, body: listFilter })
downloadArrayBuffer(buffer, `${prjctName} list.xlsx`)
return return
} }
if (payload.mode === 'list-change-history') { if (payload.mode === 'list-change-history') {
const buffer = await downloadListUpdateHistoryMutation.mutateAsync(listFilter) await submitJob.mutateAsync({ jobType, path: 'downloads/update-history', body: listFilter })
downloadArrayBuffer(buffer, `${prjctName} update-history.xlsx`)
return return
} }
if (payload.mode === 'upload-file') { if (payload.mode === 'upload-file') {
const buffer = await downloadListItemFileMutation.mutateAsync(listFilter) await submitJob.mutateAsync({ jobType, path: 'downloads/item-files', body: listFilter })
downloadArrayBuffer(buffer, `${prjctName} upload-files.zip`, 'application/zip')
return return
} }
const buffer = await downloadListEventHistoryMutation.mutateAsync({ await submitJob.mutateAsync({ jobType, path: `downloads/event-history?includeResult=${payload.includeResult}`, body: {
listFilter, listFilter,
resultCodeTypes: [ResultCodeType.CONTACT, ResultCodeType.INTERVIEW, ResultCodeType.SURVEY], resultCodeTypes: [ResultCodeType.CONTACT, ResultCodeType.INTERVIEW, ResultCodeType.SURVEY],
searchBase: payload.contactHistoryType === 'latest' ? ListEventHistoryBase.LATEST : ListEventHistoryBase.ALL, searchBase: payload.contactHistoryType === 'latest' ? ListEventHistoryBase.LATEST : ListEventHistoryBase.ALL,
historyOrder: payload.historyOrder ?? ListEventHistoryOrder.DESC,
dateRange: toDateTimeRange(payload.contactHistoryDateFrom, payload.contactHistoryDateTo), dateRange: toDateTimeRange(payload.contactHistoryDateFrom, payload.contactHistoryDateTo),
}) } })
downloadArrayBuffer(buffer, `${prjctName} contact-history.xlsx`)
} }
if (!mounted || !restoreResolved) return <LoadingOverlayAdapter force /> if (!mounted || !restoreResolved) return <LoadingOverlayAdapter force />
return ( return (
<ListJobPageQueryContext.Provider value="LIST_RESET">
<div className="space-y-6 text-sm"> <div className="space-y-6 text-sm">
<ListJobGatePanel gate={pageGate} showCurrentJob={false} />
<ListJobRefreshNotice monitor={pageMonitor} clearsSelection={selectedRows.length > 0} />
{canManageList && ( {canManageList && (
<ListManageActions <ListManageActions
showAdminActions={isInternal} showAdminActions={isInternal}
runningActions={runningActions}
disabledActions={disabledActions}
headerManageDisabled={pageGate.submitBlocked}
onReset={() => showDialog('listResetDialog')} onReset={() => showDialog('listResetDialog')}
onHeaderManage={() => showDialog('listHeaderManageDialog')} onHeaderManage={() => { if (!pageGate.submitBlocked) showDialog('listHeaderManageDialog') }}
onUpload={() => showDialog('listUploadDialog')} onUpload={() => showDialog('listUploadDialog')}
onDownload={openDownloadDialog} onDownload={openDownloadDialog}
onMessageSend={openMessageDialog} onMessageSend={openMessageDialog}
@@ -276,6 +341,7 @@ const ListManagePage = () => {
)} )}
<ListSearchTable <ListSearchTable
key={prjctIdx}
prjctIdx={prjctIdx} prjctIdx={prjctIdx}
enabled={enabled} enabled={enabled}
userRole={userRole} userRole={userRole}
@@ -284,7 +350,11 @@ const ListManagePage = () => {
resultCodes={resultCodeArray} resultCodes={resultCodeArray}
surveys={surveyArray} surveys={surveyArray}
listHeaders={headerManageRows} listHeaders={headerManageRows}
fieldInterviewEnabled={selectedProject?.ff !== false}
enableBatchEdit={canManageList} enableBatchEdit={canManageList}
batchEditDisabled={isActionDisabled('LIST_UPDATE')}
dataRevision={dataRevision}
selectMode={canManageList ? 'multi' : 'click-event'}
refreshKey={listRefreshKey} refreshKey={listRefreshKey}
onCurrentFilterChange={setCurrentListFilter} onCurrentFilterChange={setCurrentListFilter}
onFilterSummaryChange={setFilterSummary} onFilterSummaryChange={setFilterSummary}
@@ -300,12 +370,21 @@ const ListManagePage = () => {
initialSearchState={restoredForThisProject} initialSearchState={restoredForThisProject}
onSearchStateChange={setSearchUiState} onSearchStateChange={setSearchUiState}
focusRowId={restoredForThisProject?.sid} focusRowId={restoredForThisProject?.sid}
collapsibleFiltersOnMobile
/> />
{isInternal && ( {isInternal && (
<> <>
<ListResetDialog filterSummary={filterSummary} onConfirm={handleResetConfirm} /> <ListResetDialog
key={prjctIdx}
prjctIdx={prjctIdx}
surveys={projectInfoQuery.data?.surveys}
selectedSids={selectedSidSet}
filterSummary={filterSummary}
onConfirm={handleResetConfirm}
/>
<ListUploadDialog <ListUploadDialog
prjctIdx={prjctIdx}
onUpload={handleUploadConfirm} onUpload={handleUploadConfirm}
onDownloadTemplate={handleDownloadTemplate} onDownloadTemplate={handleDownloadTemplate}
uploadHistory={uploadHistoryQuery.data ?? []} uploadHistory={uploadHistoryQuery.data ?? []}
@@ -315,13 +394,19 @@ const ListManagePage = () => {
}} }}
headerRows={headerManageRows} headerRows={headerManageRows}
/> />
<ListHeaderManageDialog prjctIdx={prjctIdx} rows={headerManageRows} onConfirm={handleHeaderManageConfirm} /> <ListHeaderManageDialog prjctIdx={prjctIdx} rows={headerManageRows} onConfirm={handleHeaderManageConfirm} saveDisabled={pageGate.submitBlocked} />
</> </>
)} )}
{canManageList && ( {canManageList && (
<> <>
<ListDownloadDialog mode={downloadMode} filterSummary={filterSummary} onDownload={handleDownloadConfirm} /> <ListDownloadDialog
prjctIdx={prjctIdx}
mode={downloadMode}
selectedSids={selectedSidSet}
filterSummary={filterSummary}
onDownload={handleDownloadConfirm}
/>
<MessageSendDialog <MessageSendDialog
mode={messageSendMode} mode={messageSendMode}
listHeaders={headerManageRows} listHeaders={headerManageRows}
@@ -334,6 +419,7 @@ const ListManagePage = () => {
</> </>
)} )}
</div> </div>
</ListJobPageQueryContext.Provider>
) )
} }

View File

@@ -1,12 +1,14 @@
import { MessageType, type TemplateEmail } from "@kri/common/noti-hub"; import { MessageType, TemplatePurpose, type TemplateEmail } from "@kri/common/noti-hub";
import MessageTemplate from "@/components/message-template/MessageTemplate"; import MessageTemplate from "@/components/message-template/MessageTemplate";
import type { TemplateWithPurpose } from "@/types/message";
const EmailTemplatePage = () => { const EmailTemplatePage = () => {
const defaultEmailTemplate : TemplateEmail = { const defaultEmailTemplate : TemplateWithPurpose & TemplateEmail = {
tmplatIdx: undefined, tmplatIdx: undefined,
itrntPrjctCd: '', itrntPrjctCd: '',
tmplatTy: MessageType.EMAIL, tmplatTy: MessageType.EMAIL,
tmplatPurpose: TemplatePurpose.NORMAL,
tmplatNm: '', tmplatNm: '',
tmplatTitle: '', tmplatTitle: '',
tmplatBody: '', tmplatBody: '',

View File

@@ -0,0 +1,13 @@
'use client'
import KkoMessageTemplate from "@/components/message-template/KkoMessageTemplate";
const KkoTemplatePage = () => {
return (
<div className="space-y-6 text-sm">
<KkoMessageTemplate />
</div>
)
}
export default KkoTemplatePage;

View File

@@ -1,14 +1,16 @@
'use client' 'use client'
import { MessageType, type TemplateSms } from "@kri/common/noti-hub"; import { MessageType, TemplatePurpose, type TemplateSms } from "@kri/common/noti-hub";
import MessageTemplate from "@/components/message-template/MessageTemplate"; import MessageTemplate from "@/components/message-template/MessageTemplate";
import type { TemplateWithPurpose } from "@/types/message";
const SmsTemplatePage = () => { const SmsTemplatePage = () => {
const defaultSmsTemplate : TemplateSms = { const defaultSmsTemplate : TemplateWithPurpose & TemplateSms = {
tmplatIdx: undefined, tmplatIdx: undefined,
itrntPrjctCd: '', itrntPrjctCd: '',
tmplatTy: MessageType.SMS, tmplatTy: MessageType.SMS,
tmplatPurpose: TemplatePurpose.NORMAL,
tmplatNm: '', tmplatNm: '',
tmplatTitle: undefined, tmplatTitle: undefined,
tmplatBody: '', tmplatBody: '',

View File

@@ -1,7 +1,10 @@
'use client' 'use client'
import {useMemo, useState} from "react"; import {useMemo, useState} from "react";
import {ChevronDown} from "lucide-react";
import AppPageTitle from "@/components/app-shell/AppPageTitle"; import AppPageTitle from "@/components/app-shell/AppPageTitle";
import {Badge} from "@/components/ui/badge";
import {Button} from "@/components/ui/button"; import {Button} from "@/components/ui/button";
import {cn} from "@/lib/utils";
import {DataTable} from "@/components/data-table/DataTable"; import {DataTable} from "@/components/data-table/DataTable";
import {getProjectColumns} from "@/components/table-column/ProjectTableColumn"; import {getProjectColumns} from "@/components/table-column/ProjectTableColumn";
import { import {
@@ -23,10 +26,11 @@ import { useMounted } from "@kri/common/hooks";
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter"; import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
import {useItrntUserList} from "@/hooks/useItrntUserList"; import {useItrntUserList} from "@/hooks/useItrntUserList";
import {useRouter} from "next/navigation"; import {useRouter} from "next/navigation";
import type {Route} from "next";
import {useCreateProjectMutation, useProjectListQuery, useProjectOwnerListQuery} from "@/query/project"; import {useCreateProjectMutation, useProjectListQuery, useProjectOwnerListQuery} from "@/query/project";
import {useGroupCodeListQuery} from "@/query/intranet"; import {useGroupCodeListQuery} from "@/query/intranet";
import {PROJECT_STATUS_LABEL} from "@/const/projectConst"; import {PROJECT_STATUS_LABEL} from "@/const/projectConst";
import {isManager} from "@/utils/userRole"; import {isInternalManager, isManager} from "@/utils/userRole";
const MainPage = () => { const MainPage = () => {
const router = useRouter(); const router = useRouter();
@@ -41,7 +45,6 @@ const MainPage = () => {
const [sorting, setSorting] = useState<SortingState>([]); const [sorting, setSorting] = useState<SortingState>([]);
const [query, setQuery] = useState<ProjectListQuery>(); const [query, setQuery] = useState<ProjectListQuery>();
const statusArray: MultiSelectOption[] = useMemo(() => { const statusArray: MultiSelectOption[] = useMemo(() => {
return (Object.values(ProjectStatus).filter((v) => typeof v === "number") as number[]) return (Object.values(ProjectStatus).filter((v) => typeof v === "number") as number[])
.sort((a, b) => a - b) .sort((a, b) => a - b)
@@ -99,10 +102,13 @@ const MainPage = () => {
const [searchStatus, setSearchStatus] = useState<string[]>([]); const [searchStatus, setSearchStatus] = useState<string[]>([]);
const [searchDept, setSearchDept] = useState<string[]>([]); const [searchDept, setSearchDept] = useState<string[]>([]);
const [searchFw, setSearchFw] = useState<string[]>([]); const [searchFw, setSearchFw] = useState<string[]>([]);
// 모바일(md 미만)에서만 필터 영역을 접고 펼친다. md 이상에서는 항상 노출된다.
const [filtersOpen, setFiltersOpen] = useState(false);
const hasActiveFilters = searchStatus.length > 0 || searchDept.length > 0 || searchFw.length > 0;
const columns = getProjectColumns(users, groupCodeLabelMap);
const userId = auth.user?.userId ?? ""; const userId = auth.user?.userId ?? "";
const userRole = auth.user?.userRole; const userRole = auth.user?.userRole;
const isInternal = isInternalManager(userRole);
const handleSearchClick = () => { const handleSearchClick = () => {
const searchStatusCode:ProjectStatus[] = searchStatus const searchStatusCode:ProjectStatus[] = searchStatus
@@ -123,9 +129,7 @@ const MainPage = () => {
showDialog('projectCreateDialog'); showDialog('projectCreateDialog');
} }
const handleSubmit = async (data: ProjectCreateRequest): Promise<void> => { const navigateWithProject = (projectInfo: ProjectInfo, path: Route) => {
const projectInfo = await createMutation.mutateAsync(data);
setSelectedProject({ setSelectedProject({
prjctIdx: projectInfo.prjctIdx, prjctIdx: projectInfo.prjctIdx,
prjctCd: projectInfo.prjctCd, prjctCd: projectInfo.prjctCd,
@@ -136,22 +140,19 @@ const MainPage = () => {
ff: projectInfo.ff ff: projectInfo.ff
} as SelectedProject); } as SelectedProject);
router.push("/project/info"); router.push(path);
}; };
const handleClick = (projectInfo:ProjectInfo) => { const handleSubmit = async (data: ProjectCreateRequest): Promise<void> => {
setSelectedProject({ const projectInfo = await createMutation.mutateAsync(data);
prjctIdx: projectInfo.prjctIdx, navigateWithProject(projectInfo, "/project/info");
prjctCd: projectInfo.prjctCd, };
prjctName: projectInfo.prjctName,
itrntPrjctCd: projectInfo.itrntPrjctCd,
ownerDept: projectInfo.ownerDept,
ownerFw: projectInfo.ownerFw,
ff: projectInfo.ff
} as SelectedProject);
router.push(`/list/manage`); const handleClick = (projectInfo: ProjectInfo) => navigateWithProject(projectInfo, "/list/manage");
}
const handleNavigateToInfo = (projectInfo: ProjectInfo) => navigateWithProject(projectInfo, "/project/info");
const columns = getProjectColumns(users, groupCodeLabelMap, isInternal ? handleNavigateToInfo : undefined);
if (!mounted || isLoading) return <LoadingOverlayAdapter force />; if (!mounted || isLoading) return <LoadingOverlayAdapter force />;
@@ -159,11 +160,12 @@ const MainPage = () => {
<div className="space-y-6 text-sm"> <div className="space-y-6 text-sm">
<AppPageTitle titleText={"프로젝트"}/> <AppPageTitle titleText={"프로젝트"}/>
<div className="flex gap-2 items-center"> <div className="flex flex-col gap-2 md:flex-row md:flex-wrap md:items-center">
<div className="flex flex-1 items-center gap-2"> <div className="flex flex-col gap-2 md:flex-1 md:flex-row md:flex-wrap md:items-center">
<div className="flex items-center gap-2">
<Input <Input
placeholder="프로젝트 코드 Or 프로젝트 명" placeholder="프로젝트 코드 Or 프로젝트 명"
className="w-120 h-9 bg-white" className="h-9 flex-1 bg-white md:w-120 md:flex-none"
value={searchText} value={searchText}
onChange={(e) => setSearchText(e.target.value)} onChange={(e) => setSearchText(e.target.value)}
onKeyDown={(e) => { onKeyDown={(e) => {
@@ -172,6 +174,34 @@ const MainPage = () => {
} }
}} }}
/> />
<Button
className="md:hidden"
onClick={handleSearchClick}
>
검색
</Button>
</div>
<Button
type="button"
variant="outline"
className="w-full justify-between md:hidden"
aria-expanded={filtersOpen}
aria-controls="project-search-filters"
onClick={() => setFiltersOpen((prev) => !prev)}
>
<span className="flex items-center gap-2">
필터
{hasActiveFilters ? <Badge>적용 중</Badge> : null}
</span>
<ChevronDown className={cn("h-4 w-4 transition-transform", filtersOpen && "rotate-180")} />
</Button>
<div
id="project-search-filters"
className={cn(
"flex flex-col gap-2 md:flex-row md:flex-wrap md:items-center",
!filtersOpen && "hidden md:flex",
)}
>
{ {
isManager(userRole) && isManager(userRole) &&
<KriMultiSelect <KriMultiSelect
@@ -181,7 +211,7 @@ const MainPage = () => {
getValue={(item) => item.value} getValue={(item) => item.value}
getLabel={(item) => item.label} getLabel={(item) => item.label}
placeholder="진행 상태" placeholder="진행 상태"
widthClassName="w-60" widthClassName="w-full md:w-60"
heightClassName="h-9" heightClassName="h-9"
/> />
} }
@@ -192,7 +222,7 @@ const MainPage = () => {
getValue={(item) => item.value} getValue={(item) => item.value}
getLabel={(item) => item.label} getLabel={(item) => item.label}
placeholder="담당 그룹" placeholder="담당 그룹"
widthClassName="w-60" widthClassName="w-full md:w-60"
heightClassName="h-9" heightClassName="h-9"
/> />
<KriMultiSelect <KriMultiSelect
@@ -202,20 +232,25 @@ const MainPage = () => {
getValue={(item) => item.value} getValue={(item) => item.value}
getLabel={(item) => item.label} getLabel={(item) => item.label}
placeholder="담당 실사" placeholder="담당 실사"
widthClassName="w-60" widthClassName="w-full md:w-60"
heightClassName="h-9" heightClassName="h-9"
/> />
</div>
<Button <Button
className="hidden md:inline-flex"
onClick={handleSearchClick} onClick={handleSearchClick}
> >
검색 검색
</Button> </Button>
</div> </div>
{isInternal && (
<Button <Button
className="w-full md:w-auto"
onClick={handleCreateClick} onClick={handleCreateClick}
> >
프로젝트 등록 프로젝트 등록
</Button> </Button>
)}
</div> </div>
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden"> <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">

View File

@@ -11,12 +11,14 @@ import { clientEnv } from "@/lib/env.client";
import { MessageType } from "@kri/common/noti-hub"; import { MessageType } from "@kri/common/noti-hub";
import type { SendResultSummaryResponse } from "@kri/common/noti-hub"; import type { SendResultSummaryResponse } from "@kri/common/noti-hub";
const SEND_TYPE_ORDER = [MessageType.SMS, MessageType.LMS_MMS, MessageType.EMAIL] as const; const SEND_TYPE_ORDER = [MessageType.SMS, MessageType.LMS, MessageType.MMS, MessageType.EMAIL, MessageType.KKO] as const;
const SEND_TYPE_LABEL: Record<number, string> = { const SEND_TYPE_LABEL: Record<number, string> = {
[MessageType.SMS]: "단문", [MessageType.SMS]: "단문",
[MessageType.LMS_MMS]: "장문", [MessageType.LMS]: "장문",
[MessageType.MMS]: "첨부 문자",
[MessageType.EMAIL]: "메일", [MessageType.EMAIL]: "메일",
[MessageType.KKO]: "알림톡",
}; };
type SummaryRow = { type SummaryRow = {
@@ -27,6 +29,7 @@ type SummaryRow = {
successCount: number; successCount: number;
failCount: number; failCount: number;
standByCount: number; standByCount: number;
canceledCount: number;
}; };
const sum = (list: SendResultSummaryResponse[], field: keyof SendResultSummaryResponse) => const sum = (list: SendResultSummaryResponse[], field: keyof SendResultSummaryResponse) =>
@@ -43,34 +46,22 @@ const buildRows = (data: SendResultSummaryResponse[]): SummaryRow[] =>
successCount: sum(matched, "successCount"), successCount: sum(matched, "successCount"),
failCount: sum(matched, "failCount"), failCount: sum(matched, "failCount"),
standByCount: sum(matched, "standByCount"), standByCount: sum(matched, "standByCount"),
canceledCount: sum(matched, "canceledCount"),
}; };
}); });
const moneyUnit = (value: number) => `${value.toLocaleString()}원`; const moneyUnit = (value: number) => `${value.toLocaleString()}원`;
const caseUnit = (value: number) => `${value.toLocaleString()}건`; const caseUnit = (value: number) => `${value.toLocaleString()}건`;
const getFirstDayOfMonth = (date: Date) => {
const d = new Date(date.getFullYear(), date.getMonth(), 1);
return d.toISOString().slice(0, 10);
};
const getLastDayOfMonth = (date: Date) => {
const d = new Date(date.getFullYear(), date.getMonth() + 1, 0);
return d.toISOString().slice(0, 10);
};
const MessageProgressPage = () => { const MessageProgressPage = () => {
const mounted = useMounted(); const mounted = useMounted();
const { selectedProject } = useSelectedProject(); const { selectedProject } = useSelectedProject();
const [dateRange, setDateRange] = useState(() => { const [dateRange, setDateRange] = useState({ from: "", to: "" });
const now = new Date();
return { from: getFirstDayOfMonth(now), to: getLastDayOfMonth(now) };
});
const prjctCd = selectedProject?.prjctCd ?? ""; const prjctCd = selectedProject?.prjctCd ?? "";
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? ""; const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? "";
const enabled = mounted && !!prjctCd && !!dateRange.from && !!dateRange.to; const enabled = mounted && !!prjctCd;
const summaryQuery = useSendResultSummaryQuery( const summaryQuery = useSendResultSummaryQuery(
{ {
@@ -92,6 +83,7 @@ const MessageProgressPage = () => {
successCount: rows.reduce((acc, row) => acc + row.successCount, 0), successCount: rows.reduce((acc, row) => acc + row.successCount, 0),
failCount: rows.reduce((acc, row) => acc + row.failCount, 0), failCount: rows.reduce((acc, row) => acc + row.failCount, 0),
standByCount: rows.reduce((acc, row) => acc + row.standByCount, 0), standByCount: rows.reduce((acc, row) => acc + row.standByCount, 0),
canceledCount: rows.reduce((acc, row) => acc + row.canceledCount, 0),
}), }),
[rows], [rows],
); );
@@ -106,7 +98,7 @@ const MessageProgressPage = () => {
<div className="rounded-md border overflow-hidden"> <div className="rounded-md border overflow-hidden">
<table className="w-full text-sm"> <table className="w-full text-sm">
<thead className="bg-blue-50"> <thead className="bg-primary text-primary-foreground">
<tr> <tr>
<th className="h-10 px-3 text-center font-semibold border-b">유형</th> <th className="h-10 px-3 text-center font-semibold border-b">유형</th>
<th className="h-10 px-3 text-center font-semibold border-b">단가</th> <th className="h-10 px-3 text-center font-semibold border-b">단가</th>
@@ -115,6 +107,7 @@ const MessageProgressPage = () => {
<th className="h-10 px-3 text-center font-semibold border-b">성공</th> <th className="h-10 px-3 text-center font-semibold border-b">성공</th>
<th className="h-10 px-3 text-center font-semibold border-b">실패</th> <th className="h-10 px-3 text-center font-semibold border-b">실패</th>
<th className="h-10 px-3 text-center font-semibold border-b">발송중</th> <th className="h-10 px-3 text-center font-semibold border-b">발송중</th>
<th className="h-10 px-3 text-center font-semibold border-b">취소</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -127,6 +120,7 @@ const MessageProgressPage = () => {
<td className="h-10 px-3 text-center">{caseUnit(row.successCount)}</td> <td className="h-10 px-3 text-center">{caseUnit(row.successCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(row.failCount)}</td> <td className="h-10 px-3 text-center">{caseUnit(row.failCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(row.standByCount)}</td> <td className="h-10 px-3 text-center">{caseUnit(row.standByCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(row.canceledCount)}</td>
</tr> </tr>
))} ))}
<tr className="bg-gray-50 font-semibold"> <tr className="bg-gray-50 font-semibold">
@@ -136,6 +130,7 @@ const MessageProgressPage = () => {
<td className="h-10 px-3 text-center">{caseUnit(total.successCount)}</td> <td className="h-10 px-3 text-center">{caseUnit(total.successCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(total.failCount)}</td> <td className="h-10 px-3 text-center">{caseUnit(total.failCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(total.standByCount)}</td> <td className="h-10 px-3 text-center">{caseUnit(total.standByCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(total.canceledCount)}</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>

View File

@@ -1,19 +1,18 @@
'use client' 'use client'
import { useEffect, useRef, useState } from "react";
import { useMounted } from "@kri/common/hooks"; import { useMounted } from "@kri/common/hooks";
import AppPageTitle from "@/components/app-shell/AppPageTitle"; import AppPageTitle from "@/components/app-shell/AppPageTitle";
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter"; import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { useSelectedProject } from "@/hooks/useSelectedProject"; import { useSelectedProject } from "@/hooks/useSelectedProject";
import { useProjectInfoQuery, useSurveyRedirectUrlQuery } from "@/query/project"; import { useProjectInfoQuery } from "@/query/project";
import { clientEnv } from "@/lib/env.client";
import { SurveyType } from "@/types/project"; import { SurveyType } from "@/types/project";
import { SURVEY_TYPE_LABEL } from "@/const/projectConst"; import { SURVEY_TYPE_LABEL } from "@/const/projectConst";
const SurveyProgressPage = () => { const SurveyProgressPage = () => {
const mounted = useMounted(); const mounted = useMounted();
const { selectedProject } = useSelectedProject(); const { selectedProject } = useSelectedProject();
const openedForRef = useRef<string | null>(null);
const prjctIdx = selectedProject?.prjctIdx ?? 0; const prjctIdx = selectedProject?.prjctIdx ?? 0;
const enabled = mounted && prjctIdx > 0; const enabled = mounted && prjctIdx > 0;
@@ -21,35 +20,7 @@ const SurveyProgressPage = () => {
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled); const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled);
const surveys = projectInfoQuery.data?.surveys ?? []; const surveys = projectInfoQuery.data?.surveys ?? [];
const [activeSurveyIdx, setActiveSurveyIdx] = useState<number | null>(null); const isLoading = !mounted || projectInfoQuery.isLoading;
const [openedUrl, setOpenedUrl] = useState<string | null>(null);
const selectedSurvey = surveys.find((s) => s.prjctSurveyIdx === activeSurveyIdx) ?? null;
const surveyTy = selectedSurvey?.surveyTy ?? SurveyType.NONE;
const isKonKiwi = surveyTy === SurveyType.KON || surveyTy === SurveyType.KIWI;
const isKiwi = surveyTy === SurveyType.KIWI ? 1 : 0;
const pkey = selectedSurvey?.surveyPrjctCd ?? "";
const redirectUrlEnabled = enabled && !!selectedSurvey && isKonKiwi && !!pkey;
const redirectUrlQuery = useSurveyRedirectUrlQuery(isKiwi, pkey, redirectUrlEnabled);
const targetUrl = !selectedSurvey
? null
: isKonKiwi
? (redirectUrlQuery.data ?? null)
: surveyTy === SurveyType.EXTERNAL
? (selectedSurvey.surveyDashboardUrl || null)
: null;
useEffect(() => {
if (!targetUrl || openedForRef.current === targetUrl) return;
openedForRef.current = targetUrl;
window.open(targetUrl, "_blank");
setOpenedUrl(targetUrl);
}, [targetUrl]);
const isLoading = !mounted || projectInfoQuery.isLoading || (redirectUrlEnabled && redirectUrlQuery.isLoading);
if (isLoading) return <LoadingOverlayAdapter force />; if (isLoading) return <LoadingOverlayAdapter force />;
@@ -62,7 +33,14 @@ const SurveyProgressPage = () => {
) : ( ) : (
<div className="max-w-[600px] space-y-2"> <div className="max-w-[600px] space-y-2">
{surveys.map((survey) => { {surveys.map((survey) => {
const hasReport = survey.surveyTy !== SurveyType.NONE; const isKonKiwi = survey.surveyTy === SurveyType.KON || survey.surveyTy === SurveyType.KIWI;
let targetUrl: string | null = null;
if (isKonKiwi && survey.surveyPrjctCd) {
const projectType = survey.surveyTy === SurveyType.KIWI ? 1 : 0;
targetUrl = `${clientEnv.KART_URL}/Report/Current?projectType=${projectType}&pkey=${encodeURIComponent(survey.surveyPrjctCd)}`;
} else if (survey.surveyTy === SurveyType.EXTERNAL) {
targetUrl = survey.surveyDashboardUrl || null;
}
return ( return (
<div <div
key={survey.prjctSurveyIdx ?? survey.surveyOrder} key={survey.prjctSurveyIdx ?? survey.surveyOrder}
@@ -72,28 +50,21 @@ const SurveyProgressPage = () => {
<p className="font-semibold">{survey.surveyName}</p> <p className="font-semibold">{survey.surveyName}</p>
<p className="text-xs text-muted-foreground">{SURVEY_TYPE_LABEL[survey.surveyTy]}</p> <p className="text-xs text-muted-foreground">{SURVEY_TYPE_LABEL[survey.surveyTy]}</p>
</div> </div>
<Button {targetUrl ? (
type="button" <Button asChild>
disabled={!hasReport} <a href={targetUrl} target="_blank" rel="noopener noreferrer">
onClick={() => setActiveSurveyIdx(survey.prjctSurveyIdx ?? null)}
>
바로가기 바로가기
</a>
</Button> </Button>
) : (
<Button type="button" disabled>바로가기</Button>
)}
</div> </div>
); );
})} })}
</div> </div>
)} )}
{openedUrl ? (
<p>
새 창에서 열립니다. 열리지 않았다면{" "}
<a href={openedUrl} target="_blank" rel="noreferrer" className="text-blue-600 underline">
여기
</a>
를 클릭해 주세요.
</p>
) : null}
</div> </div>
); );
}; };

View File

@@ -13,7 +13,7 @@ import {useDialog} from '@/hooks/useDialog'
import ResultCodeDialog from '@/components/dialog/ResultCodeDialog' import ResultCodeDialog from '@/components/dialog/ResultCodeDialog'
import { useDebouncedValue, useMounted } from "@kri/common/hooks"; import { useDebouncedValue, useMounted } from "@kri/common/hooks";
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter' import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
import { X } from 'lucide-react' import { X, Copy, Check } from 'lucide-react'
import { import {
ProjectInfo, ProjectSurvey, ProjectUpdateRequest, ResultCode, ProjectInfo, ProjectSurvey, ProjectUpdateRequest, ResultCode,
ProjectStatus, ResultCodeType, SurveyType ProjectStatus, ResultCodeType, SurveyType
@@ -123,7 +123,6 @@ const createSurveyDraft = (surveyOrder: number): SurveyDraft => ({
surveyPrjctCd: '', surveyPrjctCd: '',
surveyUrl: '', surveyUrl: '',
surveyFullUrl: null, surveyFullUrl: null,
surveyShortUrl: null,
surveyDashboardUrl: '', surveyDashboardUrl: '',
}) })
@@ -168,7 +167,6 @@ const SurveyCard = ({ survey, index, itrntPrjctCd, userTeam, invalidField, onReg
surveyPrjctCd: '', surveyPrjctCd: '',
surveyUrl: '', surveyUrl: '',
surveyFullUrl: null, surveyFullUrl: null,
surveyShortUrl: null,
surveyDashboardUrl: '', surveyDashboardUrl: '',
}) })
} }
@@ -178,14 +176,57 @@ const SurveyCard = ({ survey, index, itrntPrjctCd, userTeam, invalidField, onReg
surveyPrjctCd: value, surveyPrjctCd: value,
surveyUrl: buildKonKiwiSurveyUrl(survey.surveyTy), surveyUrl: buildKonKiwiSurveyUrl(survey.surveyTy),
surveyFullUrl: null, surveyFullUrl: null,
surveyShortUrl: null,
}) })
} }
// KON/KIWI는 호스트 placeholder까지 고정하고 '?' 이후 쿼리스트링만 편집 가능하게 한다.
const konKiwiPlaceholderPrefix = survey.surveyTy === SurveyType.KIWI ? 'https://[$KIWI-URL]' : 'https://[$KON-URL]'
// 저장 후 surveyUrl의 placeholder가 실제(단축) 호스트로 치환되므로 현재 base를 그대로 접두어로 쓴다.
const konKiwiUrlBase = survey.surveyUrl?.trim()
? survey.surveyUrl.split('?')[0]
: konKiwiPlaceholderPrefix
const konKiwiQuery = (() => {
const url = survey.surveyUrl ?? ''
const idx = url.indexOf('?')
return idx >= 0 ? url.slice(idx + 1) : ''
})()
const handleKonKiwiQueryChange = (nextQuery: string) => {
// 파라미터만 수정: surveyUrl base(단축/placeholder)는 유지하고 뒤 파라미터만 교체한다.
const patch: Partial<ProjectSurvey> = {
surveyUrl: `${konKiwiUrlBase}?${nextQuery}`,
}
// surveyFullUrl은 base(psidx 등)는 고정하고, 동일한 파라미터 꼬리만 함께 교체한다.
// 파라미터 꼬리를 갖지 않는 값(순수 단축 URL 등)은 건드리지 않는다.
const fullUrl = survey.surveyFullUrl
if (fullUrl && konKiwiQuery && fullUrl.endsWith(konKiwiQuery)) {
patch.surveyFullUrl = fullUrl.slice(0, fullUrl.length - konKiwiQuery.length) + nextQuery
}
onChange(survey.uiKey, patch)
}
const [copiedField, setCopiedField] = useState<'url' | 'fullUrl' | null>(null)
const copyToClipboard = async (value: string | null | undefined, field: 'url' | 'fullUrl') => {
const text = value?.trim() ?? ''
if (!text) return
try {
await navigator.clipboard.writeText(text)
setCopiedField(field)
setTimeout(() => setCopiedField((prev) => (prev === field ? null : prev)), 1500)
} catch {
// 클립보드 접근 실패 시 무시
}
}
return ( return (
<div className="space-y-3 rounded-lg border p-4"> <div className="space-y-3 rounded-lg border p-4">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<p className="text-base font-semibold">설문 {index + 1}</p> <p className="text-base font-semibold">설문 {index + 1}</p>
<span className="text-sm font-semibold ">
(설문 번호: {survey.prjctSurveyIdx ?? '미발급'})
</span>
</div>
<Button type="button" variant="ghost" size="icon-sm" onClick={() => onRemove(survey.uiKey)} aria-label="설문 삭제"> <Button type="button" variant="ghost" size="icon-sm" onClick={() => onRemove(survey.uiKey)} aria-label="설문 삭제">
<X className="h-4 w-4" /> <X className="h-4 w-4" />
</Button> </Button>
@@ -238,23 +279,60 @@ const SurveyCard = ({ survey, index, itrntPrjctCd, userTeam, invalidField, onReg
heightClassName="h-9" heightClassName="h-9"
widthClassName="w-full" widthClassName="w-full"
/> />
{kartProjectListQuery.isError && (
<div role="alert" className="flex items-center gap-2 text-destructive">
<span>프로젝트 목록을 불러오지 못했습니다.</span>
<Button type="button" variant="outline" size="sm" onClick={() => void kartProjectListQuery.refetch()}>
다시 시도
</Button>
</div>
)}
</div> </div>
)} )}
<div className="space-y-2"> <div className="space-y-2">
<div className="flex items-center gap-2">
<Label className="text-base">설문 URL</Label> <Label className="text-base">설문 URL</Label>
</div>
<div className="flex items-center gap-2">
{isKonKiwi ? (
<div className="flex flex-1 items-center">
<span className="inline-flex h-9 items-center whitespace-nowrap rounded-l-md border border-r-0 bg-gray-100 px-3 text-sm text-muted-foreground">
{konKiwiUrlBase}?
</span>
<Input
ref={onRegisterFieldRef(survey.uiKey, 'surveyUrl')}
value={konKiwiQuery}
onChange={(e) => handleKonKiwiQueryChange(e.target.value)}
placeholder="sid=[$SID]"
className="h-9 rounded-l-none"
aria-invalid={invalidField === 'surveyUrl'}
/>
</div>
) : (
<Input <Input
ref={onRegisterFieldRef(survey.uiKey, 'surveyUrl')} ref={onRegisterFieldRef(survey.uiKey, 'surveyUrl')}
value={survey.surveyUrl || ''} value={survey.surveyUrl || ''}
onChange={(e) => onChange(survey.uiKey, { onChange={(e) => onChange(survey.uiKey, {
surveyUrl: e.target.value, surveyUrl: e.target.value,
surveyFullUrl: null, surveyFullUrl: null,
surveyShortUrl: null,
})} })}
placeholder="https://" placeholder="https://"
className="h-9" className="h-9 flex-1"
aria-invalid={invalidField === 'surveyUrl'} aria-invalid={invalidField === 'surveyUrl'}
/> />
)}
<Button
type="button"
variant="outline"
onClick={() => copyToClipboard(survey.surveyUrl, 'url')}
disabled={!survey.surveyUrl?.trim()}
aria-label="설문 URL 복사"
className="h-9 w-9 shrink-0 p-0"
>
{copiedField === 'url' ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
</Button>
</div>
</div> </div>
{survey.surveyTy === SurveyType.EXTERNAL && ( {survey.surveyTy === SurveyType.EXTERNAL && (
@@ -333,7 +411,7 @@ const SurveyCard = ({ survey, index, itrntPrjctCd, userTeam, invalidField, onReg
const ProjectInfoPage = () => { const ProjectInfoPage = () => {
const router = useRouter(); const router = useRouter();
const mounted = useMounted(); const mounted = useMounted();
const {selectedProject} = useSelectedProject(); const {selectedProject, setSelectedProject} = useSelectedProject();
const {isDialogOpen, showDialog, hideDialog} = useDialog(); const {isDialogOpen, showDialog, hideDialog} = useDialog();
const {users} = useItrntUserList(); const {users} = useItrntUserList();
const {auth} = useAuth(); const {auth} = useAuth();
@@ -374,7 +452,7 @@ const ProjectInfoPage = () => {
const updateMutation = useUpdateProjectMutation(prjctIdx); const updateMutation = useUpdateProjectMutation(prjctIdx);
const deleteMutation = useDeleteProjectMutation(prjctIdx); const deleteMutation = useDeleteProjectMutation(prjctIdx);
const uploadScenarioMutation = useUploadScenarioImageMutation(prjctIdx, projectInfo.prjctCd); const uploadScenarioMutation = useUploadScenarioImageMutation(projectInfo.prjctCd);
const [resultCodeArray, setResultCodeArray] = useState<ResultCode[]>([]); const [resultCodeArray, setResultCodeArray] = useState<ResultCode[]>([]);
const [assignCmpnIdArray, setAssignCmpnIdArray] = useState<string[]>([]); const [assignCmpnIdArray, setAssignCmpnIdArray] = useState<string[]>([]);
@@ -544,6 +622,16 @@ const ProjectInfoPage = () => {
} }
await updateMutation.mutateAsync(requestUpdateProject); await updateMutation.mutateAsync(requestUpdateProject);
const savedProjectInfo = requestUpdateProject.projectInfo;
setSelectedProject({
prjctIdx: savedProjectInfo.prjctIdx,
prjctCd: savedProjectInfo.prjctCd,
prjctName: savedProjectInfo.prjctName,
itrntPrjctCd: savedProjectInfo.itrntPrjctCd,
ownerDept: savedProjectInfo.ownerDept,
ownerFw: savedProjectInfo.ownerFw,
ff: savedProjectInfo.ff,
});
initialProjectInfoRef.current = projectInfo; initialProjectInfoRef.current = projectInfo;
alert("저장되었습니다."); alert("저장되었습니다.");
} }
@@ -700,7 +788,9 @@ const ProjectInfoPage = () => {
<div className="border rounded-lg p-6 space-y-4 bg-white mt-3"> <div className="border rounded-lg p-6 space-y-4 bg-white mt-3">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<h3 className="text-xl font-semibold">설문 연동</h3> <div className="flex items-center gap-4">
<h3 className="shrink-0 text-xl font-semibold">설문 연동</h3>
</div>
<Button type="button" variant="outline" onClick={handleAddSurvey}> <Button type="button" variant="outline" onClick={handleAddSurvey}>
설문 추가 설문 추가
</Button> </Button>

View File

@@ -9,17 +9,25 @@ import {useRouter} from "next/navigation";
import {apiError} from "@kri/common/http"; import {apiError} from "@kri/common/http";
import {NONE_HTTP_ERROR} from "@kri/common/http"; import {NONE_HTTP_ERROR} from "@kri/common/http";
import {useLoginMutation} from "@/query/auth"; import {useLoginMutation} from "@/query/auth";
import {useInternalInfoQuery} from "@/query/internal";
import {cn} from "@/lib/utils";
const LoginPage = () => { const LoginPage = () => {
const router = useRouter(); const router = useRouter();
const loginMutation = useLoginMutation(); const loginMutation = useLoginMutation();
const internalInfoQuery = useInternalInfoQuery(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [userId, setUserId] = useState<string>(""); const [userId, setUserId] = useState<string>("");
const [userPw, setUserPw] = useState<string>(""); const [userPw, setUserPw] = useState<string>("");
const clientIp = internalInfoQuery.data?.clientIp || "";
const clientId = internalInfoQuery.data?.clientId || "";
const isCallSeat = clientIp.startsWith("10.10.15");
const isCallSeatAndUnable = isCallSeat && clientId === "";
const passwordInputRef = useRef<HTMLInputElement | null>(null); const passwordInputRef = useRef<HTMLInputElement | null>(null);
const tryLogin = async () => { const tryLogin = async () => {
@@ -107,7 +115,12 @@ const LoginPage = () => {
ref={passwordInputRef} ref={passwordInputRef}
/> />
</div> </div>
<p className="text-base">
IP: {clientIp}
</p>
<p className={cn("text-base", isCallSeatAndUnable && "font-bold text-red-500")}>
{isCallSeatAndUnable? "전화걸기 이용 불가(관리자에게 문의해 주세요)" : `자리번호: ${clientId}`}
</p>
{error && ( {error && (
<p className="text-sm text-red-500"> <p className="text-sm text-red-500">
{error} {error}
@@ -116,7 +129,7 @@ const LoginPage = () => {
<Button <Button
type="submit" type="submit"
className="w-full mt-6 h-11" className="w-full mt-3 h-11"
disabled={loginMutation.isPending} disabled={loginMutation.isPending}
onClick={(e) => { onClick={(e) => {
e.preventDefault(); e.preventDefault();

View File

@@ -14,10 +14,8 @@ const toRedirectSlug = (slug: string): RedirectSlug | null => {
const redirectPage = async ({ const redirectPage = async ({
params, params,
searchParams,
}: redirectPageProps) => { }: redirectPageProps) => {
const { slug } = await params; const { slug } = await params;
const sp = searchParams ? await searchParams : undefined;
const redirectSlug = toRedirectSlug(slug); const redirectSlug = toRedirectSlug(slug);
if (!redirectSlug) notFound(); if (!redirectSlug) notFound();

View File

@@ -2,6 +2,7 @@
import {RouteContext} from "@/types/common"; import {RouteContext} from "@/types/common";
import {createContactApi} from "@/lib/http-server"; import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@kri/common/http"; import {errorToResponse} from "@kri/common/http";
import type {ProjectCompanyAssignSummary, ProjectFieldworkAssignSummary} from "@/types/list";
export const GET = async (req: NextRequest, context: RouteContext) => { export const GET = async (req: NextRequest, context: RouteContext) => {
try { try {
@@ -19,6 +20,25 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
return NextResponse.json(result, { status: 200 }); return NextResponse.json(result, { status: 200 });
} }
if (action === "prjct-cmpn-summary" && slug.length === 2) {
const result = await contactApi.get<ProjectCompanyAssignSummary>(`/assign/prjct-cmpn-summary/${slug[1]}`);
return NextResponse.json(result, { status: 200 });
}
if (action === "prjct-fieldwork-summary" && slug.length === 2) {
const assignType = req.nextUrl.searchParams.get("assignType");
const cmpnIds = req.nextUrl.searchParams.get("cmpnIds");
if (!assignType) {
return NextResponse.json({ message: "assignType이 필요합니다." }, { status: 400 });
}
const query = `?assignType=${assignType}${cmpnIds ? `&cmpnIds=${encodeURIComponent(cmpnIds)}` : ""}`;
const result = await contactApi.get<ProjectFieldworkAssignSummary>(
`/assign/prjct-fieldwork-summary/${slug[1]}${query}`,
);
return NextResponse.json(result, { status: 200 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 }); return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) { } catch (error: unknown) {
return errorToResponse(error); return errorToResponse(error);
@@ -44,37 +64,6 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
return new NextResponse(null, { status: 204 }); return new NextResponse(null, { status: 204 });
} }
if (action === "list" && slug.length === 3) {
const body = await req.json().catch(() => null);
if (!body) {
return NextResponse.json(
{ message: "요청 바디가 없습니다." },
{ status: 400 }
);
}
const result = await contactApi.put<number>(`/assign/list/${slug[1]}/${slug[2]}`, body);
return NextResponse.json(result, { status: 200 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
export const DELETE = async (req: NextRequest, context: RouteContext) => {
try {
const { slug = [] } = await context.params;
const [action] = slug;
const contactApi = await createContactApi();
if (action === "list" && slug[1] === "reset" && slug.length === 3) {
const body = await req.json().catch(() => null);
const result = await contactApi.del<number>(`/assign/list/reset/${slug[2]}`, { json: body });
return NextResponse.json(result, { status: 200 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 }); return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) { } catch (error: unknown) {
return errorToResponse(error); return errorToResponse(error);

View File

@@ -0,0 +1,22 @@
import { NextResponse } from "next/server";
import { errorToResponse } from "@kri/common/http";
import { createContactApi } from "@/lib/http-server";
import {isLoginUser} from "@/lib/auth-user";
export async function GET(_request: Request, context: { params: Promise<{ slug?: string[] }> }) {
const { slug = [] } = await context.params;
if (slug.length !== 1 || slug[0] !== "my-info")
return NextResponse.json({ message: "Not found" }, { status: 404, headers: { "Cache-Control": "no-store" } });
try {
const api = await createContactApi();
const user = await api.get<unknown>("/auth/my-info", { cache: "no-store" });
if (!isLoginUser(user)) {
return NextResponse.json({ message: "Invalid user response" }, { status: 502, headers: { "Cache-Control": "no-store" } });
}
return NextResponse.json({ userId: user.userId, userName: user.userName, userCmpn: user.userCmpn, userTeam: user.userTeam, userRole: user.userRole }, { headers: { "Cache-Control": "no-store" } });
} catch (error) {
const response = errorToResponse(error);
response.headers.set("Cache-Control", "no-store");
return response;
}
}

View File

@@ -33,11 +33,14 @@ const toRequiredNumber = (value: string): number | null => {
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null; return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;
}; };
const toRequiredSid = (value: string): string | null =>
value.length > 0 ? value : null;
const buildExternalEventBody = ( const buildExternalEventBody = (
req: NextRequest, req: NextRequest,
action: ExternalAction, action: ExternalAction,
prjctSurveyIdx: number, prjctSurveyIdx: number,
sid: number, sid: string,
): ExternalEventBody => { ): ExternalEventBody => {
const pathname = req.nextUrl.pathname; const pathname = req.nextUrl.pathname;
const h = req.headers; const h = req.headers;
@@ -51,7 +54,7 @@ const buildExternalEventBody = (
entryType: getEntryTypeCode(h), entryType: getEntryTypeCode(h),
action: actionCode, action: actionCode,
psidx: String(prjctSurveyIdx), psidx: String(prjctSurveyIdx),
sid: String(sid), sid,
remoteAddr: getHeader(h, "x-orig-ip") || getClientIp(req), remoteAddr: getHeader(h, "x-orig-ip") || getClientIp(req),
uri: getHeader(h, "x-orig-uri") || pathname, uri: getHeader(h, "x-orig-uri") || pathname,
url: getHeader(h, "x-orig-url") || req.url, url: getHeader(h, "x-orig-url") || req.url,
@@ -75,7 +78,7 @@ const handleExternalEvent = async (req: NextRequest, context: RouteContext) => {
} }
const prjctSurveyIdx = toRequiredNumber((searchParams.get("psidx") ?? "").trim()); const prjctSurveyIdx = toRequiredNumber((searchParams.get("psidx") ?? "").trim());
const sid = toRequiredNumber((searchParams.get("sid") ?? "").trim()); const sid = toRequiredSid((searchParams.get("sid") ?? "").trim());
if (!prjctSurveyIdx || !sid) { if (!prjctSurveyIdx || !sid) {
return NextResponse.json({ message: "psidx, sid는 필수입니다." }, { status: 400 }); return NextResponse.json({ message: "psidx, sid는 필수입니다." }, { status: 400 });

View File

@@ -1,6 +1,6 @@
import {NextRequest, NextResponse} from "next/server"; import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common"; import {RouteContext} from "@/types/common";
import {createKartApi} from "@/lib/http-server"; import {createContactApi} from "@/lib/http-server";
import {KonKiwiProjectInfo} from "@/types/project"; import {KonKiwiProjectInfo} from "@/types/project";
import {errorToResponse} from "@kri/common/http"; import {errorToResponse} from "@kri/common/http";
@@ -9,32 +9,19 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
const { searchParams } = new URL(req.url); const { searchParams } = new URL(req.url);
const {slug = []} = await context.params; const {slug = []} = await context.params;
const [action] = slug; const [action] = slug;
const kartApi = await createKartApi(); const contactApi = await createContactApi();
if(action === "project-list" && slug.length === 4){ if(action === "project-list" && slug.length === 3){
const keyword = (searchParams.get("keyword") ?? "").trim(); const keyword = (searchParams.get("keyword") ?? "").trim();
const result = await kartApi.get<KonKiwiProjectInfo[]>( const [, intranetCode, projectType] = slug;
`/project/list/${slug[1]}/${slug[2]}/${slug[3]}`, if (!intranetCode.trim() || intranetCode.length > 32 || !["0", "1"].includes(projectType)) {
{ query: keyword ? { keyword } : {} } return NextResponse.json({ message: "프로젝트 정보를 확인해 주세요." }, { status: 400 });
);
return NextResponse.json(result, { status: 200 });
} }
const result = await contactApi.get<KonKiwiProjectInfo[]>(`/kart/project/list`, {
if(action === "survey-redirect-url" && slug.length === 3){ query: { intranetCode, projectType, ...(keyword ? { keyword } : {}) },
const [, isKiwi, pkey] = slug;
const skey = await kartApi.get<string>(`/encrypt/pkey`, {
headers: { pkey, iskiwi: isKiwi },
}); });
const shortUrl = await kartApi.post<string>( return NextResponse.json(result, { status: 200 });
`/uri/short`,
{ realURI: "/Report/Current", mode: "U" },
{ headers: { skey } },
);
return NextResponse.json(shortUrl, { status: 200 });
} }
return NextResponse.json({ message: "Not found" }, { status: 404 }); return NextResponse.json({ message: "Not found" }, { status: 404 });

View File

@@ -2,31 +2,13 @@ import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common"; import {RouteContext} from "@/types/common";
import {createContactApi} from "@/lib/http-server"; import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@kri/common/http"; import {errorToResponse} from "@kri/common/http";
import type {ListCallHistSession} from "@/types/list"; import type {ListCallHist} from "@/types/list";
export const GET = async (_req: NextRequest, context: RouteContext) => {
try {
const { slug = [] } = await context.params;
const [action, agentSessionId] = slug;
if (action !== "session" || !agentSessionId) {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
const contactApi = await createContactApi();
const result = await contactApi.get<ListCallHistSession>(
`/list-call-hist/session/${encodeURIComponent(agentSessionId)}`,
);
return NextResponse.json(result, { status: 200 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
export const PUT = async (req: NextRequest, context: RouteContext) => { export const PUT = async (req: NextRequest, context: RouteContext) => {
try { try {
const { slug = [] } = await context.params; const { slug = [] } = await context.params;
const [prjctIdx, sid] = slug; const [prjctIdx, sid, action] = slug;
if (!prjctIdx || !sid) { if (!prjctIdx || !sid || (action !== "call-start" && action !== "call-close")) {
return NextResponse.json({ message: "Not found" }, { status: 404 }); return NextResponse.json({ message: "Not found" }, { status: 404 });
} }
@@ -36,7 +18,10 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
} }
const contactApi = await createContactApi(); const contactApi = await createContactApi();
const result = await contactApi.put(`/list-call-hist/${prjctIdx}/${sid}`, body); const result = await contactApi.put<ListCallHist>(
`/list-call-hist/${prjctIdx}/${encodeURIComponent(sid)}/${action}`,
body,
);
return NextResponse.json(result, { status: 200 }); return NextResponse.json(result, { status: 200 });
} catch (error: unknown) { } catch (error: unknown) {
return errorToResponse(error); return errorToResponse(error);

View File

@@ -0,0 +1,115 @@
import { NextRequest, NextResponse } from "next/server";
import { RouteContext } from "@/types/common";
import { createContactApiWithApiKey } from "@/lib/http-server";
import { errorToResponse } from "@kri/common/http";
import { ListSearchExternal } from "@/types/list";
const getApiKey = (req: NextRequest) => req.headers.get("x-api-key");
// backend가 제공하는 메소드/경로 그대로 사용 (path variable)
export const GET = async (req: NextRequest, context: RouteContext) => {
try {
const apiKey = getApiKey(req);
if (!apiKey) {
return NextResponse.json({ message: "X-API-Key는 필수입니다." }, { status: 401 });
}
const { slug = [] } = await context.params;
const [action, prjctCd, sid] = slug;
const contactApi = await createContactApiWithApiKey(apiKey);
if (action === "header" && prjctCd) {
const result = await contactApi.get<string[]>(`/list-external/header/${encodeURIComponent(prjctCd)}`);
return NextResponse.json(result, { status: 200 });
}
if (action === "search" && prjctCd && sid) {
const result = await contactApi.get<ListSearchExternal>(
`/list-external/search/${encodeURIComponent(prjctCd)}/${encodeURIComponent(sid)}`,
);
return NextResponse.json(result, { status: 200 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
// backend가 제공하는 메소드/경로 그대로 사용 (path variable)
export const PATCH = async (req: NextRequest, context: RouteContext) => {
try {
const apiKey = getApiKey(req);
if (!apiKey) {
return NextResponse.json({ message: "X-API-Key는 필수입니다." }, { status: 401 });
}
const { slug = [] } = await context.params;
const [action, prjctCd, sid] = slug;
if (action === "update" && prjctCd && sid) {
const body = await req.json().catch(() => null);
const contactApi = await createContactApiWithApiKey(apiKey);
const result = await contactApi.patch<number>(
`/list-external/update/${encodeURIComponent(prjctCd)}/${encodeURIComponent(sid)}`,
body,
);
return NextResponse.json(result, { status: 200 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
// 외부 연동 호환용: 항상 POST, path variable을 모두 url 쿼리 파람으로 받아 backend path variable로 전달
export const POST = async (req: NextRequest, context: RouteContext) => {
try {
const apiKey = getApiKey(req);
if (!apiKey) {
return NextResponse.json({ message: "X-API-Key는 필수입니다." }, { status: 401 });
}
const { slug = [] } = await context.params;
const [action] = slug;
const { searchParams } = req.nextUrl;
const prjctCd = searchParams.get("prjctCd");
const sid = searchParams.get("sid");
const contactApi = await createContactApiWithApiKey(apiKey);
if (action === "header") {
if (!prjctCd) {
return NextResponse.json({ message: "prjctCd는 필수입니다." }, { status: 400 });
}
const result = await contactApi.get<string[]>(`/list-external/header/${encodeURIComponent(prjctCd)}`);
return NextResponse.json(result, { status: 200 });
}
if (action === "search") {
if (!prjctCd || !sid) {
return NextResponse.json({ message: "prjctCd, sid는 필수입니다." }, { status: 400 });
}
const result = await contactApi.get<ListSearchExternal>(
`/list-external/search/${encodeURIComponent(prjctCd)}/${encodeURIComponent(sid)}`,
);
return NextResponse.json(result, { status: 200 });
}
if (action === "update") {
if (!prjctCd || !sid) {
return NextResponse.json({ message: "prjctCd, sid는 필수입니다." }, { status: 400 });
}
const body = await req.json().catch(() => null);
const result = await contactApi.patch<number>(
`/list-external/update/${encodeURIComponent(prjctCd)}/${encodeURIComponent(sid)}`,
body,
);
return NextResponse.json(result, { status: 200 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};

View File

@@ -4,19 +4,23 @@ import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@kri/common/http"; import {errorToResponse} from "@kri/common/http";
import type {ListEventHistory, ListUpdateHistory} from "@/types/list"; import type {ListEventHistory, ListUpdateHistory} from "@/types/list";
export const GET = async (req: NextRequest, context: RouteContext) => { export const GET = async (_req: NextRequest, context: RouteContext) => {
try { try {
const { slug = [] } = await context.params; const { slug = [] } = await context.params;
const [action] = slug; const [action] = slug;
const contactApi = await createContactApi(); const contactApi = await createContactApi();
if (action === "event" && slug.length === 3) { if (action === "event" && slug.length === 3) {
const result = await contactApi.get<ListEventHistory[]>(`/list-hist/event/${slug[1]}/${slug[2]}`); const result = await contactApi.get<ListEventHistory[]>(
`/list-hist/event/${slug[1]}/${encodeURIComponent(slug[2])}`,
);
return NextResponse.json(result, { status: 200 }); return NextResponse.json(result, { status: 200 });
} }
if (action === "update" && slug.length === 3) { if (action === "update" && slug.length === 3) {
const result = await contactApi.get<ListUpdateHistory[]>(`/list-hist/update/${slug[1]}/${slug[2]}`); const result = await contactApi.get<ListUpdateHistory[]>(
`/list-hist/update/${slug[1]}/${encodeURIComponent(slug[2])}`,
);
return NextResponse.json(result, { status: 200 }); return NextResponse.json(result, { status: 200 });
} }
@@ -26,6 +30,23 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
} }
}; };
export const DELETE = async (_req: NextRequest, context: RouteContext) => {
try {
const { slug = [] } = await context.params;
const [action] = slug;
const contactApi = await createContactApi();
if (action === "event" && slug.length === 2) {
await contactApi.del(`/list-hist/event/${slug[1]}`);
return new NextResponse(null, { status: 204 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
export const PUT = async (req: NextRequest, context: RouteContext) => { export const PUT = async (req: NextRequest, context: RouteContext) => {
try { try {
const { slug = [] } = await context.params; const { slug = [] } = await context.params;

View File

@@ -0,0 +1,59 @@
import { NextRequest, NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import { errorToResponse } from '@kri/common/http'
import { createContactApi } from '@/lib/http-server'
import { serverEnv } from '@/lib/env.server'
import { CookieKeys } from '@/store/cookie/cookie-keys'
import type { RouteContext } from '@/types/common'
const project = '[1-9][0-9]*'
const key = '[a-f0-9]{32}'
const getPath = new RegExp(`^${project}/(?:availability|upload-reset-active|my-active|${key}(?:/(?:sid-failures|range-failures|validation-errors|source-file|files/[0-9]+|message-report/(?:batches|preparation-failures)))?)$`)
const postPath = new RegExp(`^${project}/(?:upload|reset|${key}/cancel|mutations/(?:update|assign-reset|assign/[^/]+)|downloads/(?:list|event-history|update-history|item-files)|messages/(?:email|sms|kko))$`)
// The shared HTTP client decodes binary bodies. Forward file bodies as streams instead.
async function forwardFile(req: NextRequest, path: string) {
const token = (await cookies()).get(CookieKeys.AuthToken)?.value
if (!token) return NextResponse.json({ message: '로그인이 필요합니다.' }, { status: 401 })
const headers = new Headers({ Authorization: `Bearer ${token}` })
if (req.method === 'POST') {
const type = req.headers.get('content-type')
if (!type?.startsWith('multipart/form-data;')) return NextResponse.json({ message: '파일 요청 형식이 올바르지 않습니다.' }, { status: 400 })
headers.set('Content-Type', type)
}
const options: RequestInit & { duplex?: 'half' } = {
method: req.method, headers, cache: 'no-store', redirect: 'error',
signal: AbortSignal.any([req.signal, AbortSignal.timeout(300_000)]),
...(req.method === 'POST' ? { body: req.body, duplex: 'half' as const } : {}),
}
const upstream = await fetch(`${serverEnv.API_CONTACT_SERVER.replace(/\/$/, '')}/list/jobs/${path}`, options)
const responseHeaders = new Headers({ 'Cache-Control': 'no-store' })
for (const name of ['Content-Type', 'Content-Disposition', 'Content-Length']) {
const value = upstream.headers.get(name)
if (value) responseHeaders.set(name, value)
}
return new NextResponse(upstream.body, { status: upstream.status, headers: responseHeaders })
}
async function proxy(req: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params
const path = slug.map(encodeURIComponent).join('/')
if (!(req.method === 'GET' ? getPath : postPath).test(path)) return NextResponse.json({ message: '지원하지 않는 작업 경로입니다.' }, { status: 404 })
if (/\/(source-file|files\/[0-9]+|upload)$/.test(path)) return await forwardFile(req, path)
const query = new URLSearchParams()
for (const name of ['offset', 'limit', 'includeResult', 'jobType']) {
const value = req.nextUrl.searchParams.get(name)
if (value !== null) query.set(name, value)
}
const url = `/list/jobs/${path}${query.size ? `?${query}` : ''}`
const api = await createContactApi()
const value = req.method === 'GET'
? await api.get(url, { cache: 'no-store' })
: await api.post(url, await req.json().catch(() => undefined))
return NextResponse.json(value, { headers: { 'Cache-Control': 'no-store' } })
} catch (error: unknown) { return errorToResponse(error) }
}
export const GET = proxy
export const POST = proxy

View File

@@ -9,7 +9,7 @@ const excelHeaders = {
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
}; };
export const GET = async (req: NextRequest, context: RouteContext) => { export const GET = async (_req: NextRequest, context: RouteContext) => {
try { try {
const {slug = []} = await context.params; const {slug = []} = await context.params;
const [action] = slug; const [action] = slug;
@@ -28,13 +28,15 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
} }
if (action === "search-sid" && slug.length === 3) { if (action === "search-sid" && slug.length === 3) {
const result = await contactApi.get<ListSearchWithFullResult>(`/list/search-sid/${slug[1]}/${slug[2]}`); const result = await contactApi.get<ListSearchWithFullResult>(
`/list/search-sid/${slug[1]}/${encodeURIComponent(slug[2])}`,
);
return NextResponse.json(result, { status: 200 }); return NextResponse.json(result, { status: 200 });
} }
if (action === "item-file-download" && slug.length === 4) { if (action === "item-file-download" && slug.length === 4) {
const result = await contactApi.get<ArrayBuffer>( const result = await contactApi.get<ArrayBuffer>(
`/list/item-file/download/${slug[1]}/${slug[2]}/${slug[3]}`, `/list/item-file/download/${slug[1]}/${encodeURIComponent(slug[2])}/${slug[3]}`,
{ expectBinary: true }, { expectBinary: true },
); );
return new NextResponse(result, { return new NextResponse(result, {
@@ -94,46 +96,10 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
if (action === "item-file-upload" && slug.length === 3) { if (action === "item-file-upload" && slug.length === 3) {
const form = await req.formData(); const form = await req.formData();
await contactApi.postForm(`/list/item-file/upload/${slug[1]}/${slug[2]}`, form); await contactApi.postForm(`/list/item-file/upload/${slug[1]}/${encodeURIComponent(slug[2])}`, form);
return new NextResponse(null, { status: 204 }); return new NextResponse(null, { status: 204 });
} }
if (action === "excel-upload") {
const form = await req.formData();
const result = await contactApi.postForm(`/list/excel/upload/${slug[1]}`, form);
return NextResponse.json(result, { status: 200 });
}
if (action === "excel-download") {
const body = await req.json().catch(() => null);
const result = await contactApi.post<ArrayBuffer>(`/list/excel/download/${slug[1]}`, body, { expectBinary: true });
return new NextResponse(result, { status: 200, headers: excelHeaders });
}
if (action === "excel-download-update") {
const body = await req.json().catch(() => null);
const result = await contactApi.post<ArrayBuffer>(`/list/excel/download/update/${slug[1]}`, body, {
expectBinary: true,
});
return new NextResponse(result, { status: 200, headers: excelHeaders });
}
if (action === "event-history-download") {
const body = await req.json().catch(() => null);
const result = await contactApi.post<ArrayBuffer>(`/list-hist/excel/download/event/${slug[1]}`, body, {
expectBinary: true,
});
return new NextResponse(result, { status: 200, headers: excelHeaders });
}
if (action === "item-file-download") {
const body = await req.json().catch(() => null);
const result = await contactApi.post<ArrayBuffer>(`/list/item-file/download/${slug[1]}`, body, {
expectBinary: true,
});
return new NextResponse(result, { status: 200, headers: { "Content-Type": "application/zip" } });
}
if (action === "upload-history-file") { if (action === "upload-history-file") {
const result = await contactApi.post<ArrayBuffer>( const result = await contactApi.post<ArrayBuffer>(
`/list/excel/upload-history/file/${slug[1]}/${slug[2]}`, `/list/excel/upload-history/file/${slug[1]}/${slug[2]}`,
@@ -171,15 +137,3 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => {
return errorToResponse(error); return errorToResponse(error);
} }
}; };
export const DELETE = async (req: NextRequest, context: RouteContext) => {
try {
const { slug = [] } = await context.params;
const body = await req.json().catch(() => null);
const contactApi = await createContactApi();
const result = await contactApi.del<number>(`/list/${slug[0]}`, { json: body });
return NextResponse.json(result, { status: 200 });
} catch (error: unknown) {
return errorToResponse(error);
}
};

View File

@@ -1,9 +1,8 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import type { LoginRequest, LoginUser } from "@kri/common"; import type { LoginRequest, LoginUser } from "@kri/common";
import {serverEnv} from "@/lib/env.server"; import {setAuthCookie} from "@/lib/auth-cookie";
import {createContactApi} from "@/lib/http-server"; import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@kri/common/http"; import {errorToResponse} from "@kri/common/http";
import {CookieKeys} from "@/store/cookie/cookie-keys";
//?ㅼ젣 Backend //?ㅼ젣 Backend
type LoginResponse = { type LoginResponse = {
@@ -19,13 +18,7 @@ export const POST = async (req: NextRequest) => {
const result = await contactApi.post<LoginResponse>("/auth/login", body); const result = await contactApi.post<LoginResponse>("/auth/login", body);
const res = NextResponse.json(result.user, { status: 200 }); const res = NextResponse.json(result.user, { status: 200 });
res.cookies.set(CookieKeys.AuthToken, result.accessToken, { setAuthCookie(res, result.accessToken);
httpOnly: true,
secure: serverEnv.ENV === "prod",
sameSite: "lax",
path: "/",
maxAge: 24 * 60 * 60, // 24?쒓컙
});
return res; return res;
} catch (error : unknown) { } catch (error : unknown) {

View File

@@ -1,12 +1,11 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import {serverEnv} from "@/lib/env.server"; import {setAuthCookie} from "@/lib/auth-cookie";
import {createContactApi} from "@/lib/http-server"; import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@kri/common/http"; import {errorToResponse} from "@kri/common/http";
import {RouteContext} from "@/types/common"; import {RouteContext} from "@/types/common";
import {CookieKeys} from "@/store/cookie/cookie-keys";
export async function POST( export async function POST(
req: NextRequest, _req: NextRequest,
context: RouteContext context: RouteContext
) { ) {
try { try {
@@ -22,13 +21,7 @@ export async function POST(
await contactApi.post<boolean>(url); await contactApi.post<boolean>(url);
const res = NextResponse.json({ ok: true }); const res = NextResponse.json({ ok: true });
res.cookies.set(CookieKeys.AuthToken, "", { setAuthCookie(res, "");
httpOnly: true,
secure: serverEnv.ENV === "prod",
sameSite: "lax",
path: "/",
maxAge: 0,
});
return res; return res;
} catch (error: unknown) { } catch (error: unknown) {

View File

@@ -1,20 +1,19 @@
import {NextRequest, NextResponse} from "next/server"; import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common"; import {RouteContext} from "@/types/common";
import {createNotihubApi} from "@/lib/http-server"; import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@kri/common/http"; import {errorToResponse} from "@kri/common/http";
import type {FileResponse, PageRequest, PageResponse} from "@kri/common"; import type {FileResponse, PageRequest, PageResponse} from "@kri/common";
import type {BulkSendInfo, SendResultSummaryRequest, SendResultSummaryResponse} from "@kri/common/noti-hub"; import type {BulkSendInfo, SendResultInfo, SendResultSummaryRequest, SendResultSummaryResponse} from "@kri/common/noti-hub";
import type {SendResultInfo} from "@/types/message";
export const GET = async (req: NextRequest, context: RouteContext) => { export const GET = async (req: NextRequest, context: RouteContext) => {
try { try {
const {slug = []} = await context.params; const {slug = []} = await context.params;
const [action, sendTy, reqstSvc, prjctCd] = slug; const [action, sendTy, reqstSvc, prjctCd] = slug;
const notihubApi = await createNotihubApi(); const contactApi = await createContactApi();
if (action === "bulk-list" && sendTy && reqstSvc && prjctCd) { if (action === "bulk-list" && sendTy && reqstSvc && prjctCd) {
const result = await notihubApi.get<BulkSendInfo[]>( const result = await contactApi.get<BulkSendInfo[]>(
`/report/bulk-list/${sendTy}/${reqstSvc}/${prjctCd}`, `/message-report/bulk-list/${sendTy}/${reqstSvc}/${prjctCd}`,
); );
return NextResponse.json(result, {status: 200}); return NextResponse.json(result, {status: 200});
} }
@@ -23,8 +22,8 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
const [, sid, prjctCdParam, reqstSvcParam] = slug; const [, sid, prjctCdParam, reqstSvcParam] = slug;
const channelTy = req.nextUrl.searchParams.get("channelTy"); const channelTy = req.nextUrl.searchParams.get("channelTy");
const query = channelTy ? `?channelTy=${channelTy}` : ""; const query = channelTy ? `?channelTy=${channelTy}` : "";
const result = await notihubApi.get<SendResultInfo[]>( const result = await contactApi.get<SendResultInfo[]>(
`/report/send-result/${sid}/${prjctCdParam}/${reqstSvcParam}${query}`, `/message-report/send-result/${encodeURIComponent(sid)}/${prjctCdParam}/${reqstSvcParam}${query}`,
); );
return NextResponse.json(result, {status: 200}); return NextResponse.json(result, {status: 200});
} }
@@ -39,7 +38,7 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
try { try {
const {slug = []} = await context.params; const {slug = []} = await context.params;
const [action, bulkSendKey] = slug; const [action, bulkSendKey] = slug;
const notihubApi = await createNotihubApi(); const contactApi = await createContactApi();
if (action === "bulk-detail" && bulkSendKey) { if (action === "bulk-detail" && bulkSendKey) {
const body: PageRequest | null = await req.json().catch(() => null); const body: PageRequest | null = await req.json().catch(() => null);
@@ -47,16 +46,16 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400}); return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
} }
const result = await notihubApi.post<PageResponse<SendResultInfo>>( const result = await contactApi.post<PageResponse<SendResultInfo>>(
`/report/bulk-detail/${bulkSendKey}`, `/message-report/bulk-detail/${bulkSendKey}`,
body, body,
); );
return NextResponse.json(result, {status: 200}); return NextResponse.json(result, {status: 200});
} }
if (action === "bulk-detail-excel" && bulkSendKey) { if (action === "bulk-detail-excel" && bulkSendKey) {
const result = await notihubApi.post<FileResponse>( const result = await contactApi.post<FileResponse>(
`/report/bulk-detail/excel/${bulkSendKey}`, `/message-report/bulk-detail-excel/${bulkSendKey}`,
undefined, undefined,
); );
return NextResponse.json(result, {status: 200}); return NextResponse.json(result, {status: 200});
@@ -68,8 +67,8 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400}); return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
} }
const result = await notihubApi.post<SendResultSummaryResponse[]>( const result = await contactApi.post<SendResultSummaryResponse[]>(
`/report/send-result-summary`, `/message-report/send-result-summary`,
body, body,
); );
return NextResponse.json(result, {status: 200}); return NextResponse.json(result, {status: 200});

View File

@@ -0,0 +1,65 @@
import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common";
import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@kri/common/http";
import type {SendCancelResponse} from "@kri/common/noti-hub";
import type {MessageSendChannel, SendSingleResponse} from "@/types/message";
const isChannel = (value: string): value is MessageSendChannel =>
value === "sms" || value === "email" || value === "kko";
const BULK_SEND_KEY_MAX_LENGTH = 32;
const readCancelBody = (body: unknown, target: string): Record<string, number | string> | null => {
if (!body || typeof body !== "object") return null;
if (target === "single") {
const sendIdx = (body as {sendIdx?: unknown}).sendIdx;
return typeof sendIdx === "number" && Number.isSafeInteger(sendIdx) && sendIdx > 0 ? {sendIdx} : null;
}
if (target === "bulk") {
const bulkSendKey = (body as {bulkSendKey?: unknown}).bulkSendKey;
return typeof bulkSendKey === "string" && bulkSendKey.trim() !== "" && bulkSendKey.length <= BULK_SEND_KEY_MAX_LENGTH
? {bulkSendKey}
: null;
}
return null;
};
export const POST = async (req: NextRequest, context: RouteContext) => {
try {
const {slug = []} = await context.params;
const [channel, action, prjctIdx] = slug;
const contactApi = await createContactApi();
// 예약 취소 (POST /message-send/cancel/{single|bulk}). 채널 구분 없이 공통 API를 사용한다.
if (channel === "cancel") {
if (action !== "single" && action !== "bulk") {
return NextResponse.json({message: "Not found"}, {status: 404});
}
const cancelBody = readCancelBody(await req.json().catch(() => null), action);
if (!cancelBody) {
return NextResponse.json({message: "취소 요청 값이 올바르지 않습니다."}, {status: 400});
}
const result = await contactApi.post<SendCancelResponse>(`/message-send/cancel/${action}`, cancelBody);
return NextResponse.json(result, {status: 200});
}
if (!isChannel(channel) || !prjctIdx) {
return NextResponse.json({message: "Not found"}, {status: 404});
}
const body = await req.json().catch(() => null);
if (!body) {
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
}
if (action === "single") {
const result = await contactApi.post<SendSingleResponse>(`/message-send/${channel}/single/${prjctIdx}`, body);
return NextResponse.json(result, {status: 200});
}
return NextResponse.json({message: "Not found"}, {status: 404});
} catch (error: unknown) {
return errorToResponse(error);
}
};

View File

@@ -1,26 +1,69 @@
import {NextRequest, NextResponse} from "next/server"; import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common"; import {RouteContext} from "@/types/common";
import {createNotihubApi} from "@/lib/http-server"; import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@kri/common/http"; import {errorToResponse} from "@kri/common/http";
import type { Template, TemplateSummary } from "@kri/common/noti-hub"; import type { KkoSenderProfile } from "@/types/message";
import type { KkoTemplateDetail, KkoTemplateListResponse, Template, TemplateSummary } from "@kri/common/noti-hub";
// 외부 알림톡 템플릿 목록·상세 조회. JSON 본문을 contact-back에 그대로 전달한다.
export const POST = async (req: NextRequest, context: RouteContext) => {
try{
const {slug = []} = await context.params;
const [channel, action] = slug;
if (channel !== "kko" || slug.length !== 2 || (action !== "list" && action !== "detail")) {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
const body = await req.json().catch(() => null);
if (!body || typeof body !== "object") {
return NextResponse.json({ message: "요청 바디가 없습니다." }, { status: 400 });
}
const contactApi = await createContactApi();
const result = action === "list"
? await contactApi.post<KkoTemplateListResponse>(`/message-template/kko/list`, body)
: await contactApi.post<KkoTemplateDetail>(`/message-template/kko/detail`, body);
return NextResponse.json(result, { status: 200 });
} catch (error: unknown) {
return errorToResponse(error);
}
}
export const GET = async (req: NextRequest, context: RouteContext) => { export const GET = async (req: NextRequest, context: RouteContext) => {
try{ try{
const { searchParams } = new URL(req.url); const { searchParams } = new URL(req.url);
const {slug = []} = await context.params; const {slug = []} = await context.params;
const [action] = slug; const [action] = slug;
const notihubApi = await createNotihubApi(); const contactApi = await createContactApi();
if (slug.length === 2 && action === "kko" && slug[1] === "profiles") {
const result = await contactApi.get<KkoSenderProfile[]>(`/message-template/kko/profiles`);
return NextResponse.json(result, { status: 200 });
}
if(slug.length === 2 && slug[1] === "attachment"){
const fileName = searchParams.get("fileName");
if (!fileName) {
return NextResponse.json({ message: "fileName은 필수입니다." }, { status: 400 });
}
const result = await contactApi.get<ArrayBuffer>(
`/message-template/${slug[0]}/attachment?fileName=${encodeURIComponent(fileName)}`,
{ expectBinary: true },
);
return new NextResponse(result, { status: 200, headers: { "Content-Type": "application/octet-stream" } });
}
if(slug.length === 1){ if(slug.length === 1){
const result = await notihubApi.get<Template>( const result = await contactApi.get<Template>(
`/template/${slug[0]}`, `/message-template/${slug[0]}`,
); );
return NextResponse.json(result, { status: 200 }); return NextResponse.json(result, { status: 200 });
} }
if(action === "list" && slug.length === 3){ if(action === "list" && slug.length === 3){
const result = await notihubApi.get<TemplateSummary[]>( const result = await contactApi.get<TemplateSummary[]>(
`/template/list/${slug[1]}/${slug[2]}`, `/message-template/list/${slug[1]}/${slug[2]}`,
); );
return NextResponse.json(result, { status: 200 }); return NextResponse.json(result, { status: 200 });
} }
@@ -33,10 +76,9 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
export const PUT = async (req: NextRequest, context: RouteContext) => { export const PUT = async (req: NextRequest, context: RouteContext) => {
try{ try{
const { searchParams } = new URL(req.url);
const {slug = []} = await context.params; const {slug = []} = await context.params;
const [action] = slug; const [action] = slug;
const notihubApi = await createNotihubApi(); const contactApi = await createContactApi();
if(action === "body-image" && slug.length === 2){ if(action === "body-image" && slug.length === 2){
const itrntPrjctCd = slug[1]; const itrntPrjctCd = slug[1];
@@ -51,8 +93,8 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
); );
} }
const result = await notihubApi.putForm<string>( const result = await contactApi.putForm<string>(
`/template/body-image/${itrntPrjctCd}`, `/message-template/body-image/${itrntPrjctCd}`,
formData formData
); );
@@ -60,15 +102,15 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
} }
if(!action){ if(!action){
const body = await req.json().catch(() => null); const formData = await req.formData().catch(() => null);
if (!body) { if (!formData) {
return NextResponse.json( return NextResponse.json(
{ message: "요청 바디가 없습니다." }, { message: "요청 바디가 없습니다." },
{ status: 400 } { status: 400 }
); );
} }
const result = await notihubApi.put<Template>(`/template`, body); const result = await contactApi.putForm<Template>(`/message-template`, formData);
return NextResponse.json(result, { status: 200 }); return NextResponse.json(result, { status: 200 });
} }
@@ -80,21 +122,20 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
export const PATCH = async (req: NextRequest, context: RouteContext) => { export const PATCH = async (req: NextRequest, context: RouteContext) => {
try{ try{
const { searchParams } = new URL(req.url);
const {slug = []} = await context.params; const {slug = []} = await context.params;
const [action] = slug; const [action] = slug;
const notihubApi = await createNotihubApi(); const contactApi = await createContactApi();
if(!action){ if(!action){
const body = await req.json().catch(() => null); const formData = await req.formData().catch(() => null);
if (!body) { if (!formData) {
return NextResponse.json( return NextResponse.json(
{ message: "요청 바디가 없습니다." }, { message: "요청 바디가 없습니다." },
{ status: 400 } { status: 400 }
); );
} }
const result = await notihubApi.patch<Template>(`/template`, body); const result = await contactApi.request<Template>(`/message-template`, { method: "PATCH", form: formData });
return NextResponse.json(result, { status: 200 }); return NextResponse.json(result, { status: 200 });
} }
@@ -103,3 +144,20 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => {
return errorToResponse(error); return errorToResponse(error);
} }
} }
// 템플릿 삭제. 성공 응답은 빈 body이므로 JSON으로 파싱하지 않는다.
export const DELETE = async (req: NextRequest, context: RouteContext) => {
try{
const {slug = []} = await context.params;
const [tmplatIdx] = slug;
if (slug.length !== 1 || !/^[1-9]\d*$/.test(tmplatIdx)) {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
const contactApi = await createContactApi();
await contactApi.del(`/message-template/${tmplatIdx}`, { expectText: true });
return new NextResponse(null, { status: 204 });
} catch (error: unknown) {
return errorToResponse(error);
}
}

View File

@@ -1,38 +0,0 @@
import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common";
import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@kri/common/http";
import type {MessageBulkSendResponse} from "@/types/message";
const isChannel = (value: string): value is "sms" | "email" => value === "sms" || value === "email";
export const POST = async (req: NextRequest, context: RouteContext) => {
try {
const {slug = []} = await context.params;
const [channel, action, prjctIdx] = slug;
const contactApi = await createContactApi();
if (!isChannel(channel) || !prjctIdx) {
return NextResponse.json({message: "Not found"}, {status: 404});
}
const body = await req.json().catch(() => null);
if (!body) {
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
}
if (action === "single") {
await contactApi.post(`/message/${channel}/single/${prjctIdx}`, body);
return new NextResponse(null, {status: 204});
}
if (action === "bulk") {
const result = await contactApi.post<MessageBulkSendResponse>(`/message/${channel}/bulk/${prjctIdx}`, body);
return NextResponse.json(result, {status: 200});
}
return NextResponse.json({message: "Not found"}, {status: 404});
} catch (error: unknown) {
return errorToResponse(error);
}
};

View File

@@ -1,5 +1,5 @@
import {NextRequest, NextResponse} from "next/server"; import {NextRequest, NextResponse} from "next/server";
import {createContactApi, createIntranetApi} from "@/lib/http-server"; import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@kri/common/http"; import {errorToResponse} from "@kri/common/http";
import type {PageResponse} from "@kri/common"; import type {PageResponse} from "@kri/common";
import {RouteContext} from "@/types/common"; import {RouteContext} from "@/types/common";
@@ -172,10 +172,9 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => {
} }
}; };
export const DELETE = async (req: NextRequest, context: RouteContext) => { export const DELETE = async (_req: NextRequest, context: RouteContext) => {
try { try {
const {slug = []} = await context.params; const {slug = []} = await context.params;
const [action] = slug;
const contactApi = await createContactApi(); const contactApi = await createContactApi();
if(slug.length === 1){ if(slug.length === 1){

View File

@@ -11,7 +11,22 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
const contactApi = await createContactApi(); const contactApi = await createContactApi();
if (action === "sid" && slug.length === 3) { if (action === "sid" && slug.length === 3) {
const result = await contactApi.get<ListReserve[]>(`/reserve/${slug[1]}/sid/${slug[2]}`); const result = await contactApi.get<ListReserve[]>(
`/reserve/${slug[1]}/sid/${encodeURIComponent(slug[2])}`,
);
return NextResponse.json(result, { status: 200 });
}
if (action === "user" && slug.length === 3 && slug[2] === "search") {
const fromDt = req.nextUrl.searchParams.get("fromDt");
const toDt = req.nextUrl.searchParams.get("toDt");
if (!fromDt || !toDt) {
return NextResponse.json({ message: "fromDt, toDt가 필요합니다." }, { status: 400 });
}
const result = await contactApi.get<ListReserve[]>(
`/reserve/user/${encodeURIComponent(slug[1])}/search?fromDt=${fromDt}&toDt=${toDt}`,
);
return NextResponse.json(result, { status: 200 }); return NextResponse.json(result, { status: 200 });
} }
@@ -20,13 +35,20 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
return NextResponse.json(result, { status: 200 }); return NextResponse.json(result, { status: 200 });
} }
if (action === "user" && slug.length === 2) {
const requestPast = req.nextUrl.searchParams.get("requestPast");
const query = requestPast !== null ? `?requestPast=${requestPast}` : "";
const result = await contactApi.get<ListReserve[]>(`/reserve/user/${encodeURIComponent(slug[1])}${query}`);
return NextResponse.json(result, { status: 200 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 }); return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) { } catch (error: unknown) {
return errorToResponse(error); return errorToResponse(error);
} }
}; };
export const PUT = async (req: NextRequest, context: RouteContext) => { export const PUT = async (req: NextRequest) => {
try { try {
const body = await req.json().catch(() => null); const body = await req.json().catch(() => null);
if (!body) { if (!body) {

View File

@@ -1,14 +1,12 @@
import {NextRequest, NextResponse} from "next/server"; import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common"; import {RouteContext} from "@/types/common";
import {createContactApi} from "@/lib/http-server"; import {createContactApi} from "@/lib/http-server";
import {ProjectInfo, ProjectOwnerResponse, ResultCode} from "@/types/project"; import {ResultCode} from "@/types/project";
import {errorToResponse} from "@kri/common/http"; import {errorToResponse} from "@kri/common/http";
export const GET = async (req: NextRequest, context: RouteContext) => { export const GET = async (_req: NextRequest, context: RouteContext) => {
try { try {
const { searchParams } = new URL(req.url);
const {slug = []} = await context.params; const {slug = []} = await context.params;
const [action] = slug;
const contactApi = await createContactApi(); const contactApi = await createContactApi();
if(slug.length === 1){ if(slug.length === 1){

View File

@@ -4,7 +4,7 @@ import {RoleInfo} from "@/types/role";
import {errorToResponse} from "@kri/common/http"; import {errorToResponse} from "@kri/common/http";
import {RouteContext} from "@/types/common"; import {RouteContext} from "@/types/common";
export const GET = async (req: NextRequest, context: RouteContext) => { export const GET = async (_req: NextRequest, context: RouteContext) => {
try { try {
const { slug = [] } = await context.params; const { slug = [] } = await context.params;
const [action] = slug; const [action] = slug;

View File

@@ -149,7 +149,7 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => {
} }
}; };
export const DELETE = async (req: NextRequest, context: RouteContext) => { export const DELETE = async (_req: NextRequest, context: RouteContext) => {
try { try {
const { slug = [] } = await context.params; const { slug = [] } = await context.params;
const [userId] = slug ?? []; const [userId] = slug ?? [];

View File

@@ -163,14 +163,43 @@
cursor: pointer; cursor: pointer;
} }
/* 미리보기(.kri-editor-preview)는 실제 발송 HTML을 그대로 dangerouslySetInnerHTML로 그린다.
Tailwind preflight가 img를 display:block + vertical-align:middle로 리셋하는데,
실제 메일 클라이언트에는 이 리셋 CSS가 없어 img가 브라우저 기본값(inline, vertical-align:baseline)으로
렌더링된다. 미리보기가 실제 발송 결과와 같아 보이도록 두 속성 다 기본값으로 되돌린다. */
.kri-editor-preview img {
display: inline;
vertical-align: baseline;
}
/* 에디터 편집 화면은 [&_p]:my-2 유틸리티로 문단 사이 margin을 주지만,
미리보기는 Tailwind preflight가 p의 기본 margin을 0으로 리셋해 내용 없는 빈 <p></p>가
높이 0으로 사라진다. 편집 화면과 동일하게 margin을 줘서 빈 줄이 보이도록 한다. */
.kri-editor-preview p {
margin: 0.5em 0;
}
.kri-editor-preview p:first-child {
margin-top: 0;
}
.kri-editor-preview p:last-child {
margin-bottom: 0;
}
/* 내용이 전혀 없는 <p></p>는 높이가 0이라 위/아래 margin이 서로 collapse되어 사라진다.
min-height로 실제 높이를 줘서 collapse를 막아야 빈 줄이 화면에 보인다. */
.kri-editor-preview p:empty {
min-height: 1em;
}
.ProseMirror .ProseMirror-selectednode img { .ProseMirror .ProseMirror-selectednode img {
outline: 5px solid #0ea5e9; outline: 5px solid #0ea5e9;
outline-offset: -5px; outline-offset: -5px;
} }
/* 리사이즈 컨테이너 기본 배치 */ /* 리사이즈 컨테이너 기본 배치 */
/* Tiptap ResizableNodeView가 style.display = "flex"를 인라인으로 강제 지정하므로,
inline 이미지 노드처럼 줄바꿈 없이 배치하려면 !important로 덮어써야 한다. */
.ProseMirror [data-resize-container] { .ProseMirror [data-resize-container] {
position: relative; position: relative;
display: inline-block; display: inline-block !important;
} }
/* 리사이즈 핸들 공통 스타일 */ /* 리사이즈 핸들 공통 스타일 */
@@ -222,3 +251,4 @@
.ProseMirror [data-resize-container][data-resize-state="resizing"] { .ProseMirror [data-resize-container][data-resize-state="resizing"] {
outline: 1px dashed #0ea5e9; outline: 1px dashed #0ea5e9;
} }

View File

@@ -2,7 +2,7 @@ import type { Metadata } from "next";
import {Geist, Geist_Mono} from "next/font/google"; import {Geist, Geist_Mono} from "next/font/google";
import { AppProvider } from "@/components/providers/AppProvider"; import { AppProvider } from "@/components/providers/AppProvider";
import "./globals.css"; import "./globals.css";
import {Toaster} from "sonner"; import {Toaster} from "@/components/ui/sonner";
const geistSans = Geist({ const geistSans = Geist({
variable: "--font-geist-sans", variable: "--font-geist-sans",

View File

@@ -1,14 +1,26 @@
"use client"; "use client";
import Image from "next/image"; import Image from "next/image";
import { LogOut, ZoomIn, ZoomOut } from "lucide-react"; import { CalendarClock, LogOut, UserRound, ZoomIn, ZoomOut } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { KriHeader } from "@/components/layout/KriHeader"; import { KriHeader } from "@/components/layout/KriHeader";
import type { TopMenuItem } from "@/config/menu.types"; import type { TopMenuItem } from "@/config/menu.types";
import type { LoginUser } from "@kri/common"; import type { LoginUser } from "@kri/common";
import { cn } from "@/lib/utils";
import { useInternalInfoQuery } from "@/query/internal";
import { useCtiConnectionStatus } from "@/hooks/useCtiConnectionStatus";
interface AppHeaderProps { interface AppHeaderProps {
isMain: boolean; isMain: boolean;
isContactPage: boolean;
menuOpen: boolean; menuOpen: boolean;
activeTopId: string; activeTopId: string;
topMenus: TopMenuItem[]; topMenus: TopMenuItem[];
@@ -20,10 +32,12 @@ interface AppHeaderProps {
onNavigate: (path: string) => void; onNavigate: (path: string) => void;
decreaseFontSize: () => void; decreaseFontSize: () => void;
increaseFontSize: () => void; increaseFontSize: () => void;
onOpenReserveSearch: () => void;
} }
export function AppHeader({ export function AppHeader({
isMain, isMain,
isContactPage,
menuOpen, menuOpen,
activeTopId, activeTopId,
topMenus, topMenus,
@@ -35,53 +49,107 @@ export function AppHeader({
onNavigate, onNavigate,
decreaseFontSize, decreaseFontSize,
increaseFontSize, increaseFontSize,
onOpenReserveSearch,
}: AppHeaderProps) { }: AppHeaderProps) {
const internalInfoQuery = useInternalInfoQuery(!!userInfo);
const seatNo = internalInfoQuery.data?.clientId ?? "";
const ctiConnectionStatus = useCtiConnectionStatus();
const isCtiConnected = ctiConnectionStatus === "open";
const showProjectTitle = isViewProjectTitle && !!projectName;
return ( return (
<>
<KriHeader <KriHeader
logo={ logo={
<div className="flex h-10 w-20 items-center justify-center"> <div className="flex h-10 w-16 items-center justify-center sm:w-20">
<Image <Image
src="/kri_logo.png" src="/kri_logo.png"
alt="KRI 로고" alt="KRI 로고"
width={120} width={120}
height={40} height={40}
className="object-contain" className="h-full w-full object-contain"
priority priority
/> />
</div> </div>
} }
homePath="/" homePath="/"
menus={topMenus} menus={isContactPage? []:topMenus}
activeMenuId={activeTopId} activeMenuId={activeTopId}
menuOpen={menuOpen} menuOpen={menuOpen}
showMenuButton={!isMain} showMenuButton={!isMain && !isContactPage}
onToggleMenu={onToggleMenu} onToggleMenu={onToggleMenu}
onNavigate={(path) => onNavigate(path)} onNavigate={(path) => {if(!isContactPage) onNavigate(path)}}
className="border-gray-200 bg-white" className="border-gray-200 bg-white"
innerClassName="h-16 px-4" // 모바일(sm 미만)은 헤더 폭이 좁아 로고와 우측 버튼이 겹치지 않도록 간격을 줄인다.
innerClassName="h-16 gap-2 px-2 sm:gap-4 sm:px-4"
center={ center={
isViewProjectTitle && projectName ? ( showProjectTitle ? (
<h1 className="ml-3 text-2xl font-bold">{projectName}</h1> <h1 className="ml-3 hidden truncate text-2xl font-bold lg:block" title={projectName}>{projectName}</h1>
) : null ) : null
} }
right={ right={
<> <>
<div className="flex items-center gap-1 border-r pr-4"> <div className="flex items-center gap-1 border-r pr-2 sm:pr-4">
<Button variant="ghost" size="icon" onClick={decreaseFontSize} title="폰트 작게"> <Button variant="ghost" size="icon" className="size-8 sm:size-9" onClick={decreaseFontSize} title="폰트 작게">
<ZoomOut className="h-4 w-4" /> <ZoomOut className="h-4 w-4" />
</Button> </Button>
<span className="min-w-[3rem] text-center text-xs text-gray-500">{fontSize}px</span> <span className="min-w-6 text-center text-xs text-gray-500" title={`글자 크기 ${fontSize}px`}>{fontSize}</span>
<Button variant="ghost" size="icon" onClick={increaseFontSize} title="폰트 크게"> <Button variant="ghost" size="icon" className="size-8 sm:size-9" onClick={increaseFontSize} title="폰트 크게">
<ZoomIn className="h-4 w-4" /> <ZoomIn className="h-4 w-4" />
</Button> </Button>
</div> </div>
<span className="hidden text-sm text-gray-600 sm:inline">{userInfo?.userName || ""}</span> <Button variant="ghost" size="icon-lg" className="size-8 sm:size-10" onClick={onOpenReserveSearch} title="예약 내역 조회">
<Button variant="ghost" size="sm" className="gap-2" onClick={() => onNavigate("/logout")}> <CalendarClock className="size-6" />
<LogOut className="h-4 w-4" />
<span className="hidden sm:inline">로그아웃</span>
</Button> </Button>
<span className="hidden items-center gap-1.5 text-sm text-gray-600 sm:inline-flex">
{userInfo?.userName || ""}
{seatNo ? (
<span className="inline-flex items-center gap-1">
{`(${seatNo})`}
<span
className={cn(
"inline-block h-2 w-2 rounded-full",
isCtiConnected ? "bg-green-500" : "bg-red-500",
)}
title={isCtiConnected ? "CTI 연결됨" : "CTI 연결 안됨"}
/>
</span>
) : null}
</span>
<Button variant="ghost" size="sm" className="hidden gap-2 sm:inline-flex" onClick={() => onNavigate("/logout")}>
<LogOut className="h-4 w-4" />
<span>로그아웃</span>
</Button>
{/* 모바일(sm 미만)은 헤더 폭이 좁아 이름과 로그아웃을 사용자 메뉴로 묶는다. CTI는 모바일에서 사용하지 않아 표시하지 않는다. */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="size-8 sm:hidden" title="사용자 메뉴" aria-label="사용자 메뉴">
<UserRound className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{userInfo?.userName ? (
<>
<DropdownMenuLabel>{`${userInfo.userName} 님`}</DropdownMenuLabel>
<DropdownMenuSeparator />
</>
) : null}
<DropdownMenuItem onSelect={() => onNavigate("/logout")}>
<LogOut className="h-4 w-4" />
로그아웃
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</> </>
} }
/> />
{/* 모바일(lg 미만)은 헤더 공간이 좁아 프로젝트명을 헤더 아래 한 줄로 내려 표시한다. */}
{showProjectTitle ? (
<div className="border-b border-gray-200 bg-white px-4 py-2 lg:hidden">
<h1 className="truncate text-center text-lg font-bold" title={projectName}>{projectName}</h1>
</div>
) : null}
</>
); );
} }

View File

@@ -2,18 +2,22 @@
import { ReactNode, useEffect, useMemo, useState } from "react"; import { ReactNode, useEffect, useMemo, useState } from "react";
import { usePathname, useRouter } from "next/navigation"; import { usePathname, useRouter } from "next/navigation";
import type { Route } from "next";
import { useMounted } from "@kri/common/hooks"; import { useMounted } from "@kri/common/hooks";
import { getCurrentPositionMeta } from "@kri/common/browser"; import { getCurrentPositionMeta } from "@kri/common/browser";
import { KriMainLayout } from "@/components/layout/KriMainLayout"; import { KriMainLayout } from "@/components/layout/KriMainLayout";
import { AppHeader } from "@/components/app-shell/AppHeader"; import { AppHeader } from "@/components/app-shell/AppHeader";
import { AppSidebar } from "@/components/app-shell/AppSidebar"; import { AppSidebar } from "@/components/app-shell/AppSidebar";
import ReserveSearchDialog from "@/components/dialog/ReserveSearchDialog";
import { useFontSize } from "@/hooks/useFontSize"; import { useFontSize } from "@/hooks/useFontSize";
import { useAuth } from "@/hooks/useAuth"; import { useAuth } from "@/hooks/useAuth";
import { useSelectedProject } from "@/hooks/useSelectedProject"; import { useSelectedProject } from "@/hooks/useSelectedProject";
import { useDialog } from "@/hooks/useDialog";
import { manageSideMenus, projectSideMenus, topMenus } from "@/config/menu.data"; import { manageSideMenus, projectSideMenus, topMenus } from "@/config/menu.data";
import type { SideMenuItem, SideSubMenuItem, TopMenuItem } from "@/config/menu.types"; import type { SideMenuItem, SideSubMenuItem, TopMenuItem } from "@/config/menu.types";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { FONT_SIZE } from "@/const/commonConst"; import { FONT_SIZE } from "@/const/commonConst";
import { ListJobWatcher } from "@/components/list/ListJobWatcher";
type AppMainLayoutProps = { type AppMainLayoutProps = {
children: ReactNode; children: ReactNode;
@@ -103,11 +107,13 @@ export default function AppMainLayout({ children, initialFontSize }: AppMainLayo
const { auth } = useAuth(); const { auth } = useAuth();
const { selectedProject, isSelectedProjectHydrated } = useSelectedProject(); const { selectedProject, isSelectedProjectHydrated } = useSelectedProject();
const { showDialog } = useDialog();
const [menuOpen, setMenuOpen] = useState(true); const [menuOpen, setMenuOpen] = useState(true);
const [fontSize, setFontSize] = useFontSize(initialFontSize, { hydrateFromCookie: false }); const [fontSize, setFontSize] = useFontSize(initialFontSize, { hydrateFromCookie: false });
const userRole = auth.user?.userRole; const userRole = auth.user?.userRole;
const isMain = pathname === "/"; const isMain = pathname === "/";
const isContactPage = pathname.startsWith("/list/contact");
const isProjectMenu = !pathname.startsWith("/manage"); const isProjectMenu = !pathname.startsWith("/manage");
const isViewProjectTitle = !isMain && isProjectMenu && !pathname.startsWith("/project/info"); const isViewProjectTitle = !isMain && isProjectMenu && !pathname.startsWith("/project/info");
const visibleTopMenus = useMemo(() => filterTopMenusByRole(topMenus, userRole), [userRole]); const visibleTopMenus = useMemo(() => filterTopMenusByRole(topMenus, userRole), [userRole]);
@@ -137,7 +143,8 @@ export default function AppMainLayout({ children, initialFontSize }: AppMainLayo
}); });
const movePage = (path: string) => { const movePage = (path: string) => {
router.push(path); // 메뉴 설정(menu.data.ts)의 경로라 typedRoutes가 정적으로 검사할 수 없다.
router.push(path as Route);
}; };
const decreaseFontSize = () => { const decreaseFontSize = () => {
@@ -148,6 +155,11 @@ export default function AppMainLayout({ children, initialFontSize }: AppMainLayo
setFontSize(Math.min(FONT_SIZE.MAX, fontSize + 2)); setFontSize(Math.min(FONT_SIZE.MAX, fontSize + 2));
}; };
// 모바일(lg 미만)에서는 사이드바가 본문을 덮는 오버레이라 메뉴를 접힌 상태로 시작한다.
useEffect(() => {
if (!window.matchMedia("(min-width: 64rem)").matches) setMenuOpen(false);
}, []);
useEffect(() => { useEffect(() => {
if (!mounted) return; if (!mounted) return;
@@ -186,14 +198,15 @@ export default function AppMainLayout({ children, initialFontSize }: AppMainLayo
<KriMainLayout <KriMainLayout
fullHeight={false} fullHeight={false}
className={cn("bg-gray-50", "h-screen overflow-hidden")} className={cn("bg-gray-50", "h-screen overflow-hidden")}
bodyClassName={cn(!isMain && "min-h-0")} bodyClassName={cn(!isMain && isContactPage && "min-h-0")}
mainClassName={cn("p-4", "min-h-0")} mainClassName={cn("p-4", "min-h-0")}
mainStyle={{ fontSize: `var(--content-font-size, ${initialFontSize}px)` }} mainStyle={{ fontSize: `var(--content-font-size, ${initialFontSize}px)` }}
sidebarOpen={!isMain && menuOpen} sidebarOpen={!isMain && !isContactPage && menuOpen}
onSidebarOpenChange={setMenuOpen} onSidebarOpenChange={setMenuOpen}
header={ header={
<AppHeader <AppHeader
isMain={isMain} isMain={isMain}
isContactPage={isContactPage}
menuOpen={menuOpen} menuOpen={menuOpen}
activeTopId={activeTop.id} activeTopId={activeTop.id}
topMenus={visibleTopMenus} topMenus={visibleTopMenus}
@@ -205,10 +218,11 @@ export default function AppMainLayout({ children, initialFontSize }: AppMainLayo
onNavigate={movePage} onNavigate={movePage}
decreaseFontSize={decreaseFontSize} decreaseFontSize={decreaseFontSize}
increaseFontSize={increaseFontSize} increaseFontSize={increaseFontSize}
onOpenReserveSearch={() => showDialog("reserveSearchDialog")}
/> />
} }
sidebar={ sidebar={
!isMain ? ( !isMain && !isContactPage ? (
<AppSidebar <AppSidebar
isProjectMenu={isProjectMenu} isProjectMenu={isProjectMenu}
sideMenus={sideMenus} sideMenus={sideMenus}
@@ -222,6 +236,8 @@ export default function AppMainLayout({ children, initialFontSize }: AppMainLayo
} }
> >
{children} {children}
{mounted && auth.user && <ListJobWatcher userId={auth.user.userId} prjctIdx={selectedProject?.prjctIdx ?? 0} />}
<ReserveSearchDialog />
</KriMainLayout> </KriMainLayout>
); );
} }

View File

@@ -0,0 +1,19 @@
"use client";
import type { ReactNode } from "react";
import { useAuthSession } from "@/hooks/useAuthSession";
export function AuthSessionGate({ children }: { children: ReactNode }) {
const session = useAuthSession();
const user = session.data;
const checking = session.isPending || session.isFetching;
const identity = user && JSON.stringify([user.userId, user.userRole, user.userTeam, user.userCmpn]);
return <>
{session.isError && !checking && <div role="alert" className="p-8 text-center text-sm">
<p>로그인 정보를 확인하지 못했습니다.</p>
<button type="button" onClick={() => { void session.refetch(); }}>다시 시도</button>
</div>}
{user && <div key={identity} hidden={session.isError}>{children}</div>}
</>;
}

View File

@@ -1,17 +1,25 @@
'use client' 'use client'
import { useMemo } from 'react' import { useMemo, useState } from 'react'
import { useCmpnListQuery } from '@/query/cmpn' import { useCmpnListQuery } from '@/query/cmpn'
import { useFieldworkUsersQuery } from '@/query/user' import { useFieldworkUsersQuery } from '@/query/user'
import { useAssignedCmpnIdsQuery, useAssignedFieldworkIdsQuery } from '@/query/project' import {
useAssignedCmpnIdsQuery,
useAssignedCmpnSummaryQuery,
useAssignedFieldworkIdsQuery,
useAssignedFieldworkSummaryQuery,
} from '@/query/project'
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
import { ListHeaderAssignConst } from '@/const/listConst' import { ListHeaderAssignConst } from '@/const/listConst'
import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from '@/const/userConst' import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from '@/const/userConst'
import { isInternalManager } from '@/utils/userRole'
import type { ListHeaderAssignType } from '@/types/list' import type { ListHeaderAssignType } from '@/types/list'
export type AssignTargetListProps = { export type AssignTargetListProps = {
prjctIdx: number prjctIdx: number
enabled: boolean enabled: boolean
assignType: ListHeaderAssignType assignType: ListHeaderAssignType
userRole: number
selectedId?: string selectedId?: string
onSelect: (id: string) => void onSelect: (id: string) => void
} }
@@ -61,25 +69,113 @@ export function useAssignTargetRows({ prjctIdx, enabled, assignType }: UseAssign
]) ])
} }
export function AssignTargetList({ prjctIdx, enabled, assignType, selectedId, onSelect }: AssignTargetListProps) { type AssignSummaryRow = {
const rows = useAssignTargetRows({ prjctIdx, enabled, assignType }) id: string
name: string
assignedCount: number
cmpn?: string
}
export function AssignTargetList({
prjctIdx,
enabled,
assignType,
userRole,
selectedId,
onSelect
}: AssignTargetListProps) {
const isOutsource = assignType === ListHeaderAssignConst.OUTSOURCE
const canFilterByCmpn = !isOutsource && isInternalManager(userRole)
const showCmpnColumn = canFilterByCmpn
const [cmpnIds, setCmpnIds] = useState<string[]>([])
const cmpnListQuery = useCmpnListQuery()
const cmpnSummaryQuery = useAssignedCmpnSummaryQuery(prjctIdx, enabled && isOutsource)
const fieldworkSummaryQuery = useAssignedFieldworkSummaryQuery(
prjctIdx,
assignType,
cmpnIds,
enabled && !isOutsource,
)
const summary = isOutsource ? cmpnSummaryQuery.data : fieldworkSummaryQuery.data
const isLoading = isOutsource ? cmpnSummaryQuery.isLoading : fieldworkSummaryQuery.isLoading
const cmpnAliasById = useMemo(
() => new Map((cmpnListQuery.data ?? []).map((cmpn) => [cmpn.cmpnId, cmpn.cmpnAlias || cmpn.cmpnId])),
[cmpnListQuery.data],
)
const rows = useMemo<AssignSummaryRow[]>(() => {
if (isOutsource) {
return (cmpnSummaryQuery.data?.assignees ?? []).map((item) => ({
id: item.cmpnId,
name: item.cmpnAlias || item.cmpnId,
assignedCount: item.assignedCount,
}))
}
return (fieldworkSummaryQuery.data?.assignees ?? []).map((item) => ({
id: item.userId,
name: item.userName,
assignedCount: item.assignedCount,
cmpn: cmpnAliasById.get(item.userCmpn) ?? item.userCmpn,
}))
}, [isOutsource, cmpnSummaryQuery.data, fieldworkSummaryQuery.data, cmpnAliasById])
return ( return (
<div className="border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm"> <div className="flex h-[78vh] flex-col border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
<div className="h-[78vh] overflow-y-auto"> {summary ? (
<div className="shrink-0 border-b border-gray-200 bg-gray-50 px-3 py-1 text-lg font-semibold text-gray-700">
전체 {summary.totalCount}건 · 미배정 {summary.unassignedCount}건
</div>
) : null}
{canFilterByCmpn ? (
<div className="shrink-0 border-b border-gray-200 p-2">
<KriMultiSelect
items={cmpnListQuery.data ?? []}
value={cmpnIds}
onChange={setCmpnIds}
getValue={(item) => item.cmpnId}
getLabel={(item) => item.cmpnAlias || item.cmpnId}
placeholder="외주사 선택(전체)"
widthClassName="w-full"
heightClassName="h-9"
/>
</div>
) : null}
<div className="flex-1 overflow-y-auto">
<table className="w-full table-fixed"> <table className="w-full table-fixed">
<colgroup> <colgroup>
<col className="w-28" /> <col className="w-20" />
<col /> <col />
{showCmpnColumn ? <col className="w-20" /> : null}
<col className="w-14" />
</colgroup> </colgroup>
<thead className="bg-primary text-white sticky top-0"> <thead className="bg-primary text-white sticky top-0">
<tr> <tr>
<th className="p-2 text-left text-base font-medium">ID</th> <th className="p-2 text-left text-base font-medium">ID</th>
<th className="p-2 text-left text-base font-medium">이름</th> <th className="p-2 text-left text-base font-medium">이름</th>
{showCmpnColumn ? <th className="p-2 text-left text-base font-medium">회사</th> : null}
<th className="p-2 text-right text-base font-medium">배정</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{rows.map((row) => ( {isLoading ? (
<tr>
<td colSpan={showCmpnColumn ? 4 : 3} className="p-4 text-center text-sm text-muted-foreground">
불러오는 중...
</td>
</tr>
) : rows.length === 0 ? (
<tr>
<td colSpan={showCmpnColumn ? 4 : 3} className="p-4 text-center text-sm text-muted-foreground">
대상이 없습니다.
</td>
</tr>
) : (
rows.map((row) => (
<tr <tr
key={row.id} key={row.id}
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${ className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
@@ -89,8 +185,11 @@ export function AssignTargetList({ prjctIdx, enabled, assignType, selectedId, on
> >
<td className="p-2 text-base truncate">{row.id}</td> <td className="p-2 text-base truncate">{row.id}</td>
<td className="p-2 text-base truncate">{row.name}</td> <td className="p-2 text-base truncate">{row.name}</td>
{showCmpnColumn ? <td className="p-2 text-base truncate">{row.cmpn}</td> : null}
<td className="p-2 text-base text-right">{row.assignedCount}</td>
</tr> </tr>
))} ))
)}
</tbody> </tbody>
</table> </table>
</div> </div>

View File

@@ -3,14 +3,15 @@
import * as React from 'react' import * as React from 'react'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import { MultiSelect } from '@/components/common/multi-select' import { MultiSelect } from '@/components/common/multi-select'
import type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select' import type { MultiSelectOption, MultiSelectRef, MultiSelectSearchMatch } from '@/components/common/multi-select'
export type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select' export type { MultiSelectOption, MultiSelectRef, MultiSelectSearchMatch } from '@/components/common/multi-select'
export interface KriAutoCompleteBaseProps<T> { export interface KriAutoCompleteBaseProps<T> {
items: T[] items: T[]
searchable?: boolean searchable?: boolean
searchMode?: 'filter' | 'inputOnly' searchMode?: 'filter' | 'inputOnly'
searchMatch?: MultiSelectSearchMatch
defaultSearchValue?: string defaultSearchValue?: string
onSearchValueChange?: (value: string) => void onSearchValueChange?: (value: string) => void
placeholder?: string placeholder?: string
@@ -24,6 +25,8 @@ export interface KriAutoCompleteBaseProps<T> {
getLabel?: (item: T) => string getLabel?: (item: T) => string
withInfo?: boolean withInfo?: boolean
disabled?: boolean disabled?: boolean
/** Dialog 안에서 사용될 때 팝오버 스크롤이 막히지 않도록 기본 true (Radix Dialog + non-modal Popover 중첩 스크롤락 이슈 우회) */
modalPopover?: boolean
'aria-invalid'?: boolean 'aria-invalid'?: boolean
} }
@@ -56,6 +59,7 @@ export function KriMultiSelect<T = unknown>({
onChange, onChange,
searchable = true, searchable = true,
searchMode = 'filter', searchMode = 'filter',
searchMatch = 'contains',
defaultSearchValue = '', defaultSearchValue = '',
onSearchValueChange, onSearchValueChange,
maxCount = 1, maxCount = 1,
@@ -74,6 +78,7 @@ export function KriMultiSelect<T = unknown>({
onItemsChange, onItemsChange,
onOptionsChange, onOptionsChange,
disabled, disabled,
modalPopover = true,
'aria-invalid': ariaInvalid, 'aria-invalid': ariaInvalid,
}: KriMultiSelectProps<T>) { }: KriMultiSelectProps<T>) {
const options = React.useMemo( const options = React.useMemo(
@@ -97,6 +102,7 @@ export function KriMultiSelect<T = unknown>({
badgeLabelClassName={badgeLabelClassName} badgeLabelClassName={badgeLabelClassName}
searchable={searchable} searchable={searchable}
searchMode={searchMode} searchMode={searchMode}
searchMatch={searchMatch}
defaultSearchValue={defaultSearchValue} defaultSearchValue={defaultSearchValue}
onSearchValueChange={onSearchValueChange} onSearchValueChange={onSearchValueChange}
maxCount={maxCount} maxCount={maxCount}
@@ -105,6 +111,7 @@ export function KriMultiSelect<T = unknown>({
resetOnDefaultValueChange resetOnDefaultValueChange
deduplicateOptions deduplicateOptions
disabled={disabled} disabled={disabled}
modalPopover={modalPopover}
aria-invalid={ariaInvalid} aria-invalid={ariaInvalid}
/> />
</div> </div>
@@ -131,6 +138,7 @@ function KriSingleSelectInner<T>(
onChange, onChange,
searchable = true, searchable = true,
searchMode = 'filter', searchMode = 'filter',
searchMatch = 'contains',
defaultSearchValue = '', defaultSearchValue = '',
onSearchValueChange, onSearchValueChange,
placeholder = '옵션을 선택하세요', placeholder = '옵션을 선택하세요',
@@ -152,6 +160,7 @@ function KriSingleSelectInner<T>(
clearLabel = '선택 해제', clearLabel = '선택 해제',
clearValue = '__CLEAR__', clearValue = '__CLEAR__',
disabled, disabled,
modalPopover = true,
'aria-invalid': ariaInvalid, 'aria-invalid': ariaInvalid,
}: KriSingleSelectProps<T>, }: KriSingleSelectProps<T>,
forwardedRef: React.ForwardedRef<MultiSelectRef>, forwardedRef: React.ForwardedRef<MultiSelectRef>,
@@ -211,6 +220,7 @@ function KriSingleSelectInner<T>(
badgeLabelClassName={badgeLabelClassName ?? 'min-w-0 flex-1'} badgeLabelClassName={badgeLabelClassName ?? 'min-w-0 flex-1'}
searchable={searchable} searchable={searchable}
searchMode={searchMode} searchMode={searchMode}
searchMatch={searchMatch}
defaultSearchValue={defaultSearchValue} defaultSearchValue={defaultSearchValue}
onSearchValueChange={onSearchValueChange} onSearchValueChange={onSearchValueChange}
preventDeselect={preventDeselect} preventDeselect={preventDeselect}
@@ -221,6 +231,7 @@ function KriSingleSelectInner<T>(
resetOnDefaultValueChange resetOnDefaultValueChange
deduplicateOptions deduplicateOptions
disabled={disabled} disabled={disabled}
modalPopover={modalPopover}
title={showSelectedTooltip ? selectedLabel ?? value : undefined} title={showSelectedTooltip ? selectedLabel ?? value : undefined}
aria-invalid={ariaInvalid} aria-invalid={ariaInvalid}
/> />

View File

@@ -0,0 +1,247 @@
'use client'
import { useState, type CSSProperties, type KeyboardEvent } from 'react'
import { Check } from 'lucide-react'
import { Slider as SliderPrimitive } from 'radix-ui'
import { Button } from '@/components/ui/button'
import { ColorPicker, ColorPickerArea, ColorPickerHueSlider } from '@/components/common/color-palette/color-picker'
import { Input } from '@/components/ui/input'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { cn } from '@/lib/utils'
import { formatHexColor, isLightHexColor, normalizeHexColor, parseHexColor } from '@/components/common/color-palette/color'
export const KRI_COLOR_PALETTE_DEFAULT_COLORS = [
'#111827', '#4B5563', '#9CA3AF', '#E5E7EB', '#EF4444', '#F97316', '#F59E0B', '#EAB308',
'#84CC16', '#22C55E', '#14B8A6', '#06B6D4', '#3B82F6', '#6366F1', '#A855F7', '#EC4899',
] as const
const CUSTOM_PICKER_FALLBACK = '#3B82F6'
const CHECKERBOARD = 'repeating-conic-gradient(#ccc 0% 25%, #fff 0% 50%) 0% 50% / 8px 8px'
export type KriColorPaletteProps = {
/** `#RRGGBB` 또는 `#RRGGBBAA` 형식의 색상. 지정되지 않았으면 null */
value: string | null
onChange: (value: string | null) => void
colors?: readonly string[]
/** 색상 영역·색조 슬라이더·HEX 입력 노출 여부 */
allowCustom?: boolean
/**
* 투명도 슬라이더 노출 및 `#RRGGBBAA` 입력 허용 여부.
* false여도 전달받은 값의 투명도는 표시·보존하며, 사용자가 색을 바꾸면 불투명(`#RRGGBB`)으로 바뀐다.
*/
allowAlpha?: boolean
allowClear?: boolean
disabled?: boolean
placeholder?: string
className?: string
'aria-label'?: string
}
const swatchStyle = (color: string): CSSProperties => ({
background: `linear-gradient(${color}, ${color}), ${CHECKERBOARD}`,
})
export function KriColorPalette({
value,
onChange,
colors = KRI_COLOR_PALETTE_DEFAULT_COLORS,
allowCustom = true,
allowAlpha = false,
allowClear = true,
disabled = false,
placeholder = '색상 없음',
className,
'aria-label': ariaLabel = '색상 선택',
}: KriColorPaletteProps) {
const normalizedValue = normalizeHexColor(value)
const parsedValue = parseHexColor(normalizedValue)
const currentAlpha = parsedValue?.alpha ?? 255
const [open, setOpen] = useState(false)
// 프리셋·HEX 입력·제거로 값이 바뀌면 색상 영역을 새 값으로 다시 초기화한다.
const [pickerKey, setPickerKey] = useState(0)
const [hexDraft, setHexDraft] = useState(normalizedValue ?? '')
const [hexDraftSource, setHexDraftSource] = useState(normalizedValue)
const [hexInvalid, setHexInvalid] = useState(false)
if (hexDraftSource !== normalizedValue) {
setHexDraftSource(normalizedValue)
setHexDraft(normalizedValue ?? '')
setHexInvalid(false)
}
const withAlpha = (rgb: string) => formatHexColor(rgb, allowAlpha ? currentAlpha : 255)
const selectDiscrete = (next: string | null) => {
onChange(next)
setPickerKey((key) => key + 1)
}
const handlePickerChange = (next: string) => {
const parsed = parseHexColor(next)
if (!parsed) return
const nextValue = withAlpha(parsed.rgb)
if (nextValue === normalizedValue) return
onChange(nextValue)
}
const handleAlphaChange = (values: number[]) => {
const percent = values[0] ?? 100
const nextValue = formatHexColor(parsedValue?.rgb ?? CUSTOM_PICKER_FALLBACK, (percent / 100) * 255)
if (nextValue === normalizedValue) return
onChange(nextValue)
}
const commitHexDraft = () => {
if (hexDraft.trim() === '') {
setHexDraft(normalizedValue ?? '')
setHexInvalid(false)
return
}
// 전달받은 값을 그대로 두고 포커스만 이동한 경우(투명도 포함 값 포함)는 변경으로 보지 않는다.
if (normalizeHexColor(hexDraft) === normalizedValue) {
setHexDraft(normalizedValue ?? '')
setHexInvalid(false)
return
}
const parsed = parseHexColor(hexDraft)
if (!parsed || (!allowAlpha && parsed.alpha !== 255)) {
setHexInvalid(true)
return
}
const nextValue = formatHexColor(parsed.rgb, parsed.alpha)
setHexInvalid(false)
setHexDraft(nextValue)
if (nextValue !== normalizedValue) selectDiscrete(nextValue)
}
const handleHexKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key !== 'Enter') return
event.preventDefault()
commitHexDraft()
}
const hexFormatLabel = allowAlpha ? '#RRGGBB 또는 #RRGGBBAA' : '#RRGGBB'
const alphaPercent = Math.round((currentAlpha / 255) * 100)
// disabled이면 트리거 상태와 무관하게 팝오버가 열리지 않도록 한다(이미 열린 상태에서 disabled로 바뀐 경우 포함).
const resolvedOpen = open && !disabled
return (
<Popover open={resolvedOpen} onOpenChange={(nextOpen) => setOpen(nextOpen && !disabled)}>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
size="sm"
disabled={disabled}
aria-label={`${ariaLabel}: ${normalizedValue ?? placeholder}`}
className={cn('w-full justify-start gap-2 px-2 font-normal', className)}
>
<span
aria-hidden
className={cn('size-4 shrink-0 rounded-sm border', !normalizedValue && 'bg-[linear-gradient(to_bottom_right,transparent_calc(50%-1px),var(--destructive)_calc(50%-1px)_calc(50%+1px),transparent_calc(50%+1px))]')}
style={normalizedValue ? swatchStyle(normalizedValue) : undefined}
/>
<span className={cn('truncate font-mono text-xs', !normalizedValue && 'text-muted-foreground font-sans')}>
{normalizedValue ?? placeholder}
</span>
</Button>
</PopoverTrigger>
<PopoverContent align="start" className="w-64 space-y-3 p-3">
<div className="grid grid-cols-8 gap-1.5" role="group" aria-label="기본 색상">
{colors.map((color) => {
const parsedColor = parseHexColor(color)
if (!parsedColor) return null
const selected = parsedColor.rgb === parsedValue?.rgb
const checkColorClass = isLightHexColor(parsedColor.rgb) ? 'text-black' : 'text-white'
return (
<button
key={parsedColor.rgb}
type="button"
className="focus-visible:ring-ring flex size-6 items-center justify-center rounded-sm border focus-visible:ring-2 focus-visible:outline-none"
style={{ backgroundColor: parsedColor.rgb }}
aria-label={`색상 ${parsedColor.rgb}`}
aria-pressed={selected}
title={parsedColor.rgb}
onClick={() => selectDiscrete(withAlpha(parsedColor.rgb))}
>
{selected ? <Check className={cn('size-3.5', checkColorClass)} /> : null}
</button>
)
})}
</div>
{allowCustom ? (
<div className="space-y-3 border-t pt-3">
<ColorPicker
key={pickerKey}
inline
defaultValue={parsedValue?.rgb ?? CUSTOM_PICKER_FALLBACK}
onValueChange={handlePickerChange}
className="flex flex-col gap-3"
>
<ColorPickerArea className="h-32" />
<ColorPickerHueSlider aria-label="색조" />
</ColorPicker>
{allowAlpha ? (
<div className="flex items-center gap-2">
<SliderPrimitive.Root
className="relative flex w-full touch-none items-center select-none"
min={0}
max={100}
step={1}
value={[alphaPercent]}
onValueChange={handleAlphaChange}
aria-label="투명도"
>
<SliderPrimitive.Track
className="relative h-3 w-full grow overflow-hidden rounded-full"
style={{ background: CHECKERBOARD }}
>
<div
className="absolute inset-0 rounded-full"
style={{ background: `linear-gradient(to right, transparent, ${parsedValue?.rgb ?? CUSTOM_PICKER_FALLBACK})` }}
/>
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="border-primary/50 bg-background focus-visible:ring-ring block size-4 rounded-full border shadow focus-visible:ring-1 focus-visible:outline-none" />
</SliderPrimitive.Root>
<span className="text-muted-foreground w-10 shrink-0 text-right font-mono text-xs">{alphaPercent}%</span>
</div>
) : null}
<div className="space-y-1">
<Input
value={hexDraft}
onChange={(event) => {
setHexDraft(event.target.value)
setHexInvalid(false)
}}
onBlur={commitHexDraft}
onKeyDown={handleHexKeyDown}
placeholder={allowAlpha ? '#RRGGBBAA' : '#RRGGBB'}
maxLength={allowAlpha ? 9 : 7}
aria-label="HEX 색상 코드"
aria-invalid={hexInvalid}
className="h-8 font-mono text-sm"
/>
{hexInvalid ? <p className="text-destructive text-xs">{hexFormatLabel} 형식으로 입력해 주세요.</p> : null}
</div>
</div>
) : null}
{allowClear ? (
<div className="flex justify-end border-t pt-2">
<Button
type="button"
variant="ghost"
size="sm"
disabled={!normalizedValue}
onClick={() => selectDiscrete(null)}
>
색상 제거
</Button>
</div>
) : null}
</PopoverContent>
</Popover>
)
}

View File

@@ -17,6 +17,11 @@ export type KriDateTimePickerProps = {
contentClassName?: string contentClassName?: string
disabled?: boolean disabled?: boolean
modalPopover?: boolean modalPopover?: boolean
startHour?: number
endHour?: number
minuteStep?: number
hourLabel?: string
minuteLabel?: string
} }
const parseDateTime = (value: string): { date: Date | undefined; time: string } => { const parseDateTime = (value: string): { date: Date | undefined; time: string } => {
@@ -67,6 +72,11 @@ export function KriDateTimePicker({
contentClassName, contentClassName,
disabled = false, disabled = false,
modalPopover = true, modalPopover = true,
startHour,
endHour,
minuteStep,
hourLabel,
minuteLabel,
}: KriDateTimePickerProps) { }: KriDateTimePickerProps) {
const [open, setOpen] = React.useState(false) const [open, setOpen] = React.useState(false)
const { date, time } = parseDateTime(value) const { date, time } = parseDateTime(value)
@@ -106,11 +116,17 @@ export function KriDateTimePicker({
mode="single" mode="single"
selected={date} selected={date}
onSelect={handleDateSelect} onSelect={handleDateSelect}
autoFocus
/> />
<KriTimePicker <KriTimePicker
value={time || '00:00'} value={time || '00:00'}
onChange={handleTimeChange} onChange={handleTimeChange}
disabled={!date} disabled={!date}
startHour={startHour}
endHour={endHour}
minuteStep={minuteStep}
hourLabel={hourLabel}
minuteLabel={minuteLabel}
/> />
</div> </div>
</PopoverContent> </PopoverContent>

View File

@@ -9,10 +9,10 @@ import { cn } from '@/lib/utils'
import { KRI_PW_REGEX, ONLY_ALLOWED_PW_REGEX } from '@/const/validationConst' import { KRI_PW_REGEX, ONLY_ALLOWED_PW_REGEX } from '@/const/validationConst'
const requirements = [ const requirements = [
{ test: (value: string) => /[A-Za-z]/.test(value), text: '영문 1개 이상' }, //{ test: (value: string) => /[A-Za-z]/.test(value), text: '영문 1개 이상' },
{ test: (value: string) => /\d/.test(value), text: '숫자 1개 이상' }, //{ test: (value: string) => /\d/.test(value), text: '숫자 1개 이상' },
{ test: (value: string) => value.length >= 8 && value.length <= 20, text: '8~20자' }, //{ test: (value: string) => value.length >= 1 && value.length <= 20, text: '1~20자' },
{ test: (value: string) => !value || ONLY_ALLOWED_PW_REGEX.test(value), text: '허용 문자만 사용' }, { test: (value: string) => !value || KRI_PW_REGEX.test(value), text: '영문, 숫자, 허용된 특수문자를 사용하여 1~20자로 입력해야 합니다.' },
] ]
export type KriPasswordRef = { export type KriPasswordRef = {
@@ -55,12 +55,13 @@ export const KriPassword = forwardRef<KriPasswordRef, KriPasswordProps>(function
const score = checks.filter((item) => item.met).length const score = checks.filter((item) => item.met).length
const statusText = useMemo(() => { const statusText = useMemo(() => {
if (!value) return '비밀번호를 입력하세요' if (!value) return '비밀번호를 입력하세요.'
if (!hasOnlyAllowedChars) return '허용되지 않는 문자가 포함되어 있어요' if (!hasOnlyAllowedChars) return '허용되지 않는 문자가 포함되어 있습니다.'
return isValid ? '사용 가능한 비밀번호입니다' : '영문과 숫자를 포함한 8~20자로 입력하세요' return isValid ? '사용 가능한 비밀번호입니다' : '영문, 숫자, 허용된 특수문자를 사용하여 1~20자로 입력해야 합니다.'
}, [hasOnlyAllowedChars, isValid, value]) }, [hasOnlyAllowedChars, isValid, value])
const barClass = score <= 1 ? 'bg-destructive' : score === 2 ? 'bg-orange-500' : score === 3 ? 'bg-yellow-400' : 'bg-green-500' //const barClass = score <= 1 ? 'bg-destructive' : score === 2 ? 'bg-orange-500' : score === 3 ? 'bg-yellow-400' : 'bg-green-500'
const barClass = 'bg-green-500'
return ( return (
<div className={cn('w-full space-y-2', className)}> <div className={cn('w-full space-y-2', className)}>

View File

@@ -9,6 +9,10 @@ export type KriTimePickerProps = {
onChange: (value: string) => void onChange: (value: string) => void
disabled?: boolean disabled?: boolean
minuteStep?: number minuteStep?: number
startHour?: number
endHour?: number
hourLabel?: string
minuteLabel?: string
className?: string className?: string
} }
@@ -27,18 +31,37 @@ const formatTime = (hour: number, minute: number) => {
return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}` return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
} }
const normalizeHour = (hour: number, fallback: number) => {
return Number.isFinite(hour) ? Math.min(23, Math.max(0, Math.trunc(hour))) : fallback
}
export function KriTimePicker({ export function KriTimePicker({
value, value,
onChange, onChange,
disabled = false, disabled = false,
minuteStep = 5, minuteStep = 5,
startHour = 0,
endHour = 23,
hourLabel = '시',
minuteLabel = '분',
className, className,
}: KriTimePickerProps) { }: KriTimePickerProps) {
const { hour: selectedHour, minute: selectedMinute } = parseTime(value) const { hour: selectedHour, minute: selectedMinute } = parseTime(value)
const normalizedMinuteStep = Number.isFinite(minuteStep) && minuteStep > 0 const normalizedMinuteStep = Number.isFinite(minuteStep) && minuteStep > 0
? Math.min(Math.floor(minuteStep), 60) ? Math.min(Math.floor(minuteStep), 60)
: 5 : 5
const hours = Array.from({ length: 24 }, (_, index) => index)
const clampedStartHour = normalizeHour(startHour, 0)
const clampedEndHour = normalizeHour(endHour, 23)
// startHour > endHour로 잘못 지정된 경우, 두 값을 뒤바꿔 유효한 범위로 되돌린다.
const [normalizedStartHour, normalizedEndHour] = clampedStartHour > clampedEndHour
? [clampedEndHour, clampedStartHour]
: [clampedStartHour, clampedEndHour]
const hours = Array.from(
{ length: normalizedEndHour - normalizedStartHour + 1 },
(_, index) => normalizedStartHour + index,
)
const minutes = Array.from( const minutes = Array.from(
{ length: Math.ceil(60 / normalizedMinuteStep) }, { length: Math.ceil(60 / normalizedMinuteStep) },
(_, index) => index * normalizedMinuteStep, (_, index) => index * normalizedMinuteStep,
@@ -47,7 +70,7 @@ export function KriTimePicker({
const handleTimeChange = (type: 'hour' | 'minute', nextValue: number) => { const handleTimeChange = (type: 'hour' | 'minute', nextValue: number) => {
if (disabled) return if (disabled) return
const nextHour = type === 'hour' ? nextValue : selectedHour ?? 0 const nextHour = type === 'hour' ? nextValue : selectedHour ?? normalizedStartHour
const nextMinute = type === 'minute' ? nextValue : selectedMinute ?? 0 const nextMinute = type === 'minute' ? nextValue : selectedMinute ?? 0
onChange(formatTime(nextHour, nextMinute)) onChange(formatTime(nextHour, nextMinute))
@@ -55,7 +78,9 @@ export function KriTimePicker({
return ( return (
<div className={cn('flex flex-col divide-y sm:h-[300px] sm:flex-row sm:divide-x sm:divide-y-0', className)}> <div className={cn('flex flex-col divide-y sm:h-[300px] sm:flex-row sm:divide-x sm:divide-y-0', className)}>
<ScrollArea className="w-64 sm:w-auto"> <div className="flex flex-col">
<div className="mt-1 p-1 align-middle text-center text-base border-b">{hourLabel}</div>
<ScrollArea className="w-64 sm:w-auto sm:min-h-0 sm:flex-1">
<div className="flex p-2 sm:flex-col"> <div className="flex p-2 sm:flex-col">
{hours.map((hour) => ( {hours.map((hour) => (
<Button <Button
@@ -73,8 +98,11 @@ export function KriTimePicker({
</div> </div>
<ScrollBar orientation="horizontal" className="sm:hidden" /> <ScrollBar orientation="horizontal" className="sm:hidden" />
</ScrollArea> </ScrollArea>
</div>
<ScrollArea className="w-64 sm:w-auto"> <div className="flex flex-col">
<div className="mt-1 p-1 align-middle text-center text-base border-b">{minuteLabel}</div>
<ScrollArea className="w-64 sm:w-auto sm:min-h-0 sm:flex-1">
<div className="flex p-2 sm:flex-col"> <div className="flex p-2 sm:flex-col">
{minutes.map((minute) => ( {minutes.map((minute) => (
<Button <Button
@@ -93,6 +121,7 @@ export function KriTimePicker({
<ScrollBar orientation="horizontal" className="sm:hidden" /> <ScrollBar orientation="horizontal" className="sm:hidden" />
</ScrollArea> </ScrollArea>
</div> </div>
</div>
) )
} }

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,42 @@
export type ParsedHexColor = {
/** `#RRGGBB` (대문자) */
rgb: string
/** 0~255. 투명도가 없는 값은 255 */
alpha: number
}
const HEX_COLOR_PATTERN = /^#?([0-9A-F]{6})([0-9A-F]{2})?$/
/** `#RRGGBB` 또는 `#RRGGBBAA`(대소문자 무관, `#` 생략 가능)를 해석한다. 형식이 다르면 null. */
export const parseHexColor = (value: string | null | undefined): ParsedHexColor | null => {
if (!value) return null
const match = HEX_COLOR_PATTERN.exec(value.trim().toUpperCase())
if (!match) return null
return {
rgb: `#${match[1]}`,
alpha: match[2] ? Number.parseInt(match[2], 16) : 255,
}
}
/** 투명도가 255이면 `#RRGGBB`, 아니면 `#RRGGBBAA`로 만든다. */
export const formatHexColor = (rgb: string, alpha = 255): string => {
const clamped = Math.max(0, Math.min(255, Math.round(alpha)))
if (clamped === 255) return rgb.toUpperCase()
return `${rgb.toUpperCase()}${clamped.toString(16).padStart(2, '0').toUpperCase()}`
}
/** 정규화된 hex 문자열. 형식이 다르면 null. */
export const normalizeHexColor = (value: string | null | undefined): string | null => {
const parsed = parseHexColor(value)
return parsed ? formatHexColor(parsed.rgb, parsed.alpha) : null
}
/** 흰 배경 위에 그렸을 때 밝은 색인지 판단한다(투명도 반영). 글자색 대비 결정에 쓴다. */
export const isLightHexColor = (value: string): boolean => {
const parsed = parseHexColor(value)
if (!parsed) return true
const ratio = parsed.alpha / 255
const channel = (offset: number) => Number.parseInt(parsed.rgb.slice(offset, offset + 2), 16) * ratio + 255 * (1 - ratio)
const luminance = (channel(1) * 299 + channel(3) * 587 + channel(5) * 114) / 1000
return luminance > 150
}

View File

@@ -0,0 +1,8 @@
import * as React from "react";
function useRefWithInit<T>(init: () => T): React.RefObject<T> {
const [ref] = React.useState(() => ({ current: init() }));
return ref;
}
export { useRefWithInit };

View File

@@ -0,0 +1,14 @@
import { useLayoutEffect } from "radix-ui/internal";
import * as React from "react";
function useValueAsRef<T>(value: T) {
const ref = React.useRef<T>(value);
useLayoutEffect(() => {
ref.current = value;
});
return ref;
}
export { useValueAsRef };

View File

@@ -0,0 +1,154 @@
"use client";
import * as React from "react";
type InputValue = string[] | string;
interface VisuallyHiddenInputProps<T = InputValue> extends Omit<
React.InputHTMLAttributes<HTMLInputElement>,
"value" | "checked" | "onReset"
> {
value?: T;
checked?: boolean;
control: HTMLElement | null;
bubbles?: boolean;
}
function VisuallyHiddenInput<T = InputValue>(
props: VisuallyHiddenInputProps<T>,
) {
const {
control,
value,
checked,
bubbles = true,
type = "hidden",
style,
...inputProps
} = props;
const isCheckInput = React.useMemo(
() => type === "checkbox" || type === "radio" || type === "switch",
[type],
);
const inputRef = React.useRef<HTMLInputElement>(null);
const prevValueRef = React.useRef<T | boolean | undefined>(
isCheckInput ? checked : value,
);
const [measuredSize, setMeasuredSize] = React.useState<{
control: HTMLElement;
width: number;
height: number;
} | null>(null);
const controlSize = React.useMemo<{
width?: number;
height?: number;
}>(
() =>
control && measuredSize?.control === control
? { width: measuredSize.width, height: measuredSize.height }
: {},
[control, measuredSize],
);
React.useLayoutEffect(() => {
if (!control) return;
if (typeof window === "undefined") return;
const resizeObserver = new ResizeObserver((entries) => {
if (!Array.isArray(entries) || !entries.length) return;
const entry = entries[0];
if (!entry) return;
let width: number;
let height: number;
if ("borderBoxSize" in entry) {
const borderSizeEntry = entry.borderBoxSize;
const borderSize = Array.isArray(borderSizeEntry)
? borderSizeEntry[0]
: borderSizeEntry;
width = borderSize.inlineSize;
height = borderSize.blockSize;
} else {
width = control.offsetWidth;
height = control.offsetHeight;
}
setMeasuredSize({ control, width, height });
});
resizeObserver.observe(control, { box: "border-box" });
return () => {
resizeObserver.disconnect();
};
}, [control]);
React.useEffect(() => {
const currentValue = isCheckInput ? checked : value;
const prevValue = prevValueRef.current;
prevValueRef.current = currentValue;
const input = inputRef.current;
if (!input) return;
const inputProto = window.HTMLInputElement.prototype;
const propertyKey = isCheckInput ? "checked" : "value";
const eventType = isCheckInput ? "click" : "input";
let serializedCurrentValue: unknown = value;
if (isCheckInput) {
serializedCurrentValue = checked;
} else if (typeof value === "object" && value !== null) {
serializedCurrentValue = JSON.stringify(value);
}
const descriptor = Object.getOwnPropertyDescriptor(inputProto, propertyKey);
const setter = descriptor?.set;
if (prevValue !== currentValue && setter) {
const event = new Event(eventType, { bubbles });
setter.call(input, serializedCurrentValue);
input.dispatchEvent(event);
}
}, [value, checked, bubbles, isCheckInput]);
const composedStyle = React.useMemo<React.CSSProperties>(() => {
return {
...style,
...(controlSize.width !== undefined && controlSize.height !== undefined
? controlSize
: {}),
border: 0,
clip: "rect(0 0 0 0)",
clipPath: "inset(50%)",
height: "1px",
margin: "-1px",
overflow: "hidden",
padding: 0,
position: "absolute",
whiteSpace: "nowrap",
width: "1px",
};
}, [style, controlSize]);
return (
<input
type={type}
{...inputProps}
ref={inputRef}
aria-hidden={isCheckInput}
tabIndex={-1}
defaultChecked={isCheckInput ? checked : undefined}
style={composedStyle}
/>
);
}
export { VisuallyHiddenInput };

View File

@@ -31,6 +31,7 @@ function MultiSelectInner<T>(
hideSelectAll = false, hideSelectAll = false,
searchable = true, searchable = true,
searchMode = 'filter', searchMode = 'filter',
searchMatch = 'fuzzy',
defaultSearchValue = '', defaultSearchValue = '',
onSearchValueChange, onSearchValueChange,
emptyIndicator = '검색 결과가 없습니다.', emptyIndicator = '검색 결과가 없습니다.',
@@ -201,6 +202,7 @@ function MultiSelectInner<T>(
selectedValues={selectedValues} selectedValues={selectedValues}
searchable={searchable} searchable={searchable}
searchMode={searchMode} searchMode={searchMode}
searchMatch={searchMatch}
searchValue={searchValue} searchValue={searchValue}
onSearchValueChange={handleSearchChange} onSearchValueChange={handleSearchChange}
hideSelectAll={hideSelectAll} hideSelectAll={hideSelectAll}

View File

@@ -11,14 +11,19 @@ import {
CommandSeparator, CommandSeparator,
} from '@/components/ui/command' } from '@/components/ui/command'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptions } from './types' import type { MultiSelectGroup, MultiSelectOption, MultiSelectOptions, MultiSelectSearchMatch } from './types'
import { isGroupedOptions } from './utils' import { isGroupedOptions } from './utils'
function containsFilter(value: string, search: string) {
return value.toLowerCase().includes(search.toLowerCase()) ? 1 : 0
}
interface MultiSelectContentProps<T> { interface MultiSelectContentProps<T> {
options: MultiSelectOptions<T> options: MultiSelectOptions<T>
selectedValues: string[] selectedValues: string[]
searchable: boolean searchable: boolean
searchMode: 'filter' | 'inputOnly' searchMode: 'filter' | 'inputOnly'
searchMatch?: MultiSelectSearchMatch
searchValue: string searchValue: string
onSearchValueChange: (value: string) => void onSearchValueChange: (value: string) => void
hideSelectAll: boolean hideSelectAll: boolean
@@ -96,6 +101,7 @@ export function MultiSelectContent<T>({
selectedValues, selectedValues,
searchable, searchable,
searchMode, searchMode,
searchMatch = 'fuzzy',
searchValue, searchValue,
onSearchValueChange, onSearchValueChange,
hideSelectAll, hideSelectAll,
@@ -111,7 +117,7 @@ export function MultiSelectContent<T>({
const allSelected = selectableOptions.length > 0 && selectableOptions.every((option) => selectedValues.includes(option.value)) const allSelected = selectableOptions.length > 0 && selectableOptions.every((option) => selectedValues.includes(option.value))
return ( return (
<Command shouldFilter={searchMode === 'filter'}> <Command shouldFilter={searchMode === 'filter'} filter={searchMatch === 'contains' ? containsFilter : undefined}>
{searchable ? ( {searchable ? (
<CommandInput <CommandInput
value={searchValue} value={searchValue}

View File

@@ -3,6 +3,7 @@ export type {
AnimationConfig, AnimationConfig,
MultiSelectGroup, MultiSelectGroup,
MultiSelectOption, MultiSelectOption,
MultiSelectSearchMatch,
MultiSelectOptions, MultiSelectOptions,
MultiSelectProps, MultiSelectProps,
MultiSelectRef, MultiSelectRef,

View File

@@ -28,6 +28,7 @@ export interface MultiSelectGroup<T = unknown> {
export type MultiSelectOptions<T = unknown> = MultiSelectOption<T>[] | MultiSelectGroup<T>[] export type MultiSelectOptions<T = unknown> = MultiSelectOption<T>[] | MultiSelectGroup<T>[]
export type MultiSelectSelectionMode = 'single' | 'multiple' export type MultiSelectSelectionMode = 'single' | 'multiple'
export type MultiSelectSearchMatch = 'fuzzy' | 'contains'
export type MultiSelectVariant = 'default' | 'secondary' | 'destructive' | 'inverted' export type MultiSelectVariant = 'default' | 'secondary' | 'destructive' | 'inverted'
export interface MultiSelectResponsiveSettings { export interface MultiSelectResponsiveSettings {
@@ -65,6 +66,7 @@ export interface MultiSelectProps<T = unknown>
hideSelectAll?: boolean hideSelectAll?: boolean
searchable?: boolean searchable?: boolean
searchMode?: 'filter' | 'inputOnly' searchMode?: 'filter' | 'inputOnly'
searchMatch?: MultiSelectSearchMatch
defaultSearchValue?: string defaultSearchValue?: string
onSearchValueChange?: (value: string) => void onSearchValueChange?: (value: string) => void
emptyIndicator?: React.ReactNode emptyIndicator?: React.ReactNode

View File

@@ -1,7 +1,7 @@
'use client' 'use client'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import type { OnChangeFn, PaginationState, Row, RowSelectionState, SortingState } from '@tanstack/react-table' import type { OnChangeFn, PaginationState, Row, RowPinningState, RowSelectionState, SortingState } from '@tanstack/react-table'
import { flexRender, getCoreRowModel, getPaginationRowModel, getSortedRowModel, useReactTable } from '@tanstack/react-table' import { flexRender, getCoreRowModel, getPaginationRowModel, getSortedRowModel, useReactTable } from '@tanstack/react-table'
import { ArrowDown, ArrowUp, ArrowUpDown } from 'lucide-react' import { ArrowDown, ArrowUp, ArrowUpDown } from 'lucide-react'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
@@ -12,6 +12,8 @@ import type { DataTableColumn, DataTableProps } from './DataTable.type'
import { DataTablePagination } from './DataTablePagination' import { DataTablePagination } from './DataTablePagination'
import { usePreventClickOnDrag } from './hooks/usePreventClickOnDrag' import { usePreventClickOnDrag } from './hooks/usePreventClickOnDrag'
const EMPTY_PINNED_ROWS: never[] = []
export function DataTable<TData, TValue = unknown>({ export function DataTable<TData, TValue = unknown>({
columns, columns,
data, data,
@@ -23,6 +25,7 @@ export function DataTable<TData, TValue = unknown>({
totalCount: serverTotalCount, totalCount: serverTotalCount,
pagination: externalPagination, pagination: externalPagination,
onPaginationChange: onServerPaginationChange, onPaginationChange: onServerPaginationChange,
sorting: externalSorting,
onSortingChange: onServerSortingChange, onSortingChange: onServerSortingChange,
selectMode = 'none', selectMode = 'none',
onRowClick, onRowClick,
@@ -34,11 +37,14 @@ export function DataTable<TData, TValue = unknown>({
emptyText = '데이터가 없습니다.', emptyText = '데이터가 없습니다.',
className, className,
maxBodyHeight, maxBodyHeight,
disablePagination = false,
topPinnedRows = EMPTY_PINNED_ROWS,
bottomPinnedRows = EMPTY_PINNED_ROWS,
}: Readonly<DataTableProps<TData, TValue>>) { }: Readonly<DataTableProps<TData, TValue>>) {
const [internalPagination, setInternalPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: defaultPageSize }) const [internalPagination, setInternalPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: defaultPageSize })
const [sorting, setSorting] = useState<SortingState>([]) const [internalSorting, setInternalSorting] = useState<SortingState>([])
const [rowSelection, setRowSelection] = useState<RowSelectionState>({}) const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
const containerRef = useRef<HTMLDivElement>(null) const scrollContainerRef = useRef<HTMLDivElement>(null)
const drag = usePreventClickOnDrag() const drag = usePreventClickOnDrag()
const selectionEnabled = selectMode === 'single' || selectMode === 'multi' const selectionEnabled = selectMode === 'single' || selectMode === 'multi'
@@ -54,7 +60,7 @@ export function DataTable<TData, TValue = unknown>({
aria-label="전체 선택" aria-label="전체 선택"
/> />
) : null, ) : null,
cell: ({ row }) => ( cell: ({ row }) => row.getIsPinned() ? null : (
<Checkbox <Checkbox
checked={row.getIsSelected()} checked={row.getIsSelected()}
onCheckedChange={(value) => { onCheckedChange={(value) => {
@@ -73,6 +79,7 @@ export function DataTable<TData, TValue = unknown>({
}, [columns, selectMode, selectionEnabled]) }, [columns, selectMode, selectionEnabled])
const pagination = isClient ? internalPagination : (externalPagination ?? internalPagination) const pagination = isClient ? internalPagination : (externalPagination ?? internalPagination)
const sorting = !isClient && externalSorting ? externalSorting : internalSorting
useEffect(() => { useEffect(() => {
setRowSelection({}) setRowSelection({})
@@ -95,28 +102,59 @@ export function DataTable<TData, TValue = unknown>({
[isClient, onServerPaginationChange], [isClient, onServerPaginationChange],
) )
const handleSortingChange = useCallback<OnChangeFn<SortingState>>(
(updater) => {
const nextSorting = typeof updater === 'function' ? updater(sorting) : updater
if (!isClient && onServerSortingChange) {
onServerSortingChange(nextSorting)
return
}
setInternalSorting(nextSorting)
},
[isClient, onServerSortingChange, sorting],
)
const combinedData = useMemo(
() => [...topPinnedRows, ...data, ...bottomPinnedRows],
[topPinnedRows, data, bottomPinnedRows],
)
const internalGetRowId = useCallback((_row: TData, index: number) => {
if (index < topPinnedRows.length) return `__top-pinned-${index}`
if (index >= topPinnedRows.length + data.length) {
return `__bottom-pinned-${index - topPinnedRows.length - data.length}`
}
const originalIndex = index - topPinnedRows.length
return getRowId ? getRowId(data[originalIndex], originalIndex) : String(originalIndex)
}, [topPinnedRows.length, data, getRowId])
const rowPinning = useMemo<RowPinningState>(() => ({
top: topPinnedRows.map((_, i) => `__top-pinned-${i}`),
bottom: bottomPinnedRows.map((_, i) => `__bottom-pinned-${i}`),
}), [topPinnedRows, bottomPinnedRows])
const table = useReactTable({ const table = useReactTable({
data, data: combinedData,
columns: enhancedColumns, columns: enhancedColumns,
pageCount: isClient ? undefined : serverPageCount, pageCount: isClient ? undefined : serverPageCount,
state: { sorting, pagination, rowSelection }, state: { sorting, pagination, rowSelection, rowPinning },
enableRowSelection: selectionEnabled, enableRowSelection: (row) => selectionEnabled && !row.getIsPinned(),
enableRowPinning: true,
keepPinnedRows: true,
onRowSelectionChange: setRowSelection, onRowSelectionChange: setRowSelection,
onSortingChange: setSorting, onSortingChange: handleSortingChange,
onPaginationChange: handlePaginationChange, onPaginationChange: handlePaginationChange,
getCoreRowModel: getCoreRowModel(), getCoreRowModel: getCoreRowModel(),
getSortedRowModel: isClient ? getSortedRowModel() : undefined, getSortedRowModel: isClient ? getSortedRowModel() : undefined,
getPaginationRowModel: isClient ? getPaginationRowModel() : undefined, getPaginationRowModel: isClient && !disablePagination ? getPaginationRowModel() : undefined,
manualPagination: !isClient, manualPagination: !isClient,
manualSorting: !isClient, manualSorting: !isClient,
enableSortingRemoval: false, enableSortingRemoval: false,
...(getRowId ? { getRowId } : {}), getRowId: internalGetRowId,
}) })
useEffect(() => {
if (!isClient) onServerSortingChange?.(sorting)
}, [isClient, onServerSortingChange, sorting])
useEffect(() => { useEffect(() => {
if (!selectionEnabled) return if (!selectionEnabled) return
onRowSelectionChange?.(table.getSelectedRowModel().rows.map((row) => row.original)) onRowSelectionChange?.(table.getSelectedRowModel().rows.map((row) => row.original))
@@ -124,7 +162,7 @@ export function DataTable<TData, TValue = unknown>({
useEffect(() => { useEffect(() => {
if (!focusRowId) return if (!focusRowId) return
const target = containerRef.current?.querySelector<HTMLElement>(`[data-row-id="${CSS.escape(focusRowId)}"]`) const target = scrollContainerRef.current?.querySelector<HTMLElement>(`[data-row-id="${CSS.escape(focusRowId)}"]`)
target?.scrollIntoView({ behavior: 'smooth', block: 'center' }) target?.scrollIntoView({ behavior: 'smooth', block: 'center' })
}, [focusRowId, data]) }, [focusRowId, data])
@@ -150,15 +188,48 @@ export function DataTable<TData, TValue = unknown>({
const totalCount = isClient ? data.length : (serverTotalCount ?? 0) const totalCount = isClient ? data.length : (serverTotalCount ?? 0)
const topRows = table.getTopRows()
const centerRows = table.getCenterRows()
const bottomRows = table.getBottomRows()
const [topOffsets, setTopOffsets] = useState<number[]>([])
const [bottomOffsets, setBottomOffsets] = useState<number[]>([])
useLayoutEffect(() => {
if (!maxBodyHeight) return
const container = scrollContainerRef.current
if (!container) return
const headerHeight = container.querySelector('thead')?.getBoundingClientRect().height ?? 0
const bodyRows = Array.from(container.querySelectorAll('tbody > tr'))
const topRowEls = bodyRows.slice(0, topRows.length)
const bottomRowEls = bottomRows.length ? bodyRows.slice(-bottomRows.length) : []
let topAcc = headerHeight
setTopOffsets(topRowEls.map((element) => {
const offset = topAcc
topAcc += element.getBoundingClientRect().height
return offset
}))
let bottomAcc = 0
const offsets: number[] = []
for (let index = bottomRowEls.length - 1; index >= 0; index -= 1) {
offsets[index] = bottomAcc
bottomAcc += bottomRowEls[index].getBoundingClientRect().height
}
setBottomOffsets(offsets)
}, [maxBodyHeight, topRows.length, bottomRows.length, centerRows.length])
return ( return (
<div className={cn('w-full space-y-4', className)}> <div className={cn('w-full space-y-4', className)}>
<div <div
ref={containerRef} ref={scrollContainerRef}
className={cn('relative w-full overflow-x-auto rounded-md border', maxBodyHeight && 'overflow-y-auto')} className={cn('relative w-full overflow-x-auto rounded-md border', maxBodyHeight && 'overflow-y-auto')}
style={maxBodyHeight ? { maxHeight: maxBodyHeight } : undefined} style={maxBodyHeight ? { maxHeight: maxBodyHeight } : undefined}
> >
<table className="w-full caption-bottom text-sm"> <table className="w-full caption-bottom text-sm">
<TableHeader className={cn(maxBodyHeight && 'sticky top-0 z-10 bg-background')}> <TableHeader className={cn(maxBodyHeight && 'sticky top-0 z-20 bg-background')}>
{table.getHeaderGroups().map((headerGroup) => ( {table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id} className="hover:bg-transparent"> <TableRow key={headerGroup.id} className="hover:bg-transparent">
{headerGroup.headers.map((header) => { {headerGroup.headers.map((header) => {
@@ -171,7 +242,7 @@ export function DataTable<TData, TValue = unknown>({
<TableHead <TableHead
key={header.id} key={header.id}
className={cn( className={cn(
'text-base font-semibold text-foreground', 'text-base font-semibold bg-primary text-primary-foreground',
column.id === 'actions' && 'w-[140px] text-center', column.id === 'actions' && 'w-[140px] text-center',
maxWidth && 'overflow-hidden text-ellipsis', maxWidth && 'overflow-hidden text-ellipsis',
)} )}
@@ -181,9 +252,16 @@ export function DataTable<TData, TValue = unknown>({
}} }}
> >
{!header.isPlaceholder && column.getCanSort() ? ( {!header.isPlaceholder && column.getCanSort() ? (
<Button type="button" variant="ghost" className="flex gap-1 px-0 text-base font-semibold" onClick={column.getToggleSortingHandler()}> <Button
type="button"
variant="ghost"
className={cn(
"flex gap-1 px-0 text-base font-semibold",
)}
onClick={column.getToggleSortingHandler()}
>
<span>{content}</span> <span>{content}</span>
{sorted === 'asc' ? <ArrowUp className="size-3" /> : sorted === 'desc' ? <ArrowDown className="size-3" /> : <ArrowUpDown className="text-muted-foreground size-3" />} {sorted === 'asc' ? <ArrowUp className="size-3" /> : sorted === 'desc' ? <ArrowDown className="size-3" /> : <ArrowUpDown className="size-3" />}
</Button> </Button>
) : content} ) : content}
</TableHead> </TableHead>
@@ -193,7 +271,19 @@ export function DataTable<TData, TValue = unknown>({
))} ))}
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{table.getRowModel().rows.length ? table.getRowModel().rows.map((row) => ( {topRows.map((row, index) => (
<TableRow
key={row.id}
className={cn(
'bg-muted text-base font-semibold [&>td]:px-2 [&>td]:py-1.5',
maxBodyHeight && 'sticky z-10',
)}
style={maxBodyHeight ? { top: topOffsets[index] ?? 0 } : undefined}
>
{row.getVisibleCells().map((cell) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
</TableRow>
))}
{centerRows.length ? centerRows.map((row) => (
<TableRow <TableRow
key={row.id} key={row.id}
data-row-id={row.id} data-row-id={row.id}
@@ -228,10 +318,23 @@ export function DataTable<TData, TValue = unknown>({
)) : ( )) : (
<TableRow><TableCell colSpan={enhancedColumns.length} className="h-24 text-center">{emptyText}</TableCell></TableRow> <TableRow><TableCell colSpan={enhancedColumns.length} className="h-24 text-center">{emptyText}</TableCell></TableRow>
)} )}
{bottomRows.map((row, index) => (
<TableRow
key={row.id}
className={cn(
'bg-muted text-base font-semibold [&>td]:px-2 [&>td]:py-1.5',
maxBodyHeight && 'sticky z-10',
)}
style={maxBodyHeight ? { bottom: bottomOffsets[index] ?? 0 } : undefined}
>
{row.getVisibleCells().map((cell) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
</TableRow>
))}
</TableBody> </TableBody>
</table> </table>
</div> </div>
{!disablePagination && (
<DataTablePagination <DataTablePagination
table={table} table={table}
isClient={isClient} isClient={isClient}
@@ -239,6 +342,7 @@ export function DataTable<TData, TValue = unknown>({
pageSizeOptions={pageSizeOptions} pageSizeOptions={pageSizeOptions}
paginationItemsToDisplay={paginationItemsToDisplay} paginationItemsToDisplay={paginationItemsToDisplay}
/> />
)}
</div> </div>
) )
} }

View File

@@ -33,6 +33,7 @@ export interface DataTableProps<TData, TValue = unknown> {
totalCount?: number totalCount?: number
pagination?: PaginationState pagination?: PaginationState
onPaginationChange?: (updater: Updater<PaginationState>) => void onPaginationChange?: (updater: Updater<PaginationState>) => void
sorting?: SortingState
onSortingChange?: (sorting: SortingState) => void onSortingChange?: (sorting: SortingState) => void
selectMode?: SelectMode selectMode?: SelectMode
onRowClick?: (row: TData) => void onRowClick?: (row: TData) => void
@@ -44,4 +45,7 @@ export interface DataTableProps<TData, TValue = unknown> {
emptyText?: string emptyText?: string
className?: string className?: string
maxBodyHeight?: string maxBodyHeight?: string
disablePagination?: boolean
topPinnedRows?: TData[]
bottomPinnedRows?: TData[]
} }

View File

@@ -15,7 +15,7 @@ export function usePagination({ currentPage, totalPages, paginationItemsToDispla
const visibleCount = Math.max(1, paginationItemsToDisplay) const visibleCount = Math.max(1, paginationItemsToDisplay)
const half = Math.floor(visibleCount / 2) const half = Math.floor(visibleCount / 2)
let startPage = Math.max(1, currentPage - half) let startPage = Math.max(1, currentPage - half)
let endPage = Math.min(totalPages, startPage + visibleCount - 1) const endPage = Math.min(totalPages, startPage + visibleCount - 1)
if (endPage - startPage + 1 < visibleCount) { if (endPage - startPage + 1 < visibleCount) {
startPage = Math.max(1, endPage - visibleCount + 1) startPage = Math.max(1, endPage - visibleCount + 1)

View File

@@ -15,6 +15,7 @@ import {
import { KriSingleSelect } from '@/components/common/KriAutoComplete' import { KriSingleSelect } from '@/components/common/KriAutoComplete'
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption' import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
import { useDialog } from '@/hooks/useDialog' import { useDialog } from '@/hooks/useDialog'
import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate'
import type { DialogId } from '@/store/jotai/dialog' import type { DialogId } from '@/store/jotai/dialog'
import type { FilterValueOption, ListFilterTarget } from '@/types/list' import type { FilterValueOption, ListFilterTarget } from '@/types/list'
import { type ProjectSurvey, type ResultCode, ResultCodeType } from '@/types/project' import { type ProjectSurvey, type ResultCode, ResultCodeType } from '@/types/project'
@@ -47,12 +48,14 @@ export type BatchEditPayload = {
} }
export type ListBatchEditDialogProps = { export type ListBatchEditDialogProps = {
prjctIdx: number
dialogId?: DialogId dialogId?: DialogId
open?: boolean open?: boolean
onOpenChange?: (open: boolean) => void onOpenChange?: (open: boolean) => void
headerOptions: BatchEditOption[] headerOptions: BatchEditOption[]
resultCodes: ResultCode[] resultCodes: ResultCode[]
surveys: ProjectSurvey[] surveys: ProjectSurvey[]
selectedSids: string[]
filterSummary?: string[] filterSummary?: string[]
initialRows?: BatchEditRow[] initialRows?: BatchEditRow[]
initialResultCodes?: BatchEditResultCodes initialResultCodes?: BatchEditResultCodes
@@ -74,12 +77,14 @@ const resultCodeGroups: { type: Exclude<ResultCodeType, ResultCodeType.SURVEY>;
] ]
const ListBatchEditDialog = ({ const ListBatchEditDialog = ({
prjctIdx,
dialogId = 'listBatchEditDialog', dialogId = 'listBatchEditDialog',
open, open,
onOpenChange, onOpenChange,
headerOptions, headerOptions,
resultCodes, resultCodes,
surveys, surveys,
selectedSids,
filterSummary, filterSummary,
initialRows = [], initialRows = [],
initialResultCodes = {}, initialResultCodes = {},
@@ -96,6 +101,7 @@ const ListBatchEditDialog = ({
const rowInputRefs = useRef<Map<string, HTMLInputElement>>(new Map()) const rowInputRefs = useRef<Map<string, HTMLInputElement>>(new Map())
const resolvedOpen = open ?? isDialogOpen(dialogId) const resolvedOpen = open ?? isDialogOpen(dialogId)
const gate = useListJobGate({ prjctIdx, jobType: 'LIST_UPDATE', active: resolvedOpen })
const defaultHeaderId = headerOptions[0]?.id ?? 0 const defaultHeaderId = headerOptions[0]?.id ?? 0
const isFileHeader = (headerId: number) => headerOptions.find((option) => option.id === headerId)?.listHderTy === ListHeaderConst.FILE const isFileHeader = (headerId: number) => headerOptions.find((option) => option.id === headerId)?.listHderTy === ListHeaderConst.FILE
@@ -105,8 +111,6 @@ const ListBatchEditDialog = ({
if (!resolvedOpen) return if (!resolvedOpen) return
if (initialRows.length > 0) { if (initialRows.length > 0) {
setRows(initialRows.map((row) => ({ ...row }))) setRows(initialRows.map((row) => ({ ...row })))
} else if (defaultHeaderId > 0) {
setRows([createRow(defaultHeaderId, isFileHeader(defaultHeaderId) ? LIST_BATCH_EDIT_FILE_DELETE_VALUE : '')])
} else { } else {
setRows([]) setRows([])
} }
@@ -114,7 +118,7 @@ const ListBatchEditDialog = ({
setSurveyResultSelections({ ...initialSurveyResultCodes }) setSurveyResultSelections({ ...initialSurveyResultCodes })
setTarget('filtered') setTarget('filtered')
setInvalidRowId(null) setInvalidRowId(null)
}, [resolvedOpen, initialRows, initialResultCodes, initialSurveyResultCodes, defaultHeaderId]) }, [resolvedOpen, initialRows, initialResultCodes, initialSurveyResultCodes])
const handleOpenChange = (nextOpen: boolean) => { const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen) onOpenChange?.(nextOpen)
@@ -168,8 +172,9 @@ const ListBatchEditDialog = ({
} }
const handleConfirm = async () => { const handleConfirm = async () => {
if (gate.submitBlocked || submitting) return
setInvalidRowId(null) setInvalidRowId(null)
if (!validateApplyFilterTarget(target, filterSummary)) return if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
const normalized = rows.filter((row) => row.headerId > 0 && row.value.trim().length > 0) const normalized = rows.filter((row) => row.headerId > 0 && row.value.trim().length > 0)
const surveyResultCodes = Object.entries(surveyResultSelections).map(([prjctSurveyIdx, resultCd]) => ({ const surveyResultCodes = Object.entries(surveyResultSelections).map(([prjctSurveyIdx, resultCd]) => ({
@@ -203,7 +208,6 @@ const ListBatchEditDialog = ({
setSubmitting(true) setSubmitting(true)
try { try {
await onConfirm({ rows: normalized, resultCodes: resultCodeSelections, surveyResultCodes, target }) await onConfirm({ rows: normalized, resultCodes: resultCodeSelections, surveyResultCodes, target })
handleOpenChange(false)
} finally { } finally {
setSubmitting(false) setSubmitting(false)
} }
@@ -214,22 +218,32 @@ const ListBatchEditDialog = ({
open={resolvedOpen} open={resolvedOpen}
onOpenChange={handleOpenChange} onOpenChange={handleOpenChange}
title={<span className="text-2xl font-bold">일괄 수정</span>} title={<span className="text-2xl font-bold">일괄 수정</span>}
contentClassName="sm:max-w-[900px]" contentClassName="sm:max-w-[900px] max-h-[90vh] overflow-y-auto"
bodyClassName="space-y-4" bodyClassName="space-y-4"
footer={ footer={
<> <>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}> <Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소 {gate.hasCurrentJob ? '닫기' : '취소'}
</Button> </Button>
<Button type="button" onClick={handleConfirm} disabled={submitting}> {!gate.hasCurrentJob && (
<Button type="button" onClick={handleConfirm} disabled={submitting || gate.submitBlocked}>
적용 적용
</Button> </Button>
)}
</> </>
} }
> >
<ListJobGatePanel gate={gate} acknowledgeLabel="새 작업" />
{!gate.hasCurrentJob && <>
<div className="rounded-md border p-4 space-y-4"> <div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold">적용 대상</p> <p className="text-lg font-semibold">적용 대상</p>
<ApplyFilterOption value={target} onValueChange={setTarget} idPrefix="batch-edit-target" filterSummary={filterSummary} /> <ApplyFilterOption
value={target}
onValueChange={setTarget}
idPrefix="batch-edit-target"
selectedSids={selectedSids}
filterSummary={filterSummary}
/>
</div> </div>
<div className="rounded-md border p-4 space-y-3"> <div className="rounded-md border p-4 space-y-3">
@@ -393,6 +407,7 @@ const ListBatchEditDialog = ({
<Plus className="w-4 h-4" /> <Plus className="w-4 h-4" />
행 추가 행 추가
</Button> </Button>
</>}
</KriDialog> </KriDialog>
) )
} }

View File

@@ -7,15 +7,29 @@ import type { ListFilterTarget } from "@/types/list";
export type ApplyFilterOptionValue = ListFilterTarget export type ApplyFilterOptionValue = ListFilterTarget
type ApplyFilterTargetValidation = {
selectedCount: number
filterSummary?: string[]
}
/** /**
* "필터 적용 대상만"을 선택했는데 실제로 적용된 필터가 없는 경우를 검사한다. * 선택 항목과 필터 적용 대상의 유효성을 각각 실제 상태값으로 검사한다.
* alert 후 진행을 막아야 하는 호출부에서 공통으로 사용한다. * alert 후 진행을 막아야 하는 호출부에서 공통으로 사용한다.
*/ */
export const validateApplyFilterTarget = (value: ApplyFilterOptionValue, filterSummary?: string[]): boolean => { export const validateApplyFilterTarget = (
if (value === 'filtered' && (filterSummary?.length ?? 0) === 0) { value: ApplyFilterOptionValue,
alert('적용된 필터가 없습니다. 필터를 적용해 주세요.') { selectedCount, filterSummary }: ApplyFilterTargetValidation,
): boolean => {
if (value === "selected" && selectedCount === 0) {
alert("선택된 항목이 없습니다. 항목을 선택해 주세요")
return false return false
} }
if (value === "filtered" && (filterSummary?.length ?? 0) === 0) {
alert("적용된 필터가 없습니다. 필터를 적용해 주세요.")
return false
}
return true return true
} }
@@ -23,11 +37,13 @@ type ApplyFilterGroupProps = {
value: ApplyFilterOptionValue value: ApplyFilterOptionValue
onValueChange: (value: ApplyFilterOptionValue) => void onValueChange: (value: ApplyFilterOptionValue) => void
idPrefix: string idPrefix: string
/** 현재 선택된 리스트의 SID 목록 */
selectedSids?: string[]
/** '필터 적용 대상만' 선택 시 보여줄, 사람이 읽을 수 있는 현재 필터 조건 목록 */ /** '필터 적용 대상만' 선택 시 보여줄, 사람이 읽을 수 있는 현재 필터 조건 목록 */
filterSummary?: string[] filterSummary?: string[]
} }
const ApplyFilterOption = ({ value, onValueChange, idPrefix, filterSummary }: ApplyFilterGroupProps) => { const ApplyFilterOption = ({ value, onValueChange, idPrefix, selectedSids, filterSummary }: ApplyFilterGroupProps) => {
return ( return (
<div className="space-y-3"> <div className="space-y-3">
<RadioGroup <RadioGroup
@@ -49,6 +65,19 @@ const ApplyFilterOption = ({ value, onValueChange, idPrefix, filterSummary }: Ap
</div> </div>
</RadioGroup> </RadioGroup>
{value === 'selected' && selectedSids !== undefined && (
<div className="rounded-md border px-4 py-3 text-sm">
<p className="font-semibold mb-1">선택된 SID ({selectedSids.length}개)</p>
{selectedSids.length > 0 ? (
<p className="text-muted-foreground max-h-40 overflow-y-auto break-words">
{selectedSids.join(', ')}
</p>
) : (
<p className="text-muted-foreground">선택된 항목이 없습니다.</p>
)}
</div>
)}
{value === 'filtered' && filterSummary !== undefined && ( {value === 'filtered' && filterSummary !== undefined && (
<div className="rounded-md border px-4 py-3 text-sm"> <div className="rounded-md border px-4 py-3 text-sm">
<p className="font-semibold mb-1">적용된 필터</p> <p className="font-semibold mb-1">적용된 필터</p>

View File

@@ -4,19 +4,30 @@ import { useState } from 'react'
import { Download } from 'lucide-react' import { Download } from 'lucide-react'
import { KriDialog } from '@/components/common/KriDialog' import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Label } from '@/components/ui/label' import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group' import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { useDialog } from '@/hooks/useDialog' import { useDialog } from '@/hooks/useDialog'
import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate'
import { LIST_DOWNLOAD_JOB_TYPE } from '@/const/listJobConst'
import type { DialogId } from '@/store/jotai/dialog' import type { DialogId } from '@/store/jotai/dialog'
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption' import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
import KriDateRangePicker from '@/components/common/KriDateRangePicker' import KriDateRangePicker from '@/components/common/KriDateRangePicker'
import type { ContactHistoryDownloadType, ListDownloadMode, ListDownloadPayload, ListFilterTarget } from '@/types/list' import {
type ContactHistoryDownloadType,
ListEventHistoryOrder,
type ListDownloadMode,
type ListDownloadPayload,
type ListFilterTarget,
} from '@/types/list'
export type ListDownloadDialogProps = { export type ListDownloadDialogProps = {
prjctIdx: number
dialogId?: DialogId dialogId?: DialogId
open?: boolean open?: boolean
onOpenChange?: (open: boolean) => void onOpenChange?: (open: boolean) => void
mode: ListDownloadMode mode: ListDownloadMode
selectedSids: string[]
filterSummary?: string[] filterSummary?: string[]
onDownload: (payload: ListDownloadPayload) => void | Promise<void> onDownload: (payload: ListDownloadPayload) => void | Promise<void>
} }
@@ -29,10 +40,12 @@ const titleMap: Record<ListDownloadMode, string> = {
} }
const ListDownloadDialog = ({ const ListDownloadDialog = ({
prjctIdx,
dialogId = 'listDownloadDialog', dialogId = 'listDownloadDialog',
open, open,
onOpenChange, onOpenChange,
mode, mode,
selectedSids,
filterSummary, filterSummary,
onDownload, onDownload,
}: ListDownloadDialogProps) => { }: ListDownloadDialogProps) => {
@@ -41,9 +54,12 @@ const ListDownloadDialog = ({
const [contactHistoryDateFrom, setContactHistoryDateFrom] = useState('') const [contactHistoryDateFrom, setContactHistoryDateFrom] = useState('')
const [contactHistoryDateTo, setContactHistoryDateTo] = useState('') const [contactHistoryDateTo, setContactHistoryDateTo] = useState('')
const [contactHistoryType, setContactHistoryType] = useState<ContactHistoryDownloadType>('all') const [contactHistoryType, setContactHistoryType] = useState<ContactHistoryDownloadType>('all')
const [historyOrder, setHistoryOrder] = useState<ListEventHistoryOrder>(ListEventHistoryOrder.DESC)
const [includeResult, setIncludeResult] = useState(true)
const [submitting, setSubmitting] = useState(false) const [submitting, setSubmitting] = useState(false)
const resolvedOpen = open ?? isDialogOpen(dialogId) const resolvedOpen = open ?? isDialogOpen(dialogId)
const gate = useListJobGate({ prjctIdx, jobType: LIST_DOWNLOAD_JOB_TYPE[mode], active: resolvedOpen })
const handleOpenChange = (nextOpen: boolean) => { const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen) onOpenChange?.(nextOpen)
@@ -55,7 +71,8 @@ const ListDownloadDialog = ({
} }
const handleDownload = async () => { const handleDownload = async () => {
if (!validateApplyFilterTarget(target, filterSummary)) return if (gate.submitBlocked || submitting) return
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
if (mode === 'contact-history') { if (mode === 'contact-history') {
const hasFrom = contactHistoryDateFrom.length > 0 const hasFrom = contactHistoryDateFrom.length > 0
@@ -76,11 +93,12 @@ const ListDownloadDialog = ({
mode, mode,
target, target,
onlyFiltered: target === 'filtered', onlyFiltered: target === 'filtered',
includeResult,
contactHistoryDateFrom: mode === 'contact-history' ? contactHistoryDateFrom || undefined : undefined, contactHistoryDateFrom: mode === 'contact-history' ? contactHistoryDateFrom || undefined : undefined,
contactHistoryDateTo: mode === 'contact-history' ? contactHistoryDateTo || undefined : undefined, contactHistoryDateTo: mode === 'contact-history' ? contactHistoryDateTo || undefined : undefined,
contactHistoryType: mode === 'contact-history' ? contactHistoryType : undefined, contactHistoryType: mode === 'contact-history' ? contactHistoryType : undefined,
historyOrder: mode === 'contact-history' ? historyOrder : undefined,
}) })
handleOpenChange(false)
} finally { } finally {
setSubmitting(false) setSubmitting(false)
} }
@@ -91,20 +109,24 @@ const ListDownloadDialog = ({
open={resolvedOpen} open={resolvedOpen}
onOpenChange={handleOpenChange} onOpenChange={handleOpenChange}
title={<span className="text-2xl font-bold">{titleMap[mode]}</span>} title={<span className="text-2xl font-bold">{titleMap[mode]}</span>}
contentClassName="sm:max-w-[560px]" contentClassName="sm:max-w-[560px] max-h-[90vh] overflow-y-auto"
bodyClassName="space-y-4" bodyClassName="space-y-4"
footer={ footer={
<> <>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}> <Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소 {gate.hasCurrentJob ? '닫기' : '취소'}
</Button> </Button>
<Button type="button" onClick={handleDownload} disabled={submitting} className="gap-2"> {!gate.hasCurrentJob && (
<Button type="button" onClick={handleDownload} disabled={submitting || gate.submitBlocked} className="gap-2">
<Download className="w-4 h-4" /> <Download className="w-4 h-4" />
다운로드 다운로드
</Button> </Button>
)}
</> </>
} }
> >
<ListJobGatePanel gate={gate} acknowledgeLabel="새 작업" />
{!gate.hasCurrentJob && <>
{mode === 'contact-history' ? ( {mode === 'contact-history' ? (
<div className="rounded-md border p-4 space-y-4"> <div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold">조회 기간</p> <p className="text-lg font-semibold">조회 기간</p>
@@ -120,8 +142,24 @@ const ListDownloadDialog = ({
) : null} ) : null}
<div className="rounded-md border p-4 space-y-4"> <div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold">다운로드 범위</p> <p className="text-lg font-semibold">다운로드 범위</p>
<ApplyFilterOption value={target} onValueChange={setTarget} idPrefix="download-scope-target" filterSummary={filterSummary} /> <ApplyFilterOption
value={target}
onValueChange={setTarget}
idPrefix="download-scope-target"
selectedSids={selectedSids}
filterSummary={filterSummary}
/>
</div> </div>
{mode === 'list' || mode === 'contact-history' ? (
<div className="flex items-center gap-2 rounded-md border p-4">
<Checkbox
id="download-include-result"
checked={includeResult}
onCheckedChange={(checked) => setIncludeResult(checked === true)}
/>
<Label className="text-base" htmlFor="download-include-result">결과값 포함</Label>
</div>
) : null}
{mode === 'contact-history' ? ( {mode === 'contact-history' ? (
<div className="rounded-md border p-4 space-y-4"> <div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold">이력 기준</p> <p className="text-lg font-semibold">이력 기준</p>
@@ -141,6 +179,26 @@ const ListDownloadDialog = ({
</RadioGroup> </RadioGroup>
</div> </div>
) : null} ) : null}
{mode === 'contact-history' && contactHistoryType === 'all' ? (
<div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold">이력 순서</p>
<RadioGroup
value={historyOrder}
onValueChange={(value) => setHistoryOrder(value as ListEventHistoryOrder)}
className="flex items-center gap-6 flex-wrap"
>
<div className="flex items-center gap-2">
<RadioGroupItem value={ListEventHistoryOrder.DESC} id="download-history-order-desc" />
<Label className="text-base" htmlFor="download-history-order-desc">최근 이력이 왼쪽부터</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem value={ListEventHistoryOrder.ASC} id="download-history-order-asc" />
<Label className="text-base" htmlFor="download-history-order-asc">오래된 이력이 왼쪽부터</Label>
</div>
</RadioGroup>
</div>
) : null}
</>}
</KriDialog> </KriDialog>
) )
} }

View File

@@ -1,7 +1,7 @@
'use client' 'use client'
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
import { Plus, X } from 'lucide-react' import { RotateCcw } from 'lucide-react'
import { KriDialog } from '@/components/common/KriDialog' import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
@@ -33,12 +33,13 @@ export const operatorLabel: Record<FilterOperator, string> = {
notContains: '포함하지 않음', notContains: '포함하지 않음',
empty: '값 없음', empty: '값 없음',
notEmpty: '값 있음', notEmpty: '값 있음',
none: '필터 없음',
} }
const createFilterRow = (headerId: number, headerOptions: FilterHeaderOption[]): FilterRow => ({ const createFilterRow = (headerId: number, headerOptions: FilterHeaderOption[]): FilterRow => ({
id: crypto.randomUUID(), id: crypto.randomUUID(),
headerId, headerId,
operator: headerOptions.find((option) => option.id === headerId)?.allowedOperators[0] ?? 'eq', operator: headerOptions.find((option) => option.id === headerId)?.defaultOperator ?? 'eq',
textValue: '', textValue: '',
multiValues: [], multiValues: [],
}) })
@@ -56,18 +57,17 @@ const ListFilterDialog = ({
const [submitting, setSubmitting] = useState(false) const [submitting, setSubmitting] = useState(false)
const resolvedOpen = open ?? isDialogOpen(dialogId) const resolvedOpen = open ?? isDialogOpen(dialogId)
const defaultHeaderId = headerOptions.find((option) => !option.disabled)?.id ?? 0
useEffect(() => { useEffect(() => {
if (!resolvedOpen) return if (!resolvedOpen) return
if (initialRows.length > 0) { const initialByHeaderId = new Map(initialRows.map((row) => [row.headerId, row]))
setRows(initialRows.map((row) => ({ ...row }))) setRows(
return headerOptions.map((option) => {
} const existing = initialByHeaderId.get(option.id)
if (defaultHeaderId > 0) { return existing ? { ...existing } : createFilterRow(option.id, headerOptions)
setRows([createFilterRow(defaultHeaderId, headerOptions)]) }),
} )
}, [resolvedOpen, initialRows, defaultHeaderId, headerOptions]) }, [resolvedOpen, initialRows, headerOptions])
const handleOpenChange = (nextOpen: boolean) => { const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen) onOpenChange?.(nextOpen)
@@ -78,17 +78,8 @@ const ListFilterDialog = ({
hideDialog(dialogId) hideDialog(dialogId)
} }
const handleAddRow = () => { const handleChangeRow = (headerId: number, updater: (row: FilterRow) => FilterRow) => {
if (defaultHeaderId <= 0) return setRows((prev) => prev.map((row) => (row.headerId === headerId ? updater(row) : row)))
setRows((prev) => [...prev, createFilterRow(defaultHeaderId, headerOptions)])
}
const handleRemoveRow = (id: string) => {
setRows((prev) => prev.filter((row) => row.id !== id))
}
const handleChangeRow = (id: string, updater: (row: FilterRow) => FilterRow) => {
setRows((prev) => prev.map((row) => (row.id === id ? updater(row) : row)))
} }
const getHeaderOption = (headerId: number) => headerOptions.find((item) => item.id === headerId) const getHeaderOption = (headerId: number) => headerOptions.find((item) => item.id === headerId)
@@ -108,6 +99,7 @@ const ListFilterDialog = ({
rows rows
.map((row) => { .map((row) => {
if (isDisabledHeader(row.headerId)) return null if (isDisabledHeader(row.headerId)) return null
if (row.operator === 'none') return null
if (row.operator === 'empty' || row.operator === 'notEmpty') return row if (row.operator === 'empty' || row.operator === 'notEmpty') return row
if (isListValueHeader(row.headerId)) return row.multiValues.length > 0 ? row : null if (isListValueHeader(row.headerId)) return row.multiValues.length > 0 ? row : null
return row.textValue.trim().length > 0 ? row : null return row.textValue.trim().length > 0 ? row : null
@@ -116,14 +108,19 @@ const ListFilterDialog = ({
[rows, headerOptions], [rows, headerOptions],
) )
const handleConfirm = async () => { // 잠긴 헤더는 조회 조건에 쓰이지 않으므로 초기화 필요 여부 판단에서 제외한다.
// rows가 아예 없으면 "필터를 전부 지우겠다"는 의도이므로 그대로 통과시킨다. const isResettable = rows.some((row) => {
// rows는 있는데 값을 안 채워 serializedRows가 비면, 실수로 방치된 조건일 가능성이 높아 알려준다. if (isDisabledHeader(row.headerId)) return false
if (rows.length > 0 && serializedRows.length === 0) { const defaultOperator = getHeaderOption(row.headerId)?.defaultOperator ?? 'eq'
alert('필터 조건을 입력해주세요.') return row.operator !== defaultOperator || row.textValue !== '' || row.multiValues.length > 0
return })
// 다이얼로그 내 입력만 기본값으로 되돌린다. 실제 반영은 "적용"을 눌러야 이뤄진다.
const handleReset = () => {
setRows(headerOptions.map((option) => createFilterRow(option.id, headerOptions)))
} }
const handleConfirm = async () => {
setSubmitting(true) setSubmitting(true)
try { try {
await onConfirm(serializedRows) await onConfirm(serializedRows)
@@ -151,61 +148,46 @@ const ListFilterDialog = ({
} }
> >
<div className="overflow-hidden rounded-md border"> <div className="overflow-hidden rounded-md border">
<div className="grid h-11 grid-cols-[1fr_140px_1.4fr_64px] items-center border-b bg-muted px-4 text-sm font-semibold"> <div className="grid h-11 grid-cols-[1fr_140px_1.4fr] items-center border-b bg-muted px-4 text-sm font-semibold">
<span>헤더</span> <span>헤더</span>
<span>비교 연산자</span> <span>비교 연산자</span>
<div className="flex items-center justify-between gap-2">
<span>값</span> <span>값</span>
<span /> <Button
type="button"
variant="ghost"
size="sm"
className="h-7 text-muted-foreground"
onClick={handleReset}
disabled={submitting || !isResettable}
>
<RotateCcw className="size-3.5" />
초기화
</Button>
</div>
</div> </div>
<div className="max-h-80 overflow-auto"> <div className="max-h-170 overflow-auto">
{rows.map((row) => { {rows.map((row) => {
const valueOptions = getValueOptions(row.headerId) const valueOptions = getValueOptions(row.headerId)
const listMode = isListValueHeader(row.headerId) const listMode = isListValueHeader(row.headerId)
const disabled = isDisabledHeader(row.headerId) const disabled = isDisabledHeader(row.headerId)
const rowAllowedOperators = getAllowedOperators(row.headerId) const rowAllowedOperators = getAllowedOperators(row.headerId)
const isEmptyOperator = row.operator === 'empty' || row.operator === 'notEmpty' const isValuelessOperator = row.operator === 'empty' || row.operator === 'notEmpty' || row.operator === 'none'
const headerLabel = getHeaderOption(row.headerId)?.label ?? String(row.headerId)
return ( return (
<div <div
key={row.id} key={row.headerId}
className="grid min-h-12 grid-cols-[1fr_140px_1.4fr_64px] items-center gap-2 border-b px-4 py-2 last:border-b-0" className="grid min-h-12 grid-cols-[1fr_140px_1.4fr] items-center gap-2 border-b px-4 py-2 last:border-b-0"
> >
<Select <span className={disabled ? 'text-sm text-muted-foreground' : 'text-sm'}>{headerLabel}</span>
value={String(row.headerId)}
disabled={disabled}
onValueChange={(value) => {
const nextHeaderId = Number(value)
const nextAllowedOperators = getAllowedOperators(nextHeaderId)
handleChangeRow(row.id, (current) => ({
...current,
headerId: nextHeaderId,
operator: nextAllowedOperators.includes(current.operator)
? current.operator
: nextAllowedOperators[0] ?? 'eq',
textValue: '',
multiValues: [],
}))
}}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="헤더 선택" />
</SelectTrigger>
<SelectContent>
{headerOptions.map((option) => (
<SelectItem key={option.id} value={String(option.id)} disabled={option.disabled}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
<Select <Select
value={row.operator} value={row.operator}
disabled={disabled} disabled={disabled}
onValueChange={(value) => onValueChange={(value) =>
handleChangeRow(row.id, (current) => ({ handleChangeRow(row.headerId, (current) => ({
...current, ...current,
operator: value as FilterOperator, operator: value as FilterOperator,
})) }))
@@ -223,7 +205,7 @@ const ListFilterDialog = ({
</SelectContent> </SelectContent>
</Select> </Select>
{isEmptyOperator ? ( {isValuelessOperator ? (
<Input placeholder="값을 입력할 필요 없음" value="" disabled /> <Input placeholder="값을 입력할 필요 없음" value="" disabled />
) : listMode ? ( ) : listMode ? (
<KriMultiSelect <KriMultiSelect
@@ -231,7 +213,7 @@ const ListFilterDialog = ({
value={row.multiValues} value={row.multiValues}
disabled={disabled} disabled={disabled}
onChange={(values) => onChange={(values) =>
handleChangeRow(row.id, (current) => ({ handleChangeRow(row.headerId, (current) => ({
...current, ...current,
multiValues: values, multiValues: values,
})) }))
@@ -252,36 +234,18 @@ const ListFilterDialog = ({
value={row.textValue} value={row.textValue}
disabled={disabled} disabled={disabled}
onChange={(event) => onChange={(event) =>
handleChangeRow(row.id, (current) => ({ handleChangeRow(row.headerId, (current) => ({
...current, ...current,
textValue: event.target.value, textValue: event.target.value,
})) }))
} }
/> />
)} )}
<div className="flex justify-center">
<Button
type="button"
variant="ghost"
size="icon-sm"
disabled={disabled}
onClick={() => handleRemoveRow(row.id)}
aria-label="조건 제거"
>
<X className="h-4 w-4" />
</Button>
</div>
</div> </div>
) )
})} })}
</div> </div>
</div> </div>
<Button type="button" variant="outline" onClick={handleAddRow} className="gap-2" disabled={defaultHeaderId <= 0}>
<Plus className="h-4 w-4" />
조건 추가
</Button>
</KriDialog> </KriDialog>
) )
} }

View File

@@ -1,6 +1,6 @@
'use client' 'use client'
import { CSSProperties, useEffect, useState } from 'react' import { CSSProperties, useEffect, useRef, useState } from 'react'
import { import {
closestCenter, closestCenter,
DndContext, DndContext,
@@ -20,6 +20,7 @@ import {
} from '@dnd-kit/sortable' } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities' import { CSS } from '@dnd-kit/utilities'
import { GripVertical, Plus, Trash2 } from 'lucide-react' import { GripVertical, Plus, Trash2 } from 'lucide-react'
import { KriColorPalette } from '@/components/common/KriColorPalette'
import { KriDialog } from '@/components/common/KriDialog' import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox' import { Checkbox } from '@/components/ui/checkbox'
@@ -29,7 +30,7 @@ import { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog' import type { DialogId } from '@/store/jotai/dialog'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import { listHeader, ListHeaderGrade, ListHeaderType } from '@/types/list' import { listHeader, ListHeaderGrade, ListHeaderType } from '@/types/list'
import { LIST_HEADER_TYPE_LABEL, LIST_HEADER_TYPE_OPTIONS } from '@/const/listConst' import { LIST_HEADER_TYPE_LABEL, LIST_HEADER_TYPE_OPTIONS, ListHeaderConst } from '@/const/listConst'
export type ListHeaderManageDialogProps = { export type ListHeaderManageDialogProps = {
dialogId?: DialogId dialogId?: DialogId
@@ -38,27 +39,48 @@ export type ListHeaderManageDialogProps = {
prjctIdx: number prjctIdx: number
rows: listHeader[] rows: listHeader[]
onConfirm: (rows: listHeader[]) => void | Promise<void> onConfirm: (rows: listHeader[]) => void | Promise<void>
saveDisabled?: boolean
} }
type ListHeaderRowProps = { type ListHeaderRowProps = {
row: listHeader row: listHeader
activeId: number | null activeId: number | null
onHeaderColorChange: (id: number, color: string | null) => void
onHeaderNameChange: (id: number, listHderNm: string) => void onHeaderNameChange: (id: number, listHderNm: string) => void
onHeaderTypeChange: (id: number, listHderTy: ListHeaderType) => void onHeaderTypeChange: (id: number, listHderTy: ListHeaderType) => void
onFlagChange: (id: number, field: 'useColView' | 'useFilter' | 'useIntrvwerView' | 'useIntrvwerEdit', checked: boolean) => void onFlagChange: (id: number, field: 'useColView' | 'useFilter' | 'useIntrvwerView' | 'useIntrvwerEdit', checked: boolean) => void
onDelete: (id: number) => void onDelete: (id: number) => void
} }
const COMMON_GRADE_ORDER_START = 101
const isCommonGrade = (grade: ListHeaderGrade) => grade === ListHeaderGrade.COMMON const isCommonGrade = (grade: ListHeaderGrade) => grade === ListHeaderGrade.COMMON
const isImmutableGrade = (grade: ListHeaderGrade) => grade === ListHeaderGrade.IMMUTABLE const isImmutableGrade = (grade: ListHeaderGrade) => grade === ListHeaderGrade.IMMUTABLE
const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange, onFlagChange, onDelete }: ListHeaderRowProps) => { const isInterviewerEditDisabled = (row: listHeader) =>
isImmutableGrade(row.listHderGrad) ||
row.listHderTy === ListHeaderConst.IS_USE ||
row.listHderTy === ListHeaderConst.OUTSOURCE ||
row.listHderTy === ListHeaderConst.CONTACT_INTERVIEWER ||
row.listHderTy === ListHeaderConst.FIELD_INTERVIEWER
const ListHeaderRow = ({
row,
activeId,
onHeaderColorChange,
onHeaderNameChange,
onHeaderTypeChange,
onFlagChange,
onDelete,
}: ListHeaderRowProps) => {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: row.listHderId }) const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: row.listHderId })
const canEditName = isCommonGrade(row.listHderGrad) const canEditName = isCommonGrade(row.listHderGrad)
const canEditType = isCommonGrade(row.listHderGrad) const canEditType = isCommonGrade(row.listHderGrad)
const canDelete = isCommonGrade(row.listHderGrad) const canDelete = isCommonGrade(row.listHderGrad)
const canEditFlags = !isImmutableGrade(row.listHderGrad) const canEditFlags = !isImmutableGrade(row.listHderGrad)
const canSort = isCommonGrade(row.listHderGrad) const canSort = isCommonGrade(row.listHderGrad)
// IMMUTABLE 헤더의 색상은 서버가 저장하지 않으므로 선택을 막는다.
const canEditColor = !isImmutableGrade(row.listHderGrad)
const style: CSSProperties = { const style: CSSProperties = {
transform: CSS.Transform.toString(transform), transform: CSS.Transform.toString(transform),
@@ -76,7 +98,7 @@ const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange,
ref={setNodeRef} ref={setNodeRef}
style={style} style={style}
className={cn( className={cn(
'h-12 px-4 border-b last:border-b-0 grid grid-cols-[56px_1fr_150px_96px_96px_110px_110px_88px] items-center gap-2', 'h-12 px-4 border-b last:border-b-0 grid grid-cols-[56px_1fr_150px_120px_96px_96px_110px_110px_88px] items-center gap-2',
(activeId === row.listHderId || isDragging) && 'bg-muted', (activeId === row.listHderId || isDragging) && 'bg-muted',
)} )}
> >
@@ -121,6 +143,12 @@ const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange,
))} ))}
</SelectContent> </SelectContent>
</Select> </Select>
<KriColorPalette
value={row.listHderColor ?? null}
onChange={(color) => onHeaderColorChange(row.listHderId, color)}
disabled={!canEditColor}
aria-label={`${row.listHderNm} 헤더 색상`}
/>
<div className="flex items-center gap-2 justify-center"> <div className="flex items-center gap-2 justify-center">
<Checkbox <Checkbox
id={`header-visible-${row.listHderId}`} id={`header-visible-${row.listHderId}`}
@@ -150,7 +178,7 @@ const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange,
id={`header-intrvwer-edit-${row.listHderId}`} id={`header-intrvwer-edit-${row.listHderId}`}
checked={row.useIntrvwerEdit} checked={row.useIntrvwerEdit}
onCheckedChange={(checked) => onFlagChange(row.listHderId, 'useIntrvwerEdit', checked === true)} onCheckedChange={(checked) => onFlagChange(row.listHderId, 'useIntrvwerEdit', checked === true)}
disabled={!canEditFlags} disabled={isInterviewerEditDisabled(row)}
/> />
</div> </div>
<div className="flex justify-center"> <div className="flex justify-center">
@@ -177,11 +205,13 @@ const ListHeaderManageDialog = ({
prjctIdx, prjctIdx,
rows, rows,
onConfirm, onConfirm,
saveDisabled = false,
}: ListHeaderManageDialogProps) => { }: ListHeaderManageDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog() const { isDialogOpen, showDialog, hideDialog } = useDialog()
const [localRows, setLocalRows] = useState<listHeader[]>([]) const [localRows, setLocalRows] = useState<listHeader[]>([])
const [activeId, setActiveId] = useState<number | null>(null) const [activeId, setActiveId] = useState<number | null>(null)
const [submitting, setSubmitting] = useState(false) const [submitting, setSubmitting] = useState(false)
const originalRowsRef = useRef<listHeader[]>([])
const resolvedOpen = open ?? isDialogOpen(dialogId) const resolvedOpen = open ?? isDialogOpen(dialogId)
const sensors = useSensors( const sensors = useSensors(
@@ -191,7 +221,9 @@ const ListHeaderManageDialog = ({
useEffect(() => { useEffect(() => {
if (!resolvedOpen) return if (!resolvedOpen) return
setLocalRows(rows.map((row) => ({ ...row }))) const sorted = [...rows].sort((a, b) => a.listHderOrder - b.listHderOrder).map((row) => ({ ...row }))
setLocalRows(sorted)
originalRowsRef.current = sorted.map((row) => ({ ...row }))
}, [resolvedOpen, rows]) }, [resolvedOpen, rows])
const handleOpenChange = (nextOpen: boolean) => { const handleOpenChange = (nextOpen: boolean) => {
@@ -242,6 +274,16 @@ const ListHeaderManageDialog = ({
) )
} }
const handleHeaderColorChange = (id: number, listHderColor: string | null) => {
setLocalRows((prev) =>
prev.map((row) => {
if (row.listHderId !== id) return row
if (isImmutableGrade(row.listHderGrad)) return row
return { ...row, listHderColor }
}),
)
}
const handleHeaderNameChange = (id: number, listHderNm: string) => { const handleHeaderNameChange = (id: number, listHderNm: string) => {
setLocalRows((prev) => setLocalRows((prev) =>
prev.map((row) => { prev.map((row) => {
@@ -261,6 +303,7 @@ const ListHeaderManageDialog = ({
prev.map((row) => { prev.map((row) => {
if (row.listHderId !== id) return row if (row.listHderId !== id) return row
if (isImmutableGrade(row.listHderGrad)) return row if (isImmutableGrade(row.listHderGrad)) return row
if (field === 'useIntrvwerEdit' && isInterviewerEditDisabled(row)) return row
return { ...row, [field]: checked } return { ...row, [field]: checked }
}), }),
) )
@@ -287,6 +330,7 @@ const ListHeaderManageDialog = ({
useColView: true, useColView: true,
useIntrvwerView: false, useIntrvwerView: false,
useIntrvwerEdit: false, useIntrvwerEdit: false,
listHderColor: null,
} }
return [...prev, nextRow] return [...prev, nextRow]
@@ -294,13 +338,50 @@ const ListHeaderManageDialog = ({
} }
const handleConfirm = async () => { const handleConfirm = async () => {
if (saveDisabled || submitting) return
const names = localRows.map((row) => row.listHderNm.trim())
if (names.some((name) => name.length === 0)) {
alert('헤더명을 입력해 주세요.')
return
}
const duplicateNames = [...new Set(names.filter((name, index) => names.indexOf(name) !== index))]
if (duplicateNames.length > 0) {
alert(`중복된 헤더명이 있습니다: ${duplicateNames.join(', ')}`)
return
}
const localById = new Map(localRows.map((row) => [row.listHderId, row]))
const renamedNames = originalRowsRef.current
.filter((row) => {
const current = localById.get(row.listHderId)
return current && current.listHderNm.trim() !== row.listHderNm.trim()
})
.map((row) => row.listHderNm)
const deletedNames = originalRowsRef.current
.filter((row) => !localById.has(row.listHderId))
.map((row) => row.listHderNm)
if (renamedNames.length > 0 || deletedNames.length > 0) {
const messageLines = [
'헤더명이 수정 되거나 헤더가 삭제되면 KON또는 KON-KIWI의 리스트 관련 하드코딩이 있다면 해당 문항에 문제가 생길 수 있습니다. 진행 하시겠습니까?\n',
]
if (renamedNames.length > 0) messageLines.push(`수정예정: ${renamedNames.join(', ')}`)
if (deletedNames.length > 0) messageLines.push(`삭제예정: ${deletedNames.join(', ')}`)
if (!window.confirm(messageLines.join('\n'))) return
}
setSubmitting(true) setSubmitting(true)
try { try {
const orderedRows = localRows.map((row, index) => ({ let defaultOrder = 0
...row, let commonOrder = COMMON_GRADE_ORDER_START - 1
prjctIdx: row.prjctIdx ?? prjctIdx, const orderedRows = localRows.map((row) => {
listHderOrder: index + 1, const isCommon = isCommonGrade(row.listHderGrad)
})) const listHderOrder = isCommon ? (commonOrder += 1) : (defaultOrder += 1)
const listHderNm = isCommon ? row.listHderNm.trim() : row.listHderNm
return { ...row, prjctIdx: row.prjctIdx ?? prjctIdx, listHderOrder, listHderNm }
})
await onConfirm(orderedRows) await onConfirm(orderedRows)
handleOpenChange(false) handleOpenChange(false)
} finally { } finally {
@@ -319,14 +400,16 @@ const ListHeaderManageDialog = ({
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}> <Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소 취소
</Button> </Button>
<Button type="button" onClick={handleConfirm} disabled={submitting}> <Button type="button" onClick={handleConfirm} disabled={submitting || saveDisabled}>
저장 저장
</Button> </Button>
</> </>
} }
> >
{saveDisabled && <p role="alert" className="mb-2 text-sm text-amber-800">리스트 작업이 진행 중이거나 작업 상태를 확인할 수 없어 헤더를 저장할 수 없습니다.</p>}
<div className="flex justify-end mb-2"> <div className="flex justify-between mb-2">
<span className="text-base text-red-600 font-semibold">⚠️ 헤더명이 수정 되거나 헤더가 삭제되면 KON또는 KON-KIWI의 리스트 관련 하드코딩에 영향이 있을 수 있습니다.</span>
<Button type="button" className="gap-2 bg-blue" onClick={handleAddHeader} disabled={submitting}> <Button type="button" className="gap-2 bg-blue" onClick={handleAddHeader} disabled={submitting}>
<Plus className="w-4 h-4" /> <Plus className="w-4 h-4" />
헤더 추가 헤더 추가
@@ -334,10 +417,11 @@ const ListHeaderManageDialog = ({
</div> </div>
<div className="rounded-md border overflow-hidden"> <div className="rounded-md border overflow-hidden">
<div className="h-11 px-4 border-b bg-muted grid grid-cols-[56px_1fr_150px_96px_96px_110px_110px_88px] items-center gap-2 text-sm font-semibold"> <div className="h-11 px-4 border-b bg-muted grid grid-cols-[56px_1fr_150px_120px_96px_96px_110px_110px_88px] items-center gap-2 text-sm font-semibold">
<span>순서</span> <span>순서</span>
<span>헤더명</span> <span>헤더명</span>
<span>헤더 타입</span> <span>헤더 타입</span>
<span>헤더 색상</span>
<span>헤더 노출</span> <span>헤더 노출</span>
<span>필터 사용</span> <span>필터 사용</span>
<span>면접원 노출</span> <span>면접원 노출</span>
@@ -359,6 +443,7 @@ const ListHeaderManageDialog = ({
key={row.listHderId} key={row.listHderId}
row={row} row={row}
activeId={activeId} activeId={activeId}
onHeaderColorChange={handleHeaderColorChange}
onHeaderNameChange={handleHeaderNameChange} onHeaderNameChange={handleHeaderNameChange}
onHeaderTypeChange={handleHeaderTypeChange} onHeaderTypeChange={handleHeaderTypeChange}
onFlagChange={handleFlagChange} onFlagChange={handleFlagChange}

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