summaryrefslogtreecommitdiff
path: root/lib/rfq-last/table/rfq-items-dialog.tsx
blob: c640f3bd37353d5a71b1568e49f97301c5dbed63 (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
"use client"

import * as React from "react"
import { format } from "date-fns"
import { Package, ExternalLink, Download, FileText } from "lucide-react"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Skeleton } from "@/components/ui/skeleton"
import { Separator } from "@/components/ui/separator"
import { toast } from "sonner"
import { RfqsLastView } from "@/db/schema"
import { getRfqItemsAction } from "../service"
import { getDesignDocumentsForRfqItemsAction } from "@/lib/pos"
import { downloadFile } from "@/lib/file-download"

// 품목 타입
interface RfqItem {
  id: number
  rfqsLastId: number | null
  rfqItem: string | null
  prItem: string | null
  prNo: string | null
  materialCode: string | null
  materialCategory: string | null
  acc: string | null
  materialDescription: string | null
  size: string | null
  deliveryDate: Date | null
  quantity: number | null
  uom: string | null
  grossWeight: number | null
  gwUom: string | null
  specNo: string | null
  specUrl: string | null
  trackingNo: string | null
  majorYn: boolean | null
  remark: string | null
  projectDef: string | null
  projectSc: string | null
  projectKl: string | null
  projectLc: string | null
  projectDl: string | null
  // RFQ 관련 정보
  rfqCode: string | null
  rfqType: string | null
  rfqTitle: string | null
  itemCode: string | null
  itemName: string | null
  projectCode: string | null
  projectName: string | null
}

interface ItemStatistics {
  total: number
  major: number
  regular: number
  totalQuantity: number
  totalWeight: number
}

interface RfqItemsDialogProps {
  isOpen: boolean
  onClose: () => void
  rfqData: RfqsLastView
}

