summaryrefslogtreecommitdiff
path: root/lib/vendor-document-list/ship/bulk-b4-upload-dialog.tsx
blob: 3ff2f46782638bb3cba72abc65dd3bde9982f0ae (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
545
546
547
548
549
550
551
552
"use client"

import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { toast } from "sonner"
import { useRouter } from "next/navigation"

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import { Button } from "@/components/ui/button"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import {
  Upload,
  X,
  Loader2,
  CheckCircle2,
  AlertCircle,
  AlertTriangle,
  FileText,
} from "lucide-react"

import { bulkUploadB4Documents } from "../enhanced-document-service"

// 파일명 파싱 유틸리티
function parseFileName(fileName: string): { docNumber: string | null; revision: string | null } {
  // 공백으로 단어 분리 (첫 번째는 파일명으로 무시)
  const words = fileName.trim().split(/\s+/).filter(word => word.length > 0)

  if (words.length < 2) {
    return { docNumber: null, revision: null }
  }

  // 마지막 단어에서 확장자와 리비전을 분리
  const lastWord = words[words.length - 1]
  const lastDotIndex = lastWord.lastIndexOf('.')

  let revision: string | null = null

  if (lastDotIndex !== -1) {
    // 마지막 '.' 기준으로 확장자 앞부분만 사용
    const beforeExt = lastWord.substring(0, lastDotIndex)

    // revision 패턴 찾기 (R01, r01, REV01, rev01 등)
    const revisionMatch = beforeExt.match(/[Rr](?:EV)?(\d+)/)
    revision = revisionMatch ? revisionMatch[0].toUpperCase() : null
  }

  // 문서번호: 첫 번째(파일명)와 마지막(REV.ext)을 제외한 모든 단어들을 '-'로 연결
  const docWords = words.slice(1, -1) // 첫 번째와 마지막 제외
  const docNumber = docWords.length > 0
    ? docWords.join('-').toUpperCase()
    : null

  return { docNumber, revision }
}

// Form schema
const formSchema = z.object({
  projectId: z.string().min(1, "Please select a project"),
  files: z.array(z.instanceof(File)).min(1, "Please select files"),
})

export interface ProjectOption {
  id: string
  code: string
}

interface BulkB4UploadDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  projectOptions: ProjectOption[]
}

interface ParsedFile {
  file: File
  docNumber: string | null
  revision: string | null
  status: 'pending' | 'uploading' | 'success' | 'error' | 'ignored'
  message?: string
}

