summaryrefslogtreecommitdiff
path: root/lib/vendor-document-list/table/revision-upload-dialog.tsx
blob: 546fa7a31ad675822ec3ac307a50c3af6f2379c1 (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
"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 { useSession } from "next-auth/react"
import { mutate } from "swr" // ✅ SWR mutate import 추가

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Dropzone,
  DropzoneDescription,
  DropzoneInput,
  DropzoneTitle,
  DropzoneUploadIcon,
  DropzoneZone,
} from "@/components/ui/dropzone"
import {
  FileList,
  FileListAction,
  FileListHeader,
  FileListIcon,
  FileListInfo,
  FileListItem,
  FileListName,
  FileListSize,
} from "@/components/ui/file-list"
import { Badge } from "@/components/ui/badge"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Upload, X, Loader2 } from "lucide-react"
import prettyBytes from "pretty-bytes"
import { EnhancedDocumentsView } from "@/db/schema/vendorDocu"

// 리비전 업로드 스키마
const revisionUploadSchema = z.object({
  stage: z.string().min(1, "스테이지는 필수입니다"),
  revision: z.string().min(1, "리비전은 필수입니다"),
  uploaderName: z.string().optional(),
  comment: z.string().optional(),
  attachments: z.array(z.instanceof(File)).min(1, "최소 1개 파일이 필요합니다"),
})

type RevisionUploadSchema = z.infer<typeof revisionUploadSchema>

interface RevisionUploadDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  document: EnhancedDocumentsView | null
  projectType: "ship" | "plant"
  presetStage?: string
  presetRevision?: string
  mode?: 'new' | 'append'
  onUploadComplete?: () => void // ✅ 업로드 완료 콜백 추가
}

function getTargetSystem(projectType: "ship" | "plant") {
  return projectType === "ship" ? "DOLCE" : "SWP"
}

