summaryrefslogtreecommitdiff
path: root/lib/project-gtc/table/update-gtc-file-sheet.tsx
blob: 65a6bb45f5fde631c1750faa2e3939368cd157fe (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
"use client"

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

import { Button } from "@/components/ui/button"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import {
  Form,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { uploadProjectGtcFile } from "../service"
import type { ProjectGtcView } from "@/db/schema"

const updateProjectSchema = z.object({
  gtcFile: z.instanceof(File).optional(),
})

type UpdateProjectFormValues = z.infer<typeof updateProjectSchema>

interface UpdateGtcFileSheetProps {
  project: ProjectGtcView | null
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function UpdateGtcFileSheet({
  project,
  open,
  onOpenChange,
}: UpdateGtcFileSheetProps) {
  const [isLoading, setIsLoading] = React.useState(false)
  const [selectedFile, setSelectedFile] = React.useState<File | null>(null)

  const form = useForm<UpdateProjectFormValues>({
    resolver: zodResolver(updateProjectSchema),
    defaultValues: {
      gtcFile: undefined,
    },
  })

  // 기존 값 세팅 (프로젝트 변경 시)
  React.useEffect(() => {
    if (project) {
      form.reset({
        gtcFile: undefined,
      })
      setSelectedFile(null)
    }
  }, [project, form])

  // 파일 선택 처리
  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      // PDF 파일만 허용
      if (file.type !== 'application/pdf') {
        toast.error("PDF 파일만 업로드 가능합니다.")
        return
      }
      setSelectedFile(file)
      form.setValue("gtcFile", file)
    }
  }

  // 폼 제출 핸들러
  async function onSubmit(data: UpdateProjectFormValues) {
    if (!project) {
      toast.error("프로젝트 정보를 찾을 수 없습니다.")
      return
    }
    
    setIsLoading(true)
    try {
      // GTC 파일이 있으면 업로드
      if (data.gtcFile) {
        const fileResult = await uploadProjectGtcFile(project.id, data.gtcFile)
        if (!fileResult.success) {
          toast.error(fileResult.error || "GTC 파일 업로드에 실패했습니다.")
          return
        }
        toast.success("GTC 파일이 성공적으로 업로드되었습니다.")
      } else {
        toast.info("변경사항이 없습니다.")
      }
      
      form.reset()
      setSelectedFile(null)
      onOpenChange(false)
    } catch (error) {
      console.error("GTC 파일 업로드 오류:", error)
      toast.error("GTC 파일 업로드 중 오류가 발생했습니다.")
    } finally {
      setIsLoading(false)
    }
  }

  if (!project) return null

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="flex flex-col gap-6 sm:max-w-xl">
        <SheetHeader className="text-left">
          <SheetTitle>GTC 파일 수정</SheetTitle>
          <SheetDescription>
            프로젝트 정보는 수정할 수 없으며, GTC 파일만 업로드할 수 있습니다.
          </SheetDescription>
        </SheetHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-4">
            {/* 프로젝트 정보 (읽기 전용) */}
            <div className="space-y-4">
              <div>
                <FormLabel>프로젝트 코드</FormLabel>
                <Input
                  value={project.code}
                  disabled
                  className="bg-muted"
                />
              </div>
              <div>
                <FormLabel>프로젝트명</FormLabel>
                <Input
                  value={project.name}
                  disabled
                  className="bg-muted"
                />
              </div>
              <div>
                <FormLabel>프로젝트 타입</FormLabel>
                <Input
                  value={project.type}
                  disabled
                  className="bg-muted"
                />
              </div>
            </div>

            {/* GTC 파일 업로드 */}
            <FormField
              control={form.control}
              name="gtcFile"
              render={() => (
                <FormItem>
                  <FormLabel>GTC 파일 (PDF만, 선택 시 기존 파일 교체)</FormLabel>
                  <div className="space-y-2">
                    <label
                      htmlFor="gtc-file-input"
                      className="flex flex-col items-center justify-center w-full min-h-[8rem] border-2 border-dashed border-gray-300 rounded-lg cursor-pointer bg-gray-50 hover:bg-gray-100"
                    >
                      <div className="flex flex-col items-center justify-center p-4 text-center">
                        <Upload className="w-8 h-8 mb-2 text-gray-500" />
                        <span className="mb-1 text-base font-semibold text-gray-800">
                          {selectedFile
                            ? selectedFile.name
                            : project.originalFileName
                              ? `현재 파일: ${project.originalFileName}`
                              : "현재 파일 없음"}
                        </span>
                        {selectedFile ? (
                           <span className="text-xs text-gray-500">
                             ({(selectedFile.size / 1024 / 1024).toFixed(2)} MB)
                           </span>
                        ) : (
                          <>
                            <p className="mb-2 text-sm text-gray-500">
                              또는 클릭하여 파일을 선택하세요
                            </p>
                            <p className="text-xs text-gray-500">
                              PDF 파일만
                            </p>
                          </>
                        )}
                      </div>
                      <input
                        id="gtc-file-input"
                        type="file"
                        className="hidden"
                        accept=".pdf"
                        onChange={handleFileSelect}
                        disabled={isLoading}
                      />
                    </label>
                  </div>
                  <FormMessage />
                </FormItem>
              )}
            />
            <SheetFooter className="gap-2 pt-2 sm:space-x-0">
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
                disabled={isLoading}
              >
                취소
              </Button>
              <Button type="submit" disabled={isLoading || !selectedFile}>
                {isLoading ? "업로드 중..." : "GTC 파일 업로드"}
              </Button>
            </SheetFooter>
          </form>
        </Form>
      </SheetContent>
    </Sheet>
  )
}