From d8b565276d39591091f744ddeeebb37804cbb0f0 Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Mon, 20 Jul 2026 14:59:52 +0900 Subject: [PATCH 1/2] =?UTF-8?q?260720=5F01=5FDOC:=20=EC=9D=98=EB=AF=B8=20?= =?UTF-8?q?=EC=97=86=EB=8A=94=20=ED=8C=8C=EC=9D=BC=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/claudeCodeEditorTabs.xml | 21 --------------------- 1 file changed, 21 deletions(-) delete mode 100644 .idea/claudeCodeEditorTabs.xml diff --git a/.idea/claudeCodeEditorTabs.xml b/.idea/claudeCodeEditorTabs.xml deleted file mode 100644 index e8330c8..0000000 --- a/.idea/claudeCodeEditorTabs.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - \ No newline at end of file -- 2.49.0.windows.1 From 2dd5b88c6fa4eced6c1801c34a8a9f25de85a93d Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Wed, 22 Jul 2026 16:53:00 +0900 Subject: [PATCH 2/2] =?UTF-8?q?260722=5F01=5FENH:=20=EB=B2=84=EA=B7=B8=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20=EB=B0=8F=20=EA=B0=9C=EC=84=A0=20=EC=82=AC?= =?UTF-8?q?=ED=95=AD=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/claudeCodeEditorTabs.xml | 21 + src/app/(pages)/(main)/assign/list/page.tsx | 16 +- .../(pages)/(main)/assign/project/page.tsx | 21 +- src/app/(pages)/(main)/list/contact/page.tsx | 17 +- src/app/(pages)/(main)/list/manage/page.tsx | 7 +- src/app/(pages)/(main)/manage/user/page.tsx | 11 +- src/app/(pages)/(main)/page.tsx | 22 +- .../(pages)/(main)/progress/survey/page.tsx | 83 ++- src/app/(pages)/(main)/project/info/page.tsx | 634 ++++++++++++------ src/app/(pages)/login/page.tsx | 8 +- src/app/api/external/[[...slug]]/route.ts | 14 +- src/app/api/intranet/[[...slug]]/route.ts | 8 +- .../api/list-call-hist/[[...slug]]/route.ts | 19 + src/app/api/list/[[...slug]]/route.ts | 11 + src/components/common/KriAutoComplete.tsx | 88 ++- src/components/common/KriPassword.tsx | 29 +- src/components/common/KriSelect.tsx | 56 +- .../common/multi-select/MultiSelect.tsx | 4 +- .../multi-select/MultiSelectTrigger.tsx | 4 +- src/components/common/multi-select/types.ts | 1 + src/components/data-table/DataTable.tsx | 25 +- src/components/data-table/DataTable.type.ts | 9 +- src/components/dialog/CmpnUpsertDialog.tsx | 86 ++- src/components/dialog/ListBatchEditDialog.tsx | 121 +++- .../ListDialogOption/ApplyFilterOption.tsx | 12 + src/components/dialog/ListDownloadDialog.tsx | 4 +- src/components/dialog/ListResetDialog.tsx | 5 +- src/components/dialog/ListUploadDialog.tsx | 7 +- .../dialog/MessageHistoryDialog.tsx | 5 +- src/components/dialog/MessageSendDialog.tsx | 4 +- src/components/dialog/ProjectCreateDialog.tsx | 121 ++-- .../dialog/SingleMessageSendDialog.tsx | 1 - src/components/dialog/UserUploadDialog.tsx | 7 +- src/components/dialog/UserUpsertDialog.tsx | 150 +++-- .../kri-editor/KriEditorHtmlOnly.tsx | 2 +- src/components/kri-editor/KriEditorSms.tsx | 2 +- .../kri-editor/KriEditorWysiwyg.tsx | 10 +- .../list-contact/ListContactEventPanel.tsx | 27 +- .../list-contact/ListContactInfoPanel.tsx | 170 +++-- src/components/list/ListSearchTable.tsx | 101 ++- .../message-template/MessageTemplate.tsx | 89 +-- .../message-template/MessageVariableList.tsx | 78 +++ src/components/providers/AppProvider.tsx | 13 +- .../table-column/CmpnTableColumn.tsx | 2 + .../table-column/ListTableColumn.tsx | 137 ++-- .../table-column/ProjectTableColumn.tsx | 14 +- .../table-column/UserTableColumn.tsx | 3 + src/components/ui/input.tsx | 3 +- src/const/projectConst.ts | 4 +- src/const/userConst.ts | 3 - src/const/validationConst.ts | 17 + src/hooks/useCtiLastCallHistId.ts | 10 +- src/lib/cti/ctiClient.ts | 162 ++++- src/query/intranet.ts | 13 +- src/query/key/keys.ts | 1 + src/query/list.ts | 17 +- src/query/project.ts | 8 +- src/query/user.ts | 7 +- src/store/jotai/project.ts | 2 - src/store/storage/storage-keys.ts | 4 +- src/types/external.ts | 4 +- src/types/list.ts | 43 +- src/types/message.ts | 4 + src/types/project.ts | 19 +- src/types/user.ts | 5 + src/utils/listAccess.ts | 6 +- src/utils/validation.ts | 50 ++ 67 files changed, 1925 insertions(+), 736 deletions(-) create mode 100644 .idea/claudeCodeEditorTabs.xml create mode 100644 src/components/message-template/MessageVariableList.tsx create mode 100644 src/const/validationConst.ts create mode 100644 src/utils/validation.ts diff --git a/.idea/claudeCodeEditorTabs.xml b/.idea/claudeCodeEditorTabs.xml new file mode 100644 index 0000000..58da843 --- /dev/null +++ b/.idea/claudeCodeEditorTabs.xml @@ -0,0 +1,21 @@ + + + + + + + + \ No newline at end of file diff --git a/src/app/(pages)/(main)/assign/list/page.tsx b/src/app/(pages)/(main)/assign/list/page.tsx index 64f952f..3fc1b39 100644 --- a/src/app/(pages)/(main)/assign/list/page.tsx +++ b/src/app/(pages)/(main)/assign/list/page.tsx @@ -11,7 +11,7 @@ import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs' import { KriMultiSelect } from '@/components/common/KriAutoComplete' import { AssignTargetList, useAssignTargetRows } from '@/components/assign/AssignTargetList' import { ListSearchTable } from '@/components/list/ListSearchTable' -import { useResultCodesQuery } from '@/query/project' +import { useProjectInfoQuery, useResultCodesQuery } from '@/query/project' import { useListHeaderQuery } from '@/query/list' import { useResetListAssignMutation, useUpsertListAssignMutation } from '@/query/assign' import { ListHeaderAssignConst, LIST_HEADER_TYPE_LABEL } from '@/const/listConst' @@ -42,14 +42,17 @@ const ListAssignPage = () => { const [assignFilterIds, setAssignFilterIds] = useState([]) const [transferResve, setTransferResve] = useState(false) const [currentListFilter, setCurrentListFilter] = useState(() => createEmptyListFilter()) + const [filterSummary, setFilterSummary] = useState([]) const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled) + const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled) const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled) const upsertListAssignMutation = useUpsertListAssignMutation(prjctIdx) const resetListAssignMutation = useResetListAssignMutation(prjctIdx) const assignTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType }) const resultCodeArray = useMemo(() => resultCodesQuery.data ?? [], [resultCodesQuery.data]) + const surveyArray = useMemo(() => projectInfoQuery.data?.surveys ?? [], [projectInfoQuery.data]) const listHeaders = useMemo(() => listHeaderQuery.data ?? [], [listHeaderQuery.data]) const handleTabChange = (value: string) => { @@ -91,12 +94,16 @@ const ListAssignPage = () => { return { type: assignType, values: assignFilterIds } }, [assignType, assignFilterIds]) + const hasNoAppliedFilter = () => filterSummary.length === 0 && assignFilterIds.length === 0 + const handleAssign = async () => { if (!selectedAssignId) { alert('배정할 대상을 선택해주세요.') return } - + if (hasNoAppliedFilter() && !confirm('적용된 필터가 없습니다. 전체 리스트를 대상으로 진행 하시겠습니까?')) { + return + } await upsertListAssignMutation.mutateAsync({ assignId: selectedAssignId, @@ -110,6 +117,9 @@ const ListAssignPage = () => { } const handleResetAssign = async () => { + if (hasNoAppliedFilter() && !confirm('적용된 필터가 없습니다. 전체 리스트를 대상으로 진행 하시겠습니까?')) { + return + } if (!confirm('정말 배정을 초기화 하시겠습니까?')) return await resetListAssignMutation.mutateAsync({ @@ -151,9 +161,11 @@ const ListAssignPage = () => { userId={auth?.user?.userId ?? ''} userCmpn={auth?.user?.userCmpn ?? ''} resultCodes={resultCodeArray} + surveys={surveyArray} listHeaders={listHeaders} selectMode="none" onCurrentFilterChange={setCurrentListFilter} + onFilterSummaryChange={setFilterSummary} excludeFilterHeaderTypes={[assignType]} externalAssignFilter={externalAssignFilter} filterActions={ diff --git a/src/app/(pages)/(main)/assign/project/page.tsx b/src/app/(pages)/(main)/assign/project/page.tsx index b54ac7e..2894851 100644 --- a/src/app/(pages)/(main)/assign/project/page.tsx +++ b/src/app/(pages)/(main)/assign/project/page.tsx @@ -141,9 +141,7 @@ const ProjectAssignPage = () => { }; const { - assignBase, assignView, - ableBase, ableView, } = useMemo(() => { const roleVal = roleFilter?.value; @@ -168,9 +166,7 @@ const ProjectAssignPage = () => { const _ableView = kAble ? _ableBase0.filter((u) => kwFilter(u, kAble)) : _ableBase0; return { - assignBase: _assignBase, assignView: _assignView, - ableBase: _ableBase0, ableView: _ableView, }; }, [ @@ -218,18 +214,21 @@ const ProjectAssignPage = () => { alert("저장되었습니다."); }; + // 로그인 계정의 소속 회사를 기본 선택하되, 매치되는 게 없으면 자사(ownCmpn) 중 가장 상단 1개로 대체한다. useEffect(() => { const cmpn = auth.user?.userCmpn ?? ""; - const hasAuthCmpn = companyArray.some((company) => company.cmpnId === cmpn); - - if (cmpn && hasAuthCmpn) { + if (cmpn && companyArray.some((company) => company.cmpnId === cmpn)) { setCompanyFilter(cmpn); return; } - if (companyFilter && !companyArray.some((company) => company.cmpnId === companyFilter)) { - setCompanyFilter(""); + // 이미 유효한 값이 선택돼 있으면(사용자가 직접 고른 값 포함) 그대로 둔다. + if (companyFilter && companyArray.some((company) => company.cmpnId === companyFilter)) { + return; } + + const ownCmpn = companyArray.find((company) => company.ownCmpn); + setCompanyFilter(ownCmpn?.cmpnId ?? ""); }, [auth.user?.userCmpn, companyArray, companyFilter]); useEffect(() => { @@ -331,7 +330,7 @@ const ProjectAssignPage = () => { /> - 배정된 {roleFilter?.label} ( {assignBase.length}명 ) + 배정된 {roleFilter?.label} ( {assignView.length}명 ) @@ -424,7 +423,7 @@ const ProjectAssignPage = () => { /> - 배정 가능 {roleFilter?.label} ({ableBase.length}명 ) + 배정 가능 {roleFilter?.label} ({ableView.length}명 ) diff --git a/src/app/(pages)/(main)/list/contact/page.tsx b/src/app/(pages)/(main)/list/contact/page.tsx index 74a6e6e..84ef8f8 100644 --- a/src/app/(pages)/(main)/list/contact/page.tsx +++ b/src/app/(pages)/(main)/list/contact/page.tsx @@ -2,7 +2,7 @@ import { Suspense, useEffect, useMemo, useState } from "react"; import { useRouter, useSearchParams } from "next/navigation"; -import { ArrowLeft, CalendarClock } from "lucide-react"; +import { ArrowLeft, CalendarClock, RefreshCw } from "lucide-react"; import { useMounted } from "@kri/common/hooks"; import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter"; import { Button } from "@/components/ui/button"; @@ -93,7 +93,6 @@ const ListContactPageContent = () => { listDetailQuery.refetch(); } catch (e) { console.error(e); - alert("저장 중 오류가 발생했습니다."); } }; @@ -108,6 +107,17 @@ const ListContactPageContent = () => {

