From 47fb72704161b4b58a27c7f5c679fc44618de9a1 Mon Sep 17 00:00:00 2001
From: dujinkim <dujin.kim@dtsolution.co.kr>
Date: Tue, 4 Nov 2025 10:03:32 +0000
Subject: (최겸) 구매 견적 내 RFQ Cancel/Delete, 연동제 적용, MRC Type 개발
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 lib/rfq-last/vendor/add-vendor-dialog.tsx | 122 +++++++++++++++++++++++++-----
 1 file changed, 104 insertions(+), 18 deletions(-)

(limited to 'lib/rfq-last/vendor/add-vendor-dialog.tsx')

diff --git a/lib/rfq-last/vendor/add-vendor-dialog.tsx b/lib/rfq-last/vendor/add-vendor-dialog.tsx
index 8566763f..6b4efe74 100644
--- a/lib/rfq-last/vendor/add-vendor-dialog.tsx
+++ b/lib/rfq-last/vendor/add-vendor-dialog.tsx
@@ -27,9 +27,10 @@ import {
 import { Check, ChevronsUpDown, Loader2, X, Plus, FileText, Shield, Globe, Settings } from "lucide-react";
 import { cn } from "@/lib/utils";
 import { toast } from "sonner";
-import { addVendorsToRfq } from "../service";
+import { addVendorsToRfq, getRfqItemsAction } from "../service";
 import { getVendorsForSelection } from "@/lib/b-rfq/service";
 import { Badge } from "@/components/ui/badge";
+import { getMrcTypeByMatnr } from "@/lib/mdg/actions/material-service";
 import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
 import { ScrollArea } from "@/components/ui/scroll-area";
 import { Alert, AlertDescription } from "@/components/ui/alert";
@@ -68,13 +69,83 @@ export function AddVendorDialog({
   // 각 벤더별 기본계약 요구사항 상태
   const [vendorContracts, setVendorContracts] = React.useState<VendorContract[]>([]);
 
-  // 일괄 적용용 기본값
+  // MRC Type이 "P"인지 확인하는 상태
+  const [hasMrcTypeP, setHasMrcTypeP] = React.useState(false);
+  const [isCheckingMrcType, setIsCheckingMrcType] = React.useState(false);
+
+  // 일괄 적용용 기본값 (MRC Type과 외자업체 여부에 따라 동적으로 설정)
   const [defaultContract, setDefaultContract] = React.useState({
-    agreementYn: true,
-    ndaYn: true,
+    agreementYn: false,
+    ndaYn: false,
     gtcType: "none" as "general" | "project" | "none"
   });
 
+  // MRC Type 확인
+  const checkMrcType = React.useCallback(async () => {
+    setIsCheckingMrcType(true);
+    try {
+      const itemsResult = await getRfqItemsAction(rfqId);
+      if (itemsResult.success && itemsResult.data && itemsResult.data.length > 0) {
+        // 모든 품목의 MRC Type 확인
+        const mrcTypeChecks = await Promise.all(
+          itemsResult.data
+            .filter(item => item.materialCode) // materialCode가 있는 경우만
+            .map(async (item) => {
+              try {
+                console.log(item.materialCode, "item.materialCode");
+                const mrcType = await getMrcTypeByMatnr(item.materialCode);
+                console.log(mrcType, "mrcType");
+                return mrcType === "P";
+              } catch (error) {
+                console.error(`Failed to get MRC Type for ${item.materialCode}:`, error);
+                return false;
+              }
+            })
+        );
+        console.log(mrcTypeChecks, "mrcTypeChecks");
+
+        // 하나라도 "P"가 있으면 true
+        const hasP = mrcTypeChecks.some(check => check === true);
+        setHasMrcTypeP(hasP);
+        console.log(hasP, "hasP");
+
+        // MRC Type이 "P"이고 국내업체인 경우에만 기본값을 true로 설정
+        if (hasP) {
+          setDefaultContract(prev => ({
+            ...prev,
+            agreementYn: true,
+            ndaYn: true
+          }));
+        } else {
+          setDefaultContract(prev => ({
+            ...prev,
+            agreementYn: false,
+            ndaYn: false
+          }));
+        }
+      } else {
+        // 품목이 없으면 기본값 false
+        setHasMrcTypeP(false);
+        setDefaultContract(prev => ({
+          ...prev,
+          agreementYn: false,
+          ndaYn: false
+        }));
+      }
+    } catch (error) {
+      console.error("Failed to check MRC Type:", error);
+      // 에러 발생 시 기본값 false
+      setHasMrcTypeP(false);
+      setDefaultContract(prev => ({
+        ...prev,
+        agreementYn: false,
+        ndaYn: false
+      }));
+    } finally {
+      setIsCheckingMrcType(false);
+    }
+  }, [rfqId]);
+
   // 벤더 로드
   const loadVendors = React.useCallback(async () => {
     try {
@@ -91,8 +162,9 @@ export function AddVendorDialog({
   React.useEffect(() => {
     if (open) {
       loadVendors();
+      checkMrcType();
     }
-  }, [open, loadVendors]);
+  }, [open, loadVendors, checkMrcType]);
 
   // 초기화
   React.useEffect(() => {
@@ -100,14 +172,20 @@ export function AddVendorDialog({
       setSelectedVendors([]);
       setVendorContracts([]);
       setActiveTab("vendors");
+      setHasMrcTypeP(false);
       setDefaultContract({
-        agreementYn: true,
-        ndaYn: true,
+        agreementYn: false,
+        ndaYn: false,
         gtcType: "none"
       });
     }
   }, [open]);
 
+  // 외자업체 여부 확인
+  const isInternationalVendor = (vendor: any) => {
+    return vendor.country && vendor.country !== "KR" && vendor.country !== "한국";
+  };
+
   // 벤더 추가
   const handleAddVendor = (vendor: any) => {
     if (!selectedVendors.find(v => v.id === vendor.id)) {
@@ -115,13 +193,15 @@ export function AddVendorDialog({
       setSelectedVendors(updatedVendors);
 
       // 해당 벤더의 기본계약 설정 추가
-      const isInternational = vendor.country && vendor.country !== "KR" && vendor.country !== "한국";
+      const isInternational = isInternationalVendor(vendor);
+      // 외자업체이거나 MRC Type이 "P"가 아닌 경우 false로 설정
+      const shouldCheckAgreement = hasMrcTypeP && !isInternational;
       setVendorContracts([
         ...vendorContracts,
         {
           vendorId: vendor.id,
-          agreementYn: defaultContract.agreementYn,
-          ndaYn: defaultContract.ndaYn,
+          agreementYn: shouldCheckAgreement,
+          ndaYn: shouldCheckAgreement,
           gtcType: isInternational ? defaultContract.gtcType : "none"
         }
       ]);
@@ -149,11 +229,13 @@ export function AddVendorDialog({
     setVendorContracts(contracts =>
       contracts.map(c => {
         const vendor = selectedVendors.find(v => v.id === c.vendorId);
-        const isInternational = vendor?.country && vendor.country !== "KR" && vendor.country !== "한국";
+        const isInternational = isInternationalVendor(vendor);
+        // 외자업체이거나 MRC Type이 "P"가 아닌 경우 false로 설정
+        const shouldCheckAgreement = hasMrcTypeP && !isInternational;
         return {
           ...c,
-          agreementYn: defaultContract.agreementYn,
-          ndaYn: defaultContract.ndaYn,
+          agreementYn: shouldCheckAgreement,
+          ndaYn: shouldCheckAgreement,
           gtcType: isInternational ? defaultContract.gtcType : "none"
         };
       })
@@ -236,7 +318,7 @@ export function AddVendorDialog({
 
         {/* 탭 */}
         <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as any)} className="flex-1 flex flex-col min-h-0">
-          <TabsList className="mx-6 grid w-fit grid-cols-2">
+          <TabsList className="ml-6 grid w-fit grid-cols-2">
             <TabsTrigger value="vendors">
               1. 벤더 선택
               {selectedVendors.length > 0 && (
@@ -378,7 +460,7 @@ export function AddVendorDialog({
           <TabsContent value="contracts" className="flex-1 flex flex-col px-6 py-4 overflow-hidden min-h-0">
             <div className="flex-1 overflow-y-auto space-y-4 min-h-0">
               {/* 일괄 적용 카드 */}
-              <Card>
+              {/* <Card>
                 <CardHeader className="pb-3">
                   <CardTitle className="text-base flex items-center gap-2">
                     <Settings className="h-4 w-4" />
@@ -395,6 +477,7 @@ export function AddVendorDialog({
                         <Checkbox
                           id="default-agreement"
                           checked={defaultContract.agreementYn}
+                          disabled={!hasMrcTypeP || isCheckingMrcType}
                           onCheckedChange={(checked) =>
                             setDefaultContract({ ...defaultContract, agreementYn: !!checked })
                           }
@@ -407,6 +490,7 @@ export function AddVendorDialog({
                         <Checkbox
                           id="default-nda"
                           checked={defaultContract.ndaYn}
+                          disabled={!hasMrcTypeP || isCheckingMrcType}
                           onCheckedChange={(checked) =>
                             setDefaultContract({ ...defaultContract, ndaYn: !!checked })
                           }
@@ -448,7 +532,7 @@ export function AddVendorDialog({
                     모든 벤더에 적용
                   </Button>
                 </CardContent>
-              </Card>
+              </Card> */}
 
               {/* 개별 벤더 설정 */}
               <Card className="flex flex-col min-h-0">
@@ -463,7 +547,7 @@ export function AddVendorDialog({
                     <div className="space-y-4">
                       {selectedVendors.map((vendor) => {
                         const contract = vendorContracts.find(c => c.vendorId === vendor.id);
-                        const isInternational = vendor.country && vendor.country !== "KR" && vendor.country !== "한국";
+                        const isInternational = isInternationalVendor(vendor);
 
                         return (
                           <div key={vendor.id} className="border rounded-lg p-4 space-y-3">
@@ -485,6 +569,7 @@ export function AddVendorDialog({
                                 <div className="flex items-center space-x-2">
                                   <Checkbox
                                     checked={contract?.agreementYn || false}
+                                    disabled={!hasMrcTypeP || isInternational}
                                     onCheckedChange={(checked) =>
                                       updateVendorContract(vendor.id, "agreementYn", !!checked)
                                     }
@@ -494,11 +579,12 @@ export function AddVendorDialog({
                                 <div className="flex items-center space-x-2">
                                   <Checkbox
                                     checked={contract?.ndaYn || false}
+                                    disabled={!hasMrcTypeP || isInternational}
                                     onCheckedChange={(checked) =>
                                       updateVendorContract(vendor.id, "ndaYn", !!checked)
                                     }
                                   />
-                                  <label className="text-sm">NDA</label>
+                                  <label className="text-sm">비밀유지 계약 (NDA)</label>
                                 </div>
                               </div>
 
-- 
cgit v1.2.3

