From 37f55540833c2d5894513eca9fc8f7c6233fc2d2 Mon Sep 17 00:00:00 2001 From: dujinkim Date: Thu, 29 May 2025 05:17:13 +0000 Subject: (대표님) 0529 14시 16분 변경사항 저장 (Vendor Data, Docu) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/forms/services.ts | 140 +++--- lib/items/service.ts | 201 +++++++-- lib/items/table/items-table.tsx | 161 +++++-- lib/items/validations.ts | 6 +- lib/rfqs-tech/table/rfqs-table-columns.tsx | 2 +- lib/sedp/sync-object-class.ts | 248 ++++++++++- lib/tbe-tech/table/tbe-table-columns.tsx | 2 +- lib/tbe-tech/table/tbe-table.tsx | 7 +- lib/tech-vendor-rfq-response/service.ts | 467 +++++++++++++++++++++ lib/tech-vendor-rfq-response/types.ts | 76 ++++ .../vendor-cbe-table/cbe-table-columns.tsx | 365 ++++++++++++++++ .../vendor-cbe-table/cbe-table.tsx | 272 ++++++++++++ .../vendor-cbe-table/comments-sheet.tsx | 323 ++++++++++++++ .../vendor-cbe-table/respond-cbe-sheet.tsx | 427 +++++++++++++++++++ .../vendor-cbe-table/rfq-detail-dialog.tsx | 79 ++++ .../rfq-items-table/rfq-items-table-column.tsx | 62 +++ .../rfq-items-table/rfq-items-table.tsx | 86 ++++ .../vendor-rfq-table/ItemsDialog.tsx | 127 ++++++ .../vendor-rfq-table/attachment-rfq-sheet.tsx | 106 +++++ .../vendor-rfq-table/comments-sheet.tsx | 320 ++++++++++++++ .../vendor-rfq-table/feature-flags-provider.tsx | 108 +++++ .../vendor-rfq-table/rfqs-table-columns.tsx | 424 +++++++++++++++++++ .../rfqs-table-toolbar-actions.tsx | 40 ++ .../vendor-rfq-table/rfqs-table.tsx | 280 ++++++++++++ .../vendor-tbe-table/comments-sheet.tsx | 348 +++++++++++++++ .../vendor-tbe-table/rfq-detail-dialog.tsx | 75 ++++ .../vendor-tbe-table/tbe-table-columns.tsx | 350 +++++++++++++++ .../vendor-tbe-table/tbe-table.tsx | 191 +++++++++ .../vendor-tbe-table/tbeFileHandler.tsx | 354 ++++++++++++++++ 29 files changed, 5496 insertions(+), 151 deletions(-) create mode 100644 lib/tech-vendor-rfq-response/service.ts create mode 100644 lib/tech-vendor-rfq-response/types.ts create mode 100644 lib/tech-vendor-rfq-response/vendor-cbe-table/cbe-table-columns.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-cbe-table/cbe-table.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-cbe-table/comments-sheet.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-cbe-table/respond-cbe-sheet.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-cbe-table/rfq-detail-dialog.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-cbe-table/rfq-items-table/rfq-items-table-column.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-cbe-table/rfq-items-table/rfq-items-table.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-rfq-table/ItemsDialog.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-rfq-table/attachment-rfq-sheet.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-rfq-table/comments-sheet.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-rfq-table/feature-flags-provider.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-rfq-table/rfqs-table-columns.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-rfq-table/rfqs-table-toolbar-actions.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-rfq-table/rfqs-table.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-tbe-table/comments-sheet.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-tbe-table/rfq-detail-dialog.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-tbe-table/tbe-table-columns.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-tbe-table/tbe-table.tsx create mode 100644 lib/tech-vendor-rfq-response/vendor-tbe-table/tbeFileHandler.tsx (limited to 'lib') diff --git a/lib/forms/services.ts b/lib/forms/services.ts index 8f40162c..0fbe68a6 100644 --- a/lib/forms/services.ts +++ b/lib/forms/services.ts @@ -10,6 +10,7 @@ import { formEntries, formMetas, forms, + tagClassAttributes, tagClasses, tags, tagSubfieldOptions, @@ -154,23 +155,85 @@ export async function revalidateForms(contractItemId: number) { } } +export interface EditableFieldsInfo { + tagNo: string; + editableFields: string[]; // 편집 가능한 필드 키 목록 +} + +// TAG별 편집 가능 필드 조회 함수 +async function getEditableFieldsByTag( + contractItemId: number, + projectId: number +): Promise> { + try { + // 1. 해당 contractItemId의 모든 태그 조회 + const tagList = await db + .select({ + tagNo: tags.tagNo, + tagClass: tags.class + }) + .from(tags) + .where(eq(tags.contractItemId, contractItemId)); + + const editableFieldsMap = new Map(); + + // 2. 각 태그별로 편집 가능 필드 계산 + for (const tag of tagList) { + try { + // 2-1. tagClasses에서 해당 class(label)와 projectId로 tagClass 찾기 + const tagClassResult = await db + .select({ id: tagClasses.id }) + .from(tagClasses) + .where( + and( + eq(tagClasses.label, tag.tagClass), + eq(tagClasses.projectId, projectId) + ) + ) + .limit(1); + + if (tagClassResult.length === 0) { + console.warn(`No tagClass found for class: ${tag.tagClass}, projectId: ${projectId}`); + editableFieldsMap.set(tag.tagNo, []); // 편집 불가능 + continue; + } + + // 2-2. tagClassAttributes에서 편집 가능한 필드 목록 조회 + const editableAttributes = await db + .select({ attId: tagClassAttributes.attId }) + .from(tagClassAttributes) + .where(eq(tagClassAttributes.tagClassId, tagClassResult[0].id)) + .orderBy(tagClassAttributes.seq); + + // 2-3. attId 목록 저장 + const editableFields = editableAttributes.map(attr => attr.attId); + editableFieldsMap.set(tag.tagNo, editableFields); + + } catch (error) { + console.error(`Error processing tag ${tag.tagNo}:`, error); + editableFieldsMap.set(tag.tagNo, []); // 에러 시 편집 불가능 + } + } + + return editableFieldsMap; + } catch (error) { + console.error('Error getting editable fields by tag:', error); + return new Map(); + } +} /** * "가장 최신 1개 row"를 가져오고, * data가 배열이면 그 배열을 반환, * 그리고 이 로직 전체를 unstable_cache로 감싸 캐싱. */ export async function getFormData(formCode: string, contractItemId: number) { - // 고유 캐시 키 (formCode + contractItemId) const cacheKey = `form-data-${formCode}-${contractItemId}`; console.log(cacheKey, "getFormData") try { - // 1) unstable_cache로 전체 로직을 감싼다 const result = await unstable_cache( async () => { - // --- 기존 로직 시작 (projectId 고려하도록 수정) --- - - // (0) contractItemId로부터 projectId 조회 + // 기존 로직으로 projectId, columns, data 가져오기 const contractItemResult = await db .select({ projectId: projects.id @@ -183,12 +246,11 @@ export async function getFormData(formCode: string, contractItemId: number) { if (contractItemResult.length === 0) { console.warn(`[getFormData] No contract item found with ID: ${contractItemId}`); - return { columns: null, data: [] }; + return { columns: null, data: [], editableFieldsMap: new Map() }; } const projectId = contractItemResult[0].projectId; - // (1) form_metas 조회 - 이제 projectId도 조건에 포함 const metaRows = await db .select() .from(formMetas) @@ -204,10 +266,9 @@ export async function getFormData(formCode: string, contractItemId: number) { const meta = metaRows[0] ?? null; if (!meta) { console.warn(`[getFormData] No form meta found for formCode: ${formCode} and projectId: ${projectId}`); - return { columns: null, data: [] }; + return { columns: null, data: [], editableFieldsMap: new Map() }; } - // (2) form_entries에서 (formCode, contractItemId)에 해당하는 "가장 최신" 한 행 const entryRows = await db .select() .from(formEntries) @@ -222,19 +283,11 @@ export async function getFormData(formCode: string, contractItemId: number) { const entry = entryRows[0] ?? null; - // columns: DB에 저장된 JSON (DataTableColumnJSON[]) let columns = meta.columns as DataTableColumnJSON[]; - - // 제외할 key들 정의 const excludeKeys = ['CLS_ID', 'BF_TAG_NO', 'TAG_TYPE_ID', 'PIC_NO']; - - // 제외할 key들을 가진 컬럼들을 필터링해서 제거 columns = columns.filter(col => !excludeKeys.includes(col.key)); columns.forEach((col) => { - // 이미 displayLabel이 있으면 그대로 두고, - // 없으면 uom이 있으면 "label (uom)" 형태, - // 둘 다 없으면 label만 쓴다. if (!col.displayLabel) { if (col.uom) { col.displayLabel = `${col.label} (${col.uom})`; @@ -244,39 +297,35 @@ export async function getFormData(formCode: string, contractItemId: number) { } }); - // data: 만약 entry가 없거나, data가 아닌 형태면 빈 배열 let data: Array> = []; if (entry) { if (Array.isArray(entry.data)) { data = entry.data; } else { - console.warn( - "formEntries data was not an array. Using empty array." - ); + console.warn("formEntries data was not an array. Using empty array."); } } - return { columns, data, projectId }; // projectId도 반환 (필요시) - // --- 기존 로직 끝 --- + // *** 새로 추가: 편집 가능 필드 정보 계산 *** + const editableFieldsMap = await getEditableFieldsByTag(contractItemId, projectId); + + return { columns, data, editableFieldsMap }; }, - [cacheKey], // 캐시 키 의존성 + [cacheKey], { - revalidate: 60, // 1분 캐시 - tags: [cacheKey], // 캐시 태그 + revalidate: 60, + tags: [cacheKey], } )(); return result; } catch (cacheError) { console.error(`[getFormData] Cache operation failed:`, cacheError); - - // --- fallback: 캐시 문제 시 직접 쿼리 시도 --- + + // Fallback logic (기존과 동일하게 editableFieldsMap 추가) try { - console.log( - `[getFormData] Fallback DB query for (${formCode}, ${contractItemId})` - ); + console.log(`[getFormData] Fallback DB query for (${formCode}, ${contractItemId})`); - // (0) contractItemId로부터 projectId 조회 const contractItemResult = await db .select({ projectId: projects.id @@ -289,12 +338,11 @@ export async function getFormData(formCode: string, contractItemId: number) { if (contractItemResult.length === 0) { console.warn(`[getFormData] Fallback: No contract item found with ID: ${contractItemId}`); - return { columns: null, data: [] }; + return { columns: null, data: [], editableFieldsMap: new Map() }; } const projectId = contractItemResult[0].projectId; - // (1) form_metas - projectId 고려 const metaRows = await db .select() .from(formMetas) @@ -310,10 +358,9 @@ export async function getFormData(formCode: string, contractItemId: number) { const meta = metaRows[0] ?? null; if (!meta) { console.warn(`[getFormData] Fallback: No form meta found for formCode: ${formCode} and projectId: ${projectId}`); - return { columns: null, data: [] }; + return { columns: null, data: [], editableFieldsMap: new Map() }; } - // (2) form_entries const entryRows = await db .select() .from(formEntries) @@ -329,17 +376,10 @@ export async function getFormData(formCode: string, contractItemId: number) { const entry = entryRows[0] ?? null; let columns = meta.columns as DataTableColumnJSON[]; - - // 제외할 key들 정의 const excludeKeys = ['CLS_ID', 'BF_TAG_NO', 'TAG_TYPE_ID', 'PIC_NO']; - - // 제외할 key들을 가진 컬럼들을 필터링해서 제거 columns = columns.filter(col => !excludeKeys.includes(col.key)); columns.forEach((col) => { - // 이미 displayLabel이 있으면 그대로 두고, - // 없으면 uom이 있으면 "label (uom)" 형태, - // 둘 다 없으면 label만 쓴다. if (!col.displayLabel) { if (col.uom) { col.displayLabel = `${col.label} (${col.uom})`; @@ -354,21 +394,21 @@ export async function getFormData(formCode: string, contractItemId: number) { if (Array.isArray(entry.data)) { data = entry.data; } else { - console.warn( - "formEntries data was not an array. Using empty array (fallback)." - ); + console.warn("formEntries data was not an array. Using empty array (fallback)."); } } - return { columns, data, projectId }; // projectId도 반환 (필요시) + // Fallback에서도 편집 가능 필드 정보 계산 + const editableFieldsMap = await getEditableFieldsByTag(contractItemId, projectId); + + return { columns, data, projectId, editableFieldsMap }; } catch (dbError) { console.error(`[getFormData] Fallback DB query failed:`, dbError); - return { columns: null, data: [] }; + return { columns: null, data: [], editableFieldsMap: new Map() }; } } } - -/** +/**1 * contractId와 formCode(itemCode)를 사용하여 contractItemId를 찾는 서버 액션 * * @param contractId - 계약 ID diff --git a/lib/items/service.ts b/lib/items/service.ts index 99ef79ef..35d2fa01 100644 --- a/lib/items/service.ts +++ b/lib/items/service.ts @@ -25,29 +25,105 @@ import { countItems, deleteItemById, deleteItemsByIds, findAllItems, insertItem, * Next.js의 unstable_cache를 사용해 일정 시간 캐시. */ export async function getItems(input: GetItemsSchema) { - + const safePerPage = Math.min(input.perPage, 100); + return unstable_cache( async () => { try { - const offset = (input.page - 1) * input.perPage; + const offset = (input.page - 1) * safePerPage; + + const advancedWhere = filterColumns({ + table: items, + filters: input.filters, + joinOperator: input.joinOperator, + }); + + let globalWhere; + if (input.search) { + const s = `%${input.search}%`; + globalWhere = or( + ilike(items.itemLevel, s), + ilike(items.itemCode, s), + ilike(items.itemName, s), + ilike(items.description, s), + ilike(items.parentItemCode, s), + ilike(items.unitOfMeasure, s), + ilike(items.steelType, s), + ilike(items.gradeMaterial, s), + ilike(items.baseUnitOfMeasure, s), + ilike(items.changeDate, s) + ); + } + + const finalWhere = and(advancedWhere, globalWhere); + + const orderBy = input.sort.length > 0 + ? input.sort.map((item) => + item.desc ? desc(items[item.id]) : asc(items[item.id]) + ) + : [asc(items.createdAt)]; + + const { data, total } = await db.transaction(async (tx) => { + const data = await selectItems(tx, { + where: finalWhere, + orderBy, + offset, + limit: safePerPage, + }); + + const total = await countItems(tx, finalWhere); + return { data, total }; + }); + + const pageCount = Math.ceil(total / safePerPage); + return { data, pageCount }; + } catch (err) { + console.error(err); + return { data: [], pageCount: 0 }; + } + }, + [JSON.stringify({...input, perPage: safePerPage})], + { + revalidate: 3600, + tags: ["items"], + } + )(); +} + +export interface GetItemsInfiniteInput extends Omit { + cursor?: string; + limit?: number; +} + +// 무한 스크롤 결과 타입 +export interface GetItemsInfiniteResult { + data: any[]; + hasNextPage: boolean; + nextCursor: string | null; + total?: number | null; +} - // const advancedTable = input.flags.includes("advancedTable"); - const advancedTable = true; +export async function getItemsInfinite(input: GetItemsInfiniteInput): Promise { + return unstable_cache( + async () => { + try { + // 페이지 크기 제한 (기존과 동일한 방식) + const safeLimit = Math.min(input.limit || 50, 100); - // advancedTable 모드면 filterColumns()로 where 절 구성 + // 고급 필터링 (기존과 완전 동일) const advancedWhere = filterColumns({ table: items, filters: input.filters, joinOperator: input.joinOperator, }); - - let globalWhere + // 전역 검색 (기존과 완전 동일) + let globalWhere; if (input.search) { - const s = `%${input.search}%` + const s = `%${input.search}%`; globalWhere = or( ilike(items.itemLevel, s), - ilike(items.itemCode, s), + ilike(items.itemCode, s), ilike(items.itemName, s), ilike(items.description, s), ilike(items.parentItemCode, s), @@ -56,58 +132,107 @@ export async function getItems(input: GetItemsSchema) { ilike(items.gradeMaterial, s), ilike(items.baseUnitOfMeasure, s), ilike(items.changeDate, s) - ) - // 필요시 여러 칼럼 OR조건 (status, priority, etc) + ); } - const finalWhere = and( - // advancedWhere or your existing conditions - advancedWhere, - globalWhere // and()함수로 결합 or or() 등으로 결합 - ) - + // 커서 기반 페이지네이션 조건 추가 + let cursorWhere; + if (input.cursor) { + cursorWhere = gt(items.id, input.cursor); + } - // 아니면 ilike, inArray, gte 등으로 where 절 구성 - const where = finalWhere - + // 모든 조건 결합 + const finalWhere = and(advancedWhere, globalWhere, cursorWhere); + + // 정렬 (기존과 동일하지만 id 정렬 보장) + let orderBy = input.sort.length > 0 + ? input.sort.map((item) => + item.desc ? desc(items[item.id]) : asc(items[item.id]) + ) + : [asc(items.createdAt)]; + + // 무한 스크롤에서는 id 정렬이 필수 (커서 기반 페이지네이션용) + const hasIdSort = orderBy.some(sort => { + const column = sort.constructor.name.includes('desc') + ? sort.column + : sort.column; + return column === items.id; + }); - const orderBy = - input.sort.length > 0 - ? input.sort.map((item) => - item.desc ? desc(items[item.id]) : asc(items[item.id]) - ) - : [asc(items.createdAt)]; + if (!hasIdSort) { + orderBy.push(asc(items.id)); + } - // 트랜잭션 내부에서 Repository 호출 + // 트랜잭션으로 데이터 조회 (기존과 동일한 패턴) const { data, total } = await db.transaction(async (tx) => { + // limit + 1로 다음 페이지 존재 여부 확인 const data = await selectItems(tx, { - where, + where: finalWhere, orderBy, - offset, - limit: input.perPage, + limit: safeLimit + 1, }); - const total = await countItems(tx, where); + // 첫 페이지에서만 전체 개수 계산 (성능 최적화) + let total = null; + if (!input.cursor) { + // 커서 조건 제외하고 전체 개수 계산 + const countWhere = and(advancedWhere, globalWhere); + total = await countItems(tx, countWhere); + } + return { data, total }; }); - const pageCount = Math.ceil(total / input.perPage); + // 다음 페이지 존재 여부 및 커서 설정 + const hasNextPage = data.length > safeLimit; + const resultItems = hasNextPage ? data.slice(0, safeLimit) : data; + const nextCursor = hasNextPage && resultItems.length > 0 + ? resultItems[resultItems.length - 1].id + : null; + + return { + data: resultItems, + hasNextPage, + nextCursor, + total, + }; - return { data, pageCount }; } catch (err) { - // 에러 발생 시 디폴트 - console.error(err) - return { data: [], pageCount: 0 }; + console.error('getItemsInfinite error:', err); + return { + data: [], + hasNextPage: false, + nextCursor: null, + total: 0, + }; } }, - [JSON.stringify(input)], // 캐싱 키 + [JSON.stringify({ ...input, limit: Math.min(input.limit || 50, 100) })], { revalidate: 3600, - tags: ["items"], // revalidateTag("items") 호출 시 무효화 + tags: ["items"], } )(); } +// 통합된 Items 조회 함수 (모드별 자동 분기) +export async function getItemsUnified(input: GetItemsSchema & { mode?: 'pagination' | 'infinite'; cursor?: string }): Promise { + // perPage 기반 모드 자동 결정 + const isInfiniteMode = input.perPage >= 1_000_000; + + if (isInfiniteMode || input.mode === 'infinite') { + // 무한 스크롤 모드 + return getItemsInfinite({ + ...input, + limit: 50, // 실제로는 50개씩 로드 + cursor: input.cursor, + }); + } else { + // 기존 페이지네이션 모드 + return getItems(input); + } +} + /* ----------------------------------------------------- 2) 생성(Create) diff --git a/lib/items/table/items-table.tsx b/lib/items/table/items-table.tsx index 2bc1c913..c05b4348 100644 --- a/lib/items/table/items-table.tsx +++ b/lib/items/table/items-table.tsx @@ -9,8 +9,12 @@ import type { import { useDataTable } from "@/hooks/use-data-table" import { DataTable } from "@/components/data-table/data-table" +import { InfiniteDataTable } from "@/components/data-table/infinite-data-table" import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar" import { useFeatureFlags } from "./feature-flags-provider" +import { Button } from "@/components/ui/button" +import { RotateCcw, Info } from "lucide-react" +import { Alert, AlertDescription } from "@/components/ui/alert" import { getItems } from "../service" import { Item } from "@/db/schema/items" @@ -20,7 +24,7 @@ import { UpdateItemSheet } from "./update-item-sheet" import { DeleteItemsDialog } from "./delete-items-dialog" interface ItemsTableProps { - promises: Promise< + promises?: Promise< [ Awaited>, ] @@ -30,11 +34,11 @@ interface ItemsTableProps { export function ItemsTable({ promises }: ItemsTableProps) { const { featureFlags } = useFeatureFlags() - const [{ data, pageCount }] = - React.use(promises) - - console.log(data) + // 페이지네이션 모드 데이터 + const paginationData = promises ? React.use(promises) : null + const [{ data = [], pageCount = 0 }] = paginationData || [{ data: [], pageCount: 0 }] + console.log('ItemsTable data:', data.length, 'items') const [rowAction, setRowAction] = React.useState | null>(null) @@ -44,17 +48,7 @@ export function ItemsTable({ promises }: ItemsTableProps) { [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[] = [ { id: "itemCode", @@ -62,16 +56,6 @@ export function ItemsTable({ promises }: ItemsTableProps) { }, ] - /** - * 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[] = [ { id: "itemLevel", @@ -130,8 +114,15 @@ export function ItemsTable({ promises }: ItemsTableProps) { }, ] - - const { table } = useDataTable({ + // 확장된 useDataTable 훅 사용 (pageSize 기반 자동 전환) + const { + table, + infiniteScroll, + isInfiniteMode, + effectivePageSize, + handlePageSizeChange, + urlState + } = useDataTable({ data, columns, pageCount, @@ -145,24 +136,104 @@ export function ItemsTable({ promises }: ItemsTableProps) { getRowId: (originalRow) => String(originalRow.id), shallow: false, clearOnDefault: true, + // 무한 스크롤 설정 + infiniteScrollConfig: { + apiEndpoint: "/api/table/items/infinite", + tableName: "items", + maxPageSize: 100, + }, }) - return ( - <> - - - - - + // 새로고침 핸들러 + const handleRefresh = () => { + if (isInfiniteMode && infiniteScroll) { + infiniteScroll.refresh() + } else { + window.location.reload() + } + } - + return ( +
+ + {/*
+
+ +
+
*/} + + {/* 에러 상태 (무한 스크롤 모드) */} + {isInfiniteMode && infiniteScroll?.error && ( + + + 데이터를 불러오는 중 오류가 발생했습니다. + + + + )} + + {/* 로딩 상태가 아닐 때만 테이블 렌더링 */} + {!(isInfiniteMode && infiniteScroll?.isLoading && infiniteScroll?.isEmpty) ? ( + <> + {/* 도구 모음 */} + + + + + {/* 테이블 렌더링 */} + {isInfiniteMode ? ( + // 무한 스크롤 모드: InfiniteDataTable 사용 (자체 페이지네이션 없음) + + ) : ( + // 페이지네이션 모드: DataTable 사용 (내장 페이지네이션 활용) + + )} + + ) : ( + /* 로딩 스켈레톤 (무한 스크롤 초기 로딩) */ +
+
+ 무한 스크롤 모드로 데이터를 로드하고 있습니다... +
+ {Array.from({ length: 10 }).map((_, i) => ( +
+ ))} +
+ )} + + {/* 기존 다이얼로그들 */} setRowAction(null)} @@ -175,6 +246,6 @@ export function ItemsTable({ promises }: ItemsTableProps) { showTrigger={false} onSuccess={() => rowAction?.row.toggleSelected(false)} /> - +
) -} +} \ No newline at end of file diff --git a/lib/items/validations.ts b/lib/items/validations.ts index 14fc27b1..bb90e931 100644 --- a/lib/items/validations.ts +++ b/lib/items/validations.ts @@ -37,6 +37,7 @@ export const searchParamsCache = createSearchParamsCache({ search: parseAsString.withDefault(""), }) +export type GetItemsSchema = Awaited> export const createItemSchema = z.object({ itemCode: z.string().min(1, "아이템 코드는 필수입니다"), @@ -51,6 +52,8 @@ export const createItemSchema = z.object({ changeDate: z.string().max(8).nullable().optional(), baseUnitOfMeasure: z.string().max(3).nullable().optional(), }) +export type CreateItemSchema = z.infer + export const updateItemSchema = z.object({ itemCode: z.string().optional(), @@ -65,7 +68,4 @@ export const updateItemSchema = z.object({ changeDate: z.string().max(8).nullable().optional(), baseUnitOfMeasure: z.string().max(3).nullable().optional(), }) - -export type GetItemsSchema = Awaited> -export type CreateItemSchema = z.infer export type UpdateItemSchema = z.infer diff --git a/lib/rfqs-tech/table/rfqs-table-columns.tsx b/lib/rfqs-tech/table/rfqs-table-columns.tsx index 86660dc7..03089341 100644 --- a/lib/rfqs-tech/table/rfqs-table-columns.tsx +++ b/lib/rfqs-tech/table/rfqs-table-columns.tsx @@ -95,7 +95,7 @@ export function getColumns({ // 아이템과 첨부파일이 모두 0보다 커야 진행 가능 if (itemCount > 0 && attachCount > 0) { router.push( - `/evcp/rfq/${rfq.rfqId}` + `/evcp/rfq-tech/${rfq.rfqId}` ) } else { // 조건을 충족하지 않는 경우 토스트 알림 표시 diff --git a/lib/sedp/sync-object-class.ts b/lib/sedp/sync-object-class.ts index 68b9384f..5fd3ebff 100644 --- a/lib/sedp/sync-object-class.ts +++ b/lib/sedp/sync-object-class.ts @@ -1,5 +1,5 @@ import db from "@/db/db"; -import { projects, tagClasses, tagTypes } from '@/db/schema'; +import { projects, tagClassAttributes, tagClasses, tagTypes } from '@/db/schema'; import { eq, and } from 'drizzle-orm'; import { getSEDPToken } from "./sedp-token"; @@ -13,7 +13,7 @@ interface ObjectClass { DESC: string; TAG_TYPE_ID: string | null; PRT_CLS_ID: string | null; - LNK_ATT: any[]; + LNK_ATT: LinkAttribute[]; DELETED: boolean; DEL_USER: string | null; DEL_DTM: string | null; @@ -40,12 +40,123 @@ interface SyncResult { count?: number; error?: string; } + interface TagType { TYPE_ID: string; DESC: string; PROJ_NO: string; // 기타 필드들... } + +interface LinkAttribute { + ATT_ID: string; + DEF_VAL: string; + UOM_ID: string; + SEQ: number; +} + +// 태그 클래스 속성 저장 함수 +async function saveTagClassAttributes( + tagClassId: number, + attributes: LinkAttribute[] +): Promise { + try { + if (attributes.length === 0) { + console.log(`태그 클래스 ID ${tagClassId}에 저장할 속성이 없습니다.`); + return; + } + + // 현재 태그 클래스의 모든 속성 조회 + const existingAttributes = await db.select() + .from(tagClassAttributes) + .where(eq(tagClassAttributes.tagClassId, tagClassId)); + + // 속성 ID 기준으로 맵 생성 + const existingAttributeMap = new Map( + existingAttributes.map(attr => [attr.attId, attr]) + ); + + // API에 있는 속성 ID 목록 + const apiAttributeIds = new Set(attributes.map(attr => attr.ATT_ID)); + + // 삭제할 속성 ID 목록 + const attributeIdsToDelete = existingAttributes + .map(attr => attr.attId) + .filter(attId => !apiAttributeIds.has(attId)); + + // 새로 추가할 항목과 업데이트할 항목 분리 + const toInsert = []; + const toUpdate = []; + + for (const attr of attributes) { + const record = { + tagClassId: tagClassId, + attId: attr.ATT_ID, + defVal: attr.DEF_VAL, + uomId: attr.UOM_ID, + seq: attr.SEQ, + updatedAt: new Date() + }; + + if (existingAttributeMap.has(attr.ATT_ID)) { + // 업데이트 항목 + toUpdate.push(record); + } else { + // 새로 추가할 항목 + toInsert.push({ + ...record, + createdAt: new Date() + }); + } + } + + // 1. 새 항목 삽입 + if (toInsert.length > 0) { + await db.insert(tagClassAttributes).values(toInsert); + console.log(`태그 클래스 ID ${tagClassId}에 ${toInsert.length}개의 새 속성 추가 완료`); + } + + // 2. 기존 항목 업데이트 + for (const item of toUpdate) { + await db.update(tagClassAttributes) + .set({ + defVal: item.defVal, + uomId: item.uomId, + seq: item.seq, + updatedAt: item.updatedAt + }) + .where( + and( + eq(tagClassAttributes.tagClassId, item.tagClassId), + eq(tagClassAttributes.attId, item.attId) + ) + ); + } + + if (toUpdate.length > 0) { + console.log(`태그 클래스 ID ${tagClassId}의 ${toUpdate.length}개 속성 업데이트 완료`); + } + + // 3. 더 이상 존재하지 않는 항목 삭제 + if (attributeIdsToDelete.length > 0) { + for (const attId of attributeIdsToDelete) { + await db.delete(tagClassAttributes) + .where( + and( + eq(tagClassAttributes.tagClassId, tagClassId), + eq(tagClassAttributes.attId, attId) + ) + ); + } + console.log(`태그 클래스 ID ${tagClassId}에서 ${attributeIdsToDelete.length}개의 속성 삭제 완료`); + } + + } catch (error) { + console.error(`태그 클래스 속성 저장 실패 (태그 클래스 ID: ${tagClassId}):`, error); + throw error; + } +} + // 오브젝트 클래스 데이터 가져오기 async function getObjectClasses(projectCode: string, token:string): Promise { try { @@ -255,7 +366,7 @@ async function getAllTagTypes(projectCode: string, token: string): Promise 0) { - await db.insert(tagClasses).values(toInsert); + // returning을 사용하여 삽입된 레코드의 ID와 code를 가져옴 + const insertedClasses = await db.insert(tagClasses) + .values(toInsert) + .returning({ id: tagClasses.id, code: tagClasses.code }); + totalChanged += toInsert.length; console.log(`프로젝트 ID ${projectId}에 ${toInsert.length}개의 새 오브젝트 클래스 추가 완료`); + + // 새로 삽입된 각 클래스의 LNK_ATT 속성 처리 + for (const insertedClass of insertedClasses) { + const originalClass = classesToSave.find(cls => cls.CLS_ID === insertedClass.code); + if (originalClass && originalClass.LNK_ATT && originalClass.LNK_ATT.length > 0) { + try { + await saveTagClassAttributes(insertedClass.id, originalClass.LNK_ATT); + } catch (error) { + console.error(`태그 클래스 ${insertedClass.code}의 속성 저장 실패:`, error); + // 속성 저장 실패해도 계속 진행 + } + } + } } - // 2. 기존 항목 업데이트 + // 2. 기존 항목 업데이트 및 속성 처리 for (const item of toUpdate) { await db.update(tagClasses) .set({ @@ -380,6 +507,30 @@ async function saveObjectClassesToDatabase( eq(tagClasses.projectId, item.projectId) ) ); + + // 업데이트된 클래스의 ID 조회 + const updatedClass = await db.select({ id: tagClasses.id }) + .from(tagClasses) + .where( + and( + eq(tagClasses.code, item.code), + eq(tagClasses.projectId, item.projectId) + ) + ) + .limit(1); + + if (updatedClass.length > 0) { + const originalClass = classesToSave.find(cls => cls.CLS_ID === item.code); + if (originalClass && originalClass.LNK_ATT) { + try { + await saveTagClassAttributes(updatedClass[0].id, originalClass.LNK_ATT); + } catch (error) { + console.error(`태그 클래스 ${item.code}의 속성 업데이트 실패:`, error); + // 속성 업데이트 실패해도 계속 진행 + } + } + } + totalChanged += 1; } @@ -387,7 +538,7 @@ async function saveObjectClassesToDatabase( console.log(`프로젝트 ID ${projectId}의 ${toUpdate.length}개 오브젝트 클래스 업데이트 완료`); } - // 3. 더 이상 존재하지 않는 항목 삭제 + // 3. 더 이상 존재하지 않는 항목 삭제 (CASCADE로 속성도 자동 삭제됨) if (codesToDelete.length > 0) { for (const code of codesToDelete) { await db.delete(tagClasses) @@ -409,7 +560,7 @@ async function saveObjectClassesToDatabase( } } -// 5. 메인 동기화 함수 수정 +// 메인 동기화 함수 export async function syncObjectClasses() { try { console.log('오브젝트 클래스 동기화 시작:', new Date().toISOString()); @@ -420,7 +571,7 @@ export async function syncObjectClasses() { // 2. 모든 프로젝트 가져오기 const allProjects = await db.select().from(projects); - // 3. 모든 프로젝트에 대해 먼저 태그 타입 동기화 (바로 이 부분이 추가됨) + // 3. 모든 프로젝트에 대해 먼저 태그 타입 동기화 console.log('모든 프로젝트의 태그 타입 동기화 시작...'); const tagTypeResults = await Promise.allSettled( @@ -467,6 +618,7 @@ export async function syncObjectClasses() { const objectClasses = await getObjectClasses(project.code, token); // 데이터베이스에 저장 (skipTagTypeSync를 true로 설정하여 태그 타입 동기화 건너뜀) + // 이 과정에서 LNK_ATT 속성도 함께 처리됨 const count = await saveObjectClassesToDatabase(project.id, objectClasses, project.code, token, true); return { @@ -534,4 +686,80 @@ export async function syncObjectClasses() { console.error('오브젝트 클래스 동기화 중 오류 발생:', error); throw error; } +} + +// 유틸리티 함수들 (필요시 사용) +export async function getTagClassWithAttributes(tagClassId: number) { + const tagClass = await db.select() + .from(tagClasses) + .where(eq(tagClasses.id, tagClassId)) + .limit(1); + + if (tagClass.length === 0) { + return null; + } + + const attributes = await db.select() + .from(tagClassAttributes) + .where(eq(tagClassAttributes.tagClassId, tagClassId)) + .orderBy(tagClassAttributes.seq); + + return { + ...tagClass[0], + attributes + }; +} + +export async function getProjectTagClassesWithAttributes(projectId: number) { + const result = await db.select({ + // 태그 클래스 정보 + id: tagClasses.id, + code: tagClasses.code, + label: tagClasses.label, + tagTypeCode: tagClasses.tagTypeCode, + createdAt: tagClasses.createdAt, + updatedAt: tagClasses.updatedAt, + // 속성 정보 + attributeId: tagClassAttributes.id, + attId: tagClassAttributes.attId, + defVal: tagClassAttributes.defVal, + uomId: tagClassAttributes.uomId, + seq: tagClassAttributes.seq + }) + .from(tagClasses) + .leftJoin(tagClassAttributes, eq(tagClasses.id, tagClassAttributes.tagClassId)) + .where(eq(tagClasses.projectId, projectId)) + .orderBy(tagClasses.code, tagClassAttributes.seq); + + // 결과를 태그 클래스별로 그룹화 + const groupedResult = result.reduce((acc, row) => { + const tagClassId = row.id; + + if (!acc[tagClassId]) { + acc[tagClassId] = { + id: row.id, + code: row.code, + label: row.label, + tagTypeCode: row.tagTypeCode, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + attributes: [] + }; + } + + // 속성이 있는 경우에만 추가 + if (row.attributeId) { + acc[tagClassId].attributes.push({ + id: row.attributeId, + attId: row.attId, + defVal: row.defVal, + uomId: row.uomId, + seq: row.seq + }); + } + + return acc; + }, {} as Record); + + return Object.values(groupedResult); } \ No newline at end of file diff --git a/lib/tbe-tech/table/tbe-table-columns.tsx b/lib/tbe-tech/table/tbe-table-columns.tsx index 2349db7e..bb86e578 100644 --- a/lib/tbe-tech/table/tbe-table-columns.tsx +++ b/lib/tbe-tech/table/tbe-table-columns.tsx @@ -293,7 +293,7 @@ const commentsColumn: ColumnDef = { ), cell: ({ row }) => { const vendor = row.original - const commCount = vendor.comments?.length ?? 0 + const commCount = vendor.comments?.filter(c => c.evaluationId === vendor.tbeId)?.length ?? 0 function handleClick() { // setRowAction() 로 type 설정 diff --git a/lib/tbe-tech/table/tbe-table.tsx b/lib/tbe-tech/table/tbe-table.tsx index 3d981450..3537f16a 100644 --- a/lib/tbe-tech/table/tbe-table.tsx +++ b/lib/tbe-tech/table/tbe-table.tsx @@ -61,7 +61,7 @@ export function AllTbeTable({ promises }: VendorsTableProps) { // 새로운 벤더 데이터 추가 vendorMap.set(vendorId, { ...item, - vendorResponseId: item.id, + // vendorResponseId: item.id, technicalResponseId: item.id, rfqId: item.rfqId }) @@ -106,6 +106,7 @@ export function AllTbeTable({ promises }: VendorsTableProps) { openCommentSheet( rowAction.row.original.vendorId ?? 0, rowAction.row.original.rfqId ?? 0, + rowAction.row.original.tbeId ?? 0, ) } else if (rowAction.type === "files") { openFilesDialog( @@ -144,10 +145,10 @@ export function AllTbeTable({ promises }: VendorsTableProps) { // ----------------------------------------------------------- // 댓글 시트 열기 // ----------------------------------------------------------- - async function openCommentSheet(vendorId: number, rfqId: number) { + async function openCommentSheet(vendorId: number, rfqId: number, tbeId: number) { setInitialComments([]) setIsLoadingComments(true) - const comments = rowAction?.row.original.comments + const comments = rowAction?.row.original.comments?.filter(c => c.evaluationId === tbeId) try { if (comments && comments.length > 0) { const commentWithAttachments: TbeComment[] = await Promise.all( diff --git a/lib/tech-vendor-rfq-response/service.ts b/lib/tech-vendor-rfq-response/service.ts new file mode 100644 index 00000000..b706d42a --- /dev/null +++ b/lib/tech-vendor-rfq-response/service.ts @@ -0,0 +1,467 @@ +'use server' + +import { revalidateTag, unstable_cache } from "next/cache"; +import db from "@/db/db"; +import { and, desc, eq, inArray, isNull, or, sql } from "drizzle-orm"; +import { rfqAttachments, rfqComments, rfqItems, vendorResponses } from "@/db/schema/rfq"; +import { vendorResponsesView, vendorTechnicalResponses, vendorCommercialResponses, vendorResponseAttachments } from "@/db/schema/rfq"; +import { items, itemOffshoreTop, itemOffshoreHull } from "@/db/schema/items"; +import { GetRfqsForVendorsSchema } from "../rfqs-tech/validations"; +import { ItemData } from "./vendor-cbe-table/rfq-items-table/rfq-items-table"; +import * as z from "zod" + + + +export async function getRfqResponsesForVendor(input: GetRfqsForVendorsSchema, vendorId: number) { + return unstable_cache( + async () => { + const offset = (input.page - 1) * input.perPage; + const limit = input.perPage; + + // 1) 메인 쿼리: vendorResponsesView 사용 + const { rows, total } = await db.transaction(async (tx) => { + // 검색 조건 + let globalWhere; + if (input.search) { + const s = `%${input.search}%`; + globalWhere = or( + sql`${vendorResponsesView.rfqCode} ILIKE ${s}`, + sql`${vendorResponsesView.projectName} ILIKE ${s}`, + sql`${vendorResponsesView.rfqDescription} ILIKE ${s}` + ); + } + + // 협력업체 ID 필터링 + const mainWhere = and(eq(vendorResponsesView.vendorId, vendorId), globalWhere); + + // 정렬: 응답 시간순 + const orderBy = [desc(vendorResponsesView.respondedAt)]; + + // (A) 데이터 조회 + const data = await tx + .select() + .from(vendorResponsesView) + .where(mainWhere) + .orderBy(...orderBy) + .offset(offset) + .limit(limit); + + // (B) 전체 개수 카운트 + const [{ count }] = await tx + .select({ + count: sql`count(*)`.as("count"), + }) + .from(vendorResponsesView) + .where(mainWhere); + + return { rows: data, total: Number(count) }; + }); + + // 2) rfqId 고유 목록 추출 + const distinctRfqs = [...new Set(rows.map((r) => r.rfqId))]; + if (distinctRfqs.length === 0) { + return { data: [], pageCount: 0 }; + } + + // 3) 추가 데이터 조회 + // 3-A) RFQ 아이템 + const itemsAll = await db + .select({ + id: rfqItems.id, + rfqId: rfqItems.rfqId, + itemCode: rfqItems.itemCode, + itemList: sql`COALESCE(${itemOffshoreTop.itemList}, ${itemOffshoreHull.itemList})`.as('itemList'), + subItemList: sql`COALESCE(${itemOffshoreTop.subItemList}, ${itemOffshoreHull.subItemList})`.as('subItemList'), + quantity: rfqItems.quantity, + description: rfqItems.description, + uom: rfqItems.uom, + }) + .from(rfqItems) + .leftJoin(itemOffshoreTop, eq(rfqItems.itemCode, itemOffshoreTop.itemCode)) + .leftJoin(itemOffshoreHull, eq(rfqItems.itemCode, itemOffshoreHull.itemCode)) + .where(inArray(rfqItems.rfqId, distinctRfqs)); + + // 3-B) RFQ 첨부 파일 (협력업체용) + const attachAll = await db + .select() + .from(rfqAttachments) + .where( + and( + inArray(rfqAttachments.rfqId, distinctRfqs), + isNull(rfqAttachments.vendorId) + ) + ); + + // 3-C) RFQ 코멘트 + const commAll = await db + .select() + .from(rfqComments) + .where( + and( + inArray(rfqComments.rfqId, distinctRfqs), + or( + isNull(rfqComments.vendorId), + eq(rfqComments.vendorId, vendorId) + ) + ) + ); + + + // 3-E) 협력업체 응답 상세 - 기술 + const technicalResponsesAll = await db + .select() + .from(vendorTechnicalResponses) + .where( + inArray( + vendorTechnicalResponses.responseId, + rows.map((r) => r.responseId) + ) + ); + + // 3-F) 협력업체 응답 상세 - 상업 + const commercialResponsesAll = await db + .select() + .from(vendorCommercialResponses) + .where( + inArray( + vendorCommercialResponses.responseId, + rows.map((r) => r.responseId) + ) + ); + + // 3-G) 협력업체 응답 첨부 파일 + const responseAttachmentsAll = await db + .select() + .from(vendorResponseAttachments) + .where( + inArray( + vendorResponseAttachments.responseId, + rows.map((r) => r.responseId) + ) + ); + + // 4) 데이터 그룹화 + // RFQ 아이템 그룹화 + const itemsByRfqId = new Map(); + for (const it of itemsAll) { + if (!itemsByRfqId.has(it.rfqId)) { + itemsByRfqId.set(it.rfqId, []); + } + itemsByRfqId.get(it.rfqId)!.push({ + id: it.id, + itemCode: it.itemCode, + itemList: it.itemList, + subItemList: it.subItemList, + quantity: it.quantity, + description: it.description, + uom: it.uom, + }); + } + + // RFQ 첨부 파일 그룹화 + const attachByRfqId = new Map(); + for (const att of attachAll) { + const rid = att.rfqId!; + if (!attachByRfqId.has(rid)) { + attachByRfqId.set(rid, []); + } + attachByRfqId.get(rid)!.push({ + id: att.id, + fileName: att.fileName, + filePath: att.filePath, + vendorId: att.vendorId, + evaluationId: att.evaluationId, + }); + } + + // RFQ 코멘트 그룹화 + const commByRfqId = new Map(); + for (const c of commAll) { + const rid = c.rfqId!; + if (!commByRfqId.has(rid)) { + commByRfqId.set(rid, []); + } + commByRfqId.get(rid)!.push({ + id: c.id, + commentText: c.commentText, + vendorId: c.vendorId, + evaluationId: c.evaluationId, + createdAt: c.createdAt, + }); + } + + + // 기술 응답 그룹화 + const techResponseByResponseId = new Map(); + for (const tr of technicalResponsesAll) { + techResponseByResponseId.set(tr.responseId, { + id: tr.id, + summary: tr.summary, + notes: tr.notes, + createdAt: tr.createdAt, + updatedAt: tr.updatedAt, + }); + } + + // 상업 응답 그룹화 + const commResponseByResponseId = new Map(); + for (const cr of commercialResponsesAll) { + commResponseByResponseId.set(cr.responseId, { + id: cr.id, + totalPrice: cr.totalPrice, + currency: cr.currency, + paymentTerms: cr.paymentTerms, + incoterms: cr.incoterms, + deliveryPeriod: cr.deliveryPeriod, + warrantyPeriod: cr.warrantyPeriod, + validityPeriod: cr.validityPeriod, + priceBreakdown: cr.priceBreakdown, + commercialNotes: cr.commercialNotes, + createdAt: cr.createdAt, + updatedAt: cr.updatedAt, + }); + } + + // 응답 첨부 파일 그룹화 + const respAttachByResponseId = new Map(); + for (const ra of responseAttachmentsAll) { + const rid = ra.responseId!; + if (!respAttachByResponseId.has(rid)) { + respAttachByResponseId.set(rid, []); + } + respAttachByResponseId.get(rid)!.push({ + id: ra.id, + fileName: ra.fileName, + filePath: ra.filePath, + attachmentType: ra.attachmentType, + description: ra.description, + uploadedAt: ra.uploadedAt, + uploadedBy: ra.uploadedBy, + }); + } + + // 5) 최종 데이터 결합 + const final = rows.map((row) => { + return { + // 응답 정보 + responseId: row.responseId, + responseStatus: row.responseStatus, + respondedAt: row.respondedAt, + + // RFQ 기본 정보 + rfqId: row.rfqId, + rfqCode: row.rfqCode, + rfqDescription: row.rfqDescription, + rfqDueDate: row.rfqDueDate, + rfqStatus: row.rfqStatus, + + rfqCreatedAt: row.rfqCreatedAt, + rfqUpdatedAt: row.rfqUpdatedAt, + rfqCreatedBy: row.rfqCreatedBy, + + // 프로젝트 정보 + projectId: row.projectId, + projectCode: row.projectCode, + projectName: row.projectName, + + // 협력업체 정보 + vendorId: row.vendorId, + vendorName: row.vendorName, + vendorCode: row.vendorCode, + + // RFQ 관련 데이터 + items: itemsByRfqId.get(row.rfqId) || [], + attachments: attachByRfqId.get(row.rfqId) || [], + comments: commByRfqId.get(row.rfqId) || [], + + // 평가 정보 + tbeEvaluation: row.tbeId ? { + id: row.tbeId, + result: row.tbeResult, + } : null, + cbeEvaluation: row.cbeId ? { + id: row.cbeId, + result: row.cbeResult, + } : null, + + // 협력업체 응답 상세 + technicalResponse: techResponseByResponseId.get(row.responseId) || null, + commercialResponse: commResponseByResponseId.get(row.responseId) || null, + responseAttachments: respAttachByResponseId.get(row.responseId) || [], + + // 응답 상태 표시 + hasTechnicalResponse: row.hasTechnicalResponse, + hasCommercialResponse: row.hasCommercialResponse, + attachmentCount: row.attachmentCount || 0, + }; + }); + + const pageCount = Math.ceil(total / input.perPage); + return { data: final, pageCount }; + }, + [JSON.stringify(input), `${vendorId}`], + { + revalidate: 600, + tags: ["rfqs-vendor", `vendor-${vendorId}`], + } + )(); +} + + +export async function getItemsByRfqId(rfqId: number): Promise { + try { + if (!rfqId || isNaN(Number(rfqId))) { + return { + success: false, + error: "Invalid RFQ ID provided", + } + } + + // Query the database to get all items for the given RFQ ID + const items = await db + .select() + .from(rfqItems) + .where(eq(rfqItems.rfqId, rfqId)) + .orderBy(rfqItems.itemCode) + + + return { + success: true, + data: items as ItemData[], + } + } catch (error) { + console.error("Error fetching RFQ items:", error) + + return { + success: false, + error: error instanceof Error ? error.message : "Unknown error occurred when fetching RFQ items", + } + } +} + + +// Define the schema for validation +const commercialResponseSchema = z.object({ + responseId: z.number(), + vendorId: z.number(), // Added vendorId field + responseStatus: z.enum(["PENDING", "IN_PROGRESS", "SUBMITTED", "REJECTED", "ACCEPTED"]), + totalPrice: z.number().optional(), + currency: z.string().default("USD"), + paymentTerms: z.string().optional(), + incoterms: z.string().optional(), + deliveryPeriod: z.string().optional(), + warrantyPeriod: z.string().optional(), + validityPeriod: z.string().optional(), + priceBreakdown: z.string().optional(), + commercialNotes: z.string().optional(), +}) + +type CommercialResponseInput = z.infer + +interface ResponseType { + success: boolean + error?: string + data?: any +} + +export async function updateCommercialResponse(input: CommercialResponseInput): Promise { + try { + // Validate input data + const validated = commercialResponseSchema.parse(input) + + // Check if a commercial response already exists for this responseId + const existingResponse = await db + .select() + .from(vendorCommercialResponses) + .where(eq(vendorCommercialResponses.responseId, validated.responseId)) + .limit(1) + + const now = new Date() + + if (existingResponse.length > 0) { + // Update existing record + await db + .update(vendorCommercialResponses) + .set({ + responseStatus: validated.responseStatus, + totalPrice: validated.totalPrice, + currency: validated.currency, + paymentTerms: validated.paymentTerms, + incoterms: validated.incoterms, + deliveryPeriod: validated.deliveryPeriod, + warrantyPeriod: validated.warrantyPeriod, + validityPeriod: validated.validityPeriod, + priceBreakdown: validated.priceBreakdown, + commercialNotes: validated.commercialNotes, + updatedAt: now, + }) + .where(eq(vendorCommercialResponses.responseId, validated.responseId)) + + } else { + // Return error instead of creating a new record + return { + success: false, + error: "해당 응답 ID에 대한 상업 응답 정보를 찾을 수 없습니다." + } + } + + // Also update the main vendor response status if submitted + if (validated.responseStatus === "SUBMITTED") { + // Get the vendor response + const vendorResponseResult = await db + .select() + .from(vendorResponses) + .where(eq(vendorResponses.id, validated.responseId)) + .limit(1) + + if (vendorResponseResult.length > 0) { + // Update the main response status to RESPONDED + await db + .update(vendorResponses) + .set({ + responseStatus: "RESPONDED", + updatedAt: now, + }) + .where(eq(vendorResponses.id, validated.responseId)) + } + } + + // Use vendorId for revalidateTag + revalidateTag(`cbe-vendor-${validated.vendorId}`) + + return { + success: true, + data: { responseId: validated.responseId } + } + + } catch (error) { + console.error("Error updating commercial response:", error) + + if (error instanceof z.ZodError) { + return { + success: false, + error: "유효하지 않은 데이터가 제공되었습니다." + } + } + + return { + success: false, + error: error instanceof Error ? error.message : "Unknown error occurred" + } + } +} +// Helper function to get responseId from rfqId and vendorId +export async function getCommercialResponseByResponseId(responseId: number): Promise { + try { + const response = await db + .select() + .from(vendorCommercialResponses) + .where(eq(vendorCommercialResponses.responseId, responseId)) + .limit(1) + + return response.length > 0 ? response[0] : null + } catch (error) { + console.error("Error getting commercial response:", error) + return null + } +} \ No newline at end of file diff --git a/lib/tech-vendor-rfq-response/types.ts b/lib/tech-vendor-rfq-response/types.ts new file mode 100644 index 00000000..f8ae1fcf --- /dev/null +++ b/lib/tech-vendor-rfq-response/types.ts @@ -0,0 +1,76 @@ +// RFQ 아이템 타입 +export interface RfqResponseItem { + id: number; + itemCode: string; + itemList?: string | null; + subItemList?: string | null; + quantity?: number; + uom?: string; + description?: string | null; +} + +// RFQ 첨부 파일 타입 +export interface RfqResponseAttachment { + id: number; + fileName: string; + filePath: string; + vendorId?: number | null; + evaluationId?: number | null; +} + +// RFQ 코멘트 타입 +export interface RfqResponseComment { + id: number; + commentText: string; + vendorId?: number | null; + evaluationId?: number | null; + createdAt: Date; + commentedBy?: number; +} + +// 최종 RfqResponse 타입 - RFQ 참여 응답만 포함하도록 간소화 +export interface RfqResponse { + // 응답 정보 + responseId: number; + responseStatus: "INVITED" | "ACCEPTED" | "DECLINED" | "REVIEWING" | "RESPONDED"; + respondedAt: Date; + + // RFQ 기본 정보 + rfqId: number; + rfqCode: string; + rfqDescription?: string | null; + rfqDueDate?: Date | null; + rfqStatus: string; + rfqCreatedAt: Date; + rfqUpdatedAt: Date; + rfqCreatedBy?: number | null; + + // 프로젝트 정보 + projectId?: number | null; + projectCode?: string | null; + projectName?: string | null; + + // 협력업체 정보 + vendorId: number; + vendorName: string; + vendorCode?: string | null; + + // RFQ 관련 데이터 + items: RfqResponseItem[]; + attachments: RfqResponseAttachment[]; + comments: RfqResponseComment[]; +} + +// DataTable 등에서 사용할 수 있도록 id 필드를 추가한 확장 타입 +export interface RfqResponseWithId extends RfqResponse { + id: number; // rfqId와 동일하게 사용 +} + +// 페이지네이션 결과 타입 +export interface RfqResponsesResult { + data: RfqResponseWithId[]; + pageCount: number; +} + +// 이전 버전과의 호환성을 위한 RfqWithAll 타입 (이름만 유지) +export type RfqWithAll = RfqResponseWithId; \ No newline at end of file diff --git a/lib/tech-vendor-rfq-response/vendor-cbe-table/cbe-table-columns.tsx b/lib/tech-vendor-rfq-response/vendor-cbe-table/cbe-table-columns.tsx new file mode 100644 index 00000000..c7be0bf4 --- /dev/null +++ b/lib/tech-vendor-rfq-response/vendor-cbe-table/cbe-table-columns.tsx @@ -0,0 +1,365 @@ +"use client" + +import * as React from "react" +import { type DataTableRowAction } from "@/types/table" +import { type ColumnDef } from "@tanstack/react-table" +import { Download, Loader2, MessageSquare, FileEdit } from "lucide-react" +import { formatDate } from "@/lib/utils" +import { Badge } from "@/components/ui/badge" +import { Button } from "@/components/ui/button" +import { Checkbox } from "@/components/ui/checkbox" +import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header" +import { useRouter } from "next/navigation" +import { VendorWithCbeFields, vendorResponseCbeColumnsConfig } from "@/config/vendorCbeColumnsConfig" +import { toast } from "sonner" + + +type NextRouter = ReturnType + +interface GetColumnsProps { + setRowAction: React.Dispatch< + React.SetStateAction | null> + > + router: NextRouter + openCommentSheet: (vendorId: number) => void + handleDownloadCbeFiles: (vendorId: number, rfqId: number) => void + loadingVendors: Record + openVendorContactsDialog: (rfqId: number, rfq: VendorWithCbeFields) => void + // New prop for handling commercial response + openCommercialResponseSheet: (responseId: number, rfq: VendorWithCbeFields) => void +} + +/** + * tanstack table 컬럼 정의 (중첩 헤더 버전) + */ +export function getColumns({ + setRowAction, + router, + openCommentSheet, + handleDownloadCbeFiles, + loadingVendors, + openVendorContactsDialog, + openCommercialResponseSheet +}: 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) 그룹화(Nested) 컬럼 구성 + // ---------------------------------------------------------------- + const groupMap: Record[]> = {} + + vendorResponseCbeColumnsConfig.forEach((cfg) => { + const groupName = cfg.group || "_noGroup" + if (!groupMap[groupName]) { + groupMap[groupName] = [] + } + + // childCol: ColumnDef + const childCol: ColumnDef = { + accessorKey: cfg.id, + enableResizing: true, + header: ({ column }) => ( + + ), + meta: { + excelHeader: cfg.excelHeader, + group: cfg.group, + type: cfg.type, + }, + maxSize: 120, + // 셀 렌더링 + cell: ({ row, getValue }) => { + // 1) 필드값 가져오기 + const val = getValue() + + + if (cfg.id === "rfqCode") { + const rfq = row.original; + const rfqId = rfq.rfqId; + + // 협력업체 이름을 클릭할 수 있는 버튼으로 렌더링 + const handleVendorNameClick = () => { + if (rfqId) { + openVendorContactsDialog(rfqId, rfq); // vendor 전체 객체 전달 + } else { + toast.error("협력업체 ID를 찾을 수 없습니다."); + } + }; + + return ( + + ); + } + + // Commercial Response Status에 배지 적용 + if (cfg.id === "commercialResponseStatus") { + const status = val as string; + + if (!status) return -; + + let variant: "default" | "outline" | "secondary" | "destructive" = "outline"; + + switch (status) { + case "SUBMITTED": + variant = "default"; // Green + break; + case "IN_PROGRESS": + variant = "secondary"; // Orange/Yellow + break; + case "PENDING": + variant = "outline"; // Gray + break; + default: + variant = "outline"; + } + + return ( + + {status.toLowerCase().replace("_", " ")} + + ); + } + + // 예) TBE Updated (날짜) + if (cfg.id === "respondedAt" || cfg.id === "rfqDueDate" ) { + const dateVal = val as Date | undefined + if (!dateVal) return null + return formatDate(dateVal) + } + + // 그 외 필드는 기본 값 표시 + return val ?? "" + }, + } + + groupMap[groupName].push(childCol) + }) + + // groupMap → nestedColumns + const nestedColumns: ColumnDef[] = [] + Object.entries(groupMap).forEach(([groupName, colDefs]) => { + if (groupName === "_noGroup") { + nestedColumns.push(...colDefs) + } else { + nestedColumns.push({ + id: groupName, + header: groupName, + columns: colDefs, + }) + } + }) + + // ---------------------------------------------------------------- + // 3) Respond 컬럼 (새로 추가) + // ---------------------------------------------------------------- + const respondColumn: ColumnDef = { + id: "respond", + header: ({ column }) => ( + + ), + cell: ({ row }) => { + const vendor = row.original + const responseId = vendor.responseId + + if (!responseId) { + return
-
+ } + + const handleClick = () => { + openCommercialResponseSheet(responseId, vendor) + } + + // Status에 따라 버튼 variant 변경 + let variant: "default" | "outline" | "ghost" | "secondary" = "default" + let buttonText = "Respond" + + if (vendor.commercialResponseStatus === "SUBMITTED") { + variant = "outline" + buttonText = "Update" + } else if (vendor.commercialResponseStatus === "IN_PROGRESS") { + variant = "secondary" + buttonText = "Continue" + } + + return ( + + ) + }, + enableSorting: false, + maxSize: 200, + minSize: 115, + } + + // ---------------------------------------------------------------- + // 4) Comments 컬럼 + // ---------------------------------------------------------------- + const commentsColumn: ColumnDef = { + id: "comments", + header: ({ column }) => ( + + ), + cell: ({ row }) => { + const vendor = row.original + const commCount = vendor.comments?.length ?? 0 + + function handleClick() { + // rowAction + openCommentSheet + setRowAction({ row, type: "comments" }) + openCommentSheet(vendor.responseId ?? 0) + } + + return ( + + ) + }, + enableSorting: false, + maxSize: 80 + } + + // ---------------------------------------------------------------- + // 5) 파일 다운로드 컬럼 (개별 로딩 상태 적용) + // ---------------------------------------------------------------- + const downloadColumn: ColumnDef = { + id: "attachDownload", + header: ({ column }) => ( + + ), + cell: ({ row }) => { + const vendor = row.original + const vendorId = vendor.vendorId + const rfqId = vendor.rfqId + const files = vendor.files?.length || 0 + + if (!vendorId || !rfqId) { + return
-
+ } + + // 각 행별로 로딩 상태 확인 (vendorId_rfqId 형식의 키 사용) + const rowKey = `${vendorId}_${rfqId}` + const isRowLoading = loadingVendors[rowKey] === true + + // 템플릿 파일이 없으면 다운로드 버튼 비활성화 + const isDisabled = files <= 0 || isRowLoading + + return ( + + ) + }, + enableSorting: false, + maxSize: 80, + } + + // ---------------------------------------------------------------- + // 6) 최종 컬럼 배열 (respondColumn 추가) + // ---------------------------------------------------------------- + return [ + selectColumn, + ...nestedColumns, + respondColumn, // 응답 컬럼 추가 + downloadColumn, + commentsColumn, + ] +} \ No newline at end of file diff --git a/lib/tech-vendor-rfq-response/vendor-cbe-table/cbe-table.tsx b/lib/tech-vendor-rfq-response/vendor-cbe-table/cbe-table.tsx new file mode 100644 index 00000000..94e29a95 --- /dev/null +++ b/lib/tech-vendor-rfq-response/vendor-cbe-table/cbe-table.tsx @@ -0,0 +1,272 @@ +"use client" + +import * as React from "react" +import { useRouter } from "next/navigation" +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 "./cbe-table-columns" +import { + fetchRfqAttachmentsbyCommentId, + getCBEbyVendorId, + getFileFromRfqAttachmentsbyid, + fetchCbeFiles +} from "../../rfqs-tech/service" +import { useSession } from "next-auth/react" +import { CbeComment, CommentSheet } from "./comments-sheet" +import { VendorWithCbeFields } from "@/config/vendorCbeColumnsConfig" +import { toast } from "sonner" +import { RfqDeailDialog } from "./rfq-detail-dialog" +import { CommercialResponseSheet } from "./respond-cbe-sheet" + +interface VendorsTableProps { + promises: Promise< + [ + Awaited>, + ] + > +} + +export function CbeVendorTable({ promises }: VendorsTableProps) { + const { data: session } = useSession() + const userVendorId = session?.user?.companyId + const userId = Number(session?.user?.id) + // Suspense로 받아온 데이터 + const [{ data, pageCount }] = React.use(promises) + const [rowAction, setRowAction] = React.useState | null>(null) + const [selectedCbeId, setSelectedCbeId] = React.useState(null) + + // 개별 협력업체별 로딩 상태를 관리하는 맵 + const [loadingVendors, setLoadingVendors] = React.useState>({}) + + const router = useRouter() + + // 코멘트 관련 상태 + const [initialComments, setInitialComments] = React.useState([]) + const [commentSheetOpen, setCommentSheetOpen] = React.useState(false) + const [selectedRfqIdForComments, setSelectedRfqIdForComments] = React.useState(null) + + // 상업 응답 관련 상태 + const [commercialResponseSheetOpen, setCommercialResponseSheetOpen] = React.useState(false) + const [selectedResponseId, setSelectedResponseId] = React.useState(null) + const [selectedRfq, setSelectedRfq] = React.useState(null) + + // RFQ 상세 관련 상태 + const [rfqDetailDialogOpen, setRfqDetailDialogOpen] = React.useState(false) + const [selectedRfqId, setSelectedRfqId] = React.useState(null) + const [selectedRfqDetail, setSelectedRfqDetail] = React.useState(null) + + React.useEffect(() => { + if (rowAction?.type === "comments") { + // rowAction가 새로 세팅된 뒤 여기서 openCommentSheet 실행 + openCommentSheet(Number(rowAction.row.original.responseId)) + } + }, [rowAction]) + + async function openCommentSheet(responseId: number) { + setInitialComments([]) + + const comments = rowAction?.row.original.comments + const rfqId = rowAction?.row.original.rfqId + + if (comments && comments.length > 0) { + const commentWithAttachments: CbeComment[] = await Promise.all( + comments.map(async (c) => { + // 서버 액션을 사용하여 코멘트 첨부 파일 가져오기 + const attachments = await fetchRfqAttachmentsbyCommentId(c.id) + + return { + ...c, + commentedBy: userId, // DB나 API 응답에 있다고 가정 + attachments, + } + }) + ) + + setInitialComments(commentWithAttachments) + } + + if(rfqId) { + setSelectedRfqIdForComments(rfqId) + } + setSelectedCbeId(responseId) + setCommentSheetOpen(true) + } + + // 상업 응답 시트 열기 + function openCommercialResponseSheet(responseId: number, rfq: VendorWithCbeFields) { + setSelectedResponseId(responseId) + setSelectedRfq(rfq) + setCommercialResponseSheetOpen(true) + } + + // RFQ 상세 대화상자 열기 + function openRfqDetailDialog(rfqId: number, rfq: VendorWithCbeFields) { + setSelectedRfqId(rfqId) + setSelectedRfqDetail(rfq) + setRfqDetailDialogOpen(true) + } + + const handleDownloadCbeFiles = React.useCallback( + async (vendorId: number, rfqId: number) => { + // 고유 키 생성: vendorId_rfqId + const rowKey = `${vendorId}_${rfqId}` + + // 해당 협력업체의 로딩 상태만 true로 설정 + setLoadingVendors(prev => ({ + ...prev, + [rowKey]: true + })) + + try { + const { files, error } = await fetchCbeFiles(vendorId, rfqId); + if (error) { + toast.error(error); + return; + } + if (files.length === 0) { + toast.warning("다운로드할 CBE 파일이 없습니다"); + return; + } + // 순차적으로 파일 다운로드 + for (const file of files) { + await downloadFile(file.id); + } + toast.success(`${files.length}개의 CBE 파일이 다운로드되었습니다`); + } catch (error) { + toast.error("CBE 파일을 다운로드하는 데 실패했습니다"); + console.error(error); + } finally { + // 해당 협력업체의 로딩 상태만 false로 되돌림 + setLoadingVendors(prev => ({ + ...prev, + [rowKey]: false + })) + } + }, + [] + ); + + const downloadFile = React.useCallback(async (fileId: number) => { + try { + const { file, error } = await getFileFromRfqAttachmentsbyid(fileId); + if (error || !file) { + throw new Error(error || "파일 정보를 가져오는 데 실패했습니다"); + } + + const link = document.createElement("a"); + link.href = `/api/rfq-download?path=${encodeURIComponent(file.filePath)}`; + link.download = file.fileName; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + + return true; + } catch (error) { + console.error(error); + return false; + } + }, []); + + // 응답 성공 후 데이터 갱신 + const handleResponseSuccess = React.useCallback(() => { + // 필요한 경우 데이터 다시 가져오기 + router.refresh() + }, [router]); + + // getColumns() 호출 시 필요한 핸들러들 주입 + const columns = React.useMemo( + () => getColumns({ + setRowAction, + router, + openCommentSheet, + handleDownloadCbeFiles, + loadingVendors, + openVendorContactsDialog: openRfqDetailDialog, + openCommercialResponseSheet, + }), + [ + setRowAction, + router, + openCommentSheet, + handleDownloadCbeFiles, + loadingVendors, + openRfqDetailDialog, + openCommercialResponseSheet + ] + ); + + // 필터 필드 정의 + const filterFields: DataTableFilterField[] = [] + const advancedFilterFields: DataTableAdvancedFilterField[] = [ + + ] + + const { table } = useDataTable({ + data, + columns, + pageCount, + filterFields, + enablePinning: true, + enableAdvancedFilter: true, + initialState: { + sorting: [{ id: "respondedAt", desc: true }], + columnPinning: { right: ["respond", "comments"] }, // respond 컬럼을 오른쪽에 고정 + }, + getRowId: (originalRow) => String(originalRow.responseId), + shallow: false, + clearOnDefault: true, + }) + + return ( + <> + + + + + {/* 코멘트 시트 */} + {commentSheetOpen && selectedRfqIdForComments && selectedCbeId !== null && ( + + )} + + {/* 상업 응답 시트 */} + {commercialResponseSheetOpen && selectedResponseId !== null && selectedRfq && ( + + )} + + {/* RFQ 상세 대화상자 */} + {rfqDetailDialogOpen && selectedRfqId !== null && ( + + )} + + ) +} \ No newline at end of file diff --git a/lib/tech-vendor-rfq-response/vendor-cbe-table/comments-sheet.tsx b/lib/tech-vendor-rfq-response/vendor-cbe-table/comments-sheet.tsx new file mode 100644 index 00000000..6a92f4d9 --- /dev/null +++ b/lib/tech-vendor-rfq-response/vendor-cbe-table/comments-sheet.tsx @@ -0,0 +1,323 @@ +"use client" + +import * as React from "react" +import { useForm, useFieldArray } from "react-hook-form" +import { z } from "zod" +import { zodResolver } from "@hookform/resolvers/zod" +import { Download, X, Loader2 } from "lucide-react" +import prettyBytes from "pretty-bytes" +import { toast } from "sonner" + +import { + Sheet, + SheetClose, + SheetContent, + SheetDescription, + SheetFooter, + SheetHeader, + SheetTitle, +} from "@/components/ui/sheet" +import { Button } from "@/components/ui/button" +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form" +import { Textarea } from "@/components/ui/textarea" +import { + Dropzone, + DropzoneZone, + DropzoneUploadIcon, + DropzoneTitle, + DropzoneDescription, + DropzoneInput, +} from "@/components/ui/dropzone" +import { + Table, + TableHeader, + TableRow, + TableHead, + TableBody, + TableCell, +} from "@/components/ui/table" + +import { formatDate } from "@/lib/utils" +import { createRfqCommentWithAttachments } from "@/lib/rfqs-tech/service" + + +export interface CbeComment { + id: number + commentText: string + commentedBy?: number + commentedByEmail?: string + createdAt?: Date + attachments?: { + id: number + fileName: string + filePath: string + }[] +} + +// 1) props 정의 +interface CommentSheetProps extends React.ComponentPropsWithRef { + initialComments?: CbeComment[] + currentUserId: number + rfqId: number + tbeId?: number + cbeId?: number + vendorId: number + onCommentsUpdated?: (comments: CbeComment[]) => void + isLoading?: boolean // New prop +} + +// 2) 폼 스키마 +const commentFormSchema = z.object({ + commentText: z.string().min(1, "댓글을 입력하세요."), + newFiles: z.array(z.any()).optional(), // File[] +}) +type CommentFormValues = z.infer + +const MAX_FILE_SIZE = 30e6 // 30MB + +export function CommentSheet({ + rfqId, + vendorId, + initialComments = [], + currentUserId, + tbeId, + cbeId, + onCommentsUpdated, + isLoading = false, // Default to false + ...props +}: CommentSheetProps) { + + + const [comments, setComments] = React.useState(initialComments) + const [isPending, startTransition] = React.useTransition() + + React.useEffect(() => { + setComments(initialComments) + }, [initialComments]) + + const form = useForm({ + resolver: zodResolver(commentFormSchema), + defaultValues: { + commentText: "", + newFiles: [], + }, + }) + + const { fields: newFileFields, append, remove } = useFieldArray({ + control: form.control, + name: "newFiles", + }) + + // (A) 기존 코멘트 렌더링 + function renderExistingComments() { + + if (isLoading) { + return ( +
+ + Loading comments... +
+ ) + } + + if (comments.length === 0) { + return

No comments yet

+ } + return ( + + + + Comment + Attachments + Created At + Created By + + + + {comments.map((c) => ( + + {c.commentText} + + {!c.attachments?.length && ( + No files + )} + {c.attachments?.length && ( +
+ {c.attachments.map((att) => ( + + ))} +
+ )} +
+ {c.createdAt ? formatDate(c.createdAt) : "-"} + {c.commentedByEmail ?? "-"} +
+ ))} +
+
+ ) + } + + // (B) 파일 드롭 + function handleDropAccepted(files: File[]) { + append(files) + } + + // (C) Submit + async function onSubmit(data: CommentFormValues) { + if (!rfqId) return + startTransition(async () => { + try { + const res = await createRfqCommentWithAttachments({ + rfqId, + vendorId, + commentText: data.commentText, + commentedBy: currentUserId, + evaluationId: null, + cbeId: cbeId, + files: data.newFiles, + }) + + if (!res.ok) { + throw new Error("Failed to create comment") + } + + toast.success("Comment created") + + // 임시로 새 코멘트 추가 + const newComment: CbeComment = { + id: res.commentId, // 서버 응답 + commentText: data.commentText, + commentedBy: currentUserId, + createdAt: res.createdAt, + attachments: + data.newFiles?.map((f) => ({ + id: Math.floor(Math.random() * 1e6), + fileName: f.name, + filePath: "/uploads/" + f.name, + })) || [], + } + setComments((prev) => [...prev, newComment]) + onCommentsUpdated?.([...comments, newComment]) + + form.reset() + } catch (err: any) { + console.error(err) + toast.error("Error: " + err.message) + } + }) + } + + return ( + + + + Comments + + 필요시 첨부파일과 함께 문의/코멘트를 남길 수 있습니다. + + + +
{renderExistingComments()}
+ +
+ + ( + + New Comment + +