export function RfqItemsDialog({ isOpen, onClose, rfqData }: RfqItemsDialogProps) {
  const [items, setItems] = React.useState<RfqItem[]>([])
  const [statistics, setStatistics] = React.useState<ItemStatistics | null>(null)
  const [isLoading, setIsLoading] = React.useState(false)
  // 자재코드별 설계 문서 매핑
  const [designDocuments, setDesignDocuments] = React.useState<Record<string, {
    id: number;
    fileName: string;
    filePath: string;
    fileSize: number | null;
    fileType: string | null;
    description: string | null;
  }>>({})
  const [isLoadingDocs, setIsLoadingDocs] = React.useState(false)

  // 품목 목록 및 설계 문서 로드
  React.useEffect(() => {
    if (!isOpen || !rfqData.id) return

    const loadData = async () => {
      setIsLoading(true)
      setIsLoadingDocs(true)
      
      try {
        // 1. 품목 목록 로드
        const itemsResult = await getRfqItemsAction(rfqData.id)
        
        if (itemsResult.success) {
          setItems(itemsResult.data)
          setStatistics(itemsResult.statistics || null)
        } else {
          toast.error(itemsResult.error || "품목을 불러오는데 실패했습니다")
          setItems([])
          setStatistics(null)
        }

        // 2. 설계 문서 매핑 로드
        const docsResult = await getDesignDocumentsForRfqItemsAction(rfqData.id)
        
        if (docsResult.success && docsResult.documents) {
          setDesignDocuments(docsResult.documents)
        } else {
          console.warn("설계 문서 매핑 로드 실패:", docsResult.error)
          setDesignDocuments({})
        }
        
      } catch (error) {
        console.error("데이터 로드 오류:", error)
        toast.error("데이터를 불러오는데 실패했습니다")
        setItems([])
        setStatistics(null)
        setDesignDocuments({})
      } finally {
        setIsLoading(false)
        setIsLoadingDocs(false)
      }
    }

    loadData()
  }, [isOpen, rfqData.id])

  // 사양서 링크 열기
  const handleOpenSpec = (specUrl: string) => {
    window.open(specUrl, '_blank', 'noopener,noreferrer')
  }

  // 설계 문서 다운로드
  const handleDownloadDesignDoc = async (materialCode: string, fileName: string, filePath: string) => {
    try {
      await downloadFile(filePath, fileName, {
        action: 'download',
        showToast: true
      })
    } catch (error) {
      console.error("설계 문서 다운로드 오류:", error)
      toast.error("설계 문서 다운로드에 실패했습니다")
    }
  }

  // 파일 크기 포맷팅
  const formatFileSize = (bytes: number | null) => {
    if (!bytes) return ""
    const sizes = ['B', 'KB', 'MB', 'GB']
    if (bytes === 0) return '0 B'
    const i = Math.floor(Math.log(bytes) / Math.log(1024))
    return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i]
  }


  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-7xl h-[90vh] flex flex-col">
        <DialogHeader>
          <DialogTitle>견적 품목 목록</DialogTitle>
          <DialogDescription>
            {rfqData.rfqCode} - {rfqData.rfqTitle || rfqData.itemName || "품목 정보"}
          </DialogDescription>
        </DialogHeader>

        {/* 통계 정보 */}
        {statistics && !isLoading && (
          <>
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3 py-3">
<div className="text-center">
                <div className="text-2xl font-bold text-primary">{statistics.total}</div>
                <div className="text-xs text-muted-foreground">전체 품목</div>
              </div>
              {/* <div className="text-center">
                <div className="text-2xl font-bold text-blue-600">{statistics.major}</div>
                <div className="text-xs text-muted-foreground">주요 품목</div>
              </div> */}
              <div className="text-center">
                <div className="text-2xl font-bold text-gray-600">{statistics.regular}</div>
                <div className="text-xs text-muted-foreground">일반 품목</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-green-600">{statistics.totalQuantity.toLocaleString()}</div>
                <div className="text-xs text-muted-foreground">총 수량</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-orange-600">{statistics.totalWeight.toLocaleString()}</div>
                <div className="text-xs text-muted-foreground">총 중량 (KG)</div>
              </div>
            </div>
            <Separator />
          </>
        )}

        <ScrollArea className="flex-1">
          {isLoading ? (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[60px]">아이템</TableHead>
                  <TableHead className="w-[120px]">자재코드</TableHead>
                  <TableHead>자재명</TableHead>
                  <TableHead className="w-[80px]">수량</TableHead>
                  <TableHead className="w-[60px]">수량단위</TableHead>
                  <TableHead className="w-[80px]">중량</TableHead>
                  <TableHead className="w-[60px]">중량단위</TableHead>
                  <TableHead className="w-[100px]">납기일</TableHead>
                  <TableHead className="w-[100px]">PR번호</TableHead>
                  <TableHead className="w-[120px]">사양/설계문서</TableHead>
                  <TableHead>비고</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {[...Array(3)].map((_, i) => (
                  <TableRow key={i}>
                    <TableCell><Skeleton className="h-8 w-full" /></TableCell>
                    <TableCell><Skeleton className="h-8 w-full" /></TableCell>
                    <TableCell><Skeleton className="h-8 w-full" /></TableCell>
                    <TableCell><Skeleton className="h-8 w-full" /></TableCell>
                    <TableCell><Skeleton className="h-8 w-full" /></TableCell>
                    <TableCell><Skeleton className="h-8 w-full" /></TableCell>
                    <TableCell><Skeleton className="h-8 w-full" /></TableCell>
                    <TableCell><Skeleton className="h-8 w-full" /></TableCell>
                    <TableCell><Skeleton className="h-8 w-full" /></TableCell>
                    <TableCell><Skeleton className="h-8 w-full" /></TableCell>
                    <TableCell><Skeleton className="h-8 w-full" /></TableCell>
                    <TableCell><Skeleton className="h-8 w-full" /></TableCell>
                    <TableCell><Skeleton className="h-8 w-full" /></TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          ) : items.length === 0 ? (
            <div className="text-center text-muted-foreground py-12">
              <Package className="h-12 w-12 mx-auto mb-4 text-muted-foreground" />
              <p>품목이 없습니다.</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[60px]">아이템</TableHead>
                  <TableHead className="w-[120px]">자재코드</TableHead>
                  <TableHead>자재명</TableHead>
                  <TableHead className="w-[80px]">수량</TableHead>
                  <TableHead className="w-[60px]">수량단위</TableHead>
                  <TableHead className="w-[80px]">중량</TableHead>
                  <TableHead className="w-[60px]">중량단위</TableHead>
                  <TableHead className="w-[100px]">납기일</TableHead>
                  <TableHead className="w-[100px]">PR번호</TableHead>
                  <TableHead className="w-[100px]">PR 아이템 번호</TableHead>
                  <TableHead className="w-[120px]">사양/설계문서</TableHead>
                  <TableHead className="w-[100px]">프로젝트</TableHead>
                  <TableHead>비고</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {items.map((item, index) => (
                  <TableRow key={item.id} className={item.majorYn ? "bg-blue-50 border-l-4 border-l-blue-500" : ""}>
                    <TableCell>
                      <div className="flex flex-col items-center gap-1">
                        <span className="text-xs font-mono">#{index + 1}</span>
                        {item.majorYn && (
                          <Badge variant="default" className="text-xs px-1 py-0">
                            주요
                          </Badge>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-col">
                        <span className="font-mono text-sm font-medium">{item.materialCode || "-"}</span>
                        {item.acc && (
                          <span className="text-xs text-muted-foreground font-mono">
                            ACC: {item.acc}
                          </span>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-col">
                        <span className="text-sm font-medium" title={item.materialDescription || ""}>
                          {item.materialDescription || "-"}
                        </span>
                        {item.materialCategory && (
                          <span className="text-xs text-muted-foreground">
                            {item.materialCategory}
                          </span>
                        )}
                        {item.size && (
                          <span className="text-xs text-muted-foreground">
                            크기: {item.size}
                          </span>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm font-medium">
                        {item.quantity ? item.quantity.toLocaleString() : "-"}
                      </span>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-muted-foreground">
                        {item.uom || "-"}
                      </span>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm font-medium">
                        {item.grossWeight ? item.grossWeight.toLocaleString() : "-"}
                      </span>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-muted-foreground">
                        {item.gwUom || "-"}
                      </span>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm">
                        {item.deliveryDate ? format(new Date(item.deliveryDate), "yyyy-MM-dd") : "-"}
                      </span>
                    </TableCell>
                    <TableCell>
                      <span className="text-xs font-mono">{item.prNo || "-"}</span>
                    </TableCell>
                    <TableCell>
                      <span className="text-xs font-mono">{item.prItem || "-"}</span>
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-col gap-1">
                        {/* 기존 스펙 정보 */}
                        <div className="flex items-center gap-1">
                          {item.specNo && (
                            <span className="text-xs font-mono">{item.specNo}</span>
                          )}
                          {item.specUrl && (
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-5 w-5 p-0"
                              onClick={() => handleOpenSpec(item.specUrl!)}
                              title="사양서 열기"
                            >
                              <ExternalLink className="h-3 w-3" />
                            </Button>
                          )}
                        </div>
                        
                        {/* 설계 문서 다운로드 */}
                        {item.materialCode && designDocuments[item.materialCode] && (
                          <div className="flex items-center gap-1">
                            <FileText className="h-3 w-3 text-blue-500" />
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-5 p-1 text-xs text-blue-600 hover:text-blue-800"
                              onClick={() => handleDownloadDesignDoc(
                                item.materialCode!,
                                designDocuments[item.materialCode!].fileName,
                                designDocuments[item.materialCode!].filePath
                              )}
                              title={`설계문서: ${designDocuments[item.materialCode!].fileName} (${formatFileSize(designDocuments[item.materialCode!].fileSize)})`}
                            >
                              <Download className="h-3 w-3 mr-1" />
                              설계문서
                            </Button>
                          </div>
                        )}
                        
                        {/* 트래킹 번호 */}
                        {item.trackingNo && (
                          <div className="text-xs text-muted-foreground">
                            TRK: {item.trackingNo}
                          </div>
                        )}
                        
                        {/* 설계 문서 로딩 상태 */}
                        {isLoadingDocs && item.materialCode && (
                          <div className="text-xs text-muted-foreground">
                            설계문서 확인 중...
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="text-xs">
                        {[
                          item.projectDef && `${item.projectDef}`,
                          item.projectSc && `SC: ${item.projectSc}`,
                          item.projectKl && `KL: ${item.projectKl}`,
                          item.projectLc && `LC: ${item.projectLc}`,
                          item.projectDl && `DL: ${item.projectDl}`
                        ].filter(Boolean).join(" | ") || "-"}
                      </div>
                    </TableCell>
                    <TableCell>
                      <span className="text-xs" title={item.remark || ""}>
                        {item.remark ? (item.remark.length > 30 ? `${item.remark.slice(0, 30)}...` : item.remark) : "-"}
                      </span>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </ScrollArea>

        {/* 하단 통계 정보 */}
        {statistics && !isLoading && (
          <div className="border-t pt-3 text-xs text-muted-foreground">
            <div className="flex justify-between items-center">
              <span>
                총 {statistics.total}개 품목 
                {/* (주요: {statistics.major}개, 일반: {statistics.regular}개) */}
              </span>
              <span>
                전체 수량: {statistics.totalQuantity.toLocaleString()} | 
                전체 중량: {statistics.totalWeight.toLocaleString()} KG
              </span>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  )
}