260806_01_ENH: 이메일 첨부파일 등록 추가 #21
@@ -11,6 +11,19 @@ export const GET = async (req: NextRequest, context: RouteContext) => {
|
|||||||
const [action] = slug;
|
const [action] = slug;
|
||||||
const notihubApi = await createNotihubApi();
|
const notihubApi = await createNotihubApi();
|
||||||
|
|
||||||
|
if(slug.length === 2 && slug[1] === "attachment"){
|
||||||
|
const fileName = searchParams.get("fileName");
|
||||||
|
if (!fileName) {
|
||||||
|
return NextResponse.json({ message: "fileName은 필수입니다." }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await notihubApi.get<ArrayBuffer>(
|
||||||
|
`/template/${slug[0]}/attachment?fileName=${encodeURIComponent(fileName)}`,
|
||||||
|
{ expectBinary: true },
|
||||||
|
);
|
||||||
|
return new NextResponse(result, { status: 200, headers: { "Content-Type": "application/octet-stream" } });
|
||||||
|
}
|
||||||
|
|
||||||
if(slug.length === 1){
|
if(slug.length === 1){
|
||||||
const result = await notihubApi.get<Template>(
|
const result = await notihubApi.get<Template>(
|
||||||
`/template/${slug[0]}`,
|
`/template/${slug[0]}`,
|
||||||
@@ -60,15 +73,15 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if(!action){
|
if(!action){
|
||||||
const body = await req.json().catch(() => null);
|
const formData = await req.formData().catch(() => null);
|
||||||
if (!body) {
|
if (!formData) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ message: "요청 바디가 없습니다." },
|
{ message: "요청 바디가 없습니다." },
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await notihubApi.put<Template>(`/template`, body);
|
const result = await notihubApi.putForm<Template>(`/template`, formData);
|
||||||
return NextResponse.json(result, { status: 200 });
|
return NextResponse.json(result, { status: 200 });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,15 +99,15 @@ export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
|||||||
const notihubApi = await createNotihubApi();
|
const notihubApi = await createNotihubApi();
|
||||||
|
|
||||||
if(!action){
|
if(!action){
|
||||||
const body = await req.json().catch(() => null);
|
const formData = await req.formData().catch(() => null);
|
||||||
if (!body) {
|
if (!formData) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ message: "요청 바디가 없습니다." },
|
{ message: "요청 바디가 없습니다." },
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await notihubApi.patch<Template>(`/template`, body);
|
const result = await notihubApi.request<Template>(`/template`, { method: "PATCH", form: formData });
|
||||||
return NextResponse.json(result, { status: 200 });
|
return NextResponse.json(result, { status: 200 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ import ApplyFilterOption, { validateApplyFilterTarget } from './ListDialogOption
|
|||||||
import { KriEditor } from '@/components/kri-editor'
|
import { KriEditor } from '@/components/kri-editor'
|
||||||
import { normalizeQrCodeForEditor, QR_CODE_ALLOWED_HTML, renderQrCodePreviewHtml } from '@/components/message-template/qrcode'
|
import { normalizeQrCodeForEditor, QR_CODE_ALLOWED_HTML, renderQrCodePreviewHtml } from '@/components/message-template/qrcode'
|
||||||
import { applyLinkPreviewClass } from '@/components/kri-editor/utils/linkPreview'
|
import { applyLinkPreviewClass } from '@/components/kri-editor/utils/linkPreview'
|
||||||
|
import TemplateAttachmentList from '@/components/message-template/TemplateAttachmentList'
|
||||||
|
import type { TemplateEmailWithAttachments } from '@/types/message'
|
||||||
|
|
||||||
export type MessageSendMode = 'email' | 'sms'
|
export type MessageSendMode = 'email' | 'sms'
|
||||||
|
|
||||||
@@ -339,19 +341,25 @@ const MessageSendDialog = ({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div
|
<>
|
||||||
className={cn('kri-editor-preview rounded-md border bg-muted/30 p-3')}
|
<div
|
||||||
dangerouslySetInnerHTML={{
|
className={cn('kri-editor-preview rounded-md border bg-muted/30 p-3')}
|
||||||
__html: renderQrCodePreviewHtml(
|
dangerouslySetInnerHTML={{
|
||||||
applyLinkPreviewClass(
|
__html: renderQrCodePreviewHtml(
|
||||||
sanitizeHtmlForPreview(
|
applyLinkPreviewClass(
|
||||||
normalizeQrCodeForEditor(selectedTemplate.tmplatBody) || '(내용 없음)',
|
sanitizeHtmlForPreview(
|
||||||
QR_CODE_ALLOWED_HTML,
|
normalizeQrCodeForEditor(selectedTemplate.tmplatBody) || '(내용 없음)',
|
||||||
|
QR_CODE_ALLOWED_HTML,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
}}
|
||||||
}}
|
/>
|
||||||
/>
|
<TemplateAttachmentList
|
||||||
|
tmplatIdx={selectedTemplate.tmplatIdx}
|
||||||
|
atchFl={(selectedTemplate as TemplateEmailWithAttachments).atchFl}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -19,7 +19,8 @@ import { sanitizeHtmlForPreview } from '@/components/kri-editor/utils/sanitizeHt
|
|||||||
import { KriEditor } from '@/components/kri-editor'
|
import { KriEditor } from '@/components/kri-editor'
|
||||||
import { getNearestFutureDateTime } from '@/lib/datetime'
|
import { getNearestFutureDateTime } from '@/lib/datetime'
|
||||||
import type { DialogId } from '@/store/jotai/dialog'
|
import type { DialogId } from '@/store/jotai/dialog'
|
||||||
import type { MessageSendChannel } from '@/types/message'
|
import type { MessageSendChannel, TemplateEmailWithAttachments } from '@/types/message'
|
||||||
|
import TemplateAttachmentList from '@/components/message-template/TemplateAttachmentList'
|
||||||
|
|
||||||
const titleMap: Record<MessageSendChannel, string> = {
|
const titleMap: Record<MessageSendChannel, string> = {
|
||||||
email: '메일 발송',
|
email: '메일 발송',
|
||||||
@@ -214,10 +215,16 @@ const SingleMessageSendDialog = ({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div
|
<>
|
||||||
className="rounded-md border bg-muted/30 p-3 text-sm"
|
<div
|
||||||
dangerouslySetInnerHTML={{ __html: sanitizeHtmlForPreview(selectedTemplate.tmplatBody || '(내용 없음)') }}
|
className="rounded-md border bg-muted/30 p-3 text-sm"
|
||||||
/>
|
dangerouslySetInnerHTML={{ __html: sanitizeHtmlForPreview(selectedTemplate.tmplatBody || '(내용 없음)') }}
|
||||||
|
/>
|
||||||
|
<TemplateAttachmentList
|
||||||
|
tmplatIdx={selectedTemplate.tmplatIdx}
|
||||||
|
atchFl={(selectedTemplate as TemplateEmailWithAttachments).atchFl}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -10,20 +10,23 @@ import {
|
|||||||
TemplateSms,
|
TemplateSms,
|
||||||
TemplateSummary
|
TemplateSummary
|
||||||
} from "@kri/common/noti-hub";
|
} from "@kri/common/noti-hub";
|
||||||
|
import {Paperclip, X} from "lucide-react";
|
||||||
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
|
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
|
||||||
import {Label} from "@/components/ui/label";
|
import {Label} from "@/components/ui/label";
|
||||||
import {KriSingleSelect} from "@/components/common/KriAutoComplete";
|
import {KriSingleSelect} from "@/components/common/KriAutoComplete";
|
||||||
import {SMS_TYPE_OPTIONS} from "@/const/messageTemplateConst";
|
import {SMS_TYPE_OPTIONS, TEMPLATE_ATTACHMENT_MAX_BYTES, TEMPLATE_ATTACHMENT_MAX_COUNT} from "@/const/messageTemplateConst";
|
||||||
import {Input} from "@/components/ui/input";
|
import {Input} from "@/components/ui/input";
|
||||||
import {Checkbox} from "@/components/ui/checkbox";
|
import {Checkbox} from "@/components/ui/checkbox";
|
||||||
import {KriEditor, KriEditorCommand} from "@/components/kri-editor";
|
import {KriEditor, KriEditorCommand} from "@/components/kri-editor";
|
||||||
import {Button} from "@/components/ui/button";
|
import {Button} from "@/components/ui/button";
|
||||||
import { isBlank } from "@kri/common";
|
import { isBlank } from "@kri/common";
|
||||||
|
import { downloadFile } from "@kri/common/browser";
|
||||||
import {cn} from "@/lib/utils";
|
import {cn} from "@/lib/utils";
|
||||||
import {ProjectMainTemplateUpdateRequest, ProjectSurvey} from "@/types/project";
|
import {ProjectMainTemplateUpdateRequest, ProjectSurvey} from "@/types/project";
|
||||||
import type { DataVerification } from "@kri/common";
|
import type { DataVerification } from "@kri/common";
|
||||||
import {COMMON_TEXT_REGEX} from "@/const/validationConst";
|
import {COMMON_TEXT_REGEX} from "@/const/validationConst";
|
||||||
import {formatKoreanPhoneNumber} from "@/utils/phone";
|
import {formatKoreanPhoneNumber} from "@/utils/phone";
|
||||||
|
import type {TemplateEmailWithAttachments} from "@/types/message";
|
||||||
import {
|
import {
|
||||||
useTemplateListQuery,
|
useTemplateListQuery,
|
||||||
useMainTemplateIdxQuery,
|
useMainTemplateIdxQuery,
|
||||||
@@ -31,6 +34,7 @@ import {
|
|||||||
useSaveTemplateMutation,
|
useSaveTemplateMutation,
|
||||||
useUpdateMainTemplateMutation,
|
useUpdateMainTemplateMutation,
|
||||||
useUploadTemplateBodyImageMutation,
|
useUploadTemplateBodyImageMutation,
|
||||||
|
useDownloadTemplateAttachmentMutation,
|
||||||
} from "@/query/message";
|
} from "@/query/message";
|
||||||
import {listHeader} from "@/types/list";
|
import {listHeader} from "@/types/list";
|
||||||
import {useListHeaderQuery} from "@/query/list";
|
import {useListHeaderQuery} from "@/query/list";
|
||||||
@@ -61,6 +65,11 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
|||||||
const [selectedTemplate, setSelectedTemplate] = useState<Template>(defaultTemplate);
|
const [selectedTemplate, setSelectedTemplate] = useState<Template>(defaultTemplate);
|
||||||
const [selectedTemplateIdx, setSelectedTemplateIdx] = useState<number | null>(null);
|
const [selectedTemplateIdx, setSelectedTemplateIdx] = useState<number | null>(null);
|
||||||
|
|
||||||
|
// 이메일 첨부파일 draft (신규 첨부 / 기존 첨부 삭제 예정). 저장 성공 시, 템플릿 전환 시 초기화된다.
|
||||||
|
const [newAttachmentFiles, setNewAttachmentFiles] = useState<File[]>([]);
|
||||||
|
const [deletedAttachmentNames, setDeletedAttachmentNames] = useState<string[]>([]);
|
||||||
|
const attachmentInputRef = useRef<HTMLInputElement | null>(null);
|
||||||
|
|
||||||
const isSmsTemplate = (t: Template): t is TemplateSms =>
|
const isSmsTemplate = (t: Template): t is TemplateSms =>
|
||||||
(SMS_TYPE_ARRAY as readonly MessageType[]).includes(t.tmplatTy);
|
(SMS_TYPE_ARRAY as readonly MessageType[]).includes(t.tmplatTy);
|
||||||
|
|
||||||
@@ -89,8 +98,21 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
|||||||
const listHderList = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data])
|
const listHderList = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data])
|
||||||
const surveys = useMemo<ProjectSurvey[]>(() => projectInfoQuery.data?.surveys ?? [], [projectInfoQuery.data?.surveys])
|
const surveys = useMemo<ProjectSurvey[]>(() => projectInfoQuery.data?.surveys ?? [], [projectInfoQuery.data?.surveys])
|
||||||
|
|
||||||
|
// 서버에 저장된 첨부파일명 목록 (파이프(|) 구분, 이메일 템플릿만 해당)
|
||||||
|
const existingAttachmentNames = useMemo<string[]>(() => {
|
||||||
|
if (isSmsTemplate(selectedTemplate)) return [];
|
||||||
|
const atchFl = (selectedTemplate as TemplateEmailWithAttachments).atchFl;
|
||||||
|
return atchFl ? atchFl.split("|").filter(Boolean) : [];
|
||||||
|
}, [selectedTemplate]);
|
||||||
|
|
||||||
|
const resetAttachmentDraft = () => {
|
||||||
|
setNewAttachmentFiles([]);
|
||||||
|
setDeletedAttachmentNames([]);
|
||||||
|
};
|
||||||
|
|
||||||
// Mutations
|
// Mutations
|
||||||
const saveTemplateMutation = useSaveTemplateMutation(chnnlTy, itrntPrjctCd);
|
const saveTemplateMutation = useSaveTemplateMutation(chnnlTy, itrntPrjctCd);
|
||||||
|
const downloadAttachmentMutation = useDownloadTemplateAttachmentMutation(selectedTemplate.tmplatIdx ?? 0);
|
||||||
const updateMainTemplateMutation = useUpdateMainTemplateMutation(prjctIdx, chnnlTy);
|
const updateMainTemplateMutation = useUpdateMainTemplateMutation(prjctIdx, chnnlTy);
|
||||||
const uploadBodyImageMutation = useUploadTemplateBodyImageMutation(itrntPrjctCd);
|
const uploadBodyImageMutation = useUploadTemplateBodyImageMutation(itrntPrjctCd);
|
||||||
|
|
||||||
@@ -111,6 +133,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
|||||||
setSelectedTemplate(projectDefaultTemplate);
|
setSelectedTemplate(projectDefaultTemplate);
|
||||||
setMainDesired(false);
|
setMainDesired(false);
|
||||||
mainTemplateAppliedRef.current = false;
|
mainTemplateAppliedRef.current = false;
|
||||||
|
resetAttachmentDraft();
|
||||||
|
|
||||||
}, [selectedProject, defaultTemplate]);
|
}, [selectedProject, defaultTemplate]);
|
||||||
|
|
||||||
@@ -127,6 +150,7 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
|||||||
if (!d) return;
|
if (!d) return;
|
||||||
if (selectedTemplateIdx && d.tmplatIdx === selectedTemplateIdx) {
|
if (selectedTemplateIdx && d.tmplatIdx === selectedTemplateIdx) {
|
||||||
setSelectedTemplate(d);
|
setSelectedTemplate(d);
|
||||||
|
resetAttachmentDraft();
|
||||||
}
|
}
|
||||||
}, [templateDetailQuery.data, selectedTemplateIdx]);
|
}, [templateDetailQuery.data, selectedTemplateIdx]);
|
||||||
|
|
||||||
@@ -207,12 +231,14 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
|||||||
setSelectedTemplateIdx(null);
|
setSelectedTemplateIdx(null);
|
||||||
setSelectedTemplate(projectDefaultTemplate);
|
setSelectedTemplate(projectDefaultTemplate);
|
||||||
setMainDesired(false);
|
setMainDesired(false);
|
||||||
|
resetAttachmentDraft();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const idx = Number(templateIdxString);
|
const idx = Number(templateIdxString);
|
||||||
if (!Number.isFinite(idx)) return;
|
if (!Number.isFinite(idx)) return;
|
||||||
setSelectedTemplateIdx(idx);
|
setSelectedTemplateIdx(idx);
|
||||||
|
resetAttachmentDraft();
|
||||||
};
|
};
|
||||||
|
|
||||||
const toggleMainTemplate = async () => {
|
const toggleMainTemplate = async () => {
|
||||||
@@ -254,6 +280,78 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
|||||||
[selectedProject, uploadBodyImageMutation]
|
[selectedProject, uploadBodyImageMutation]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const handlePickAttachmentFiles = () => {
|
||||||
|
attachmentInputRef.current?.click();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAttachmentFilesSelected = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const picked = Array.from(e.target.files ?? []);
|
||||||
|
e.target.value = "";
|
||||||
|
if (picked.length === 0) return;
|
||||||
|
|
||||||
|
const nextFiles = [...newAttachmentFiles];
|
||||||
|
const nextDeleted = [...deletedAttachmentNames];
|
||||||
|
|
||||||
|
for (const file of picked) {
|
||||||
|
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 미만이어야 합니다.`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (nextFiles.some((f) => f.name === file.name)) {
|
||||||
|
alert(`${file.name}: 이미 추가된 파일명입니다.`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 기존 첨부와 같은 이름이면 "교체"로 처리 (deleteFileNames에도 같은 이름을 포함해야 함)
|
||||||
|
const isReplacingExisting = existingAttachmentNames.includes(file.name) && !nextDeleted.includes(file.name);
|
||||||
|
|
||||||
|
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}개까지 가능합니다.`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isReplacingExisting) nextDeleted.push(file.name);
|
||||||
|
nextFiles.push(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
setNewAttachmentFiles(nextFiles);
|
||||||
|
setDeletedAttachmentNames(nextDeleted);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemoveNewAttachmentFile = (fileName: string) => {
|
||||||
|
setNewAttachmentFiles((prev) => prev.filter((f) => f.name !== fileName));
|
||||||
|
// 교체 목적으로 같은 이름을 삭제 예정에 넣었던 것이라면, 새 파일을 취소했으니 삭제 예정도 취소한다.
|
||||||
|
if (existingAttachmentNames.includes(fileName)) {
|
||||||
|
setDeletedAttachmentNames((prev) => prev.filter((name) => name !== fileName));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDownloadAttachment = async (fileName: string) => {
|
||||||
|
try {
|
||||||
|
const buffer = await downloadAttachmentMutation.mutateAsync(fileName);
|
||||||
|
downloadFile(new Blob([buffer], { type: "application/octet-stream" }), fileName);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
alert("첨부파일 다운로드에 실패했습니다.");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleToggleDeleteExistingAttachment = (fileName: string) => {
|
||||||
|
setDeletedAttachmentNames((prev) =>
|
||||||
|
prev.includes(fileName) ? prev.filter((name) => name !== fileName) : [...prev, fileName],
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
const submitTemplate = async (method: "put" | "patch") => {
|
const submitTemplate = async (method: "put" | "patch") => {
|
||||||
const v = validateTemplate(selectedTemplate);
|
const v = validateTemplate(selectedTemplate);
|
||||||
if (!v.success) {
|
if (!v.success) {
|
||||||
@@ -272,10 +370,14 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
|||||||
const res = await saveTemplateMutation.mutateAsync({
|
const res = await saveTemplateMutation.mutateAsync({
|
||||||
method,
|
method,
|
||||||
template: templateToSave,
|
template: templateToSave,
|
||||||
|
newFiles: newAttachmentFiles,
|
||||||
|
// 신규 생성(복사 포함)에서는 deleteFileNames를 사용하지 않는다.
|
||||||
|
deleteFileNames: method === "patch" ? deletedAttachmentNames : undefined,
|
||||||
});
|
});
|
||||||
|
|
||||||
setSelectedTemplate(res);
|
setSelectedTemplate(res);
|
||||||
setSelectedTemplateIdx(res.tmplatIdx ?? null);
|
setSelectedTemplateIdx(res.tmplatIdx ?? null);
|
||||||
|
resetAttachmentDraft();
|
||||||
|
|
||||||
// 대표 템플릿 의도가 true면 저장된 템플릿을 대표로 반영
|
// 대표 템플릿 의도가 true면 저장된 템플릿을 대표로 반영
|
||||||
if (mainDesired && selectedProject?.prjctIdx && res.tmplatIdx) {
|
if (mainDesired && selectedProject?.prjctIdx && res.tmplatIdx) {
|
||||||
@@ -453,6 +555,93 @@ const MessageTemplate = ({ pageTitle, defaultTemplate }: MessageTemplateProps) =
|
|||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{!isSms && (
|
||||||
|
<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})
|
||||||
|
</Label>
|
||||||
|
<Button type="button" variant="outline" size="sm" className="gap-2" onClick={handlePickAttachmentFiles}>
|
||||||
|
<Paperclip className="h-4 w-4" />
|
||||||
|
파일 추가
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<input
|
||||||
|
ref={attachmentInputRef}
|
||||||
|
type="file"
|
||||||
|
multiple
|
||||||
|
className="hidden"
|
||||||
|
onChange={handleAttachmentFilesSelected}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{(existingAttachmentNames.length > 0 || newAttachmentFiles.length > 0) && (
|
||||||
|
<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);
|
||||||
|
return (
|
||||||
|
<li key={`existing-${name}`} className="flex items-center justify-between gap-2 text-sm">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="link"
|
||||||
|
className={cn(
|
||||||
|
"h-auto max-w-full justify-start truncate p-0 underline",
|
||||||
|
markedForDelete && "text-muted-foreground line-through",
|
||||||
|
)}
|
||||||
|
onClick={() => handleDownloadAttachment(name)}
|
||||||
|
disabled={downloadAttachmentMutation.isPending}
|
||||||
|
title={name}
|
||||||
|
>
|
||||||
|
{name}
|
||||||
|
</Button>
|
||||||
|
{isReplaced ? (
|
||||||
|
<span className="shrink-0 text-xs text-muted-foreground">교체됨</span>
|
||||||
|
) : (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="h-6 shrink-0 px-2 text-xs"
|
||||||
|
onClick={() => handleToggleDeleteExistingAttachment(name)}
|
||||||
|
>
|
||||||
|
{markedForDelete ? "복원" : "삭제"}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{newAttachmentFiles.map((file) => (
|
||||||
|
<li key={`new-${file.name}`} className="flex items-center justify-between gap-2 text-sm">
|
||||||
|
<span className="truncate text-green-700">
|
||||||
|
{file.name} <span className="text-muted-foreground">(신규, {(file.size / 1024).toFixed(1)}KB)</span>
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon-sm"
|
||||||
|
className="h-6 w-6 shrink-0"
|
||||||
|
onClick={() => handleRemoveNewAttachmentFile(file.name)}
|
||||||
|
aria-label={`${file.name} 제거`}
|
||||||
|
>
|
||||||
|
<X className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
파일당 {(TEMPLATE_ATTACHMENT_MAX_BYTES / 1000).toLocaleString()}KB 미만, 최대 {TEMPLATE_ATTACHMENT_MAX_COUNT}개까지 첨부할 수 있습니다.
|
||||||
|
</p>
|
||||||
|
{selectedTemplate.tmplatIdx && (
|
||||||
|
<p className="text-xs text-red-600">
|
||||||
|
⚠️ 복사 후 저장시 첨부파일은 복사 되지 않습니다.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isSms && (
|
{isSms && (
|
||||||
|
|||||||
53
src/components/message-template/TemplateAttachmentList.tsx
Normal file
53
src/components/message-template/TemplateAttachmentList.tsx
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { downloadFile } from '@kri/common/browser'
|
||||||
|
import { useDownloadTemplateAttachmentMutation } from '@/query/message'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
export type TemplateAttachmentListProps = {
|
||||||
|
tmplatIdx?: number
|
||||||
|
atchFl?: string
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const TemplateAttachmentList = ({ tmplatIdx, atchFl, className }: TemplateAttachmentListProps) => {
|
||||||
|
const attachmentNames = atchFl?.split('|').filter(Boolean) ?? []
|
||||||
|
const downloadMutation = useDownloadTemplateAttachmentMutation(tmplatIdx ?? 0)
|
||||||
|
|
||||||
|
if (!tmplatIdx || attachmentNames.length === 0) return null
|
||||||
|
|
||||||
|
const handleDownload = async (fileName: string) => {
|
||||||
|
try {
|
||||||
|
const buffer = await downloadMutation.mutateAsync(fileName)
|
||||||
|
downloadFile(new Blob([buffer], { type: 'application/octet-stream' }), fileName)
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e)
|
||||||
|
alert('첨부파일 다운로드에 실패했습니다.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn('space-y-1', className)}>
|
||||||
|
<p className="text-sm font-semibold">첨부파일</p>
|
||||||
|
<ul className="space-y-1">
|
||||||
|
{attachmentNames.map((fileName) => (
|
||||||
|
<li key={fileName}>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="link"
|
||||||
|
className="h-auto max-w-full justify-start truncate p-0 underline"
|
||||||
|
onClick={() => handleDownload(fileName)}
|
||||||
|
disabled={downloadMutation.isPending}
|
||||||
|
title={fileName}
|
||||||
|
>
|
||||||
|
{fileName}
|
||||||
|
</Button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default TemplateAttachmentList
|
||||||
@@ -14,3 +14,7 @@ export const SMS_TYPE_OPTIONS = [
|
|||||||
{ value: MessageType.SMS, label: SMS_TYPE_LABEL[MessageType.SMS] },
|
{ value: MessageType.SMS, label: SMS_TYPE_LABEL[MessageType.SMS] },
|
||||||
{ value: MessageType.LMS_MMS, label: SMS_TYPE_LABEL[MessageType.LMS_MMS] },
|
{ value: MessageType.LMS_MMS, label: SMS_TYPE_LABEL[MessageType.LMS_MMS] },
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
|
// 이메일 템플릿 첨부파일 제한 (첨부파일은 이메일 템플릿만 지원)
|
||||||
|
export const TEMPLATE_ATTACHMENT_MAX_COUNT = 5;
|
||||||
|
export const TEMPLATE_ATTACHMENT_MAX_BYTES = 1_000_000;
|
||||||
|
|||||||
@@ -56,11 +56,25 @@ export function useSaveTemplateMutation(chnnlTy: ChannelType, itrntPrjctCd: stri
|
|||||||
const qc = useQueryClient();
|
const qc = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (v: { method: "put" | "patch"; template: Template }) => {
|
mutationFn: async (v: {
|
||||||
const { method, template } = v;
|
method: "put" | "patch";
|
||||||
|
template: Template;
|
||||||
|
newFiles?: File[];
|
||||||
|
deleteFileNames?: string[];
|
||||||
|
}) => {
|
||||||
|
const { method, template, newFiles = [], deleteFileNames = [] } = v;
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append(
|
||||||
|
"template",
|
||||||
|
new Blob([JSON.stringify(template)], { type: "application/json" }),
|
||||||
|
);
|
||||||
|
newFiles.forEach((file) => formData.append("files", file));
|
||||||
|
deleteFileNames.forEach((name) => formData.append("deleteFileNames", name));
|
||||||
|
|
||||||
return method === "put"
|
return method === "put"
|
||||||
? nextApi.put<Template>(`/message-template`, template)
|
? nextApi.putForm<Template>(`/message-template`, formData)
|
||||||
: nextApi.patch<Template>(`/message-template`, template);
|
: nextApi.request<Template>(`/message-template`, { method: "PATCH", form: formData });
|
||||||
},
|
},
|
||||||
onSuccess: (res) => {
|
onSuccess: (res) => {
|
||||||
if (res.tmplatIdx) {
|
if (res.tmplatIdx) {
|
||||||
@@ -71,6 +85,18 @@ export function useSaveTemplateMutation(chnnlTy: ChannelType, itrntPrjctCd: stri
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 템플릿 첨부파일 단건 다운로드 (GET /template/{tmplatIdx}/attachment?fileName=...)
|
||||||
|
*/
|
||||||
|
export function useDownloadTemplateAttachmentMutation(tmplatIdx: number) {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (fileName: string) =>
|
||||||
|
nextApi.get<ArrayBuffer>(`/message-template/${tmplatIdx}/attachment?fileName=${encodeURIComponent(fileName)}`, {
|
||||||
|
expectBinary: true,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export function useUpdateMainTemplateMutation(prjctIdx: number, chnnlTy: ChannelType) {
|
export function useUpdateMainTemplateMutation(prjctIdx: number, chnnlTy: ChannelType) {
|
||||||
const qc = useQueryClient();
|
const qc = useQueryClient();
|
||||||
const key = qk.mainTemplate(prjctIdx, chnnlTy);
|
const key = qk.mainTemplate(prjctIdx, chnnlTy);
|
||||||
|
|||||||
@@ -1,7 +1,16 @@
|
|||||||
|
import type { TemplateEmail } from '@kri/common/noti-hub';
|
||||||
import type { ListFilter } from './list';
|
import type { ListFilter } from './list';
|
||||||
|
|
||||||
export type MessageSendChannel = 'sms' | 'email';
|
export type MessageSendChannel = 'sms' | 'email';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @kri/common의 TemplateEmail에는 atchFl(첨부파일 필드)이 아직 없어 로컬에서 확장한다.
|
||||||
|
* 조회 응답 전용 필드로, 파이프(|)로 구분된 첨부파일명 목록이 내려온다. 요청 시엔 사용하지 않는다.
|
||||||
|
*/
|
||||||
|
export type TemplateEmailWithAttachments = TemplateEmail & {
|
||||||
|
atchFl?: string;
|
||||||
|
};
|
||||||
|
|
||||||
export type MessageSendSingleRequest = {
|
export type MessageSendSingleRequest = {
|
||||||
tmplatIdx: number;
|
tmplatIdx: number;
|
||||||
resve: boolean;
|
resve: boolean;
|
||||||
|
|||||||
Reference in New Issue
Block a user