diff options
Diffstat (limited to 'lib')
31 files changed, 1064 insertions, 3613 deletions
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<TemplateFormValues> = {
- 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() { <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
- name="templateCode"
+ name="templateName"
render={({ field }) => (
<FormItem>
<FormLabel>
- 템플릿 코드 <span className="text-red-500">*</span>
+ 템플릿 이름 <span className="text-red-500">*</span>
</FormLabel>
- <FormControl>
- <Input
- placeholder="TEMPLATE_001"
- {...field}
- style={{ textTransform: 'uppercase' }}
- onChange={(e) => field.onChange(e.target.value.toUpperCase())}
- />
- </FormControl>
+ <Select onValueChange={field.onChange} defaultValue={field.value}>
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue placeholder="템플릿 이름을 선택하세요" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ {TEMPLATE_NAME_OPTIONS.map((option) => (
+ <SelectItem key={option} value={option}>
+ {option}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
<FormDescription>
- 영문 대문자, 숫자, '_', '-'만 사용 가능
+ 미리 정의된 템플릿 중에서 선택
</FormDescription>
<FormMessage />
</FormItem>
@@ -338,6 +357,10 @@ export function AddTemplateDialog() { </FormControl>
<FormDescription>
템플릿 버전 (기본값: 1)
+ <br />
+ <span className="text-xs text-muted-foreground">
+ 동일한 템플릿 이름의 리비전은 중복될 수 없습니다.
+ </span>
</FormDescription>
<FormMessage />
</FormItem>
@@ -347,22 +370,6 @@ export function AddTemplateDialog() { <FormField
control={form.control}
- name="templateName"
- render={({ field }) => (
- <FormItem>
- <FormLabel>
- 템플릿 이름 <span className="text-red-500">*</span>
- </FormLabel>
- <FormControl>
- <Input placeholder="기본 계약서 템플릿" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
name="legalReviewRequired"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm">
@@ -459,18 +466,19 @@ export function AddTemplateDialog() { <Dropzone
onDrop={handleFileChange}
accept={{
- 'application/pdf': ['.pdf']
+ 'application/msword': ['.doc'],
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx']
}}
>
<DropzoneZone>
<DropzoneUploadIcon className="h-10 w-10 text-muted-foreground" />
<DropzoneTitle>
- {selectedFile ? selectedFile.name : "PDF 파일을 여기에 드래그하세요"}
+ {selectedFile ? selectedFile.name : "워드 파일을 여기에 드래그하세요"}
</DropzoneTitle>
<DropzoneDescription>
{selectedFile
? `파일 크기: ${(selectedFile.size / (1024 * 1024)).toFixed(2)} MB`
- : "또는 클릭하여 PDF 파일을 선택하세요 (최대 100MB)"}
+ : "또는 클릭하여 워드 파일(.doc, .docx)을 선택하세요 (최대 100MB)"}
</DropzoneDescription>
<DropzoneInput />
</DropzoneZone>
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<React.SetStateAction<DataTableRowAction<BasicContractTemplate> | null>>
+ router: ReturnType<typeof useRouter>
}
/**
- * 파일 다운로드 함수
+ * 파일 다운로드 함수 (공용 유틸리티 사용)
*/
-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<BasicContractTemplate>[] {
+export function getColumns({ setRowAction, router }: GetColumnsProps): ColumnDef<BasicContractTemplate>[] {
// ----------------------------------------------------------------
// 1) select 컬럼 (체크박스)
// ----------------------------------------------------------------
@@ -126,6 +118,10 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<BasicCo const [isUpdatePending, startUpdateTransition] = React.useTransition()
const template = row.original;
+ const handleViewDetails = () => {
+ router.push(`/evcp/basic-contract-template/${template.id}`);
+ };
+
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -138,6 +134,13 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<BasicCo </Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-40">
+ <DropdownMenuItem onSelect={handleViewDetails}>
+ <Eye className="mr-2 h-4 w-4" />
+ View Details
+ </DropdownMenuItem>
+
+ <DropdownMenuSeparator />
+
<DropdownMenuItem
onSelect={() => setRowAction({ row, type: "update" })}
>
@@ -201,27 +204,20 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<BasicCo header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약문서명" />,
cell: ({ row }) => {
const template = row.original;
- const scopeText = scopeHelpers.getScopeDisplayText(template);
+
+ const handleClick = () => {
+ router.push(`/evcp/basic-contract-template/${template.id}`);
+ };
+
return (
<div className="flex flex-col min-w-0">
- <span className="truncate">{template.templateName}</span>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <span className="text-xs text-muted-foreground cursor-help truncate">
- {scopeText}
- </span>
- </TooltipTrigger>
- <TooltipContent>
- <div className="space-y-1">
- <p className="font-medium">적용 범위:</p>
- {scopeHelpers.getApplicableScopeLabels(template).map(label => (
- <p key={label} className="text-xs">• {label}</p>
- ))}
- </div>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
+ <button
+ onClick={handleClick}
+ className="truncate text-left hover:text-blue-600 hover:underline cursor-pointer transition-colors"
+ title="클릭하여 상세보기"
+ >
+ {template.templateName}
+ </button>
</div>
);
},
@@ -229,18 +225,6 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<BasicCo enableResizing: true,
},
{
- accessorKey: "templateCode",
- header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약문서 번호" />,
- cell: ({ row }) => {
- const template = row.original;
- return (
- <span className="font-medium">{template.templateCode}</span>
- );
- },
- size: 120,
- enableResizing: true,
- },
- {
accessorKey: "revision",
header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="Rev." />,
cell: ({ row }) => {
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<SetStateAction<WebViewerInstance | null>>; +} + +export function BasicContractTemplateViewer({ + templateId, + filePath, + instance, + setInstance, +}: BasicContractTemplateViewerProps) { + const [fileLoading, setFileLoading] = useState<boolean>(true); + const viewer = useRef<HTMLDivElement>(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 ( + <div className="relative w-full h-full overflow-hidden"> + <div + ref={viewer} + className="w-full h-full" + style={{ + position: 'relative', + overflow: 'hidden', + contain: 'layout style paint', // CSS containment로 격리 + }} + > + {fileLoading && ( + <div className="absolute inset-0 flex flex-col items-center justify-center bg-white bg-opacity-90 z-10"> + <Loader2 className="h-8 w-8 text-blue-500 animate-spin mb-4" /> + <p className="text-sm text-muted-foreground">문서 로딩 중...</p> + </div> + )} + </div> + </div> + ); +} + +// 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<DataTableRowAction<BasicContractTemplate> | 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 ( <> - - <DataTable table={table}> + <DataTable table={table}> <DataTableAdvancedToolbar table={table} filterFields={advancedFilterFields} > <TemplateTableToolbarActions table={table} /> - - </DataTableAdvancedToolbar> + </DataTableAdvancedToolbar> </DataTable> <DeleteTemplatesDialog @@ -97,8 +90,6 @@ export function BasicContractTemplateTable({ promises }: BasicTemplateTableProps onOpenChange={() => 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<void>; +} + +// 변수 패턴 감지를 위한 정규식 +const VARIABLE_PATTERN = /\{\{([^}]+)\}\}/g; + +export function TemplateEditorWrapper({ + templateId, + filePath, + fileName, + refreshAction +}: TemplateEditorWrapperProps) { + const [instance, setInstance] = React.useState<WebViewerInstance | null>(null); + const [isSaving, setIsSaving] = React.useState(false); + const [documentVariables, setDocumentVariables] = React.useState<string[]>([]); + + // 문서에서 변수 추출 + 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 ( + <div className="h-full flex flex-col"> + {/* 상단 도구 모음 */} + <div className="border-b bg-gray-50 p-3"> + <div className="flex items-center justify-between"> + <div className="flex items-center space-x-2"> + <Button + variant="outline" + size="sm" + onClick={handleSave} + disabled={isSaving || !instance} + > + {isSaving ? ( + <> + <RefreshCw className="mr-2 h-4 w-4 animate-spin" /> + 저장 중... + </> + ) : ( + <> + <Save className="mr-2 h-4 w-4" /> + 저장 + </> + )} + </Button> + + <Button + variant="outline" + size="sm" + onClick={handleRefresh} + > + <RefreshCw className="mr-2 h-4 w-4" /> + 새로고침 + </Button> + </div> + + <div className="flex items-center space-x-2"> + <Badge variant="outline"> + <FileText className="mr-1 h-3 w-3" /> + {fileName} + </Badge> + {documentVariables.length > 0 && ( + <Badge variant="secondary"> + <Type className="mr-1 h-3 w-3" /> + 변수 {documentVariables.length}개 + </Badge> + )} + </div> + </div> + + {/* 변수 도구 */} + {(documentVariables.length > 0 || predefinedVariables.length > 0) && ( + <div className="mt-3 p-3 bg-white rounded border"> + <div className="mb-2"> + <h4 className="text-sm font-medium flex items-center"> + <Type className="mr-2 h-4 w-4 text-blue-500" /> + 변수 관리 + </h4> + </div> + + <div className="space-y-3"> + {/* 발견된 변수들 */} + {documentVariables.length > 0 && ( + <div> + <p className="text-xs text-muted-foreground mb-2">문서에서 발견된 변수:</p> + <div className="flex flex-wrap gap-1"> + {documentVariables.map((variable, index) => ( + <Badge key={index} variant="outline" className="text-xs"> + {`{{${variable}}}`} + </Badge> + ))} + </div> + </div> + )} + + {/* 미리 정의된 변수들 */} + <div> + <p className="text-xs text-muted-foreground mb-2">자주 사용하는 변수 (클릭하여 복사):</p> + <div className="flex flex-wrap gap-1"> + {predefinedVariables.map((variable, index) => ( + <Button + key={index} + variant="ghost" + size="sm" + className="h-6 px-2 text-xs" + onClick={() => insertVariable(variable)} + > + {`{{${variable}}}`} + </Button> + ))} + </div> + </div> + </div> + </div> + )} + </div> + + {/* 뷰어 영역 (확대 문제 해결을 위한 컨테이너 격리) */} + <div className="flex-1 relative overflow-hidden"> + <div className="absolute inset-0"> + <BasicContractTemplateViewer + templateId={templateId} + filePath={filePath} + instance={instance} + setInstance={setInstance} + /> + </div> + </div> + + {/* 하단 안내 (한글 입력 팁 포함) */} + <div className="border-t bg-gray-50 p-2"> + <div className="flex items-center justify-between text-xs text-muted-foreground"> + <div className="flex items-center"> + <AlertCircle className="inline h-3 w-3 mr-1" /> + {'{{변수명}}'} 형식으로 변수를 삽입하면 계약서 생성 시 실제 값으로 치환됩니다. + </div> + <div className="flex items-center text-orange-600"> + <AlertCircle className="inline h-3 w-3 mr-1" /> + 한글 입력 제한시 외부 에디터에서 작성 후 복사-붙여넣기를 사용하세요. + </div> + </div> + </div> + </div> + ); +}
\ 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<UpdateTemplateSchema>({ 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 ( <Sheet {...props}> - <SheetContent className="flex flex-col gap-6 sm:max-w-[600px] overflow-y-auto"> - <SheetHeader className="text-left"> + <SheetContent className="sm:max-w-[600px] h-[100vh] flex flex-col p-0"> + {/* 고정된 헤더 */} + <SheetHeader className="p-6 pb-4 border-b"> <SheetTitle>템플릿 업데이트</SheetTitle> <SheetDescription> 템플릿 정보를 수정하고 변경사항을 저장하세요 + <span className="text-red-500 mt-1 block text-sm">* 표시된 항목은 필수 입력사항입니다.</span> </SheetDescription> </SheetHeader> - <Form {...form}> - <form - onSubmit={form.handleSubmit(onSubmit)} - className="flex flex-col gap-6" - > - {/* 기본 정보 */} - <Card> - <CardHeader> - <CardTitle className="text-lg">기본 정보</CardTitle> - <CardDescription> - 현재 적용 범위: {scopeHelpers.getScopeDisplayText(template)} - </CardDescription> - </CardHeader> - <CardContent className="space-y-4"> - <div className="grid grid-cols-1 md:grid-cols-2 gap-4"> - <FormField - control={form.control} - name="templateCode" - render={({ field }) => ( - <FormItem> - <FormLabel>템플릿 코드</FormLabel> - <FormControl> - <Input - {...field} - readOnly - className="bg-muted" - /> - </FormControl> - <FormDescription> - 템플릿 코드는 수정할 수 없습니다. - </FormDescription> - </FormItem> - )} - /> + {/* 스크롤 가능한 컨텐츠 영역 */} + <div className="flex-1 overflow-y-auto px-6"> + <Form {...form}> + <form + onSubmit={form.handleSubmit(onSubmit)} + className="space-y-6 py-4" + > + {/* 기본 정보 */} + <Card> + <CardHeader> + <CardTitle className="text-lg">기본 정보</CardTitle> + <CardDescription> + 현재 적용 범위: {scopeHelpers.getScopeDisplayText(template)} + </CardDescription> + </CardHeader> + <CardContent className="space-y-4"> + <div className="grid grid-cols-1 md:grid-cols-2 gap-4"> + <FormField + control={form.control} + name="templateName" + render={({ field }) => ( + <FormItem> + <FormLabel> + 템플릿 이름 <span className="text-red-500">*</span> + </FormLabel> + <Select onValueChange={field.onChange} defaultValue={field.value}> + <FormControl> + <SelectTrigger> + <SelectValue placeholder="템플릿 이름을 선택하세요" /> + </SelectTrigger> + </FormControl> + <SelectContent> + <SelectGroup> + {TEMPLATE_NAME_OPTIONS.map((option) => ( + <SelectItem key={option} value={option}> + {option} + </SelectItem> + ))} + </SelectGroup> + </SelectContent> + </Select> + <FormDescription> + 미리 정의된 템플릿 중에서 선택 + </FormDescription> + <FormMessage /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="revision" + render={({ field }) => ( + <FormItem> + <FormLabel>리비전</FormLabel> + <FormControl> + <Input + type="number" + min="1" + {...field} + onChange={(e) => field.onChange(parseInt(e.target.value) || 1)} + /> + </FormControl> + <FormDescription> + 템플릿 버전을 업데이트하세요. + <br /> + <span className="text-xs text-muted-foreground"> + 동일한 템플릿 이름의 리비전은 중복될 수 없습니다. + </span> + </FormDescription> + <FormMessage /> + </FormItem> + )} + /> + </div> <FormField control={form.control} - name="revision" + name="legalReviewRequired" render={({ field }) => ( - <FormItem> - <FormLabel>리비전</FormLabel> + <FormItem className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm"> + <div className="space-y-0.5"> + <FormLabel>법무검토 필요</FormLabel> + <FormDescription> + 법무팀 검토가 필요한 템플릿인지 설정 + </FormDescription> + </div> <FormControl> - <Input - type="number" - min="1" - {...field} - onChange={(e) => field.onChange(parseInt(e.target.value) || 1)} + <Switch + checked={field.value} + onCheckedChange={field.onChange} /> </FormControl> - <FormDescription> - 템플릿 버전을 업데이트하세요. - </FormDescription> - <FormMessage /> </FormItem> )} /> - </div> + </CardContent> + </Card> - <FormField - control={form.control} - name="templateName" - render={({ field }) => ( - <FormItem> - <FormLabel>템플릿 이름</FormLabel> - <FormControl> - <Input placeholder="템플릿 이름을 입력하세요" {...field} /> - </FormControl> - <FormMessage /> - </FormItem> + {/* 적용 범위 */} + <Card> + <CardHeader> + <CardTitle className="text-lg"> + 적용 범위 <span className="text-red-500">*</span> + </CardTitle> + <CardDescription> + 이 템플릿이 적용될 사업부를 선택하세요. ({selectedScopesCount}개 선택됨) + </CardDescription> + </CardHeader> + <CardContent className="space-y-4"> + <div className="flex items-center space-x-2"> + <Checkbox + id="select-all" + checked={selectedScopesCount === BUSINESS_UNITS.length} + onCheckedChange={handleSelectAllScopes} + /> + <label htmlFor="select-all" className="text-sm font-medium"> + 전체 선택 + </label> + </div> + + <Separator /> + + <div className="grid grid-cols-2 md:grid-cols-4 gap-4"> + {BUSINESS_UNITS.map((unit) => ( + <FormField + key={unit.key} + control={form.control} + name={unit.key as keyof UpdateTemplateSchema} + render={({ field }) => ( + <FormItem className="flex flex-row items-start space-x-3 space-y-0"> + <FormControl> + <Checkbox + checked={field.value as boolean} + onCheckedChange={field.onChange} + /> + </FormControl> + <div className="space-y-1 leading-none"> + <FormLabel className="text-sm font-normal"> + {unit.label} + </FormLabel> + </div> + </FormItem> + )} + /> + ))} + </div> + + {form.formState.errors.shipBuildingApplicable && ( + <p className="text-sm text-destructive"> + {form.formState.errors.shipBuildingApplicable.message} + </p> )} - /> + </CardContent> + </Card> - <div className="grid grid-cols-1 md:grid-cols-2 gap-4"> + {/* 파일 업데이트 */} + <Card> + <CardHeader> + <CardTitle className="text-lg">파일 업데이트</CardTitle> + <CardDescription> + 현재 파일: {template.fileName} + </CardDescription> + </CardHeader> + <CardContent> <FormField control={form.control} - name="status" - render={({ field }) => ( + name="file" + render={() => ( <FormItem> - <FormLabel>상태</FormLabel> - <Select - defaultValue={field.value} - onValueChange={field.onChange} - > - <FormControl> - <SelectTrigger> - <SelectValue placeholder="템플릿 상태 선택" /> - </SelectTrigger> - </FormControl> - <SelectContent> - <SelectGroup> - <SelectItem value="ACTIVE">활성</SelectItem> - <SelectItem value="DISPOSED">폐기</SelectItem> - </SelectGroup> - </SelectContent> - </Select> + <FormLabel>템플릿 파일 (선택사항)</FormLabel> + <FormControl> + <Dropzone + onDrop={handleFileChange} + accept={{ + 'application/msword': ['.doc'], + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'] + }} + > + <DropzoneZone> + <DropzoneUploadIcon className="h-10 w-10 text-muted-foreground" /> + <DropzoneTitle> + {selectedFile + ? selectedFile.name + : "새 워드 파일을 드래그하세요 (선택사항)"} + </DropzoneTitle> + <DropzoneDescription> + {selectedFile + ? `파일 크기: ${(selectedFile.size / (1024 * 1024)).toFixed(2)} MB` + : "또는 클릭하여 워드 파일(.doc, .docx)을 선택하세요 (최대 100MB)"} + </DropzoneDescription> + <DropzoneInput /> + </DropzoneZone> + </Dropzone> + </FormControl> <FormMessage /> </FormItem> )} /> - </div> - - <FormField - control={form.control} - name="legalReviewRequired" - render={({ field }) => ( - <FormItem className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm"> - <div className="space-y-0.5"> - <FormLabel>법무검토 필요</FormLabel> - <FormDescription> - 법무팀 검토가 필요한 템플릿인지 설정 - </FormDescription> - </div> - <FormControl> - <Switch - checked={field.value} - onCheckedChange={field.onChange} - /> - </FormControl> - </FormItem> - )} - /> - </CardContent> - </Card> - - {/* 적용 범위 */} - <Card> - <CardHeader> - <CardTitle className="text-lg">적용 범위</CardTitle> - <CardDescription> - 이 템플릿이 적용될 사업부를 선택하세요. ({selectedScopesCount}개 선택됨) - </CardDescription> - </CardHeader> - <CardContent className="space-y-4"> - <div className="flex items-center space-x-2"> - <Checkbox - id="select-all" - checked={selectedScopesCount === BUSINESS_UNITS.length} - onCheckedChange={handleSelectAllScopes} - /> - <label htmlFor="select-all" className="text-sm font-medium"> - 전체 선택 - </label> - </div> - - <Separator /> - - <div className="grid grid-cols-2 md:grid-cols-4 gap-4"> - {BUSINESS_UNITS.map((unit) => ( - <FormField - key={unit.key} - control={form.control} - name={unit.key as keyof UpdateTemplateSchema} - render={({ field }) => ( - <FormItem className="flex flex-row items-start space-x-3 space-y-0"> - <FormControl> - <Checkbox - checked={field.value as boolean} - onCheckedChange={field.onChange} - /> - </FormControl> - <div className="space-y-1 leading-none"> - <FormLabel className="text-sm font-normal"> - {unit.label} - </FormLabel> - </div> - </FormItem> - )} - /> - ))} - </div> - - {form.formState.errors.shipBuildingApplicable && ( - <p className="text-sm text-destructive"> - {form.formState.errors.shipBuildingApplicable.message} - </p> - )} - </CardContent> - </Card> + </CardContent> + </Card> + </form> + </Form> + </div> - {/* 파일 업데이트 */} - <Card> - <CardHeader> - <CardTitle className="text-lg">파일 업데이트</CardTitle> - <CardDescription> - 현재 파일: {template.fileName} - </CardDescription> - </CardHeader> - <CardContent> - <FormField - control={form.control} - name="file" - render={() => ( - <FormItem> - <FormLabel>템플릿 파일 (선택사항)</FormLabel> - <FormControl> - <Dropzone - onDrop={handleFileChange} - accept={{ - 'application/pdf': ['.pdf'] - }} - > - <DropzoneZone> - <DropzoneUploadIcon className="h-10 w-10 text-muted-foreground" /> - <DropzoneTitle> - {selectedFile - ? selectedFile.name - : "새 파일을 드래그하세요 (선택사항)"} - </DropzoneTitle> - <DropzoneDescription> - {selectedFile - ? `파일 크기: ${(selectedFile.size / (1024 * 1024)).toFixed(2)} MB` - : "또는 클릭하여 파일을 선택하세요"} - </DropzoneDescription> - <DropzoneInput /> - </DropzoneZone> - </Dropzone> - </FormControl> - <FormMessage /> - </FormItem> - )} - /> - </CardContent> - </Card> - - <SheetFooter className="gap-2 pt-2 sm:space-x-0"> - <SheetClose asChild> - <Button type="button" variant="outline"> - 취소 - </Button> - </SheetClose> - <Button - type="submit" - disabled={isUpdatePending || !form.formState.isValid} - > - {isUpdatePending && ( - <Loader - className="mr-2 size-4 animate-spin" - aria-hidden="true" - /> - )} - 저장 - </Button> - </SheetFooter> - </form> - </Form> + {/* 고정된 푸터 */} + <SheetFooter className="p-6 pt-4 border-t"> + <SheetClose asChild> + <Button type="button" variant="outline"> + 취소 + </Button> + </SheetClose> + <Button + type="button" + onClick={form.handleSubmit(onSubmit)} + disabled={isUpdatePending || !form.formState.isValid} + > + {isUpdatePending && ( + <Loader + className="mr-2 size-4 animate-spin" + aria-hidden="true" + /> + )} + 저장 + </Button> + </SheetFooter> </SheetContent> </Sheet> ) 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 </div> {/* 헤더 액션 버튼들 */} - <div className="flex items-center gap-2"> + {/* <div className="flex items-center gap-2"> <Button variant="outline" size="sm" asChild> <Link href={`/evcp/templates/${template.slug}/send`}> 테스트 발송 </Link> </Button> - </div> + </div> */} </div> <Separator /> @@ -166,7 +166,6 @@ export function TemplateEditor({ templateSlug, initialTemplate }: TemplateEditor <ul className="space-y-1 text-purple-800"> <li>• 변수 관리에서 필요한 변수 추가</li> <li>• 설정에서 카테고리 및 설명 수정</li> - <li>• 테스트 발송으로 실제 이메일 확인</li> </ul> </div> </div> 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<UOM | nul } // contractItemId 조회 함수 +// contractItemId 조회 함수 (수정됨) async function getContractItemsByItemCodes(itemCodes: string[], projectId: number): Promise<Map<string, number[]>> { 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<string, number[]>(); 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<void> { // 기존 아이템 확인 (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<void> { // 기존 아이템 확인 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<string, never>, Record<string, never>, Record<string, never>>) { - 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<Record<string, number>>((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<CreateVendorCandidateSchema>({ - 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 ( - <Dialog open={open} onOpenChange={handleDialogOpenChange}> - {/* 모달을 열기 위한 버튼 */} - <DialogTrigger asChild> - <Button variant="default" size="sm"> - Add Vendor Candidate - </Button> - </DialogTrigger> - - <DialogContent className="sm:max-w-[525px]"> - <DialogHeader> - <DialogTitle>Create New Vendor Candidate</DialogTitle> - <DialogDescription> - 새 Vendor Candidate 정보를 입력하고 <b>Create</b> 버튼을 누르세요. - </DialogDescription> - </DialogHeader> - - {/* shadcn/ui Form을 이용해 react-hook-form과 연결 */} - <Form {...form}> - <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6"> - <div className="grid grid-cols-1 md:grid-cols-2 gap-4"> - {/* Company Name 필드 */} - <FormField - control={form.control} - name="companyName" - render={({ field }) => ( - <FormItem> - <FormLabel>Company Name <span className="text-red-500">*</span></FormLabel> - <FormControl> - <Input - placeholder="Enter company name" - {...field} - disabled={isSubmitting} - /> - </FormControl> - <FormMessage /> - </FormItem> - )} - /> - - {/* Tax ID 필드 (새로 추가) */} - <FormField - control={form.control} - name="taxId" - render={({ field }) => ( - <FormItem> - <FormLabel>Tax ID</FormLabel> - <FormControl> - <Input - placeholder="Tax identification number" - {...field} - disabled={isSubmitting} - /> - </FormControl> - <FormMessage /> - </FormItem> - )} - /> - - {/* Contact Email 필드 */} - <FormField - control={form.control} - name="contactEmail" - render={({ field }) => ( - <FormItem> - <FormLabel>Contact Email<span className="text-red-500">*</span></FormLabel> - <FormControl> - <Input - placeholder="email@example.com" - type="email" - {...field} - disabled={isSubmitting} - /> - </FormControl> - <FormMessage /> - </FormItem> - )} - /> - - {/* Contact Phone 필드 */} - <FormField - control={form.control} - name="contactPhone" - render={({ field }) => ( - <FormItem> - <FormLabel>Contact Phone</FormLabel> - <FormControl> - <Input - placeholder="+82-10-1234-5678" - {...field} - disabled={isSubmitting} - /> - </FormControl> - <FormMessage /> - </FormItem> - )} - /> - - {/* Address 필드 */} - <FormField - control={form.control} - name="address" - render={({ field }) => ( - <FormItem className="col-span-full"> - <FormLabel>Address</FormLabel> - <FormControl> - <Input - placeholder="Company address" - {...field} - disabled={isSubmitting} - /> - </FormControl> - <FormMessage /> - </FormItem> - )} - /> - - {/* Country 필드 */} - <FormField - control={form.control} - name="country" - render={({ field }) => { - const selectedCountry = countryArray.find( - (c) => c.code === field.value - ) - return ( - <FormItem> - <FormLabel>Country</FormLabel> - <Popover> - <PopoverTrigger asChild> - <FormControl> - <Button - variant="outline" - role="combobox" - className={cn( - "w-full justify-between", - !field.value && "text-muted-foreground" - )} - disabled={isSubmitting} - > - {selectedCountry - ? selectedCountry.label - : "Select a country"} - <ChevronsUpDown className="ml-2 h-4 w-4 opacity-50" /> - </Button> - </FormControl> - </PopoverTrigger> - <PopoverContent className="w-[300px] p-0"> - <Command> - <CommandInput placeholder="Search country..." /> - <CommandList> - <CommandEmpty>No country found.</CommandEmpty> - <CommandGroup className="max-h-[300px] overflow-y-auto"> - {countryArray.map((country) => ( - <CommandItem - key={country.code} - value={country.label} - onSelect={() => - field.onChange(country.code) - } - > - <Check - className={cn( - "mr-2 h-4 w-4", - country.code === field.value - ? "opacity-100" - : "opacity-0" - )} - /> - {country.label} - </CommandItem> - ))} - </CommandGroup> - </CommandList> - </Command> - </PopoverContent> - </Popover> - <FormMessage /> - </FormItem> - ) - }} - /> - - {/* Source 필드 */} - <FormField - control={form.control} - name="source" - render={({ field }) => ( - <FormItem> - <FormLabel>Source <span className="text-red-500">*</span></FormLabel> - <FormControl> - <Input - placeholder="Where this candidate was found" - {...field} - disabled={isSubmitting} - /> - </FormControl> - <FormMessage /> - </FormItem> - )} - /> - - - {/* Items 필드 (새로 추가) */} - <FormField - control={form.control} - name="items" - render={({ field }) => ( - <FormItem className="col-span-full"> - <FormLabel>Items <span className="text-red-500">*</span></FormLabel> - <FormControl> - <Textarea - placeholder="List of items or products this vendor provides" - className="min-h-[80px]" - {...field} - disabled={isSubmitting} - /> - </FormControl> - <FormMessage /> - </FormItem> - )} - /> - - {/* Remark 필드 (새로 추가) */} - <FormField - control={form.control} - name="remark" - render={({ field }) => ( - <FormItem className="col-span-full"> - <FormLabel>Remarks</FormLabel> - <FormControl> - <Textarea - placeholder="Additional notes or comments" - className="min-h-[80px]" - {...field} - disabled={isSubmitting} - /> - </FormControl> - <FormMessage /> - </FormItem> - )} - /> - </div> - - <DialogFooter> - <Button - type="button" - variant="outline" - onClick={() => setOpen(false)} - disabled={isSubmitting} - > - Cancel - </Button> - <Button type="submit" disabled={isSubmitting}> - {isSubmitting ? "Creating..." : "Create"} - </Button> - </DialogFooter> - </form> - </Form> - </DialogContent> - </Dialog> - ) -}
\ No newline at end of file diff --git a/lib/tech-vendor-candidates/table/candidates-table-columns.tsx b/lib/tech-vendor-candidates/table/candidates-table-columns.tsx deleted file mode 100644 index aa6d0ef1..00000000 --- a/lib/tech-vendor-candidates/table/candidates-table-columns.tsx +++ /dev/null @@ -1,199 +0,0 @@ -"use client" - -import * as React from "react" -import { type DataTableRowAction } from "@/types/table" -import { type ColumnDef } from "@tanstack/react-table" -import { Ellipsis } from "lucide-react" -import { toast } from "sonner" - -import { getErrorMessage } from "@/lib/handle-error" -import { formatDate, formatDateTime } from "@/lib/utils" -import { Badge } from "@/components/ui/badge" -import { Button } from "@/components/ui/button" -import { Checkbox } from "@/components/ui/checkbox" -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuRadioGroup, - DropdownMenuRadioItem, - DropdownMenuSeparator, - DropdownMenuShortcut, - DropdownMenuSub, - DropdownMenuSubContent, - DropdownMenuSubTrigger, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu" - -import { getCandidateStatusIcon } from "@/lib/vendor-candidates/utils" -import { candidateColumnsConfig } from "@/config/candidatesColumnsConfig" -import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header" -import { VendorCandidatesWithVendorInfo } from "@/db/schema" - -interface GetColumnsProps { - setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<VendorCandidatesWithVendorInfo> | null>> -} - -/** - * tanstack table 컬럼 정의 (중첩 헤더 버전) - */ -export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<VendorCandidatesWithVendorInfo>[] { - // ---------------------------------------------------------------- - // 1) select 컬럼 (체크박스) - // ---------------------------------------------------------------- - const selectColumn: ColumnDef<VendorCandidatesWithVendorInfo> = { - id: "select", - header: ({ table }) => ( - <Checkbox - checked={ - table.getIsAllPageRowsSelected() || - (table.getIsSomePageRowsSelected() && "indeterminate") - } - onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)} - aria-label="Select all" - className="translate-y-0.5" - /> - ), - cell: ({ row }) => ( - <Checkbox - checked={row.getIsSelected()} - onCheckedChange={(value) => row.toggleSelected(!!value)} - aria-label="Select row" - className="translate-y-0.5" - /> - ), - size:40, - enableSorting: false, - enableHiding: false, - } - - // ---------------------------------------------------------------- - // 2) actions 컬럼 (Dropdown 메뉴) - // ---------------------------------------------------------------- -// "actions" 컬럼 예시 -const actionsColumn: ColumnDef<VendorCandidatesWithVendorInfo> = { - id: "actions", - enableHiding: false, - cell: function Cell({ row }) { - return ( - <DropdownMenu> - <DropdownMenuTrigger asChild> - <Button - aria-label="Open menu" - variant="ghost" - className="flex size-8 p-0 data-[state=open]:bg-muted" - > - <Ellipsis className="size-4" aria-hidden="true" /> - </Button> - </DropdownMenuTrigger> - <DropdownMenuContent align="end" className="w-40"> - <DropdownMenuItem - onSelect={() => setRowAction({ row, type: "update" })} - > - 편집 - </DropdownMenuItem> - <DropdownMenuItem - onSelect={() => setRowAction({ row, type: "delete" })} - > - 삭제 - <DropdownMenuShortcut>⌘⌫</DropdownMenuShortcut> - </DropdownMenuItem> - - {/* 여기서 Log 보기 액션 추가 */} - <DropdownMenuItem - onSelect={() => setRowAction({ row, type: "log" })} - > - 감사 로그 보기 - </DropdownMenuItem> - </DropdownMenuContent> - </DropdownMenu> - ) - }, - size: 40, -} - - - // ---------------------------------------------------------------- - // 3) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성 - // ---------------------------------------------------------------- - // 3-1) groupMap: { [groupName]: ColumnDef<VendorCandidatesWithVendorInfo>[] } - const groupMap: Record<string, ColumnDef<VendorCandidatesWithVendorInfo>[]> = {} - - candidateColumnsConfig.forEach((cfg) => { - // 만약 group가 없으면 "_noGroup" 처리 - const groupName = cfg.group || "_noGroup" - - if (!groupMap[groupName]) { - groupMap[groupName] = [] - } - - // child column 정의 - const childCol: ColumnDef<VendorCandidatesWithVendorInfo> = { - accessorKey: cfg.id, - enableResizing: true, - header: ({ column }) => ( - <DataTableColumnHeaderSimple column={column} title={cfg.label} /> - ), - meta: { - excelHeader: cfg.excelHeader, - group: cfg.group, - type: cfg.type, - }, - cell: ({ row, cell }) => { - - if (cfg.id === "status") { - const statusVal = row.original.status - if (!statusVal) return null - const Icon = getCandidateStatusIcon(statusVal) - return ( - <div className="flex w-[6.25rem] items-center"> - <Icon className="mr-2 size-4 text-muted-foreground" aria-hidden="true" /> - <span className="capitalize">{statusVal}</span> - </div> - ) - } - - - if (cfg.id === "createdAt" ||cfg.id === "updatedAt" ) { - const dateVal = cell.getValue() as Date - return formatDateTime(dateVal, "KR") - } - - // code etc... - return row.getValue(cfg.id) ?? "" - }, - } - - groupMap[groupName].push(childCol) - }) - - // ---------------------------------------------------------------- - // 3-2) groupMap에서 실제 상위 컬럼(그룹)을 만들기 - // ---------------------------------------------------------------- - const nestedColumns: ColumnDef<VendorCandidatesWithVendorInfo>[] = [] - - // 순서를 고정하고 싶다면 group 순서를 미리 정의하거나 sort해야 함 - // 여기서는 그냥 Object.entries 순서 - Object.entries(groupMap).forEach(([groupName, colDefs]) => { - if (groupName === "_noGroup") { - // 그룹 없음 → 그냥 최상위 레벨 컬럼 - nestedColumns.push(...colDefs) - } else { - // 상위 컬럼 - nestedColumns.push({ - id: groupName, - header: groupName, // "Basic Info", "Metadata" 등 - columns: colDefs, - }) - } - }) - - // ---------------------------------------------------------------- - // 4) 최종 컬럼 배열: select, nestedColumns, actions - // ---------------------------------------------------------------- - return [ - selectColumn, - ...nestedColumns, - actionsColumn, - ] -}
\ No newline at end of file diff --git a/lib/tech-vendor-candidates/table/candidates-table-floating-bar.tsx b/lib/tech-vendor-candidates/table/candidates-table-floating-bar.tsx deleted file mode 100644 index baf4a583..00000000 --- a/lib/tech-vendor-candidates/table/candidates-table-floating-bar.tsx +++ /dev/null @@ -1,395 +0,0 @@ -"use client" - -import * as React from "react" -import { SelectTrigger } from "@radix-ui/react-select" -import { type Table } from "@tanstack/react-table" -import { - ArrowUp, - CheckCircle2, - Download, - Loader, - Trash2, - X, - Mail, -} from "lucide-react" -import { toast } from "sonner" - -import { exportTableToExcel } from "@/lib/export" -import { Button } from "@/components/ui/button" -import { Portal } from "@/components/ui/portal" -import { - Select, - SelectContent, - SelectGroup, - SelectItem, -} from "@/components/ui/select" -import { Separator } from "@/components/ui/separator" -import { - Tooltip, - TooltipContent, - TooltipTrigger, -} from "@/components/ui/tooltip" -import { Kbd } from "@/components/kbd" -import { useSession } from "next-auth/react" // next-auth 세션 훅 - -import { ActionConfirmDialog } from "@/components/ui/action-dialog" -import { VendorCandidatesWithVendorInfo, vendorCandidates } from "@/db/schema/vendors" -import { - bulkUpdateVendorCandidateStatus, - removeCandidates, -} from "../service" - -/** - * 테이블 상단/하단에 고정되는 Floating Bar - * 상태 일괄 변경, 초대, 삭제, Export 등을 수행 - */ -interface CandidatesTableFloatingBarProps { - table: Table<VendorCandidatesWithVendorInfo> -} - -export function VendorCandidateTableFloatingBar({ - table, -}: CandidatesTableFloatingBarProps) { - const rows = table.getFilteredSelectedRowModel().rows - const { data: session, status } = useSession() - - // React 18의 startTransition 사용 (isPending으로 트랜지션 상태 확인) - const [isPending, startTransition] = React.useTransition() - const [action, setAction] = React.useState< - "update-status" | "export" | "delete" | "invite" - >() - const [popoverOpen, setPopoverOpen] = React.useState(false) - - // ESC 키로 selection 해제 - React.useEffect(() => { - function handleKeyDown(event: KeyboardEvent) { - if (event.key === "Escape") { - table.toggleAllRowsSelected(false) - } - } - window.addEventListener("keydown", handleKeyDown) - return () => window.removeEventListener("keydown", handleKeyDown) - }, [table]) - - // 공용 Confirm Dialog (ActionConfirmDialog) 제어 - const [confirmDialogOpen, setConfirmDialogOpen] = React.useState(false) - const [confirmProps, setConfirmProps] = React.useState<{ - title: string - description?: string - onConfirm: () => Promise<void> | void - }>({ - title: "", - description: "", - onConfirm: () => {}, - }) - - /** - * 1) 삭제 버튼 클릭 시 Confirm Dialog 열기 - */ - function handleDeleteConfirm() { - setAction("delete") - - setConfirmProps({ - title: `Delete ${rows.length} candidate${ - rows.length > 1 ? "s" : "" - }?`, - description: "This action cannot be undone.", - onConfirm: async () => { - startTransition(async () => { - if (!session?.user?.id) { - toast.error("인증 오류. 로그인 정보를 찾을 수 없습니다.") - return - } - const userId = Number(session.user.id) - - // removeCandidates 호출 시 userId를 넘긴다고 가정 - const { error } = await removeCandidates( - { - ids: rows.map((row) => row.original.id), - }, - userId - ) - - if (error) { - toast.error(error) - return - } - toast.success("Candidates deleted successfully") - table.toggleAllRowsSelected(false) - setConfirmDialogOpen(false) - }) - }, - }) - setConfirmDialogOpen(true) - } - - /** - * 2) 선택된 후보들의 상태 일괄 업데이트 - */ - function handleSelectStatus(newStatus: VendorCandidatesWithVendorInfo["status"]) { - setAction("update-status") - - setConfirmProps({ - title: `Update ${rows.length} candidate${ - rows.length > 1 ? "s" : "" - } with status: ${newStatus}?`, - description: "This action will override their current status.", - onConfirm: async () => { - startTransition(async () => { - if (!session?.user?.id) { - toast.error("인증 오류. 로그인 정보를 찾을 수 없습니다.") - return - } - const userId = Number(session.user.id) - - const { error } = await bulkUpdateVendorCandidateStatus({ - ids: rows.map((row) => row.original.id), - status: newStatus, - userId, - comment: `Bulk status update to ${newStatus}`, - }) - - if (error) { - toast.error(error) - return - } - toast.success("Candidates updated") - setConfirmDialogOpen(false) - table.toggleAllRowsSelected(false) - }) - }, - }) - setConfirmDialogOpen(true) - } - - /** - * 3) 초대하기 (status = "INVITED" + 이메일 발송) - */ - function handleInvite() { - setAction("invite") - setConfirmProps({ - title: `Invite ${rows.length} candidate${ - rows.length > 1 ? "s" : "" - }?`, - description: - "This will change their status to INVITED and send invitation emails.", - onConfirm: async () => { - startTransition(async () => { - if (!session?.user?.id) { - toast.error("인증 오류. 로그인 정보를 찾을 수 없습니다.") - return - } - const userId = Number(session.user.id) - - const { error } = await bulkUpdateVendorCandidateStatus({ - ids: rows.map((row) => row.original.id), - status: "INVITED", - userId, - comment: "Bulk invite action", - }) - - if (error) { - toast.error(error) - return - } - toast.success("Invitation emails sent successfully") - table.toggleAllRowsSelected(false) - setConfirmDialogOpen(false) - }) - }, - }) - setConfirmDialogOpen(true) - } - - return ( - <> - {/* 선택된 row가 있을 때 표시되는 Floating Bar */} - <div className="flex justify-center w-full my-4"> - <div className="flex items-center gap-2 rounded-md border bg-background p-2 text-foreground shadow"> - {/* 선택된 갯수 표시 + Clear selection 버튼 */} - <div className="flex h-7 items-center rounded-md border border-dashed pl-2.5 pr-1"> - <span className="whitespace-nowrap text-xs"> - {rows.length} selected - </span> - <Separator orientation="vertical" className="ml-2 mr-1" /> - <Tooltip> - <TooltipTrigger asChild> - <Button - variant="ghost" - size="icon" - className="size-5 hover:border" - onClick={() => table.toggleAllRowsSelected(false)} - > - <X className="size-3.5 shrink-0" aria-hidden="true" /> - </Button> - </TooltipTrigger> - <TooltipContent className="flex items-center border bg-accent px-2 py-1 font-semibold text-foreground dark:bg-zinc-900"> - <p className="mr-2">Clear selection</p> - <Kbd abbrTitle="Escape" variant="outline"> - Esc - </Kbd> - </TooltipContent> - </Tooltip> - </div> - - <Separator orientation="vertical" className="hidden h-5 sm:block" /> - - {/* 우측 액션들: 초대, 상태변경, Export, 삭제 */} - <div className="flex items-center gap-1.5"> - {/* 초대하기 */} - <Tooltip> - <TooltipTrigger asChild> - <Button - variant="secondary" - size="sm" - className="h-7 border" - onClick={handleInvite} - disabled={isPending} - > - {isPending && action === "invite" ? ( - <Loader - className="mr-1 size-3.5 animate-spin" - aria-hidden="true" - /> - ) : ( - <Mail className="mr-1 size-3.5" aria-hidden="true" /> - )} - <span>Invite</span> - </Button> - </TooltipTrigger> - <TooltipContent className="border bg-accent font-semibold text-foreground dark:bg-zinc-900"> - <p>Send invitation emails</p> - </TooltipContent> - </Tooltip> - - {/* 상태 업데이트 (Select) */} - <Select - onValueChange={(value: VendorCandidatesWithVendorInfo["status"]) => { - handleSelectStatus(value) - }} - > - <Tooltip> - <SelectTrigger asChild> - <TooltipTrigger asChild> - <Button - variant="secondary" - size="icon" - className="size-7 border data-[state=open]:bg-accent data-[state=open]:text-accent-foreground" - disabled={isPending} - > - {isPending && action === "update-status" ? ( - <Loader - className="size-3.5 animate-spin" - aria-hidden="true" - /> - ) : ( - <CheckCircle2 className="size-3.5" aria-hidden="true" /> - )} - </Button> - </TooltipTrigger> - </SelectTrigger> - <TooltipContent className="border bg-accent font-semibold text-foreground dark:bg-zinc-900"> - <p>Update status</p> - </TooltipContent> - </Tooltip> - <SelectContent align="center"> - <SelectGroup> - {vendorCandidates.status.enumValues.map((status) => ( - <SelectItem - key={status} - value={status} - className="capitalize" - > - {status} - </SelectItem> - ))} - </SelectGroup> - </SelectContent> - </Select> - - {/* Export 버튼 */} - <Tooltip> - <TooltipTrigger asChild> - <Button - variant="secondary" - size="icon" - className="size-7 border" - onClick={() => { - setAction("export") - startTransition(() => { - exportTableToExcel(table, { - excludeColumns: ["select", "actions"], - onlySelected: true, - }) - }) - }} - disabled={isPending} - > - {isPending && action === "export" ? ( - <Loader - className="size-3.5 animate-spin" - aria-hidden="true" - /> - ) : ( - <Download className="size-3.5" aria-hidden="true" /> - )} - </Button> - </TooltipTrigger> - <TooltipContent className="border bg-accent font-semibold text-foreground dark:bg-zinc-900"> - <p>Export candidates</p> - </TooltipContent> - </Tooltip> - - {/* 삭제 버튼 */} - <Tooltip> - <TooltipTrigger asChild> - <Button - variant="secondary" - size="icon" - className="size-7 border" - onClick={handleDeleteConfirm} - disabled={isPending} - > - {isPending && action === "delete" ? ( - <Loader - className="size-3.5 animate-spin" - aria-hidden="true" - /> - ) : ( - <Trash2 className="size-3.5" aria-hidden="true" /> - )} - </Button> - </TooltipTrigger> - <TooltipContent className="border bg-accent font-semibold text-foreground dark:bg-zinc-900"> - <p>Delete candidates</p> - </TooltipContent> - </Tooltip> - </div> - </div> - </div> - - {/* 공용 Confirm Dialog */} - <ActionConfirmDialog - open={confirmDialogOpen} - onOpenChange={setConfirmDialogOpen} - title={confirmProps.title} - description={confirmProps.description} - onConfirm={confirmProps.onConfirm} - isLoading={ - isPending && - (action === "delete" || action === "update-status" || action === "invite") - } - confirmLabel={ - action === "delete" - ? "Delete" - : action === "update-status" - ? "Update" - : action === "invite" - ? "Invite" - : "Confirm" - } - confirmVariant={action === "delete" ? "destructive" : "default"} - /> - </> - ) -} diff --git a/lib/tech-vendor-candidates/table/candidates-table-toolbar-actions.tsx b/lib/tech-vendor-candidates/table/candidates-table-toolbar-actions.tsx deleted file mode 100644 index 17462841..00000000 --- a/lib/tech-vendor-candidates/table/candidates-table-toolbar-actions.tsx +++ /dev/null @@ -1,93 +0,0 @@ -"use client" - -import * as React from "react" -import { type Table } from "@tanstack/react-table" -import { Download, FileDown, Upload } from "lucide-react" - -import { exportTableToExcel } from "@/lib/export" -import { Button } from "@/components/ui/button" -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu" - -import { AddCandidateDialog } from "./add-candidates-dialog" -import { DeleteCandidatesDialog } from "./delete-candidates-dialog" -import { InviteCandidatesDialog } from "./invite-candidates-dialog" -import { ImportVendorCandidatesButton } from "./import-button" -import { exportVendorCandidateTemplate } from "./excel-template-download" -import { VendorCandidatesWithVendorInfo } from "@/db/schema/vendors" - - -interface CandidatesTableToolbarActionsProps { - table: Table<VendorCandidatesWithVendorInfo> -} - -export function CandidatesTableToolbarActions({ table }: CandidatesTableToolbarActionsProps) { - const selectedRows = table.getFilteredSelectedRowModel().rows - const hasSelection = selectedRows.length > 0 - const [refreshKey, setRefreshKey] = React.useState(0) - - // Handler to refresh the table after import - const handleImportSuccess = () => { - // Trigger a refresh of the table data - setRefreshKey(prev => prev + 1) - } - - return ( - <div className="flex items-center gap-2"> - {/* Show actions only when rows are selected */} - {hasSelection ? ( - <> - {/* Invite dialog - new addition */} - <InviteCandidatesDialog - candidates={selectedRows.map((row) => row.original)} - onSuccess={() => table.toggleAllRowsSelected(false)} - /> - - {/* Delete dialog */} - <DeleteCandidatesDialog - candidates={selectedRows.map((row) => row.original)} - onSuccess={() => table.toggleAllRowsSelected(false)} - /> - </> - ) : null} - - {/* Add new candidate dialog */} - <AddCandidateDialog /> - - {/* Import Excel button */} - <ImportVendorCandidatesButton onSuccess={handleImportSuccess} /> - - {/* Export dropdown menu */} - <DropdownMenu> - <DropdownMenuTrigger asChild> - <Button variant="outline" size="sm" className="gap-2"> - <Download className="size-4" aria-hidden="true" /> - <span className="hidden sm:inline">Export</span> - </Button> - </DropdownMenuTrigger> - <DropdownMenuContent align="end"> - <DropdownMenuItem - onClick={() => { - exportTableToExcel(table, { - filename: "vendor-candidates", - excludeColumns: ["select", "actions"], - useGroupHeader: false, - }) - }} - > - <FileDown className="mr-2 h-4 w-4" /> - <span>Export Current Data</span> - </DropdownMenuItem> - <DropdownMenuItem onClick={exportVendorCandidateTemplate}> - <FileDown className="mr-2 h-4 w-4" /> - <span>Download Template</span> - </DropdownMenuItem> - </DropdownMenuContent> - </DropdownMenu> - </div> - ) -}
\ No newline at end of file diff --git a/lib/tech-vendor-candidates/table/candidates-table.tsx b/lib/tech-vendor-candidates/table/candidates-table.tsx deleted file mode 100644 index 9dab8f6d..00000000 --- a/lib/tech-vendor-candidates/table/candidates-table.tsx +++ /dev/null @@ -1,173 +0,0 @@ -"use client" - -import * as React from "react" -import type { - DataTableAdvancedFilterField, - DataTableFilterField, - DataTableRowAction, -} from "@/types/table" - -import { toSentenceCase } from "@/lib/utils" -import { useDataTable } from "@/hooks/use-data-table" -import { DataTable } from "@/components/data-table/data-table" -import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar" - -import { useFeatureFlags } from "./feature-flags-provider" -import { getVendorCandidateCounts, getVendorCandidates } from "../service" -import { vendorCandidates ,VendorCandidatesWithVendorInfo} from "@/db/schema/vendors" -import { VendorCandidateTableFloatingBar } from "./candidates-table-floating-bar" -import { getColumns } from "./candidates-table-columns" -import { CandidatesTableToolbarActions } from "./candidates-table-toolbar-actions" -import { DeleteCandidatesDialog } from "./delete-candidates-dialog" -import { UpdateCandidateSheet } from "./update-candidate-sheet" -import { getCandidateStatusIcon } from "@/lib/vendor-candidates/utils" - -interface VendorCandidatesTableProps { - promises: Promise< - [ - Awaited<ReturnType<typeof getVendorCandidates>>, - Awaited<ReturnType<typeof getVendorCandidateCounts>>, - ] - > -} - -export function VendorCandidateTable({ promises }: VendorCandidatesTableProps) { - const { featureFlags } = useFeatureFlags() - - const [{ data, pageCount }, statusCounts] = - React.use(promises) - - - - const [rowAction, setRowAction] = - React.useState<DataTableRowAction<VendorCandidatesWithVendorInfo> | null>(null) - - const columns = React.useMemo( - () => getColumns({ setRowAction }), - [setRowAction] - ) - - /** - * This component can render either a faceted filter or a search filter based on the `options` prop. - * - * @prop options - An array of objects, each representing a filter option. If provided, a faceted filter is rendered. If not, a search filter is rendered. - * - * Each `option` object has the following properties: - * @prop {string} label - The label for the filter option. - * @prop {string} value - The value for the filter option. - * @prop {React.ReactNode} [icon] - An optional icon to display next to the label. - * @prop {boolean} [withCount] - An optional boolean to display the count of the filter option. - */ - const filterFields: DataTableFilterField<VendorCandidatesWithVendorInfo>[] = [ - - { - id: "status", - label: "Status", - options: vendorCandidates.status.enumValues.map((status) => ({ - label: toSentenceCase(status), - value: status, - count: statusCounts[status], - })), - }, - - ] - - /** - * Advanced filter fields for the data table. - * These fields provide more complex filtering options compared to the regular filterFields. - * - * Key differences from regular filterFields: - * 1. More field types: Includes 'text', 'multi-select', 'date', and 'boolean'. - * 2. Enhanced flexibility: Allows for more precise and varied filtering options. - * 3. Used with DataTableAdvancedToolbar: Enables a more sophisticated filtering UI. - * 4. Date and boolean types: Adds support for filtering by date ranges and boolean values. - */ - const advancedFilterFields: DataTableAdvancedFilterField<VendorCandidatesWithVendorInfo>[] = [ - { - id: "companyName", - label: "Company Name", - type: "text", - }, - { - id: "contactEmail", - label: "Contact Email", - type: "text", - }, - { - id: "contactPhone", - label: "Contact Phone", - type: "text", - }, - { - id: "source", - label: "source", - type: "text", - }, - { - id: "status", - label: "Status", - type: "multi-select", - options: vendorCandidates.status.enumValues.map((status) => ({ - label: (status), - value: status, - icon: getCandidateStatusIcon(status), - count: statusCounts[status], - })), - }, - - { - id: "createdAt", - label: "수집일", - type: "date", - }, - ] - - - const { table } = useDataTable({ - data, - columns, - pageCount, - filterFields, - enablePinning: true, - enableAdvancedFilter: true, - initialState: { - sorting: [{ id: "createdAt", desc: true }], - columnPinning: { right: ["actions"] }, - }, - getRowId: (originalRow) => String(originalRow.id), - shallow: false, - clearOnDefault: true, - }) - - return ( - <> - <DataTable - table={table} - floatingBar={<VendorCandidateTableFloatingBar table={table} />} - > - - <DataTableAdvancedToolbar - table={table} - filterFields={advancedFilterFields} - shallow={false} - > - <CandidatesTableToolbarActions table={table} /> - </DataTableAdvancedToolbar> - - </DataTable> - <UpdateCandidateSheet - open={rowAction?.type === "update"} - onOpenChange={() => setRowAction(null)} - candidate={rowAction?.row.original ?? null} - /> - <DeleteCandidatesDialog - open={rowAction?.type === "delete"} - onOpenChange={() => setRowAction(null)} - candidates={rowAction?.row.original ? [rowAction?.row.original] : []} - showTrigger={false} - onSuccess={() => rowAction?.row.toggleSelected(false)} - /> - - </> - ) -} diff --git a/lib/tech-vendor-candidates/table/delete-candidates-dialog.tsx b/lib/tech-vendor-candidates/table/delete-candidates-dialog.tsx deleted file mode 100644 index bc231109..00000000 --- a/lib/tech-vendor-candidates/table/delete-candidates-dialog.tsx +++ /dev/null @@ -1,159 +0,0 @@ -"use client" - -import * as React from "react" -import { type Row } from "@tanstack/react-table" -import { Loader, Trash } from "lucide-react" -import { toast } from "sonner" - -import { useMediaQuery } from "@/hooks/use-media-query" -import { Button } from "@/components/ui/button" -import { - Dialog, - DialogClose, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, - DialogTrigger, -} from "@/components/ui/dialog" -import { - Drawer, - DrawerClose, - DrawerContent, - DrawerDescription, - DrawerFooter, - DrawerHeader, - DrawerTitle, - DrawerTrigger, -} from "@/components/ui/drawer" - -import { removeCandidates } from "../service" -import { VendorCandidatesWithVendorInfo } from "@/db/schema" -import { useSession } from "next-auth/react" // next-auth 세션 훅 - -interface DeleteCandidatesDialogProps - extends React.ComponentPropsWithoutRef<typeof Dialog> { - candidates: Row<VendorCandidatesWithVendorInfo>["original"][] - showTrigger?: boolean - onSuccess?: () => void -} - -export function DeleteCandidatesDialog({ - candidates, - showTrigger = true, - onSuccess, - ...props -}: DeleteCandidatesDialogProps) { - const [isDeletePending, startDeleteTransition] = React.useTransition() - const isDesktop = useMediaQuery("(min-width: 640px)") - const { data: session, status } = useSession() - - function onDelete() { - startDeleteTransition(async () => { - - if (!session?.user?.id) { - toast.error("인증 오류. 로그인 정보를 찾을 수 없습니다.") - return - } - - const userId = Number(session.user.id) - - const { error } = await removeCandidates({ - ids: candidates.map((candidate) => candidate.id), - }, userId) - - if (error) { - toast.error(error) - return - } - - props.onOpenChange?.(false) - toast.success("Candidates deleted") - onSuccess?.() - }) - } - - if (isDesktop) { - return ( - <Dialog {...props}> - {showTrigger ? ( - <DialogTrigger asChild> - <Button variant="outline" size="sm"> - <Trash className="mr-2 size-4" aria-hidden="true" /> - Delete ({candidates.length}) - </Button> - </DialogTrigger> - ) : null} - <DialogContent> - <DialogHeader> - <DialogTitle>Are you absolutely sure?</DialogTitle> - <DialogDescription> - This action cannot be undone. This will permanently delete your{" "} - <span className="font-medium">{candidates.length}</span> - {candidates.length === 1 ? " candidate" : " candidates"} from our servers. - </DialogDescription> - </DialogHeader> - <DialogFooter className="gap-2 sm:space-x-0"> - <DialogClose asChild> - <Button variant="outline">Cancel</Button> - </DialogClose> - <Button - aria-label="Delete selected rows" - variant="destructive" - onClick={onDelete} - disabled={isDeletePending} - > - {isDeletePending && ( - <Loader - className="mr-2 size-4 animate-spin" - aria-hidden="true" - /> - )} - Delete - </Button> - </DialogFooter> - </DialogContent> - </Dialog> - ) - } - - return ( - <Drawer {...props}> - {showTrigger ? ( - <DrawerTrigger asChild> - <Button variant="outline" size="sm"> - <Trash className="mr-2 size-4" aria-hidden="true" /> - Delete ({candidates.length}) - </Button> - </DrawerTrigger> - ) : null} - <DrawerContent> - <DrawerHeader> - <DrawerTitle>Are you absolutely sure?</DrawerTitle> - <DrawerDescription> - This action cannot be undone. This will permanently delete your{" "} - <span className="font-medium">{candidates.length}</span> - {candidates.length === 1 ? " candidate" : " candidates"} from our servers. - </DrawerDescription> - </DrawerHeader> - <DrawerFooter className="gap-2 sm:space-x-0"> - <DrawerClose asChild> - <Button variant="outline">Cancel</Button> - </DrawerClose> - <Button - aria-label="Delete selected rows" - variant="destructive" - onClick={onDelete} - disabled={isDeletePending} - > - {isDeletePending && ( - <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" /> - )} - Delete - </Button> - </DrawerFooter> - </DrawerContent> - </Drawer> - ) -} diff --git a/lib/tech-vendor-candidates/table/excel-template-download.tsx b/lib/tech-vendor-candidates/table/excel-template-download.tsx deleted file mode 100644 index 673680db..00000000 --- a/lib/tech-vendor-candidates/table/excel-template-download.tsx +++ /dev/null @@ -1,128 +0,0 @@ -"use client" - -import { type Table } from "@tanstack/react-table" -import ExcelJS from "exceljs" -import { VendorCandidates } from "@/db/schema/vendors" - -/** - * Export an empty template for vendor candidates with column headers - * matching the expected import format - */ -export async function exportVendorCandidateTemplate() { - // Create a new workbook and worksheet - const workbook = new ExcelJS.Workbook() - const worksheet = workbook.addWorksheet("Vendor Candidates") - - // Define the columns with expected headers - const columns = [ - { header: "Company Name", key: "companyName", width: 30 }, - { header: "Tax ID", key: "taxId", width: 20 }, - { header: "Contact Email", key: "contactEmail", width: 30 }, - { header: "Contact Phone", key: "contactPhone", width: 20 }, - { header: "Address", key: "address", width: 40 }, - { header: "Country", key: "country", width: 20 }, - { header: "Source", key: "source", width: 20 }, - { header: "Items", key: "items", width: 40 }, - { header: "Remark", key: "remark", width: 40 }, - { header: "Status", key: "status", width: 15 }, - ] - - // Add columns to the worksheet - worksheet.columns = columns - - // Style the header row - const headerRow = worksheet.getRow(2) - headerRow.font = { bold: true } - headerRow.alignment = { horizontal: "center" } - headerRow.eachCell((cell) => { - cell.fill = { - type: "pattern", - pattern: "solid", - fgColor: { argb: "FFCCCCCC" }, - } - - // Mark required fields with a red asterisk - const requiredFields = ["Company Name", "Source", "Items"] - if (requiredFields.includes(cell.value as string)) { - cell.value = `${cell.value} *` - cell.font = { bold: true, color: { argb: "FFFF0000" } } - } - }) - - // Add example data rows - const exampleData = [ - { - companyName: "ABC Corporation", - taxId: "123-45-6789", - contactEmail: "contact@abc.com", - contactPhone: "+1-123-456-7890", - address: "123 Business Ave, Suite 100, New York, NY 10001", - country: "US", - source: "Website", - items: "Electronic components, Circuit boards, Sensors", - remark: "Potential supplier for Project X", - status: "COLLECTED", - }, - { - companyName: "XYZ Ltd.", - taxId: "GB987654321", - contactEmail: "info@xyz.com", - contactPhone: "+44-987-654-3210", - address: "45 Industrial Park, London, EC2A 4PX", - country: "GB", - source: "Referral", - items: "Steel components, Metal frames, Industrial hardware", - remark: "Met at trade show in March", - status: "COLLECTED", - }, - ] - - // Add the example rows to the worksheet - exampleData.forEach((data) => { - worksheet.addRow(data) - }) - - // Add data validation for Status column - const statusValues = ["COLLECTED", "INVITED", "DISCARDED"] - const statusColumn = columns.findIndex(col => col.key === "status") + 1 - const statusColLetter = String.fromCharCode(64 + statusColumn) - - for (let i = 4; i <= 100; i++) { // Apply to rows 4-100 (after example data) - worksheet.getCell(`${statusColLetter}${i}`).dataValidation = { - type: 'list', - allowBlank: true, - formulae: [`"${statusValues.join(',')}"`] - } - } - - // Add instructions row - worksheet.insertRow(1, ["Please fill in the data below. Required fields are marked with an asterisk (*): Company Name, Source, Items"]) - worksheet.mergeCells(`A1:${String.fromCharCode(64 + columns.length)}1`) - const instructionRow = worksheet.getRow(1) - instructionRow.font = { bold: true, color: { argb: "FF0000FF" } } - instructionRow.alignment = { horizontal: "center" } - instructionRow.height = 30 - - // Auto-width columns based on content - worksheet.columns.forEach(column => { - if (column.key) { // Check that column.key is defined - const dataMax = Math.max(...worksheet.getColumn(column.key).values - .filter(value => value !== null && value !== undefined) - .map(value => String(value).length) - ) - column.width = Math.max(column.width || 10, dataMax + 2) - } - }) - - // Download the workbook - const buffer = await workbook.xlsx.writeBuffer() - const blob = new Blob([buffer], { - type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - }) - const url = URL.createObjectURL(blob) - const link = document.createElement("a") - link.href = url - link.download = "vendor-candidates-template.xlsx" - link.click() - URL.revokeObjectURL(url) -}
\ No newline at end of file diff --git a/lib/tech-vendor-candidates/table/feature-flags-provider.tsx b/lib/tech-vendor-candidates/table/feature-flags-provider.tsx deleted file mode 100644 index 81131894..00000000 --- a/lib/tech-vendor-candidates/table/feature-flags-provider.tsx +++ /dev/null @@ -1,108 +0,0 @@ -"use client" - -import * as React from "react" -import { useQueryState } from "nuqs" - -import { dataTableConfig, type DataTableConfig } from "@/config/data-table" -import { cn } from "@/lib/utils" -import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group" -import { - Tooltip, - TooltipContent, - TooltipTrigger, -} from "@/components/ui/tooltip" - -type FeatureFlagValue = DataTableConfig["featureFlags"][number]["value"] - -interface FeatureFlagsContextProps { - featureFlags: FeatureFlagValue[] - setFeatureFlags: (value: FeatureFlagValue[]) => void -} - -const FeatureFlagsContext = React.createContext<FeatureFlagsContextProps>({ - featureFlags: [], - setFeatureFlags: () => {}, -}) - -export function useFeatureFlags() { - const context = React.useContext(FeatureFlagsContext) - if (!context) { - throw new Error( - "useFeatureFlags must be used within a FeatureFlagsProvider" - ) - } - return context -} - -interface FeatureFlagsProviderProps { - children: React.ReactNode -} - -export function FeatureFlagsProvider({ children }: FeatureFlagsProviderProps) { - const [featureFlags, setFeatureFlags] = useQueryState<FeatureFlagValue[]>( - "flags", - { - defaultValue: [], - parse: (value) => value.split(",") as FeatureFlagValue[], - serialize: (value) => value.join(","), - eq: (a, b) => - a.length === b.length && a.every((value, index) => value === b[index]), - clearOnDefault: true, - shallow: false, - } - ) - - return ( - <FeatureFlagsContext.Provider - value={{ - featureFlags, - setFeatureFlags: (value) => void setFeatureFlags(value), - }} - > - <div className="w-full overflow-x-auto"> - <ToggleGroup - type="multiple" - variant="outline" - size="sm" - value={featureFlags} - onValueChange={(value: FeatureFlagValue[]) => setFeatureFlags(value)} - className="w-fit gap-0" - > - {dataTableConfig.featureFlags.map((flag, index) => ( - <Tooltip key={flag.value}> - <ToggleGroupItem - value={flag.value} - className={cn( - "gap-2 whitespace-nowrap rounded-none px-3 text-xs data-[state=on]:bg-accent/70 data-[state=on]:hover:bg-accent/90", - { - "rounded-l-sm border-r-0": index === 0, - "rounded-r-sm": - index === dataTableConfig.featureFlags.length - 1, - } - )} - asChild - > - <TooltipTrigger> - <flag.icon className="size-3.5 shrink-0" aria-hidden="true" /> - {flag.label} - </TooltipTrigger> - </ToggleGroupItem> - <TooltipContent - align="start" - side="bottom" - sideOffset={6} - className="flex max-w-60 flex-col space-y-1.5 border bg-background py-2 font-semibold text-foreground" - > - <div>{flag.tooltipTitle}</div> - <div className="text-xs text-muted-foreground"> - {flag.tooltipDescription} - </div> - </TooltipContent> - </Tooltip> - ))} - </ToggleGroup> - </div> - {children} - </FeatureFlagsContext.Provider> - ) -} diff --git a/lib/tech-vendor-candidates/table/feature-flags.tsx b/lib/tech-vendor-candidates/table/feature-flags.tsx deleted file mode 100644 index aaae6af2..00000000 --- a/lib/tech-vendor-candidates/table/feature-flags.tsx +++ /dev/null @@ -1,96 +0,0 @@ -"use client" - -import * as React from "react" -import { useQueryState } from "nuqs" - -import { dataTableConfig, type DataTableConfig } from "@/config/data-table" -import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group" -import { - Tooltip, - TooltipContent, - TooltipTrigger, -} from "@/components/ui/tooltip" - -type FeatureFlagValue = DataTableConfig["featureFlags"][number]["value"] - -interface TasksTableContextProps { - featureFlags: FeatureFlagValue[] - setFeatureFlags: (value: FeatureFlagValue[]) => void -} - -const TasksTableContext = React.createContext<TasksTableContextProps>({ - featureFlags: [], - setFeatureFlags: () => {}, -}) - -export function useTasksTable() { - const context = React.useContext(TasksTableContext) - if (!context) { - throw new Error("useTasksTable must be used within a TasksTableProvider") - } - return context -} - -export function TasksTableProvider({ children }: React.PropsWithChildren) { - const [featureFlags, setFeatureFlags] = useQueryState<FeatureFlagValue[]>( - "featureFlags", - { - defaultValue: [], - parse: (value) => value.split(",") as FeatureFlagValue[], - serialize: (value) => value.join(","), - eq: (a, b) => - a.length === b.length && a.every((value, index) => value === b[index]), - clearOnDefault: true, - } - ) - - return ( - <TasksTableContext.Provider - value={{ - featureFlags, - setFeatureFlags: (value) => void setFeatureFlags(value), - }} - > - <div className="w-full overflow-x-auto"> - <ToggleGroup - type="multiple" - variant="outline" - size="sm" - value={featureFlags} - onValueChange={(value: FeatureFlagValue[]) => setFeatureFlags(value)} - className="w-fit" - > - {dataTableConfig.featureFlags.map((flag) => ( - <Tooltip key={flag.value}> - <ToggleGroupItem - value={flag.value} - className="whitespace-nowrap px-3 text-xs" - asChild - > - <TooltipTrigger> - <flag.icon - className="mr-2 size-3.5 shrink-0" - aria-hidden="true" - /> - {flag.label} - </TooltipTrigger> - </ToggleGroupItem> - <TooltipContent - align="start" - side="bottom" - sideOffset={6} - className="flex max-w-60 flex-col space-y-1.5 border bg-background py-2 font-semibold text-foreground" - > - <div>{flag.tooltipTitle}</div> - <div className="text-xs text-muted-foreground"> - {flag.tooltipDescription} - </div> - </TooltipContent> - </Tooltip> - ))} - </ToggleGroup> - </div> - {children} - </TasksTableContext.Provider> - ) -} diff --git a/lib/tech-vendor-candidates/table/import-button.tsx b/lib/tech-vendor-candidates/table/import-button.tsx deleted file mode 100644 index ad1e6862..00000000 --- a/lib/tech-vendor-candidates/table/import-button.tsx +++ /dev/null @@ -1,233 +0,0 @@ -"use client" - -import React, { useRef } from 'react' -import ExcelJS from 'exceljs' -import { toast } from 'sonner' -import { Button } from '@/components/ui/button' -import { Upload, Loader } from 'lucide-react' -import { createVendorCandidate } from '../service' -import { Input } from '@/components/ui/input' -import { useSession } from "next-auth/react" // next-auth 세션 훅 추가 -import { decryptWithServerAction } from '@/components/drm/drmUtils' // DRM 복호화 함수 import - -interface ImportExcelProps { - onSuccess?: () => void -} - -export function ImportVendorCandidatesButton({ onSuccess }: ImportExcelProps) { - const fileInputRef = useRef<HTMLInputElement>(null) - const [isImporting, setIsImporting] = React.useState(false) - const { data: session } = useSession() // status 제거 (사용하지 않음) - - // Helper function to get cell value as string - const getCellValueAsString = (cell: ExcelJS.Cell): string => { - if (!cell || cell.value === undefined || cell.value === null) return ''; - - if (typeof cell.value === 'string') return cell.value.trim(); - if (typeof cell.value === 'number') return cell.value.toString(); - - // Handle rich text - if (typeof cell.value === 'object' && 'richText' in cell.value) { - return cell.value.richText.map((rt: { text: string }) => rt.text).join(''); - } - - // Handle dates - if (cell.value instanceof Date) { - return cell.value.toISOString().split('T')[0]; - } - - // Fallback - return String(cell.value); - } - - const handleImport = async (event: React.ChangeEvent<HTMLInputElement>) => { - const file = event.target.files?.[0] - if (!file) return - - setIsImporting(true) - - try { - // DRM 복호화 시도 (실패시 원본 파일 사용) - let data: ArrayBuffer; - try { - data = await decryptWithServerAction(file); - console.log('[Import] DRM 복호화 성공'); - } catch (decryptError) { - console.warn('[Import] DRM 복호화 실패, 원본 파일 사용:', decryptError); - data = await file.arrayBuffer(); - } - - // Read the Excel file using ExcelJS - const workbook = new ExcelJS.Workbook() - await workbook.xlsx.load(data) - - // Get the first worksheet - const worksheet = workbook.getWorksheet(1) - if (!worksheet) { - toast.error("No worksheet found in the spreadsheet") - return - } - - // Check if there's an instruction row - const hasInstructionRow = worksheet.getRow(1).getCell(1).value !== null && - worksheet.getRow(1).getCell(2).value === null; - - // Get header row index (row 2 if there's an instruction row, otherwise row 1) - const headerRowIndex = hasInstructionRow ? 2 : 1; - - // Get column headers and their indices - const headerRow = worksheet.getRow(headerRowIndex); - const headers: Record<number, string> = {}; - const columnIndices: Record<string, number> = {}; - - headerRow.eachCell((cell, colNumber) => { - const header = getCellValueAsString(cell); - headers[colNumber] = header; - columnIndices[header] = colNumber; - }); - - // Process data rows - const rows: Record<string, string>[] = []; - const startRow = headerRowIndex + 1; - - for (let i = startRow; i <= worksheet.rowCount; i++) { - const row = worksheet.getRow(i); - - // Skip empty rows - if (row.cellCount === 0) continue; - - // Check if this is likely an example row - const isExample = i === startRow && worksheet.getRow(i + 1).values?.length === 0; - if (isExample) continue; - - const rowData: Record<string, string> = {}; - let hasData = false; - - // Map the data using header indices - Object.entries(columnIndices).forEach(([header, colIndex]) => { - const value = getCellValueAsString(row.getCell(colIndex)); - if (value) { - rowData[header] = value; - hasData = true; - } - }); - - if (hasData) { - rows.push(rowData); - } - } - - if (rows.length === 0) { - toast.error("No data found in the spreadsheet") - setIsImporting(false) - return - } - - // Process each row - let successCount = 0; - let errorCount = 0; - - // Create promises for all vendor candidate creation operations - const promises = rows.map(async (row) => { - try { - // Map Excel columns to our data model - const candidateData = { - companyName: String(row['Company Name'] || ''), - contactEmail: String(row['Contact Email'] || ''), - contactPhone: String(row['Contact Phone'] || ''), - taxId: String(row['Tax ID'] || ''), - address: String(row['Address'] || ''), - country: String(row['Country'] || ''), - source: String(row['Source'] || ''), - items: String(row['Items'] || ''), - remark: String(row['Remark'] || row['Remarks'] || ''), - // Default to COLLECTED if not specified - status: (row['Status'] || 'COLLECTED') as "COLLECTED" | "INVITED" | "DISCARDED" - }; - - // Validate required fields - if (!candidateData.companyName || !candidateData.source || - !candidateData.items) { - console.error("Missing required fields", candidateData); - errorCount++; - return null; - } - - if (!session || !session.user || !session.user.id) { - toast.error("인증 오류. 로그인 정보를 찾을 수 없습니다.") - return - } - - // Create the vendor candidate (userId는 이미 number 타입이므로 변환 불필요) - const result = await createVendorCandidate(candidateData) - - if (result.error) { - console.error(`Failed to import row: ${result.error}`, candidateData); - errorCount++; - return null; - } - - successCount++; - return result.data; - } catch (error) { - console.error("Error processing row:", error, row); - errorCount++; - return null; - } - }); - - // Wait for all operations to complete - await Promise.all(promises); - - // Show results - if (successCount > 0) { - toast.success(`Successfully imported ${successCount} vendor candidates`); - if (errorCount > 0) { - toast.warning(`Failed to import ${errorCount} rows due to errors`); - } - // Call the success callback to refresh data - onSuccess?.(); - } else if (errorCount > 0) { - toast.error(`Failed to import all ${errorCount} rows due to errors`); - } - - } catch (error) { - console.error("Import error:", error); - toast.error("Error importing data. Please check file format."); - } finally { - setIsImporting(false); - // Reset the file input - if (fileInputRef.current) { - fileInputRef.current.value = ''; - } - } - } - - return ( - <> - <Input - type="file" - ref={fileInputRef} - onChange={handleImport} - accept=".xlsx,.xls" - className="hidden" - /> - <Button - variant="outline" - size="sm" - onClick={() => fileInputRef.current?.click()} - disabled={isImporting} - className="gap-2" - > - {isImporting ? ( - <Loader className="size-4 animate-spin" aria-hidden="true" /> - ) : ( - <Upload className="size-4" aria-hidden="true" /> - )} - <span className="hidden sm:inline"> - {isImporting ? "Importing..." : "Import"} - </span> - </Button> - </> - ) -}
\ No newline at end of file diff --git a/lib/tech-vendor-candidates/table/invite-candidates-dialog.tsx b/lib/tech-vendor-candidates/table/invite-candidates-dialog.tsx deleted file mode 100644 index 570cf96a..00000000 --- a/lib/tech-vendor-candidates/table/invite-candidates-dialog.tsx +++ /dev/null @@ -1,230 +0,0 @@ -"use client" - -import * as React from "react" -import { type Row } from "@tanstack/react-table" -import { Loader, Mail, AlertCircle, XCircle } from "lucide-react" -import { toast } from "sonner" - -import { useMediaQuery } from "@/hooks/use-media-query" -import { Button } from "@/components/ui/button" -import { - Dialog, - DialogClose, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, - DialogTrigger, -} from "@/components/ui/dialog" -import { - Drawer, - DrawerClose, - DrawerContent, - DrawerDescription, - DrawerFooter, - DrawerHeader, - DrawerTitle, - DrawerTrigger, -} from "@/components/ui/drawer" -import { - Alert, - AlertTitle, - AlertDescription -} from "@/components/ui/alert" - -import { VendorCandidates } from "@/db/schema/vendors" -import { bulkUpdateVendorCandidateStatus } from "../service" -import { useSession } from "next-auth/react" // next-auth 세션 훅 - -interface InviteCandidatesDialogProps - extends React.ComponentPropsWithoutRef<typeof Dialog> { - candidates: Row<VendorCandidates>["original"][] - showTrigger?: boolean - onSuccess?: () => void -} - -export function InviteCandidatesDialog({ - candidates, - showTrigger = true, - onSuccess, - ...props -}: InviteCandidatesDialogProps) { - const [isInvitePending, startInviteTransition] = React.useTransition() - const isDesktop = useMediaQuery("(min-width: 640px)") - const { data: session, status } = useSession() - - // 후보자를 상태별로 분류 - const discardedCandidates = candidates.filter(candidate => candidate.status === "DISCARDED") - const nonDiscardedCandidates = candidates.filter(candidate => candidate.status !== "DISCARDED") - - // 이메일 유무에 따라 초대 가능한 후보자 분류 (DISCARDED가 아닌 후보자 중에서) - const candidatesWithEmail = nonDiscardedCandidates.filter(candidate => candidate.contactEmail) - const candidatesWithoutEmail = nonDiscardedCandidates.filter(candidate => !candidate.contactEmail) - - // 각 카테고리 수 - const invitableCount = candidatesWithEmail.length - const hasUninvitableCandidates = candidatesWithoutEmail.length > 0 - const hasDiscardedCandidates = discardedCandidates.length > 0 - - function onInvite() { - startInviteTransition(async () => { - // 이메일이 있고 DISCARDED가 아닌 후보자만 상태 업데이트 - - if (!session?.user?.id) { - toast.error("인증 오류. 로그인 정보를 찾을 수 없습니다.") - return - } - - const { error } = await bulkUpdateVendorCandidateStatus({ - ids: candidatesWithEmail.map((candidate) => candidate.id), - status: "INVITED", - }) - - if (error) { - toast.error(error) - return - } - - props.onOpenChange?.(false) - - if (invitableCount === 0) { - toast.warning("No invitation sent - no eligible candidates with email addresses") - } else { - let skipMessage = "" - - if (hasUninvitableCandidates && hasDiscardedCandidates) { - skipMessage = ` ${candidatesWithoutEmail.length} candidates without email and ${discardedCandidates.length} discarded candidates were skipped.` - } else if (hasUninvitableCandidates) { - skipMessage = ` ${candidatesWithoutEmail.length} candidates without email were skipped.` - } else if (hasDiscardedCandidates) { - skipMessage = ` ${discardedCandidates.length} discarded candidates were skipped.` - } - - toast.success(`Invitation emails sent to ${invitableCount} candidates.${skipMessage}`) - } - - onSuccess?.() - }) - } - - // 초대 버튼 비활성화 조건 - const disableInviteButton = isInvitePending || invitableCount === 0 - - const DialogComponent = ( - <> - <div className="space-y-4"> - {/* 이메일 없는 후보자 알림 */} - {hasUninvitableCandidates && ( - <Alert> - <AlertCircle className="h-4 w-4" /> - <AlertTitle>Missing Email Addresses</AlertTitle> - <AlertDescription> - {candidatesWithoutEmail.length} candidate{candidatesWithoutEmail.length > 1 ? 's' : ''} {candidatesWithoutEmail.length > 1 ? 'don't' : 'doesn't'} have email addresses and won't receive invitations. - </AlertDescription> - </Alert> - )} - - {/* 폐기된 후보자 알림 */} - {hasDiscardedCandidates && ( - <Alert variant="destructive"> - <XCircle className="h-4 w-4" /> - <AlertTitle>Discarded Candidates</AlertTitle> - <AlertDescription> - {discardedCandidates.length} candidate{discardedCandidates.length > 1 ? 's have' : ' has'} been discarded and won't receive invitations. - </AlertDescription> - </Alert> - )} - - <DialogDescription> - {invitableCount > 0 ? ( - <> - This will send invitation emails to{" "} - <span className="font-medium">{invitableCount}</span> - {invitableCount === 1 ? " candidate" : " candidates"} and change their status to INVITED. - </> - ) : ( - <> - No candidates can be invited because none of the selected candidates have valid email addresses or they have been discarded. - </> - )} - </DialogDescription> - </div> - </> - ) - - if (isDesktop) { - return ( - <Dialog {...props}> - {showTrigger ? ( - <DialogTrigger asChild> - <Button variant="outline" size="sm" className="gap-2"> - <Mail className="size-4" aria-hidden="true" /> - Invite ({candidates.length}) - </Button> - </DialogTrigger> - ) : null} - <DialogContent> - <DialogHeader> - <DialogTitle>Send invitations?</DialogTitle> - </DialogHeader> - {DialogComponent} - <DialogFooter className="gap-2 sm:space-x-0"> - <DialogClose asChild> - <Button variant="outline">Cancel</Button> - </DialogClose> - <Button - aria-label="Invite selected vendors" - variant="default" - onClick={onInvite} - disabled={disableInviteButton} - > - {isInvitePending && ( - <Loader - className="mr-2 size-4 animate-spin" - aria-hidden="true" - /> - )} - Send Invitations - </Button> - </DialogFooter> - </DialogContent> - </Dialog> - ) - } - - return ( - <Drawer {...props}> - {showTrigger ? ( - <DrawerTrigger asChild> - <Button variant="outline" size="sm" className="gap-2"> - <Mail className="size-4" aria-hidden="true" /> - Invite ({candidates.length}) - </Button> - </DrawerTrigger> - ) : null} - <DrawerContent> - <DrawerHeader> - <DrawerTitle>Send invitations?</DrawerTitle> - </DrawerHeader> - {DialogComponent} - <DrawerFooter className="gap-2 sm:space-x-0"> - <DrawerClose asChild> - <Button variant="outline">Cancel</Button> - </DrawerClose> - <Button - aria-label="Invite selected vendors" - variant="default" - onClick={onInvite} - disabled={disableInviteButton} - > - {isInvitePending && ( - <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" /> - )} - Send Invitations - </Button> - </DrawerFooter> - </DrawerContent> - </Drawer> - ) -}
\ No newline at end of file diff --git a/lib/tech-vendor-candidates/table/update-candidate-sheet.tsx b/lib/tech-vendor-candidates/table/update-candidate-sheet.tsx deleted file mode 100644 index 3d278126..00000000 --- a/lib/tech-vendor-candidates/table/update-candidate-sheet.tsx +++ /dev/null @@ -1,437 +0,0 @@ -"use client" - -import * as React from "react" -import { zodResolver } from "@hookform/resolvers/zod" -import { Check, ChevronsUpDown, Loader } from "lucide-react" -import { useForm } from "react-hook-form" -import { toast } from "sonner" -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 { Button } from "@/components/ui/button" -import { - Form, - FormControl, - FormField, - FormItem, - FormLabel, - FormMessage, -} from "@/components/ui/form" -import { - Select, - SelectContent, - SelectGroup, - SelectItem, - SelectTrigger, - SelectValue, -} from "@/components/ui/select" -import { - Sheet, - SheetClose, - SheetContent, - SheetDescription, - SheetFooter, - SheetHeader, - SheetTitle, -} from "@/components/ui/sheet" -import { Input } from "@/components/ui/input" -import { Textarea } from "@/components/ui/textarea" -import { - Popover, - PopoverContent, - PopoverTrigger, -} from "@/components/ui/popover" -import { - Command, - CommandEmpty, - CommandGroup, - CommandInput, - CommandItem, - CommandList, -} from "@/components/ui/command" -import { useSession } from "next-auth/react" // next-auth 세션 훅 - -import { updateVendorCandidateSchema, UpdateVendorCandidateSchema } from "../validations" -import { updateVendorCandidate } from "../service" -import { vendorCandidates,VendorCandidatesWithVendorInfo} from "@/db/schema" - -// 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, -})) - -interface UpdateCandidateSheetProps - extends React.ComponentPropsWithRef<typeof Sheet> { - candidate: VendorCandidatesWithVendorInfo | null -} - -export function UpdateCandidateSheet({ candidate, ...props }: UpdateCandidateSheetProps) { - const [isUpdatePending, startUpdateTransition] = React.useTransition() - const { data: session, status } = useSession() - - // Set default values from candidate data when the component receives a new candidate - - React.useEffect(() => { - if (candidate) { - form.reset({ - id: candidate.id, - companyName: candidate.companyName, - taxId: candidate.taxId, - contactEmail: candidate.contactEmail || "", // null을 빈 문자열로 변환 - contactPhone: candidate.contactPhone || "", - address: candidate.address || "", - country: candidate.country || "", - source: candidate.source || "", - items: candidate.items, - remark: candidate.remark || "", - status: candidate.status, - }) - } - }, [candidate]) - - - const form = useForm<UpdateVendorCandidateSchema>({ - resolver: zodResolver(updateVendorCandidateSchema), - defaultValues: { - id: candidate?.id || 0, - companyName: candidate?.companyName || "", - taxId: candidate?.taxId || "", - contactEmail: candidate?.contactEmail || "", - contactPhone: candidate?.contactPhone || "", - address: candidate?.address || "", - country: candidate?.country || "", - source: candidate?.source || "", - items: candidate?.items || "", - remark: candidate?.remark || "", - status: candidate?.status || "COLLECTED", - }, - }) - - function onSubmit(input: UpdateVendorCandidateSchema) { - startUpdateTransition(async () => { - - if (!session?.user?.id) { - toast.error("인증 오류. 로그인 정보를 찾을 수 없습니다.") - return - } - const userId = Number(session.user.id) - - if (!candidate) return - - const { error } = await updateVendorCandidate({ - ...input, - }, userId) - - if (error) { - toast.error(error) - return - } - - form.reset() - props.onOpenChange?.(false) - toast.success("Vendor candidate updated") - }) - } - - return ( - <Sheet {...props}> - <SheetContent className="flex flex-col gap-6 sm:max-w-md overflow-y-auto"> - <SheetHeader className="text-left"> - <SheetTitle>Update Vendor Candidate</SheetTitle> - <SheetDescription> - Update the vendor candidate details and save the changes - </SheetDescription> - </SheetHeader> - <Form {...form}> - <form - onSubmit={form.handleSubmit(onSubmit)} - className="flex flex-col gap-4" - > - {/* Company Name Field */} - <FormField - control={form.control} - name="companyName" - render={({ field }) => ( - <FormItem> - <FormLabel>Company Name <span className="text-red-500">*</span></FormLabel> - <FormControl> - <Input - placeholder="Enter company name" - {...field} - disabled={isUpdatePending} - /> - </FormControl> - <FormMessage /> - </FormItem> - )} - /> - - {/* Tax ID Field */} - <FormField - control={form.control} - name="taxId" - render={({ field }) => ( - <FormItem> - <FormLabel>Tax ID</FormLabel> - <FormControl> - <Input - placeholder="Enter tax ID" - {...field} - disabled={isUpdatePending} - /> - </FormControl> - <FormMessage /> - </FormItem> - )} - /> - - {/* Contact Email Field */} - <FormField - control={form.control} - name="contactEmail" - render={({ field }) => ( - <FormItem> - <FormLabel>Contact Email</FormLabel> - <FormControl> - <Input - placeholder="email@example.com" - type="email" - {...field} - disabled={isUpdatePending} - /> - </FormControl> - <FormMessage /> - </FormItem> - )} - /> - - {/* Contact Phone Field */} - <FormField - control={form.control} - name="contactPhone" - render={({ field }) => ( - <FormItem> - <FormLabel>Contact Phone</FormLabel> - <FormControl> - <Input - placeholder="+82-10-1234-5678" - {...field} - disabled={isUpdatePending} - /> - </FormControl> - <FormMessage /> - </FormItem> - )} - /> - - {/* Address Field */} - <FormField - control={form.control} - name="address" - render={({ field }) => ( - <FormItem> - <FormLabel>Address</FormLabel> - <FormControl> - <Input - placeholder="Enter company address" - {...field} - disabled={isUpdatePending} - /> - </FormControl> - <FormMessage /> - </FormItem> - )} - /> - - {/* Country Field */} - <FormField - control={form.control} - name="country" - render={({ field }) => { - const selectedCountry = countryArray.find( - (c) => c.code === field.value - ) - return ( - <FormItem> - <FormLabel>Country</FormLabel> - <Popover> - <PopoverTrigger asChild> - <FormControl> - <Button - variant="outline" - role="combobox" - className={cn( - "w-full justify-between", - !field.value && "text-muted-foreground" - )} - disabled={isUpdatePending} - > - {selectedCountry - ? selectedCountry.label - : "Select a country"} - <ChevronsUpDown className="ml-2 h-4 w-4 opacity-50" /> - </Button> - </FormControl> - </PopoverTrigger> - <PopoverContent className="w-[300px] p-0"> - <Command> - <CommandInput placeholder="Search country..." /> - <CommandList> - <CommandEmpty>No country found.</CommandEmpty> - <CommandGroup className="max-h-[300px] overflow-y-auto"> - {countryArray.map((country) => ( - <CommandItem - key={country.code} - value={country.label} - onSelect={() => - field.onChange(country.code) - } - > - <Check - className={cn( - "mr-2 h-4 w-4", - country.code === field.value - ? "opacity-100" - : "opacity-0" - )} - /> - {country.label} - </CommandItem> - ))} - </CommandGroup> - </CommandList> - </Command> - </PopoverContent> - </Popover> - <FormMessage /> - </FormItem> - ) - }} - /> - - {/* Source Field */} - <FormField - control={form.control} - name="source" - render={({ field }) => ( - <FormItem> - <FormLabel>Source <span className="text-red-500">*</span></FormLabel> - <FormControl> - <Input - placeholder="Where this candidate was found" - {...field} - disabled={isUpdatePending} - /> - </FormControl> - <FormMessage /> - </FormItem> - )} - /> - - {/* Items Field */} - <FormField - control={form.control} - name="items" - render={({ field }) => ( - <FormItem> - <FormLabel>Items <span className="text-red-500">*</span></FormLabel> - <FormControl> - <Textarea - placeholder="List of items or products this vendor provides" - className="min-h-[80px]" - {...field} - disabled={isUpdatePending} - /> - </FormControl> - <FormMessage /> - </FormItem> - )} - /> - - {/* Remark Field */} - <FormField - control={form.control} - name="remark" - render={({ field }) => ( - <FormItem> - <FormLabel>Remark</FormLabel> - <FormControl> - <Textarea - placeholder="Additional notes or comments" - className="min-h-[80px]" - {...field} - disabled={isUpdatePending} - /> - </FormControl> - <FormMessage /> - </FormItem> - )} - /> - - {/* Status Field */} - <FormField - control={form.control} - name="status" - render={({ field }) => ( - <FormItem> - <FormLabel>Status</FormLabel> - <Select - onValueChange={field.onChange} - defaultValue={field.value} - disabled={isUpdatePending} - > - <FormControl> - <SelectTrigger className="capitalize"> - <SelectValue placeholder="Select a status" /> - </SelectTrigger> - </FormControl> - <SelectContent> - <SelectGroup> - {vendorCandidates.status.enumValues.map((item) => ( - <SelectItem - key={item} - value={item} - className="capitalize" - > - {item} - </SelectItem> - ))} - </SelectGroup> - </SelectContent> - </Select> - <FormMessage /> - </FormItem> - )} - /> - - <SheetFooter className="gap-2 pt-2 sm:space-x-0"> - <SheetClose asChild> - <Button type="button" variant="outline" disabled={isUpdatePending}> - Cancel - </Button> - </SheetClose> - <Button disabled={isUpdatePending}> - {isUpdatePending && ( - <Loader - className="mr-2 size-4 animate-spin" - aria-hidden="true" - /> - )} - Save - </Button> - </SheetFooter> - </form> - </Form> - </SheetContent> - </Sheet> - ) -}
\ No newline at end of file diff --git a/lib/tech-vendor-candidates/utils.ts b/lib/tech-vendor-candidates/utils.ts deleted file mode 100644 index 4c21b873..00000000 --- a/lib/tech-vendor-candidates/utils.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { - Activity, - AlertCircle, - AlertTriangle, - ArrowDownIcon, - ArrowRightIcon, - ArrowUpIcon, - AwardIcon, - BadgeCheck, - CheckCircle2, - CircleHelp, - CircleIcon, - CircleX, - ClipboardCheck, - ClipboardList, - FileCheck2, - FilePenLine, - FileX2, - MailCheck, - PencilIcon, - SearchIcon, - SendIcon, - Timer, - Trash2, - XCircle, -} from "lucide-react" - -import { TechVendorCandidate } from "@/db/schema/techVendors" - - -export function getCandidateStatusIcon(status: TechVendorCandidate["status"]) { - const statusIcons = { - COLLECTED: ClipboardList, // Data collection icon - INVITED: MailCheck, // Email sent and checked icon - DISCARDED: Trash2, // Trashed/discarded icon - } - - return statusIcons[status] || CircleIcon -} - diff --git a/lib/tech-vendor-candidates/validations.ts b/lib/tech-vendor-candidates/validations.ts deleted file mode 100644 index d2ef4d53..00000000 --- a/lib/tech-vendor-candidates/validations.ts +++ /dev/null @@ -1,148 +0,0 @@ -import { techVendorCandidatesWithVendorInfo } from "@/db/schema/techVendors" -import { - createSearchParamsCache, - parseAsArrayOf, - parseAsInteger, - parseAsString, - parseAsStringEnum, -} from "nuqs/server" -import * as z from "zod" -import { getFiltersStateParser, getSortingStateParser } from "@/lib/parsers" - -export const searchParamsTechCandidateCache = createSearchParamsCache({ - // Common flags - flags: parseAsArrayOf(z.enum(["advancedTable", "floatingBar"])).withDefault([]), - from: parseAsString.withDefault(""), - to: parseAsString.withDefault(""), - // Paging - page: parseAsInteger.withDefault(1), - perPage: parseAsInteger.withDefault(10), - - // Sorting - adjusting for vendorInvestigationsView - sort: getSortingStateParser<typeof techVendorCandidatesWithVendorInfo.$inferSelect>().withDefault([ - { id: "createdAt", desc: true }, - ]), - - // Advanced filter - filters: getFiltersStateParser().withDefault([]), - joinOperator: parseAsStringEnum(["and", "or"]).withDefault("and"), - - // Global search - search: parseAsString.withDefault(""), - - // ----------------------------------------------------------------- - // Fields specific to vendor investigations - // ----------------------------------------------------------------- - - // investigationStatus: PLANNED, IN_PROGRESS, COMPLETED, CANCELED - status: parseAsStringEnum(["COLLECTED", "INVITED", "DISCARDED"]), - - // In case you also want to filter by vendorName, vendorCode, etc. - companyName: parseAsString.withDefault(""), - contactEmail: parseAsString.withDefault(""), - contactPhone: parseAsString.withDefault(""), - country: parseAsString.withDefault(""), - source: parseAsString.withDefault(""), - - -}) - -// Finally, export the type you can use in your server action: -export type GetTechVendorsCandidateSchema = Awaited<ReturnType<typeof searchParamsTechCandidateCache.parse>> - - -// Updated version of the updateVendorCandidateSchema -export const updateVendorCandidateSchema = z.object({ - id: z.number(), - // 필수 필드 - companyName: z.string().min(1, "회사명은 필수입니다").max(255), - // null을 명시적으로 처리 - contactEmail: z.union([ - z.string().email("유효한 이메일 형식이 아닙니다").max(255), - z.literal(''), - z.null() - ]).optional().transform(val => val === null ? '' : val), - contactPhone: z.union([z.string().max(50), z.literal(''), z.null()]).optional() - .transform(val => val === null ? '' : val), - country: z.union([z.string().max(100), z.literal(''), z.null()]).optional() - .transform(val => val === null ? '' : val), - // 필수 필드 - source: z.string().min(1, "출처는 필수입니다").max(100), - address: z.union([z.string(), z.literal(''), z.null()]).optional() - .transform(val => val === null ? '' : val), - taxId: z.union([z.string(), z.literal(''), z.null()]).optional() - .transform(val => val === null ? '' : val), - // 필수 필드 - items: z.string().min(1, "항목은 필수입니다"), - remark: z.union([z.string(), z.literal(''), z.null()]).optional() - .transform(val => val === null ? '' : val), - status: z.enum(["COLLECTED", "INVITED", "DISCARDED"]), - updatedAt: z.date().optional().default(() => new Date()), -});; - -// Create schema for vendor candidates -export const createVendorCandidateSchema = z.object({ - companyName: z.string().min(1, "회사명은 필수입니다").max(255), - // contactEmail을 필수값으로 변경 - contactEmail: z.string().min(1, "이메일은 필수입니다").email("유효한 이메일 형식이 아닙니다").max(255), - contactPhone: z.string().max(50).optional(), - country: z.string().max(100).optional(), - source: z.string().min(1, "출처는 필수입니다").max(100), - address: z.string().optional(), - taxId: z.string().optional(), - items: z.string().min(1, "항목은 필수입니다"), - remark: z.string().optional(), - vendorId: z.number().optional(), - status: z.enum(["COLLECTED", "INVITED", "DISCARDED"]).default("COLLECTED"), -}); - -// Export types for both schemas -export type UpdateVendorCandidateSchema = z.infer<typeof updateVendorCandidateSchema>; -export type CreateVendorCandidateSchema = z.infer<typeof createVendorCandidateSchema>; - - -export const removeCandidatesSchema = z.object({ - ids: z.array(z.number()).min(1, "At least one candidate ID must be provided"), -}); - -export type RemoveCandidatesInput = z.infer<typeof removeCandidatesSchema>; - -// 기술영업 벤더 후보 생성 스키마 -export const createTechVendorCandidateSchema = z.object({ - companyName: z.string().min(1, "Company name is required"), - contactEmail: z.string().email("Invalid email").optional(), - contactPhone: z.string().optional(), - taxId: z.string().optional(), - address: z.string().optional(), - country: z.string().optional(), - source: z.string().optional(), - status: z.enum(["COLLECTED", "INVITED", "DISCARDED"]).default("COLLECTED"), - remark: z.string().optional(), - items: z.string().min(1, "Items are required"), - vendorId: z.number().optional(), -}); - -// 기술영업 벤더 후보 업데이트 스키마 -export const updateTechVendorCandidateSchema = z.object({ - id: z.number(), - companyName: z.string().min(1, "Company name is required").optional(), - contactEmail: z.string().email("Invalid email").optional(), - contactPhone: z.string().optional(), - taxId: z.string().optional(), - address: z.string().optional(), - country: z.string().optional(), - source: z.string().optional(), - status: z.enum(["COLLECTED", "INVITED", "DISCARDED"]).optional(), - remark: z.string().optional(), - items: z.string().optional(), - vendorId: z.number().optional(), -}); - -// 기술영업 벤더 후보 삭제 스키마 -export const removeTechCandidatesSchema = z.object({ - ids: z.array(z.number()).min(1, "At least one ID is required"), -}); - -export type CreateTechVendorCandidateSchema = z.infer<typeof createTechVendorCandidateSchema> -export type UpdateTechVendorCandidateSchema = z.infer<typeof updateTechVendorCandidateSchema> -export type RemoveTechCandidatesInput = z.infer<typeof removeTechCandidatesSchema>
\ No newline at end of file diff --git a/lib/tech-vendors/possible-items/possible-items-columns.tsx b/lib/tech-vendors/possible-items/possible-items-columns.tsx index 71bcb3b8..ef48c5b5 100644 --- a/lib/tech-vendors/possible-items/possible-items-columns.tsx +++ b/lib/tech-vendors/possible-items/possible-items-columns.tsx @@ -57,7 +57,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<TechVen {
accessorKey: "itemCode",
header: ({ column }) => (
- <DataTableColumnHeaderSimple column={column} title="아이템 코드" />
+ <DataTableColumnHeaderSimple column={column} title="자재 그룹" />
),
cell: ({ row }) => (
<div className="font-mono text-sm">
@@ -90,7 +90,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<TechVen {
accessorKey: "itemList",
header: ({ column }) => (
- <DataTableColumnHeaderSimple column={column} title="아이템명" />
+ <DataTableColumnHeaderSimple column={column} title="자재명" />
),
cell: ({ row }) => {
const itemList = row.getValue("itemList") as string | null
@@ -126,7 +126,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<TechVen {
accessorKey: "subItemList",
header: ({ column }) => (
- <DataTableColumnHeaderSimple column={column} title="서브아이템" />
+ <DataTableColumnHeaderSimple column={column} title="자재명(상세)" />
),
cell: ({ row }) => {
const subItemList = row.getValue("subItemList") as string | null
diff --git a/lib/tech-vendors/possible-items/possible-items-toolbar-actions.tsx b/lib/tech-vendors/possible-items/possible-items-toolbar-actions.tsx index 707d0513..074dc187 100644 --- a/lib/tech-vendors/possible-items/possible-items-toolbar-actions.tsx +++ b/lib/tech-vendors/possible-items/possible-items-toolbar-actions.tsx @@ -67,7 +67,7 @@ export function PossibleItemsTableToolbarActions({ onClick={onAdd}
>
<Plus className="mr-2 h-4 w-4" />
- 아이템 추가
+ 자재 연결하기
</Button>
{selectedRows.length > 0 && (
diff --git a/lib/techsales-rfq/table/detail-table/vendor-communication-drawer.tsx b/lib/techsales-rfq/table/detail-table/vendor-communication-drawer.tsx index 5b60ef0f..e6cd32a9 100644 --- a/lib/techsales-rfq/table/detail-table/vendor-communication-drawer.tsx +++ b/lib/techsales-rfq/table/detail-table/vendor-communication-drawer.tsx @@ -320,9 +320,9 @@ export function VendorCommunicationDrawer({ };
// 첨부파일 다운로드
- const handleAttachmentDownload = (attachment: Attachment) => {
- // TODO: 실제 다운로드 구현
- window.open(attachment.filePath, '_blank');
+ const handleAttachmentDownload = async (attachment: Attachment) => {
+ const { downloadFile } = await import("@/lib/file-download");
+ await downloadFile(attachment.filePath, attachment.originalFileName);
};
// 파일 아이콘 선택
diff --git a/lib/vendors/validations.ts b/lib/vendors/validations.ts index 6c106600..681bac62 100644 --- a/lib/vendors/validations.ts +++ b/lib/vendors/validations.ts @@ -150,6 +150,8 @@ const contactSchema = z.object({ .min(1, "Contact name is required") .max(255, "Max length 255"), contactPosition: z.string().max(100).optional(), + contactDepartment: z.string().max(100).optional(), + contactTask: z.string().max(100).optional(), contactEmail: z.string().email("Invalid email").max(255), contactPhone: z.string().max(50).optional(), isPrimary: z.boolean().default(false).optional()}) @@ -225,16 +227,16 @@ export const createVendorSchema = z .max(100, "Max length 100"), website: z.string().url("유효하지 않은 URL입니다. https:// 혹은 http:// 로 시작하는 주소를 입력해주세요.").max(255).optional(), - attachedFiles: z.any() - .refine( - val => { - return val && - (Array.isArray(val) ? val.length > 0 : - val instanceof FileList ? val.length > 0 : - val && typeof val === 'object' && 'length' in val && val.length > 0); - }, - { message: "첨부 파일은 필수입니다." } - ), + // attachedFiles: z.any() + // .refine( + // val => { + // return val && + // (Array.isArray(val) ? val.length > 0 : + // val instanceof FileList ? val.length > 0 : + // val && typeof val === 'object' && 'length' in val && val.length > 0); + // }, + // { message: "첨부 파일은 필수입니다." } + // ), status: vendorStatusEnum.default("PENDING_REVIEW"), |
