summaryrefslogtreecommitdiff
path: root/lib/site-visit/vendor-info-sheet.tsx
blob: c0b1ab7e1b4fe00e0c6737d16b5184d810ed15e1 (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
"use client"

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

import { Button } from "@/components/ui/button"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"

import { toast } from "sonner"
import { Upload, X, FileText } from "lucide-react"

// 협력업체 정보 입력 스키마
const vendorInfoSchema = z.object({
  // 공장 정보
  factoryName: z.string().min(1, "공장명을 입력해주세요."),
  factoryLocation: z.string().min(1, "공장위치를 입력해주세요."),
  factoryAddress: z.string().min(1, "공장주소를 입력해주세요."),
  
  // 공장 PIC 정보
  factoryPicName: z.string().min(1, "공장 PIC 이름을 입력해주세요."),
  factoryPicPhone: z.string().min(1, "공장 PIC 전화번호를 입력해주세요."),
  factoryPicEmail: z.string().email("올바른 이메일 주소를 입력해주세요."),
  
  // 공장 가는 법
  factoryDirections: z.string().min(1, "공장 가는 법을 입력해주세요."),
  
  // 공장 출입절차
  accessProcedure: z.string().min(1, "공장 출입절차를 입력해주세요."),
  
  // 첨부파일
  hasAttachments: z.boolean().default(false),
  
  // 기타 정보
  otherInfo: z.string().optional(),
})

export type VendorInfoFormValues = z.infer<typeof vendorInfoSchema>

interface VendorInfoSheetProps {
  isOpen: boolean
  onClose: () => void
  onSubmit: (data: VendorInfoFormValues & { attachments?: File[] }) => Promise<void>
  siteVisitRequestId: number
  initialData?: VendorInfoFormValues | null
}

export function VendorInfoSheet({
  isOpen,
  onClose,
  onSubmit,
  siteVisitRequestId,
  initialData,
}: VendorInfoSheetProps) {
  const [isPending, setIsPending] = React.useState(false)
  const [selectedFiles, setSelectedFiles] = React.useState<File[]>([])
  const fileInputRef = React.useRef<HTMLInputElement>(null)

  const form = useForm<VendorInfoFormValues>({
    resolver: zodResolver(vendorInfoSchema),
    defaultValues: {
      factoryName: "",
      factoryLocation: "",
      factoryAddress: "",
      factoryPicName: "",
      factoryPicPhone: "",
      factoryPicEmail: "",
      factoryDirections: "",
      accessProcedure: "",

      hasAttachments: false,
      otherInfo: "",
    },
  })

  // Sheet가 열릴 때마다 폼 재설정
  React.useEffect(() => {
    if (isOpen) {
      if (initialData) {
        form.reset(initialData)
      } else {
        form.reset({
          factoryName: "",
          factoryLocation: "",
          factoryAddress: "",
          factoryPicName: "",
          factoryPicPhone: "",
          factoryPicEmail: "",
          factoryDirections: "",
          accessProcedure: "",

          hasAttachments: false,
          otherInfo: "",
        })
      }
    }
  }, [isOpen, form, initialData])

  // 파일 업로드 핸들러
  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files
    if (!files || files.length === 0) return

    const newFiles = Array.from(files)
    
    // 파일 크기 체크 (10MB)
    const validFiles = newFiles.filter(file => {
      if (file.size > 10 * 1024 * 1024) {
        toast.error(`${file.name}: 파일 크기가 10MB를 초과합니다.`)
        return false
      }
      return true
    })

    if (validFiles.length > 0) {
      setSelectedFiles(prev => [...prev, ...validFiles])
      form.setValue("hasAttachments", true)
      toast.success(`${validFiles.length}개 파일이 추가되었습니다.`)
    }
  }

  // 파일 삭제 핸들러
  const handleRemoveFile = (index: number) => {
    setSelectedFiles(prev => prev.filter((_, i) => i !== index))
    const newFileCount = selectedFiles.length - 1
    form.setValue("hasAttachments", newFileCount > 0)
  }

  async function handleSubmit(data: VendorInfoFormValues) {
    setIsPending(true)
    try {
      // 첨부파일 정보를 포함하여 제출
      const submitData = {
        ...data,
        siteVisitRequestId,
        attachments: selectedFiles
      }
      await onSubmit(submitData)
      toast.success("협력업체 정보가 성공적으로 제출되었습니다.")
      onClose()
    } catch (error) {
      toast.error("협력업체 정보 제출 중 오류가 발생했습니다.")
      console.error("협력업체 정보 제출 오류:", error)
    } finally {
      setIsPending(false)
    }
  }

  return (
    <Sheet open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <SheetContent className="w-[600px] sm:w-[700px] overflow-y-auto">
        <SheetHeader>
          <SheetTitle>협력업체 정보 입력</SheetTitle>
          <SheetDescription>
            방문실사 관련 협력업체 정보를 입력해주세요.
          </SheetDescription>
        </SheetHeader>
        
        <Form {...form}>
          <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6">
            {/* 공장 정보 */}
            <div className="space-y-4">
              <h3 className="text-lg font-semibold">공장 정보</h3>
              
              <div className="space-y-4">
                <FormField
                  control={form.control}
                  name="factoryName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>공장명 *</FormLabel>
                      <FormControl>
                        <Input placeholder="공장명을 입력하세요" {...field} disabled={isPending} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={form.control}
                  name="factoryLocation"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>공장위치 *</FormLabel>
                      <FormControl>
                        <Input placeholder="국가 또는 지역 (예: Finland, 부산)" {...field} disabled={isPending} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={form.control}
                  name="factoryAddress"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>공장주소 *</FormLabel>
                      <FormControl>
                        <Textarea 
                          placeholder="상세 주소를 입력하세요" 
                          {...field} 
                          disabled={isPending}
                          className="min-h-[80px]"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>

            {/* 공장 PIC 정보 */}
            <div className="space-y-4">
              <h3 className="text-lg font-semibold">공장 PIC 정보</h3>
              
              <div className="space-y-4">
                <FormField
                  control={form.control}
                  name="factoryPicName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>이름 *</FormLabel>
                      <FormControl>
                        <Input placeholder="PIC 이름" {...field} disabled={isPending} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={form.control}
                  name="factoryPicPhone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>전화번호 *</FormLabel>
                      <FormControl>
                        <Input placeholder="전화번호" {...field} disabled={isPending} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={form.control}
                  name="factoryPicEmail"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>이메일 *</FormLabel>
                      <FormControl>
                        <Input placeholder="이메일 주소" {...field} disabled={isPending} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>

            {/* 공장 가는 법 */}
            <div className="space-y-4">
              <h3 className="text-lg font-semibold">공장 가는 법</h3>
              
              <FormField
                control={form.control}
                name="factoryDirections"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>공장 가는 법 *</FormLabel>
                    <FormControl>
                      <Textarea 
                        placeholder="공항에서 공장까지 가는 방법, 대중교통 정보 등을 상세히 입력하세요" 
                        {...field} 
                        disabled={isPending}
                        className="min-h-[100px]"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* 공장 출입절차 */}
            <div className="space-y-4">
              <h3 className="text-lg font-semibold">공장 출입절차</h3>
              
              <FormField
                control={form.control}
                name="accessProcedure"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>공장 출입절차 *</FormLabel>
                    <FormControl>
                      <Textarea 
                        placeholder="신분증 제출, 출입증 교환, 준비물 등 출입 절차를 상세히 입력하세요" 
                        {...field} 
                        disabled={isPending}
                        className="min-h-[100px]"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>



            {/* 첨부파일 */}
            <div className="space-y-4">
              <h3 className="text-lg font-semibold">첨부파일</h3>
              
              {/* 파일 업로드 */}
              <div className="space-y-2">
                <FormLabel>파일 업로드</FormLabel>
                <div className="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center">
                  <input
                    ref={fileInputRef}
                    type="file"
                    multiple
                    accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png"
                    onChange={handleFileUpload}
                    className="hidden"
                    disabled={isPending}
                  />
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => fileInputRef.current?.click()}
                    disabled={isPending}
                    className="w-full"
                  >
                    <Upload className="h-4 w-4 mr-2" />
                    파일 선택
                  </Button>
                  <p className="text-xs text-muted-foreground mt-2">
                    PDF, Word, Excel, 이미지 파일 (최대 10MB)
                  </p>
                </div>
              </div>

              {/* 첨부된 파일 목록 */}
              <div>
                <FormLabel>첨부된 파일</FormLabel>
                <div className="space-y-2">
                  {selectedFiles.length > 0 ? (
                    selectedFiles.map((file, index) => (
                      <div key={index} className="flex items-center justify-between p-2 border rounded-md">
                        <div className="flex items-center space-x-2 flex-1 min-w-0">
                          <FileText className="h-4 w-4 text-muted-foreground" />
                          <span className="text-sm truncate">{file.name}</span>
                          <span className="text-xs text-muted-foreground">
                            ({Math.round(file.size / 1024)}KB)
                          </span>
                        </div>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => handleRemoveFile(index)}
                          disabled={isPending}
                          className="text-destructive hover:text-destructive"
                        >
                          <X className="h-4 w-4" />
                        </Button>
                      </div>
                    ))
                  ) : (
                    <div className="text-sm text-muted-foreground text-center py-4">
                      첨부된 파일이 없습니다.
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* 기타 정보 */}
            <div className="space-y-4">
              <h3 className="text-lg font-semibold">기타 정보</h3>
              
              <FormField
                control={form.control}
                name="otherInfo"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>기타 정보 (선택사항)</FormLabel>
                    <FormControl>
                      <Textarea 
                        placeholder="추가로 전달하고 싶은 정보가 있다면 입력하세요" 
                        {...field} 
                        disabled={isPending}
                        className="min-h-[80px]"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <SheetFooter>
              <Button
                type="button"
                variant="outline"
                onClick={onClose}
                disabled={isPending}
              >
                취소
              </Button>
              <Button type="submit" disabled={isPending}>
                {isPending ? "처리 중..." : "정보입력"}
              </Button>
            </SheetFooter>
          </form>
        </Form>
      </SheetContent>
    </Sheet>
  )
}