From 2ef02e27dbe639876fa3b90c30307dda183545ec Mon Sep 17 00:00:00 2001 From: dujinkim Date: Thu, 17 Jul 2025 10:50:52 +0000 Subject: (최겸) 기술영업 변경사항 적용 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/items-tech/table/add-items-dialog.tsx | 108 +++---- lib/items-tech/table/hull/import-item-handler.tsx | 10 +- lib/items-tech/table/hull/item-excel-template.tsx | 10 - .../table/hull/offshore-hull-table-columns.tsx | 4 +- .../hull/offshore-hull-table-toolbar-actions.tsx | 8 +- lib/items-tech/table/import-excel-button.tsx | 16 +- lib/items-tech/table/ship/Items-ship-table.tsx | 1 + lib/items-tech/table/ship/import-item-handler.tsx | 32 ++- .../table/ship/items-ship-table-columns.tsx | 4 +- .../table/ship/items-table-toolbar-actions.tsx | 9 +- lib/items-tech/table/top/import-item-handler.tsx | 28 +- lib/items-tech/table/top/item-excel-template.tsx | 7 - .../table/top/offshore-top-table-columns.tsx | 4 +- .../top/offshore-top-table-toolbar-actions.tsx | 8 +- lib/items-tech/table/update-items-sheet.tsx | 7 +- lib/items-tech/validations.ts | 18 +- lib/tech-vendor-invitation-token.ts | 83 ++++++ .../contacts-table/add-contact-dialog.tsx | 21 ++ .../contacts-table/contact-table-columns.tsx | 45 +-- lib/tech-vendors/items-table/add-item-dialog.tsx | 308 -------------------- .../items-table/feature-flags-provider.tsx | 108 ------- .../items-table/item-table-columns.tsx | 192 ------------- .../items-table/item-table-toolbar-actions.tsx | 104 ------- lib/tech-vendors/items-table/item-table.tsx | 83 ------ .../tech-vendor-rfq-history-table-columns.tsx | 243 ++++++++++++++++ ...ch-vendor-rfq-history-table-toolbar-actions.tsx | 52 ++++ .../tech-vendor-rfq-history-table.tsx | 120 ++++++++ lib/tech-vendors/service.ts | 312 ++++++++++++++++++--- lib/tech-vendors/table/add-vendor-dialog.tsx | 74 ++--- .../table/invite-tech-vendor-dialog.tsx | 184 ++++++++++++ .../table/tech-vendors-table-columns.tsx | 117 ++++---- .../table/tech-vendors-table-toolbar-actions.tsx | 16 ++ lib/tech-vendors/table/tech-vendors-table.tsx | 5 +- lib/tech-vendors/utils.ts | 10 +- lib/tech-vendors/validations.ts | 50 +++- 35 files changed, 1319 insertions(+), 1082 deletions(-) create mode 100644 lib/tech-vendor-invitation-token.ts delete mode 100644 lib/tech-vendors/items-table/add-item-dialog.tsx delete mode 100644 lib/tech-vendors/items-table/feature-flags-provider.tsx delete mode 100644 lib/tech-vendors/items-table/item-table-columns.tsx delete mode 100644 lib/tech-vendors/items-table/item-table-toolbar-actions.tsx delete mode 100644 lib/tech-vendors/items-table/item-table.tsx create mode 100644 lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table-columns.tsx create mode 100644 lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table-toolbar-actions.tsx create mode 100644 lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table.tsx create mode 100644 lib/tech-vendors/table/invite-tech-vendor-dialog.tsx (limited to 'lib') diff --git a/lib/items-tech/table/add-items-dialog.tsx b/lib/items-tech/table/add-items-dialog.tsx index ee8ee8b8..1b0d00c7 100644 --- a/lib/items-tech/table/add-items-dialog.tsx +++ b/lib/items-tech/table/add-items-dialog.tsx @@ -4,7 +4,7 @@ import * as React from "react" import { useRouter } from "next/navigation" import { zodResolver } from "@hookform/resolvers/zod" import { useForm } from "react-hook-form" -import { Plus } from "lucide-react" +import { Plus, Loader } from "lucide-react" import * as z from "zod" import { Button } from "@/components/ui/button" @@ -44,6 +44,7 @@ const shipbuildingWorkTypes = [ { label: "선실", value: "선실" }, { label: "배관", value: "배관" }, { label: "철의", value: "철의" }, + { label: "선체", value: "선체" }, ] as const // 해양 TOP 공종 유형 정의 @@ -60,12 +61,14 @@ const offshoreHullWorkTypes = [ { label: "HE", value: "HE" }, { label: "HH", value: "HH" }, { label: "HM", value: "HM" }, + { label: "HO", value: "HO" }, + { label: "HP", value: "HP" }, { label: "NC", value: "NC" }, ] as const // 기본 아이템 스키마 const itemFormSchema = z.object({ - itemCode: z.string().min(1, "아이템 코드는 필수입니다"), + itemCode: z.string().optional(), workType: z.string().min(1, "공종은 필수입니다"), // 조선 및 해양 아이템 공통 필드 itemList: z.string().optional(), @@ -83,6 +86,7 @@ interface AddItemDialogProps { export function AddItemDialog({ itemType }: AddItemDialogProps) { const router = useRouter() const [open, setOpen] = React.useState(false) + const [isAddPending, startAddTransition] = React.useTransition() // 기본값 설정 const getDefaultValues = () => { @@ -120,53 +124,55 @@ export function AddItemDialog({ itemType }: AddItemDialogProps) { }) const onSubmit = async (data: ItemFormValues) => { - try { - switch (itemType) { - case 'shipbuilding': - if (!data.shipTypes) { - toast.error("선종은 필수입니다") - return - } + startAddTransition(async () => { + try { + switch (itemType) { + case 'shipbuilding': + if (!data.shipTypes) { + toast.error("선종은 필수입니다") + return + } + + await createShipbuildingItem({ + itemCode: data.itemCode || "", + workType: data.workType as "기장" | "전장" | "선실" | "배관" | "철의" | "선체", + shipTypes: data.shipTypes, + itemList: data.itemList || null, + }); + break; - await createShipbuildingItem({ - itemCode: data.itemCode, - workType: data.workType, - shipTypes: data.shipTypes, - itemList: data.itemList || null, - }); - break; - - case 'offshoreTop': - await createOffshoreTopItem({ - itemCode: data.itemCode, - workType: data.workType as "TM" | "TS" | "TE" | "TP", - itemList: data.itemList || null, - subItemList: data.subItemList || null - }); - break; - - case 'offshoreHull': - await createOffshoreHullItem({ - itemCode: data.itemCode, - workType: data.workType as "HA" | "HE" | "HH" | "HM" | "NC", - itemList: data.itemList || null, - subItemList: data.subItemList || null - }); - break; + case 'offshoreTop': + await createOffshoreTopItem({ + itemCode: data.itemCode || "", + workType: data.workType as "TM" | "TS" | "TE" | "TP", + itemList: data.itemList || null, + subItemList: data.subItemList || null + }); + break; + + case 'offshoreHull': + await createOffshoreHullItem({ + itemCode: data.itemCode || "", + workType: data.workType as "HA" | "HE" | "HH" | "HM" | "HO" | "HP" | "NC", + itemList: data.itemList || null, + subItemList: data.subItemList || null + }); + break; + + default: + toast.error("지원하지 않는 아이템 타입입니다"); + return; + } - default: - toast.error("지원하지 않는 아이템 타입입니다"); - return; + toast.success("아이템이 성공적으로 추가되었습니다") + setOpen(false) + form.reset(getDefaultValues()) + router.refresh() + } catch (error) { + toast.error("아이템 추가 중 오류가 발생했습니다") + console.error(error) } - - toast.success("아이템이 성공적으로 추가되었습니다") - setOpen(false) - form.reset(getDefaultValues()) - router.refresh() - } catch (error) { - toast.error("아이템 추가 중 오류가 발생했습니다") - console.error(error) - } + }) } const getItemTypeLabel = () => { @@ -315,7 +321,15 @@ export function AddItemDialog({ itemType }: AddItemDialogProps) { - + diff --git a/lib/items-tech/table/hull/import-item-handler.tsx b/lib/items-tech/table/hull/import-item-handler.tsx index aa0c7992..8c8fc57d 100644 --- a/lib/items-tech/table/hull/import-item-handler.tsx +++ b/lib/items-tech/table/hull/import-item-handler.tsx @@ -4,11 +4,11 @@ import { z } from "zod" import { createOffshoreHullItem } from "../../service" // 해양 HULL 기능(공종) 유형 enum -const HULL_WORK_TYPES = ["HA", "HE", "HH", "HM", "NC"] as const; +const HULL_WORK_TYPES = ["HA", "HE", "HH", "HM", "HO", "HP", "NC"] as const; // 아이템 데이터 검증을 위한 Zod 스키마 const itemSchema = z.object({ - itemCode: z.string().min(1, "아이템 코드는 필수입니다"), + itemCode: z.string().optional(), workType: z.enum(HULL_WORK_TYPES, { required_error: "기능(공종)은 필수입니다", }), @@ -19,7 +19,7 @@ const itemSchema = z.object({ interface ProcessResult { successCount: number; errorCount: number; - errors?: Array<{ row: number; message: string }>; + errors: Array<{ row: number; message: string; itemCode?: string; workType?: string }>; } /** @@ -45,7 +45,7 @@ export async function processHullFileImport( // 데이터 행이 없으면 빈 결과 반환 if (dataRows.length === 0) { - return { successCount: 0, errorCount: 0 }; + return { successCount: 0, errorCount: 0, errors: [] }; } // 각 행에 대해 처리 @@ -89,7 +89,7 @@ export async function processHullFileImport( // 해양 HULL 아이템 생성 const result = await createOffshoreHullItem({ itemCode: cleanedRow.itemCode, - workType: cleanedRow.workType as "HA" | "HE" | "HH" | "HM" | "NC", + workType: cleanedRow.workType as "HA" | "HE" | "HH" | "HM" | "HO" | "HP" | "NC", itemList: cleanedRow.itemList, subItemList: cleanedRow.subItemList, }); diff --git a/lib/items-tech/table/hull/item-excel-template.tsx b/lib/items-tech/table/hull/item-excel-template.tsx index 13ec1973..79512b9b 100644 --- a/lib/items-tech/table/hull/item-excel-template.tsx +++ b/lib/items-tech/table/hull/item-excel-template.tsx @@ -1,9 +1,6 @@ import * as ExcelJS from 'exceljs'; import { saveAs } from "file-saver"; -// 해양 HULL 기능(공종) 유형 -const HULL_WORK_TYPES = ["HA", "HE", "HH", "HM", "NC"] as const; - /** * 해양 HULL 아이템 데이터 가져오기를 위한 Excel 템플릿 파일 생성 및 다운로드 */ @@ -79,13 +76,6 @@ export async function exportHullItemTemplate() { } }); - // 워크시트에 공종 유형 관련 메모 추가 - const infoRow = worksheet.addRow(['공종 유형 안내: ' + HULL_WORK_TYPES.join(', ')]); - infoRow.font = { bold: true, color: { argb: 'FF0000FF' } }; - worksheet.mergeCells(`A${infoRow.number}:F${infoRow.number}`); - - - // 워크시트 보호 (선택적) worksheet.protect('', { selectLockedCells: true, diff --git a/lib/items-tech/table/hull/offshore-hull-table-columns.tsx b/lib/items-tech/table/hull/offshore-hull-table-columns.tsx index 19782c42..efc6c583 100644 --- a/lib/items-tech/table/hull/offshore-hull-table-columns.tsx +++ b/lib/items-tech/table/hull/offshore-hull-table-columns.tsx @@ -162,7 +162,7 @@ export function getOffshoreHullColumns({ setRowAction }: GetColumnsProps): Colum header: ({ column }) => ( ), - cell: ({ row }) => formatDate(row.original.createdAt, "KR"), + cell: ({ row }) => formatDate(row.original.createdAt), enableSorting: true, enableHiding: true, meta: { @@ -174,7 +174,7 @@ export function getOffshoreHullColumns({ setRowAction }: GetColumnsProps): Colum header: ({ column }) => ( ), - cell: ({ row }) => formatDate(row.original.updatedAt, "KR"), + cell: ({ row }) => formatDate(row.original.updatedAt), enableSorting: true, enableHiding: true, meta: { diff --git a/lib/items-tech/table/hull/offshore-hull-table-toolbar-actions.tsx b/lib/items-tech/table/hull/offshore-hull-table-toolbar-actions.tsx index ad6f86b2..642dfea7 100644 --- a/lib/items-tech/table/hull/offshore-hull-table-toolbar-actions.tsx +++ b/lib/items-tech/table/hull/offshore-hull-table-toolbar-actions.tsx @@ -70,12 +70,10 @@ export function OffshoreHullTableToolbarActions({ table }: OffshoreHullTableTool // 필요한 헤더 직접 정의 (필터링 문제 해결) const headers = [ - { key: 'itemCode', header: '아이템 코드' }, - { key: 'itemName', header: '아이템 명' }, - { key: 'description', header: '설명' }, + { key: 'itemCode', header: '자재 그룹' }, { key: 'workType', header: '기능(공종)' }, - { key: 'itemList', header: '아이템 리스트' }, - { key: 'subItemList', header: '서브 아이템 리스트' }, + { key: 'itemList', header: '자재명' }, + { key: 'subItemList', header: '자재명(상세)' }, ].filter(header => !excludeColumns.includes(header.key)); console.log("내보내기 헤더:", headers); diff --git a/lib/items-tech/table/import-excel-button.tsx b/lib/items-tech/table/import-excel-button.tsx index 02736664..4565c365 100644 --- a/lib/items-tech/table/import-excel-button.tsx +++ b/lib/items-tech/table/import-excel-button.tsx @@ -84,7 +84,6 @@ export function ImportItemButton({ itemType, onSuccess }: ImportItemButtonProps) // 복호화 실패 시 원본 파일 사용 arrayBuffer = await file.arrayBuffer(); } - // ExcelJS 워크북 로드 const workbook = new ExcelJS.Workbook(); await workbook.xlsx.load(arrayBuffer); @@ -94,21 +93,21 @@ export function ImportItemButton({ itemType, onSuccess }: ImportItemButtonProps) if (!worksheet) { throw new Error("Excel 파일에 워크시트가 없습니다."); } - // 헤더 행 찾기 let headerRowIndex = 1; let headerRow: ExcelJS.Row | undefined; let headerValues: (string | null)[] = []; + worksheet.eachRow((row, rowNumber) => { const values = row.values as (string | null)[]; - if (!headerRow && values.some(v => v === "자재 그룹" || v === "itemCode" || v === "item_code")) { + if (!headerRow && values.some(v => v === "자재 그룹" || v === "자재 코드" || v === "itemCode" || v === "item_code")) { headerRowIndex = rowNumber; headerRow = row; headerValues = [...values]; } }); - + if (!headerRow) { throw new Error("Excel 파일에서 헤더 행을 찾을 수 없습니다."); } @@ -173,7 +172,7 @@ export function ImportItemButton({ itemType, onSuccess }: ImportItemButtonProps) }; // 선택된 타입에 따라 적절한 프로세스 함수 호출 - let result; + let result: { successCount: number; errorCount: number; errors?: Array<{ row: number; message: string; itemCode?: string; workType?: string }> }; if (itemType === "top") { result = await processTopFileImport(dataRows, updateProgress); } else if (itemType === "hull") { @@ -185,7 +184,12 @@ export function ImportItemButton({ itemType, onSuccess }: ImportItemButtonProps) toast.success(`${result.successCount}개의 ${ITEM_TYPE_NAMES[itemType]}이(가) 성공적으로 가져와졌습니다.`); if (result.errorCount > 0) { - toast.warning(`${result.errorCount}개의 항목은 처리할 수 없었습니다.`); + const errorDetails = result.errors?.map((error: { row: number; message: string; itemCode?: string; workType?: string }) => + `행 ${error.row}: ${error.itemCode || '알 수 없음'} (${error.workType || '알 수 없음'}) - ${error.message}` + ).join('\n') || '오류 정보를 가져올 수 없습니다.'; + + console.error('Import 오류 상세:', errorDetails); + toast.error(`${result.errorCount}개의 항목 처리 실패. 콘솔에서 상세 내용을 확인하세요.`); } // 상태 초기화 및 다이얼로그 닫기 diff --git a/lib/items-tech/table/ship/Items-ship-table.tsx b/lib/items-tech/table/ship/Items-ship-table.tsx index feab288a..cf41b3cf 100644 --- a/lib/items-tech/table/ship/Items-ship-table.tsx +++ b/lib/items-tech/table/ship/Items-ship-table.tsx @@ -90,6 +90,7 @@ export function ItemsShipTable({ promises }: ItemsTableProps) { { label: "선실", value: "선실" }, { label: "배관", value: "배관" }, { label: "철의", value: "철의" }, + { label: "선체", value: "선체" }, ], }, { diff --git a/lib/items-tech/table/ship/import-item-handler.tsx b/lib/items-tech/table/ship/import-item-handler.tsx index a47e451b..57546cc6 100644 --- a/lib/items-tech/table/ship/import-item-handler.tsx +++ b/lib/items-tech/table/ship/import-item-handler.tsx @@ -5,8 +5,8 @@ import { createShipbuildingImportItem } from "../../service" // 아이템 생성 // 아이템 데이터 검증을 위한 Zod 스키마 const itemSchema = z.object({ - itemCode: z.string().min(1, "아이템 코드는 필수입니다"), - workType: z.enum(["기장", "전장", "선실", "배관", "철의"], { + itemCode: z.string().optional(), + workType: z.enum(["기장", "전장", "선실", "배관", "철의", "선체"], { required_error: "기능(공종)은 필수입니다", }), shipTypes: z.string().nullable().optional(), @@ -16,7 +16,7 @@ const itemSchema = z.object({ interface ProcessResult { successCount: number; errorCount: number; - errors?: Array<{ row: number; message: string }>; + errors: Array<{ row: number; message: string; itemCode?: string; workType?: string }>; } /** @@ -42,7 +42,7 @@ export async function processFileImport( // 데이터 행이 없으면 빈 결과 반환 if (dataRows.length === 0) { - return { successCount: 0, errorCount: 0 }; + return { successCount: 0, errorCount: 0, errors: [] }; } // 각 행에 대해 처리 @@ -78,7 +78,12 @@ export async function processFileImport( err => `${err.path.join('.')}: ${err.message}` ).join(', '); - errors.push({ row: rowIndex, message: errorMessage }); + errors.push({ + row: rowIndex, + message: errorMessage, + itemCode: cleanedRow.itemCode, + workType: cleanedRow.workType + }); errorCount++; continue; } @@ -86,7 +91,7 @@ export async function processFileImport( // 아이템 생성 const result = await createShipbuildingImportItem({ itemCode: cleanedRow.itemCode, - workType: cleanedRow.workType as "기장" | "전장" | "선실" | "배관" | "철의", + workType: cleanedRow.workType as "기장" | "전장" | "선실" | "배관" | "철의" | "선체", shipTypes: cleanedRow.shipTypes, itemList: cleanedRow.itemList, }); @@ -96,16 +101,25 @@ export async function processFileImport( } else { errors.push({ row: rowIndex, - message: result.message || result.error || "알 수 없는 오류" + message: result.message || result.error || "알 수 없는 오류", + itemCode: cleanedRow.itemCode, + workType: cleanedRow.workType }); errorCount++; } } catch (error) { console.error(`${rowIndex}행 처리 오류:`, error); + + // cleanedRow가 정의되지 않은 경우를 처리 + const itemCode = row["자재 그룹"] || row["itemCode"] || ""; + const workType = row["기능(공종)"] || row["workType"] || ""; + errors.push({ row: rowIndex, - message: error instanceof Error ? error.message : "알 수 없는 오류" + message: error instanceof Error ? error.message : "알 수 없는 오류", + itemCode: typeof itemCode === 'string' ? itemCode.trim() : String(itemCode).trim(), + workType: typeof workType === 'string' ? workType.trim() : String(workType).trim() }); errorCount++; } @@ -120,6 +134,6 @@ export async function processFileImport( return { successCount, errorCount, - errors: errors.length > 0 ? errors : undefined + errors }; } \ No newline at end of file diff --git a/lib/items-tech/table/ship/items-ship-table-columns.tsx b/lib/items-tech/table/ship/items-ship-table-columns.tsx index 7018ae43..13ba2480 100644 --- a/lib/items-tech/table/ship/items-ship-table-columns.tsx +++ b/lib/items-tech/table/ship/items-ship-table-columns.tsx @@ -165,7 +165,7 @@ export function getShipbuildingColumns({ setRowAction }: GetColumnsProps): Colum header: ({ column }) => ( ), - cell: ({ row }) => formatDate(row.original.createdAt, "KR"), + cell: ({ row }) => formatDate(row.original.createdAt), enableSorting: true, enableHiding: true, meta: { @@ -177,7 +177,7 @@ export function getShipbuildingColumns({ setRowAction }: GetColumnsProps): Colum header: ({ column }) => ( ), - cell: ({ row }) => formatDate(row.original.updatedAt, "KR"), + cell: ({ row }) => formatDate(row.original.updatedAt), enableSorting: true, enableHiding: true, meta: { diff --git a/lib/items-tech/table/ship/items-table-toolbar-actions.tsx b/lib/items-tech/table/ship/items-table-toolbar-actions.tsx index e58ba135..29995327 100644 --- a/lib/items-tech/table/ship/items-table-toolbar-actions.tsx +++ b/lib/items-tech/table/ship/items-table-toolbar-actions.tsx @@ -23,7 +23,7 @@ import { ImportItemButton } from "../import-excel-button" interface ShipbuildingItem { id: number; itemId: number; - workType: "기장" | "전장" | "선실" | "배관" | "철의"; + workType: "기장" | "전장" | "선실" | "배관" | "철의" | "선체"; shipTypes: string; itemCode: string; itemName: string; @@ -70,12 +70,11 @@ export function ItemsTableToolbarActions({ table }: ItemsTableToolbarActionsProp // 필요한 헤더 직접 정의 (필터링 문제 해결) const headers = [ - { key: 'itemCode', header: '아이템 코드' }, - { key: 'itemName', header: '아이템 명' }, - { key: 'description', header: '설명' }, + { key: 'itemCode', header: '자재 그룹' }, { key: 'workType', header: '기능(공종)' }, { key: 'shipTypes', header: '선종' }, - { key: 'itemList', header: '아이템 리스트' } + { key: 'itemList', header: '자재명' }, + { key: 'subItemList', header: '자재명(상세)' }, ].filter(header => !excludeColumns.includes(header.key)); console.log("내보내기 헤더:", headers); diff --git a/lib/items-tech/table/top/import-item-handler.tsx b/lib/items-tech/table/top/import-item-handler.tsx index 541ec4ef..0a163791 100644 --- a/lib/items-tech/table/top/import-item-handler.tsx +++ b/lib/items-tech/table/top/import-item-handler.tsx @@ -8,7 +8,7 @@ const TOP_WORK_TYPES = ["TM", "TS", "TE", "TP"] as const; // 아이템 데이터 검증을 위한 Zod 스키마 const itemSchema = z.object({ - itemCode: z.string().min(1, "아이템 코드는 필수입니다"), + itemCode: z.string().optional(), workType: z.enum(TOP_WORK_TYPES, { required_error: "기능(공종)은 필수입니다", }), @@ -19,7 +19,7 @@ const itemSchema = z.object({ interface ProcessResult { successCount: number; errorCount: number; - errors?: Array<{ row: number; message: string }>; + errors: Array<{ row: number; message: string; itemCode?: string; workType?: string }>; } /** @@ -45,7 +45,7 @@ export async function processTopFileImport( // 데이터 행이 없으면 빈 결과 반환 if (dataRows.length === 0) { - return { successCount: 0, errorCount: 0 }; + return { successCount: 0, errorCount: 0, errors: [] }; } // 각 행에 대해 처리 @@ -81,7 +81,12 @@ export async function processTopFileImport( err => `${err.path.join('.')}: ${err.message}` ).join(', '); - errors.push({ row: rowIndex, message: errorMessage }); + errors.push({ + row: rowIndex, + message: errorMessage, + itemCode: cleanedRow.itemCode, + workType: cleanedRow.workType + }); errorCount++; continue; } @@ -99,15 +104,24 @@ export async function processTopFileImport( } else { errors.push({ row: rowIndex, - message: result.message || result.error || "알 수 없는 오류" + message: result.message || result.error || "알 수 없는 오류", + itemCode: cleanedRow.itemCode, + workType: cleanedRow.workType }); errorCount++; } } catch (error) { console.error(`${rowIndex}행 처리 오류:`, error); + + // cleanedRow가 정의되지 않은 경우를 처리 + const itemCode = row["자재 그룹"] || row["itemCode"] || ""; + const workType = row["기능(공종)"] || row["workType"] || ""; + errors.push({ row: rowIndex, - message: error instanceof Error ? error.message : "알 수 없는 오류" + message: error instanceof Error ? error.message : "알 수 없는 오류", + itemCode: typeof itemCode === 'string' ? itemCode.trim() : String(itemCode).trim(), + workType: typeof workType === 'string' ? workType.trim() : String(workType).trim() }); errorCount++; } @@ -122,6 +136,6 @@ export async function processTopFileImport( return { successCount, errorCount, - errors: errors.length > 0 ? errors : undefined + errors }; } diff --git a/lib/items-tech/table/top/item-excel-template.tsx b/lib/items-tech/table/top/item-excel-template.tsx index f547d617..b67d91be 100644 --- a/lib/items-tech/table/top/item-excel-template.tsx +++ b/lib/items-tech/table/top/item-excel-template.tsx @@ -1,8 +1,6 @@ import * as ExcelJS from 'exceljs'; import { saveAs } from "file-saver"; -// 해양 TOP 기능(공종) 유형 -const TOP_WORK_TYPES = ["TM", "TS", "TE", "TP"] as const; /** * 해양 TOP 아이템 데이터 가져오기를 위한 Excel 템플릿 파일 생성 및 다운로드 @@ -81,11 +79,6 @@ export async function exportTopItemTemplate() { } }); - // 워크시트에 공종 유형 관련 메모 추가 - const infoRow = worksheet.addRow(['공종 유형 안내: ' + TOP_WORK_TYPES.join(', ')]); - infoRow.font = { bold: true, color: { argb: 'FF0000FF' } }; - worksheet.mergeCells(`A${infoRow.number}:F${infoRow.number}`); - // 워크시트 보호 (선택적) worksheet.protect('', { diff --git a/lib/items-tech/table/top/offshore-top-table-columns.tsx b/lib/items-tech/table/top/offshore-top-table-columns.tsx index c2df4b75..93f27492 100644 --- a/lib/items-tech/table/top/offshore-top-table-columns.tsx +++ b/lib/items-tech/table/top/offshore-top-table-columns.tsx @@ -162,7 +162,7 @@ export function getOffshoreTopColumns({ setRowAction }: GetColumnsProps): Column header: ({ column }) => ( ), - cell: ({ row }) => formatDate(row.original.createdAt, "KR"), + cell: ({ row }) => formatDate(row.original.createdAt), enableSorting: true, enableHiding: true, meta: { @@ -174,7 +174,7 @@ export function getOffshoreTopColumns({ setRowAction }: GetColumnsProps): Column header: ({ column }) => ( ), - cell: ({ row }) => formatDate(row.original.updatedAt, "KR"), + cell: ({ row }) => formatDate(row.original.updatedAt), enableSorting: true, enableHiding: true, meta: { diff --git a/lib/items-tech/table/top/offshore-top-table-toolbar-actions.tsx b/lib/items-tech/table/top/offshore-top-table-toolbar-actions.tsx index f91adf96..bf10560f 100644 --- a/lib/items-tech/table/top/offshore-top-table-toolbar-actions.tsx +++ b/lib/items-tech/table/top/offshore-top-table-toolbar-actions.tsx @@ -70,12 +70,10 @@ export function OffshoreTopTableToolbarActions({ table }: OffshoreTopTableToolba // 필요한 헤더 직접 정의 (필터링 문제 해결) const headers = [ - { key: 'itemCode', header: '아이템 코드' }, - { key: 'itemName', header: '아이템 명' }, - { key: 'description', header: '설명' }, + { key: 'itemCode', header: '자재 그룹' }, { key: 'workType', header: '기능(공종)' }, - { key: 'itemList', header: '아이템 리스트' }, - { key: 'subItemList', header: '서브 아이템 리스트' }, + { key: 'itemList', header: '자재명' }, + { key: 'subItemList', header: '자재명(상세)' }, ].filter(header => !excludeColumns.includes(header.key)); console.log("내보내기 헤더:", headers); diff --git a/lib/items-tech/table/update-items-sheet.tsx b/lib/items-tech/table/update-items-sheet.tsx index 16dfcb71..978e83d5 100644 --- a/lib/items-tech/table/update-items-sheet.tsx +++ b/lib/items-tech/table/update-items-sheet.tsx @@ -44,6 +44,7 @@ const shipbuildingWorkTypes = [ { value: "선실", label: "선실" }, { value: "배관", label: "배관" }, { value: "철의", label: "철의" }, + { value: "선체", label: "선체" }, ] as const const offshoreTopWorkTypes = [ @@ -58,6 +59,8 @@ const offshoreHullWorkTypes = [ { value: "HE", label: "HE" }, { value: "HH", label: "HH" }, { value: "HM", label: "HM" }, + { value: "HO", label: "HO" }, + { value: "HP", label: "HP" }, { value: "NC", label: "NC" }, ] as const @@ -65,7 +68,7 @@ const offshoreHullWorkTypes = [ type ShipbuildingItem = { id: number itemCode: string - workType: "기장" | "전장" | "선실" | "배관" | "철의" + workType: "기장" | "전장" | "선실" | "배관" | "철의" | "선체" shipTypes: string itemList: string | null } @@ -81,7 +84,7 @@ type OffshoreTopItem = { type OffshoreHullItem = { id: number itemCode: string - workType: "HA" | "HE" | "HH" | "HM" | "NC" + workType: "HA" | "HE" | "HH" | "HM" | "HO" | "HP" | "NC" itemList: string | null subItemList: string | null } diff --git a/lib/items-tech/validations.ts b/lib/items-tech/validations.ts index 653f0af8..95a34b58 100644 --- a/lib/items-tech/validations.ts +++ b/lib/items-tech/validations.ts @@ -24,6 +24,8 @@ export const shipbuildingSearchParamsCache = createSearchParamsCache({ itemList: parseAsString.withDefault(""), filters: getFiltersStateParser().withDefault([]), joinOperator: parseAsStringEnum(["and", "or"]).withDefault("and"), + shipFilters: getFiltersStateParser().withDefault([]), + shipJoinOperator: parseAsStringEnum(["and", "or"]).withDefault("and"), search: parseAsString.withDefault(""), }) @@ -42,6 +44,8 @@ export const offshoreTopSearchParamsCache = createSearchParamsCache({ subItemList: parseAsString.withDefault(""), filters: getFiltersStateParser().withDefault([]), joinOperator: parseAsStringEnum(["and", "or"]).withDefault("and"), + topFilters: getFiltersStateParser().withDefault([]), + topJoinOperator: parseAsStringEnum(["and", "or"]).withDefault("and"), search: parseAsString.withDefault(""), }) @@ -59,6 +63,8 @@ export const offshoreHullSearchParamsCache = createSearchParamsCache({ subItemList: parseAsString.withDefault(""), filters: getFiltersStateParser().withDefault([]), joinOperator: parseAsStringEnum(["and", "or"]).withDefault("and"), + hullFilters: getFiltersStateParser().withDefault([]), + hullJoinOperator: parseAsStringEnum(["and", "or"]).withDefault("and"), search: parseAsString.withDefault(""), }) @@ -66,7 +72,7 @@ export const offshoreHullSearchParamsCache = createSearchParamsCache({ // 조선 아이템 업데이트 스키마 export const updateShipbuildingItemSchema = z.object({ itemCode: z.string(), - workType: z.string().optional(), + workType: z.enum(["기장", "전장", "선실", "배관", "철의", "선체"]).optional(), shipTypes: z.string().optional(), itemList: z.string().optional(), }) @@ -80,7 +86,7 @@ export type UpdateShipbuildingItemSchema = z.infer { + const expiresAt = Date.now() + 7 * 24 * 60 * 60 * 1000; // 7일 + + const token = await new SignJWT({ + vendorId: payload.vendorId, + vendorName: payload.vendorName, + email: payload.email, + type: "tech-vendor-invitation", + expiresAt, + }) + .setProtectedHeader({ alg: "HS256" }) + .setIssuedAt() + .setExpirationTime("7d") + .sign(key); + + return token; +} + +/** + * 기술영업 벤더 초대 토큰 검증 + */ +export async function verifyTechVendorInvitationToken( + token: string +): Promise { + try { + const { payload } = await jwtVerify(token, key); + + const tokenPayload = payload as unknown as TechVendorInvitationPayload; + + // 토큰 타입 검증 + if (tokenPayload.type !== "tech-vendor-invitation") { + console.error("Invalid token type:", tokenPayload.type); + return null; + } + + // 만료 시간 검증 + if (Date.now() > tokenPayload.expiresAt) { + console.error("Token has expired"); + return null; + } + + return tokenPayload; + } catch (error) { + console.error("Token verification failed:", error); + return null; + } +} + +/** + * 초대 토큰을 포함한 가입 URL 생성 + */ +export async function createTechVendorSignupUrl(token: string): Promise { + const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3000"; + return `${baseUrl}/ko/auth/tech-signup?token=${token}`; +} \ No newline at end of file diff --git a/lib/tech-vendors/contacts-table/add-contact-dialog.tsx b/lib/tech-vendors/contacts-table/add-contact-dialog.tsx index 05e5092e..ff845e20 100644 --- a/lib/tech-vendors/contacts-table/add-contact-dialog.tsx +++ b/lib/tech-vendors/contacts-table/add-contact-dialog.tsx @@ -39,6 +39,7 @@ export function AddContactDialog({ vendorId }: AddContactDialogProps) { contactPosition: "", contactEmail: "", contactPhone: "", + country: "", isPrimary: false, }, }) @@ -50,6 +51,12 @@ export function AddContactDialog({ vendorId }: AddContactDialogProps) { alert(`에러: ${result.error}`) return } + + // 성공 시 메시지 표시 + if (result.data?.message) { + alert(result.data.message) + } + // 성공 시 모달 닫고 폼 리셋 form.reset() setOpen(false) @@ -139,6 +146,20 @@ export function AddContactDialog({ vendorId }: AddContactDialogProps) { )} /> + ( + + Country + + + + + + )} + /> + {/* 단순 checkbox */} | null>>; + setRowAction: React.Dispatch | null>>; } /** * tanstack table 컬럼 정의 (중첩 헤더 버전) */ -export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef[] { +export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef[] { // ---------------------------------------------------------------- // 1) select 컬럼 (체크박스) // ---------------------------------------------------------------- - const selectColumn: ColumnDef = { + const selectColumn: ColumnDef = { id: "select", header: ({ table }) => ( = { + const actionsColumn: ColumnDef = { id: "actions", enableHiding: false, cell: function Cell({ row }) { - const [isUpdatePending, startUpdateTransition] = React.useTransition() - return ( @@ -95,7 +80,6 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef { setRowAction({ row, type: "update" }) - }} > Edit @@ -118,10 +102,10 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef[] } - const groupMap: Record[]> = {} + // 3-1) groupMap: { [groupName]: ColumnDef[] } + const groupMap: Record[]> = {} - vendorContactsColumnsConfig.forEach((cfg) => { + techVendorContactsColumnsConfig.forEach((cfg) => { // 만약 group가 없으면 "_noGroup" 처리 const groupName = cfg.group || "_noGroup" @@ -130,7 +114,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef = { + const childCol: ColumnDef = { accessorKey: cfg.id, enableResizing: true, header: ({ column }) => ( @@ -142,19 +126,16 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef { - - if (cfg.id === "createdAt") { const dateVal = cell.getValue() as Date - return formatDate(dateVal, "KR") + return formatDate(dateVal) } if (cfg.id === "updatedAt") { const dateVal = cell.getValue() as Date - return formatDate(dateVal, "KR") + return formatDate(dateVal) } - // code etc... return row.getValue(cfg.id) ?? "" }, @@ -166,7 +147,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef[] = [] + const nestedColumns: ColumnDef[] = [] // 순서를 고정하고 싶다면 group 순서를 미리 정의하거나 sort해야 함 // 여기서는 그냥 Object.entries 순서 diff --git a/lib/tech-vendors/items-table/add-item-dialog.tsx b/lib/tech-vendors/items-table/add-item-dialog.tsx deleted file mode 100644 index 21875295..00000000 --- a/lib/tech-vendors/items-table/add-item-dialog.tsx +++ /dev/null @@ -1,308 +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 { useRouter } from "next/navigation" - -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 { - Form, - FormControl, - FormField, - FormItem, - FormLabel, -} from "@/components/ui/form" -import { - Popover, - PopoverContent, - PopoverTrigger, -} from "@/components/ui/popover" -import { - Command, - CommandEmpty, - CommandGroup, - CommandInput, - CommandItem, - CommandList, -} from "@/components/ui/command" -import { cn } from "@/lib/utils" -import { toast } from "sonner" - -import { - createTechVendorItemSchema, - type CreateTechVendorItemSchema, -} from "@/lib/tech-vendors/validations" - -import { createTechVendorItem, getItemsForTechVendor, ItemDropdownOption } from "../service" - -interface AddItemDialogProps { - vendorId: number - vendorType: string // UI에서 전달하지만 내부적으로는 사용하지 않음 -} - -export function AddItemDialog({ vendorId }: AddItemDialogProps) { - const router = useRouter() - const [open, setOpen] = React.useState(false) - const [commandOpen, setCommandOpen] = React.useState(false) - const [items, setItems] = React.useState([]) - const [filteredItems, setFilteredItems] = React.useState([]) - const [isLoading, setIsLoading] = React.useState(false) - const [searchTerm, setSearchTerm] = React.useState("") - - const [selectedItem, setSelectedItem] = React.useState<{ - itemName: string; - description: string; - } | null>(null) - - const form = useForm({ - resolver: zodResolver(createTechVendorItemSchema), - defaultValues: { - vendorId, - itemCode: "", - }, - }) - - const fetchItems = React.useCallback(async () => { - if (items.length > 0) return - - console.log(`[AddItemDialog] fetchItems - 벤더 ID: ${vendorId} 시작`) - - setIsLoading(true) - try { - console.log(`[AddItemDialog] getItemsForTechVendor 호출 - vendorId: ${vendorId}`) - const result = await getItemsForTechVendor(vendorId) - console.log(`[AddItemDialog] getItemsForTechVendor 결과:`, result) - - if (result.data) { - console.log(`[AddItemDialog] 사용 가능한 아이템 목록:`, result.data) - setItems(result.data as ItemDropdownOption[]) - setFilteredItems(result.data as ItemDropdownOption[]) - } else if (result.error) { - console.error("[AddItemDialog] 아이템 조회 실패:", result.error) - toast.error(result.error) - } - } catch (err) { - console.error("[AddItemDialog] 아이템 조회 실패:", err) - toast.error("아이템 목록을 불러오는데 실패했습니다.") - } finally { - setIsLoading(false) - console.log(`[AddItemDialog] fetchItems 완료`) - } - }, [items.length, vendorId]) - - React.useEffect(() => { - if (commandOpen) { - console.log(`[AddItemDialog] Popover 열림 - fetchItems 호출`) - fetchItems() - } - }, [commandOpen, fetchItems]) - - React.useEffect(() => { - if (!items.length) return - - if (!searchTerm.trim()) { - setFilteredItems(items) - return - } - - console.log(`[AddItemDialog] 검색어로 필터링: "${searchTerm}"`) - const lowerSearch = searchTerm.toLowerCase() - const filtered = items.filter(item => - item.itemCode.toLowerCase().includes(lowerSearch) || - item.itemList.toLowerCase().includes(lowerSearch) || - (item.subItemList && item.subItemList.toLowerCase().includes(lowerSearch)) - ) - - console.log(`[AddItemDialog] 필터링 결과: ${filtered.length}개 아이템`) - setFilteredItems(filtered) - }, [searchTerm, items]) - - const handleSelectItem = (item: ItemDropdownOption) => { - console.log(`[AddItemDialog] 아이템 선택: ${item.itemCode}`) - form.setValue("itemCode", item.itemCode, { shouldValidate: true }) - setSelectedItem({ - itemName: item.itemList, - description: item.subItemList || "", - }) - console.log(`[AddItemDialog] 선택된 아이템 정보:`, { - itemCode: item.itemCode, - itemName: item.itemList, - description: item.subItemList || "" - }) - setCommandOpen(false) - } - - async function onSubmit(data: CreateTechVendorItemSchema) { - console.log(`[AddItemDialog] 폼 제출 시작 - 데이터:`, data) - try { - if (!data.itemCode) { - console.error(`[AddItemDialog] itemCode가 없습니다.`) - toast.error("아이템을 선택해주세요.") - return - } - - console.log(`[AddItemDialog] createTechVendorItem 호출 - vendorId: ${data.vendorId}, itemCode: ${data.itemCode}`) - const submitData = { - ...data, - itemName: selectedItem?.itemName || "기술영업" - } - console.log(`[AddItemDialog] 최종 제출 데이터:`, submitData) - - const result = await createTechVendorItem(submitData) - console.log(`[AddItemDialog] createTechVendorItem 결과:`, result) - - if (result.error) { - console.error(`[AddItemDialog] 추가 실패:`, result.error) - toast.error(result.error) - return - } - - console.log(`[AddItemDialog] 아이템 추가 성공`) - toast.success("아이템이 추가되었습니다.") - form.reset() - setSelectedItem(null) - setOpen(false) - console.log(`[AddItemDialog] 화면 새로고침 시작`) - router.refresh() - console.log(`[AddItemDialog] 화면 새로고침 완료`) - } catch (err) { - console.error("[AddItemDialog] 아이템 추가 오류:", err) - toast.error("아이템 추가 중 오류가 발생했습니다.") - } - } - - function handleDialogOpenChange(nextOpen: boolean) { - console.log(`[AddItemDialog] 다이얼로그 상태 변경: ${nextOpen ? '열림' : '닫힘'}`) - if (!nextOpen) { - form.reset() - setSelectedItem(null) - } - setOpen(nextOpen) - } - - const selectedItemCode = form.watch("itemCode") - console.log(`[AddItemDialog] 현재 선택된 itemCode:`, selectedItemCode) - const displayItemName = selectedItem?.itemName || "" - - return ( - - - - - - - - Create New Item - - 아이템을 선택한 후 Create 버튼을 누르세요. - - - -
- { - console.log(`[AddItemDialog] 폼 제출 이벤트 발생`) - form.handleSubmit(onSubmit)(e) - }} className="flex flex-col flex-1 overflow-hidden"> -
-
- 아이템 선택 - - - - - - - - - 검색 결과가 없습니다 - {isLoading ? ( -
로딩 중...
- ) : ( - - {filteredItems.map((item) => ( - handleSelectItem(item)} - > - - {item.itemCode} - - {item.itemList} - - ))} - - )} -
-
-
-
-
- - {selectedItem && ( -
-

선택된 아이템 정보

- - ( - - - - - - )} - /> - -
-
Item Name
-
{selectedItem.itemName}
-
- - {selectedItem.description && ( -
-
Description
-
{selectedItem.description}
-
- )} -
- )} -
- - - - -
- -
-
- ) -} \ No newline at end of file diff --git a/lib/tech-vendors/items-table/feature-flags-provider.tsx b/lib/tech-vendors/items-table/feature-flags-provider.tsx deleted file mode 100644 index 81131894..00000000 --- a/lib/tech-vendors/items-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({ - 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( - "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 ( - void setFeatureFlags(value), - }} - > -
- setFeatureFlags(value)} - className="w-fit gap-0" - > - {dataTableConfig.featureFlags.map((flag, index) => ( - - - - - - -
{flag.tooltipTitle}
-
- {flag.tooltipDescription} -
-
-
- ))} -
-
- {children} -
- ) -} diff --git a/lib/tech-vendors/items-table/item-table-columns.tsx b/lib/tech-vendors/items-table/item-table-columns.tsx deleted file mode 100644 index 72986849..00000000 --- a/lib/tech-vendors/items-table/item-table-columns.tsx +++ /dev/null @@ -1,192 +0,0 @@ -"use client" - -import * as React from "react" -import { type DataTableRowAction } from "@/types/table" -import { type ColumnDef } from "@tanstack/react-table" -import { MoreHorizontal } from "lucide-react" -import { format } from "date-fns" -import { ko } from "date-fns/locale" - -import { Badge } from "@/components/ui/badge" -import { Button } from "@/components/ui/button" -import { Checkbox } from "@/components/ui/checkbox" -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuLabel, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu" - -import { TechVendorItemsView } from "@/db/schema/techVendors" -import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header" -import { - techVendorItemsColumnsConfig, - shipbuildingColumnsConfig, - offshoreTopColumnsConfig, - offshoreHullColumnsConfig -} from "@/config/techVendorItemsColumnsConfig" - -interface ColumnConfig { - id: string - label: string - excelHeader: string - type: string - minWidth: number - defaultWidth: number - group?: string -} - -interface GetColumnsOptions { - setRowAction: React.Dispatch | null>> - vendorType: string -} - -export function getColumns({ setRowAction, vendorType }: GetColumnsOptions): ColumnDef[] { - // 벤더 타입에 따라 적절한 컬럼 설정 선택 - const columnsConfig = (() => { - switch (vendorType) { - case "조선": - return shipbuildingColumnsConfig; - case "해양TOP": - return offshoreTopColumnsConfig; - case "해양HULL": - return offshoreHullColumnsConfig; - default: - return techVendorItemsColumnsConfig; - } - })(); - - // ---------------------------------------------------------------- - // 1) select 컬럼 (체크박스) - // ---------------------------------------------------------------- - const selectColumn: ColumnDef = { - id: "select", - header: ({ table }) => ( - table.toggleAllPageRowsSelected(!!value)} - aria-label="Select all" - className="translate-y-[2px]" - /> - ), - cell: ({ row }) => ( - row.toggleSelected(!!value)} - aria-label="Select row" - className="translate-y-[2px]" - /> - ), - enableSorting: false, - enableHiding: false, - } - - // ---------------------------------------------------------------- - // 2) actions 컬럼 (Dropdown 메뉴) - // ---------------------------------------------------------------- - // const actionsColumn: ColumnDef = { - // id: "actions", - // cell: ({ row }) => { - // return ( - // - // - // - // - // - // Actions - // - // setRowAction({ - // type: "update", - // row, - // }) - // }> - // View Details - // - // - // - // ) - // }, - // } - - // ---------------------------------------------------------------- - // 3) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성 - // ---------------------------------------------------------------- - const groupMap: Record[]> = {} - - columnsConfig.forEach((cfg: ColumnConfig) => { - // 만약 group가 없으면 "_noGroup" 처리 - const groupName = cfg.group || "_noGroup" - - if (!groupMap[groupName]) { - groupMap[groupName] = [] - } - - // child column 정의 - const childCol: ColumnDef = { - accessorKey: cfg.id, - enableResizing: true, - header: ({ column }) => ( - - ), - minSize: cfg.minWidth, - size: cfg.defaultWidth, - meta: { - excelHeader: cfg.excelHeader, - group: cfg.group, - type: cfg.type, - }, - cell: ({ row, cell }) => { - if (cfg.id === "createdAt" || cfg.id === "updatedAt") { - const dateVal = cell.getValue() as Date - return format(dateVal, "PPP", { locale: ko }) - } - - if (cfg.id === "techVendorType") { - const type = cell.getValue() as string - return type ? ( - - {type} - - ) : null - } - - return row.getValue(cfg.id) ?? "" - }, - } - - groupMap[groupName].push(childCol) - }) - - // ---------------------------------------------------------------- - // 3-2) groupMap에서 실제 상위 컬럼(그룹)을 만들기 - // ---------------------------------------------------------------- - const nestedColumns: ColumnDef[] = [] - - Object.entries(groupMap).forEach(([groupName, colDefs]) => { - if (groupName === "_noGroup") { - nestedColumns.push(...colDefs) - } else { - nestedColumns.push({ - id: groupName, - header: groupName, - columns: colDefs, - }) - } - }) - - // ---------------------------------------------------------------- - // 4) 최종 컬럼 배열: select, nestedColumns, actions - // ---------------------------------------------------------------- - return [ - selectColumn, - ...nestedColumns, - // actionsColumn, - ] -} \ No newline at end of file diff --git a/lib/tech-vendors/items-table/item-table-toolbar-actions.tsx b/lib/tech-vendors/items-table/item-table-toolbar-actions.tsx deleted file mode 100644 index b327ff56..00000000 --- a/lib/tech-vendors/items-table/item-table-toolbar-actions.tsx +++ /dev/null @@ -1,104 +0,0 @@ -"use client" - -import * as React from "react" -import { type Table } from "@tanstack/react-table" -import { Download, Upload } from "lucide-react" -import { toast } from "sonner" - -import { exportTableToExcel } from "@/lib/export" -import { Button } from "@/components/ui/button" -import { TechVendorItemsView } from "@/db/schema/techVendors" -import { AddItemDialog } from "./add-item-dialog" -import { importTasksExcel } from "@/lib/tasks/service" - -interface TechVendorItemsTableToolbarActionsProps { - table: Table - vendorId: number - vendorType: string -} - -export function TechVendorItemsTableToolbarActions({ table, vendorId, vendorType }: TechVendorItemsTableToolbarActionsProps) { - // 파일 input을 숨기고, 버튼 클릭 시 참조해 클릭하는 방식 - const fileInputRef = React.useRef(null) - - // 파일이 선택되었을 때 처리 - async function onFileChange(event: React.ChangeEvent) { - const file = event.target.files?.[0] - if (!file) return - - // 파일 초기화 (동일 파일 재업로드 시에도 onChange가 트리거되도록) - event.target.value = "" - - // 서버 액션 or API 호출 - try { - // 예: 서버 액션 호출 - const { errorFile, errorMessage } = await importTasksExcel(file) - - if (errorMessage) { - toast.error(errorMessage) - } - if (errorFile) { - // 에러 엑셀을 다운로드 - const url = URL.createObjectURL(errorFile) - const link = document.createElement("a") - link.href = url - link.download = "errors.xlsx" - link.click() - URL.revokeObjectURL(url) - } else { - // 성공 - toast.success("Import success") - // 필요 시 revalidateTag("tasks") 등 - } - - } catch (err) { - console.error("파일 업로드 중 오류가 발생했습니다:", err) - toast.error("파일 업로드 중 오류가 발생했습니다.") - } - } - - function handleImportClick() { - // 숨겨진 요소를 클릭 - fileInputRef.current?.click() - } - - return ( -
- - {/* */} - - {/** 3) Import 버튼 (파일 업로드) */} - - {/* - 실제로는 숨겨진 input과 연결: - - accept=".xlsx,.xls" 등으로 Excel 파일만 업로드 허용 - */} - - - {/** 4) Export 버튼 */} - -
- ) -} \ No newline at end of file diff --git a/lib/tech-vendors/items-table/item-table.tsx b/lib/tech-vendors/items-table/item-table.tsx deleted file mode 100644 index 2eecd829..00000000 --- a/lib/tech-vendors/items-table/item-table.tsx +++ /dev/null @@ -1,83 +0,0 @@ -"use client" - -import * as React from "react" -import type { - DataTableAdvancedFilterField, - DataTableFilterField, - DataTableRowAction, -} from "@/types/table" - -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 { getColumns } from "./item-table-columns" -import { getVendorItemsByType } from "@/lib/tech-vendors/service" -import { TechVendorItemsTableToolbarActions } from "./item-table-toolbar-actions" - -interface TechVendorItemsTableProps { - promises: Promise>> - vendorId: number - vendorType: string -} - -export function TechVendorItemsTable({ promises, vendorId, vendorType }: TechVendorItemsTableProps) { - // Suspense로 받아온 데이터 - const { data } = React.use(promises) - - const [rowAction, setRowAction] = React.useState | null>(null) - - const columns = React.useMemo( - () => getColumns({ - setRowAction, - vendorType - }), - [vendorType] - ) - - const filterFields: DataTableFilterField[] = [] - - const advancedFilterFields: DataTableAdvancedFilterField[] = [ - { id: "itemList", label: "Item List", type: "text" }, - { id: "itemCode", label: "Item Code", type: "text" }, - { id: "workType", label: "Work Type", type: "text" }, - { id: "subItemList", label: "Sub Item List", type: "text" }, - { id: "createdAt", label: "Created at", type: "date" }, - { id: "updatedAt", label: "Updated at", type: "date" }, - ] - - const { table } = useDataTable({ - data, - columns, - pageCount: 1, - filterFields, - enablePinning: true, - enableAdvancedFilter: true, - initialState: { - sorting: [{ id: "createdAt", desc: true }], - columnPinning: { right: ["actions"] }, - }, - getRowId: (originalRow) => String(originalRow.itemCode), - shallow: false, - clearOnDefault: true, - }) - - return ( - <> - - - - - - - ) -} \ No newline at end of file diff --git a/lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table-columns.tsx b/lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table-columns.tsx new file mode 100644 index 00000000..a7eed1d2 --- /dev/null +++ b/lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table-columns.tsx @@ -0,0 +1,243 @@ +"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 Link from "next/link" + +import { formatDate } from "@/lib/utils" +import { Button } from "@/components/ui/button" +import { Checkbox } from "@/components/ui/checkbox" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu" +import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header" +import { techVendorRfqHistoryColumnsConfig } from "@/config/techVendorRfqHistoryColumnsConfig" +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip" + +export interface TechVendorRfqHistoryRow { + id: number; + rfqCode: string | null; + description: string | null; + projectCode: string | null; + projectName: string | null; + projectType: string | null; // 프로젝트 타입 추가 + status: string; + totalAmount: string | null; + currency: string | null; + dueDate: Date | null; + createdAt: Date; + quotationCode: string | null; + submittedAt: Date | null; +} + +// 프로젝트 타입에 따른 RFQ 페이지 URL 생성 함수 +function getRfqPageUrl(projectType: string | null, description: string | null): string { + const baseUrls = { + 'SHIP': '/evcp/budgetary-tech-sales-ship', + 'TOP': '/evcp/budgetary-tech-sales-top', + 'HULL': '/evcp/budgetary-tech-sales-hull' + }; + + const url = baseUrls[projectType as keyof typeof baseUrls] || '/evcp/budgetary-tech-sales-ship'; + + // description이 있으면 search 파라미터로 추가 + if (description) { + return `${url}?search=${encodeURIComponent(description)}`; + } + + return url; +} + +// 프로젝트 타입 표시 함수 +function getProjectTypeDisplay(projectType: string | null): string { + const typeMap = { + 'SHIP': '조선', + 'TOP': '해양TOP', + 'HULL': '해양HULL' + }; + + return typeMap[projectType as keyof typeof typeMap] || projectType || '-'; +} + +interface GetColumnsProps { + setRowAction: React.Dispatch | null>>; +} + +export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef[] { + // ---------------------------------------------------------------- + // 1) select 컬럼 (체크박스) + // ---------------------------------------------------------------- + const selectColumn: ColumnDef = { + id: "select", + header: ({ table }) => ( + table.toggleAllPageRowsSelected(!!value)} + aria-label="Select all" + className="translate-y-0.5" + /> + ), + cell: ({ row }) => ( + row.toggleSelected(!!value)} + aria-label="Select row" + className="translate-y-0.5" + /> + ), + size: 40, + enableSorting: false, + enableHiding: false, + } + + // ---------------------------------------------------------------- + // 2) actions 컬럼 (Dropdown 메뉴) + // ---------------------------------------------------------------- + const actionsColumn: ColumnDef = { + id: "actions", + enableHiding: false, + cell: function Cell({ row }) { + return ( + + + + + + setRowAction({ row, type: "update" })} + > + View Details + + + + ) + }, + size: 40, + } + + // ---------------------------------------------------------------- + // 3) 일반 컬럼들 + // ---------------------------------------------------------------- + const basicColumns: ColumnDef[] = techVendorRfqHistoryColumnsConfig.map((cfg) => { + const column: ColumnDef = { + accessorKey: cfg.id, + header: ({ column }) => ( + + ), + size: cfg.size, + } + + if (cfg.id === "rfqCode") { + column.cell = ({ row }) => { + const rfqCode = row.original.rfqCode + const projectType = row.original.projectType + if (!rfqCode) return null + + const rfqUrl = getRfqPageUrl(projectType, rfqCode); + + return ( + + + + {rfqCode} + + + +
+
{rfqCode}
+
+ 클릭하여 RFQ 페이지로 이동 +
+
+
+
+ ) + } + } + + if (cfg.id === "projectType") { + column.cell = ({ row }) => { + const projectType = row.original.projectType + return ( +
+ {getProjectTypeDisplay(projectType)} +
+ ) + } + } + + if (cfg.id === "status") { + column.cell = ({ row }) => { + const statusVal = row.original.status + if (!statusVal) return null + return ( +
+ {statusVal} +
+ ) + } + } + + if (cfg.id === "totalAmount") { + column.cell = ({ row }) => { + const amount = row.original.totalAmount + const currency = row.original.currency + if (!amount || !currency) return - + return ( +
+ {`${currency} ${Number(amount).toLocaleString()}`} +
+ ) + } + } + + if (cfg.id === "dueDate" || cfg.id === "createdAt") { + column.cell = ({ row }) => { + const dateValue = row.getValue(cfg.id) as Date + if (!dateValue) return - + return ( +
+ {formatDate(dateValue)} +
+ ) + } + } + + if (cfg.id === "projectCode" || cfg.id === "projectName") { + column.cell = ({ row }) => { + const value = row.getValue(cfg.id) as string | null + if (!value) return - + return value + } + column.size = 100; + } + + return column + }) + + // ---------------------------------------------------------------- + // 4) 최종 컬럼 배열 + // ---------------------------------------------------------------- + return [ + selectColumn, + ...basicColumns, + actionsColumn, + ] +} \ No newline at end of file diff --git a/lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table-toolbar-actions.tsx b/lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table-toolbar-actions.tsx new file mode 100644 index 00000000..e09cc17f --- /dev/null +++ b/lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table-toolbar-actions.tsx @@ -0,0 +1,52 @@ +"use client" + +import * as React from "react" +import { type Table } from "@tanstack/react-table" +import { Download } from "lucide-react" + +import { exportTableToExcel } from "@/lib/export" +import { Button } from "@/components/ui/button" + +interface TechVendorRfqHistoryRow { + id: number; + rfqCode: string | null; + description: string | null; + projectCode: string | null; + projectName: string | null; + status: string; + totalAmount: string | null; + currency: string | null; + dueDate: Date | null; + createdAt: Date; + quotationCode: string | null; + submittedAt: Date | null; +} + +interface TechVendorRfqHistoryTableToolbarActionsProps { + table: Table +} + +export function TechVendorRfqHistoryTableToolbarActions({ + table, +}: TechVendorRfqHistoryTableToolbarActionsProps) { + return ( +
+ + {/** Export 버튼 */} + +
+ ) +} \ No newline at end of file diff --git a/lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table.tsx b/lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table.tsx new file mode 100644 index 00000000..642c2d9c --- /dev/null +++ b/lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table.tsx @@ -0,0 +1,120 @@ +"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 { getColumns, type TechVendorRfqHistoryRow } from "./tech-vendor-rfq-history-table-columns" +import { getTechVendorRfqHistory } from "../service" +import { TechVendorRfqHistoryTableToolbarActions } from "./tech-vendor-rfq-history-table-toolbar-actions" +import { getRFQStatusIcon } from "@/lib/tasks/utils" +import { TooltipProvider } from "@/components/ui/tooltip" + +interface TechVendorRfqHistoryTableProps { + promises: Promise< + [ + Awaited>, + ] + > +} + +export function TechVendorRfqHistoryTable({ promises }: TechVendorRfqHistoryTableProps) { + const [{ data, pageCount }] = React.use(promises) + + const [rowAction, setRowAction] = React.useState | null>(null) + + // rowAction 처리 (향후 확장 가능) + React.useEffect(() => { + if (rowAction?.type === "update") { + // TODO: 상세보기 모달 등 구현 + console.log("View details for:", rowAction.row.original) + setRowAction(null) + } + }, [rowAction]) + + const columns = React.useMemo(() => getColumns({ + setRowAction, + }), [setRowAction]); + + const filterFields: DataTableFilterField[] = [ + { + id: "rfqCode", + label: "RFQ 코드", + placeholder: "RFQ 코드 검색...", + }, + { + id: "status", + label: "상태", + options: ["DRAFT", "PUBLISHED", "EVALUATION", "AWARDED"].map((status) => ({ + label: toSentenceCase(status), + value: status, + icon: getRFQStatusIcon(status as "DRAFT" | "PUBLISHED" | "EVALUATION" | "AWARDED"), + })), + }, + { + id: "projectCode", + label: "프로젝트 코드", + placeholder: "프로젝트 코드 검색...", + } + ] + + const advancedFilterFields: DataTableAdvancedFilterField[] = [ + { id: "rfqCode", label: "RFQ 코드", type: "text" }, + { id: "description", label: "RFQ 제목", type: "text" }, + { id: "projectCode", label: "프로젝트 코드", type: "text" }, + { id: "projectName", label: "프로젝트명", type: "text" }, + { + id: "status", + label: "상태", + type: "multi-select", + options: ["DRAFT", "PUBLISHED", "EVALUATION", "AWARDED"].map((status) => ({ + label: toSentenceCase(status), + value: status, + icon: getRFQStatusIcon(status as "DRAFT" | "PUBLISHED" | "EVALUATION" | "AWARDED"), + })), + }, + { id: "dueDate", label: "마감일", type: "date" }, + { 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: true, + clearOnDefault: true, + }) + + return ( + <> + + + + + + + + + ) +} \ No newline at end of file diff --git a/lib/tech-vendors/service.ts b/lib/tech-vendors/service.ts index da4a44eb..cb5aa89f 100644 --- a/lib/tech-vendors/service.ts +++ b/lib/tech-vendors/service.ts @@ -4,6 +4,7 @@ import { revalidateTag, unstable_noStore } from "next/cache"; import db from "@/db/db"; import { techVendorAttachments, techVendorContacts, techVendorPossibleItems, techVendors, techVendorItemsView, type TechVendor, techVendorCandidates } from "@/db/schema/techVendors"; import { items, itemShipbuilding, itemOffshoreTop, itemOffshoreHull } from "@/db/schema/items"; +import { users } from "@/db/schema/users"; import { filterColumns } from "@/lib/filter-columns"; import { unstable_cache } from "@/lib/unstable-cache"; @@ -32,12 +33,12 @@ import type { CreateTechVendorContactSchema, GetTechVendorItemsSchema, CreateTechVendorItemSchema, + GetTechVendorRfqHistorySchema, } from "./validations"; import { asc, desc, ilike, inArray, and, or, eq, isNull, not } from "drizzle-orm"; import path from "path"; import { sql } from "drizzle-orm"; -import { users } from "@/db/schema/users"; import { decryptWithServerAction } from "@/components/drm/drmUtils"; import { deleteFile, saveDRMFile } from "../file-stroage"; @@ -510,13 +511,16 @@ export async function createTechVendorContact(input: CreateTechVendorContactSche contactPosition: input.contactPosition || "", contactEmail: input.contactEmail, contactPhone: input.contactPhone || "", + country: input.country || "", isPrimary: input.isPrimary || false, }); + return newContact; }); // 캐시 무효화 revalidateTag(`tech-vendor-contacts-${input.vendorId}`); + revalidateTag("users"); return { data: null, error: null }; } catch (err) { @@ -1245,6 +1249,109 @@ export const findVendorById = async (id: number): Promise => } }; +/* ----------------------------------------------------- + 8) 기술영업 벤더 RFQ 히스토리 조회 +----------------------------------------------------- */ + +/** + * 기술영업 벤더의 RFQ 히스토리 조회 (간단한 버전) + */ +export async function getTechVendorRfqHistory(input: GetTechVendorRfqHistorySchema, id:number) { + try { + + // 먼저 해당 벤더의 견적서가 있는지 확인 + const { techSalesVendorQuotations } = await import("@/db/schema/techSales"); + + const quotationCheck = await db + .select({ count: sql`count(*)`.as("count") }) + .from(techSalesVendorQuotations) + .where(eq(techSalesVendorQuotations.vendorId, id)); + + console.log(`벤더 ${id}의 견적서 개수:`, quotationCheck[0]?.count); + + if (quotationCheck[0]?.count === 0) { + console.log("해당 벤더의 견적서가 없습니다."); + return { data: [], pageCount: 0 }; + } + + const offset = (input.page - 1) * input.perPage; + const { techSalesRfqs } = await import("@/db/schema/techSales"); + const { biddingProjects } = await import("@/db/schema/projects"); + + // 간단한 조회 + let whereCondition = eq(techSalesVendorQuotations.vendorId, id); + + // 검색이 있다면 추가 + if (input.search) { + const s = `%${input.search}%`; + const searchCondition = and( + whereCondition, + or( + ilike(techSalesRfqs.rfqCode, s), + ilike(techSalesRfqs.description, s), + ilike(biddingProjects.pspid, s), + ilike(biddingProjects.projNm, s) + ) + ); + whereCondition = searchCondition; + } + + // 데이터 조회 - 테이블에 필요한 필드들 (프로젝트 타입 추가) + const data = await db + .select({ + id: techSalesRfqs.id, + rfqCode: techSalesRfqs.rfqCode, + description: techSalesRfqs.description, + projectCode: biddingProjects.pspid, + projectName: biddingProjects.projNm, + projectType: biddingProjects.pjtType, // 프로젝트 타입 추가 + status: techSalesRfqs.status, + totalAmount: techSalesVendorQuotations.totalPrice, + currency: techSalesVendorQuotations.currency, + dueDate: techSalesRfqs.dueDate, + createdAt: techSalesRfqs.createdAt, + quotationCode: techSalesVendorQuotations.quotationCode, + submittedAt: techSalesVendorQuotations.submittedAt, + }) + .from(techSalesVendorQuotations) + .innerJoin(techSalesRfqs, eq(techSalesVendorQuotations.rfqId, techSalesRfqs.id)) + .leftJoin(biddingProjects, eq(techSalesRfqs.biddingProjectId, biddingProjects.id)) + .where(whereCondition) + .orderBy(desc(techSalesRfqs.createdAt)) + .limit(input.perPage) + .offset(offset); + + console.log("조회된 데이터:", data.length, "개"); + + // 전체 개수 조회 + const totalResult = await db + .select({ count: sql`count(*)`.as("count") }) + .from(techSalesVendorQuotations) + .innerJoin(techSalesRfqs, eq(techSalesVendorQuotations.rfqId, techSalesRfqs.id)) + .leftJoin(biddingProjects, eq(techSalesRfqs.biddingProjectId, biddingProjects.id)) + .where(whereCondition); + + const total = totalResult[0]?.count || 0; + const pageCount = Math.ceil(total / input.perPage); + + console.log("기술영업 벤더 RFQ 히스토리 조회 완료", { + id, + dataLength: data.length, + total, + pageCount + }); + + return { data, pageCount }; + } catch (err) { + console.error("기술영업 벤더 RFQ 히스토리 조회 오류:", { + err, + id, + stack: err instanceof Error ? err.stack : undefined + }); + return { data: [], pageCount: 0 }; + } +} + /** * 기술영업 벤더 엑셀 import 시 유저 생성 및 아이템 등록 */ @@ -1408,43 +1515,91 @@ export async function createTechVendorFromSignup(params: { try { console.log("기술영업 벤더 회원가입 시작:", params.vendorData.vendorName); + // 초대 토큰 검증 + let existingVendorId: number | null = null; + if (params.invitationToken) { + const { verifyTechVendorInvitationToken } = await import("@/lib/tech-vendor-invitation-token"); + const tokenPayload = await verifyTechVendorInvitationToken(params.invitationToken); + + if (!tokenPayload) { + throw new Error("유효하지 않은 초대 토큰입니다."); + } + + existingVendorId = tokenPayload.vendorId; + console.log("초대 토큰 검증 성공, 벤더 ID:", existingVendorId); + } + const result = await db.transaction(async (tx) => { - // 1. 이메일 중복 체크 - const existingVendor = await tx.query.techVendors.findFirst({ - where: eq(techVendors.email, params.vendorData.email), - columns: { id: true, vendorName: true } - }); + let vendorResult; + + if (existingVendorId) { + // 기존 벤더 정보 업데이트 + const [updatedVendor] = await tx.update(techVendors) + .set({ + vendorName: params.vendorData.vendorName, + vendorCode: params.vendorData.vendorCode || null, + taxId: params.vendorData.taxId, + country: params.vendorData.country, + address: params.vendorData.address || null, + phone: params.vendorData.phone || null, + email: params.vendorData.email, + website: params.vendorData.website || null, + techVendorType: params.vendorData.techVendorType, + status: "QUOTE_COMPARISON", // 가입 완료 시 QUOTE_COMPARISON으로 변경 + representativeName: params.vendorData.representativeName || null, + representativeEmail: params.vendorData.representativeEmail || null, + representativePhone: params.vendorData.representativePhone || null, + representativeBirth: params.vendorData.representativeBirth || null, + items: params.vendorData.items, + updatedAt: new Date(), + }) + .where(eq(techVendors.id, existingVendorId)) + .returning(); + + vendorResult = updatedVendor; + console.log("기존 벤더 정보 업데이트 완료:", vendorResult.id); + } else { + // 1. 이메일 중복 체크 (새 벤더인 경우) + const existingVendor = await tx.query.techVendors.findFirst({ + where: eq(techVendors.email, params.vendorData.email), + columns: { id: true, vendorName: true } + }); - if (existingVendor) { - throw new Error(`이미 등록된 이메일입니다: ${params.vendorData.email}`); - } + if (existingVendor) { + throw new Error(`이미 등록된 이메일입니다: ${params.vendorData.email}`); + } - // 2. 벤더 생성 - const [newVendor] = await tx.insert(techVendors).values({ - vendorName: params.vendorData.vendorName, - vendorCode: params.vendorData.vendorCode || null, - taxId: params.vendorData.taxId, - country: params.vendorData.country, - address: params.vendorData.address || null, - phone: params.vendorData.phone || null, - email: params.vendorData.email, - website: params.vendorData.website || null, - techVendorType: params.vendorData.techVendorType, - status: "ACTIVE", - representativeName: params.vendorData.representativeName || null, - representativeEmail: params.vendorData.representativeEmail || null, - representativePhone: params.vendorData.representativePhone || null, - representativeBirth: params.vendorData.representativeBirth || null, - items: params.vendorData.items, - }).returning(); + // 2. 새 벤더 생성 + const [newVendor] = await tx.insert(techVendors).values({ + vendorName: params.vendorData.vendorName, + vendorCode: params.vendorData.vendorCode || null, + taxId: params.vendorData.taxId, + country: params.vendorData.country, + address: params.vendorData.address || null, + phone: params.vendorData.phone || null, + email: params.vendorData.email, + website: params.vendorData.website || null, + techVendorType: params.vendorData.techVendorType, + status: "ACTIVE", + isQuoteComparison: false, + representativeName: params.vendorData.representativeName || null, + representativeEmail: params.vendorData.representativeEmail || null, + representativePhone: params.vendorData.representativePhone || null, + representativeBirth: params.vendorData.representativeBirth || null, + items: params.vendorData.items, + }).returning(); + + vendorResult = newVendor; + console.log("새 벤더 생성 완료:", vendorResult.id); + } - console.log("기술영업 벤더 생성 성공:", newVendor.id); + // 이 부분은 위에서 이미 처리되었으므로 주석 처리 // 3. 연락처 생성 if (params.contacts && params.contacts.length > 0) { for (const [index, contact] of params.contacts.entries()) { await tx.insert(techVendorContacts).values({ - vendorId: newVendor.id, + vendorId: vendorResult.id, contactName: contact.contactName, contactPosition: contact.contactPosition || null, contactEmail: contact.contactEmail, @@ -1457,7 +1612,7 @@ export async function createTechVendorFromSignup(params: { // 4. 첨부파일 처리 if (params.files && params.files.length > 0) { - await storeTechVendorFiles(tx, newVendor.id, params.files, "GENERAL"); + await storeTechVendorFiles(tx, vendorResult.id, params.files, "GENERAL"); console.log("첨부파일 저장 완료:", params.files.length, "개"); } @@ -1474,7 +1629,7 @@ export async function createTechVendorFromSignup(params: { const [newUser] = await tx.insert(users).values({ name: params.vendorData.vendorName, email: params.vendorData.email, - techCompanyId: newVendor.id, // 중요: techCompanyId 설정 + techCompanyId: vendorResult.id, // 중요: techCompanyId 설정 domain: "partners", }).returning(); userId = newUser.id; @@ -1483,7 +1638,7 @@ export async function createTechVendorFromSignup(params: { // 기존 유저의 techCompanyId 업데이트 if (!existingUser.techCompanyId) { await tx.update(users) - .set({ techCompanyId: newVendor.id }) + .set({ techCompanyId: vendorResult.id }) .where(eq(users.id, existingUser.id)); console.log("기존 유저의 techCompanyId 업데이트:", existingUser.id); } @@ -1494,13 +1649,13 @@ export async function createTechVendorFromSignup(params: { if (params.vendorData.email) { await tx.update(techVendorCandidates) .set({ - vendorId: newVendor.id, + vendorId: vendorResult.id, status: "INVITED" }) .where(eq(techVendorCandidates.contactEmail, params.vendorData.email)); } - return { vendor: newVendor, userId }; + return { vendor: vendorResult, userId }; }); // 캐시 무효화 @@ -1538,6 +1693,7 @@ export async function addTechVendor(input: { representativeEmail?: string | null; representativePhone?: string | null; representativeBirth?: string | null; + isQuoteComparison?: boolean; }) { unstable_noStore(); @@ -1565,7 +1721,7 @@ export async function addTechVendor(input: { const [newVendor] = await tx.insert(techVendors).values({ vendorName: input.vendorName, vendorCode: input.vendorCode || null, - taxId: input.taxId, + taxId: input.taxId || null, country: input.country || null, countryEng: input.countryEng || null, countryFab: input.countryFab || null, @@ -1577,7 +1733,8 @@ export async function addTechVendor(input: { email: input.email, website: input.website || null, techVendorType: Array.isArray(input.techVendorType) ? input.techVendorType.join(',') : input.techVendorType, - status: "ACTIVE", + status: input.isQuoteComparison ? "PENDING_INVITE" : "ACTIVE", + isQuoteComparison: input.isQuoteComparison || false, representativeName: input.representativeName || null, representativeEmail: input.representativeEmail || null, representativePhone: input.representativePhone || null, @@ -1586,7 +1743,11 @@ export async function addTechVendor(input: { console.log("벤더 생성 성공:", newVendor.id); - // 3. 유저 생성 (techCompanyId 설정) + // 3. 견적비교용 벤더인 경우 PENDING_REVIEW 상태로 생성됨 + // 초대는 별도의 초대 버튼을 통해 진행 + console.log("벤더 생성 완료:", newVendor.id, "상태:", newVendor.status); + + // 4. 유저 생성 (techCompanyId 설정) console.log("유저 생성 시도:", input.email); // 이미 존재하는 유저인지 확인 @@ -1650,3 +1811,80 @@ export async function getTechVendorPossibleItemsCount(vendorId: number): Promise } } +/** + * 기술영업 벤더 초대 메일 발송 + */ +export async function inviteTechVendor(params: { + vendorId: number; + subject: string; + message: string; + recipientEmail: string; +}) { + unstable_noStore(); + + try { + console.log("기술영업 벤더 초대 메일 발송 시작:", params.vendorId); + + const result = await db.transaction(async (tx) => { + // 벤더 정보 조회 + const vendor = await tx.query.techVendors.findFirst({ + where: eq(techVendors.id, params.vendorId), + }); + + if (!vendor) { + throw new Error("벤더를 찾을 수 없습니다."); + } + + // 벤더 상태를 INVITED로 변경 (PENDING_INVITE에서) + if (vendor.status !== "PENDING_INVITE") { + throw new Error("초대 가능한 상태가 아닙니다. (PENDING_INVITE 상태만 초대 가능)"); + } + + await tx.update(techVendors) + .set({ + status: "INVITED", + updatedAt: new Date(), + }) + .where(eq(techVendors.id, params.vendorId)); + + // 초대 토큰 생성 + const { createTechVendorInvitationToken, createTechVendorSignupUrl } = await import("@/lib/tech-vendor-invitation-token"); + const { sendEmail } = await import("@/lib/mail/sendEmail"); + + const invitationToken = await createTechVendorInvitationToken({ + vendorId: vendor.id, + vendorName: vendor.vendorName, + email: params.recipientEmail, + }); + + const signupUrl = await createTechVendorSignupUrl(invitationToken); + + // 초대 메일 발송 + await sendEmail({ + to: params.recipientEmail, + subject: params.subject, + template: "tech-vendor-invitation", + context: { + companyName: vendor.vendorName, + language: "ko", + registrationLink: signupUrl, + customMessage: params.message, + } + }); + + console.log("초대 메일 발송 완료:", params.recipientEmail); + + return { vendor, invitationToken, signupUrl }; + }); + + // 캐시 무효화 + revalidateTag("tech-vendors"); + + console.log("기술영업 벤더 초대 완료:", result); + return { success: true, data: result }; + } catch (error) { + console.error("기술영업 벤더 초대 실패:", error); + return { success: false, error: getErrorMessage(error) }; + } +} + diff --git a/lib/tech-vendors/table/add-vendor-dialog.tsx b/lib/tech-vendors/table/add-vendor-dialog.tsx index da9880d4..22c03bcc 100644 --- a/lib/tech-vendors/table/add-vendor-dialog.tsx +++ b/lib/tech-vendors/table/add-vendor-dialog.tsx @@ -51,6 +51,7 @@ const addVendorSchema = z.object({ representativeEmail: z.string().email("올바른 이메일 주소를 입력해주세요").optional().or(z.literal("")), representativePhone: z.string().optional(), representativeBirth: z.string().optional(), + isQuoteComparison: z.boolean().default(false), }) type AddVendorFormData = z.infer @@ -84,6 +85,7 @@ export function AddVendorDialog({ onSuccess }: AddVendorDialogProps) { representativeEmail: "", representativePhone: "", representativeBirth: "", + isQuoteComparison: false, }, }) @@ -108,6 +110,7 @@ export function AddVendorDialog({ onSuccess }: AddVendorDialogProps) { representativePhone: data.representativePhone || null, representativeBirth: data.representativeBirth || null, taxId: data.taxId || "", + isQuoteComparison: data.isQuoteComparison, }) if (result.success) { @@ -238,6 +241,31 @@ export function AddVendorDialog({ onSuccess }: AddVendorDialogProps) { )} /> + + ( + + + + +
+ + 견적비교용 벤더 + +