export function BulkB4UploadDialog({ 
  open, 
  onOpenChange,
  projectOptions
}: BulkB4UploadDialogProps) {
  const [isUploading, setIsUploading] = React.useState(false)
  const [parsedFiles, setParsedFiles] = React.useState<ParsedFile[]>([])
  const [isDragging, setIsDragging] = React.useState(false)
  const [currentProjectId, setCurrentProjectId] = React.useState<string>("")
  const [showProjectChangeWarning, setShowProjectChangeWarning] = React.useState(false)
  const [pendingProjectId, setPendingProjectId] = React.useState<string>("")
  const router = useRouter()
  
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      projectId: "",
      files: [],
    },
  })
  
  // 프로젝트 변경 핸들러
  const handleProjectChange = (newProjectId: string) => {
    // 기존 파일 목록이 있고, 다른 프로젝트로 변경하는 경우 경고 표시
    if (parsedFiles.length > 0 && currentProjectId && currentProjectId !== newProjectId) {
      setPendingProjectId(newProjectId)
      setShowProjectChangeWarning(true)
    } else {
      // 파일 목록이 비어있거나 첫 선택인 경우 바로 변경
      setCurrentProjectId(newProjectId)
      form.setValue("projectId", newProjectId)
    }
  }
  
  // 프로젝트 변경 확인 처리
  const confirmProjectChange = () => {
    // 파일 목록 초기화하고 프로젝트 변경
    setParsedFiles([])
    form.setValue("files", [])
    setCurrentProjectId(pendingProjectId)
    form.setValue("projectId", pendingProjectId)
    setShowProjectChangeWarning(false)
    setPendingProjectId("")
  }
  
  // 프로젝트 변경 취소 처리
  const cancelProjectChange = () => {
    setShowProjectChangeWarning(false)
    setPendingProjectId("")
  }
  
  // 파일 선택 시 파싱
  const handleFilesChange = (files: File[]) => {
    const parsed = files.map(file => {
      const { docNumber, revision } = parseFileName(file.name)
      return {
        file,
        docNumber,
        revision,
        status: docNumber ? 'pending' as const : 'ignored' as const,
        message: !docNumber ? 'docNumber를 찾을 수 없음' : undefined
      }
    })

    // 기존 파일들과 새 파일들을 합침 (중복 파일명은 제외)
    const existingFileNames = new Set(parsedFiles.map(pf => pf.file.name))
    const newFiles = parsed.filter(pf => !existingFileNames.has(pf.file.name))
    const combinedParsed = [...parsedFiles, ...newFiles]
    const combinedFiles = [...parsedFiles.map(pf => pf.file), ...newFiles.map(pf => pf.file)]

    setParsedFiles(combinedParsed)
    form.setValue("files", combinedFiles)
  }
  
  // 파일 제거
  const removeFile = (index: number) => {
    const newParsedFiles = parsedFiles.filter((_, i) => i !== index)
    setParsedFiles(newParsedFiles)
    form.setValue("files", newParsedFiles.map(pf => pf.file))
  }
  
  // Drag & Drop 핸들러
  const handleDragEnter = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setIsDragging(true)
  }
  
  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    // 자식 요소로 이동할 때도 leave가 발생하므로 실제로 영역을 벗어날 때만 처리
    if (e.currentTarget === e.target) {
      setIsDragging(false)
    }
  }
  
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    // 드롭 가능하도록 설정
    e.dataTransfer.dropEffect = 'copy'
  }
  
  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setIsDragging(false)
    
    const droppedFiles = Array.from(e.dataTransfer.files)
    if (droppedFiles.length > 0) {
      handleFilesChange(droppedFiles)
    }
  }
  
  // 업로드 처리
  async function onSubmit(values: z.infer<typeof formSchema>) {
    setIsUploading(true)
    
    try {
      // 유효한 파일만 필터링
      const validFiles = parsedFiles.filter(pf => pf.docNumber && pf.status === 'pending')
      
      if (validFiles.length === 0) {
        toast.error("업로드 가능한 파일이 없습니다")
        return
      }
      
      // 파일별로 상태 업데이트
      setParsedFiles(prev => prev.map(pf => 
        pf.docNumber && pf.status === 'pending' 
          ? { ...pf, status: 'uploading' as const }
          : pf
      ))
      
      // FormData 생성
      const formData = new FormData()
      formData.append("projectId", values.projectId)
      
      validFiles.forEach((pf, index) => {
        formData.append(`file_${index}`, pf.file)
        formData.append(`docNumber_${index}`, pf.docNumber!)
        formData.append(`revision_${index}`, pf.revision || "00")
      })
      
      formData.append("fileCount", String(validFiles.length))
      
      // 서버 액션 호출
      const result = await bulkUploadB4Documents(formData)
      
      if (result.success) {
        // 성공한 파일들 표시
        setParsedFiles(prev => prev.map(pf => {
          const uploadResult = result.results?.find(r => 
            r.docNumber === pf.docNumber && r.revision === (pf.revision || "00")
          )
          
          if (uploadResult?.success) {
            return { ...pf, status: 'success' as const, message: uploadResult.message }
          } else if (uploadResult) {
            return { ...pf, status: 'error' as const, message: uploadResult.error }
          }
          return pf
        }))
        
        toast.success(`${result.successCount}/${validFiles.length} 파일 업로드 완료`)
        
        // 모두 성공하면 닫기
        if (result.successCount === validFiles.length) {
          setTimeout(() => {
            onOpenChange(false)
            router.refresh()
          }, 1500)
        }
      } else {
        toast.error(result.error || "업로드 실패")
        setParsedFiles(prev => prev.map(pf => 
          pf.status === 'uploading' 
            ? { ...pf, status: 'error' as const, message: result.error }
            : pf
        ))
      }
    } catch {
      toast.error("업로드 중 오류가 발생했습니다")
      setParsedFiles(prev => prev.map(pf => 
        pf.status === 'uploading' 
          ? { ...pf, status: 'error' as const, message: '업로드 실패' }
          : pf
      ))
    } finally {
      setIsUploading(false)
    }
  }
  
  // 다이얼로그 닫을 때 초기화
  React.useEffect(() => {
    if (!open) {
      form.reset()
      setParsedFiles([])
      setIsDragging(false)
      setCurrentProjectId("")
      setShowProjectChangeWarning(false)
      setPendingProjectId("")
    }
  }, [open, form])
  
  const validFileCount = parsedFiles.filter(pf => pf.docNumber).length
  const ignoredFileCount = parsedFiles.filter(pf => !pf.docNumber).length
  
  return (
    <>
      {/* 프로젝트 변경 경고 다이얼로그 */}
      <AlertDialog open={showProjectChangeWarning} onOpenChange={setShowProjectChangeWarning}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>프로젝트 변경 확인</AlertDialogTitle>
            <AlertDialogDescription>
              프로젝트를 변경하면 현재 선택된 {parsedFiles.length}개의 파일이 모두 제거됩니다.
              계속하시겠습니까?
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={cancelProjectChange}>취소</AlertDialogCancel>
            <AlertDialogAction onClick={confirmProjectChange}>확인</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 메인 업로드 다이얼로그 */}
      <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl">
        <DialogHeader>
          <DialogTitle>B4 Document Bulk Upload</DialogTitle>
          <DialogDescription>
            Document numbers and revisions will be automatically extracted from file names.
            Format: [filename] [DOC1] [DOC2] ... [DOCN] [REV].[ext]
            Examples:
            &quot;testfile TANK ANA R01.pdf&quot; → Document Number: TANK-ANA, Revision: R01
            &quot;drawing ABC DEF GHI JKL R02.pdf&quot; → Document Number: ABC-DEF-GHI-JKL, Revision: R02
          </DialogDescription>
        </DialogHeader>
        
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="projectId"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Select Project *</FormLabel>
                  <Select 
                    onValueChange={handleProjectChange} 
                    value={field.value}
                    disabled={isUploading}
                  >
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="Please select a project" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {projectOptions.map(project => (
                        <SelectItem key={project.id} value={project.id}>
                          {project.code}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
            
            <div className="space-y-2">
              <FormLabel>Select Files</FormLabel>
              <div 
                className={`border-2 border-dashed rounded-lg p-6 transition-all duration-200 ${
                  !currentProjectId || isUploading
                    ? 'border-muted-foreground/20 opacity-50 cursor-not-allowed'
                    : isDragging 
                      ? 'border-primary bg-primary/5 scale-[1.02]' 
                      : 'border-muted-foreground/30 hover:border-muted-foreground/50'
                }`}
                onDragEnter={!currentProjectId || isUploading ? undefined : handleDragEnter}
                onDragLeave={!currentProjectId || isUploading ? undefined : handleDragLeave}
                onDragOver={!currentProjectId || isUploading ? undefined : handleDragOver}
                onDrop={!currentProjectId || isUploading ? undefined : handleDrop}
              >
                <input
                  type="file"
                  multiple
                  accept=".pdf,.doc,.docx,.xls,.xlsx,.dwg,.dxf"
                  onChange={(e) => handleFilesChange(Array.from(e.target.files || []))}
                  className="hidden"
                  id="file-upload"
                  disabled={!currentProjectId || isUploading}
                />
                <label
                  htmlFor="file-upload"
                  className={`flex flex-col items-center justify-center ${
                    !currentProjectId || isUploading ? 'cursor-not-allowed' : 'cursor-pointer'
                  }`}
                >
                  <Upload className={`h-10 w-10 mb-2 transition-colors ${
                    isDragging ? 'text-primary' : 'text-muted-foreground'
                  }`} />
                  <p className={`text-sm transition-colors ${
                    isDragging ? 'text-primary font-medium' : 'text-muted-foreground'
                  }`}>
                    {!currentProjectId 
                      ? '먼저 프로젝트를 선택해주세요' 
                      : isDragging 
                        ? '파일을 여기에 놓으세요' 
                        : '클릭하거나 파일을 드래그하여 업로드'
                    }
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">
                    PDF, DOC, DOCX, XLS, XLSX, DWG, DXF
                  </p>
                </label>
              </div>
            </div>
            
            {parsedFiles.length > 0 && (
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <FormLabel>Selected Files</FormLabel>
                  <div className="flex gap-2">
                    <Badge variant="default">
                      Valid: {validFileCount}
                    </Badge>
                    {ignoredFileCount > 0 && (
                      <Badge variant="secondary">
                        Ignored: {ignoredFileCount}
                      </Badge>
                    )}
                  </div>
                </div>
                
                <div className="max-h-[250px] border rounded-lg p-2 overflow-y-auto">
                  <div className="space-y-2">
                    {parsedFiles.map((pf, index) => (
                      <div
                        key={index}
                        className="flex items-center justify-between p-2 rounded-lg bg-muted/30"
                      >
                        <div className="flex items-center gap-3 flex-1">
                          <FileText className="h-4 w-4 text-muted-foreground" />
                          <div className="flex-1 min-w-0">
                            <p className="text-sm font-medium truncate">
                              {pf.file.name}
                            </p>
                            <div className="flex items-center gap-2 mt-1">
                              {pf.docNumber ? (
                                <>
                                  <Badge variant="outline" className="text-xs">
                                    Doc: {pf.docNumber}
                                  </Badge>
                                  {pf.revision && (
                                    <Badge variant="outline" className="text-xs">
                                      Rev: {pf.revision}
                                    </Badge>
                                  )}
                                </>
                              ) : (
                                <span className="text-xs text-muted-foreground">
                                  {pf.message}
                                </span>
                              )}
                            </div>
                          </div>
                          
                          <div className="flex items-center gap-2">
                            {pf.status === 'uploading' && (
                              <Loader2 className="h-4 w-4 animate-spin" />
                            )}
                            {pf.status === 'success' && (
                              <CheckCircle2 className="h-4 w-4 text-emerald-500 dark:text-emerald-400" />
                            )}
                            {pf.status === 'error' && (
                              <AlertCircle className="h-4 w-4 text-destructive" />
                            )}
                            {pf.status === 'ignored' && (
                              <AlertTriangle className="h-4 w-4 text-yellow-500" />
                            )}
                            
                            {!isUploading && (
                              <Button
                                type="button"
                                variant="ghost"
                                size="sm"
                                onClick={() => removeFile(index)}
                              >
                                <X className="h-4 w-4" />
                              </Button>
                            )}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}
            
            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
                disabled={isUploading}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={isUploading || validFileCount === 0 || !form.watch("projectId")}
              >
                {isUploading ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Uploading...
                  </>
                ) : (
                  <>
                    <Upload className="mr-2 h-4 w-4" />
                    Upload ({validFileCount} files)
                  </>
                )}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
    </>
  )
}