summaryrefslogtreecommitdiff
path: root/lib/basic-contract/template/update-basicContract-sheet.tsx
blob: 90bb81a4f9072ce3196808097b43e73ac9ccb4d9 (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
"use client"

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

import { Button } from "@/components/ui/button"
import { Switch } from "@/components/ui/switch"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormDescription,
} from "@/components/ui/form"
import {
  Sheet,
  SheetClose,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import {
  Dropzone,
  DropzoneZone,
  DropzoneUploadIcon,
  DropzoneTitle,
  DropzoneDescription,
  DropzoneInput
} from "@/components/ui/dropzone"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { updateTemplate } from "../service"
import { BasicContractTemplate } from "@/db/schema"
import { scopeHelpers } from "@/config/basicContractColumnsConfig"

// 업데이트 템플릿 스키마 정의 (파일 업데이트 중심)
export const updateTemplateSchema = z.object({
  legalReviewRequired: z.boolean(),
  file: z
    .instanceof(File, { message: "파일을 업로드해주세요." })
    .refine((file) => file.size <= 100 * 1024 * 1024, {
      message: "파일 크기는 100MB 이하여야 합니다.",
    })
    .refine(
      (file) =>
        file.type === 'application/msword' ||
        file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      { message: "워드 파일(.doc, .docx)만 업로드 가능합니다." }
    )
    .optional(),
});

export type UpdateTemplateSchema = z.infer<typeof updateTemplateSchema>

interface UpdateTemplateSheetProps
  extends React.ComponentPropsWithRef<typeof Sheet> {
  template: BasicContractTemplate | null
  onSuccess?: () => void
}

export function UpdateTemplateSheet({ template, onSuccess, ...props }: UpdateTemplateSheetProps) {
  const [isUpdatePending, startUpdateTransition] = React.useTransition()
  const [selectedFile, setSelectedFile] = React.useState<File | null>(null)

  const form = useForm<UpdateTemplateSchema>({
    resolver: zodResolver(updateTemplateSchema),
    defaultValues: {
      legalReviewRequired: template?.legalReviewRequired ?? false,
    },
    mode: "onChange"
  })

  // 파일 선택 핸들러
  const handleFileChange = (files: File[]) => {
    if (files.length > 0) {
      const file = files[0];
      setSelectedFile(file);
      form.setValue("file", file);
    }
  };

  // 템플릿 변경 시 폼 값 업데이트
  React.useEffect(() => {
    if (template) {
      form.reset({
        legalReviewRequired: template.legalReviewRequired ?? false,
      });
    }
  }, [template, form]);

  function onSubmit(input: UpdateTemplateSchema) {
    startUpdateTransition(async () => {
      if (!template) return

      // FormData 객체 생성하여 파일과 데이터를 함께 전송
      const formData = new FormData();
      formData.append("templateName", template.templateName); // 기존 템플릿 이름 추가
      formData.append("legalReviewRequired", input.legalReviewRequired.toString());

      if (input.file) {
        formData.append("file", input.file);
      }

      try {
        // 서비스 함수 호출
        const { error } = await updateTemplate({
          id: template.id,
          formData,
        });

        if (error) {
          toast.error(error);
          return;
        }

        form.reset();
        setSelectedFile(null);
        props.onOpenChange?.(false);
        toast.success("템플릿이 성공적으로 업데이트되었습니다.");
        onSuccess?.();
      } catch (error) {
        console.error("Update error:", error);
        toast.error("템플릿 업데이트 중 오류가 발생했습니다.");
      }
    });
  }

  if (!template) return null;

  return (
    <Sheet {...props}>
      <SheetContent className="sm:max-w-[500px] h-[100vh] flex flex-col p-0">
        {/* 고정된 헤더 */}
        <SheetHeader className="p-6 pb-4 border-b">
          <SheetTitle>템플릿 업데이트</SheetTitle>
          <SheetDescription>
            템플릿 파일을 업데이트하고 설정을 변경하세요
          </SheetDescription>
        </SheetHeader>

        {/* 스크롤 가능한 컨텐츠 영역 */}
        <div className="flex-1 overflow-y-auto px-6">
          <Form {...form}>
            <form
              onSubmit={form.handleSubmit(onSubmit)}
              className="space-y-6 py-4"
            >
              {/* 템플릿 정보 표시 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">템플릿 정보</CardTitle>
                  <CardDescription>
                    현재 템플릿의 기본 정보입니다
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid grid-cols-1 gap-4">
                    <div className="space-y-2">
                      <label className="text-sm font-medium">템플릿 이름</label>
                      <div className="px-3 py-2 border rounded-md bg-gray-50">
                        {template.templateName}
                      </div>
                    </div>
                    
                    <div className="space-y-2">
                      <label className="text-sm font-medium">현재 리비전</label>
                      <div className="px-3 py-2 border rounded-md bg-gray-50">
                        <Badge variant="outline">v{template.revision}</Badge>
                      </div>
                    </div>
                     
                    <div className="space-y-2">
                      <label className="text-sm font-medium">현재 파일</label>
                      <div className="px-3 py-2 border rounded-md bg-gray-50">
                        {template.fileName}
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* 설정 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">설정</CardTitle>
                  <CardDescription>
                    템플릿 관련 설정을 변경할 수 있습니다
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <FormField
                    control={form.control}
                    name="legalReviewRequired"
                    render={({ field }) => (
                      <FormItem className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm">
                        <div className="space-y-0.5">
                          <FormLabel>법무검토 필요</FormLabel>
                          <FormDescription>
                            법무팀 검토가 필요한 템플릿인지 설정
                          </FormDescription>
                        </div>
                        <FormControl>
                          <Switch
                            checked={field.value}
                            onCheckedChange={field.onChange}
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />
                </CardContent>
              </Card>

              {/* 파일 업데이트 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">파일 업데이트</CardTitle>
                  <CardDescription>
                    새로운 템플릿 파일을 업로드하세요
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <FormField
                    control={form.control}
                    name="file"
                    render={() => (
                      <FormItem>
                        <FormLabel>새 템플릿 파일 (선택사항)</FormLabel>
                        <FormControl>
                          <Dropzone
                            onDrop={handleFileChange}
                            accept={{
                              'application/msword': ['.doc'],
                              'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx']
                            }}
                          >
                            <DropzoneZone>
                              <DropzoneUploadIcon className="h-10 w-10 text-muted-foreground" />
                              <DropzoneTitle>
                                {selectedFile
                                  ? selectedFile.name
                                  : "새 워드 파일을 드래그하세요"}
                              </DropzoneTitle>
                              <DropzoneDescription>
                                {selectedFile
                                  ? `파일 크기: ${(selectedFile.size / (1024 * 1024)).toFixed(2)} MB`
                                  : "또는 클릭하여 워드 파일(.doc, .docx)을 선택하세요 (최대 100MB)"}
                              </DropzoneDescription>
                              <DropzoneInput />
                            </DropzoneZone>
                          </Dropzone>
                        </FormControl>
                        <FormDescription>
                          파일을 업로드하지 않으면 기존 파일이 유지됩니다
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </CardContent>
              </Card>
            </form>
          </Form>
        </div>

        {/* 고정된 푸터 */}
        <SheetFooter className="p-6 pt-4 border-t">
          <SheetClose asChild>
            <Button type="button" variant="outline">
              취소
            </Button>
          </SheetClose>
          <Button
            type="button"
            onClick={form.handleSubmit(onSubmit)}
            disabled={isUpdatePending}
          >
            {isUpdatePending && (
              <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" />
            )}
            업데이트
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  )
}