summaryrefslogtreecommitdiff
path: root/lib/rfq-last/vendor/add-vendor-dialog.tsx
blob: eddd09b04211795de37ef5100a4b898f69db55c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
"use client";

import * as React from "react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Loader2, X } from "lucide-react";
import { toast } from "sonner";
import { addVendorsToRfq, getRfqItemsAction } from "../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 { Checkbox } from "@/components/ui/checkbox";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { VendorSelector } from "@/components/common/vendor/vendor-selector";
import { VendorSearchItem } from "@/components/common/vendor/vendor-service";

interface VendorContract {
  vendorId: number;
  agreementYn: boolean;
  ndaYn: boolean;
  gtcType: "general" | "project" | "none";
}

interface AddVendorDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  rfqId: number;
  rfqCategory?: "itb" | "rfq" | "general";
  onSuccess: () => void;
}

export function AddVendorDialog({
  open,
  onOpenChange,
  rfqId,
  rfqCategory = "general",
  onSuccess,
}: AddVendorDialogProps) {
  const [isLoading, setIsLoading] = React.useState(false);
  const [selectedVendors, setSelectedVendors] = React.useState<VendorSearchItem[]>([]);
  const [activeTab, setActiveTab] = React.useState<"vendors" | "contracts">("vendors");

  // 각 벤더별 기본계약 요구사항 상태
  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: 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]);

  React.useEffect(() => {
    if (open) {
      checkMrcType();
    }
  }, [open, checkMrcType]);

  // 초기화
  React.useEffect(() => {
    if (!open) {
      setSelectedVendors([]);
      setVendorContracts([]);
      setActiveTab("vendors");
      setHasMrcTypeP(false);
      setDefaultContract({
        agreementYn: false,
        ndaYn: false,
        gtcType: "none"
      });
    }
  }, [open]);

  // 외자업체 여부 확인
  const isInternationalVendor = (vendor: VendorSearchItem) => {
    return vendor.country && vendor.country !== "KR" && vendor.country !== "한국";
  };

  // 벤더 선택 변경 핸들러
  const handleVendorsChange = (vendors: VendorSearchItem[]) => {
    const prevVendorIds = selectedVendors.map(v => v.id);
    const newVendorIds = vendors.map(v => v.id);
    
    // 새로 추가된 벤더들 찾기
    const addedVendors = vendors.filter(v => !prevVendorIds.includes(v.id));
    
    // 제거된 벤더들 찾기
    const removedVendorIds = prevVendorIds.filter(id => !newVendorIds.includes(id));
    
    // 제거된 벤더의 계약 정보 삭제
    if (removedVendorIds.length > 0) {
      setVendorContracts(vendorContracts.filter(c => !removedVendorIds.includes(c.vendorId)));
    }
    
    // 새로 추가된 벤더의 계약 정보 추가
    const newContracts = addedVendors.map(vendor => {
      const isInternational = isInternationalVendor(vendor);
      
      let shouldCheckAgreement = false;
      
      // ITB인 경우: 국내기업만 체크
      if (rfqCategory === "itb") {
        shouldCheckAgreement = !isInternational;
      } else {
        // 기존 로직: 외자업체이거나 MRC Type이 "P"가 아닌 경우 false로 설정
        shouldCheckAgreement = hasMrcTypeP && !isInternational;
      }
      
      return {
        vendorId: vendor.id,
        agreementYn: shouldCheckAgreement,
        ndaYn: shouldCheckAgreement,
        gtcType: isInternational ? defaultContract.gtcType : "none"
      };
    });
    
    if (newContracts.length > 0) {
      setVendorContracts([...vendorContracts, ...newContracts]);
    }
    
    setSelectedVendors(vendors);
  };

  // 개별 벤더의 계약 설정 업데이트
  const updateVendorContract = (vendorId: number, field: string, value: any) => {
    setVendorContracts(contracts =>
      contracts.map(c =>
        c.vendorId === vendorId ? { ...c, [field]: value } : c
      )
    );
  };

  // 모든 벤더에 일괄 적용
  const applyToAll = () => {
    setVendorContracts(contracts =>
      contracts.map(c => {
        const vendor = selectedVendors.find(v => v.id === c.vendorId);
        const isInternational = isInternationalVendor(vendor);
        // 외자업체이거나 MRC Type이 "P"가 아닌 경우 false로 설정
        const shouldCheckAgreement = hasMrcTypeP && !isInternational;
        return {
          ...c,
          agreementYn: shouldCheckAgreement,
          ndaYn: shouldCheckAgreement,
          gtcType: isInternational ? defaultContract.gtcType : "none"
        };
      })
    );
    toast.success("모든 벤더에 기본계약 설정이 적용되었습니다.");
  };

  // 제출 처리
  const handleSubmit = async () => {
    if (selectedVendors.length === 0) {
      toast.error("최소 1개 이상의 벤더를 선택해주세요.");
      return;
    }

    setIsLoading(true);

    try {
      // 각 벤더별로 개별 추가
      const results = await Promise.all(
        selectedVendors.map(async (vendor) => {
          const contract = vendorContracts.find(c => c.vendorId === vendor.id);
          return addVendorsToRfq({
            rfqId,
            vendorIds: [vendor.id],
            conditions: null,
            contractRequirements: contract || defaultContract
          });
        })
      );

      // 결과 확인
      const successCount = results.filter(r => r.success).length;
      const failedCount = results.length - successCount;

      if (successCount > 0) {
        toast.success(
          <div>
            <p>{successCount}개 벤더가 추가되었습니다.</p>
            {failedCount > 0 && (
              <p className="text-sm text-destructive mt-1">
                {failedCount}개 벤더 추가 실패
              </p>
            )}
            <p className="text-sm text-muted-foreground mt-1">
              벤더 목록에서 '정보 일괄 입력' 버튼으로 조건을 설정하세요.
            </p>
          </div>
        );
        onSuccess();
        onOpenChange(false);
      } else {
        toast.error("벤더 추가에 실패했습니다.");
      }
    } catch (error) {
      console.error("Submit error:", error);
      toast.error("오류가 발생했습니다.");
    } finally {
      setIsLoading(false);
    }
  };

  // 선택된 벤더가 있고 계약 탭으로 이동 가능한지
  const canProceedToContracts = selectedVendors.length > 0;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] p-0 flex flex-col">
        {/* 헤더 */}
        <DialogHeader className="p-6 pb-0">
          <DialogTitle>벤더 추가</DialogTitle>
          <DialogDescription>
            견적 요청을 보낼 벤더를 선택하고 각 벤더별 기본계약 요구사항을 설정하세요.
          </DialogDescription>
        </DialogHeader>

        {/* 탭 */}
        <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as any)} className="flex-1 flex flex-col min-h-0">
          <TabsList className="ml-6 grid w-fit grid-cols-2">
            <TabsTrigger value="vendors">
              1. 벤더 선택
              {selectedVendors.length > 0 && (
                <Badge variant="secondary" className="ml-2">
                  {selectedVendors.length}
                </Badge>
              )}
            </TabsTrigger>
            <TabsTrigger value="contracts" disabled={!canProceedToContracts}>
              2. 기본계약 설정
            </TabsTrigger>
          </TabsList>

          {/* 벤더 선택 탭 */}
          <TabsContent value="vendors" className="flex-1 flex flex-col px-6 py-4 overflow-y-auto min-h-0">
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">벤더 선택</CardTitle>
                <CardDescription>
                  RFQ를 발송할 벤더를 선택하세요. 여러 개 선택 가능합니다.
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {/* 벤더 선택 */}
                  <VendorSelector
                    selectedVendors={selectedVendors}
                    onVendorsChange={handleVendorsChange}
                    singleSelect={false}
                    placeholder="벤더명 또는 코드로 검색..."
                    noValuePlaceHolder="벤더를 선택하세요"
                    showInitialData={true}
                    includeCountry={true}
                  />

                  {selectedVendors.length === 0 && (
                    <div className="text-center py-8 text-muted-foreground">
                      <p className="text-sm">아직 선택된 벤더가 없습니다.</p>
                      <p className="text-xs mt-1">위 필드를 클릭하여 벤더를 검색하고 추가하세요.</p>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* 기본계약 설정 탭 */}
          <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>
                <CardHeader className="pb-3">
                  <CardTitle className="text-base flex items-center gap-2">
                    <Settings className="h-4 w-4" />
                    일괄 적용 설정
                  </CardTitle>
                  <CardDescription>
                    모든 벤더에 동일한 설정을 적용할 수 있습니다.
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <div className="flex items-center space-x-2">
                        <Checkbox
                          id="default-agreement"
                          checked={defaultContract.agreementYn}
                          disabled={!hasMrcTypeP || isCheckingMrcType}
                          onCheckedChange={(checked) =>
                            setDefaultContract({ ...defaultContract, agreementYn: !!checked })
                          }
                        />
                        <label htmlFor="default-agreement" className="text-sm font-medium">
                          기술자료 제공 동의
                        </label>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Checkbox
                          id="default-nda"
                          checked={defaultContract.ndaYn}
                          disabled={!hasMrcTypeP || isCheckingMrcType}
                          onCheckedChange={(checked) =>
                            setDefaultContract({ ...defaultContract, ndaYn: !!checked })
                          }
                        />
                        <label htmlFor="default-nda" className="text-sm font-medium">
                          비밀유지 계약 (NDA)
                        </label>
                      </div>
                    </div>
                    <div className="space-y-2">
                      <Label className="text-sm">GTC (국외 업체용)</Label>
                      <RadioGroup
                        value={defaultContract.gtcType}
                        onValueChange={(value: any) =>
                          setDefaultContract({ ...defaultContract, gtcType: value })
                        }
                      >
                        <div className="flex items-center space-x-2">
                          <RadioGroupItem value="none" id="default-gtc-none" />
                          <label htmlFor="default-gtc-none" className="text-sm">없음</label>
                        </div>
                        <div className="flex items-center space-x-2">
                          <RadioGroupItem value="general" id="default-gtc-general" />
                          <label htmlFor="default-gtc-general" className="text-sm">General GTC</label>
                        </div>
                        <div className="flex items-center space-x-2">
                          <RadioGroupItem value="project" id="default-gtc-project" />
                          <label htmlFor="default-gtc-project" className="text-sm">Project GTC</label>
                        </div>
                      </RadioGroup>
                    </div>
                  </div>
                  <Button
                    variant="secondary"
                    size="sm"
                    onClick={applyToAll}
                    className="w-full"
                  >
                    모든 벤더에 적용
                  </Button>
                </CardContent>
              </Card> */}

              {/* 개별 벤더 설정 */}
              <Card className="flex flex-col min-h-0">
                <CardHeader className="pb-3">
                  <CardTitle className="text-base">개별 벤더 기본계약 설정</CardTitle>
                  <CardDescription>
                    각 벤더별로 다른 기본계약을 요구할 수 있습니다.
                  </CardDescription>
                </CardHeader>
                <CardContent className="flex-1 min-h-0">
                  <ScrollArea className="h-[250px] pr-4">
                    <div className="space-y-4">
                      {selectedVendors.map((vendor) => {
                        const contract = vendorContracts.find(c => c.vendorId === vendor.id);
                        const isInternational = isInternationalVendor(vendor);

                        return (
                          <div key={vendor.id} className="border rounded-lg p-4 space-y-3">
                            <div className="flex items-center justify-between">
                              <div className="flex items-center gap-2">
                                <Badge variant="outline">{vendor.vendorCode || "-"}</Badge>
                                <span className="font-medium">{vendor.vendorName}</span>
                                {vendor.country && (
                                  <Badge
                                    variant={isInternational ? "secondary" : "default"}
                                    className="text-xs"
                                  >
                                    {vendor.country}
                                  </Badge>
                                )}
                              </div>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                              <div className="space-y-2">
                                <div className="flex items-center space-x-2">
                                  <Checkbox
                                    checked={contract?.agreementYn || false}
                                    disabled={
                                      rfqCategory === "itb" 
                                        ? true  // ITB는 항상 비활성화
                                        : (!hasMrcTypeP || isInternational)  // 기존 로직
                                    }
                                    onCheckedChange={(checked) =>
                                      updateVendorContract(vendor.id, "agreementYn", !!checked)
                                    }
                                  />
                                  <label className="text-sm">기술자료 제공</label>
                                </div>
                                <div className="flex items-center space-x-2">
                                  <Checkbox
                                    checked={contract?.ndaYn || false}
                                    disabled={
                                      rfqCategory === "itb" 
                                        ? true  // ITB는 항상 비활성화
                                        : (!hasMrcTypeP || isInternational)  // 기존 로직
                                    }
                                    onCheckedChange={(checked) =>
                                      updateVendorContract(vendor.id, "ndaYn", !!checked)
                                    }
                                  />
                                  <label className="text-sm">비밀유지 계약 (NDA)</label>
                                </div>
                              </div>

                              {isInternational && (
                                <div className="space-y-1">
                                  <Label className="text-xs">GTC</Label>
                                  <RadioGroup
                                    value={contract?.gtcType || "none"}
                                    onValueChange={(value) =>
                                      updateVendorContract(vendor.id, "gtcType", value)
                                    }
                                  >
                                    <div className="flex items-center space-x-2">
                                      <RadioGroupItem value="none" id={`${vendor.id}-none`} />
                                      <label htmlFor={`${vendor.id}-none`} className="text-xs">없음</label>
                                    </div>
                                    <div className="flex items-center space-x-2">
                                      <RadioGroupItem value="general" id={`${vendor.id}-general`} />
                                      <label htmlFor={`${vendor.id}-general`} className="text-xs">General</label>
                                    </div>
                                    <div className="flex items-center space-x-2">
                                      <RadioGroupItem value="project" id={`${vendor.id}-project`} />
                                      <label htmlFor={`${vendor.id}-project`} className="text-xs">Project</label>
                                    </div>
                                  </RadioGroup>
                                </div>
                              )}

                              {!isInternational && (
                                <div className="text-xs text-muted-foreground">
                                  국내 업체 - GTC 불필요
                                </div>
                              )}
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </ScrollArea>
                </CardContent>
              </Card>
            </div>
          </TabsContent>
        </Tabs>

        {/* 푸터 */}
        <DialogFooter className="p-6 pt-0 border-t">
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isLoading}
          >
            취소
          </Button>
          {activeTab === "vendors" && canProceedToContracts && (
            <Button
              onClick={() => setActiveTab("contracts")}
            >
              다음: 기본계약 설정
            </Button>
          )}
          {activeTab === "contracts" && (
            <Button
              onClick={handleSubmit}
              disabled={isLoading || selectedVendors.length === 0}
            >
              {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {selectedVendors.length > 0
                ? `${selectedVendors.length}개 벤더 추가`
                : '벤더 추가'
              }
            </Button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}