+ 체크 시 초대 메일을 발송하고 벤더가 직접 가입할 수 있습니다. +

+
+
+ )} + /> {/* 연락처 정보 */} @@ -333,52 +361,6 @@ export function AddVendorDialog({ onSuccess }: AddVendorDialogProps) { - {/* 담당자 정보 */} -
-

담당자 정보

-
- ( - - 담당자명 - - - - - - )} - /> - ( - - 담당자 전화번호 - - - - - - )} - /> -
- ( - - 담당자 이메일 - - - - - - )} - /> -
- {/* 대표자 정보 */}

대표자 정보

diff --git a/lib/tech-vendors/table/invite-tech-vendor-dialog.tsx b/lib/tech-vendors/table/invite-tech-vendor-dialog.tsx new file mode 100644 index 00000000..823b2f4d --- /dev/null +++ b/lib/tech-vendors/table/invite-tech-vendor-dialog.tsx @@ -0,0 +1,184 @@ +"use client" + +import * as React from "react" +import { Button } from "@/components/ui/button" +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@/components/ui/dialog" +import { Badge } from "@/components/ui/badge" +import { Mail, Send, Loader2, UserCheck } from "lucide-react" +import { toast } from "sonner" +import { TechVendor } from "@/db/schema/techVendors" +import { inviteTechVendor } from "../service" + +// 더 이상 폼 스키마 불필요 + +interface InviteTechVendorDialogProps { + vendors: TechVendor[] + open?: boolean + onOpenChange?: (open: boolean) => void + showTrigger?: boolean + onSuccess?: () => void +} + +export function InviteTechVendorDialog({ + vendors, + open, + onOpenChange, + showTrigger = true, + onSuccess, +}: InviteTechVendorDialogProps) { + const [isLoading, setIsLoading] = React.useState(false) + + const onSubmit = async () => { + if (vendors.length === 0) { + toast.error("초대할 벤더를 선택해주세요.") + return + } + + setIsLoading(true) + try { + let successCount = 0 + let errorCount = 0 + + for (const vendor of vendors) { + try { + const result = await inviteTechVendor({ + vendorId: vendor.id, + subject: "기술영업 협력업체 등록 초대", + message: `안녕하세요. + +저희 EVCP 플랫폼에서 기술영업 협력업체로 등록하여 다양한 프로젝트에 참여하실 수 있는 기회를 제공하고 있습니다. + +아래 링크를 통해 업체 정보를 등록하시기 바랍니다. + +감사합니다.`, + recipientEmail: vendor.email || "", + }) + + if (result.success) { + successCount++ + } else { + errorCount++ + console.error(`벤더 ${vendor.vendorName} 초대 실패:`, result.error) + } + } catch (error) { + errorCount++ + console.error(`벤더 ${vendor.vendorName} 초대 실패:`, error) + } + } + + if (successCount > 0) { + toast.success(`${successCount}개 업체에 초대 메일이 성공적으로 발송되었습니다.`) + onOpenChange?.(false) + onSuccess?.() + } + + if (errorCount > 0) { + toast.error(`${errorCount}개 업체 초대 메일 발송에 실패했습니다.`) + } + } catch (error) { + console.error("초대 메일 발송 실패:", error) + toast.error("초대 메일 발송 중 오류가 발생했습니다.") + } finally { + setIsLoading(false) + } + } + + const getStatusBadge = (status: string) => { + const statusConfig = { + ACTIVE: { variant: "default" as const, text: "활성 상태", className: "bg-emerald-100 text-emerald-800" }, + INACTIVE: { variant: "secondary" as const, text: "비활성 상태", className: "bg-gray-100 text-gray-800" }, + PENDING_INVITE: { variant: "outline" as const, text: "초대 대기", className: "bg-blue-100 text-blue-800" }, + INVITED: { variant: "outline" as const, text: "초대 완료", className: "bg-green-100 text-green-800" }, + QUOTE_COMPARISON: { variant: "outline" as const, text: "견적 비교", className: "bg-purple-100 text-purple-800" }, + BLACKLISTED: { variant: "destructive" as const, text: "거래 금지", className: "bg-red-100 text-red-800" }, + } + + const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.INACTIVE + return {config.text} + } + + if (vendors.length === 0) { + return null + } + + return ( + + {showTrigger && ( + + + + )} + + + + + 기술영업 벤더 초대 + + + 선택한 {vendors.length}개 벤더에게 등록 초대 메일을 발송합니다. + + + +
+ {/* 벤더 정보 */} +
+

