summaryrefslogtreecommitdiff
path: root/lib/vendor-document-list/table/enhanced-documents-table.tsx
blob: f840a10c1a2603e5ab16d63f4770c28507a824c6 (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
"use client"

import * as React from "react"
import type {
  DataTableAdvancedFilterField,
  DataTableFilterField,
  DataTableRowAction,
} from "@/types/table"

import { useDataTable } from "@/hooks/use-data-table"
import { StageRevisionExpandedContent } from "./stage-revision-expanded-content"
import { RevisionUploadDialog } from "./revision-upload-dialog"
// ✅ UpdateDocumentSheet import 추가
import { EnhancedDocTableToolbarActions } from "./enhanced-doc-table-toolbar-actions"
import { getEnhancedDocuments } from "../enhanced-document-service"
import type { EnhancedDocument } from "@/types/enhanced-documents"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { 
  AlertTriangle, 
  Clock, 
  TrendingUp, 
  Target, 
  Users,
} from "lucide-react"
import { getUpdatedEnhancedColumns } from "./enhanced-doc-table-columns"
import { ExpandableDataTable } from "@/components/data-table/expandable-data-table"
import { toast } from "sonner"
import { UpdateDocumentSheet } from "./update-doc-sheet"

interface FinalIntegratedDocumentsTableProps {
  promises: Promise<[Awaited<ReturnType<typeof getEnhancedDocuments>>]>
  selectedPackageId: number
  projectType: "ship" | "plant"
  // ✅ contractId 추가 (AddDocumentListDialog에서 필요)
  contractId: number
}

export function EnhancedDocumentsTable({
  promises,
  selectedPackageId,
  projectType,
  contractId, // ✅ contractId 추가
}: FinalIntegratedDocumentsTableProps) {
  // 데이터 로딩
  const [{ data, pageCount, total }] = React.use(promises)

  console.log(data)


  // 상태 관리
  const [rowAction, setRowAction] = React.useState<DataTableRowAction<EnhancedDocument> | null>(null)
  const [expandedRows, setExpandedRows] = React.useState<Set<string>>(new Set())
  const [quickFilter, setQuickFilter] = React.useState<'all' | 'overdue' | 'due_soon' | 'in_progress' | 'high_priority'>('all')
  
  // ✅ 스테이지 확장 상태 관리 (문서별로 관리)
  const [expandedStages, setExpandedStages] = React.useState<Record<string, Record<number, boolean>>>({})
  
  // ✅ 다이얼로그 상태들 - editDialogOpen -> editSheetOpen으로 변경
  const [uploadDialogOpen, setUploadDialogOpen] = React.useState(false)
  const [editSheetOpen, setEditSheetOpen] = React.useState(false) // Sheet로 변경
  const [selectedDocument, setSelectedDocument] = React.useState<EnhancedDocument | null>(null)
  const [selectedStage, setSelectedStage] = React.useState<string>("")
  const [selectedRevision, setSelectedRevision] = React.useState<string>("")
  const [uploadMode, setUploadMode] = React.useState<'new' | 'append'>('new')

  // 다음 리비전 계산 함수
  const getNextRevision = React.useCallback((currentRevision: string): string => {
    if (!currentRevision) return "A"
    
    // 알파벳 리비전 (A, B, C...)
    if (/^[A-Z]$/.test(currentRevision)) {
      const charCode = currentRevision.charCodeAt(0)
      if (charCode < 90) { // Z가 아닌 경우
        return String.fromCharCode(charCode + 1)
      }
      return "AA" // Z 다음은 AA
    }
    
    // 숫자 리비전 (1, 2, 3...)
    if (/^\d+$/.test(currentRevision)) {
      return String(parseInt(currentRevision) + 1)
    }
    
    // 기타 복잡한 리비전 형태는 그대로 반환
    return currentRevision
  }, [])

  // 컬럼 정의
  const columns = React.useMemo(
    () => getUpdatedEnhancedColumns({ 
      setRowAction: (action) => {
        setRowAction(action)
        if (action) {
          setSelectedDocument(action.row.original)
          
          // 액션 타입에 따른 다이얼로그 열기
          switch (action.type) {
            case "update":
              setEditSheetOpen(true) // ✅ Sheet 열기로 변경
              break
            case "upload":
              setSelectedStage(action.row.original.currentStageName || "")
              setUploadDialogOpen(true)
              break
            case "view":
              // 상세보기는 확장된 행으로 대체
              const rowId = action.row.id
              const newExpanded = new Set(expandedRows)
              if (newExpanded.has(rowId)) {
                newExpanded.delete(rowId)
              } else {
                newExpanded.add(rowId)
              }
              setExpandedRows(newExpanded)
              break
          }
        }
      },
      projectType
    }),
    [expandedRows, projectType]
  )

  // 통계 계산
  const stats = React.useMemo(() => {
    const totalDocs = data.length
    const overdue = data.filter(doc => doc.isOverdue).length
    const dueSoon = data.filter(doc => 
      doc.daysUntilDue !== null && 
      doc.daysUntilDue >= 0 && 
      doc.daysUntilDue <= 3
    ).length
    const inProgress = data.filter(doc => doc.currentStageStatus === 'IN_PROGRESS').length
    const highPriority = data.filter(doc => doc.currentStagePriority === 'HIGH').length
    const avgProgress = totalDocs > 0 
      ? Math.round(data.reduce((sum, doc) => sum + (doc.progressPercentage || 0), 0) / totalDocs)
      : 0
    
    return { 
      total: totalDocs, 
      overdue, 
      dueSoon, 
      inProgress, 
      highPriority, 
      avgProgress 
    }
  }, [data])

  // 빠른 필터링
  const filteredData = React.useMemo(() => {
    switch (quickFilter) {
      case 'overdue':
        return data.filter(doc => doc.isOverdue)
      case 'due_soon':
        return data.filter(doc => 
          doc.daysUntilDue !== null && 
          doc.daysUntilDue >= 0 && 
          doc.daysUntilDue <= 3
        )
      case 'in_progress':
        return data.filter(doc => doc.currentStageStatus === 'IN_PROGRESS')
      case 'high_priority':
        return data.filter(doc => doc.currentStagePriority === 'HIGH')
      default:
        return data
    }
  }, [data, quickFilter])

  // ✅ 핸들러 함수 수정: 모드 매개변수 추가
  const handleUploadRevision = React.useCallback((document: EnhancedDocument, stageName?: string, currentRevision?: string, mode: 'new' | 'append' = 'new') => {
    setSelectedDocument(document)
    setSelectedStage(stageName || document.currentStageName || "")
    setUploadMode(mode) // ✅ 모드 설정
    
    if (mode === 'new') {
      // 새 리비전 생성: currentRevision이 있으면 다음 리비전을 자동 계산
      if (currentRevision) {
        const nextRevision = getNextRevision(currentRevision)
        setSelectedRevision(nextRevision)
      } else {
        // 스테이지의 최신 리비전을 찾아서 다음 리비전 계산
        const latestRevision = findLatestRevisionInStage(document, stageName || document.currentStageName || "")
        if (latestRevision) {
          setSelectedRevision(getNextRevision(latestRevision))
        } else {
          setSelectedRevision("A") // 첫 번째 리비전
        }
      }
    } else {
      // 기존 리비전에 파일 추가: 같은 리비전 번호 사용
      setSelectedRevision(currentRevision || "")
    }
    
    setUploadDialogOpen(true)
  }, [getNextRevision])

  // ✅ 스테이지에서 최신 리비전을 찾는 헬퍼 함수
  const findLatestRevisionInStage = React.useCallback((document: EnhancedDocument, stageName: string) => {
    const stage = document.allStages?.find(s => s.stageName === stageName)
    if (!stage || !stage.revisions || stage.revisions.length === 0) {
      return null
    }
    
    // 리비전들을 정렬해서 최신 것 찾기 (간단한 알파벳/숫자 정렬)
    const sortedRevisions = [...stage.revisions].sort((a, b) => {
      // 알파벳과 숫자를 구분해서 정렬
      const aIsAlpha = /^[A-Z]+$/.test(a.revision)
      const bIsAlpha = /^[A-Z]+$/.test(b.revision)
      
      if (aIsAlpha && bIsAlpha) {
        return a.revision.localeCompare(b.revision)
      } else if (!aIsAlpha && !bIsAlpha) {
        return parseInt(a.revision) - parseInt(b.revision)
      } else {
        return aIsAlpha ? -1 : 1 // 알파벳이 숫자보다 먼저
      }
    })
    
    return sortedRevisions[sortedRevisions.length - 1]?.revision || null
  }, [])

  // ✅ 새 문서 추가 핸들러 - EnhancedDocTableToolbarActions에서 AddDocumentListDialog를 직접 렌더링하므로 별도 상태 관리 불필요
  const handleNewDocument = () => {
    // AddDocumentListDialog는 자체적으로 Dialog trigger를 가지므로 별도 처리 불필요
    // EnhancedDocTableToolbarActions에서 처리됨
  }

  // ✅ 스테이지 토글 핸들러 추가
  const handleStageToggle = React.useCallback((documentId: string, stageId: number) => {
    setExpandedStages(prev => ({
      ...prev,
      [documentId]: {
        ...prev[documentId],
        [stageId]: !prev[documentId]?.[stageId]
      }
    }))
  }, [])

  const handleBulkAction = async (action: string, selectedRows: any[]) => {
    try {
      if (action === 'bulk_approve') {
        // 일괄 승인 로직
        const stageIds = selectedRows
          .map(row => row.original.currentStageId)
          .filter(Boolean)
        
        if (stageIds.length > 0) {
          // await bulkUpdateStageStatus(stageIds, 'APPROVED')
          toast.success(`${stageIds.length}개 항목이 승인되었습니다.`)
        }
      } else if (action === 'bulk_upload') {
        // 일괄 업로드 로직
        toast.info("일괄 업로드 기능은 준비 중입니다.")
      }
    } catch (error) {
      toast.error("일괄 작업 중 오류가 발생했습니다.")
    }
  }

  // ✅ 다이얼로그 닫기 함수 수정
  const closeAllDialogs = () => {
    setUploadDialogOpen(false)
    setEditSheetOpen(false) // editDialogOpen -> editSheetOpen
    setSelectedDocument(null)
    setSelectedStage("")
    setSelectedRevision("")
    setUploadMode('new') // ✅ 모드 초기화
    setRowAction(null)
  }

  // ✅ EnhancedDocument를 UpdateDocumentSheet의 document 형식으로 변환하는 함수
  const convertToUpdateFormat = React.useCallback((doc: EnhancedDocument | null) => {
    if (!doc) return null
    
    return {
      id: doc.documentId,
      contractId: contractId, // contractId 사용
      docNumber: doc.docNumber,
      title: doc.title,
      status: doc.status || "pending", // 기본값 설정
      description: doc.description || null,
      remarks: doc.remarks || null,
    }
  }, [contractId])

  // 필터 필드 정의
  const filterFields: DataTableFilterField<EnhancedDocument>[] = [
    {
      label: "문서번호",
      value: "docNumber",
      placeholder: "문서번호로 검색...",
    },
    {
      label: "제목",
      value: "title", 
      placeholder: "제목으로 검색...",
    },
  ]

  const advancedFilterFields: DataTableAdvancedFilterField<EnhancedDocument>[] = [
    {
      id: "docNumber",
      label: "문서번호",
      type: "text",
    },
    {
      id: "title",
      label: "문서제목",
      type: "text",
    },
    {
      id: "currentStageStatus",
      label: "스테이지 상태",
      type: "select",
      options: [
        { label: "계획됨", value: "PLANNED" },
        { label: "진행중", value: "IN_PROGRESS" },
        { label: "제출됨", value: "SUBMITTED" },
        { label: "승인됨", value: "APPROVED" },
        { label: "완료됨", value: "COMPLETED" },
      ],
    },
    {
      id: "currentStagePriority",
      label: "우선순위",
      type: "select",
      options: [
        { label: "높음", value: "HIGH" },
        { label: "보통", value: "MEDIUM" },
        { label: "낮음", value: "LOW" },
      ],
    },
    {
      id: "isOverdue",
      label: "지연 여부",
      type: "select",
      options: [
        { label: "지연됨", value: "true" },
        { label: "정상", value: "false" },
      ],
    },
    {
      id: "currentStageAssigneeName",
      label: "담당자",
      type: "text",
    },
    {
      id: "createdAt",
      label: "생성일",
      type: "date",
    },
  ]

  // 데이터 테이블 훅
  const { table } = useDataTable({
    data: filteredData,
    columns,
    pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{ id: "createdAt", desc: true }],
      columnPinning: { right: ["actions"] },
    },
    getRowId: (originalRow) => String(originalRow.documentId),
    shallow: false,
    clearOnDefault: true,
    columnResizeMode: "onEnd",
  })

  return (
    <div className="space-y-6">
      {/* 통계 대시보드 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setQuickFilter('all')}>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">전체 문서</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.total}</div>
            <p className="text-xs text-muted-foreground">
              총 {total}개 중 {stats.total}개 표시
            </p>
          </CardContent>
        </Card>
        
        <Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setQuickFilter('overdue')}>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">지연 문서</CardTitle>
            <AlertTriangle className="h-4 w-4 text-red-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-red-600">{stats.overdue}</div>
            <p className="text-xs text-muted-foreground">즉시 확인 필요</p>
          </CardContent>
        </Card>
        
        <Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setQuickFilter('due_soon')}>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">마감 임박</CardTitle>
            <Clock className="h-4 w-4 text-orange-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-orange-600">{stats.dueSoon}</div>
            <p className="text-xs text-muted-foreground">3일 이내 마감</p>
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">평균 진행률</CardTitle>
            <Target className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{stats.avgProgress}%</div>
            <p className="text-xs text-muted-foreground">전체 프로젝트 진행도</p>
          </CardContent>
        </Card>
      </div>

      {/* 빠른 필터 */}
      <div className="flex gap-2 overflow-x-auto pb-2">
        <Badge 
          variant={quickFilter === 'all' ? 'default' : 'outline'}
          className="cursor-pointer hover:bg-primary hover:text-primary-foreground whitespace-nowrap"
          onClick={() => setQuickFilter('all')}
        >
          전체 ({stats.total})
        </Badge>
        <Badge 
          variant={quickFilter === 'overdue' ? 'destructive' : 'outline'}
          className="cursor-pointer hover:bg-destructive hover:text-destructive-foreground whitespace-nowrap"
          onClick={() => setQuickFilter('overdue')}
        >
          <AlertTriangle className="w-3 h-3 mr-1" />
          지연 ({stats.overdue})
        </Badge>
        <Badge 
          variant={quickFilter === 'due_soon' ? 'default' : 'outline'}
          className="cursor-pointer hover:bg-orange-500 hover:text-white whitespace-nowrap"
          onClick={() => setQuickFilter('due_soon')}
        >
          <Clock className="w-3 h-3 mr-1" />
          마감임박 ({stats.dueSoon})
        </Badge>
        <Badge 
          variant={quickFilter === 'in_progress' ? 'default' : 'outline'}
          className="cursor-pointer hover:bg-blue-500 hover:text-white whitespace-nowrap"
          onClick={() => setQuickFilter('in_progress')}
        >
          <Users className="w-3 h-3 mr-1" />
          진행중 ({stats.inProgress})
        </Badge>
        <Badge 
          variant={quickFilter === 'high_priority' ? 'destructive' : 'outline'}
          className="cursor-pointer hover:bg-destructive hover:text-destructive-foreground whitespace-nowrap"
          onClick={() => setQuickFilter('high_priority')}
        >
          <Target className="w-3 h-3 mr-1" />
          높은우선순위 ({stats.highPriority})
        </Badge>
      </div>

      {/* 메인 테이블 - 가로스크롤 문제 해결을 위한 구조 개선 */}
      <div className="space-y-4">
        <div className="rounded-md border bg-white overflow-hidden">
        <ExpandableDataTable 
          table={table}
          expandable={true}
          expandedRows={expandedRows}
          setExpandedRows={setExpandedRows}
          renderExpandedContent={(document) => (
            <div className="">
              <StageRevisionExpandedContent 
                document={document}
                onUploadRevision={handleUploadRevision}
                projectType={projectType}
                expandedStages={expandedStages[String(document.documentId)] || {}}
                onStageToggle={(stageId) => handleStageToggle(String(document.documentId), stageId)}
              />
            </div>
          )}
          expandedRowClassName="!p-0"
          // clickableColumns={[
          //   'docNumber',    
          //   'title',        
          //   'currentStageStatus', 
          //   'progressPercentage', 
          // ]}
          excludeFromClick={[
            'actions',      
            'select'        
          ]}
        >
            <DataTableAdvancedToolbar
              table={table}
              filterFields={advancedFilterFields}
              shallow={false}
            >
              <EnhancedDocTableToolbarActions
                table={table}
                projectType={projectType}
                selectedPackageId={selectedPackageId}
                contractId={contractId} // ✅ contractId 추가
                onNewDocument={handleNewDocument}
                onBulkAction={handleBulkAction}
              />
            </DataTableAdvancedToolbar>
          </ExpandableDataTable>
        </div>
      </div>

      {/* ✅ 분리된 다이얼로그들 - UpdateDocumentSheet와 AddDocumentListDialog로 교체 */}
      
      {/* 리비전 업로드 다이얼로그 - mode props 추가 */}
      <RevisionUploadDialog
        open={uploadDialogOpen}
        onOpenChange={(open) => {
          if (!open) closeAllDialogs()
          else setUploadDialogOpen(open)
        }}
        document={selectedDocument}
        projectType={projectType}
        presetStage={selectedStage}
        presetRevision={selectedRevision}
        mode={uploadMode}
      />

      {/* ✅ 문서 편집 Sheet로 교체 */}
      <UpdateDocumentSheet
        open={editSheetOpen}
        onOpenChange={(open) => {
          if (!open) closeAllDialogs()
          else setEditSheetOpen(open)
        }}
        document={convertToUpdateFormat(selectedDocument)}
      />
    </div>
  )
}