901 lines
36 KiB
TypeScript
901 lines
36 KiB
TypeScript
'use client'
|
|
|
|
import {useEffect, useState, useCallback, useRef, useMemo} from 'react'
|
|
import AppPageTitle from '@/components/app-shell/AppPageTitle'
|
|
import {Button} from '@/components/ui/button'
|
|
import {Input} from '@/components/ui/input'
|
|
import {Label} from '@/components/ui/label'
|
|
import {RadioGroup, RadioGroupItem} from '@/components/ui/radio-group'
|
|
import {Checkbox} from '@/components/ui/checkbox'
|
|
import {Tabs, TabsContent, TabsList, TabsTrigger} from '@/components/ui/tabs'
|
|
import {KriMultiSelect, KriSingleSelect} from '@/components/common/KriAutoComplete'
|
|
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, Copy, Check } from 'lucide-react'
|
|
import {
|
|
ProjectInfo, ProjectSurvey, ProjectUpdateRequest, ResultCode,
|
|
ProjectStatus, ResultCodeType, SurveyType
|
|
} from "@/types/project";
|
|
import {
|
|
PROJECT_STATUS_LABEL,
|
|
PROJECT_STATUS_ORDER,
|
|
SURVEY_TYPE_LABEL,
|
|
SURVEY_TYPE_ORDER,
|
|
} 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, type KriEditorCommand} from "@/components/kri-editor";
|
|
import {useRouter} from "next/navigation";
|
|
import {
|
|
useProjectInfoQuery,
|
|
useResultCodesQuery,
|
|
useAssignedCmpnIdsQuery,
|
|
useUpdateProjectMutation,
|
|
useDeleteProjectMutation,
|
|
useUploadScenarioImageMutation, useKartProjectListQuery,
|
|
} from "@/query/project";
|
|
import { useCmpnListQuery } from "@/query/cmpn";
|
|
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,
|
|
prjctCd: '',
|
|
prjctName: '',
|
|
itrntPrjctCd: '',
|
|
prjctStatus: ProjectStatus.WAITING,
|
|
ownerDept: '',
|
|
ownerFw: '',
|
|
callerTelNum: '',
|
|
surveys: [],
|
|
ff: false,
|
|
useContactSenario: false,
|
|
contactSenario: '',
|
|
regUser: '',
|
|
regDt: '',
|
|
}
|
|
|
|
type ExternalTab = 'redirect' | 'api'
|
|
type SurveyDraft = ProjectSurvey & { uiKey: string }
|
|
|
|
const baseUrl = 'https://contact.kric.com'
|
|
const sidParam = 'sid=[$SID]'
|
|
const surveyIdxParam = 'psidx=[$prjctSurveyIdx]'
|
|
|
|
const externalUrls = {
|
|
redirect: {
|
|
complete: `${baseUrl}/redirect/complete?${surveyIdxParam}&${sidParam}`,
|
|
screen: `${baseUrl}/redirect/screen?${surveyIdxParam}&${sidParam}`,
|
|
quota: `${baseUrl}/redirect/quota?${surveyIdxParam}&${sidParam}`,
|
|
},
|
|
api: {
|
|
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 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,
|
|
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,
|
|
surveyDashboardUrl: '',
|
|
})
|
|
}
|
|
|
|
const handleKartSelect = (value: string) => {
|
|
onChange(survey.uiKey, {
|
|
surveyPrjctCd: value,
|
|
surveyUrl: buildKonKiwiSurveyUrl(survey.surveyTy),
|
|
surveyFullUrl: null,
|
|
})
|
|
}
|
|
|
|
// KON/KIWI는 호스트 placeholder까지 고정하고 '?' 이후 쿼리스트링만 편집 가능하게 한다.
|
|
const konKiwiPlaceholderPrefix = survey.surveyTy === SurveyType.KIWI ? 'https://[$KIWI-URL]' : 'https://[$KON-URL]'
|
|
// 저장 후 surveyUrl의 placeholder가 실제(단축) 호스트로 치환되므로 현재 base를 그대로 접두어로 쓴다.
|
|
const konKiwiUrlBase = survey.surveyUrl?.trim()
|
|
? survey.surveyUrl.split('?')[0]
|
|
: konKiwiPlaceholderPrefix
|
|
const konKiwiQuery = (() => {
|
|
const url = survey.surveyUrl ?? ''
|
|
const idx = url.indexOf('?')
|
|
return idx >= 0 ? url.slice(idx + 1) : ''
|
|
})()
|
|
|
|
const handleKonKiwiQueryChange = (nextQuery: string) => {
|
|
// 파라미터만 수정: surveyUrl base(단축/placeholder)는 유지하고 뒤 파라미터만 교체한다.
|
|
const patch: Partial<ProjectSurvey> = {
|
|
surveyUrl: `${konKiwiUrlBase}?${nextQuery}`,
|
|
}
|
|
// surveyFullUrl은 base(psidx 등)는 고정하고, 동일한 파라미터 꼬리만 함께 교체한다.
|
|
// 파라미터 꼬리를 갖지 않는 값(순수 단축 URL 등)은 건드리지 않는다.
|
|
const fullUrl = survey.surveyFullUrl
|
|
if (fullUrl && konKiwiQuery && fullUrl.endsWith(konKiwiQuery)) {
|
|
patch.surveyFullUrl = fullUrl.slice(0, fullUrl.length - konKiwiQuery.length) + nextQuery
|
|
}
|
|
onChange(survey.uiKey, patch)
|
|
}
|
|
|
|
const [copiedField, setCopiedField] = useState<'url' | 'fullUrl' | null>(null)
|
|
const copyToClipboard = async (value: string | null | undefined, field: 'url' | 'fullUrl') => {
|
|
const text = value?.trim() ?? ''
|
|
if (!text) return
|
|
try {
|
|
await navigator.clipboard.writeText(text)
|
|
setCopiedField(field)
|
|
setTimeout(() => setCopiedField((prev) => (prev === field ? null : prev)), 1500)
|
|
} catch {
|
|
// 클립보드 접근 실패 시 무시
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div className="space-y-3 rounded-lg border p-4">
|
|
<div className="flex items-center justify-between">
|
|
<div className="flex items-center gap-2">
|
|
<p className="text-base font-semibold">설문 {index + 1}</p>
|
|
<span className="text-sm font-semibold ">
|
|
(설문 번호: {survey.prjctSurveyIdx ?? '미발급'})
|
|
</span>
|
|
</div>
|
|
<Button type="button" variant="ghost" size="icon-sm" onClick={() => onRemove(survey.uiKey)} aria-label="설문 삭제">
|
|
<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"
|
|
/>
|
|
{kartProjectListQuery.isError && (
|
|
<div role="alert" className="flex items-center gap-2 text-destructive">
|
|
<span>프로젝트 목록을 불러오지 못했습니다.</span>
|
|
<Button type="button" variant="outline" size="sm" onClick={() => void kartProjectListQuery.refetch()}>
|
|
다시 시도
|
|
</Button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
<div className="space-y-2">
|
|
<div className="flex items-center gap-2">
|
|
<Label className="text-base">설문 URL</Label>
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
{isKonKiwi ? (
|
|
<div className="flex flex-1 items-center">
|
|
<span className="inline-flex h-9 items-center whitespace-nowrap rounded-l-md border border-r-0 bg-gray-100 px-3 text-sm text-muted-foreground">
|
|
{konKiwiUrlBase}?
|
|
</span>
|
|
<Input
|
|
ref={onRegisterFieldRef(survey.uiKey, 'surveyUrl')}
|
|
value={konKiwiQuery}
|
|
onChange={(e) => handleKonKiwiQueryChange(e.target.value)}
|
|
placeholder="sid=[$SID]"
|
|
className="h-9 rounded-l-none"
|
|
aria-invalid={invalidField === 'surveyUrl'}
|
|
/>
|
|
</div>
|
|
) : (
|
|
<Input
|
|
ref={onRegisterFieldRef(survey.uiKey, 'surveyUrl')}
|
|
value={survey.surveyUrl || ''}
|
|
onChange={(e) => onChange(survey.uiKey, {
|
|
surveyUrl: e.target.value,
|
|
surveyFullUrl: null,
|
|
})}
|
|
placeholder="https://"
|
|
className="h-9 flex-1"
|
|
aria-invalid={invalidField === 'surveyUrl'}
|
|
/>
|
|
)}
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
onClick={() => copyToClipboard(survey.surveyUrl, 'url')}
|
|
disabled={!survey.surveyUrl?.trim()}
|
|
aria-label="설문 URL 복사"
|
|
className="h-9 w-9 shrink-0 p-0"
|
|
>
|
|
{copiedField === 'url' ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
{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();
|
|
const mounted = useMounted();
|
|
const {selectedProject, setSelectedProject} = useSelectedProject();
|
|
const {isDialogOpen, showDialog, hideDialog} = useDialog();
|
|
const {users} = useItrntUserList();
|
|
const {auth} = useAuth();
|
|
|
|
const [projectInfo, setProjectInfo] = useState<ProjectInfo>(defaultProjectInfo);
|
|
const [surveys, setSurveys] = useState<SurveyDraft[]>([]);
|
|
|
|
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 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 groupCodeListQuery = useGroupCodeListQuery(mounted);
|
|
|
|
const updateMutation = useUpdateProjectMutation(prjctIdx);
|
|
const deleteMutation = useDeleteProjectMutation(prjctIdx);
|
|
const uploadScenarioMutation = useUploadScenarioImageMutation(projectInfo.prjctCd);
|
|
|
|
const [resultCodeArray, setResultCodeArray] = useState<ResultCode[]>([]);
|
|
const [assignCmpnIdArray, setAssignCmpnIdArray] = useState<string[]>([]);
|
|
const [changeResultCodeType, setChangeResultCodeType] = useState<ResultCodeType[]>([]);
|
|
|
|
const cmpnOptionArray: MultiSelectOption[] = useMemo(() => {
|
|
const arr = cmpnListQuery.data ?? [];
|
|
return arr.filter((cmpn) => !cmpn.ownCmpn).map((cmpn) => ({
|
|
value: cmpn.cmpnId,
|
|
label: cmpn.cmpnAlias || cmpn.cmpnId,
|
|
}));
|
|
}, [cmpnListQuery.data]);
|
|
|
|
const callerTelNumArray = callerTelNumListQuery.data ?? [];
|
|
|
|
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"))
|
|
.map((code) => ({ value: code, label: groupCodeLabelMap.get(code) ?? code }));
|
|
}, [users, groupCodeLabelMap]);
|
|
|
|
const fwArray: MultiSelectOption[] = useMemo(() => {
|
|
return (users ?? [])
|
|
.filter((u) => u.userId === projectInfo.ownerFw || u.userTeam === FW_TEAM)
|
|
.map((u) => ({value: u.userId, label: u.userNm}));
|
|
}, [users, projectInfo.ownerFw]);
|
|
|
|
const handleChange = (field: keyof ProjectInfo, value: any) => {
|
|
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) {
|
|
alert("프로젝트 코드가 없습니다. 잠시 후 다시 시도해주세요.");
|
|
return "";
|
|
}
|
|
|
|
const url = await uploadScenarioMutation.mutateAsync(file);
|
|
sessionTempUrlsRef.current.add(url);
|
|
return url;
|
|
},
|
|
[uploadScenarioMutation, projectInfo.prjctCd]
|
|
);
|
|
|
|
const handleResultCodeClick = () => {
|
|
showDialog('resultCodeDialog')
|
|
}
|
|
|
|
const handleSubmit = async () => {
|
|
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,
|
|
surveys: surveys.map(({ uiKey, ...rest }) => rest),
|
|
},
|
|
resultCodeList: updateCodeArray,
|
|
assignCmpnIdList: assignCmpnIdArray,
|
|
}
|
|
|
|
await updateMutation.mutateAsync(requestUpdateProject);
|
|
const savedProjectInfo = requestUpdateProject.projectInfo;
|
|
setSelectedProject({
|
|
prjctIdx: savedProjectInfo.prjctIdx,
|
|
prjctCd: savedProjectInfo.prjctCd,
|
|
prjctName: savedProjectInfo.prjctName,
|
|
itrntPrjctCd: savedProjectInfo.itrntPrjctCd,
|
|
ownerDept: savedProjectInfo.ownerDept,
|
|
ownerFw: savedProjectInfo.ownerFw,
|
|
ff: savedProjectInfo.ff,
|
|
});
|
|
initialProjectInfoRef.current = projectInfo;
|
|
alert("저장되었습니다.");
|
|
}
|
|
|
|
const handleDeleteClick = async () => {
|
|
if (!confirm("복구 할 수 없습니다. 정말 삭제 하시겠습니까?")) return;
|
|
if (!selectedProject) {
|
|
alert("옳지 않은 요청입니다.");
|
|
return;
|
|
}
|
|
|
|
await deleteMutation.mutateAsync();
|
|
router.push("/");
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (projectInfoQuery.data) {
|
|
setProjectInfo(projectInfoQuery.data);
|
|
setSurveys(projectInfoQuery.data.surveys.map((s) => ({ ...s, uiKey: crypto.randomUUID() })));
|
|
initialProjectInfoRef.current = projectInfoQuery.data;
|
|
}
|
|
}, [projectInfoQuery.data]);
|
|
|
|
useEffect(() => {
|
|
if (resultCodesQuery.data) {
|
|
setResultCodeArray(resultCodesQuery.data);
|
|
}
|
|
}, [resultCodesQuery.data]);
|
|
|
|
useEffect(() => {
|
|
if (assignedCmpnQuery.data) {
|
|
setAssignCmpnIdArray(assignedCmpnQuery.data);
|
|
}
|
|
}, [assignedCmpnQuery.data]);
|
|
|
|
if (!mounted) return <LoadingOverlayAdapter force />
|
|
|
|
return (
|
|
<div className="min-h-full">
|
|
<div className="space-y-6 pb-24 px-6">
|
|
<div className="max-w-[900px]">
|
|
<AppPageTitle titleText="프로젝트 정보" />
|
|
|
|
{/* 1. 기본 정보 */}
|
|
<div className="border rounded-lg p-6 space-y-5 bg-white mt-6">
|
|
<h3 className="text-xl font-semibold">프로젝트 기본 정보</h3>
|
|
<div className="space-y-4">
|
|
<div className="space-y-2">
|
|
<Label className="text-base">프로젝트 코드</Label>
|
|
<Input value={projectInfo.prjctCd || ''} disabled className="bg-gray-100 h-9" />
|
|
</div>
|
|
|
|
<div className="grid grid-cols-[1fr_auto] gap-3 items-end">
|
|
<div className="space-y-2">
|
|
<Label className="text-base">진행 상태</Label>
|
|
<RadioGroup
|
|
value={String(projectInfo.prjctStatus ?? ProjectStatus.WAITING)}
|
|
onValueChange={(v) => handleChange('prjctStatus', Number(v) as ProjectStatus)}
|
|
className="flex gap-4"
|
|
>
|
|
{PROJECT_STATUS_ORDER.map((s) => {
|
|
const id = `status-${s}`;
|
|
return (
|
|
<div key={s} className="flex items-center space-x-2">
|
|
<RadioGroupItem value={String(s)} id={id} />
|
|
<Label htmlFor={id} className="font-normal cursor-pointer text-base">
|
|
{PROJECT_STATUS_LABEL[s]}
|
|
</Label>
|
|
</div>
|
|
);
|
|
})}
|
|
</RadioGroup>
|
|
</div>
|
|
|
|
<Button onClick={handleResultCodeClick} className="h-9 text-base whitespace-nowrap">
|
|
결과 코드 설정
|
|
</Button>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<Label className="text-base">
|
|
프로젝트 명<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>
|
|
|
|
<div className="grid grid-cols-3 gap-4">
|
|
<div className="space-y-2">
|
|
<Label className="text-base">담당 그룹</Label>
|
|
<KriSingleSelect
|
|
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"
|
|
/>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<Label className="text-base">담당 실사</Label>
|
|
<KriSingleSelect
|
|
items={fwArray}
|
|
value={projectInfo.ownerFw || ''}
|
|
onChange={(value) => handleChange('ownerFw', value)}
|
|
getValue={(item) => item.value}
|
|
getLabel={(item) => item.label}
|
|
placeholder="담당 실사를 선택하세요"
|
|
heightClassName="h-9"
|
|
widthClassName="w-full"
|
|
/>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<Label className="text-base">발신 번호</Label>
|
|
<KriSingleSelect
|
|
items={callerTelNumArray}
|
|
value={projectInfo.callerTelNum || ''}
|
|
onChange={(value) => handleChange('callerTelNum', value)}
|
|
getValue={(item) => item.telNum}
|
|
getLabel={(item) => formatKoreanPhoneNumber(item.telNum)}
|
|
placeholder="발신 번호를 선택하세요"
|
|
heightClassName="h-9"
|
|
widthClassName="w-full"
|
|
/>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="border rounded-lg p-6 space-y-4 bg-white mt-3">
|
|
<h3 className="text-xl font-semibold">외주사</h3>
|
|
<KriMultiSelect
|
|
items={cmpnOptionArray}
|
|
value={assignCmpnIdArray}
|
|
onChange={(value) => setAssignCmpnIdArray(value)}
|
|
getValue={(item) => item.value}
|
|
getLabel={(item) => item.label}
|
|
maxCount={2}
|
|
placeholder="없음"
|
|
heightClassName="h-9"
|
|
widthClassName="w-full"
|
|
/>
|
|
</div>
|
|
|
|
<div className="border rounded-lg p-6 space-y-4 bg-white mt-3">
|
|
<div className="flex items-center justify-between">
|
|
<div className="flex items-center gap-4">
|
|
<h3 className="shrink-0 text-xl font-semibold">설문 연동</h3>
|
|
</div>
|
|
<Button type="button" variant="outline" onClick={handleAddSurvey}>
|
|
설문 추가
|
|
</Button>
|
|
</div>
|
|
|
|
{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>
|
|
)}
|
|
</div>
|
|
|
|
<div className="border rounded-lg p-6 space-y-4 bg-white mt-3">
|
|
<h3 className="text-xl font-semibold">기타 옵션</h3>
|
|
|
|
<div className="space-y-4">
|
|
<div className="flex items-center space-x-2">
|
|
<Checkbox
|
|
id="ff"
|
|
checked={projectInfo.ff || false}
|
|
onCheckedChange={(checked) => handleChange('ff', checked === true)}
|
|
/>
|
|
<Label htmlFor="ff" className="font-normal cursor-pointer text-base">
|
|
현장 면접 진행
|
|
</Label>
|
|
</div>
|
|
|
|
<div className="flex items-center space-x-2">
|
|
<Checkbox
|
|
id="useContactSenario"
|
|
checked={projectInfo.useContactSenario || false}
|
|
onCheckedChange={(checked) => handleChange('useContactSenario', checked === true)}
|
|
/>
|
|
<Label htmlFor="useContactSenario" className="font-normal cursor-pointer text-base">
|
|
컨택 시나리오
|
|
</Label>
|
|
</div>
|
|
|
|
{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="mt-4 w-full"
|
|
debounceMs={600} // 기본 400ms, 원하면 늘리세요(예: 600~1000)
|
|
onImageUpload={async (file) => await handleImageUpload(file)} // 사용 시만
|
|
/>
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="fixed left-0 right-0 bottom-0 z-[20] border-t bg-white/80 backdrop-blur shadow-sm">
|
|
<div className="px-6 py-3">
|
|
<div className="max-w-[836px] ml-0">
|
|
<div className="flex justify-end gap-2">
|
|
<Button
|
|
variant="destructive"
|
|
className="w-32 h-10 text-base"
|
|
onClick={handleDeleteClick}
|
|
>
|
|
삭제
|
|
</Button>
|
|
<Button onClick={handleSubmit} className="w-32 h-10 text-base">
|
|
저장
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<ResultCodeDialog
|
|
open={isDialogOpen('resultCodeDialog')}
|
|
onOpenChange={(open) => (open ? showDialog('resultCodeDialog') : hideDialog('resultCodeDialog'))}
|
|
changeCodeType={changeResultCodeType}
|
|
onChangeCodeType={setChangeResultCodeType}
|
|
sourceArray={resultCodeArray}
|
|
onSave={setResultCodeArray}
|
|
/>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
export default ProjectInfoPage
|