diff options
Diffstat (limited to 'lib/techsales-rfq')
15 files changed, 935 insertions, 284 deletions
diff --git a/lib/techsales-rfq/repository.ts b/lib/techsales-rfq/repository.ts index 07c9ddf8..abf831c1 100644 --- a/lib/techsales-rfq/repository.ts +++ b/lib/techsales-rfq/repository.ts @@ -260,6 +260,7 @@ export async function selectTechSalesVendorQuotationsWithJoin( validUntil: techSalesVendorQuotations.validUntil,
status: techSalesVendorQuotations.status,
remark: techSalesVendorQuotations.remark,
+ quotationVersion: techSalesVendorQuotations.quotationVersion,
rejectionReason: techSalesVendorQuotations.rejectionReason,
// 날짜 정보
diff --git a/lib/techsales-rfq/service.ts b/lib/techsales-rfq/service.ts index 44537876..afbd2f55 100644 --- a/lib/techsales-rfq/service.ts +++ b/lib/techsales-rfq/service.ts @@ -33,6 +33,7 @@ import { getServerSession } from "next-auth/next"; import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { sendEmail } from "../mail/sendEmail";
import { formatDate } from "../utils";
+import { itemShipbuilding, itemOffshoreTop, itemOffshoreHull } from "@/db/schema/items";
import { techVendors, techVendorPossibleItems, techVendorContacts } from "@/db/schema/techVendors";
import { deleteFile, saveDRMFile, saveFile } from "@/lib/file-stroage";
import { decryptWithServerAction } from "@/components/drm/drmUtils";
@@ -101,22 +102,26 @@ export async function getTechSalesRfqsWithJoin(input: GetTechSalesRfqsSchema & { try {
// 마감일이 지났고 아직 Closed가 아닌 RFQ를 일괄 Closed로 변경
await db.update(techSalesRfqs)
- .set({ status: "Closed", updatedAt: new Date() })
- .where(
- and(
- lt(techSalesRfqs.dueDate, new Date()),
- ne(techSalesRfqs.status, "Closed")
- )
- );
+ .set({ status: "Closed", updatedAt: new Date() })
+ .where(
+ and(
+ lt(techSalesRfqs.dueDate, new Date()),
+ ne(techSalesRfqs.status, "Closed")
+ )
+ );
const offset = (input.page - 1) * input.perPage;
// 기본 필터 처리 - RFQFilterBox에서 오는 필터
const basicFilters = input.basicFilters || [];
const basicJoinOperator = input.basicJoinOperator || "and";
- // 고급 필터 처리 - 테이블의 DataTableFilterList에서 오는 필터
- const advancedFilters = input.filters || [];
+
+ // 고급 필터 처리 - workTypes을 먼저 제외
+ const advancedFilters = (input.filters || []).filter(f => f.id !== "workTypes");
const advancedJoinOperator = input.joinOperator || "and";
+ // workTypes 필터는 별도로 추출
+ const workTypesFilter = (input.filters || []).find(f => f.id === "workTypes");
+
// 기본 필터 조건 생성
let basicWhere;
if (basicFilters.length > 0) {
@@ -127,7 +132,7 @@ export async function getTechSalesRfqsWithJoin(input: GetTechSalesRfqsSchema & { });
}
- // 고급 필터 조건 생성
+ // 고급 필터 조건 생성 (workTypes 제외)
let advancedWhere;
if (advancedFilters.length > 0) {
advancedWhere = filterColumns({
@@ -149,11 +154,33 @@ export async function getTechSalesRfqsWithJoin(input: GetTechSalesRfqsSchema & { );
}
+ // workTypes 필터 처리 (고급 필터에서 제외된 workTypes만 별도 처리)
+ let workTypesWhere;
+ if (workTypesFilter && Array.isArray(workTypesFilter.value) && workTypesFilter.value.length > 0) {
+ // RFQ 아이템 테이블들과 조인하여 workType이 포함된 RFQ만 추출
+ // (조선, 해양TOP, 해양HULL 모두 포함)
+ const rfqIdsWithWorkTypes = db
+ .selectDistinct({ rfqId: techSalesRfqItems.rfqId })
+ .from(techSalesRfqItems)
+ .leftJoin(itemShipbuilding, eq(techSalesRfqItems.itemShipbuildingId, itemShipbuilding.id))
+ .leftJoin(itemOffshoreTop, eq(techSalesRfqItems.itemOffshoreTopId, itemOffshoreTop.id))
+ .leftJoin(itemOffshoreHull, eq(techSalesRfqItems.itemOffshoreHullId, itemOffshoreHull.id))
+ .where(
+ or(
+ inArray(itemShipbuilding.workType, workTypesFilter.value),
+ inArray(itemOffshoreTop.workType, workTypesFilter.value),
+ inArray(itemOffshoreHull.workType, workTypesFilter.value)
+ )
+ );
+ workTypesWhere = inArray(techSalesRfqs.id, rfqIdsWithWorkTypes);
+ }
+
// 모든 조건 결합
const whereConditions = [];
if (basicWhere) whereConditions.push(basicWhere);
if (advancedWhere) whereConditions.push(advancedWhere);
if (globalWhere) whereConditions.push(globalWhere);
+ if (workTypesWhere) whereConditions.push(workTypesWhere);
// 조건이 있을 때만 and() 사용
const finalWhere = whereConditions.length > 0
@@ -743,13 +770,51 @@ export async function sendTechSalesRfqToVendors(input: { // 5. 담당자별 아이템 매핑 정보 저장 (중복 방지)
for (const item of rfqItems) {
- // tech_vendor_possible_items에서 해당 벤더의 아이템 찾기
- const vendorPossibleItem = await tx.query.techVendorPossibleItems.findFirst({
- where: and(
- eq(techVendorPossibleItems.vendorId, quotation.vendor!.id),
- eq(techVendorPossibleItems.itemCode, item.itemCode || '')
- )
- });
+ let vendorPossibleItem = null;
+ // 조선: 아이템코드 + 선종으로 조선아이템테이블에서 찾기, 해양: 아이템코드로만 찾기
+ if (item.itemType === "SHIP" && item.itemCode && item.shipTypes) {
+ // 조선: itemShipbuilding에서 itemCode, shipTypes로 찾기
+ const shipbuildingItem = await tx.query.itemShipbuilding.findFirst({
+ where: and(
+ eq(itemShipbuilding.itemCode, item.itemCode),
+ eq(itemShipbuilding.shipTypes, item.shipTypes)
+ )
+ });
+ if (shipbuildingItem?.id) {
+ vendorPossibleItem = await tx.query.techVendorPossibleItems.findFirst({
+ where: and(
+ eq(techVendorPossibleItems.vendorId, quotation.vendor!.id),
+ eq(techVendorPossibleItems.shipbuildingItemId, shipbuildingItem.id)
+ )
+ });
+ }
+ } else if (item.itemType === "TOP" && item.itemCode) {
+ // 해양 TOP: itemOffshoreTop에서 itemCode로 찾기
+ const offshoreTopItem = await tx.query.itemOffshoreTop.findFirst({
+ where: eq(itemOffshoreTop.itemCode, item.itemCode)
+ });
+ if (offshoreTopItem?.id) {
+ vendorPossibleItem = await tx.query.techVendorPossibleItems.findFirst({
+ where: and(
+ eq(techVendorPossibleItems.vendorId, quotation.vendor!.id),
+ eq(techVendorPossibleItems.offshoreTopItemId, offshoreTopItem.id)
+ )
+ });
+ }
+ } else if (item.itemType === "HULL" && item.itemCode) {
+ // 해양 HULL: itemOffshoreHull에서 itemCode로 찾기
+ const offshoreHullItem = await tx.query.itemOffshoreHull.findFirst({
+ where: eq(itemOffshoreHull.itemCode, item.itemCode)
+ });
+ if (offshoreHullItem?.id) {
+ vendorPossibleItem = await tx.query.techVendorPossibleItems.findFirst({
+ where: and(
+ eq(techVendorPossibleItems.vendorId, quotation.vendor!.id),
+ eq(techVendorPossibleItems.offshoreHullItemId, offshoreHullItem.id)
+ )
+ });
+ }
+ }
if (vendorPossibleItem) {
// contact_possible_items 중복 체크
@@ -2665,75 +2730,157 @@ export async function getTechSalesRfqCandidateVendors(rfqId: number) { return { data: [], error: null };
}
- // 3. 아이템 코드들 추출
- const itemCodes: string[] = [];
+ // 3. 아이템 ID들 추출 (타입별로)
+ const shipItemIds: number[] = [];
+ const topItemIds: number[] = [];
+ const hullItemIds: number[] = [];
+
rfqItems.forEach(item => {
- if (item.itemType === "SHIP" && item.itemShipbuilding?.itemCode) {
- itemCodes.push(item.itemShipbuilding.itemCode);
- } else if (item.itemType === "TOP" && item.itemOffshoreTop?.itemCode) {
- itemCodes.push(item.itemOffshoreTop.itemCode);
- } else if (item.itemType === "HULL" && item.itemOffshoreHull?.itemCode) {
- itemCodes.push(item.itemOffshoreHull.itemCode);
+ if (item.itemType === "SHIP" && item.itemShipbuilding?.id) {
+ shipItemIds.push(item.itemShipbuilding.id);
+ } else if (item.itemType === "TOP" && item.itemOffshoreTop?.id) {
+ topItemIds.push(item.itemOffshoreTop.id);
+ } else if (item.itemType === "HULL" && item.itemOffshoreHull?.id) {
+ hullItemIds.push(item.itemOffshoreHull.id);
}
});
- if (itemCodes.length === 0) {
+ if (shipItemIds.length === 0 && topItemIds.length === 0 && hullItemIds.length === 0) {
return { data: [], error: null };
}
- // 4. RFQ 타입에 따른 벤더 타입 매핑
- const vendorTypeFilter = rfq.rfqType === "SHIP" ? "SHIP" :
- rfq.rfqType === "TOP" ? "OFFSHORE_TOP" :
- rfq.rfqType === "HULL" ? "OFFSHORE_HULL" : null;
+ // 4. 각 타입별로 매칭되는 벤더들 조회
+ const candidateVendorsMap = new Map();
+
+ // 조선 아이템 매칭 벤더들
+ if (shipItemIds.length > 0) {
+ const shipVendors = await tx
+ .select({
+ id: techVendors.id,
+ vendorId: techVendors.id,
+ vendorName: techVendors.vendorName,
+ vendorCode: techVendors.vendorCode,
+ country: techVendors.country,
+ email: techVendors.email,
+ phone: techVendors.phone,
+ status: techVendors.status,
+ techVendorType: techVendors.techVendorType,
+ matchedItemCode: itemShipbuilding.itemCode,
+ })
+ .from(techVendorPossibleItems)
+ .innerJoin(techVendors, eq(techVendorPossibleItems.vendorId, techVendors.id))
+ .innerJoin(itemShipbuilding, eq(techVendorPossibleItems.shipbuildingItemId, itemShipbuilding.id))
+ .where(
+ and(
+ inArray(techVendorPossibleItems.shipbuildingItemId, shipItemIds),
+ or(
+ eq(techVendors.status, "ACTIVE"),
+ eq(techVendors.status, "QUOTE_COMPARISON")
+ )
+ )
+ );
+
+ shipVendors.forEach(vendor => {
+ const key = vendor.vendorId;
+ if (!candidateVendorsMap.has(key)) {
+ candidateVendorsMap.set(key, {
+ ...vendor,
+ matchedItemCodes: [],
+ matchedItemCount: 0
+ });
+ }
+ candidateVendorsMap.get(key).matchedItemCodes.push(vendor.matchedItemCode);
+ candidateVendorsMap.get(key).matchedItemCount++;
+ });
+ }
+
+ // 해양 TOP 아이템 매칭 벤더들
+ if (topItemIds.length > 0) {
+ const topVendors = await tx
+ .select({
+ id: techVendors.id,
+ vendorId: techVendors.id,
+ vendorName: techVendors.vendorName,
+ vendorCode: techVendors.vendorCode,
+ country: techVendors.country,
+ email: techVendors.email,
+ phone: techVendors.phone,
+ status: techVendors.status,
+ techVendorType: techVendors.techVendorType,
+ matchedItemCode: itemOffshoreTop.itemCode,
+ })
+ .from(techVendorPossibleItems)
+ .innerJoin(techVendors, eq(techVendorPossibleItems.vendorId, techVendors.id))
+ .innerJoin(itemOffshoreTop, eq(techVendorPossibleItems.offshoreTopItemId, itemOffshoreTop.id))
+ .where(
+ and(
+ inArray(techVendorPossibleItems.offshoreTopItemId, topItemIds),
+ or(
+ eq(techVendors.status, "ACTIVE"),
+ eq(techVendors.status, "QUOTE_COMPARISON")
+ )
+ )
+ );
- if (!vendorTypeFilter) {
- return { data: [], error: "지원되지 않는 RFQ 타입입니다." };
+ topVendors.forEach(vendor => {
+ const key = vendor.vendorId;
+ if (!candidateVendorsMap.has(key)) {
+ candidateVendorsMap.set(key, {
+ ...vendor,
+ matchedItemCodes: [],
+ matchedItemCount: 0
+ });
+ }
+ candidateVendorsMap.get(key).matchedItemCodes.push(vendor.matchedItemCode);
+ candidateVendorsMap.get(key).matchedItemCount++;
+ });
}
- // 5. 매칭되는 벤더들 조회 (타입 필터링 포함)
- const candidateVendors = await tx
- .select({
- id: techVendors.id, // 벤더 ID를 id로 명명하여 key 문제 해결
- vendorId: techVendors.id, // 호환성을 위해 유지
- vendorName: techVendors.vendorName,
- vendorCode: techVendors.vendorCode,
- country: techVendors.country,
- email: techVendors.email,
- phone: techVendors.phone,
- status: techVendors.status,
- techVendorType: techVendors.techVendorType,
- matchedItemCodes: sql<string[]>`
- array_agg(DISTINCT ${techVendorPossibleItems.itemCode})
- `,
- matchedItemCount: sql<number>`
- count(DISTINCT ${techVendorPossibleItems.itemCode})
- `,
- })
- .from(techVendorPossibleItems)
- .innerJoin(techVendors, eq(techVendorPossibleItems.vendorId, techVendors.id))
- .where(
- and(
- inArray(techVendorPossibleItems.itemCode, itemCodes),
- or(
- eq(techVendors.status, "ACTIVE"),
- eq(techVendors.status, "QUOTE_COMPARISON") // 견적비교용 벤더도 RFQ 초대 가능
+ // 해양 HULL 아이템 매칭 벤더들
+ if (hullItemIds.length > 0) {
+ const hullVendors = await tx
+ .select({
+ id: techVendors.id,
+ vendorId: techVendors.id,
+ vendorName: techVendors.vendorName,
+ vendorCode: techVendors.vendorCode,
+ country: techVendors.country,
+ email: techVendors.email,
+ phone: techVendors.phone,
+ status: techVendors.status,
+ techVendorType: techVendors.techVendorType,
+ matchedItemCode: itemOffshoreHull.itemCode,
+ })
+ .from(techVendorPossibleItems)
+ .innerJoin(techVendors, eq(techVendorPossibleItems.vendorId, techVendors.id))
+ .innerJoin(itemOffshoreHull, eq(techVendorPossibleItems.offshoreHullItemId, itemOffshoreHull.id))
+ .where(
+ and(
+ inArray(techVendorPossibleItems.offshoreHullItemId, hullItemIds),
+ or(
+ eq(techVendors.status, "ACTIVE"),
+ eq(techVendors.status, "QUOTE_COMPARISON")
+ )
)
- // 벤더 타입 필터링 임시 제거 - 데이터 확인 후 다시 추가
- // eq(techVendors.techVendorType, vendorTypeFilter)
- )
- )
- .groupBy(
- techVendorPossibleItems.vendorId,
- techVendors.id,
- techVendors.vendorName,
- techVendors.vendorCode,
- techVendors.country,
- techVendors.email,
- techVendors.phone,
- techVendors.status,
- techVendors.techVendorType
- )
- .orderBy(desc(sql`count(DISTINCT ${techVendorPossibleItems.itemCode})`));
+ );
+
+ hullVendors.forEach(vendor => {
+ const key = vendor.vendorId;
+ if (!candidateVendorsMap.has(key)) {
+ candidateVendorsMap.set(key, {
+ ...vendor,
+ matchedItemCodes: [],
+ matchedItemCount: 0
+ });
+ }
+ candidateVendorsMap.get(key).matchedItemCodes.push(vendor.matchedItemCode);
+ candidateVendorsMap.get(key).matchedItemCount++;
+ });
+ }
+
+ // 5. 결과 정렬 (매칭된 아이템 수 기준 내림차순)
+ const candidateVendors = Array.from(candidateVendorsMap.values())
+ .sort((a, b) => b.matchedItemCount - a.matchedItemCount);
return { data: candidateVendors, error: null };
});
@@ -2830,44 +2977,78 @@ export async function addTechVendorsToTechSalesRfq(input: { })
.returning({ id: techSalesVendorQuotations.id });
- // 🆕 RFQ의 아이템 코드들을 tech_vendor_possible_items에 추가
+ // 🆕 RFQ의 아이템들을 tech_vendor_possible_items에 추가
try {
// RFQ의 아이템들 조회
const rfqItemsResult = await getTechSalesRfqItems(input.rfqId);
if (rfqItemsResult.data && rfqItemsResult.data.length > 0) {
for (const item of rfqItemsResult.data) {
- const {
- itemCode,
- itemList,
- workType, // 공종
- shipTypes, // 선종 (배열일 수 있음)
- subItemList // 서브아이템리스트 (있을 수도 있음)
- } = item;
-
- // 동적 where 조건 생성: 값이 있으면 비교, 없으면 비교하지 않음
- const whereConds = [
- eq(techVendorPossibleItems.vendorId, vendorId),
- itemCode ? eq(techVendorPossibleItems.itemCode, itemCode) : undefined,
- itemList ? eq(techVendorPossibleItems.itemList, itemList) : undefined,
- workType ? eq(techVendorPossibleItems.workType, workType) : undefined,
- shipTypes ? eq(techVendorPossibleItems.shipTypes, shipTypes) : undefined,
- subItemList ? eq(techVendorPossibleItems.subItemList, subItemList) : undefined,
- ].filter(Boolean);
-
- const existing = await tx.query.techVendorPossibleItems.findFirst({
- where: and(...whereConds)
- });
-
- if (!existing) {
- await tx.insert(techVendorPossibleItems).values({
- vendorId : vendorId,
- itemCode: itemCode ?? null,
- itemList: itemList ?? null,
- workType: workType ?? null,
- shipTypes: shipTypes ?? null,
- subItemList: subItemList ?? null,
+ let vendorPossibleItem = null;
+ // 조선: 아이템코드 + 선종으로 조선아이템테이블에서 찾기, 해양: 아이템코드로만 찾기
+ if (item.itemType === "SHIP" && item.itemCode && item.shipTypes) {
+ // 조선: itemShipbuilding에서 itemCode, shipTypes로 찾기
+ const shipbuildingItem = await tx.query.itemShipbuilding.findFirst({
+ where: and(
+ eq(itemShipbuilding.itemCode, item.itemCode),
+ eq(itemShipbuilding.shipTypes, item.shipTypes)
+ )
});
+ if (shipbuildingItem?.id) {
+ vendorPossibleItem = await tx.query.techVendorPossibleItems.findFirst({
+ where: and(
+ eq(techVendorPossibleItems.vendorId, vendorId),
+ eq(techVendorPossibleItems.shipbuildingItemId, shipbuildingItem.id)
+ )
+ });
+
+ if (!vendorPossibleItem) {
+ await tx.insert(techVendorPossibleItems).values({
+ vendorId: vendorId,
+ shipbuildingItemId: shipbuildingItem.id,
+ });
+ }
+ }
+ } else if (item.itemType === "TOP" && item.itemCode) {
+ // 해양 TOP: itemOffshoreTop에서 itemCode로 찾기
+ const offshoreTopItem = await tx.query.itemOffshoreTop.findFirst({
+ where: eq(itemOffshoreTop.itemCode, item.itemCode)
+ });
+ if (offshoreTopItem?.id) {
+ vendorPossibleItem = await tx.query.techVendorPossibleItems.findFirst({
+ where: and(
+ eq(techVendorPossibleItems.vendorId, vendorId),
+ eq(techVendorPossibleItems.offshoreTopItemId, offshoreTopItem.id)
+ )
+ });
+
+ if (!vendorPossibleItem) {
+ await tx.insert(techVendorPossibleItems).values({
+ vendorId: vendorId,
+ offshoreTopItemId: offshoreTopItem.id,
+ });
+ }
+ }
+ } else if (item.itemType === "HULL" && item.itemCode) {
+ // 해양 HULL: itemOffshoreHull에서 itemCode로 찾기
+ const offshoreHullItem = await tx.query.itemOffshoreHull.findFirst({
+ where: eq(itemOffshoreHull.itemCode, item.itemCode)
+ });
+ if (offshoreHullItem?.id) {
+ vendorPossibleItem = await tx.query.techVendorPossibleItems.findFirst({
+ where: and(
+ eq(techVendorPossibleItems.vendorId, vendorId),
+ eq(techVendorPossibleItems.offshoreHullItemId, offshoreHullItem.id)
+ )
+ });
+
+ if (!vendorPossibleItem) {
+ await tx.insert(techVendorPossibleItems).values({
+ vendorId: vendorId,
+ offshoreHullItemId: offshoreHullItem.id,
+ });
+ }
+ }
}
}
}
@@ -3368,11 +3549,6 @@ export async function getAcceptedTechSalesVendorQuotations(input: { const offset = (input.page - 1) * input.perPage;
// 기본 WHERE 조건: status = 'Accepted'만 조회, rfqType이 'SHIP'이 아닌 것만
- // const baseConditions = [
- // eq(techSalesVendorQuotations.status, 'Accepted'),
- // sql`${techSalesRfqs.rfqType} != 'SHIP'` // 조선 RFQ 타입 제외
- // ];
- // 기본 WHERE 조건: status = 'Accepted'만 조회, rfqType이 'SHIP'이 아닌 것만
const baseConditions = [or(
eq(techSalesVendorQuotations.status, 'Submitted'),
eq(techSalesVendorQuotations.status, 'Accepted')
@@ -3566,6 +3742,7 @@ export async function getTechVendorsContacts(vendorIds: number[]) { contactId: techVendorContacts.id,
contactName: techVendorContacts.contactName,
contactPosition: techVendorContacts.contactPosition,
+ contactTitle: techVendorContacts.contactTitle,
contactEmail: techVendorContacts.contactEmail,
contactPhone: techVendorContacts.contactPhone,
isPrimary: techVendorContacts.isPrimary,
@@ -3599,6 +3776,7 @@ export async function getTechVendorsContacts(vendorIds: number[]) { id: row.contactId,
contactName: row.contactName,
contactPosition: row.contactPosition,
+ contactTitle: row.contactTitle,
contactEmail: row.contactEmail,
contactPhone: row.contactPhone,
isPrimary: row.isPrimary
@@ -3614,6 +3792,7 @@ export async function getTechVendorsContacts(vendorIds: number[]) { id: number;
contactName: string;
contactPosition: string | null;
+ contactTitle: string | null;
contactEmail: string;
contactPhone: string | null;
isPrimary: boolean;
@@ -3710,4 +3889,96 @@ export async function uploadQuotationAttachments( error: error instanceof Error ? error.message : '파일 업로드 중 오류가 발생했습니다.'
};
}
+}
+
+/**
+ * Update SHI Comment (revisionNote) for the current revision of a quotation.
+ * Only the revisionNote is updated in the tech_sales_vendor_quotation_revisions table.
+ */
+export async function updateSHIComment(revisionId: number, revisionNote: string) {
+ try {
+ const updatedRevision = await db
+ .update(techSalesVendorQuotationRevisions)
+ .set({
+ revisionNote: revisionNote,
+ })
+ .where(eq(techSalesVendorQuotationRevisions.id, revisionId))
+ .returning();
+
+ if (updatedRevision.length === 0) {
+ return { data: null, error: "revision을 업데이트할 수 없습니다." };
+ }
+
+ return { data: updatedRevision[0], error: null };
+ } catch (error) {
+ console.error("SHI Comment 업데이트 중 오류:", error);
+ return { data: null, error: "SHI Comment 업데이트 중 오류가 발생했습니다." };
+ }
+}
+
+// RFQ 단일 조회 함수 추가
+export async function getTechSalesRfqById(id: number) {
+ try {
+ const rfq = await db.query.techSalesRfqs.findFirst({
+ where: eq(techSalesRfqs.id, id),
+ });
+ const project = await db
+ .select({
+ id: biddingProjects.id,
+ projectCode: biddingProjects.pspid,
+ projectName: biddingProjects.projNm,
+ pjtType: biddingProjects.pjtType,
+ ptypeNm: biddingProjects.ptypeNm,
+ projMsrm: biddingProjects.projMsrm,
+ })
+ .from(biddingProjects)
+ .where(eq(biddingProjects.id, rfq?.biddingProjectId ?? 0));
+
+ if (!rfq) {
+ return { data: null, error: "RFQ를 찾을 수 없습니다." };
+ }
+
+ return { data: { ...rfq, project }, error: null };
+ } catch (err) {
+ console.error("Error fetching RFQ:", err);
+ return { data: null, error: getErrorMessage(err) };
+ }
+}
+
+// RFQ 업데이트 함수 수정 (description으로 통일)
+export async function updateTechSalesRfq(data: {
+ id: number;
+ description: string;
+ dueDate: Date;
+ updatedBy: number;
+}) {
+ try {
+ return await db.transaction(async (tx) => {
+ const rfq = await tx.query.techSalesRfqs.findFirst({
+ where: eq(techSalesRfqs.id, data.id),
+ });
+
+ if (!rfq) {
+ return { data: null, error: "RFQ를 찾을 수 없습니다." };
+ }
+
+ const [updatedRfq] = await tx
+ .update(techSalesRfqs)
+ .set({
+ description: data.description, // description 필드로 업데이트
+ dueDate: data.dueDate,
+ updatedAt: new Date(),
+ })
+ .where(eq(techSalesRfqs.id, data.id))
+ .returning();
+
+ revalidateTag("techSalesRfqs");
+ revalidatePath(getTechSalesRevalidationPath(rfq.rfqType || "SHIP"));
+
+ return { data: updatedRfq, error: null };
+ });
+ } catch (err) {
+ console.error("Error updating RFQ:", err);
+ return { data: null, error: getErrorMessage(err) };
+ }
}
\ No newline at end of file diff --git a/lib/techsales-rfq/table/detail-table/quotation-contacts-view-dialog.tsx b/lib/techsales-rfq/table/detail-table/quotation-contacts-view-dialog.tsx index 3e793b62..61c97b1b 100644 --- a/lib/techsales-rfq/table/detail-table/quotation-contacts-view-dialog.tsx +++ b/lib/techsales-rfq/table/detail-table/quotation-contacts-view-dialog.tsx @@ -20,6 +20,7 @@ interface QuotationContact { contactId: number
contactName: string
contactPosition: string | null
+ contactTitle: string | null
contactEmail: string
contactPhone: string | null
contactCountry: string | null
@@ -129,6 +130,11 @@ export function QuotationContactsViewDialog({ {contact.contactPosition}
</p>
)}
+ {contact.contactTitle && (
+ <p className="text-sm text-muted-foreground">
+ {contact.contactTitle}
+ </p>
+ )}
{contact.contactCountry && (
<p className="text-xs text-muted-foreground">
{contact.contactCountry}
diff --git a/lib/techsales-rfq/table/detail-table/quotation-history-dialog.tsx b/lib/techsales-rfq/table/detail-table/quotation-history-dialog.tsx index 0f5158d9..7d972b91 100644 --- a/lib/techsales-rfq/table/detail-table/quotation-history-dialog.tsx +++ b/lib/techsales-rfq/table/detail-table/quotation-history-dialog.tsx @@ -1,5 +1,4 @@ "use client"
-
import * as React from "react"
import { useState, useEffect } from "react"
import {
@@ -16,6 +15,8 @@ import { Skeleton } from "@/components/ui/skeleton" import { Clock, User, AlertCircle, Paperclip } from "lucide-react"
import { formatDate } from "@/lib/utils"
import { toast } from "sonner"
+import { Button } from "@/components/ui/button"
+import { updateSHIComment } from "@/lib/techsales-rfq/service";
interface QuotationAttachment {
id: number
@@ -37,7 +38,7 @@ interface QuotationSnapshot { totalPrice: string | null
validUntil: Date | null
remark: string | null
- status: string | null
+ status: string
quotationVersion: number | null
submittedAt: Date | null
acceptedAt: Date | null
@@ -93,7 +94,9 @@ function QuotationCard({ isCurrent = false,
revisedBy,
revisedAt,
- attachments
+ attachments,
+ revisionId,
+ revisionNote,
}: {
data: QuotationSnapshot | QuotationHistoryData["current"]
version: number
@@ -101,9 +104,36 @@ function QuotationCard({ revisedBy?: string | null
revisedAt?: Date
attachments?: QuotationAttachment[]
+ revisionId?: number
+ revisionNote?: string | null
}) {
const statusInfo = statusConfig[data.status as keyof typeof statusConfig] ||
{ label: data.status || "알 수 없음", color: "bg-gray-100 text-gray-800" }
+
+ const [editValue, setEditValue] = React.useState(revisionNote || "");
+ const [isSaving, setIsSaving] = React.useState(false);
+
+ React.useEffect(() => {
+ setEditValue(revisionNote || "");
+ }, [revisionNote]);
+
+ const handleSave = async () => {
+ if (!revisionId) return;
+
+ setIsSaving(true);
+ try {
+ const result = await updateSHIComment(revisionId, editValue);
+ if (result.error) {
+ toast.error(result.error);
+ } else {
+ toast.success("저장 완료");
+ }
+ } catch (error) {
+ toast.error("저장 중 오류가 발생했습니다");
+ } finally {
+ setIsSaving(false);
+ }
+ };
return (
<Card className={`${isCurrent ? "border-blue-500 shadow-md" : "border-gray-200"}`}>
@@ -117,12 +147,6 @@ function QuotationCard({ {statusInfo.label}
</Badge>
</div>
- {/* {changeReason && (
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
- <FileText className="size-4" />
- <span>{changeReason}</span>
- </div>
- )} */}
</CardHeader>
<CardContent className="space-y-3">
<div className="grid grid-cols-2 gap-4">
@@ -147,6 +171,21 @@ function QuotationCard({ </div>
)}
+ {revisionId && (
+ <div>
+ <p className="text-sm font-medium text-muted-foreground mt-2">SHI Comment</p>
+ <textarea
+ className="w-full min-h-[60px] p-2 border rounded bg-gray-50 text-sm"
+ value={editValue}
+ onChange={e => setEditValue(e.target.value)}
+ disabled={isSaving}
+ />
+ <Button size="sm" onClick={handleSave} disabled={isSaving} className="mt-2">
+ 저장
+ </Button>
+ </div>
+)}
+
{/* 첨부파일 섹션 */}
{attachments && attachments.length > 0 && (
<div>
@@ -209,16 +248,15 @@ export function QuotationHistoryDialog({ }: QuotationHistoryDialogProps) {
const [data, setData] = useState<QuotationHistoryData | null>(null)
const [isLoading, setIsLoading] = useState(false)
-
+
useEffect(() => {
if (open && quotationId) {
loadQuotationHistory()
}
}, [open, quotationId])
-
+
const loadQuotationHistory = async () => {
if (!quotationId) return
-
try {
setIsLoading(true)
const { getTechSalesVendorQuotationWithRevisions } = await import("@/lib/techsales-rfq/service")
@@ -238,14 +276,14 @@ export function QuotationHistoryDialog({ setIsLoading(false)
}
}
-
+
const handleOpenChange = (newOpen: boolean) => {
onOpenChange(newOpen)
if (!newOpen) {
setData(null) // 다이얼로그 닫을 때 데이터 초기화
}
}
-
+
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="w-[80vw] max-h-[90vh] overflow-y-auto">
@@ -257,54 +295,55 @@ export function QuotationHistoryDialog({ </DialogHeader>
<div className="space-y-4 overflow-x-auto">
- {isLoading ? (
- <div className="space-y-4">
- {[1, 2, 3].map((i) => (
- <div key={i} className="space-y-3">
- <Skeleton className="h-6 w-32" />
- <Skeleton className="h-32 w-full" />
- </div>
- ))}
- </div>
- ) : data ? (
- <>
- {/* 현재 버전 */}
- <QuotationCard
- data={data.current}
- version={data.current.quotationVersion || 1}
- isCurrent={true}
- attachments={data.current.attachments}
- />
-
- {/* 이전 버전들 */}
- {data.revisions.length > 0 ? (
- data.revisions.map((revision) => (
- <QuotationCard
- key={revision.id}
- data={revision.snapshot}
- version={revision.version}
- changeReason={revision.changeReason}
- revisedBy={revision.revisedByName}
- revisedAt={revision.revisedAt}
- attachments={revision.attachments}
- />
- ))
- ) : (
- <div className="text-center py-8 text-muted-foreground">
- <AlertCircle className="size-12 mx-auto mb-2 opacity-50" />
- <p>수정 이력이 없습니다.</p>
- <p className="text-sm">이 견적서는 아직 수정되지 않았습니다.</p>
- </div>
- )}
- </>
- ) : (
- <div className="text-center py-8 text-muted-foreground">
- <AlertCircle className="size-12 mx-auto mb-2 opacity-50" />
- <p>견적서 정보를 불러올 수 없습니다.</p>
- </div>
- )}
- </div>
+ {isLoading ? (
+ <div className="space-y-4">
+ {[1, 2, 3].map((i) => (
+ <div key={i} className="space-y-3">
+ <Skeleton className="h-6 w-32" />
+ <Skeleton className="h-32 w-full" />
+ </div>
+ ))}
+ </div>
+ ) : data ? (
+ <>
+ {/* 현재 버전 - SHI Comment 없이 표시 */}
+ <QuotationCard
+ data={data.current}
+ version={data.current.quotationVersion || 1}
+ isCurrent={true}
+ attachments={data.current.attachments}
+ />
+
+ {/* 이전 버전들 (스냅샷) - SHI Comment 포함 */}
+ {data.revisions.length > 0 ? (
+ data.revisions.map((revision) => (
+ <QuotationCard
+ key={revision.id}
+ data={revision.snapshot}
+ version={revision.version}
+ revisedBy={revision.revisedByName}
+ revisedAt={revision.revisedAt}
+ attachments={revision.attachments}
+ revisionId={revision.id}
+ revisionNote={revision.revisionNote}
+ />
+ ))
+ ) : (
+ <div className="text-center py-8 text-muted-foreground">
+ <AlertCircle className="size-12 mx-auto mb-2 opacity-50" />
+ <p>수정 이력이 없습니다.</p>
+ <p className="text-sm">이 견적서는 아직 수정되지 않았습니다.</p>
+ </div>
+ )}
+ </>
+ ) : (
+ <div className="text-center py-8 text-muted-foreground">
+ <AlertCircle className="size-12 mx-auto mb-2 opacity-50" />
+ <p>견적서 정보를 불러올 수 없습니다.</p>
+ </div>
+ )}
+ </div>
</DialogContent>
</Dialog>
)
-}
\ No newline at end of file +}
\ No newline at end of file diff --git a/lib/techsales-rfq/table/detail-table/rfq-detail-column.tsx b/lib/techsales-rfq/table/detail-table/rfq-detail-column.tsx index e4141520..7ece2406 100644 --- a/lib/techsales-rfq/table/detail-table/rfq-detail-column.tsx +++ b/lib/techsales-rfq/table/detail-table/rfq-detail-column.tsx @@ -46,6 +46,7 @@ export interface RfqDetailView { createdByName: string | null
quotationCode?: string | null
rfqCode?: string | null
+ quotationVersion?: number | null
quotationAttachments?: Array<{
id: number
revisionId: number
@@ -185,6 +186,22 @@ export function getRfqDetailColumns({ enableResizing: true,
size: 160,
},
+ // [Rev 컬럼 추가]
+ {
+ id: "rev",
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="Rev" />
+ ),
+ cell: ({ row }) => {
+ const version = row.original.quotationVersion ?? 0;
+ return <div className="text-center font-mono">{version}</div>;
+ },
+ meta: {
+ excelHeader: "Rev"
+ },
+ enableResizing: false,
+ size: 60,
+ },
{
accessorKey: "totalPrice",
header: ({ column }) => (
@@ -227,6 +244,7 @@ export function getRfqDetailColumns({ enableResizing: true,
size: 140,
},
+
{
accessorKey: "quotationAttachments",
header: ({ column }) => (
diff --git a/lib/techsales-rfq/table/detail-table/rfq-detail-table.tsx b/lib/techsales-rfq/table/detail-table/rfq-detail-table.tsx index acf67497..8bfb8299 100644 --- a/lib/techsales-rfq/table/detail-table/rfq-detail-table.tsx +++ b/lib/techsales-rfq/table/detail-table/rfq-detail-table.tsx @@ -730,8 +730,8 @@ export function RfqDetailTables({ selectedRfq, maxHeight }: RfqDetailTablesProps onSuccess={handleRefreshData}
/>
- {/* 다중 벤더 삭제 확인 다이얼로그
- <DeleteVendorDialog
+ {/* 다중 벤더 삭제 확인 다이얼로그 */}
+ {/* <DeleteVendorDialog
open={deleteConfirmDialogOpen}
onOpenChange={setDeleteConfirmDialogOpen}
vendors={selectedRows}
diff --git a/lib/techsales-rfq/table/detail-table/vendor-communication-drawer.tsx b/lib/techsales-rfq/table/detail-table/vendor-communication-drawer.tsx index e6cd32a9..5b60ef0f 100644 --- a/lib/techsales-rfq/table/detail-table/vendor-communication-drawer.tsx +++ b/lib/techsales-rfq/table/detail-table/vendor-communication-drawer.tsx @@ -320,9 +320,9 @@ export function VendorCommunicationDrawer({ };
// 첨부파일 다운로드
- const handleAttachmentDownload = async (attachment: Attachment) => {
- const { downloadFile } = await import("@/lib/file-download");
- await downloadFile(attachment.filePath, attachment.originalFileName);
+ const handleAttachmentDownload = (attachment: Attachment) => {
+ // TODO: 실제 다운로드 구현
+ window.open(attachment.filePath, '_blank');
};
// 파일 아이콘 선택
diff --git a/lib/techsales-rfq/table/detail-table/vendor-contact-selection-dialog.tsx b/lib/techsales-rfq/table/detail-table/vendor-contact-selection-dialog.tsx index aa6f6c2f..031f4aa2 100644 --- a/lib/techsales-rfq/table/detail-table/vendor-contact-selection-dialog.tsx +++ b/lib/techsales-rfq/table/detail-table/vendor-contact-selection-dialog.tsx @@ -21,6 +21,7 @@ interface VendorContact { id: number
contactName: string
contactPosition: string | null
+ contactTitle: string | null
contactEmail: string
contactPhone: string | null
isPrimary: boolean
@@ -283,6 +284,11 @@ export function VendorContactSelectionDialog({ {contact.contactPosition}
</p>
)}
+ {contact.contactTitle && (
+ <p className="text-sm text-muted-foreground">
+ {contact.contactTitle}
+ </p>
+ )}
</div>
</div>
</div>
diff --git a/lib/techsales-rfq/table/rfq-filter-sheet.tsx b/lib/techsales-rfq/table/rfq-filter-sheet.tsx index a03e6167..7db8305d 100644 --- a/lib/techsales-rfq/table/rfq-filter-sheet.tsx +++ b/lib/techsales-rfq/table/rfq-filter-sheet.tsx @@ -48,7 +48,32 @@ const filterSchema = z.object({ from: z.date().optional(),
to: z.date().optional(),
}).optional(),
+ workTypes: z.array(z.string()).optional(),
})
+// 공종 옵션 정의 (tech-vendors와 동일)
+const workTypeOptions = [
+ // 조선 workTypes
+ { value: "기장", label: "기장" },
+ { value: "전장", label: "전장" },
+ { value: "선실", label: "선실" },
+ { value: "배관", label: "배관" },
+ { value: "철의", label: "철의" },
+ { value: "선체", label: "선체" },
+ // 해양TOP workTypes
+ { value: "TM", label: "TM" },
+ { value: "TS", label: "TS" },
+ { value: "TE", label: "TE" },
+ { value: "TP", label: "TP" },
+ { value: "TA", label: "TA" },
+ // 해양HULL workTypes
+ { value: "HA", label: "HA" },
+ { value: "HE", label: "HE" },
+ { value: "HH", label: "HH" },
+ { value: "HM", label: "HM" },
+ { value: "NC", label: "NC" },
+ { value: "HO", label: "HO" },
+ { value: "HP", label: "HP" },
+];
// 상태 옵션 정의 (TechSales RFQ 상태에 맞게 수정)
const statusOptions = [
@@ -89,13 +114,13 @@ export function RFQFilterSheet({ // nuqs로 URL 상태 관리 - 파라미터명을 'basicFilters'로 변경
const [filters, setFilters] = useQueryState(
- "basicFilters",
+ "filters",
getFiltersStateParser().withDefault([])
)
// joinOperator 설정
const [joinOperator, setJoinOperator] = useQueryState(
- "basicJoinOperator",
+ "joinOperator",
parseAsStringEnum(["and", "or"]).withDefault("and")
)
@@ -118,6 +143,7 @@ export function RFQFilterSheet({ from: undefined,
to: undefined,
},
+ workTypes: [],
},
})
@@ -274,6 +300,16 @@ export function RFQFilterSheet({ })
}
+ if (data.workTypes && data.workTypes.length > 0) {
+ newFilters.push({
+ id: "workTypes",
+ value: data.workTypes,
+ type: "multi-select" as const,
+ operator: "eq" as const,
+ rowId: generateId()
+ })
+ }
+
console.log("기본 필터 적용:", newFilters);
// 마지막 적용된 필터 업데이트
@@ -313,6 +349,7 @@ export function RFQFilterSheet({ createdByName: "",
status: "",
dateRange: { from: undefined, to: undefined },
+ workTypes: [],
});
// 필터와 조인 연산자를 초기화
@@ -446,6 +483,7 @@ export function RFQFilterSheet({ </FormItem>
)}
/>
+
{/* 자재명 */}
<FormField
@@ -561,44 +599,6 @@ export function RFQFilterSheet({ )}
/>
- {/* 선종명 */}
- <FormField
- control={form.control}
- name="ptypeNm"
- render={({ field }) => (
- <FormItem>
- <FormLabel>{t("선종명")}</FormLabel>
- <FormControl>
- <div className="relative">
- <Input
- placeholder={t("선종명 입력")}
- {...field}
- className={cn(field.value && "pr-8", "bg-white")}
- disabled={isInitializing}
- />
- {field.value && (
- <Button
- type="button"
- variant="ghost"
- size="icon"
- className="absolute right-0 top-0 h-full px-2"
- onClick={(e) => {
- e.stopPropagation();
- form.setValue("ptypeNm", "");
- }}
- disabled={isInitializing}
- >
- <X className="size-3.5" />
- <span className="sr-only">Clear</span>
- </Button>
- )}
- </div>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
-
{/* 요청자 */}
<FormField
control={form.control}
@@ -685,43 +685,38 @@ export function RFQFilterSheet({ )}
/>
- {/* RFQ 전송일 */}
+ {/* 공종 */}
<FormField
control={form.control}
- name="dateRange"
+ name="workTypes"
render={({ field }) => (
<FormItem>
- <FormLabel>{t("RFQ 전송일")}</FormLabel>
- <FormControl>
- <div className="relative">
- <DateRangePicker
- triggerSize="default"
- triggerClassName="w-full bg-white"
- align="start"
- showClearButton={true}
- placeholder={t("RFQ 전송일 범위를 고르세요")}
- date={field.value || undefined}
- onDateChange={field.onChange}
- disabled={isInitializing}
- />
- {(field.value?.from || field.value?.to) && (
- <Button
- type="button"
- variant="ghost"
- size="icon"
- className="absolute right-10 top-0 h-full px-2"
- onClick={(e) => {
- e.stopPropagation();
- form.setValue("dateRange", { from: undefined, to: undefined });
+ <FormLabel>공종</FormLabel>
+ <div className="grid grid-cols-2 gap-2">
+ {workTypeOptions.map((option) => (
+ <div key={option.value} className="flex items-center space-x-2">
+ <input
+ type="checkbox"
+ id={`workType-${option.value}`}
+ checked={field.value?.includes(option.value) || false}
+ onChange={(e) => {
+ const checked = e.target.checked;
+ const updatedValue = checked
+ ? [...(field.value || []), option.value]
+ : (field.value || []).filter((value) => value !== option.value);
+ field.onChange(updatedValue);
}}
disabled={isInitializing}
+ />
+ <label
+ htmlFor={`workType-${option.value}`}
+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
- <X className="size-3.5" />
- <span className="sr-only">Clear</span>
- </Button>
- )}
- </div>
- </FormControl>
+ {option.label}
+ </label>
+ </div>
+ ))}
+ </div>
<FormMessage />
</FormItem>
)}
diff --git a/lib/techsales-rfq/table/rfq-table-column.tsx b/lib/techsales-rfq/table/rfq-table-column.tsx index f41857cd..2bc5b5b4 100644 --- a/lib/techsales-rfq/table/rfq-table-column.tsx +++ b/lib/techsales-rfq/table/rfq-table-column.tsx @@ -9,6 +9,9 @@ import { DataTableRowAction } from "@/types/table" import { Paperclip, Package, FileText, BarChart3 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { TechSalesRfq } from "./rfq-table"
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
+import { MoreHorizontal } from "lucide-react"
+import { Edit } from "lucide-react"
interface GetColumnsProps {
setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<TechSalesRfq> | null>>;
@@ -409,5 +412,35 @@ export function getColumns({ excelHeader: "CBE 결과"
},
},
+ // getColumns 함수 내 컬럼 배열 마지막에 추가
+{
+ id: "actions",
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="" />
+ ),
+ cell: ({ row }) => {
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-8 w-8 p-0"
+ >
+ <MoreHorizontal className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setRowAction({ row, type: "update" })}>
+ <span>수정하기 </span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+ },
+ enableSorting: false,
+ enableResizing: false,
+ size: 60,
+}
]
}
\ No newline at end of file diff --git a/lib/techsales-rfq/table/rfq-table.tsx b/lib/techsales-rfq/table/rfq-table.tsx index e3551625..e1e511c8 100644 --- a/lib/techsales-rfq/table/rfq-table.tsx +++ b/lib/techsales-rfq/table/rfq-table.tsx @@ -17,7 +17,7 @@ import { import { useDataTable } from "@/hooks/use-data-table"
import { DataTable } from "@/components/data-table/data-table"
import { getColumns } from "./rfq-table-column"
-import { useEffect, useMemo } from "react"
+import { useEffect, useMemo, useState } from "react"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { RFQTableToolbarActions } from "./rfq-table-toolbar-actions"
import { getTechSalesRfqsWithJoin, getTechSalesRfqAttachments } from "@/lib/techsales-rfq/service"
@@ -29,6 +29,7 @@ import { ProjectDetailDialog } from "./project-detail-dialog" import { RFQFilterSheet } from "./rfq-filter-sheet"
import { TechSalesRfqAttachmentsSheet, ExistingTechSalesAttachment } from "./tech-sales-rfq-attachments-sheet"
import { RfqItemsViewDialog } from "./rfq-items-view-dialog"
+import UpdateSheet from "./update-rfq-sheet"
// 기본적인 RFQ 타입 정의 (repository selectTechSalesRfqsWithJoin 반환 타입에 맞춤)
export interface TechSalesRfq {
id: number
@@ -103,7 +104,10 @@ export function RFQListTable({ // 패널 collapse 상태
const [panelHeight, setPanelHeight] = React.useState<number>(55)
-
+ // RFQListTable 컴포넌트 내부의 rowAction 처리 부분 수정
+ const [updateSheetOpen, setUpdateSheetOpen] = useState(false);
+ const [selectedRfqIdForUpdate, setSelectedRfqIdForUpdate] = useState<number | null>(null);
+
// 고정 높이 설정을 위한 상수 (실제 측정값으로 조정 필요)
const LAYOUT_HEADER_HEIGHT = 64 // Layout Header 높이
const LAYOUT_FOOTER_HEIGHT = 60 // Layout Footer 높이 (있다면 실제 값)
@@ -246,8 +250,10 @@ export function RFQListTable({ setIsProjectDetailOpen(true);
break;
case "update":
- console.log("Update rfq:", rowAction.row.original)
- break;
+ // RFQ 수정 시트 열기
+ setSelectedRfqIdForUpdate(rowAction.row.original.id);
+ setUpdateSheetOpen(true);
+ break;
case "delete":
console.log("Delete rfq:", rowAction.row.original)
break;
@@ -391,6 +397,7 @@ export function RFQListTable({ { label: "TS", value: "TS" },
{ label: "TE", value: "TE" },
{ label: "TP", value: "TP" },
+ { label: "TA", value: "TA" },
// 해양HULL workTypes
{ label: "HA", value: "HA" },
{ label: "HE", value: "HE" },
@@ -450,8 +457,6 @@ export function RFQListTable({ }
}
- console.log(panelHeight)
-
return (
<div
className={cn("flex flex-col relative", className)}
@@ -631,6 +636,17 @@ export function RFQListTable({ rfqType: selectedRfqForItems.rfqType
} : null}
/>
+ {updateSheetOpen && selectedRfqIdForUpdate && (
+ <UpdateSheet
+ open={updateSheetOpen}
+ onOpenChange={setUpdateSheetOpen}
+ rfqId={selectedRfqIdForUpdate}
+ onUpdated={() => {
+ // 테이블 새로고침 로직
+ // 필요한 경우 여기에 추가
+ }}
+ />
+ )}
</div>
)
}
\ No newline at end of file diff --git a/lib/techsales-rfq/table/update-rfq-sheet.tsx b/lib/techsales-rfq/table/update-rfq-sheet.tsx new file mode 100644 index 00000000..7dcc0e0e --- /dev/null +++ b/lib/techsales-rfq/table/update-rfq-sheet.tsx @@ -0,0 +1,267 @@ +"use client";
+import * as React from "react";
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { z } from "zod";
+import { format } from "date-fns";
+import { ko } from "date-fns/locale/ko";
+import { toast } from "sonner";
+import { Loader2, CalendarIcon } from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription, SheetFooter, SheetClose } from "@/components/ui/sheet";
+import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
+import { Calendar } from "@/components/ui/calendar";
+import { cn } from "@/lib/utils";
+import { updateTechSalesRfq, getTechSalesRfqById } from "@/lib/techsales-rfq/service";
+
+// Zod schema for form validation
+const updateRfqSchema = z.object({
+ rfqId: z.number().min(1, "RFQ ID is required"),
+ description: z.string(),
+ dueDate: z.string(),
+});
+
+type UpdateRfqSchema = z.infer<typeof updateRfqSchema>;
+
+interface UpdateSheetProps {
+ open: boolean;
+ onOpenChange?: (open: boolean) => void;
+ rfqId: number;
+ onUpdated?: () => void;
+}
+
+export default function UpdateSheet({ open, onOpenChange, rfqId, onUpdated }: UpdateSheetProps) {
+ const [isPending, startTransition] = React.useTransition();
+ const [projectInfo, setProjectInfo] = React.useState({
+ projNm: "",
+ sector: "",
+ projMsrm: "",
+ ptypeNm: "",
+ rfqNo: "",
+ });
+ const [isLoading, setIsLoading] = React.useState(false);
+
+ // Initialize form with React Hook Form and Zod
+ const form = useForm<UpdateRfqSchema>({
+ resolver: zodResolver(updateRfqSchema),
+ defaultValues: {
+ rfqId,
+ description: "",
+ dueDate: "",
+ },
+ });
+
+ // Load RFQ data when sheet opens
+ React.useEffect(() => {
+ if (open && rfqId) {
+ loadRfqData();
+ }
+ }, [open, rfqId]);
+
+ const loadRfqData = async () => {
+ try {
+ setIsLoading(true);
+ const result = await getTechSalesRfqById(rfqId);
+ if (result.error) {
+ toast.error(result.error);
+ onOpenChange?.(false);
+ return;
+ }
+ if (result.data) {
+ form.reset({
+ rfqId,
+ description: result.data.description || "",
+ dueDate: result.data.dueDate ? new Date(result.data.dueDate).toISOString().slice(0, 10) : "",
+ });
+ setProjectInfo({
+ projNm: result.data.project[0].projectName || "",
+ sector: result.data.project[0].pjtType || "",
+ projMsrm: result.data.project[0].projMsrm || "",
+ ptypeNm: result.data.project[0].ptypeNm || "",
+ rfqNo: result.data.rfqCode || "",
+ });
+ }
+ } catch (error: any) {
+ toast.error("RFQ 정보를 불러오는 중 오류가 발생했습니다: " + error.message);
+ onOpenChange?.(false);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ // Form submission handler with debug logs
+ async function onSubmit(values: UpdateRfqSchema) {
+ console.log("Form submitted with values:", values);
+ startTransition(async () => {
+ try {
+ console.log("Submitting RFQ update for ID:", values.rfqId);
+ const result = await updateTechSalesRfq({
+ id: values.rfqId,
+ description: values.description,
+ dueDate: new Date(values.dueDate),
+ updatedBy: 1, // Replace with actual user ID
+ });
+ if (result.error) {
+ console.error("Update error:", result.error);
+ toast.error(result.error);
+ } else {
+ console.log("RFQ updated successfully");
+ toast.success("RFQ가 성공적으로 업데이트되었습니다!");
+ onUpdated?.();
+ onOpenChange?.(false);
+ form.reset();
+ }
+ } catch (error: any) {
+ console.error("Update failed with error:", error.message);
+ toast.error("업데이트 중 오류 발생: " + error.message);
+ }
+ });
+ }
+
+ // Debug form errors on change
+ React.useEffect(() => {
+ const subscription = form.watch(() => {
+ console.log("Form values changed:", form.getValues());
+ console.log("Form errors:", form.formState.errors);
+ });
+ return () => subscription.unsubscribe();
+ }, [form]);
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent className="flex flex-col h-full sm:max-w-xl bg-gray-50">
+ <SheetHeader className="text-left flex-shrink-0">
+ <SheetTitle className="text-2xl font-bold">RFQ 수정</SheetTitle>
+ <SheetDescription className="">
+ RFQ 정보를 수정합니다. 모든 필드를 입력한 후 저장 버튼을 클릭하세요.
+ </SheetDescription>
+ </SheetHeader>
+
+ <div className="flex-1 overflow-y-auto py-4">
+ {isLoading ? (
+ <div className="flex justify-center items-center py-12">
+ <Loader2 className="h-10 w-10 animate-spin" />
+ </div>
+ ) : (
+ <div className="space-y-6">
+ <div className="bg-white shadow-sm rounded-lg p-5 border border-gray-200">
+ <div className="grid grid-cols-2 gap-4 text-sm">
+ <div>
+ <span className="font-semibold text-gray-700">프로젝트명:</span> {projectInfo.projNm}
+ </div>
+ <div>
+ <span className="font-semibold text-gray-700">섹터:</span> {projectInfo.sector}
+ </div>
+ <div>
+ <span className="font-semibold text-gray-700">척수:</span> {projectInfo.projMsrm}
+ </div>
+ <div>
+ <span className="font-semibold text-gray-700">선종:</span> {projectInfo.ptypeNm}
+ </div>
+ <div>
+ <span className="font-semibold text-gray-700">RFQ No:</span> {projectInfo.rfqNo}
+ </div>
+ </div>
+ </div>
+
+ <Form {...form}>
+ <form id="update-rfq-form" onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-4">
+ <FormField
+ control={form.control}
+ name="description"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel className="text-sm font-medium text-gray-700">RFQ Title</FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ placeholder="RFQ Title을 입력하세요"
+ className="border-gray-300 rounded-md"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="dueDate"
+ render={({ field }) => (
+ <FormItem className="flex flex-col">
+ <FormLabel>마감일</FormLabel>
+ <Popover>
+ <PopoverTrigger asChild>
+ <FormControl>
+ <Button
+ variant="outline"
+ className={cn(
+ "w-full pl-3 text-left font-normal",
+ !field.value && "text-muted-foreground"
+ )}
+ >
+ {field.value ? (
+ format(new Date(field.value), "PPP", { locale: ko })
+ ) : (
+ <span>마감일을 선택하세요</span>
+ )}
+ <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
+ </Button>
+ </FormControl>
+ </PopoverTrigger>
+ <PopoverContent className="w-auto p-0" align="start">
+ <Calendar
+ mode="single"
+ selected={field.value ? new Date(field.value) : undefined}
+ onSelect={(date) => {
+ // date-fns format을 사용해 yyyy-MM-dd로 변환하여 string 저장
+ if (date) {
+ field.onChange(format(date, "yyyy-MM-dd"));
+ }
+ }}
+ disabled={(date) =>
+ date < new Date() || date < new Date("1900-01-01")
+ }
+ initialFocus
+ />
+ </PopoverContent>
+ </Popover>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </form>
+ </Form>
+ </div>
+ )}
+ </div>
+
+ <SheetFooter className="gap-2 pt-2 sm:space-x-0 flex-shrink-0">
+ <SheetClose asChild>
+ <Button
+ type="button"
+ variant="outline"
+ disabled={isPending}
+ className="border-gray-300 text-gray-700 hover:bg-gray-100 rounded-md"
+ >
+ 취소
+ </Button>
+ </SheetClose>
+ <Button
+ type="submit"
+ form="update-rfq-form"
+ disabled={isPending}
+ className="bg-blue-600 hover:bg-blue-700 text-white rounded-md"
+ onClick={() => console.log("Save button clicked")}
+ >
+ {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />}
+ 저장
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ );
+}
\ No newline at end of file diff --git a/lib/techsales-rfq/vendor-response/detail/project-info-tab.tsx b/lib/techsales-rfq/vendor-response/detail/project-info-tab.tsx index 771db896..8a45f529 100644 --- a/lib/techsales-rfq/vendor-response/detail/project-info-tab.tsx +++ b/lib/techsales-rfq/vendor-response/detail/project-info-tab.tsx @@ -80,12 +80,12 @@ export function ProjectInfoTab({ quotation }: ProjectInfoTabProps) { <div className="text-sm font-medium text-muted-foreground">자재 그룹</div>
<div className="text-sm">{rfq.materialCode || "N/A"}</div>
</div>
- <div className="space-y-2">
+ {/* <div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground">마감일</div>
<div className="text-sm">
{rfq.dueDate ? formatDate(rfq.dueDate) : "N/A"}
</div>
- </div>
+ </div> */}
<div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground">RFQ 상태</div>
<div className="text-sm">{rfq.status || "N/A"}</div>
diff --git a/lib/techsales-rfq/vendor-response/detail/quotation-response-tab.tsx b/lib/techsales-rfq/vendor-response/detail/quotation-response-tab.tsx index 9411ed02..087e2a4d 100644 --- a/lib/techsales-rfq/vendor-response/detail/quotation-response-tab.tsx +++ b/lib/techsales-rfq/vendor-response/detail/quotation-response-tab.tsx @@ -96,10 +96,9 @@ export function QuotationResponseTab({ quotation }: QuotationResponseTabProps) { const rfq = quotation.rfq
const isDueDatePassed = rfq?.dueDate ? new Date(rfq.dueDate) < new Date() : false
- // const canSubmit = !["Accepted", "Rejected"].includes(quotation.status) && !isDueDatePassed
- // const canEdit = !["Accepted", "Rejected"].includes(quotation.status) && !isDueDatePassed
const canSubmit = !["Accepted", "Rejected"].includes(quotation.status)
const canEdit = !["Accepted", "Rejected"].includes(quotation.status)
+
// 파일 업로드 핸들러
const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
const files = event.target.files
@@ -264,13 +263,13 @@ export function QuotationResponseTab({ quotation }: QuotationResponseTabProps) { <div className="text-sm font-medium text-muted-foreground">견적서 상태</div>
<div className="text-sm">{getStatusLabel(quotation.status)}</div>
</div>
- <div className="space-y-2">
+ {/* <div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground">RFQ 마감일</div>
<div className="text-sm">
{rfq?.dueDate ? formatDate(rfq.dueDate) : "N/A"}
</div>
- </div>
- <div className="space-y-2">
+ </div> */}
+ {/* <div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground">남은 시간</div>
<div className="text-sm">
{isDueDatePassed ? (
@@ -283,19 +282,19 @@ export function QuotationResponseTab({ quotation }: QuotationResponseTabProps) { "N/A"
)}
</div>
- </div>
+ </div> */}
</div>
- {isDueDatePassed && (
+ {/* {isDueDatePassed && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
RFQ 마감일이 지났습니다. 견적서를 수정하거나 제출할 수 없습니다.
</AlertDescription>
</Alert>
- )}
+ )} */}
- {!canEdit && !isDueDatePassed && (
+ {!canEdit && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
diff --git a/lib/techsales-rfq/vendor-response/table/vendor-quotations-table-columns.tsx b/lib/techsales-rfq/vendor-response/table/vendor-quotations-table-columns.tsx index 328def80..46b14f46 100644 --- a/lib/techsales-rfq/vendor-response/table/vendor-quotations-table-columns.tsx +++ b/lib/techsales-rfq/vendor-response/table/vendor-quotations-table-columns.tsx @@ -508,26 +508,26 @@ export function getColumns({ router, openAttachmentsSheet, openItemsDialog, open // enableSorting: true,
// enableHiding: true,
// },
- {
- accessorKey: "dueDate",
- header: ({ column }) => (
- <DataTableColumnHeaderSimple column={column} title="마감일" />
- ),
- cell: ({ row }) => {
- const dueDate = row.getValue("dueDate") as Date;
- const isOverdue = dueDate && new Date() > new Date(dueDate);
+ // {
+ // accessorKey: "dueDate",
+ // header: ({ column }) => (
+ // <DataTableColumnHeaderSimple column={column} title="마감일" />
+ // ),
+ // cell: ({ row }) => {
+ // const dueDate = row.getValue("dueDate") as Date;
+ // const isOverdue = dueDate && new Date() > new Date(dueDate);
- return (
- <div className="w-28">
- <span className={`text-sm ${isOverdue ? "text-red-600 font-medium" : ""}`}>
- {dueDate ? formatDate(dueDate) : "N/A"}
- </span>
- </div>
- );
- },
- enableSorting: true,
- enableHiding: true,
- },
+ // return (
+ // <div className="w-28">
+ // <span className={`text-sm ${isOverdue ? "text-red-600 font-medium" : ""}`}>
+ // {dueDate ? formatDate(dueDate) : "N/A"}
+ // </span>
+ // </div>
+ // );
+ // },
+ // enableSorting: true,
+ // enableHiding: true,
+ // },
// {
// accessorKey: "rejectionReason",
// header: ({ column }) => (
|
