454 lines
19 KiB
TypeScript
454 lines
19 KiB
TypeScript
'use client'
|
||
|
||
import { useRef, useState, type ReactNode } from 'react'
|
||
import { Mail, MessageCircle, 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 { LIST_IS_USE_LABEL } from '@/components/table-column/ListTableColumn'
|
||
import { useDialog } from '@/hooks/useDialog'
|
||
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 ProjectSurvey, type ResultCode, ResultCodeType } from '@/types/project'
|
||
import { formatKst } from '@kri/common'
|
||
import { isListFieldEditableForContact, isListFieldVisibleForContact } from '@/utils/listAccess'
|
||
import { substituteVariables } from '@/lib/variableSubstitution'
|
||
import { formatKoreanPhoneNumber } from '@/utils/phone'
|
||
import { isLightHexColor, normalizeHexColor } from '@/components/common/color-palette/color'
|
||
import SurveyQrDialog from '@/components/dialog/SurveyQrDialog'
|
||
import SingleMessageSendDialog from '@/components/dialog/SingleMessageSendDialog'
|
||
import { ctiClient } from '@/lib/cti/ctiClient'
|
||
import { useCtiConnectionStatus } from '@/hooks/useCtiConnectionStatus'
|
||
import { useCtiCallPhase } from '@/hooks/useCtiCallPhase'
|
||
import { cn } from '@/lib/utils'
|
||
import { downloadFile } from '@kri/common/browser'
|
||
import {
|
||
buildKkoVariableValues,
|
||
buildListContactVariableValues,
|
||
resolveListHeaderValue,
|
||
} from '@/components/list-contact/listContactVariables'
|
||
|
||
export type ListContactInfoPanelProps = {
|
||
prjctIdx: number
|
||
sid: string
|
||
itrntPrjctCd: string
|
||
userRole: number
|
||
isEditing: boolean
|
||
listHeaders: listHeader[]
|
||
detail?: ListSearchWithFullResult
|
||
surveys: ProjectSurvey[]
|
||
callerTelNum?: string
|
||
resultCodes: ResultCode[]
|
||
formValues: Record<number, string>
|
||
onFieldChange: (listHderId: number, value: string) => void
|
||
onSaved?: () => void
|
||
}
|
||
|
||
export const buildInitialValues = (listHeaders: listHeader[], detail?: ListSearchWithFullResult) => {
|
||
const values: Record<number, string> = {}
|
||
|
||
for (const header of listHeaders) {
|
||
if (header.listHderTy === ListHeaderConst.SID) continue
|
||
if (!isListFieldVisibleForContact(header)) continue
|
||
// 사용 허용은 저장 시 코드("0"/"1"/"9")로 보내야 하므로 폼 값은 코드로 둔다.
|
||
// 문자·알림톡 변수 치환은 resolveListHeaderValue의 라벨을 그대로 사용한다.
|
||
if (header.listHderTy === ListHeaderConst.IS_USE) {
|
||
values[header.listHderId] = detail?.use != null ? String(detail.use) : ''
|
||
continue
|
||
}
|
||
values[header.listHderId] = resolveListHeaderValue(header, detail)
|
||
}
|
||
|
||
return values
|
||
}
|
||
|
||
const IS_USE_OPTIONS = Object.entries(LIST_IS_USE_LABEL).map(([value, label]) => ({ value, label }))
|
||
|
||
const disabledContrastClass = 'bg-white disabled:opacity-100 disabled:text-foreground disabled:bg-muted/60'
|
||
// Input/textarea는 수정 불가 상태에서도 드래그 선택/복사가 가능해야 해서 disabled 대신 readOnly를 쓴다.
|
||
// disabled는 공용 Input 컴포넌트의 disabled:pointer-events-none 때문에 마우스 이벤트 자체를 못 받는다.
|
||
const readOnlyContrastClass = 'bg-white read-only:text-foreground read-only:bg-muted/60'
|
||
|
||
const getCallButtonLabel = (isDialing: boolean, isOnCall: boolean, isEnding: boolean) => {
|
||
if (isEnding) return '종료 요청 중'
|
||
if (isDialing) return '거는 중'
|
||
if (isOnCall) return '전화 끊기'
|
||
return '전화'
|
||
}
|
||
|
||
const getCallButtonTitle = (isCtiReady: boolean, isDialing: boolean, isEnding: boolean) => {
|
||
if (!isCtiReady) return '전화 시스템에 연결되어 있지 않습니다.'
|
||
if (isDialing) return '전화를 거는 중입니다.'
|
||
if (isEnding) return '통화 종료를 확인하고 있습니다.'
|
||
return undefined
|
||
}
|
||
|
||
const FieldRow = ({ label, color, children }: { label: string; color?: string | null; children: ReactNode }) => {
|
||
// 헤더에 지정한 색상(투명도 포함)이 기본색보다 우선한다. 형식이 잘못된 값은 기본색으로 표시한다.
|
||
const headerColor = normalizeHexColor(color)
|
||
const isDarkHeaderColor = headerColor !== null && !isLightHexColor(headerColor)
|
||
|
||
return (
|
||
<div className="flex items-center gap-3">
|
||
<Label
|
||
className={cn(
|
||
'w-24 shrink-0 wrap-anywhere rounded-md px-2 py-2.5 text-sm leading-snug font-bold',
|
||
headerColor === null && 'bg-blue-100',
|
||
isDarkHeaderColor ? 'text-white' : 'text-foreground',
|
||
)}
|
||
style={headerColor ? { backgroundColor: headerColor } : undefined}
|
||
>
|
||
{label}
|
||
</Label>
|
||
<div className="min-w-0 flex-1">{children}</div>
|
||
</div>
|
||
)
|
||
}
|
||
|
||
const ListContactInfoPanel = ({
|
||
prjctIdx,
|
||
sid,
|
||
itrntPrjctCd,
|
||
userRole,
|
||
isEditing,
|
||
listHeaders,
|
||
detail,
|
||
surveys,
|
||
callerTelNum,
|
||
resultCodes,
|
||
formValues,
|
||
onFieldChange,
|
||
onSaved,
|
||
}: 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 ctiCallPhase = useCtiCallPhase()
|
||
const isDialing = ctiCallPhase === 'dialing'
|
||
const isEnding = ctiCallPhase === 'ending'
|
||
const isOnCall = ctiCallPhase === 'active' || isEnding
|
||
|
||
const visibleHeaders = listHeaders
|
||
.filter((header) => isListFieldVisibleForContact(header))
|
||
.sort((a, b) => {
|
||
if (a.listHderTy === ListHeaderConst.MEMO) return 1
|
||
if (b.listHderTy === ListHeaderConst.MEMO) return -1
|
||
return a.listHderOrder - b.listHderOrder
|
||
})
|
||
|
||
const surveyResultByIdx = new Map((detail?.surveyResults ?? []).map((result) => [result.prjctSurveyIdx, result]))
|
||
|
||
const surveyUrlValues = buildListContactVariableValues(listHeaders, detail, sid)
|
||
// 알림톡은 #{설문명}도 설문 URL로 치환한다. 문자·메일은 기존처럼 헤더 값만 쓴다.
|
||
const kkoVariableValues = buildKkoVariableValues(surveyUrlValues, surveys)
|
||
|
||
const handleStartSurvey = (survey: ProjectSurvey) => {
|
||
if (!survey.surveyUrl) return
|
||
window.open(substituteVariables(survey.surveyUrl, surveyUrlValues), '_blank', 'noopener,noreferrer')
|
||
}
|
||
|
||
const handleShowQr = (survey: ProjectSurvey) => {
|
||
if (!survey.surveyUrl) return
|
||
setQrTargetUrl(substituteVariables(survey.surveyUrl, surveyUrlValues))
|
||
showDialog('surveyQrDialog')
|
||
}
|
||
|
||
const handleSend = (channel: MessageSendChannel, headerId: number) => {
|
||
setSendTarget({ channel, headerId })
|
||
showDialog('singleMessageSendDialog')
|
||
}
|
||
|
||
const handleCall = (telNum: string, listHderId: number) => {
|
||
if (!isCtiReady || isDialing || isEnding) return
|
||
if (isOnCall) {
|
||
ctiClient.hangup()
|
||
return
|
||
}
|
||
|
||
if (!telNum.trim()) {
|
||
alert('전화번호가 없습니다.')
|
||
return
|
||
}
|
||
// CTI는 ANINumber가 비어 있으면 Default 발신번호로 건다고 하지만, 의도치 않은 번호로 나가지 않도록 막는다.
|
||
if (!callerTelNum?.trim()) {
|
||
alert('프로젝트에 발신 번호가 등록되지 않았습니다.')
|
||
return
|
||
}
|
||
ctiClient.makeCall({ dialNumber: telNum, prjctIdx, sid, listHderId, aniNumber: callerTelNum ?? '' })
|
||
}
|
||
|
||
const handlePickFile = (listHderId: number) => {
|
||
setUploadingHeaderId(listHderId)
|
||
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 = ''
|
||
if (!file || uploadingHeaderId === null) return
|
||
|
||
await uploadItemFileMutation.mutateAsync({ listHderId: uploadingHeaderId, file })
|
||
setUploadingHeaderId(null)
|
||
alert('파일이 업로드되었습니다.')
|
||
onSaved?.()
|
||
}
|
||
|
||
return (
|
||
<div className="space-y-2 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 canEditField = isListFieldEditableForContact(header, userRole)
|
||
const editable = isEditing && canEditField
|
||
const value = formValues[header.listHderId] ?? ''
|
||
const onChange = (next: string) => onFieldChange(header.listHderId, next)
|
||
|
||
if (header.listHderTy === ListHeaderConst.MEMO || header.listHderTy === ListHeaderConst.MULTILINE_TEXT) {
|
||
return (
|
||
<FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
|
||
<textarea
|
||
className={`flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ${readOnlyContrastClass}`}
|
||
value={value}
|
||
readOnly={!editable}
|
||
onChange={(e) => onChange(e.target.value)}
|
||
/>
|
||
</FieldRow>
|
||
)
|
||
}
|
||
|
||
if (header.listHderTy === ListHeaderConst.TEL_NUM) {
|
||
return (
|
||
<FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
|
||
{/* 모바일(md 미만)은 버튼을 입력란 아래 줄로 내린다. */}
|
||
<div className="flex flex-col gap-2 md:flex-row">
|
||
<Input
|
||
value={formatKoreanPhoneNumber(value)}
|
||
readOnly={!editable}
|
||
onChange={(e) => onChange(e.target.value.replace(/\D/g, ''))}
|
||
className={readOnlyContrastClass}
|
||
/>
|
||
<div className="flex shrink-0 flex-wrap gap-2">
|
||
<Button
|
||
type="button"
|
||
variant="outline"
|
||
className={cn('shrink-0 gap-2', isOnCall && 'bg-accent text-accent-foreground')}
|
||
disabled={isEditing || !isCtiReady || isDialing || isEnding}
|
||
title={getCallButtonTitle(isCtiReady, isDialing, isEnding)}
|
||
onClick={() => handleCall(value, header.listHderId)}
|
||
>
|
||
<Phone className="h-4 w-4" />
|
||
{getCallButtonLabel(isDialing, isOnCall, isEnding)}
|
||
</Button>
|
||
<Button
|
||
type="button"
|
||
variant="outline"
|
||
className="shrink-0 gap-2"
|
||
disabled={isEditing}
|
||
onClick={() => handleSend('sms', header.listHderId)}
|
||
>
|
||
<MessageSquare className="h-4 w-4" />
|
||
발송
|
||
</Button>
|
||
<Button
|
||
type="button"
|
||
variant="outline"
|
||
className="shrink-0 gap-2"
|
||
disabled={isEditing}
|
||
onClick={() => handleSend('kko', header.listHderId)}
|
||
>
|
||
<MessageCircle className="h-4 w-4" />
|
||
알림톡
|
||
</Button>
|
||
</div>
|
||
</div>
|
||
{(isDialing || isOnCall) &&
|
||
<p className="text-sm text-red-600 font-medium mt-1">
|
||
⚠️ 전화를 끊어야만 통화 종료가 기록됩니다.
|
||
</p>
|
||
}
|
||
</FieldRow>
|
||
)
|
||
}
|
||
|
||
if (header.listHderTy === ListHeaderConst.EMAIL) {
|
||
return (
|
||
<FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
|
||
<div className="flex flex-col gap-2 md:flex-row">
|
||
<Input
|
||
value={value}
|
||
readOnly={!editable}
|
||
onChange={(e) => onChange(e.target.value)}
|
||
className={readOnlyContrastClass}
|
||
/>
|
||
<div className="flex shrink-0 gap-2">
|
||
<Button
|
||
type="button"
|
||
variant="outline"
|
||
className="shrink-0 gap-2"
|
||
disabled={isEditing}
|
||
onClick={() => handleSend('email', header.listHderId)}
|
||
>
|
||
<Mail className="h-4 w-4" />
|
||
발송
|
||
</Button>
|
||
</div>
|
||
</div>
|
||
</FieldRow>
|
||
)
|
||
}
|
||
|
||
if (header.listHderTy === ListHeaderConst.FILE) {
|
||
return (
|
||
<FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
|
||
<div className="flex items-center gap-2">
|
||
<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={isEditing || 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={isEditing || uploadItemFileMutation.isPending}
|
||
onClick={() => handlePickFile(header.listHderId)}
|
||
>
|
||
<Paperclip className="h-4 w-4" />
|
||
업로드
|
||
</Button>
|
||
) : null}
|
||
</div>
|
||
</FieldRow>
|
||
)
|
||
}
|
||
|
||
if (header.listHderTy === ListHeaderConst.IS_USE) {
|
||
return (
|
||
<FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
|
||
<KriSingleSelect
|
||
items={IS_USE_OPTIONS}
|
||
value={value}
|
||
disabled={!editable}
|
||
onChange={onChange}
|
||
getValue={(item) => item.value}
|
||
getLabel={(item) => item.label}
|
||
searchable={false}
|
||
preventDeselect
|
||
widthClassName="w-full"
|
||
heightClassName="h-9"
|
||
className={disabledContrastClass}
|
||
/>
|
||
</FieldRow>
|
||
)
|
||
}
|
||
|
||
if (header.listHderTy === ListHeaderConst.CONTENT_ITEM && (header.filterContents?.length ?? 0) > 0) {
|
||
return (
|
||
<FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
|
||
<KriSingleSelect
|
||
items={header.filterContents ?? []}
|
||
value={value}
|
||
disabled={!editable}
|
||
onChange={onChange}
|
||
getValue={(item) => item}
|
||
getLabel={(item) => item}
|
||
widthClassName="w-full"
|
||
heightClassName="h-9"
|
||
className={disabledContrastClass}
|
||
/>
|
||
</FieldRow>
|
||
)
|
||
}
|
||
|
||
return (
|
||
<FieldRow key={header.listHderId} label={header.listHderNm} color={header.listHderColor}>
|
||
<Input
|
||
value={value}
|
||
readOnly={!editable}
|
||
onChange={(e) => onChange(e.target.value)}
|
||
className={readOnlyContrastClass}
|
||
/>
|
||
</FieldRow>
|
||
)
|
||
})}
|
||
|
||
{surveys
|
||
.filter((survey) => !!survey.surveyUrl)
|
||
.map((survey) => {
|
||
const result = survey.prjctSurveyIdx != null ? surveyResultByIdx.get(survey.prjctSurveyIdx) : undefined
|
||
const hasSurveyResponse = result !== undefined
|
||
|
||
return (
|
||
<FieldRow key={survey.prjctSurveyIdx ?? survey.surveyOrder} label={survey.surveyName || 'Web'}>
|
||
{/* 모바일(md 미만)은 응답 상태를 버튼 아래 줄로 내린다. */}
|
||
<div className="flex flex-col items-start gap-2 md:flex-row md:items-center">
|
||
<div className="flex items-center gap-2">
|
||
<Button type="button" className="gap-2" disabled={isEditing} onClick={() => handleStartSurvey(survey)}>
|
||
조사 시작
|
||
</Button>
|
||
<Button type="button" variant="outline" className="gap-2" disabled={isEditing} onClick={() => handleShowQr(survey)}>
|
||
<QrCode className="h-4 w-4" />
|
||
QR
|
||
</Button>
|
||
</div>
|
||
{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}
|
||
itrntPrjctCd={itrntPrjctCd}
|
||
sid={sid}
|
||
destHeaderId={sendTarget?.headerId ?? 0}
|
||
variableValues={sendTarget?.channel === 'kko' ? kkoVariableValues : surveyUrlValues}
|
||
/>
|
||
</div>
|
||
)
|
||
}
|
||
|
||
export default ListContactInfoPanel
|