Compare commits

...

54 Commits

Author SHA1 Message Date
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
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
606b6e30d0 261112_02_ENH: CTI 통화 이력 복구·재시도 로직 제거 및 시작·종료 저장 단일 요청으로 간소화 2026-11-12 14:01:28 +09:00
4daf2daf9c 261112_01_FIX: CTI 종료 이력 저장 404 시 재시도 중단 및 오류 팝업 미노출 2026-11-12 12:07:13 +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
d595ea8b8c 261105_02_ENH: 문자·이메일·알림톡 예약 발송 시 과거 일시 선택 차단 2026-11-05 12:36:08 +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
dd4fc8f230 261103_03_ENH: 공유 인증 사용자 정보 동기화 및 프로젝트 접근 전환 개선 2026-11-03 15:11:33 +09:00
7f9cbe4f09 261103_02_FIX: 다른 서비스와 도메인 인증 겹치지 않도록 키변경 2026-11-03 10:48:30 +09:00
d91fc8f5a8 261103_01_FIX: KriAutoComplete 기본 검색을 contains 방식으로 변경 2026-11-03 08:37:04 +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
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
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
81 changed files with 4662 additions and 1553 deletions

View File

@@ -1,9 +1,9 @@
NEXT_PUBLIC_ENV=dev NEXT_PUBLIC_ENV=dev
NEXT_PUBLIC_API_BASE=https://test-contact.kric.com/api NEXT_PUBLIC_API_BASE=https://test-contact.kric.com/api
NEXT_PUBLIC_KART_URL=https://test-kart.kric.com
ENV=dev ENV=dev
CONTACT_SERVER=http://127.0.0.1:4001 CONTACT_SERVER=http://127.0.0.1:4001
API_CONTACT_SERVER=http://127.0.0.1:4001/api/v1 API_CONTACT_SERVER=http://127.0.0.1:4001/api/v1
API_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,9 +1,9 @@
NEXT_PUBLIC_ENV=local NEXT_PUBLIC_ENV=local
NEXT_PUBLIC_API_BASE=http://localhost:4000/api NEXT_PUBLIC_API_BASE=http://localhost:4000/api
NEXT_PUBLIC_KART_URL=https://test-kart.kric.com
ENV=local ENV=local
CONTACT_SERVER=http://localhost:4001 CONTACT_SERVER=http://localhost:4001
API_CONTACT_SERVER=http://localhost:4001/api/v1 API_CONTACT_SERVER=http://localhost:4001/api/v1
API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1 API_INTRANET_SERVER=https://intranet-ext.kric.com/api/v1
API_KART_SERVER=https://rapi.kric.com/api/v1 AUTH_COOKIE_DOMAIN=
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230

View File

@@ -1,9 +1,9 @@
NEXT_PUBLIC_ENV=prod NEXT_PUBLIC_ENV=prod
NEXT_PUBLIC_API_BASE=https://contact.kric.com/api NEXT_PUBLIC_API_BASE=https://contact.kric.com/api
NEXT_PUBLIC_KART_URL=https://kart.kric.com
ENV=prod ENV=prod
CONTACT_SERVER=http://127.0.0.1:4001 CONTACT_SERVER=http://127.0.0.1:4001
API_CONTACT_SERVER=http://127.0.0.1:4001/api/v1 API_CONTACT_SERVER=http://127.0.0.1:4001/api/v1
API_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

@@ -229,6 +229,7 @@ When implementation is complete, report in Korean:
- Treat the current React version, component style, state management, routing, styling, and test approach as authoritative. - 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. - Do not perform unrelated class-to-hook, JavaScript-to-TypeScript, state-library, styling-system, or React-to-Next.js migrations.
- Keep components focused and follow the repository's established split between presentation, state, data access, and side effects. - Keep 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. - 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. - 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. - Preserve public component props and shared UI contracts unless a coordinated breaking change is explicitly approved.
@@ -265,6 +266,35 @@ Before each related task, read the current contents of every matching reference,
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. 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 ## KriUiRegistry Consumer Contract
When implementing or changing frontend UI, use this order: When implementing or changing frontend UI, use this order:
@@ -274,6 +304,28 @@ When implementing or changing frontend UI, use this order:
3. Otherwise, prefer a suitable shadcn/ui component. 3. Otherwise, prefer a suitable shadcn/ui component.
4. Create a custom component only when the preceding options cannot meet the requirement safely. 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 ### Required Shared References
Before each related task, read the current contents of every matching reference, even if it was read earlier in the session. Before each related task, read the current contents of every matching reference, even if it was read earlier in the session.

1285
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

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

View File