export function RevisionUploadDialog({
  open,
  onOpenChange,
  document,
  projectType,
  presetStage,
  presetRevision,
  mode = 'new',
  onUploadComplete, // ✅ 추가된 prop
}: RevisionUploadDialogProps) {

  const targetSystem = React.useMemo(
    () => getTargetSystem(projectType),
    [projectType]
  )

  const [selectedFiles, setSelectedFiles] = React.useState<File[]>([])
  const [isUploading, setIsUploading] = React.useState(false)
  const [uploadProgress, setUploadProgress] = React.useState(0)
  const router = useRouter()

  // ✅ next-auth session 가져오기
  const { data: session } = useSession()

  // 사용 가능한 스테이지 옵션
  const stageOptions = React.useMemo(() => {
    if (document?.allStages) {
      return document.allStages.map(stage => stage.stageName)
    }
    return ["Issued for Review", "AFC", "Final Issue"]
  }, [document])

  const form = useForm<RevisionUploadSchema>({
    resolver: zodResolver(revisionUploadSchema),
    defaultValues: {
      stage: presetStage || document?.currentStageName || "",
      revision: presetRevision || "",
      uploaderName: session?.user?.name || "",
      comment: "",
      attachments: [],
    },
  })

  // ✅ session이 로드되면 uploaderName 업데이트
  React.useEffect(() => {
    if (session?.user?.name) {
      form.setValue('uploaderName', session.user.name)
    }
  }, [session?.user?.name, form])

  // ✅ presetStage와 presetRevision이 변경될 때 폼 값 업데이트
  React.useEffect(() => {
    if (presetStage) {
      form.setValue('stage', presetStage)
    }
    if (presetRevision) {
      form.setValue('revision', presetRevision)
    }
  }, [presetStage, presetRevision, form])

  // 파일 드롭 처리
  const handleDropAccepted = (acceptedFiles: File[]) => {
    const newFiles = [...selectedFiles, ...acceptedFiles]
    setSelectedFiles(newFiles)
    form.setValue('attachments', newFiles, { shouldValidate: true })
  }

  const removeFile = (index: number) => {
    const updatedFiles = [...selectedFiles]
    updatedFiles.splice(index, 1)
    setSelectedFiles(updatedFiles)
    form.setValue('attachments', updatedFiles, { shouldValidate: true })
  }

  // ✅ 캐시 갱신 함수
  const refreshCaches = async () => {
    try {
      // 1. 서버 컴포넌트 캐시 갱신 (Enhanced Documents 등)
      router.refresh()
      
      // 2. SWR 캐시 갱신 (Sync Status)
      if (document?.contractId) {
        await mutate(`/api/sync/status/${document.contractId}/${targetSystem}`)
        console.log('✅ Sync status cache refreshed')
      }
      
      // 3. 다른 관련 SWR 캐시들도 갱신 (필요시)
      await mutate(key => 
        typeof key === 'string' && 
        key.includes('sync') && 
        key.includes(String(document?.contractId))
      )
      
      // 4. 상위 컴포넌트 콜백 호출
      onUploadComplete?.()
      
      console.log('✅ All caches refreshed after upload')
    } catch (error) {
      console.error('❌ Cache refresh failed:', error)
    }
  }

  // 업로드 처리
  async function onSubmit(data: RevisionUploadSchema) {
    if (!document) return

    setIsUploading(true)
    setUploadProgress(0)

    try {
      const formData = new FormData()
      formData.append("documentId", String(document.documentId))
      formData.append("stage", data.stage)
      formData.append("revision", data.revision)
      formData.append("mode", mode)
      formData.append("targetSystem", targetSystem)

      if (data.uploaderName) {
        formData.append("uploaderName", data.uploaderName)
      }
      
      if (data.comment) {
        formData.append("comment", data.comment)
      }

      // 파일들 추가
      data.attachments.forEach((file) => {
        formData.append("attachments", file)
      })

      // 진행률 업데이트 시뮬레이션
      const updateProgress = (progress: number) => {
        setUploadProgress(Math.min(progress, 95))
      }

      // 파일 크기에 따른 진행률 시뮬레이션
      const totalSize = data.attachments.reduce((sum, file) => sum + file.size, 0)
      let uploadedSize = 0
      
      const progressInterval = setInterval(() => {
        uploadedSize += totalSize * 0.1
        const progress = Math.min((uploadedSize / totalSize) * 100, 90)
        updateProgress(progress)
      }, 300)

      // ✅ 실제 API 호출
      const response = await fetch('/api/revision-upload', {
        method: 'POST',
        body: formData,
      })

      clearInterval(progressInterval)

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || errorData.details || '업로드에 실패했습니다.')
      }

      const result = await response.json()
      setUploadProgress(100)

      toast.success(
        result.message || 
        `리비전 ${data.revision}이 성공적으로 업로드되었습니다. (${result.data?.uploadedFiles?.length || 0}개 파일)`
      )
      
      console.log('✅ 업로드 성공:', result)
      
      // ✅ 캐시 갱신 및 다이얼로그 닫기
      setTimeout(async () => {
        await refreshCaches()
        handleDialogClose()
      }, 1000)

    } catch (error) {
      console.error('❌ 업로드 오류:', error)
      toast.error(error instanceof Error ? error.message : "업로드 중 오류가 발생했습니다")
    } finally {
      setIsUploading(false)
      setTimeout(() => setUploadProgress(0), 2000)
    }
  }

  const handleDialogClose = () => {
    form.reset({
      stage: presetStage || document?.currentStageName || "",
      revision: presetRevision || "",
      uploaderName: session?.user?.name || "",
      comment: "",
      attachments: [],
    })
    setSelectedFiles([])
    setIsUploading(false)
    setUploadProgress(0)
    onOpenChange(false)
  }

  return (
    <Dialog open={open} onOpenChange={handleDialogClose}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Upload className="w-5 h-5" />
            {mode === 'new' ? '새 리비전 업로드' : '파일 추가'}
          </DialogTitle>
          <DialogDescription>
            {document ? `${document.docNumber} - ${document.title}` : 
             mode === 'new' ? "문서에 새 리비전을 업로드합니다." : "기존 리비전에 파일을 추가합니다."}
          </DialogDescription>
          
          <div className="flex items-center gap-2 pt-2">
            <Badge variant={projectType === "ship" ? "default" : "secondary"}>
              {projectType === "ship" ? "조선 프로젝트" : "플랜트 프로젝트"}
            </Badge>
            {/* ✅ 타겟 시스템 표시 추가 */}
            <Badge variant="outline" className="text-xs">
              → {targetSystem}
            </Badge>
            {session?.user?.name && (
              <Badge variant="outline" className="text-xs">
                업로더: {session.user.name}
              </Badge>
            )}
            {mode === 'append' && presetRevision && (
              <Badge variant="outline" className="text-xs">
                리비전 {presetRevision}에 파일 추가
              </Badge>
            )}
            {mode === 'new' && presetRevision && (
              <Badge variant="outline" className="text-xs">
                다음 리비전: {presetRevision}
              </Badge>
            )}
          </div>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="stage"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>스테이지</FormLabel>
                    <Select onValueChange={field.onChange} value={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="스테이지 선택" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {stageOptions.map((stage) => (
                          <SelectItem key={stage} value={stage}>
                            {stage}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="revision"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>리비전</FormLabel>
                    <FormControl>
                      <Input 
                        {...field} 
                        placeholder="예: A, B, 1, 2..." 
                        readOnly={mode === 'append'}
                        className={mode === 'append' ? 'bg-gray-50' : ''}
                      />
                    </FormControl>
                    <FormMessage />
                    {mode === 'new' && presetRevision && (
                      <p className="text-xs text-gray-500">
                        자동으로 계산된 다음 리비전입니다.
                      </p>
                    )}
                    {mode === 'append' && (
                      <p className="text-xs text-gray-500">
                        기존 리비전에 파일을 추가합니다.
                      </p>
                    )}
                  </FormItem>
                )}
              />
            </div>

            <FormField
              control={form.control}
              name="uploaderName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>업로더명</FormLabel>
                  <FormControl>
                    <Input 
                      {...field} 
                      placeholder="업로더 이름을 입력하세요"
                      className="bg-gray-50"
                    />
                  </FormControl>
                  <FormMessage />
                  <p className="text-xs text-gray-500">
                    로그인된 사용자 정보가 자동으로 입력됩니다.
                  </p>
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="comment"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>코멘트 (선택)</FormLabel>
                  <FormControl>
                    <Textarea {...field} placeholder="코멘트를 입력하세요" rows={3} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 파일 업로드 영역 */}
            <FormField
              control={form.control}
              name="attachments"
              render={() => (
                <FormItem>
                  <FormLabel>파일 첨부</FormLabel>
                  <Dropzone
                    maxSize={3e9} // 3GB
                    multiple={true}
                    onDropAccepted={handleDropAccepted}
                    disabled={isUploading}
                  >
                    <DropzoneZone className="flex justify-center">
                      <FormControl>
                        <DropzoneInput />
                      </FormControl>
                      <div className="flex items-center gap-6">
                        <DropzoneUploadIcon />
                        <div className="grid gap-0.5">
                          <DropzoneTitle>파일을 여기에 드롭하세요</DropzoneTitle>
                          <DropzoneDescription>
                            또는 클릭하여 파일을 선택하세요
                          </DropzoneDescription>
                        </div>
                      </div>
                    </DropzoneZone>
                  </Dropzone>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 선택된 파일 목록 */}
            {selectedFiles.length > 0 && (
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <h6 className="text-sm font-semibold">
                    선택된 파일 ({selectedFiles.length})
                  </h6>
                </div>
                <ScrollArea className="max-h-[200px]">
                  <FileList>
                    {selectedFiles.map((file, index) => (
                      <FileListItem key={index} className="p-3">
                        <FileListHeader>
                          <FileListIcon />
                          <FileListInfo>
                            <FileListName>{file.name}</FileListName>
                            <FileListSize>{file.size}</FileListSize>
                          </FileListInfo>
                          <FileListAction 
                            onClick={() => removeFile(index)} 
                            disabled={isUploading}
                          >
                            <X className="h-4 w-4" />
                          </FileListAction>
                        </FileListHeader>
                      </FileListItem>
                    ))}
                  </FileList>
                </ScrollArea>
              </div>
            )}

            {/* 업로드 진행 상태 */}
            {isUploading && (
              <div className="space-y-2">
                <div className="flex items-center gap-2">
                  <Loader2 className="h-4 w-4 animate-spin" />
                  <span className="text-sm">{uploadProgress}% 업로드 중...</span>
                </div>
                <div className="h-2 w-full bg-muted rounded-full overflow-hidden">
                  <div 
                    className="h-full bg-primary rounded-full transition-all" 
                    style={{ width: `${uploadProgress}%` }} 
                  />
                </div>
              </div>
            )}

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={handleDialogClose}
                disabled={isUploading}
              >
                취소
              </Button>
              <Button 
                type="submit" 
                disabled={isUploading || selectedFiles.length === 0}
              >
                {isUploading ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    업로드 중...
                  </>
                ) : (
                  <>
                    <Upload className="mr-2 h-4 w-4" />
                    업로드
                  </>
                )}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}