summaryrefslogtreecommitdiff
path: root/lib/welding/table/ocr-table-toolbar-actions.tsx
blob: 120ff54fecfc04ab691148c204440302e15fc0b8 (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
"use client"

import * as React from "react"
import { type Table } from "@tanstack/react-table"
import { Download, RefreshCcw, Upload, FileText, Loader2, ChevronDown } from "lucide-react"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Progress } from "@/components/ui/progress"
import { Badge } from "@/components/ui/badge"
import { toast } from "sonner"
import { OcrRow } from "@/db/schema"
import { exportTableToExcel } from "@/lib/export_all"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { getOcrAllRows } from "../service"
import { exportOcrDataToExcel } from "./exporft-ocr-data"

interface OcrTableToolbarActionsProps {
  table: Table<OcrRow>
}

interface UploadProgress {
  stage: string
  progress: number
  message: string
}

export function OcrTableToolbarActions({ table }: OcrTableToolbarActionsProps) {
  const [isLoading, setIsLoading] = React.useState(false)
  const [isUploading, setIsUploading] = React.useState(false)
  const [uploadProgress, setUploadProgress] = React.useState<UploadProgress | null>(null)
  const [isUploadDialogOpen, setIsUploadDialogOpen] = React.useState(false)
  const [selectedFile, setSelectedFile] = React.useState<File | null>(null)
  const fileInputRef = React.useRef<HTMLInputElement>(null)
  const [isExporting, setIsExporting] = React.useState(false)

  // 다이얼로그 닫기 핸들러 - 업로드 중에는 닫기 방지
  const handleDialogOpenChange = (open: boolean) => {
    // 다이얼로그를 닫으려고 할 때
    if (!open) {
      // 업로드가 진행 중이면 닫기를 방지
      if (isUploading && uploadProgress?.stage !== "complete") {
        toast.warning("Cannot close while processing. Please wait for completion.", {
          description: "OCR processing is in progress..."
        })
        return // 다이얼로그를 닫지 않음
      }

      // 업로드가 진행 중이 아니거나 완료되었으면 초기화 후 닫기
      resetUpload()
    }

    setIsUploadDialogOpen(open)
  }

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      setSelectedFile(file)
    }
  }

  const validateFile = (file: File): string | null => {
    // 파일 크기 체크 (10MB)
    if (file.size > 10 * 1024 * 1024) {
      return "File size must be less than 10MB"
    }

    // 파일 타입 체크
    const allowedTypes = [
      'application/pdf',
      'image/jpeg',
      'image/jpg',
      'image/png',
      'image/tiff',
      'image/bmp'
    ]

    if (!allowedTypes.includes(file.type)) {
      return "Only PDF and image files (JPG, PNG, TIFF, BMP) are supported"
    }

    return null
  }

  const uploadFile = async () => {
    if (!selectedFile) {
      toast.error("Please select a file first")
      return
    }

    const validationError = validateFile(selectedFile)
    if (validationError) {
      toast.error(validationError)
      return
    }

    try {
      setIsUploading(true)
      setUploadProgress({
        stage: "preparing",
        progress: 10,
        message: "Preparing file upload..."
      })

      const formData = new FormData()
      formData.append('file', selectedFile)

      setUploadProgress({
        stage: "uploading",
        progress: 30,
        message: "Uploading file and processing..."
      })

      const response = await fetch('/api/ocr/enhanced', {
        method: 'POST',
        body: formData,
      })

      setUploadProgress({
        stage: "processing",
        progress: 70,
        message: "Analyzing document with OCR..."
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || 'OCR processing failed')
      }

      const result = await response.json()

      setUploadProgress({
        stage: "saving",
        progress: 90,
        message: "Saving results to database..."
      })

      if (result.success) {
        setUploadProgress({
          stage: "complete",
          progress: 100,
          message: "OCR processing completed successfully!"
        })

        toast.success(
          `OCR completed! Extracted ${result.metadata.totalRows} rows from ${result.metadata.totalTables} tables`,
          {
            description: result.warnings?.length
              ? `Warnings: ${result.warnings.join(', ')}`
              : undefined
          }
        )

        // 성공 후 다이얼로그 닫기 및 상태 초기화
        setTimeout(() => {
          setIsUploadDialogOpen(false)
          resetUpload()

          // 테이블 새로고침
          window.location.reload()
        }, 2000)

      } else {
        throw new Error(result.error || 'Unknown error occurred')
      }

    } catch (error) {
      console.error('Error uploading file:', error)
      toast.error(
        error instanceof Error
          ? error.message
          : 'An error occurred while processing the file'
      )
      setUploadProgress(null)
    } finally {
      setIsUploading(false)
    }
  }

  const resetUpload = () => {
    setSelectedFile(null)
    setUploadProgress(null)
    if (fileInputRef.current) {
      fileInputRef.current.value = ''
    }
  }

  // Cancel 버튼 핸들러
  const handleCancelClick = () => {
    if (isUploading && uploadProgress?.stage !== "complete") {
      // 업로드 진행 중이면 취소 불가능 메시지
      toast.warning("Cannot cancel while processing. Please wait for completion.", {
        description: "OCR processing cannot be interrupted safely."
      })
    } else {
      // 업로드 중이 아니거나 완료되었으면 다이얼로그 닫기
      setIsUploadDialogOpen(false)
      resetUpload()
    }
  }

  // 현재 페이지 데이터만 내보내기
  const exportCurrentPage = () => {
    exportTableToExcel(table, {
      filename: "OCR Result (Current Page)",
      excludeColumns: ["select", "actions"],
    })
  }

  // 전체 데이터 내보내기
  const exportAllData = async () => {
    if (isExporting) return

    setIsExporting(true)

    try {
      toast.loading("전체 데이터를 가져오는 중...", {
        description: "잠시만 기다려주세요."
      })

      // 모든 데이터 가져오기
      const allData = await getOcrAllRows()

      toast.dismiss()

      if (allData.length === 0) {
        toast.warning("내보낼 데이터가 없습니다.")
        return
      }

      console.log(allData)

      // 새로운 단순한 export 함수 사용
      await exportOcrDataToExcel(allData, `OCR Result (All Data - ${allData.length} rows)`)

      toast.success(`전체 데이터 ${allData.length}개 행이 성공적으로 내보내졌습니다.`)

    } catch (error) {
      console.error('Error exporting all data:', error)
      toast.error('전체 데이터 내보내기 중 오류가 발생했습니다.')
    } finally {
      setIsExporting(false)
    }
  }

  return (
    <div className="flex items-center gap-2">
      {/* OCR 업로드 다이얼로그 */}
      <Dialog open={isUploadDialogOpen} onOpenChange={handleDialogOpenChange}>
        <DialogTrigger asChild>
          <Button variant="samsung" size="sm" className="gap-2">
            <Upload className="size-4" aria-hidden="true" />
            <span className="hidden sm:inline">Upload OCR</span>
          </Button>
        </DialogTrigger>
        <DialogContent
          className="sm:max-w-md"
          // 업로드 중에는 ESC 키로도 닫기 방지
          onEscapeKeyDown={(e) => {
            if (isUploading && uploadProgress?.stage !== "complete") {
              e.preventDefault()
              toast.warning("Cannot close while processing. Please wait for completion.")
            }
          }}
          // 업로드 중에는 외부 클릭으로도 닫기 방지  
          onInteractOutside={(e) => {
            if (isUploading && uploadProgress?.stage !== "complete") {
              e.preventDefault()
              toast.warning("Cannot close while processing. Please wait for completion.")
            }
          }}
        >
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              Upload Document for OCR
              {/* 업로드 중일 때 로딩 인디케이터 표시 */}
              {isUploading && uploadProgress?.stage !== "complete" && (
                <Loader2 className="size-4 animate-spin text-muted-foreground" />
              )}
            </DialogTitle>
            <DialogDescription>
              {isUploading && uploadProgress?.stage !== "complete"
                ? "Processing in progress. Please do not close this dialog."
                : "Upload a PDF or image file to extract table data using OCR technology."
              }
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* 파일 선택 */}
            <div className="space-y-2">
              <Label htmlFor="file-upload">Select File</Label>
              <Input
                ref={fileInputRef}
                id="file-upload"
                type="file"
                accept=".pdf,.jpg,.jpeg,.png,.tiff,.bmp"
                onChange={handleFileSelect}
                disabled={isUploading}
              />
              <p className="text-xs text-muted-foreground">
                Supported formats: PDF, JPG, PNG, TIFF, BMP (Max 10MB)
              </p>
            </div>

            {/* 선택된 파일 정보 */}
            {selectedFile && (
              <div className="rounded-lg border p-3 space-y-2">
                <div className="flex items-center gap-2">
                  <FileText className="size-4 text-muted-foreground" />
                  <span className="text-sm font-medium">{selectedFile.name}</span>
                </div>
                <div className="flex items-center gap-4 text-xs text-muted-foreground">
                  <span>Size: {(selectedFile.size / 1024 / 1024).toFixed(2)} MB</span>
                  <span>Type: {selectedFile.type}</span>
                </div>
              </div>
            )}

            {/* 업로드 진행상황 */}
            {uploadProgress && (
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">Processing...</span>
                  <Badge variant={uploadProgress.stage === "complete" ? "default" : "secondary"}>
                    {uploadProgress.stage}
                  </Badge>
                </div>
                <Progress value={uploadProgress.progress} className="h-2" />
                <p className="text-xs text-muted-foreground">
                  {uploadProgress.message}
                </p>

                {/* 진행 중일 때 안내 메시지 */}
                {isUploading && uploadProgress.stage !== "complete" && (
                  <div className="flex items-center gap-2 p-2 bg-blue-50 dark:bg-blue-950/20 rounded-md">
                    <Loader2 className="size-3 animate-spin text-blue-600" />
                    <p className="text-xs text-blue-700 dark:text-blue-300">
                      Please wait... This dialog will close automatically when complete.
                    </p>
                  </div>
                )}
              </div>
            )}

            {/* 액션 버튼들 */}
            <div className="flex justify-end gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={handleCancelClick}
                disabled={false} // 항상 클릭 가능하지만 핸들러에서 처리
              >
                {isUploading && uploadProgress?.stage !== "complete" ? "Close" : "Cancel"}
              </Button>
              <Button
                size="sm"
                onClick={uploadFile}
                disabled={!selectedFile || isUploading}
                className="gap-2"
              >
                {isUploading ? (
                  <Loader2 className="size-4 animate-spin" aria-hidden="true" />
                ) : (
                  <Upload className="size-4" aria-hidden="true" />
                )}
                {isUploading ? "Processing..." : "Start OCR"}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Export 버튼 */}
      {/* Export 드롭다운 메뉴 */}
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            variant="outline"
            size="sm"
            className="gap-2"
            disabled={isExporting}
          >
            {isExporting ? (
              <Loader2 className="size-4 animate-spin" aria-hidden="true" />
            ) : (
              <Download className="size-4" aria-hidden="true" />
            )}
            <span className="hidden sm:inline">
              {isExporting ? "Exporting..." : "Export"}
            </span>
            <ChevronDown className="size-3" aria-hidden="true" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-[200px]">
          <DropdownMenuItem onClick={exportAllData} disabled={isExporting}>
            <Download className="mr-2 size-4" />
            전체 데이터 내보내기
          </DropdownMenuItem>
          <DropdownMenuSeparator />
          <DropdownMenuItem onClick={exportCurrentPage} disabled={isExporting}>
            <Download className="mr-2 size-4" />
            현재 페이지 내보내기
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  )
}