develop #44

Merged
gitadmin merged 3 commits from develop into master 2026-10-02 13:55:32 +09:00
12 changed files with 335 additions and 153 deletions

View File

@@ -15,20 +15,15 @@ import {
useTemplateListQuery,
useTemplateQuery,
} from '@/query/message'
import { ChannelType, TemplateSms } from '@kri/common/noti-hub'
import { cn } from '@/lib/utils'
import { ChannelType } from '@kri/common/noti-hub'
import { getNearestFutureDateTime } from '@/lib/datetime'
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, { validateApplyFilterTarget } from './ListDialogOption/ApplyFilterOption'
import { KriEditor } from '@/components/kri-editor'
import { normalizeQrCodeForEditor, renderQrCodePreviewHtml } from '@/components/message-template/qrcode'
import { sanitizeEmailHtml } from '@/components/message-template/emailHtmlPolicy'
import { applyLinkPreviewClass } from '@/components/kri-editor/utils/linkPreview'
import TemplateAttachmentList from '@/components/message-template/TemplateAttachmentList'
import type { TemplateEmailWithAttachments, TemplateSummaryWithPurpose } from '@/types/message'
import MessageSendPreview from '@/components/message-template/MessageSendPreview'
import type { TemplateSummaryWithPurpose } from '@/types/message'
import { TEMPLATE_PURPOSE } from '@/const/messageTemplateConst'
export type MessageSendMode = 'email' | 'sms'
@@ -323,50 +318,7 @@ const MessageSendDialog = ({
</div>
</div>
<div className="rounded-md border p-4 space-y-2">
<p className="text-lg font-semibold">미리보기</p>
{!selectedTemplate && <p className="text-sm text-muted-foreground">선택된 템플릿이 없습니다.</p>}
{selectedTemplate && (
<>
{chnnlTy !== ChannelType.SMS && (
<div className="rounded border p-2 text-lg font-semibold">{`제목: ${selectedTemplate.tmplatTitle}` || '(제목 없음)'}</div>
)}
{chnnlTy === ChannelType.SMS ? (
<div className="flex flex-col items-center">
<KriEditor
mode="sms"
value={(selectedTemplate as TemplateSms).tmplatBody ?? ""}
onChange={() => {}}
isSmsReadOnly
placeholder="문자 내용을 입력해 주세요"
className="max-w-80 mx-0"
debounceMs={600}
smsTitle={(selectedTemplate as TemplateSms).tmplatTitle}
/>
</div>
) : (
<>
<div
className={cn('kri-editor-preview rounded-md border bg-muted/30 p-3')}
dangerouslySetInnerHTML={{
__html: renderQrCodePreviewHtml(
applyLinkPreviewClass(
sanitizeEmailHtml(
normalizeQrCodeForEditor(selectedTemplate.tmplatBody) || '(내용 없음)',
),
),
),
}}
/>
<TemplateAttachmentList
tmplatIdx={selectedTemplate.tmplatIdx}
atchFl={(selectedTemplate as TemplateEmailWithAttachments).atchFl}
/>
</>
)}
</>
)}
</div>
<MessageSendPreview chnnlTy={chnnlTy} template={selectedTemplate} />
</KriDialog>
)
}

View File

