260805_01_ENH: 이메일 템플릿 저장 시 빈 칸 유지, 외부 설문에서 리스트 단건 조회, 리스트 헤더조회, 리스트 단건 수정 기능 사용할수 있도록 api 라우트 생성 및 cors 완화 #19

Merged
gitadmin merged 1 commits from develop into master 2026-08-05 12:20:22 +09:00
10 changed files with 220 additions and 15 deletions
Showing only changes of commit 6a2265e767 - Show all commits

View File

@@ -29,6 +29,17 @@ const nextConfig = createKriNextConfig({
},
],
},
{
source: "/api/list-external/:path*",
headers: [
{ key: "Access-Control-Allow-Origin", value: "*" },
{ key: "Access-Control-Allow-Methods", value: "GET,POST,PATCH" },
{
key: "Access-Control-Allow-Headers",
value: "Content-Type, X-API-Key",
},
],
},
];
},
}) satisfies NextConfig;

View File

@@ -0,0 +1,115 @@
import { NextRequest, NextResponse } from "next/server";
import { RouteContext } from "@/types/common";
import { createContactApiWithApiKey } from "@/lib/http-server";
import { errorToResponse } from "@kri/common/http";
import { ListSearchExternal } from "@/types/list";
const getApiKey = (req: NextRequest) => req.headers.get("x-api-key");
// backend가 제공하는 메소드/경로 그대로 사용 (path variable)
export const GET = async (req: NextRequest, context: RouteContext) => {
try {
const apiKey = getApiKey(req);
if (!apiKey) {
return NextResponse.json({ message: "X-API-Key는 필수입니다." }, { status: 401 });
}
const { slug = [] } = await context.params;
const [action, prjctIdx, sid] = slug;
const contactApi = await createContactApiWithApiKey(apiKey);
if (action === "header" && prjctIdx) {
const result = await contactApi.get<string[]>(`/list-external/header/${prjctIdx}`);
return NextResponse.json(result, { status: 200 });
}
if (action === "search" && prjctIdx && sid) {
const result = await contactApi.get<ListSearchExternal>(
`/list-external/search/${prjctIdx}/${encodeURIComponent(sid)}`,
);
return NextResponse.json(result, { status: 200 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
// backend가 제공하는 메소드/경로 그대로 사용 (path variable)
export const PATCH = async (req: NextRequest, context: RouteContext) => {
try {
const apiKey = getApiKey(req);
if (!apiKey) {
return NextResponse.json({ message: "X-API-Key는 필수입니다." }, { status: 401 });
}
const { slug = [] } = await context.params;
const [action, prjctIdx, sid] = slug;
if (action === "update" && prjctIdx && sid) {
const body = await req.json().catch(() => null);
const contactApi = await createContactApiWithApiKey(apiKey);
const result = await contactApi.patch<number>(
`/list-external/update/${prjctIdx}/${encodeURIComponent(sid)}`,
body,
);
return NextResponse.json(result, { status: 200 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
// 외부 연동 호환용: 항상 POST, path variable을 모두 url 쿼리 파람으로 받아 backend path variable로 전달
export const POST = async (req: NextRequest, context: RouteContext) => {
try {
const apiKey = getApiKey(req);
if (!apiKey) {
return NextResponse.json({ message: "X-API-Key는 필수입니다." }, { status: 401 });
}
const { slug = [] } = await context.params;
const [action] = slug;
const { searchParams } = req.nextUrl;
const prjctIdx = searchParams.get("prjctIdx");
const sid = searchParams.get("sid");
const contactApi = await createContactApiWithApiKey(apiKey);
if (action === "header") {
if (!prjctIdx) {
return NextResponse.json({ message: "prjctIdx는 필수입니다." }, { status: 400 });
}
const result = await contactApi.get<string[]>(`/list-external/header/${prjctIdx}`);
return NextResponse.json(result, { status: 200 });
}
if (action === "search") {
if (!prjctIdx || !sid) {
return NextResponse.json({ message: "prjctIdx, sid는 필수입니다." }, { status: 400 });
}
const result = await contactApi.get<ListSearchExternal>(
`/list-external/search/${prjctIdx}/${encodeURIComponent(sid)}`,
);
return NextResponse.json(result, { status: 200 });
}
if (action === "update") {
if (!prjctIdx || !sid) {
return NextResponse.json({ message: "prjctIdx, sid는 필수입니다." }, { status: 400 });
}
const body = await req.json().catch(() => null);
const result = await contactApi.patch<number>(
`/list-external/update/${prjctIdx}/${encodeURIComponent(sid)}`,
body,
);
return NextResponse.json(result, { status: 200 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
};

View File

@@ -172,6 +172,24 @@
vertical-align: baseline;
}
/* 에디터 편집 화면은 [&_p]:my-2 유틸리티로 문단 사이 margin을 주지만,
미리보기는 Tailwind preflight가 p의 기본 margin을 0으로 리셋해 내용 없는 빈 <p></p>가
높이 0으로 사라진다. 편집 화면과 동일하게 margin을 줘서 빈 줄이 보이도록 한다. */
.kri-editor-preview p {
margin: 0.5em 0;
}
.kri-editor-preview p:first-child {
margin-top: 0;
}
.kri-editor-preview p:last-child {
margin-bottom: 0;
}
/* 내용이 전혀 없는 <p></p>는 높이가 0이라 위/아래 margin이 서로 collapse되어 사라진다.
min-height로 실제 높이를 줘서 collapse를 막아야 빈 줄이 화면에 보인다. */
.kri-editor-preview p:empty {
min-height: 1em;
}
.ProseMirror .ProseMirror-selectednode img {
outline: 5px solid #0ea5e9;
outline-offset: -5px;

View File

@@ -1,6 +1,6 @@
'use client'
import { CSSProperties, useEffect, useState } from 'react'
import { CSSProperties, useEffect, useRef, useState } from 'react'
import {
closestCenter,
DndContext,
@@ -182,6 +182,7 @@ const ListHeaderManageDialog = ({
const [localRows, setLocalRows] = useState<listHeader[]>([])
const [activeId, setActiveId] = useState<number | null>(null)
const [submitting, setSubmitting] = useState(false)
const originalRowsRef = useRef<listHeader[]>([])
const resolvedOpen = open ?? isDialogOpen(dialogId)
const sensors = useSensors(
@@ -191,7 +192,9 @@ const ListHeaderManageDialog = ({
useEffect(() => {
if (!resolvedOpen) return
setLocalRows([...rows].sort((a, b) => a.listHderOrder - b.listHderOrder).map((row) => ({ ...row })))
const sorted = [...rows].sort((a, b) => a.listHderOrder - b.listHderOrder).map((row) => ({ ...row }))
setLocalRows(sorted)
originalRowsRef.current = sorted.map((row) => ({ ...row }))
}, [resolvedOpen, rows])
const handleOpenChange = (nextOpen: boolean) => {
@@ -294,6 +297,35 @@ const ListHeaderManageDialog = ({
}
const handleConfirm = async () => {
const names = localRows.map((row) => row.listHderNm.trim())
const duplicateNames = [...new Set(names.filter((name, index) => names.indexOf(name) !== index))]
if (duplicateNames.length > 0) {
alert(`중복된 헤더명이 있습니다: ${duplicateNames.join(', ')}`)
return
}
const localById = new Map(localRows.map((row) => [row.listHderId, row]))
const renamedNames = originalRowsRef.current
.filter((row) => {
const current = localById.get(row.listHderId)
return current && current.listHderNm.trim() !== row.listHderNm.trim()
})
.map((row) => row.listHderNm)
const deletedNames = originalRowsRef.current
.filter((row) => !localById.has(row.listHderId))
.map((row) => row.listHderNm)
if (renamedNames.length > 0 || deletedNames.length > 0) {
const messageLines = [
'헤더명이 수정 되거나 헤더가 삭제되면 KON또는 KON-KIWI의 리스트 관련 하드코딩이 있다면 해당 문항에 문제가 생길 수 있습니다. 진행 하시겠습니까?\n',
]
if (renamedNames.length > 0) messageLines.push(`수정예정: ${renamedNames.join(', ')}`)
if (deletedNames.length > 0) messageLines.push(`삭제예정: ${deletedNames.join(', ')}`)
if (!window.confirm(messageLines.join('\n'))) return
}
setSubmitting(true)
try {
const orderedRows = localRows.map((row, index) => ({
@@ -326,7 +358,8 @@ const ListHeaderManageDialog = ({
}
>
<div className="flex justify-end mb-2">
<div className="flex justify-between mb-2">
<span className="text-base text-red-600 font-semibold">⚠️ 헤더명이 수정 되거나 헤더가 삭제되면 KON또는 KON-KIWI의 리스트 관련 하드코딩에 영향이 있을 수 있습니다.</span>
<Button type="button" className="gap-2 bg-blue" onClick={handleAddHeader} disabled={submitting}>
<Plus className="w-4 h-4" />
헤더 추가

View File

@@ -8,6 +8,7 @@ import { resolveUploadUrl } from './types'
import { compressImage } from './utils/imageCompression'
import { useDebouncedChange } from './hooks/useDebouncedChange'
import { sanitizeHtmlForPreview } from './utils/sanitizeHtml'
import { preserveEmptyParagraphs } from './utils/emptyParagraph'
import { useTextareaInsert } from './hooks/useTextareaInsert'
type HtmlOnlyProps = Omit<KriEditorProps, 'mode'> & { mode: 'html' }
@@ -121,7 +122,7 @@ export function KriEditorHtmlOnly({
}
}
const previewHtml = React.useMemo(() => sanitizeHtmlForPreview(html), [html])
const previewHtml = React.useMemo(() => sanitizeHtmlForPreview(preserveEmptyParagraphs(html)), [html])
return (
<div className={cn('rounded-md border bg-background', className)}>

View File

@@ -26,6 +26,7 @@ import { FontSize } from "./extensions/font-size";
import { Div } from "./extensions/div";
import { compressImage } from "./utils/imageCompression";
import { sanitizeHtml } from "./utils/sanitizeHtml";
import { preserveEmptyParagraphs } from "./utils/emptyParagraph";
import { applyLinkPreviewClass, KRI_EDITOR_LINK_CLASS } from "./utils/linkPreview";
import { Toolbar } from "./toolbar/Toolbar";
import { useDebouncedChange } from "./hooks/useDebouncedChange";
@@ -192,7 +193,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
if (viewRef.current === "html") return;
const nextHtml = editor.getHTML();
setPreviewSource(nextHtml);
scheduleChange(nextHtml);
scheduleChange(preserveEmptyParagraphs(nextHtml));
},
editorProps: {
@@ -444,7 +445,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
const safe = sanitizeHtmlOpt ? sanitizeHtml(raw, allowedCustomHtml) : raw;
editor.commands.setContent(safe, { emitUpdate: false, parseOptions: { preserveWhitespace: "full" } });
flushChange(editor.getHTML());
flushChange(preserveEmptyParagraphs(editor.getHTML()));
setView("wysiwyg");
}, [allowedCustomHtml, editor, flushChange, sanitizeHtmlOpt]);
@@ -506,8 +507,8 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
if (!editor) return;
const onBlur = () => {
if (viewRef.current === "html") flushChange(htmlDraftRef.current);
else flushChange(editor.getHTML());
if (viewRef.current === "html") flushChange(preserveEmptyParagraphs(htmlDraftRef.current));
else flushChange(preserveEmptyParagraphs(editor.getHTML()));
};
editor.on("blur", onBlur);
@@ -542,7 +543,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
if (!editor) return;
restoreSelection();
editor.chain().focus().insertContent(text).run();
flushChange(editor.getHTML());
flushChange(preserveEmptyParagraphs(editor.getHTML()));
},
}),
[editor, restoreSelection, flushChange, insertTextareaText]
@@ -563,7 +564,8 @@ export function KriEditorWysiwyg(props: KriEditorProps) {
}, [command, editor, props.onCommandReady]);
const previewHtml = useMemo(() => {
const sanitized = sanitizeHtmlOpt ? sanitizeHtml(previewSource, allowedCustomHtml) : previewSource;
const preserved = preserveEmptyParagraphs(previewSource);
const sanitized = sanitizeHtmlOpt ? sanitizeHtml(preserved, allowedCustomHtml) : preserved;
const withLinkStyle = applyLinkPreviewClass(sanitized);
return transformPreviewHtml ? transformPreviewHtml(withLinkStyle) : withLinkStyle;
}, [allowedCustomHtml, previewSource, sanitizeHtmlOpt, transformPreviewHtml]);

View File

@@ -0,0 +1,9 @@
const EMPTY_PARAGRAPH_PATTERN = /<p((?:\s+[^>]*)?)>\s*<\/p>/gi;
/**
* 내용이 전혀 없는 <p></p>는 CSS margin이 collapse되어 이메일 클라이언트 등
* 우리 앱 밖에서는 높이 0으로 붙어버린다. &nbsp;를 채워 실제 콘텐츠로 줄 높이를 보장한다.
*/
export function preserveEmptyParagraphs(html: string): string {
return html.replace(EMPTY_PARAGRAPH_PATTERN, (_match, attrs: string) => `<p${attrs}>&nbsp;</p>`);
}

View File

@@ -205,7 +205,7 @@ const ListContactInfoPanel = ({
type="button"
variant="outline"
className={cn('shrink-0 gap-2', isOnCall && 'bg-accent text-accent-foreground')}
disabled={!isCtiReady || isDialing}
disabled={isEditing || !isCtiReady || isDialing}
title={getCallButtonTitle(isCtiReady, isDialing)}
onClick={() => handleCall(value, header.listHderId)}
>
@@ -216,6 +216,7 @@ const ListContactInfoPanel = ({
type="button"
variant="outline"
className="shrink-0 gap-2"
disabled={isEditing}
onClick={() => handleSend('sms', header.listHderId)}
>
<MessageSquare className="h-4 w-4" />
@@ -245,6 +246,7 @@ const ListContactInfoPanel = ({
type="button"
variant="outline"
className="shrink-0 gap-2"
disabled={isEditing}
onClick={() => handleSend('email', header.listHderId)}
>
<Mail className="h-4 w-4" />
@@ -264,7 +266,7 @@ const ListContactInfoPanel = ({
<button
type="button"
className="max-w-full cursor-pointer text-left text-primary hover:text-primary/80 disabled:cursor-wait disabled:opacity-60"
disabled={downloadItemFileMutation.isPending}
disabled={isEditing || downloadItemFileMutation.isPending}
title={value}
onClick={() => handleDownloadFile(header.listHderId, value)}
>
@@ -284,7 +286,7 @@ const ListContactInfoPanel = ({
type="button"
variant="outline"
className="shrink-0 gap-2"
disabled={uploadItemFileMutation.isPending}
disabled={isEditing || uploadItemFileMutation.isPending}
onClick={() => handlePickFile(header.listHderId)}
>
<Paperclip className="h-4 w-4" />
@@ -335,10 +337,10 @@ const ListContactInfoPanel = ({
return (
<FieldRow key={survey.prjctSurveyIdx ?? survey.surveyOrder} label={survey.surveyName || 'Web'}>
<div className="flex items-center gap-2">
<Button type="button" className="gap-2" onClick={() => handleStartSurvey(survey)}>
<Button type="button" className="gap-2" disabled={isEditing} onClick={() => handleStartSurvey(survey)}>
조사 시작
</Button>
<Button type="button" variant="outline" className="gap-2" onClick={() => handleShowQr(survey)}>
<Button type="button" variant="outline" className="gap-2" disabled={isEditing} onClick={() => handleShowQr(survey)}>
<QrCode className="h-4 w-4" />
QR
</Button>

View File

@@ -20,6 +20,14 @@ export const createContactApi = () => {
return createServerApi(serverEnv.API_CONTACT_SERVER);
};
// KON/KON-KIWI 등 쿠키 세션이 없는 외부 시스템이 X-API-Key로 호출하는 경우 사용.
// 받은 X-API-Key를 backend로 그대로 전달한다.
export const createContactApiWithApiKey = (apiKey: string) => {
return createServerApi(serverEnv.API_CONTACT_SERVER, {
"X-API-Key": apiKey,
});
};
//Todo: Front에서 바로 붙지 말고 Backend를 통해서 처리 하도록 수정 필요
export const createNotihubApi = () => {
return createServerApi(serverEnv.API_NOTIHUB_SERVER);

View File

@@ -367,3 +367,9 @@ export type ListSearchWithFullResult = ListSearchWithResult & {
mailSendResult: ListSendResult;
smsSendResult?: ListSendResult;
};
export type ListSearchExternal = {
prjctIdx: number;
sid: string;
itemList: Record<string, string>;
};