Compare commits

...

201 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
91920301ef Merge pull request 'develop' (#7) from develop into master
Reviewed-on: #7
2026-07-22 16:57:26 +09:00
2dd5b88c6f 260722_01_ENH: 버그 수정 및 개선 사항 수정 2026-07-22 16:53:00 +09:00
d8b565276d 260720_01_DOC: 의미 없는 파일 삭제 2026-07-20 14:59:52 +09:00
c7f261fb26 Merge pull request '260716_04_ENH: 내부 통신용 API 통신 실패 시 alert 노출 X' (#6) from develop into master
Reviewed-on: #6
2026-07-16 16:24:56 +09:00
b5b335bfe8 260716_04_ENH: 내부 통신용 API 통신 실패 시 alert 노출 X 2026-07-16 16:24:06 +09:00
bb2c0c1951 Merge pull request '260716_03_ENH: 권한 별 노출에 대한 수정' (#5) from develop into master
Reviewed-on: #5
2026-07-16 15:59:51 +09:00
4ca93ab26a 260716_03_ENH: 권한 별 노출에 대한 수정 2026-07-16 15:58:59 +09:00
8352c8ca8d Merge pull request '260716_02_ENH: 프로젝트에 발신 번호추가 및 리다이렉트 url, api 수정' (#4) from develop into master
Reviewed-on: #4
2026-07-16 15:22:09 +09:00
7275c77db0 260716_02_ENH: 프로젝트에 발신 번호추가 및 리다이렉트 url, api 수정 2026-07-16 14:10:42 +09:00
c12953ad9c Merge pull request 'develop' (#3) from develop into master
Reviewed-on: #3
2026-07-16 09:38:00 +09:00
36c7b41191 260716_01_ENH: 본 서버에서 기동 후 중간 테스트를 위한 커밋 2026-07-16 09:12:57 +09:00
c710a60beb 260714_03_BUG: env 파일 수정 2026-07-14 12:11:25 +09:00
22994c8434 260714_02_BUG: 차트의 useResizeKey 안의 timer type 오류 수정 2026-07-14 11:52:04 +09:00
d14fa3720d Merge pull request 'feature-list' (#2) from feature-list into develop
Reviewed-on: #2
2026-07-14 11:37:51 +09:00
192d47bdb1 260714_01_ENH: 테스트 서버에서 기동 후 중간 테스트를 위한 커밋 2026-07-14 10:59:07 +09:00
a8ce35f5bf 260702_01_ENH: 리스트 작업 도중 공용 ui를 적용하기 위한 중간 커밋 2026-07-02 17:02:17 +09:00
6944064377 260427_01_ENH: 리스트 다이얼로그 및 리스트 작업 시작 2026-04-27 09:55:51 +09:00
1953b6528b 260324_01_ENH: 구동 포트 변경 2026-03-24 10:02:41 +09:00
f7ce249aa7 260312_01_ENH: Error 페이지 및 Redirect 페이지 구현 2026-03-12 09:36:09 +09:00
bedcfbc9d1 Merge pull request '260303_01_ENH: TanStack Query 적용' (#1) from feature-TanStack-Query into develop
Reviewed-on: #1
2026-03-03 16:11:07 +09:00
d8e894b136 260303_01_ENH: TanStack Query 적용 2026-03-03 16:07:41 +09:00
316 changed files with 29740 additions and 9137 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.

5
.env
View File

@@ -1 +1,4 @@
NEXT_PUBLIC_STORE_KEY = 4b6f7265615265736561726368-496e7465726e6174696f6e616c-49545465616d NEXT_PUBLIC_STORE_KEY = 4b6f7265615265736561726368-496e7465726e6174696f6e616c-49545465616d
NEXT_PUBLIC_REQUEST_SVC = kri-contact
NEXT_PUBLIC_API_INTERNAL=https://intranet.kric.com
NEXT_PUBLIC_CTI_WS_URL=wss://teracall.kric.com:2302

View File

@@ -1,10 +1,9 @@
NEXT_PUBLIC_ENV=dev NEXT_PUBLIC_ENV=dev
NEXT_PUBLIC_API_BASE=http://localhost:3000/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://localhost:4001 CONTACT_SERVER=http://127.0.0.1:4001
API_CONTACT_SERVER=http://localhost: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,15 +1,9 @@
NEXT_PUBLIC_ENV=local NEXT_PUBLIC_ENV=local
NEXT_PUBLIC_API_BASE=http://localhost:3000/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://localhost:4011/api/v1
API_NOTIHUB_SERVER=https://noti-hub.kric.com/api/v1
#API_INTRANET_SERVER=http://localhost:3031/api/v1
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1 API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
AUTH_COOKIE_DOMAIN=
API_KART_SERVER=https://rapi.kric.com/api/v1
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=http://localhost:3000/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://localhost:4001 CONTACT_SERVER=http://127.0.0.1:4001
API_CONTACT_SERVER=http://localhost: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

View File

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

6
.idea/misc.xml generated
View File

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>

2
.npmrc Normal file
View File

@@ -0,0 +1,2 @@
@kri:registry=https://gitea.kric.com/api/packages/KRi/npm/
//gitea.kric.com/api/packages/KRi/npm/:_authToken=${GITEA_NPM_TOKEN}

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

@@ -1,18 +1,47 @@
import type { NextConfig } from "next"; import type { NextConfig } from "next";
import { createEnv, createKriNextConfig, env } from "@kri/common/config";
const nextConfig: NextConfig = { const nextEnv = createEnv({
/* config options here */ CONTACT_SERVER: env.required("CONTACT_SERVER", process.env.CONTACT_SERVER),
output: "standalone", });
reactCompiler: true,
const nextConfig = createKriNextConfig({
async rewrites() { async rewrites() {
return [ return [
{ {
source: "/contact-senario/:path*", source: "/contact-senario/:path*",
destination: `${process.env.CONTACT_SERVER}/contact-senario/:path*`, destination: `${nextEnv.CONTACT_SERVER}/contact-senario/:path*`,
}, },
]; ];
}, },
};
async headers() {
return [
{
source: "/api/external/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: "*" },
{ key: "Access-Control-Allow-Methods", value: "GET,POST,PUT,PATCH,DELETE" },
{
key: "Access-Control-Allow-Headers",
value: "Content-Type, Authorization, X-Requested-With",
},
],
},
{
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;
export default nextConfig; export default nextConfig;

3525
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -3,12 +3,16 @@
"version": "0.1.0", "version": "0.1.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev -p 4000",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start -p 4000",
"lint": "eslint" "lint": "eslint"
}, },
"dependencies": { "dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@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",
@@ -19,8 +23,10 @@
"@radix-ui/react-separator": "^1.1.8", "@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4", "@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-tabs": "^1.1.13", "@radix-ui/react-tabs": "^1.1.13",
"@tanstack/react-query": "^5.90.21",
"@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",
@@ -34,30 +40,35 @@
"@tiptap/extension-underline": "^3.13.0", "@tiptap/extension-underline": "^3.13.0",
"@tiptap/react": "^3.12.0", "@tiptap/react": "^3.12.0",
"@tiptap/starter-kit": "^3.12.0", "@tiptap/starter-kit": "^3.12.0",
"@types/lodash": "^4.17.21",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1", "cmdk": "^1.1.1",
"crypto-js": "^4.2.0", "cn": "0.5.2",
"date-fns": "^4.4.0",
"dompurify": "^3.4.10",
"echarts": "^6.1.0",
"echarts-for-react": "^3.0.6",
"jotai": "^2.15.1", "jotai": "^2.15.1",
"lodash": "^4.17.21",
"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",
"radix-ui": "^1.6.1",
"react": "^19.2.1", "react": "^19.2.1",
"react-day-picker": "^10.0.1",
"react-dom": "^19.2.1", "react-dom": "^19.2.1",
"sonner": "^2.0.7", "sonner": "^2.0.7",
"tailwind-merge": "^3.4.0" "xlsx": "^0.18.5"
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/postcss": "^4", "@tailwindcss/postcss": "^4",
"@types/crypto-js": "^4.2.2", "@types/node": "^24.19.2",
"@types/node": "^20", "@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"

View File

@@ -1 +0,0 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

Before

Width:  |  Height:  |  Size: 391 B

View File

@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

Before

Width:  |  Height:  |  Size: 1.0 KiB

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

BIN
public/qr_example.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 851 KiB

View File

@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

Before

Width:  |  Height:  |  Size: 128 B

View File

@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

Before

Width:  |  Height:  |  Size: 385 B

View File

@@ -0,0 +1,263 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { useAtom } from 'jotai'
import { listJobOpenRequestAtom } from '@/store/jotai/list-job'
import { useMounted } from '@kri/common/hooks'
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
import { useAuth } from '@/hooks/useAuth'
import { useSelectedProject } from '@/hooks/useSelectedProject'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
import { AssignTargetList, useAssignTargetRows } from '@/components/assign/AssignTargetList'
import { ListSearchTable } from '@/components/list/ListSearchTable'
import { useProjectInfoQuery, useResultCodesQuery } from '@/query/project'
import { useListHeaderQuery } from '@/query/list'
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 { createEmptyListFilter, type ListFilter, type ListHeaderAssignType, type listHeader } from '@/types/list'
import type { ResultCode } from '@/types/project'
import { isExternalManager } from '@/utils/userRole'
const ASSIGN_TAB_TYPES: ListHeaderAssignType[] = [
ListHeaderAssignConst.CONTACT_INTERVIEWER,
ListHeaderAssignConst.FIELD_INTERVIEWER,
ListHeaderAssignConst.OUTSOURCE,
]
const ASSIGNED_SENTINEL = '__ASSIGNED__'
const UNASSIGNED_SENTINEL = '__UNASSIGNED__'
const isAssignFilterSentinel = (value: string) => value === ASSIGNED_SENTINEL || value === UNASSIGNED_SENTINEL
const ListAssignPage = () => {
const mounted = useMounted()
const { auth } = useAuth()
const { selectedProject } = useSelectedProject()
const prjctIdx = selectedProject?.prjctIdx ?? 0
const enabled = mounted && prjctIdx > 0
const userRole = auth?.user?.userRole ?? 0
const isExternalUser = isExternalManager(userRole)
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 [assignFilterIds, setAssignFilterIds] = useState<string[]>([])
const [transferResve, setTransferResve] = useState(false)
const [currentListFilter, setCurrentListFilter] = useState<ListFilter>(() => createEmptyListFilter())
const [filterSummary, setFilterSummary] = useState<string[]>([])
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled)
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled)
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
const assignMutation = useSubmitListJob(prjctIdx)
const pageMonitor = useListJobPageMonitor(prjctIdx, 'LIST_ASSIGN', enabled, {
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 surveyArray = useMemo(() => projectInfoQuery.data?.surveys ?? [], [projectInfoQuery.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) => {
setAssignType(Number(value) as ListHeaderAssignType)
setSelectedAssignId(undefined)
}
// "배정됨"/"배정되지 않음"은 실제 대상 선택과 동시에 선택될 수 없다: 새로 클릭된 쪽만 남긴다.
const handleAssignFilterChange = (next: string[]) => {
const addedSentinel = next.find((value) => isAssignFilterSentinel(value) && !assignFilterIds.includes(value))
if (addedSentinel) {
setAssignFilterIds([addedSentinel])
return
}
setAssignFilterIds(next.filter((value) => !isAssignFilterSentinel(value)))
}
const assignFilterItems = useMemo(
() => [
{ id: ASSIGNED_SENTINEL, name: '배정됨' },
{ id: UNASSIGNED_SENTINEL, name: '배정되지 않음' },
...assignTargetRows,
],
[assignTargetRows],
)
const externalAssignFilter = useMemo(() => {
if (assignFilterIds[0] === ASSIGNED_SENTINEL) {
return { type: effectiveAssignType, values: [] as string[], condition: 'assigned' as const }
}
if (assignFilterIds[0] === UNASSIGNED_SENTINEL) {
return { type: effectiveAssignType, values: [] as string[], condition: 'unassigned' as const }
}
return { type: effectiveAssignType, values: assignFilterIds }
}, [effectiveAssignType, assignFilterIds])
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 () => {
if (assignGate.submitBlocked || assignMutation.isPending) return
if (!selectedAssignId) {
alert('배정할 대상을 선택해주세요.')
return
}
if (hasNoAppliedFilter() && !confirm('적용된 필터가 없습니다. 전체 리스트를 대상으로 진행 하시겠습니까?')) {
return
}
await assignMutation.mutateAsync({
jobType: 'LIST_ASSIGN',
path: `mutations/assign/${encodeURIComponent(selectedAssignId)}`,
body: {
assignType: effectiveAssignType,
transferResve: effectiveAssignType === ListHeaderAssignConst.OUTSOURCE? false : transferResve,
listFilter: currentListFilter,
},
})
}
const handleResetAssign = async () => {
if (assignGate.submitBlocked || assignMutation.isPending) return
if (hasNoAppliedFilter() && !confirm('적용된 필터가 없습니다. 전체 리스트를 대상으로 진행 하시겠습니까?')) {
return
}
if (!confirm('정말 배정을 초기화 하시겠습니까?')) return
await assignMutation.mutateAsync({
jobType: 'LIST_ASSIGN',
path: 'mutations/assign-reset',
body: {
assignType: effectiveAssignType,
listFilter: currentListFilter,
},
})
}
if (!mounted || !selectedProject) return <LoadingOverlayAdapter force />
return (
<ListJobPageQueryContext.Provider value="LIST_ASSIGN">
<div className="flex gap-4 text-sm">
<div className="w-72 shrink-0 space-y-2">
<Tabs value={String(effectiveAssignType)} onValueChange={handleTabChange}>
<TabsList className={`grid w-full ${assignTabTypes.length === 2 ? 'grid-cols-2' : assignTabTypes.length === 1 ? 'grid-cols-1' : 'grid-cols-3'}`}>
{assignTabTypes.map((type) => (
<TabsTrigger key={type} value={String(type)}>
{LIST_HEADER_TYPE_LABEL[type]}
</TabsTrigger>
))}
</TabsList>
</Tabs>
<AssignTargetList
prjctIdx={prjctIdx}
enabled={enabled}
assignType={effectiveAssignType}
userRole={userRole}
selectedId={selectedAssignId}
onSelect={setSelectedAssignId}
/>
</div>
<div className="min-w-0 flex-1 space-y-2">
<ListJobGatePanel gate={assignGate} />
<ListJobRefreshNotice monitor={pageMonitor} />
<ListSearchTable
dataRevision={dataRevision}
prjctIdx={prjctIdx}
enabled={enabled}
userRole={userRole}
userId={auth?.user?.userId ?? ''}
userCmpn={auth?.user?.userCmpn ?? ''}
resultCodes={resultCodeArray}
surveys={surveyArray}
listHeaders={listHeaders}
fieldInterviewEnabled={selectedProject.ff !== false}
selectMode="none"
onCurrentFilterChange={setCurrentListFilter}
onFilterSummaryChange={setFilterSummary}
excludeFilterHeaderTypes={[effectiveAssignType]}
externalAssignFilter={externalAssignFilter}
filterActions={
<KriMultiSelect
items={assignFilterItems}
value={assignFilterIds}
onChange={handleAssignFilterChange}
getValue={(item) => item.id}
getLabel={(item) => item.name}
placeholder={`${LIST_HEADER_TYPE_LABEL[effectiveAssignType]} 필터`}
widthClassName="w-56"
heightClassName="h-9"
/>
}
rightActions={
<>
{effectiveAssignType === ListHeaderAssignConst.CONTACT_INTERVIEWER && (
<label className="flex items-center gap-2 text-base cursor-pointer">
<Checkbox
checked={transferResve}
onCheckedChange={(checked) => setTransferResve(checked === true)}
/>
예약 이관
</label>
)}
<Button type="button" onClick={handleAssign} disabled={assignMutation.isPending || assignGate.submitBlocked}>
배정
</Button>
<Button type="button" variant="outline" onClick={handleResetAssign} disabled={assignMutation.isPending || assignGate.submitBlocked}>
배정 초기화
</Button>
</>
}
/>
</div>
</div>
</ListJobPageQueryContext.Provider>
)
}
export default ListAssignPage

View File

@@ -0,0 +1,473 @@
'use client'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Checkbox } from '@/components/ui/checkbox'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
import { ProjectInfo } from "@/types/project";
import { PROJECT_SEARCH_COUNT } from "@/const/projectConst";
import { useDebouncedValue, useMounted } from "@kri/common/hooks";
import { UserInfo } from "@/types/user";
import { useSelectedProject } from "@/hooks/useSelectedProject";
import { KriSelect, KriSelectItem } from "@/components/common/KriSelect";
import { useAuth } from "@/hooks/useAuth";
import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from "@/const/userConst";
import {
useFieldworkUsersQuery,
useRoleListQuery,
} from "@/query/user";
import { useCmpnListQuery } from "@/query/cmpn";
import {
useAssignedCmpnIdsQuery,
useAssignedFieldworkIdsQuery,
useSaveAssignedFieldworkMutation,
useProjectTopQuery,
} from "@/query/project";
import { isExternalManager, isFieldWorkUser } from "@/utils/userRole";
const ProjectAssignPage = () => {
const mounted = useMounted();
const { auth } = useAuth();
const { selectedProject } = useSelectedProject();
const prjctIdx = selectedProject?.prjctIdx ?? 0;
const enabled = mounted && prjctIdx > 0;
// 외주사 계정은 자기 회사 배정만 봐야 하므로 회사 select 자체를 조작하지 못하게 막는다.
const isExternalUser = isExternalManager(auth.user?.userRole);
const companyQuery = useCmpnListQuery();
const fwUsersQuery = useFieldworkUsersQuery(enabled);
const assignedCmpnIdsQuery = useAssignedCmpnIdsQuery(prjctIdx, enabled);
const assignedIdsQuery = useAssignedFieldworkIdsQuery(prjctIdx, enabled);
const saveAssignMutation = useSaveAssignedFieldworkMutation(prjctIdx);
const roleQuery = useRoleListQuery();
const [searchKeyword, setSearchKeyword] = useState("");
const debouncedKeyword = useDebouncedValue(searchKeyword, 500);
const projectTopQuery = useProjectTopQuery(PROJECT_SEARCH_COUNT, debouncedKeyword, mounted);
const projectArray = projectTopQuery.data ?? [];
const companyArray = useMemo(() => {
const companies = companyQuery.data ?? [];
const assignedCmpnIds = new Set(assignedCmpnIdsQuery.data ?? []);
return companies.filter((company) => company.ownCmpn || assignedCmpnIds.has(company.cmpnId));
}, [assignedCmpnIdsQuery.data, companyQuery.data]);
const roleArray: KriSelectItem[] = useMemo(() => {
const roles = roleQuery.data ?? [];
return roles
.filter(r => isFieldWorkUser(r.roleCd))
.filter(r => selectedProject?.ff !== false || r.roleCd !== FIELD_INTERVIEWER_ROLE)
.map(r => ({ value: String(r.roleCd), label: r.roleNm }));
}, [roleQuery.data, selectedProject?.ff]);
const [companyFilter, setCompanyFilter] = useState<string>('');
const [roleFilter, setRoleFilter] = useState<KriSelectItem | undefined>(undefined);
const fwUserArray = fwUsersQuery.data ?? [];
const [originAssign, setOriginAssign] = useState<UserInfo[]>([]);
const [assignUserArray, setAssignUserArray] = useState<UserInfo[]>([]);
const [dirty, setDirty] = useState(false);
// 선택/검색(좌/우)
const [selectedAssignUser, setSelectedAssignUser] = useState<string[]>([]);
const [searchAssign, setSearchAssign] = useState('');
const debouncedAssign = useDebouncedValue(searchAssign, 500);
const [selectedAbleUser, setSelectedAbleUser] = useState<string[]>([]);
const [searchAble, setSearchAble] = useState('');
const debouncedAble = useDebouncedValue(searchAble, 500);
const resetSelect = useCallback(() => {
setSelectedAssignUser([]);
setSelectedAbleUser([]);
setSearchAssign('');
setSearchAble('');
}, []);
const resetSelectAndAssign = useCallback(() => {
resetSelect();
setAssignUserArray(structuredClone(originAssign));
setDirty(false);
}, [originAssign, resetSelect]);
const [sourceProject, setSourceProject] = useState<ProjectInfo | undefined>(undefined);
const handleSelectProject = (info: ProjectInfo | null) => {
setSourceProject(info ?? undefined);
resetSelect();
};
const sourcePrjctIdx = sourceProject?.prjctIdx ?? 0;
const sourceAssignedIdsQuery = useAssignedFieldworkIdsQuery(
sourcePrjctIdx,
mounted && sourcePrjctIdx > 0
);
const ableUserArray: UserInfo[] = useMemo(() => {
if (sourcePrjctIdx > 0) {
const ids = sourceAssignedIdsQuery.data ?? [];
return fwUserArray.filter(u => ids.includes(u.userId));
}
return structuredClone(fwUserArray);
}, [fwUserArray, sourcePrjctIdx, sourceAssignedIdsQuery.data]);
const handleSelectAllLeft = (checked: boolean) => {
setSelectedAssignUser(checked ? assignView.map(u => u.userId) : []);
};
const handleSelectAllRight = (checked: boolean) => {
setSelectedAbleUser(checked ? ableView.map(u => u.userId) : []);
};
const handleToggleUnassign = (id: string) => {
setSelectedAssignUser(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
};
const handleToggleAssign = (id: string) => {
setSelectedAbleUser(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
};
const handleCompanyChange = (v: string) => {
resetSelectAndAssign();
setCompanyFilter(v);
};
const handleRoleChange = (item: KriSelectItem) => {
resetSelectAndAssign();
setRoleFilter(item);
};
const {
assignView,
ableView,
} = useMemo(() => {
const roleVal = roleFilter?.value;
const cmpnVal = companyFilter;
const passBase = (u: UserInfo) =>
(!roleVal || String(u.userRole) === roleVal) &&
(!cmpnVal || u.userCmpn === cmpnVal);
const kwFilter = (u: UserInfo, k: string) =>
u.userId.includes(k) || u.userName.includes(k);
// LEFT
const _assignBase = assignUserArray.filter(passBase);
const kAssign = debouncedAssign.trim();
const _assignView = kAssign ? _assignBase.filter((u) => kwFilter(u, kAssign)) : _assignBase;
// RIGHT (exclude already assigned)
const assignedSet = new Set(assignUserArray.map((u) => u.userId));
const _ableBase0 = ableUserArray.filter(passBase).filter((u) => !assignedSet.has(u.userId));
const kAble = debouncedAble.trim();
const _ableView = kAble ? _ableBase0.filter((u) => kwFilter(u, kAble)) : _ableBase0;
return {
assignView: _assignView,
ableView: _ableView,
};
}, [
assignUserArray,
ableUserArray,
roleFilter?.value,
companyFilter,
debouncedAssign,
debouncedAble,
]);
const assignInfoString = useMemo(() => {
const cmpnAssign = companyFilter ? originAssign.filter(u => u.userCmpn === companyFilter) : originAssign;
return roleArray.map(role => {
const cnt = cmpnAssign.filter(u => String(u.userRole) === role.value).length;
return `${role.label} : ${cnt}`;
}).join(' / ');
}, [roleArray, originAssign, companyFilter]);
const handleAssign = () => {
const toAssign = ableView.filter(u => selectedAbleUser.includes(u.userId));
if (toAssign.length === 0) return;
setAssignUserArray(prev => [...prev, ...toAssign]);
setSelectedAbleUser([]);
setDirty(true);
};
const handleRemove = () => {
if (selectedAssignUser.length === 0) return;
setAssignUserArray(prev => prev.filter(u => !selectedAssignUser.includes(u.userId)));
setSelectedAssignUser([]);
setDirty(true);
};
const handleSave = async () => {
if (!selectedProject) {
alert("옳지 않은 요청입니다.");
return;
}
await saveAssignMutation.mutateAsync(assignUserArray.map(u => u.userId));
setOriginAssign(structuredClone(assignUserArray));
setDirty(false);
alert("저장되었습니다.");
};
// 로그인 계정의 소속 회사를 기본 선택하되, 매치되는 게 없으면 자사(ownCmpn) 중 가장 상단 1개로 대체한다.
useEffect(() => {
// 이미 유효한 값이 선택돼 있으면(사용자가 직접 고른 값 포함) 그대로 둔다.
if (companyFilter && companyArray.some((company) => company.cmpnId === companyFilter)) {
return;
}
const cmpn = auth.user?.userCmpn ?? "";
if (cmpn && companyArray.some((company) => company.cmpnId === cmpn)) {
setCompanyFilter(cmpn);
return;
}
const ownCmpn = companyArray.find((company) => company.ownCmpn);
setCompanyFilter(ownCmpn?.cmpnId ?? "");
}, [auth.user?.userCmpn, companyArray, companyFilter]);
useEffect(() => {
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));
setRoleFilter(contactRole ?? roleArray[0]);
}, [roleArray, roleFilter]);
// prjctIdx 바뀌면: 편집 상태 초기화(서버 데이터 다시 주입 받을 준비)
useEffect(() => {
if (!enabled) return;
setDirty(false);
resetSelect();
setOriginAssign([]);
setAssignUserArray([]);
}, [enabled, prjctIdx, resetSelect]);
// 서버 배정 ids + fwUserArray 준비되면 "초기 1회" 주입
useEffect(() => {
if (!enabled) return;
if (dirty) return;
const ids = assignedIdsQuery.data;
if (!ids) return;
// fwUserArray가 아직 비어있을 수 있으니 둘 다 준비된 상태에서만
if (!fwUserArray || fwUserArray.length === 0) return;
const assignUserInfoArray = fwUserArray.filter(u => ids.includes(u.userId));
setAssignUserArray(assignUserInfoArray);
setOriginAssign(structuredClone(assignUserInfoArray));
resetSelect();
}, [enabled, dirty, assignedIdsQuery.data, fwUserArray, resetSelect]);
if (!mounted || !selectedProject) return null;
return (
<div className="bg-gray-50 p-1">
<div className="max-w-7xl mx-auto">
<div className="mb-6 rounded-lg border border-gray-200 bg-white p-2 shadow-sm">
<div className="flex flex-col gap-3 sm:flex-row sm:items-end">
<div className="w-full sm:w-auto flex items-center gap-3">
<div className="w-14 text-lg font-medium text-gray-700 whitespace-nowrap text-right">회사</div>
<KriSelect
items={companyArray}
value={companyFilter}
onChange={handleCompanyChange}
getValue={(item) => item.cmpnId}
getLabel={(item) => item.cmpnAlias || item.cmpnId}
placeholder="회사 선택"
className="w-56 h-9"
useAll={false}
disabled={isExternalUser}
/>
</div>
<div className="w-full sm:w-auto flex items-center gap-3">
<div className="w-14 text-lg font-medium text-gray-700 whitespace-nowrap text-right">대상</div>
<KriSelect
items={roleArray}
value={roleFilter?.value || ""}
onChangeOption={handleRoleChange}
placeholder="대상 선택"
className="w-56 h-9"
useAll={false}
getValue={(x) => x.value}
getLabel={(x) => x.label}
/>
</div>
</div>
</div>
<div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] gap-6 mb-6">
<div className="min-w-0">
<div className="p-2 bg-primary text-white rounded-lg text-lg mb-2 h-13 flex items-center">
<span className="truncate w-full">{assignInfoString}</span>
</div>
<div className="border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
<div className="bg-gray-50 p-2 border-b border-gray-200">
<Input
placeholder="면접원 ID Or 면접원 이름"
value={searchAssign}
onChange={(e) => setSearchAssign(e.target.value)}
className="bg-white border-gray-300"
/>
</div>
<div className="h-[550px] overflow-y-auto">
<table className="w-full">
<thead className="bg-primary text-white sticky top-0">
<tr>
<th className="p-2 text-left w-12">
<Checkbox
checked={selectedAssignUser.length === assignView.length && assignView.length > 0}
onCheckedChange={handleSelectAllLeft}
className="border-white"
/>
</th>
<th className="p-2 text-left text-base font-medium">
배정된 {roleFilter?.label} ( {assignView.length}명 )
</th>
</tr>
</thead>
<tbody>
{assignView.map((userInfo) => (
<tr
key={userInfo.userId}
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
selectedAssignUser.includes(userInfo.userId) ? 'bg-blue-50' : ''
}`}
onClick={() => handleToggleUnassign(userInfo.userId)}
>
<td className="p-2">
<Checkbox
onClick={(e) => e.stopPropagation()}
checked={selectedAssignUser.includes(userInfo.userId)}
onCheckedChange={() => handleToggleUnassign(userInfo.userId)}
/>
</td>
<td className="p-2 text-base">
{userInfo.userName} ({userInfo.userId})
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
<div className="flex flex-col justify-center gap-4">
<Button
onClick={handleAssign}
disabled={selectedAbleUser.length === 0}
className="w-36 h-12 flex items-center justify-center text-base disabled:bg-gray-300"
>
<ChevronLeft className="w-5 h-5" />
<span className="ml-2">배정 {selectedAbleUser.length}명</span>
</Button>
<Button
onClick={handleRemove}
disabled={selectedAssignUser.length === 0}
className="bg-red-600 hover:bg-red-700 w-36 h-12 flex items-center justify-center text-base disabled:bg-gray-300"
>
<ChevronRight className="w-5 h-5" />
<span className="ml-2">제외 {selectedAssignUser.length}명</span>
</Button>
</div>
<div className="min-w-0">
<div className="p-2 bg-primary text-white rounded-lg text-lg mb-2 h-13">
<KriSingleSelect<ProjectInfo>
items={projectArray}
value={String(sourceProject?.prjctIdx ?? "")}
onChange={() => {}}
withInfo
onItemChange={handleSelectProject}
searchMode="inputOnly"
onSearchValueChange={setSearchKeyword}
placeholder="프로젝트 검색..."
widthClassName="w-full"
heightClassName="h-9"
preventDeselect
hideOptionCheck
useClear
getLabel={(item) => `${item.prjctCd}_${item.prjctName}`}
getValue={(item) => String(item.prjctIdx)}
/>
</div>
<div className="border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
<div className="bg-gray-50 p-2 border-b border-gray-200">
<Input
placeholder="면접원 ID Or 면접원 이름"
value={searchAble}
onChange={(e) => setSearchAble(e.target.value)}
className="bg-white border-gray-300"
/>
</div>
<div className="h-[550px] overflow-y-auto">
<table className="w-full">
<thead className="bg-primary text-white sticky top-0">
<tr>
<th className="p-2 text-left w-12">
<Checkbox
checked={selectedAbleUser.length === ableView.length && ableView.length > 0}
onCheckedChange={handleSelectAllRight}
className="border-white"
/>
</th>
<th className="p-2 text-left text-base font-medium">
배정 가능 {roleFilter?.label} ({ableView.length}명 )
</th>
</tr>
</thead>
<tbody>
{ableView.map((user) => (
<tr
key={user.userId}
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
selectedAbleUser.includes(user.userId) ? 'bg-blue-50' : ''
}`}
onClick={() => handleToggleAssign(user.userId)}
>
<td className="p-2">
<Checkbox
onClick={(e) => e.stopPropagation()}
checked={selectedAbleUser.includes(user.userId)}
onCheckedChange={() => handleToggleAssign(user.userId)}
/>
</td>
<td className="p-2 text-base">
{user.userName} ({user.userId})
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
</div>
<div className="flex justify-center">
<Button
onClick={handleSave}
className=" px-12 h-9 text-base font-medium"
>
저장
</Button>
</div>
</div>
</div>
)
}
export default ProjectAssignPage;

View File

@@ -1,14 +1,15 @@
import MainLayout from "@/components/layout/MainLayout"; import { AuthSessionGate } from "@/components/app-shell/AuthSessionGate";
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";
import {CookieKeys} from "@/store/cookie/cookie-keys"; import {CookieKeys} from "@/store/cookie/cookie-keys";
import {FONT_SIZE} from "@/const/commonConst"; import {FONT_SIZE} from "@/const/commonConst";
function parseFontSize(raw: string | undefined | null) { function parseFontSize(raw: string | undefined | null) {
if (!raw) return FONT_SIZE.MIN; if (!raw) return FONT_SIZE.DEFAULT;
const parsed = parseInt(raw, 10); const parsed = parseInt(raw, 10);
if (Number.isNaN(parsed)) return FONT_SIZE.MIN; if (Number.isNaN(parsed)) return FONT_SIZE.DEFAULT;
return Math.min( return Math.min(
FONT_SIZE.MAX, FONT_SIZE.MAX,
@@ -23,7 +24,7 @@ export default async function MainLayoutWrapper({
}) { }) {
const cookieStore = await cookies(); const cookieStore = await cookies();
const fontSize = cookieStore.get(CookieKeys.FontSize); const fontSize = cookieStore.get(CookieKeys.FontSize);
const accessToken = cookieStore.get("access_token")?.value; const accessToken = cookieStore.get(CookieKeys.AuthToken)?.value;
const initialFontSize = parseFontSize(fontSize?.value); const initialFontSize = parseFontSize(fontSize?.value);
if (!accessToken) { if (!accessToken) {
@@ -31,8 +32,8 @@ export default async function MainLayoutWrapper({
} }
return ( return (
<MainLayout initialFontSize={initialFontSize}> <AuthSessionGate><AppMainLayout initialFontSize={initialFontSize}>
{children} {children}
</MainLayout> </AppMainLayout></AuthSessionGate>
); );
} }

View File

@@ -1,8 +0,0 @@
const ListAssignPage = () => {
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
//redirect(url);
return (<div>This is List Assign Page</div>)
}
export default ListAssignPage;

View File

@@ -1,8 +1,257 @@
const ListContactPage = () => { 'use client'
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
//redirect(url);
return (<div>This is List Contact Page</div>) import { Suspense, useEffect, useMemo, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { ArrowLeft, RefreshCw } from "lucide-react";
import { useMounted } from "@kri/common/hooks";
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/hooks/useAuth";
import { useSelectedProject } from "@/hooks/useSelectedProject";
import { useListDetailQuery, useListHeaderQuery, useUpdateListMutation } from "@/query/list";
import { useProjectInfoQuery, useResultCodesQuery } from "@/query/project";
import ListContactInfoPanel, { buildInitialValues } from "@/components/list-contact/ListContactInfoPanel";
import ListContactEventPanel from "@/components/list-contact/ListContactEventPanel";
import ListUpdateHistoryPanel from "@/components/list-contact/ListUpdateHistoryPanel";
import { createEmptyListFilter, type listHeader } from "@/types/list";
import type { ResultCode } from "@/types/project";
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 router = useRouter();
const searchParams = useSearchParams();
const sid = searchParams.get("sid") ?? "";
const mounted = useMounted();
const { auth } = useAuth();
const { selectedProject } = useSelectedProject();
const prjctIdx = selectedProject?.prjctIdx ?? 0;
const prjctCd = selectedProject?.prjctCd ?? "";
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? "";
const userId = auth?.user?.userId ?? "";
const userRole = auth?.user?.userRole ?? 0;
const ctiCallPhase = useCtiCallPhase();
const shouldBlockNavigation = CTI_CALL_PHASE.includes(ctiCallPhase);
const hasObservedCall = useRef(false);
const queriesEnabled = 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 resultCodesQuery = useResultCodesQuery(prjctIdx, queriesEnabled);
const updateListMutation = useUpdateListMutation(prjctIdx);
const listHeaders = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data]);
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data]);
const [isEditing, setIsEditing] = useState(false);
const initialFormValues = useMemo(
() => buildInitialValues(listHeaders, listDetailQuery.data),
[listHeaders, listDetailQuery.data],
);
const [formValues, setFormValues] = useState<Record<number, string>>(initialFormValues);
useEffect(() => {
setFormValues(initialFormValues);
}, [initialFormValues]);
useEffect(() => {
if (sid) return;
alert("sid가 없으면 진행할 수 없습니다.");
router.push("/list/manage");
}, [sid, router]);
const handleGoToListManage = () => {
if(shouldBlockNavigation){
alert("통화 중에는 이동할 수 없습니다.");
return;
}
router.push("/list/manage");
};
const handleFieldChange = (listHderId: number, value: string) => {
setFormValues((prev) => ({ ...prev, [listHderId]: value }));
};
const handleCancelEdit = () => {
setFormValues(initialFormValues);
setIsEditing(false);
};
const handleToggleEdit = async () => {
if (!isEditing) {
setIsEditing(true);
return;
}
try {
await updateListMutation.mutateAsync({
updateContents: Object.fromEntries(Object.entries(formValues)),
listFilter: { ...createEmptyListFilter(), sidSet: [sid] },
});
alert("저장되었습니다.");
setIsEditing(false);
listDetailQuery.refetch();
} catch (e) {
console.error(e);
}
};
if (!sid) return null;
if (!mounted || !selectedProject) return <LoadingOverlayAdapter force />;
return (
<div className="space-y-6 text-sm">
{/* 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="목록으로">
<ArrowLeft className="h-4 w-4" />
</Button>
<h1 className="text-xl font-bold tracking-tight max-lg:whitespace-nowrap lg:text-2xl">컨택 진행</h1>
<span className="text-xl font-bold tracking-tight max-lg:min-w-0 max-lg:truncate lg:text-2xl">SID: {sid}</span>
<Button
type="button"
variant="ghost"
size="icon-sm"
disabled={listDetailQuery.isFetching}
aria-label="리스트 정보 새로고침"
title="리스트 정보 새로고침"
onClick={() => listDetailQuery.refetch()}
>
<RefreshCw className={`h-4 w-4 ${listDetailQuery.isFetching ? "animate-spin" : ""}`} />
</Button>
<div className="ml-auto flex items-center gap-2">
{isEditing ? (
<Button type="button" variant="outline" disabled={updateListMutation.isPending} onClick={handleCancelEdit}>
취소
</Button>
) : null}
<Button type="button" disabled={updateListMutation.isPending} onClick={handleToggleEdit}>
{isEditing ? '저장' : '수정'}
</Button>
</div>
</div>
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<div className="h-[80vh] space-y-4 overflow-y-auto">
<ListContactInfoPanel
prjctIdx={prjctIdx}
sid={sid}
itrntPrjctCd={itrntPrjctCd}
userRole={userRole}
isEditing={isEditing}
listHeaders={listHeaders}
detail={listDetailQuery.data}
surveys={projectInfoQuery.data?.surveys ?? []}
callerTelNum={projectInfoQuery.data?.callerTelNum}
resultCodes={resultCodeArray}
formValues={formValues}
onFieldChange={handleFieldChange}
onSaved={() => listDetailQuery.refetch()}
/>
{isManager(userRole) ? (
<ListUpdateHistoryPanel prjctIdx={prjctIdx} sid={sid} listHeaders={listHeaders} />
) : null}
</div>
<ListContactEventPanel
prjctIdx={prjctIdx}
sid={sid}
prjctCd={prjctCd}
userId={userId}
userRole={userRole}
resultCodes={resultCodeArray}
useFF={projectInfoQuery.data?.ff ?? false}
useContactSenario={projectInfoQuery.data?.useContactSenario ?? false}
contactSenario={projectInfoQuery.data?.contactSenario}
listHeaders={listHeaders}
detail={listDetailQuery.data}
/>
</div>
</div>
)
} }
export default ListContactPage; const ListContactPage = () => (
<Suspense fallback={null}>
<ListContactPageContent />
</Suspense>
);
export default ListContactPage;

View File

@@ -1,25 +1,426 @@
"use client"; 'use client'
import {useFontSizeValue} from "@/hooks/useFontSize"; import { useEffect, useMemo, useRef, useState } from 'react'
import {useMounted} from "@/hooks/useMounted"; import { useAtom } from 'jotai'
import {LoadingOverlay} from "@/components/common/LoadingOverlay"; import { toast } from 'sonner'
import BodyTitle from "@/components/layout/BodyTitle"; import { listJobOpenRequestAtom } from '@/store/jotai/list-job'
import {useSelectedProject} from "@/hooks/useSelectedProject"; import type { PaginationState } from '@tanstack/react-table'
import ProjectTitle from "@/components/layout/ProjectTitle"; import { useQueryClient } from '@tanstack/react-query'
import { useRouter } from 'next/navigation'
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
import { useMounted } from "@kri/common/hooks";
import { useAuth } from '@/hooks/useAuth'
import { useDialog } from '@/hooks/useDialog'
import { useSelectedProject } from '@/hooks/useSelectedProject'
import { useStorage } from '@/hooks/useStorage'
import { StorageKeys } from '@/store/storage/storage-keys'
import { ListManageActions, type ListManageActionKey } from '@/components/list/ListManageActions'
import { ListSearchTable } from '@/components/list/ListSearchTable'
import {
useDownloadListExcelTemplateMutation,
useDownloadUploadHistoryFileMutation,
useListHeaderQuery,
useListUploadHistoryQuery,
useUpdateListHeaderMutation,
} 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 type { ListTableRow } from '@/components/table-column/ListTableColumn'
import {
createEmptyListFilter,
ListEventHistoryBase,
ListEventHistoryOrder,
type LastListVisit,
type ListDownloadMode,
type ListDownloadPayload,
type ListFilter,
type ListFilterTarget,
type listHeader,
type ListSearchUiState,
type ListResetRequest,
type ListResetSelection,
type ListUploadRequest,
} from '@/types/list'
import { type ResultCode, ResultCodeType } from '@/types/project'
import ListResetDialog from '@/components/dialog/ListResetDialog'
import ListUploadDialog from '@/components/dialog/ListUploadDialog'
import ListHeaderManageDialog from '@/components/dialog/ListHeaderManageDialog'
import ListDownloadDialog from '@/components/dialog/ListDownloadDialog'
import MessageSendDialog, { type MessageSendMode } from '@/components/dialog/MessageSendDialog'
import MessageHistoryDialog from '@/components/dialog/MessageHistoryDialog'
import { downloadFile } from '@kri/common/browser'
import {CONTACT_INTERVIEWER_ROLE} from "@/const/userConst";
import { isInternalManager, isManager } from "@/utils/userRole";
import { applyListAccessFilter } from "@/utils/listAccess";
const toDateTimeRange = (from?: string, to?: string) => {
if (!from || !to) return undefined
return {
startDate: `${from}T00:00:00`,
endDate: `${to}T23:59:59`,
}
}
const downloadArrayBuffer = (buffer: ArrayBuffer, filename: string, type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') => {
downloadFile(new Blob([buffer], { type }), filename)
}
const createEmptySearchUiState = (): ListSearchUiState => ({
searchText: '',
searchContactResult: [],
searchContactDateRange: { from: '', to: '' },
searchInterviewResult: [],
surveyResultSelections: {},
filterRows: [],
sorting: [],
})
const ListManagePage = () => { const ListManagePage = () => {
const fontSize = useFontSizeValue(); const router = useRouter()
const mounted = useMounted(); const queryClient = useQueryClient()
const mounted = useMounted()
const { auth } = useAuth()
const { showDialog } = useDialog()
const { selectedProject, isSelectedProjectHydrated } = useSelectedProject()
const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom)
if (!mounted) return <LoadingOverlay force />; const [downloadMode, setDownloadMode] = useState<ListDownloadMode>('list')
const [messageSendMode, setMessageSendMode] = useState<MessageSendMode>('email')
const [selectedRows, setSelectedRows] = useState<ListTableRow[]>([])
const [currentListFilter, setCurrentListFilter] = useState<ListFilter>(() => createEmptyListFilter())
const [filterSummary, setFilterSummary] = useState<string[]>([])
const [searchUiState, setSearchUiState] = useState<ListSearchUiState>(createEmptySearchUiState)
const [listRefreshKey, setListRefreshKey] = useState(0)
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 25 })
const [restoredVisit, setRestoredVisit] = useState<LastListVisit | null>(null)
const [restoreResolved, setRestoreResolved] = useState(false)
const previousPrjctIdxRef = useRef(0)
const { get: getLastListVisit, set: setLastListVisit, remove: removeLastListVisit } = useStorage(
StorageKeys.LastListVisit,
)
const userRole = auth?.user?.userRole ?? CONTACT_INTERVIEWER_ROLE
const userId = auth?.user?.userId ?? ''
const userCmpn = auth?.user?.userCmpn ?? ''
const prjctName = selectedProject?.prjctName ?? ''
const prjctIdx = selectedProject?.prjctIdx ?? 0
const enabled = mounted && prjctIdx > 0
const canManageList = isManager(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 projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled)
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
const uploadHistoryQuery = useListUploadHistoryQuery(prjctIdx, enabled)
const downloadListExcelTemplateMutation = useDownloadListExcelTemplateMutation()
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 downloadUploadHistoryFileMutation = useDownloadUploadHistoryFileMutation(prjctIdx)
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
const surveyArray = useMemo(() => projectInfoQuery.data?.surveys ?? [], [projectInfoQuery.data])
const headerManageRows = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data])
// 컨택 진행 화면에서 돌아왔을 때 1회만 복원하고, 재방문 시 다시 나타나지 않도록 즉시 지운다.
// ListSearchTable이 첫 마운트될 때 초기 페이지네이션 값이 확정돼 있어야 하므로(useState는 이후 prop
// 변경을 반영하지 않음), selectedProject 하이드레이션이 끝나기 전에는 ListSearchTable을 아예 그리지 않는다.
useEffect(() => {
if (!mounted || !isSelectedProjectHydrated || restoreResolved) return
const stored = getLastListVisit()
if (stored) {
setRestoredVisit(stored)
removeLastListVisit()
}
setRestoreResolved(true)
}, [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 selectedSidSet = useMemo(
() =>
selectedRows
.map((row) => row.sid)
.filter((sid): sid is string | number => typeof sid === 'string' || typeof sid === 'number')
.map(String),
[selectedRows],
)
const refreshList = () => {
setListRefreshKey((prev) => prev + 1)
}
const buildTargetFilter = (target: ListFilterTarget) => {
if (target === 'all') {
return applyListAccessFilter(createEmptyListFilter(), { userRole, userId, userCmpn })
}
if (target === 'selected') {
return applyListAccessFilter(
{
...createEmptyListFilter(),
sidSet: selectedSidSet,
},
{ userRole, userId, userCmpn },
)
}
return applyListAccessFilter(currentListFilter, { userRole, userId, userCmpn })
}
const handleStartContact = (row: ListTableRow) => {
const sid = String(row.sid ?? '')
setLastListVisit({
prjctIdx,
sid,
pageIndex: pagination.pageIndex,
pageSize: pagination.pageSize,
...searchUiState,
})
router.push(`/list/contact?sid=${encodeURIComponent(sid)}`)
}
const openDownloadDialog = (mode: ListDownloadMode) => {
setDownloadMode(mode)
showDialog('listDownloadDialog')
}
const openMessageDialog = (mode: MessageSendMode) => {
setMessageSendMode(mode)
showDialog('messageSendDialog')
}
const handleResetConfirm = async (payload: { target: ListFilterTarget; selection: ListResetSelection }) => {
const body: ListResetRequest = {
...payload.selection,
listFilter: buildTargetFilter(payload.target),
}
await submitJob.mutateAsync({ jobType: 'LIST_RESET', path: 'reset', body })
}
const handleUploadConfirm = async (file: File, request: ListUploadRequest) => {
await submitJob.mutateAsync({ jobType: 'LIST_UPLOAD', path: 'upload', file, body: request })
}
const handleDownloadTemplate = async () => {
if (!prjctIdx) {
alert("프로젝트를 선택해주세요.")
return
}
const buffer = await downloadListExcelTemplateMutation.mutateAsync(prjctIdx)
downloadArrayBuffer(buffer, `${prjctName} list-upload-template.xlsx`)
}
const handleHeaderManageConfirm = async (rows: listHeader[]) => {
await updateListHeaderMutation.mutateAsync(rows)
}
const handleDownloadConfirm = async (payload: ListDownloadPayload) => {
const listFilter = buildTargetFilter(payload.target)
const jobType = LIST_DOWNLOAD_JOB_TYPE[payload.mode]
if (payload.mode === 'list') {
await submitJob.mutateAsync({ jobType, path: `downloads/list?includeResult=${payload.includeResult}`, body: listFilter })
return
}
if (payload.mode === 'list-change-history') {
await submitJob.mutateAsync({ jobType, path: 'downloads/update-history', body: listFilter })
return
}
if (payload.mode === 'upload-file') {
await submitJob.mutateAsync({ jobType, path: 'downloads/item-files', body: listFilter })
return
}
await submitJob.mutateAsync({ jobType, path: `downloads/event-history?includeResult=${payload.includeResult}`, body: {
listFilter,
resultCodeTypes: [ResultCodeType.CONTACT, ResultCodeType.INTERVIEW, ResultCodeType.SURVEY],
searchBase: payload.contactHistoryType === 'latest' ? ListEventHistoryBase.LATEST : ListEventHistoryBase.ALL,
historyOrder: payload.historyOrder ?? ListEventHistoryOrder.DESC,
dateRange: toDateTimeRange(payload.contactHistoryDateFrom, payload.contactHistoryDateTo),
} })
}
if (!mounted || !restoreResolved) return <LoadingOverlayAdapter force />
return ( return (
<div className="space-y-6 content-text-sm"> <ListJobPageQueryContext.Provider value="LIST_RESET">
<div> <div className="space-y-6 text-sm">
This is Manage List Page <span>{fontSize}</span> <ListJobGatePanel gate={pageGate} showCurrentJob={false} />
</div> <ListJobRefreshNotice monitor={pageMonitor} clearsSelection={selectedRows.length > 0} />
</div> {canManageList && (
); <ListManageActions
}; showAdminActions={isInternal}
runningActions={runningActions}
disabledActions={disabledActions}
headerManageDisabled={pageGate.submitBlocked}
onReset={() => showDialog('listResetDialog')}
onHeaderManage={() => { if (!pageGate.submitBlocked) showDialog('listHeaderManageDialog') }}
onUpload={() => showDialog('listUploadDialog')}
onDownload={openDownloadDialog}
onMessageSend={openMessageDialog}
onMessageHistory={() => showDialog('messageHistoryDialog')}
/>
)}
export default ListManagePage; <ListSearchTable
key={prjctIdx}
prjctIdx={prjctIdx}
enabled={enabled}
userRole={userRole}
userId={userId}
userCmpn={userCmpn}
resultCodes={resultCodeArray}
surveys={surveyArray}
listHeaders={headerManageRows}
fieldInterviewEnabled={selectedProject?.ff !== false}
enableBatchEdit={canManageList}
batchEditDisabled={isActionDisabled('LIST_UPDATE')}
dataRevision={dataRevision}
selectMode={canManageList ? 'multi' : 'click-event'}
refreshKey={listRefreshKey}
onCurrentFilterChange={setCurrentListFilter}
onFilterSummaryChange={setFilterSummary}
onSelectedRowsChange={setSelectedRows}
onRowClick={!canManageList ? handleStartContact : undefined}
onRowDoubleClick={canManageList ? handleStartContact : undefined}
initialPagination={
restoredForThisProject
? { pageIndex: restoredForThisProject.pageIndex, pageSize: restoredForThisProject.pageSize }
: undefined
}
onPaginationChange={setPagination}
initialSearchState={restoredForThisProject}
onSearchStateChange={setSearchUiState}
focusRowId={restoredForThisProject?.sid}
collapsibleFiltersOnMobile
/>
{isInternal && (
<>
<ListResetDialog
key={prjctIdx}
prjctIdx={prjctIdx}
surveys={projectInfoQuery.data?.surveys}
selectedSids={selectedSidSet}
filterSummary={filterSummary}
onConfirm={handleResetConfirm}
/>
<ListUploadDialog
prjctIdx={prjctIdx}
onUpload={handleUploadConfirm}
onDownloadTemplate={handleDownloadTemplate}
uploadHistory={uploadHistoryQuery.data ?? []}
onDownloadHistory={async (item) => {
const buffer = await downloadUploadHistoryFileMutation.mutateAsync(item.listUploadLogId)
downloadArrayBuffer(buffer, item.fileName)
}}
headerRows={headerManageRows}
/>
<ListHeaderManageDialog prjctIdx={prjctIdx} rows={headerManageRows} onConfirm={handleHeaderManageConfirm} saveDisabled={pageGate.submitBlocked} />
</>
)}
{canManageList && (
<>
<ListDownloadDialog
prjctIdx={prjctIdx}
mode={downloadMode}
selectedSids={selectedSidSet}
filterSummary={filterSummary}
onDownload={handleDownloadConfirm}
/>
<MessageSendDialog
mode={messageSendMode}
listHeaders={headerManageRows}
currentFilter={currentListFilter}
selectedRows={selectedRows}
filterSummary={filterSummary}
onSent={refreshList}
/>
<MessageHistoryDialog />
</>
)}
</div>
</ListJobPageQueryContext.Provider>
)
}
export default ListManagePage

View File

@@ -0,0 +1,99 @@
'use client'
import { useState } from "react";
import { Button } from "@/components/ui/button";
import AppPageTitle from "@/components/app-shell/AppPageTitle";
import { DataTable } from "@/components/data-table/DataTable";
import { getCmpnColumns } from "@/components/table-column/CmpnTableColumn";
import CmpnUpsertDialog from "@/components/dialog/CmpnUpsertDialog";
import { useDialog } from "@/hooks/useDialog";
import { useMounted } from "@kri/common/hooks";
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
import type { CmpnInfoSaveRequest } from "@/types/cmpn";
import {
useCheckCmpnIdDuplicateMutation,
useCmpnDetailQuery,
useCmpnListQuery,
useUpsertCmpnMutation,
} from "@/query/cmpn";
const CmpnManagePage = () => {
const { showDialog } = useDialog();
const mounted = useMounted();
const cmpnListQuery = useCmpnListQuery();
const checkDupMutation = useCheckCmpnIdDuplicateMutation();
const upsertMutation = useUpsertCmpnMutation();
const [editCmpnId, setEditCmpnId] = useState<string | null>(null);
const [dialogMode, setDialogMode] = useState<'create' | 'edit'>('create');
const cmpnDetailQuery = useCmpnDetailQuery(editCmpnId ?? "", !!editCmpnId);
const cmpnList = cmpnListQuery.data ?? [];
const handleCreateClick = () => {
setDialogMode("create");
setEditCmpnId(null);
showDialog("cmpnUpsertDialog");
};
const handleEdit = (cmpnId: string) => {
setDialogMode("edit");
setEditCmpnId(cmpnId);
showDialog("cmpnUpsertDialog");
};
const handleCheckDuplicate = (cmpnId: string) => {
return checkDupMutation.mutateAsync(cmpnId);
};
const handleSubmit = async (data: CmpnInfoSaveRequest): Promise<void> => {
await upsertMutation.mutateAsync({ mode: dialogMode, data });
if (dialogMode === "create") {
alert("등록되었습니다.");
} else {
alert("수정되었습니다.");
}
};
const columns = getCmpnColumns({
onEdit: handleEdit,
});
if (!mounted) return <LoadingOverlayAdapter force />;
return (
<div className="space-y-6 text-sm">
<AppPageTitle titleText={"회사 관리"} />
<div className="flex justify-end">
<Button onClick={handleCreateClick}>
회사 등록
</Button>
</div>
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
<DataTable
columns={columns}
data={cmpnList}
isClient={true}
selectMode="single"
defaultPageSize={10}
pageSizeOptions={[10, 20, 30, 50]}
getRowId={(row) => row.cmpnId}
maxBodyHeight="71vh"
/>
</div>
<CmpnUpsertDialog
mode={dialogMode}
initialData={dialogMode === "edit" ? (cmpnDetailQuery.data ?? undefined) : undefined}
onSubmit={handleSubmit}
onCheckDuplicate={handleCheckDuplicate}
/>
</div>
);
}
export default CmpnManagePage;

View File

@@ -1,199 +1,184 @@
'use client' 'use client'
import {useEffect, useState} from "react"; import { useMemo, useState } from "react";
import {Button} from "@/components/ui/button"; import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input"; import {Input} from "@/components/ui/input";
import BodyTitle from "@/components/layout/BodyTitle"; import AppPageTitle from "@/components/app-shell/AppPageTitle";
import { DataTable } from "@/components/data-table/DataTable"; import { DataTable } from "@/components/data-table/DataTable";
import { getUserColumns } from "../../../../../components/table-column/UserTableColumn"; import { getUserColumns } from "@/components/table-column/UserTableColumn";
import _ from "lodash";
import UserUpsertDialog from "@/components/dialog/UserUpsertDialog"; import UserUpsertDialog from "@/components/dialog/UserUpsertDialog";
import {UserInfo, UserInfoSaveRequest, UserUploadResponse} from "@/types/user"; import {UserInfoSaveRequest} from "@/types/user";
import UserUploadDialog from "@/components/dialog/UserUploadDialog"; import UserUploadDialog from "@/components/dialog/UserUploadDialog";
import {useDialog} from "@/hooks/useDialog"; import {useDialog} from "@/hooks/useDialog";
import {downloadBase64File, downloadFile} from "@/lib/utils"; import { downloadBase64File, downloadFile, XLSX_MIME_TYPE } from "@kri/common/browser";
import {nextApi} from "@/lib/http-client";
import {useLoading} from "@/hooks/useLoading";
import {RoleInfo} from "@/types/role";
import {DataVerification} from "@/types/common";
import {apiError} from "@/lib/http-util";
import {KriMultiSelect} from "@/components/common/KriAutoComplete"; import {KriMultiSelect} from "@/components/common/KriAutoComplete";
import {useAuth} from "@/hooks/useAuth"; import {useAuth} from "@/hooks/useAuth";
import {MultiSelectOption} from "@/components/ui/multi-select"; import type { MultiSelectOption } from "@/components/common/KriAutoComplete";
import {useMounted} from "@/hooks/useMounted"; import { useMounted } from "@kri/common/hooks";
import {LoadingOverlay} from "@/components/common/LoadingOverlay"; import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
import {DEFAULT_COMPANY_NAME, EXTERNAL_USER_ROLE} from "@/const/userConst"; import {Upload} from "lucide-react";
import {
useRoleListQuery,
useUsersQuery,
useUserDetailQuery,
useCheckUserIdDuplicateMutation,
useUpsertUserMutation,
useDeleteUserMutation,
useUploadUsersExcelMutation,
useDownloadUserExcelTemplateMutation,
} from "@/query/user";
import { useCmpnListQuery } from "@/query/cmpn";
import { isInternalManager } from "@/utils/userRole";
const UserManagePage = () => { const UserManagePage = () => {
const { showDialog } = useDialog(); const { showDialog } = useDialog();
const mounted = useMounted(); const mounted = useMounted();
const { withLoadingAsync } = useLoading();
const { auth } = useAuth();
const [userList, setUserList] = useState<UserInfo[]>([]); const { auth } = useAuth();
const [viewList, setViewList] = useState<UserInfo[]>([]); const roleQuery = useRoleListQuery();
const [selectedUserArray, setSelectedUserArray] = useState<UserInfo[]>([]); const cmpnQuery = useCmpnListQuery();
const [userCmpnArray, setUserCmpnArray] = useState<string[]>([]); const usersQuery = useUsersQuery();
const [userRoleArray, setUserRoleArray] = useState<MultiSelectOption[]>([]);
const checkDupMutation = useCheckUserIdDuplicateMutation();
const upsertMutation = useUpsertUserMutation();
const deleteMutation = useDeleteUserMutation();
const uploadMutation = useUploadUsersExcelMutation();
const downloadTemplateMutation = useDownloadUserExcelTemplateMutation();
const [editUserId, setEditUserId] = useState<string | null>(null);
const userDetailQuery = useUserDetailQuery(editUserId ?? "", !!editUserId);
const userRoleArray: MultiSelectOption[] = useMemo(() => {
const roles = roleQuery.data ?? [];
return roles.map((r) => ({ value: String(r.roleCd), label: r.roleNm }));
}, [roleQuery.data]);
const userCmpnArray = cmpnQuery.data ?? [];
const userList = usersQuery.data ?? [];
const [searchText, setSearchText] = useState(''); const [searchText, setSearchText] = useState('');
const [searchCmpn, setSearchCmpn] = useState<string[]>([]); const [searchCmpn, setSearchCmpn] = useState<string[]>([]);
const [searchRole, setSearchRole] = useState<string[]>([]); const [searchRole, setSearchRole] = useState<string[]>([]);
const [dialogMode, setDialogMode] = useState<'create' | 'edit'>('create') const [dialogMode, setDialogMode] = useState<'create' | 'edit'>('create')
const [editData, setEditData] = useState<Partial<UserInfoSaveRequest>>();
const setUserData = async () => { const viewList = useMemo(() => {
const roleList = await nextApi.get<RoleInfo[]>("/role"); let temp = userList;
setUserRoleArray(
roleList.map((role) => ({
value: String(role.roleCd),
label: role.roleNm,
}))
);
const cmpnList = await nextApi.get<string[]>("/user/cmpn"); const keyword = searchText.trim();
setUserCmpnArray(cmpnList); if (keyword) {
const kw = keyword.toLowerCase();
temp = temp.filter((row) =>
[row.userId, row.userName].some((v) => (v ?? "").toLowerCase().includes(kw))
);
}
const userData = await nextApi.get<UserInfo[]>("/user"); if (searchCmpn.length > 0) {
setUserList(userData); temp = temp.filter((row) => searchCmpn.includes(row.userCmpn));
} }
if (searchRole.length > 0) {
temp = temp.filter((row) => searchRole.includes(String(row.userRole)));
}
return temp;
}, [userList, searchText, searchCmpn, searchRole]);
// 등록 버튼 클릭 // 등록 버튼 클릭
const handleCreateClick = () => { const handleCreateClick = () => {
setDialogMode('create'); setDialogMode("create");
setEditData(undefined); setEditUserId(null);
showDialog('userUpsertDialog'); showDialog("userUpsertDialog");
} };
// 중복 체크 // 중복 체크
const handleCheckDuplicate = async (userId: string): Promise<DataVerification> => { const handleCheckDuplicate = (userId: string) => {
return nextApi.get<DataVerification>("/user/check-user-id", { return checkDupMutation.mutateAsync(userId);
query: { userId }, };
});
}
const handleSubmit = async (data: UserInfoSaveRequest): Promise<void> => { const handleSubmit = async (data: UserInfoSaveRequest): Promise<void> => {
if (dialogMode === 'create') { await upsertMutation.mutateAsync({ mode: dialogMode, data });
await nextApi.put<void>("/user", data);
if (dialogMode === "create") {
alert("등록되었습니다.");
} else { } else {
await nextApi.patch<void>("/user", data); alert("수정되었습니다.");
} }
await setUserData(); };
}
const handleEdit = (userId: string) => { const handleEdit = (userId: string) => {
setDialogMode('edit'); setDialogMode("edit");
nextApi.get<UserInfo>(`/user/${userId}`) setEditUserId(userId);
.then((data) => { showDialog("userUpsertDialog");
setEditData(data); };
showDialog('userUpsertDialog');
})
.catch((e) => {
const err = apiError(e);
console.error(err.status, err.code, err.message);
});
// 수정 로직 또는 모달 열기
}
const handleDelete = (userId: string) => { const handleDelete = async (userId: string) => {
// 삭제 확인 후 데이터 삭제 if (!confirm("정말 삭제하시겠습니까?")) return;
if (confirm('정말 삭제하시겠습니까?')) {
//삭제 await deleteMutation.mutateAsync(userId);
nextApi.del<void>(`/user/${encodeURIComponent(userId)}`) alert("삭제되었습니다.");
.then(async () => { };
alert("삭제 됐습니다.");
await setUserData();
})
.catch((e) => {
const err = apiError(e);
console.error(err.status, err.code, err.message);
});
}
}
const uploadFile = async (file: File) => { const uploadFile = async (file: File) => {
const formData = new FormData(); const res = await uploadMutation.mutateAsync(file);
formData.append("file", file); // key 이름은 백엔드 @RequestPart("file") 와 동일해야 함
const res = await nextApi.postForm<UserUploadResponse>("/user/excel", formData);
if (res.hasErrorFile && res.errorFileBase64) { if (res.hasErrorFile && res.errorFileBase64) {
downloadBase64File(res.errorFileBase64, res.errorFileName ?? "error.xlsx"); alert("업로드 중 오류가 발생하여 오류 파일을 다운로드합니다.");
downloadBase64File(res.errorFileBase64, res.errorFileName ?? "error.xlsx", XLSX_MIME_TYPE);
} }
else{ else{
await setUserData(); alert(`${res.successCount}개의 계정이 생성되었습니다.`);
} }
} };
const downloadTemplate = async () => { const downloadTemplate = async () => {
const buffer = await nextApi.post<ArrayBuffer>( const buffer = await downloadTemplateMutation.mutateAsync();
"/user/excel-template",
undefined,
{ expectBinary: true }
);
if (buffer.byteLength > 0) { if (buffer.byteLength > 0) {
const blob = new Blob([buffer], { const blob = new Blob([buffer], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
}); });
downloadFile(blob, "사용자 업로드 양식.xlsx"); downloadFile(blob, "사용자_업로드_양식.xlsx");
alert("다운로드 됐습니다."); alert("다운로드되었습니다.");
} else { } else {
console.log("빈 파일입니다."); console.log("빈 파일입니다.");
} }
} };
const columns = getUserColumns( const columns = getUserColumns(
{ {
onEdit: handleEdit, onEdit: handleEdit,
onDelete: handleDelete onDelete: handleDelete
}, },
userRoleArray userRoleArray,
userCmpnArray
); );
useEffect(() => {
withLoadingAsync(setUserData);
}, []);
useEffect(() => {
let tempData = _.cloneDeep(userList);
const keyword = searchText.trim();
if (keyword){
tempData = tempData.filter((row) =>
[row.userId, row.userName].some((v) => v.toLowerCase().includes(keyword.toLowerCase()))
);
}
if(searchCmpn.length > 0){
tempData = tempData.filter((row) => searchCmpn.includes(row.userCmpn));
}
if(searchRole.length > 0){
tempData = tempData.filter((row) => searchRole.includes(String(row.userRole)));
}
setViewList(tempData);
}, [searchText, searchCmpn, searchRole, userList]);
const isInternal = const isInternal =
mounted && mounted &&
auth.user?.userRole != null && isInternalManager(auth.user?.userRole)
auth.user.userRole < EXTERNAL_USER_ROLE
const userCmpn = auth.user?.userCmpn ?? DEFAULT_COMPANY_NAME; // 로그인 계정의 소속 회사를 기본 선택하되, 회사 목록에 매치되는 게 없으면 자사(ownCmpn) 중 가장 상단 1개로 대체한다.
const userCmpn = useMemo(() => {
const currentCmpnId = auth.user?.userCmpn;
const matched = userCmpnArray.find((c) => c.cmpnId === currentCmpnId);
if (matched) return matched.cmpnId;
if (!mounted) return <LoadingOverlay force />; const fallback = userCmpnArray.find((c) => c.ownCmpn);
return fallback?.cmpnId ?? currentCmpnId ?? '';
}, [auth.user?.userCmpn, userCmpnArray]);
if (!mounted) return <LoadingOverlayAdapter force />;
return ( return (
<div className="space-y-6 content-text-sm"> <div className="space-y-6 text-sm">
<BodyTitle titleText={"계정 관리"}/> <AppPageTitle titleText={"사용자 관리"}/>
<div className="flex gap-2 items-center"> <div className="flex gap-2 items-center">
<div className="flex flex-1 items-center gap-2"> <div className="flex flex-1 items-center gap-2">
<Input <Input
placeholder="면접원 ID Or 면접원 이름" placeholder="사용자 ID 또는 사용자 이름"
className="w-70 h-9 bg-white" className="w-70 h-9 bg-white"
value={searchText} value={searchText}
onChange={(e) => setSearchText(e.target.value)} onChange={(e) => setSearchText(e.target.value)}
@@ -204,6 +189,8 @@ const UserManagePage = () => {
items={userCmpnArray} items={userCmpnArray}
value={searchCmpn} value={searchCmpn}
onChange={setSearchCmpn} onChange={setSearchCmpn}
getValue={(item) => item.cmpnId}
getLabel={(item) => item.cmpnAlias || item.cmpnId}
placeholder="소속 회사" placeholder="소속 회사"
widthClassName="w-70" widthClassName="w-70"
heightClassName="h-9" heightClassName="h-9"
@@ -221,16 +208,16 @@ const UserManagePage = () => {
/> />
</div> </div>
<Button <Button
className="content-text-lg"
onClick={handleCreateClick} onClick={handleCreateClick}
> >
면접원 등록 사용자 등록
</Button> </Button>
<Button <Button
onClick={() => showDialog('userUploadDialog')} onClick={() => showDialog('userUploadDialog')}
className="gap-2 bg-green-600 hover:bg-green-700 content-text-lg" className="gap-2 bg-excel"
> >
면접원 일괄 등록 <Upload className="w-4 h-4" />
사용자 일괄 등록
</Button> </Button>
</div> </div>
@@ -239,17 +226,17 @@ const UserManagePage = () => {
columns={columns} columns={columns}
data={viewList} data={viewList}
isClient={true} isClient={true}
selectMode='single' selectMode='none'
onRowSelectionChange={setSelectedUserArray}
defaultPageSize={10} defaultPageSize={10}
pageSizeOptions={[10, 20, 30, 50]} pageSizeOptions={[10, 20, 30, 50]}
getRowId={(row) => row.userId} // row.id = userId getRowId={(row) => row.userId} // row.id = userId
maxBodyHeight="71vh"
/> />
</div> </div>
<UserUpsertDialog <UserUpsertDialog
mode={dialogMode} mode={dialogMode}
initialData={editData} initialData={dialogMode === "edit" ? (userDetailQuery.data ?? undefined) : undefined}
isInternal={isInternal} isInternal={isInternal}
userCmpn={userCmpn} userCmpn={userCmpn}
userCmpnArray={userCmpnArray} userCmpnArray={userCmpnArray}
@@ -266,4 +253,4 @@ const UserManagePage = () => {
); );
} }
export default UserManagePage; export default UserManagePage;

View File

@@ -1,13 +1,14 @@
import {MessageType, TemplateEmail} from "@/types/messageTemplate"; 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 BodyTitle from "@/components/layout/BodyTitle"; 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: '',
@@ -16,10 +17,10 @@ const EmailTemplatePage = () => {
} }
return ( return (
<div className="space-y-6 content-text-sm"> <div className="space-y-6 text-sm">
<MessageTemplate pageTitle={"이메일 템플릿 관리"} defaultTemplate={defaultEmailTemplate}/> <MessageTemplate pageTitle={"이메일 템플릿 관리"} defaultTemplate={defaultEmailTemplate}/>
</div> </div>
) )
} }
export default EmailTemplatePage; export default EmailTemplatePage;

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,15 +1,16 @@
'use client' 'use client'
import {MessageType, TemplateSms} from "@/types/messageTemplate"; 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 BodyTitle from "@/components/layout/BodyTitle"; 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: '',
@@ -18,10 +19,10 @@ const SmsTemplatePage = () => {
} }
return ( return (
<div className="space-y-6 content-text-sm"> <div className="space-y-6 text-sm">
<MessageTemplate pageTitle="문자 템플릿 관리" defaultTemplate={defaultSmsTemplate}/> <MessageTemplate pageTitle="문자 템플릿 관리" defaultTemplate={defaultSmsTemplate}/>
</div> </div>
) )
} }
export default SmsTemplatePage; export default SmsTemplatePage;

View File

@@ -1,61 +1,114 @@
'use client' 'use client'
import {useEffect, useRef, useState} from "react"; import {useMemo, useState} from "react";
import BodyTitle from "@/components/layout/BodyTitle"; import {ChevronDown} from "lucide-react";
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 {
ProjectCreateRequest, ProjectCreateRequest,
ProjectInfo, ProjectInfo,
ProjectListQuery, ProjectListQuery,
ProjectListRequest, ProjectOwnerResponse,
ProjectStatus ProjectStatus
} from "@/types/project"; } from "@/types/project";
import {Input} from "@/components/ui/input"; import {Input} from "@/components/ui/input";
import {KriMultiSelect} from "@/components/common/KriAutoComplete"; import {KriMultiSelect} from "@/components/common/KriAutoComplete";
import {MultiSelectOption} from "@/components/ui/multi-select"; import type { MultiSelectOption } from "@/components/common/KriAutoComplete";
import {PaginationState, SortingState} from "@tanstack/react-table"; import {PaginationState, SortingState} from "@tanstack/react-table";
import {PageRequest, PageResponse} from "@/types/common";
import ProjectCreateDialog from "@/components/dialog/ProjectCreateDialog"; import ProjectCreateDialog from "@/components/dialog/ProjectCreateDialog";
import {useDialog} from "@/hooks/useDialog"; import {useDialog} from "@/hooks/useDialog";
import {useLoading} from "@/hooks/useLoading";
import {useAuth} from "@/hooks/useAuth"; import {useAuth} from "@/hooks/useAuth";
import {nextApi} from "@/lib/http-client";
import {useSelectedProject} from "@/hooks/useSelectedProject"; import {useSelectedProject} from "@/hooks/useSelectedProject";
import {SelectedProject} from "@/store/jotai/project"; import {SelectedProject} from "@/store/jotai/project";
import {useMounted} from "@/hooks/useMounted"; import { useMounted } from "@kri/common/hooks";
import {LoadingOverlay} from "@/components/common/LoadingOverlay"; import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
import {FW_USER_ROLE} from "@/const/userConst";
import {useItrntUserList} from "@/hooks/useItrntUserList"; import {useItrntUserList} from "@/hooks/useItrntUserList";
import {useRouter} from "next/navigation";
import type {Route} from "next";
import {useCreateProjectMutation, useProjectListQuery, useProjectOwnerListQuery} from "@/query/project";
import {useGroupCodeListQuery} from "@/query/intranet";
import {PROJECT_STATUS_LABEL} from "@/const/projectConst";
import {isInternalManager, isManager} from "@/utils/userRole";
const MainPage = () => { const MainPage = () => {
const router = useRouter();
const mounted = useMounted();
const { users, isLoading } = useItrntUserList(); const { users, isLoading } = useItrntUserList();
const { showDialog } = useDialog(); const { showDialog } = useDialog();
const { withLoadingAsync } = useLoading();
const mounted = useMounted();
const { auth } = useAuth(); const { auth } = useAuth();
const { clearSelectedProject, setSelectedProject } = useSelectedProject(); const { setSelectedProject } = useSelectedProject();
const [statusArray, setStatusArray] = useState<MultiSelectOption[]>([]);
const [deptArray, setDeptArray] = useState<string[]>([]);
const [fwArray, setFwArray] = useState<string[]>([]);
const [searchText, setSearchText] = useState('');
const [searchStatus, setSearchStatus] = useState<string[]>([]);
const [searchDept, setSearchDept] = useState<string[]>([]);
const [searchFw, setSearchFw] = useState<string[]>([]);
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 10 }); const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 10 });
const [sorting, setSorting] = useState<SortingState>([]); const [sorting, setSorting] = useState<SortingState>([]);
const [query, setQuery] = useState<ProjectListQuery>(); const [query, setQuery] = useState<ProjectListQuery>();
const [viewList, setViewList] = useState<ProjectInfo[]>([]); const statusArray: MultiSelectOption[] = useMemo(() => {
const [pageCount, setPageCount] = useState(0); return (Object.values(ProjectStatus).filter((v) => typeof v === "number") as number[])
const [totalCount, setTotalCount] = useState(0); .sort((a, b) => a - b)
.map((v) => ({
value: String(v),
label: PROJECT_STATUS_LABEL[v as ProjectStatus],
}));
}, []);
const enabled = mounted && !isLoading; // intranet user list 준비된 뒤에만 호출
const ownerQuery = useProjectOwnerListQuery(enabled);
const groupCodeListQuery = useGroupCodeListQuery(enabled);
const groupCodeLabelMap = useMemo(() => {
return new Map((groupCodeListQuery.data ?? []).map((g) => [g.groupCode, g.groupCodeLabel]));
}, [groupCodeListQuery.data]);
const deptArray = useMemo(() => {
const ownerDeptList = ownerQuery.data?.ownerDeptList ?? [];
return ownerDeptList.map((code) => ({
value: code,
label: groupCodeLabelMap.get(code) ?? code,
}));
}, [ownerQuery.data?.ownerDeptList, groupCodeLabelMap]);
const fwArray = useMemo(() => {
const ownerFwIDList = ownerQuery.data?.ownerFwList ?? [];
return ownerFwIDList.map((fwID) => ({
value: fwID,
label: users.find(u => u.userId === fwID)?.userNm ?? "",
}));
}, [ownerQuery.data?.ownerFwList]);
const sort = sorting?.[0] ?? { id: "prjctIdx", desc: true as const };
const listQuery = useProjectListQuery({
query,
pageIndex: pagination.pageIndex,
pageSize: pagination.pageSize,
sortBy: sort.id,
sortDir: sort.desc ? "desc" : "asc",
enabled,
});
const viewList = listQuery.data?.content ?? [];
const totalCount = listQuery.data?.totalElements ?? 0;
const pageCount = listQuery.data?.totalPages ?? 0;
const createMutation = useCreateProjectMutation?.();
const [searchText, setSearchText] = useState('');
const [searchStatus, setSearchStatus] = useState<string[]>([]);
const [searchDept, setSearchDept] = 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);
const userId = auth.user?.userId ?? ""; const userId = auth.user?.userId ?? "";
const userRole = auth.user?.userRole ?? FW_USER_ROLE; const userRole = auth.user?.userRole;
const isInternal = isInternalManager(userRole);
const handleSearchClick = () => { const handleSearchClick = () => {
const searchStatusCode:ProjectStatus[] = searchStatus const searchStatusCode:ProjectStatus[] = searchStatus
@@ -76,8 +129,7 @@ const MainPage = () => {
showDialog('projectCreateDialog'); showDialog('projectCreateDialog');
} }
const handleSubmit = async (data:ProjectCreateRequest): Promise<void> => { const navigateWithProject = (projectInfo: ProjectInfo, path: Route) => {
const projectInfo = await nextApi.put<ProjectInfo>("/project", data);
setSelectedProject({ setSelectedProject({
prjctIdx: projectInfo.prjctIdx, prjctIdx: projectInfo.prjctIdx,
prjctCd: projectInfo.prjctCd, prjctCd: projectInfo.prjctCd,
@@ -85,141 +137,120 @@ const MainPage = () => {
itrntPrjctCd: projectInfo.itrntPrjctCd, itrntPrjctCd: projectInfo.itrntPrjctCd,
ownerDept: projectInfo.ownerDept, ownerDept: projectInfo.ownerDept,
ownerFw: projectInfo.ownerFw, ownerFw: projectInfo.ownerFw,
ff: projectInfo.ff
} as SelectedProject); } as SelectedProject);
window.location.href = `/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,
} as SelectedProject);
window.location.href = `/list/manage`; const handleClick = (projectInfo: ProjectInfo) => navigateWithProject(projectInfo, "/list/manage");
}
// 중복 호출 방지(초기 mount에서 pagination/sorting 콜백이 각각 한번씩 날아오는 케이스 방어) const handleNavigateToInfo = (projectInfo: ProjectInfo) => navigateWithProject(projectInfo, "/project/info");
const lastReqKeyRef = useRef<string>("");
useEffect(() => { const columns = getProjectColumns(users, groupCodeLabelMap, isInternal ? handleNavigateToInfo : undefined);
const reqKey = JSON.stringify({ query, pagination, sorting});
if (lastReqKeyRef.current === reqKey) return;
lastReqKeyRef.current = reqKey;
const sort = sorting?.[0] ?? {id: "prjctIdx", desc: true}; if (!mounted || isLoading) return <LoadingOverlayAdapter force />;
const pageReq: PageRequest = {
pageIndex: pagination.pageIndex,
pageSize: pagination.pageSize,
sortBy: sort.id,
sortDir: sort.desc ? "desc" : "asc"
};
const searchBody: ProjectListRequest = {
prjctText: query?.prjctText || "",
prjctStatusList: query?.prjctStatusList || [],
ownerDeptList: query?.ownerDeptList || [],
ownerFwList: query?.ownerFwList || [],
pageRequest: pageReq,
}
withLoadingAsync(() =>
nextApi.post<PageResponse<ProjectInfo>>("/project/list", searchBody)
.then((r) => {
setViewList(r.content);
setTotalCount(r.totalElements);
setPageCount(r.totalPages);
})
.catch(() => {
setViewList([]);
setTotalCount(0);
setPageCount(0);
})
);
}, [query, pagination, sorting]);
useEffect(() => {
clearSelectedProject();
const options: MultiSelectOption[] = Object.entries(ProjectStatus)
.sort(([a], [b]) => Number(a) - Number(b))
.map(([key, label]) => ({ value: key, label: String(label) }));
setStatusArray(options);
nextApi.get<ProjectOwnerResponse>("/project/owner-list")
.then((res) => {
setDeptArray(res.ownerDeptList);
setFwArray(res.ownerFwList);
});
}, []);
if (!mounted || isLoading) return <LoadingOverlay force />;
return ( return (
<div className="space-y-6 content-text-sm"> <div className="space-y-6 text-sm">
<BodyTitle 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">
<Input <div className="flex items-center gap-2">
placeholder="프로젝트 코드 Or 프로젝트 명" <Input
className="w-120 h-9 bg-white" placeholder="프로젝트 코드 Or 프로젝트 명"
value={searchText} className="h-9 flex-1 bg-white md:w-120 md:flex-none"
onChange={(e) => setSearchText(e.target.value)} value={searchText}
onKeyDown={(e) => { onChange={(e) => setSearchText(e.target.value)}
if (e.key === "Enter") { onKeyDown={(e) => {
handleSearchClick(); if (e.key === "Enter") {
} handleSearchClick();
}} }
/> }}
{ />
userRole < FW_USER_ROLE && <Button
<KriMultiSelect className="md:hidden"
items={statusArray} onClick={handleSearchClick}
value={searchStatus} >
onChange={setSearchStatus} 검색
getValue={(item) => item.value} </Button>
getLabel={(item) => item.label} </div>
placeholder="진행 상태"
widthClassName="w-60"
heightClassName="h-9"
/>
}
<KriMultiSelect
items={deptArray}
value={searchDept}
onChange={setSearchDept}
placeholder="담당 그룹"
widthClassName="w-60"
heightClassName="h-9"
/>
<KriMultiSelect
items={fwArray}
value={searchFw}
onChange={setSearchFw}
placeholder="담당 실사"
widthClassName="w-60"
heightClassName="h-9"
/>
<Button <Button
className="content-text-lg" 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) &&
<KriMultiSelect
items={statusArray}
value={searchStatus}
onChange={setSearchStatus}
getValue={(item) => item.value}
getLabel={(item) => item.label}
placeholder="진행 상태"
widthClassName="w-full md:w-60"
heightClassName="h-9"
/>
}
<KriMultiSelect
items={deptArray}
value={searchDept}
onChange={setSearchDept}
getValue={(item) => item.value}
getLabel={(item) => item.label}
placeholder="담당 그룹"
widthClassName="w-full md:w-60"
heightClassName="h-9"
/>
<KriMultiSelect
items={fwArray}
value={searchFw}
onChange={setSearchFw}
getValue={(item) => item.value}
getLabel={(item) => item.label}
placeholder="담당 실사"
widthClassName="w-full md:w-60"
heightClassName="h-9"
/>
</div>
<Button
className="hidden md:inline-flex"
onClick={handleSearchClick} onClick={handleSearchClick}
> >
검색 검색
</Button> </Button>
</div> </div>
<Button {isInternal && (
className="content-text-lg" <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">
@@ -229,12 +260,14 @@ const MainPage = () => {
isClient={false} isClient={false}
pageCount={pageCount} pageCount={pageCount}
totalCount={totalCount} totalCount={totalCount}
pagination={pagination}
onPaginationChange={setPagination} onPaginationChange={setPagination}
onSortingChange={setSorting} onSortingChange={setSorting}
selectMode='click-event' selectMode='click-event'
onRowClick={handleClick} onRowClick={handleClick}
pageSizeOptions={[10, 20, 30, 50]} pageSizeOptions={[10, 20, 30, 50]}
getRowId={(row) => row.prjctCd} // row.id = userId getRowId={(row) => row.prjctCd} // row.id = userId
maxBodyHeight="71vh"
/> />
</div> </div>
@@ -247,4 +280,4 @@ const MainPage = () => {
) )
} }
export default MainPage; export default MainPage;

View File

@@ -1,8 +1,17 @@
const ContactProgressPage = () => { 'use client'
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
//redirect(url);
return (<div>This is Contact Progress Page</div>) import { ProgressPageContent } from "@/components/progress/ProgressPageContent";
} import { ProgressEventType } from "@/types/progress";
import { ResultCodeType } from "@/types/project";
export default ContactProgressPage; const ContactProgressPage = () => (
<ProgressPageContent
eventTy={ProgressEventType.CONTACT}
resultCdTy={ResultCodeType.CONTACT}
pageTitle="컨택 현황"
domainLabel="컨택"
personLabel="컨택인력"
/>
);
export default ContactProgressPage;

View File

@@ -1,8 +0,0 @@
const FieldworkProgressPage = () => {
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
//redirect(url);
return (<div>This is Fieldwork Progress Page</div>)
}
export default FieldworkProgressPage;

View File

@@ -0,0 +1,17 @@
'use client'
import { ProgressPageContent } from "@/components/progress/ProgressPageContent";
import { ProgressEventType } from "@/types/progress";
import { ResultCodeType } from "@/types/project";
const InterviewProgressPage = () => (
<ProgressPageContent
eventTy={ProgressEventType.INTERVIEW}
resultCdTy={ResultCodeType.INTERVIEW}
pageTitle="면접 현황"
domainLabel="면접"
personLabel="면접원"
/>
);
export default InterviewProgressPage;

View File

@@ -1,8 +1,146 @@
'use client'
import { useMemo, useState } from "react";
import { useMounted } from "@kri/common/hooks";
import AppPageTitle from "@/components/app-shell/AppPageTitle";
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
import KriDateRangePicker from "@/components/common/KriDateRangePicker";
import { useSelectedProject } from "@/hooks/useSelectedProject";
import { useSendResultSummaryQuery } from "@/query/message";
import { clientEnv } from "@/lib/env.client";
import { MessageType } from "@kri/common/noti-hub";
import type { SendResultSummaryResponse } from "@kri/common/noti-hub";
const SEND_TYPE_ORDER = [MessageType.SMS, MessageType.LMS, MessageType.MMS, MessageType.EMAIL, MessageType.KKO] as const;
const SEND_TYPE_LABEL: Record<number, string> = {
[MessageType.SMS]: "단문",
[MessageType.LMS]: "장문",
[MessageType.MMS]: "첨부 문자",
[MessageType.EMAIL]: "메일",
[MessageType.KKO]: "알림톡",
};
type SummaryRow = {
sendTy: number;
price: number;
totalCount: number;
cost: number;
successCount: number;
failCount: number;
standByCount: number;
canceledCount: number;
};
const sum = (list: SendResultSummaryResponse[], field: keyof SendResultSummaryResponse) =>
list.reduce((acc, item) => acc + (item[field] as number | undefined ?? 0), 0);
const buildRows = (data: SendResultSummaryResponse[]): SummaryRow[] =>
SEND_TYPE_ORDER.map((sendTy) => {
const matched = data.filter((item) => item.sendTy === sendTy);
return {
sendTy,
price: matched[0]?.price ?? 0,
totalCount: sum(matched, "totalCount"),
cost: sum(matched, "cost"),
successCount: sum(matched, "successCount"),
failCount: sum(matched, "failCount"),
standByCount: sum(matched, "standByCount"),
canceledCount: sum(matched, "canceledCount"),
};
});
const moneyUnit = (value: number) => `${value.toLocaleString()}원`;
const caseUnit = (value: number) => `${value.toLocaleString()}건`;
const MessageProgressPage = () => { const MessageProgressPage = () => {
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" }); const mounted = useMounted();
//redirect(url); const { selectedProject } = useSelectedProject();
return (<div>This is Message Progress Page</div>) const [dateRange, setDateRange] = useState({ from: "", to: "" });
}
export default MessageProgressPage; const prjctCd = selectedProject?.prjctCd ?? "";
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? "";
const enabled = mounted && !!prjctCd;
const summaryQuery = useSendResultSummaryQuery(
{
reqstSvc: clientEnv.REQUEST_SVC,
itrntPrjctCd,
prjctCd,
sendStartDt: dateRange.from ? `${dateRange.from}T00:00:00` : undefined,
sendEndDt: dateRange.to ? `${dateRange.to}T23:59:59` : undefined,
},
enabled,
);
const rows = useMemo(() => buildRows(summaryQuery.data ?? []), [summaryQuery.data]);
const total = useMemo(
() => ({
totalCount: rows.reduce((acc, row) => acc + row.totalCount, 0),
cost: rows.reduce((acc, row) => acc + row.cost, 0),
successCount: rows.reduce((acc, row) => acc + row.successCount, 0),
failCount: rows.reduce((acc, row) => acc + row.failCount, 0),
standByCount: rows.reduce((acc, row) => acc + row.standByCount, 0),
canceledCount: rows.reduce((acc, row) => acc + row.canceledCount, 0),
}),
[rows],
);
if (!mounted) return <LoadingOverlayAdapter force />;
return (
<div className="space-y-6 text-sm">
<AppPageTitle titleText="발송 현황" />
<KriDateRangePicker value={dateRange} onChange={setDateRange} className="w-80" />
<div className="rounded-md border overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-primary text-primary-foreground">
<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>
<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>
</thead>
<tbody>
{rows.map((row) => (
<tr key={row.sendTy} className="border-b last:border-b-0">
<td className="h-10 px-3 text-center">{SEND_TYPE_LABEL[row.sendTy]}</td>
<td className="h-10 px-3 text-center">{moneyUnit(row.price)}</td>
<td className="h-10 px-3 text-center">{caseUnit(row.totalCount)}</td>
<td className="h-10 px-3 text-center">{moneyUnit(row.cost)}</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.standByCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(row.canceledCount)}</td>
</tr>
))}
<tr className="bg-gray-50 font-semibold">
<td className="h-10 px-3 text-center" colSpan={2}>합계</td>
<td className="h-10 px-3 text-center">{caseUnit(total.totalCount)}</td>
<td className="h-10 px-3 text-center">{moneyUnit(total.cost)}</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.standByCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(total.canceledCount)}</td>
</tr>
</tbody>
</table>
</div>
<p className="text-xs text-muted-foreground">
※ 보낸 내역을 토대로 계산된 값으로 실제 정산 금액과 차이가 발생할 수 있습니다.
</p>
</div>
);
};
export default MessageProgressPage;

View File

@@ -0,0 +1,72 @@
'use client'
import { useMounted } from "@kri/common/hooks";
import AppPageTitle from "@/components/app-shell/AppPageTitle";
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
import { Button } from "@/components/ui/button";
import { useSelectedProject } from "@/hooks/useSelectedProject";
import { useProjectInfoQuery } from "@/query/project";
import { clientEnv } from "@/lib/env.client";
import { SurveyType } from "@/types/project";
import { SURVEY_TYPE_LABEL } from "@/const/projectConst";
const SurveyProgressPage = () => {
const mounted = useMounted();
const { selectedProject } = useSelectedProject();
const prjctIdx = selectedProject?.prjctIdx ?? 0;
const enabled = mounted && prjctIdx > 0;
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled);
const surveys = projectInfoQuery.data?.surveys ?? [];
const isLoading = !mounted || projectInfoQuery.isLoading;
if (isLoading) return <LoadingOverlayAdapter force />;
return (
<div className="space-y-6 text-sm">
<AppPageTitle titleText="설문 현황" />
{surveys.length === 0 ? (
<p className="text-muted-foreground">연결된 설문이 없습니다.</p>
) : (
<div className="max-w-[600px] space-y-2">
{surveys.map((survey) => {
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 (
<div
key={survey.prjctSurveyIdx ?? survey.surveyOrder}
className="flex items-center justify-between rounded-lg border bg-white p-4"
>
<div>
<p className="font-semibold">{survey.surveyName}</p>
<p className="text-xs text-muted-foreground">{SURVEY_TYPE_LABEL[survey.surveyTy]}</p>
</div>
{targetUrl ? (
<Button asChild>
<a href={targetUrl} target="_blank" rel="noopener noreferrer">
바로가기
</a>
</Button>
) : (
<Button type="button" disabled>바로가기</Button>
)}
</div>
);
})}
</div>
)}
</div>
);
};
export default SurveyProgressPage;

View File

@@ -1,498 +0,0 @@
'use client'
import {useCallback, useEffect, useMemo, useState} from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Checkbox } from '@/components/ui/checkbox'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
import {ProjectInfo} from "@/types/project";
import {nextApi} from "@/lib/http-client";
import {PROJECT_SEARCH_COUNT} from "@/const/projectConst";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {useMounted} from "@/hooks/useMounted";
import {UserInfo} from "@/types/user";
import {useSelectedProject} from "@/hooks/useSelectedProject";
import {KriSelect, KriSelectItem} from "@/components/common/KriSelect";
import {useAuth} from "@/hooks/useAuth";
import {RoleInfo} from "@/types/role";
import {CONTACT_USER_ROLE, FW_USER_ROLE} from "@/const/userConst";
import {useLoading} from "@/hooks/useLoading";
import _ from "lodash";
const ProjectAssignPage = () => {
const mounted = useMounted();
const { withLoadingAsync } = useLoading();
const { auth } = useAuth();
const { selectedProject } = useSelectedProject();
const [projectArray, setProjectArray] = useState<ProjectInfo[]>([]);
const [searchKeyword, setSearchKeyword] = useState("");
const debouncedKeyword = useDebouncedValue(searchKeyword, 500);
const [sourceProject, setSourceProject] = useState<ProjectInfo>();
const [companyArray, setCompanyArray] = useState<string[]>([]);
const [companyFilter, setCompanyFilter] = useState<string>('');
const [roleArray, setRoleArray] = useState<KriSelectItem[]>([]);
const [roleFilter, setRoleFilter] = useState<KriSelectItem>();
const [fwUserArray, setFwUserArray] = useState<UserInfo[]>([]);
const [originAssign, setOriginAssign] = useState<UserInfo[]>([]);
const [assignUserArray, setAssignUserArray] = useState<UserInfo[]>([]);
const [selectedAssignUser, setSelectedAssignUser] = useState<string[]>([]);
const [searchAssign, setSearchAssign] = useState('');
const debouncedAssign = useDebouncedValue(searchAssign, 500);
const [assignInfoString, setAssignInfoString] = useState<string>('');
const [ableUserArray, setAbleUserArray] = useState<UserInfo[]>([]);
const [selectedAbleUser, setSelectedAbleUser] = useState<string[]>([]);
const [searchAble, setSearchAble] = useState('');
const debouncedAble = useDebouncedValue(searchAble, 500);
const searchTopProject = async (keyword: string) => {
const res = await nextApi.get<ProjectInfo[]>(
`/project/top/${PROJECT_SEARCH_COUNT}`,
{ query: { keyword } }
);
setProjectArray(res);
};
const handleSelectProject = (info:ProjectInfo|null) => {
if(info === null){
setSourceProject(undefined)
}
else{
setSourceProject(info);
}
}
const handleSelectAllLeft = (checked: boolean) => {
if (checked) {
setSelectedAssignUser(assignUserArray.map(u => u.userId))
} else {
setSelectedAssignUser([])
}
}
const handleSelectAllRight = (checked: boolean) => {
if (checked) {
setSelectedAbleUser(ableUserArray.map(u => u.userId))
} else {
setSelectedAbleUser([])
}
}
const handleToggleUnassign = (id: string) => {
setSelectedAssignUser(prev =>
prev.includes(id)
? prev.filter(x => x !== id)
: [...prev, id]
)
}
const handleToggleAssign = (id: string) => {
setSelectedAbleUser(prev =>
prev.includes(id)
? prev.filter(x => x !== id)
: [...prev, id]
)
}
const appendUserInfo = (
userIdArray:string[],
sourceArray:UserInfo[]
) => {
return sourceArray.filter(user => userIdArray.includes(user.userId));
}
const resetSelect = () => {
setSelectedAssignUser([]);
setSelectedAbleUser([]);
//검색도 초기화
setSearchAssign('');
setSearchAble('');
}
const resetSelectAndAssign = () => {
resetSelect();
setAssignUserArray(_.cloneDeep(originAssign));
};
const handleCompanyChange = (v: string) => {
resetSelectAndAssign();
setCompanyFilter(v);
// 필요하면 데이터도 같이 재조회/재계산 트리거
};
const handleRoleChange = (item: KriSelectItem) => {
resetSelectAndAssign();
setRoleFilter(item);
};
const handleAssign = () => {
const toAssign = ableUserArray.filter(u => selectedAbleUser.includes(u.userId));
setAssignUserArray(prev => [...prev, ...toAssign]);
setSelectedAbleUser([]);
}
const handleRemove = () => {
const toRemove = assignUserArray.filter(u => selectedAssignUser.includes(u.userId));
setAssignUserArray(prev => prev.filter(u => !selectedAssignUser.includes(u.userId)));
setSelectedAssignUser([]);
}
const handleSave = async () => {
if(selectedProject){
await nextApi.put(
`/assign/prjct-fieldwork/${selectedProject.prjctIdx}`,
assignUserArray.map(u => u.userId)
)
setOriginAssign(_.cloneDeep(assignUserArray));
alert("저장되었습니다.");
}
else{
alert("옳지 않은 요청입니다.");
}
}
const baseFiltered = useCallback((users: UserInfo[]) => {
return users.filter(
(u) =>
String(u.userRole) === roleFilter?.value &&
u.userCmpn === companyFilter
);
}, [roleFilter, companyFilter]);
const withKeyword = useCallback((users: UserInfo[], keyword: string) => {
const k = keyword.trim();
if (!k) return users;
return users.filter(
(u) => u.userId.includes(k) || u.userName.includes(k)
);
}, []);
const assignBase = useMemo(
() => baseFiltered(assignUserArray),
[assignUserArray, baseFiltered]
);
const assignView = useMemo(
() => withKeyword(assignBase, debouncedAssign),
[assignBase, debouncedAssign, withKeyword]
);
const assignedIdSet = useMemo(
() => new Set(assignUserArray.map(u => u.userId)),
[assignUserArray]
);
const ableBase = useMemo(
() => baseFiltered(ableUserArray)
.filter((user) => !assignedIdSet.has(user.userId)),
[ableUserArray, baseFiltered, assignedIdSet]
);
const ableView = useMemo(
() => withKeyword(ableBase, debouncedAble)
.filter((user) => !assignedIdSet.has(user.userId)),
[ableBase, debouncedAble, withKeyword, assignedIdSet]
);
useEffect(() => {
if(selectedProject){
const keyword = debouncedKeyword.trim();
searchTopProject(keyword);
}
}, [debouncedKeyword]);
useEffect(() => {
withLoadingAsync(async () => {
nextApi.get<UserInfo[]>("/user/fieldwork")
.then(res => setFwUserArray(res));
nextApi.get<string[]>("/user/cmpn")
.then((res) => setCompanyArray(res));
const roleList = await nextApi.get<RoleInfo[]>("/role")
const roleOptionArray = roleList
.filter(role => role.roleCd >= FW_USER_ROLE)
.map((role) => ({
value: String(role.roleCd),
label: role.roleNm,
}))
setRoleArray(roleOptionArray);
const contactRole = roleOptionArray.find((role) => role.value === CONTACT_USER_ROLE.toString());
if(contactRole){
setRoleFilter(contactRole);
}
})
}, []);
useEffect(() => {
if(auth.user){
setCompanyFilter(auth.user.userCmpn || "")
}
}, [auth.user]);
useEffect(() => {
withLoadingAsync(async () => {
if(selectedProject){
const res = await nextApi.get<string[]>(`/assign/prjct-fieldwork/${selectedProject.prjctIdx}`);
const assignUserInfoArray = appendUserInfo(res, fwUserArray);
setAssignUserArray(assignUserInfoArray);
setOriginAssign(assignUserInfoArray);
}else{
setAssignUserArray([]);
setOriginAssign([]);
}
resetSelect();
});
}, [fwUserArray, selectedProject, roleArray]);
useEffect(() => {
const assignString = roleArray.map((role) => {
const assignCount = originAssign.filter(user => user.userRole.toString() === role.value).length
return `${role.label} : ${assignCount}`;
}).join(' / ');
setAssignInfoString(assignString);
}, [originAssign]);
useEffect(() => {
withLoadingAsync(async () => {
let ableUserList :UserInfo[] = [];
if(sourceProject){
const res = await nextApi.get<string[]>(`/assign/prjct-fieldwork/${sourceProject.prjctIdx}`);
ableUserList = appendUserInfo(res, fwUserArray);
}
else{
ableUserList = _.cloneDeep(fwUserArray);
}
setAbleUserArray(ableUserList);
});
}, [fwUserArray, sourceProject]);
if (!mounted || !selectedProject) return null
return (
<div className="min-h-screen bg-gray-50 p-1">
<div className="max-w-7xl mx-auto">
{/* 공용 필터 바 (회사 / 대상) */}
<div className="mb-6 rounded-lg border border-gray-200 bg-white p-4 shadow-sm">
<div className="flex flex-col gap-3 sm:flex-row sm:items-end">
<div className="w-full sm:w-auto flex items-center gap-3">
<div className="w-14 content-text-lg font-medium text-gray-700 whitespace-nowrap text-right">
회사
</div>
<KriSelect
items={companyArray}
value={companyFilter}
onChange={handleCompanyChange}
placeholder="회사 선택"
className="w-56 h-9"
useAll={false}
/>
</div>
<div className="w-full sm:w-auto flex items-center gap-3">
<div className="w-14 content-text-lg font-medium text-gray-700 whitespace-nowrap text-right">
대상
</div>
<KriSelect
items={roleArray}
value={roleFilter?.value || ""}
onChangeOption={handleRoleChange}
placeholder="대상 선택"
className="w-56 h-9"
useAll={false}
getValue={(x) => x.value}
getLabel={(x) => x.label}
/>
</div>
</div>
</div>
{/* 메인 배정 영역 */}
<div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] gap-6 mb-6">
{/* 왼쪽: 배정된 면접원 */}
<div className="min-w-0">
<div className="p-3 bg-black text-white rounded-lg content-text-lg mb-2 h-15 flex items-center">
<span className="truncate w-full">
{assignInfoString}
</span>
</div>
<div className="border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
<div className="bg-gray-50 p-3 border-b border-gray-200">
<Input
placeholder="면접원 ID Or 면접원 이름"
value={searchAssign}
onChange={(e) => setSearchAssign(e.target.value)}
className="bg-white border-gray-300"
/>
</div>
<div className="h-[600px] overflow-y-auto">
<table className="w-full">
<thead className="bg-black text-white sticky top-0">
<tr>
<th className="p-3 text-left w-12">
<Checkbox
checked={selectedAssignUser.length === assignView.length && assignView.length > 0}
onCheckedChange={handleSelectAllLeft}
className="border-white"
/>
</th>
<th className="p-3 text-left content-text-base font-medium">배정된 {roleFilter?.label} ( {assignBase.length}명 )</th>
</tr>
</thead>
<tbody>
{assignView
.map((userInfo) => (
<tr
key={userInfo.userId}
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
selectedAssignUser.includes(userInfo.userId) ? 'bg-blue-50' : ''
}`}
onClick={() => handleToggleUnassign(userInfo.userId)}
>
<td className="p-3">
<Checkbox
onClick={(e) => e.stopPropagation()}
checked={selectedAssignUser.includes(userInfo.userId)}
onCheckedChange={() => handleToggleUnassign(userInfo.userId)}
/>
</td>
<td className="p-3 content-text-base">
{userInfo.userName} ({userInfo.userId})
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
{/* 가운데: 배정/제외 버튼 */}
<div className="flex flex-col justify-center gap-4">
<Button
onClick={handleAssign}
disabled={selectedAbleUser.length === 0}
className="bg-black hover:bg-gray-800 w-36 h-12 flex items-center justify-center content-text-base disabled:bg-gray-300"
>
<ChevronLeft className="w-5 h-5" />
<span className="ml-2">배정 {selectedAbleUser.length}명</span>
</Button>
<Button
onClick={handleRemove}
disabled={selectedAssignUser.length === 0}
className="bg-red-600 hover:bg-red-700 w-36 h-12 flex items-center justify-center content-text-base disabled:bg-gray-300"
>
<ChevronRight className="w-5 h-5" />
<span className="ml-2">제외 {selectedAssignUser.length}명</span>
</Button>
</div>
{/* 오른쪽: 전체 면접원 풀 */}
<div className="min-w-0">
<div className="p-3 bg-black text-white rounded-lg content-text-lg mb-2 h-15">
<KriSingleSelect
<ProjectInfo>
items={projectArray}
value={String(sourceProject?.prjctIdx ?? "")}
onChange={() => {}}
withInfo
onItemChange={handleSelectProject}
searchMode="inputOnly"
onSearchValueChange={setSearchKeyword}
placeholder="프로젝트 검색..."
widthClassName="w-full"
heightClassName="h-9"
preventDeselect
hideOptionCheck
useClear
getLabel={(item) => `${item.prjctCd}_${item.prjctName}`}
getValue={(item) => String(item.prjctIdx)}
/>
</div>
<div className="border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
<div className="bg-gray-50 p-3 border-b border-gray-200">
<Input
placeholder="면접원 ID Or 면접원 이름"
value={searchAble}
onChange={(e) => setSearchAble(e.target.value)}
className="bg-white border-gray-300"
/>
</div>
<div className="h-[600px] overflow-y-auto">
<table className="w-full">
<thead className="bg-black text-white sticky top-0">
<tr>
<th className="p-3 text-left w-12">
<Checkbox
checked={selectedAbleUser.length === ableView.length && ableView.length > 0}
onCheckedChange={handleSelectAllRight}
className="border-white"
/>
</th>
<th className="p-3 text-left content-text-base font-medium">배정 가능 {roleFilter?.label} ({ableBase.length}명 )</th>
</tr>
</thead>
<tbody>
{ableView
.map((user) => (
<tr
key={user.userId}
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
selectedAbleUser.includes(user.userId) ? 'bg-blue-50' : ''
}`}
onClick={() => handleToggleAssign(user.userId)}
>
<td className="p-3">
<Checkbox
onClick={(e) => e.stopPropagation()}
checked={selectedAbleUser.includes(user.userId)}
onCheckedChange={() => handleToggleAssign(user.userId)}
/>
</td>
<td className="p-3 content-text-base">
{user.userName} ({user.userId})
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
</div>
{/* 하단 저장 버튼 */}
<div className="flex justify-center">
<Button
onClick={handleSave}
className="bg-black hover:bg-gray-800 px-12 h-11 content-text-base font-medium"
>
저장
</Button>
</div>
</div>
</div>
)
}
export default ProjectAssignPage;

File diff suppressed because it is too large Load Diff

View File

@@ -1,103 +1,57 @@
"use client"; "use client";
import Image from "next/image"; import Image from "next/image";
import {Button} from "@/components/ui/button"; import {Button} from "@/components/ui/button";
import {Card, CardContent, CardHeader} from "@/components/ui/card"; import {Card, CardContent, CardHeader} from "@/components/ui/card";
import {Input} from "@/components/ui/input"; import {Input} from "@/components/ui/input";
import React, {useEffect, useRef, useState} from "react"; import React, { useEffect, useRef, useState } from "react";
import { nextApi } from "@/lib/http-client"; import {useRouter} from "next/navigation";
import {useSearchParams} from "next/navigation"; import {apiError} from "@kri/common/http";
import {LoginUser} from "@/types/auth"; import {NONE_HTTP_ERROR} from "@kri/common/http";
import { useAuth } from "@/hooks/useAuth"; import {useLoginMutation} from "@/query/auth";
import { useLoading } from "@/hooks/useLoading"; import {useInternalInfoQuery} from "@/query/internal";
import { useStorage } from "@/hooks/useStorage" import {cn} from "@/lib/utils";
import { StorageKeys } from "@/store/storage/storage-keys";
import {apiError} from "@/lib/http-util";
import {NONE_HTTP_ERROR} from "@/const/commonConst";
const LoginPage = () => { const LoginPage = () => {
const searchParams = useSearchParams(); const router = useRouter();
const { auth, setFromLoginResponse } = useAuth();
const { withLoadingAsync } = useLoading(); const loginMutation = useLoginMutation();
const { get: getSeatNumberStorage, set: setSeatNumberStorage } = useStorage(StorageKeys.SeatNumber); const internalInfoQuery = useInternalInfoQuery(true);
const { get: getLoginTypeStorage, set: setLoginTypeStorage } = useStorage(StorageKeys.LoginType);
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 [seatNum, setSeatNum] = useState<string>(getSeatNumberStorage());
const [loginType, setLoginType] = useState<string>(getLoginTypeStorage()); 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 seatNumberInputRef = useRef<HTMLInputElement | null>(null);
const tryLogin = () => { const tryLogin = async () => {
if(!userId){ if (!userId) return alert("아이디를 입력해주세요.");
alert("아이디를 입력해 주세요"); if (!userPw) return alert("비밀번호를 입력해주세요.");
return;
}
if(!userPw){
alert("PW를 입력해 주세요");
return;
}
if(loginType === "call" && !seatNum){
alert("자리번호를 입력해 주세요");
return;
}
setError(null); setError(null);
const loginRequestBody = {userId, userPw}; try {
const loginRequestOptions = {autoLogoutOnAuthError: false}; await loginMutation.mutateAsync({ userId, userPw });
} catch (e) {
// withLoading 래퍼로 API 호출 전/후 로딩 표시를 자동으로 처리 const err = apiError(e, {
return withLoadingAsync(() => fallbackMessage: "로그인에 실패했습니다.",
nextApi.post<LoginUser>( });
"/login", loginRequestBody, loginRequestOptions if (err.status === 401 || err.status === 403) setError("아이디 또는 비밀번호를 다시 확인해주세요.");
).then(async (data) => { // Jotai 기반 전역 인증 상태 갱신 else if (err.code === NONE_HTTP_ERROR) setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
try { else setError(`로그인에 실패했습니다. (${err.message})`);
setSeatNumberStorage(seatNum); }
setLoginTypeStorage(loginType);
} catch (e) {
// 저장 실패는 치명적이지 않으므로 콘솔 로깅만
console.warn("Failed to persist SeatNumber to secure storage:", e);
}
setFromLoginResponse(data, seatNum);
}).catch((e) => {
const err = apiError(e);
console.error(err.status, err.code, err.message);
if (err.status === 401 || err.status === 403) {
setError("아이디 또는 비밀번호를 다시 확인해주세요.");
}
else if(err.code === NONE_HTTP_ERROR) {
setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
}
else {
setError(`로그인에 실패했습니다. (status: ${err.status})`);
}
})
);
} }
useEffect(() => { useEffect(() => {
if(auth.user){ if (loginMutation.isSuccess) {
window.location.replace("/"); router.replace("/");
} }
}, [auth.user]); }, [loginMutation.isSuccess, router]);
// URL 쿼리 파라미터에서 type 수신
useEffect(() => {
const typeParam = searchParams.get("type") ?? "";
let seatNumTemp = "";
if(typeParam === "call") {
seatNumTemp = getSeatNumberStorage();
}
setSeatNum(seatNumTemp);
setLoginType(typeParam);
}, [searchParams]);
const handleIdKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => { const handleIdKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
if (e.key === "Enter") { if (e.key === "Enter") {
@@ -107,19 +61,6 @@ const LoginPage = () => {
}; };
const handlePwKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => { const handlePwKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
if (e.key === "Enter") {
e.preventDefault();
const seatNumberInput = seatNumberInputRef.current;
if(loginType === "call" && seatNumberInput?.value === ""){
seatNumberInput.focus();
}
else{
tryLogin();
}
}
};
const handleSeatNumberKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
if (e.key === "Enter") { if (e.key === "Enter") {
e.preventDefault(); e.preventDefault();
tryLogin(); tryLogin();
@@ -135,7 +76,7 @@ const LoginPage = () => {
<Image <Image
src="/kri_logo.png" // public/kri_logo.png src="/kri_logo.png" // public/kri_logo.png
alt="KRI 로고" alt="KRI 로고"
width={500} // 원하는 크기로 줄이기 width={500}
height={500} height={500}
className="object-contain ml-10" className="object-contain ml-10"
priority priority
@@ -146,13 +87,13 @@ const LoginPage = () => {
<CardContent> <CardContent>
<div className="space-y-4"> <div className="space-y-4">
<div className="space-y-2"> <div className="space-y-2">
<label className="text-sm font-medium">ID</label> <label className="text-base font-medium">ID</label>
<Input <Input
id="id" id="id"
name="id" name="id"
type="text" type="text"
required required
placeholder="아이디를 입력하세요" placeholder="ID"
value={userId} value={userId}
onChange={(e) => setUserId(e.currentTarget.value)} onChange={(e) => setUserId(e.currentTarget.value)}
onKeyDown={handleIdKeyDown} onKeyDown={handleIdKeyDown}
@@ -160,39 +101,26 @@ const LoginPage = () => {
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<label className="text-sm font-medium">Password</label> <label className="text-base font-medium">Password</label>
<Input <Input
id="password" id="password"
name="password" name="password"
type="password" type="password"
autoComplete="current-password" autoComplete="current-password"
required required
placeholder="PW를 입력하세요" placeholder="Password"
value={userPw} value={userPw}
onChange={(e) => setUserPw(e.currentTarget.value)} onChange={(e) => setUserPw(e.currentTarget.value)}
onKeyDown={handlePwKeyDown} onKeyDown={handlePwKeyDown}
ref={passwordInputRef} ref={passwordInputRef}
/> />
</div> </div>
<p className="text-base">
{loginType === "call"? IP: {clientIp}
<div className="space-y-2"> </p>
<label className="text-sm font-medium">자리번호 (면접원)</label> <p className={cn("text-base", isCallSeatAndUnable && "font-bold text-red-500")}>
<Input {isCallSeatAndUnable? "전화걸기 이용 불가(관리자에게 문의해 주세요)" : `자리번호: ${clientId}`}
id="seatNum" </p>
name="seatNum"
type="text"
placeholder="자리번호를 입력하세요"
value={seatNum}
onChange={(e) => setSeatNum(e.currentTarget.value)}
onKeyDown={handleSeatNumberKeyDown}
ref={seatNumberInputRef}
/>
</div>
:
null
}
{error && ( {error && (
<p className="text-sm text-red-500"> <p className="text-sm text-red-500">
{error} {error}
@@ -201,7 +129,8 @@ 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}
onClick={(e) => { onClick={(e) => {
e.preventDefault(); e.preventDefault();
tryLogin(); tryLogin();
@@ -216,4 +145,4 @@ const LoginPage = () => {
); );
} }
export default LoginPage; export default LoginPage;

View File

@@ -1,49 +1,20 @@
'use client' 'use client'
import { useLogoutMutation } from "@/query/auth";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useAuth } from "@/hooks/useAuth"; import { useEffect } from "react";
import {useSelectedProject} from "@/hooks/useSelectedProject";
import {useStorage} from "@/hooks/useStorage";
import {StorageKeys} from "@/store/storage/storage-keys";
import {useEffect} from "react";
import {nextApi} from "@/lib/http-client";
import {useLoading} from "@/hooks/useLoading";
import {apiError} from "@/lib/http-util";
const LogoutPage = () => { const LogoutPage = () => {
const { get: getLoginTypeStorage, set: setLoginTypeStorage } = useStorage(StorageKeys.LoginType);
const { auth, logout } = useAuth();
const { clearSelectedProject } = useSelectedProject();
const { withLoadingAsync } = useLoading();
const router = useRouter(); const router = useRouter();
const logoutMutation = useLogoutMutation();
useEffect(() => { useEffect(() => {
(async () => {
const runLogout = async () => { await logoutMutation.mutateAsync();
const userId = auth.user?.userId ?? ""; router.replace("/login");
clearSelectedProject(); })();
logout();
try {
if(userId !== ""){
const logoutRequestOptions = {autoLogoutOnAuthError: false};
await nextApi.post(`/logout/${userId}`, null, logoutRequestOptions);
}
} catch (e) {
const err = apiError(e);
console.error(err.status, err.code, err.message);
}
const loginType = getLoginTypeStorage();
const loginUrl = loginType === "call" ? "/login?type=call" : "/login";
router.replace(loginUrl);
};
withLoadingAsync(runLogout);
}, []); }, []);
// Nothing to render while redirecting
return null; return null;
} };
export default LogoutPage; export default LogoutPage;

View File

@@ -0,0 +1,28 @@
import RedirectLanding from "@/components/external/RedirectLanding";
import {notFound} from "next/navigation";
import {ALLOW_REDIRECT} from "@/const/commonConst";
import {RedirectSlug} from "@/types/common";
type redirectPageProps = {
params: Promise<{ slug: string }>;
searchParams?: Promise<Record<string, string | string[] | undefined>>;
}
const toRedirectSlug = (slug: string): RedirectSlug | null => {
return ALLOW_REDIRECT.has(slug.toLowerCase()) ? (slug.toLowerCase() as RedirectSlug) : null;
}
const redirectPage = async ({
params,
}: redirectPageProps) => {
const { slug } = await params;
const redirectSlug = toRedirectSlug(slug);
if (!redirectSlug) notFound();
return (
<RedirectLanding redirectSlug={redirectSlug} />
)
}
export default redirectPage;

View File

@@ -0,0 +1,35 @@
import ErrorPage from "@/components/external/Error";
import {ErrorCode} from "@/types/common";
function toErrorCode(raw: string | undefined): ErrorCode {
if (raw === "500") return "500";
// fetch_error, 기타 알 수 없는 코드 → 500으로 처리
if (raw && raw !== "404") return "500";
return "404";
}
type RedirectErrorPageProps = {
searchParams: Promise<Record<string, string | string[] | undefined>>;
};
const RedirectErrorPage = async ({ searchParams }: RedirectErrorPageProps) => {
const sp = await searchParams;
console.log(sp)
const code = toErrorCode(sp.code as string | undefined);
const sid = (sp.sid as string | undefined) ?? "";
return (
<ErrorPage
code={code}
errorDescription={
sid
? `오류가 발생했습니다. 관리자에게 문의할 경우 아래 코드를 전달해 주세요.\n리스트 ID : ${sid}`
: undefined
}
/>
)
}
export default RedirectErrorPage

View File

@@ -1,7 +1,8 @@
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/server-api"; import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@/lib/http-util"; 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 {
@@ -9,8 +10,8 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
const [action] = slug; const [action] = slug;
const contactApi = await createContactApi(); const contactApi = await createContactApi();
if (action === "prjct-outsource" && slug.length === 2) { if (action === "prjct-cmpn" && slug.length === 2) {
const result = await contactApi.get<string[]>(`/assign/prjct-outsource/${slug[1]}`); const result = await contactApi.get<string[]>(`/assign/prjct-cmpn/${slug[1]}`);
return NextResponse.json(result, { status: 200 }); return NextResponse.json(result, { status: 200 });
} }
@@ -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);
@@ -31,7 +51,7 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
const [action] = slug; const [action] = slug;
const contactApi = await createContactApi(); const contactApi = await createContactApi();
if (action === "prjct-fieldwork" && slug.length === 2) { if ((action === "prjct-fieldwork" || action === "prjct-cmpn") && slug.length === 2) {
const body = await req.json().catch(() => null); const body = await req.json().catch(() => null);
if (!body) { if (!body) {
return NextResponse.json( return NextResponse.json(
@@ -40,7 +60,7 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
); );
} }
await contactApi.put(`/assign/prjct-fieldwork/${slug[1]}`, body); await contactApi.put(`/assign/${action}/${slug[1]}`, body);
return new NextResponse(null, { status: 204 }); return new NextResponse(null, { status: 204 });
} }
@@ -48,4 +68,4 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
} 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

@@ -0,0 +1,93 @@
import { NextRequest, NextResponse } from "next/server";
import { createContactApi } from "@/lib/http-server";
import type { CmpnInfo } from "@/types/cmpn";
import type { DataVerification } from "@kri/common";
import type { RouteContext } from "@/types/common";
import { errorToResponse } from "@kri/common/http";
export const GET = async (req: NextRequest, context: RouteContext) => {
try {
const { slug = [] } = await context.params;
const [action] = slug;
const contactApi = await createContactApi();
if (action === "check-cmpn-id") {
const cmpnId = req.nextUrl.searchParams.get("cmpnId") ?? "";
if (!cmpnId) {
return NextResponse.json(
{ message: "cmpnId 파라미터가 없습니다." },
{ status: 400 }
);
}
const result = await contactApi.get<DataVerification>("/cmpn/check-cmpn-id", {
query: { cmpnId },
});
return NextResponse.json(result, { status: 200 });
}
if (slug.length === 1) {
const result = await contactApi.get<CmpnInfo>(`/cmpn/${encodeURIComponent(action)}`);
return NextResponse.json(result, { status: 200 });
}
if (!action) {
const result = await contactApi.get<CmpnInfo[]>("/cmpn");
return NextResponse.json(result, { status: 200 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
export const PUT = async (req: NextRequest, context: RouteContext) => {
try {
const { slug = [] } = await context.params;
const [action] = slug ?? [];
const contactApi = await createContactApi();
if (!action) {
const body = await req.json().catch(() => null);
if (!body) {
return NextResponse.json(
{ message: "요청 바디가 없습니다." },
{ status: 400 }
);
}
await contactApi.put("/cmpn", body);
return new NextResponse(null, { status: 204 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
export const PATCH = async (req: NextRequest, context: RouteContext) => {
try {
const { slug = [] } = await context.params;
const [action] = slug ?? [];
const contactApi = await createContactApi();
if (!action) {
const body = await req.json().catch(() => null);
if (!body) {
return NextResponse.json(
{ message: "요청 바디가 없습니다." },
{ status: 400 }
);
}
await contactApi.patch("/cmpn", body);
return new NextResponse(null, { status: 204 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};

View File

@@ -1 +1,99 @@
//외부 설문에 뎐동 되는 API // External survey event API.
import { NextRequest, NextResponse } from "next/server";
import { RouteContext } from "@/types/common";
import { errorToResponse } from "@kri/common/http";
import { getClientIp } from "@kri/common/server";
import {
EXTERNAL_ACTION_CODE_BY_SLUG,
EXTERNAL_ENTRY_TYPE_CODE,
ExternalAction,
ExternalEntryTypeCode,
ExternalEventBody,
} from "@/types/external";
import {createContactApi} from "@/lib/http-server";
const getHeader = (headers: Headers, name: string): string | null => {
const value = headers.get(name);
return value && value.trim().length > 0 ? value : null;
};
const getEntryTypeCode = (headers: Headers): ExternalEntryTypeCode => {
return getHeader(headers, "x-entry-type") === "redirect"
? EXTERNAL_ENTRY_TYPE_CODE.redirect
: EXTERNAL_ENTRY_TYPE_CODE.api;
};
const toExternalAction = (value: string): ExternalAction | null => {
return value in EXTERNAL_ACTION_CODE_BY_SLUG ? (value as ExternalAction) : null;
};
const toRequiredNumber = (value: string): number | null => {
const parsed = Number(value);
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;
};
const toRequiredSid = (value: string): string | null =>
value.length > 0 ? value : null;
const buildExternalEventBody = (
req: NextRequest,
action: ExternalAction,
prjctSurveyIdx: number,
sid: string,
): ExternalEventBody => {
const pathname = req.nextUrl.pathname;
const h = req.headers;
const actionCode = EXTERNAL_ACTION_CODE_BY_SLUG[action];
return {
action: actionCode,
prjctSurveyIdx,
sid,
meta: {
entryType: getEntryTypeCode(h),
action: actionCode,
psidx: String(prjctSurveyIdx),
sid,
remoteAddr: getHeader(h, "x-orig-ip") || getClientIp(req),
uri: getHeader(h, "x-orig-uri") || pathname,
url: getHeader(h, "x-orig-url") || req.url,
userAgent: getHeader(h, "x-orig-user-agent") || getHeader(h, "user-agent"),
referer: getHeader(h, "x-orig-referer") || getHeader(h, "referer"),
origin: getHeader(h, "x-orig-origin") || getHeader(h, "origin"),
xForwardedFor: getHeader(h, "x-orig-x-forwarded-for") || getHeader(h, "x-forwarded-for"),
forwarded: getHeader(h, "x-orig-forwarded") || getHeader(h, "forwarded"),
},
};
};
const handleExternalEvent = async (req: NextRequest, context: RouteContext) => {
try {
const { searchParams } = req.nextUrl;
const { slug = [] } = await context.params;
const action = toExternalAction((slug[0] ?? "").toLowerCase());
if (slug.length !== 1 || !action) {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
const prjctSurveyIdx = toRequiredNumber((searchParams.get("psidx") ?? "").trim());
const sid = toRequiredSid((searchParams.get("sid") ?? "").trim());
if (!prjctSurveyIdx || !sid) {
return NextResponse.json({ message: "psidx, sid는 필수입니다." }, { status: 400 });
}
const body = buildExternalEventBody(req, action, prjctSurveyIdx, sid);
const contactApi = await createContactApi();
await contactApi.post(`/list-hist/survey`, body);
return new NextResponse(null, { status: 204 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
export const GET = handleExternalEvent;
export const POST = handleExternalEvent;

View File

@@ -1,9 +1,9 @@
import {NextRequest, NextResponse} from "next/server"; import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common"; import {RouteContext} from "@/types/common";
import {createContactApi, createIntranetApi} from "@/lib/server-api"; import {createIntranetApi} from "@/lib/http-server";
import {IntranetProjectSearchResponse, ProjectInfo, ProjectOwnerResponse} from "@/types/project"; import {CallerTelNumInfo, IntranetProjectSearchResponse} from "@/types/project";
import {errorToResponse} from "@/lib/http-util"; import {errorToResponse} from "@kri/common/http";
import {ItrntUserInfo} from "@/types/user"; import {GroupCodeInfo, ItrntUserInfo} from "@/types/user";
export const GET = async (req: NextRequest, context: RouteContext) => { export const GET = async (req: NextRequest, context: RouteContext) => {
try { try {
@@ -28,8 +28,20 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
return NextResponse.json(result, { status: 200 }); return NextResponse.json(result, { status: 200 });
} }
if(action === "caller-tel-num"){
const result = await itrntApi.get<CallerTelNumInfo[]>(`/telnum/caller`);
return NextResponse.json(result, { status: 200 });
}
if(action === "group-code-list"){
const result = await itrntApi.get<GroupCodeInfo[]>(`/user/group-code-list`);
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

@@ -1,22 +1,25 @@
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/server-api"; import {createContactApi} from "@/lib/http-server";
import {KonKiwiProjectInfo} from "@/types/project"; import {KonKiwiProjectInfo} from "@/types/project";
import {errorToResponse} from "@/lib/http-util"; 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 { 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 });
); }
const result = await contactApi.get<KonKiwiProjectInfo[]>(`/kart/project/list`, {
query: { intranetCode, projectType, ...(keyword ? { keyword } : {}) },
});
return NextResponse.json(result, { status: 200 }); return NextResponse.json(result, { status: 200 });
} }
@@ -25,4 +28,4 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
} catch (error: unknown) { } catch (error: unknown) {
return errorToResponse(error); return errorToResponse(error);
} }
}; };

View File

@@ -0,0 +1,29 @@
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 {ListCallHist} from "@/types/list";
export const PUT = async (req: NextRequest, context: RouteContext) => {
try {
const { slug = [] } = await context.params;
const [prjctIdx, sid, action] = slug;
if (!prjctIdx || !sid || (action !== "call-start" && action !== "call-close")) {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
const body = await req.json().catch(() => null);
if (!body) {
return NextResponse.json({ message: "요청 바디가 없습니다." }, { status: 400 });
}
const contactApi = await createContactApi();
const result = await contactApi.put<ListCallHist>(
`/list-call-hist/${prjctIdx}/${encodeURIComponent(sid)}/${action}`,
body,
);
return NextResponse.json(result, { status: 200 });
} catch (error: unknown) {
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

@@ -0,0 +1,73 @@
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 {ListEventHistory, ListUpdateHistory} from "@/types/list";
export const GET = async (_req: NextRequest, context: RouteContext) => {
try {
const { slug = [] } = await context.params;
const [action] = slug;
const contactApi = await createContactApi();
if (action === "event" && slug.length === 3) {
const result = await contactApi.get<ListEventHistory[]>(
`/list-hist/event/${slug[1]}/${encodeURIComponent(slug[2])}`,
);
return NextResponse.json(result, { status: 200 });
}
if (action === "update" && slug.length === 3) {
const result = await contactApi.get<ListUpdateHistory[]>(
`/list-hist/update/${slug[1]}/${encodeURIComponent(slug[2])}`,
);
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 === "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) => {
try {
const { slug = [] } = await context.params;
const [action] = slug;
const contactApi = await createContactApi();
if (action === "event") {
const body = await req.json().catch(() => null);
if (!body) {
return NextResponse.json(
{ message: "요청 바디가 없습니다." },
{ status: 400 }
);
}
await contactApi.put(`/list-hist/event`, body);
return new NextResponse(null, { status: 204 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};

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

@@ -0,0 +1,139 @@
import {NextRequest, NextResponse} from "next/server";
import type {PageResponse} from "@kri/common";
import {RouteContext} from "@/types/common";
import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@kri/common/http";
import {listHeader, ListSearchRequest, ListSearchWithFullResult} from "@/types/list";
const excelHeaders = {
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
};
export const GET = async (_req: NextRequest, context: RouteContext) => {
try {
const {slug = []} = await context.params;
const [action] = slug;
const contactApi = await createContactApi();
if(action === "header") {
const result = await contactApi.get<listHeader[]>(
`/list-header/${slug[1]}`,
);
return NextResponse.json(result, { status: 200 });
}
if (action === "upload-history") {
const result = await contactApi.get(`/list/excel/upload-history/${slug[1]}`);
return NextResponse.json(result, { status: 200 });
}
if (action === "search-sid" && slug.length === 3) {
const result = await contactApi.get<ListSearchWithFullResult>(
`/list/search-sid/${slug[1]}/${encodeURIComponent(slug[2])}`,
);
return NextResponse.json(result, { status: 200 });
}
if (action === "item-file-download" && slug.length === 4) {
const result = await contactApi.get<ArrayBuffer>(
`/list/item-file/download/${slug[1]}/${encodeURIComponent(slug[2])}/${slug[3]}`,
{ expectBinary: true },
);
return new NextResponse(result, {
status: 200,
headers: { "Content-Type": "application/octet-stream" },
});
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
export const POST = async (req: NextRequest, context: RouteContext) => {
try {
const {slug = []} = await context.params;
const [action] = slug;
const contactApi = await createContactApi();
if(action === "search-filter"){
const body: ListSearchRequest | null = await req.json().catch(() => null);
if (!body) {
return NextResponse.json(
{ message: "요청 바디가 없습니다." },
{ status: 400 }
);
}
const result = await contactApi.post<PageResponse<ListSearchWithFullResult>>(
`/list/search-filter/${slug[1]}`,
body,
);
return NextResponse.json(result, { status: 200 });
}
if (action === "excel-template") {
const prjctIdx = slug[1];
if (!prjctIdx) {
return NextResponse.json({ message: "prjctIdx 파라미터가 없습니다." }, { status: 400 });
}
const result = await contactApi.post<ArrayBuffer>(
`/list/excel/template/${prjctIdx}`,
undefined,
{ expectBinary: true }
);
return new NextResponse(result, {
status: 200,
headers: {
...excelHeaders,
"Content-Disposition": 'attachment; filename="list_upload_template.xlsx"',
},
});
}
if (action === "item-file-upload" && slug.length === 3) {
const form = await req.formData();
await contactApi.postForm(`/list/item-file/upload/${slug[1]}/${encodeURIComponent(slug[2])}`, form);
return new NextResponse(null, { status: 204 });
}
if (action === "upload-history-file") {
const result = await contactApi.post<ArrayBuffer>(
`/list/excel/upload-history/file/${slug[1]}/${slug[2]}`,
undefined,
{ expectBinary: true },
);
return new NextResponse(result, { status: 200, headers: excelHeaders });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
export const PATCH = async (req: NextRequest, context: RouteContext) => {
try {
const { slug = [] } = await context.params;
const [action] = slug;
const body = await req.json().catch(() => null);
const contactApi = await createContactApi();
if (action === "header") {
await contactApi.patch(`/list-header/${slug[1]}`, body);
return new NextResponse(null, { status: 204 });
}
if (action === "update") {
const result = await contactApi.patch<number>(`/list/update/${slug[1]}`, body);
return NextResponse.json(result, { status: 200 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};

View File

@@ -1,10 +1,10 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import {LoginRequest, LoginUser} from "@/types/auth"; import type { LoginRequest, LoginUser } from "@kri/common";
import {serverEnv} from "@/lib/env.server"; import {setAuthCookie} from "@/lib/auth-cookie";
import {createContactApi} from "@/lib/server-api"; import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@/lib/http-util"; import {errorToResponse} from "@kri/common/http";
//실제 Backend //?ㅼ젣 Backend
type LoginResponse = { type LoginResponse = {
accessToken: string; accessToken: string;
user: LoginUser; user: LoginUser;
@@ -18,16 +18,10 @@ 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("access_token", 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) {
return errorToResponse(error); return errorToResponse(error);
} }
} }

View File

@@ -1,11 +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/server-api"; import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@/lib/http-util"; import {errorToResponse} from "@kri/common/http";
import {RouteContext} from "@/types/common"; import {RouteContext} from "@/types/common";
export async function POST( export async function POST(
req: NextRequest, _req: NextRequest,
context: RouteContext context: RouteContext
) { ) {
try { try {
@@ -21,16 +21,10 @@ 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("access_token", "", { setAuthCookie(res, "");
httpOnly: true,
secure: serverEnv.ENV === "prod",
sameSite: "lax",
path: "/",
maxAge: 0,
});
return res; return res;
} catch (error: unknown) { } catch (error: unknown) {
return errorToResponse(error); return errorToResponse(error);
} }
} }

View File

@@ -0,0 +1,81 @@
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 {FileResponse, PageRequest, PageResponse} from "@kri/common";
import type {BulkSendInfo, SendResultInfo, SendResultSummaryRequest, SendResultSummaryResponse} from "@kri/common/noti-hub";
export const GET = async (req: NextRequest, context: RouteContext) => {
try {
const {slug = []} = await context.params;
const [action, sendTy, reqstSvc, prjctCd] = slug;
const contactApi = await createContactApi();
if (action === "bulk-list" && sendTy && reqstSvc && prjctCd) {
const result = await contactApi.get<BulkSendInfo[]>(
`/message-report/bulk-list/${sendTy}/${reqstSvc}/${prjctCd}`,
);
return NextResponse.json(result, {status: 200});
}
if (action === "send-result" && slug.length >= 4) {
const [, sid, prjctCdParam, reqstSvcParam] = slug;
const channelTy = req.nextUrl.searchParams.get("channelTy");
const query = channelTy ? `?channelTy=${channelTy}` : "";
const result = await contactApi.get<SendResultInfo[]>(
`/message-report/send-result/${encodeURIComponent(sid)}/${prjctCdParam}/${reqstSvcParam}${query}`,
);
return NextResponse.json(result, {status: 200});
}
return NextResponse.json({message: "Not found"}, {status: 404});
} catch (error: unknown) {
return errorToResponse(error);
}
};
export const POST = async (req: NextRequest, context: RouteContext) => {
try {
const {slug = []} = await context.params;
const [action, bulkSendKey] = slug;
const contactApi = await createContactApi();
if (action === "bulk-detail" && bulkSendKey) {
const body: PageRequest | null = await req.json().catch(() => null);
if (!body) {
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
}
const result = await contactApi.post<PageResponse<SendResultInfo>>(
`/message-report/bulk-detail/${bulkSendKey}`,
body,
);
return NextResponse.json(result, {status: 200});
}
if (action === "bulk-detail-excel" && bulkSendKey) {
const result = await contactApi.post<FileResponse>(
`/message-report/bulk-detail-excel/${bulkSendKey}`,
undefined,
);
return NextResponse.json(result, {status: 200});
}
if (action === "send-result-summary") {
const body: SendResultSummaryRequest | null = await req.json().catch(() => null);
if (!body) {
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
}
const result = await contactApi.post<SendResultSummaryResponse[]>(
`/message-report/send-result-summary`,
body,
);
return NextResponse.json(result, {status: 200});
}
return NextResponse.json({message: "Not found"}, {status: 404});
} catch (error: unknown) {
return errorToResponse(error);
}
};

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/server-api"; import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@/lib/http-util"; import {errorToResponse} from "@kri/common/http";
import {Template, TemplateSummary} from "@/types/messageTemplate"; 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 });
} }
@@ -102,4 +143,21 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => {
} catch (error: unknown) { } catch (error: unknown) {
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

@@ -0,0 +1,39 @@
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 {ProgressDateResponse, ProgressSearchRequest, ProgressUserResponse} from "@/types/progress";
const ACTION_PATH: Record<string, string> = {
"user": "/progress/user",
"last-date": "/progress/last-date",
"date": "/progress/date",
};
export const POST = async (req: NextRequest, context: RouteContext) => {
try {
const {slug = []} = await context.params;
const [action, prjctIdx, eventTy] = slug;
const contactApi = await createContactApi();
const basePath = ACTION_PATH[action];
if (!basePath || !prjctIdx || !eventTy) {
return NextResponse.json({message: "Not found"}, {status: 404});
}
const body: ProgressSearchRequest | null = await req.json().catch(() => null);
if (!body) {
return NextResponse.json({message: "요청 바디가 없습니다."}, {status: 400});
}
if (action === "user") {
const result = await contactApi.post<ProgressUserResponse[]>(`${basePath}/${prjctIdx}/${eventTy}`, body);
return NextResponse.json(result, {status: 200});
}
const result = await contactApi.post<ProgressDateResponse[]>(`${basePath}/${prjctIdx}/${eventTy}`, body);
return NextResponse.json(result, {status: 200});
} catch (error: unknown) {
return errorToResponse(error);
}
};

View File

@@ -1,8 +1,9 @@
import {NextRequest, NextResponse} from "next/server"; import {NextRequest, NextResponse} from "next/server";
import {createContactApi, createIntranetApi} from "@/lib/server-api"; import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@/lib/http-util"; import {errorToResponse} from "@kri/common/http";
import {PageResponse, RouteContext} from "@/types/common"; import type {PageResponse} from "@kri/common";
import {IntranetProjectSearchResponse, ProjectInfo, ProjectOwnerResponse, ResultCode} from "@/types/project"; import {RouteContext} from "@/types/common";
import {ProjectInfo, ProjectListRequest, ProjectOwnerResponse} from "@/types/project";
export const GET = async (req: NextRequest, context: RouteContext) => { export const GET = async (req: NextRequest, context: RouteContext) => {
try { try {
@@ -51,7 +52,7 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
const contactApi = await createContactApi(); const contactApi = await createContactApi();
if(action === "list"){ if(action === "list"){
const body = await req.json().catch(() => null); const body: ProjectListRequest | null = await req.json().catch(() => null);
if (!body) { if (!body) {
return NextResponse.json( return NextResponse.json(
{ message: "요청 바디가 없습니다." }, { message: "요청 바디가 없습니다." },
@@ -171,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){
@@ -186,4 +186,4 @@ export const DELETE = async (req: NextRequest, context: RouteContext) => {
} catch (error: unknown) { } catch (error: unknown) {
return errorToResponse(error); return errorToResponse(error);
} }
}; };

View File

@@ -0,0 +1,64 @@
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 {ListReserve} from "@/types/list";
export const GET = async (req: NextRequest, context: RouteContext) => {
try {
const { slug = [] } = await context.params;
const [action] = slug;
const contactApi = await createContactApi();
if (action === "sid" && slug.length === 3) {
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 });
}
if (action === "user" && slug.length === 3) {
const result = await contactApi.get<ListReserve[]>(`/reserve/${slug[1]}/user/${slug[2]}`);
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 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
export const PUT = async (req: NextRequest) => {
try {
const body = await req.json().catch(() => null);
if (!body) {
return NextResponse.json({ message: "요청 바디가 없습니다." }, { status: 400 });
}
const contactApi = await createContactApi();
const result = await contactApi.put<ListReserve>(`/reserve`, body);
return NextResponse.json(result, { status: 200 });
} catch (error: unknown) {
return errorToResponse(error);
}
};

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/server-api"; import {createContactApi} from "@/lib/http-server";
import {ProjectInfo, ProjectOwnerResponse, ResultCode} from "@/types/project"; import {ResultCode} from "@/types/project";
import {errorToResponse} from "@/lib/http-util"; 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){
@@ -20,4 +18,4 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
} catch (error: unknown) { } catch (error: unknown) {
return errorToResponse(error); return errorToResponse(error);
} }
}; };

View File

@@ -1,10 +1,10 @@
import {NextRequest, NextResponse} from "next/server"; import {NextRequest, NextResponse} from "next/server";
import {createContactApi} from "@/lib/server-api"; import {createContactApi} from "@/lib/http-server";
import {RoleInfo} from "@/types/role"; import {RoleInfo} from "@/types/role";
import {errorToResponse} from "@/lib/http-util"; 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;
@@ -19,4 +19,4 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
} catch (error: unknown) { } catch (error: unknown) {
return errorToResponse(error); return errorToResponse(error);
} }
}; };

View File

@@ -1,8 +1,9 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import { createContactApi } from "@/lib/server-api"; import { createContactApi } from "@/lib/http-server";
import {UserInfo, UserUploadResponse} from "@/types/user"; import type { UserInfo } from "@/types/user";
import {DataVerification, RouteContext} from "@/types/common"; import type { DataVerification, ExcelUploadResult } from "@kri/common";
import {errorToResponse} from "@/lib/http-util"; import type { RouteContext } from "@/types/common";
import {errorToResponse} from "@kri/common/http";
export const GET = async (req: NextRequest, context: RouteContext) => { export const GET = async (req: NextRequest, context: RouteContext) => {
try { try {
@@ -25,16 +26,6 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
return NextResponse.json(result, { status: 200 }); return NextResponse.json(result, { status: 200 });
} }
if(action === "cmpn"){
const result = await contactApi.get<string[]>("/user/cmpn");
return NextResponse.json(result, { status: 200 });
}
if(action === "outsource"){
const result = await contactApi.get<UserInfo[]>("/user/outsource");
return NextResponse.json(result, { status: 200 });
}
if(action === "fieldwork"){ if(action === "fieldwork"){
const result = await contactApi.get<UserInfo[]>("/user/fieldwork"); const result = await contactApi.get<UserInfo[]>("/user/fieldwork");
return NextResponse.json(result, { status: 200 }); return NextResponse.json(result, { status: 200 });
@@ -63,7 +54,7 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
const [action] = slug ?? []; const [action] = slug ?? [];
const contactApi = await createContactApi(); const contactApi = await createContactApi();
if (action === "excel") { if (action === "excel-upload") {
const formData = await req.formData(); const formData = await req.formData();
const file = formData.get("file") as File | null; const file = formData.get("file") as File | null;
@@ -77,8 +68,8 @@ export const POST = async (req: NextRequest, context: RouteContext) => {
const backendForm = new FormData(); const backendForm = new FormData();
backendForm.append("file", file, file.name); backendForm.append("file", file, file.name);
const result = await contactApi.postForm<UserUploadResponse>( const result = await contactApi.postForm<ExcelUploadResult>(
"/user/excel", "/user/excel/upload",
backendForm backendForm
); );
@@ -158,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

@@ -4,189 +4,158 @@
@custom-variant dark (&:is(.dark *)); @custom-variant dark (&:is(.dark *));
@theme inline { @theme inline {
--color-background: var(--background); --color-background: var(--background);
--color-foreground: var(--foreground); --color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans); --font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono); --font-mono: var(--font-geist-mono);
--color-sidebar-ring: var(--sidebar-ring); /* --content-font-size 배율 기반 font-size 스케일 (기본 text-* 유틸을 그대로 대체) */
--color-sidebar-border: var(--sidebar-border); --text-xs: calc(var(--content-font-size) * 0.75);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground); --text-sm: calc(var(--content-font-size) * 0.875);
--color-sidebar-accent: var(--sidebar-accent); --text-base: var(--content-font-size);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground); --text-lg: calc(var(--content-font-size) * 1.125);
--color-sidebar-primary: var(--sidebar-primary); --text-xl: calc(var(--content-font-size) * 1.25);
--color-sidebar-foreground: var(--sidebar-foreground); --text-2xl: calc(var(--content-font-size) * 1.5);
--color-sidebar: var(--sidebar); --text-3xl: calc(var(--content-font-size) * 1.875);
--color-chart-5: var(--chart-5); --text-4xl: calc(var(--content-font-size) * 2.25);
--color-chart-4: var(--chart-4); --text-5xl: calc(var(--content-font-size) * 3);
--color-chart-3: var(--chart-3); --text-6xl: calc(var(--content-font-size) * 3.75);
--color-chart-2: var(--chart-2); --text-7xl: calc(var(--content-font-size) * 4.5);
--color-chart-1: var(--chart-1); --text-8xl: calc(var(--content-font-size) * 6);
--color-ring: var(--ring); --text-9xl: calc(var(--content-font-size) * 8);
--color-input: var(--input); --color-sidebar-ring: var(--sidebar-ring);
--color-border: var(--border); --color-sidebar-border: var(--sidebar-border);
--color-destructive: var(--destructive); --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-accent-foreground: var(--accent-foreground); --color-sidebar-accent: var(--sidebar-accent);
--color-accent: var(--accent); --color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-muted-foreground: var(--muted-foreground); --color-sidebar-primary: var(--sidebar-primary);
--color-muted: var(--muted); --color-sidebar-foreground: var(--sidebar-foreground);
--color-secondary-foreground: var(--secondary-foreground); --color-sidebar: var(--sidebar);
--color-secondary: var(--secondary); --color-chart-5: var(--chart-5);
--color-primary-foreground: var(--primary-foreground); --color-chart-4: var(--chart-4);
--color-primary: var(--primary); --color-chart-3: var(--chart-3);
--color-popover-foreground: var(--popover-foreground); --color-chart-2: var(--chart-2);
--color-popover: var(--popover); --color-chart-1: var(--chart-1);
--color-card-foreground: var(--card-foreground); --color-ring: var(--ring);
--color-card: var(--card); --color-input: var(--input);
--radius-sm: calc(var(--radius) - 4px); --color-border: var(--border);
--radius-md: calc(var(--radius) - 2px); --color-destructive: var(--destructive);
--radius-lg: var(--radius); --color-accent-foreground: var(--accent-foreground);
--radius-xl: calc(var(--radius) + 4px); --color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
} }
:root { :root {
--radius: 0.625rem; --radius: 0.625rem;
--background: oklch(1 0 0); --background: oklch(1 0 0);
--foreground: oklch(0.145 0 0); --foreground: oklch(0.145 0 0);
--card: oklch(1 0 0); --card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0); --card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0); --popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0); --popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0); --primary: oklch(0.33 0.07 255);
--primary-foreground: oklch(0.985 0 0); --primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0); --secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0); --secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0); --muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0); --muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0); --accent: oklch(0.87 0.18 95);
--accent-foreground: oklch(0.205 0 0); --accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325); --destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0); --border: oklch(0.922 0 0);
--input: oklch(0.922 0 0); --input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0); --ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116); --chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704); --chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392); --chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429); --chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08); --chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0); --sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0); --sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0); --sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0); --sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0); --sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0); --sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0); --sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0); --sidebar-ring: oklch(0.708 0 0);
--content-font-size: 14px; --content-font-size: 14px;
} }
.dark { .dark {
--background: oklch(0.145 0 0); --background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0); --foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0); --card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0); --card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0); --popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0); --popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0); --primary: oklch(0.55 0.09 255);
--primary-foreground: oklch(0.205 0 0); --primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.269 0 0); --secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0); --secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0); --muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0); --muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0); --accent: oklch(0.8 0.17 95);
--accent-foreground: oklch(0.985 0 0); --accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.704 0.191 22.216); --destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%); --border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%); --input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0); --ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376); --chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48); --chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08); --chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9); --chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439); --chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0); --sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0); --sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376); --sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0); --sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0); --sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0); --sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%); --sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0); --sidebar-ring: oklch(0.556 0 0);
} }
/* 배율별 유틸 클래스 */ .bg-excel {
.content-text-xs { background-color: #217346;
font-size: calc(var(--content-font-size) * 0.75); }
.bg-excel:hover {
background-color: #185c37;
} }
.content-text-sm { .bg-blue {
font-size: calc(var(--content-font-size) * 0.875); background-color: var(--color-blue-600);
}
.bg-blue:hover {
background-color: var(--color-blue-700);
} }
.content-text-base { /*
font-size: var(--content-font-size); * [제거됨] .content-text-* / .placeholder-content-text-*
} * --font-size-* 를 @theme inline 에 등록했기 때문에
* 기본 text-xs ~ text-4xl 유틸이 이미 --content-font-size 배율을 반영합니다.
.content-text-lg { * placeholder 스타일도 Tailwind 기본 placeholder: variant로 대체 가능합니다.
font-size: calc(var(--content-font-size) * 1.125); * 예) placeholder-content-text-sm -> placeholder:text-sm
} */
.content-text-xl {
font-size: calc(var(--content-font-size) * 1.25);
}
.content-text-2xl {
font-size: calc(var(--content-font-size) * 1.5);
}
.content-text-3xl {
font-size: calc(var(--content-font-size) * 1.875);
}
.content-text-4xl {
font-size: calc(var(--content-font-size) * 2.25);
}
@layer utilities {
.placeholder-content-text-xs::placeholder {
font-size: calc(var(--content-font-size) * 0.75);
}
.placeholder-content-text-sm::placeholder {
font-size: calc(var(--content-font-size) * 0.875);
}
.placeholder-content-text-base::placeholder {
font-size: var(--content-font-size);
}
.placeholder-content-text-lg::placeholder {
font-size: calc(var(--content-font-size) * 1.125);
}
.placeholder-content-text-xl::placeholder {
font-size: calc(var(--content-font-size) * 1.25);
}
.placeholder-content-text-2xl::placeholder {
font-size: calc(var(--content-font-size) * 1.5);
}
.placeholder-content-text-3xl::placeholder {
font-size: calc(var(--content-font-size) * 1.875);
}
.placeholder-content-text-4xl::placeholder {
font-size: calc(var(--content-font-size) * 2.25);
}
}
@layer base { @layer base {
* { * {
@apply border-border outline-ring/50; @apply border-border outline-ring/50;
} }
body { body {
@apply bg-background text-foreground; @apply bg-background text-foreground;
} }
} }
/*************************TipTap 이미지 Resize Node*******************************/ /*************************TipTap 이미지 Resize Node*******************************/
@@ -194,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;
} }
/* 리사이즈 핸들 공통 스타일 */ /* 리사이즈 핸들 공통 스타일 */
@@ -252,4 +250,5 @@
/* 리사이즈 중인 상태를 잡고 싶으면 */ /* 리사이즈 중인 상태를 잡고 싶으면 */
.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",

