260722_01_ENH: 버그 수정 및 개선 사항 수정
This commit is contained in:
@@ -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<string[]>([])
|
||||
const [transferResve, setTransferResve] = useState(false)
|
||||
const [currentListFilter, setCurrentListFilter] = useState<ListFilter>(() => createEmptyListFilter())
|
||||
const [filterSummary, setFilterSummary] = useState<string[]>([])
|
||||
|
||||
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled)
|
||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled)
|
||||
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
|
||||
const upsertListAssignMutation = useUpsertListAssignMutation(prjctIdx)
|
||||
const resetListAssignMutation = useResetListAssignMutation(prjctIdx)
|
||||
const assignTargetRows = useAssignTargetRows({ prjctIdx, enabled, assignType })
|
||||
|
||||
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
|
||||
const surveyArray = useMemo(() => projectInfoQuery.data?.surveys ?? [], [projectInfoQuery.data])
|
||||
const listHeaders = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data])
|
||||
|
||||
const 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={
|
||||
|
||||
@@ -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 = () => {
|
||||
/>
|
||||
</th>
|
||||
<th className="p-2 text-left text-base font-medium">
|
||||
배정된 {roleFilter?.label} ( {assignBase.length}명 )
|
||||
배정된 {roleFilter?.label} ( {assignView.length}명 )
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -424,7 +423,7 @@ const ProjectAssignPage = () => {
|
||||
/>
|
||||
</th>
|
||||
<th className="p-2 text-left text-base font-medium">
|
||||
배정 가능 {roleFilter?.label} ({ableBase.length}명 )
|
||||
배정 가능 {roleFilter?.label} ({ableView.length}명 )
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
@@ -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 = () => {
|
||||
</Button>
|
||||
<h1 className="text-2xl font-bold tracking-tight">컨택 진행</h1>
|
||||
<span className="text-2xl font-bold tracking-tight">SID: {sid}</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
disabled={listDetailQuery.isFetching}
|
||||
aria-label="리스트 정보 새로고침"
|
||||
title="리스트 정보 새로고침"
|
||||
onClick={() => listDetailQuery.refetch()}
|
||||
>
|
||||
<RefreshCw className={`h-4 w-4 ${listDetailQuery.isFetching ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('reservationListDialog')}>
|
||||
<CalendarClock className="h-4 w-4" />
|
||||
@@ -129,7 +139,7 @@ const ListContactPageContent = () => {
|
||||
isEditing={isEditing}
|
||||
listHeaders={listHeaders}
|
||||
detail={listDetailQuery.data}
|
||||
surveyUrl={projectInfoQuery.data?.surveyUrl}
|
||||
surveys={projectInfoQuery.data?.surveys ?? []}
|
||||
callerTelNum={projectInfoQuery.data?.callerTelNum}
|
||||
resultCodes={resultCodeArray}
|
||||
formValues={formValues}
|
||||
@@ -149,6 +159,7 @@ const ListContactPageContent = () => {
|
||||
userId={userId}
|
||||
userRole={userRole}
|
||||
resultCodes={resultCodeArray}
|
||||
useFF={projectInfoQuery.data?.ff ?? false}
|
||||
useContactSenario={projectInfoQuery.data?.useContactSenario ?? false}
|
||||
contactSenario={projectInfoQuery.data?.contactSenario}
|
||||
/>
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
useUpdateListHeaderMutation,
|
||||
useUploadListExcelMutation,
|
||||
} from '@/query/list'
|
||||
import { useResultCodesQuery } from '@/query/project'
|
||||
import { useProjectInfoQuery, useResultCodesQuery } from '@/query/project'
|
||||
import type { ListTableRow } from '@/components/table-column/ListTableColumn'
|
||||
import {
|
||||
createEmptyListFilter,
|
||||
@@ -69,7 +69,7 @@ const createEmptySearchUiState = (): ListSearchUiState => ({
|
||||
searchText: '',
|
||||
searchContactResult: [],
|
||||
searchInterviewResult: [],
|
||||
searchSurveyResult: [],
|
||||
surveyResultSelections: {},
|
||||
filterRows: [],
|
||||
sorting: [],
|
||||
})
|
||||
@@ -107,6 +107,7 @@ const ListManagePage = () => {
|
||||
const isInternal = isInternalManager(userRole);
|
||||
|
||||
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled)
|
||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled)
|
||||
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
|
||||
const uploadHistoryQuery = useListUploadHistoryQuery(prjctIdx, enabled)
|
||||
const downloadListExcelTemplateMutation = useDownloadListExcelTemplateMutation()
|
||||
@@ -120,6 +121,7 @@ const ListManagePage = () => {
|
||||
const downloadUploadHistoryFileMutation = useDownloadUploadHistoryFileMutation(prjctIdx)
|
||||
|
||||
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data])
|
||||
const surveyArray = useMemo(() => projectInfoQuery.data?.surveys ?? [], [projectInfoQuery.data])
|
||||
const headerManageRows = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data])
|
||||
|
||||
// 컨택 진행 화면에서 돌아왔을 때 1회만 복원하고, 재방문 시 다시 나타나지 않도록 즉시 지운다.
|
||||
@@ -280,6 +282,7 @@ const ListManagePage = () => {
|
||||
userId={userId}
|
||||
userCmpn={userCmpn}
|
||||
resultCodes={resultCodeArray}
|
||||
surveys={surveyArray}
|
||||
listHeaders={headerManageRows}
|
||||
enableBatchEdit={canManageList}
|
||||
refreshKey={listRefreshKey}
|
||||
|
||||
@@ -16,7 +16,6 @@ import {useAuth} from "@/hooks/useAuth";
|
||||
import type { MultiSelectOption } from "@/components/common/KriAutoComplete";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import {DEFAULT_COMPANY_NAME} from "@/const/userConst";
|
||||
import {Upload} from "lucide-react";
|
||||
import {
|
||||
useRoleListQuery,
|
||||
@@ -160,7 +159,15 @@ const UserManagePage = () => {
|
||||
mounted &&
|
||||
isInternalManager(auth.user?.userRole)
|
||||
|
||||
const userCmpn = auth.user?.userCmpn ?? DEFAULT_COMPANY_NAME;
|
||||
// 로그인 계정의 소속 회사를 기본 선택하되, 회사 목록에 매치되는 게 없으면 자사(ownCmpn) 중 가장 상단 1개로 대체한다.
|
||||
const userCmpn = useMemo(() => {
|
||||
const currentCmpnId = auth.user?.userCmpn;
|
||||
const matched = userCmpnArray.find((c) => c.cmpnId === currentCmpnId);
|
||||
if (matched) return matched.cmpnId;
|
||||
|
||||
const fallback = userCmpnArray.find((c) => c.ownCmpn);
|
||||
return fallback?.cmpnId ?? currentCmpnId ?? '';
|
||||
}, [auth.user?.userCmpn, userCmpnArray]);
|
||||
|
||||
if (!mounted) return <LoadingOverlayAdapter force />;
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdap
|
||||
import {useItrntUserList} from "@/hooks/useItrntUserList";
|
||||
import {useRouter} from "next/navigation";
|
||||
import {useCreateProjectMutation, useProjectListQuery, useProjectOwnerListQuery} from "@/query/project";
|
||||
import {useGroupCodeListQuery} from "@/query/intranet";
|
||||
import {PROJECT_STATUS_LABEL} from "@/const/projectConst";
|
||||
import {isManager} from "@/utils/userRole";
|
||||
|
||||
@@ -52,8 +53,21 @@ const MainPage = () => {
|
||||
|
||||
const enabled = mounted && !isLoading; // intranet user list 준비된 뒤에만 호출
|
||||
const ownerQuery = useProjectOwnerListQuery(enabled);
|
||||
const groupCodeListQuery = useGroupCodeListQuery(enabled);
|
||||
|
||||
const groupCodeLabelMap = useMemo(() => {
|
||||
return new Map((groupCodeListQuery.data ?? []).map((g) => [g.groupCode, g.groupCodeLabel]));
|
||||
}, [groupCodeListQuery.data]);
|
||||
|
||||
const deptArray = useMemo(() => {
|
||||
const ownerDeptList = ownerQuery.data?.ownerDeptList ?? [];
|
||||
|
||||
return ownerDeptList.map((code) => ({
|
||||
value: code,
|
||||
label: groupCodeLabelMap.get(code) ?? code,
|
||||
}));
|
||||
}, [ownerQuery.data?.ownerDeptList, groupCodeLabelMap]);
|
||||
|
||||
const deptArray = ownerQuery.data?.ownerDeptList ?? [];
|
||||
const fwArray = useMemo(() => {
|
||||
const ownerFwIDList = ownerQuery.data?.ownerFwList ?? [];
|
||||
|
||||
@@ -86,7 +100,7 @@ const MainPage = () => {
|
||||
const [searchDept, setSearchDept] = useState<string[]>([]);
|
||||
const [searchFw, setSearchFw] = useState<string[]>([]);
|
||||
|
||||
const columns = getProjectColumns(users);
|
||||
const columns = getProjectColumns(users, groupCodeLabelMap);
|
||||
const userId = auth.user?.userId ?? "";
|
||||
const userRole = auth.user?.userRole;
|
||||
|
||||
@@ -119,7 +133,6 @@ const MainPage = () => {
|
||||
itrntPrjctCd: projectInfo.itrntPrjctCd,
|
||||
ownerDept: projectInfo.ownerDept,
|
||||
ownerFw: projectInfo.ownerFw,
|
||||
surveyTy: projectInfo.surveyTy,
|
||||
ff: projectInfo.ff
|
||||
} as SelectedProject);
|
||||
|
||||
@@ -134,7 +147,6 @@ const MainPage = () => {
|
||||
itrntPrjctCd: projectInfo.itrntPrjctCd,
|
||||
ownerDept: projectInfo.ownerDept,
|
||||
ownerFw: projectInfo.ownerFw,
|
||||
surveyTy: projectInfo.surveyTy,
|
||||
ff: projectInfo.ff
|
||||
} as SelectedProject);
|
||||
|
||||
@@ -177,6 +189,8 @@ const MainPage = () => {
|
||||
items={deptArray}
|
||||
value={searchDept}
|
||||
onChange={setSearchDept}
|
||||
getValue={(item) => item.value}
|
||||
getLabel={(item) => item.label}
|
||||
placeholder="담당 그룹"
|
||||
widthClassName="w-60"
|
||||
heightClassName="h-9"
|
||||
|
||||
@@ -1,66 +1,99 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useMounted } from "@kri/common/hooks";
|
||||
import AppPageTitle from "@/components/app-shell/AppPageTitle";
|
||||
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { useProjectInfoQuery, useSurveyRedirectUrlQuery } from "@/query/project";
|
||||
import { SurveyType } from "@/types/project";
|
||||
import { SURVEY_TYPE_LABEL } from "@/const/projectConst";
|
||||
|
||||
const SurveyProgressPage = () => {
|
||||
const mounted = useMounted();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
const openedRef = useRef(false);
|
||||
const openedForRef = useRef<string | null>(null);
|
||||
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||
const enabled = mounted && prjctIdx > 0;
|
||||
|
||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled);
|
||||
const projectInfo = projectInfoQuery.data;
|
||||
const surveyTy = projectInfo?.surveyTy ?? SurveyType.NONE;
|
||||
const surveys = projectInfoQuery.data?.surveys ?? [];
|
||||
|
||||
const [activeSurveyIdx, setActiveSurveyIdx] = useState<number | null>(null);
|
||||
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 = projectInfo?.surveyPrjctCd ?? "";
|
||||
const pkey = selectedSurvey?.surveyPrjctCd ?? "";
|
||||
|
||||
const redirectUrlEnabled = enabled && !!projectInfo && isKonKiwi && !!pkey;
|
||||
const redirectUrlEnabled = enabled && !!selectedSurvey && isKonKiwi && !!pkey;
|
||||
const redirectUrlQuery = useSurveyRedirectUrlQuery(isKiwi, pkey, redirectUrlEnabled);
|
||||
|
||||
const targetUrl = isKonKiwi
|
||||
? (redirectUrlQuery.data ?? null)
|
||||
: surveyTy === SurveyType.EXTERNAL
|
||||
? (projectInfo?.surveyDashboardUrl || null)
|
||||
: null;
|
||||
const targetUrl = !selectedSurvey
|
||||
? null
|
||||
: isKonKiwi
|
||||
? (redirectUrlQuery.data ?? null)
|
||||
: surveyTy === SurveyType.EXTERNAL
|
||||
? (selectedSurvey.surveyDashboardUrl || null)
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
if (openedRef.current || !targetUrl) return;
|
||||
openedRef.current = true;
|
||||
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 (targetUrl) {
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText="설문 현황" />
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText="설문 현황" />
|
||||
|
||||
{surveys.length === 0 ? (
|
||||
<p className="text-muted-foreground">연결된 설문이 없습니다.</p>
|
||||
) : (
|
||||
<div className="max-w-[600px] space-y-2">
|
||||
{surveys.map((survey) => {
|
||||
const hasReport = survey.surveyTy !== SurveyType.NONE;
|
||||
return (
|
||||
<div
|
||||
key={survey.prjctSurveyIdx ?? survey.surveyOrder}
|
||||
className="flex items-center justify-between rounded-lg border bg-white p-4"
|
||||
>
|
||||
<div>
|
||||
<p className="font-semibold">{survey.surveyName}</p>
|
||||
<p className="text-xs text-muted-foreground">{SURVEY_TYPE_LABEL[survey.surveyTy]}</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={!hasReport}
|
||||
onClick={() => setActiveSurveyIdx(survey.prjctSurveyIdx ?? null)}
|
||||
>
|
||||
바로가기
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{openedUrl ? (
|
||||
<p>
|
||||
새 창에서 열립니다. 열리지 않았다면{" "}
|
||||
<a href={targetUrl} target="_blank" rel="noreferrer" className="text-blue-600 underline">
|
||||
<a href={openedUrl} target="_blank" rel="noreferrer" className="text-blue-600 underline">
|
||||
여기
|
||||
</a>
|
||||
를 클릭해 주세요.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 text-sm">
|
||||
<AppPageTitle titleText="연결 가능한 현황이 없습니다." />
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -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<ProjectSurvey>) => void
|
||||
onRemove: (uiKey: string) => void
|
||||
}
|
||||
|
||||
const SurveyCard = ({ survey, index, itrntPrjctCd, userTeam, invalidField, onRegisterFieldRef, onChange, onRemove }: SurveyCardProps) => {
|
||||
const [externalTab, setExternalTab] = useState<ExternalTab>('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 (
|
||||
<div className="space-y-3 rounded-lg border p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-base font-semibold">설문 {index + 1}</p>
|
||||
<Button type="button" variant="ghost" size="icon-sm" onClick={() => onRemove(survey.uiKey)} aria-label="설문 삭제">
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">
|
||||
설문명<span className="text-red-500 ml-1">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
ref={onRegisterFieldRef(survey.uiKey, 'surveyName')}
|
||||
value={survey.surveyName}
|
||||
onChange={(e) => onChange(survey.uiKey, { surveyName: e.target.value })}
|
||||
placeholder="설문명을 입력하세요"
|
||||
className="h-9"
|
||||
aria-invalid={invalidField === 'surveyName'}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">설문 타입</Label>
|
||||
<RadioGroup value={String(survey.surveyTy)} onValueChange={handleTypeChange} className="flex h-9 items-center gap-4">
|
||||
{SURVEY_TYPE_ORDER.map((t) => {
|
||||
const id = `survey-${survey.uiKey}-${t}`
|
||||
return (
|
||||
<div key={t} className="flex items-center space-x-2">
|
||||
<RadioGroupItem value={String(t)} id={id} />
|
||||
<Label htmlFor={id} className="font-normal cursor-pointer text-base">
|
||||
{SURVEY_TYPE_LABEL[t]}
|
||||
</Label>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</RadioGroup>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isKonKiwi && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">{SURVEY_TYPE_LABEL[survey.surveyTy]} 프로젝트</Label>
|
||||
<KriSingleSelect
|
||||
items={surveyProjectArray}
|
||||
value={survey.surveyPrjctCd || ''}
|
||||
onChange={handleKartSelect}
|
||||
getValue={(item) => item.pkey}
|
||||
getLabel={(item) => `[${item.pkey}] ${item.title}`}
|
||||
searchMode={"inputOnly"}
|
||||
onSearchValueChange={setSurveyKeyword}
|
||||
placeholder="프로젝트를 선택하세요"
|
||||
heightClassName="h-9"
|
||||
widthClassName="w-full"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">설문 URL</Label>
|
||||
<Input
|
||||
ref={onRegisterFieldRef(survey.uiKey, 'surveyUrl')}
|
||||
value={survey.surveyUrl || ''}
|
||||
onChange={(e) => onChange(survey.uiKey, {
|
||||
surveyUrl: e.target.value,
|
||||
surveyFullUrl: null,
|
||||
surveyShortUrl: null,
|
||||
})}
|
||||
placeholder="https://"
|
||||
className="h-9"
|
||||
aria-invalid={invalidField === 'surveyUrl'}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{survey.surveyTy === SurveyType.EXTERNAL && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">설문 대시보드 URL</Label>
|
||||
<Input
|
||||
ref={onRegisterFieldRef(survey.uiKey, 'surveyDashboardUrl')}
|
||||
value={survey.surveyDashboardUrl || ''}
|
||||
onChange={(e) => onChange(survey.uiKey, { surveyDashboardUrl: e.target.value })}
|
||||
placeholder="https://"
|
||||
className="h-9"
|
||||
aria-invalid={invalidField === 'surveyDashboardUrl'}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{survey.surveyTy === SurveyType.EXTERNAL && (
|
||||
<div className="space-y-2">
|
||||
<Tabs value={externalTab} onValueChange={(v) => setExternalTab(v as ExternalTab)} className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="redirect">리다이렉트</TabsTrigger>
|
||||
<TabsTrigger value="api">API</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="redirect" className="mt-4">
|
||||
<div className="border rounded-lg p-4 space-y-3 bg-gray-50">
|
||||
<div className="font-semibold">리다이렉트 URL</div>
|
||||
<div className="grid gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 text-base">완료:</Label>
|
||||
<Input value={replaceParams(externalUrls.redirect.complete)} readOnly className="bg-white h-9" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 text-base">스크린 아웃:</Label>
|
||||
<Input value={replaceParams(externalUrls.redirect.screen)} readOnly className="bg-white h-9" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 text-base">쿼터 풀:</Label>
|
||||
<Input value={replaceParams(externalUrls.redirect.quota)} readOnly className="bg-white h-9" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="api" className="mt-4">
|
||||
<div className="border rounded-lg p-4 space-y-3 bg-gray-50">
|
||||
<div className="font-semibold">API URL</div>
|
||||
<div className="grid gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 text-base">시작 API:</Label>
|
||||
<Input value={replaceParams(externalUrls.api.start)} readOnly className="bg-white h-9" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 text-base">완료 API:</Label>
|
||||
<Input value={replaceParams(externalUrls.api.complete)} readOnly className="bg-white h-9" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 text-base">스크린 API:</Label>
|
||||
<Input value={replaceParams(externalUrls.api.screen)} readOnly className="bg-white h-9" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 text-base">쿼터 API:</Label>
|
||||
<Input value={replaceParams(externalUrls.api.quota)} readOnly className="bg-white h-9" />
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">API Method는 Post를 사용하시면 됩니다.</p>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const ProjectInfoPage = () => {
|
||||
const router = useRouter();
|
||||
@@ -94,42 +339,38 @@ const ProjectInfoPage = () => {
|
||||
const {auth} = useAuth();
|
||||
|
||||
const [projectInfo, setProjectInfo] = useState<ProjectInfo>(defaultProjectInfo);
|
||||
const [surveyKeyword, setSurveyKeyword] = useState('');
|
||||
const debouncedKeyword = useDebouncedValue(surveyKeyword, 500);
|
||||
const [surveys, setSurveys] = useState<SurveyDraft[]>([]);
|
||||
|
||||
const [externalTab, setExternalTab] = useState<ExternalTab>('redirect')
|
||||
const sessionTempUrlsRef = useRef<Set<string>>(new Set());
|
||||
const initialProjectInfoRef = useRef<ProjectInfo | null>(null);
|
||||
const scenarioEditorCmdRef = useRef<KriEditorCommand | null>(null);
|
||||
|
||||
const [invalidField, setInvalidField] = useState<'prjctName' | null>(null);
|
||||
const [invalidSurveyField, setInvalidSurveyField] = useState<{ uiKey: string; field: SurveyInvalidField } | null>(null);
|
||||
const prjctNameRef = useRef<HTMLInputElement>(null);
|
||||
const surveyFieldRefs = useRef<Map<string, HTMLInputElement>>(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<ProjectSurvey>) => {
|
||||
setSurveys((prev) => prev.map((s) => (s.uiKey === uiKey ? { ...s, ...patch } : s)))
|
||||
}
|
||||
|
||||
const handleImageUpload = useCallback(
|
||||
async (file: File): Promise<string> => {
|
||||
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 <LoadingOverlayAdapter force />
|
||||
|
||||
return (
|
||||
@@ -333,10 +628,12 @@ const ProjectInfoPage = () => {
|
||||
프로젝트 명<span className="text-red-500 ml-1">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
ref={prjctNameRef}
|
||||
value={projectInfo.prjctName || ''}
|
||||
onChange={(e) => handleChange('prjctName', e.target.value)}
|
||||
placeholder="프로젝트명을 입력하세요"
|
||||
className="h-9"
|
||||
aria-invalid={invalidField === 'prjctName'}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -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 = () => {
|
||||
</div>
|
||||
|
||||
<div className="border rounded-lg p-6 space-y-4 bg-white mt-3">
|
||||
<h3 className="text-xl font-semibold">설문 연동</h3>
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-xl font-semibold">설문 연동</h3>
|
||||
<Button type="button" variant="outline" onClick={handleAddSurvey}>
|
||||
설문 추가
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<RadioGroup
|
||||
value={String(projectInfo.surveyTy ?? SurveyType.NONE)}
|
||||
onValueChange={handleSurveyTyChange}
|
||||
className="flex gap-4"
|
||||
>
|
||||
{SURVEY_TYPE_ORDER.map((t) => {
|
||||
const id = `survey-${t}`; // 유니크 보장
|
||||
return (
|
||||
<div key={t} className="flex items-center space-x-2">
|
||||
<RadioGroupItem value={String(t)} id={id} />
|
||||
<Label htmlFor={id} className="font-normal cursor-pointer text-base">
|
||||
{SURVEY_TYPE_LABEL[t]}
|
||||
</Label>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</RadioGroup>
|
||||
|
||||
{(projectInfo.surveyTy === SurveyType.KON || projectInfo.surveyTy === SurveyType.KIWI) && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">{SURVEY_TYPE_LABEL[projectInfo.surveyTy]} 프로젝트</Label>
|
||||
<KriSingleSelect
|
||||
items={surveyProjectArray}
|
||||
value={projectInfo.surveyPrjctCd || ''}
|
||||
onChange={handleSurveyPrjctCdChange}
|
||||
getValue={(item) => item.pkey}
|
||||
getLabel={(item) => `[${item.pkey}] ${item.title}`}
|
||||
searchMode={"inputOnly"}
|
||||
onSearchValueChange={setSurveyKeyword}
|
||||
placeholder="프로젝트를 선택하세요"
|
||||
heightClassName="h-9"
|
||||
widthClassName="w-full"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{projectInfo.surveyTy !== SurveyType.NONE && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">설문 URL</Label>
|
||||
<Input
|
||||
value={projectInfo.surveyUrl || ''}
|
||||
onChange={(e) => handleChange('surveyUrl', e.target.value)}
|
||||
placeholder="https://"
|
||||
className="h-9"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{projectInfo.surveyTy === SurveyType.EXTERNAL && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">설문 대시보드 URL</Label>
|
||||
<Input
|
||||
value={projectInfo.surveyDashboardUrl || ''}
|
||||
onChange={(e) => handleChange('surveyDashboardUrl', e.target.value)}
|
||||
placeholder="https://"
|
||||
className="h-9"
|
||||
{surveys.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">연결된 설문이 없습니다. "설문 추가"로 등록해주세요.</p>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{surveys.map((survey, index) => (
|
||||
<SurveyCard
|
||||
key={survey.uiKey}
|
||||
survey={survey}
|
||||
index={index}
|
||||
itrntPrjctCd={projectInfo.itrntPrjctCd}
|
||||
userTeam={userTeam}
|
||||
invalidField={invalidSurveyField?.uiKey === survey.uiKey ? invalidSurveyField.field : null}
|
||||
onRegisterFieldRef={registerSurveyFieldRef}
|
||||
onChange={handleSurveyChange}
|
||||
onRemove={handleRemoveSurvey}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{projectInfo.surveyTy === SurveyType.EXTERNAL && (
|
||||
<div className="space-y-2">
|
||||
<Tabs value={externalTab} onValueChange={(v) => setExternalTab(v as ExternalTab)} className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="redirect">리다이렉트</TabsTrigger>
|
||||
<TabsTrigger value="api">API</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="redirect" className="mt-4">
|
||||
<div className="border rounded-lg p-4 space-y-3 bg-gray-50">
|
||||
<div className="font-semibold">리다이렉트 URL</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 text-base">완료:</Label>
|
||||
<Input value={replacePrjctIdx(externalUrls.redirect.complete)} readOnly className="bg-white h-9" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 text-base">스크린 아웃:</Label>
|
||||
<Input value={replacePrjctIdx(externalUrls.redirect.screen)} readOnly className="bg-white h-9" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 text-base">쿼터 풀:</Label>
|
||||
<Input value={replacePrjctIdx(externalUrls.redirect.quota)} readOnly className="bg-white h-9" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="api" className="mt-4">
|
||||
<div className="border rounded-lg p-4 space-y-3 bg-gray-50">
|
||||
<div className="font-semibold">API URL</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 text-base">시작 API:</Label>
|
||||
<Input value={replacePrjctIdx(externalUrls.api.start)} readOnly className="bg-white h-9" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 text-base">완료 API:</Label>
|
||||
<Input value={replacePrjctIdx(externalUrls.api.complete)} readOnly className="bg-white h-9" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 text-base">스크린 API:</Label>
|
||||
<Input value={replacePrjctIdx(externalUrls.api.screen)} readOnly className="bg-white h-9" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="w-24 text-base">쿼터 API:</Label>
|
||||
<Input value={replacePrjctIdx(externalUrls.api.quota)} readOnly className="bg-white h-9" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">API Method는 Post를 사용하시면 됩니다.</p>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -549,11 +755,17 @@ const ProjectInfoPage = () => {
|
||||
|
||||
{projectInfo.useContactSenario && (
|
||||
<div className="ml-6 border rounded p-4 bg-gray-50 text-sm text-gray-600">
|
||||
<MessageVariableList
|
||||
listHeaders={listHeaderQuery.data ?? []}
|
||||
surveys={surveys}
|
||||
onInsert={(value) => scenarioEditorCmdRef.current?.insertText(value)}
|
||||
/>
|
||||
<KriEditor
|
||||
value={projectInfo.contactSenario ?? "<p></p>"}
|
||||
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)} // 사용 시만
|
||||
/>
|
||||
|
||||
@@ -23,15 +23,15 @@ const LoginPage = () => {
|
||||
const passwordInputRef = useRef<HTMLInputElement | null>(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}
|
||||
|
||||
14
src/app/api/external/[[...slug]]/route.ts
vendored
14
src/app/api/external/[[...slug]]/route.ts
vendored
@@ -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);
|
||||
|
||||
@@ -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<GroupCodeInfo[]>(`/user/group-code-list`);
|
||||
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
|
||||
@@ -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<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) => {
|
||||
try {
|
||||
|
||||
@@ -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<ArrayBuffer>(
|
||||
`/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);
|
||||
|
||||
@@ -18,11 +18,13 @@ export interface KriAutoCompleteBaseProps<T> {
|
||||
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<T = unknown> extends KriAutoCompleteBaseProps<T> {
|
||||
@@ -59,11 +61,12 @@ export function KriMultiSelect<T = unknown>({
|
||||
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<T = unknown>({
|
||||
onItemsChange,
|
||||
onOptionsChange,
|
||||
disabled,
|
||||
'aria-invalid': ariaInvalid,
|
||||
}: KriMultiSelectProps<T>) {
|
||||
const options = React.useMemo(
|
||||
() => toOptions(items, getValue, getLabel, withInfo),
|
||||
@@ -78,7 +82,7 @@ export function KriMultiSelect<T = unknown>({
|
||||
)
|
||||
|
||||
return (
|
||||
<div className={cn('flex-none', widthClassName, heightClassName)}>
|
||||
<div className={cn('flex-none min-w-0', widthClassName, heightClassName)}>
|
||||
<MultiSelect<T>
|
||||
options={options}
|
||||
defaultValue={value}
|
||||
@@ -90,6 +94,7 @@ export function KriMultiSelect<T = unknown>({
|
||||
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<T = unknown>({
|
||||
resetOnDefaultValueChange
|
||||
deduplicateOptions
|
||||
disabled={disabled}
|
||||
aria-invalid={ariaInvalid}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
@@ -118,34 +124,50 @@ export interface KriSingleSelectProps<T = unknown> extends KriAutoCompleteBasePr
|
||||
showSelectedTooltip?: boolean
|
||||
}
|
||||
|
||||
export function KriSingleSelect<T = unknown>({
|
||||
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<T>) {
|
||||
function KriSingleSelectInner<T>(
|
||||
{
|
||||
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<T>,
|
||||
forwardedRef: React.ForwardedRef<MultiSelectRef>,
|
||||
) {
|
||||
const ref = React.useRef<MultiSelectRef>(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<T = unknown>({
|
||||
const selectedLabel = options.find((option) => option.value === value)?.label
|
||||
|
||||
return (
|
||||
<div className={cn('flex-none', widthClassName, heightClassName)}>
|
||||
<div className={cn('flex-none min-w-0', widthClassName, heightClassName)}>
|
||||
<MultiSelect<T>
|
||||
ref={ref}
|
||||
options={options}
|
||||
@@ -186,6 +208,7 @@ export function KriSingleSelect<T = unknown>({
|
||||
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<T = unknown>({
|
||||
deduplicateOptions
|
||||
disabled={disabled}
|
||||
title={showSelectedTooltip ? selectedLabel ?? value : undefined}
|
||||
aria-invalid={ariaInvalid}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const KriSingleSelect = React.forwardRef(KriSingleSelectInner) as <T = unknown>(
|
||||
props: KriSingleSelectProps<T> & { ref?: React.ForwardedRef<MultiSelectRef> },
|
||||
) => React.ReactElement
|
||||
|
||||
@@ -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<KriPasswordRef, KriPasswordProps>(function KriPassword({
|
||||
value,
|
||||
onChange,
|
||||
id,
|
||||
@@ -38,12 +40,17 @@ export function KriPassword({
|
||||
disabled,
|
||||
className,
|
||||
showStrength = true,
|
||||
}: KriPasswordProps) {
|
||||
'aria-invalid': ariaInvalid,
|
||||
}, forwardedRef) {
|
||||
const inputRef = useRef<HTMLInputElement>(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 ? <Label htmlFor={inputId}>{label}</Label> : null}
|
||||
<div className="relative">
|
||||
<Input
|
||||
ref={inputRef}
|
||||
id={inputId}
|
||||
type={isVisible ? 'text' : 'password'}
|
||||
placeholder={placeholder}
|
||||
@@ -68,6 +76,7 @@ export function KriPassword({
|
||||
className="pr-9"
|
||||
disabled={disabled}
|
||||
autoComplete="new-password"
|
||||
aria-invalid={ariaInvalid}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
@@ -113,6 +122,6 @@ export function KriPassword({
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
export default KriPassword
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import type { CSSProperties } from 'react'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { cn } from '@/lib/utils'
|
||||
@@ -9,6 +10,10 @@ export type KriSelectItem = {
|
||||
label: string
|
||||
}
|
||||
|
||||
export type KriSelectRef = {
|
||||
focus: () => void
|
||||
}
|
||||
|
||||
export type KriSelectProps<T> = {
|
||||
items: T[]
|
||||
value: string
|
||||
@@ -24,6 +29,7 @@ export type KriSelectProps<T> = {
|
||||
getLabel?: (item: T) => string
|
||||
useAll?: boolean
|
||||
disabled?: boolean
|
||||
'aria-invalid'?: boolean
|
||||
}
|
||||
|
||||
const HEIGHT_CLASS_VALUE: Record<string, CSSProperties['height']> = {
|
||||
@@ -34,22 +40,34 @@ const HEIGHT_CLASS_VALUE: Record<string, CSSProperties['height']> = {
|
||||
'h-10': '2.5rem',
|
||||
}
|
||||
|
||||
export function KriSelect<T>({
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
onChangeOption,
|
||||
placeholder,
|
||||
className,
|
||||
heightClassName,
|
||||
triggerTextClassName,
|
||||
contentClassName,
|
||||
itemClassName,
|
||||
getValue,
|
||||
getLabel,
|
||||
useAll = true,
|
||||
disabled,
|
||||
}: KriSelectProps<T>) {
|
||||
function KriSelectInner<T>(
|
||||
{
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
onChangeOption,
|
||||
placeholder,
|
||||
className,
|
||||
heightClassName,
|
||||
triggerTextClassName,
|
||||
contentClassName,
|
||||
itemClassName,
|
||||
getValue,
|
||||
getLabel,
|
||||
useAll = true,
|
||||
disabled,
|
||||
'aria-invalid': ariaInvalid,
|
||||
}: KriSelectProps<T>,
|
||||
forwardedRef: React.ForwardedRef<KriSelectRef>,
|
||||
) {
|
||||
const triggerRef = React.useRef<HTMLButtonElement>(null)
|
||||
React.useImperativeHandle(
|
||||
forwardedRef,
|
||||
() => ({
|
||||
focus: () => triggerRef.current?.focus(),
|
||||
}),
|
||||
[],
|
||||
)
|
||||
const extractValue = (item: T) => (getValue ? getValue(item) : String(item))
|
||||
const extractLabel = (item: T) => (getLabel ? getLabel(item) : String(item))
|
||||
const triggerStyle: CSSProperties | undefined = heightClassName
|
||||
@@ -70,9 +88,11 @@ export function KriSelect<T>({
|
||||
}}
|
||||
>
|
||||
<SelectTrigger
|
||||
ref={triggerRef}
|
||||
className={cn('w-fit whitespace-nowrap bg-white', triggerTextClassName, heightClassName, className)}
|
||||
style={triggerStyle}
|
||||
aria-label={placeholder ?? 'select'}
|
||||
aria-invalid={ariaInvalid}
|
||||
>
|
||||
<SelectValue placeholder={placeholder} />
|
||||
</SelectTrigger>
|
||||
@@ -96,3 +116,7 @@ export function KriSelect<T>({
|
||||
</Select>
|
||||
)
|
||||
}
|
||||
|
||||
export const KriSelect = React.forwardRef(KriSelectInner) as <T = unknown>(
|
||||
props: KriSelectProps<T> & { ref?: React.ForwardedRef<KriSelectRef> },
|
||||
) => React.ReactElement
|
||||
|
||||
@@ -18,7 +18,7 @@ function MultiSelectInner<T>(
|
||||
defaultValue = [],
|
||||
stickySelectedOptions = [],
|
||||
onStickySelectedOptionsChange,
|
||||
placeholder = 'Select options',
|
||||
placeholder = '옵션을 선택하세요',
|
||||
maxCount = 3,
|
||||
maxSelected,
|
||||
selectionMode = 'multiple',
|
||||
@@ -27,6 +27,7 @@ function MultiSelectInner<T>(
|
||||
className,
|
||||
spanClassName,
|
||||
badgeClassName,
|
||||
badgeLabelClassName,
|
||||
hideSelectAll = false,
|
||||
searchable = true,
|
||||
searchMode = 'filter',
|
||||
@@ -181,6 +182,7 @@ function MultiSelectInner<T>(
|
||||
variant={variant}
|
||||
spanClassName={spanClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
badgeLabelClassName={badgeLabelClassName}
|
||||
onRemove={(value) => emit(selectedValues.filter((selected) => selected !== value))}
|
||||
onClear={() => emit([])}
|
||||
className={cn(autoSize && 'w-auto', className)}
|
||||
|
||||
@@ -19,6 +19,7 @@ interface MultiSelectTriggerProps<T> extends Omit<React.ButtonHTMLAttributes<HTM
|
||||
variant: MultiSelectVariant
|
||||
spanClassName?: string
|
||||
badgeClassName?: string
|
||||
badgeLabelClassName?: string
|
||||
onRemove: (value: string) => void
|
||||
onClear: () => void
|
||||
}
|
||||
@@ -35,6 +36,7 @@ export const MultiSelectTrigger = React.forwardRef(function MultiSelectTriggerIn
|
||||
variant,
|
||||
spanClassName,
|
||||
badgeClassName,
|
||||
badgeLabelClassName,
|
||||
className,
|
||||
disabled,
|
||||
onRemove,
|
||||
@@ -84,7 +86,7 @@ export const MultiSelectTrigger = React.forwardRef(function MultiSelectTriggerIn
|
||||
style={{ background: option.style?.gradient ?? option.style?.badgeColor }}
|
||||
>
|
||||
{!hideIcons && Icon ? <Icon className="size-3.5" /> : null}
|
||||
<span className="max-w-48 truncate">{option.label}</span>
|
||||
<span className={cn('truncate', badgeLabelClassName ?? 'max-w-48')}>{option.label}</span>
|
||||
{!preventDeselect ? (
|
||||
<span
|
||||
role="button"
|
||||
|
||||
@@ -61,6 +61,7 @@ export interface MultiSelectProps<T = unknown>
|
||||
variant?: MultiSelectVariant
|
||||
spanClassName?: string
|
||||
badgeClassName?: string
|
||||
badgeLabelClassName?: string
|
||||
hideSelectAll?: boolean
|
||||
searchable?: boolean
|
||||
searchMode?: 'filter' | 'inputOnly'
|
||||
|
||||
@@ -165,12 +165,20 @@ export function DataTable<TData, TValue = unknown>({
|
||||
const column = header.column
|
||||
const sorted = column.getIsSorted()
|
||||
const content = header.isPlaceholder ? null : flexRender(column.columnDef.header, header.getContext())
|
||||
const maxWidth = column.columnDef.meta?.maxWidth
|
||||
|
||||
return (
|
||||
<TableHead
|
||||
key={header.id}
|
||||
className={cn('text-base font-semibold text-foreground', column.id === 'actions' && 'w-[140px] text-center')}
|
||||
style={{ width: header.getSize() !== 150 ? header.getSize() : undefined }}
|
||||
className={cn(
|
||||
'text-base font-semibold text-foreground',
|
||||
column.id === 'actions' && 'w-[140px] text-center',
|
||||
maxWidth && 'overflow-hidden text-ellipsis',
|
||||
)}
|
||||
style={{
|
||||
width: header.getSize() !== 150 ? header.getSize() : undefined,
|
||||
maxWidth,
|
||||
}}
|
||||
>
|
||||
{!header.isPlaceholder && column.getCanSort() ? (
|
||||
<Button type="button" variant="ghost" className="flex gap-1 px-0 text-base font-semibold" onClick={column.getToggleSortingHandler()}>
|
||||
@@ -204,7 +212,18 @@ export function DataTable<TData, TValue = unknown>({
|
||||
row.id === focusRowId && 'bg-accent',
|
||||
)}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
|
||||
{row.getVisibleCells().map((cell) => {
|
||||
const maxWidth = cell.column.columnDef.meta?.maxWidth
|
||||
return (
|
||||
<TableCell
|
||||
key={cell.id}
|
||||
className={cn(maxWidth && 'overflow-hidden text-ellipsis')}
|
||||
style={maxWidth ? { maxWidth } : undefined}
|
||||
>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
)) : (
|
||||
<TableRow><TableCell colSpan={enhancedColumns.length} className="h-24 text-center">{emptyText}</TableCell></TableRow>
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import type { ColumnDef, PaginationState, SortingState, Updater } from '@tanstack/react-table'
|
||||
import type { ColumnDef, PaginationState, RowData, SortingState, Updater } from '@tanstack/react-table'
|
||||
|
||||
// 컬럼별 meta.maxWidth를 지정하면 DataTable이 헤더/셀 너비를 그 값으로 제한하고 넘치는 내용은 ...으로 표시한다.
|
||||
declare module '@tanstack/react-table' {
|
||||
interface ColumnMeta<TData extends RowData, TValue> {
|
||||
maxWidth?: number | string
|
||||
}
|
||||
}
|
||||
|
||||
export type SelectMode = 'none' | 'click-event' | 'single' | 'multi'
|
||||
export type DataTableColumn<TData, TValue = unknown> = ColumnDef<TData, TValue>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
@@ -9,7 +9,9 @@ import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import type { CmpnInfoSaveRequest } from '@/types/cmpn'
|
||||
import type { DataVerification } from "@kri/common";
|
||||
import { apiError, NONE_HTTP_ERROR, UNKNOWN_HTTP_ERROR } from "@kri/common/http";
|
||||
import { COMMON_TEXT_REGEX } from "@/const/validationConst";
|
||||
import { validateValue } from "@/utils/validation";
|
||||
import { formatKoreanPhoneNumber } from "@/utils/phone";
|
||||
|
||||
export type CmpnUpsertDialogProps = {
|
||||
dialogId?: DialogId
|
||||
@@ -43,6 +45,12 @@ const CmpnUpsertDialog = ({
|
||||
const [formData, setFormData] = useState<CmpnInfoSaveRequest>(createDefaultCmpnInfo);
|
||||
const [isCheckedDuplicate, setIsCheckedDuplicate] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [invalidField, setInvalidField] = useState<'cmpnId' | 'cmpnAlias' | 'cmpnTel' | 'memo' | null>(null);
|
||||
|
||||
const cmpnIdRef = useRef<HTMLInputElement>(null);
|
||||
const cmpnAliasRef = useRef<HTMLInputElement>(null);
|
||||
const cmpnTelRef = useRef<HTMLInputElement>(null);
|
||||
const memoRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId);
|
||||
|
||||
@@ -57,6 +65,7 @@ const CmpnUpsertDialog = ({
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setInvalidField(null);
|
||||
if (initialData) {
|
||||
setFormData({
|
||||
...createDefaultCmpnInfo(),
|
||||
@@ -87,6 +96,8 @@ const CmpnUpsertDialog = ({
|
||||
const cmpnId = formData.cmpnId.trim();
|
||||
if (!cmpnId) {
|
||||
alert("회사 ID를 입력해주세요.");
|
||||
setInvalidField('cmpnId');
|
||||
cmpnIdRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -105,18 +116,53 @@ const CmpnUpsertDialog = ({
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setInvalidField(null);
|
||||
|
||||
if (!formData.cmpnId.trim()) {
|
||||
alert("회사 ID를 입력해주세요.");
|
||||
setInvalidField('cmpnId');
|
||||
cmpnIdRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
if (mode === 'create' && !isCheckedDuplicate) {
|
||||
alert("회사 ID 중복체크를 해주세요.");
|
||||
setInvalidField('cmpnId');
|
||||
cmpnIdRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!formData.cmpnAlias.trim()) {
|
||||
alert("별칭을 입력해주세요.");
|
||||
const cmpnAliasCheck = validateValue(formData.cmpnAlias, {
|
||||
required: true,
|
||||
requiredMessage: "별칭을 입력해주세요.",
|
||||
maxLength: 32,
|
||||
pattern: COMMON_TEXT_REGEX,
|
||||
patternMessage: "별칭에 허용되지 않는 문자가 포함되어 있습니다.",
|
||||
});
|
||||
if (!cmpnAliasCheck.valid) {
|
||||
alert(cmpnAliasCheck.message);
|
||||
setInvalidField('cmpnAlias');
|
||||
cmpnAliasRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
const cmpnTelCheck = validateValue(formData.cmpnTel ?? '', {
|
||||
maxLength: 16,
|
||||
pattern: COMMON_TEXT_REGEX,
|
||||
patternMessage: "전화번호에 허용되지 않는 문자가 포함되어 있습니다.",
|
||||
});
|
||||
if (!cmpnTelCheck.valid) {
|
||||
alert(cmpnTelCheck.message);
|
||||
setInvalidField('cmpnTel');
|
||||
cmpnTelRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
const memoCheck = validateValue(formData.memo ?? '', { maxLength: 2048 });
|
||||
if (!memoCheck.valid) {
|
||||
alert(memoCheck.message);
|
||||
setInvalidField('memo');
|
||||
memoRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -133,15 +179,7 @@ const CmpnUpsertDialog = ({
|
||||
});
|
||||
handleOpenChange(false);
|
||||
} catch (e) {
|
||||
const err = apiError(e, {
|
||||
fallbackMessage: "Save failed.",
|
||||
});
|
||||
console.error(err.status, err.code, err.message);
|
||||
if (err.code !== NONE_HTTP_ERROR && err.code !== UNKNOWN_HTTP_ERROR) {
|
||||
alert(err.message);
|
||||
} else {
|
||||
alert("저장에 실패했습니다.");
|
||||
}
|
||||
console.error(e);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
@@ -180,11 +218,13 @@ const CmpnUpsertDialog = ({
|
||||
</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
ref={cmpnIdRef}
|
||||
id="cmpnId"
|
||||
placeholder="Enter company ID"
|
||||
placeholder="회사 ID를 입력하세요"
|
||||
value={formData.cmpnId}
|
||||
onChange={(e) => handleInputChange('cmpnId', e.target.value)}
|
||||
disabled={mode === 'edit'}
|
||||
aria-invalid={invalidField === 'cmpnId'}
|
||||
/>
|
||||
{mode === 'create' && (
|
||||
<Button
|
||||
@@ -200,30 +240,36 @@ const CmpnUpsertDialog = ({
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="cmpnAlias">별칭</Label>
|
||||
<Input
|
||||
ref={cmpnAliasRef}
|
||||
id="cmpnAlias"
|
||||
placeholder="Enter alias"
|
||||
placeholder="별칭을 입력하세요"
|
||||
value={formData.cmpnAlias ?? ''}
|
||||
onChange={(e) => handleInputChange('cmpnAlias', e.target.value)}
|
||||
aria-invalid={invalidField === 'cmpnAlias'}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="cmpnTel">전화번호</Label>
|
||||
<Input
|
||||
ref={cmpnTelRef}
|
||||
id="cmpnTel"
|
||||
placeholder="Enter tel"
|
||||
value={formData.cmpnTel ?? ''}
|
||||
onChange={(e) => handleInputChange('cmpnTel', e.target.value)}
|
||||
placeholder="전화번호를 입력하세요"
|
||||
value={formatKoreanPhoneNumber(formData.cmpnTel ?? '')}
|
||||
onChange={(e) => handleInputChange('cmpnTel', e.target.value.replace(/\D/g, ''))}
|
||||
aria-invalid={invalidField === 'cmpnTel'}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="memo">메모</Label>
|
||||
<textarea
|
||||
ref={memoRef}
|
||||
id="memo"
|
||||
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 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
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 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20"
|
||||
rows={3}
|
||||
placeholder="Enter memo"
|
||||
placeholder="메모를 입력하세요"
|
||||
value={formData.memo ?? ''}
|
||||
onChange={(e) => handleInputChange('memo', e.target.value)}
|
||||
aria-invalid={invalidField === 'memo'}
|
||||
/>
|
||||
</div>
|
||||
</KriDialog>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Plus, X } from 'lucide-react'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -13,12 +13,15 @@ import {
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
|
||||
import ApplyFilterOption from './ListDialogOption/ApplyFilterOption'
|
||||
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import type { FilterValueOption, ListFilterTarget } from '@/types/list'
|
||||
import { type ResultCode, ResultCodeType } from '@/types/project'
|
||||
import { type ProjectSurvey, type ResultCode, ResultCodeType } from '@/types/project'
|
||||
import { ListHeaderConst, LIST_BATCH_EDIT_FILE_DELETE_VALUE } from '@/const/listConst'
|
||||
import { COMMON_TEXT_REGEX } from '@/const/validationConst'
|
||||
import { validateValue } from '@/utils/validation'
|
||||
import { formatKoreanPhoneNumber } from '@/utils/phone'
|
||||
|
||||
export type BatchEditOption = {
|
||||
id: number
|
||||
@@ -33,11 +36,13 @@ export type BatchEditRow = {
|
||||
value: string
|
||||
}
|
||||
|
||||
export type BatchEditResultCodes = Partial<Record<ResultCodeType, number>>
|
||||
export type BatchEditResultCodes = Partial<Record<Exclude<ResultCodeType, ResultCodeType.SURVEY>, number>>
|
||||
export type BatchEditSurveyResultCodes = Record<number, number>
|
||||
|
||||
export type BatchEditPayload = {
|
||||
rows: BatchEditRow[]
|
||||
resultCodes: BatchEditResultCodes
|
||||
surveyResultCodes: { prjctSurveyIdx: number; resultCd: number }[]
|
||||
target: ListFilterTarget
|
||||
}
|
||||
|
||||
@@ -47,9 +52,11 @@ export type ListBatchEditDialogProps = {
|
||||
onOpenChange?: (open: boolean) => void
|
||||
headerOptions: BatchEditOption[]
|
||||
resultCodes: ResultCode[]
|
||||
surveys: ProjectSurvey[]
|
||||
filterSummary?: string[]
|
||||
initialRows?: BatchEditRow[]
|
||||
initialResultCodes?: BatchEditResultCodes
|
||||
initialSurveyResultCodes?: BatchEditSurveyResultCodes
|
||||
onConfirm: (payload: BatchEditPayload) => void | Promise<void>
|
||||
}
|
||||
|
||||
@@ -61,10 +68,9 @@ const createRow = (headerId: number, value = ''): BatchEditRow => ({
|
||||
|
||||
const NO_CHANGE = '__no_change__'
|
||||
|
||||
const resultCodeGroups: { type: ResultCodeType; label: string }[] = [
|
||||
const resultCodeGroups: { type: Exclude<ResultCodeType, ResultCodeType.SURVEY>; label: string }[] = [
|
||||
{ type: ResultCodeType.CONTACT, label: '컨택 결과' },
|
||||
{ type: ResultCodeType.INTERVIEW, label: '면접 결과' },
|
||||
{ type: ResultCodeType.SURVEY, label: '설문 결과' },
|
||||
]
|
||||
|
||||
const ListBatchEditDialog = ({
|
||||
@@ -73,21 +79,27 @@ const ListBatchEditDialog = ({
|
||||
onOpenChange,
|
||||
headerOptions,
|
||||
resultCodes,
|
||||
surveys,
|
||||
filterSummary,
|
||||
initialRows = [],
|
||||
initialResultCodes = {},
|
||||
initialSurveyResultCodes = {},
|
||||
onConfirm,
|
||||
}: ListBatchEditDialogProps) => {
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||
const [rows, setRows] = useState<BatchEditRow[]>([])
|
||||
const [resultCodeSelections, setResultCodeSelections] = useState<BatchEditResultCodes>({})
|
||||
const [surveyResultSelections, setSurveyResultSelections] = useState<BatchEditSurveyResultCodes>({})
|
||||
const [target, setTarget] = useState<ListFilterTarget>('filtered')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [invalidRowId, setInvalidRowId] = useState<string | null>(null)
|
||||
const rowInputRefs = useRef<Map<string, HTMLInputElement>>(new Map())
|
||||
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||
const defaultHeaderId = headerOptions[0]?.id ?? 0
|
||||
|
||||
const isFileHeader = (headerId: number) => headerOptions.find((option) => option.id === headerId)?.listHderTy === ListHeaderConst.FILE
|
||||
const isTelHeader = (headerId: number) => headerOptions.find((option) => option.id === headerId)?.listHderTy === ListHeaderConst.TEL_NUM
|
||||
|
||||
useEffect(() => {
|
||||
if (!resolvedOpen) return
|
||||
@@ -99,8 +111,10 @@ const ListBatchEditDialog = ({
|
||||
setRows([])
|
||||
}
|
||||
setResultCodeSelections({ ...initialResultCodes })
|
||||
setSurveyResultSelections({ ...initialSurveyResultCodes })
|
||||
setTarget('filtered')
|
||||
}, [resolvedOpen, initialRows, initialResultCodes, defaultHeaderId])
|
||||
setInvalidRowId(null)
|
||||
}, [resolvedOpen, initialRows, initialResultCodes, initialSurveyResultCodes, defaultHeaderId])
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
onOpenChange?.(nextOpen)
|
||||
@@ -131,7 +145,7 @@ const ListBatchEditDialog = ({
|
||||
setRows((prev) => prev.map((row) => (row.id === id ? { ...row, value } : row)))
|
||||
}
|
||||
|
||||
const handleChangeResultCode = (type: ResultCodeType, value: string) => {
|
||||
const handleChangeResultCode = (type: Exclude<ResultCodeType, ResultCodeType.SURVEY>, value: string) => {
|
||||
setResultCodeSelections((prev) => {
|
||||
if (value === NO_CHANGE) {
|
||||
const next = { ...prev }
|
||||
@@ -142,17 +156,53 @@ const ListBatchEditDialog = ({
|
||||
})
|
||||
}
|
||||
|
||||
const handleChangeSurveyResultCode = (prjctSurveyIdx: number, value: string) => {
|
||||
setSurveyResultSelections((prev) => {
|
||||
if (value === NO_CHANGE) {
|
||||
const next = { ...prev }
|
||||
delete next[prjctSurveyIdx]
|
||||
return next
|
||||
}
|
||||
return { ...prev, [prjctSurveyIdx]: Number(value) }
|
||||
})
|
||||
}
|
||||
|
||||
const handleConfirm = async () => {
|
||||
setInvalidRowId(null)
|
||||
if (!validateApplyFilterTarget(target, filterSummary)) return
|
||||
|
||||
const normalized = rows.filter((row) => row.headerId > 0 && row.value.trim().length > 0)
|
||||
const hasResultCodeChange = Object.keys(resultCodeSelections).length > 0
|
||||
const surveyResultCodes = Object.entries(surveyResultSelections).map(([prjctSurveyIdx, resultCd]) => ({
|
||||
prjctSurveyIdx: Number(prjctSurveyIdx),
|
||||
resultCd,
|
||||
}))
|
||||
const hasResultCodeChange = Object.keys(resultCodeSelections).length > 0 || surveyResultCodes.length > 0
|
||||
if (normalized.length === 0 && !hasResultCodeChange) {
|
||||
alert('일괄 수정할 항목을 입력해주세요.')
|
||||
return
|
||||
}
|
||||
|
||||
// 직접 값을 타이핑하는 행(선택형/파일 삭제가 아닌 행)만 형식을 검증한다.
|
||||
for (const row of normalized) {
|
||||
const isFreeTextRow = !isFileHeader(row.headerId) && getValueOptions(row.headerId) === undefined
|
||||
if (!isFreeTextRow) continue
|
||||
|
||||
const valueCheck = validateValue(row.value, {
|
||||
maxLength: 2048,
|
||||
pattern: COMMON_TEXT_REGEX,
|
||||
patternMessage: '수정 값에 허용되지 않는 문자가 포함되어 있습니다.',
|
||||
})
|
||||
if (!valueCheck.valid) {
|
||||
alert(valueCheck.message)
|
||||
setInvalidRowId(row.id)
|
||||
rowInputRefs.current.get(row.id)?.focus()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await onConfirm({ rows: normalized, resultCodes: resultCodeSelections, target })
|
||||
await onConfirm({ rows: normalized, resultCodes: resultCodeSelections, surveyResultCodes, target })
|
||||
handleOpenChange(false)
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
@@ -215,6 +265,41 @@ const ListBatchEditDialog = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{surveys.length > 0 ? (
|
||||
<div className="rounded-md border p-4 space-y-3">
|
||||
<p className="font-semibold text-sm">설문별 결과 수정</p>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
|
||||
{surveys.map((survey) => (
|
||||
<div key={survey.prjctSurveyIdx} className="space-y-1">
|
||||
<p className="text-sm text-muted-foreground">{survey.surveyName}</p>
|
||||
<Select
|
||||
value={
|
||||
survey.prjctSurveyIdx != null && surveyResultSelections[survey.prjctSurveyIdx] !== undefined
|
||||
? String(surveyResultSelections[survey.prjctSurveyIdx])
|
||||
: NO_CHANGE
|
||||
}
|
||||
onValueChange={(v) => survey.prjctSurveyIdx != null && handleChangeSurveyResultCode(survey.prjctSurveyIdx, v)}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="변경 안함" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={NO_CHANGE}>변경 안함</SelectItem>
|
||||
{resultCodes
|
||||
.filter((code) => code.resultCdTy === ResultCodeType.SURVEY && code.resultCd !== 0)
|
||||
.map((code) => (
|
||||
<SelectItem key={code.resultCdUUID} value={String(code.resultCd)}>
|
||||
{code.resultCdLbl}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<p className="font-semibold text-sm">항목값 수정</p>
|
||||
<div className="rounded-md border overflow-hidden">
|
||||
<div className="h-11 px-4 border-b bg-muted grid grid-cols-[1fr_2fr_64px] items-center text-sm font-semibold">
|
||||
@@ -263,11 +348,27 @@ const ListBatchEditDialog = ({
|
||||
widthClassName="w-full"
|
||||
className="w-full"
|
||||
/>
|
||||
) : isTelHeader(row.headerId) ? (
|
||||
<Input
|
||||
ref={(el) => {
|
||||
if (el) rowInputRefs.current.set(row.id, el)
|
||||
else rowInputRefs.current.delete(row.id)
|
||||
}}
|
||||
value={formatKoreanPhoneNumber(row.value)}
|
||||
onChange={(e) => handleChangeValue(row.id, e.target.value.replace(/\D/g, ''))}
|
||||
placeholder="수정할 값을 입력해주세요"
|
||||
aria-invalid={invalidRowId === row.id}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
ref={(el) => {
|
||||
if (el) rowInputRefs.current.set(row.id, el)
|
||||
else rowInputRefs.current.delete(row.id)
|
||||
}}
|
||||
value={row.value}
|
||||
onChange={(e) => handleChangeValue(row.id, e.target.value)}
|
||||
placeholder="수정할 값을 입력해주세요"
|
||||
aria-invalid={invalidRowId === row.id}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -7,6 +7,18 @@ import type { ListFilterTarget } from "@/types/list";
|
||||
|
||||
export type ApplyFilterOptionValue = ListFilterTarget
|
||||
|
||||
/**
|
||||
* "필터 적용 대상만"을 선택했는데 실제로 적용된 필터가 없는 경우를 검사한다.
|
||||
* alert 후 진행을 막아야 하는 호출부에서 공통으로 사용한다.
|
||||
*/
|
||||
export const validateApplyFilterTarget = (value: ApplyFilterOptionValue, filterSummary?: string[]): boolean => {
|
||||
if (value === 'filtered' && (filterSummary?.length ?? 0) === 0) {
|
||||
alert('적용된 필터가 없습니다. 필터를 적용해 주세요.')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type ApplyFilterGroupProps = {
|
||||
value: ApplyFilterOptionValue
|
||||
onValueChange: (value: ApplyFilterOptionValue) => void
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Label } from '@/components/ui/label'
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import ApplyFilterOption from './ListDialogOption/ApplyFilterOption'
|
||||
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
|
||||
import KriDateRangePicker from '@/components/common/KriDateRangePicker'
|
||||
import type { ContactHistoryDownloadType, ListDownloadMode, ListDownloadPayload, ListFilterTarget } from '@/types/list'
|
||||
|
||||
@@ -55,6 +55,8 @@ const ListDownloadDialog = ({
|
||||
}
|
||||
|
||||
const handleDownload = async () => {
|
||||
if (!validateApplyFilterTarget(target, filterSummary)) return
|
||||
|
||||
if (mode === 'contact-history') {
|
||||
const hasFrom = contactHistoryDateFrom.length > 0
|
||||
const hasTo = contactHistoryDateTo.length > 0
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Label } from '@/components/ui/label'
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import ApplyFilterOption from './ListDialogOption/ApplyFilterOption'
|
||||
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
|
||||
import type { ListFilterTarget, ListResetScope } from '@/types/list'
|
||||
|
||||
export type ListResetDialogProps = {
|
||||
@@ -42,6 +42,9 @@ const ListResetDialog = ({
|
||||
}
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (!validateApplyFilterTarget(target, filterSummary)) return
|
||||
if (target === 'all' && !confirm('전체 리스트가 초기화 됩니다. 진행하시겠습니까?')) return
|
||||
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await onConfirm({ target, scope })
|
||||
|
||||
@@ -189,8 +189,8 @@ const ListUploadDialog = ({
|
||||
})
|
||||
resetState()
|
||||
handleOpenChange(false)
|
||||
} catch {
|
||||
alert('리스트 업로드 중 오류가 발생했습니다.')
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
@@ -314,6 +314,9 @@ const ListUploadDialog = ({
|
||||
</Button>
|
||||
<input ref={fileInputRef} type="file" accept={ACCEPT_EXTENSIONS.join(',')} className="hidden" onChange={handleSelectFile} />
|
||||
</div>
|
||||
<p className="text-sm text-red-600 font-medium">
|
||||
⚠️ 해당 파일의 내용대로 배정도 수정됩니다.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{selectedFile && excelHeaders.length > 0 && compareRows.length > 0 && (
|
||||
|
||||
@@ -16,6 +16,7 @@ import type { DialogId } from '@/store/jotai/dialog'
|
||||
import type { BulkSendInfo } from '@kri/common/noti-hub'
|
||||
import type { SendResultInfo } from '@/types/message'
|
||||
import {clientEnv} from "@/lib/env.client";
|
||||
import { formatKoreanPhoneNumber } from "@/utils/phone";
|
||||
|
||||
export type MessageHistoryType = 'sms' | 'email'
|
||||
|
||||
@@ -43,9 +44,9 @@ const historyColumns: DataTableColumn<BulkSendInfo>[] = [
|
||||
]
|
||||
|
||||
const detailColumns: DataTableColumn<SendResultInfo>[] = [
|
||||
{ id: 'destTo', header: '수신처', accessorFn: (row) => row.destEml || row.destTel || '-' },
|
||||
{ id: 'destTo', header: '수신처', accessorFn: (row) => row.destEml || (row.destTel ? formatKoreanPhoneNumber(row.destTel) : '') || '-' },
|
||||
{ id: 'destNm', header: '수신자명', accessorFn: (row) => row.destNm ?? '-' },
|
||||
{ id: 'sendFrom', header: '발신지', accessorFn: (row) => row.sendEml || 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: 'sendDt', header: '발송 일시', accessorFn: (row) => (row.sendDt ? formatKst(row.sendDt, 'dateTime') : '-') },
|
||||
{ id: 'regDt', header: '등록 일시', accessorFn: (row) => (row.regDt ? formatKst(row.regDt, 'dateTime') : '-') },
|
||||
|
||||
@@ -23,7 +23,7 @@ import type { DialogId } from '@/store/jotai/dialog'
|
||||
import { createEmptyListFilter, type ListFilter, type ListFilterTarget, type listHeader } from '@/types/list'
|
||||
import { ListHeaderConst } from '@/const/listConst'
|
||||
import type { ListTableRow } from '@/components/table-column/ListTableColumn'
|
||||
import ApplyFilterOption from './ListDialogOption/ApplyFilterOption'
|
||||
import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
|
||||
import { KriEditor } from '@/components/kri-editor'
|
||||
|
||||
export type MessageSendMode = 'email' | 'sms'
|
||||
@@ -151,6 +151,7 @@ const MessageSendDialog = ({
|
||||
}
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (!validateApplyFilterTarget(target, filterSummary)) return
|
||||
if (!selectedTemplate || !templateIdx) {
|
||||
alert('템플릿을 선택해 주세요.')
|
||||
return
|
||||
@@ -196,7 +197,6 @@ const MessageSendDialog = ({
|
||||
handleOpenChange(false)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
alert('발송 중 오류가 발생했습니다.')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
'use client'
|
||||
|
||||
import {useState, useEffect, useMemo} from 'react'
|
||||
import {useState, useEffect, useMemo, useRef} from 'react'
|
||||
import { KriDialog } from "@/components/common/KriDialog";
|
||||
import {Label} from "@/components/ui/label";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {KriSingleSelect} from "@/components/common/KriAutoComplete";
|
||||
import type {MultiSelectRef} from "@/components/common/KriAutoComplete";
|
||||
import {useDialog} from "@/hooks/useDialog";
|
||||
import type {DialogId} from "@/store/jotai/dialog";
|
||||
import {NONE_HTTP_ERROR, UNKNOWN_HTTP_ERROR} from "@kri/common/http";
|
||||
import {apiError} from "@kri/common/http";
|
||||
import {ProjectCreateRequest} from "@/types/project";
|
||||
import { useDebouncedValue } from "@kri/common/hooks";
|
||||
import {PROJECT_NAME_REGEX} from "@/const/projectConst";
|
||||
import {FW_TEAM, USER_NAME_REGEX} from "@/const/userConst";
|
||||
import {FW_TEAM} from "@/const/userConst";
|
||||
import {COMMON_TEXT_REGEX, USER_NAME_REGEX} from "@/const/validationConst";
|
||||
import { validateValue } from "@/utils/validation";
|
||||
import type { MultiSelectOption } from "@/components/common/KriAutoComplete";
|
||||
import {ItrntUserInfo} from "@/types/user";
|
||||
import {useIntranetProjectListQuery} from "@/query/intranet";
|
||||
import {useGroupCodeListQuery, useIntranetProjectListQuery} from "@/query/intranet";
|
||||
|
||||
export type ProjectCreateDialogProps = {
|
||||
/** Jotai로 관리할 다이얼로그 ID */
|
||||
@@ -45,10 +45,11 @@ const ProjectCreateDialog = ({
|
||||
ownerFw: ownerFw,
|
||||
}
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog();
|
||||
const [deptArray, setDeptArray] = useState<string[]>([]);
|
||||
const [deptArray, setDeptArray] = useState<MultiSelectOption[]>([]);
|
||||
const [fwArray, setFwArray] = useState<MultiSelectOption[]>([]);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [formData, setFormData] = useState<ProjectCreateRequest>(defaultProjectInfo);
|
||||
const [invalidField, setInvalidField] = useState<'itrntPrjctCd' | 'prjctName' | 'ownerDept' | 'ownerFw' | null>(null);
|
||||
|
||||
// 실제 Dialog에 전달할 open 값
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId);
|
||||
@@ -56,9 +57,20 @@ const ProjectCreateDialog = ({
|
||||
const [itrntKeyword, setItrntKeyword] = useState('');
|
||||
const debouncedKeyword = useDebouncedValue(itrntKeyword, 500);
|
||||
|
||||
const itrntPrjctRef = useRef<MultiSelectRef>(null);
|
||||
const prjctNameRef = useRef<HTMLInputElement>(null);
|
||||
const ownerDeptRef = useRef<MultiSelectRef>(null);
|
||||
const ownerFwRef = useRef<MultiSelectRef>(null);
|
||||
|
||||
const itrntPrjctListQuery = useIntranetProjectListQuery(debouncedKeyword, resolvedOpen);
|
||||
const itrntPrjctArray = useMemo(() => itrntPrjctListQuery.data ?? [] ,[itrntPrjctListQuery.data]);
|
||||
|
||||
const groupCodeListQuery = useGroupCodeListQuery(resolvedOpen);
|
||||
const groupCodeLabelMap = useMemo(
|
||||
() => new Map((groupCodeListQuery.data ?? []).map((g) => [g.groupCode, g.groupCodeLabel])),
|
||||
[groupCodeListQuery.data]
|
||||
);
|
||||
|
||||
// 부모 콜백과 jotai 상태를 함께 처리
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
onOpenChange?.(nextOpen);
|
||||
@@ -88,32 +100,51 @@ const ProjectCreateDialog = ({
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if(!formData.itrntPrjctCd.trim()){
|
||||
alert("Please select an intranet project.");
|
||||
setInvalidField(null);
|
||||
|
||||
const itrntPrjctCheck = validateValue(formData.itrntPrjctCd, {
|
||||
required: true,
|
||||
requiredMessage: "인트라넷 프로젝트를 선택해주세요.",
|
||||
});
|
||||
if (!itrntPrjctCheck.valid) {
|
||||
alert(itrntPrjctCheck.message);
|
||||
setInvalidField('itrntPrjctCd');
|
||||
itrntPrjctRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
if (!formData.prjctName.trim()) {
|
||||
alert("Please enter project name.");
|
||||
const prjctNameCheck = validateValue(formData.prjctName, {
|
||||
required: true,
|
||||
requiredMessage: "프로젝트명을 입력해주세요.",
|
||||
maxLength: 128,
|
||||
pattern: COMMON_TEXT_REGEX,
|
||||
patternMessage: "프로젝트명에 허용되지 않는 문자가 포함되어 있습니다.",
|
||||
});
|
||||
if (!prjctNameCheck.valid) {
|
||||
alert(prjctNameCheck.message);
|
||||
setInvalidField('prjctName');
|
||||
prjctNameRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
if (!PROJECT_NAME_REGEX.test(formData.prjctName)) {
|
||||
alert("프로젝트명에 허용되지 않는 문자가 포함되어 있습니다.");
|
||||
const ownerDeptCheck = validateValue(formData.ownerDept, {
|
||||
required: true,
|
||||
requiredMessage: "담당 그룹을 입력해주세요.",
|
||||
pattern: USER_NAME_REGEX,
|
||||
patternMessage: "해당 그룹이 올바르지 않습니다.",
|
||||
});
|
||||
if (!ownerDeptCheck.valid) {
|
||||
alert(ownerDeptCheck.message);
|
||||
setInvalidField('ownerDept');
|
||||
ownerDeptRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
if(!formData.ownerDept.trim()){
|
||||
alert("Please enter owner department.");
|
||||
return;
|
||||
}
|
||||
if(!USER_NAME_REGEX.test(formData.ownerDept)){
|
||||
alert("해당 그룹이 올바르지 않습니다.");
|
||||
return;
|
||||
}
|
||||
if(!formData.ownerFw.trim()){
|
||||
alert("Please enter owner department.");
|
||||
return;
|
||||
}
|
||||
if(!USER_NAME_REGEX.test(formData.ownerDept)){
|
||||
alert("해당 SV가 올바르지 않습니다.");
|
||||
const ownerFwCheck = validateValue(formData.ownerFw, {
|
||||
required: true,
|
||||
requiredMessage: "담당 실사(SV)를 입력해주세요.",
|
||||
});
|
||||
if (!ownerFwCheck.valid) {
|
||||
alert(ownerFwCheck.message);
|
||||
setInvalidField('ownerFw');
|
||||
ownerFwRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -122,15 +153,7 @@ const ProjectCreateDialog = ({
|
||||
await onSubmit(formData as ProjectCreateRequest);
|
||||
handleOpenChange(false);
|
||||
} catch (e) {
|
||||
const err = apiError(e, {
|
||||
fallbackMessage: "Save failed.",
|
||||
});
|
||||
if(err.code !== NONE_HTTP_ERROR && err.code !== UNKNOWN_HTTP_ERROR){
|
||||
alert(err.message);
|
||||
}
|
||||
else{
|
||||
alert("저장에 실패했습니다.");
|
||||
}
|
||||
console.error(e);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
@@ -138,6 +161,7 @@ const ProjectCreateDialog = ({
|
||||
|
||||
useEffect(() => {
|
||||
setFormData(defaultProjectInfo);
|
||||
setInvalidField(null);
|
||||
}, [resolvedOpen])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -146,7 +170,10 @@ const ProjectCreateDialog = ({
|
||||
userTeams.push("T900");
|
||||
}
|
||||
userTeams = userTeams.sort((a, b) => a.localeCompare(b, "ko"));
|
||||
setDeptArray(userTeams);
|
||||
setDeptArray(userTeams.map((code) => ({
|
||||
value: code,
|
||||
label: groupCodeLabelMap.get(code) ?? code,
|
||||
})));
|
||||
|
||||
const userOptions: MultiSelectOption[] = users
|
||||
.filter(u => u.userId == ownerFw || u.userTeam == FW_TEAM)
|
||||
@@ -155,7 +182,7 @@ const ProjectCreateDialog = ({
|
||||
label: u.userNm,
|
||||
}));
|
||||
setFwArray(userOptions);
|
||||
}, [users]);
|
||||
}, [users, groupCodeLabelMap]);
|
||||
|
||||
return (
|
||||
<KriDialog
|
||||
@@ -189,6 +216,7 @@ const ProjectCreateDialog = ({
|
||||
인트라넷 프로젝트<span className="text-red-500 ml-1">*</span>
|
||||
</Label>
|
||||
<KriSingleSelect
|
||||
ref={itrntPrjctRef}
|
||||
items={itrntPrjctArray}
|
||||
value={String(formData.itrntPrjctCd)}
|
||||
onChange={(e) => handleInputChange('itrntPrjctCd', e)}
|
||||
@@ -199,17 +227,20 @@ const ProjectCreateDialog = ({
|
||||
placeholder="인트라넷 프로젝트"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
aria-invalid={invalidField === 'itrntPrjctCd'}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="prjctName">
|
||||
Project name<span className="text-red-500 ml-1">*</span>
|
||||
프로젝트명<span className="text-red-500 ml-1">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
ref={prjctNameRef}
|
||||
id="prjctName"
|
||||
placeholder="Enter project name"
|
||||
placeholder="프로젝트명을 입력하세요"
|
||||
value={formData.prjctName}
|
||||
onChange={(e) => handleInputChange('prjctName', e.target.value)}
|
||||
aria-invalid={invalidField === 'prjctName'}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
@@ -217,12 +248,16 @@ const ProjectCreateDialog = ({
|
||||
담당 그룹<span className="text-red-500 ml-1">*</span>
|
||||
</Label>
|
||||
<KriSingleSelect
|
||||
ref={ownerDeptRef}
|
||||
items={deptArray}
|
||||
value={formData.ownerDept || ''}
|
||||
onChange={(value) => handleInputChange('ownerDept', value)}
|
||||
placeholder="Select owner department"
|
||||
getValue={(item) => item.value}
|
||||
getLabel={(item) => item.label}
|
||||
placeholder="담당 그룹을 선택하세요"
|
||||
heightClassName="h-9"
|
||||
widthClassName="w-full"
|
||||
aria-invalid={invalidField === 'ownerDept'}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
@@ -230,14 +265,16 @@ const ProjectCreateDialog = ({
|
||||
담당 실사<span className="text-red-500 ml-1">*</span>
|
||||
</Label>
|
||||
<KriSingleSelect
|
||||
ref={ownerFwRef}
|
||||
items={fwArray}
|
||||
value={formData.ownerFw || ''}
|
||||
onChange={(value) => handleInputChange('ownerFw', value)}
|
||||
getValue={(item) => item.value}
|
||||
getLabel={(item) => item.label}
|
||||
placeholder="Select owner department"
|
||||
placeholder="담당 실사를 선택하세요"
|
||||
heightClassName="h-9"
|
||||
widthClassName="w-full"
|
||||
aria-invalid={invalidField === 'ownerFw'}
|
||||
/>
|
||||
</div>
|
||||
</KriDialog>
|
||||
|
||||
@@ -132,7 +132,6 @@ const SingleMessageSendDialog = ({
|
||||
handleOpenChange(false)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
alert('발송 중 오류가 발생했습니다.')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import { useState, useRef } from 'react'
|
||||
import {Download, Upload, X} from 'lucide-react'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import {apiError} from "@kri/common/http";
|
||||
|
||||
export type UserUploadDialogProps = {
|
||||
/** jotai로 관리할 dialog id */
|
||||
@@ -92,11 +91,7 @@ const UserUploadDialog = ({
|
||||
handleRemoveFile();
|
||||
handleOpenChange(false);
|
||||
} catch (e) {
|
||||
const err = apiError(e, {
|
||||
fallbackMessage: "File upload failed.",
|
||||
});
|
||||
console.error(err.status, err.code, err.message);
|
||||
alert("업로드에 실패했습니다.");
|
||||
console.error(e);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { KriDialog } from '@/components/common/KriDialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
@@ -8,14 +8,14 @@ import { Label } from '@/components/ui/label'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import { UserInfoSaveRequest } from '@/types/user'
|
||||
import KriPassword, { KRI_PW_REGEX } from "@/components/common/KriPassword";
|
||||
import {KriSelect, KriSelectItem} from "@/components/common/KriSelect";
|
||||
import KriPassword, { type KriPasswordRef } from "@/components/common/KriPassword";
|
||||
import {KriSelect, KriSelectItem, type KriSelectRef} from "@/components/common/KriSelect";
|
||||
import type { DataVerification } from "@kri/common";
|
||||
import {apiError} from "@kri/common/http";
|
||||
import {CONTACT_INTERVIEWER_ROLE, FW_TEAM, USER_NAME_REGEX} from "@/const/userConst";
|
||||
import {NONE_HTTP_ERROR, UNKNOWN_HTTP_ERROR} from "@kri/common/http";
|
||||
import {CONTACT_INTERVIEWER_ROLE, FW_TEAM} from "@/const/userConst";
|
||||
import {KRI_PW_REGEX, USER_NAME_REGEX} from "@/const/validationConst";
|
||||
import type { CmpnInfo } from "@/types/cmpn";
|
||||
import { isExternalManager, isFieldWorkUser } from "@/utils/userRole";
|
||||
import { validateValue } from "@/utils/validation";
|
||||
|
||||
// 외주사(EXTERNAL_USER_ROLE_GROUP)와 콜센터/컨택원/면접원(FW_USER_ROLE_GROUP)은 배정 체계가 완전히 달라
|
||||
// 서로 넘나드는 권한 수정을 지원하지 않는다. 하나 새로 만들어서 넘기는 게 맞다.
|
||||
@@ -69,6 +69,13 @@ const UserUpsertDialog = ({
|
||||
|
||||
const [isCheckedDuplicate, setIsCheckedDuplicate] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [invalidField, setInvalidField] = useState<'userId' | 'userPw' | 'userName' | 'userCmpn' | 'memo' | null>(null);
|
||||
|
||||
const userIdRef = useRef<HTMLInputElement>(null);
|
||||
const userPwRef = useRef<KriPasswordRef>(null);
|
||||
const userNameRef = useRef<HTMLInputElement>(null);
|
||||
const userCmpnRef = useRef<KriSelectRef>(null);
|
||||
const memoRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
// 실제 Dialog에 전달할 open 값
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId);
|
||||
@@ -86,6 +93,7 @@ const UserUpsertDialog = ({
|
||||
|
||||
// initialData / mode / open 변경 시 폼 세팅
|
||||
useEffect(() => {
|
||||
setInvalidField(null);
|
||||
if (initialData) {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
@@ -108,6 +116,12 @@ const UserUpsertDialog = ({
|
||||
return userRoleArray.filter((item) => !isCrossExternalFwRoleChange(initialRole, Number(item.value)))
|
||||
}, [mode, initialData?.userRole, userRoleArray])
|
||||
|
||||
// 외주 실사(외주사) 권한은 자사 소속을 가질 수 없으므로 회사 선택지에서 제외한다.
|
||||
const availableCmpnArray = useMemo(() => {
|
||||
if (!isExternalManager(formData.userRole)) return userCmpnArray
|
||||
return userCmpnArray.filter((c) => !c.ownCmpn)
|
||||
}, [userCmpnArray, formData.userRole])
|
||||
|
||||
const handleInputChange = <K extends keyof UserInfoSaveRequest>(field: K, value: UserInfoSaveRequest[K]) => {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
@@ -120,8 +134,11 @@ const UserUpsertDialog = ({
|
||||
}
|
||||
|
||||
const handleCheckDuplicate = async () => {
|
||||
if (!formData.userId.trim()) {
|
||||
alert("아이디를 입력해주세요.");
|
||||
const userIdCheck = validateValue(formData.userId, { required: true, requiredMessage: "아이디를 입력해주세요." });
|
||||
if (!userIdCheck.valid) {
|
||||
alert(userIdCheck.message);
|
||||
setInvalidField('userId');
|
||||
userIdRef.current?.focus();
|
||||
return
|
||||
}
|
||||
|
||||
@@ -140,28 +157,73 @@ const UserUpsertDialog = ({
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!formData.userId.trim()) {
|
||||
alert("아이디를 입력해주세요.");
|
||||
setInvalidField(null);
|
||||
|
||||
const userIdCheck = validateValue(formData.userId, { required: true, requiredMessage: "아이디를 입력해주세요." });
|
||||
if (!userIdCheck.valid) {
|
||||
alert(userIdCheck.message);
|
||||
setInvalidField('userId');
|
||||
userIdRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
if (mode === 'create' && !isCheckedDuplicate) {
|
||||
alert("아이디 중복체크를 해주세요.");
|
||||
setInvalidField('userId');
|
||||
userIdRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
if (!formData.userPw.trim()) {
|
||||
alert("비밀번호를 입력해주세요.");
|
||||
const userPwCheck = validateValue(formData.userPw, {
|
||||
required: true,
|
||||
requiredMessage: "비밀번호를 입력해주세요.",
|
||||
pattern: KRI_PW_REGEX,
|
||||
patternMessage: "비밀번호는 영문과 숫자를 포함한 8~20자로 입력해주세요.",
|
||||
});
|
||||
if (!userPwCheck.valid) {
|
||||
alert(userPwCheck.message);
|
||||
setInvalidField('userPw');
|
||||
userPwRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
if (!KRI_PW_REGEX.test(formData.userPw)) {
|
||||
alert("비밀번호는 영문과 숫자를 포함한 8~20자로 입력해주세요.");
|
||||
const userNameCheck = validateValue(formData.userName, {
|
||||
required: true,
|
||||
requiredMessage: "이름을 입력해주세요.",
|
||||
maxLength: 32,
|
||||
pattern: USER_NAME_REGEX,
|
||||
patternMessage: "이름에 허용되지 않는 문자가 포함되어 있습니다.",
|
||||
});
|
||||
if (!userNameCheck.valid) {
|
||||
alert(userNameCheck.message);
|
||||
setInvalidField('userName');
|
||||
userNameRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
if (!formData.userName.trim()) {
|
||||
alert("이름을 입력해주세요.");
|
||||
|
||||
const userCmpnCheck = validateValue(formData.userCmpn, {
|
||||
required: true,
|
||||
requiredMessage: "회사를 선택해주세요.",
|
||||
});
|
||||
if (!userCmpnCheck.valid) {
|
||||
alert(userCmpnCheck.message);
|
||||
setInvalidField('userCmpn');
|
||||
userCmpnRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
if(!USER_NAME_REGEX.test(formData.userName)){
|
||||
alert("올바르지 않은 이름입니다.");
|
||||
|
||||
if (isExternalManager(formData.userRole)) {
|
||||
const selectedCmpn = userCmpnArray.find((c) => c.cmpnId === formData.userCmpn);
|
||||
if (selectedCmpn?.ownCmpn) {
|
||||
alert("외주 실사 권한은 자사를 소속 회사로 선택할 수 없습니다.");
|
||||
setInvalidField('userCmpn');
|
||||
userCmpnRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const memoCheck = validateValue(formData.memo ?? '', { maxLength: 2048 });
|
||||
if (!memoCheck.valid) {
|
||||
alert(memoCheck.message);
|
||||
setInvalidField('memo');
|
||||
memoRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -173,16 +235,7 @@ const UserUpsertDialog = ({
|
||||
await onSubmit(formData as UserInfoSaveRequest);
|
||||
handleOpenChange(false);
|
||||
} catch (e) {
|
||||
const err = apiError(e, {
|
||||
fallbackMessage: "Save failed.",
|
||||
});
|
||||
console.error(err.status, err.code, err.message);
|
||||
if(err.code !== NONE_HTTP_ERROR && err.code !== UNKNOWN_HTTP_ERROR){
|
||||
alert(err.message);
|
||||
}
|
||||
else{
|
||||
alert("저장에 실패했습니다.");
|
||||
}
|
||||
console.error(e);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
@@ -221,11 +274,13 @@ const UserUpsertDialog = ({
|
||||
</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
ref={userIdRef}
|
||||
id="userId"
|
||||
placeholder="Enter ID"
|
||||
placeholder="아이디를 입력하세요"
|
||||
value={formData.userId}
|
||||
onChange={(e) => handleInputChange('userId', e.target.value)}
|
||||
disabled={mode === 'edit'}
|
||||
aria-invalid={invalidField === 'userId'}
|
||||
/>
|
||||
{mode === 'create' && (
|
||||
<Button
|
||||
@@ -240,14 +295,16 @@ const UserUpsertDialog = ({
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="password">
|
||||
PW<span className="text-red-500 ml-1">*</span>
|
||||
Password<span className="text-red-500 ml-1">*</span>
|
||||
</Label>
|
||||
<KriPassword
|
||||
ref={userPwRef}
|
||||
id="password"
|
||||
label=""
|
||||
value={formData.userPw}
|
||||
onChange={(v) => handleInputChange('userPw', v)}
|
||||
placeholder="Enter password"
|
||||
placeholder="비밀번호를 입력하세요"
|
||||
aria-invalid={invalidField === 'userPw'}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
@@ -255,14 +312,18 @@ const UserUpsertDialog = ({
|
||||
이름<span className="text-red-500 ml-1">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
ref={userNameRef}
|
||||
id="userName"
|
||||
placeholder="Enter name"
|
||||
placeholder="이름을 입력하세요"
|
||||
value={formData.userName}
|
||||
onChange={(e) => handleInputChange('userName', e.target.value)}
|
||||
aria-invalid={invalidField === 'userName'}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label>계정 권한</Label>
|
||||
<Label>
|
||||
계정 권한 <span className="text-red-500 ml-1">*</span>
|
||||
</Label>
|
||||
<KriSelect
|
||||
items={availableRoleArray}
|
||||
value={String(formData.userRole)}
|
||||
@@ -272,7 +333,15 @@ const UserUpsertDialog = ({
|
||||
if(mode !== 'create'){
|
||||
alert("권한이 변경되면 해당 계정에 배정된 리스트 정보가 초기화됩니다.");
|
||||
}
|
||||
handleInputChange('userRole', Number(e));
|
||||
const nextRole = Number(e);
|
||||
handleInputChange('userRole', nextRole);
|
||||
|
||||
if (isExternalManager(nextRole)) {
|
||||
const currentCmpn = userCmpnArray.find((c) => c.cmpnId === formData.userCmpn);
|
||||
if (currentCmpn?.ownCmpn) {
|
||||
handleInputChange('userCmpn', '');
|
||||
}
|
||||
}
|
||||
}}
|
||||
useAll={false}
|
||||
className="w-full min-w-0 overflow-hidden [&>span]:truncate"
|
||||
@@ -280,9 +349,12 @@ const UserUpsertDialog = ({
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label>소속 회사</Label>
|
||||
<Label>
|
||||
소속 회사 <span className="text-red-500 ml-1">*</span>
|
||||
</Label>
|
||||
<KriSelect
|
||||
items={userCmpnArray}
|
||||
ref={userCmpnRef}
|
||||
items={availableCmpnArray}
|
||||
value={formData.userCmpn}
|
||||
getValue={(item) => item.cmpnId}
|
||||
getLabel={(item) => item.cmpnAlias || item.cmpnId}
|
||||
@@ -291,15 +363,17 @@ const UserUpsertDialog = ({
|
||||
disabled={mode !== 'create'}
|
||||
className="w-full min-w-0 overflow-hidden [&>span]:truncate"
|
||||
heightClassName="h-9"
|
||||
aria-invalid={invalidField === 'userCmpn'}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="memo">메모</Label>
|
||||
<textarea id="memo" 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 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
<textarea ref={memoRef} id="memo" 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 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20"
|
||||
rows={3}
|
||||
placeholder="Enter memo"
|
||||
placeholder="메모를 입력하세요"
|
||||
value={formData.memo}
|
||||
onChange={(e) => handleInputChange('memo', e.target.value)}
|
||||
aria-invalid={invalidField === 'memo'}
|
||||
/>
|
||||
</div>
|
||||
</KriDialog>
|
||||
|
||||
@@ -117,7 +117,7 @@ export function KriEditorHtmlOnly({
|
||||
})
|
||||
} catch (error) {
|
||||
if (onImageUploadError) onImageUploadError(error)
|
||||
else toast.error('이미지 업로드에 실패했습니다.')
|
||||
else console.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -79,7 +79,6 @@ export function KriEditorSms({
|
||||
|
||||
return (
|
||||
<div className={cn('mx-auto w-full max-w-[320px]', className)}>
|
||||
{label ? <div className="mb-2 text-sm font-semibold">{label}</div> : null}
|
||||
<div className="relative h-[600px] w-full overflow-hidden rounded-[40px] border-8 border-gray-800 bg-white shadow-2xl">
|
||||
<div className="absolute top-0 left-1/2 z-10 h-6 w-32 -translate-x-1/2 rounded-b-2xl bg-gray-800" />
|
||||
<div className="flex h-full flex-col bg-gray-50 px-4 pt-8 pb-4">
|
||||
@@ -106,6 +105,7 @@ export function KriEditorSms({
|
||||
{...textareaInsert.bindSelectionHandlers}
|
||||
/>
|
||||
</div>
|
||||
{label ? <div className="my-2 text-sm font-semibold text-red-600">{label}</div> : null}
|
||||
{byteSize > maxBytes ? (
|
||||
<p className="mt-2 px-2 text-center text-xs font-medium text-red-600">
|
||||
최대 용량을 {byteSize - maxBytes}byte 초과했습니다.
|
||||
|
||||
@@ -193,7 +193,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
editorProps: {
|
||||
attributes: {
|
||||
class: cn(
|
||||
"min-h-[180px] px-3 py-2 focus:outline-none",
|
||||
"min-h-[180px] max-h-[420px] overflow-y-auto px-3 py-2 focus:outline-none",
|
||||
"[&_p]:my-2 [&_p:first-child]:mt-0 [&_p:last-child]:mb-0",
|
||||
"[&_ul]:list-disc [&_ul]:pl-6 [&_ol]:list-decimal [&_ol]:pl-6",
|
||||
"[&_li]:my-1",
|
||||
@@ -408,7 +408,6 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
if(onImageUploadError){
|
||||
onImageUploadError(err);
|
||||
}else{
|
||||
toast.error("이미지 업로드에 실패했습니다.");
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
@@ -477,11 +476,14 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
|
||||
if (viewRef.current === "html") return;
|
||||
if (value == null) return;
|
||||
|
||||
// 빈 문자열("")은 ProseMirror 스키마상 유효한 문서가 아니라 setContent가 조용히 실패해
|
||||
// 이전 템플릿 본문이 그대로 남는 문제가 있었음 -> 빈 값은 빈 문단으로 정규화해서 비교/설정.
|
||||
const normalizedValue = value || "<p></p>";
|
||||
const current = editor.getHTML();
|
||||
|
||||
if (value !== current && value !== optimisticHtmlRef.current) {
|
||||
if (normalizedValue !== current && normalizedValue !== optimisticHtmlRef.current) {
|
||||
// 이미지가 포함된 HTML 업데이트면, 아예 editor를 새로 생성
|
||||
editor.commands.setContent(value, {
|
||||
editor.commands.setContent(normalizedValue, {
|
||||
emitUpdate: false,
|
||||
parseOptions: {preserveWhitespace: "full"},
|
||||
});
|
||||
|
||||
@@ -124,7 +124,7 @@ const ContactEventSection = ({
|
||||
const isContactType = resultCodeType === ResultCodeType.CONTACT
|
||||
|
||||
const historyQuery = useListEventHistoryQuery(prjctIdx, sid, true)
|
||||
const ctiLastCallHistId = useCtiLastCallHistId()
|
||||
const ctiLastCallHistId = useCtiLastCallHistId(prjctIdx, Number(sid))
|
||||
const listCallHistIdx = isContactType ? ctiLastCallHistId : null
|
||||
|
||||
const handleResultCdChange = (next: string) => {
|
||||
@@ -280,6 +280,7 @@ export type ListContactEventPanelProps = {
|
||||
userId: string
|
||||
userRole: number
|
||||
resultCodes: ResultCode[]
|
||||
useFF: boolean
|
||||
useContactSenario: boolean
|
||||
contactSenario?: string
|
||||
}
|
||||
@@ -291,6 +292,7 @@ const ListContactEventPanel = ({
|
||||
userId,
|
||||
userRole,
|
||||
resultCodes,
|
||||
useFF,
|
||||
useContactSenario,
|
||||
contactSenario,
|
||||
}: ListContactEventPanelProps) => {
|
||||
@@ -341,16 +343,19 @@ const ListContactEventPanel = ({
|
||||
|
||||
<SendResultHistory sid={sid} prjctCd={prjctCd} />
|
||||
|
||||
<ContactEventSection
|
||||
title="인터뷰 요원 확인사항"
|
||||
prjctIdx={prjctIdx}
|
||||
sid={sid}
|
||||
resultCodeType={ResultCodeType.INTERVIEW}
|
||||
resultCodes={resultCodes}
|
||||
showInput={showInterviewInput}
|
||||
submitting={addListEventMutation.isPending}
|
||||
onSubmit={handleAddEvent(ResultCodeType.INTERVIEW)}
|
||||
/>
|
||||
{useFF &&
|
||||
<ContactEventSection
|
||||
title="인터뷰 요원 확인사항"
|
||||
prjctIdx={prjctIdx}
|
||||
sid={sid}
|
||||
resultCodeType={ResultCodeType.INTERVIEW}
|
||||
resultCodes={resultCodes}
|
||||
showInput={showInterviewInput}
|
||||
submitting={addListEventMutation.isPending}
|
||||
onSubmit={handleAddEvent(ResultCodeType.INTERVIEW)}
|
||||
/>
|
||||
}
|
||||
|
||||
|
||||
{useContactSenario && contactSenario ? (
|
||||
<div className="space-y-2 rounded-lg border bg-white p-4">
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
'use client'
|
||||
|
||||
import { useRef, useState, type ReactNode } from 'react'
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
||||
import { Mail, MessageSquare, Paperclip, Phone, QrCode } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import { useUploadListItemFileMutation } from '@/query/list'
|
||||
import { useDownloadListItemFileByHeaderMutation, useUploadListItemFileMutation } from '@/query/list'
|
||||
import { ListHeaderConst } from '@/const/listConst'
|
||||
import type { listHeader, ListSearchWithFullResult } from '@/types/list'
|
||||
import type { MessageSendChannel } from '@/types/message'
|
||||
import { type ResultCode, ResultCodeType } from '@/types/project'
|
||||
import { type ProjectSurvey, type ResultCode, ResultCodeType } from '@/types/project'
|
||||
import { formatKst } from '@kri/common'
|
||||
import { isListFieldEditableForContact, isListFieldVisibleForContact } from '@/utils/listAccess'
|
||||
import { substituteSurveyUrl } from '@/lib/surveyUrl'
|
||||
import { formatKoreanPhoneNumber } from '@/utils/phone'
|
||||
import SurveyQrDialog from '@/components/dialog/SurveyQrDialog'
|
||||
import SingleMessageSendDialog from '@/components/dialog/SingleMessageSendDialog'
|
||||
import { ctiClient } from '@/lib/cti/ctiClient'
|
||||
@@ -22,6 +23,7 @@ import { useCtiConnectionStatus } from '@/hooks/useCtiConnectionStatus'
|
||||
import { useCtiAgentStatus } from '@/hooks/useCtiAgentStatus'
|
||||
import { CTI_ON_CALL_STATUSES } from '@/const/ctiConst'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { downloadFile } from '@kri/common/browser'
|
||||
|
||||
export type ListContactInfoPanelProps = {
|
||||
prjctIdx: number
|
||||
@@ -31,7 +33,7 @@ export type ListContactInfoPanelProps = {
|
||||
isEditing: boolean
|
||||
listHeaders: listHeader[]
|
||||
detail?: ListSearchWithFullResult
|
||||
surveyUrl?: string
|
||||
surveys: ProjectSurvey[]
|
||||
callerTelNum?: string
|
||||
resultCodes: ResultCode[]
|
||||
formValues: Record<number, string>
|
||||
@@ -72,7 +74,7 @@ const ListContactInfoPanel = ({
|
||||
isEditing,
|
||||
listHeaders,
|
||||
detail,
|
||||
surveyUrl,
|
||||
surveys,
|
||||
callerTelNum,
|
||||
resultCodes,
|
||||
formValues,
|
||||
@@ -81,29 +83,47 @@ const ListContactInfoPanel = ({
|
||||
}: ListContactInfoPanelProps) => {
|
||||
const { showDialog } = useDialog()
|
||||
const uploadItemFileMutation = useUploadListItemFileMutation(prjctIdx, sid)
|
||||
const downloadItemFileMutation = useDownloadListItemFileByHeaderMutation(prjctIdx, sid)
|
||||
const fileInputRef = useRef<HTMLInputElement | null>(null)
|
||||
const [uploadingHeaderId, setUploadingHeaderId] = useState<number | null>(null)
|
||||
const [sendTarget, setSendTarget] = useState<{ channel: MessageSendChannel; headerId: number } | null>(null)
|
||||
const [qrTargetUrl, setQrTargetUrl] = useState('')
|
||||
const ctiConnectionStatus = useCtiConnectionStatus()
|
||||
const isCtiReady = ctiConnectionStatus === 'open'
|
||||
const ctiAgentStatus = useCtiAgentStatus()
|
||||
const isOnCall = ctiAgentStatus !== null && (CTI_ON_CALL_STATUSES as readonly string[]).includes(ctiAgentStatus)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOnCall) return
|
||||
|
||||
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
|
||||
event.preventDefault()
|
||||
event.returnValue = true
|
||||
}
|
||||
|
||||
window.addEventListener('beforeunload', handleBeforeUnload)
|
||||
return () => window.removeEventListener('beforeunload', handleBeforeUnload)
|
||||
}, [isOnCall])
|
||||
|
||||
const visibleHeaders = listHeaders
|
||||
.filter((header) => isListFieldVisibleForContact(header))
|
||||
.sort((a, b) => a.listHderOrder - b.listHderOrder)
|
||||
.sort((a, b) => {
|
||||
if (a.listHderTy === ListHeaderConst.MEMO) return 1
|
||||
if (b.listHderTy === ListHeaderConst.MEMO) return -1
|
||||
return a.listHderOrder - b.listHderOrder
|
||||
})
|
||||
|
||||
const substitutedSurveyUrl = surveyUrl ? substituteSurveyUrl(surveyUrl, sid) : ''
|
||||
const surveyResult = detail?.surveyResult
|
||||
const hasSurveyResponse = surveyResult?.lastResultCd !== undefined
|
||||
const surveyResultLabel = hasSurveyResponse
|
||||
? resultCodes.find((rc) => rc.resultCdTy === ResultCodeType.SURVEY && rc.resultCd === surveyResult?.lastResultCd)
|
||||
?.resultCdLbl ?? String(surveyResult?.lastResultCd)
|
||||
: ''
|
||||
const surveyResultByIdx = new Map((detail?.surveyResults ?? []).map((result) => [result.prjctSurveyIdx, result]))
|
||||
|
||||
const handleStartSurvey = () => {
|
||||
if (!substitutedSurveyUrl) return
|
||||
window.open(substitutedSurveyUrl, '_blank', 'noopener,noreferrer')
|
||||
const handleStartSurvey = (survey: ProjectSurvey) => {
|
||||
if (!survey.surveyUrl) return
|
||||
window.open(substituteSurveyUrl(survey.surveyUrl, sid), '_blank', 'noopener,noreferrer')
|
||||
}
|
||||
|
||||
const handleShowQr = (survey: ProjectSurvey) => {
|
||||
if (!survey.surveyUrl) return
|
||||
setQrTargetUrl(substituteSurveyUrl(survey.surveyUrl, sid))
|
||||
showDialog('surveyQrDialog')
|
||||
}
|
||||
|
||||
const handleSend = (channel: MessageSendChannel, headerId: number) => {
|
||||
@@ -112,7 +132,13 @@ const ListContactInfoPanel = ({
|
||||
}
|
||||
|
||||
const handleCall = (telNum: string, listHderId: number) => {
|
||||
if (!telNum || !isCtiReady || isOnCall) return
|
||||
if (!isCtiReady) return
|
||||
// CTI_HANGUP_PENDING_VENDOR: 외주사 Hangup 명령 동작 확인 후 통화 중 버튼을 활성화하면 즉시 사용할 수 있다.
|
||||
if (isOnCall) {
|
||||
ctiClient.hangup()
|
||||
return
|
||||
}
|
||||
if (!telNum) return
|
||||
ctiClient.makeCall({ dialNumber: telNum, prjctIdx, sid: Number(sid), listHderId, aniNumber: callerTelNum ?? '' })
|
||||
}
|
||||
|
||||
@@ -121,6 +147,11 @@ const ListContactInfoPanel = ({
|
||||
fileInputRef.current?.click()
|
||||
}
|
||||
|
||||
const handleDownloadFile = async (listHderId: number, fileName: string) => {
|
||||
const buffer = await downloadItemFileMutation.mutateAsync(listHderId)
|
||||
downloadFile(new Blob([buffer], { type: 'application/octet-stream' }), fileName)
|
||||
}
|
||||
|
||||
const handleFileSelected = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
e.target.value = ''
|
||||
@@ -136,11 +167,11 @@ const ListContactInfoPanel = ({
|
||||
<div className="space-y-4 rounded-lg border bg-white p-4">
|
||||
<h2 className="text-lg font-bold">리스트 정보</h2>
|
||||
<input type="file" ref={fileInputRef} className="hidden" onChange={handleFileSelected} />
|
||||
|
||||
{visibleHeaders.map((header) => {
|
||||
if (header.listHderTy === ListHeaderConst.SID) return null
|
||||
|
||||
const editable = isEditing && isListFieldEditableForContact(header, userRole)
|
||||
const canEditField = isListFieldEditableForContact(header, userRole)
|
||||
const editable = isEditing && canEditField
|
||||
const value = formValues[header.listHderId] ?? ''
|
||||
const onChange = (next: string) => onFieldChange(header.listHderId, next)
|
||||
|
||||
@@ -162,9 +193,9 @@ const ListContactInfoPanel = ({
|
||||
<FieldRow key={header.listHderId} label={header.listHderNm}>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={value}
|
||||
value={formatKoreanPhoneNumber(value)}
|
||||
disabled={!editable}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
onChange={(e) => onChange(e.target.value.replace(/\D/g, ''))}
|
||||
className={disabledContrastClass}
|
||||
/>
|
||||
<Button
|
||||
@@ -220,17 +251,38 @@ const ListContactInfoPanel = ({
|
||||
return (
|
||||
<FieldRow key={header.listHderId} label={header.listHderNm}>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="min-w-0 flex-1 truncate text-sm">{value || '업로드된 파일 없음'}</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="shrink-0 gap-2"
|
||||
disabled={!editable || uploadItemFileMutation.isPending}
|
||||
onClick={() => handlePickFile(header.listHderId)}
|
||||
>
|
||||
<Paperclip className="h-4 w-4" />
|
||||
업로드
|
||||
</Button>
|
||||
<div className="min-w-0 flex-1 truncate text-sm">
|
||||
{value ? (
|
||||
<button
|
||||
type="button"
|
||||
className="max-w-full cursor-pointer text-left text-primary hover:text-primary/80 disabled:cursor-wait disabled:opacity-60"
|
||||
disabled={downloadItemFileMutation.isPending}
|
||||
title={value}
|
||||
onClick={() => handleDownloadFile(header.listHderId, value)}
|
||||
>
|
||||
<span
|
||||
className="block truncate"
|
||||
style={{ textDecorationLine: 'underline', textUnderlineOffset: '3px' }}
|
||||
>
|
||||
{value}
|
||||
</span>
|
||||
</button>
|
||||
) : (
|
||||
<span>업로드된 파일 없음</span>
|
||||
)}
|
||||
</div>
|
||||
{canEditField ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="shrink-0 gap-2"
|
||||
disabled={uploadItemFileMutation.isPending}
|
||||
onClick={() => handlePickFile(header.listHderId)}
|
||||
>
|
||||
<Paperclip className="h-4 w-4" />
|
||||
업로드
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</FieldRow>
|
||||
)
|
||||
@@ -266,31 +318,37 @@ const ListContactInfoPanel = ({
|
||||
)
|
||||
})}
|
||||
|
||||
{surveyUrl ? (
|
||||
<FieldRow label="Web">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button type="button" className="gap-2" onClick={handleStartSurvey}>
|
||||
조사 시작
|
||||
</Button>
|
||||
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('surveyQrDialog')}>
|
||||
<QrCode className="h-4 w-4" />
|
||||
QR
|
||||
</Button>
|
||||
{hasSurveyResponse ? (
|
||||
<span className="text-sm">
|
||||
[{surveyResultLabel}]{' '}
|
||||
<span className="text-muted-foreground">
|
||||
({formatKst(surveyResult?.lastResultDt ?? '', 'dateHourMin')})
|
||||
</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">[응답없음]</span>
|
||||
)}
|
||||
</div>
|
||||
</FieldRow>
|
||||
) : null}
|
||||
{surveys
|
||||
.filter((survey) => !!survey.surveyUrl)
|
||||
.map((survey) => {
|
||||
const result = survey.prjctSurveyIdx != null ? surveyResultByIdx.get(survey.prjctSurveyIdx) : undefined
|
||||
const hasSurveyResponse = result !== undefined
|
||||
|
||||
<SurveyQrDialog url={substitutedSurveyUrl} />
|
||||
return (
|
||||
<FieldRow key={survey.prjctSurveyIdx ?? survey.surveyOrder} label={survey.surveyName || 'Web'}>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button type="button" className="gap-2" onClick={() => handleStartSurvey(survey)}>
|
||||
조사 시작
|
||||
</Button>
|
||||
<Button type="button" variant="outline" className="gap-2" onClick={() => handleShowQr(survey)}>
|
||||
<QrCode className="h-4 w-4" />
|
||||
QR
|
||||
</Button>
|
||||
{hasSurveyResponse ? (
|
||||
<span className="text-sm">
|
||||
[{resultCodes.find((rc) => rc.resultCdTy === ResultCodeType.SURVEY && rc.resultCd === result.lastResultCd)
|
||||
?.resultCdLbl ?? String(result.lastResultCd)}]{' '}
|
||||
<span className="text-muted-foreground">({formatKst(result.lastResultDt, 'dateHourMin')})</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">[응답없음]</span>
|
||||
)}
|
||||
</div>
|
||||
</FieldRow>
|
||||
)
|
||||
})}
|
||||
|
||||
<SurveyQrDialog url={qrTargetUrl} />
|
||||
<SingleMessageSendDialog
|
||||
channel={sendTarget?.channel ?? 'sms'}
|
||||
prjctIdx={prjctIdx}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Input } from '@/components/ui/input'
|
||||
import { DataTable } from '@/components/data-table/DataTable'
|
||||
import type { DataTableColumn, SelectMode } from '@/components/data-table/DataTable.type'
|
||||
import { KriMultiSelect } from '@/components/common/KriAutoComplete'
|
||||
import ListBatchEditDialog, { type BatchEditPayload, type BatchEditResultCodes, type BatchEditRow } from '@/components/dialog/ListBatchEditDialog'
|
||||
import ListBatchEditDialog, { type BatchEditPayload, type BatchEditResultCodes, type BatchEditRow, type BatchEditSurveyResultCodes } from '@/components/dialog/ListBatchEditDialog'
|
||||
import ListFilterDialog, { operatorLabel } from '@/components/dialog/ListFilterDialog'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import { useListSearchQuery, useUpdateListMutation } from '@/query/list'
|
||||
@@ -30,8 +30,9 @@ import {
|
||||
type ListOtherItemFilterCondition,
|
||||
type ListSearchRequest,
|
||||
type ListSearchUiState,
|
||||
type SurveyResultSelections,
|
||||
} from '@/types/list'
|
||||
import { type ResultCode, ResultCodeType } from '@/types/project'
|
||||
import { type ProjectSurvey, type ResultCode, ResultCodeType } from '@/types/project'
|
||||
import {
|
||||
applyListAccessFilter,
|
||||
getLockedListFilterHeaderTypes,
|
||||
@@ -46,6 +47,7 @@ export type ListSearchTableProps = {
|
||||
userId: string
|
||||
userCmpn: string
|
||||
resultCodes: ResultCode[]
|
||||
surveys: ProjectSurvey[]
|
||||
listHeaders: listHeader[]
|
||||
enableBatchEdit?: boolean
|
||||
refreshKey?: number
|
||||
@@ -154,6 +156,7 @@ export function ListSearchTable({
|
||||
userId,
|
||||
userCmpn,
|
||||
resultCodes,
|
||||
surveys,
|
||||
listHeaders,
|
||||
enableBatchEdit = false,
|
||||
refreshKey = 0,
|
||||
@@ -178,12 +181,13 @@ export function ListSearchTable({
|
||||
const [searchText, setSearchText] = useState(initialSearchState?.searchText ?? '')
|
||||
const [searchContactResult, setSearchContactResult] = useState<string[]>(initialSearchState?.searchContactResult ?? [])
|
||||
const [searchInterviewResult, setSearchInterviewResult] = useState<string[]>(initialSearchState?.searchInterviewResult ?? [])
|
||||
const [searchSurveyResult, setSearchSurveyResult] = useState<string[]>(initialSearchState?.searchSurveyResult ?? [])
|
||||
const [surveyResultSelections, setSurveyResultSelections] = useState<SurveyResultSelections>(initialSearchState?.surveyResultSelections ?? {})
|
||||
const [pagination, setPagination] = useState<PaginationState>(initialPagination ?? { pageIndex: 0, pageSize: 25 })
|
||||
const [sorting, setSorting] = useState<SortingState>(initialSearchState?.sorting ?? [])
|
||||
const [filterRows, setFilterRows] = useState<FilterRow[]>(initialSearchState?.filterRows ?? [])
|
||||
const [batchRows, setBatchRows] = useState<BatchEditRow[]>([])
|
||||
const [batchResultCodes, setBatchResultCodes] = useState<BatchEditResultCodes>({})
|
||||
const [batchSurveyResultCodes, setBatchSurveyResultCodes] = useState<BatchEditSurveyResultCodes>({})
|
||||
const [selectedRows, setSelectedRows] = useState<ListTableRow[]>([])
|
||||
|
||||
const updateListMutation = useUpdateListMutation(prjctIdx)
|
||||
@@ -247,8 +251,13 @@ export function ListSearchTable({
|
||||
listFilter.resultCodeMap = {
|
||||
[ResultCodeType.CONTACT]: searchContactResult.map(Number),
|
||||
[ResultCodeType.INTERVIEW]: searchInterviewResult.map(Number),
|
||||
[ResultCodeType.SURVEY]: searchSurveyResult.map(Number),
|
||||
}
|
||||
listFilter.surveyResultConditions = Object.entries(surveyResultSelections)
|
||||
.filter(([, codes]) => codes.length > 0)
|
||||
.map(([prjctSurveyIdx, codes]) => ({
|
||||
prjctSurveyIdx: Number(prjctSurveyIdx),
|
||||
resultCodes: codes.map(Number),
|
||||
}))
|
||||
|
||||
filterRows.forEach((row) => {
|
||||
const header = accessibleFilterHeaderById.get(row.headerId)
|
||||
@@ -320,7 +329,7 @@ export function ListSearchTable({
|
||||
pagination.pageSize,
|
||||
searchContactResult,
|
||||
searchInterviewResult,
|
||||
searchSurveyResult,
|
||||
surveyResultSelections,
|
||||
searchText,
|
||||
sorting,
|
||||
userCmpn,
|
||||
@@ -334,6 +343,12 @@ export function ListSearchTable({
|
||||
[resultCodes],
|
||||
)
|
||||
|
||||
const surveyResultCodeLabel = useCallback(
|
||||
(code: string) =>
|
||||
resultCodes.find((item) => item.resultCdTy === ResultCodeType.SURVEY && String(item.resultCd) === code)?.resultCdLbl ?? code,
|
||||
[resultCodes],
|
||||
)
|
||||
|
||||
// ApplyFilterOption의 "필터 적용 대상만"을 고를 때 보여줄, 사람이 읽을 수 있는 현재 필터 조건 요약.
|
||||
// 실제 서버로 보내는 listSearchRequest와 같은 유효성 조건(잠긴 헤더 제외, 빈 값 제외 등)을 따라간다.
|
||||
const filterSummaryLines = useMemo<string[]>(() => {
|
||||
@@ -347,13 +362,19 @@ export function ListSearchTable({
|
||||
const resultSummaryGroups: { label: string; type: ResultCodeType; values: string[] }[] = [
|
||||
{ label: '컨택 결과', type: ResultCodeType.CONTACT, values: searchContactResult },
|
||||
{ label: '면접 결과', type: ResultCodeType.INTERVIEW, values: searchInterviewResult },
|
||||
{ label: '설문 결과', type: ResultCodeType.SURVEY, values: searchSurveyResult },
|
||||
]
|
||||
resultSummaryGroups.forEach(({ label, type, values }) => {
|
||||
if (values.length === 0) return
|
||||
lines.push(`${label}: ${values.map((value) => resultCodeLabel(type, value)).join(', ')}`)
|
||||
})
|
||||
|
||||
surveys.forEach((survey) => {
|
||||
if (survey.prjctSurveyIdx == null) return
|
||||
const codes = surveyResultSelections[survey.prjctSurveyIdx] ?? []
|
||||
if (codes.length === 0) return
|
||||
lines.push(`${survey.surveyName} 결과: ${codes.map(surveyResultCodeLabel).join(', ')}`)
|
||||
})
|
||||
|
||||
filterRows.forEach((row) => {
|
||||
const header = accessibleFilterHeaderById.get(row.headerId)
|
||||
if (!header || lockedListFilterHeaderTypes.has(header.listHderTy)) return
|
||||
@@ -386,7 +407,9 @@ export function ListSearchTable({
|
||||
resultCodeLabel,
|
||||
searchContactResult,
|
||||
searchInterviewResult,
|
||||
searchSurveyResult,
|
||||
surveys,
|
||||
surveyResultSelections,
|
||||
surveyResultCodeLabel,
|
||||
searchText,
|
||||
])
|
||||
|
||||
@@ -422,8 +445,8 @@ export function ListSearchTable({
|
||||
|
||||
const columns = useMemo<DataTableColumn<ListTableRow, unknown>[]>(() => {
|
||||
if (!listHeaders.length) return []
|
||||
return getListColumns(listHeaders, resultCodes, userRole)
|
||||
}, [listHeaders, resultCodes, userRole])
|
||||
return getListColumns(listHeaders, resultCodes, userRole, surveys)
|
||||
}, [listHeaders, resultCodes, userRole, surveys])
|
||||
|
||||
const viewList = useMemo<ListTableRow[]>(
|
||||
() => (listSearchQuery.data?.content ?? []).map((row) => ({ ...row, ...row.itemList })),
|
||||
@@ -467,13 +490,21 @@ export function ListSearchTable({
|
||||
setPagination((prev) => ({ ...prev, pageIndex: 0 }))
|
||||
}
|
||||
|
||||
const handleBatchConfirm = async ({ rows, resultCodes: resultCodeSelections, target }: BatchEditPayload) => {
|
||||
const handleChangeSurveyResult = (prjctSurveyIdx: number, codes: string[]) => {
|
||||
setSurveyResultSelections((prev) => ({ ...prev, [prjctSurveyIdx]: codes }))
|
||||
}
|
||||
|
||||
const surveyResultCodeOptions = resultCodes.filter((item) => item.resultCdTy === ResultCodeType.SURVEY)
|
||||
|
||||
const handleBatchConfirm = async ({ rows, resultCodes: resultCodeSelections, surveyResultCodes, target }: BatchEditPayload) => {
|
||||
setBatchRows(rows)
|
||||
setBatchResultCodes(resultCodeSelections)
|
||||
setBatchSurveyResultCodes(Object.fromEntries(surveyResultCodes.map((item) => [item.prjctSurveyIdx, item.resultCd])))
|
||||
const updateContents = Object.fromEntries(rows.map((row) => [String(row.headerId), row.value]))
|
||||
await updateListMutation.mutateAsync({
|
||||
updateContents,
|
||||
updateResultCodes: resultCodeSelections,
|
||||
updateSurveyResultCodes: surveyResultCodes,
|
||||
listFilter: buildTargetFilter(target),
|
||||
})
|
||||
await listSearchQuery.refetch()
|
||||
@@ -492,7 +523,7 @@ export function ListSearchTable({
|
||||
searchText,
|
||||
searchContactResult,
|
||||
searchInterviewResult,
|
||||
searchSurveyResult,
|
||||
surveyResultSelections,
|
||||
filterRows,
|
||||
sorting,
|
||||
})
|
||||
@@ -500,7 +531,7 @@ export function ListSearchTable({
|
||||
searchText,
|
||||
searchContactResult,
|
||||
searchInterviewResult,
|
||||
searchSurveyResult,
|
||||
surveyResultSelections,
|
||||
filterRows,
|
||||
sorting,
|
||||
onSearchStateChange,
|
||||
@@ -530,12 +561,12 @@ export function ListSearchTable({
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
placeholder="Search SID"
|
||||
className="h-9 bg-white flex-1 min-w-0"
|
||||
placeholder="SID 검색"
|
||||
className="h-9 bg-white flex-1 min-w-0 max-w-xs"
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(sanitizeSidInput(e.target.value))}
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex-1 min-w-0 max-w-xs">
|
||||
<KriMultiSelect
|
||||
items={resultCodes.filter((item) => item.resultCdTy === ResultCodeType.CONTACT)}
|
||||
value={searchContactResult}
|
||||
@@ -547,7 +578,7 @@ export function ListSearchTable({
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex-1 min-w-0 max-w-xs">
|
||||
<KriMultiSelect
|
||||
items={resultCodes.filter((item) => item.resultCdTy === ResultCodeType.INTERVIEW)}
|
||||
value={searchInterviewResult}
|
||||
@@ -559,23 +590,29 @@ export function ListSearchTable({
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<KriMultiSelect
|
||||
items={resultCodes.filter((item) => item.resultCdTy === ResultCodeType.SURVEY)}
|
||||
value={searchSurveyResult}
|
||||
onChange={setSearchSurveyResult}
|
||||
getValue={(item) => String(item.resultCd)}
|
||||
getLabel={(item) => item.resultCdLbl}
|
||||
placeholder="설문 결과"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
</div>
|
||||
<Button className="text-lg shrink-0" onClick={handleSearchClick}>
|
||||
검색
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{surveys.length > 0 ? (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{surveys
|
||||
.filter((survey) => survey.prjctSurveyIdx != null)
|
||||
.map((survey) => (
|
||||
<div key={survey.prjctSurveyIdx} className="flex-1 min-w-[180px] max-w-xs">
|
||||
<KriMultiSelect
|
||||
items={surveyResultCodeOptions}
|
||||
value={surveyResultSelections[survey.prjctSurveyIdx as number] ?? []}
|
||||
onChange={(value) => handleChangeSurveyResult(survey.prjctSurveyIdx as number, value)}
|
||||
getValue={(item) => String(item.resultCd)}
|
||||
getLabel={(item) => item.resultCdLbl}
|
||||
placeholder={`${survey.surveyName} 결과`}
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="flex items-center gap-2 flex-wrap justify-between">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('listFilterDialog')}>
|
||||
@@ -620,9 +657,11 @@ export function ListSearchTable({
|
||||
<ListBatchEditDialog
|
||||
headerOptions={headerOptions}
|
||||
resultCodes={resultCodes}
|
||||
surveys={surveys}
|
||||
filterSummary={filterSummaryLines}
|
||||
initialRows={batchRows}
|
||||
initialResultCodes={batchResultCodes}
|
||||
initialSurveyResultCodes={batchSurveyResultCodes}
|
||||
onConfirm={handleBatchConfirm}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -20,8 +20,10 @@ import {KriEditor, KriEditorCommand} from "@/components/kri-editor";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import { isBlank } from "@kri/common";
|
||||
import {cn} from "@/lib/utils";
|
||||
import {ProjectMainTemplateUpdateRequest} from "@/types/project";
|
||||
import {ProjectMainTemplateUpdateRequest, ProjectSurvey} from "@/types/project";
|
||||
import type { DataVerification } from "@kri/common";
|
||||
import {COMMON_TEXT_REGEX} from "@/const/validationConst";
|
||||
import {formatKoreanPhoneNumber} from "@/utils/phone";
|
||||
import {
|
||||
useTemplateListQuery,
|
||||
useMainTemplateIdxQuery,
|
||||
@@ -32,6 +34,8 @@ import {
|
||||
} from "@/query/message";
|
||||
import {listHeader} from "@/types/list";
|
||||
import {useListHeaderQuery} from "@/query/list";
|
||||
import {useProjectInfoQuery} from "@/query/project";
|
||||
import {MessageVariableList} from "@/components/message-template/MessageVariableList";
|
||||
|
||||
interface MessageTemplateProps {
|
||||
pageTitle: string;
|
||||
@@ -68,10 +72,12 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
||||
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, chnnlTy, enabled);
|
||||
const templateDetailQuery = useTemplateQuery(selectedTemplateIdx ?? 0, enabled && !!selectedTemplateIdx);
|
||||
const listHeaderQuery = useListHeaderQuery(prjctIdx, enabled)
|
||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled)
|
||||
|
||||
const templateList = useMemo<TemplateSummary[]>(() => templateListQuery.data ?? [], [templateListQuery.data]);
|
||||
const mainTemplateIdx = useMemo<number | null>(() => mainTemplateQuery.data ?? null, [mainTemplateQuery.data]);
|
||||
const listHderList = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data])
|
||||
const surveys = useMemo<ProjectSurvey[]>(() => projectInfoQuery.data?.surveys ?? [], [projectInfoQuery.data?.surveys])
|
||||
|
||||
// Mutations
|
||||
const saveTemplateMutation = useSaveTemplateMutation(chnnlTy, itrntPrjctCd);
|
||||
@@ -155,16 +161,29 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
||||
|
||||
if (isBlank(tpl.itrntPrjctCd)) return fail("itrntPrjctCd", "인트라넷 프로젝트 코드가 없습니다.");
|
||||
if (isBlank(tpl.tmplatNm)) return fail("tmplatNm", "템플릿명을 입력해 주세요.");
|
||||
if (tpl.tmplatNm.length > 32) return fail("tmplatNm", "템플릿명은 32자 이하로 입력해주세요.");
|
||||
if (!COMMON_TEXT_REGEX.test(tpl.tmplatNm)) return fail("tmplatNm", "템플릿명에 허용되지 않는 문자가 포함되어 있습니다.");
|
||||
if (isBlank(tpl.tmplatBody)) return fail("tmplatBody", "본문을 입력해 주세요.");
|
||||
if (isBlank(tpl.sendNm)) return fail("sendNm", "발신자명을 입력해 주세요.");
|
||||
if (tpl.sendNm.length > 32) return fail("sendNm", "발신자명은 32자 이하로 입력해주세요.");
|
||||
if (!COMMON_TEXT_REGEX.test(tpl.sendNm)) return fail("sendNm", "발신자명에 허용되지 않는 문자가 포함되어 있습니다.");
|
||||
|
||||
if (!isBlank(tpl.tmplatTitle)) {
|
||||
if (tpl.tmplatTitle!.length > 128) return fail("tmplatTitle", "제목은 128자 이하로 입력해주세요.");
|
||||
if (!COMMON_TEXT_REGEX.test(tpl.tmplatTitle!)) return fail("tmplatTitle", "제목에 허용되지 않는 문자가 포함되어 있습니다.");
|
||||
}
|
||||
|
||||
if (tpl.tmplatTy === MessageType.EMAIL) {
|
||||
if (isBlank(tpl.tmplatTitle)) return fail("tmplatTitle", "이메일 제목을 입력해 주세요.");
|
||||
if (isBlank(tpl.sendEml)) return fail("sendEml", "발신 이메일을 입력해 주세요.");
|
||||
if (tpl.sendEml.length > 64) return fail("sendEml", "발신 이메일은 64자 이하로 입력해주세요.");
|
||||
if (!COMMON_TEXT_REGEX.test(tpl.sendEml)) return fail("sendEml", "발신 이메일에 허용되지 않는 문자가 포함되어 있습니다.");
|
||||
return ok();
|
||||
}
|
||||
|
||||
if (isBlank(tpl.sendTel)) return fail("sendTel", "발신 전화번호를 입력해 주세요.");
|
||||
if (tpl.sendTel.length > 16) return fail("sendTel", "발신 전화번호는 16자 이하로 입력해주세요.");
|
||||
if (!COMMON_TEXT_REGEX.test(tpl.sendTel)) return fail("sendTel", "발신 전화번호에 허용되지 않는 문자가 포함되어 있습니다.");
|
||||
return ok();
|
||||
};
|
||||
|
||||
@@ -253,7 +272,6 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
||||
alert(method === "put" ? "저장되었습니다." : "수정되었습니다.");
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
alert(method === "put" ? "저장에 실패했습니다." : "수정에 실패했습니다.");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -319,23 +337,6 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
||||
clearLabel="새 테플릿 생성"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{isSms && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-base">타입</Label>
|
||||
<KriSingleSelect
|
||||
items={[...SMS_TYPE_OPTIONS]}
|
||||
value={String(selectedTemplate.tmplatTy || MessageType.SMS)}
|
||||
onChange={(value) => handleChange("tmplatTy", Number(value) as any)}
|
||||
placeholder="템플릿 타입을 선택해 주세요"
|
||||
heightClassName="h-9"
|
||||
widthClassName="w-full"
|
||||
getLabel={(item) => item.label}
|
||||
getValue={(item) => String(item.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="tmplatNm" className="text-base">
|
||||
템플릿 명
|
||||
@@ -358,47 +359,14 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
||||
value={selectedTemplate.tmplatTitle || ""}
|
||||
onChange={(e) => handleChange("tmplatTitle", e.target.value as any)}
|
||||
/>
|
||||
{isSmsTemplate(selectedTemplate) &&
|
||||
<p className="text-sm text-red-600 font-medium">
|
||||
⚠️ 제목이 있으면 본문 길이와 상관없이 LMS로 발송 됩니다.
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center">
|
||||
<Label className="text-base">변수 리스트</Label>
|
||||
</div>
|
||||
|
||||
<div className="border rounded-md overflow-hidden">
|
||||
<div className="bg-blue-100 grid grid-cols-2 border-b">
|
||||
<div className="py-2 px-3 text-center font-medium border-r text-base">
|
||||
리스트 헤더명
|
||||
</div>
|
||||
<div className="py-2 px-3 text-center font-medium text-base">
|
||||
치환 문자
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-h-50 overflow-y-auto">
|
||||
{listHderList.map((h) => {
|
||||
const placeholder = `[\$${h.listHderNm}]`;
|
||||
return (
|
||||
<div
|
||||
key={h.listHderId}
|
||||
className="grid grid-cols-2 border-b last:border-b-0 hover:bg-blue-50 cursor-pointer transition-colors"
|
||||
onPointerDown={(e) => {
|
||||
e.preventDefault();
|
||||
handleVariableClick(placeholder);
|
||||
}}
|
||||
>
|
||||
<div className="py-2 px-3 text-center border-r text-sm">
|
||||
{h.listHderNm}
|
||||
</div>
|
||||
<div className="py-2 px-3 text-center text-sm">
|
||||
{placeholder}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<MessageVariableList listHeaders={listHderList} surveys={surveys} onInsert={handleVariableClick} />
|
||||
|
||||
{selectedTemplate ? (
|
||||
isSmsTemplate(selectedTemplate) ? (
|
||||
@@ -408,8 +376,8 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
||||
</Label>
|
||||
<Input
|
||||
id="sendTel"
|
||||
value={selectedTemplate.sendTel}
|
||||
onChange={(e) => handleChange("sendTel", e.target.value as any)}
|
||||
value={formatKoreanPhoneNumber(selectedTemplate.sendTel)}
|
||||
onChange={(e) => handleChange("sendTel", e.target.value.replace(/\D/g, '') as any)}
|
||||
placeholder="발신 번호를 입력하세요"
|
||||
className="w-full"
|
||||
/>
|
||||
@@ -467,6 +435,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
||||
<div className="mt-6 lg:mt-0 lg:border-l lg:pl-6">
|
||||
<KriEditor
|
||||
mode="sms"
|
||||
label={selectedTemplate.tmplatTy === MessageType.SMS ? "️️* 발송 시 길이에 따라 LMS로 발송 될 수 있음" : undefined}
|
||||
value={(selectedTemplate as TemplateSms).tmplatBody ?? ""}
|
||||
onChange={(html: string) => setTemplateBody(html)}
|
||||
placeholder="문자 내용을 입력해 주세요"
|
||||
|
||||
78
src/components/message-template/MessageVariableList.tsx
Normal file
78
src/components/message-template/MessageVariableList.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
import { Label } from "@/components/ui/label";
|
||||
import type { listHeader } from "@/types/list";
|
||||
import type { ProjectSurvey } from "@/types/project";
|
||||
|
||||
type MessageVariableListProps = {
|
||||
listHeaders: listHeader[];
|
||||
surveys: ProjectSurvey[];
|
||||
onInsert: (value: string) => void;
|
||||
};
|
||||
|
||||
type VariableRowProps = {
|
||||
id: string;
|
||||
name: string;
|
||||
value: string;
|
||||
onInsert: (value: string) => void;
|
||||
};
|
||||
|
||||
const VariableRow = ({ id, name, value, onInsert }: VariableRowProps) => (
|
||||
<div
|
||||
key={id}
|
||||
className="grid cursor-pointer grid-cols-2 border-b transition-colors last:border-b-0 hover:bg-blue-50"
|
||||
onPointerDown={(event) => {
|
||||
event.preventDefault();
|
||||
onInsert(value);
|
||||
}}
|
||||
>
|
||||
<div className="px-3 py-2 text-center text-sm border-r">{name}</div>
|
||||
<div className="min-w-0 break-all px-3 py-2 text-center text-sm" title={value}>
|
||||
{value}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
export const MessageVariableList = ({ listHeaders, surveys, onInsert }: MessageVariableListProps) => {
|
||||
const availableSurveys = surveys.filter((survey) => survey.surveyUrl?.trim());
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center">
|
||||
<Label className="text-base">변수 리스트</Label>
|
||||
</div>
|
||||
|
||||
<div className="overflow-hidden rounded-md border">
|
||||
<div className="grid grid-cols-2 border-b bg-blue-100">
|
||||
<div className="border-r px-3 py-2 text-center text-base font-medium">리스트 헤더명</div>
|
||||
<div className="px-3 py-2 text-center text-base font-medium">치환 문자</div>
|
||||
</div>
|
||||
|
||||
<div className="max-h-50 overflow-y-auto">
|
||||
{listHeaders.map((header) => {
|
||||
const placeholder = `[$${header.listHderNm}]`;
|
||||
return (
|
||||
<VariableRow
|
||||
key={`header-${header.listHderId}`}
|
||||
id={`header-${header.listHderId}`}
|
||||
name={header.listHderNm}
|
||||
value={placeholder}
|
||||
onInsert={onInsert}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{availableSurveys.map((survey) => {
|
||||
const surveyUrl = survey.surveyUrl?.trim() ?? "";
|
||||
return (
|
||||
<VariableRow
|
||||
key={`survey-${survey.prjctSurveyIdx ?? survey.surveyOrder}`}
|
||||
id={`survey-${survey.prjctSurveyIdx ?? survey.surveyOrder}`}
|
||||
name={survey.surveyName}
|
||||
value={surveyUrl}
|
||||
onInsert={onInsert}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -9,7 +9,18 @@ import { CtiConnectionSync } from "./CtiConnectionSync";
|
||||
export function AppProvider({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<JotaiProvider>
|
||||
<QueryProvider>
|
||||
<QueryProvider
|
||||
clientConfig={{
|
||||
defaultOptions: {
|
||||
// 개별 쿼리/뮤테이션에서 meta를 지정하지 않았을 때 적용되는 기본값.
|
||||
// 조회(GET)는 기본적으로 전역 로딩에서 제외하고, 화면을 막아야 하는
|
||||
// 실제 액션인 뮤테이션만 기본적으로 전역 로딩에 포함시킨다.
|
||||
// 전역 로딩이 필요한 조회는 해당 훅에서 meta: { ignoreGlobalLoading: false }로 opt-in한다.
|
||||
queries: { meta: { ignoreGlobalLoading: true } },
|
||||
mutations: { meta: { ignoreGlobalLoading: false } },
|
||||
},
|
||||
}}
|
||||
>
|
||||
<QueryLoadingSync />
|
||||
<CtiConnectionSync />
|
||||
<LoadingOverlayAdapter />
|
||||
|
||||
@@ -2,6 +2,7 @@ import { ColumnDef } from "@tanstack/react-table";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Pencil } from "lucide-react";
|
||||
import type { CmpnInfo } from "@/types/cmpn";
|
||||
import { formatKoreanPhoneNumber } from "@/utils/phone";
|
||||
|
||||
export type CmpnColumnsActions = {
|
||||
onEdit: (cmpnId: string) => void
|
||||
@@ -21,6 +22,7 @@ export const getCmpnColumns = (actions: CmpnColumnsActions): ColumnDef<CmpnInfo>
|
||||
{
|
||||
accessorKey: "cmpnTel",
|
||||
header: "전화번호",
|
||||
cell: ({ row }) => formatKoreanPhoneNumber(row.original.cmpnTel ?? ""),
|
||||
enableSorting: true,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { DataTableColumn } from "@/components/data-table/DataTable.type";
|
||||
import {ListContactResult, listHeader, ListIsUse, ListResultBase, ListSendResult} from "@/types/list";
|
||||
import {ListContactResult, listHeader, ListIsUse, ListResultBase, ListSendResult, SurveyResult} from "@/types/list";
|
||||
import { ListHeaderConst, ListHeaderDefaultConst, ListHeaderDefaultFieldConst } from "@/const/listConst";
|
||||
import { formatKst } from "@kri/common";
|
||||
import { ResultCode, ResultCodeType } from "@/types/project";
|
||||
import { formatKoreanPhoneNumber } from "@/utils/phone";
|
||||
import { ProjectSurvey, ResultCode, ResultCodeType } from "@/types/project";
|
||||
import { isListHeaderVisibleByAccess } from "@/utils/listAccess";
|
||||
|
||||
export type ListTableRow = Record<string, unknown>;
|
||||
@@ -15,117 +16,111 @@ export const LIST_IS_USE_LABEL: Record<ListIsUse, string> = {
|
||||
[ListIsUse.TEST]: "테스트",
|
||||
};
|
||||
|
||||
const getResultColumns = (resultCodeArray: ResultCode[]): DataTableColumn<ListTableRow>[] => {
|
||||
const getResultColumns = (resultCodeArray: ResultCode[], surveys: ProjectSurvey[]): DataTableColumn<ListTableRow>[] => {
|
||||
const labelByTypeCode = new Map<string, string>();
|
||||
resultCodeArray.forEach((item) => {
|
||||
labelByTypeCode.set(`${item.resultCdTy}:${item.resultCd}`, item.resultCdLbl);
|
||||
});
|
||||
|
||||
const getResultLabel = (resultType: ResultCodeType, result?: ListResultBase) => {
|
||||
const formatResult = (
|
||||
result?: ListResultBase,
|
||||
options?: { resultType?: ResultCodeType; showCount?: boolean },
|
||||
) => {
|
||||
const lastResultCd = result?.lastResultCd;
|
||||
if (lastResultCd === undefined) return "";
|
||||
|
||||
return labelByTypeCode.get(`${resultType}:${lastResultCd}`) ?? "";
|
||||
}
|
||||
|
||||
const formatResult = (resultType: ResultCodeType, result?: ListContactResult) => {
|
||||
const lastResultCd = result?.lastResultCd;
|
||||
if (lastResultCd === undefined) return "";
|
||||
|
||||
const label = getResultLabel(resultType, result);
|
||||
const fallbackLabel =
|
||||
options?.resultType !== undefined ? labelByTypeCode.get(`${options.resultType}:${lastResultCd}`) ?? "" : "";
|
||||
const label = result?.lastResultViewLabel || fallbackLabel;
|
||||
const showCount = options?.showCount ?? true;
|
||||
const count = result?.attemptCount ?? 0;
|
||||
const dt = `(${formatKst(result?.lastResultDt ?? "", "dateHourMin")})`;
|
||||
const resultText = `${lastResultCd}. ${label} (${count}회)`;
|
||||
const resultText = showCount ? `${lastResultCd}. ${label} (${count}회)` : `${lastResultCd}. ${label}`;
|
||||
const dt = result?.lastResultDt ? formatKst(result.lastResultDt, "dateHourMin") : "";
|
||||
|
||||
return (
|
||||
<div className="leading-tight">
|
||||
<div>{resultText}</div>
|
||||
<div>{dt}</div>
|
||||
{dt && <div>({dt})</div>}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const formatSendResult = (result?: ListSendResult) => {
|
||||
const label = result?.lastResultLabel ?? "";
|
||||
const dt = `(${formatKst(result?.lastResultDt ?? "", "dateHourMin")})`;
|
||||
const formatSurveyResult = (result?: SurveyResult) => {
|
||||
if (result === undefined) return "";
|
||||
|
||||
const fallbackLabel = labelByTypeCode.get(`${ResultCodeType.SURVEY}:${result.lastResultCd}`) ?? "";
|
||||
const dt = result.lastResultDt ? formatKst(result.lastResultDt, "dateHourMin") : "";
|
||||
|
||||
return (
|
||||
<div className="leading-tight">
|
||||
<div>{label}</div>
|
||||
<div>{dt}</div>
|
||||
</div>
|
||||
<div className="leading-tight">
|
||||
<div>{`${result.lastResultCd}. ${fallbackLabel}`}</div>
|
||||
{dt && <div>({dt})</div>}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const formatSurveyResult = (result?: ListResultBase) => {
|
||||
const lastResultCd = result?.lastResultCd;
|
||||
if (lastResultCd === undefined) return "";
|
||||
|
||||
const label = getResultLabel(ResultCodeType.SURVEY, result);
|
||||
const dt = `(${formatKst(result?.lastResultDt ?? "", "dateHourMin")})`;
|
||||
|
||||
return (
|
||||
<div className="leading-tight">
|
||||
<div>{label}</div>
|
||||
<div>{dt}</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
const columns: DataTableColumn<ListTableRow>[] = [
|
||||
{
|
||||
id: "contactResult",
|
||||
id: "result-contact",
|
||||
header: "컨택 결과",
|
||||
accessorFn: (row) => (row.contactResult as ListContactResult | undefined)?.lastResultCd ?? null,
|
||||
cell: ({ row }) =>
|
||||
formatResult(ResultCodeType.CONTACT, row.original.contactResult as ListContactResult | undefined),
|
||||
enableSorting: false,
|
||||
formatResult(row.original.contactResult as ListContactResult | undefined, { resultType: ResultCodeType.CONTACT }),
|
||||
enableSorting: true,
|
||||
},
|
||||
{
|
||||
id: "mailSendResult",
|
||||
header: "email 발송 결과",
|
||||
cell: ({ row }) =>
|
||||
formatSendResult(row.original.mailSendResult as ListSendResult | undefined),
|
||||
formatResult(row.original.mailSendResult as ListSendResult | undefined),
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
id: "smsSendResult",
|
||||
header: "문자 발송 결과",
|
||||
cell: ({ row }) =>
|
||||
formatSendResult(row.original.smsSendResult as ListSendResult | undefined),
|
||||
formatResult(row.original.smsSendResult as ListSendResult | undefined),
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
id: "interviewResult",
|
||||
id: "result-interview",
|
||||
header: "면접 결과",
|
||||
accessorFn: (row) => (row.interviewResult as ListContactResult | undefined)?.lastResultCd ?? null,
|
||||
cell: ({ row }) =>
|
||||
formatResult(ResultCodeType.INTERVIEW, row.original.interviewResult as ListContactResult | undefined),
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
id: "surveyStatus",
|
||||
header: "설문 진행 상태",
|
||||
cell: ({ row }) =>
|
||||
formatSurveyResult(row.original.surveyResult as ListResultBase | undefined),
|
||||
enableSorting: false,
|
||||
formatResult(row.original.interviewResult as ListContactResult | undefined, { resultType: ResultCodeType.INTERVIEW }),
|
||||
enableSorting: true,
|
||||
},
|
||||
...surveys.map((survey): DataTableColumn<ListTableRow> => ({
|
||||
id: `result-survey-${survey.prjctSurveyIdx}`,
|
||||
header: survey.surveyName,
|
||||
accessorFn: (row) => {
|
||||
const surveyResults = (row.surveyResults as SurveyResult[] | undefined) ?? [];
|
||||
return surveyResults.find((item) => item.prjctSurveyIdx === survey.prjctSurveyIdx)?.lastResultCd ?? null;
|
||||
},
|
||||
cell: ({ row }) => {
|
||||
const surveyResults = (row.original.surveyResults as SurveyResult[] | undefined) ?? [];
|
||||
const result = surveyResults.find((item) => item.prjctSurveyIdx === survey.prjctSurveyIdx);
|
||||
return formatSurveyResult(result);
|
||||
},
|
||||
enableSorting: true,
|
||||
})),
|
||||
];
|
||||
|
||||
const resultColumnOrder = new Map([
|
||||
["contactResult", 0],
|
||||
["interviewResult", 1],
|
||||
["surveyStatus", 2],
|
||||
["result-contact", 0],
|
||||
["result-interview", 1],
|
||||
["mailSendResult", 3],
|
||||
["smsSendResult", 4],
|
||||
]);
|
||||
|
||||
return columns.sort((a, b) => (resultColumnOrder.get(a.id ?? "") ?? 0) - (resultColumnOrder.get(b.id ?? "") ?? 0));
|
||||
return columns.sort((a, b) => (resultColumnOrder.get(a.id ?? "") ?? 2) - (resultColumnOrder.get(b.id ?? "") ?? 2));
|
||||
};
|
||||
|
||||
export const getListColumns = (
|
||||
listHeaders: listHeader[],
|
||||
resultCodeArray: ResultCode[],
|
||||
userRole: number
|
||||
userRole: number,
|
||||
surveys: ProjectSurvey[]
|
||||
): DataTableColumn<ListTableRow>[] => {
|
||||
const visibleHeaders = listHeaders
|
||||
.filter((header) => isListHeaderVisibleByAccess(header, userRole))
|
||||
@@ -139,7 +134,7 @@ export const getListColumns = (
|
||||
id: `assign-${header.listHderTy}`,
|
||||
header: header.listHderNm,
|
||||
accessorFn: (row) => (row.assignList as Record<number, string> | undefined)?.[header.listHderTy] ?? "",
|
||||
enableSorting: false,
|
||||
enableSorting: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -152,6 +147,18 @@ export const getListColumns = (
|
||||
};
|
||||
}
|
||||
|
||||
if(field === ListHeaderDefaultFieldConst[ListHeaderDefaultConst.MEMO]){
|
||||
return {
|
||||
id: field,
|
||||
header: header.listHderNm,
|
||||
accessorFn: (row) => row[field] ?? "",
|
||||
meta: {
|
||||
maxWidth: 200,
|
||||
},
|
||||
enableSorting: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (field) {
|
||||
return {
|
||||
id: field,
|
||||
@@ -161,6 +168,16 @@ export const getListColumns = (
|
||||
};
|
||||
}
|
||||
|
||||
if (header.listHderTy === ListHeaderConst.TEL_NUM) {
|
||||
return {
|
||||
id: String(header.listHderId),
|
||||
header: header.listHderNm,
|
||||
accessorFn: (row) => row[String(header.listHderId)] ?? "",
|
||||
cell: ({ row }) => formatKoreanPhoneNumber(String(row.original[String(header.listHderId)] ?? "")),
|
||||
enableSorting: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (header.listHderTy === ListHeaderConst.FILE) {
|
||||
return {
|
||||
id: `file-${header.listHderId}`,
|
||||
@@ -177,7 +194,7 @@ export const getListColumns = (
|
||||
};
|
||||
});
|
||||
|
||||
const resultColumns = getResultColumns(resultCodeArray);
|
||||
const resultColumns = getResultColumns(resultCodeArray, surveys);
|
||||
|
||||
return [...headerColumns, ...resultColumns];
|
||||
};
|
||||
|
||||
@@ -6,7 +6,10 @@ import {cn} from "@/lib/utils";
|
||||
import {PROJECT_STATUS_CLASS, PROJECT_STATUS_LABEL} from "@/const/projectConst";
|
||||
import {ItrntUserInfo} from "@/types/user";
|
||||
|
||||
export const getProjectColumns = (users:ItrntUserInfo[]): ColumnDef<ProjectInfo>[] => [
|
||||
export const getProjectColumns = (
|
||||
users:ItrntUserInfo[],
|
||||
groupCodeLabelMap: Map<string, string> = new Map(),
|
||||
): ColumnDef<ProjectInfo>[] => [
|
||||
{
|
||||
accessorKey: "prjctIdx",
|
||||
header: "No",
|
||||
@@ -16,11 +19,17 @@ export const getProjectColumns = (users:ItrntUserInfo[]): ColumnDef<ProjectInfo>
|
||||
accessorKey: "prjctCd",
|
||||
header: "프로젝트 코드",
|
||||
enableSorting: true,
|
||||
meta: {
|
||||
maxWidth: 180
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "prjctName",
|
||||
header: "프로젝트 명",
|
||||
enableSorting: true,
|
||||
meta: {
|
||||
maxWidth: 1000
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "prjctStatus",
|
||||
@@ -36,6 +45,9 @@ export const getProjectColumns = (users:ItrntUserInfo[]): ColumnDef<ProjectInfo>
|
||||
accessorKey: "ownerDept",
|
||||
header: "담당 그룹",
|
||||
enableSorting: true,
|
||||
cell: ({row}) => (
|
||||
groupCodeLabelMap.get(row.original.ownerDept) ?? row.original.ownerDept
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "ownerFw",
|
||||
|
||||
@@ -56,6 +56,9 @@ export const getUserColumns = (
|
||||
accessorKey: "memo",
|
||||
header: "메모",
|
||||
enableSorting: false,
|
||||
meta: {
|
||||
maxWidth: 180,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
|
||||
@@ -2,9 +2,10 @@ import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
function Input({ className, type, ref, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
ref={ref}
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {ProjectStatus, ResultCodeType, SurveyType} from "@/types/project";
|
||||
|
||||
// 설문 카드는 항상 실제 타입(KON/KIWI/외부)을 가져야 하므로 "없음"은 선택지에서 제외한다.
|
||||
export const SURVEY_TYPE_ORDER = [
|
||||
SurveyType.NONE,
|
||||
SurveyType.KON,
|
||||
SurveyType.KIWI,
|
||||
SurveyType.EXTERNAL,
|
||||
@@ -15,7 +15,6 @@ export const SURVEY_TYPE_LABEL = {
|
||||
} as const satisfies Record<SurveyType, string>;
|
||||
|
||||
export const SURVEY_TYPE_OPTIONS = [
|
||||
{ value: SurveyType.NONE, label: SURVEY_TYPE_LABEL[SurveyType.NONE] },
|
||||
{ value: SurveyType.KON, label: SURVEY_TYPE_LABEL[SurveyType.KON] },
|
||||
{ value: SurveyType.KIWI, label: SURVEY_TYPE_LABEL[SurveyType.KIWI] },
|
||||
{ value: SurveyType.EXTERNAL, label: SURVEY_TYPE_LABEL[SurveyType.EXTERNAL] },
|
||||
@@ -58,7 +57,6 @@ export const RESULT_CODE_TYPE_OPTIONS = [
|
||||
{ value: ResultCodeType.SURVEY, label: RESULT_CODE_TYPE_LABEL[ResultCodeType.SURVEY] },
|
||||
] as const;
|
||||
|
||||
export const PROJECT_NAME_REGEX= /^[^\u0000-\u001F\u007F]+$/
|
||||
export const PROJECT_SEARCH_COUNT = 20
|
||||
|
||||
// 결과 코드 값 자체가 시스템 동작을 결정하는 약속된(고정) 코드들
|
||||
|
||||
@@ -3,8 +3,5 @@ export const FW_USER_ROLE_GROUP = 9
|
||||
export const CONTACT_INTERVIEWER_ROLE = 9002
|
||||
export const FIELD_INTERVIEWER_ROLE = 9003
|
||||
|
||||
export const USER_NAME_REGEX = /^[가-힣A-Za-z][가-힣A-Za-z0-9_ ()]*$/
|
||||
export const DEFAULT_COMPANY_NAME = 'KRI'
|
||||
|
||||
export const FW_TEAM = "S101"
|
||||
export const QC_TEAM = "S201"
|
||||
|
||||
17
src/const/validationConst.ts
Normal file
17
src/const/validationConst.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
// 여러 화면에 흩어져 있던 검증용 정규식을 한 곳에서 관리한다.
|
||||
// 신규 정규식이 필요하면 여기에 추가하고, src/utils/validation.ts의 validateValue와 함께 사용한다.
|
||||
|
||||
// 프로젝트명 등 일반 텍스트 입력에 공통으로 쓰는 화이트리스트.
|
||||
// 한글/영문/숫자/공백 + 지정된 특수문자만 허용하고,
|
||||
// 그 외 문자(이모지, 다른 언어 문자, 제어문자 등)는 전부 거부한다.
|
||||
export const COMMON_TEXT_REGEX = /^[가-힣A-Za-z0-9 !@#$%^&*()_+\-={}\[\]:;"'<>,.?/·~]+$/
|
||||
|
||||
// 한글/영문으로 시작하고, 한글/영문/숫자/언더스코어/공백/괄호만 허용
|
||||
export const USER_NAME_REGEX = /^[가-힣A-Za-z][가-힣A-Za-z0-9_ ()]*$/
|
||||
|
||||
// 비밀번호에 허용되는 특수문자 안내 텍스트
|
||||
export const ALLOWED_PW_SPECIALS_TEXT = `~ ! @ # $ % ^ & * ( ) _ + - = { } [ ] : ; " ' < > , . ? /`
|
||||
// 비밀번호에 허용된 문자만 사용했는지
|
||||
export const ONLY_ALLOWED_PW_REGEX = /^[A-Za-z\d~!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]+$/
|
||||
// 영문 1개 이상 + 숫자 1개 이상 포함, 8~20자, 허용된 문자만 사용
|
||||
export const KRI_PW_REGEX = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]{8,20}$/
|
||||
@@ -1,8 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { useCallback, useSyncExternalStore } from "react";
|
||||
import { ctiClient } from "@/lib/cti/ctiClient";
|
||||
|
||||
export function useCtiLastCallHistId() {
|
||||
return useSyncExternalStore(ctiClient.subscribe, ctiClient.getLastCallHistId, () => null);
|
||||
export function useCtiLastCallHistId(prjctIdx: number, sid: number) {
|
||||
const getSnapshot = useCallback(
|
||||
() => ctiClient.getLastCallHistIdFor(prjctIdx, sid),
|
||||
[prjctIdx, sid],
|
||||
);
|
||||
return useSyncExternalStore(ctiClient.subscribe, getSnapshot, () => null);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { clientEnv } from "@/lib/env.client";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import { CTI_AGENT_GROUP, CTI_AGENT_STATUS } from "@/const/ctiConst";
|
||||
import type { ListCallHist, ListCallHistRequest } from "@/types/list";
|
||||
import type { ListCallHist, ListCallHistRequest, ListCallHistSession } from "@/types/list";
|
||||
import { getLocalStorage, removeLocalStorage, setLocalStorage } from "@/store/storage/secure-storage";
|
||||
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||
|
||||
// TEMP_CTI_LOG: 배포 후 CTI 연동 오류를 콘솔에서 바로 확인하기 위한 임시 로그.
|
||||
// 안정화되면 "TEMP_CTI_LOG"로 검색해서 이 파일의 관련 로그를 전부 제거할 것.
|
||||
@@ -29,6 +31,20 @@ type CtiCallContext = {
|
||||
listHderId: number;
|
||||
};
|
||||
|
||||
type PersistedCtiState = {
|
||||
version: 1;
|
||||
agentLoginId: string;
|
||||
agentStatus: string | null;
|
||||
currentCallContext: CtiCallContext | null;
|
||||
lastCallContext: CtiCallContext | null;
|
||||
agentSessionId: string | null;
|
||||
lastCallHistId: number | null;
|
||||
updatedAt: number;
|
||||
};
|
||||
|
||||
const CTI_STATE_VERSION = 1;
|
||||
const CTI_STATE_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
let socket: WebSocket | null = null;
|
||||
let connectionState: CtiConnectionState = "idle";
|
||||
let currentAgentLoginId: string | null = null;
|
||||
@@ -36,6 +52,8 @@ let currentConnectionKey: string | null = null;
|
||||
let currentLoginParams: CtiLoginParams | null = null;
|
||||
let agentStatus: string | null = null;
|
||||
let currentCallContext: CtiCallContext | null = null;
|
||||
let lastCallContext: CtiCallContext | null = null;
|
||||
let currentAgentSessionId: string | null = null;
|
||||
let lastCallHistId: number | null = null;
|
||||
|
||||
const listeners = new Set<() => void>();
|
||||
@@ -44,6 +62,103 @@ const notify = () => {
|
||||
listeners.forEach((listener) => listener());
|
||||
};
|
||||
|
||||
const isCallContext = (value: unknown): value is CtiCallContext => {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const context = value as Partial<CtiCallContext>;
|
||||
return (
|
||||
typeof context.prjctIdx === "number" &&
|
||||
Number.isFinite(context.prjctIdx) &&
|
||||
typeof context.sid === "number" &&
|
||||
Number.isFinite(context.sid) &&
|
||||
typeof context.listHderId === "number" &&
|
||||
Number.isFinite(context.listHderId)
|
||||
);
|
||||
};
|
||||
|
||||
const isPersistedCtiState = (value: unknown): value is PersistedCtiState => {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const state = value as Partial<PersistedCtiState>;
|
||||
return (
|
||||
state.version === CTI_STATE_VERSION &&
|
||||
typeof state.agentLoginId === "string" &&
|
||||
(state.agentStatus === null || typeof state.agentStatus === "string") &&
|
||||
(state.currentCallContext === null || isCallContext(state.currentCallContext)) &&
|
||||
(state.lastCallContext === null || isCallContext(state.lastCallContext)) &&
|
||||
(state.agentSessionId === null || typeof state.agentSessionId === "string") &&
|
||||
(state.lastCallHistId === null || typeof state.lastCallHistId === "number") &&
|
||||
typeof state.updatedAt === "number"
|
||||
);
|
||||
};
|
||||
|
||||
const persistCtiState = () => {
|
||||
if (!currentAgentLoginId) return;
|
||||
setLocalStorage(StorageKeys.CtiState, {
|
||||
version: CTI_STATE_VERSION,
|
||||
agentLoginId: currentAgentLoginId,
|
||||
agentStatus,
|
||||
currentCallContext,
|
||||
lastCallContext,
|
||||
agentSessionId: currentAgentSessionId,
|
||||
lastCallHistId,
|
||||
updatedAt: Date.now(),
|
||||
} satisfies PersistedCtiState);
|
||||
};
|
||||
|
||||
const restoreCtiState = (agentLoginId: string) => {
|
||||
const stored = getLocalStorage(StorageKeys.CtiState);
|
||||
if (
|
||||
!isPersistedCtiState(stored) ||
|
||||
stored.agentLoginId !== agentLoginId ||
|
||||
Date.now() - stored.updatedAt > CTI_STATE_TTL_MS
|
||||
) {
|
||||
if (stored !== null) removeLocalStorage(StorageKeys.CtiState);
|
||||
return false;
|
||||
}
|
||||
|
||||
agentStatus = stored.agentStatus;
|
||||
currentCallContext = stored.currentCallContext;
|
||||
lastCallContext = stored.lastCallContext;
|
||||
currentAgentSessionId = stored.agentSessionId;
|
||||
lastCallHistId = stored.lastCallHistId;
|
||||
notify();
|
||||
return true;
|
||||
};
|
||||
|
||||
const recoverLastCallHistId = async (agentLoginId: string) => {
|
||||
const agentSessionId = currentAgentSessionId;
|
||||
const callContext = currentCallContext ?? lastCallContext;
|
||||
if (!agentSessionId || lastCallHistId !== null || !callContext) return;
|
||||
|
||||
try {
|
||||
const result = await nextApi.get<ListCallHistSession>(
|
||||
`/list-call-hist/session/${encodeURIComponent(agentSessionId)}`,
|
||||
);
|
||||
|
||||
const isSameCall =
|
||||
currentAgentLoginId === agentLoginId &&
|
||||
currentAgentSessionId === agentSessionId &&
|
||||
result.agentSessionId === agentSessionId &&
|
||||
result.prjctIdx === callContext.prjctIdx &&
|
||||
result.sid === callContext.sid &&
|
||||
result.listHderId === callContext.listHderId;
|
||||
|
||||
if (!isSameCall) {
|
||||
console.warn("[CTI][TEMP_LOG] recovered call history does not match persisted context", {
|
||||
agentSessionId,
|
||||
callContext,
|
||||
result,
|
||||
}); // TEMP_CTI_LOG
|
||||
return;
|
||||
}
|
||||
|
||||
lastCallContext = callContext;
|
||||
setLastCallHistId(result.listCallHistIdx);
|
||||
console.log("[CTI][TEMP_LOG] recovered listCallHistIdx ->", result.listCallHistIdx); // TEMP_CTI_LOG
|
||||
} catch (error) {
|
||||
console.warn("[CTI][TEMP_LOG] failed to recover call history", { agentSessionId, error }); // TEMP_CTI_LOG
|
||||
}
|
||||
};
|
||||
|
||||
const setConnectionState = (next: CtiConnectionState) => {
|
||||
connectionState = next;
|
||||
notify();
|
||||
@@ -51,11 +166,13 @@ const setConnectionState = (next: CtiConnectionState) => {
|
||||
|
||||
const setAgentStatus = (next: string | null) => {
|
||||
agentStatus = next;
|
||||
persistCtiState();
|
||||
notify();
|
||||
};
|
||||
|
||||
const setLastCallHistId = (next: number | null) => {
|
||||
lastCallHistId = next;
|
||||
persistCtiState();
|
||||
notify();
|
||||
};
|
||||
|
||||
@@ -68,7 +185,8 @@ const saveCallHistory = (parsed: Record<string, unknown>, options: { clearContex
|
||||
return;
|
||||
}
|
||||
|
||||
const { prjctIdx, sid, listHderId } = currentCallContext;
|
||||
const callContext = currentCallContext;
|
||||
const { prjctIdx, sid, listHderId } = callContext;
|
||||
const startTime = typeof parsed.StartTime === "string" ? parsed.StartTime : "";
|
||||
|
||||
const body: ListCallHistRequest = {
|
||||
@@ -87,20 +205,37 @@ const saveCallHistory = (parsed: Record<string, unknown>, options: { clearContex
|
||||
recordFileName: String(parsed.RecordFileName ?? ""),
|
||||
};
|
||||
|
||||
currentAgentSessionId = body.agentSessionId || currentAgentSessionId;
|
||||
persistCtiState();
|
||||
|
||||
if (
|
||||
options.clearContextAfter &&
|
||||
body.totalTime <= 0 &&
|
||||
body.talkTime <= 0 &&
|
||||
body.recordFileName.trim() === ""
|
||||
) {
|
||||
console.warn(
|
||||
"[CTI][TEMP_LOG] CallClosed has no backend endDt marker (totalTime, talkTime, recordFileName)",
|
||||
parsed,
|
||||
); // TEMP_CTI_LOG
|
||||
}
|
||||
|
||||
console.log("[CTI][TEMP_LOG] saving call history", { prjctIdx, sid, body }); // TEMP_CTI_LOG
|
||||
nextApi
|
||||
.put<ListCallHist>(`/list-call-hist/${prjctIdx}/${sid}`, body)
|
||||
.then((result) => {
|
||||
console.log("[CTI][TEMP_LOG] call history saved, listCallHistIdx =", result?.listCallHistIdx); // TEMP_CTI_LOG
|
||||
lastCallContext = callContext;
|
||||
setLastCallHistId(result?.listCallHistIdx ?? null);
|
||||
if (options.clearContextAfter && currentCallContext === callContext) {
|
||||
currentCallContext = null;
|
||||
persistCtiState();
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("[CTI][TEMP_LOG] failed to save call history", error); // TEMP_CTI_LOG
|
||||
});
|
||||
|
||||
if (options.clearContextAfter) {
|
||||
currentCallContext = null;
|
||||
}
|
||||
};
|
||||
|
||||
// WS 서버 -> 클라이언트로 오는 메시지는 ZCommand가 기준값이다.
|
||||
@@ -125,11 +260,13 @@ const handleIncomingMessage = (raw: unknown) => {
|
||||
}
|
||||
case "StartSessionRecord": {
|
||||
console.log("[CTI][TEMP_LOG] StartSessionRecord ->", parsed); // TEMP_CTI_LOG
|
||||
setAgentStatus("2");
|
||||
saveCallHistory(parsed, { clearContextAfter: false });
|
||||
break;
|
||||
}
|
||||
case "CallClosed": {
|
||||
console.log("[CTI][TEMP_LOG] CallClosed ->", parsed); // TEMP_CTI_LOG
|
||||
setAgentStatus(null);
|
||||
saveCallHistory(parsed, { clearContextAfter: true });
|
||||
break;
|
||||
}
|
||||
@@ -163,11 +300,11 @@ const teardownSocket = () => {
|
||||
socket = null;
|
||||
}
|
||||
setConnectionState("idle");
|
||||
setAgentStatus(null);
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
console.log("[CTI][TEMP_LOG] logout called, currentAgentLoginId =", currentAgentLoginId, "connectionState =", connectionState); // TEMP_CTI_LOG
|
||||
const shouldClearPersistedState = currentAgentLoginId !== null;
|
||||
if (currentAgentLoginId && connectionState === "open") {
|
||||
send({ ZCommand: "Logout", AgentLoginID: currentAgentLoginId });
|
||||
}
|
||||
@@ -176,7 +313,11 @@ const logout = () => {
|
||||
currentConnectionKey = null;
|
||||
currentLoginParams = null;
|
||||
currentCallContext = null;
|
||||
lastCallContext = null;
|
||||
currentAgentSessionId = null;
|
||||
setAgentStatus(null);
|
||||
setLastCallHistId(null);
|
||||
if (shouldClearPersistedState) removeLocalStorage(StorageKeys.CtiState);
|
||||
};
|
||||
|
||||
const connectAndLogin = (params: CtiLoginParams) => {
|
||||
@@ -203,6 +344,8 @@ const connectAndLogin = (params: CtiLoginParams) => {
|
||||
currentAgentLoginId = params.agentLoginId;
|
||||
currentConnectionKey = key;
|
||||
currentLoginParams = params;
|
||||
const restored = restoreCtiState(params.agentLoginId);
|
||||
if (restored) void recoverLastCallHistId(params.agentLoginId);
|
||||
setConnectionState("connecting");
|
||||
|
||||
console.log("[CTI][TEMP_LOG] opening websocket ->", clientEnv.CTI_WS_URL); // TEMP_CTI_LOG
|
||||
@@ -252,10 +395,14 @@ export const ctiClient = {
|
||||
getConnectionState: () => connectionState,
|
||||
getAgentStatus: () => agentStatus,
|
||||
getLastCallHistId: () => lastCallHistId,
|
||||
getLastCallHistIdFor: (prjctIdx: number, sid: number) =>
|
||||
lastCallContext?.prjctIdx === prjctIdx && lastCallContext.sid === sid ? lastCallHistId : null,
|
||||
makeCall: (params: CtiMakeCallParams) => {
|
||||
if (!currentAgentLoginId || !currentLoginParams) return;
|
||||
console.log("[CTI][TEMP_LOG] makeCall", params); // TEMP_CTI_LOG
|
||||
currentCallContext = { prjctIdx: params.prjctIdx, sid: params.sid, listHderId: params.listHderId };
|
||||
lastCallContext = null;
|
||||
currentAgentSessionId = null;
|
||||
setLastCallHistId(null); // 새 통화 시작, 이전 통화의 listCallHistIdx는 더 이상 유효하지 않음
|
||||
send({
|
||||
ZCommand: "MakeCall",
|
||||
@@ -265,8 +412,9 @@ export const ctiClient = {
|
||||
});
|
||||
},
|
||||
hangup: requireAgent((agentLoginId) => {
|
||||
// CTI_HANGUP_PENDING_VENDOR: 외주사와 ZCommand/동작 확인 후 UI 활성화 예정.
|
||||
console.log("[CTI][TEMP_LOG] hangup"); // TEMP_CTI_LOG
|
||||
send({ ZCommand: "HangUp", AgentLoginID: agentLoginId });
|
||||
send({ ZCommand: "Hangup", AgentLoginID: agentLoginId });
|
||||
}),
|
||||
setReady: requireAgent((agentLoginId) => {
|
||||
console.log("[CTI][TEMP_LOG] setReady"); // TEMP_CTI_LOG
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
import {keepPreviousData, useQuery} from "@tanstack/react-query";
|
||||
import {qk} from "@/query/key/keys";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {ItrntUserInfo} from "@/types/user";
|
||||
import {CallerTelNumInfo, IntranetProjectSearchResponse, KonKiwiProjectInfo} from "@/types/project";
|
||||
import {GroupCodeInfo, ItrntUserInfo} from "@/types/user";
|
||||
import {CallerTelNumInfo, IntranetProjectSearchResponse} from "@/types/project";
|
||||
|
||||
export function useIntranetProjectListQuery(keyword: string, enabled: boolean) {
|
||||
const kw = keyword.trim();
|
||||
@@ -43,4 +43,13 @@ export function useCallerTelNumListQuery(enabled: boolean) {
|
||||
enabled,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useGroupCodeListQuery(enabled: boolean = true) {
|
||||
return useQuery({
|
||||
queryKey: qk.groupCodeList(),
|
||||
queryFn: () => nextApi.get<GroupCodeInfo[]>("/intranet/group-code-list"),
|
||||
enabled,
|
||||
staleTime: 10 * 60_000,
|
||||
});
|
||||
}
|
||||
@@ -47,6 +47,7 @@ export const qk = {
|
||||
intranetProjectList: (keyword: string) => ["intranet", "project-list", keyword] as const,
|
||||
intranetUsers: () => ["intranet", "user-list"] as const,
|
||||
callerTelNumList: () => ["intranet", "caller-tel-num"] as const,
|
||||
groupCodeList: () => ["intranet", "group-code-list"] as const,
|
||||
/********** 인트라넷 관련 **********/
|
||||
|
||||
/********** 리스트 관련 **********/
|
||||
|
||||
@@ -32,7 +32,7 @@ export function useListHeaderQuery(prjctIdx: number, enabled: boolean) {
|
||||
staleTime: 0, // 항상 오래된 데이터 취급
|
||||
refetchOnMount: "always", // 컴포넌트 다시 붙을 때마다
|
||||
placeholderData: keepPreviousData,
|
||||
meta: { ignoreGlobalLoading: true },
|
||||
meta: { ignoreGlobalLoading: false },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -50,8 +50,8 @@ const serializeListSearchRequest = (request: ListSearchRequest) => ({
|
||||
resultCodeMap: request.listFilter.resultCodeMap ?? {
|
||||
[ResultCodeType.CONTACT]: [],
|
||||
[ResultCodeType.INTERVIEW]: [],
|
||||
[ResultCodeType.SURVEY]: [],
|
||||
},
|
||||
surveyResultConditions: request.listFilter.surveyResultConditions ?? [],
|
||||
memoConditions: request.listFilter.memoConditions ?? [],
|
||||
otherItemConditions: request.listFilter.otherItemConditions ?? [],
|
||||
},
|
||||
@@ -72,7 +72,7 @@ export function useListSearchQuery(prjctIdx: number, request: ListSearchRequest,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
placeholderData: keepPreviousData,
|
||||
meta: { ignoreGlobalLoading: true },
|
||||
meta: { ignoreGlobalLoading: false },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ export function useListDetailQuery(prjctIdx: number, sid: string, enabled: boole
|
||||
refetchOnMount: "always",
|
||||
// 조사 시작으로 새 창이 뜬 뒤 응답을 마치고 이 탭으로 돌아왔을 때 최신 상태(설문 응답 등)를 바로 보여주기 위함.
|
||||
refetchOnWindowFocus: true,
|
||||
meta: { ignoreGlobalLoading: true },
|
||||
meta: { ignoreGlobalLoading: false },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -162,6 +162,15 @@ export function useUploadListItemFileMutation(prjctIdx: number, sid: string) {
|
||||
});
|
||||
}
|
||||
|
||||
export function useDownloadListItemFileByHeaderMutation(prjctIdx: number, sid: string) {
|
||||
return useMutation({
|
||||
mutationFn: (listHderId: number) =>
|
||||
nextApi.get<ArrayBuffer>(`/list/item-file-download/${prjctIdx}/${sid}/${listHderId}`, {
|
||||
expectBinary: true,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export function useDownloadListExcelTemplateMutation() {
|
||||
return useMutation({
|
||||
mutationFn: (prjctIdx: number) =>
|
||||
|
||||
@@ -238,8 +238,6 @@ export function useDeleteProjectMutation(prjctIdx: number) {
|
||||
* 시나리오 이미지 업로드 (엔드포인트 spelling은 너 서버 기준으로)
|
||||
*/
|
||||
export function useUploadScenarioImageMutation(prjctIdx: number, prjctCd: string) {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (file: File): Promise<string> => {
|
||||
const formData = new FormData();
|
||||
@@ -248,9 +246,7 @@ export function useUploadScenarioImageMutation(prjctIdx: number, prjctCd: string
|
||||
// 서버가 업로드된 이미지 URL을 문자열로 반환한다는 전제
|
||||
return await nextApi.postForm<string>(`/project/senario-image/${prjctCd}`, formData);
|
||||
},
|
||||
onSuccess: () => {
|
||||
// 업로드 결과가 projectInfo에 반영된다면 해당 프로젝트만 갱신
|
||||
qc.invalidateQueries({ queryKey: qk.projectInfo(prjctIdx) });
|
||||
},
|
||||
// 업로드는 URL만 돌려받는 동작이라 projectInfo를 실제로 바꾸지 않는다.
|
||||
// 여기서 invalidate하면 편집 중(저장 전) projectInfo refetch가 발생해 미저장 폼 값을 덮어쓴다.
|
||||
});
|
||||
}
|
||||
|
||||
@@ -70,6 +70,7 @@ export function useUpsertUserMutation() {
|
||||
},
|
||||
onSuccess: (_res, v) => {
|
||||
qc.invalidateQueries({ queryKey: qk.users() });
|
||||
qc.invalidateQueries({ queryKey: qk.fieldworkUsers() });
|
||||
|
||||
const userId = (v.data as any)?.userId;
|
||||
if (userId) {
|
||||
@@ -83,7 +84,10 @@ export function useDeleteUserMutation() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) => nextApi.del<void>(`/user/${encodeURIComponent(userId)}`),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: qk.users() }),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: qk.users() });
|
||||
qc.invalidateQueries({ queryKey: qk.fieldworkUsers() });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -99,6 +103,7 @@ export function useUploadUsersExcelMutation() {
|
||||
onSuccess: (res) => {
|
||||
if (!res.hasErrorFile) {
|
||||
qc.invalidateQueries({ queryKey: qk.users() });
|
||||
qc.invalidateQueries({ queryKey: qk.fieldworkUsers() });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||
import { createPersistentAtom } from "@kri/common/jotai";
|
||||
import { sessionJsonStorage } from "@/store/storage/secure-storage";
|
||||
import {SurveyType} from "@/types/project";
|
||||
|
||||
export type SelectedProject = {
|
||||
prjctIdx: number;
|
||||
@@ -12,7 +11,6 @@ export type SelectedProject = {
|
||||
itrntPrjctCd: string;
|
||||
ownerDept: string;
|
||||
ownerFw: string;
|
||||
surveyTy: SurveyType;
|
||||
ff: boolean;
|
||||
};
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ export const StorageKeys = {
|
||||
SelectedProject: "kri:selectedProject",
|
||||
ItrntUserList:"kri:itrntUserList",
|
||||
LastListVisit: "kri:lastListVisit",
|
||||
CtiState: "kri:ctiState",
|
||||
//SidebarCollapsed: "kri:sidebarCollapsed",
|
||||
// 필요하면 여기 계속 추가
|
||||
} as const;
|
||||
@@ -12,6 +13,7 @@ export const StorageType: Record<StorageKey, "local" | "session"> = {
|
||||
[StorageKeys.SelectedProject]: "session",
|
||||
[StorageKeys.ItrntUserList]: "session",
|
||||
[StorageKeys.LastListVisit]: "session",
|
||||
[StorageKeys.CtiState]: "local",
|
||||
};
|
||||
|
||||
export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys];
|
||||
export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys];
|
||||
|
||||
@@ -20,7 +20,7 @@ export type ExternalAction = keyof typeof EXTERNAL_ACTION_CODE_BY_SLUG;
|
||||
export type ExternalEventMeta = {
|
||||
entryType: ExternalEntryTypeCode;
|
||||
action: ExternalActionCode;
|
||||
pid: string;
|
||||
psidx: string;
|
||||
sid: string;
|
||||
remoteAddr: string | null;
|
||||
uri: string;
|
||||
@@ -34,7 +34,7 @@ export type ExternalEventMeta = {
|
||||
|
||||
export type ExternalEventBody = {
|
||||
action: ExternalActionCode;
|
||||
prjctIdx: number;
|
||||
prjctSurveyIdx: number;
|
||||
sid: number;
|
||||
meta: ExternalEventMeta;
|
||||
};
|
||||
|
||||
@@ -115,13 +115,19 @@ export type listHeader = {
|
||||
filterContents?: string[];
|
||||
};
|
||||
|
||||
export type SurveyResultCondition = {
|
||||
prjctSurveyIdx: number;
|
||||
resultCodes: number[];
|
||||
};
|
||||
|
||||
export type ListFilter = {
|
||||
sidSet: string[];
|
||||
listUseSet: ListIsUse[];
|
||||
listUseConditions: ListFilterCondition[];
|
||||
assignUserMap: Record<ListHeaderAssignType, string[]>;
|
||||
assignConditions: ListAssignFilterCondition[];
|
||||
resultCodeMap: Record<ResultCodeType, number[]>;
|
||||
resultCodeMap: Record<Exclude<ResultCodeType, ResultCodeType.SURVEY>, number[]>;
|
||||
surveyResultConditions: SurveyResultCondition[];
|
||||
memoConditions: ListFilterCondition[];
|
||||
otherItemConditions: ListOtherItemFilterCondition[];
|
||||
};
|
||||
@@ -139,8 +145,8 @@ export const createEmptyListFilter = (): ListFilter => ({
|
||||
resultCodeMap: {
|
||||
[ResultCodeType.CONTACT]: [],
|
||||
[ResultCodeType.INTERVIEW]: [],
|
||||
[ResultCodeType.SURVEY]: [],
|
||||
},
|
||||
surveyResultConditions: [],
|
||||
memoConditions: [],
|
||||
otherItemConditions: [],
|
||||
});
|
||||
@@ -148,11 +154,14 @@ export const createEmptyListFilter = (): ListFilter => ({
|
||||
// ListSearchTable의 검색/필터 UI 상태 중, 페이지를 떠났다가 돌아왔을 때 "같은 목록·같은 순서"를
|
||||
// 재현하기 위해 함께 기억해야 하는 부분. pageIndex만 기억하면 필터가 없어져 목록 순서가 달라져서
|
||||
// 엉뚱한 페이지로 안내하게 된다(예: "SID 30~40" 필터를 걸면 SID 30이 1페이지지만, 필터 없이는 2페이지일 수 있음).
|
||||
// 설문별 결과 필터 선택값. key는 prjctSurveyIdx, value는 선택된 결과 코드(문자열) 목록.
|
||||
export type SurveyResultSelections = Record<number, string[]>;
|
||||
|
||||
export type ListSearchUiState = {
|
||||
searchText: string;
|
||||
searchContactResult: string[];
|
||||
searchInterviewResult: string[];
|
||||
searchSurveyResult: string[];
|
||||
surveyResultSelections: SurveyResultSelections;
|
||||
filterRows: FilterRow[];
|
||||
sorting: { id: string; desc: boolean }[];
|
||||
};
|
||||
@@ -193,7 +202,8 @@ export type ListUploadHistory = {
|
||||
|
||||
export type ListUpdateRequest = {
|
||||
updateContents: Record<string, string>;
|
||||
updateResultCodes?: Partial<Record<ResultCodeType, number>>;
|
||||
updateResultCodes?: Partial<Record<Exclude<ResultCodeType, ResultCodeType.SURVEY>, number>>;
|
||||
updateSurveyResultCodes?: { prjctSurveyIdx: number; resultCd: number }[];
|
||||
listFilter: ListFilter;
|
||||
};
|
||||
|
||||
@@ -275,6 +285,15 @@ export type ListCallHist = ListCallHistRequest & {
|
||||
regDt: string;
|
||||
};
|
||||
|
||||
export type ListCallHistSession = {
|
||||
listCallHistIdx: number;
|
||||
agentSessionId: string;
|
||||
destSessionId: string;
|
||||
prjctIdx: number;
|
||||
sid: number;
|
||||
listHderId: number;
|
||||
};
|
||||
|
||||
export type ListReserveRequest = {
|
||||
prjctIdx: number;
|
||||
sid: number;
|
||||
@@ -311,18 +330,26 @@ export type ListEventHistDownloadRequest = {
|
||||
export type ListResultBase = {
|
||||
lastResultCd: number;
|
||||
lastResultDt: string;
|
||||
lastResultViewLabel: string;
|
||||
attemptCount: number;
|
||||
};
|
||||
|
||||
export type ListSendResult = ListResultBase & {
|
||||
lastResultLabel: string;
|
||||
};
|
||||
export type ListSendResult = ListResultBase;
|
||||
|
||||
export type ListContactResult = ListResultBase & {
|
||||
lastUser: string;
|
||||
assignUser: string;
|
||||
};
|
||||
|
||||
export type SurveyResult = {
|
||||
prjctSurveyIdx: number;
|
||||
surveyName: string;
|
||||
surveyTy: number;
|
||||
lastResultCd: number;
|
||||
lastResultDt: string;
|
||||
attemptCount: number;
|
||||
};
|
||||
|
||||
export type ListSearchBase = {
|
||||
prjctIdx: number;
|
||||
sid: number;
|
||||
@@ -335,7 +362,7 @@ export type ListSearchBase = {
|
||||
export type ListSearchWithResult = ListSearchBase & {
|
||||
contactResult: ListContactResult;
|
||||
interviewResult: ListContactResult;
|
||||
surveyResult: ListResultBase;
|
||||
surveyResults: SurveyResult[];
|
||||
};
|
||||
|
||||
export type ListSearchWithFullResult = ListSearchWithResult & {
|
||||
|
||||
@@ -38,6 +38,10 @@ export type SendResultInfo = {
|
||||
cmid: string;
|
||||
bulkSendKey?: string;
|
||||
sendTy: number;
|
||||
itrntPrjctCd: string;
|
||||
reqstSvc: string;
|
||||
prjctCd: string;
|
||||
sid: string;
|
||||
resve: boolean;
|
||||
resultCode: number;
|
||||
resultLabel?: string;
|
||||
|
||||
@@ -17,7 +17,7 @@ export enum ProjectStatus {
|
||||
export enum ResultCodeType {
|
||||
CONTACT = 21,
|
||||
INTERVIEW = 22,
|
||||
SURVEY = 99,
|
||||
SURVEY = 91,
|
||||
}
|
||||
|
||||
export enum ExternalActionCode {
|
||||
@@ -27,6 +27,18 @@ export enum ExternalActionCode {
|
||||
QUOTA = 98,
|
||||
}
|
||||
|
||||
export type ProjectSurvey = {
|
||||
prjctSurveyIdx?: number | null;
|
||||
surveyOrder: number;
|
||||
surveyName: string;
|
||||
surveyTy: SurveyType;
|
||||
surveyPrjctCd?: string | null;
|
||||
surveyUrl?: string | null;
|
||||
surveyFullUrl?: string | null;
|
||||
surveyShortUrl?: string | null;
|
||||
surveyDashboardUrl?: string | null;
|
||||
};
|
||||
|
||||
export type ProjectInfo = {
|
||||
prjctIdx: number; // Long
|
||||
prjctCd: string;
|
||||
@@ -36,10 +48,7 @@ export type ProjectInfo = {
|
||||
ownerDept: string;
|
||||
ownerFw: string;
|
||||
callerTelNum: string;
|
||||
surveyTy: SurveyType;
|
||||
surveyPrjctCd?: string;
|
||||
surveyUrl?: string;
|
||||
surveyDashboardUrl?: string;
|
||||
surveys: ProjectSurvey[];
|
||||
ff: boolean;
|
||||
useContactSenario: boolean;
|
||||
contactSenario?: string;
|
||||
|
||||
@@ -6,6 +6,11 @@ export type ItrntUserInfo = {
|
||||
userRole: number;
|
||||
};
|
||||
|
||||
export type GroupCodeInfo = {
|
||||
groupCode: string;
|
||||
groupCodeLabel: string;
|
||||
};
|
||||
|
||||
export type UserInfo = {
|
||||
userId: string
|
||||
userPw?: string
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ListHeaderAssignConst, ListHeaderConst } from "@/const/listConst";
|
||||
import { CONTACT_INTERVIEWER_ROLE, FIELD_INTERVIEWER_ROLE } from "@/const/userConst";
|
||||
import { ListIsUse, type ListFilter, type listHeader } from "@/types/list";
|
||||
import { isExternalManager, isFieldWorkUser, isInternalManager } from "@/utils/userRole";
|
||||
import {isExternalManager, isFieldWorkUser, isInternalManager, isManager} from "@/utils/userRole";
|
||||
|
||||
type ListAccessUser = {
|
||||
userRole?: number | null;
|
||||
@@ -23,9 +23,9 @@ export const isListFilterVisibleByAccess = (header: listHeader, userRole?: numbe
|
||||
// 컨택 진행 화면(/list/contact)은 역할과 무관하게 면접원 노출 항목만 보여준다.
|
||||
export const isListFieldVisibleForContact = (header: listHeader) => header.useIntrvwerView;
|
||||
|
||||
// SID는 항상 읽기 전용. internal 권한은 그 외 전부 수정 가능, 그 외 역할은 헤더별 면접원 수정가능 여부를 따른다.
|
||||
// SID는 항상 읽기 전용. manager 권한은 그 외 전부 수정 가능, 그 외 역할은 헤더별 면접원 수정가능 여부를 따른다.
|
||||
export const isListFieldEditableForContact = (header: listHeader, userRole?: number | null) =>
|
||||
header.listHderTy !== ListHeaderConst.SID && (isInternalManager(userRole) || header.useIntrvwerEdit);
|
||||
header.listHderTy !== ListHeaderConst.SID && (isManager(userRole) || header.useIntrvwerEdit);
|
||||
|
||||
export const getLockedListFilterHeaderTypes = (userRole?: number | null) => {
|
||||
const lockedTypes = new Set<number>();
|
||||
|
||||
50
src/utils/validation.ts
Normal file
50
src/utils/validation.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
export interface ValidateOptions {
|
||||
/** 값이 비어있으면(trim 후 빈 문자열) 실패 처리 */
|
||||
required?: boolean
|
||||
requiredMessage?: string
|
||||
/** 최소 길이(trim 후 기준) */
|
||||
minLength?: number
|
||||
/** 최대 길이(trim 후 기준) */
|
||||
maxLength?: number
|
||||
lengthMessage?: string
|
||||
/** 형식 검증용 정규식(trim 후 값에 대해 test) */
|
||||
pattern?: RegExp
|
||||
patternMessage?: string
|
||||
}
|
||||
|
||||
export interface ValidateResult {
|
||||
valid: boolean
|
||||
message?: string
|
||||
}
|
||||
|
||||
const DEFAULT_REQUIRED_MESSAGE = '값을 입력해주세요.'
|
||||
const DEFAULT_PATTERN_MESSAGE = '형식이 올바르지 않습니다.'
|
||||
|
||||
/**
|
||||
* 값이 비었는지 / 길이가 맞는지 / 정규식에 맞는지를 옵션으로 선택해서 검사한다.
|
||||
* 빈 값이고 required가 아니면 나머지 검사는 건너뛰고 통과 처리한다.
|
||||
*/
|
||||
export function validateValue(value: string, options: ValidateOptions): ValidateResult {
|
||||
const trimmed = value.trim()
|
||||
|
||||
if (!trimmed) {
|
||||
if (options.required) {
|
||||
return { valid: false, message: options.requiredMessage ?? DEFAULT_REQUIRED_MESSAGE }
|
||||
}
|
||||
return { valid: true }
|
||||
}
|
||||
|
||||
if (options.minLength !== undefined && trimmed.length < options.minLength) {
|
||||
return { valid: false, message: options.lengthMessage ?? `${options.minLength}자 이상 입력해주세요.` }
|
||||
}
|
||||
|
||||
if (options.maxLength !== undefined && trimmed.length > options.maxLength) {
|
||||
return { valid: false, message: options.lengthMessage ?? `${options.maxLength}자 이하로 입력해주세요.` }
|
||||
}
|
||||
|
||||
if (options.pattern && !options.pattern.test(trimmed)) {
|
||||
return { valid: false, message: options.patternMessage ?? DEFAULT_PATTERN_MESSAGE }
|
||||
}
|
||||
|
||||
return { valid: true }
|
||||
}
|
||||
Reference in New Issue
Block a user