컨택 진행

SID: {sid} +
+
+ ); + })} + + )} + + {openedUrl ? (

새 창에서 열립니다. 열리지 않았다면{" "} - + 여기 를 클릭해 주세요.

- - ); - } - - return ( -
- + ) : null}
); }; diff --git a/src/app/(pages)/(main)/project/info/page.tsx b/src/app/(pages)/(main)/project/info/page.tsx index 0d74fac..58e86f4 100644 --- a/src/app/(pages)/(main)/project/info/page.tsx +++ b/src/app/(pages)/(main)/project/info/page.tsx @@ -13,8 +13,9 @@ import {useDialog} from '@/hooks/useDialog' import ResultCodeDialog from '@/components/dialog/ResultCodeDialog' import { useDebouncedValue, useMounted } from "@kri/common/hooks"; import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter' +import { X } from 'lucide-react' import { - ProjectInfo, ProjectUpdateRequest, ResultCode, + ProjectInfo, ProjectSurvey, ProjectUpdateRequest, ResultCode, ProjectStatus, ResultCodeType, SurveyType } from "@/types/project"; import { @@ -25,10 +26,12 @@ import { } from "@/const/projectConst"; import type { MultiSelectOption } from "@/components/common/KriAutoComplete"; import {FW_TEAM} from "@/const/userConst"; +import {COMMON_TEXT_REGEX} from "@/const/validationConst"; +import {validateValue} from "@/utils/validation"; import {useItrntUserList} from "@/hooks/useItrntUserList"; import {useSelectedProject} from "@/hooks/useSelectedProject"; import {useAuth} from "@/hooks/useAuth"; -import {KriEditor} from "@/components/kri-editor"; +import {KriEditor, type KriEditorCommand} from "@/components/kri-editor"; import {useRouter} from "next/navigation"; import { useProjectInfoQuery, @@ -39,8 +42,10 @@ import { useUploadScenarioImageMutation, useKartProjectListQuery, } from "@/query/project"; import { useCmpnListQuery } from "@/query/cmpn"; -import { useCallerTelNumListQuery } from "@/query/intranet"; +import { useCallerTelNumListQuery, useGroupCodeListQuery } from "@/query/intranet"; import { formatKoreanPhoneNumber } from "@/utils/phone"; +import { useListHeaderQuery } from "@/query/list"; +import { MessageVariableList } from "@/components/message-template/MessageVariableList"; const defaultProjectInfo: ProjectInfo = { prjctIdx: 0, @@ -51,10 +56,7 @@ const defaultProjectInfo: ProjectInfo = { ownerDept: '', ownerFw: '', callerTelNum: '', - surveyTy: SurveyType.NONE, - surveyPrjctCd: '', - surveyUrl: '', - surveyDashboardUrl: '', + surveys: [], ff: false, useContactSenario: false, contactSenario: '', @@ -63,27 +65,270 @@ const defaultProjectInfo: ProjectInfo = { } type ExternalTab = 'redirect' | 'api' +type SurveyDraft = ProjectSurvey & { uiKey: string } const baseUrl = 'https://contact.kric.com' const sidParam = 'sid=[$SID]' -const externalPidParamBase = 'contact-pid=[$prjctIdx]' -const internalPidParamBase = 'pid=[$prjctIdx]' +const surveyIdxParam = 'psidx=[$prjctSurveyIdx]' const externalUrls = { redirect: { - complete: `${baseUrl}/redirect/complete?${internalPidParamBase}&${sidParam}`, - screen: `${baseUrl}/redirect/screen?${internalPidParamBase}&${sidParam}`, - quota: `${baseUrl}/redirect/quota?${internalPidParamBase}&${sidParam}`, + complete: `${baseUrl}/redirect/complete?${surveyIdxParam}&${sidParam}`, + screen: `${baseUrl}/redirect/screen?${surveyIdxParam}&${sidParam}`, + quota: `${baseUrl}/redirect/quota?${surveyIdxParam}&${sidParam}`, }, api: { - start: `${baseUrl}/api/external/start?${internalPidParamBase}&${sidParam}`, - complete: `${baseUrl}/api/external/complete?${internalPidParamBase}&${sidParam}`, - screen: `${baseUrl}/api/external/screen?${internalPidParamBase}&${sidParam}`, - quota: `${baseUrl}/api/external/quota?${internalPidParamBase}&${sidParam}`, + start: `${baseUrl}/api/external/start?${surveyIdxParam}&${sidParam}`, + complete: `${baseUrl}/api/external/complete?${surveyIdxParam}&${sidParam}`, + screen: `${baseUrl}/api/external/screen?${surveyIdxParam}&${sidParam}`, + quota: `${baseUrl}/api/external/quota?${surveyIdxParam}&${sidParam}`, }, } as const -const internalSurvey = new Set([SurveyType.KON, SurveyType.KIWI]); +const buildKonKiwiSurveyUrl = (surveyTy: SurveyType) => + surveyTy === SurveyType.KON ? 'https://[$KON-URL]?sid=[$SID]' : 'https://[$KIWI-URL]?sid=[$SID]' + +const isValidHttpUrl = (value: string) => { + try { + const url = new URL(value) + return url.protocol === 'http:' || url.protocol === 'https:' + } catch { + return false + } +} + +const isValidSurveyUrl = (value: string) => { + const konToken = '[$KON-URL]' + const kiwiToken = '[$KIWI-URL]' + const hasKonToken = value.includes(konToken) + const hasKiwiToken = value.includes(kiwiToken) + if (hasKonToken && hasKiwiToken) return false + + const placeholderHost = hasKonToken ? 'kon-url.invalid' : hasKiwiToken ? 'kiwi-url.invalid' : null + const normalized = placeholderHost + ? value.replace(hasKonToken ? konToken : kiwiToken, placeholderHost) + : value + if (normalized.includes(konToken) || normalized.includes(kiwiToken)) return false + + if (!isValidHttpUrl(normalized)) return false + return placeholderHost === null || new URL(normalized).hostname === placeholderHost +} + +const createSurveyDraft = (surveyOrder: number): SurveyDraft => ({ + uiKey: crypto.randomUUID(), + prjctSurveyIdx: null, + surveyOrder, + surveyName: '', + surveyTy: SurveyType.KON, + surveyPrjctCd: '', + surveyUrl: '', + surveyFullUrl: null, + surveyShortUrl: null, + surveyDashboardUrl: '', +}) + +type SurveyInvalidField = 'surveyName' | 'surveyUrl' | 'surveyDashboardUrl' + +type SurveyCardProps = { + survey: SurveyDraft + index: number + itrntPrjctCd: string + userTeam: string + invalidField: SurveyInvalidField | null + onRegisterFieldRef: (uiKey: string, field: SurveyInvalidField) => (el: HTMLInputElement | null) => void + onChange: (uiKey: string, patch: Partial) => void + onRemove: (uiKey: string) => void +} + +const SurveyCard = ({ survey, index, itrntPrjctCd, userTeam, invalidField, onRegisterFieldRef, onChange, onRemove }: SurveyCardProps) => { + const [externalTab, setExternalTab] = useState('redirect') + const [surveyKeyword, setSurveyKeyword] = useState('') + const debouncedKeyword = useDebouncedValue(surveyKeyword, 500) + + const isKonKiwi = survey.surveyTy === SurveyType.KON || survey.surveyTy === SurveyType.KIWI + const isKiwi = survey.surveyTy === SurveyType.KIWI ? 1 : 0 + const kartEnabled = !!itrntPrjctCd && !!userTeam && isKonKiwi + + const kartProjectListQuery = useKartProjectListQuery({ + itrntPrjctCd, + userTeam, + isKiwi, + keyword: debouncedKeyword, + enabled: kartEnabled, + }) + const surveyProjectArray = kartProjectListQuery.data ?? [] + + const replaceParams = (url: string) => + survey.prjctSurveyIdx != null ? url.replace('[$prjctSurveyIdx]', String(survey.prjctSurveyIdx)) : url + + const handleTypeChange = (value: string) => { + const nextTy = Number(value) as SurveyType + onChange(survey.uiKey, { + surveyTy: nextTy, + surveyPrjctCd: '', + surveyUrl: '', + surveyFullUrl: null, + surveyShortUrl: null, + surveyDashboardUrl: '', + }) + } + + const handleKartSelect = (value: string) => { + onChange(survey.uiKey, { + surveyPrjctCd: value, + surveyUrl: buildKonKiwiSurveyUrl(survey.surveyTy), + surveyFullUrl: null, + surveyShortUrl: null, + }) + } + + return ( +
+
+