9
src/app/not-found.tsx Normal file
View File

@@ -0,0 +1,9 @@
import ErrorPage from "@/components/external/Error";
const NotFound = () => {
return (
<ErrorPage code="404" />
)
}
export default NotFound

View File

@@ -0,0 +1,155 @@
"use client";
import Image from "next/image";
import { CalendarClock, LogOut, UserRound, ZoomIn, ZoomOut } from "lucide-react";
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 type { TopMenuItem } from "@/config/menu.types";
import type { LoginUser } from "@kri/common";
import { cn } from "@/lib/utils";
import { useInternalInfoQuery } from "@/query/internal";
import { useCtiConnectionStatus } from "@/hooks/useCtiConnectionStatus";
interface AppHeaderProps {
isMain: boolean;
isContactPage: boolean;
menuOpen: boolean;
activeTopId: string;
topMenus: TopMenuItem[];
isViewProjectTitle: boolean;
projectName?: string;
userInfo?: LoginUser;
fontSize: number;
onToggleMenu: () => void;
onNavigate: (path: string) => void;
decreaseFontSize: () => void;
increaseFontSize: () => void;
onOpenReserveSearch: () => void;
}
export function AppHeader({
isMain,
isContactPage,
menuOpen,
activeTopId,
topMenus,
isViewProjectTitle,
projectName,
userInfo,
fontSize,
onToggleMenu,
onNavigate,
decreaseFontSize,
increaseFontSize,
onOpenReserveSearch,
}: AppHeaderProps) {
const internalInfoQuery = useInternalInfoQuery(!!userInfo);
const seatNo = internalInfoQuery.data?.clientId ?? "";
const ctiConnectionStatus = useCtiConnectionStatus();
const isCtiConnected = ctiConnectionStatus === "open";
const showProjectTitle = isViewProjectTitle && !!projectName;
return (
<>
<KriHeader
logo={
<div className="flex h-10 w-16 items-center justify-center sm:w-20">
<Image
src="/kri_logo.png"
alt="KRI 로고"
width={120}
height={40}
className="h-full w-full object-contain"
priority
/>
</div>
}
homePath="/"
menus={isContactPage? []:topMenus}
activeMenuId={activeTopId}
menuOpen={menuOpen}
showMenuButton={!isMain && !isContactPage}
onToggleMenu={onToggleMenu}
onNavigate={(path) => {if(!isContactPage) onNavigate(path)}}
className="border-gray-200 bg-white"
// 모바일(sm 미만)은 헤더 폭이 좁아 로고와 우측 버튼이 겹치지 않도록 간격을 줄인다.
innerClassName="h-16 gap-2 px-2 sm:gap-4 sm:px-4"
center={
showProjectTitle ? (
<h1 className="ml-3 hidden truncate text-2xl font-bold lg:block" title={projectName}>{projectName}</h1>
) : null
}
right={
<>
<div className="flex items-center gap-1 border-r pr-2 sm:pr-4">
<Button variant="ghost" size="icon" className="size-8 sm:size-9" onClick={decreaseFontSize} title="폰트 작게">
<ZoomOut className="h-4 w-4" />
</Button>
<span className="min-w-6 text-center text-xs text-gray-500" title={`글자 크기 ${fontSize}px`}>{fontSize}</span>
<Button variant="ghost" size="icon" className="size-8 sm:size-9" onClick={increaseFontSize} title="폰트 크게">
<ZoomIn className="h-4 w-4" />
</Button>
</div>
<Button variant="ghost" size="icon-lg" className="size-8 sm:size-10" onClick={onOpenReserveSearch} title="예약 내역 조회">
<CalendarClock className="size-6" />
</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

@@ -0,0 +1,243 @@
"use client";
import { ReactNode, useEffect, useMemo, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import type { Route } from "next";
import { useMounted } from "@kri/common/hooks";
import { getCurrentPositionMeta } from "@kri/common/browser";
import { KriMainLayout } from "@/components/layout/KriMainLayout";
import { AppHeader } from "@/components/app-shell/AppHeader";
import { AppSidebar } from "@/components/app-shell/AppSidebar";
import ReserveSearchDialog from "@/components/dialog/ReserveSearchDialog";
import { useFontSize } from "@/hooks/useFontSize";
import { useAuth } from "@/hooks/useAuth";
import { useSelectedProject } from "@/hooks/useSelectedProject";
import { useDialog } from "@/hooks/useDialog";
import { manageSideMenus, projectSideMenus, topMenus } from "@/config/menu.data";
import type { SideMenuItem, SideSubMenuItem, TopMenuItem } from "@/config/menu.types";
import { cn } from "@/lib/utils";
import { FONT_SIZE } from "@/const/commonConst";
import { ListJobWatcher } from "@/components/list/ListJobWatcher";
type AppMainLayoutProps = {
children: ReactNode;
initialFontSize: number;
};
type AccessControlledItem = {
path?: string;
accessRole: number[];
children?: AccessControlledItem[];
match?: (pathname: string) => boolean;
};
function canAccess(accessRole: number[], userRole: number | undefined): boolean {
return accessRole.length === 0 || (userRole !== undefined && accessRole.includes(userRole));
}
function filterTopMenusByRole(menus: TopMenuItem[], userRole: number | undefined): TopMenuItem[] {
return menus.filter((menu) => canAccess(menu.accessRole, userRole));
}
function filterSubMenusByRole(children: SideSubMenuItem[] | undefined, userRole: number | undefined): SideSubMenuItem[] | undefined {
const filtered = children?.filter((child) => canAccess(child.accessRole, userRole));
return filtered?.length ? filtered : undefined;
}
function filterSideMenusByRole(menus: SideMenuItem[], userRole: number | undefined): SideMenuItem[] {
return menus.reduce<SideMenuItem[]>((acc, menu) => {
if (!canAccess(menu.accessRole, userRole)) return acc;
const children = filterSubMenusByRole(menu.children, userRole);
if (!menu.path && menu.children?.length && !children?.length) return acc;
acc.push({
...menu,
...(children ? { children } : { children: undefined }),
});
return acc;
}, []);
}
function pathMatches(item: AccessControlledItem, pathname: string): boolean {
if (item.match?.(pathname)) return true;
return Boolean(item.path && (pathname === item.path || pathname.startsWith(`${item.path}/`)));
}
function findSideAccessChain(pathname: string, menus: SideMenuItem[]): AccessControlledItem[] | null {
const matches: AccessControlledItem[][] = [];
menus.forEach((menu) => {
if (menu.path && pathMatches(menu, pathname)) {
matches.push([menu]);
}
menu.children?.forEach((child) => {
if (pathMatches(child, pathname)) {
matches.push([menu, child]);
}
});
});
if (!matches.length) return null;
return matches.sort((a, b) => {
const aPath = a.at(-1)?.path ?? "";
const bPath = b.at(-1)?.path ?? "";
return bPath.length - aPath.length;
})[0];
}
function findTopAccessChain(pathname: string, menus: TopMenuItem[]): AccessControlledItem[] | null {
const match = menus.find((menu) => pathMatches(menu, pathname));
return match ? [match] : null;
}
function findAccessChain(pathname: string): AccessControlledItem[] | null {
return (
findSideAccessChain(pathname, [...projectSideMenus, ...manageSideMenus]) ??
findTopAccessChain(pathname, topMenus)
);
}
export default function AppMainLayout({ children, initialFontSize }: AppMainLayoutProps) {
const router = useRouter();
const pathname = usePathname();
const mounted = useMounted();
const { auth } = useAuth();
const { selectedProject, isSelectedProjectHydrated } = useSelectedProject();
const { showDialog } = useDialog();
const [menuOpen, setMenuOpen] = useState(true);
const [fontSize, setFontSize] = useFontSize(initialFontSize, { hydrateFromCookie: false });
const userRole = auth.user?.userRole;
const isMain = pathname === "/";
const isContactPage = pathname.startsWith("/list/contact");
const isProjectMenu = !pathname.startsWith("/manage");
const isViewProjectTitle = !isMain && isProjectMenu && !pathname.startsWith("/project/info");
const visibleTopMenus = useMemo(() => filterTopMenusByRole(topMenus, userRole), [userRole]);
const visibleProjectSideMenus = useMemo(() => filterSideMenusByRole(projectSideMenus, userRole), [userRole]);
const visibleManageSideMenus = useMemo(() => filterSideMenusByRole(manageSideMenus, userRole), [userRole]);
const activeTop = visibleTopMenus.find((menu) => menu.match?.(pathname)) ?? visibleTopMenus[0] ?? topMenus[0];
const sideMenus = isProjectMenu ? visibleProjectSideMenus : visibleManageSideMenus;
const hasRouteAccess = useMemo(() => {
if (!auth.user) return true;
const accessChain = findAccessChain(pathname);
if (!accessChain) return true;
return accessChain.every((item) => canAccess(item.accessRole, userRole));
}, [auth.user, pathname, userRole]);
const [openMenus, setOpenMenus] = useState<Record<string, boolean>>(() => {
const initial: Record<string, boolean> = {};
sideMenus.forEach((item) => {
if (item.children?.some((child) => pathname === child.path || pathname.startsWith(`${child.path}/`))) {
initial[item.id] = true;
}
});
return initial;
});
const movePage = (path: string) => {
// 메뉴 설정(menu.data.ts)의 경로라 typedRoutes가 정적으로 검사할 수 없다.
router.push(path as Route);
};
const decreaseFontSize = () => {
setFontSize(Math.max(FONT_SIZE.MIN, fontSize - 2));
};
const increaseFontSize = () => {
setFontSize(Math.min(FONT_SIZE.MAX, fontSize + 2));
};
// 모바일(lg 미만)에서는 사이드바가 본문을 덮는 오버레이라 메뉴를 접힌 상태로 시작한다.
useEffect(() => {
if (!window.matchMedia("(min-width: 64rem)").matches) setMenuOpen(false);
}, []);
useEffect(() => {
if (!mounted) return;
if (!auth.user) {
router.replace("/logout");
}
}, [auth.user, mounted, router]);
// 컨택결과 저장 시점에 GPS 권한 프롬프트가 뜨면 저장이 지연/누락될 수 있어,
// 로그인 후 메인 진입 시점에 미리 권한을 받아 위치를 캐시해둔다(결과는 사용하지 않음).
useEffect(() => {
if (!mounted || !auth.user) return;
void getCurrentPositionMeta();
}, [mounted, auth.user]);
useEffect(() => {
if (!mounted || !auth.user || hasRouteAccess) return;
alert("접근 권한이 없습니다.");
router.replace("/");
}, [auth.user, hasRouteAccess, mounted, router]);
useEffect(() => {
if (!isSelectedProjectHydrated) return;
if (!hasRouteAccess) return;
if (!isMain && isProjectMenu && !selectedProject) {
alert("선택된 프로젝트가 없습니다.");
router.replace("/");
}
}, [hasRouteAccess, isMain, isProjectMenu, isSelectedProjectHydrated, router, selectedProject]);
if (mounted && auth.user && !hasRouteAccess) return null;
return (
<KriMainLayout
fullHeight={false}
className={cn("bg-gray-50", "h-screen overflow-hidden")}
bodyClassName={cn(!isMain && isContactPage && "min-h-0")}
mainClassName={cn("p-4", "min-h-0")}
mainStyle={{ fontSize: `var(--content-font-size, ${initialFontSize}px)` }}
sidebarOpen={!isMain && !isContactPage && menuOpen}
onSidebarOpenChange={setMenuOpen}
header={
<AppHeader
isMain={isMain}
isContactPage={isContactPage}
menuOpen={menuOpen}
activeTopId={activeTop.id}
topMenus={visibleTopMenus}
isViewProjectTitle={isViewProjectTitle}
projectName={selectedProject?.prjctName}
userInfo={auth.user ?? undefined}
fontSize={fontSize}
onToggleMenu={() => setMenuOpen((prev) => !prev)}
onNavigate={movePage}
decreaseFontSize={decreaseFontSize}
increaseFontSize={increaseFontSize}
onOpenReserveSearch={() => showDialog("reserveSearchDialog")}
/>
}
sidebar={
!isMain && !isContactPage ? (
<AppSidebar
isProjectMenu={isProjectMenu}
sideMenus={sideMenus}
isOpen={menuOpen}
pathname={pathname}
openMenus={openMenus}
onOpenMenusChange={setOpenMenus}
onNavigate={movePage}
/>
) : undefined
}
>
{children}
{mounted && auth.user && <ListJobWatcher userId={auth.user.userId} prjctIdx={selectedProject?.prjctIdx ?? 0} />}
<ReserveSearchDialog />
</KriMainLayout>
);
}

View File

@@ -0,0 +1,10 @@
import { KriPageTitle } from "@/components/layout/KriPageTitle";
interface AppPageTitleProps {
titleText: string;
}
export default function AppPageTitle({ titleText }: AppPageTitleProps) {
return <KriPageTitle title={titleText} />;
}

View File

@@ -0,0 +1,50 @@
"use client";
import { KriSidebar } from "@/components/layout/KriSidebar";
import { AppSidebarProjectSearch } from "@/components/app-shell/AppSidebarProjectSearch";
import type { SideMenuItem } from "@/config/menu.types";
interface AppSidebarProps {
isProjectMenu: boolean;
sideMenus: SideMenuItem[];
isOpen: boolean;
pathname: string;
openMenus: Record<string, boolean>;
onOpenMenusChange: (openMenus: Record<string, boolean>) => void;
onNavigate: (path: string) => void;
}
export function AppSidebar({
isProjectMenu,
sideMenus,
isOpen,
pathname,
openMenus,
onOpenMenusChange,
onNavigate,
}: AppSidebarProps) {
const openItemIds = Object.entries(openMenus)
.filter(([, open]) => open)
.map(([id]) => id);
return (
<KriSidebar
items={sideMenus}
isOpen={isOpen}
pathname={pathname}
header={isProjectMenu ? <AppSidebarProjectSearch /> : null}
openItemIds={openItemIds}
onOpenItemIdsChange={(ids) => {
onOpenMenusChange(
sideMenus.reduce<Record<string, boolean>>((acc, item) => {
acc[item.id] = ids.includes(item.id);
return acc;
}, {}),
);
}}
onNavigate={(path) => onNavigate(path)}
className="border-gray-200 bg-white"
/>
);
}

View File

@@ -1,45 +1,32 @@
import {nextApi} from "@/lib/http-client"; import { useDebouncedValue, useMounted } from "@kri/common/hooks";
import {ProjectInfo} from "@/types/project"; import {useMemo, useState} from "react";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {useEffect, useState} from "react";
import {KriSingleSelect} from "@/components/common/KriAutoComplete"; import {KriSingleSelect} from "@/components/common/KriAutoComplete";
import {useSelectedProject} from "@/hooks/useSelectedProject"; import {useSelectedProject} from "@/hooks/useSelectedProject";
import {useLoading} from "@/hooks/useLoading";
import {useMounted} from "@/hooks/useMounted";
import {PROJECT_SEARCH_COUNT} from "@/const/projectConst"; import {PROJECT_SEARCH_COUNT} from "@/const/projectConst";
import {SelectedProject} from "@/store/jotai/project"; import {SelectedProject} from "@/store/jotai/project";
import {useProjectTopQuery} from "@/query/project";
export const SidebarProjectSearch = () =>{ export const AppSidebarProjectSearch = () =>{
const mounted = useMounted(); const mounted = useMounted();
const { selectedProject, setSelectedProject } = useSelectedProject(); const { selectedProject, setSelectedProject } = useSelectedProject();
const [searchKeyword, setSearchKeyword] = useState(selectedProject?.prjctCd || "");
const [searchKeyword, setSearchKeyword] = useState("");
const debouncedKeyword = useDebouncedValue(searchKeyword, 500); const debouncedKeyword = useDebouncedValue(searchKeyword, 500);
const [projectArray, setProjectArray] = useState<SelectedProject[]>([]);
const searchTopProject = async (keyword: string) => { const enabled = mounted && !!selectedProject;
const res = await nextApi.get<ProjectInfo[]>( const topQuery = useProjectTopQuery(PROJECT_SEARCH_COUNT, debouncedKeyword, enabled);
`/project/top/${PROJECT_SEARCH_COUNT}`,
{ query: { keyword } }
);
setProjectArray(res); const projectArray = useMemo(() => {
const data = topQuery.data ?? [];
return selectedProject ? [selectedProject, ...data] : data;
}, [topQuery.data, selectedProject]);
const handleSelectProject = (info: SelectedProject | null) => {
if (!info) return;
setSelectedProject(info);
}; };
const handleSelectProject = (info:SelectedProject|null) => { if (!mounted || !selectedProject) return null;
if(info === null) return;
setSelectedProject(info);
}
useEffect(() => {
if(selectedProject){
const keyword = debouncedKeyword.trim();
searchTopProject(keyword);
}
}, [debouncedKeyword]);
if (!mounted || !selectedProject) return null
return ( return (
<KriSingleSelect <KriSingleSelect
@@ -52,7 +39,6 @@ export const SidebarProjectSearch = () =>{
searchMode="inputOnly" searchMode="inputOnly"
onSearchValueChange={setSearchKeyword} onSearchValueChange={setSearchKeyword}
placeholder="프로젝트 검색..." placeholder="프로젝트 검색..."
spanClassName="content-text-sm"
widthClassName="w-full" widthClassName="w-full"
heightClassName="h-9" heightClassName="h-9"
preventDeselect preventDeselect
@@ -62,4 +48,4 @@ export const SidebarProjectSearch = () =>{
getValue={(item) => String(item.prjctIdx)} getValue={(item) => String(item.prjctIdx)}
/> />
); );
} }

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

@@ -0,0 +1,15 @@
"use client";
import { useAtomValue } from "jotai";
import { KriLoadingOverlay, type KriLoadingOverlayProps } from "@/components/common/KriLoadingOverlay";
import { loadingAtom } from "@/store/jotai/loading";
export type LoadingOverlayAdapterProps = Omit<KriLoadingOverlayProps, "open"> & {
force?: boolean;
};
export function LoadingOverlayAdapter({ force = false, ...props }: LoadingOverlayAdapterProps) {
const open = useAtomValue(loadingAtom);
return <KriLoadingOverlay open={force || open} {...props} />;
}

View File

@@ -0,0 +1,6 @@
export { AppHeader } from "./AppHeader";
export { AppSidebar } from "./AppSidebar";
export { LoadingOverlayAdapter } from "./LoadingOverlayAdapter";
export { default as AppMainLayout } from "./AppMainLayout";
export { default as AppPageTitle } from "./AppPageTitle";

View File

@@ -0,0 +1,200 @@
'use client'
import { useMemo, useState } from 'react'
import { useCmpnListQuery } from '@/query/cmpn'
import { useFieldworkUsersQuery } from '@/query/user'
import {
useAssignedCmpnIdsQuery,
useAssignedCmpnSummaryQuery,
useAssignedFieldworkIdsQuery,
useAssignedFieldworkSummaryQuery,
} from '@/query/project'
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
import { ListHeaderAssignConst } from '@/const/listConst'
import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from '@/const/userConst'
import { isInternalManager } from '@/utils/userRole'
import type { ListHeaderAssignType } from '@/types/list'
export type AssignTargetListProps = {
prjctIdx: number
enabled: boolean
assignType: ListHeaderAssignType
userRole: number
selectedId?: string
onSelect: (id: string) => void
}
export type AssignTargetRow = {
id: string
name: string
}
export type UseAssignTargetRowsArgs = {
prjctIdx: number
enabled: boolean
assignType: ListHeaderAssignType
}
export function useAssignTargetRows({ prjctIdx, enabled, assignType }: UseAssignTargetRowsArgs): AssignTargetRow[] {
const isOutsource = assignType === ListHeaderAssignConst.OUTSOURCE
const assignedCmpnIdsQuery = useAssignedCmpnIdsQuery(prjctIdx, enabled && isOutsource)
const cmpnListQuery = useCmpnListQuery()
const assignedFieldworkIdsQuery = useAssignedFieldworkIdsQuery(prjctIdx, enabled && !isOutsource)
const fieldworkUsersQuery = useFieldworkUsersQuery(enabled && !isOutsource)
return useMemo<AssignTargetRow[]>(() => {
if (isOutsource) {
const assignedIds = new Set(assignedCmpnIdsQuery.data ?? [])
return (cmpnListQuery.data ?? [])
.filter((cmpn) => assignedIds.has(cmpn.cmpnId))
.map((cmpn) => ({ id: cmpn.cmpnId, name: cmpn.cmpnAlias || cmpn.cmpnId }))
}
const targetRole =
assignType === ListHeaderAssignConst.CONTACT_INTERVIEWER ? CONTACT_INTERVIEWER_ROLE : FIELD_INTERVIEWER_ROLE
const assignedIds = new Set(assignedFieldworkIdsQuery.data ?? [])
return (fieldworkUsersQuery.data ?? [])
.filter((user) => assignedIds.has(user.userId) && user.userRole === targetRole)
.map((user) => ({ id: user.userId, name: user.userName }))
}, [
assignType,
isOutsource,
assignedCmpnIdsQuery.data,
cmpnListQuery.data,
assignedFieldworkIdsQuery.data,
fieldworkUsersQuery.data,
])
}
type AssignSummaryRow = {
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 (
<div className="flex h-[78vh] flex-col border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
{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">
<colgroup>
<col className="w-20" />
<col />
{showCmpnColumn ? <col className="w-20" /> : null}
<col className="w-14" />
</colgroup>
<thead className="bg-primary text-white sticky top-0">
<tr>
<th className="p-2 text-left text-base font-medium">ID</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>
</thead>
<tbody>
{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
key={row.id}
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
selectedId === row.id ? 'bg-accent' : ''
}`}
onClick={() => onSelect(row.id)}
>
<td className="p-2 text-base truncate">{row.id}</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>
))
)}
</tbody>
</table>
</div>
</div>
)
}
export default AssignTargetList

View File

@@ -0,0 +1,147 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import type { ComponentType, CSSProperties } from 'react'
import type { EChartsOption } from 'echarts'
import { CHART_HEIGHTS } from './chart.config'
import { useResizeKey } from './useResizeKey'
type EChartsSeries = NonNullable<EChartsOption['series']>
type ReactEChartsProps = {
option: EChartsOption
className?: string
style?: CSSProperties
notMerge?: boolean
lazyUpdate?: boolean
onEvents?: Record<string, (params: unknown) => void>
}
export type BaseEChartProps = {
option: EChartsOption
height?: number | string
className?: string
contentClassName?: string
chartClassName?: string
style?: CSSProperties
contentStyle?: CSSProperties
chartStyle?: CSSProperties
notMerge?: boolean
lazyUpdate?: boolean
onEvents?: Record<string, (params: unknown) => void>
resizeDebounceMs?: number
normalizeValues?: boolean
decimalPlaces?: number
}
const roundNumber = (value: number, decimalPlaces: number) => {
const factor = 10 ** decimalPlaces
return Math.round((value + Number.EPSILON) * factor) / factor
}
const normalizeDataValue = (value: unknown, decimalPlaces: number): unknown => {
if (typeof value === 'number') {
return roundNumber(value, decimalPlaces)
}
if (Array.isArray(value)) {
return value.map((item) => normalizeDataValue(item, decimalPlaces))
}
if (value && typeof value === 'object' && 'value' in value) {
const dataItem = value as Record<string, unknown>
return {
...dataItem,
value: normalizeDataValue(dataItem.value, decimalPlaces),
}
}
return value
}
const normalizeSeries = (
series: EChartsOption['series'] | undefined,
decimalPlaces: number,
): EChartsOption['series'] => {
if (!series) return series
const normalizeOne = (seriesOption: EChartsSeries): EChartsSeries => {
const candidate = seriesOption as Record<string, unknown>
const data = candidate.data
if (!Array.isArray(data)) {
return seriesOption
}
return {
...candidate,
data: data.map((value) => normalizeDataValue(value, decimalPlaces)),
} as EChartsSeries
}
return (Array.isArray(series) ? series.map((item) => normalizeOne(item as EChartsSeries)) : normalizeOne(series)) as EChartsOption['series']
}
export function BaseEChart({
option,
height = CHART_HEIGHTS.DEFAULT,
className,
contentClassName,
chartClassName,
style,
contentStyle,
chartStyle,
notMerge = true,
lazyUpdate = false,
onEvents,
resizeDebounceMs = 150,
normalizeValues = true,
decimalPlaces = 2,
}: BaseEChartProps) {
const resizeKey = useResizeKey(resizeDebounceMs)
const [ReactECharts, setReactECharts] = useState<ComponentType<ReactEChartsProps> | null>(null)
useEffect(() => {
let cancelled = false
void import('echarts-for-react').then((module) => {
if (!cancelled) {
setReactECharts(() => module.default as ComponentType<ReactEChartsProps>)
}
})
return () => {
cancelled = true
}
}, [])
const normalizedOption = useMemo<EChartsOption>(() => {
if (!normalizeValues) return option
return {
...option,
series: normalizeSeries(option.series, decimalPlaces),
}
}, [decimalPlaces, normalizeValues, option])
return (
<div className={className} style={{ display: 'flex', flexDirection: 'column', height, ...style }}>
<div className={contentClassName} style={{ flex: 1, minHeight: 0, ...contentStyle }}>
{ReactECharts ? (
<ReactECharts
key={resizeKey}
option={normalizedOption}
className={chartClassName}
style={{ width: '100%', height: '100%', ...chartStyle }}
notMerge={notMerge}
lazyUpdate={lazyUpdate}
onEvents={onEvents}
/>
) : null}
</div>
</div>
)
}
export default BaseEChart

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