@@ -17,6 +17,7 @@ import { useProjectInfoQuery, useResultCodesQuery } from '@/query/project'
import { useListHeaderQuery } from '@/query/list' import { useListHeaderQuery } from '@/query/list'
import { ListJobPageQueryContext, useSubmitListJob } from '@/query/list-job' import { ListJobPageQueryContext, useSubmitListJob } from '@/query/list-job'
import { ListJobGatePanel } from '@/components/list/ListJobGate' import { ListJobGatePanel } from '@/components/list/ListJobGate'
import { ListJobRefreshNotice } from '@/components/list/ListJobRefreshNotice'
import { useListJobPageMonitor } from '@/hooks/useListJobPageMonitor' import { useListJobPageMonitor } from '@/hooks/useListJobPageMonitor'
import { ListHeaderAssignConst, LIST_HEADER_TYPE_LABEL } from '@/const/listConst' import { ListHeaderAssignConst, LIST_HEADER_TYPE_LABEL } from '@/const/listConst'
import { createEmptyListFilter, type ListFilter, type ListHeaderAssignType, type listHeader } from '@/types/list' import { createEmptyListFilter, type ListFilter, type ListHeaderAssignType, type listHeader } from '@/types/list'
@@ -60,7 +61,11 @@ const ListAssignPage = () => {
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled) const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled)
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled) const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
const assignMutation = useSubmitListJob(prjctIdx) const assignMutation = useSubmitListJob(prjctIdx)
const { gate: assignGate, dataRevision } = useListJobPageMonitor(prjctIdx, 'LIST_ASSIGN', enabled) const pageMonitor = useListJobPageMonitor(prjctIdx, 'LIST_ASSIGN', enabled, {
hasSelection: !!selectedAssignId,
isSubmitting: assignMutation.isPending,
})
const { gate: assignGate, dataRevision } = pageMonitor
const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom) const [openRequest, setOpenRequest] = useAtom(listJobOpenRequestAtom)
const assignTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType: effectiveAssignType }) const assignTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType: effectiveAssignType })
@@ -200,6 +205,7 @@ const ListAssignPage = () => {
<div className="min-w-0 flex-1 space-y-2"> <div className="min-w-0 flex-1 space-y-2">
<ListJobGatePanel gate={assignGate} /> <ListJobGatePanel gate={assignGate} />
<ListJobRefreshNotice monitor={pageMonitor} />
<ListSearchTable <ListSearchTable
dataRevision={dataRevision} dataRevision={dataRevision}
prjctIdx={prjctIdx} prjctIdx={prjctIdx}

View File

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

View File

@@ -1,6 +1,6 @@
'use client' 'use client'
import { Suspense, useEffect, useMemo, useState } from "react"; import { Suspense, useEffect, useMemo, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation"; import { useRouter, useSearchParams } from "next/navigation";
import { ArrowLeft, RefreshCw } from "lucide-react"; import { ArrowLeft, RefreshCw } from "lucide-react";
import { useMounted } from "@kri/common/hooks"; import { useMounted } from "@kri/common/hooks";
@@ -37,6 +37,7 @@ const ListContactPageContent = () => {
const userRole = auth?.user?.userRole ?? 0; const userRole = auth?.user?.userRole ?? 0;
const ctiCallPhase = useCtiCallPhase(); const ctiCallPhase = useCtiCallPhase();
const shouldBlockNavigation = CTI_CALL_PHASE.includes(ctiCallPhase); const shouldBlockNavigation = CTI_CALL_PHASE.includes(ctiCallPhase);
const hasObservedCall = useRef(false);
const queriesEnabled = mounted && prjctIdx > 0; const queriesEnabled = mounted && prjctIdx > 0;
const enabled = queriesEnabled && !!sid; const enabled = queriesEnabled && !!sid;
@@ -74,10 +75,12 @@ const ListContactPageContent = () => {
const hasGuardEntry = window.history.state?.[CALL_NAVIGATION_GUARD_KEY] === true; const hasGuardEntry = window.history.state?.[CALL_NAVIGATION_GUARD_KEY] === true;
if (!shouldBlockNavigation) { if (!shouldBlockNavigation) {
if (hasGuardEntry) window.history.back(); if (hasGuardEntry && hasObservedCall.current) window.history.back();
hasObservedCall.current = false;
return; return;
} }
hasObservedCall.current = true;
let isRestoringHistory = false; let isRestoringHistory = false;
if (!hasGuardEntry) { if (!hasGuardEntry) {

View File

@@ -25,6 +25,7 @@ import {
} from '@/query/list' } from '@/query/list'
import { ListJobPageQueryContext, useMyActiveListJobs, useSubmitListJob } from '@/query/list-job' import { ListJobPageQueryContext, useMyActiveListJobs, useSubmitListJob } from '@/query/list-job'
import { ListJobGatePanel } from '@/components/list/ListJobGate' import { ListJobGatePanel } from '@/components/list/ListJobGate'
import { ListJobRefreshNotice } from '@/components/list/ListJobRefreshNotice'
import { useListJobPageMonitor } from '@/hooks/useListJobPageMonitor' import { useListJobPageMonitor } from '@/hooks/useListJobPageMonitor'
import { useTrackedListJobs } from '@/store/list-job-tracker' import { useTrackedListJobs } from '@/store/list-job-tracker'
import { isListPageActionBlocked } from '@/utils/listJobAvailability' import { isListPageActionBlocked } from '@/utils/listJobAvailability'
@@ -43,8 +44,8 @@ import {
type ListFilterTarget, type ListFilterTarget,
type listHeader, type listHeader,
type ListSearchUiState, type ListSearchUiState,
ListResetMode, type ListResetRequest,
type ListResetScope, type ListResetSelection,
type ListUploadRequest, type ListUploadRequest,
} from '@/types/list' } from '@/types/list'
import { type ResultCode, ResultCodeType } from '@/types/project' import { type ResultCode, ResultCodeType } from '@/types/project'
@@ -115,7 +116,8 @@ const ListManagePage = () => {
const canManageList = isManager(userRole); const canManageList = isManager(userRole);
// 리스트 초기화/헤더 관리/업로드는 내부 관리자 전용 — 외주사 계정에는 노출되면 안 됨. // 리스트 초기화/헤더 관리/업로드는 내부 관리자 전용 — 외주사 계정에는 노출되면 안 됨.
const isInternal = isInternalManager(userRole); const isInternal = isInternalManager(userRole);
const { gate: pageGate, dataRevision } = useListJobPageMonitor(prjctIdx, 'LIST_RESET', enabled) const pageMonitor = useListJobPageMonitor(prjctIdx, 'LIST_RESET', enabled, { hasSelection: selectedRows.length > 0 })
const { gate: pageGate, dataRevision } = pageMonitor
const trackedJobs = useTrackedListJobs() const trackedJobs = useTrackedListJobs()
useEffect(() => { useEffect(() => {
@@ -262,11 +264,12 @@ const ListManagePage = () => {
showDialog('messageSendDialog') showDialog('messageSendDialog')
} }
const handleResetConfirm = async (payload: { target: ListFilterTarget; scope: ListResetScope }) => { const handleResetConfirm = async (payload: { target: ListFilterTarget; selection: ListResetSelection }) => {
await submitJob.mutateAsync({ jobType: 'LIST_RESET', path: 'reset', body: { const body: ListResetRequest = {
resetMode: payload.scope === 'result-and-history' ? ListResetMode.HIST : ListResetMode.ALL, ...payload.selection,
listFilter: buildTargetFilter(payload.target), listFilter: buildTargetFilter(payload.target),
} }) }
await submitJob.mutateAsync({ jobType: 'LIST_RESET', path: 'reset', body })
} }
const handleUploadConfirm = async (file: File, request: ListUploadRequest) => { const handleUploadConfirm = async (file: File, request: ListUploadRequest) => {
@@ -321,6 +324,7 @@ const ListManagePage = () => {
<ListJobPageQueryContext.Provider value="LIST_RESET"> <ListJobPageQueryContext.Provider value="LIST_RESET">
<div className="space-y-6 text-sm"> <div className="space-y-6 text-sm">
<ListJobGatePanel gate={pageGate} showCurrentJob={false} /> <ListJobGatePanel gate={pageGate} showCurrentJob={false} />
<ListJobRefreshNotice monitor={pageMonitor} clearsSelection={selectedRows.length > 0} />
{canManageList && ( {canManageList && (
<ListManageActions <ListManageActions
showAdminActions={isInternal} showAdminActions={isInternal}
@@ -372,7 +376,9 @@ const ListManagePage = () => {
{isInternal && ( {isInternal && (
<> <>
<ListResetDialog <ListResetDialog
key={prjctIdx}
prjctIdx={prjctIdx} prjctIdx={prjctIdx}
surveys={projectInfoQuery.data?.surveys}
selectedSids={selectedSidSet} selectedSids={selectedSidSet}
filterSummary={filterSummary} filterSummary={filterSummary}
onConfirm={handleResetConfirm} onConfirm={handleResetConfirm}

View File

@@ -11,11 +11,12 @@ import { clientEnv } from "@/lib/env.client";
import { MessageType } from "@kri/common/noti-hub"; import { MessageType } from "@kri/common/noti-hub";
import type { SendResultSummaryResponse } from "@kri/common/noti-hub"; import type { SendResultSummaryResponse } from "@kri/common/noti-hub";
const SEND_TYPE_ORDER = [MessageType.SMS, MessageType.LMS_MMS, MessageType.EMAIL, MessageType.KKO] as const; const SEND_TYPE_ORDER = [MessageType.SMS, MessageType.LMS, MessageType.MMS, MessageType.EMAIL, MessageType.KKO] as const;
const SEND_TYPE_LABEL: Record<number, string> = { const SEND_TYPE_LABEL: Record<number, string> = {
[MessageType.SMS]: "단문", [MessageType.SMS]: "단문",
[MessageType.LMS_MMS]: "장문", [MessageType.LMS]: "장문",
[MessageType.MMS]: "첨부 문자",
[MessageType.EMAIL]: "메일", [MessageType.EMAIL]: "메일",
[MessageType.KKO]: "알림톡", [MessageType.KKO]: "알림톡",
}; };
@@ -28,6 +29,7 @@ type SummaryRow = {
successCount: number; successCount: number;
failCount: number; failCount: number;
standByCount: number; standByCount: number;
canceledCount: number;
}; };
const sum = (list: SendResultSummaryResponse[], field: keyof SendResultSummaryResponse) => const sum = (list: SendResultSummaryResponse[], field: keyof SendResultSummaryResponse) =>
@@ -44,6 +46,7 @@ const buildRows = (data: SendResultSummaryResponse[]): SummaryRow[] =>
successCount: sum(matched, "successCount"), successCount: sum(matched, "successCount"),
failCount: sum(matched, "failCount"), failCount: sum(matched, "failCount"),
standByCount: sum(matched, "standByCount"), standByCount: sum(matched, "standByCount"),
canceledCount: sum(matched, "canceledCount"),
}; };
}); });
@@ -80,6 +83,7 @@ const MessageProgressPage = () => {
successCount: rows.reduce((acc, row) => acc + row.successCount, 0), successCount: rows.reduce((acc, row) => acc + row.successCount, 0),
failCount: rows.reduce((acc, row) => acc + row.failCount, 0), failCount: rows.reduce((acc, row) => acc + row.failCount, 0),
standByCount: rows.reduce((acc, row) => acc + row.standByCount, 0), standByCount: rows.reduce((acc, row) => acc + row.standByCount, 0),
canceledCount: rows.reduce((acc, row) => acc + row.canceledCount, 0),
}), }),
[rows], [rows],
); );
@@ -103,6 +107,7 @@ const MessageProgressPage = () => {
<th className="h-10 px-3 text-center font-semibold border-b">성공</th> <th className="h-10 px-3 text-center font-semibold border-b">성공</th>
<th className="h-10 px-3 text-center font-semibold border-b">실패</th> <th className="h-10 px-3 text-center font-semibold border-b">실패</th>
<th className="h-10 px-3 text-center font-semibold border-b">발송중</th> <th className="h-10 px-3 text-center font-semibold border-b">발송중</th>
<th className="h-10 px-3 text-center font-semibold border-b">취소</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -115,6 +120,7 @@ const MessageProgressPage = () => {
<td className="h-10 px-3 text-center">{caseUnit(row.successCount)}</td> <td className="h-10 px-3 text-center">{caseUnit(row.successCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(row.failCount)}</td> <td className="h-10 px-3 text-center">{caseUnit(row.failCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(row.standByCount)}</td> <td className="h-10 px-3 text-center">{caseUnit(row.standByCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(row.canceledCount)}</td>
</tr> </tr>
))} ))}
<tr className="bg-gray-50 font-semibold"> <tr className="bg-gray-50 font-semibold">
@@ -124,6 +130,7 @@ const MessageProgressPage = () => {
<td className="h-10 px-3 text-center">{caseUnit(total.successCount)}</td> <td className="h-10 px-3 text-center">{caseUnit(total.successCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(total.failCount)}</td> <td className="h-10 px-3 text-center">{caseUnit(total.failCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(total.standByCount)}</td> <td className="h-10 px-3 text-center">{caseUnit(total.standByCount)}</td>
<td className="h-10 px-3 text-center">{caseUnit(total.canceledCount)}</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>

View File

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

View File

@@ -279,6 +279,14 @@ const SurveyCard = ({ survey, index, itrntPrjctCd, userTeam, invalidField, onReg
heightClassName="h-9" heightClassName="h-9"
widthClassName="w-full" widthClassName="w-full"
/> />
{kartProjectListQuery.isError && (
<div role="alert" className="flex items-center gap-2 text-destructive">
<span>프로젝트 목록을 불러오지 못했습니다.</span>
<Button type="button" variant="outline" size="sm" onClick={() => void kartProjectListQuery.refetch()}>
다시 시도
</Button>
</div>
)}
</div> </div>
)} )}

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

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

View File

@@ -2,25 +2,7 @@ import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common"; import {RouteContext} from "@/types/common";
import {createContactApi} from "@/lib/http-server"; import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@kri/common/http"; import {errorToResponse} from "@kri/common/http";
import type {ListCallHist, ListCallHistSession} from "@/types/list"; import type {ListCallHist} from "@/types/list";
export const GET = async (_req: NextRequest, context: RouteContext) => {
try {
const { slug = [] } = await context.params;
const [action, agentSessionId] = slug;
if (action !== "session" || !agentSessionId) {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
const contactApi = await createContactApi();
const result = await contactApi.get<ListCallHistSession>(
`/list-call-hist/session/${encodeURIComponent(agentSessionId)}`,
);
return NextResponse.json(result, { status: 200 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
export const PUT = async (req: NextRequest, context: RouteContext) => { export const PUT = async (req: NextRequest, context: RouteContext) => {
try { try {
@@ -45,21 +27,3 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
return errorToResponse(error); return errorToResponse(error);
} }
}; };
export const PATCH = async (_req: NextRequest, context: RouteContext) => {
try {
const { slug = [] } = await context.params;
const [action, agentSessionId] = slug;
if (action !== "hangup" || !agentSessionId) {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
const contactApi = await createContactApi();
const result = await contactApi.patch<boolean>(
`/list-call-hist/hangup/${encodeURIComponent(agentSessionId)}`,
);
return NextResponse.json(result, { status: 200 });
} catch (error: unknown) {
return errorToResponse(error);
}
};

View File

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

View File

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

View File

@@ -2,17 +2,48 @@ import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common"; import {RouteContext} from "@/types/common";
import {createContactApi} from "@/lib/http-server"; import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@kri/common/http"; import {errorToResponse} from "@kri/common/http";
import type {SendCancelResponse} from "@kri/common/noti-hub";
import type {MessageSendChannel, SendSingleResponse} from "@/types/message"; import type {MessageSendChannel, SendSingleResponse} from "@/types/message";
const isChannel = (value: string): value is MessageSendChannel => const isChannel = (value: string): value is MessageSendChannel =>
value === "sms" || value === "email" || value === "kko"; 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) => { export const POST = async (req: NextRequest, context: RouteContext) => {
try { try {
const {slug = []} = await context.params; const {slug = []} = await context.params;
const [channel, action, prjctIdx] = slug; const [channel, action, prjctIdx] = slug;
const contactApi = await createContactApi(); 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) { if (!isChannel(channel) || !prjctIdx) {
return NextResponse.json({message: "Not found"}, {status: 404}); return NextResponse.json({message: "Not found"}, {status: 404});
} }

View File

@@ -2,6 +2,7 @@
import {RouteContext} from "@/types/common"; import {RouteContext} from "@/types/common";
import {createContactApi} from "@/lib/http-server"; import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@kri/common/http"; import {errorToResponse} from "@kri/common/http";
import type { KkoSenderProfile } from "@/types/message";
import type { KkoTemplateDetail, KkoTemplateListResponse, Template, TemplateSummary } from "@kri/common/noti-hub"; import type { KkoTemplateDetail, KkoTemplateListResponse, Template, TemplateSummary } from "@kri/common/noti-hub";
// 외부 알림톡 템플릿 목록·상세 조회. JSON 본문을 contact-back에 그대로 전달한다. // 외부 알림톡 템플릿 목록·상세 조회. JSON 본문을 contact-back에 그대로 전달한다.
@@ -35,6 +36,11 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
const [action] = slug; const [action] = slug;
const contactApi = await createContactApi(); 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"){ if(slug.length === 2 && slug[1] === "attachment"){
const fileName = searchParams.get("fileName"); const fileName = searchParams.get("fileName");
if (!fileName) { if (!fileName) {
@@ -138,3 +144,20 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => {
return errorToResponse(error); return errorToResponse(error);
} }
} }
// 템플릿 삭제. 성공 응답은 빈 body이므로 JSON으로 파싱하지 않는다.
export const DELETE = async (req: NextRequest, context: RouteContext) => {
try{
const {slug = []} = await context.params;
const [tmplatIdx] = slug;
if (slug.length !== 1 || !/^[1-9]\d*$/.test(tmplatIdx)) {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
const contactApi = await createContactApi();
await contactApi.del(`/message-template/${tmplatIdx}`, { expectText: true });
return new NextResponse(null, { status: 204 });
} catch (error: unknown) {
return errorToResponse(error);
}
}

View File

@@ -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

@@ -3,14 +3,15 @@
import * as React from 'react' import * as React from 'react'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import { MultiSelect } from '@/components/common/multi-select' import { MultiSelect } from '@/components/common/multi-select'
import type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select' import type { MultiSelectOption, MultiSelectRef, MultiSelectSearchMatch } from '@/components/common/multi-select'
export type { MultiSelectOption, MultiSelectRef } from '@/components/common/multi-select' export type { MultiSelectOption, MultiSelectRef, MultiSelectSearchMatch } from '@/components/common/multi-select'
export interface KriAutoCompleteBaseProps<T> { export interface KriAutoCompleteBaseProps<T> {
items: T[] items: T[]
searchable?: boolean searchable?: boolean
searchMode?: 'filter' | 'inputOnly' searchMode?: 'filter' | 'inputOnly'
searchMatch?: MultiSelectSearchMatch
defaultSearchValue?: string defaultSearchValue?: string
onSearchValueChange?: (value: string) => void onSearchValueChange?: (value: string) => void
placeholder?: string placeholder?: string
@@ -58,6 +59,7 @@ export function KriMultiSelect<T = unknown>({
onChange, onChange,
searchable = true, searchable = true,
searchMode = 'filter', searchMode = 'filter',
searchMatch = 'contains',
defaultSearchValue = '', defaultSearchValue = '',
onSearchValueChange, onSearchValueChange,
maxCount = 1, maxCount = 1,
@@ -100,6 +102,7 @@ export function KriMultiSelect<T = unknown>({
badgeLabelClassName={badgeLabelClassName} badgeLabelClassName={badgeLabelClassName}
searchable={searchable} searchable={searchable}
searchMode={searchMode} searchMode={searchMode}
searchMatch={searchMatch}
defaultSearchValue={defaultSearchValue} defaultSearchValue={defaultSearchValue}
onSearchValueChange={onSearchValueChange} onSearchValueChange={onSearchValueChange}
maxCount={maxCount} maxCount={maxCount}
@@ -135,6 +138,7 @@ function KriSingleSelectInner<T>(
onChange, onChange,
searchable = true, searchable = true,
searchMode = 'filter', searchMode = 'filter',
searchMatch = 'contains',
defaultSearchValue = '', defaultSearchValue = '',
onSearchValueChange, onSearchValueChange,
placeholder = '옵션을 선택하세요', placeholder = '옵션을 선택하세요',
@@ -216,6 +220,7 @@ function KriSingleSelectInner<T>(
badgeLabelClassName={badgeLabelClassName ?? 'min-w-0 flex-1'} badgeLabelClassName={badgeLabelClassName ?? 'min-w-0 flex-1'}
searchable={searchable} searchable={searchable}
searchMode={searchMode} searchMode={searchMode}
searchMatch={searchMatch}
defaultSearchValue={defaultSearchValue} defaultSearchValue={defaultSearchValue}
onSearchValueChange={onSearchValueChange} onSearchValueChange={onSearchValueChange}
preventDeselect={preventDeselect} preventDeselect={preventDeselect}

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,7 @@
'use client' 'use client'
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
import { RotateCcw } from 'lucide-react'
import { KriDialog } from '@/components/common/KriDialog' import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
@@ -107,6 +108,18 @@ const ListFilterDialog = ({
[rows, headerOptions], [rows, headerOptions],
) )
// 잠긴 헤더는 조회 조건에 쓰이지 않으므로 초기화 필요 여부 판단에서 제외한다.
const isResettable = rows.some((row) => {
if (isDisabledHeader(row.headerId)) return false
const defaultOperator = getHeaderOption(row.headerId)?.defaultOperator ?? 'eq'
return row.operator !== defaultOperator || row.textValue !== '' || row.multiValues.length > 0
})
// 다이얼로그 내 입력만 기본값으로 되돌린다. 실제 반영은 "적용"을 눌러야 이뤄진다.
const handleReset = () => {
setRows(headerOptions.map((option) => createFilterRow(option.id, headerOptions)))
}
const handleConfirm = async () => { const handleConfirm = async () => {
setSubmitting(true) setSubmitting(true)
try { try {
@@ -138,7 +151,20 @@ const ListFilterDialog = ({
<div className="grid h-11 grid-cols-[1fr_140px_1.4fr] items-center border-b bg-muted px-4 text-sm font-semibold"> <div className="grid h-11 grid-cols-[1fr_140px_1.4fr] items-center border-b bg-muted px-4 text-sm font-semibold">
<span>헤더</span> <span>헤더</span>
<span>비교 연산자</span> <span>비교 연산자</span>
<span>값</span> <div className="flex items-center justify-between gap-2">
<span>값</span>
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 text-muted-foreground"
onClick={handleReset}
disabled={submitting || !isResettable}
>
<RotateCcw className="size-3.5" />
초기화
</Button>
</div>
</div> </div>
<div className="max-h-170 overflow-auto"> <div className="max-h-170 overflow-auto">

View File

@@ -20,6 +20,7 @@ import {
} from '@dnd-kit/sortable' } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities' import { CSS } from '@dnd-kit/utilities'
import { GripVertical, Plus, Trash2 } from 'lucide-react' import { GripVertical, Plus, Trash2 } from 'lucide-react'
import { KriColorPalette } from '@/components/common/KriColorPalette'
import { KriDialog } from '@/components/common/KriDialog' import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox' import { Checkbox } from '@/components/ui/checkbox'
@@ -29,7 +30,7 @@ import { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog' import type { DialogId } from '@/store/jotai/dialog'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import { listHeader, ListHeaderGrade, ListHeaderType } from '@/types/list' import { listHeader, ListHeaderGrade, ListHeaderType } from '@/types/list'
import { LIST_HEADER_TYPE_LABEL, LIST_HEADER_TYPE_OPTIONS } from '@/const/listConst' import { LIST_HEADER_TYPE_LABEL, LIST_HEADER_TYPE_OPTIONS, ListHeaderConst } from '@/const/listConst'
export type ListHeaderManageDialogProps = { export type ListHeaderManageDialogProps = {
dialogId?: DialogId dialogId?: DialogId
@@ -44,6 +45,7 @@ export type ListHeaderManageDialogProps = {
type ListHeaderRowProps = { type ListHeaderRowProps = {
row: listHeader row: listHeader
activeId: number | null activeId: number | null
onHeaderColorChange: (id: number, color: string | null) => void
onHeaderNameChange: (id: number, listHderNm: string) => void onHeaderNameChange: (id: number, listHderNm: string) => void
onHeaderTypeChange: (id: number, listHderTy: ListHeaderType) => void onHeaderTypeChange: (id: number, listHderTy: ListHeaderType) => void
onFlagChange: (id: number, field: 'useColView' | 'useFilter' | 'useIntrvwerView' | 'useIntrvwerEdit', checked: boolean) => void onFlagChange: (id: number, field: 'useColView' | 'useFilter' | 'useIntrvwerView' | 'useIntrvwerEdit', checked: boolean) => void
@@ -55,13 +57,30 @@ const COMMON_GRADE_ORDER_START = 101
const isCommonGrade = (grade: ListHeaderGrade) => grade === ListHeaderGrade.COMMON const isCommonGrade = (grade: ListHeaderGrade) => grade === ListHeaderGrade.COMMON
const isImmutableGrade = (grade: ListHeaderGrade) => grade === ListHeaderGrade.IMMUTABLE const isImmutableGrade = (grade: ListHeaderGrade) => grade === ListHeaderGrade.IMMUTABLE
const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange, onFlagChange, onDelete }: ListHeaderRowProps) => { const isInterviewerEditDisabled = (row: listHeader) =>
isImmutableGrade(row.listHderGrad) ||
row.listHderTy === ListHeaderConst.IS_USE ||
row.listHderTy === ListHeaderConst.OUTSOURCE ||
row.listHderTy === ListHeaderConst.CONTACT_INTERVIEWER ||
row.listHderTy === ListHeaderConst.FIELD_INTERVIEWER
const ListHeaderRow = ({
row,
activeId,
onHeaderColorChange,
onHeaderNameChange,
onHeaderTypeChange,
onFlagChange,
onDelete,
}: ListHeaderRowProps) => {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: row.listHderId }) const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: row.listHderId })
const canEditName = isCommonGrade(row.listHderGrad) const canEditName = isCommonGrade(row.listHderGrad)
const canEditType = isCommonGrade(row.listHderGrad) const canEditType = isCommonGrade(row.listHderGrad)
const canDelete = isCommonGrade(row.listHderGrad) const canDelete = isCommonGrade(row.listHderGrad)
const canEditFlags = !isImmutableGrade(row.listHderGrad) const canEditFlags = !isImmutableGrade(row.listHderGrad)
const canSort = isCommonGrade(row.listHderGrad) const canSort = isCommonGrade(row.listHderGrad)
// IMMUTABLE 헤더의 색상은 서버가 저장하지 않으므로 선택을 막는다.
const canEditColor = !isImmutableGrade(row.listHderGrad)
const style: CSSProperties = { const style: CSSProperties = {
transform: CSS.Transform.toString(transform), transform: CSS.Transform.toString(transform),
@@ -79,7 +98,7 @@ const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange,
ref={setNodeRef} ref={setNodeRef}
style={style} style={style}
className={cn( className={cn(
'h-12 px-4 border-b last:border-b-0 grid grid-cols-[56px_1fr_150px_96px_96px_110px_110px_88px] items-center gap-2', 'h-12 px-4 border-b last:border-b-0 grid grid-cols-[56px_1fr_150px_120px_96px_96px_110px_110px_88px] items-center gap-2',
(activeId === row.listHderId || isDragging) && 'bg-muted', (activeId === row.listHderId || isDragging) && 'bg-muted',
)} )}
> >
@@ -124,6 +143,12 @@ const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange,
))} ))}
</SelectContent> </SelectContent>
</Select> </Select>
<KriColorPalette
value={row.listHderColor ?? null}
onChange={(color) => onHeaderColorChange(row.listHderId, color)}
disabled={!canEditColor}
aria-label={`${row.listHderNm} 헤더 색상`}
/>
<div className="flex items-center gap-2 justify-center"> <div className="flex items-center gap-2 justify-center">
<Checkbox <Checkbox
id={`header-visible-${row.listHderId}`} id={`header-visible-${row.listHderId}`}
@@ -153,7 +178,7 @@ const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange,
id={`header-intrvwer-edit-${row.listHderId}`} id={`header-intrvwer-edit-${row.listHderId}`}
checked={row.useIntrvwerEdit} checked={row.useIntrvwerEdit}
onCheckedChange={(checked) => onFlagChange(row.listHderId, 'useIntrvwerEdit', checked === true)} onCheckedChange={(checked) => onFlagChange(row.listHderId, 'useIntrvwerEdit', checked === true)}
disabled={!canEditFlags} disabled={isInterviewerEditDisabled(row)}
/> />
</div> </div>
<div className="flex justify-center"> <div className="flex justify-center">
@@ -249,6 +274,16 @@ const ListHeaderManageDialog = ({
) )
} }
const handleHeaderColorChange = (id: number, listHderColor: string | null) => {
setLocalRows((prev) =>
prev.map((row) => {
if (row.listHderId !== id) return row
if (isImmutableGrade(row.listHderGrad)) return row
return { ...row, listHderColor }
}),
)
}
const handleHeaderNameChange = (id: number, listHderNm: string) => { const handleHeaderNameChange = (id: number, listHderNm: string) => {
setLocalRows((prev) => setLocalRows((prev) =>
prev.map((row) => { prev.map((row) => {
@@ -268,6 +303,7 @@ const ListHeaderManageDialog = ({
prev.map((row) => { prev.map((row) => {
if (row.listHderId !== id) return row if (row.listHderId !== id) return row
if (isImmutableGrade(row.listHderGrad)) return row if (isImmutableGrade(row.listHderGrad)) return row
if (field === 'useIntrvwerEdit' && isInterviewerEditDisabled(row)) return row
return { ...row, [field]: checked } return { ...row, [field]: checked }
}), }),
) )
@@ -294,6 +330,7 @@ const ListHeaderManageDialog = ({
useColView: true, useColView: true,
useIntrvwerView: false, useIntrvwerView: false,
useIntrvwerEdit: false, useIntrvwerEdit: false,
listHderColor: null,
} }
return [...prev, nextRow] return [...prev, nextRow]
@@ -303,6 +340,10 @@ const ListHeaderManageDialog = ({
const handleConfirm = async () => { const handleConfirm = async () => {
if (saveDisabled || submitting) return if (saveDisabled || submitting) return
const names = localRows.map((row) => row.listHderNm.trim()) const names = localRows.map((row) => row.listHderNm.trim())
if (names.some((name) => name.length === 0)) {
alert('헤더명을 입력해 주세요.')
return
}
const duplicateNames = [...new Set(names.filter((name, index) => names.indexOf(name) !== index))] const duplicateNames = [...new Set(names.filter((name, index) => names.indexOf(name) !== index))]
if (duplicateNames.length > 0) { if (duplicateNames.length > 0) {
alert(`중복된 헤더명이 있습니다: ${duplicateNames.join(', ')}`) alert(`중복된 헤더명이 있습니다: ${duplicateNames.join(', ')}`)
@@ -336,8 +377,10 @@ const ListHeaderManageDialog = ({
let defaultOrder = 0 let defaultOrder = 0
let commonOrder = COMMON_GRADE_ORDER_START - 1 let commonOrder = COMMON_GRADE_ORDER_START - 1
const orderedRows = localRows.map((row) => { const orderedRows = localRows.map((row) => {
const listHderOrder = isCommonGrade(row.listHderGrad) ? (commonOrder += 1) : (defaultOrder += 1) const isCommon = isCommonGrade(row.listHderGrad)
return { ...row, prjctIdx: row.prjctIdx ?? prjctIdx, listHderOrder } const listHderOrder = isCommon ? (commonOrder += 1) : (defaultOrder += 1)
const listHderNm = isCommon ? row.listHderNm.trim() : row.listHderNm
return { ...row, prjctIdx: row.prjctIdx ?? prjctIdx, listHderOrder, listHderNm }
}) })
await onConfirm(orderedRows) await onConfirm(orderedRows)
handleOpenChange(false) handleOpenChange(false)
@@ -374,10 +417,11 @@ const ListHeaderManageDialog = ({
</div> </div>
<div className="rounded-md border overflow-hidden"> <div className="rounded-md border overflow-hidden">
<div className="h-11 px-4 border-b bg-muted grid grid-cols-[56px_1fr_150px_96px_96px_110px_110px_88px] items-center gap-2 text-sm font-semibold"> <div className="h-11 px-4 border-b bg-muted grid grid-cols-[56px_1fr_150px_120px_96px_96px_110px_110px_88px] items-center gap-2 text-sm font-semibold">
<span>순서</span> <span>순서</span>
<span>헤더명</span> <span>헤더명</span>
<span>헤더 타입</span> <span>헤더 타입</span>
<span>헤더 색상</span>
<span>헤더 노출</span> <span>헤더 노출</span>
<span>필터 사용</span> <span>필터 사용</span>
<span>면접원 노출</span> <span>면접원 노출</span>
@@ -399,6 +443,7 @@ const ListHeaderManageDialog = ({
key={row.listHderId} key={row.listHderId}
row={row} row={row}
activeId={activeId} activeId={activeId}
onHeaderColorChange={handleHeaderColorChange}
onHeaderNameChange={handleHeaderNameChange} onHeaderNameChange={handleHeaderNameChange}
onHeaderTypeChange={handleHeaderTypeChange} onHeaderTypeChange={handleHeaderTypeChange}
onFlagChange={handleFlagChange} onFlagChange={handleFlagChange}

View File

@@ -3,26 +3,44 @@
import { useState } from 'react' import { useState } from 'react'
import { KriDialog } from '@/components/common/KriDialog' import { KriDialog } from '@/components/common/KriDialog'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Label } from '@/components/ui/label' import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { useDialog } from '@/hooks/useDialog' import { useDialog } from '@/hooks/useDialog'
import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate' import { ListJobGatePanel, useListJobGate } from '@/components/list/ListJobGate'
import type { DialogId } from '@/store/jotai/dialog' import type { DialogId } from '@/store/jotai/dialog'
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption' import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
import type { ListFilterTarget, ListResetScope } from '@/types/list' import type { ListFilterTarget, ListResetSelection } from '@/types/list'
import type { ProjectSurvey } from '@/types/project'
export type ListResetDialogProps = { export type ListResetDialogProps = {
prjctIdx: number prjctIdx: number
/** 프로젝트에 연동된 설문 목록. undefined면 아직 불러오지 못한 상태로 보고 초기화를 막는다. */
surveys?: ProjectSurvey[]
dialogId?: DialogId dialogId?: DialogId
open?: boolean open?: boolean
onOpenChange?: (open: boolean) => void onOpenChange?: (open: boolean) => void
selectedSids: string[] selectedSids: string[]
filterSummary?: string[] filterSummary?: string[]
onConfirm: (payload: { target: ListFilterTarget; scope: ListResetScope }) => void | Promise<void> onConfirm: (payload: { target: ListFilterTarget; selection: ListResetSelection }) => void | Promise<void>
}
type ResetSurveyOption = { prjctSurveyIdx: number; surveyName: string }
const toResetSurveyOptions = (surveys: ProjectSurvey[]): ResetSurveyOption[] => {
const seen = new Set<number>()
return [...surveys]
.sort((a, b) => a.surveyOrder - b.surveyOrder)
.flatMap((survey) => {
const id = survey.prjctSurveyIdx
if (id == null || seen.has(id)) return []
seen.add(id)
return [{ prjctSurveyIdx: id, surveyName: survey.surveyName }]
})
} }
const ListResetDialog = ({ const ListResetDialog = ({
prjctIdx, prjctIdx,
surveys,
dialogId = 'listResetDialog', dialogId = 'listResetDialog',
open, open,
onOpenChange, onOpenChange,
@@ -32,12 +50,39 @@ const ListResetDialog = ({
}: ListResetDialogProps) => { }: ListResetDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog() const { isDialogOpen, showDialog, hideDialog } = useDialog()
const [target, setTarget] = useState<ListFilterTarget>('selected') const [target, setTarget] = useState<ListFilterTarget>('selected')
const [scope, setScope] = useState<ListResetScope>('result-and-history') const [resetList, setResetList] = useState(false)
const [resetContactHistory, setResetContactHistory] = useState(false)
const [resetInterviewHistory, setResetInterviewHistory] = useState(false)
const [selectedSurveyIds, setSelectedSurveyIds] = useState<number[]>([])
const [submitting, setSubmitting] = useState(false) const [submitting, setSubmitting] = useState(false)
const resolvedOpen = open ?? isDialogOpen(dialogId) const resolvedOpen = open ?? isDialogOpen(dialogId)
const gate = useListJobGate({ prjctIdx, jobType: 'LIST_RESET', active: resolvedOpen }) const gate = useListJobGate({ prjctIdx, jobType: 'LIST_RESET', active: resolvedOpen })
const surveysReady = surveys !== undefined
const surveyOptions = toResetSurveyOptions(surveys ?? [])
const allSurveyIds = surveyOptions.map((survey) => survey.prjctSurveyIdx)
// 설문 목록이 다시 조회되어 빠진 설문이 있으면 요청에서 제외한다.
const checkedSurveyIds = allSurveyIds.filter((id) => selectedSurveyIds.includes(id))
const hasSelection = resetList || resetContactHistory || resetInterviewHistory || checkedSurveyIds.length > 0
// 리스트 초기화는 모든 이력을 포함해야 하므로 이력을 전부 선택하고 잠근다.
// 해제 시에는 잠금 중 화면에 보이던 전체 선택 상태를 그대로 유지한다(잠금 중 로드된 설문 포함).
const handleResetListChange = (checked: boolean) => {
setResetList(checked)
setResetContactHistory(true)
setResetInterviewHistory(true)
setSelectedSurveyIds(allSurveyIds)
}
const handleSurveyChange = (id: number, checked: boolean) => {
setSelectedSurveyIds((prev) => (checked ? [...prev.filter((v) => v !== id), id] : prev.filter((v) => v !== id)))
}
const buildSelection = (): ListResetSelection => resetList
? { resetList: true, resetContactHistory: true, resetInterviewHistory: true, resetSurveyIds: allSurveyIds }
: { resetList: false, resetContactHistory, resetInterviewHistory, resetSurveyIds: checkedSurveyIds }
const handleOpenChange = (nextOpen: boolean) => { const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen) onOpenChange?.(nextOpen)
if (nextOpen) { if (nextOpen) {
@@ -47,14 +92,33 @@ const ListResetDialog = ({
hideDialog(dialogId) hideDialog(dialogId)
} }
// '새 작업'(완료 확인)을 누르면 이전 작업의 대상·범위를 이어 쓰지 않도록 초기값으로 되돌린다.
const gatePanel = {
...gate,
acknowledge: () => {
gate.acknowledge()
setTarget('selected')
setResetList(false)
setResetContactHistory(false)
setResetInterviewHistory(false)
setSelectedSurveyIds([])
},
}
// 전체 대상은 선택 시점에도 한 번 확인한다. 취소하면 기존 대상을 유지한다.
const handleTargetChange = (next: ListFilterTarget) => {
if (next === 'all' && target !== 'all' && !confirm('전체 대상을 선택하면 프로젝트의 모든 리스트가 초기화 대상이 됩니다. 선택하시겠습니까?')) return
setTarget(next)
}
const handleConfirm = async () => { const handleConfirm = async () => {
if (gate.submitBlocked || submitting) return if (gate.submitBlocked || submitting || !surveysReady || !hasSelection) return
if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return if (!validateApplyFilterTarget(target, { selectedCount: selectedSids.length, filterSummary })) return
if (target === 'all' && !confirm('전체 리스트가 초기화 됩니다. 진행하시겠습니까?')) return if (target === 'all' && !confirm('전체 리스트가 초기화 됩니다. 진행하시겠습니까?')) return
setSubmitting(true) setSubmitting(true)
try { try {
await onConfirm({ target, scope }) await onConfirm({ target, selection: buildSelection() })
} finally { } finally {
setSubmitting(false) setSubmitting(false)
} }
@@ -73,20 +137,25 @@ const ListResetDialog = ({
{gate.hasCurrentJob ? '닫기' : '취소'} {gate.hasCurrentJob ? '닫기' : '취소'}
</Button> </Button>
{!gate.hasCurrentJob && ( {!gate.hasCurrentJob && (
<Button type="button" variant="destructive" onClick={handleConfirm} disabled={submitting || gate.submitBlocked}> <Button
type="button"
variant="destructive"
onClick={handleConfirm}
disabled={submitting || gate.submitBlocked || !surveysReady || !hasSelection}
>
초기화 초기화
</Button> </Button>
)} )}
</> </>
} }
> >
<ListJobGatePanel gate={gate} acknowledgeLabel="새 작업" /> <ListJobGatePanel gate={gatePanel} acknowledgeLabel="새 작업" />
{!gate.hasCurrentJob && <> {!gate.hasCurrentJob && <>
<div className="rounded-md border p-4 space-y-4"> <div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold text-red-600">초기화 대상</p> <p className="text-lg font-semibold text-red-600">초기화 대상</p>
<ApplyFilterOption <ApplyFilterOption
value={target} value={target}
onValueChange={(v) => setTarget(v)} onValueChange={handleTargetChange}
idPrefix="list-reset-target" idPrefix="list-reset-target"
selectedSids={selectedSids} selectedSids={selectedSids}
filterSummary={filterSummary} filterSummary={filterSummary}
@@ -95,16 +164,63 @@ const ListResetDialog = ({
<div className="rounded-md border p-4 space-y-4"> <div className="rounded-md border p-4 space-y-4">
<p className="text-lg font-semibold text-red-600">초기화 범위</p> <p className="text-lg font-semibold text-red-600">초기화 범위</p>
<RadioGroup value={scope} onValueChange={(v) => setScope(v as ListResetScope)} className="space-y-2"> <div className="space-y-3">
<div className="flex items-center gap-2"> <div className="flex flex-wrap items-center gap-x-6 gap-y-2">
<RadioGroupItem value="result-and-history" id="list-reset-scope-result-history" /> <div className="flex items-center gap-2">
<Label className="text-base" htmlFor="list-reset-scope-result-history">결과 + 이력 삭제</Label> <Checkbox
id="list-reset-scope-list"
checked={resetList}
onCheckedChange={(checked) => handleResetListChange(checked === true)}
/>
<Label className="text-base" htmlFor="list-reset-scope-list">리스트</Label>
</div>
<div className="flex items-center gap-2">
<Checkbox
id="list-reset-scope-contact"
checked={resetList || resetContactHistory}
disabled={resetList}
onCheckedChange={(checked) => setResetContactHistory(checked === true)}
/>
<Label className="text-base" htmlFor="list-reset-scope-contact">컨택이력</Label>
</div>
<div className="flex items-center gap-2">
<Checkbox
id="list-reset-scope-interview"
checked={resetList || resetInterviewHistory}
disabled={resetList}
onCheckedChange={(checked) => setResetInterviewHistory(checked === true)}
/>
<Label className="text-base" htmlFor="list-reset-scope-interview">면접이력</Label>
</div>
</div> </div>
<div className="flex items-center gap-2"> {(!surveysReady || surveyOptions.length > 0) && (
<RadioGroupItem value="list-only" id="list-reset-scope-list-only" /> <div className="space-y-2">
<Label className="text-base" htmlFor="list-reset-scope-list-only">결과 + 이력 + 리스트 삭제</Label> <p className="text-sm font-medium text-muted-foreground">설문 상태이력</p>
</div> {!surveysReady && <p className="text-sm text-muted-foreground">설문 목록을 불러오는 중입니다.</p>}
</RadioGroup> <div className="flex flex-wrap items-center gap-x-6 gap-y-2">
{surveyOptions.map((survey) => {
const id = `list-reset-scope-survey-${survey.prjctSurveyIdx}`
return (
<div key={survey.prjctSurveyIdx} className="flex items-center gap-2">
<Checkbox
id={id}
checked={resetList || checkedSurveyIds.includes(survey.prjctSurveyIdx)}
disabled={resetList}
onCheckedChange={(checked) => handleSurveyChange(survey.prjctSurveyIdx, checked === true)}
/>
<Label className="text-base" htmlFor={id}>{survey.surveyName}</Label>
</div>
)
})}
</div>
</div>
)}
</div>
<ul className="list-disc space-y-1 pl-5 text-sm text-muted-foreground">
<li>선택한 이력은 해당 유형의 이력과 최신 상태가 함께 초기화되며, 선택하지 않은 이력은 유지됩니다.</li>
<li>리스트를 선택하면 리스트와 모든 이력이 함께 초기화됩니다.</li>
<li>설문 상태이력 초기화는 외부 설문 시스템의 실제 응답 데이터를 삭제하지 않습니다.</li>
</ul>
</div> </div>
</>} </>}
</KriDialog> </KriDialog>

View File

@@ -203,7 +203,7 @@ const ListUploadDialog = ({
const serverHeader = compareRows[index] const serverHeader = compareRows[index]
// compareRows가 이미 listHderOrder 기준 정렬이라 위치로 순서를 보장한다. listHderOrder 값 자체는 // compareRows가 이미 listHderOrder 기준 정렬이라 위치로 순서를 보장한다. listHderOrder 값 자체는
// COMMON 헤더가 101부터 채번되어 index+1과 리터럴하게 같지 않을 수 있으므로(정상), 이름만 비교한다. // COMMON 헤더가 101부터 채번되어 index+1과 리터럴하게 같지 않을 수 있으므로(정상), 이름만 비교한다.
const isMatched = !!serverHeader && serverHeader.listHderNm === header const isMatched = !!serverHeader && serverHeader.listHderNm.trim() === header
const isSettingRequired = !hasCommonHeader && index >= baseHeaderRows.length const isSettingRequired = !hasCommonHeader && index >= baseHeaderRows.length
return { return {
header, header,

View File

@@ -8,12 +8,15 @@ import type { DataTableColumn } from '@/components/data-table/DataTable.type'
import { useDialog } from '@/hooks/useDialog' import { useDialog } from '@/hooks/useDialog'
import { useSelectedProject } from '@/hooks/useSelectedProject' import { useSelectedProject } from '@/hooks/useSelectedProject'
import { useBulkSendDetailExcelMutation, useBulkSendDetailQuery, useBulkSendListQuery } from '@/query/message' import { useBulkSendDetailExcelMutation, useBulkSendDetailQuery, useBulkSendListQuery } from '@/query/message'
import { MessageType } from '@kri/common/noti-hub' import { isSendCancelable, MessageType } from '@kri/common/noti-hub'
import { MESSAGE_TYPE_LABEL } from '@/const/messageTemplateConst'
import { downloadBase64File, XLSX_MIME_TYPE } from '@kri/common/browser' import { downloadBase64File, XLSX_MIME_TYPE } from '@kri/common/browser'
import { formatKst } from '@kri/common' import { formatKst } from '@kri/common'
import type { PaginationState } from '@tanstack/react-table' import type { PaginationState } from '@tanstack/react-table'
import type { DialogId } from '@/store/jotai/dialog' import type { DialogId } from '@/store/jotai/dialog'
import type { BulkSendInfo, SendResultInfo } from '@kri/common/noti-hub' import type { BulkSendInfo, SendResultInfo } from '@kri/common/noti-hub'
import type { SendCancelRequest } from '@/types/message'
import { useSendCancel } from '@/hooks/useSendCancel'
import {clientEnv} from "@/lib/env.client"; import {clientEnv} from "@/lib/env.client";
import { formatKoreanPhoneNumber } from "@/utils/phone"; import { formatKoreanPhoneNumber } from "@/utils/phone";
@@ -31,7 +34,40 @@ const tabLabelMap: Record<MessageHistoryType, string> = {
kko: '알림톡', kko: '알림톡',
} }
const historyColumns: DataTableColumn<BulkSendInfo>[] = [ // 취소 일시가 없으면 빈 칸으로 둔다.
const formatCancelDt = (cancelDt: string | undefined) => (cancelDt ? formatKst(cancelDt, 'dateTime') : null)
// 버튼만 셀 가운데에 둔다. 취소 일시는 다른 컬럼과 같은 기본 정렬을 따른다.
const CancelButton = ({ disabled, onClick }: { disabled: boolean; onClick: () => void }) => (
<div className="flex justify-center">
<Button
type="button"
size="sm"
variant="outline"
disabled={disabled}
onClick={(e) => {
// 벌크 목록은 행 클릭으로 상세를 여므로 버튼 클릭이 행 선택으로 번지지 않게 한다.
e.stopPropagation()
onClick()
}}
>
예약 취소
</Button>
</div>
)
type CancelColumnOptions = {
/** false(면접원)이면 취소 버튼 대신 취소 일시(없으면 빈 칸)를 표시한다. */
canCancel: boolean
onCancel: (request: SendCancelRequest) => void
cancelPending: boolean
}
// 버튼은 서버의 cancelable로만 판단한다(값이 없는 구버전 응답은 취소 불가). 최종 결과는 취소 API 응답 건수로 안내한다.
const canCancelDetail = (row: SendResultInfo) => isSendCancelable(row) && !!row.sendIdx
// 취소 컬럼에는 취소 가능하면 버튼, 아니면 취소 일시(없으면 빈 칸) 중 하나만 표시한다.
const buildHistoryColumns = ({ canCancel, onCancel, cancelPending }: CancelColumnOptions): DataTableColumn<BulkSendInfo>[] => [
{ id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') }, { id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') },
{ id: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') }, { id: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') },
{ id: 'resve', header: '구분', accessorFn: (row) => (row.resve ? '예약' : '즉시') }, { id: 'resve', header: '구분', accessorFn: (row) => (row.resve ? '예약' : '즉시') },
@@ -39,15 +75,44 @@ const historyColumns: DataTableColumn<BulkSendInfo>[] = [
{ id: 'sendCnt', header: '발송수', accessorFn: (row) => row.sendCnt.toLocaleString() }, { id: 'sendCnt', header: '발송수', accessorFn: (row) => row.sendCnt.toLocaleString() },
{ id: 'succesCnt', header: '성공', accessorFn: (row) => row.succesCnt.toLocaleString() }, { id: 'succesCnt', header: '성공', accessorFn: (row) => row.succesCnt.toLocaleString() },
{ id: 'failCnt', header: '실패', accessorFn: (row) => row.failCnt.toLocaleString() }, { id: 'failCnt', header: '실패', accessorFn: (row) => row.failCnt.toLocaleString() },
{
id: 'cancelDt',
header: '취소 일시',
accessorFn: (row) => row.cancelDt ?? '',
cell: ({ row }) =>
canCancel && isSendCancelable(row.original) ? (
<CancelButton
disabled={cancelPending}
onClick={() => onCancel({ type: 'bulk', bulkSendKey: row.original.bulkSendKey })}
/>
) : (
formatCancelDt(row.original.cancelDt)
),
},
{ id: 'completeDt', header: '완료 일시', accessorFn: (row) => (row.completeDt ? formatKst(row.completeDt, 'dateTime') : '-') }, { id: 'completeDt', header: '완료 일시', accessorFn: (row) => (row.completeDt ? formatKst(row.completeDt, 'dateTime') : '-') },
{ id: 'regUser', header: '등록자', accessorFn: (row) => row.regUser ?? '-' }, { id: 'regUser', header: '등록자', accessorFn: (row) => row.regUser ?? '-' },
] ]
const detailColumns: DataTableColumn<SendResultInfo>[] = [ const buildDetailColumns = ({ canCancel, onCancel, cancelPending }: CancelColumnOptions): DataTableColumn<SendResultInfo>[] => [
{ id: 'sendTy', header: '유형', accessorFn: (row) => MESSAGE_TYPE_LABEL[row.sendTy] ?? String(row.sendTy) },
{ id: 'destTo', header: '수신처', accessorFn: (row) => row.destEml || (row.destTel ? formatKoreanPhoneNumber(row.destTel) : '') || '-' }, { id: 'destTo', header: '수신처', accessorFn: (row) => row.destEml || (row.destTel ? formatKoreanPhoneNumber(row.destTel) : '') || '-' },
{ id: 'destNm', header: '수신자명', accessorFn: (row) => row.destNm ?? '-' }, { id: 'destNm', header: '수신자명', accessorFn: (row) => row.destNm ?? '-' },
{ id: 'sendFrom', header: '발신지', accessorFn: (row) => row.sendEml || (row.sendTel ? formatKoreanPhoneNumber(row.sendTel) : '') || '-' }, { id: 'sendFrom', header: '발신지', accessorFn: (row) => row.sendEml || (row.sendTel ? formatKoreanPhoneNumber(row.sendTel) : '') || '-' },
{ id: 'resultViewLabel', header: '결과', accessorFn: (row) => row.resultViewLabel || row.resultLabel || String(row.resultCode) }, { id: 'resultViewLabel', header: '결과', accessorFn: (row) => row.resultViewLabel || row.resultLabel || String(row.resultCode) },
{
// 개별 건의 현재 취소 상태는 결과 컬럼(resultCode 라벨)으로 표시한다.
id: 'cancelDt',
header: '취소 일시',
accessorFn: (row) => row.cancelDt ?? '',
cell: ({ row }) => {
const { sendIdx, cancelDt } = row.original
return canCancel && canCancelDetail(row.original) && sendIdx ? (
<CancelButton disabled={cancelPending} onClick={() => onCancel({ type: 'single', sendIdx })} />
) : (
formatCancelDt(cancelDt)
)
},
},
{ id: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') }, { id: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') },
{ id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') }, { id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') },
] ]
@@ -69,21 +134,15 @@ const MessageHistoryDialog = ({
const emailListQuery = useBulkSendListQuery(MessageType.EMAIL, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'email') const emailListQuery = useBulkSendListQuery(MessageType.EMAIL, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'email')
const smsListQuery = useBulkSendListQuery(MessageType.SMS, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'sms') const smsListQuery = useBulkSendListQuery(MessageType.SMS, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'sms')
const lmsListQuery = useBulkSendListQuery(MessageType.LMS_MMS, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'sms')
const kkoListQuery = useBulkSendListQuery(MessageType.KKO, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'kko') const kkoListQuery = useBulkSendListQuery(MessageType.KKO, clientEnv.REQUEST_SVC, prjctCd, enabled && tab === 'kko')
const visibleRows = useMemo(() => { const visibleRows = useMemo(() => {
if (tab === 'email') return emailListQuery.data ?? [] if (tab === 'email') return emailListQuery.data ?? []
if (tab === 'kko') return kkoListQuery.data ?? [] if (tab === 'kko') return kkoListQuery.data ?? []
// 문자 길이에 따라 SMS로 발송된 건도 자동으로 LMS/MMS로 전환될 수 있는데, 이 경우 두 목록 API가 // 21/22/23 경로는 모두 문자 채널 전체를 반환하므로 한 번만 조회한다.
// 같은 bulkSendKey를 각각 반환해 합치면 행이 중복된다. bulkSendKey 기준으로 한 번만 남긴다. return [...(smsListQuery.data ?? [])].sort((a, b) => (b.regDt ?? '').localeCompare(a.regDt ?? ''))
const merged = new Map<string, BulkSendInfo>() }, [tab, emailListQuery.data, smsListQuery.data, kkoListQuery.data])
for (const row of [...(smsListQuery.data ?? []), ...(lmsListQuery.data ?? [])]) {
merged.set(row.bulkSendKey, row)
}
return Array.from(merged.values()).sort((a, b) => (b.regDt ?? '').localeCompare(a.regDt ?? ''))
}, [tab, emailListQuery.data, smsListQuery.data, lmsListQuery.data, kkoListQuery.data])
const detailQuery = useBulkSendDetailQuery( const detailQuery = useBulkSendDetailQuery(
selectedKey ?? '', selectedKey ?? '',
@@ -96,6 +155,9 @@ const MessageHistoryDialog = ({
enabled && !!selectedKey, enabled && !!selectedKey,
) )
const detailExcelMutation = useBulkSendDetailExcelMutation() const detailExcelMutation = useBulkSendDetailExcelMutation()
const { canCancel, cancel, isPending: cancelPending } = useSendCancel()
const historyColumns = buildHistoryColumns({ canCancel, onCancel: cancel, cancelPending })
const detailColumns = buildDetailColumns({ canCancel, onCancel: cancel, cancelPending })
const handleOpenChange = (nextOpen: boolean) => { const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen) onOpenChange?.(nextOpen)
@@ -134,7 +196,7 @@ const MessageHistoryDialog = ({
title={<span className="text-2xl font-bold">발송 이력</span>} title={<span className="text-2xl font-bold">발송 이력</span>}
contentClassName="sm:max-w-[1200px] max-h-[90vh] overflow-y-auto" contentClassName="sm:max-w-[1200px] max-h-[90vh] overflow-y-auto"
closeLabel="닫기" closeLabel="닫기"
bodyClassName="space-y-4" bodyClassName="min-w-0 space-y-4"
> >
<div className="flex gap-2"> <div className="flex gap-2">
<Button type="button" variant={tab === 'sms' ? 'default' : 'outline'} onClick={() => handleSelectTab('sms')}> <Button type="button" variant={tab === 'sms' ? 'default' : 'outline'} onClick={() => handleSelectTab('sms')}>
@@ -174,7 +236,7 @@ const MessageHistoryDialog = ({
<DataTable<SendResultInfo> <DataTable<SendResultInfo>
columns={detailColumns} columns={detailColumns}
data={detailQuery.data?.content ?? []} data={detailQuery.data?.content ?? []}
getRowId={(row) => row.cmid} getRowId={(row) => (row.sendIdx ? String(row.sendIdx) : row.cmid)}
isClient={false} isClient={false}
pageCount={detailQuery.data?.totalPages ?? 0} pageCount={detailQuery.data?.totalPages ?? 0}
totalCount={detailQuery.data?.totalElements ?? 0} totalCount={detailQuery.data?.totalElements ?? 0}

View File

@@ -14,7 +14,7 @@ import {
useTemplateListQuery, useTemplateListQuery,
useTemplateQuery, useTemplateQuery,
} from '@/query/message' } from '@/query/message'
import { getNearestFutureDateTime, toReserveSendDt } from '@/lib/datetime' import { getNearestFutureDateTime, isPastReserveDateTime, toReserveSendDt } from '@/lib/datetime'
import type { DialogId } from '@/store/jotai/dialog' import type { DialogId } from '@/store/jotai/dialog'
import { createEmptyListFilter, type ListFilter, type ListFilterTarget, type listHeader } from '@/types/list' import { createEmptyListFilter, type ListFilter, type ListFilterTarget, type listHeader } from '@/types/list'
import { ListHeaderConst } from '@/const/listConst' import { ListHeaderConst } from '@/const/listConst'
@@ -183,6 +183,10 @@ const MessageSendDialog = ({
alert('예약 발송 일시를 선택해 주세요.') alert('예약 발송 일시를 선택해 주세요.')
return return
} }
if (scheduleType === 'reserve' && isPastReserveDateTime(reserveAt)) {
alert('예약 발송 일시는 현재 시각 이후로 선택해 주세요.')
return
}
const listFilter = buildListFilter() const listFilter = buildListFilter()
if (target === 'selected' && listFilter.sidSet.length === 0) { if (target === 'selected' && listFilter.sidSet.length === 0) {
alert('수신 대상이 없습니다.') alert('수신 대상이 없습니다.')

View File

@@ -15,7 +15,7 @@ import {
useTemplateQuery, useTemplateQuery,
} from '@/query/message' } from '@/query/message'
import type { TemplateSummary } from '@kri/common/noti-hub' import type { TemplateSummary } from '@kri/common/noti-hub'
import { getNearestFutureDateTime, toReserveSendDt } from '@/lib/datetime' import { getNearestFutureDateTime, isPastReserveDateTime, toReserveSendDt } from '@/lib/datetime'
import type { DialogId } from '@/store/jotai/dialog' import type { DialogId } from '@/store/jotai/dialog'
import type { MessageSendChannel, PhoneVerificationSendData } from '@/types/message' import type { MessageSendChannel, PhoneVerificationSendData } from '@/types/message'
import MessageSendPreview from '@/components/message-template/MessageSendPreview' import MessageSendPreview from '@/components/message-template/MessageSendPreview'
@@ -127,6 +127,10 @@ const SingleMessageSendDialog = ({
alert('예약 발송 일시를 선택해 주세요.') alert('예약 발송 일시를 선택해 주세요.')
return return
} }
if (scheduleType === 'reserve' && isPastReserveDateTime(reserveAt)) {
alert('예약 발송 일시는 현재 시각 이후로 선택해 주세요.')
return
}
setSubmitting(true) setSubmitting(true)
try { try {

View File

@@ -8,8 +8,23 @@ import { useTextareaInsert } from './hooks/useTextareaInsert'
type SmsEditorProps = Omit<KriEditorProps, 'mode'> & { mode: 'sms' } type SmsEditorProps = Omit<KriEditorProps, 'mode'> & { mode: 'sms' }
type SmsMessageType = 'SMS' | 'LMS' | 'MMS'
function calculateBytes(value: string): number { function calculateBytes(value: string): number {
return Array.from(value).reduce((total, character) => total + (character.charCodeAt(0) > 127 ? 2 : 1), 0) return new TextEncoder().encode(value).byteLength
}
// 첨부파일이 있으면 MMS, 제목이 있거나 smsMaxBytes 이상이면 LMS, 나머지는 SMS로 미리보기 판정한다.
function getSmsMessageType(hasAttachment: boolean, byteSize: number, smsMaxBytes: number, title: string): SmsMessageType {
if (hasAttachment) return 'MMS'
if (byteSize >= smsMaxBytes || Boolean(title)) return 'LMS'
return 'SMS'
}
function getTextareaMinHeight(hasImages: boolean, hasTitle: boolean): string {
if (hasImages) return '160px'
if (hasTitle) return '320px'
return '360px'
} }
export function KriEditorSms({ export function KriEditorSms({
@@ -34,14 +49,25 @@ export function KriEditorSms({
const [text, setText] = React.useState(value || '') const [text, setText] = React.useState(value || '')
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null) const textareaRef = React.useRef<HTMLTextAreaElement | null>(null)
const latestTextRef = React.useRef(text) const latestTextRef = React.useRef(text)
const lastTypeRef = React.useRef<'SMS' | 'LMS' | null>(null) const lastTypeRef = React.useRef<SmsMessageType | null>(null)
const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs) const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs)
const textareaInsert = useTextareaInsert(textareaRef) const textareaInsert = useTextareaInsert(textareaRef)
const previewText = smsPreviewSuffix ? `${text}\n${smsPreviewSuffix}` : text const previewText = smsPreviewSuffix ? `${text}\n${smsPreviewSuffix}` : text
const byteSize = React.useMemo(() => calculateBytes(previewText), [previewText]) const byteSize = React.useMemo(() => calculateBytes(previewText), [previewText])
const messageType: 'SMS' | 'LMS' = byteSize > smsMaxBytes || Boolean(smsTitle) || smsHasAttachment ? 'LMS' : 'SMS' const messageType = getSmsMessageType(smsHasAttachment, byteSize, smsMaxBytes, smsTitle)
const maxBytes = messageType === 'SMS' ? smsMaxBytes : lmsMaxBytes const maxBytes = messageType === 'SMS' ? smsMaxBytes : lmsMaxBytes
function getBadgeColor(): string {
switch (messageType) {
case 'SMS':
return 'bg-red-500'
case 'LMS':
return 'bg-blue-500'
case 'MMS':
return 'bg-green-500'
}
}
const commitText = React.useCallback((next: string, immediate = false) => { const commitText = React.useCallback((next: string, immediate = false) => {
setText(next) setText(next)
latestTextRef.current = next latestTextRef.current = next
@@ -90,8 +116,8 @@ export function KriEditorSms({
<div className="flex h-full flex-col bg-gray-50 px-4 pt-8 pb-4"> <div className="flex h-full flex-col bg-gray-50 px-4 pt-8 pb-4">
<div className="mb-3 flex items-center justify-between px-2"> <div className="mb-3 flex items-center justify-between px-2">
<span className="text-xs font-medium text-gray-600">{byteSize}/{maxBytes}byte</span> <span className="text-xs font-medium text-gray-600">{byteSize}/{maxBytes}byte</span>
<span className={cn('rounded-md px-3 py-1 text-xs font-bold text-white', messageType === 'LMS' ? 'bg-blue-500' : 'bg-red-500')}> <span className={cn('rounded-md px-3 py-1 text-xs font-bold text-white', getBadgeColor())}>
{messageType === 'LMS' ? 'LMS/MMS' : 'SMS'} {messageType}
</span> </span>
</div> </div>
<div className={cn('flex flex-1 flex-col rounded-2xl bg-white shadow-sm', smsImages.length > 0 ? 'overflow-y-auto' : 'overflow-hidden')}> <div className={cn('flex flex-1 flex-col rounded-2xl bg-white shadow-sm', smsImages.length > 0 ? 'overflow-y-auto' : 'overflow-hidden')}>
@@ -116,7 +142,7 @@ export function KriEditorSms({
onBlur={() => flushChange(latestTextRef.current)} onBlur={() => flushChange(latestTextRef.current)}
placeholder={placeholder} placeholder={placeholder}
readOnly={isSmsReadOnly} readOnly={isSmsReadOnly}
style={{ minHeight: smsImages.length > 0 ? '160px' : smsTitle ? '320px' : '360px' }} style={{ minHeight: getTextareaMinHeight(smsImages.length > 0, Boolean(smsTitle)) }}
{...textareaInsert.bindSelectionHandlers} {...textareaInsert.bindSelectionHandlers}
/> />
{smsPreviewSuffix ? ( {smsPreviewSuffix ? (

View File

@@ -39,6 +39,58 @@ import { useImageMapOverlay } from "./hooks/useImageMapOverlay";
type ViewMode = "wysiwyg" | "html"; type ViewMode = "wysiwyg" | "html";
type ToolbarEndSlotProps = Pick<KriEditorProps, "renderToolbarEnd"> & {
editor: Editor;
command: KriEditorCommand;
view: ViewMode;
};
// command는 ref를 사용하는 함수 묶음이라, 렌더 중 외부 함수에 직접 넘기면 React Compiler가
// ref 접근으로 판단한다. 별도 컴포넌트의 props로 전달해 렌더 범위를 분리한다(동작 동일).
function ToolbarEndSlot({ renderToolbarEnd, editor, command, view }: Readonly<ToolbarEndSlotProps>) {
return <>{renderToolbarEnd?.({ editor, command, view })}</>;
}
// 주입된 정제 함수가 우선이고, 없으면 sanitizeHtml 옵션에 따라 기본 정제기를 사용한다.
function sanitizeEditorHtml(
html: string,
htmlSanitizer: KriEditorProps["htmlSanitizer"],
sanitizeEnabled: boolean,
allowedCustomHtml: KriEditorProps["allowedCustomHtml"],
): string {
if (htmlSanitizer) return htmlSanitizer(html);
if (sanitizeEnabled) return sanitizeHtml(html, allowedCustomHtml);
return html;
}
function writeHtmlDraft(
draftRef: { current: string },
textareaRef: { current: HTMLTextAreaElement | null },
html: string,
): void {
draftRef.current = html;
if (textareaRef.current) textareaRef.current.value = html;
}
// 외부에서 본문이 변경된 경우에만 기존 editor 문서를 갱신한다.
function syncEditorContent(editor: Editor, value: string, optimisticHtml: string): void {
// 빈 문자열("")은 ProseMirror 스키마상 유효한 문서가 아니라 setContent가 조용히 실패해
// 이전 템플릿 본문이 그대로 남는 문제가 있었음 -> 빈 값은 빈 문단으로 정규화해서 비교/설정.
const normalizedValue = value || "<p></p>";
if (normalizedValue === editor.getHTML() || normalizedValue === optimisticHtml) return;
editor.commands.setContent(normalizedValue, {
emitUpdate: false,
parseOptions: { preserveWhitespace: "full" },
});
// resize가 활성화된 TipTap 이미지 NodeView는 노드의 src 변경을 기존 DOM에 반영하지 않는다.
// editor 전체 대신 NodeView만 다시 생성해 이미지를 갱신하고 편집 포커스는 유지한다.
if (normalizedValue.includes("<img")) {
editor.createNodeViews();
}
}
function getToolbarState(editor: Editor): ToolbarState { function getToolbarState(editor: Editor): ToolbarState {
const ts = editor.getAttributes("textStyle") as { fontSize?: string | null; fontFamily?: string | null; color?: string | null }; const ts = editor.getAttributes("textStyle") as { fontSize?: string | null; fontFamily?: string | null; color?: string | null };
const hl = editor.getAttributes("highlight") as { color?: string | null }; const hl = editor.getAttributes("highlight") as { color?: string | null };
@@ -70,7 +122,7 @@ function getToolbarState(editor: Editor): ToolbarState {
}; };
} }
export function KriEditorWysiwyg(props: KriEditorProps) { export function KriEditorWysiwyg(props: Readonly<KriEditorProps>) {
const { const {
label, label,
@@ -134,6 +186,9 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
}, [view]); }, [view]);
const htmlDraftRef = useRef<string>(value ?? ""); const htmlDraftRef = useRef<string>(value ?? "");
// HTML textarea는 비제어 컴포넌트다. 렌더 중 ref를 읽지 않도록, HTML 보기로 전환하는 시점의
// 초안을 state로 보관해 textarea가 마운트될 때의 초기값(defaultValue)으로만 사용한다.
const [htmlTextareaSeed, setHtmlTextareaSeed] = useState<string>(value ?? "");
const canImageUpload = Boolean(onImageUpload); const canImageUpload = Boolean(onImageUpload);
const selectionRef = useRef<{ from: number; to: number } | null>(null); const selectionRef = useRef<{ from: number; to: number } | null>(null);
@@ -471,6 +526,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
if (viewRef.current === "wysiwyg") { if (viewRef.current === "wysiwyg") {
const raw = editor.getHTML(); const raw = editor.getHTML();
htmlDraftRef.current = raw; htmlDraftRef.current = raw;
setHtmlTextareaSeed(raw);
setView("html"); setView("html");
// WYSIWYG에서 막 넘어온, 사용자가 직접 타이핑하지 않은 HTML이므로 // WYSIWYG에서 막 넘어온, 사용자가 직접 타이핑하지 않은 HTML이므로
@@ -492,14 +548,12 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
toast.message(compatibility.reason ?? "현재 HTML은 WYSIWYG로 전환할 수 없습니다."); toast.message(compatibility.reason ?? "현재 HTML은 WYSIWYG로 전환할 수 없습니다.");
return; return;
} }
const safe = htmlSanitizer const safe = sanitizeEditorHtml(raw, htmlSanitizer, sanitizeHtmlOpt, allowedCustomHtml);
? htmlSanitizer(raw)
: sanitizeHtmlOpt ? sanitizeHtml(raw, allowedCustomHtml) : raw;
editor.commands.setContent(safe, { emitUpdate: false, parseOptions: { preserveWhitespace: "full" } }); editor.commands.setContent(safe, { emitUpdate: false, parseOptions: { preserveWhitespace: "full" } });
flushChange(preserveEmptyParagraphs(editor.getHTML())); flushChange(preserveEmptyParagraphs(editor.getHTML()));
setView("wysiwyg"); setView("wysiwyg");
}, [allowedCustomHtml, editor, flushChange, getCompatibility, htmlSanitizer, sanitizeHtmlOpt]); }, [allowedCustomHtml, editor, flushChange, getCompatibility, htmlSanitizer, sanitizeHtmlOpt, setView, setPreviewSource, setHtmlTextareaSeed]);
const formatHtmlView = useCallback(async () => { const formatHtmlView = useCallback(async () => {
try { try {
@@ -512,7 +566,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
toast.error("HTML 정렬에 실패했습니다."); toast.error("HTML 정렬에 실패했습니다.");
console.error(err); console.error(err);
} }
}, [scheduleChange]); }, [scheduleChange, setPreviewSource]);
useEffect(() => { useEffect(() => {
if (!editor) return; if (!editor) return;
@@ -544,46 +598,28 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
useEffect(() => { useEffect(() => {
setPreviewSource(value ?? ""); setPreviewSource(value ?? "");
if (!editor) return; if (!editor || value == null) return;
if (value == null) return;
const compatibility = getCompatibility(value); // WYSIWYG로 손실 없이 편집할 수 없는 값은 HTML 보기로 전환해 원문을 유지한다.
if (showHtmlToggle && !compatibility.compatible) { if (showHtmlToggle && !getCompatibility(value).compatible) {
htmlDraftRef.current = value; writeHtmlDraft(htmlDraftRef, htmlTextareaRef, value);
if (htmlTextareaRef.current) htmlTextareaRef.current.value = value;
if (viewRef.current !== "html") { if (viewRef.current !== "html") {
viewRef.current = "html"; viewRef.current = "html";
setHtmlTextareaSeed(value);
setView("html"); setView("html");
} }
return; return;
} }
if (viewRef.current === "html") { if (viewRef.current === "html") {
if (getWysiwygCompatibility && value !== optimisticHtmlRef.current && value !== htmlDraftRef.current) { const isExternalChange = value !== optimisticHtmlRef.current && value !== htmlDraftRef.current;
htmlDraftRef.current = value; if (getWysiwygCompatibility && isExternalChange) {
if (htmlTextareaRef.current) htmlTextareaRef.current.value = value; writeHtmlDraft(htmlDraftRef, htmlTextareaRef, value);
} }
return; return;
} }
// 빈 문자열("")은 ProseMirror 스키마상 유효한 문서가 아니라 setContent가 조용히 실패해 syncEditorContent(editor, value, optimisticHtmlRef.current);
// 이전 템플릿 본문이 그대로 남는 문제가 있었음 -> 빈 값은 빈 문단으로 정규화해서 비교/설정.
const normalizedValue = value || "<p></p>";
const current = editor.getHTML();
if (normalizedValue !== current && normalizedValue !== optimisticHtmlRef.current) {
// 외부에서 본문이 변경된 경우에만 기존 editor 문서를 갱신한다.
editor.commands.setContent(normalizedValue, {
emitUpdate: false,
parseOptions: {preserveWhitespace: "full"},
});
// resize가 활성화된 TipTap 이미지 NodeView는 노드의 src 변경을 기존 DOM에 반영하지 않는다.
// editor 전체 대신 NodeView만 다시 생성해 이미지를 갱신하고 편집 포커스는 유지한다.
if (normalizedValue.includes("<img")) {
editor.createNodeViews();
}
}
}, [value, editor, view, getCompatibility, getWysiwygCompatibility, showHtmlToggle]); }, [value, editor, view, getCompatibility, getWysiwygCompatibility, showHtmlToggle]);
useEffect(() => { useEffect(() => {
@@ -648,14 +684,13 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
const previewHtml = useMemo(() => { const previewHtml = useMemo(() => {
const preserved = preserveEmptyParagraphs(previewSource); const preserved = preserveEmptyParagraphs(previewSource);
const sanitized = htmlSanitizer const sanitized = sanitizeEditorHtml(preserved, htmlSanitizer, sanitizeHtmlOpt, allowedCustomHtml);
? htmlSanitizer(preserved)
: sanitizeHtmlOpt ? sanitizeHtml(preserved, allowedCustomHtml) : preserved;
const withLinkStyle = applyLinkPreviewClass(sanitized); const withLinkStyle = applyLinkPreviewClass(sanitized);
return transformPreviewHtml ? transformPreviewHtml(withLinkStyle) : withLinkStyle; return transformPreviewHtml ? transformPreviewHtml(withLinkStyle) : withLinkStyle;
}, [allowedCustomHtml, htmlSanitizer, previewSource, sanitizeHtmlOpt, transformPreviewHtml]); }, [allowedCustomHtml, htmlSanitizer, previewSource, sanitizeHtmlOpt, transformPreviewHtml]);
const imageMapOverlayBoxes = useImageMapOverlay(previewContainerRef, previewHtml); // 이미지맵을 사용할 때만 미리보기에 <area> 영역을 표시한다.
const imageMapOverlayBoxes = useImageMapOverlay(previewContainerRef, previewHtml, enableImageMap && showPreview);
const wysiwygCompatibility = useMemo( const wysiwygCompatibility = useMemo(
() => getCompatibility(view === "html" ? previewSource : (editor?.getHTML() ?? previewSource)), () => getCompatibility(view === "html" ? previewSource : (editor?.getHTML() ?? previewSource)),
@@ -704,7 +739,11 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
onAddRow={addRow} onAddRow={addRow}
onAddColumn={addColumn} onAddColumn={addColumn}
onDeleteTable={deleteTable} onDeleteTable={deleteTable}
customContent={props.renderToolbarEnd?.({ editor, command, view })} customContent={
props.renderToolbarEnd ? (
<ToolbarEndSlot renderToolbarEnd={props.renderToolbarEnd} editor={editor} command={command} view={view} />
) : undefined
}
/> />
</div> </div>
) : null} ) : null}
@@ -718,7 +757,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
<textarea <textarea
ref={htmlTextareaRef} ref={htmlTextareaRef}
className="h-[220px] w-full resize-y rounded-md border bg-background p-3 font-mono text-sm outline-none" className="h-[220px] w-full resize-y rounded-md border bg-background p-3 font-mono text-sm outline-none"
defaultValue={htmlDraftRef.current} defaultValue={htmlTextareaSeed}
onMouseDown={(e) => e.stopPropagation()} onMouseDown={(e) => e.stopPropagation()}
onChange={(e) => { onChange={(e) => {
htmlDraftRef.current = e.target.value; htmlDraftRef.current = e.target.value;
@@ -730,9 +769,9 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
{...htmlTi.bindSelectionHandlers} {...htmlTi.bindSelectionHandlers}
/> />
{!wysiwygCompatibility.compatible ? ( {!wysiwygCompatibility.compatible ? (
<p className="mt-2 text-xs text-amber-700" role="status"> <output className="mt-2 block text-xs text-amber-700">
{wysiwygCompatibility.reason ?? "현재 HTML은 WYSIWYG에서 손실 없이 편집할 수 없습니다."} {wysiwygCompatibility.reason ?? "현재 HTML은 WYSIWYG에서 손실 없이 편집할 수 없습니다."}
</p> </output>
) : null} ) : null}
</div> </div>
)} )}

View File

@@ -2,16 +2,18 @@ import { useLayoutEffect, useRef, useState } from "react"
import { computeImageMapOverlayBoxes, type ImageMapOverlayBox } from "../utils/imageMapOverlay" import { computeImageMapOverlayBoxes, type ImageMapOverlayBox } from "../utils/imageMapOverlay"
// previewHtml이 바뀔 때마다(이미지 로드/리사이즈 포함) <map>/<area> 오버레이 위치를 다시 계산한다. // previewHtml이 바뀔 때마다(이미지 로드/리사이즈 포함) <map>/<area> 오버레이 위치를 다시 계산한다.
// enabled가 false이면 계산·관찰하지 않는다.
export function useImageMapOverlay( export function useImageMapOverlay(
containerRef: React.RefObject<HTMLElement | null>, containerRef: React.RefObject<HTMLElement | null>,
previewHtml: string, previewHtml: string,
enabled = true,
): ImageMapOverlayBox[] { ): ImageMapOverlayBox[] {
const [boxes, setBoxes] = useState<ImageMapOverlayBox[]>([]) const [boxes, setBoxes] = useState<ImageMapOverlayBox[]>([])
const frameRef = useRef<number | null>(null) const frameRef = useRef<number | null>(null)
useLayoutEffect(() => { useLayoutEffect(() => {
const container = containerRef.current const container = containerRef.current
if (!container) { if (!enabled || !container) {
setBoxes([]) setBoxes([])
return return
} }
@@ -40,7 +42,7 @@ export function useImageMapOverlay(
resizeObserver.disconnect() resizeObserver.disconnect()
window.removeEventListener("resize", scheduleRecompute) window.removeEventListener("resize", scheduleRecompute)
} }
}, [containerRef, previewHtml]) }, [containerRef, previewHtml, enabled])
return boxes return boxes
} }

View File

@@ -80,12 +80,13 @@ export type KriEditorProps = {
onImageUploadError?: (error: unknown) => void onImageUploadError?: (error: unknown) => void
debounceMs?: number debounceMs?: number
smsTitle?: string smsTitle?: string
changeSmsType?: (type: 'SMS' | 'LMS') => void /** Preview only; consumers must handle MMS. Actual delivery type is determined by the server. */
changeSmsType?: (type: 'SMS' | 'LMS' | 'MMS') => void
isSmsReadOnly?: boolean isSmsReadOnly?: boolean
smsMaxBytes?: number smsMaxBytes?: number
lmsMaxBytes?: number lmsMaxBytes?: number
smsPreviewSuffix?: string smsPreviewSuffix?: string
/** 첨부파일이 있으면 길이·제목과 무관하게 LMS/MMS로 판정한다. */ /** 첨부파일이 있으면 길이·제목과 무관하게 MMS로 판정한다. */
smsHasAttachment?: boolean smsHasAttachment?: boolean
/** 문자 미리보기의 제목과 본문 사이에 표시할 첨부 이미지 */ /** 문자 미리보기의 제목과 본문 사이에 표시할 첨부 이미지 */
smsImages?: KriEditorSmsImage[] smsImages?: KriEditorSmsImage[]

View File

@@ -10,8 +10,10 @@ import { useAddListEventMutation, useDeleteListEventMutation, useListEventHistor
import { useSendResultBySidQuery } from '@/query/message' import { useSendResultBySidQuery } from '@/query/message'
import { useInternalInfoQuery } from '@/query/internal' import { useInternalInfoQuery } from '@/query/internal'
import { clientEnv } from '@/lib/env.client' import { clientEnv } from '@/lib/env.client'
import { ChannelType } from '@kri/common/noti-hub' import { ChannelType, isSendCancelable } from '@kri/common/noti-hub'
import { MESSAGE_TYPE_LABEL } from '@/const/messageTemplateConst'
import type { SendResultInfo } from '@kri/common/noti-hub' import type { SendResultInfo } from '@kri/common/noti-hub'
import { useSendCancel } from '@/hooks/useSendCancel'
import { formatKst } from '@kri/common' import { formatKst } from '@kri/common'
import { type ResultCode, ResultCodeType } from '@/types/project' import { type ResultCode, ResultCodeType } from '@/types/project'
import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from '@/const/userConst' import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from '@/const/userConst'
@@ -239,6 +241,8 @@ const ContactEventSection = ({
} }
const SendResultTable = ({ isLoading, results }: { isLoading: boolean; results: SendResultInfo[] }) => { const SendResultTable = ({ isLoading, results }: { isLoading: boolean; results: SendResultInfo[] }) => {
const { canCancel: canCancelSend, cancel, isPending: cancelPending } = useSendCancel()
if (isLoading) { if (isLoading) {
return <div className="rounded-md border p-4 text-center text-sm text-muted-foreground">불러오는 중...</div> return <div className="rounded-md border p-4 text-center text-sm text-muted-foreground">불러오는 중...</div>
} }
@@ -252,19 +256,42 @@ const SendResultTable = ({ isLoading, results }: { isLoading: boolean; results:
<table className="w-full text-sm"> <table className="w-full text-sm">
<thead className="sticky top-0 bg-muted"> <thead className="sticky top-0 bg-muted">
<tr> <tr>
<th className="p-2 text-left">유형</th>
<th className="p-2 text-left">수신처</th> <th className="p-2 text-left">수신처</th>
<th className="p-2 text-left">결과</th> <th className="p-2 text-left">결과</th>
<th className="p-2 text-left">발송일시</th> <th className="p-2 text-left">발송일시</th>
{canCancelSend ? <th className="p-2 text-left"><span className="sr-only">예약 취소</span></th> : null}
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{results.map((item) => ( {results.map((item) => {
<tr key={item.cmid} className="border-t"> const { sendIdx } = item
<td className="p-2">{item.destEml || item.destTel || '-'}</td> // 버튼은 서버의 cancelable로만 판단한다(값이 없는 구버전 응답은 취소 불가). 최종 결과는 취소 API 응답 건수로 안내한다.
<td className="p-2">{item.resultViewLabel || item.resultLabel || item.resultCode}</td> const canCancel = isSendCancelable(item) && !!sendIdx
<td className="p-2">{formatKst(item.sendDt, 'dateHourMin')}</td> return (
</tr> <tr key={sendIdx ?? item.cmid} className="border-t">
))} <td className="p-2">{MESSAGE_TYPE_LABEL[item.sendTy] ?? String(item.sendTy)}</td>
<td className="p-2">{item.destEml || item.destTel || '-'}</td>
<td className="p-2">{item.resultViewLabel || item.resultLabel || item.resultCode}</td>
<td className="p-2">{formatKst(item.sendDt, 'dateHourMin')}</td>
{canCancelSend ? (
<td className="p-2 text-right">
{canCancel && sendIdx ? (
<Button
type="button"
size="sm"
variant="outline"
disabled={cancelPending}
onClick={() => cancel({ type: 'single', sendIdx })}
>
예약 취소
</Button>
) : null}
</td>
) : null}
</tr>
)
})}
</tbody> </tbody>
</table> </table>
</div> </div>

View File

@@ -6,6 +6,7 @@ import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label' import { Label } from '@/components/ui/label'
import { KriSingleSelect } from '@/components/common/KriAutoComplete' import { KriSingleSelect } from '@/components/common/KriAutoComplete'
import { LIST_IS_USE_LABEL } from '@/components/table-column/ListTableColumn'
import { useDialog } from '@/hooks/useDialog' import { useDialog } from '@/hooks/useDialog'
import { useDownloadListItemFileByHeaderMutation, useUploadListItemFileMutation } from '@/query/list' import { useDownloadListItemFileByHeaderMutation, useUploadListItemFileMutation } from '@/query/list'
import { ListHeaderConst } from '@/const/listConst' import { ListHeaderConst } from '@/const/listConst'
@@ -16,6 +17,7 @@ import { formatKst } from '@kri/common'
import { isListFieldEditableForContact, isListFieldVisibleForContact } from '@/utils/listAccess' import { isListFieldEditableForContact, isListFieldVisibleForContact } from '@/utils/listAccess'
import { substituteVariables } from '@/lib/variableSubstitution' import { substituteVariables } from '@/lib/variableSubstitution'
import { formatKoreanPhoneNumber } from '@/utils/phone' import { formatKoreanPhoneNumber } from '@/utils/phone'
import { isLightHexColor, normalizeHexColor } from '@/components/common/color-palette/color'
import SurveyQrDialog from '@/components/dialog/SurveyQrDialog' import SurveyQrDialog from '@/components/dialog/SurveyQrDialog'
import SingleMessageSendDialog from '@/components/dialog/SingleMessageSendDialog' import SingleMessageSendDialog from '@/components/dialog/SingleMessageSendDialog'
import { ctiClient } from '@/lib/cti/ctiClient' import { ctiClient } from '@/lib/cti/ctiClient'
@@ -51,42 +53,60 @@ export const buildInitialValues = (listHeaders: listHeader[], detail?: ListSearc
for (const header of listHeaders) { for (const header of listHeaders) {
if (header.listHderTy === ListHeaderConst.SID) continue if (header.listHderTy === ListHeaderConst.SID) continue
if (!isListFieldVisibleForContact(header)) continue if (!isListFieldVisibleForContact(header)) continue
// 사용 허용은 저장 시 코드("0"/"1"/"9")로 보내야 하므로 폼 값은 코드로 둔다.
// 문자·알림톡 변수 치환은 resolveListHeaderValue의 라벨을 그대로 사용한다.
if (header.listHderTy === ListHeaderConst.IS_USE) {
values[header.listHderId] = detail?.use != null ? String(detail.use) : ''
continue
}
values[header.listHderId] = resolveListHeaderValue(header, detail) values[header.listHderId] = resolveListHeaderValue(header, detail)
} }
return values return values
} }
const IS_USE_OPTIONS = Object.entries(LIST_IS_USE_LABEL).map(([value, label]) => ({ value, label }))
const disabledContrastClass = 'bg-white disabled:opacity-100 disabled:text-foreground disabled:bg-muted/60' const disabledContrastClass = 'bg-white disabled:opacity-100 disabled:text-foreground disabled:bg-muted/60'
// Input/textarea는 수정 불가 상태에서도 드래그 선택/복사가 가능해야 해서 disabled 대신 readOnly를 쓴다. // Input/textarea는 수정 불가 상태에서도 드래그 선택/복사가 가능해야 해서 disabled 대신 readOnly를 쓴다.
// disabled는 공용 Input 컴포넌트의 disabled:pointer-events-none 때문에 마우스 이벤트 자체를 못 받는다. // disabled는 공용 Input 컴포넌트의 disabled:pointer-events-none 때문에 마우스 이벤트 자체를 못 받는다.
const readOnlyContrastClass = 'bg-white read-only:text-foreground read-only:bg-muted/60' const readOnlyContrastClass = 'bg-white read-only:text-foreground read-only:bg-muted/60'
const getCallButtonLabel = (isDialing: boolean, isOnCall: boolean) => { const getCallButtonLabel = (isDialing: boolean, isOnCall: boolean, isEnding: boolean) => {
if (isEnding) return '종료 요청 중'
if (isDialing) return '거는 중' if (isDialing) return '거는 중'
if (isOnCall) return '전화 끊기' if (isOnCall) return '전화 끊기'
return '전화' return '전화'
} }
const getCallButtonTitle = (isCtiReady: boolean, isDialing: boolean) => { const getCallButtonTitle = (isCtiReady: boolean, isDialing: boolean, isEnding: boolean) => {
if (!isCtiReady) return '전화 시스템에 연결되어 있지 않습니다.' if (!isCtiReady) return '전화 시스템에 연결되어 있지 않습니다.'
if (isDialing) return '전화를 거는 중입니다.' if (isDialing) return '전화를 거는 중입니다.'
if (isEnding) return '통화 종료를 확인하고 있습니다.'
return undefined return undefined
} }
const FieldRow = ({ label, editable, children }: { label: string; editable?: boolean; children: ReactNode }) => ( const FieldRow = ({ label, color, children }: { label: string; color?: string | null; children: ReactNode }) => {
<div className="flex items-center gap-3"> // 헤더에 지정한 색상(투명도 포함)이 기본색보다 우선한다. 형식이 잘못된 값은 기본색으로 표시한다.
<Label const headerColor = normalizeHexColor(color)
className={cn( const isDarkHeaderColor = headerColor !== null && !isLightHexColor(headerColor)
'w-24 shrink-0 rounded-md px-2 py-2.5 text-sm font-bold text-foreground',
editable && 'bg-blue-100', return (
)} <div className="flex items-center gap-3">
> <Label
{label} className={cn(
</Label> 'w-24 shrink-0 wrap-anywhere rounded-md px-2 py-2.5 text-sm leading-snug font-bold',
<div className="min-w-0 flex-1">{children}</div> headerColor === null && 'bg-blue-100',
</div> isDarkHeaderColor ? 'text-white' : 'text-foreground',
) )}
style={headerColor ? { backgroundColor: headerColor } : undefined}
>
{label}
</Label>
<div className="min-w-0 flex-1">{children}</div>
</div>
)
}
const ListContactInfoPanel = ({ const ListContactInfoPanel = ({
prjctIdx, prjctIdx,
@@ -114,7 +134,8 @@ const ListContactInfoPanel = ({
const isCtiReady = ctiConnectionStatus === 'open' const isCtiReady = ctiConnectionStatus === 'open'
const ctiCallPhase = useCtiCallPhase() const ctiCallPhase = useCtiCallPhase()
const isDialing = ctiCallPhase === 'dialing' const isDialing = ctiCallPhase === 'dialing'
const isOnCall = ctiCallPhase === 'active' const isEnding = ctiCallPhase === 'ending'
const isOnCall = ctiCallPhase === 'active' || isEnding
const visibleHeaders = listHeaders const visibleHeaders = listHeaders
.filter((header) => isListFieldVisibleForContact(header)) .filter((header) => isListFieldVisibleForContact(header))
@@ -147,8 +168,7 @@ const ListContactInfoPanel = ({
} }
const handleCall = (telNum: string, listHderId: number) => { const handleCall = (telNum: string, listHderId: number) => {
if (!isCtiReady || isDialing) return if (!isCtiReady || isDialing || isEnding) return
// CTI_HANGUP_PENDING_VENDOR: 외주사 Hangup 명령 동작 확인 후 통화 중 버튼을 활성화하면 즉시 사용할 수 있다.
if (isOnCall) { if (isOnCall) {
ctiClient.hangup() ctiClient.hangup()
return return
@@ -199,9 +219,9 @@ const ListContactInfoPanel = ({
const value = formValues[header.listHderId] ?? '' const value = formValues[header.listHderId] ?? ''
const onChange = (next: string) => onFieldChange(header.listHderId, next) const onChange = (next: string) => onFieldChange(header.listHderId, next)
if (header.listHderTy === ListHeaderConst.MEMO) { if (header.listHderTy === ListHeaderConst.MEMO || header.listHderTy === ListHeaderConst.MULTILINE_TEXT) {
return ( return (
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}> <FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
<textarea <textarea
className={`flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ${readOnlyContrastClass}`} className={`flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ${readOnlyContrastClass}`}
value={value} value={value}
@@ -214,7 +234,7 @@ const ListContactInfoPanel = ({
if (header.listHderTy === ListHeaderConst.TEL_NUM) { if (header.listHderTy === ListHeaderConst.TEL_NUM) {
return ( return (
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}> <FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
{/* 모바일(md 미만)은 버튼을 입력란 아래 줄로 내린다. */} {/* 모바일(md 미만)은 버튼을 입력란 아래 줄로 내린다. */}
<div className="flex flex-col gap-2 md:flex-row"> <div className="flex flex-col gap-2 md:flex-row">
<Input <Input
@@ -228,12 +248,12 @@ const ListContactInfoPanel = ({
type="button" type="button"
variant="outline" variant="outline"
className={cn('shrink-0 gap-2', isOnCall && 'bg-accent text-accent-foreground')} className={cn('shrink-0 gap-2', isOnCall && 'bg-accent text-accent-foreground')}
disabled={isEditing || !isCtiReady || isDialing} disabled={isEditing || !isCtiReady || isDialing || isEnding}
title={getCallButtonTitle(isCtiReady, isDialing)} title={getCallButtonTitle(isCtiReady, isDialing, isEnding)}
onClick={() => handleCall(value, header.listHderId)} onClick={() => handleCall(value, header.listHderId)}
> >
<Phone className="h-4 w-4" /> <Phone className="h-4 w-4" />
{getCallButtonLabel(isDialing, isOnCall)} {getCallButtonLabel(isDialing, isOnCall, isEnding)}
</Button> </Button>
<Button <Button
type="button" type="button"
@@ -268,7 +288,7 @@ const ListContactInfoPanel = ({
if (header.listHderTy === ListHeaderConst.EMAIL) { if (header.listHderTy === ListHeaderConst.EMAIL) {
return ( return (
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}> <FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
<div className="flex flex-col gap-2 md:flex-row"> <div className="flex flex-col gap-2 md:flex-row">
<Input <Input
value={value} value={value}
@@ -295,7 +315,7 @@ const ListContactInfoPanel = ({
if (header.listHderTy === ListHeaderConst.FILE) { if (header.listHderTy === ListHeaderConst.FILE) {
return ( return (
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}> <FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<div className="min-w-0 flex-1 truncate text-sm"> <div className="min-w-0 flex-1 truncate text-sm">
{value ? ( {value ? (
@@ -334,9 +354,29 @@ const ListContactInfoPanel = ({
) )
} }
if (header.listHderTy === ListHeaderConst.IS_USE) {
return (
<FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
<KriSingleSelect
items={IS_USE_OPTIONS}
value={value}
disabled={!editable}
onChange={onChange}
getValue={(item) => item.value}
getLabel={(item) => item.label}
searchable={false}
preventDeselect
widthClassName="w-full"
heightClassName="h-9"
className={disabledContrastClass}
/>
</FieldRow>
)
}
if (header.listHderTy === ListHeaderConst.CONTENT_ITEM && (header.filterContents?.length ?? 0) > 0) { if (header.listHderTy === ListHeaderConst.CONTENT_ITEM && (header.filterContents?.length ?? 0) > 0) {
return ( return (
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}> <FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
<KriSingleSelect <KriSingleSelect
items={header.filterContents ?? []} items={header.filterContents ?? []}
value={value} value={value}
@@ -353,7 +393,7 @@ const ListContactInfoPanel = ({
} }
return ( return (
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}> <FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
<Input <Input
value={value} value={value}
readOnly={!editable} readOnly={!editable}

View File

@@ -2,11 +2,10 @@
import { useEffect } from 'react' import { useEffect } from 'react'
import { useAtom } from 'jotai' import { useAtom } from 'jotai'
import { HttpError } from '@kri/common/http'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { ListJobProgress } from '@/components/list/ListJobProgress' import { ListJobProgress } from '@/components/list/ListJobProgress'
import { useAuth } from '@/hooks/useAuth' import { useAuth } from '@/hooks/useAuth'
import { isAvailabilityUnsupported, useListJob, useListJobAvailability, useUploadResetActive } from '@/query/list-job' import { isAvailabilityUnsupported, isListJobGone, useListJob, useListJobAvailability, useUploadResetActive } from '@/query/list-job'
import { findTrackedListJob, trackListJob, untrackListJob, useTrackedListJobs } from '@/store/list-job-tracker' import { findTrackedListJob, trackListJob, untrackListJob, useTrackedListJobs } from '@/store/list-job-tracker'
import { listJobLabel } from '@/const/listJobConst' import { listJobLabel } from '@/const/listJobConst'
import { blockerJobLabel, blockerPhaseLabel, blockerUserLabel, describeListJobAvailability } from '@/utils/listJobAvailability' import { blockerJobLabel, blockerPhaseLabel, blockerUserLabel, describeListJobAvailability } from '@/utils/listJobAvailability'
@@ -45,7 +44,7 @@ export function useListJobGate({ prjctIdx, jobType, active, requestLabel, pollWh
const detail = useListJob(prjctIdx, jobKey, active) const detail = useListJob(prjctIdx, jobKey, active)
const job = detail.data?.jobKey === jobKey ? detail.data : undefined const job = detail.data?.jobKey === jobKey ? detail.data : undefined
const finishedJob = job && !isActiveListJob(job.jobStatus) ? job : undefined const finishedJob = job && !isActiveListJob(job.jobStatus) ? job : undefined
const detailNotFound = detail.error instanceof HttpError && detail.error.status === 404 const detailNotFound = isListJobGone(detail.error)
useEffect(() => { useEffect(() => {
if (!active && requestMatches && openRequest.opened) setOpenRequest(null) if (!active && requestMatches && openRequest.opened) setOpenRequest(null)
@@ -61,7 +60,9 @@ export function useListJobGate({ prjctIdx, jobType, active, requestLabel, pollWh
const status: ListJobGateStatus = !active ? 'idle' const status: ListJobGateStatus = !active ? 'idle'
: isAvailabilityUnsupported(availability.error) ? 'unsupported' : isAvailabilityUnsupported(availability.error) ? 'unsupported'
: availability.isError ? 'error' : availability.isError ? 'error'
: !availability.data || (!pollWhileIdle && availability.isFetching && availability.data.allowed) ? 'checking' // 재조회 중에는 직전 결과를 유지한다. 같은 쿼리를 페이지가 주기적으로 재조회하므로 isFetching을 '확인 중'으로
// 보면 그때마다 다이얼로그가 깜빡인다. 접수 직전에는 useSubmitListJob이 다시 확인한다.
: !availability.data ? 'checking'
: availability.data.allowed ? 'allowed' : 'blocked' : availability.data.allowed ? 'allowed' : 'blocked'
return { return {

View File

@@ -9,6 +9,7 @@ import { useAuth } from '@/hooks/useAuth'
import { clientEnv } from '@/lib/env.client' import { clientEnv } from '@/lib/env.client'
import { LIST_JOB_STAGE_LABEL, LIST_JOB_STATUS_LABEL, listJobLabel } from '@/const/listJobConst' import { LIST_JOB_STAGE_LABEL, LIST_JOB_STATUS_LABEL, listJobLabel } from '@/const/listJobConst'
import { isActiveListJob, type ListJob, type ListJobFailurePage } from '@/types/list-job' import { isActiveListJob, type ListJob, type ListJobFailurePage } from '@/types/list-job'
import { formatMessageJobResult } from '@/utils/listJobResult'
type JobDetailPath = 'validation-errors' | 'sid-failures' | 'range-failures' | 'message-report/batches' | 'message-report/preparation-failures' type JobDetailPath = 'validation-errors' | 'sid-failures' | 'range-failures' | 'message-report/batches' | 'message-report/preparation-failures'
type JobDetailSection = { path: JobDetailPath; label: string } type JobDetailSection = { path: JobDetailPath; label: string }
@@ -68,9 +69,9 @@ function Progress({ job }: { job: ListJob }) {
const p = job.progress ?? {} const p = job.progress ?? {}
if (job.jobType.endsWith('_BULK')) return ( if (job.jobType.endsWith('_BULK')) return (
<div className="text-sm space-y-1"> <div className="text-sm space-y-1">
<p>수신처 {n(p.preparedRecipientCnt)} · 접수 {n(p.acceptedRecipientCnt)} · 실패 {n(p.failedRecipientCnt)} · 접수 여부 불명 {n(p.unknownRecipientCnt)}</p> <p>{formatMessageJobResult(job.progress)}</p>
<p>발송 준비 실패 SID {n(p.preparationFailedSidCnt)} · 처리 수신처 {n(p.processedRecipientCnt)} / {n(p.preparedRecipientCnt)}</p> <p>처리 수신자 {n(p.processedRecipientCnt)}건 / 준비된 수신자 {n(p.preparedRecipientCnt)}건</p>
<p className="text-muted-foreground">발송 요청의 접수 결과입니다. 실제 전달 결과는 발송 이력에서 확인하세요. 접수 여부 불명 건은 재발송 전에 확인해야 합니다.</p> <p className="text-muted-foreground">발송 요청의 접수 결과입니다. 실제 전달 결과는 발송 이력에서 확인하세요. 일부 접수 또는 접수 여부 불명이 있으면 중복 발송될 수 있으므로 전체 재발송 전에 내역을 확인해야 합니다.</p>
</div> </div>
) )
if (job.jobType.endsWith('_DOWNLOAD')) return <p className="text-sm">파일 처리 대상 {n(p.processedSidCnt)} · 작성 행 {n(p.writtenRowCnt)} · 작성 파일 {n(p.writtenFileCnt)}</p> if (job.jobType.endsWith('_DOWNLOAD')) return <p className="text-sm">파일 처리 대상 {n(p.processedSidCnt)} · 작성 행 {n(p.writtenRowCnt)} · 작성 파일 {n(p.writtenFileCnt)}</p>
@@ -166,15 +167,19 @@ export function ListJobProgress({ prjctIdx, job }: { prjctIdx: number; job: List
}, },
}) })
// 배정 작업은 진행 중일 때 operation에 따라 "배정 중"/"배정 초기화 중"으로 표시한다. // 배정 작업은 진행 중일 때 operation에 따라 "배정 중"/"배정 초기화 중"으로 표시한다.
const statusText = job.jobType === 'LIST_ASSIGN' && job.operation && job.jobStatus === 'RUNNING' let statusText = LIST_JOB_STATUS_LABEL[job.jobStatus]
? `${listJobLabel(job.jobType, job.operation)} 중` if (job.jobType === 'LIST_ASSIGN' && job.operation && job.jobStatus === 'RUNNING') {
: LIST_JOB_STATUS_LABEL[job.jobStatus] statusText = `${listJobLabel(job.jobType, job.operation)} 중`
} else if (job.jobType.endsWith('_BULK') && job.jobStatus === 'SUCCEEDED') {
statusText = '접수 완료'
}
return ( return (
<div className="space-y-3"> <div className="space-y-3">
{active && <p className="text-sm text-muted-foreground">창을 닫아도 작업은 계속되며, 완료 시 알림을 드립니다.</p>} {active && <p className="text-sm text-muted-foreground">창을 닫아도 작업은 계속되며, 완료 시 알림을 드립니다.</p>}
<p><strong>{statusText}</strong> · 단계: {stageLabel(job.jobStage)} · 접수 {job.regDt.replace('T', ' ').slice(0, 19)}</p> <p><strong>{statusText}</strong> · 단계: {stageLabel(job.jobStage)} · 접수 {job.regDt.replace('T', ' ').slice(0, 19)}</p>
<Progress job={job} /> <Progress job={job} />
{job.jobStatus !== 'SUCCEEDED' && !active && <p className="text-sm text-red-600">{job.errorMessage || (job.cancelReason === 'USER_REQUEST' ? '사용자 요청으로 중단됐습니다.' : '처리가 종료됐습니다.')} {job.jobStage === 'VALIDATION_FAILED' ? '파일 검증 단계에서 중단되어 리스트 데이터는 변경되지 않았습니다.' : '이미 반영된 내용이 있을 수 있으니 확인 후 다시 요청하세요.'}</p>} {job.jobStatus === 'PARTIALLY_SUCCEEDED' && <p className="text-sm text-amber-700">일부 대상은 접수되지 않았거나 접수 여부를 확인하지 못했습니다. 아래 접수 내역과 준비 실패 내역을 확인해 주세요.</p>}
{job.jobStatus !== 'SUCCEEDED' && job.jobStatus !== 'PARTIALLY_SUCCEEDED' && !active && <p className="text-sm text-red-600">{job.errorMessage || (job.cancelReason === 'USER_REQUEST' ? '사용자 요청으로 중단됐습니다.' : '처리가 종료됐습니다.')} {job.jobStage === 'VALIDATION_FAILED' ? '파일 검증 단계에서 중단되어 리스트 데이터는 변경되지 않았습니다.' : '이미 반영된 내용이 있을 수 있으니 확인 후 다시 요청하세요.'}</p>}
{job.jobStatus === 'FAILED' && job.failedChunkNo != null && <p className="text-sm text-red-600">실패한 처리 구간: {n(job.failedChunkNo)}번째</p>} {job.jobStatus === 'FAILED' && job.failedChunkNo != null && <p className="text-sm text-red-600">실패한 처리 구간: {n(job.failedChunkNo)}번째</p>}
{(job.resultFiles.length > 0 || job.jobType === 'LIST_UPLOAD') && <div className="flex flex-wrap gap-3 text-sm"> {(job.resultFiles.length > 0 || job.jobType === 'LIST_UPLOAD') && <div className="flex flex-wrap gap-3 text-sm">
{job.resultFiles.map(file => file.ready {job.resultFiles.map(file => file.ready

View File

@@ -0,0 +1,22 @@
'use client'
import { Button } from '@/components/ui/button'
import type { ListJobPageMonitor } from '@/hooks/useListJobPageMonitor'
export function ListJobRefreshNotice({ monitor, clearsSelection = false }: {
monitor: ListJobPageMonitor
clearsSelection?: boolean
}) {
if (!monitor.pendingRefresh) return null
return (
<div role="status" className="flex items-center justify-between gap-3 rounded-md border bg-muted/30 p-3 text-sm">
<p>{monitor.refreshError ? '목록을 새로 불러오지 못했습니다. 다시 시도해 주세요.'
: clearsSelection ? '목록이 변경되었습니다. 새로고침하면 선택한 행이 해제됩니다.'
: '목록이 변경되었습니다. 작업을 마친 뒤 새로고침해 주세요.'}</p>
<Button type="button" variant="outline" size="sm" disabled={monitor.refreshBlocked || monitor.refreshing}
onClick={() => void monitor.refresh()}>
{monitor.refreshing ? '새로고침 중…' : '새로고침'}
</Button>
</div>
)
}

View File

@@ -4,16 +4,16 @@ import { useEffect } from 'react'
import { usePathname, useRouter } from 'next/navigation' import { usePathname, useRouter } from 'next/navigation'
import { useAtom } from 'jotai' import { useAtom } from 'jotai'
import { useQueries, useQueryClient } from '@tanstack/react-query' import { useQueries, useQueryClient } from '@tanstack/react-query'
import { HttpError } from '@kri/common/http'
import { toast } from 'sonner' import { toast } from 'sonner'
import { nextApi } from '@/lib/http-client' import { nextApi } from '@/lib/http-client'
import { listJobKeys, useMyActiveListJobs } from '@/query/list-job' import { isListJobGone, listJobKeys, useMyActiveListJobs } from '@/query/list-job'
import { listJobOpenRequestAtom } from '@/store/jotai/list-job' import { listJobOpenRequestAtom } from '@/store/jotai/list-job'
import { useSelectedProject } from '@/hooks/useSelectedProject' import { useSelectedProject } from '@/hooks/useSelectedProject'
import { useDialog } from '@/hooks/useDialog' import { useDialog } from '@/hooks/useDialog'
import type { SelectedProject } from '@/store/jotai/project' import type { SelectedProject } from '@/store/jotai/project'
import { markListJobNotified, trackListJob, untrackListJob, useTrackedListJobs } from '@/store/list-job-tracker' import { markListJobNotified, trackListJob, untrackListJob, useTrackedListJobs } from '@/store/list-job-tracker'
import { LIST_JOB_VIEW, listJobLabel } from '@/const/listJobConst' import { LIST_JOB_VIEW } from '@/const/listJobConst'
import { getListJobResultNotification } from '@/utils/listJobResult'
import { isActiveListJob, isListJobType, parseListJob, type ListJob } from '@/types/list-job' import { isActiveListJob, isListJobType, parseListJob, type ListJob } from '@/types/list-job'
function isProjectSelection(value: unknown, projectId: number): value is SelectedProject { function isProjectSelection(value: unknown, projectId: number): value is SelectedProject {
@@ -89,7 +89,7 @@ export function ListJobWatcher({ userId, prjctIdx }: { userId: string; prjctIdx:
details.forEach((result, index) => { details.forEach((result, index) => {
const tracked = trackedJobs[index] const tracked = trackedJobs[index]
if (!tracked) return if (!tracked) return
if (result.error instanceof HttpError && result.error.status === 404) { if (isListJobGone(result.error)) {
untrackListJob(tracked.jobKey) untrackListJob(tracked.jobKey)
return return
} }
@@ -100,14 +100,12 @@ export function ListJobWatcher({ userId, prjctIdx }: { userId: string; prjctIdx:
void qc.invalidateQueries({ queryKey: key }) void qc.invalidateQueries({ queryKey: key })
} }
if (openRequest?.opened && openRequest.jobKey === tracked.jobKey) return if (openRequest?.opened && openRequest.jobKey === tracked.jobKey) return
const label = listJobLabel(job.jobType, job.operation)
const open = { label: '보기', onClick: () => { const open = { label: '보기', onClick: () => {
hideAll() hideAll()
setOpenRequest({ userId, prjctIdx: tracked.prjctIdx, jobType: tracked.jobType, jobKey: tracked.jobKey, opened: false }) setOpenRequest({ userId, prjctIdx: tracked.prjctIdx, jobType: tracked.jobType, jobKey: tracked.jobKey, opened: false })
} } } }
if (job.jobStatus === 'SUCCEEDED') toast.success(`${label} 작업이 완료됐습니다.`, { action: open }) const notification = getListJobResultNotification(job)
else if (job.jobStatus === 'CANCELLED') toast.info(`${label} 작업이 중단됐습니다.`, { action: open }) toast[notification.kind](notification.message, { action: open, description: notification.description })
else toast.error(`${label} 작업이 실패했습니다.`, { action: open })
}) })
}, [details, trackedJobs, openRequest, setOpenRequest, qc, userId, hideAll]) }, [details, trackedJobs, openRequest, setOpenRequest, qc, userId, hideAll])

View File

@@ -8,7 +8,6 @@ import {
TemplatePurpose, TemplatePurpose,
type KkoTemplateDetail, type KkoTemplateDetail,
type KkoTemplateSummary, type KkoTemplateSummary,
type TemplateKko,
} from "@kri/common/noti-hub"; } from "@kri/common/noti-hub";
import { isBlank, type DataVerification } from "@kri/common"; import { isBlank, type DataVerification } from "@kri/common";
import { RefreshCw } from "lucide-react"; import { RefreshCw } from "lucide-react";
@@ -22,8 +21,11 @@ import { KriEditor } from "@/components/kri-editor";
import { useSelectedProject } from "@/hooks/useSelectedProject"; import { useSelectedProject } from "@/hooks/useSelectedProject";
import { import {
fetchKkoTemplateDetail, fetchKkoTemplateDetail,
resolveDeleteTemplateErrorMessage,
useDeleteTemplateMutation,
useKkoTemplateDetailQuery, useKkoTemplateDetailQuery,
useKkoTemplateListQuery, useKkoTemplateListQuery,
useKkoSenderProfilesQuery,
useMainTemplateIdxQuery, useMainTemplateIdxQuery,
useSaveTemplateMutation, useSaveTemplateMutation,
useTemplateListQuery, useTemplateListQuery,
@@ -38,7 +40,7 @@ import {
} from "@/const/messageTemplateConst"; } from "@/const/messageTemplateConst";
import { formatKoreanPhoneNumber } from "@/utils/phone"; import { formatKoreanPhoneNumber } from "@/utils/phone";
import {ProjectMainTemplateUpdateRequest, ProjectSurvey} from "@/types/project"; import {ProjectMainTemplateUpdateRequest, ProjectSurvey} from "@/types/project";
import type { TemplateSummaryWithPurpose, TemplateWithPurpose } from "@/types/message"; import type { KkoSenderProfile, KkoTemplateWithProfile, TemplateSummaryWithPurpose, TemplateWithPurpose } from "@/types/message";
import {MessageVariableList} from "@/components/message-template/MessageVariableList"; import {MessageVariableList} from "@/components/message-template/MessageVariableList";
import {listHeader} from "@/types/list"; import {listHeader} from "@/types/list";
import {useListHeaderQuery} from "@/query/list"; import {useListHeaderQuery} from "@/query/list";
@@ -50,6 +52,7 @@ type KkoTemplateDraft = {
tmplatNm: string; tmplatNm: string;
sendTel: string; sendTel: string;
kkoTmplatCd: string; kkoTmplatCd: string;
senderKey: string;
}; };
const EMPTY_DRAFT: KkoTemplateDraft = { const EMPTY_DRAFT: KkoTemplateDraft = {
@@ -57,6 +60,7 @@ const EMPTY_DRAFT: KkoTemplateDraft = {
tmplatNm: "", tmplatNm: "",
sendTel: "", sendTel: "",
kkoTmplatCd: "", kkoTmplatCd: "",
senderKey: "",
}; };
const CHNNL_TY = ChannelType.KKO; const CHNNL_TY = ChannelType.KKO;
@@ -65,7 +69,7 @@ const KEYWORD_DEBOUNCE_MS = 400;
const isValidKeyword = (keyword: string) => const isValidKeyword = (keyword: string) =>
keyword === "" || (keyword.length >= KKO_TEMPLATE_KEYWORD_MIN_LENGTH && keyword.length <= KKO_TEMPLATE_KEYWORD_MAX_LENGTH); keyword === "" || (keyword.length >= KKO_TEMPLATE_KEYWORD_MIN_LENGTH && keyword.length <= KKO_TEMPLATE_KEYWORD_MAX_LENGTH);
const isKkoTemplate = (template: TemplateWithPurpose | undefined | null): template is TemplateKko & { tmplatPurpose: TemplatePurpose } => const isKkoTemplate = (template: TemplateWithPurpose | undefined | null): template is KkoTemplateWithProfile & { tmplatPurpose: TemplatePurpose } =>
template?.tmplatTy === MessageType.KKO; template?.tmplatTy === MessageType.KKO;
// 저장 불가 안내. 공용 isKkoTemplateSavable 기준으로 판단하고, 해당하면 저장 요청을 보내지 않는다. // 저장 불가 안내. 공용 isKkoTemplateSavable 기준으로 판단하고, 해당하면 저장 요청을 보내지 않는다.
@@ -78,7 +82,7 @@ const getUnsavableWarning = (detail: KkoTemplateDetail): string | null => {
detail.block ? "차단" : null, detail.block ? "차단" : null,
detail.dormant ? "휴면" : null, detail.dormant ? "휴면" : null,
].filter(Boolean).join(", "); ].filter(Boolean).join(", ");
return `저장할 수 없는 템플릿입니다. 승인·사용 상태가 아니거나 지원하지 않는 형식(버튼·이미지·강조 등 추가 요소 포함)입니다. (${status})`; return `저장할 수 없는 템플릿입니다. 승인 상태가 아니거나 지원하지 않는 형식(버튼·이미지·강조 등 추가 요소 포함)입니다. (${status})`;
}; };
const KkoMessageTemplate = () => { const KkoMessageTemplate = () => {
@@ -103,13 +107,17 @@ const KkoMessageTemplate = () => {
const [mainDesired, setMainDesired] = useState(false); const [mainDesired, setMainDesired] = useState(false);
const mainTemplateAppliedRef = useRef(false); const mainTemplateAppliedRef = useRef(false);
const templateDetailAppliedRef = useRef<number | null>(null);
const selectionRevisionRef = useRef(0);
const [checkingTemplate, setCheckingTemplate] = useState(false);
// Queries // Queries
const templateListQuery = useTemplateListQuery(CHNNL_TY, itrntPrjctCd, enabled); const templateListQuery = useTemplateListQuery(CHNNL_TY, itrntPrjctCd, enabled);
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, CHNNL_TY, enabled); const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, CHNNL_TY, enabled);
const templateDetailQuery = useTemplateQuery(selectedTemplateIdx ?? 0, enabled && !!selectedTemplateIdx); const templateDetailQuery = useTemplateQuery(selectedTemplateIdx ?? 0, enabled && !!selectedTemplateIdx);
const kkoListQuery = useKkoTemplateListQuery(searchKeyword, enabled); const profilesQuery = useKkoSenderProfilesQuery(enabled);
const kkoDetailQuery = useKkoTemplateDetailQuery(selectedCode, enabled); const kkoListQuery = useKkoTemplateListQuery(draft.senderKey, searchKeyword, enabled);
const kkoDetailQuery = useKkoTemplateDetailQuery(draft.senderKey, selectedCode, enabled);
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled) const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled) const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled)
@@ -128,8 +136,13 @@ const KkoMessageTemplate = () => {
// Mutations // Mutations
const saveTemplateMutation = useSaveTemplateMutation(CHNNL_TY, itrntPrjctCd); const saveTemplateMutation = useSaveTemplateMutation(CHNNL_TY, itrntPrjctCd);
const updateMainTemplateMutation = useUpdateMainTemplateMutation(prjctIdx, CHNNL_TY); const updateMainTemplateMutation = useUpdateMainTemplateMutation(prjctIdx, CHNNL_TY);
const deleteTemplateMutation = useDeleteTemplateMutation(CHNNL_TY, itrntPrjctCd, prjctIdx);
const isSaving = checkingTemplate || saveTemplateMutation.isPending;
const resetToNew = () => { const resetToNew = () => {
selectionRevisionRef.current += 1;
templateDetailAppliedRef.current = null;
setSelectedTemplateIdx(null); setSelectedTemplateIdx(null);
setDraft(EMPTY_DRAFT); setDraft(EMPTY_DRAFT);
setSavedPreview(null); setSavedPreview(null);
@@ -164,16 +177,21 @@ const KkoMessageTemplate = () => {
useEffect(() => { useEffect(() => {
const d = templateDetailQuery.data; const d = templateDetailQuery.data;
if (!isKkoTemplate(d) || !selectedTemplateIdx || d.tmplatIdx !== selectedTemplateIdx) return; if (!isKkoTemplate(d) || !selectedTemplateIdx || d.tmplatIdx !== selectedTemplateIdx) return;
if (templateDetailAppliedRef.current === selectedTemplateIdx) return;
templateDetailAppliedRef.current = selectedTemplateIdx;
const senderKey = typeof d.senderKey === "string" ? d.senderKey.trim() : "";
setDraft({ setDraft({
tmplatIdx: d.tmplatIdx, tmplatIdx: d.tmplatIdx,
tmplatNm: d.tmplatNm ?? "", tmplatNm: d.tmplatNm ?? "",
sendTel: d.sendTel ?? "", sendTel: d.sendTel ?? "",
kkoTmplatCd: d.kkoTmplatCd ?? "", kkoTmplatCd: senderKey ? d.kkoTmplatCd ?? "" : "",
senderKey,
}); });
setSavedPreview({ body: d.tmplatBody ?? "", title: d.tmplatTitle ?? "" }); selectionRevisionRef.current += 1;
setSelectedCode(""); setSavedPreview(senderKey ? { body: d.tmplatBody ?? "", title: d.tmplatTitle ?? "" } : null);
setSelectedCode(senderKey ? d.kkoTmplatCd ?? "" : "");
setSelectedSummary( setSelectedSummary(
d.kkoTmplatCd senderKey && d.kkoTmplatCd
? { templateCode: d.kkoTmplatCd, templateName: d.tmplatNm ?? "", serviceStatus: null, createdAt: null, modifiedAt: null } ? { templateCode: d.kkoTmplatCd, templateName: d.tmplatNm ?? "", serviceStatus: null, createdAt: null, modifiedAt: null }
: null, : null,
); );
@@ -191,6 +209,12 @@ const KkoMessageTemplate = () => {
} }
const idx = Number(value); const idx = Number(value);
if (!Number.isFinite(idx)) return; if (!Number.isFinite(idx)) return;
selectionRevisionRef.current += 1;
templateDetailAppliedRef.current = null;
setDraft(EMPTY_DRAFT);
setSelectedCode("");
setSelectedSummary(null);
setSavedPreview(null);
setSelectedTemplateIdx(idx); setSelectedTemplateIdx(idx);
}; };
@@ -214,8 +238,21 @@ const KkoMessageTemplate = () => {
await updateMainTemplateMutation.mutateAsync(req); await updateMainTemplateMutation.mutateAsync(req);
}; };
const handleSelectProfile = (senderKey: string) => {
if (senderKey === draft.senderKey) return;
selectionRevisionRef.current += 1;
setDraft((prev) => ({ ...prev, senderKey, kkoTmplatCd: "", tmplatNm: "" }));
setSelectedCode("");
setSelectedSummary(null);
setSavedPreview(null);
setKeywordInput("");
setSearchKeyword("");
};
const handleSelectExternal = (item: KkoTemplateSummary | null) => { const handleSelectExternal = (item: KkoTemplateSummary | null) => {
if (!item) return; if (!item || !draft.senderKey) return;
selectionRevisionRef.current += 1;
setSavedPreview(null);
setSelectedSummary(item); setSelectedSummary(item);
setSelectedCode(item.templateCode); setSelectedCode(item.templateCode);
// 템플릿 명은 선택한 알림톡 템플릿 명을 그대로 쓴다. // 템플릿 명은 선택한 알림톡 템플릿 명을 그대로 쓴다.
@@ -227,16 +264,20 @@ const KkoMessageTemplate = () => {
const fail = (fieldName: string, errMessage: string): DataVerification => ({ success: false, fieldName, errMessage }); const fail = (fieldName: string, errMessage: string): DataVerification => ({ success: false, fieldName, errMessage });
if (isBlank(itrntPrjctCd)) return fail("itrntPrjctCd", "인트라넷 프로젝트 코드가 없습니다."); if (isBlank(itrntPrjctCd)) return fail("itrntPrjctCd", "인트라넷 프로젝트 코드가 없습니다.");
if (isBlank(d.senderKey)) return fail("senderKey", "발신 프로필을 선택해 주세요.");
if (!profilesQuery.data?.some((profile) => profile.senderKey === d.senderKey)) return fail("senderKey", "사용 가능한 발신 프로필을 다시 선택해 주세요.");
if (!d.kkoTmplatCd) return fail("kkoTmplatCd", "알림톡 템플릿을 선택해 주세요."); if (!d.kkoTmplatCd) return fail("kkoTmplatCd", "알림톡 템플릿을 선택해 주세요.");
if (!KKO_TEMPLATE_CODE_REGEX.test(d.kkoTmplatCd)) return fail("kkoTmplatCd", "알림톡 템플릿 코드 형식이 올바르지 않습니다."); if (!KKO_TEMPLATE_CODE_REGEX.test(d.kkoTmplatCd)) return fail("kkoTmplatCd", "알림톡 템플릿 코드 형식이 올바르지 않습니다.");
if (isBlank(d.tmplatNm)) return fail("tmplatNm", "알림톡 템플릿 명이 없습니다."); if (isBlank(d.tmplatNm)) return fail("tmplatNm", "알림톡 템플릿 명이 없습니다.");
if (d.tmplatNm.length > 32) return fail("tmplatNm", "알림톡 템플릿 명이 32자를 초과해 저장할 수 없습니다."); if (d.tmplatNm.length > 128) return fail("tmplatNm", "알림톡 템플릿 명이 128자를 초과해 저장할 수 없습니다.");
if (isBlank(d.sendTel)) return fail("sendTel", "발신 전화번호를 입력해 주세요."); if (isBlank(d.sendTel)) return fail("sendTel", "발신 전화번호를 입력해 주세요.");
if (d.sendTel.length > 16) return fail("sendTel", "발신 전화번호는 16자 이하로 입력해주세요."); if (d.sendTel.length > 16) return fail("sendTel", "발신 전화번호는 16자 이하로 입력해주세요.");
return ok(); return ok();
}; };
const submitTemplate = async (method: "put" | "patch") => { const submitTemplate = async (method: "put" | "patch") => {
if (isSaving) return;
const revision = selectionRevisionRef.current;
const v = validateDraft(draft); const v = validateDraft(draft);
if (!v.success) { if (!v.success) {
alert(v.errMessage); alert(v.errMessage);
@@ -244,9 +285,11 @@ const KkoMessageTemplate = () => {
} }
// 저장 직전에 외부 상세를 다시 조회해 저장 가능 여부를 확인한다. // 저장 직전에 외부 상세를 다시 조회해 저장 가능 여부를 확인한다.
// 화면에서 고른 뒤 상태가 바뀌었을 수 있고, 저장된 템플릿을 수정할 때는 상세를 아직 조회하지 않았기 때문이다. // 화면에서 고른 뒤 상태가 바뀌었을 수 있으므로 최신 상태를 확인한다.
setCheckingTemplate(true);
try { try {
const latestDetail = await fetchKkoTemplateDetail(draft.kkoTmplatCd); const latestDetail = await fetchKkoTemplateDetail(draft.senderKey, draft.kkoTmplatCd);
if (revision !== selectionRevisionRef.current) return;
const warning = getUnsavableWarning(latestDetail); const warning = getUnsavableWarning(latestDetail);
if (warning) { if (warning) {
alert(warning); alert(warning);
@@ -256,10 +299,12 @@ const KkoMessageTemplate = () => {
// 조회 오류는 공통 HTTP 오류 처리로 안내된다. 입력값은 유지한다. // 조회 오류는 공통 HTTP 오류 처리로 안내된다. 입력값은 유지한다.
console.log(e); console.log(e);
return; return;
} finally {
setCheckingTemplate(false);
} }
// 본문·제목·senderKey·첨부는 보내지 않는다. 서버가 저장 시 외부 상세를 재조회해 채운다. // 본문·제목·첨부는 서버가 선택한 프로필의 외부 상세를 재조회해 채운다.
const template: TemplateKko & { tmplatPurpose: TemplatePurpose } = { const template: KkoTemplateWithProfile & { tmplatPurpose: TemplatePurpose } = {
...(method === "patch" ? { tmplatIdx: draft.tmplatIdx } : {}), ...(method === "patch" ? { tmplatIdx: draft.tmplatIdx } : {}),
itrntPrjctCd, itrntPrjctCd,
tmplatTy: MessageType.KKO, tmplatTy: MessageType.KKO,
@@ -268,11 +313,12 @@ const KkoMessageTemplate = () => {
sendNm: KKO_SENDER_NAME, sendNm: KKO_SENDER_NAME,
sendTel: draft.sendTel, sendTel: draft.sendTel,
kkoTmplatCd: draft.kkoTmplatCd, kkoTmplatCd: draft.kkoTmplatCd,
senderKey: draft.senderKey,
}; };
try { try {
const res = await saveTemplateMutation.mutateAsync({ method, template }); const res = await saveTemplateMutation.mutateAsync({ method, template });
if (!isKkoTemplate(res)) return; if (!isKkoTemplate(res) || revision !== selectionRevisionRef.current) return;
// 저장 응답의 본문·제목·코드를 최종 화면 값으로 쓴다. // 저장 응답의 본문·제목·코드를 최종 화면 값으로 쓴다.
setDraft({ setDraft({
@@ -280,10 +326,11 @@ const KkoMessageTemplate = () => {
tmplatNm: res.tmplatNm ?? draft.tmplatNm, tmplatNm: res.tmplatNm ?? draft.tmplatNm,
sendTel: res.sendTel ?? draft.sendTel, sendTel: res.sendTel ?? draft.sendTel,
kkoTmplatCd: res.kkoTmplatCd ?? draft.kkoTmplatCd, kkoTmplatCd: res.kkoTmplatCd ?? draft.kkoTmplatCd,
senderKey: res.senderKey ?? draft.senderKey,
}); });
setSavedPreview({ body: res.tmplatBody ?? "", title: res.tmplatTitle ?? "" }); setSavedPreview({ body: res.tmplatBody ?? "", title: res.tmplatTitle ?? "" });
setSelectedTemplateIdx(res.tmplatIdx ?? null); setSelectedTemplateIdx(res.tmplatIdx ?? null);
setSelectedCode(""); setSelectedCode(res.kkoTmplatCd ?? draft.kkoTmplatCd);
if (mainDesired && selectedProject?.prjctIdx && res.tmplatIdx) { if (mainDesired && selectedProject?.prjctIdx && res.tmplatIdx) {
await updateMainTemplateMutation.mutateAsync({ await updateMainTemplateMutation.mutateAsync({
@@ -300,6 +347,21 @@ const KkoMessageTemplate = () => {
} }
}; };
const handleDelete = async () => {
const tmplatIdx = draft.tmplatIdx;
if (!tmplatIdx) return;
if (!window.confirm(`'${draft.tmplatNm}' 템플릿을 삭제하시겠습니까?`)) return;
try {
await deleteTemplateMutation.mutateAsync(tmplatIdx);
resetToNew();
alert("삭제되었습니다.");
} catch (e) {
// 삭제 불가·권한 없음 등은 안내만 하고 선택 템플릿과 대표 상태는 유지한다.
alert(resolveDeleteTemplateErrorMessage(e));
}
};
const previewBody = externalDetail ? externalDetail.templateContent : savedPreview?.body ?? ""; const previewBody = externalDetail ? externalDetail.templateContent : savedPreview?.body ?? "";
const previewTitle = externalDetail ? externalDetail.templateTitle ?? "" : savedPreview?.title ?? ""; const previewTitle = externalDetail ? externalDetail.templateTitle ?? "" : savedPreview?.title ?? "";
const unsavableWarning = externalDetail ? getUnsavableWarning(externalDetail) : null; const unsavableWarning = externalDetail ? getUnsavableWarning(externalDetail) : null;
@@ -310,7 +372,7 @@ const KkoMessageTemplate = () => {
<CardHeader className="border-b"> <CardHeader className="border-b">
<CardTitle className="text-center text-lg font-bold">알림톡 템플릿 관리</CardTitle> <CardTitle className="text-center text-lg font-bold">알림톡 템플릿 관리</CardTitle>
<p className="text-center text-base text-red-600 font-medium"> <p className="text-center text-base text-red-600 font-medium">
⚠️ 알림톡 템플릿에 대한 수정 및 등록은 비즈 뿌리오에서 가능하며 여기서는 템플릿 프로젝트에 등록만 가능합니다. ⚠️ 알림톡 템플릿에 대한 수정 및 등록은 비즈 뿌리오에서 가능하며 여기서는 템플릿을 프로젝트에 등록만 가능합니다.
</p> </p>
</CardHeader> </CardHeader>
@@ -329,6 +391,7 @@ const KkoMessageTemplate = () => {
</div> </div>
<KriSingleSelect <KriSingleSelect
items={templateList} items={templateList}
disabled={isSaving}
value={String(draft.tmplatIdx || "")} value={String(draft.tmplatIdx || "")}
onChange={handleSelectTemplate} onChange={handleSelectTemplate}
placeholder="템플릿을 선택해 주세요" placeholder="템플릿을 선택해 주세요"
@@ -343,9 +406,43 @@ const KkoMessageTemplate = () => {
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label className="text-base">알림톡 템플릿</Label> <Label className="text-base">발신 프로필 (필수)</Label>
<KriSingleSelect<KkoSenderProfile>
items={profilesQuery.data ?? []}
value={draft.senderKey}
onChange={handleSelectProfile}
placeholder="발신 프로필을 선택해 주세요"
heightClassName="h-9"
widthClassName="w-full"
getLabel={(item) => item.uuid}
getValue={(item) => item.senderKey}
disabled={!enabled || isSaving || profilesQuery.isFetching || templateDetailQuery.isFetching}
preventDeselect
/>
<p className="text-xs text-muted-foreground" role="status">
{profilesQuery.isFetching
? "발신 프로필을 조회하는 중입니다."
: profilesQuery.isError
? "발신 프로필을 불러오지 못했습니다."
: !profilesQuery.data?.length
? "선택할 발신 프로필이 없습니다."
: draft.senderKey && !profilesQuery.data.some((profile) => profile.senderKey === draft.senderKey)
? "저장된 발신 프로필을 사용할 수 없습니다. 프로필을 다시 선택해 주세요."
: "발신 프로필을 선택한 뒤 알림톡 템플릿을 선택해 주세요."}
</p>
{profilesQuery.isError && (
<Button type="button" variant="outline" size="sm" onClick={() => void profilesQuery.refetch()}>
발신 프로필 다시 조회
</Button>
)}
</div>
<div className="space-y-2">
<Label className="text-base">알림톡 템플릿 (필수)</Label>
<KriSingleSelect<KkoTemplateSummary> <KriSingleSelect<KkoTemplateSummary>
key={draft.senderKey}
items={externalList} items={externalList}
disabled={!draft.senderKey || isSaving || templateDetailQuery.isFetching}
value={draft.kkoTmplatCd} value={draft.kkoTmplatCd}
onChange={() => {}} onChange={() => {}}
onItemChange={handleSelectExternal} onItemChange={handleSelectExternal}
@@ -381,10 +478,11 @@ const KkoMessageTemplate = () => {
id="kkoSendTel" id="kkoSendTel"
placeholder="발신 번호를 입력하세요" placeholder="발신 번호를 입력하세요"
value={formatKoreanPhoneNumber(draft.sendTel)} value={formatKoreanPhoneNumber(draft.sendTel)}
disabled={isSaving}
onChange={(e) => setDraft((prev) => ({ ...prev, sendTel: e.target.value.replace(/\D/g, "") }))} onChange={(e) => setDraft((prev) => ({ ...prev, sendTel: e.target.value.replace(/\D/g, "") }))}
/> />
<p className="text-sm text-red-600 font-medium"> <p className="text-sm text-red-600 font-medium">
⚠️ 비즈 뿌리오에 등록된 발신 번호가 아니면 전송되지 않습니다. ⚠️ 비즈 뿌리오(KRi 계정)에 등록된 발신 번호가 아니면 전송되지 않습니다.
</p> </p>
</div> </div>
@@ -438,14 +536,24 @@ const KkoMessageTemplate = () => {
</div> </div>
<div className="flex justify-center gap-3 pt-6"> <div className="flex justify-center gap-3 pt-6">
<Button onClick={() => void submitTemplate("put")} className="w-32 h-10" disabled={saveTemplateMutation.isPending || !!unsavableWarning}> {draft.tmplatIdx && (
<Button
variant="destructive"
onClick={() => void handleDelete()}
className="w-32 h-10"
disabled={deleteTemplateMutation.isPending || isSaving}
>
삭제
</Button>
)}
<Button onClick={() => void submitTemplate("put")} className="w-32 h-10" disabled={isSaving || !draft.senderKey || !draft.kkoTmplatCd || !!unsavableWarning}>
{draft.tmplatIdx ? "복사 후 저장" : "저장"} {draft.tmplatIdx ? "복사 후 저장" : "저장"}
</Button> </Button>
{draft.tmplatIdx && ( {draft.tmplatIdx && (
<Button <Button
onClick={() => void submitTemplate("patch")} onClick={() => void submitTemplate("patch")}
className="w-32 h-10 bg-blue-500 text-white hover:bg-blue-600" className="w-32 h-10 bg-blue-500 text-white hover:bg-blue-600"
disabled={saveTemplateMutation.isPending || !!unsavableWarning} disabled={isSaving || !draft.senderKey || !draft.kkoTmplatCd || !!unsavableWarning}
> >
수정 수정
</Button> </Button>

View File

@@ -34,7 +34,7 @@ import { downloadFile } from "@kri/common/browser";
import {cn} from "@/lib/utils"; import {cn} from "@/lib/utils";
import {ProjectMainTemplateUpdateRequest, ProjectSurvey} from "@/types/project"; import {ProjectMainTemplateUpdateRequest, ProjectSurvey} from "@/types/project";
import type { DataVerification } from "@kri/common"; import type { DataVerification } from "@kri/common";
import {COMMON_TEXT_REGEX, EMAIL_REGEX} from "@/const/validationConst"; import {COMMON_TEXT_REGEX, EMAIL_REGEX, TEMPLATE_TEXT_REGEX} from "@/const/validationConst";
import {formatKoreanPhoneNumber} from "@/utils/phone"; import {formatKoreanPhoneNumber} from "@/utils/phone";
import { import {
getTemplateAttachmentNames, getTemplateAttachmentNames,
@@ -51,6 +51,8 @@ import {
useUploadTemplateBodyImageMutation, useUploadTemplateBodyImageMutation,
useDownloadTemplateAttachmentMutation, useDownloadTemplateAttachmentMutation,
useTemplateAttachmentImagesQuery, useTemplateAttachmentImagesQuery,
useDeleteTemplateMutation,
resolveDeleteTemplateErrorMessage,
} from "@/query/message"; } from "@/query/message";
import {listHeader} from "@/types/list"; import {listHeader} from "@/types/list";
import {useListHeaderQuery} from "@/query/list"; import {useListHeaderQuery} from "@/query/list";
@@ -145,6 +147,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
const downloadAttachmentMutation = useDownloadTemplateAttachmentMutation(selectedTemplate.tmplatIdx ?? 0); const downloadAttachmentMutation = useDownloadTemplateAttachmentMutation(selectedTemplate.tmplatIdx ?? 0);
const updateMainTemplateMutation = useUpdateMainTemplateMutation(prjctIdx, chnnlTy); const updateMainTemplateMutation = useUpdateMainTemplateMutation(prjctIdx, chnnlTy);
const uploadBodyImageMutation = useUploadTemplateBodyImageMutation(itrntPrjctCd); const uploadBodyImageMutation = useUploadTemplateBodyImageMutation(itrntPrjctCd);
const deleteTemplateMutation = useDeleteTemplateMutation(chnnlTy, itrntPrjctCd, prjctIdx);
// 문자 미리보기 첨부 이미지: 유지되는 기존 첨부는 서버에서, 새 파일은 로컬 Object URL로 표시한다. // 문자 미리보기 첨부 이미지: 유지되는 기존 첨부는 서버에서, 새 파일은 로컬 Object URL로 표시한다.
const keptAttachmentImages = useTemplateAttachmentImagesQuery( const keptAttachmentImages = useTemplateAttachmentImagesQuery(
@@ -221,8 +224,8 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
setSelectedTemplate((prev) => ({ ...prev, tmplatBody: newString })); setSelectedTemplate((prev) => ({ ...prev, tmplatBody: newString }));
}; };
const setSmsType = (smsTypeString: "SMS" | "LMS") => { const setSmsType = (smsTypeString: "SMS" | "LMS" | "MMS") => {
const smsType = smsTypeString === "SMS" ? MessageType.SMS : MessageType.LMS_MMS; const smsType = MessageType[smsTypeString];
setSelectedTemplate((prev) => { setSelectedTemplate((prev) => {
if (!isSmsTemplate(prev)) return prev; if (!isSmsTemplate(prev)) return prev;
@@ -240,16 +243,17 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
if (isBlank(tpl.itrntPrjctCd)) return fail("itrntPrjctCd", "인트라넷 프로젝트 코드가 없습니다."); if (isBlank(tpl.itrntPrjctCd)) return fail("itrntPrjctCd", "인트라넷 프로젝트 코드가 없습니다.");
if (isBlank(tpl.tmplatNm)) return fail("tmplatNm", "템플릿명을 입력해 주세요."); if (isBlank(tpl.tmplatNm)) return fail("tmplatNm", "템플릿명을 입력해 주세요.");
if (tpl.tmplatNm.length > 32) return fail("tmplatNm", "템플릿명은 32자 이하로 입력해주세요."); if (tpl.tmplatNm.length > 128) return fail("tmplatNm", "템플릿명은 128자 이하로 입력해주세요.");
if (!COMMON_TEXT_REGEX.test(tpl.tmplatNm)) return fail("tmplatNm", "템플릿명에 허용되지 않는 문자가 포함되어 있습니다."); if (!TEMPLATE_TEXT_REGEX.test(tpl.tmplatNm)) return fail("tmplatNm", "템플릿명에 허용되지 않는 문자가 포함되어 있습니다.");
if (isBlank(tpl.tmplatBody)) return fail("tmplatBody", "본문을 입력해 주세요."); if (isBlank(tpl.tmplatBody)) return fail("tmplatBody", "본문을 입력해 주세요.");
if (isBlank(tpl.sendNm)) return fail("sendNm", "발신자명을 입력해 주세요."); if (isBlank(tpl.sendNm)) return fail("sendNm", "발신자명을 입력해 주세요.");
if (tpl.sendNm.length > 32) return fail("sendNm", "발신자명은 32자 이하로 입력해주세요."); if (tpl.sendNm.length > 32) return fail("sendNm", "발신자명은 32자 이하로 입력해주세요.");
if (!COMMON_TEXT_REGEX.test(tpl.sendNm)) return fail("sendNm", "발신자명에 허용되지 않는 문자가 포함되어 있습니다."); if (!TEMPLATE_TEXT_REGEX.test(tpl.sendNm)) return fail("sendNm", "발신자명에 허용되지 않는 문자가 포함되어 있습니다.");
if (!isBlank(tpl.tmplatTitle)) { if (!isBlank(tpl.tmplatTitle)) {
if (tpl.tmplatTitle!.length > 128) return fail("tmplatTitle", "제목은 128자 이하로 입력해주세요."); const titleMaxLength = isSmsTemplate(tpl) ? 64 : 128;
if (!COMMON_TEXT_REGEX.test(tpl.tmplatTitle!)) return fail("tmplatTitle", "제목에 허용되지 않는 문자가 포함되어 있습니다."); if (tpl.tmplatTitle!.length > titleMaxLength) return fail("tmplatTitle", `제목은 ${titleMaxLength}자 이하로 입력해주세요.`);
if (!TEMPLATE_TEXT_REGEX.test(tpl.tmplatTitle!)) return fail("tmplatTitle", "제목에 허용되지 않는 문자가 포함되어 있습니다.");
} }
if (tpl.tmplatTy === MessageType.EMAIL) { if (tpl.tmplatTy === MessageType.EMAIL) {
@@ -471,6 +475,21 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
await submitTemplate("patch"); await submitTemplate("patch");
}; };
const handleDelete = async () => {
const tmplatIdx = selectedTemplate.tmplatIdx;
if (!tmplatIdx) return;
if (!window.confirm(`'${selectedTemplate.tmplatNm}' 템플릿을 삭제하시겠습니까?`)) return;
try {
await deleteTemplateMutation.mutateAsync(tmplatIdx);
handleSelectTemplate("");
alert("삭제되었습니다.");
} catch (e) {
// 삭제 불가·권한 없음 등은 안내만 하고 선택 템플릿과 대표 상태는 유지한다.
alert(resolveDeleteTemplateErrorMessage(e));
}
};
return ( return (
<div <div
className={cn( className={cn(
@@ -570,7 +589,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
/> />
{isSmsTemplate(selectedTemplate) && {isSmsTemplate(selectedTemplate) &&
<p className="text-sm text-red-600 font-medium"> <p className="text-sm text-red-600 font-medium">
⚠️ 제목이 있으면 본문 길이와 상관없이 LMS/MMS로 발송 됩니다. ⚠️ 제목이 있으면 본문 길이와 상관없이 LMS로 발송됩니다. 이미지가 있으면 MMS로 발송됩니다.
</p> </p>
} }
</div> </div>
@@ -591,7 +610,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
className="w-full" className="w-full"
/> />
<p className="text-sm text-red-600 font-medium"> <p className="text-sm text-red-600 font-medium">
⚠️ 비즈 뿌리오에 등록된 발신 번호가 아니면 전송되지 않습니다. ⚠️ 비즈 뿌리오(KRi 계정)에 등록된 발신 번호가 아니면 전송되지 않습니다.
</p> </p>
</div> </div>
) : ( ) : (
@@ -749,7 +768,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
)} )}
{isSms && attachmentCount > 0 && ( {isSms && attachmentCount > 0 && (
<p className="text-xs text-red-600"> <p className="text-xs text-red-600">
⚠️ 이미지가 첨부되면 본문 길이와 상관없이 LMS/MMS로 저장됩니다. ⚠️ 이미지가 첨부되면 본문 길이와 상관없이 MMS로 저장됩니다.
</p> </p>
)} )}
{selectedTemplate.tmplatIdx && ( {selectedTemplate.tmplatIdx && (
@@ -767,7 +786,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
</p> </p>
<KriEditor <KriEditor
mode="sms" mode="sms"
label={selectedTemplate.tmplatTy === MessageType.SMS ? "️️* 발송 시 길이에 따라 LMS/MMS로 발송 될 수 있음" : undefined} label="미리보기 유형은 예상값이며, 실제 유형은 수신자별 변수 치환 후 결정됩니다."
value={selectedTemplate.tmplatBody ?? ""} value={selectedTemplate.tmplatBody ?? ""}
onChange={(html: string) => setTemplateBody(html)} onChange={(html: string) => setTemplateBody(html)}
placeholder="문자 내용을 입력해 주세요" placeholder="문자 내용을 입력해 주세요"
@@ -791,6 +810,17 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
</div> </div>
<div className="flex justify-center gap-3 pt-4"> <div className="flex justify-center gap-3 pt-4">
{selectedTemplate.tmplatIdx && (
<Button
variant="destructive"
onClick={handleDelete}
className="w-32 h-10"
disabled={deleteTemplateMutation.isPending || saveTemplateMutation.isPending}
>
삭제
</Button>
)}
<Button onClick={handleCreate} className="w-32 h-10"> <Button onClick={handleCreate} className="w-32 h-10">
{selectedTemplate.tmplatIdx ? "복사 후 저장" : "저장"} {selectedTemplate.tmplatIdx ? "복사 후 저장" : "저장"}
</Button> </Button>

View File

@@ -202,6 +202,17 @@ export const getListColumns = (
}; };
} }
if (header.listHderTy === ListHeaderConst.MULTILINE_TEXT) {
return {
accessorKey: String(header.listHderId),
header: header.listHderNm,
meta: {
maxWidth: 200,
},
enableSorting: true,
};
}
return { return {
accessorKey: String(header.listHderId), accessorKey: String(header.listHderId),
header: header.listHderNm, header: header.listHderNm,

View File

@@ -5,3 +5,5 @@ export const FONT_SIZE = {
} as const; } as const;
export const ALLOW_REDIRECT = new Set(["complete", "screen", "quota"]); export const ALLOW_REDIRECT = new Set(["complete", "screen", "quota"]);
export const AUTH_COOKIE_MAX_AGE = 24 * 60 * 60;

View File

@@ -4,11 +4,12 @@ export const CTI_AGENT_GROUP = "KRI_CONTACT";
export const CTI_CALL_PHASE: CtiCallPhase[] = [ export const CTI_CALL_PHASE: CtiCallPhase[] = [
'dialing', 'dialing',
'active' 'active',
'ending'
] as const; ] as const;
// WS 서버가 보내는 CTIAgentStatus 값 중 통화 중 또는 통화 중 재로그인 대기로 간주할 값들 // WS 서버가 보내는 발신·통화 중 상태. None(0)은 통화 중 상태가 아니다.
export const CTI_ON_CALL_STATUSES = ["0", "2", "3"] as const; export const CTI_ON_CALL_STATUSES = ["2", "3", "8"] as const;
// localStorage에 저장한 CTI 상태의 만료 시간. 마지막 저장(updatedAt) 기준이며 복원 시점에만 검사한다. // localStorage에 저장한 CTI 상태의 만료 시간. 마지막 저장(updatedAt) 기준이며 복원 시점에만 검사한다.
export const CTI_STATE_TTL_MS = 2 * 60 * 60 * 1000; export const CTI_STATE_TTL_MS = 2 * 60 * 60 * 1000;
@@ -26,3 +27,7 @@ export const CTI_AUTO_RECONNECT_BASE_MS = 1000;
export const CTI_AUTO_RECONNECT_MAX_MS = 15 * 1000; export const CTI_AUTO_RECONNECT_MAX_MS = 15 * 1000;
export const CTI_AUTO_RECONNECT_JITTER_MS = 1000; export const CTI_AUTO_RECONNECT_JITTER_MS = 1000;
// 종료 명령의 응답이 없으면 재요청할 수 있게 하되, 실제 종료로 판정하지 않는다.
export const CTI_HANGUP_TIMEOUT_MS = 10 * 1000;
export const CTI_LOGIN_TIMEOUT_MS = 15 * 1000;

View File

@@ -32,6 +32,8 @@ export const ListHeaderSpecificConst = {
EMAIL: 31, EMAIL: 31,
FILE: 81, FILE: 81,
CONTENT_ITEM: 91, CONTENT_ITEM: 91,
// 장문(여러 줄 입력 텍스트). 저장·필터·다운로드는 서버에서 일반 텍스트(99)와 같게 처리한다.
MULTILINE_TEXT: 98,
} as const; } as const;
export const ListHeaderConst = { export const ListHeaderConst = {
@@ -44,6 +46,7 @@ type ListHeaderType = (typeof ListHeaderConst)[keyof typeof ListHeaderConst];
export const LIST_HEADER_TYPE_ORDER = [ export const LIST_HEADER_TYPE_ORDER = [
ListHeaderConst.TEXT, ListHeaderConst.TEXT,
ListHeaderConst.MULTILINE_TEXT,
ListHeaderConst.CONTENT_ITEM, ListHeaderConst.CONTENT_ITEM,
ListHeaderConst.TEL_NUM, ListHeaderConst.TEL_NUM,
ListHeaderConst.EMAIL, ListHeaderConst.EMAIL,
@@ -60,6 +63,7 @@ export const LIST_HEADER_TYPE_LABEL = {
[ListHeaderConst.FIELD_INTERVIEWER]: "면접원", [ListHeaderConst.FIELD_INTERVIEWER]: "면접원",
[ListHeaderConst.MEMO]: "중요 메모", [ListHeaderConst.MEMO]: "중요 메모",
[ListHeaderConst.TEXT]: "일반", [ListHeaderConst.TEXT]: "일반",
[ListHeaderConst.MULTILINE_TEXT]: "장문",
[ListHeaderConst.TEL_NUM]: "전화번호", [ListHeaderConst.TEL_NUM]: "전화번호",
[ListHeaderConst.EMAIL]: "이메일", [ListHeaderConst.EMAIL]: "이메일",
[ListHeaderConst.FILE]: "파일 업로드", [ListHeaderConst.FILE]: "파일 업로드",

View File

@@ -29,7 +29,7 @@ export const listJobLabel = (jobType: string, operation?: ListJobOperation | nul
} }
export const LIST_JOB_STATUS_LABEL: Record<string, string> = { export const LIST_JOB_STATUS_LABEL: Record<string, string> = {
QUEUED: '대기', RUNNING: '진행 중', CANCEL_REQUESTED: '중단 요청 중', SUCCEEDED: '완료', QUEUED: '대기', RUNNING: '진행 중', CANCEL_REQUESTED: '중단 요청 중', SUCCEEDED: '완료', PARTIALLY_SUCCEEDED: '일부 접수 완료',
FAILED: '실패', CANCELLED: '중단', REJECTED: '접수 거절', FAILED: '실패', CANCELLED: '중단', REJECTED: '접수 거절',
} }

View File

@@ -18,19 +18,28 @@ export const KKO_TEMPLATE_KEYWORD_MAX_LENGTH = 50;
export const SMS_TYPE_ORDER = [ export const SMS_TYPE_ORDER = [
MessageType.SMS, MessageType.SMS,
MessageType.LMS_MMS, MessageType.LMS,
MessageType.MMS,
] as const; ] as const;
export const SMS_TYPE_LABEL = { export const SMS_TYPE_LABEL = {
[MessageType.SMS]: "SMS", [MessageType.SMS]: "SMS",
[MessageType.LMS_MMS]: "LMS/MMS", [MessageType.LMS]: "LMS",
[MessageType.MMS]: "MMS",
} as const satisfies Record<SmsType, string>; } as const satisfies Record<SmsType, string>;
export const SMS_TYPE_OPTIONS = [ export const SMS_TYPE_OPTIONS = [
{ value: MessageType.SMS, label: SMS_TYPE_LABEL[MessageType.SMS] }, { value: MessageType.SMS, label: SMS_TYPE_LABEL[MessageType.SMS] },
{ value: MessageType.LMS_MMS, label: SMS_TYPE_LABEL[MessageType.LMS_MMS] }, { value: MessageType.LMS, label: SMS_TYPE_LABEL[MessageType.LMS] },
{ value: MessageType.MMS, label: SMS_TYPE_LABEL[MessageType.MMS] },
] as const; ] as const;
export const MESSAGE_TYPE_LABEL: Record<number, string> = {
...SMS_TYPE_LABEL,
[MessageType.EMAIL]: "메일",
[MessageType.KKO]: "알림톡",
};
export const TEMPLATE_PURPOSE = { export const TEMPLATE_PURPOSE = {
NORMAL: TemplatePurpose.NORMAL, NORMAL: TemplatePurpose.NORMAL,
PHONE_VERIFICATION: TemplatePurpose.PHONE_VERIFICATION, PHONE_VERIFICATION: TemplatePurpose.PHONE_VERIFICATION,
@@ -47,7 +56,7 @@ export const PHONE_VERIFICATION_PREVIEW_SUFFIX = "인증번호는 [######] 입
export const EMAIL_TEMPLATE_ATTACHMENT_MAX_COUNT = 5; export const EMAIL_TEMPLATE_ATTACHMENT_MAX_COUNT = 5;
export const EMAIL_TEMPLATE_ATTACHMENT_MAX_BYTES = 1_000_000; export const EMAIL_TEMPLATE_ATTACHMENT_MAX_BYTES = 1_000_000;
// 문자 템플릿 첨부파일 제한 (JPG만 허용, 파일당 이하 기준, 첨부 시 LMS/MMS로 저장됨) // 문자 템플릿 첨부파일 제한 (JPG만 허용, 파일당 이하 기준, 첨부 시 MMS로 저장됨)
export const SMS_TEMPLATE_ATTACHMENT_MAX_COUNT = 3; export const SMS_TEMPLATE_ATTACHMENT_MAX_COUNT = 3;
export const SMS_TEMPLATE_ATTACHMENT_MAX_BYTES = 61_440; export const SMS_TEMPLATE_ATTACHMENT_MAX_BYTES = 61_440;
export const SMS_TEMPLATE_ATTACHMENT_EXTENSION = ".jpg"; export const SMS_TEMPLATE_ATTACHMENT_EXTENSION = ".jpg";

View File

@@ -6,6 +6,14 @@
// 그 외 문자(이모지, 다른 언어 문자, 제어문자 등)는 전부 거부한다. // 그 외 문자(이모지, 다른 언어 문자, 제어문자 등)는 전부 거부한다.
export const COMMON_TEXT_REGEX = /^[가-힣A-Za-z0-9 !@#$%^&*()_+\-={}\[\]:;"'<>,.?/·~]+$/ export const COMMON_TEXT_REGEX = /^[가-힣A-Za-z0-9 !@#$%^&*()_+\-={}\[\]:;"'<>,.?/·~]+$/
// 메시지 템플릿의 제목·템플릿명·발신자명용. 다국어(스페인어, 일본어 등)와 기호는 허용하고
// 제어·서식 문자, 줄/문단 구분자, 이모지만 거부한다.
// tsconfig target(ES2017)에서 \p{...} 리터럴 대신 RegExp 생성자로 만든다.
export const TEMPLATE_TEXT_REGEX = new RegExp(
"^[^\\p{C}\\p{Zl}\\p{Zp}\\p{Emoji_Presentation}\\u{FE0F}\\u{20E3}]+$",
"u",
)
// 이메일 기본 형식(로컬@도메인.최상위도메인)만 확인한다. 세부 규칙은 백엔드 검증을 따른다. // 이메일 기본 형식(로컬@도메인.최상위도메인)만 확인한다. 세부 규칙은 백엔드 검증을 따른다.
export const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ export const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

View File

@@ -0,0 +1,77 @@
"use client";
import { useEffect } from "react";
import { useAtomValue, useStore } from "jotai";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { apiError } from "@kri/common/http";
import { authStateAtom, useAuth } from "@/hooks/useAuth";
import { selectedProjectAtom, selectedProjectHydratedAtom } from "@/store/jotai/project";
import { nextApi } from "@/lib/http-client";
import { isLoginUser } from "@/lib/auth-user";
const SESSION_QUERY_KEY = ["auth-session"] as const;
export function useAuthSession() {
const store = useStore();
const queryClient = useQueryClient();
const router = useRouter();
const { setAuth } = useAuth();
useAtomValue(selectedProjectAtom);
const projectHydrated = useAtomValue(selectedProjectHydratedAtom);
const otherQueries = { predicate: (query: { queryKey: readonly unknown[] }) => query.queryKey[0] !== SESSION_QUERY_KEY[0] };
useEffect(() => {
const refresh = () => {
void queryClient.refetchQueries({ queryKey: SESSION_QUERY_KEY, exact: true, type: "active" }, { cancelRefetch: false });
};
window.addEventListener("focus", refresh);
return () => window.removeEventListener("focus", refresh);
}, [queryClient]);
return useQuery({
queryKey: SESSION_QUERY_KEY,
enabled: projectHydrated,
staleTime: 0,
gcTime: 0,
retry: false,
refetchOnMount: "always",
refetchOnWindowFocus: "always",
meta: { ignoreGlobalLoading: true },
queryFn: async ({ signal }) => {
const previous = store.get(authStateAtom);
try {
const user = await nextApi.get<unknown>("/auth/my-info", {
cache: "no-store",
skipUnauthorizedHandler: true, skipForbiddenHandler: true, skipResponseErrorHandler: true,
});
signal.throwIfAborted();
if (!isLoginUser(user)) throw new Error("Invalid user response");
const before = previous.user;
const changed = !before || before.userId !== user.userId || before.userRole !== user.userRole ||
before.userTeam !== user.userTeam || before.userCmpn !== user.userCmpn;
if (changed) {
await queryClient.cancelQueries(otherQueries);
signal.throwIfAborted();
queryClient.removeQueries(otherQueries);
queryClient.getMutationCache().clear();
}
if (changed || before?.userName !== user.userName) setAuth({ user });
return user;
} catch (reason) {
signal.throwIfAborted();
const status = apiError(reason).status;
if (status === 401 || status === 403) {
await queryClient.cancelQueries(otherQueries);
signal.throwIfAborted();
queryClient.removeQueries(otherQueries);
queryClient.getMutationCache().clear();
store.set(selectedProjectAtom, null);
setAuth({ user: null });
router.replace("/login");
}
throw reason;
}
},
});
}

View File

@@ -1,37 +1,108 @@
'use client' 'use client'
import { useEffect, useRef, useState } from 'react' import { useCallback, useEffect, useRef, useState } from 'react'
import { useQueryClient } from '@tanstack/react-query' import { useQueryClient } from '@tanstack/react-query'
import { useAuth } from '@/hooks/useAuth' import { useAuth } from '@/hooks/useAuth'
import { useDialog } from '@/hooks/useDialog'
import { useListJobGate } from '@/components/list/ListJobGate' import { useListJobGate } from '@/components/list/ListJobGate'
import { listMutationBlockerIds } from '@/utils/listJobAvailability' import { observeListMutations } from '@/utils/listJobAvailability'
import type { ListJobType } from '@/types/list-job' import type { ListJobType } from '@/types/list-job'
/** 두 목록 화면의 공용 감시. 타인의 변경 작업도 종료 시 현재 프로젝트 데이터를 갱신한다. */ /** 두 목록 화면의 공용 감시. 타인의 변경 작업도 종료 시 현재 프로젝트 데이터를 갱신한다. */
export function useListJobPageMonitor(prjctIdx: number, jobType: ListJobType, active: boolean) { export function useListJobPageMonitor(prjctIdx: number, jobType: ListJobType, active: boolean,
{ hasSelection = false, isSubmitting = false }: { hasSelection?: boolean; isSubmitting?: boolean } = {}) {
const gate = useListJobGate({ prjctIdx, jobType, active, pollWhileIdle: true, requestLabel: jobType === 'LIST_ASSIGN' ? '배정' : '업로드·초기화·일괄 수정' }) const gate = useListJobGate({ prjctIdx, jobType, active, pollWhileIdle: true, requestLabel: jobType === 'LIST_ASSIGN' ? '배정' : '업로드·초기화·일괄 수정' })
const qc = useQueryClient() const qc = useQueryClient()
const { auth } = useAuth() const { auth } = useAuth()
const { openDialogIds } = useDialog()
const userId = auth.user?.userId const userId = auth.user?.userId
const previous = useRef<{ scope: string; ids: string[] } | null>(null) const scope = JSON.stringify([userId, prjctIdx])
const previous = useRef<{ scope: string; snapshot: ReturnType<typeof observeListMutations>['snapshot'] } | null>(null)
const sequence = useRef(0)
const generation = useRef(0)
const [pendingChange, setPendingChange] = useState<{ scope: string; id: number } | null>(null)
const inFlight = useRef<{ scope: string; id: number } | null>(null)
const [refreshingScope, setRefreshingScope] = useState<string | null>(null)
const [errorScope, setErrorScope] = useState<string | null>(null)
const [isEditing, setIsEditing] = useState(false)
const [dataRevision, setDataRevision] = useState(0) const [dataRevision, setDataRevision] = useState(0)
useEffect(() => { useEffect(() => {
const scope = JSON.stringify([userId, prjctIdx]) if (!active || !userId) {
if (!active || !userId) { previous.current = null; return } generation.current += 1
if (previous.current?.scope !== scope) previous.current = null previous.current = null
setPendingChange(null)
setErrorScope(null)
return
}
if (previous.current?.scope !== scope) {
generation.current += 1
previous.current = null
setPendingChange(null)
setErrorScope(null)
}
const availability = gate.availability const availability = gate.availability
// 실패한 조회와 최대 20건에서 잘린 응답으로 작업 종료를 단정하지 않는다. if (!gate.availabilitySucceeded || !availability) return
if (!gate.availabilitySucceeded || !availability || availability.blockerCount > availability.blockers.length) return const observation = observeListMutations(previous.current?.snapshot, availability)
const ids = listMutationBlockerIds(availability) previous.current = { scope, snapshot: observation.snapshot }
const ended = previous.current?.ids.some(id => !ids.includes(id)) ?? false if (!observation.changed) return
previous.current = { scope, ids } sequence.current += 1
if (!ended) return setPendingChange({ scope, id: sequence.current })
// 실패·중단이어도 이미 반영된 데이터가 있을 수 있다. setErrorScope(null)
void qc.invalidateQueries({ predicate: query => }, [active, userId, scope, gate.availability, gate.availabilitySucceeded, gate.availabilityUpdatedAt])
(query.queryKey[0] === 'list' || query.queryKey[0] === 'assign') && query.queryKey[2] === prjctIdx })
setDataRevision(revision => revision + 1)
}, [active, userId, prjctIdx, gate.availability, gate.availabilitySucceeded, gate.availabilityUpdatedAt, qc])
return { gate, dataRevision } useEffect(() => {
if (!active) return
const editing = (element: EventTarget | null) => element instanceof HTMLElement
&& (element.matches('input, textarea, [contenteditable="true"], [role="combobox"]')
|| !!element.closest('[role="listbox"]'))
const focusIn = (event: FocusEvent) => setIsEditing(editing(event.target))
const focusOut = (event: FocusEvent) => setIsEditing(editing(event.relatedTarget))
setIsEditing(editing(document.activeElement))
document.addEventListener('focusin', focusIn)
document.addEventListener('focusout', focusOut)
return () => {
document.removeEventListener('focusin', focusIn)
document.removeEventListener('focusout', focusOut)
}
}, [active])
const pendingRefresh = active && !!userId && pendingChange?.scope === scope
const refreshing = refreshingScope === scope
const refreshError = errorScope === scope
const refreshBlocked = openDialogIds.length > 0 || isSubmitting
|| !gate.availabilitySucceeded || gate.status !== 'allowed'
const refresh = useCallback(async () => {
if (!pendingRefresh || !pendingChange || refreshBlocked || inFlight.current?.scope === scope) return
const request = pendingChange
const requestGeneration = generation.current
inFlight.current = request
setRefreshingScope(scope)
setErrorScope(null)
try {
await qc.invalidateQueries({ predicate: query =>
(query.queryKey[0] === 'list' || query.queryKey[0] === 'assign') && query.queryKey[2] === prjctIdx },
{ throwOnError: true })
if (previous.current?.scope !== scope || generation.current !== requestGeneration) return
// 조회 중 새 변경이 감지됐다면 다음 갱신 대상으로 남긴다.
setPendingChange(current => current === request ? null : current)
setDataRevision(revision => revision + 1)
} catch {
if (previous.current?.scope === scope && generation.current === requestGeneration) setErrorScope(scope)
} finally {
if (inFlight.current === request) {
inFlight.current = null
setRefreshingScope(current => current === scope ? null : current)
}
}
}, [pendingRefresh, pendingChange, refreshBlocked, scope, prjctIdx, qc])
useEffect(() => {
if (pendingRefresh && !hasSelection && !isEditing && !refreshing && !refreshError) void refresh()
}, [pendingRefresh, hasSelection, isEditing, refreshing, refreshError, refresh])
return { gate, dataRevision, pendingRefresh, refreshing, refreshError, refreshBlocked, refresh }
} }
export type ListJobPageMonitor = ReturnType<typeof useListJobPageMonitor>

View File

@@ -0,0 +1,36 @@
"use client";
import { useAuth } from "@/hooks/useAuth";
import { formatSendCancelResult, resolveSendCancelErrorMessage, useCancelSendMutation } from "@/query/message";
import type { SendCancelRequest } from "@/types/message";
import { isFieldWorkUser } from "@/utils/userRole";
/**
* 예약 취소 확인 → 요청 → 결과 안내.
* 최종 취소 가능 여부는 서버 응답 건수로 판단하며, 요청 중에는 isPending으로 중복 요청을 막는다.
* 면접원(FW 역할 그룹)에게는 취소 기능을 제공하지 않는다(canCancel=false).
*/
export function useSendCancel() {
const { auth } = useAuth();
const cancelMutation = useCancelSendMutation();
const canCancel = auth.user != null && !isFieldWorkUser(auth.user.userRole);
const cancel = async (request: SendCancelRequest) => {
if (!canCancel || cancelMutation.isPending) return;
const confirmMessage =
request.type === "bulk"
? "이 대량발송의 예약 건을 모두 취소하시겠습니까?\n이미 발송이 시작된 건은 취소되지 않습니다."
: "이 예약 발송을 취소하시겠습니까?\n이미 발송이 시작된 건은 취소되지 않습니다.";
if (!window.confirm(confirmMessage)) return;
try {
const res = await cancelMutation.mutateAsync(request);
alert(`예약 취소 요청이 처리되었습니다.\n${formatSendCancelResult(res)}`);
} catch (error: unknown) {
alert(resolveSendCancelErrorMessage(error));
}
};
return { canCancel, cancel, isPending: cancelMutation.isPending } as const;
}

33
src/lib/auth-cookie.ts Normal file
View File

@@ -0,0 +1,33 @@
import "server-only";
import { NextResponse } from "next/server";
import { AUTH_COOKIE_MAX_AGE } from "@/const/commonConst";
import { serverEnv } from "@/lib/env.server";
import { CookieKeys } from "@/store/cookie/cookie-keys";
/** Issue/renew the normal-login cookie, or expire it when the token is empty. */
export function setAuthCookie(response: NextResponse, token: string): void {
const production = serverEnv.ENV === "prod";
const domain = serverEnv.AUTH_COOKIE_DOMAIN;
const options = {
httpOnly: true,
secure: production,
sameSite: "lax" as const,
path: "/",
};
// Serialize each cookie separately: ResponseCookies indexes cookies by name,
// so setting the shared and host-only variants on one instance loses a header.
const append = (value: string, cookieDomain: string | undefined, maxAge: number) => {
const cookieResponse = new NextResponse(null);
cookieResponse.cookies.set(CookieKeys.AuthToken, value, {
...options,
...(cookieDomain ? { domain: cookieDomain } : {}),
maxAge,
});
for (const header of cookieResponse.headers.getSetCookie())
response.headers.append("Set-Cookie", header);
};
if (domain) append("", undefined, 0);
append(token, domain, token ? AUTH_COOKIE_MAX_AGE : 0);
}

10
src/lib/auth-user.ts Normal file
View File

@@ -0,0 +1,10 @@
import {LoginUser} from "@kri/common";
export function isLoginUser(value: unknown): value is LoginUser {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
return "userId" in value && typeof value.userId === "string" && value.userId.length > 0 &&
"userName" in value && typeof value.userName === "string" &&
"userCmpn" in value && typeof value.userCmpn === "string" &&
"userTeam" in value && typeof value.userTeam === "string" &&
"userRole" in value && typeof value.userRole === "number" && Number.isSafeInteger(value.userRole);
}

File diff suppressed because it is too large Load Diff

View File

@@ -32,3 +32,9 @@ const KST_DATE_TIME_FORMAT = new Intl.DateTimeFormat('sv-SE', {
// 이메일·문자·알림톡 공통 형식이다. // 이메일·문자·알림톡 공통 형식이다.
export const toReserveSendDt = (localDateTime: string): string => export const toReserveSendDt = (localDateTime: string): string =>
KST_DATE_TIME_FORMAT.format(new Date(localDateTime)) KST_DATE_TIME_FORMAT.format(new Date(localDateTime))
// 예약 발송 일시(로컬 시각)가 현재 시각보다 이전이거나 해석할 수 없으면 true를 반환한다.
export const isPastReserveDateTime = (localDateTime: string): boolean => {
const time = new Date(localDateTime).getTime()
return Number.isNaN(time) || time < Date.now()
}

View File

@@ -3,6 +3,8 @@ import { createEnv, env } from "@kri/common/config";
export const clientEnv = createEnv({ export const clientEnv = createEnv({
ENV: env.required("NEXT_PUBLIC_ENV", process.env.NEXT_PUBLIC_ENV), ENV: env.required("NEXT_PUBLIC_ENV", process.env.NEXT_PUBLIC_ENV),
KART_URL: env.required("NEXT_PUBLIC_KART_URL", process.env.NEXT_PUBLIC_KART_URL),
API_BASE: env.required("NEXT_PUBLIC_API_BASE", process.env.NEXT_PUBLIC_API_BASE), API_BASE: env.required("NEXT_PUBLIC_API_BASE", process.env.NEXT_PUBLIC_API_BASE),
API_INTERNAL: env.required("NEXT_PUBLIC_API_INTERNAL", process.env.NEXT_PUBLIC_API_INTERNAL), API_INTERNAL: env.required("NEXT_PUBLIC_API_INTERNAL", process.env.NEXT_PUBLIC_API_INTERNAL),

View File

@@ -5,13 +5,11 @@ import { createEnv, env } from "@kri/common/config";
export const serverEnv = createEnv({ export const serverEnv = createEnv({
ENV: env.required("ENV", process.env.ENV), ENV: env.required("ENV", process.env.ENV),
AUTH_COOKIE_DOMAIN: env.optional("AUTH_COOKIE_DOMAIN", process.env.AUTH_COOKIE_DOMAIN),
CONTACT_SERVER: env.required("CONTACT_SERVER", process.env.CONTACT_SERVER), CONTACT_SERVER: env.required("CONTACT_SERVER", process.env.CONTACT_SERVER),
API_CONTACT_SERVER: env.required("API_CONTACT_SERVER", process.env.API_CONTACT_SERVER), API_CONTACT_SERVER: env.required("API_CONTACT_SERVER", process.env.API_CONTACT_SERVER),
API_INTRANET_SERVER: env.required("API_INTRANET_SERVER", process.env.API_INTRANET_SERVER), API_INTRANET_SERVER: env.required("API_INTRANET_SERVER", process.env.API_INTRANET_SERVER),
API_KART_SERVER: env.required("API_KART_SERVER", process.env.API_KART_SERVER),
KART_API_KEY: env.required("KART_API_KEY", process.env.KART_API_KEY),
}); });

View File

@@ -32,10 +32,3 @@ export const createContactApiWithApiKey = (apiKey: string) => {
export const createIntranetApi = () => { export const createIntranetApi = () => {
return createServerApi(serverEnv.API_INTRANET_SERVER); return createServerApi(serverEnv.API_INTRANET_SERVER);
}; };
//Todo: Front에서 바로 붙지 말고 Backend를 통해서 처리 하도록 수정 필요
export const createKartApi = () => {
return createServerApi(serverEnv.API_KART_SERVER, {
"X-API-Key": serverEnv.KART_API_KEY,
});
};

View File

@@ -15,14 +15,14 @@ export const Security = createSecurity({
} }
const target = window as Window & { const target = window as Window & {
__kfpaCryptoConfigAlerted?: boolean; __kriContactCryptoConfigAlerted?: boolean;
}; };
if (target.__kfpaCryptoConfigAlerted) { if (target.__kriContactCryptoConfigAlerted) {
return; return;
} }
target.__kfpaCryptoConfigAlerted = true; target.__kriContactCryptoConfigAlerted = true;
window.alert(message); window.alert(message);
}, },
}); });

View File

@@ -1,9 +1,12 @@
"use client"; "use client";
import { useMutation, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useSetAtom } from "jotai";
import { nextApi } from "@/lib/http-client"; import { nextApi } from "@/lib/http-client";
import { useAuth } from "@/hooks/useAuth"; import { useAuth } from "@/hooks/useAuth";
import { useSelectedProject } from "@/hooks/useSelectedProject"; import { useSelectedProject } from "@/hooks/useSelectedProject";
import { clearTrackedListJobs } from "@/store/list-job-tracker";
import { listJobOpenRequestAtom } from "@/store/jotai/list-job";
import type { LoginUser } from "@kri/common"; import type { LoginUser } from "@kri/common";
export const useLoginMutation = () => { export const useLoginMutation = () => {
@@ -31,6 +34,7 @@ export const useLogoutMutation = () => {
const qc = useQueryClient(); const qc = useQueryClient();
const { auth, logout } = useAuth(); const { auth, logout } = useAuth();
const { clearSelectedProject } = useSelectedProject(); const { clearSelectedProject } = useSelectedProject();
const setListJobOpenRequest = useSetAtom(listJobOpenRequestAtom);
return useMutation({ return useMutation({
mutationFn: async () => { mutationFn: async () => {
@@ -49,6 +53,8 @@ export const useLogoutMutation = () => {
}, },
onSettled: () => { onSettled: () => {
clearSelectedProject(); clearSelectedProject();
clearTrackedListJobs();
setListJobOpenRequest(null);
logout(); logout();
qc.clear(); // 다음 사용자/세션에 서버상태 남지 않게 qc.clear(); // 다음 사용자/세션에 서버상태 남지 않게
}, },

View File

@@ -38,8 +38,6 @@ export const qk = {
/********** KON, KIWI 프로젝트 관련 KART에서 받아옴 **********/ /********** KON, KIWI 프로젝트 관련 KART에서 받아옴 **********/
kartProjectList: (itrntPrjctCd: string, userTeam: string, isKiwi: number, keyword: string) => kartProjectList: (itrntPrjctCd: string, userTeam: string, isKiwi: number, keyword: string) =>
["kart", "project-list", itrntPrjctCd, userTeam, isKiwi, keyword] as const, ["kart", "project-list", itrntPrjctCd, userTeam, isKiwi, keyword] as const,
surveyRedirectUrl: (isKiwi: number, pkey: string) =>
["kart", "survey-redirect-url", isKiwi, pkey] as const,
/********** KON, KIWI 프로젝트 관련 KART에서 받아옴 **********/ /********** KON, KIWI 프로젝트 관련 KART에서 받아옴 **********/
/********** 찐 인트라넷 관련 **********/ /********** 찐 인트라넷 관련 **********/
@@ -77,8 +75,9 @@ export const qk = {
templateAttachments: (tmplatIdx: number) => ["message-template", "attachment", tmplatIdx] as const, templateAttachments: (tmplatIdx: number) => ["message-template", "attachment", tmplatIdx] as const,
templateAttachment: (tmplatIdx: number, fileName: string) => templateAttachment: (tmplatIdx: number, fileName: string) =>
["message-template", "attachment", tmplatIdx, fileName] as const, ["message-template", "attachment", tmplatIdx, fileName] as const,
kkoTemplateList: (keyword: string) => ["message-template", "kko", "list", keyword] as const, kkoSenderProfiles: ["message-template", "kko", "profiles"] as const,
kkoTemplateDetail: (templateCode: string) => ["message-template", "kko", "detail", templateCode] as const, kkoTemplateList: (senderKey: string, keyword: string) => ["message-template", "kko", "list", senderKey, keyword] as const,
kkoTemplateDetail: (senderKey: string, templateCode: string) => ["message-template", "kko", "detail", senderKey, templateCode] as const,
bulkSendList: (sendTy: number, reqstSvc: string, prjctCd: string) => bulkSendList: (sendTy: number, reqstSvc: string, prjctCd: string) =>
["message-report", "bulk-list", sendTy, reqstSvc, prjctCd] as const, ["message-report", "bulk-list", sendTy, reqstSvc, prjctCd] as const,

View File

@@ -38,6 +38,14 @@ const fetchAvailability = async (prjctIdx: number, jobType: ListJobType) =>
/** 신규 API 미배포·롤백 상태. 반복 호출하지 않고 사전 안내만 중단한다. */ /** 신규 API 미배포·롤백 상태. 반복 호출하지 않고 사전 안내만 중단한다. */
export const isAvailabilityUnsupported = (error: unknown) => error instanceof HttpError && error.status === 404 export const isAvailabilityUnsupported = (error: unknown) => error instanceof HttpError && error.status === 404
/**
* 작업을 더 이상 조회할 수 없는 경우. 기록을 지우고 반복 조회를 멈춘다.
* - 404: 작업이 만료됐거나 내 작업이 아니다.
* - 403 PROJECT_ACCESS_DENIED: 프로젝트가 삭제됐거나 접근 권한·배정·상태가 바뀌었다.
*/
export const isListJobGone = (error: unknown) => error instanceof HttpError
&& (error.status === 404 || (error.status === 403 && apiError(error).code === 'PROJECT_ACCESS_DENIED'))
export function useSubmitListJob(prjctIdx: number) { export function useSubmitListJob(prjctIdx: number) {
const qc = useQueryClient() const qc = useQueryClient()
const { auth } = useAuth() const { auth } = useAuth()

View File

@@ -8,15 +8,20 @@ import type {
ChannelType, ChannelType,
KkoTemplateDetail, KkoTemplateDetail,
KkoTemplateListResponse, KkoTemplateListResponse,
SendCancelResponse,
SendResultInfo, SendResultInfo,
SendResultSummaryRequest, SendResultSummaryRequest,
SendResultSummaryResponse, SendResultSummaryResponse,
} from "@kri/common/noti-hub"; } from "@kri/common/noti-hub";
import { parseSendCancelResponse } from "@kri/common/noti-hub";
import type { FileResponse, PageRequest, PageResponse } from "@kri/common"; import type { FileResponse, PageRequest, PageResponse } from "@kri/common";
import { apiError, HttpError } from "@kri/common/http";
import type { ProjectMainTemplateUpdateRequest } from "@/types/project"; import type { ProjectMainTemplateUpdateRequest } from "@/types/project";
import type { import type {
KkoSenderProfile,
MessageSendChannel, MessageSendChannel,
MessageSendSingleRequest, MessageSendSingleRequest,
SendCancelRequest,
SendSingleResponse, SendSingleResponse,
} from "@/types/message"; } from "@/types/message";
import type { TemplateAttachmentImage, TemplateSummaryWithPurpose, TemplateWithPurpose } from "@/types/message"; import type { TemplateAttachmentImage, TemplateSummaryWithPurpose, TemplateWithPurpose } from "@/types/message";
@@ -87,6 +92,42 @@ export function useSaveTemplateMutation(chnnlTy: ChannelType, itrntPrjctCd: stri
}); });
} }
export const resolveDeleteTemplateErrorMessage = (error: unknown) => {
if (error instanceof HttpError) {
const { code, message } = apiError(error, { fallbackMessage: "템플릿을 삭제하지 못했습니다." });
if (error.status === 409 || code === "TEMPLATE_IN_USE") return "사용 중인 템플릿이라 삭제할 수 없습니다.";
if (error.status === 403 || code === "MESSAGE_TEMPLATE_FORBIDDEN") return "템플릿 관리 권한이 없습니다.";
return message;
}
return "템플릿을 삭제하지 못했습니다.";
};
/**
* 템플릿 삭제 (DELETE /message-template/{tmplatIdx})
* 403으로 전역 로그아웃되지 않도록 기본 오류 처리를 건너뛰고, 화면에서 resolveDeleteTemplateErrorMessage로 안내한다.
* 해당 템플릿의 대표 연결은 서버에서 제거하므로 성공 시 목록과 대표 템플릿을 다시 불러온다.
*/
export function useDeleteTemplateMutation(chnnlTy: ChannelType, itrntPrjctCd: string, prjctIdx: number) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (tmplatIdx: number) => {
await nextApi.del(`/message-template/${tmplatIdx}`, {
expectText: true,
skipForbiddenHandler: true,
skipResponseErrorHandler: true,
});
},
retry: false,
onSuccess: (_data, tmplatIdx) => {
qc.removeQueries({ queryKey: qk.template(tmplatIdx) });
qc.removeQueries({ queryKey: qk.templateAttachments(tmplatIdx) });
qc.invalidateQueries({ queryKey: qk.templateList(chnnlTy, itrntPrjctCd) });
qc.invalidateQueries({ queryKey: qk.mainTemplate(prjctIdx, chnnlTy) });
},
});
}
/** /**
* 템플릿 첨부파일 단건 다운로드 (GET /message-template/{tmplatIdx}/attachment?fileName=...) * 템플릿 첨부파일 단건 다운로드 (GET /message-template/{tmplatIdx}/attachment?fileName=...)
*/ */
@@ -164,16 +205,31 @@ export function useUploadTemplateBodyImageMutation(itrntPrjctCd: string) {
}); });
} }
/** /** 외부 알림톡 발신 프로필 조회 */
* 외부 알림톡 템플릿 목록 (POST /message-template/kko/list) export function useKkoSenderProfilesQuery(enabled: boolean) {
* keyword가 빈 값이면 기본 목록(ACT 상태 첫 페이지 최대 10개)을 조회한다.
*/
export function useKkoTemplateListQuery(keyword: string, enabled: boolean) {
return useQuery({ return useQuery({
queryKey: qk.kkoTemplateList(keyword), queryKey: qk.kkoSenderProfiles,
queryFn: async () => {
const profiles: unknown = await nextApi.get("/message-template/kko/profiles");
if (!Array.isArray(profiles) || !profiles.every((profile) =>
profile && typeof profile.senderKey === "string" && profile.senderKey.trim() &&
typeof profile.name === "string" && typeof profile.uuid === "string" && profile.uuid.trim(),
)) throw new Error("발신 프로필 응답 형식이 올바르지 않습니다.");
return profiles as KkoSenderProfile[];
},
enabled,
retry: false,
meta: { ignoreGlobalLoading: true },
});
}
/** keyword가 빈 값이면 선택한 프로필의 기본 목록을 조회한다. */
export function useKkoTemplateListQuery(senderKey: string, keyword: string, enabled: boolean) {
return useQuery({
queryKey: qk.kkoTemplateList(senderKey, keyword),
queryFn: async () => { queryFn: async () => {
const res = await nextApi const res = await nextApi
.post<KkoTemplateListResponse>(`/message-template/kko/list`, keyword ? { keyword } : {}, { .post<KkoTemplateListResponse>(`/message-template/kko/list`, { senderKey, ...(keyword ? { keyword } : {}) }, {
skipResponseErrorHandler: true, skipResponseErrorHandler: true,
}) })
.catch((error: unknown) => { .catch((error: unknown) => {
@@ -183,7 +239,7 @@ export function useKkoTemplateListQuery(keyword: string, enabled: boolean) {
// 외부 응답이므로 list가 배열이 아닌 경우를 빈 목록으로 다룬다. // 외부 응답이므로 list가 배열이 아닌 경우를 빈 목록으로 다룬다.
return Array.isArray(res?.list) ? res.list : []; return Array.isArray(res?.list) ? res.list : [];
}, },
enabled, enabled: enabled && !!senderKey,
staleTime: 0, staleTime: 0,
retry: false, retry: false,
meta: { ignoreGlobalLoading: true }, meta: { ignoreGlobalLoading: true },
@@ -193,14 +249,14 @@ export function useKkoTemplateListQuery(keyword: string, enabled: boolean) {
/** /**
* 외부 알림톡 템플릿 상세 (POST /message-template/kko/detail) * 외부 알림톡 템플릿 상세 (POST /message-template/kko/detail)
*/ */
export const fetchKkoTemplateDetail = (templateCode: string) => export const fetchKkoTemplateDetail = (senderKey: string, templateCode: string) =>
nextApi.post<KkoTemplateDetail>(`/message-template/kko/detail`, { templateCode }); nextApi.post<KkoTemplateDetail>(`/message-template/kko/detail`, { senderKey, templateCode });
export function useKkoTemplateDetailQuery(templateCode: string, enabled: boolean) { export function useKkoTemplateDetailQuery(senderKey: string, templateCode: string, enabled: boolean) {
return useQuery({ return useQuery({
queryKey: qk.kkoTemplateDetail(templateCode), queryKey: qk.kkoTemplateDetail(senderKey, templateCode),
queryFn: () => fetchKkoTemplateDetail(templateCode), queryFn: () => fetchKkoTemplateDetail(senderKey, templateCode),
enabled: enabled && !!templateCode, enabled: enabled && !!senderKey && !!templateCode,
staleTime: 0, staleTime: 0,
retry: false, retry: false,
meta: { ignoreGlobalLoading: true }, meta: { ignoreGlobalLoading: true },
@@ -297,3 +353,37 @@ export function useSendResultBySidQuery(
meta: { ignoreGlobalLoading: true }, meta: { ignoreGlobalLoading: true },
}); });
} }
export const formatSendCancelResult = (res: SendCancelResponse) =>
`취소 ${res.canceledCount.toLocaleString()}건 / 이미 취소 ${res.alreadyCanceledCount.toLocaleString()}건 / 취소 불가 ${res.notCancelableCount.toLocaleString()}건`;
// 타임아웃·연결 오류·게이트웨이 오류는 서버에서 취소가 처리됐을 수 있으므로 실패로 확정하지 않는다.
const UNCONFIRMED_CANCEL_STATUSES = new Set([0, 408, 502, 503, 504]);
export const resolveSendCancelErrorMessage = (error: unknown) => {
if (error instanceof HttpError && !UNCONFIRMED_CANCEL_STATUSES.has(error.status)) {
return apiError(error, { fallbackMessage: "예약 취소를 처리하지 못했습니다." }).message;
}
return "취소 처리 결과를 확인하지 못했습니다. 다시 조회된 목록에서 취소 상태를 확인해 주세요.";
};
/**
* 예약 취소 (POST /message-send/cancel/{single|bulk}, contactServer 경유)
* 취소 불가 건이 있어도 200으로 응답하므로 건수로 결과를 안내하고, 성공·실패와 무관하게 발송 조회를 다시 불러온다.
* 타임아웃 시 결과를 알 수 없으므로 자동 재시도하지 않는다.
*/
export function useCancelSendMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (req: SendCancelRequest) => {
const body = req.type === "single" ? { sendIdx: req.sendIdx } : { bulkSendKey: req.bulkSendKey };
const res = await nextApi.post<unknown>(`/message-send/cancel/${req.type}`, body, {
skipResponseErrorHandler: true,
});
return parseSendCancelResponse(res);
},
retry: false,
onSettled: () => queryClient.invalidateQueries({ queryKey: ["message-report"] }),
});
}

View File

@@ -121,8 +121,8 @@ export function useKartProjectListQuery(args: {
queryKey: qk.kartProjectList(args.itrntPrjctCd, args.userTeam, args.isKiwi, kw), queryKey: qk.kartProjectList(args.itrntPrjctCd, args.userTeam, args.isKiwi, kw),
queryFn: () => queryFn: () =>
nextApi.get<KonKiwiProjectInfo[]>( nextApi.get<KonKiwiProjectInfo[]>(
`/kart/project-list/${args.itrntPrjctCd}/${args.userTeam}/${args.isKiwi}`, `/kart/project-list/${encodeURIComponent(args.itrntPrjctCd)}/${args.isKiwi}`,
{ query: kw ? { keyword: kw } : {} } { query: kw ? { keyword: kw } : {}, skipForbiddenHandler: true }
), ),
enabled: args.enabled, enabled: args.enabled,
staleTime: 0, staleTime: 0,
@@ -131,19 +131,6 @@ export function useKartProjectListQuery(args: {
}); });
} }
/**
* KON/KIWI 설문 현황(리포트) 바로가기 URL
*/
export function useSurveyRedirectUrlQuery(isKiwi: number, pkey: string, enabled: boolean) {
return useQuery({
queryKey: qk.surveyRedirectUrl(isKiwi, pkey),
queryFn: () => nextApi.get<string>(`/kart/survey-redirect-url/${isKiwi}/${encodeURIComponent(pkey)}`),
enabled: enabled && !!pkey,
staleTime: 0,
meta: { ignoreGlobalLoading: true },
});
}
/** /**
* 프로젝트에 배정된 회사 ID 목록 * 프로젝트에 배정된 회사 ID 목록
*/ */

View File

@@ -1,6 +1,6 @@
export const CookieKeys = { export const CookieKeys = {
FontSize: "kri_fontSize", FontSize: "kri_fontSize",
AuthToken: "kri_authToken", AuthToken: "kri_internal_authToken",
// 필요하면 여기 계속 추가 (예: Theme: "kri_theme", ...) // 필요하면 여기 계속 추가 (예: Theme: "kri_theme", ...)
} as const; } as const;

View File

@@ -1,7 +1,7 @@
'use client' 'use client'
import { useSyncExternalStore } from 'react' import { useSyncExternalStore } from 'react'
import { getLocalStorage, setLocalStorage } from '@/store/storage/secure-storage' import { getLocalStorage, removeLocalStorage, setLocalStorage } from '@/store/storage/secure-storage'
import { StorageKeys } from '@/store/storage/storage-keys' import { StorageKeys } from '@/store/storage/storage-keys'
import { isListJobType, type ListJobType } from '@/types/list-job' import { isListJobType, type ListJobType } from '@/types/list-job'
@@ -77,6 +77,14 @@ export const untrackListJob = (jobKey: string) => {
write(jobs.filter((job) => job.jobKey !== jobKey)) write(jobs.filter((job) => job.jobKey !== jobKey))
} }
/** 로그아웃 시 다음 사용자에게 기록이 남지 않게 모두 지운다. 진행 중인 작업은 재로그인 후 my-active 조회로 다시 채워진다. */
export const clearTrackedListJobs = () => {
if (typeof window === 'undefined') return
removeLocalStorage(StorageKeys.ListJobs)
cache = EMPTY
window.dispatchEvent(new Event(CHANGE_EVENT))
}
export const findTrackedListJob = (jobs: TrackedListJob[], userId: string, prjctIdx: number, jobType: ListJobType) => export const findTrackedListJob = (jobs: TrackedListJob[], userId: string, prjctIdx: number, jobType: ListJobType) =>
jobs.find((job) => job.userId === userId && job.prjctIdx === prjctIdx && job.jobType === jobType) jobs.find((job) => job.userId === userId && job.prjctIdx === prjctIdx && job.jobType === jobType)

View File

@@ -1,4 +1,4 @@
export type ListJobStatus = 'QUEUED' | 'RUNNING' | 'CANCEL_REQUESTED' | 'SUCCEEDED' | 'FAILED' | 'CANCELLED' | 'REJECTED' export type ListJobStatus = 'QUEUED' | 'RUNNING' | 'CANCEL_REQUESTED' | 'SUCCEEDED' | 'PARTIALLY_SUCCEEDED' | 'FAILED' | 'CANCELLED' | 'REJECTED'
// 배정·배정 초기화는 LIST_ASSIGN 하나로 통합됐다. 두 명령은 operation(ASSIGN/RESET)으로만 구분한다. // 배정·배정 초기화는 LIST_ASSIGN 하나로 통합됐다. 두 명령은 operation(ASSIGN/RESET)으로만 구분한다.
export const LIST_JOB_TYPES = [ export const LIST_JOB_TYPES = [
@@ -66,18 +66,24 @@ export type ListJobBlocker = {
regDt: string regDt: string
} }
export type ListMutationCompletion = {
finishedCount: number
lastFinishedAt: string | null
}
export type ListJobAvailability = { export type ListJobAvailability = {
requestedJobType: string requestedJobType: string
allowed: boolean allowed: boolean
reasonCode: string | null reasonCode: string | null
blockerCount: number blockerCount: number
blockers: ListJobBlocker[] blockers: ListJobBlocker[]
mutationCompletion?: ListMutationCompletion
} }
export const isActiveListJob = (status: ListJobStatus) => export const isActiveListJob = (status: ListJobStatus) =>
status === 'QUEUED' || status === 'RUNNING' || status === 'CANCEL_REQUESTED' status === 'QUEUED' || status === 'RUNNING' || status === 'CANCEL_REQUESTED'
const statuses: string[] = ['QUEUED', 'RUNNING', 'CANCEL_REQUESTED', 'SUCCEEDED', 'FAILED', 'CANCELLED', 'REJECTED'] const statuses: string[] = ['QUEUED', 'RUNNING', 'CANCEL_REQUESTED', 'SUCCEEDED', 'PARTIALLY_SUCCEEDED', 'FAILED', 'CANCELLED', 'REJECTED']
const isJobKeyOrNull = (value: unknown) => value === null || (typeof value === 'string' && /^[a-f0-9]{32}$/.test(value)) const isJobKeyOrNull = (value: unknown) => value === null || (typeof value === 'string' && /^[a-f0-9]{32}$/.test(value))
export function parseListJob(value: unknown): ListJob { export function parseListJob(value: unknown): ListJob {
@@ -146,11 +152,31 @@ export function parseListJobAvailability(value: unknown): ListJobAvailability {
|| typeof body.blockerCount !== 'number' || !Array.isArray(body.blockers) || !body.blockers.every(isBlocker)) { || typeof body.blockerCount !== 'number' || !Array.isArray(body.blockers) || !body.blockers.every(isBlocker)) {
throw new Error('작업 가능 여부 응답이 올바르지 않습니다.') throw new Error('작업 가능 여부 응답이 올바르지 않습니다.')
} }
const completion = body.mutationCompletion
let mutationCompletion: ListMutationCompletion | undefined
if (completion !== undefined) {
if (!completion || typeof completion !== 'object'
|| !('finishedCount' in completion) || typeof completion.finishedCount !== 'number'
|| !Number.isSafeInteger(completion.finishedCount) || completion.finishedCount < 0
|| !('lastFinishedAt' in completion)
|| !(completion.lastFinishedAt === null || typeof completion.lastFinishedAt === 'string')
|| !(completion.finishedCount === 0 ? completion.lastFinishedAt === null
: typeof completion.lastFinishedAt === 'string'
&& /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(completion.lastFinishedAt)
&& !Number.isNaN(Date.parse(completion.lastFinishedAt)))) {
throw new Error('작업 종료 요약 응답이 올바르지 않습니다.')
}
mutationCompletion = {
finishedCount: completion.finishedCount,
lastFinishedAt: completion.lastFinishedAt,
}
}
return { return {
requestedJobType: body.requestedJobType, requestedJobType: body.requestedJobType,
allowed: body.allowed, allowed: body.allowed,
reasonCode: body.reasonCode, reasonCode: body.reasonCode,
blockerCount: body.blockerCount, blockerCount: body.blockerCount,
blockers: body.blockers, blockers: body.blockers,
...(mutationCompletion === undefined ? {} : { mutationCompletion }),
} }
} }

View File

@@ -36,11 +36,6 @@ export enum ListUploadMode {
ADD_AND_CHANGE = 1, ADD_AND_CHANGE = 1,
} }
export enum ListResetMode {
ALL = 0,
HIST = 1,
}
export enum ListEventHistoryBase { export enum ListEventHistoryBase {
ALL = 1, ALL = 1,
LATEST = 2, LATEST = 2,
@@ -90,7 +85,12 @@ export type ListDownloadPayload = {
historyOrder?: ListEventHistoryOrder; historyOrder?: ListEventHistoryOrder;
}; };
export type ListResetScope = 'result-and-history' | 'list-only'; export type ListResetSelection = {
resetList: boolean;
resetContactHistory: boolean;
resetInterviewHistory: boolean;
resetSurveyIds: number[];
};
export type ListFilterCondition = { export type ListFilterCondition = {
operator: ListFilterOperator; operator: ListFilterOperator;
@@ -121,6 +121,11 @@ export type listHeader = {
useIntrvwerView: boolean; useIntrvwerView: boolean;
useIntrvwerEdit: boolean; useIntrvwerEdit: boolean;
filterContents?: string[]; filterContents?: string[];
/**
* 헤더 색상(`#RRGGBB` 또는 `#RRGGBBAA`). null/빈 문자열은 기본색.
* 헤더 저장은 전체 덮어쓰기라 조회한 값을 그대로 다시 보내야 기존 색상이 유지된다.
*/
listHderColor?: string | null;
}; };
export type SurveyResultCondition = { export type SurveyResultCondition = {
@@ -308,8 +313,6 @@ export type ListCallHist = ListCallCloseRequest & {
regDt: string; regDt: string;
}; };
export type ListCallHistSession = ListCallHist;
export type ListReserveRequest = { export type ListReserveRequest = {
prjctIdx: number; prjctIdx: number;
sid: string; sid: string;
@@ -353,8 +356,7 @@ export type ProjectFieldworkAssignSummary = {
assignees: FieldworkAssignSummaryItem[]; assignees: FieldworkAssignSummaryItem[];
}; };
export type ListResetRequest = { export type ListResetRequest = ListResetSelection & {
resetMode: ListResetMode;
listFilter: ListFilter; listFilter: ListFilter;
}; };

View File

@@ -1,8 +1,24 @@
import type { MessageType, Template, TemplatePurpose, TemplateSummary } from '@kri/common/noti-hub'; import type {
MessageType,
SendCancelBulkRequest,
SendCancelSingleRequest,
Template,
TemplateKko,
TemplatePurpose,
TemplateSummary,
} from '@kri/common/noti-hub';
import type { ListFilter } from './list'; import type { ListFilter } from './list';
export type KkoSenderProfile = {
senderKey: string;
name: string;
uuid: string;
};
export type KkoTemplateWithProfile = TemplateKko & { senderKey?: string };
// 서버 조회 응답은 모든 채널의 템플릿에 tmplatPurpose를 내려준다. 화면 상태에서는 필수로 다룬다. // 서버 조회 응답은 모든 채널의 템플릿에 tmplatPurpose를 내려준다. 화면 상태에서는 필수로 다룬다.
export type TemplateWithPurpose = Template & { export type TemplateWithPurpose = (Exclude<Template, TemplateKko> | KkoTemplateWithProfile) & {
tmplatPurpose: TemplatePurpose; tmplatPurpose: TemplatePurpose;
}; };
@@ -30,9 +46,16 @@ export type PhoneVerificationSendData = {
export type SendSingleResponse = { export type SendSingleResponse = {
cmid: string; cmid: string;
/** 수신처를 여러 개 선택한 경우 마지막 발송 건의 식별자 */
sendIdx?: number;
data: Record<string, unknown>; data: Record<string, unknown>;
}; };
/** 예약 취소 요청. type으로 단건(/cancel/single)·벌크(/cancel/bulk) 경로를 구분한다. */
export type SendCancelRequest =
| ({ type: 'single' } & SendCancelSingleRequest)
| ({ type: 'bulk' } & SendCancelBulkRequest);
export type MessageSendSingleRequest = { export type MessageSendSingleRequest = {
tmplatIdx: number; tmplatIdx: number;
resve: boolean; resve: boolean;

View File

@@ -1,5 +1,5 @@
import { listJobLabel } from '@/const/listJobConst' import { listJobLabel } from '@/const/listJobConst'
import type { ListJobAvailability, ListJobBlocker, ListJobType } from '@/types/list-job' import type { ListJobAvailability, ListJobBlocker, ListJobType, ListMutationCompletion } from '@/types/list-job'
const MUTATION_JOB_TYPES = new Set(['LIST_UPLOAD', 'LIST_RESET', 'LIST_UPDATE', 'LIST_ASSIGN']) const MUTATION_JOB_TYPES = new Set(['LIST_UPLOAD', 'LIST_RESET', 'LIST_UPDATE', 'LIST_ASSIGN'])
@@ -8,6 +8,29 @@ export const listMutationBlockerIds = (availability: ListJobAvailability) => ava
.filter(blocker => MUTATION_JOB_TYPES.has(blocker.jobType)) .filter(blocker => MUTATION_JOB_TYPES.has(blocker.jobType))
.map(blocker => JSON.stringify([blocker.jobType, blocker.operation, blocker.requestUserId, blocker.regDt])) .map(blocker => JSON.stringify([blocker.jobType, blocker.operation, blocker.requestUserId, blocker.regDt]))
type ListMutationSnapshot = {
ids: string[] | null
completion: ListMutationCompletion | undefined
}
/** 요약은 짧은 작업도 감지한다. 구버전 서버에서는 기존 차단 목록의 종료 감지를 유지한다. */
export function observeListMutations(previous: ListMutationSnapshot | undefined, availability: ListJobAvailability) {
const ids = availability.blockerCount > availability.blockers.length ? null : listMutationBlockerIds(availability)
const completion = availability.mutationCompletion
const completionChanged = previous !== undefined && completion !== undefined
&& (previous.completion === undefined
|| previous.completion.finishedCount !== completion.finishedCount
|| previous.completion.lastFinishedAt !== completion.lastFinishedAt)
const ended = ids !== null && (previous?.ids?.some(id => !ids.includes(id)) ?? false)
return {
changed: completionChanged || ended,
snapshot: {
ids: ids ?? previous?.ids ?? null,
completion: completion ?? previous?.completion,
},
}
}
export function isListPageActionBlocked(availability: ListJobAvailability | undefined, jobType: ListJobType, unavailable: boolean) { export function isListPageActionBlocked(availability: ListJobAvailability | undefined, jobType: ListJobType, unavailable: boolean) {
if (unavailable) return true if (unavailable) return true
if (!availability) return false // availability 미배포(404)는 실제 접수 시 서버 판단에 맡긴다. if (!availability) return false // availability 미배포(404)는 실제 접수 시 서버 판단에 맡긴다.

View File

@@ -0,0 +1,58 @@
import { listJobLabel } from '@/const/listJobConst'
import type { ListJob } from '@/types/list-job'
/** SID와 수신자 건수는 단위가 다르므로 합산하지 않는다. */
export function formatMessageJobResult(progress: ListJob['progress']): string {
const p = progress ?? {}
const accepted = p.acceptedRecipientCnt
const parts = [typeof accepted === 'number' && Number.isSafeInteger(accepted) && accepted >= 0
? `${accepted.toLocaleString()}건 접수 완료` : '접수 건수 확인 불가']
const fields = [
['preparationFailedSidCnt', '준비 실패 SID', '개'],
['noDestinationSkippedSidCnt', '수신처 없음 SID', '개 제외'],
['failedRecipientCnt', '접수 실패', '건'],
['unknownRecipientCnt', '접수 여부 불명', '건'],
] as const
for (const [field, label, unit] of fields) {
const value = p[field]
if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) {
parts.push(`${label} ${value.toLocaleString()}${unit}`)
}
}
return parts.join(', ')
}
type JobNotification = {
kind: 'success' | 'warning' | 'info' | 'error'
message: string
description?: string
}
/** errorCode가 있어도 최종 성공 여부는 서버 jobStatus를 따른다. */
export function getListJobResultNotification(job: ListJob): JobNotification {
const label = listJobLabel(job.jobType, job.operation)
const messageJob = job.jobType.endsWith('_BULK')
const summary = messageJob ? formatMessageJobResult(job.progress) : undefined
switch (job.jobStatus) {
case 'SUCCEEDED':
return {
kind: 'success',
message: messageJob ? `${label} 접수 완료` : `${label} 작업이 완료됐습니다.`,
description: summary,
}
case 'PARTIALLY_SUCCEEDED':
return {
kind: 'warning',
message: `${label} 일부 접수 완료`,
description: [summary, '접수는 실제 전달 완료가 아닙니다. 전체 재발송 전에 접수 내역을 확인해 주세요.'].filter(Boolean).join('\n'),
}
case 'CANCELLED':
return { kind: 'info', message: `${label} 작업이 중단됐습니다.`, description: summary }
default:
return {
kind: 'error',
message: job.jobStatus === 'REJECTED' ? `${label} 접수가 거절됐습니다.` : `${label} 작업이 실패했습니다.`,
description: [job.errorMessage, summary].filter(Boolean).join('\n'),
}
}
}