summaryrefslogtreecommitdiff
path: root/lib/pq/pq-review-table-new/vendors-table-toolbar-actions.tsx
blob: 95cdd4d17831dc142860023999ee3759bfc19f19 (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
"use client"

import * as React from "react"
import { type Table } from "@tanstack/react-table"
import { Download, ClipboardCheck, X, Send, RefreshCw } from "lucide-react"
import { toast } from "sonner"

import { exportTableToExcel } from "@/lib/export"
import { Button } from "@/components/ui/button"
import { PQSubmission } from "./vendors-table-columns"
import {
  requestInvestigationAction,
  cancelInvestigationAction,
  sendInvestigationResultsAction,
  getFactoryLocationAnswer,
  reRequestInvestigationAction
} from "@/lib/pq/service"
import { RequestInvestigationDialog } from "./request-investigation-dialog"
import { CancelInvestigationDialog, ReRequestInvestigationDialog } from "./cancel-investigation-dialog"
import { SendResultsDialog } from "./send-results-dialog"

interface VendorsTableToolbarActionsProps {
  table: Table<PQSubmission>
}

interface InvestigationInitialData {
  investigationMethod?: "PURCHASE_SELF_EVAL" | "DOCUMENT_EVAL" | "PRODUCT_INSPECTION" | "SITE_VISIT_EVAL";
  qmManagerId?: number;
  forecastedAt?: Date;
  createdAt?: Date;
  investigationAddress?: string;
  investigationNotes?: string;
}

export function VendorsTableToolbarActions({ table }: VendorsTableToolbarActionsProps) {
  const selectedRows = table.getFilteredSelectedRowModel().rows
  const [isLoading, setIsLoading] = React.useState(false)

  // Dialog 상태 관리
  const [isRequestDialogOpen, setIsRequestDialogOpen] = React.useState(false)
  const [isCancelDialogOpen, setIsCancelDialogOpen] = React.useState(false)
  const [isSendResultsDialogOpen, setIsSendResultsDialogOpen] = React.useState(false)
  const [isReRequestDialogOpen, setIsReRequestDialogOpen] = React.useState(false)

  // 초기 데이터 상태
  const [dialogInitialData, setDialogInitialData] = React.useState<InvestigationInitialData | undefined>(undefined)

  // 실사 의뢰 대화상자 열기 핸들러
// 실사 의뢰 대화상자 열기 핸들러
const handleOpenRequestDialog = async () => {
  setIsLoading(true);
  const initialData: InvestigationInitialData = {};
  
  try {
    // 선택된 행이 정확히 1개인 경우에만 초기값 설정
    if (selectedRows.length === 1) {
      const row = selectedRows[0].original;
      
      // 승인된 PQ이고 아직 실사가 없는 경우
      if (row.status === "APPROVED" && !row.investigation) {
        // Factory Location 정보 가져오기
        const locationResponse = await getFactoryLocationAnswer(
          row.vendorId, 
          row.projectId
        );
        
        // 기본 주소 설정 - Factory Location 응답 또는 fallback
        let defaultAddress = "";
        if (locationResponse.success && locationResponse.factoryLocation) {
          defaultAddress = locationResponse.factoryLocation;
        } else {
          // Factory Location을 찾지 못한 경우 fallback
          defaultAddress = row.taxId ? 
            `${row.vendorName} 사업장 (${row.taxId})` : 
            `${row.vendorName} 사업장`;
        }
        
        // 이미 같은 회사에 대한 다른 실사가 있는지 확인
        const existingInvestigations = table.getFilteredRowModel().rows
          .map(r => r.original)
          .filter(r => 
            r.vendorId === row.vendorId && 
            r.investigation !== null
          );
        
        // 같은 업체의 이전 실사 기록이 있다면 참고하되, 주소는 Factory Location 사용
        if (existingInvestigations.length > 0) {
          // 날짜 기준으로 정렬하여 가장 최근 것을 가져옴
          const latestInvestigation = existingInvestigations.sort((a, b) => {
            const dateA = a.investigation?.createdAt || new Date(0);
            const dateB = b.investigation?.createdAt || new Date(0);
            return (dateB as Date).getTime() - (dateA as Date).getTime();
          })[0].investigation;
          
          if (latestInvestigation) {
            initialData.investigationMethod = latestInvestigation.investigationMethod || undefined;
            initialData.qmManagerId = latestInvestigation.qmManagerId || undefined;
            initialData.investigationAddress = defaultAddress; // Factory Location 사용
            
            // 날짜는 미래로 설정
            const futureDate = new Date();
            futureDate.setDate(futureDate.getDate() + 14); // 기본값으로 2주 후
            initialData.forecastedAt = futureDate;
          }
        } else {
          // 기본값 설정
          initialData.investigationMethod = undefined;
          const futureDate = new Date();
          futureDate.setDate(futureDate.getDate() + 14); // 기본값으로 2주 후
          initialData.forecastedAt = futureDate;
          initialData.investigationAddress = defaultAddress; // Factory Location 사용
        }
      }
      // 실사가 이미 있고 수정하는 경우
      // else if (row.investigation) {
      //   initialData.investigationMethod = row.investigation.investigationMethod || undefined;
      //   initialData.qmManagerId = row.investigation.qmManagerId !== null ? 
      //   row.investigation.qmManagerId : undefined;
      //   initialData.forecastedAt = row.investigation.forecastedAt || new Date();
      //   initialData.investigationAddress = row.investigation.investigationAddress || "";
      //   initialData.investigationNotes = row.investigation.investigationNotes || "";
      // }
    }
  } catch (error) {
    console.error("초기 데이터 로드 중 오류:", error);
    toast.error("초기 데이터 로드 중 오류가 발생했습니다.");
  } finally {
    setIsLoading(false);
    
    // 초기 데이터 설정 및 대화상자 열기
    setDialogInitialData(Object.keys(initialData).length > 0 ? initialData : undefined);
    setIsRequestDialogOpen(true);
  }
};
  // 실사 의뢰 요청 처리
  const handleRequestInvestigation = async (formData: {
    qmManagerId: number,
    forecastedAt: Date,
    investigationAddress: string,
    investigationNotes?: string
  }) => {
    setIsLoading(true)
    try {
      // 승인된 PQ 제출만 필터링 (미실사 PQ 제외)
      const approvedPQs = selectedRows.filter(row =>
        row.original.status === "APPROVED" && 
        !row.original.investigation && 
        row.original.type !== "NON_INSPECTION"
      )

      if (approvedPQs.length === 0) {
        if (hasNonInspectionPQ) {
          toast.error("미실사 PQ는 실사 의뢰할 수 없습니다. 미실사 PQ를 제외하고 선택해주세요.")
        } else {
          toast.error("실사를 의뢰할 수 있는 업체가 없습니다. 승인된 PQ 제출만 실사 의뢰가 가능합니다.")
        }
        return
      }

      // 서버 액션 호출
      const result = await requestInvestigationAction(
        approvedPQs.map(row => row.original.id),
        formData
      )

      if (result.success) {

        toast.success(`${result.count}개 업체에 대해 실사가 의뢰되었습니다.`)
        window.location.reload()
      } else {
        toast.error(result.error || "실사 의뢰 처리 중 오류가 발생했습니다.")
      }
    } catch (error) {
      console.error("실사 의뢰 중 오류 발생:", error)
      toast.error("실사 의뢰 중 오류가 발생했습니다.")
    } finally {
      setIsLoading(false)
      setIsRequestDialogOpen(false)
      setDialogInitialData(undefined); // 초기 데이터 초기화
    }
  }

  const handleCloseRequestDialog = () => {
    setIsRequestDialogOpen(false);
    setDialogInitialData(undefined);
  };


  // 실사 의뢰 취소 처리
  const handleCancelInvestigation = async () => {
    setIsLoading(true)
    try {
      // 실사가 계획됨 상태인 PQ만 필터링
      const plannedInvestigations = selectedRows.filter(row =>
        row.original.investigation &&
        row.original.investigation.investigationStatus === "PLANNED"
      )

      if (plannedInvestigations.length === 0) {
        toast.error("취소할 수 있는 실사 의뢰가 없습니다. 계획 상태의 실사만 취소할 수 있습니다.")
        return
      }

      // 서버 액션 호출
      const result = await cancelInvestigationAction(
        plannedInvestigations.map(row => row.original.investigation!.id)
      )

      if (result.success) {
        toast.success(`${result.count}개 업체에 대한 실사 의뢰가 취소되었습니다.`)
        window.location.reload()
      } else {
        toast.error(result.error || "실사 취소 처리 중 오류가 발생했습니다.")
      }
    } catch (error) {
      console.error("실사 의뢰 취소 중 오류 발생:", error)
      toast.error("실사 의뢰 취소 중 오류가 발생했습니다.")
    } finally {
      setIsLoading(false)
      setIsCancelDialogOpen(false)
    }
  }

  // 실사 재의뢰 처리
  const handleReRequestInvestigation = async () => {
    setIsLoading(true)
    try {
      // 취소된 실사만 필터링
      const canceledInvestigations = selectedRows.filter(row =>
        row.original.investigation &&
        row.original.investigation.investigationStatus === "CANCELED"
      )

      if (canceledInvestigations.length === 0) {
        toast.error("재의뢰할 수 있는 실사가 없습니다. 취소 상태의 실사만 재의뢰할 수 있습니다.")
        return
      }

      // 서버 액션 호출
      const result = await reRequestInvestigationAction(
        canceledInvestigations.map(row => row.original.investigation!.id)
      )

      if (result.success) {
        toast.success(`${result.count}개 업체에 대한 실사가 재의뢰되었습니다.`)
        window.location.reload()
      } else {
        toast.error(result.error || "실사 재의뢰 처리 중 오류가 발생했습니다.")
      }
    } catch (error) {
      console.error("실사 재의뢰 중 오류 발생:", error)
      toast.error("실사 재의뢰 중 오류가 발생했습니다.")
    } finally {
      setIsLoading(false)
      setIsReRequestDialogOpen(false)
    }
  }

  // 실사 결과 발송 처리
  const handleSendInvestigationResults = async (data: { purchaseComment?: string }) => {
    try {
      setIsLoading(true)

      // 완료된 실사 중 승인된 결과만 필터링
      const approvedInvestigations = selectedRows.filter(row =>
        row.original.investigation &&
        row.original.investigation.investigationStatus === "COMPLETED" &&
        row.original.investigation.evaluationResult === "APPROVED"
      )

      if (approvedInvestigations.length === 0) {
        toast.error("발송할 실사 결과가 없습니다. 완료되고 승인된 실사만 결과를 발송할 수 있습니다.")
        return
      }

      // 서버 액션 호출
      const result = await sendInvestigationResultsAction({
        investigationIds: approvedInvestigations.map(row => row.original.investigation!.id),
        purchaseComment: data.purchaseComment,
      })

      if (result.success) {
        toast.success(result.message || `${result.data?.successCount || 0}개 업체에 대한 실사 결과가 발송되었습니다.`)
        window.location.reload()
      } else {
        toast.error(result.error || "실사 결과 발송 처리 중 오류가 발생했습니다.")
      }
    } catch (error) {
      console.error("실사 결과 발송 중 오류 발생:", error)
      toast.error("실사 결과 발송 중 오류가 발생했습니다.")
    } finally {
      setIsLoading(false)
      setIsSendResultsDialogOpen(false)
    }
  }

  // 승인된 업체 수 확인 (미실사 PQ 제외)
  const approvedPQsCount = selectedRows.filter(row =>
    row.original.status === "APPROVED" && 
    !row.original.investigation && 
    row.original.type !== "NON_INSPECTION"
  ).length

  // 계획 상태 실사 수 확인
  const plannedInvestigationsCount = selectedRows.filter(row =>
    row.original.investigation &&
    row.original.investigation.investigationStatus === "PLANNED"
  ).length

  // 완료된 실사 수 확인 (승인된 결과만)
  const completedInvestigationsCount = selectedRows.filter(row =>
    row.original.investigation &&
    row.original.investigation.investigationStatus === "COMPLETED" &&
    row.original.investigation.evaluationResult === "APPROVED"
  ).length

  // 취소된 실사 수 확인
  const canceledInvestigationsCount = selectedRows.filter(row =>
    row.original.investigation &&
    row.original.investigation.investigationStatus === "CANCELED"
  ).length

  // 미실사 PQ가 선택되었는지 확인
  const hasNonInspectionPQ = selectedRows.some(row => 
    row.original.type === "NON_INSPECTION"
  )

  // 실사 방법 라벨 변환 함수
  const getInvestigationMethodLabel = (method: string): string => {
    switch (method) {
      case "PURCHASE_SELF_EVAL":
        return "구매자체평가"
      case "DOCUMENT_EVAL":
        return "서류평가"
      case "PRODUCT_INSPECTION":
        return "제품검사평가"
      case "SITE_VISIT_EVAL":
        return "방문실사평가"
      default:
        return method
    }
  }

  // 실사 결과 발송용 데이터 준비
  const auditResults = selectedRows
    .filter(row => 
      row.original.investigation &&
      row.original.investigation.investigationStatus === "COMPLETED" &&
      row.original.investigation.evaluationResult === "APPROVED"
    )
    .map(row => {
      const investigation = row.original.investigation!
      const pqSubmission = row.original
      
      // pqItems를 상세하게 포맷팅 (itemCode-itemName 형태로 모든 항목 표시)
      const formatAuditItem = (pqItems: any): string => {
        if (!pqItems) return pqSubmission.projectName || "N/A";
        
        try {
          // 이미 파싱된 객체 배열인 경우
          if (Array.isArray(pqItems)) {
            return pqItems.map(item => {
              if (typeof item === 'string') return item;
              if (typeof item === 'object') {
                const code = item.itemCode || item.code || "";
                const name = item.itemName || item.name || "";
                if (code && name) return `${code}-${name}`;
                return name || code || String(item);
              }
              return String(item);
            }).join(', ');
          }
          
          // JSON 문자열인 경우
          if (typeof pqItems === 'string') {
            try {
              const parsed = JSON.parse(pqItems);
              if (Array.isArray(parsed)) {
                return parsed.map(item => {
                  if (typeof item === 'string') return item;
                  if (typeof item === 'object') {
                    const code = item.itemCode || item.code || "";
                    const name = item.itemName || item.name || "";
                    if (code && name) return `${code}-${name}`;
                    return name || code || String(item);
                  }
                  return String(item);
                }).join(', ');
              }
              return String(parsed);
            } catch {
              return String(pqItems);
            }
          }
          
          // 기타 경우
          return String(pqItems);
        } catch {
          return pqSubmission.projectName || "N/A";
        }
      };
      
      return {
        id: investigation.id,
        vendorCode: row.original.vendorCode || "N/A",
        vendorName: row.original.vendorName || "N/A",
        vendorEmail: row.original.email || "N/A",
        vendorContactPerson: (row.original as any).representativeName || row.original.vendorName || "N/A",
        pqNumber: pqSubmission.pqNumber || "N/A",
        auditItem: formatAuditItem(pqSubmission.pqItems),
        auditFactoryAddress: investigation.investigationAddress || "N/A",
        auditMethod: getInvestigationMethodLabel(investigation.investigationMethod || ""),
        auditResult: investigation.evaluationResult === "APPROVED" ? "Pass(승인)" : 
                     investigation.evaluationResult === "SUPPLEMENT" ? "Pass(조건부승인)" : 
                     investigation.evaluationResult === "REJECTED" ? "Fail(미승인)" : "N/A",
        additionalNotes: investigation.investigationNotes || undefined,
        investigationNotes: investigation.investigationNotes || undefined,
      }
    })

  return (
    <>
      <div className="flex items-center gap-2">
        {/* 실사 의뢰 버튼 */}
        <Button
          variant="outline"
          size="sm"
          onClick={handleOpenRequestDialog} // 여기를 수정: 새로운 핸들러 함수 사용
          disabled={isLoading || selectedRows.length === 0 || hasNonInspectionPQ}
          className="gap-2"
          title={hasNonInspectionPQ ? "미실사 PQ는 실사 의뢰할 수 없습니다." : undefined}
        >
          <ClipboardCheck className="size-4" aria-hidden="true" />
          <span className="hidden sm:inline">실사 의뢰</span>
        </Button>

        {/* 실사 의뢰 취소 버튼 */}
        <Button
          variant="outline"
          size="sm"
          onClick={() => setIsCancelDialogOpen(true)}
          disabled={isLoading || selectedRows.length === 0}
          className="gap-2"
        >
          <X className="size-4" aria-hidden="true" />
          <span className="hidden sm:inline">실사 취소</span>
        </Button>

        {/* 실사 재의뢰 버튼 */}
        <Button
          variant="outline"
          size="sm"
          onClick={() => setIsReRequestDialogOpen(true)}
          disabled={isLoading || selectedRows.length === 0}
          className="gap-2"
        >
          <RefreshCw className="size-4" aria-hidden="true" />
          <span className="hidden sm:inline">실사 재의뢰</span>
        </Button>

        {/* 실사 결과 발송 버튼 */}
        <Button
          variant="outline"
          size="sm"
          onClick={() => setIsSendResultsDialogOpen(true)}
          disabled={isLoading || selectedRows.length === 0}
          className="gap-2"
        >
          <Send className="size-4" aria-hidden="true" />
          <span className="hidden sm:inline">결과 발송</span>
        </Button>

        {/** Export 버튼 */}
        <Button
          variant="outline"
          size="sm"
          onClick={() =>
            exportTableToExcel(table, {
              filename: "vendors-pq-submissions",
              excludeColumns: ["select", "actions"],
            })
          }
          className="gap-2"
        >
          <Download className="size-4" aria-hidden="true" />
          <span className="hidden sm:inline">Export</span>
        </Button>
      </div>

      {/* 실사 의뢰 Dialog */}
      <RequestInvestigationDialog
        isOpen={isRequestDialogOpen}
        onClose={handleCloseRequestDialog} // 새로운 핸들러로 변경
        onSubmit={handleRequestInvestigation}
        selectedCount={approvedPQsCount}
        initialData={dialogInitialData} // 초기 데이터 전달
      />


      {/* 실사 취소 Dialog */}
      <CancelInvestigationDialog
        isOpen={isCancelDialogOpen}
        onClose={() => setIsCancelDialogOpen(false)}
        onConfirm={handleCancelInvestigation}
        selectedCount={plannedInvestigationsCount}
      />

      {/* 실사 재의뢰 Dialog */}
      <ReRequestInvestigationDialog
        isOpen={isReRequestDialogOpen}
        onClose={() => setIsReRequestDialogOpen(false)}
        onConfirm={handleReRequestInvestigation}
        selectedCount={canceledInvestigationsCount}
      />

      {/* 결과 발송 Dialog */}
      <SendResultsDialog
        isOpen={isSendResultsDialogOpen}
        onClose={() => setIsSendResultsDialogOpen(false)}
        onConfirm={handleSendInvestigationResults}
        selectedCount={completedInvestigationsCount}
        auditResults={auditResults}
      />
    </>
  )
}