From a50bc9baea332f996e6bc3a5d70c69f6d2d0f194 Mon Sep 17 00:00:00 2001 From: dujinkim Date: Wed, 23 Jul 2025 09:08:03 +0000 Subject: (대표님, 최겸) 기본계약 템플릿 및 에디터, 기술영업 벤더정보, 파일 보안다운로드, 벤더 document sync 상태 서비스, 메뉴 Config, 기술영업 미사용 제거 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/basic-contract/service.ts | 98 +++++ .../add-basic-contract-template-dialog.tsx | 96 ++-- .../template/basic-contract-template-columns.tsx | 78 ++-- .../template/basic-contract-template-viewer.tsx | 234 ++++++++++ .../template/basic-contract-template.tsx | 31 +- .../template/template-editor-wrapper.tsx | 353 +++++++++++++++ .../template/update-basicContract-sheet.tsx | 487 ++++++++++----------- lib/email-template/editor/template-editor.tsx | 5 +- lib/evaluation-target-list/service.ts | 2 +- lib/file-download.ts | 1 + lib/sedp/sync-form.ts | 17 +- lib/sedp/sync-package.ts | 11 +- lib/tech-vendor-candidates/service.ts | 395 ----------------- .../table/add-candidates-dialog.tsx | 394 ----------------- .../table/candidates-table-columns.tsx | 199 --------- .../table/candidates-table-floating-bar.tsx | 395 ----------------- .../table/candidates-table-toolbar-actions.tsx | 93 ---- .../table/candidates-table.tsx | 173 -------- .../table/delete-candidates-dialog.tsx | 159 ------- .../table/excel-template-download.tsx | 128 ------ .../table/feature-flags-provider.tsx | 108 ----- lib/tech-vendor-candidates/table/feature-flags.tsx | 96 ---- lib/tech-vendor-candidates/table/import-button.tsx | 233 ---------- .../table/invite-candidates-dialog.tsx | 230 ---------- .../table/update-candidate-sheet.tsx | 437 ------------------ lib/tech-vendor-candidates/utils.ts | 40 -- lib/tech-vendor-candidates/validations.ts | 148 ------- .../possible-items/possible-items-columns.tsx | 6 +- .../possible-items-toolbar-actions.tsx | 2 +- .../detail-table/vendor-communication-drawer.tsx | 6 +- lib/vendors/validations.ts | 22 +- 31 files changed, 1064 insertions(+), 3613 deletions(-) create mode 100644 lib/basic-contract/template/basic-contract-template-viewer.tsx create mode 100644 lib/basic-contract/template/template-editor-wrapper.tsx delete mode 100644 lib/tech-vendor-candidates/service.ts delete mode 100644 lib/tech-vendor-candidates/table/add-candidates-dialog.tsx delete mode 100644 lib/tech-vendor-candidates/table/candidates-table-columns.tsx delete mode 100644 lib/tech-vendor-candidates/table/candidates-table-floating-bar.tsx delete mode 100644 lib/tech-vendor-candidates/table/candidates-table-toolbar-actions.tsx delete mode 100644 lib/tech-vendor-candidates/table/candidates-table.tsx delete mode 100644 lib/tech-vendor-candidates/table/delete-candidates-dialog.tsx delete mode 100644 lib/tech-vendor-candidates/table/excel-template-download.tsx delete mode 100644 lib/tech-vendor-candidates/table/feature-flags-provider.tsx delete mode 100644 lib/tech-vendor-candidates/table/feature-flags.tsx delete mode 100644 lib/tech-vendor-candidates/table/import-button.tsx delete mode 100644 lib/tech-vendor-candidates/table/invite-candidates-dialog.tsx delete mode 100644 lib/tech-vendor-candidates/table/update-candidate-sheet.tsx delete mode 100644 lib/tech-vendor-candidates/utils.ts delete mode 100644 lib/tech-vendor-candidates/validations.ts (limited to 'lib') diff --git a/lib/basic-contract/service.ts b/lib/basic-contract/service.ts index 9890cdfc..87a861e1 100644 --- a/lib/basic-contract/service.ts +++ b/lib/basic-contract/service.ts @@ -889,4 +889,102 @@ export async function checkContractRequestStatus( error: error instanceof Error ? error.message : "계약 상태 확인 중 오류가 발생했습니다." }; } +} + + +/** + * ID로 기본계약서 템플릿 조회 + */ +export async function getBasicContractTemplateByIdService(id: string) { + try { + const templateId = parseInt(id); + + if (isNaN(templateId)) { + return null; + } + + const templates = await db + .select() + .from(basicContractTemplates) + .where(eq(basicContractTemplates.id, templateId)) + .limit(1); + + if (templates.length === 0) { + return null; + } + + return templates[0]; + } catch (error) { + console.error("템플릿 조회 오류:", error); + return null; + } +} + +/** + * 템플릿 파일 저장 서버 액션 + */ +export async function saveTemplateFile(templateId: number, formData: FormData) { + try { + const file = formData.get("file") as File; + + if (!file) { + return { error: "파일이 필요합니다." }; + } + + // 기존 템플릿 정보 조회 + const existingTemplate = await db + .select() + .from(basicContractTemplates) + .where(eq(basicContractTemplates.id, templateId)) + .limit(1); + + if (existingTemplate.length === 0) { + return { error: "템플릿을 찾을 수 없습니다." }; + } + + const template = existingTemplate[0]; + + // 파일 저장 로직 (실제 파일 시스템에 저장) + const { writeFile, mkdir } = await import("fs/promises"); + const { join } = await import("path"); + + const bytes = await file.arrayBuffer(); + const buffer = Buffer.from(bytes); + + // 기존 파일 경로 사용 (덮어쓰기) + const uploadPath = join(process.cwd(), "public", template.filePath.replace(/^\//, "")); + + // 디렉토리 확인 및 생성 + const dirPath = uploadPath.substring(0, uploadPath.lastIndexOf('/')); + await mkdir(dirPath, { recursive: true }); + + // 파일 저장 + await writeFile(uploadPath, buffer); + + // 데이터베이스 업데이트 (수정일시만 업데이트) + await db + .update(basicContractTemplates) + .set({ + updatedAt: new Date(), + }) + .where(eq(basicContractTemplates.id, templateId)); + + // 캐시 무효화 + revalidatePath(`/evcp/basic-contract-template/${templateId}`); + revalidateTag("basic-contract-templates"); + + return { success: true, message: "템플릿이 성공적으로 저장되었습니다." }; + + } catch (error) { + console.error("템플릿 저장 오류:", error); + return { error: "저장 중 오류가 발생했습니다." }; + } +} + +/** + * 템플릿 페이지 새로고침 서버 액션 + */ +export async function refreshTemplatePage(templateId: string) { + revalidatePath(`/evcp/basic-contract-template/${templateId}`); + revalidateTag("basic-contract-templates"); } \ No newline at end of file diff --git a/lib/basic-contract/template/add-basic-contract-template-dialog.tsx b/lib/basic-contract/template/add-basic-contract-template-dialog.tsx index c88819e4..9b036445 100644 --- a/lib/basic-contract/template/add-basic-contract-template-dialog.tsx +++ b/lib/basic-contract/template/add-basic-contract-template-dialog.tsx @@ -41,13 +41,26 @@ import { Separator } from "@/components/ui/separator"; import { useRouter } from "next/navigation"; import { BUSINESS_UNITS } from "@/config/basicContractColumnsConfig"; -// 업데이트된 계약서 템플릿 스키마 정의 +// 템플릿 이름 옵션 정의 +const TEMPLATE_NAME_OPTIONS = [ + "준법서약", + "기술자료 요구서", + "비밀유지 계약서", + "표준하도급기본 계약서", + "General GTC", + "안전보건관리 약정서", + "동반성장", + "윤리규범 준수 서약서", + "기술자료 동의서", + "내국신용장 미개설 합의서", + "직납자재 하도급대급등 연동제 의향서" +] as const; + +// 업데이트된 계약서 템플릿 스키마 정의 (워드파일만 허용) const templateFormSchema = z.object({ - templateCode: z.string() - .min(1, "템플릿 코드는 필수입니다.") - .max(50, "템플릿 코드는 50자 이하여야 합니다.") - .regex(/^[A-Z0-9_-]+$/, "템플릿 코드는 영문 대문자, 숫자, '_', '-'만 사용 가능합니다."), - templateName: z.string().min(1, "템플릿 이름은 필수입니다."), + templateName: z.enum(TEMPLATE_NAME_OPTIONS, { + required_error: "템플릿 이름을 선택해주세요.", + }), revision: z.coerce.number().int().min(1).default(1), legalReviewRequired: z.boolean().default(false), @@ -67,8 +80,10 @@ const templateFormSchema = z.object({ message: "파일 크기는 100MB 이하여야 합니다.", }) .refine( - (file) => file.type === 'application/pdf', - { message: "PDF 파일만 업로드 가능합니다." } + (file) => + file.type === 'application/msword' || + file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + { message: "워드 파일(.doc, .docx)만 업로드 가능합니다." } ), status: z.enum(["ACTIVE", "DISPOSED"]).default("ACTIVE"), }).refine((data) => { @@ -95,10 +110,9 @@ export function AddTemplateDialog() { const [showProgress, setShowProgress] = React.useState(false); const router = useRouter(); - // 기본값 설정 + // 기본값 설정 (templateCode 제거) const defaultValues: Partial = { - templateCode: "", - templateName: "", + templateName: undefined, revision: 1, legalReviewRequired: false, shipBuildingApplicable: false, @@ -183,7 +197,7 @@ export function AddTemplateDialog() { } }; - // 폼 제출 핸들러 + // 폼 제출 핸들러 (templateCode 제거) async function onSubmit(formData: TemplateFormValues) { setIsLoading(true); try { @@ -201,14 +215,13 @@ export function AddTemplateDialog() { throw new Error("파일 업로드에 실패했습니다."); } - // 메타데이터 저장 (업데이트된 필드들 포함) + // 메타데이터 저장 (templateCode 제거됨) const saveResponse = await fetch('/api/upload/basicContract/complete', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ - templateCode: formData.templateCode, templateName: formData.templateName, revision: formData.revision, legalReviewRequired: formData.legalReviewRequired, @@ -300,22 +313,28 @@ export function AddTemplateDialog() {
( - 템플릿 코드 * + 템플릿 이름 * - - field.onChange(e.target.value.toUpperCase())} - /> - + - 영문 대문자, 숫자, '_', '-'만 사용 가능 + 미리 정의된 템플릿 중에서 선택 @@ -338,6 +357,10 @@ export function AddTemplateDialog() { 템플릿 버전 (기본값: 1) +
+ + 동일한 템플릿 이름의 리비전은 중복될 수 없습니다. +
@@ -345,22 +368,6 @@ export function AddTemplateDialog() { />
- ( - - - 템플릿 이름 * - - - - - - - )} - /> - - {selectedFile ? selectedFile.name : "PDF 파일을 여기에 드래그하세요"} + {selectedFile ? selectedFile.name : "워드 파일을 여기에 드래그하세요"} {selectedFile ? `파일 크기: ${(selectedFile.size / (1024 * 1024)).toFixed(2)} MB` - : "또는 클릭하여 PDF 파일을 선택하세요 (최대 100MB)"} + : "또는 클릭하여 워드 파일(.doc, .docx)을 선택하세요 (최대 100MB)"} diff --git a/lib/basic-contract/template/basic-contract-template-columns.tsx b/lib/basic-contract/template/basic-contract-template-columns.tsx index 3be46791..b7c2fa08 100644 --- a/lib/basic-contract/template/basic-contract-template-columns.tsx +++ b/lib/basic-contract/template/basic-contract-template-columns.tsx @@ -3,7 +3,7 @@ import * as React from "react" import { type DataTableRowAction } from "@/types/table" import { type ColumnDef } from "@tanstack/react-table" -import { Download, Ellipsis, Paperclip, CheckCircle, XCircle } from "lucide-react" +import { Download, Ellipsis, Paperclip, CheckCircle, XCircle, Eye } from "lucide-react" import { toast } from "sonner" import { getErrorMessage } from "@/lib/handle-error" @@ -29,28 +29,20 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/comp import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header" import { scopeHelpers } from "@/config/basicContractColumnsConfig" import { BasicContractTemplate } from "@/db/schema" +import { quickDownload } from "@/lib/file-download" +import { useRouter } from "next/navigation" interface GetColumnsProps { setRowAction: React.Dispatch | null>> + router: ReturnType } /** - * 파일 다운로드 함수 + * 파일 다운로드 함수 (공용 유틸리티 사용) */ -const handleFileDownload = (filePath: string, fileName: string) => { +const handleFileDownload = async (filePath: string, fileName: string) => { try { - // 전체 URL 생성 - const fullUrl = `${window.location.origin}${filePath}`; - - // a 태그를 생성하여 다운로드 실행 - const link = document.createElement('a'); - link.href = fullUrl; - link.download = fileName; // 다운로드될 파일명 설정 - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - - toast.success("파일 다운로드를 시작합니다."); + await quickDownload(filePath, fileName); } catch (error) { console.error("파일 다운로드 오류:", error); toast.error("파일 다운로드 중 오류가 발생했습니다."); @@ -60,7 +52,7 @@ const handleFileDownload = (filePath: string, fileName: string) => { /** * tanstack table 컬럼 정의 (중첩 헤더 버전) */ -export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef[] { +export function getColumns({ setRowAction, router }: GetColumnsProps): ColumnDef[] { // ---------------------------------------------------------------- // 1) select 컬럼 (체크박스) // ---------------------------------------------------------------- @@ -126,6 +118,10 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef { + router.push(`/evcp/basic-contract-template/${template.id}`); + }; + return ( @@ -138,6 +134,13 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef + + + View Details + + + + setRowAction({ row, type: "update" })} > @@ -201,45 +204,26 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef , cell: ({ row }) => { const template = row.original; - const scopeText = scopeHelpers.getScopeDisplayText(template); + + const handleClick = () => { + router.push(`/evcp/basic-contract-template/${template.id}`); + }; + return (
- {template.templateName} - - - - - {scopeText} - - - -
-

적용 범위:

- {scopeHelpers.getApplicableScopeLabels(template).map(label => ( -

• {label}

- ))} -
-
-
-
+
); }, size: 250, enableResizing: true, }, - { - accessorKey: "templateCode", - header: ({ column }) => , - cell: ({ row }) => { - const template = row.original; - return ( - {template.templateCode} - ); - }, - size: 120, - enableResizing: true, - }, { accessorKey: "revision", header: ({ column }) => , diff --git a/lib/basic-contract/template/basic-contract-template-viewer.tsx b/lib/basic-contract/template/basic-contract-template-viewer.tsx new file mode 100644 index 00000000..59989e46 --- /dev/null +++ b/lib/basic-contract/template/basic-contract-template-viewer.tsx @@ -0,0 +1,234 @@ +"use client"; + +import React, { + useState, + useEffect, + useRef, + SetStateAction, + Dispatch, +} from "react"; +import { WebViewerInstance } from "@pdftron/webviewer"; +import { Loader2 } from "lucide-react"; +import { toast } from "sonner"; + +interface BasicContractTemplateViewerProps { + templateId?: number; + filePath?: string; + instance: WebViewerInstance | null; + setInstance: Dispatch>; +} + +export function BasicContractTemplateViewer({ + templateId, + filePath, + instance, + setInstance, +}: BasicContractTemplateViewerProps) { + const [fileLoading, setFileLoading] = useState(true); + const viewer = useRef(null); + const initialized = useRef(false); + const isCancelled = useRef(false); + + // WebViewer 초기화 (기존 SignViewer와 완전히 동일) + useEffect(() => { + if (!initialized.current && viewer.current) { + initialized.current = true; + isCancelled.current = false; + + requestAnimationFrame(() => { + if (viewer.current) { + import("@pdftron/webviewer").then(({ default: WebViewer }) => { + if (isCancelled.current) { + console.log("📛 WebViewer 초기화 취소됨"); + return; + } + + // viewerElement이 확실히 존재함을 확인 + const viewerElement = viewer.current; + if (!viewerElement) return; + + WebViewer( + { + path: "/pdftronWeb", + licenseKey: process.env.NEXT_PUBLIC_PDFTRON_WEBVIEW_KEY, + fullAPI: true, + // 한글 입력 지원을 위한 설정 + enableOfficeEditing: true, // Office 편집 모드에서 IME 지원 필요 + l: "ko", // 한국어 로케일 설정 + }, + viewerElement + ).then((instance: WebViewerInstance) => { + setInstance(instance); + setFileLoading(false); + + try { + const { disableElements, enableElements, setToolbarGroup } = instance.UI; + + // 편집에 필요한 요소들 활성화 + enableElements([ + "toolbarGroup-Edit", + "toolbarGroup-Insert", + "textSelectButton", + "panToolButton" + ]); + + // 불필요한 요소들만 비활성화 + disableElements([ + "toolbarGroup-Annotate", // 주석 도구 + "toolbarGroup-Shapes", // 도형 도구 + "toolbarGroup-Forms", // 폼 도구 + "signatureToolButton", // 서명 도구 + "stampToolButton", // 스탬프 도구 + "rubberStampToolButton", // 러버스탬프 도구 + "freeHandToolButton", // 자유 그리기 + "stickyToolButton", // 스티키 노트 + "calloutToolButton", // 콜아웃 + ]); + + // 편집 툴바 설정 + setToolbarGroup("toolbarGroup-Edit"); + + // 한글 입력 지원을 위한 추가 설정 + const iframeWindow = instance.UI.iframeWindow; + if (iframeWindow && iframeWindow.document) { + // IME 지원 활성화 + const documentBody = iframeWindow.document.body; + if (documentBody) { + documentBody.style.imeMode = 'active'; + documentBody.setAttribute('lang', 'ko-KR'); + } + + // 키보드 이벤트 리스너 추가 (한글 입력 감지) + iframeWindow.document.addEventListener('compositionstart', (e) => { + console.log('🇰🇷 한글 입력 시작'); + }); + + iframeWindow.document.addEventListener('compositionend', (e) => { + console.log('🇰🇷 한글 입력 완료:', e.data); + }); + } + + console.log("📝 WebViewer 한글 지원 초기화 완료"); + } catch (uiError) { + console.warn("⚠️ UI 설정 중 오류 (무시됨):", uiError); + } + }).catch((error) => { + console.error("❌ WebViewer 초기화 실패:", error); + setFileLoading(false); + toast.error("뷰어 초기화에 실패했습니다."); + }); + }); + } + }); + } + + return () => { + if (instance) { + instance.UI.dispose(); + } + isCancelled.current = true; + setTimeout(() => cleanupHtmlStyle(), 500); + }; + }, []); + + // 문서 로드 (기존 SignViewer와 동일) + useEffect(() => { + if (!instance || !filePath) return; + + loadDocument(instance, filePath); + }, [instance, filePath]); + + // 한글 지원 Office 문서 로드 + const loadDocument = async (instance: WebViewerInstance, documentPath: string) => { + setFileLoading(true); + try { + // 절대 URL로 변환 + const fullPath = documentPath.startsWith('http') + ? documentPath + : `${window.location.origin}${documentPath}`; + + // 파일명 추출 + const fileName = documentPath.split('/').pop() || 'document.docx'; + + console.log("📄 한글 지원 Office 문서 로드 시작:", fullPath); + console.log("📎 파일명:", fileName); + + // PDFTron 공식 방법: instance.UI.loadDocument() + 한글 지원 옵션 + await instance.UI.loadDocument(fullPath, { + filename: fileName, + enableOfficeEditing: true, + // 한글 입력 지원을 위한 추가 옵션 + officeOptions: { + locale: 'ko-KR', + enableIME: true, + } + }); + + // 문서 로드 후 한글 입력 환경 설정 + setTimeout(() => { + try { + const iframeWindow = instance.UI.iframeWindow; + if (iframeWindow && iframeWindow.document) { + // Office 편집기 컨테이너 찾기 + const officeContainer = iframeWindow.document.querySelector('[data-office-editor]') || + iframeWindow.document.querySelector('.office-editor') || + iframeWindow.document.body; + + if (officeContainer) { + // 한글 입력 최적화 설정 + officeContainer.style.imeMode = 'active'; + officeContainer.setAttribute('lang', 'ko-KR'); + officeContainer.setAttribute('inputmode', 'text'); + + console.log("🇰🇷 한글 입력 환경 설정 완료"); + } + } + } catch (setupError) { + console.warn("⚠️ 한글 입력 환경 설정 실패:", setupError); + } + }, 1000); + + console.log("✅ 한글 지원 Office 편집 모드로 문서 로드 완료"); + toast.success("Office 편집 모드가 활성화되었습니다.", { + description: "한글 입력이 안 될 경우 외부에서 작성 후 복사-붙여넣기를 사용하세요." + }); + + } catch (err) { + console.error("❌ Office 문서 로딩 중 오류:", err); + toast.error(`Office 문서 로드 실패: ${err instanceof Error ? err.message : '알 수 없는 오류'}`); + } finally { + setFileLoading(false); + } + }; + + // 기존 SignViewer와 동일한 렌더링 (확대 문제 해결) + return ( +
+
+ {fileLoading && ( +
+ +

문서 로딩 중...

+
+ )} +
+
+ ); +} + +// WebViewer 정리 함수 (기존과 동일) +const cleanupHtmlStyle = () => { + // iframe 스타일 정리 (WebViewer가 추가한 스타일) + const elements = document.querySelectorAll('.Document_container'); + elements.forEach((elem) => { + elem.remove(); + }); +}; \ No newline at end of file diff --git a/lib/basic-contract/template/basic-contract-template.tsx b/lib/basic-contract/template/basic-contract-template.tsx index 0cca3a41..4fc70af4 100644 --- a/lib/basic-contract/template/basic-contract-template.tsx +++ b/lib/basic-contract/template/basic-contract-template.tsx @@ -1,6 +1,7 @@ "use client"; import * as React from "react"; +import { useRouter } from "next/navigation"; import { DataTable } from "@/components/data-table/data-table"; import { useDataTable } from "@/hooks/use-data-table"; import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"; @@ -15,7 +16,6 @@ import { UpdateTemplateSheet } from "./update-basicContract-sheet"; import { TemplateTableToolbarActions } from "./basicContract-table-toolbar-actions"; import { BasicContractTemplate } from "@/db/schema"; - interface BasicTemplateTableProps { promises: Promise< [ @@ -24,21 +24,17 @@ interface BasicTemplateTableProps { > } - export function BasicContractTemplateTable({ promises }: BasicTemplateTableProps) { - - + const router = useRouter(); const [rowAction, setRowAction] = React.useState | null>(null) - - const [{ data, pageCount }] = React.use(promises) - // 컬럼 설정 - 외부 파일에서 가져옴 + // 컬럼 설정 - router를 전달 const columns = React.useMemo( - () => getColumns({ setRowAction }), - [setRowAction] + () => getColumns({ setRowAction, router }), + [setRowAction, router] ) // config 기반으로 필터 필드 설정 @@ -47,7 +43,7 @@ export function BasicContractTemplateTable({ promises }: BasicTemplateTableProps { id: "status", label: "상태", type: "select", options: [ { label: "활성", value: "ACTIVE" }, - { label: "비활성", value: "INACTIVE" }, + { label: "폐기", value: "DISPOSED" }, ] }, { id: "fileName", label: "파일명", type: "text" }, @@ -59,7 +55,6 @@ export function BasicContractTemplateTable({ promises }: BasicTemplateTableProps data, columns, pageCount, - // filterFields, enablePinning: true, enableAdvancedFilter: true, initialState: { @@ -73,15 +68,13 @@ export function BasicContractTemplateTable({ promises }: BasicTemplateTableProps return ( <> - - + - - + setRowAction(null)} template={rowAction?.row.original ?? null} /> - - - - ); -} \ No newline at end of file + + ); +} \ No newline at end of file diff --git a/lib/basic-contract/template/template-editor-wrapper.tsx b/lib/basic-contract/template/template-editor-wrapper.tsx new file mode 100644 index 00000000..ea353b91 --- /dev/null +++ b/lib/basic-contract/template/template-editor-wrapper.tsx @@ -0,0 +1,353 @@ +"use client"; + +import * as React from "react"; +import { Button } from "@/components/ui/button"; +import { toast } from "sonner"; +import { Save, RefreshCw, Type, FileText, AlertCircle } from "lucide-react"; +import type { WebViewerInstance } from "@pdftron/webviewer"; +import { Badge } from "@/components/ui/badge"; +import { BasicContractTemplateViewer } from "./basic-contract-template-viewer"; +import { saveTemplateFile } from "../service"; + +interface TemplateEditorWrapperProps { + templateId: string | number; + filePath: string; + fileName: string; + refreshAction?: () => Promise; +} + +// 변수 패턴 감지를 위한 정규식 +const VARIABLE_PATTERN = /\{\{([^}]+)\}\}/g; + +export function TemplateEditorWrapper({ + templateId, + filePath, + fileName, + refreshAction +}: TemplateEditorWrapperProps) { + const [instance, setInstance] = React.useState(null); + const [isSaving, setIsSaving] = React.useState(false); + const [documentVariables, setDocumentVariables] = React.useState([]); + + // 문서에서 변수 추출 + const extractVariablesFromDocument = async () => { + if (!instance) return; + + try { + const { documentViewer } = instance.Core; + const doc = documentViewer.getDocument(); + + if (!doc) return; + + // 문서 텍스트 추출 + const textContent = await doc.getDocumentCompletePromise().then(async () => { + const pageCount = doc.getPageCount(); + let fullText = ""; + + for (let i = 1; i <= pageCount; i++) { + try { + const pageText = await doc.loadPageText(i); + fullText += pageText + " "; + } catch (error) { + console.warn(`페이지 ${i} 텍스트 추출 실패:`, error); + } + } + + return fullText; + }); + + // 변수 패턴 매칭 + const matches = textContent.match(VARIABLE_PATTERN); + const variables = matches + ? [...new Set(matches.map(match => match.replace(/[{}]/g, '')))] + : []; + + setDocumentVariables(variables); + + if (variables.length > 0) { + console.log("🔍 발견된 변수들:", variables); + } + + } catch (error) { + console.error("변수 추출 중 오류:", error); + } + }; + + // 인스턴스가 변경될 때마다 변수 추출 + React.useEffect(() => { + if (instance) { + // 문서 로드 완료 이벤트 리스너 추가 + const { documentViewer } = instance.Core; + + const onDocumentLoaded = () => { + setTimeout(() => extractVariablesFromDocument(), 1000); + }; + + documentViewer.addEventListener("documentLoaded", onDocumentLoaded); + + return () => { + documentViewer.removeEventListener("documentLoaded", onDocumentLoaded); + }; + } + }, [instance]); + + // 변수 삽입 함수 (한글 입력 제한 고려) + const insertVariable = async (variableName: string) => { + if (!instance) { + toast.error("뷰어가 준비되지 않았습니다."); + return; + } + + try { + const textToInsert = `{{${variableName}}}`; + + // 1단계: 클립보드 API 시도 + if (navigator.clipboard && navigator.clipboard.writeText) { + try { + await navigator.clipboard.writeText(textToInsert); + toast.success(`변수 "${textToInsert}"가 클립보드에 복사되었습니다.`, { + description: "문서에서 원하는 위치에 Ctrl+V로 붙여넣기 하세요." + }); + return; + } catch (clipboardError) { + console.warn("클립보드 API 사용 실패:", clipboardError); + } + } + + // 2단계: Office 편집기에 직접 삽입 시도 (실험적) + try { + const { documentViewer } = instance.Core; + const doc = documentViewer.getDocument(); + + if (doc && typeof doc.getOfficeEditor === 'function') { + const officeEditor = doc.getOfficeEditor(); + if (officeEditor && typeof officeEditor.insertText === 'function') { + await officeEditor.insertText(textToInsert); + toast.success(`변수 "${textToInsert}"가 문서에 삽입되었습니다.`); + return; + } + } + } catch (insertError) { + console.warn("직접 삽입 실패:", insertError); + } + + // 3단계: 임시 텍스트 영역을 통한 복사 (대안) + try { + const tempTextArea = document.createElement('textarea'); + tempTextArea.value = textToInsert; + tempTextArea.style.position = 'fixed'; + tempTextArea.style.left = '-9999px'; + document.body.appendChild(tempTextArea); + tempTextArea.select(); + document.execCommand('copy'); + document.body.removeChild(tempTextArea); + + toast.success(`변수 "${textToInsert}"가 클립보드에 복사되었습니다.`, { + description: "Office 편집기에서 한글 입력이 제한될 수 있습니다. 외부에서 작성 후 붙여넣기를 권장합니다." + }); + return; + } catch (fallbackError) { + console.warn("대안 복사 실패:", fallbackError); + } + + // 4단계: 수동 입력 안내 + toast.info(`다음 변수를 수동으로 입력해주세요: ${textToInsert}`, { + description: "한글과 변수는 외부 에디터에서 작성 후 복사-붙여넣기를 권장합니다.", + duration: 8000, + }); + + } catch (error) { + console.error("변수 삽입 오류:", error); + toast.error("변수 삽입 중 오류가 발생했습니다."); + } + }; + + // 문서 저장 + const handleSave = async () => { + if (!instance) { + toast.error("뷰어가 준비되지 않았습니다."); + return; + } + + setIsSaving(true); + try { + const { documentViewer } = instance.Core; + const doc = documentViewer.getDocument(); + + if (!doc) { + throw new Error("문서를 찾을 수 없습니다."); + } + + // Word 문서 저장 + const data = await doc.getFileData({ + downloadType: "office", // Word 파일로 저장 + includeAnnotations: true + }); + + // FormData 생성하여 서버 액션에 전달 + const formData = new FormData(); + formData.append('file', new Blob([data], { + type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + }), fileName); + + // 서버 액션 호출 + const result = await saveTemplateFile(Number(templateId), formData); + + if (result.error) { + throw new Error(result.error); + } + + toast.success("템플릿이 성공적으로 저장되었습니다."); + + // 변수 재추출 + await extractVariablesFromDocument(); + + // 페이지 새로고침 (서버 액션) + if (refreshAction) { + await refreshAction(); + } + + } catch (error) { + console.error("저장 오류:", error); + toast.error(error instanceof Error ? error.message : "저장 중 오류가 발생했습니다."); + } finally { + setIsSaving(false); + } + }; + + // 문서 새로고침 + const handleRefresh = () => { + window.location.reload(); + }; + + // 미리 정의된 변수들 + const predefinedVariables = [ + "회사명", "계약자명", "계약일자", "계약금액", + "납기일자", "담당자명", "담당자연락처", "프로젝트명", + "계약번호", "사업부", "부서명", "승인자명" + ]; + + return ( +
+ {/* 상단 도구 모음 */} +
+
+
+ + + +
+ +
+ + + {fileName} + + {documentVariables.length > 0 && ( + + + 변수 {documentVariables.length}개 + + )} +
+
+ + {/* 변수 도구 */} + {(documentVariables.length > 0 || predefinedVariables.length > 0) && ( +
+
+

+ + 변수 관리 +

+
+ +
+ {/* 발견된 변수들 */} + {documentVariables.length > 0 && ( +
+

문서에서 발견된 변수:

+
+ {documentVariables.map((variable, index) => ( + + {`{{${variable}}}`} + + ))} +
+
+ )} + + {/* 미리 정의된 변수들 */} +
+

자주 사용하는 변수 (클릭하여 복사):

+
+ {predefinedVariables.map((variable, index) => ( + + ))} +
+
+
+
+ )} +
+ + {/* 뷰어 영역 (확대 문제 해결을 위한 컨테이너 격리) */} +
+
+ +
+
+ + {/* 하단 안내 (한글 입력 팁 포함) */} +
+
+
+ + {'{{변수명}}'} 형식으로 변수를 삽입하면 계약서 생성 시 실제 값으로 치환됩니다. +
+
+ + 한글 입력 제한시 외부 에디터에서 작성 후 복사-붙여넣기를 사용하세요. +
+
+
+
+ ); +} \ No newline at end of file diff --git a/lib/basic-contract/template/update-basicContract-sheet.tsx b/lib/basic-contract/template/update-basicContract-sheet.tsx index 810e1b77..88783461 100644 --- a/lib/basic-contract/template/update-basicContract-sheet.tsx +++ b/lib/basic-contract/template/update-basicContract-sheet.tsx @@ -47,15 +47,30 @@ import { } from "@/components/ui/dropzone" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Separator } from "@/components/ui/separator" -import { Badge } from "@/components/ui/badge" import { updateTemplate } from "../service" import { BasicContractTemplate } from "@/db/schema" import { BUSINESS_UNITS, scopeHelpers } from "@/config/basicContractColumnsConfig" -// 업데이트 템플릿 스키마 정의 +// 템플릿 이름 옵션 정의 +const TEMPLATE_NAME_OPTIONS = [ + "준법서약", + "기술자료 요구서", + "비밀유지 계약서", + "표준하도급기본 계약서", + "General GTC", + "안전보건관리 약정서", + "동반성장", + "윤리규범 준수 서약서", + "기술자료 동의서", + "내국신용장 미개설 합의서", + "직납자재 하도급대급등 연동제 의향서" +] as const; + +// 업데이트 템플릿 스키마 정의 (templateCode, status 제거, 워드파일만 허용) export const updateTemplateSchema = z.object({ - templateCode: z.string().min(1, "템플릿 코드는 필수입니다."), // readonly로 처리 - templateName: z.string().min(1, "템플릿 이름은 필수입니다."), + templateName: z.enum(TEMPLATE_NAME_OPTIONS, { + required_error: "템플릿 이름을 선택해주세요.", + }), revision: z.coerce.number().int().min(1, "리비전은 1 이상이어야 합니다."), legalReviewRequired: z.boolean(), @@ -69,10 +84,18 @@ export const updateTemplateSchema = z.object({ sysApplicable: z.boolean(), infraApplicable: z.boolean(), - status: z.enum(["ACTIVE", "DISPOSED"], { - required_error: "상태는 필수 선택사항입니다.", - }), - file: z.instanceof(File, { message: "파일을 업로드해주세요." }).optional(), + file: z + .instanceof(File, { message: "파일을 업로드해주세요." }) + .refine((file) => file.size <= 100 * 1024 * 1024, { + message: "파일 크기는 100MB 이하여야 합니다.", + }) + .refine( + (file) => + file.type === 'application/msword' || + file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + { message: "워드 파일(.doc, .docx)만 업로드 가능합니다." } + ) + .optional(), }).refine((data) => { // 적어도 하나의 적용 범위는 선택되어야 함 const hasAnyScope = BUSINESS_UNITS.some(unit => @@ -99,8 +122,7 @@ export function UpdateTemplateSheet({ template, onSuccess, ...props }: UpdateTem const form = useForm({ resolver: zodResolver(updateTemplateSchema), defaultValues: { - templateCode: template?.templateCode ?? "", - templateName: template?.templateName ?? "", + templateName: template?.templateName as typeof TEMPLATE_NAME_OPTIONS[number] ?? "준법서약", revision: template?.revision ?? 1, legalReviewRequired: template?.legalReviewRequired ?? false, shipBuildingApplicable: template?.shipBuildingApplicable ?? false, @@ -111,7 +133,6 @@ export function UpdateTemplateSheet({ template, onSuccess, ...props }: UpdateTem gyApplicable: template?.gyApplicable ?? false, sysApplicable: template?.sysApplicable ?? false, infraApplicable: template?.infraApplicable ?? false, - status: (template?.status as "ACTIVE" | "DISPOSED") || "ACTIVE" }, mode: "onChange" }) @@ -136,8 +157,7 @@ export function UpdateTemplateSheet({ template, onSuccess, ...props }: UpdateTem React.useEffect(() => { if (template) { form.reset({ - templateCode: template.templateCode, - templateName: template.templateName, + templateName: template.templateName as typeof TEMPLATE_NAME_OPTIONS[number], revision: template.revision ?? 1, legalReviewRequired: template.legalReviewRequired ?? false, shipBuildingApplicable: template.shipBuildingApplicable ?? false, @@ -148,7 +168,6 @@ export function UpdateTemplateSheet({ template, onSuccess, ...props }: UpdateTem gyApplicable: template.gyApplicable ?? false, sysApplicable: template.sysApplicable ?? false, infraApplicable: template.infraApplicable ?? false, - status: template.status as "ACTIVE" | "DISPOSED", }); } }, [template, form]); @@ -162,9 +181,8 @@ export function UpdateTemplateSheet({ template, onSuccess, ...props }: UpdateTem startUpdateTransition(async () => { if (!template) return - // FormData 객체 생성하여 파일과 데이터를 함께 전송 + // FormData 객체 생성하여 파일과 데이터를 함께 전송 (templateCode, status 제거) const formData = new FormData(); - formData.append("templateCode", input.templateCode); formData.append("templateName", input.templateName); formData.append("revision", input.revision.toString()); formData.append("legalReviewRequired", input.legalReviewRequired.toString()); @@ -175,8 +193,6 @@ export function UpdateTemplateSheet({ template, onSuccess, ...props }: UpdateTem formData.append(unit.key, value.toString()); }); - formData.append("status", input.status); - if (input.file) { formData.append("file", input.file); } @@ -209,259 +225,242 @@ export function UpdateTemplateSheet({ template, onSuccess, ...props }: UpdateTem return ( - - + + {/* 고정된 헤더 */} + 템플릿 업데이트 템플릿 정보를 수정하고 변경사항을 저장하세요 + * 표시된 항목은 필수 입력사항입니다. -
- - {/* 기본 정보 */} - - - 기본 정보 - - 현재 적용 범위: {scopeHelpers.getScopeDisplayText(template)} - - - -
- ( - - 템플릿 코드 - - - - - 템플릿 코드는 수정할 수 없습니다. - - - )} - /> + {/* 스크롤 가능한 컨텐츠 영역 */} +
+ + + {/* 기본 정보 */} + + + 기본 정보 + + 현재 적용 범위: {scopeHelpers.getScopeDisplayText(template)} + + + +
+ ( + + + 템플릿 이름 * + + + + 미리 정의된 템플릿 중에서 선택 + + + + )} + /> + + ( + + 리비전 + + field.onChange(parseInt(e.target.value) || 1)} + /> + + + 템플릿 버전을 업데이트하세요. +
+ + 동일한 템플릿 이름의 리비전은 중복될 수 없습니다. + +
+ +
+ )} + /> +
( - - 리비전 + +
+ 법무검토 필요 + + 법무팀 검토가 필요한 템플릿인지 설정 + +
- field.onChange(parseInt(e.target.value) || 1)} + - - 템플릿 버전을 업데이트하세요. - -
)} /> -
+ + - ( - - 템플릿 이름 - - - - - + {/* 적용 범위 */} + + + + 적용 범위 * + + + 이 템플릿이 적용될 사업부를 선택하세요. ({selectedScopesCount}개 선택됨) + + + +
+ + +
+ + + +
+ {BUSINESS_UNITS.map((unit) => ( + ( + + + + +
+ + {unit.label} + +
+
+ )} + /> + ))} +
+ + {form.formState.errors.shipBuildingApplicable && ( +

+ {form.formState.errors.shipBuildingApplicable.message} +

)} - /> +
+
-
+ {/* 파일 업데이트 */} + + + 파일 업데이트 + + 현재 파일: {template.fileName} + + + ( + name="file" + render={() => ( - 상태 - + 템플릿 파일 (선택사항) + + + + + + {selectedFile + ? selectedFile.name + : "새 워드 파일을 드래그하세요 (선택사항)"} + + + {selectedFile + ? `파일 크기: ${(selectedFile.size / (1024 * 1024)).toFixed(2)} MB` + : "또는 클릭하여 워드 파일(.doc, .docx)을 선택하세요 (최대 100MB)"} + + + + + )} /> -
- - ( - -
- 법무검토 필요 - - 법무팀 검토가 필요한 템플릿인지 설정 - -
- - - -
- )} - /> - - - - {/* 적용 범위 */} - - - 적용 범위 - - 이 템플릿이 적용될 사업부를 선택하세요. ({selectedScopesCount}개 선택됨) - - - -
- - -
- - - -
- {BUSINESS_UNITS.map((unit) => ( - ( - - - - -
- - {unit.label} - -
-
- )} - /> - ))} -
- - {form.formState.errors.shipBuildingApplicable && ( -

- {form.formState.errors.shipBuildingApplicable.message} -

- )} -
-
+ + + + +
- {/* 파일 업데이트 */} - - - 파일 업데이트 - - 현재 파일: {template.fileName} - - - - ( - - 템플릿 파일 (선택사항) - - - - - - {selectedFile - ? selectedFile.name - : "새 파일을 드래그하세요 (선택사항)"} - - - {selectedFile - ? `파일 크기: ${(selectedFile.size / (1024 * 1024)).toFixed(2)} MB` - : "또는 클릭하여 파일을 선택하세요"} - - - - - - - - )} - /> - - - - - - - - - - - + {/* 고정된 푸터 */} + + + + + +
) diff --git a/lib/email-template/editor/template-editor.tsx b/lib/email-template/editor/template-editor.tsx index 68cade45..dc77a558 100644 --- a/lib/email-template/editor/template-editor.tsx +++ b/lib/email-template/editor/template-editor.tsx @@ -58,13 +58,13 @@ export function TemplateEditor({ templateSlug, initialTemplate }: TemplateEditor {/* 헤더 액션 버튼들 */} -
+ {/*
-
+
*/} @@ -166,7 +166,6 @@ export function TemplateEditor({ templateSlug, initialTemplate }: TemplateEditor
  • • 변수 관리에서 필요한 변수 추가
  • • 설정에서 카테고리 및 설명 수정
  • -
  • • 테스트 발송으로 실제 이메일 확인
diff --git a/lib/evaluation-target-list/service.ts b/lib/evaluation-target-list/service.ts index 251561f9..1c133e3a 100644 --- a/lib/evaluation-target-list/service.ts +++ b/lib/evaluation-target-list/service.ts @@ -305,7 +305,7 @@ export async function createEvaluationTarget( and( eq(evaluationTargets.evaluationYear, input.evaluationYear), eq(evaluationTargets.vendorId, input.vendorId), - eq(evaluationTargets.materialType, input.materialType) + eq(evaluationTargets.division, input.division) ) ) .limit(1); diff --git a/lib/file-download.ts b/lib/file-download.ts index 5e0350a0..68c4677a 100644 --- a/lib/file-download.ts +++ b/lib/file-download.ts @@ -300,6 +300,7 @@ const fetchWithTimeout = async (url: string, options: RequestInit = {}): Promise try { const response = await fetch(url, { ...options, + credentials: 'include', signal: controller.signal, }); clearTimeout(timeoutId); diff --git a/lib/sedp/sync-form.ts b/lib/sedp/sync-form.ts index f9e63caf..559c09a2 100644 --- a/lib/sedp/sync-form.ts +++ b/lib/sedp/sync-form.ts @@ -835,6 +835,7 @@ async function getUomById(projectCode: string, uomId: string): Promise> { try { if (!itemCodes.length) return new Map(); @@ -870,7 +871,7 @@ async function getContractItemsByItemCodes(itemCodes: string[], projectId: numbe ) ); - // itemCode와 contractItemId 배열의 매핑 생성 + // itemCode와 contractItemId 배열의 매핑 생성 (수정된 부분) const itemCodeToContractItemIds = new Map(); for (const item of itemRecords) { @@ -878,9 +879,17 @@ async function getContractItemsByItemCodes(itemCodes: string[], projectId: numbe if (item.packageCode) { const matchedContractItems = contractItemRecords.filter(ci => ci.itemId === item.id); if (matchedContractItems.length > 0) { - // 일치하는 모든 contractItem을 배열로 저장 const contractItemIds = matchedContractItems.map(ci => ci.id); - itemCodeToContractItemIds.set(item.packageCode, contractItemIds); + + // 기존에 해당 packageCode가 있다면 배열에 추가, 없다면 새로 생성 + if (itemCodeToContractItemIds.has(item.packageCode)) { + const existing = itemCodeToContractItemIds.get(item.packageCode)!; + // 중복 제거하면서 합치기 + const combined = [...new Set([...existing, ...contractItemIds])]; + itemCodeToContractItemIds.set(item.packageCode, combined); + } else { + itemCodeToContractItemIds.set(item.packageCode, contractItemIds); + } } } } @@ -927,7 +936,7 @@ export async function saveFormMappingsAndMetas( /* 2. Contract‑item look‑up (TOOL_TYPE) - 수정된 부분 */ /* ------------------------------------------------------------------ */ const uniqueItemCodes = [...new Set(newRegisters.filter(nr => nr.TOOL_TYPE).map(nr => nr.TOOL_TYPE as string))]; - const itemCodeToContractItemIds = await getContractItemsByItemCodes(uniqueItemCodes, projectId); + const itemCodeToContractItemIds = await getContractItemsByItemCodes(uniqueItemCodes, projectId, projectCode); /* ------------------------------------------------------------------ */ /* 3. Buffers for bulk insert */ diff --git a/lib/sedp/sync-package.ts b/lib/sedp/sync-package.ts index cdbb5987..0261e448 100644 --- a/lib/sedp/sync-package.ts +++ b/lib/sedp/sync-package.ts @@ -2,7 +2,7 @@ // src/lib/cron/syncItemsFromCodeLists.ts import db from "@/db/db"; import { projects, items } from '@/db/schema'; -import { eq } from 'drizzle-orm'; +import { eq, and } from 'drizzle-orm'; import { getSEDPToken } from "./sedp-token"; const SEDP_API_BASE_URL = process.env.SEDP_API_BASE_URL || 'http://sedpwebapi.ship.samsung.co.kr/api'; @@ -154,14 +154,15 @@ export async function syncItemsFromCodeLists(): Promise { // 기존 아이템 확인 (itemCode로 조회) const existingItem = await db.select() .from(items) - .where(eq(items.itemCode, codeValue.VALUE)) + .where(and(eq(items.itemCode, codeValue.VALUE),eq(items.ProjectNo, project.code))) .limit(1); if (existingItem.length > 0) { // 기존 아이템 업데이트 await db.update(items) .set(itemData) - .where(eq(items.itemCode, codeValue.VALUE)); + .where(and(eq(items.itemCode, codeValue.VALUE),eq(items.ProjectNo, project.code))) + totalItemsUpdated++; } else { // 새 아이템 삽입 @@ -253,13 +254,13 @@ export async function syncItemsForProject(projectCode: string): Promise { // 기존 아이템 확인 const existingItem = await db.select() .from(items) - .where(eq(items.itemCode, codeValue.VALUE)) + .where(and(eq(items.itemCode, codeValue.VALUE),eq(items.ProjectNo, projectCode))) .limit(1); if (existingItem.length > 0) { await db.update(items) .set(itemData) - .where(eq(items.itemCode, codeValue.VALUE)); + .where(and(eq(items.itemCode, codeValue.VALUE),eq(items.ProjectNo, projectCode))); itemsUpdated++; } else { await db.insert(items).values(itemData); diff --git a/lib/tech-vendor-candidates/service.ts b/lib/tech-vendor-candidates/service.ts deleted file mode 100644 index 47832236..00000000 --- a/lib/tech-vendor-candidates/service.ts +++ /dev/null @@ -1,395 +0,0 @@ -"use server"; // Next.js 서버 액션에서 직접 import하려면 (선택) - -import { asc, desc, ilike, inArray, and, or, gte, lte, eq, count } from "drizzle-orm"; -import { revalidateTag } from "next/cache"; -import { filterColumns } from "@/lib/filter-columns"; -import { unstable_cache } from "@/lib/unstable-cache"; -import { getErrorMessage } from "@/lib/handle-error"; -import db from "@/db/db"; -import { sendEmail } from "../mail/sendEmail"; -import { CreateVendorCandidateSchema, createVendorCandidateSchema, GetTechVendorsCandidateSchema, RemoveTechCandidatesInput, removeTechCandidatesSchema, updateVendorCandidateSchema, UpdateVendorCandidateSchema } from "./validations"; -import { PgTransaction } from "drizzle-orm/pg-core"; -import { techVendorCandidates, techVendorCandidatesWithVendorInfo } from "@/db/schema/techVendors"; -import { headers } from 'next/headers'; - -export async function getVendorCandidates(input: GetTechVendorsCandidateSchema) { - return unstable_cache( - async () => { - try { - const offset = (input.page - 1) * input.perPage - const fromDate = input.from ? new Date(input.from) : undefined; - const toDate = input.to ? new Date(input.to) : undefined; - - // 1) Advanced filters - const advancedWhere = filterColumns({ - table: techVendorCandidatesWithVendorInfo, - filters: input.filters, - joinOperator: input.joinOperator, - }) - - // 2) Global search - let globalWhere - if (input.search) { - const s = `%${input.search}%` - globalWhere = or( - ilike(techVendorCandidatesWithVendorInfo.companyName, s), - ilike(techVendorCandidatesWithVendorInfo.contactEmail, s), - ilike(techVendorCandidatesWithVendorInfo.contactPhone, s), - ilike(techVendorCandidatesWithVendorInfo.country, s), - ilike(techVendorCandidatesWithVendorInfo.source, s), - ilike(techVendorCandidatesWithVendorInfo.status, s), - ilike(techVendorCandidatesWithVendorInfo.taxId, s), - ilike(techVendorCandidatesWithVendorInfo.items, s), - ilike(techVendorCandidatesWithVendorInfo.remark, s), - ilike(techVendorCandidatesWithVendorInfo.address, s), - // etc. - ) - } - - // 3) Combine finalWhere - const finalWhere = and( - advancedWhere, - globalWhere, - fromDate ? gte(techVendorCandidatesWithVendorInfo.createdAt, fromDate) : undefined, - toDate ? lte(techVendorCandidatesWithVendorInfo.createdAt, toDate) : undefined - ) - - // 5) Sorting - const orderBy = - input.sort && input.sort.length > 0 - ? input.sort.map((item) => - item.desc - ? desc(techVendorCandidatesWithVendorInfo[item.id]) - : asc(techVendorCandidatesWithVendorInfo[item.id]) - ) - : [desc(techVendorCandidatesWithVendorInfo.createdAt)] - - // 6) Query & count - const { data, total } = await db.transaction(async (tx) => { - // a) Select from the view - const candidatesData = await tx - .select() - .from(techVendorCandidatesWithVendorInfo) - .where(finalWhere) - .orderBy(...orderBy) - .offset(offset) - .limit(input.perPage) - - // b) Count total - const resCount = await tx - .select({ count: count() }) - .from(techVendorCandidatesWithVendorInfo) - .where(finalWhere) - - return { data: candidatesData, total: resCount[0]?.count } - }) - - // 7) Calculate pageCount - const pageCount = Math.ceil(total / input.perPage) - - return { data, pageCount } - } catch (err) { - console.error(err) - return { data: [], pageCount: 0 } - } - }, - // Cache key - [JSON.stringify(input)], - { - revalidate: 3600, - tags: ["tech-vendor-candidates"], - } - )() -} - -export async function createVendorCandidate(input: CreateVendorCandidateSchema) { - try { - // Validate input - const validated = createVendorCandidateSchema.parse(input); - - // 트랜잭션으로 데이터 삽입 - const result = await db.transaction(async (tx) => { - // Insert into database - const [newCandidate] = await tx - .insert(techVendorCandidates) - .values({ - companyName: validated.companyName, - contactEmail: validated.contactEmail, - contactPhone: validated.contactPhone || null, - taxId: validated.taxId || "", - address: validated.address || null, - country: validated.country || null, - source: validated.source || null, - status: validated.status || "COLLECTED", - remark: validated.remark || null, - items: validated.items || "", // items가 필수 필드이므로 빈 문자열이라도 제공 - vendorId: validated.vendorId || null, - updatedAt: new Date(), - }) - .returning(); - - return newCandidate; - }); - - // Invalidate cache - revalidateTag("tech-vendor-candidates"); - - return { success: true, data: result }; - } catch (error) { - console.error("Failed to create tech vendor candidate:", error); - return { success: false, error: getErrorMessage(error) }; - } -} - - -// Helper function to group tech vendor candidates by status -async function groupVendorCandidatesByStatus(tx: PgTransaction, Record, Record>) { - return tx - .select({ - status: techVendorCandidates.status, - count: count(), - }) - .from(techVendorCandidates) - .groupBy(techVendorCandidates.status); -} - -/** - * Get count of tech vendor candidates grouped by status - */ -export async function getVendorCandidateCounts() { - return unstable_cache( - async () => { - try { - // Initialize counts object with all possible statuses set to 0 - const initial: Record<"COLLECTED" | "INVITED" | "DISCARDED", number> = { - COLLECTED: 0, - INVITED: 0, - DISCARDED: 0, - }; - - // Execute query within transaction and transform results - const result = await db.transaction(async (tx) => { - const rows = await groupVendorCandidatesByStatus(tx); - return rows.reduce>((acc, { status, count }) => { - if (status in acc) { - acc[status] = count; - } - return acc; - }, initial); - }); - - return result; - } catch (err) { - console.error("Failed to get tech vendor candidate counts:", err); - return { - COLLECTED: 0, - INVITED: 0, - DISCARDED: 0, - }; - } - }, - ["tech-vendor-candidate-status-counts"], // Cache key - { - revalidate: 3600, // Revalidate every hour - } - )(); -} - - -/** - * Update a vendor candidate - */ -export async function updateVendorCandidate(input: UpdateVendorCandidateSchema) { - try { - // Validate input - const validated = updateVendorCandidateSchema.parse(input); - - // Prepare update data (excluding id) - const { id, ...updateData } = validated; - - const headersList = await headers(); - const host = headersList.get('host') || 'localhost:3000'; - - const baseUrl = `http://${host}` - - // Add updatedAt timestamp - const dataToUpdate = { - ...updateData, - updatedAt: new Date(), - }; - - const result = await db.transaction(async (tx) => { - // 현재 데이터 조회 (상태 변경 감지를 위해) - const [existingCandidate] = await tx - .select() - .from(techVendorCandidates) - .where(eq(techVendorCandidates.id, id)); - - if (!existingCandidate) { - throw new Error("Tech vendor candidate not found"); - } - - // Update database - const [updatedCandidate] = await tx - .update(techVendorCandidates) - .set(dataToUpdate) - .where(eq(techVendorCandidates.id, id)) - .returning(); - - // 로그 작성 - const statusChanged = - updateData.status && - existingCandidate.status !== updateData.status; - - // If status was updated to "INVITED", send email - if (statusChanged && updateData.status === "INVITED" && updatedCandidate.contactEmail) { - await sendEmail({ - to: updatedCandidate.contactEmail, - subject: "Invitation to Register as a Vendor", - template: "vendor-invitation", - context: { - companyName: updatedCandidate.companyName, - language: "en", - registrationLink: `${baseUrl}/en/partners`, - } - }); - } - - return updatedCandidate; - }); - - // Invalidate cache - revalidateTag("vendor-candidates"); - - return { success: true, data: result }; - } catch (error) { - console.error("Failed to update vendor candidate:", error); - return { success: false, error: getErrorMessage(error) }; - } -} - -export async function bulkUpdateVendorCandidateStatus({ - ids, - status, -}: { - ids: number[], - status: "COLLECTED" | "INVITED" | "DISCARDED", -}) { - try { - // Validate inputs - if (!ids.length) { - return { success: false, error: "No IDs provided" }; - } - - if (!["COLLECTED", "INVITED", "DISCARDED"].includes(status)) { - return { success: false, error: "Invalid status" }; - } - - const headersList = await headers(); - const host = headersList.get('host') || 'localhost:3000'; - - const baseUrl = `http://${host}` - - const result = await db.transaction(async (tx) => { - // Update all records - const updatedCandidates = await tx - .update(techVendorCandidates) - .set({ - status, - updatedAt: new Date(), - }) - .where(inArray(techVendorCandidates.id, ids)) - .returning(); - - // If status is "INVITED", send emails to all updated candidates - if (status === "INVITED") { - const emailPromises = updatedCandidates - .filter(candidate => candidate.contactEmail) - .map(async (candidate) => { - await sendEmail({ - to: candidate.contactEmail!, - subject: "Invitation to Register as a Vendor", - template: "vendor-invitation", - context: { - companyName: candidate.companyName, - language: "en", - registrationLink: `${baseUrl}/en/partners`, - } - }); - }); - - // Wait for all emails to be sent - await Promise.all(emailPromises); - } - - return updatedCandidates; - }); - - // Invalidate cache - revalidateTag("vendor-candidates"); - - return { - success: true, - data: result, - count: result.length - }; - } catch (error) { - console.error("Failed to bulk update vendor candidates:", error); - return { success: false, error: getErrorMessage(error) }; - } -} - -// 4. 후보자 삭제 함수 업데이트 -export async function removeCandidates(input: RemoveTechCandidatesInput) { - try { - // Validate input - const validated = removeTechCandidatesSchema.parse(input); - - const result = await db.transaction(async (tx) => { - // Get candidates before deletion (for logging purposes) - const candidatesBeforeDelete = await tx - .select() - .from(techVendorCandidates) - .where(inArray(techVendorCandidates.id, validated.ids)); - - // Delete the candidates - const deletedCandidates = await tx - .delete(techVendorCandidates) - .where(inArray(techVendorCandidates.id, validated.ids)) - .returning({ id: techVendorCandidates.id }); - - return { - deletedCandidates, - candidatesBeforeDelete - }; - }); - - // If no candidates were deleted, return an error - if (!result.deletedCandidates.length) { - return { - success: false, - error: "No candidates were found with the provided IDs", - }; - } - - // Log deletion for audit purposes - console.log( - `Deleted ${result.deletedCandidates.length} vendor candidates:`, - result.candidatesBeforeDelete.map(c => `${c.id} (${c.companyName})`) - ); - - // Invalidate cache - revalidateTag("vendor-candidates"); - revalidateTag("vendor-candidate-status-counts"); - revalidateTag("vendor-candidate-total-count"); - - return { - success: true, - count: result.deletedCandidates.length, - deletedIds: result.deletedCandidates.map(c => c.id), - }; - } catch (error) { - console.error("Failed to remove vendor candidates:", error); - return { success: false, error: getErrorMessage(error) }; - } -} \ No newline at end of file diff --git a/lib/tech-vendor-candidates/table/add-candidates-dialog.tsx b/lib/tech-vendor-candidates/table/add-candidates-dialog.tsx deleted file mode 100644 index 31c39137..00000000 --- a/lib/tech-vendor-candidates/table/add-candidates-dialog.tsx +++ /dev/null @@ -1,394 +0,0 @@ -"use client" - -import * as React from "react" -import { useForm } from "react-hook-form" -import { zodResolver } from "@hookform/resolvers/zod" -import { Check, ChevronsUpDown } from "lucide-react" -import i18nIsoCountries from "i18n-iso-countries" -import enLocale from "i18n-iso-countries/langs/en.json" -import koLocale from "i18n-iso-countries/langs/ko.json" -import { cn } from "@/lib/utils" -import { useSession } from "next-auth/react" // next-auth 세션 훅 추가 - -import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog" -import { Button } from "@/components/ui/button" -import { Input } from "@/components/ui/input" -import { Textarea } from "@/components/ui/textarea" -import { useToast } from "@/hooks/use-toast" -import { - Popover, - PopoverContent, - PopoverTrigger, -} from "@/components/ui/popover" -import { - Command, - CommandEmpty, - CommandGroup, - CommandInput, - CommandItem, - CommandList, -} from "@/components/ui/command" - -// react-hook-form + shadcn/ui Form -import { - Form, - FormControl, - FormField, - FormItem, - FormLabel, - FormMessage, -} from "@/components/ui/form" - - -import { createVendorCandidateSchema, CreateVendorCandidateSchema } from "../validations" -import { createVendorCandidate } from "../service" - -// Register locales for countries -i18nIsoCountries.registerLocale(enLocale) -i18nIsoCountries.registerLocale(koLocale) - -// Generate country array -const locale = "ko" -const countryMap = i18nIsoCountries.getNames(locale, { select: "official" }) -const countryArray = Object.entries(countryMap).map(([code, label]) => ({ - code, - label, -})) - -export function AddCandidateDialog() { - const [open, setOpen] = React.useState(false) - const [isSubmitting, setIsSubmitting] = React.useState(false) - const { toast } = useToast() - const { data: session, status } = useSession() - - // react-hook-form 세팅 - const form = useForm({ - resolver: zodResolver(createVendorCandidateSchema), - defaultValues: { - companyName: "", - contactEmail: "", // 필수 입력값 - contactPhone: "", - taxId: "", - address: "", - country: "", - source: "", - items: "", - remark: "", - status: "COLLECTED", - }, - }); - - async function onSubmit(data: CreateVendorCandidateSchema) { - setIsSubmitting(true) - try { - // 세션 유효성 검사 - if (!session || !session.user || !session.user.id) { - toast({ - title: "인증 오류", - description: "로그인 정보를 찾을 수 없습니다. 다시 로그인해주세요.", - variant: "destructive", - }) - return - } - - // userId 추출 (세션 구조에 따라 조정 필요) - const userId = session.user.id - - const result = await createVendorCandidate(data, Number(userId)) - if (result.error) { - toast({ - title: "오류 발생", - description: result.error, - variant: "destructive", - }) - return - } - // 성공 시 모달 닫고 폼 리셋 - toast({ - title: "등록 완료", - description: "협력업체 후보가 성공적으로 등록되었습니다.", - }) - form.reset() - setOpen(false) - } catch (error) { - console.error("Failed to create vendor candidate:", error) - toast({ - title: "오류 발생", - description: "예상치 못한 오류가 발생했습니다.", - variant: "destructive", - }) - } finally { - setIsSubmitting(false) - } - } - - function handleDialogOpenChange(nextOpen: boolean) { - if (!nextOpen) { - form.reset() - } - setOpen(nextOpen) - } - - return ( - - {/* 모달을 열기 위한 버튼 */} - - - - - - - Create New Vendor Candidate - - 새 Vendor Candidate 정보를 입력하고 Create 버튼을 누르세요. - - - - {/* shadcn/ui Form을 이용해 react-hook-form과 연결 */} -
- -
- {/* Company Name 필드 */} - ( - - Company Name * - - - - - - )} - /> - - {/* Tax ID 필드 (새로 추가) */} - ( - - Tax ID - - - - - - )} - /> - - {/* Contact Email 필드 */} - ( - - Contact Email* - - - - - - )} - /> - - {/* Contact Phone 필드 */} - ( - - Contact Phone - - - - - - )} - /> - - {/* Address 필드 */} - ( - - Address - - - - - - )} - /> - - {/* Country 필드 */} - { - const selectedCountry = countryArray.find( - (c) => c.code === field.value - ) - return ( - - Country - - - - - - - - - - - No country found. - - {countryArray.map((country) => ( - - field.onChange(country.code) - } - > - - {country.label} - - ))} - - - - - - - - ) - }} - /> - - {/* Source 필드 */} - ( - - Source * - - - - - - )} - /> - - - {/* Items 필드 (새로 추가) */} - ( - - Items * - -