@@ -14,15 +14,12 @@ import {
useTemplateListQuery,
useTemplateQuery,
} from '@/query/message'
import { ChannelType, type TemplateSms, type TemplateSummary } from '@kri/common/noti-hub'
import { KriEditor } from '@/components/kri-editor'
import { sanitizeEmailHtml } from '@/components/message-template/emailHtmlPolicy'
import { ChannelType, type TemplateSummary } from '@kri/common/noti-hub'
import { getNearestFutureDateTime } from '@/lib/datetime'
import { escapeHtml, substituteVariables } from '@/lib/variableSubstitution'
import type { DialogId } from '@/store/jotai/dialog'
import type { MessageSendChannel, PhoneVerificationSendData, TemplateEmailWithAttachments } from '@/types/message'
import TemplateAttachmentList from '@/components/message-template/TemplateAttachmentList'
import {PHONE_VERIFICATION_PREVIEW_SUFFIX, TEMPLATE_PURPOSE} from '@/const/messageTemplateConst'
import type { MessageSendChannel, PhoneVerificationSendData } from '@/types/message'
import MessageSendPreview from '@/components/message-template/MessageSendPreview'
import { TEMPLATE_PURPOSE } from '@/const/messageTemplateConst'
const titleMap: Record<MessageSendChannel, string> = {
email: '메일 발송',
@@ -72,9 +69,6 @@ const SingleMessageSendDialog = ({
const mainTemplateQuery = useMainTemplateIdxQuery(prjctIdx, chnnlTy, enabled)
const mainTemplateIdx = mainTemplateQuery.data ?? null
const previewValues = variableValues ?? {}
const resolvedTitle = selectedTemplate ? substituteVariables(selectedTemplate.tmplatTitle ?? '', previewValues) : ''
// tmplatPurpose === 1(휴대전화번호 인증) 템플릿은 SMS/LMS 단건 즉시 발송만 허용한다.
const isPhoneVerificationTemplate = selectedTemplate?.tmplatPurpose === TEMPLATE_PURPOSE.PHONE_VERIFICATION
@@ -224,54 +218,7 @@ const SingleMessageSendDialog = ({
)}
</div>
<div className="space-y-2 rounded-md border p-4">
<p className="text-sm font-semibold">미리보기</p>
{!selectedTemplate && <p className="text-sm text-muted-foreground">선택된 템플릿이 없습니다.</p>}
{selectedTemplate && (
<>
{chnnlTy !== ChannelType.SMS && (
<div className="rounded border p-2 text-sm font-semibold">{resolvedTitle ? `제목: ${resolvedTitle}` : '(제목 없음)'}</div>
)}
{chnnlTy === ChannelType.SMS ? (
<div className="flex flex-col items-center">
<KriEditor
mode="sms"
value={substituteVariables((selectedTemplate as TemplateSms).tmplatBody ?? '', previewValues)}
onChange={() => {}}
isSmsReadOnly
smsPreviewSuffix={
selectedTemplate.tmplatPurpose === TEMPLATE_PURPOSE.PHONE_VERIFICATION
? PHONE_VERIFICATION_PREVIEW_SUFFIX
: undefined
}
placeholder="문자 내용을 입력해 주세요"
className="max-w-80 mx-0"
debounceMs={600}
smsTitle={resolvedTitle}
/>
</div>
) : (
<>
<div
className="rounded-md border bg-muted/30 p-3 text-sm"
dangerouslySetInnerHTML={{
__html: sanitizeEmailHtml(
substituteVariables(
selectedTemplate.tmplatBody || '(내용 없음)',
Object.fromEntries(Object.entries(previewValues).map(([key, val]) => [key, escapeHtml(val)])),
),
),
}}
/>
<TemplateAttachmentList
tmplatIdx={selectedTemplate.tmplatIdx}
atchFl={(selectedTemplate as TemplateEmailWithAttachments).atchFl}
/>
</>
)}
</>
)}
</div>
<MessageSendPreview chnnlTy={chnnlTy} template={selectedTemplate} variableValues={variableValues ?? {}} />
</KriDialog>
)
}

View File

@@ -27,6 +27,9 @@ export function KriEditorSms({
smsMaxBytes = 90,
lmsMaxBytes = 2000,
smsPreviewSuffix = '',
smsHasAttachment = false,
smsImages = [],
smsFrameClassName,
}: SmsEditorProps) {
const [text, setText] = React.useState(value || '')
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null)
@@ -36,7 +39,7 @@ export function KriEditorSms({
const textareaInsert = useTextareaInsert(textareaRef)
const previewText = smsPreviewSuffix ? `${text}\n${smsPreviewSuffix}` : text
const byteSize = React.useMemo(() => calculateBytes(previewText), [previewText])
const messageType: 'SMS' | 'LMS' = byteSize > smsMaxBytes || Boolean(smsTitle) ? 'LMS' : 'SMS'
const messageType: 'SMS' | 'LMS' = byteSize > smsMaxBytes || Boolean(smsTitle) || smsHasAttachment ? 'LMS' : 'SMS'
const maxBytes = messageType === 'SMS' ? smsMaxBytes : lmsMaxBytes
const commitText = React.useCallback((next: string, immediate = false) => {
@@ -82,17 +85,25 @@ 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={cn('relative h-[600px] w-full overflow-hidden rounded-[40px] border-8 border-gray-800 bg-white shadow-2xl', smsFrameClassName)}>
<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">
<div className="mb-3 flex items-center justify-between px-2">
<span className="text-xs font-medium text-gray-600">{byteSize}/{maxBytes}byte</span>
<span className={cn('rounded-md px-3 py-1 text-xs font-bold text-white', messageType === 'LMS' ? 'bg-blue-500' : 'bg-red-500')}>
{messageType}
{messageType === 'LMS' ? 'LMS/MMS' : 'SMS'}
</span>
</div>
<div className="flex flex-1 flex-col overflow-hidden rounded-2xl bg-white shadow-sm">
<div className={cn('flex flex-1 flex-col rounded-2xl bg-white shadow-sm', smsImages.length > 0 ? 'overflow-y-auto' : 'overflow-hidden')}>
{smsTitle ? <div className="px-4 pt-3 pb-2 text-sm font-bold text-gray-800">{smsTitle}</div> : null}
{smsImages.length > 0 ? (
<div className="flex shrink-0 flex-col gap-2 px-4 pt-3">
{smsImages.map((image) => (
// eslint-disable-next-line @next/next/no-img-element -- data/Object URL 미리보기라 next/image 최적화 대상이 아님
<img key={image.fileName} src={image.src} alt={image.fileName} title={image.fileName} className="w-full rounded-md object-contain" />
))}
</div>
) : null}
<textarea
ref={textareaRef}
className="w-full flex-1 resize-none bg-transparent p-4 text-sm leading-relaxed text-gray-700 outline-none"
@@ -105,7 +116,7 @@ export function KriEditorSms({
onBlur={() => flushChange(latestTextRef.current)}
placeholder={placeholder}
readOnly={isSmsReadOnly}
style={{ minHeight: smsTitle ? '320px' : '360px' }}
style={{ minHeight: smsImages.length > 0 ? '160px' : smsTitle ? '320px' : '360px' }}
{...textareaInsert.bindSelectionHandlers}
/>
{smsPreviewSuffix ? (

View File

@@ -50,6 +50,11 @@ export type KriEditorFontFamilyOption = {
value: string
}
export type KriEditorSmsImage = {
fileName: string
src: string
}
export type KriEditorProps = {
onEditorReady?: (editor: Editor | HTMLTextAreaElement | null) => void
onCommandReady?: (command: KriEditorCommand | null) => void
@@ -80,6 +85,12 @@ export type KriEditorProps = {
smsMaxBytes?: number
lmsMaxBytes?: number
smsPreviewSuffix?: string
/** 첨부파일이 있으면 길이·제목과 무관하게 LMS/MMS로 판정한다. */
smsHasAttachment?: boolean
/** 문자 미리보기의 제목과 본문 사이에 표시할 첨부 이미지 */
smsImages?: KriEditorSmsImage[]
/** 휴대폰 프레임 class (기본 높이 h-[600px] 조정 등) */
smsFrameClassName?: string
toolbar?: KriEditorToolbarConfig | false
fontFamilyOptions?: KriEditorFontFamilyOption[]
renderToolbarEnd?: (context: KriEditorToolbarContext) => ReactNode

View File

@@ -0,0 +1,105 @@
'use client'
import { ChannelType, type TemplateSms } from '@kri/common/noti-hub'
import { KriEditor } from '@/components/kri-editor'
import { applyLinkPreviewClass } from '@/components/kri-editor/utils/linkPreview'
import { sanitizeEmailHtml } from '@/components/message-template/emailHtmlPolicy'
import { normalizeQrCodeForEditor, renderQrCodePreviewHtml } from '@/components/message-template/qrcode'
import TemplateAttachmentList from '@/components/message-template/TemplateAttachmentList'
import { PHONE_VERIFICATION_PREVIEW_SUFFIX, TEMPLATE_PURPOSE } from '@/const/messageTemplateConst'
import { escapeHtml, substituteVariables } from '@/lib/variableSubstitution'
import { cn } from '@/lib/utils'
import { useTemplateAttachmentImagesQuery } from '@/query/message'
import type { TemplateEmailWithAttachments, TemplateSmsWithAttachments, TemplateWithPurpose } from '@/types/message'
// 다이얼로그(max-h 90vh)의 헤더·푸터·미리보기 제목을 뺀 높이에 맞추되,
// 본문 입력칸 최소 높이(360px)가 잘리지 않도록 480px 아래로는 줄이지 않는다.
const SMS_PREVIEW_FRAME_CLASS_NAME = 'h-[clamp(480px,calc(90vh-240px),600px)]'
export type MessageSendPreviewProps = {
chnnlTy: ChannelType
template: TemplateWithPurpose | null
/** 지정하면 [$변수] 토큰을 값으로 치환한다(없는 값은 빈 문자열). 생략하면 토큰을 그대로 보여준다. */
variableValues?: Record<string, string>
}
/**
* 문자/메일 발송 다이얼로그 공용 미리보기.
* 이메일 본문은 템플릿 관리 미리보기(KriEditor)와 같은 순서로 sanitize → 링크 스타일 → QR 예시 이미지 변환을 거친다.
*/
const MessageSendPreview = ({ chnnlTy, template, variableValues }: MessageSendPreviewProps) => {
const isSms = chnnlTy === ChannelType.SMS
const attachmentNames = template
? ((template as TemplateEmailWithAttachments | TemplateSmsWithAttachments).atchFl?.split('|').filter(Boolean) ?? [])
: []
const smsAttachmentImages = useTemplateAttachmentImagesQuery(
template?.tmplatIdx ?? 0,
isSms ? attachmentNames : [],
!!template,
)
const substitute = (contents: string, escape = false) => {
if (!variableValues) return contents
const values = escape
? Object.fromEntries(Object.entries(variableValues).map(([key, val]) => [key, escapeHtml(val)]))
: variableValues
return substituteVariables(contents, values)
}
const resolvedTitle = template ? substitute(template.tmplatTitle ?? '') : ''
return (
// min-w-0: 다이얼로그 grid 칸 너비를 넘지 않도록 한다.
<div className="min-w-0 space-y-2 rounded-md border p-4">
<p className="text-lg font-semibold">미리보기</p>
{!template && <p className="text-sm text-muted-foreground">선택된 템플릿이 없습니다.</p>}
{template && (
<>
{!isSms && (
<div className="rounded border p-2 text-lg font-semibold wrap-anywhere">{resolvedTitle ? `제목: ${resolvedTitle}` : '(제목 없음)'}</div>
)}
{/* 본문이 길어도 다이얼로그가 아닌 미리보기 영역에서만 스크롤되도록 한다.
문자는 휴대폰 프레임 내부에 자체 스크롤이 있으므로 프레임 높이만 줄이고 바깥 스크롤은 두지 않는다. */}
<div className={cn('space-y-2', !isSms && 'max-h-[60vh] overflow-y-auto')}>
{isSms ? (
<div className="flex flex-col items-center">
<KriEditor
mode="sms"
value={substitute((template as TemplateSms).tmplatBody ?? '')}
onChange={() => {}}
isSmsReadOnly
smsPreviewSuffix={
template.tmplatPurpose === TEMPLATE_PURPOSE.PHONE_VERIFICATION ? PHONE_VERIFICATION_PREVIEW_SUFFIX : undefined
}
placeholder="문자 내용을 입력해 주세요"
className="max-w-80 mx-0"
smsFrameClassName={SMS_PREVIEW_FRAME_CLASS_NAME}
debounceMs={600}
smsTitle={resolvedTitle}
smsHasAttachment={attachmentNames.length > 0}
smsImages={smsAttachmentImages}
/>
</div>
) : (
<>
<div
className="kri-editor-preview rounded-md border bg-muted/30 p-3 wrap-anywhere"
dangerouslySetInnerHTML={{
__html: renderQrCodePreviewHtml(
applyLinkPreviewClass(
sanitizeEmailHtml(normalizeQrCodeForEditor(substitute(template.tmplatBody ?? '', true)) || '(내용 없음)'),
),
),
}}
/>
<TemplateAttachmentList tmplatIdx={template.tmplatIdx} atchFl={attachmentNames.join('|')} />
</>
)}
</div>
</>
)}
</div>
)
}
export default MessageSendPreview

View File

@@ -13,9 +13,13 @@ import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
import {Label} from "@/components/ui/label";
import {KriSingleSelect} from "@/components/common/KriAutoComplete";
import {
EMAIL_TEMPLATE_ATTACHMENT_MAX_BYTES,
EMAIL_TEMPLATE_ATTACHMENT_MAX_COUNT,
PHONE_VERIFICATION_PREVIEW_SUFFIX,
TEMPLATE_ATTACHMENT_MAX_BYTES,
TEMPLATE_ATTACHMENT_MAX_COUNT,
SMS_TEMPLATE_ATTACHMENT_EXTENSION,
SMS_TEMPLATE_ATTACHMENT_MAX_BYTES,
SMS_TEMPLATE_ATTACHMENT_MAX_COUNT,
SMS_TEMPLATE_ATTACHMENT_MIME_TYPE,
TEMPLATE_PURPOSE,
TEMPLATE_PURPOSE_OPTIONS,
} from "@/const/messageTemplateConst";
@@ -32,7 +36,9 @@ import type { DataVerification } from "@kri/common";
import {COMMON_TEXT_REGEX} from "@/const/validationConst";
import {formatKoreanPhoneNumber} from "@/utils/phone";
import type {
TemplateAttachmentImage,
TemplateEmailWithAttachments,
TemplateSmsWithAttachments,
TemplateSummaryWithPurpose,
TemplateWithPurpose,
} from "@/types/message";
@@ -44,6 +50,7 @@ import {
useUpdateMainTemplateMutation,
useUploadTemplateBodyImageMutation,
useDownloadTemplateAttachmentMutation,
useTemplateAttachmentImagesQuery,
} from "@/query/message";
import {listHeader} from "@/types/list";
import {useListHeaderQuery} from "@/query/list";
@@ -71,6 +78,12 @@ interface MessageTemplateProps {
const MESSAGE_EDITOR_EXTENSIONS = [QrCode];
// 서버는 첨부 파일명 중복을 대소문자 구분 없이 판단한다.
const isSameFileName = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();
const isJpgFile = (file: File) =>
file.name.toLowerCase().endsWith(SMS_TEMPLATE_ATTACHMENT_EXTENSION) && file.type === SMS_TEMPLATE_ATTACHMENT_MIME_TYPE;
const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) => {
const { selectedProject } = useSelectedProject();
@@ -90,6 +103,8 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
const isSms = isSmsTemplate(defaultTemplate);
const chnnlTy: ChannelType = isSms ? ChannelType.SMS : ChannelType.EMAIL;
const attachmentMaxCount = isSms ? SMS_TEMPLATE_ATTACHMENT_MAX_COUNT : EMAIL_TEMPLATE_ATTACHMENT_MAX_COUNT;
const attachmentMaxBytes = isSms ? SMS_TEMPLATE_ATTACHMENT_MAX_BYTES : EMAIL_TEMPLATE_ATTACHMENT_MAX_BYTES;
// 유니온의 키를 합집합으로 뽑기
type KeysOfUnion<T> = T extends unknown ? keyof T : never;
@@ -113,13 +128,16 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
const listHderList = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data])
const surveys = useMemo<ProjectSurvey[]>(() => projectInfoQuery.data?.surveys ?? [], [projectInfoQuery.data?.surveys])
// 서버에 저장된 첨부파일명 목록 (파이프(|) 구분, 이메일 템플릿만 해당)
// 서버에 저장된 첨부파일명 목록 (파이프(|) 구분, 이메일·문자 템플릿 공통)
const existingAttachmentNames = useMemo<string[]>(() => {
if (isSmsTemplate(selectedTemplate)) return [];
const atchFl = (selectedTemplate as TemplateEmailWithAttachments).atchFl;
const atchFl = (selectedTemplate as TemplateEmailWithAttachments | TemplateSmsWithAttachments).atchFl;
return atchFl ? atchFl.split("|").filter(Boolean) : [];
}, [selectedTemplate]);
// 교체 대상(같은 이름의 새 파일)도 삭제 예정에 들어가 있으므로 여기서 제외된다.
const keptAttachmentNames = existingAttachmentNames.filter((name) => !deletedAttachmentNames.includes(name));
const attachmentCount = keptAttachmentNames.length + newAttachmentFiles.length;
const resetAttachmentDraft = () => {
setNewAttachmentFiles([]);
setDeletedAttachmentNames([]);
@@ -131,6 +149,21 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
const updateMainTemplateMutation = useUpdateMainTemplateMutation(prjctIdx, chnnlTy);
const uploadBodyImageMutation = useUploadTemplateBodyImageMutation(itrntPrjctCd);
// 문자 미리보기 첨부 이미지: 유지되는 기존 첨부는 서버에서, 새 파일은 로컬 Object URL로 표시한다.
const keptAttachmentImages = useTemplateAttachmentImagesQuery(
selectedTemplate.tmplatIdx ?? 0,
isSms ? keptAttachmentNames : [],
enabled,
);
const [newAttachmentImages, setNewAttachmentImages] = useState<TemplateAttachmentImage[]>([]);
useEffect(() => {
if (!isSms) return;
const images = newAttachmentFiles.map((file) => ({ fileName: file.name, src: URL.createObjectURL(file) }));
setNewAttachmentImages(images);
return () => images.forEach((image) => URL.revokeObjectURL(image.src));
}, [isSms, newAttachmentFiles]);
// 대표 템플릿 체크 상태(사용자 의도)
const [mainDesired, setMainDesired] = useState(false);
@@ -308,34 +341,40 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
const nextDeleted = [...deletedAttachmentNames];
for (const file of picked) {
if (isSms && !isJpgFile(file)) {
alert(`${file.name}: JPG(.jpg) 파일만 첨부할 수 있습니다.`);
continue;
}
if (file.size === 0) {
alert(`${file.name}: 빈 파일은 첨부할 수 없습니다.`);
continue;
}
if (file.size >= TEMPLATE_ATTACHMENT_MAX_BYTES) {
const alertFileSize = TEMPLATE_ATTACHMENT_MAX_BYTES / 1_000_000;
alert(`${file.name}: 파일 크기는 ${alertFileSize.toLocaleString()}MB 미만이어야 합니다.`);
if (file.size > attachmentMaxBytes) {
const sizeLimitText = isSms
? `${(SMS_TEMPLATE_ATTACHMENT_MAX_BYTES / 1024).toLocaleString()}KB 이하`
: `${(EMAIL_TEMPLATE_ATTACHMENT_MAX_BYTES / 1_000_000).toLocaleString()}MB 미만`;
alert(`${file.name}: 파일 크기는 ${sizeLimitText}여야 합니다.`);
continue;
}
if (nextFiles.some((f) => f.name === file.name)) {
if (nextFiles.some((f) => isSameFileName(f.name, file.name))) {
alert(`${file.name}: 이미 추가된 파일명입니다.`);
continue;
}
// 기존 첨부와 같은 이름이면 "교체"로 처리 (deleteFileNames에도 같은 이름을 포함해야 함)
const isReplacingExisting = existingAttachmentNames.includes(file.name) && !nextDeleted.includes(file.name);
// 기존 첨부와 같은 이름(대소문자 무시)이면 "교체"로 처리 (deleteFileNames에 기존 파일명을 포함해야 함)
const replacedExistingName = existingAttachmentNames.find((name) => isSameFileName(name, file.name));
const isReplacingExisting = !!replacedExistingName && !nextDeleted.includes(replacedExistingName);
const finalNames = new Set([
...existingAttachmentNames.filter((name) => !nextDeleted.includes(name) && name !== file.name),
...nextFiles.map((f) => f.name),
file.name,
]);
if (finalNames.size > TEMPLATE_ATTACHMENT_MAX_COUNT) {
alert(`첨부파일은 최대 ${TEMPLATE_ATTACHMENT_MAX_COUNT}개까지 가능합니다.`);
const finalCount =
existingAttachmentNames.filter((name) => !nextDeleted.includes(name) && name !== replacedExistingName).length
+ nextFiles.length
+ 1;
if (finalCount > attachmentMaxCount) {
alert(`첨부파일은 최대 ${attachmentMaxCount}개까지 가능합니다.`);
continue;
}
if (isReplacingExisting) nextDeleted.push(file.name);
if (isReplacingExisting) nextDeleted.push(replacedExistingName);
nextFiles.push(file);
}
@@ -346,8 +385,9 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
const handleRemoveNewAttachmentFile = (fileName: string) => {
setNewAttachmentFiles((prev) => prev.filter((f) => f.name !== fileName));
// 교체 목적으로 같은 이름을 삭제 예정에 넣었던 것이라면, 새 파일을 취소했으니 삭제 예정도 취소한다.
if (existingAttachmentNames.includes(fileName)) {
setDeletedAttachmentNames((prev) => prev.filter((name) => name !== fileName));
const replacedExistingName = existingAttachmentNames.find((name) => isSameFileName(name, fileName));
if (replacedExistingName) {
setDeletedAttachmentNames((prev) => prev.filter((name) => name !== replacedExistingName));
}
};
@@ -530,7 +570,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
/>
{isSmsTemplate(selectedTemplate) &&
<p className="text-sm text-red-600 font-medium">
⚠️ 제목이 있으면 본문 길이와 상관없이 LMS로 발송 됩니다.
⚠️ 제목이 있으면 본문 길이와 상관없이 LMS/MMS로 발송 됩니다.
</p>
}
</div>
@@ -619,12 +659,13 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
⚠️ &lt;map&gt;, &lt;area&gt; 가 사용된 경우 해당 영역이 반투명하게 보여집니다.
</p>
)}
</>
)}
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-base">
첨부파일 ({existingAttachmentNames.filter((name) => !deletedAttachmentNames.includes(name)).length + newAttachmentFiles.length}/{TEMPLATE_ATTACHMENT_MAX_COUNT})
{isSms ? "이미지 첨부" : "첨부파일"} ({attachmentCount}/{attachmentMaxCount})
</Label>
<Button type="button" variant="outline" size="sm" className="gap-2" onClick={handlePickAttachmentFiles}>
<Paperclip className="h-4 w-4" />
@@ -636,6 +677,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
ref={attachmentInputRef}
type="file"
multiple
accept={isSms ? `${SMS_TEMPLATE_ATTACHMENT_EXTENSION},${SMS_TEMPLATE_ATTACHMENT_MIME_TYPE}` : undefined}
className="hidden"
onChange={handleAttachmentFilesSelected}
/>
@@ -644,7 +686,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
<ul className="space-y-1 rounded-md border p-2">
{existingAttachmentNames.map((name) => {
const markedForDelete = deletedAttachmentNames.includes(name);
const isReplaced = newAttachmentFiles.some((f) => f.name === name);
const isReplaced = newAttachmentFiles.some((f) => isSameFileName(f.name, name));
return (
<li key={`existing-${name}`} className="flex items-center justify-between gap-2 text-sm">
<Button
@@ -696,17 +738,26 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
</ul>
)}
<p className="text-xs text-muted-foreground">
파일당 {(TEMPLATE_ATTACHMENT_MAX_BYTES / 1000).toLocaleString()}KB 미만, 최대 {TEMPLATE_ATTACHMENT_MAX_COUNT}개까지 첨부할 수 있습니다.
</p>
{isSms ? (
<p className="text-xs text-muted-foreground">
JPG(.jpg) 파일만, 파일당 {(SMS_TEMPLATE_ATTACHMENT_MAX_BYTES / 1024).toLocaleString()}KB 이하, 최대 {SMS_TEMPLATE_ATTACHMENT_MAX_COUNT}개까지 첨부할 수 있습니다.
</p>
) : (
<p className="text-xs text-muted-foreground">
파일당 {(EMAIL_TEMPLATE_ATTACHMENT_MAX_BYTES / 1000).toLocaleString()}KB 미만, 최대 {EMAIL_TEMPLATE_ATTACHMENT_MAX_COUNT}개까지 첨부할 수 있습니다.
</p>
)}
{isSms && attachmentCount > 0 && (
<p className="text-xs text-red-600">
⚠️ 이미지가 첨부되면 본문 길이와 상관없이 LMS/MMS로 저장됩니다.
</p>
)}
{selectedTemplate.tmplatIdx && (
<p className="text-xs text-red-600">
⚠️ 복사 후 저장시 첨부파일은 복사 되지 않습니다.
</p>
)}
</div>
</>
)}
</div>
{isSms && (
@@ -716,7 +767,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
</p>
<KriEditor
mode="sms"
label={selectedTemplate.tmplatTy === MessageType.SMS ? "️️* 발송 시 길이에 따라 LMS로 발송 될 수 있음" : undefined}
label={selectedTemplate.tmplatTy === MessageType.SMS ? "️️* 발송 시 길이에 따라 LMS/MMS로 발송 될 수 있음" : undefined}
value={(selectedTemplate as TemplateSms).tmplatBody ?? ""}
onChange={(html: string) => setTemplateBody(html)}
placeholder="문자 내용을 입력해 주세요"
@@ -732,6 +783,8 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
: undefined
}
changeSmsType={(smsTypeString) => setSmsType(smsTypeString)}
smsHasAttachment={attachmentCount > 0}
smsImages={[...keptAttachmentImages, ...newAttachmentImages]}
/>
</div>
)}

View File

@@ -7,7 +7,7 @@ export const SMS_TYPE_ORDER = [
export const SMS_TYPE_LABEL = {
[MessageType.SMS]: "SMS",
[MessageType.LMS_MMS]: "LMS",
[MessageType.LMS_MMS]: "LMS/MMS",
} as const satisfies Record<SmsType, string>;
export const SMS_TYPE_OPTIONS = [
@@ -27,6 +27,12 @@ export const TEMPLATE_PURPOSE_OPTIONS = [
export const PHONE_VERIFICATION_PREVIEW_SUFFIX = "인증번호는 [######] 입니다.";
// 이메일 템플릿 첨부파일 제한 (첨부파일은 이메일 템플릿만 지원)
export const TEMPLATE_ATTACHMENT_MAX_COUNT = 5;
export const TEMPLATE_ATTACHMENT_MAX_BYTES = 1_000_000;
// 이메일 템플릿 첨부파일 제한 (파일당 이하 기준)
export const EMAIL_TEMPLATE_ATTACHMENT_MAX_COUNT = 5;
export const EMAIL_TEMPLATE_ATTACHMENT_MAX_BYTES = 1_000_000;
// 문자 템플릿 첨부파일 제한 (JPG만 허용, 파일당 이하 기준, 첨부 시 LMS/MMS로 저장됨)
export const SMS_TEMPLATE_ATTACHMENT_MAX_COUNT = 3;
export const SMS_TEMPLATE_ATTACHMENT_MAX_BYTES = 61_440;
export const SMS_TEMPLATE_ATTACHMENT_EXTENSION = ".jpg";
export const SMS_TEMPLATE_ATTACHMENT_MIME_TYPE = "image/jpeg";

View File

@@ -39,4 +39,22 @@ export function useCtiConnection() {
agentName,
});
}, [hasUser, clientId, internalNo, externalNo, agentName]);
// 뒤로/앞으로 가기로 bfcache에 들어갔다가 돌아오면 React 상태가 그대로 복원되어 위 effect가 다시 실행되지 않는다.
// 떠날 때 CTI 서버에 Logout, 돌아올 때 다시 Login 하여 새로고침 없이 전화걸기를 쓸 수 있게 한다.
useEffect(() => {
const handlePageHide = (event: PageTransitionEvent) => {
if (event.persisted) ctiClient.suspendForPageHide();
};
const handlePageShow = (event: PageTransitionEvent) => {
if (event.persisted) ctiClient.resumeFromPageShow();
};
window.addEventListener("pagehide", handlePageHide);
window.addEventListener("pageshow", handlePageShow);
return () => {
window.removeEventListener("pagehide", handlePageHide);
window.removeEventListener("pageshow", handlePageShow);
};
}, []);
}

View File

@@ -688,9 +688,36 @@ const connectAndLogin = (params: CtiLoginParams) => {
openSocketAndLogin(params);
};
// bfcache 진입 직전(pagehide, persisted): 열려 있는 소켓으로 Logout을 보내고 소켓만 정리한다.
// 로그인 정보는 복귀(pageshow) 시 다시 로그인하기 위해 유지한다.
// 통화 중이면 통화 처리가 꼬이지 않도록 Logout은 생략한다.
const suspendForPageHide = () => {
if (!currentLoginParams) return;
stopReconnectLoop();
if (currentAgentLoginId && connectionState === "open") {
if (isCallInProgress()) {
console.log("[CTI][TEMP_LOG] pagehide logout skipped, call is in progress"); // TEMP_CTI_LOG
} else {
send({ ZCommand: "Logout", AgentLoginID: currentAgentLoginId });
}
}
teardownSocket();
};
// bfcache 복귀(pageshow, persisted): 유지해 둔 로그인 정보로 다시 연결해 로그인한다.
const resumeFromPageShow = () => {
const params = currentLoginParams;
if (!params) return;
if (connectionState === "open" || connectionState === "connecting") return;
console.log("[CTI][TEMP_LOG] pageshow resume, reconnecting"); // TEMP_CTI_LOG
connectAndLogin(params);
};
export const ctiClient = {
connectAndLogin,
logout,
suspendForPageHide,
resumeFromPageShow,
subscribe: (listener: () => void) => {
listeners.add(listener);
return () => listeners.delete(listener);

View File

@@ -74,6 +74,9 @@ export const qk = {
templateList: (chnnlTy: ChannelType, itrntPrjctCd: string) =>
["message-template", "list", chnnlTy, itrntPrjctCd] as const,
template: (tmplatIdx: number) => ["message-template", "detail", tmplatIdx] as const,
templateAttachments: (tmplatIdx: number) => ["message-template", "attachment", tmplatIdx] as const,
templateAttachment: (tmplatIdx: number, fileName: string) =>
["message-template", "attachment", tmplatIdx, fileName] as const,
bulkSendList: (sendTy: number, reqstSvc: string, prjctCd: string) =>
["message-report", "bulk-list", sendTy, reqstSvc, prjctCd] as const,

View File

@@ -1,6 +1,6 @@
"use client";
import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { keepPreviousData, useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
import { nextApi } from "@/lib/http-client";
import { qk } from "@/query/key/keys";
import type {
@@ -19,7 +19,7 @@ import type {
SendResultInfo,
SendSingleResponse,
} from "@/types/message";
import type { TemplateSummaryWithPurpose, TemplateWithPurpose } from "@/types/message";
import type { TemplateAttachmentImage, TemplateSummaryWithPurpose, TemplateWithPurpose } from "@/types/message";
export function useTemplateListQuery(chnnlTy: ChannelType, itrntPrjctCd: string, enabled: boolean) {
return useQuery({
@@ -79,6 +79,8 @@ export function useSaveTemplateMutation(chnnlTy: ChannelType, itrntPrjctCd: stri
onSuccess: (res) => {
if (res.tmplatIdx) {
qc.setQueryData(qk.template(res.tmplatIdx), res);
// 같은 파일명으로 교체될 수 있으므로 첨부 이미지 미리보기 캐시를 비운다.
qc.removeQueries({ queryKey: qk.templateAttachments(res.tmplatIdx) });
}
qc.invalidateQueries({ queryKey: qk.templateList(chnnlTy, itrntPrjctCd) });
},
@@ -97,6 +99,38 @@ export function useDownloadTemplateAttachmentMutation(tmplatIdx: number) {
});
}
const readBlobAsDataUrl = (blob: Blob) =>
new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(blob);
});
/**
* 문자 템플릿 첨부 JPG 미리보기 (파일별 캐시, 불러온 이미지만 fileNames 순서대로 반환)
* data URL로 캐시하므로 Object URL 해제가 필요 없다.
*/
export function useTemplateAttachmentImagesQuery(tmplatIdx: number, fileNames: string[], enabled: boolean) {
return useQueries({
queries: fileNames.map((fileName) => ({
queryKey: qk.templateAttachment(tmplatIdx, fileName),
queryFn: async () => {
const buffer = await nextApi.get<ArrayBuffer>(
`/message-template/${tmplatIdx}/attachment?fileName=${encodeURIComponent(fileName)}`,
{ expectBinary: true },
);
return readBlobAsDataUrl(new Blob([buffer], { type: "image/jpeg" }));
},
enabled: enabled && tmplatIdx > 0,
staleTime: 60_000,
retry: 1,
})),
combine: (results): TemplateAttachmentImage[] =>
results.flatMap((result, i) => (result.data ? [{ fileName: fileNames[i], src: result.data }] : [])),
});
}
export function useUpdateMainTemplateMutation(prjctIdx: number, chnnlTy: ChannelType) {
const qc = useQueryClient();
const key = qk.mainTemplate(prjctIdx, chnnlTy);

View File

@@ -1,4 +1,4 @@
import type { Template, TemplateEmail, TemplateSummary } from '@kri/common/noti-hub';
import type { Template, TemplateEmail, TemplateSms, TemplateSummary } from '@kri/common/noti-hub';
import type { ListFilter } from './list';
export type TemplatePurpose = 0 | 1;
@@ -22,6 +22,21 @@ export type TemplateEmailWithAttachments = TemplateEmail & {
atchFl?: string;
};
/**
* 문자 템플릿 JPG 첨부파일명 목록 (TemplateEmailWithAttachments와 동일하게 조회 응답 전용).
* 첨부가 하나라도 있으면 서버가 LMS_MMS로 저장한다.
*/
export type TemplateSmsWithAttachments = TemplateSms & {
tmplatPurpose: TemplatePurpose;
atchFl?: string;
};
/** 문자 미리보기에 표시할 첨부 이미지 (src는 data URL 또는 Object URL) */
export type TemplateAttachmentImage = {
fileName: string;
src: string;
};
export type PhoneVerificationSendData = {
verificationId: string;
expireDt: string;