설문 {index + 1}

+ +
+ +
+
+ + onChange(survey.uiKey, { surveyName: e.target.value })} + placeholder="설문명을 입력하세요" + className="h-9" + aria-invalid={invalidField === 'surveyName'} + /> +
+
+ + + {SURVEY_TYPE_ORDER.map((t) => { + const id = `survey-${survey.uiKey}-${t}` + return ( +
+ + +
+ ) + })} +
+
+
+ + {isKonKiwi && ( +
+ + item.pkey} + getLabel={(item) => `[${item.pkey}] ${item.title}`} + searchMode={"inputOnly"} + onSearchValueChange={setSurveyKeyword} + placeholder="프로젝트를 선택하세요" + heightClassName="h-9" + widthClassName="w-full" + /> +
+ )} + +
+ + onChange(survey.uiKey, { + surveyUrl: e.target.value, + surveyFullUrl: null, + surveyShortUrl: null, + })} + placeholder="https://" + className="h-9" + aria-invalid={invalidField === 'surveyUrl'} + /> +
+ + {survey.surveyTy === SurveyType.EXTERNAL && ( +
+ + onChange(survey.uiKey, { surveyDashboardUrl: e.target.value })} + placeholder="https://" + className="h-9" + aria-invalid={invalidField === 'surveyDashboardUrl'} + /> +
+ )} + + {survey.surveyTy === SurveyType.EXTERNAL && ( +
+ setExternalTab(v as ExternalTab)} className="w-full"> + + 리다이렉트 + API + + + +
+
리다이렉트 URL
+
+
+ + +
+
+ + +
+
+ + +
+
+
+
+ + +
+
API URL
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+

API Method는 Post를 사용하시면 됩니다.

+
+
+
+
+ )} +
+ ) +} const ProjectInfoPage = () => { const router = useRouter(); @@ -94,42 +339,38 @@ const ProjectInfoPage = () => { const {auth} = useAuth(); const [projectInfo, setProjectInfo] = useState(defaultProjectInfo); - const [surveyKeyword, setSurveyKeyword] = useState(''); - const debouncedKeyword = useDebouncedValue(surveyKeyword, 500); + const [surveys, setSurveys] = useState([]); - const [externalTab, setExternalTab] = useState('redirect') const sessionTempUrlsRef = useRef>(new Set()); const initialProjectInfoRef = useRef(null); + const scenarioEditorCmdRef = useRef(null); + + const [invalidField, setInvalidField] = useState<'prjctName' | null>(null); + const [invalidSurveyField, setInvalidSurveyField] = useState<{ uiKey: string; field: SurveyInvalidField } | null>(null); + const prjctNameRef = useRef(null); + const surveyFieldRefs = useRef>(new Map()); + + const registerSurveyFieldRef = useCallback( + (uiKey: string, field: SurveyInvalidField) => (el: HTMLInputElement | null) => { + const key = `${uiKey}:${field}`; + if (el) surveyFieldRefs.current.set(key, el); + else surveyFieldRefs.current.delete(key); + }, + [] + ); const userTeam = auth.user?.userTeam ?? ""; const prjctIdx = selectedProject?.prjctIdx ?? 0; const enabled = mounted && prjctIdx > 0; - - const surveyTy = projectInfo.surveyTy ?? SurveyType.NONE; - const isInternalSurvey = internalSurvey.has(surveyTy); - const isKiwi = surveyTy === SurveyType.KON ? 0 : surveyTy === SurveyType.KIWI ? 1 : 0; - -// 조회 쿼리들 + // 조회 쿼리들 const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled); const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled); + const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled); const cmpnListQuery = useCmpnListQuery(); const assignedCmpnQuery = useAssignedCmpnIdsQuery(prjctIdx, enabled); const callerTelNumListQuery = useCallerTelNumListQuery(mounted); - - const kartEnabled = - mounted && - !!projectInfo.itrntPrjctCd && - !!userTeam && - isInternalSurvey; - - const kartProjectListQuery = useKartProjectListQuery({ - itrntPrjctCd: projectInfo.itrntPrjctCd, - userTeam, - isKiwi, - keyword: debouncedKeyword, - enabled: kartEnabled, - }); + const groupCodeListQuery = useGroupCodeListQuery(mounted); const updateMutation = useUpdateProjectMutation(prjctIdx); const deleteMutation = useDeleteProjectMutation(prjctIdx); @@ -147,17 +388,22 @@ const ProjectInfoPage = () => { })); }, [cmpnListQuery.data]); - - const surveyProjectArray = kartProjectListQuery.data ?? []; const callerTelNumArray = callerTelNumListQuery.data ?? []; - const deptArray = useMemo(() => { + const groupCodeLabelMap = useMemo( + () => new Map((groupCodeListQuery.data ?? []).map((g) => [g.groupCode, g.groupCodeLabel])), + [groupCodeListQuery.data] + ); + + const deptArray: MultiSelectOption[] = useMemo(() => { const teams = Array.from(new Set((users ?? []).map((u) => u.userTeam).filter(Boolean))); if (!teams.includes("T900")) teams.push("T900"); // TFT - return teams.sort((a, b) => a.localeCompare(b, "ko")); - }, [users]); + return teams + .sort((a, b) => a.localeCompare(b, "ko")) + .map((code) => ({ value: code, label: groupCodeLabelMap.get(code) ?? code })); + }, [users, groupCodeLabelMap]); const fwArray: MultiSelectOption[] = useMemo(() => { return (users ?? []) @@ -169,6 +415,19 @@ const ProjectInfoPage = () => { setProjectInfo((prev) => ({...prev, [field]: value})) } + const handleAddSurvey = () => { + setSurveys((prev) => [...prev, createSurveyDraft(prev.length + 1)]) + } + + const handleRemoveSurvey = (uiKey: string) => { + if (!confirm('삭제 후 저장하면 이 설문은 영구적으로 삭제됩니다. 삭제하시겠습니까?')) return + setSurveys((prev) => prev.filter((s) => s.uiKey !== uiKey)) + } + + const handleSurveyChange = (uiKey: string, patch: Partial) => { + setSurveys((prev) => prev.map((s) => (s.uiKey === uiKey ? { ...s, ...patch } : s))) + } + const handleImageUpload = useCallback( async (file: File): Promise => { if (!projectInfo.prjctCd) { @@ -188,17 +447,98 @@ const ProjectInfoPage = () => { } const handleSubmit = async () => { - if (!projectInfo.prjctName) { - alert('프로젝트명을 입력해주세요.') + setInvalidField(null); + setInvalidSurveyField(null); + + const prjctNameCheck = validateValue(projectInfo.prjctName, { + required: true, + requiredMessage: '프로젝트명을 입력해주세요.', + maxLength: 128, + pattern: COMMON_TEXT_REGEX, + patternMessage: '프로젝트명에 허용되지 않는 문자가 포함되어 있습니다.', + }); + if (!prjctNameCheck.valid) { + alert(prjctNameCheck.message) + setInvalidField('prjctName') + prjctNameRef.current?.focus() return } + for (const survey of surveys) { + const label = survey.surveyName || `설문 ${survey.surveyOrder}` + + const nameCheck = validateValue(survey.surveyName, { + required: true, + requiredMessage: `${label}: 설문명을 입력해주세요.`, + maxLength: 32, + pattern: COMMON_TEXT_REGEX, + patternMessage: `${label}: 설문명에 허용되지 않는 문자가 포함되어 있습니다.`, + }) + if (!nameCheck.valid) { + alert(nameCheck.message) + setInvalidSurveyField({ uiKey: survey.uiKey, field: 'surveyName' }) + surveyFieldRefs.current.get(`${survey.uiKey}:surveyName`)?.focus() + return + } + + if (survey.surveyTy === SurveyType.KON || survey.surveyTy === SurveyType.KIWI) { + if (!survey.surveyPrjctCd?.trim()) { + alert(`${label}: 연동할 프로젝트를 선택해주세요.`) + return + } + } + + const urlCheck = validateValue(survey.surveyUrl ?? '', { + required: true, + requiredMessage: `${label}: 설문 URL을 입력해주세요.`, + maxLength: 1024, + pattern: COMMON_TEXT_REGEX, + patternMessage: `${label}: 설문 URL에 허용되지 않는 문자가 포함되어 있습니다.`, + }) + if (!urlCheck.valid) { + alert(urlCheck.message) + setInvalidSurveyField({ uiKey: survey.uiKey, field: 'surveyUrl' }) + surveyFieldRefs.current.get(`${survey.uiKey}:surveyUrl`)?.focus() + return + } + + if (!isValidSurveyUrl(survey.surveyUrl ?? '')) { + alert(`${label}: 올바른 HTTP(S) 설문 URL을 입력해 주세요.`) + setInvalidSurveyField({ uiKey: survey.uiKey, field: 'surveyUrl' }) + surveyFieldRefs.current.get(`${survey.uiKey}:surveyUrl`)?.focus() + return + } + + const dashCheck = validateValue(survey.surveyDashboardUrl ?? '', { + maxLength: 1024, + pattern: COMMON_TEXT_REGEX, + patternMessage: `${label}: 설문 대시보드 URL에 허용되지 않는 문자가 포함되어 있습니다.`, + }) + if (!dashCheck.valid) { + alert(dashCheck.message) + setInvalidSurveyField({ uiKey: survey.uiKey, field: 'surveyDashboardUrl' }) + surveyFieldRefs.current.get(`${survey.uiKey}:surveyDashboardUrl`)?.focus() + return + } + + const dashboardUrl = survey.surveyDashboardUrl?.trim() ?? '' + if (survey.surveyTy === SurveyType.EXTERNAL && dashboardUrl && !isValidHttpUrl(dashboardUrl)) { + alert(`${label}: 올바른 HTTP(S) 설문 대시보드 URL을 입력해 주세요.`) + setInvalidSurveyField({ uiKey: survey.uiKey, field: 'surveyDashboardUrl' }) + surveyFieldRefs.current.get(`${survey.uiKey}:surveyDashboardUrl`)?.focus() + return + } + } + const updateCodeArray = structuredClone( resultCodeArray.filter((rc) => changeResultCodeType.includes(rc.resultCdTy)) ); const requestUpdateProject: ProjectUpdateRequest = { - projectInfo: projectInfo, + projectInfo: { + ...projectInfo, + surveys: surveys.map(({ uiKey, ...rest }) => rest), + }, resultCodeList: updateCodeArray, assignCmpnIdList: assignCmpnIdArray, } @@ -222,6 +562,7 @@ const ProjectInfoPage = () => { useEffect(() => { if (projectInfoQuery.data) { setProjectInfo(projectInfoQuery.data); + setSurveys(projectInfoQuery.data.surveys.map((s) => ({ ...s, uiKey: crypto.randomUUID() }))); initialProjectInfoRef.current = projectInfoQuery.data; } }, [projectInfoQuery.data]); @@ -238,52 +579,6 @@ const ProjectInfoPage = () => { } }, [assignedCmpnQuery.data]); - useEffect(() => { - if (projectInfo.surveyTy !== SurveyType.EXTERNAL) { - setExternalTab('redirect') - } - }, [projectInfo.surveyTy]); - - // KON/KIWI 프로젝트 "선택"을 사용자가 직접 바꿨을 때만 surveyUrl을 자동 생성한다. - // 저장된 프로젝트를 불러오는 경우(조회) 등에는 저장돼 있는 surveyUrl을 그대로 보여줘야 한다. - const handleSurveyPrjctCdChange = (value: string) => { - setProjectInfo((prev) => { - const next = {...prev, surveyPrjctCd: value}; - - if (value && internalSurvey.has(prev.surveyTy || SurveyType.NONE)) { - const pidParam = externalPidParamBase.replace('[$prjctIdx]', String(prev.prjctIdx)); - let surveyUrl = `/project/${value}/INDEX.asp?${pidParam}&${sidParam}`; - if (prev.surveyTy === SurveyType.KON) { - surveyUrl = `https://kon.kric.com` + surveyUrl - } else if (prev.surveyTy === SurveyType.KIWI) { - surveyUrl = `https://kon.kiwisurvey.kr` + surveyUrl - } - - next.surveyUrl = surveyUrl; - } - - return next; - }) - } - - // 설문 연동(surveyTy)을 바꾸면 선택된 KON/KIWI 프로젝트, 설문 URL, 설문 대시보드 URL을 초기화한다. - // 단, 최초 조회 시점의 surveyTy로 다시 돌아오면 그때 저장돼 있던 값을 복원한다. - const handleSurveyTyChange = (value: string) => { - const nextSurveyTy = Number(value) as SurveyType; - const initial = initialProjectInfoRef.current; - const backToInitial = !!initial && initial.surveyTy === nextSurveyTy; - - setProjectInfo((prev) => ({ - ...prev, - surveyTy: nextSurveyTy, - surveyPrjctCd: backToInitial ? (initial!.surveyPrjctCd ?? '') : '', - surveyUrl: backToInitial ? (initial!.surveyUrl ?? '') : '', - surveyDashboardUrl: backToInitial ? (initial!.surveyDashboardUrl ?? '') : '', - })) - } - - const replacePrjctIdx = (url: string) => url.replace('[$prjctIdx]', String(projectInfo.prjctIdx)); - if (!mounted) return return ( @@ -333,10 +628,12 @@ const ProjectInfoPage = () => { 프로젝트 명* handleChange('prjctName', e.target.value)} placeholder="프로젝트명을 입력하세요" className="h-9" + aria-invalid={invalidField === 'prjctName'} /> @@ -347,6 +644,8 @@ const ProjectInfoPage = () => { items={deptArray} value={projectInfo.ownerDept || ''} onChange={(value) => handleChange('ownerDept', value)} + getValue={(item) => item.value} + getLabel={(item) => item.label} placeholder="담당 그룹을 선택하세요" heightClassName="h-9" widthClassName="w-full" @@ -400,124 +699,31 @@ const ProjectInfoPage = () => {
-

설문 연동

+
+

설문 연동

+ +
- - {SURVEY_TYPE_ORDER.map((t) => { - const id = `survey-${t}`; // 유니크 보장 - return ( -
- - -
- ); - })} -
- - {(projectInfo.surveyTy === SurveyType.KON || projectInfo.surveyTy === SurveyType.KIWI) && ( -
- - item.pkey} - getLabel={(item) => `[${item.pkey}] ${item.title}`} - searchMode={"inputOnly"} - onSearchValueChange={setSurveyKeyword} - placeholder="프로젝트를 선택하세요" - heightClassName="h-9" - widthClassName="w-full" - /> -
- )} - {projectInfo.surveyTy !== SurveyType.NONE && ( -
- - handleChange('surveyUrl', e.target.value)} - placeholder="https://" - className="h-9" - /> -
- )} - - {projectInfo.surveyTy === SurveyType.EXTERNAL && ( -
- - handleChange('surveyDashboardUrl', e.target.value)} - placeholder="https://" - className="h-9" + {surveys.length === 0 ? ( +

연결된 설문이 없습니다. "설문 추가"로 등록해주세요.

+ ) : ( +
+ {surveys.map((survey, index) => ( + -
- )} - - {projectInfo.surveyTy === SurveyType.EXTERNAL && ( -
- setExternalTab(v as ExternalTab)} className="w-full"> - - 리다이렉트 - API - - - -
-
리다이렉트 URL
- -
-
- - -
-
- - -
-
- - -
-
-
-
- - -
-
API URL
- -
-
- - -
-
- - -
-
- - -
-
- - -
-
- -

API Method는 Post를 사용하시면 됩니다.

-
-
-
-
+ ))} +
)}
@@ -549,11 +755,17 @@ const ProjectInfoPage = () => { {projectInfo.useContactSenario && (
+ scenarioEditorCmdRef.current?.insertText(value)} + />

"} onChange={(html: string) => handleChange("contactSenario", html)} + onCommandReady={(command) => { scenarioEditorCmdRef.current = command }} placeholder="컨택 시나리오를 작성해 주세요" - className="w-full" + className="mt-4 w-full" debounceMs={600} // 기본 400ms, 원하면 늘리세요(예: 600~1000) onImageUpload={async (file) => await handleImageUpload(file)} // 사용 시만 /> diff --git a/src/app/(pages)/login/page.tsx b/src/app/(pages)/login/page.tsx index 78da2dc..7fe9a3d 100644 --- a/src/app/(pages)/login/page.tsx +++ b/src/app/(pages)/login/page.tsx @@ -23,15 +23,15 @@ const LoginPage = () => { const passwordInputRef = useRef(null); const tryLogin = async () => { - if (!userId) return alert("Please enter ID."); - if (!userPw) return alert("Please enter password."); + if (!userId) return alert("아이디를 입력해주세요."); + if (!userPw) return alert("비밀번호를 입력해주세요."); setError(null); try { await loginMutation.mutateAsync({ userId, userPw }); } catch (e) { const err = apiError(e, { - fallbackMessage: "Login failed.", + fallbackMessage: "로그인에 실패했습니다.", }); if (err.status === 401 || err.status === 403) setError("아이디 또는 비밀번호를 다시 확인해주세요."); else if (err.code === NONE_HTTP_ERROR) setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요."); @@ -100,7 +100,7 @@ const LoginPage = () => { type="password" autoComplete="current-password" required - placeholder="password" + placeholder="Password" value={userPw} onChange={(e) => setUserPw(e.currentTarget.value)} onKeyDown={handlePwKeyDown} diff --git a/src/app/api/external/[[...slug]]/route.ts b/src/app/api/external/[[...slug]]/route.ts index 4f14577..c822948 100644 --- a/src/app/api/external/[[...slug]]/route.ts +++ b/src/app/api/external/[[...slug]]/route.ts @@ -36,7 +36,7 @@ const toRequiredNumber = (value: string): number | null => { const buildExternalEventBody = ( req: NextRequest, action: ExternalAction, - prjctIdx: number, + prjctSurveyIdx: number, sid: number, ): ExternalEventBody => { const pathname = req.nextUrl.pathname; @@ -45,12 +45,12 @@ const buildExternalEventBody = ( return { action: actionCode, - prjctIdx, + prjctSurveyIdx, sid, meta: { entryType: getEntryTypeCode(h), action: actionCode, - pid: String(prjctIdx), + psidx: String(prjctSurveyIdx), sid: String(sid), remoteAddr: getHeader(h, "x-orig-ip") || getClientIp(req), uri: getHeader(h, "x-orig-uri") || pathname, @@ -74,14 +74,14 @@ const handleExternalEvent = async (req: NextRequest, context: RouteContext) => { return NextResponse.json({ message: "Not found" }, { status: 404 }); } - const prjctIdx = toRequiredNumber((searchParams.get("pid") ?? "").trim()); + const prjctSurveyIdx = toRequiredNumber((searchParams.get("psidx") ?? "").trim()); const sid = toRequiredNumber((searchParams.get("sid") ?? "").trim()); - if (!prjctIdx || !sid) { - return NextResponse.json({ message: "pid와 sid는 필수입니다." }, { status: 400 }); + if (!prjctSurveyIdx || !sid) { + return NextResponse.json({ message: "psidx, sid는 필수입니다." }, { status: 400 }); } - const body = buildExternalEventBody(req, action, prjctIdx, sid); + const body = buildExternalEventBody(req, action, prjctSurveyIdx, sid); const contactApi = await createContactApi(); await contactApi.post(`/list-hist/survey`, body); diff --git a/src/app/api/intranet/[[...slug]]/route.ts b/src/app/api/intranet/[[...slug]]/route.ts index 48b2097..223d736 100644 --- a/src/app/api/intranet/[[...slug]]/route.ts +++ b/src/app/api/intranet/[[...slug]]/route.ts @@ -3,7 +3,7 @@ import {RouteContext} from "@/types/common"; import {createIntranetApi} from "@/lib/http-server"; import {CallerTelNumInfo, IntranetProjectSearchResponse} from "@/types/project"; import {errorToResponse} from "@kri/common/http"; -import {ItrntUserInfo} from "@/types/user"; +import {GroupCodeInfo, ItrntUserInfo} from "@/types/user"; export const GET = async (req: NextRequest, context: RouteContext) => { try { @@ -34,6 +34,12 @@ export const GET = async (req: NextRequest, context: RouteContext) => { return NextResponse.json(result, { status: 200 }); } + if(action === "group-code-list"){ + const result = await itrntApi.get(`/user/group-code-list`); + + return NextResponse.json(result, { status: 200 }); + } + return NextResponse.json({ message: "Not found" }, { status: 404 }); } catch (error: unknown) { return errorToResponse(error); diff --git a/src/app/api/list-call-hist/[[...slug]]/route.ts b/src/app/api/list-call-hist/[[...slug]]/route.ts index 0919348..459d428 100644 --- a/src/app/api/list-call-hist/[[...slug]]/route.ts +++ b/src/app/api/list-call-hist/[[...slug]]/route.ts @@ -2,6 +2,25 @@ import {NextRequest, NextResponse} from "next/server"; import {RouteContext} from "@/types/common"; import {createContactApi} from "@/lib/http-server"; import {errorToResponse} from "@kri/common/http"; +import type {ListCallHistSession} 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( + `/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) => { try { diff --git a/src/app/api/list/[[...slug]]/route.ts b/src/app/api/list/[[...slug]]/route.ts index 796eb22..76445d9 100644 --- a/src/app/api/list/[[...slug]]/route.ts +++ b/src/app/api/list/[[...slug]]/route.ts @@ -32,6 +32,17 @@ export const GET = async (req: NextRequest, context: RouteContext) => { return NextResponse.json(result, { status: 200 }); } + if (action === "item-file-download" && slug.length === 4) { + const result = await contactApi.get( + `/list/item-file/download/${slug[1]}/${slug[2]}/${slug[3]}`, + { expectBinary: true }, + ); + return new NextResponse(result, { + status: 200, + headers: { "Content-Type": "application/octet-stream" }, + }); + } + return NextResponse.json({ message: "Not found" }, { status: 404 }); } catch (error: unknown) { return errorToResponse(error); diff --git a/src/components/common/KriAutoComplete.tsx b/src/components/common/KriAutoComplete.tsx index 3c9a961..6aeb35a 100644 --- a/src/components/common/KriAutoComplete.tsx +++ b/src/components/common/KriAutoComplete.tsx @@ -18,11 +18,13 @@ export interface KriAutoCompleteBaseProps { heightClassName?: string spanClassName?: string badgeClassName?: string + badgeLabelClassName?: string className?: string getValue?: (item: T) => string getLabel?: (item: T) => string withInfo?: boolean disabled?: boolean + 'aria-invalid'?: boolean } export interface KriMultiSelectProps extends KriAutoCompleteBaseProps { @@ -59,11 +61,12 @@ export function KriMultiSelect({ maxCount = 1, maxSelected, hideSelectAll = false, - placeholder = 'Select options', + placeholder = '옵션을 선택하세요', widthClassName, heightClassName, spanClassName = 'text-base', badgeClassName = 'text-base', + badgeLabelClassName, className, getValue, getLabel, @@ -71,6 +74,7 @@ export function KriMultiSelect({ onItemsChange, onOptionsChange, disabled, + 'aria-invalid': ariaInvalid, }: KriMultiSelectProps) { const options = React.useMemo( () => toOptions(items, getValue, getLabel, withInfo), @@ -78,7 +82,7 @@ export function KriMultiSelect({ ) return ( -
+
options={options} defaultValue={value} @@ -90,6 +94,7 @@ export function KriMultiSelect({ className={cn('bg-background text-base', !widthClassName && 'w-auto', className)} spanClassName={spanClassName} badgeClassName={badgeClassName} + badgeLabelClassName={badgeLabelClassName} searchable={searchable} searchMode={searchMode} defaultSearchValue={defaultSearchValue} @@ -100,6 +105,7 @@ export function KriMultiSelect({ resetOnDefaultValueChange deduplicateOptions disabled={disabled} + aria-invalid={ariaInvalid} />
) @@ -118,34 +124,50 @@ export interface KriSingleSelectProps extends KriAutoCompleteBasePr showSelectedTooltip?: boolean } -export function KriSingleSelect({ - items, - value, - onChange, - searchable = true, - searchMode = 'filter', - defaultSearchValue = '', - onSearchValueChange, - placeholder = 'Select an option', - heightClassName, - widthClassName, - spanClassName = 'text-base', - badgeClassName = 'text-base', - className, - getValue, - getLabel, - withInfo = false, - onItemChange, - onOptionChange, - preventDeselect = false, - hideOptionCheck = false, - showSelectedTooltip = false, - useClear = false, - clearLabel = '선택 해제', - clearValue = '__CLEAR__', - disabled, -}: KriSingleSelectProps) { +function KriSingleSelectInner( + { + items, + value, + onChange, + searchable = true, + searchMode = 'filter', + defaultSearchValue = '', + onSearchValueChange, + placeholder = '옵션을 선택하세요', + heightClassName, + widthClassName, + spanClassName = 'text-base', + badgeClassName = 'text-base', + badgeLabelClassName, + className, + getValue, + getLabel, + withInfo = false, + onItemChange, + onOptionChange, + preventDeselect = false, + hideOptionCheck = false, + showSelectedTooltip = false, + useClear = false, + clearLabel = '선택 해제', + clearValue = '__CLEAR__', + disabled, + 'aria-invalid': ariaInvalid, + }: KriSingleSelectProps, + forwardedRef: React.ForwardedRef, +) { const ref = React.useRef(null) + React.useImperativeHandle( + forwardedRef, + () => ({ + reset: () => ref.current?.reset(), + getSelectedValues: () => ref.current?.getSelectedValues() ?? [], + setSelectedValues: (values) => ref.current?.setSelectedValues(values), + clear: () => ref.current?.clear(), + focus: () => ref.current?.focus(), + }), + [], + ) const options = React.useMemo(() => { const normal = toOptions(items, getValue, getLabel, withInfo) return useClear ? [{ value: clearValue, label: clearLabel }, ...normal] : normal @@ -153,7 +175,7 @@ export function KriSingleSelect({ const selectedLabel = options.find((option) => option.value === value)?.label return ( -
+
ref={ref} options={options} @@ -186,6 +208,7 @@ export function KriSingleSelect({ className={cn('bg-background text-base', !widthClassName && 'w-auto', className)} spanClassName={spanClassName} badgeClassName={badgeClassName} + badgeLabelClassName={badgeLabelClassName ?? 'min-w-0 flex-1'} searchable={searchable} searchMode={searchMode} defaultSearchValue={defaultSearchValue} @@ -199,7 +222,12 @@ export function KriSingleSelect({ deduplicateOptions disabled={disabled} title={showSelectedTooltip ? selectedLabel ?? value : undefined} + aria-invalid={ariaInvalid} />
) } + +export const KriSingleSelect = React.forwardRef(KriSingleSelectInner) as ( + props: KriSingleSelectProps & { ref?: React.ForwardedRef }, +) => React.ReactElement diff --git a/src/components/common/KriPassword.tsx b/src/components/common/KriPassword.tsx index aec2229..bb08188 100644 --- a/src/components/common/KriPassword.tsx +++ b/src/components/common/KriPassword.tsx @@ -1,23 +1,24 @@ 'use client' -import { useId, useMemo, useState } from 'react' +import { forwardRef, useId, useImperativeHandle, useMemo, useRef, useState } from 'react' import { CheckIcon, EyeIcon, EyeOffIcon, XIcon } from 'lucide-react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { cn } from '@/lib/utils' - -export const ALLOWED_SPECIALS_TEXT = `! @ # $ % ^ & * ( ) _ + - = { } [ ] : ; " ' < > , . ? /` -export const ONLY_ALLOWED_REGEX = /^[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]+$/ -export const KRI_PW_REGEX = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]{8,20}$/ +import { KRI_PW_REGEX, ONLY_ALLOWED_PW_REGEX } from '@/const/validationConst' const requirements = [ { test: (value: string) => /[A-Za-z]/.test(value), text: '영문 1개 이상' }, { test: (value: string) => /\d/.test(value), text: '숫자 1개 이상' }, { test: (value: string) => value.length >= 8 && value.length <= 20, text: '8~20자' }, - { test: (value: string) => !value || ONLY_ALLOWED_REGEX.test(value), text: '허용 문자만 사용' }, + { test: (value: string) => !value || ONLY_ALLOWED_PW_REGEX.test(value), text: '허용 문자만 사용' }, ] +export type KriPasswordRef = { + focus: () => void +} + export interface KriPasswordProps { value: string onChange: (value: string) => void @@ -27,9 +28,10 @@ export interface KriPasswordProps { disabled?: boolean className?: string showStrength?: boolean + 'aria-invalid'?: boolean } -export function KriPassword({ +export const KriPassword = forwardRef(function KriPassword({ value, onChange, id, @@ -38,12 +40,17 @@ export function KriPassword({ disabled, className, showStrength = true, -}: KriPasswordProps) { + 'aria-invalid': ariaInvalid, +}, forwardedRef) { + const inputRef = useRef(null) + useImperativeHandle(forwardedRef, () => ({ + focus: () => inputRef.current?.focus(), + }), []) const [isVisible, setIsVisible] = useState(false) const autoId = useId() const inputId = id ?? autoId const isValid = useMemo(() => KRI_PW_REGEX.test(value), [value]) - const hasOnlyAllowedChars = useMemo(() => (value ? ONLY_ALLOWED_REGEX.test(value) : true), [value]) + const hasOnlyAllowedChars = useMemo(() => (value ? ONLY_ALLOWED_PW_REGEX.test(value) : true), [value]) const checks = useMemo(() => requirements.map((item) => ({ met: item.test(value), text: item.text })), [value]) const score = checks.filter((item) => item.met).length @@ -60,6 +67,7 @@ export function KriPassword({ {label ? : null}
handleInputChange('cmpnTel', e.target.value)} + placeholder="전화번호를 입력하세요" + value={formatKoreanPhoneNumber(formData.cmpnTel ?? '')} + onChange={(e) => handleInputChange('cmpnTel', e.target.value.replace(/\D/g, ''))} + aria-invalid={invalidField === 'cmpnTel'} />