초대 대상 벤더 ({vendors.length}개)

+
+ {vendors.map((vendor) => ( +
+
+
{vendor.vendorName}
+
+ {vendor.email || "이메일 없음"} +
+
+
+ {getStatusBadge(vendor.status)} +
+
+ ))} +
+
+ + {/* 초대 확인 */} +
+ +
+ + +
+
+
+
+
+ ) +} \ No newline at end of file diff --git a/lib/tech-vendors/table/tech-vendors-table-columns.tsx b/lib/tech-vendors/table/tech-vendors-table-columns.tsx index 69396c99..052794ce 100644 --- a/lib/tech-vendors/table/tech-vendors-table-columns.tsx +++ b/lib/tech-vendors/table/tech-vendors-table-columns.tsx @@ -225,6 +225,25 @@ export function getColumns({ setRowAction, router, openItemsDialog }: GetColumns className: "bg-gray-100 text-gray-800 border-gray-300", iconColor: "text-gray-600" }; + + case "PENDING_INVITE": + return { + variant: "default", + className: "bg-blue-100 text-blue-800 border-blue-300", + iconColor: "text-blue-600" + }; + case "INVITED": + return { + variant: "default", + className: "bg-green-100 text-green-800 border-green-300", + iconColor: "text-green-600" + }; + case "QUOTE_COMPARISON": + return { + variant: "default", + className: "bg-purple-100 text-purple-800 border-purple-300", + iconColor: "text-purple-600" + }; case "BLACKLISTED": return { variant: "destructive", @@ -246,7 +265,9 @@ export function getColumns({ setRowAction, router, openItemsDialog }: GetColumns "ACTIVE": "활성 상태", "INACTIVE": "비활성 상태", "BLACKLISTED": "거래 금지", - "PENDING_REVIEW": "비교 견적" + "PENDING_INVITE": "초대 대기", + "INVITED": "초대 완료", + "QUOTE_COMPARISON": "견적 비교" }; return statusMap[status] || status; @@ -269,56 +290,58 @@ export function getColumns({ setRowAction, router, openItemsDialog }: GetColumns ); } // TechVendorType 컬럼을 badge로 표시 - // if (cfg.id === "techVendorType") { - // const techVendorType = row.original.techVendorType as string; + if (cfg.id === "techVendorType") { + const techVendorType = row.original.techVendorType as string | null | undefined; - // // 벤더 타입 파싱 개선 - // let types: string[] = []; - // if (!techVendorType) { - // types = []; - // } else if (techVendorType.startsWith('[') && techVendorType.endsWith(']')) { - // // JSON 배열 형태 - // try { - // const parsed = JSON.parse(techVendorType); - // types = Array.isArray(parsed) ? parsed.filter(Boolean) : [techVendorType]; - // } catch { - // types = [techVendorType]; - // } - // } else if (techVendorType.includes(',')) { - // // 콤마로 구분된 문자열 - // types = techVendorType.split(',').map(t => t.trim()).filter(Boolean); - // } else { - // // 단일 문자열 - // types = [techVendorType.trim()].filter(Boolean); - // } - // // 벤더 타입 정렬 - 조선 > 해양top > 해양hull 순 - // const typeOrder = ["조선", "해양top", "해양hull"]; - // types.sort((a, b) => { - // const indexA = typeOrder.indexOf(a); - // const indexB = typeOrder.indexOf(b); - - // // 정의된 순서에 있는 경우 우선순위 적용 - // if (indexA !== -1 && indexB !== -1) { - // return indexA - indexB; - // } - // return a.localeCompare(b); - // }); - // return ( - //
- // {types.length > 0 ? types.map((type, index) => ( - // - // {type} - // - // )) : ( - // - - // )} - //
- // ); - // } + // 벤더 타입 파싱 개선 - null/undefined 안전 처리 + let types: string[] = []; + if (!techVendorType) { + types = []; + } else if (techVendorType.startsWith('[') && techVendorType.endsWith(']')) { + // JSON 배열 형태 + try { + const parsed = JSON.parse(techVendorType); + types = Array.isArray(parsed) ? parsed.filter(Boolean) : [techVendorType]; + } catch { + types = [techVendorType]; + } + } else if (techVendorType.includes(',')) { + // 콤마로 구분된 문자열 + types = techVendorType.split(',').map(t => t.trim()).filter(Boolean); + } else { + // 단일 문자열 + types = [techVendorType.trim()].filter(Boolean); + } + + // 벤더 타입 정렬 - 조선 > 해양top > 해양hull 순 + const typeOrder = ["조선", "해양top", "해양hull"]; + types.sort((a, b) => { + const indexA = typeOrder.indexOf(a); + const indexB = typeOrder.indexOf(b); + + // 정의된 순서에 있는 경우 우선순위 적용 + if (indexA !== -1 && indexB !== -1) { + return indexA - indexB; + } + return a.localeCompare(b); + }); + + return ( +
+ {types.length > 0 ? types.map((type, index) => ( + + {type} + + )) : ( + - + )} +
+ ); + } // 날짜 컬럼 포맷팅 if (cfg.type === "date" && cell.getValue()) { - return formatDate(cell.getValue() as Date, "KR"); + return formatDate(cell.getValue() as Date); } return cell.getValue(); diff --git a/lib/tech-vendors/table/tech-vendors-table-toolbar-actions.tsx b/lib/tech-vendors/table/tech-vendors-table-toolbar-actions.tsx index 06b2cc42..ac7ee184 100644 --- a/lib/tech-vendors/table/tech-vendors-table-toolbar-actions.tsx +++ b/lib/tech-vendors/table/tech-vendors-table-toolbar-actions.tsx @@ -20,6 +20,7 @@ import { TechVendor } from "@/db/schema/techVendors" import { ImportTechVendorButton } from "./import-button" import { exportTechVendorTemplate } from "./excel-template-download" import { AddVendorDialog } from "./add-vendor-dialog" +import { InviteTechVendorDialog } from "./invite-tech-vendor-dialog" interface TechVendorsTableToolbarActionsProps { table: Table @@ -36,6 +37,13 @@ export function TechVendorsTableToolbarActions({ table, onRefresh }: TechVendors .rows .map(row => row.original); }, [table.getFilteredSelectedRowModel().rows]); + + // 초대 가능한 벤더들 (PENDING_INVITE 상태 + 이메일 있음) + const invitableVendors = React.useMemo(() => { + return selectedVendors.filter(vendor => + vendor.status === "PENDING_INVITE" && vendor.email + ); + }, [selectedVendors]); // 테이블의 모든 벤더 가져오기 (필터링된 결과) const allFilteredVendors = React.useMemo(() => { @@ -97,6 +105,14 @@ export function TechVendorsTableToolbarActions({ table, onRefresh }: TechVendors return (
+ {/* 초대 버튼 - 선택된 PENDING_REVIEW 벤더들이 있을 때만 표시 */} + {invitableVendors.length > 0 && ( + + )} + {/* 벤더 추가 다이얼로그 추가 */} diff --git a/lib/tech-vendors/table/tech-vendors-table.tsx b/lib/tech-vendors/table/tech-vendors-table.tsx index 125e39dc..a8e18501 100644 --- a/lib/tech-vendors/table/tech-vendors-table.tsx +++ b/lib/tech-vendors/table/tech-vendors-table.tsx @@ -59,7 +59,9 @@ export function TechVendorsTable({ promises }: TechVendorsTableProps) { "ACTIVE": "활성 상태", "INACTIVE": "비활성 상태", "BLACKLISTED": "거래 금지", - "PENDING_REVIEW": "비교 견적", + "PENDING_INVITE": "초대 대기", + "INVITED": "초대 완료", + "QUOTE_COMPARISON": "견적 비교", }; return statusMap[status] || status; @@ -187,6 +189,7 @@ export function TechVendorsTable({ promises }: TechVendorsTableProps) { onOpenChange={setItemsDialogOpen} vendor={selectedVendorForItems} /> + ) } \ No newline at end of file diff --git a/lib/tech-vendors/utils.ts b/lib/tech-vendors/utils.ts index 693a6929..e409975a 100644 --- a/lib/tech-vendors/utils.ts +++ b/lib/tech-vendors/utils.ts @@ -1,4 +1,4 @@ -import { LucideIcon, Hourglass, CheckCircle2, XCircle, CircleAlert, Clock, ShieldAlert } from "lucide-react"; +import { LucideIcon, CheckCircle2, CircleAlert, Clock, ShieldAlert, Mail, BarChart2 } from "lucide-react"; import type { TechVendor } from "@/db/schema/techVendors"; type StatusType = TechVendor["status"]; @@ -8,8 +8,12 @@ type StatusType = TechVendor["status"]; */ export function getVendorStatusIcon(status: StatusType): LucideIcon { switch (status) { - case "PENDING_REVIEW": - return Hourglass; + case "PENDING_INVITE": + return Clock; + case "INVITED": + return Mail; + case "QUOTE_COMPARISON": + return BarChart2; case "ACTIVE": return CheckCircle2; case "INACTIVE": diff --git a/lib/tech-vendors/validations.ts b/lib/tech-vendors/validations.ts index fa0d9ae3..0c850c1f 100644 --- a/lib/tech-vendors/validations.ts +++ b/lib/tech-vendors/validations.ts @@ -168,7 +168,7 @@ export const createTechVendorSchema = z .min(1, "국가 선택은 필수입니다.") .max(100, "Max length 100"), phone: z.string().max(50, "Max length 50").optional(), - website: z.string().url("유효하지 않은 URL입니다. https:// 혹은 http:// 로 시작하는 주소를 입력해주세요.").max(255).optional(), + website: z.string().max(255).optional(), files: z.any().optional(), status: z.enum(techVendors.status.enumValues).default("ACTIVE"), @@ -233,6 +233,7 @@ export const createTechVendorContactSchema = z.object({ contactPosition: z.string().max(100, "Max length 100"), contactEmail: z.string().email(), contactPhone: z.string().max(50, "Max length 50").optional(), + country: z.string().max(100, "Max length 100").optional(), isPrimary: z.boolean(), }); @@ -244,6 +245,7 @@ export const updateTechVendorContactSchema = z.object({ contactPosition: z.string().max(100, "Max length 100").optional(), contactEmail: z.string().email().optional(), contactPhone: z.string().max(50, "Max length 50").optional(), + country: z.string().max(100, "Max length 100").optional(), isPrimary: z.boolean().optional(), }); @@ -260,10 +262,56 @@ export const updateTechVendorItemSchema = z.object({ itemCode: z.string().max(100, "Max length 100"), }); +export const searchParamsRfqHistoryCache = createSearchParamsCache({ + // 공통 플래그 + flags: parseAsArrayOf(z.enum(["advancedTable", "floatingBar"])).withDefault( + [] + ), + + // 페이징 + page: parseAsInteger.withDefault(1), + perPage: parseAsInteger.withDefault(10), + + // 정렬 (RFQ 히스토리에 맞춰) + sort: getSortingStateParser<{ + id: number; + rfqCode: string | null; + description: string | null; + projectCode: string | null; + projectName: string | null; + projectType: string | null; // 프로젝트 타입 추가 + status: string; + totalAmount: string | null; + currency: string | null; + dueDate: Date | null; + createdAt: Date; + quotationCode: string | null; + submittedAt: Date | null; + }>().withDefault([ + { id: "createdAt", desc: true }, + ]), + + // 고급 필터 + filters: getFiltersStateParser().withDefault([]), + joinOperator: parseAsStringEnum(["and", "or"]).withDefault("and"), + + // 검색 키워드 + search: parseAsString.withDefault(""), + + // RFQ 히스토리 특화 필드 + rfqCode: parseAsString.withDefault(""), + description: parseAsString.withDefault(""), + projectCode: parseAsString.withDefault(""), + projectName: parseAsString.withDefault(""), + projectType: parseAsStringEnum(["SHIP", "TOP", "HULL"]), // 프로젝트 타입 필터 추가 + status: parseAsStringEnum(["DRAFT", "PUBLISHED", "EVALUATION", "AWARDED"]), +}); + // 타입 내보내기 export type GetTechVendorsSchema = Awaited> export type GetTechVendorContactsSchema = Awaited> export type GetTechVendorItemsSchema = Awaited> +export type GetTechVendorRfqHistorySchema = Awaited> export type UpdateTechVendorSchema = z.infer export type CreateTechVendorSchema = z.infer -- cgit v1.2.3