summaryrefslogtreecommitdiff
path: root/lib/vendor-document-list/ship/enhanced-documents-table.tsx
blob: d92f16dd9d550dfae0bde06ef5660f0695562173 (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
// simplified-documents-table.tsx - Project Code 필터 기능 추가
"use client"

import React from "react"
import type {
  DataTableAdvancedFilterField,
} from "@/types/table"

import { useDataTable } from "@/hooks/use-data-table"
import { getUserVendorDocuments, getUserVendorDocumentStats } from "@/lib/vendor-document-list/enhanced-document-service"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { FileText, FileInput, FileOutput, Building2 } from "lucide-react"

import { Label } from "@/components/ui/label"
import { DataTable } from "@/components/data-table/data-table"
import { SimplifiedDocumentsView } from "@/db/schema"
import { getSimplifiedDocumentColumns } from "./enhanced-doc-table-columns"
import { EnhancedDocTableToolbarActions } from "./enhanced-doc-table-toolbar-actions"
import { useQueryStates, parseAsString, parseAsStringEnum, parseAsInteger } from "nuqs"

// 🔥 Project Code 필터를 위한 Select 컴포넌트 import 추가
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"

// DrawingKind별 설명 매핑
const DRAWING_KIND_INFO = {
  B3: {
    title: "B3 Vendor",
    description: "Approval-focused drawings progressing through Approval → Work stages",
    color: "bg-primary/10 text-primary border-primary/20"
  },
  B4: {
    title: "B4 GTT", 
    description: "DOLCE-integrated drawings progressing through Pre → Work stages",
    color: "bg-emerald-50 dark:bg-emerald-950/20 text-emerald-700 dark:text-emerald-400 border-emerald-200 dark:border-emerald-800"
  },
  B5: {
    title: "B5 FMEA",
    description: "Sequential drawings progressing through First → Second stages", 
    color: "bg-purple-50 dark:bg-purple-950/20 text-purple-700 dark:text-purple-400 border-purple-200 dark:border-purple-800"
  }
} as const

interface SimplifiedDocumentsTableProps {
  allPromises: Promise<[
    Awaited<ReturnType<typeof getUserVendorDocuments>>,
    Awaited<ReturnType<typeof getUserVendorDocumentStats>>
  ]>
  onDataLoaded?: (data: SimplifiedDocumentsView[]) => void
}

export function SimplifiedDocumentsTable({
  allPromises,
  onDataLoaded,
}: SimplifiedDocumentsTableProps) {
  // 🔥 React.use() 결과를 안전하게 처리
  const promiseResults = React.use(allPromises)
  const [documentResult, statsResult] = promiseResults
  
  // 🔥 데이터 구조분해를 메모이제이션
  const documentData = React.useMemo(() => documentResult as Awaited<ReturnType<typeof getUserVendorDocuments>>, [documentResult])
  const statsData = React.useMemo(() => statsResult as Awaited<ReturnType<typeof getUserVendorDocumentStats>>, [statsResult])
  
  const { data, pageCount, drawingKind } = documentData
  const { primaryDrawingKind, projectCodeStats: serverProjectCodeStats, projectB4Stats: serverProjectB4Stats } = statsData

  // 🔥 URL searchParams를 통한 필터 상태 관리
  const [{ b4FilterType, projectCode, page }, setQueryStates] = useQueryStates(
    {
      b4FilterType: parseAsStringEnum<'all' | 'gtt_deliverable' | 'shi_input'>(['all', 'gtt_deliverable', 'shi_input']).withDefault('all'),
      projectCode: parseAsString.withDefault('all'),
      page: parseAsInteger.withDefault(1),
    },
    {
      history: "push",
      shallow: false,
    }
  )
  
  // page 변수는 현재 사용하지 않지만, setQueryStates에서 page를 업데이트하기 위해 필요
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const _ensurePageIsInState = page

  // 🔥 서버에서 받아온 프로젝트 코드 통계 사용 (필터링과 무관한 전체 통계)
  const projectCodeStats = React.useMemo(() => {
    return serverProjectCodeStats || []
  }, [serverProjectCodeStats])

  // 🔥 데이터 로드 콜백 (서버에서 이미 필터링되어 옴)
  React.useEffect(() => {
    if (data && onDataLoaded) {
      onDataLoaded(data)
    }
  }, [data, onDataLoaded])

  // 🔥 컬럼 메모이제이션 최적화 (b4FilterType에 따라 동적 변경)
  const columns = React.useMemo(
    () => getSimplifiedDocumentColumns({ b4FilterType }),
    [b4FilterType]
  )

  // 🔥 필터 필드들을 메모이제이션
  const advancedFilterFields: DataTableAdvancedFilterField<SimplifiedDocumentsView>[] = React.useMemo(() => [
    {
      id: "docNumber",
      label: "Document No",
      type: "text",
    },
    {
      id: "title",
      label: "Document Title",
      type: "text",
    },
    {
      id: "drawingKind",
      label: "Document Type",
      type: "select",
      options: [
        { label: "B3", value: "B3" },
        { label: "B4", value: "B4" },
        { label: "B5", value: "B5" },
      ],
    },
    {
      id: "projectCode",
      label: "Project Code",
      type: "text",
    },
    {
      id: "vendorName",
      label: "Vendor Name",
      type: "text",
    },
    {
      id: "vendorCode",
      label: "Vendor Code",
      type: "text",
    },
    {
      id: "pic",
      label: "PIC",
      type: "text",
    },
    {
      id: "status",
      label: "Document Status",
      type: "select",
      options: [
        { label: "Active", value: "ACTIVE" },
        { label: "Inactive", value: "INACTIVE" },
        { label: "Pending", value: "PENDING" },
        { label: "Completed", value: "COMPLETED" },
      ],
    },
    {
      id: "firstStageName",
      label: "First Stage",
      type: "text",
    },
    {
      id: "secondStageName",
      label: "Second Stage",
      type: "text",
    },
    {
      id: "firstStagePlanDate",
      label: "First Planned Date",
      type: "date",
    },
    {
      id: "firstStageActualDate",
      label: "First Actual Date",
      type: "date",
    },
    {
      id: "secondStagePlanDate",
      label: "Second Planned Date",
      type: "date",
    },
    {
      id: "secondStageActualDate",
      label: "Second Actual Date",
      type: "date",
    },
    {
      id: "issuedDate",
      label: "Issue Date",
      type: "date",
    },
    {
      id: "createdAt",
      label: "Created Date",
      type: "date",
    },
    {
      id: "updatedAt",
      label: "Updated Date",
      type: "date",
    },
  ], [])

  // 🔥 B4 전용 필드들 메모이제이션
  const b4FilterFields: DataTableAdvancedFilterField<SimplifiedDocumentsView>[] = React.useMemo(() => [
    {
      id: "cGbn",
      label: "C Category",
      type: "text",
    },
    {
      id: "dGbn",
      label: "D Category",
      type: "text",
    },
    {
      id: "degreeGbn",
      label: "Degree Category",
      type: "text",
    },
    {
      id: "deptGbn",
      label: "Dept Category",
      type: "text",
    },
    {
      id: "jGbn",
      label: "J Category",
      type: "text",
    },
    {
      id: "sGbn",
      label: "S Category",
      type: "text",
    },
  ], [])

  // 🔥 B4 문서 존재 여부 체크 메모이제이션
  const hasB4Documents = React.useMemo(() => {
    return data.some((doc: SimplifiedDocumentsView) => doc.drawingKind === 'B4')
  }, [data])

  // 🔥 최종 필터 필드 메모이제이션
  const finalFilterFields = React.useMemo(() => {
    return hasB4Documents ? [...advancedFilterFields, ...b4FilterFields] : advancedFilterFields
  }, [hasB4Documents, advancedFilterFields, b4FilterFields])

  // 🔥 테이블 초기 상태 메모이제이션
  const tableInitialState = React.useMemo(() => ({
    sorting: [{ id: "createdAt" as const, desc: true }],
    columnPinning: { right: ["actions"] },
  }), [])

  // 🔥 getRowId 함수 메모이제이션
  const getRowId = React.useCallback((originalRow: SimplifiedDocumentsView) => String(originalRow.documentId), [])

  const { table } = useDataTable({
    data,  // 서버에서 이미 필터링된 데이터 사용
    columns,
    pageCount,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: tableInitialState,
    getRowId,
    shallow: false,
    clearOnDefault: true,
    columnResizeMode: "onEnd",
  })

  // 🔥 활성 drawingKind 메모이제이션
  const activeDrawingKind = React.useMemo(() => {
    return drawingKind || primaryDrawingKind
  }, [drawingKind, primaryDrawingKind])

  // 🔥 kindInfo 메모이제이션
  const kindInfo = React.useMemo(() => {
    return activeDrawingKind ? DRAWING_KIND_INFO[activeDrawingKind] : null
  }, [activeDrawingKind])

  // 🔥 B4 문서 통계 - 프로젝트 필터링에 따라 동적으로 계산 (서버에서 받아온 전체 통계 기반)
  const b4Stats = React.useMemo(() => {
    if (!hasB4Documents || !serverProjectB4Stats) return null

    // 선택된 프로젝트에 따라 B4 통계 계산
    if (projectCode === 'all') {
      // 전체 프로젝트의 B4 통계
      const totalGttDeliverable = serverProjectB4Stats.reduce((sum, stat) => sum + stat.gttDeliverableCount, 0)
      const totalShiInput = serverProjectB4Stats.reduce((sum, stat) => sum + stat.shiInputCount, 0)
      return {
        gttDeliverableCount: totalGttDeliverable,
        shiInputCount: totalShiInput,
      }
    } else {
      // 특정 프로젝트의 B4 통계
      const projectStats = serverProjectB4Stats.find(stat => stat.code === projectCode)
      return projectStats ? {
        gttDeliverableCount: projectStats.gttDeliverableCount,
        shiInputCount: projectStats.shiInputCount,
      } : {
        gttDeliverableCount: 0,
        shiInputCount: 0,
      }
    }
  }, [hasB4Documents, serverProjectB4Stats, projectCode])

  return (
    <div className="w-full space-y-4">
      {/* DrawingKind 정보 간단 표시 */}
      {kindInfo && (
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            {/* 주석 처리된 부분은 그대로 유지 */}
          </div>
          <div className="flex items-center gap-2">
            <Badge variant="outline">
              {data.length} documents
            </Badge>
          </div>
        </div>
      )}

      {/* 🔥 필터 섹션 - Project Code 필터와 B4 필터를 함께 배치 */}
      <div className="space-y-3">
        {/* Project Code 필터 드롭다운 */}
        <div className="flex items-center gap-3 p-4 bg-muted/30 rounded-lg">
          <div className="flex items-center gap-2">
            <Building2 className="h-4 w-4 text-muted-foreground" />
            <Label className="text-sm font-medium">Project:</Label>
          </div>
          <Select
            value={projectCode}
            onValueChange={(value) => setQueryStates({ projectCode: value, page: 1 })}
          >
            <SelectTrigger className="w-[200px]">
              <SelectValue placeholder="Select a project" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">
                <div className="flex items-center justify-between w-full">
                  <span>All Projects</span>
                </div>
              </SelectItem>
              {projectCodeStats.filter(({ code }) => code !== 'Unknown').map(({ code }) => (
                <SelectItem key={code} value={code}>
                  <div className="flex items-center justify-between w-full">
                    <span className="font-mono">{code}</span>
                  </div>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          
          {projectCode !== 'all' && (
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setQueryStates({ projectCode: 'all', page: 1 })}
              className="h-8"
            >
              Clear filter
            </Button>
          )}
        </div>

        {/* B4 필터 버튼 - URL searchParams 업데이트로 변경 */}
        {hasB4Documents && b4Stats && (
          <div className="flex items-center gap-2 p-4 bg-muted/50 rounded-lg">
            <Label className="text-sm font-medium">Document Type:</Label>
            <div className="flex gap-2">
              <Button
                variant={b4FilterType === 'all' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setQueryStates({ b4FilterType: 'all', page: 1 })}
                className="gap-2"
              >
                <FileText className="h-4 w-4" />
                All
                <Badge variant="secondary" className="ml-1">
                  {b4Stats.gttDeliverableCount + b4Stats.shiInputCount}
                </Badge>
              </Button>
              <Button
                variant={b4FilterType === 'gtt_deliverable' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setQueryStates({ b4FilterType: 'gtt_deliverable', page: 1 })}
                className="gap-2"
              >
                <FileInput className="h-4 w-4" />
                GTT Deliverables
                <Badge variant="secondary" className="ml-1">
                  {b4Stats.gttDeliverableCount}
                </Badge>
              </Button>
              <Button
                variant={b4FilterType === 'shi_input' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setQueryStates({ b4FilterType: 'shi_input', page: 1 })}
                className="gap-2"
              >
                <FileOutput className="h-4 w-4" />
                SHI Input Document
                <Badge variant="secondary" className="ml-1">
                  {b4Stats.shiInputCount}
                </Badge>
              </Button>
            </div>
          </div>
        )}
      </div>

      {/* 테이블 */}
      <div className="overflow-x-auto">
        <DataTable table={table} compact>
          <DataTableAdvancedToolbar
            table={table}
            filterFields={finalFilterFields}
            shallow={false}
          >
            <EnhancedDocTableToolbarActions
              table={table}
              projectType="ship"
              b4={hasB4Documents && b4FilterType === 'gtt_deliverable'}
            />
          </DataTableAdvancedToolbar>
        </DataTable>
      </div>
    </div>
  )
}