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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
|
"use client"
import * as React from "react"
import { CalendarIcon, X } from "lucide-react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { z } from "zod"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
FormDescription,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Calendar } from "@/components/ui/calendar"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover"
import { Checkbox } from "@/components/ui/checkbox"
import { Badge } from "@/components/ui/badge"
import { toast } from "sonner"
import { getSiteVisitRequestAction } from "@/lib/site-visit/service"
import {
Dropzone,
DropzoneDescription,
DropzoneInput,
DropzoneTitle,
DropzoneUploadIcon,
DropzoneZone,
} from "@/components/ui/dropzone"
// 방문실사 요청 폼 스키마
const siteVisitRequestSchema = z.object({
// 실사 기간
inspectionDuration: z.number().min(0.5, "실사 기간을 입력해주세요."),
// 실사 요청일
requestedStartDate: z.date({
required_error: "실사 시작일을 선택해주세요.",
}),
requestedEndDate: z.date({
required_error: "실사 종료일을 선택해주세요.",
}),
// SHI 실사참석 예정부문
shiAttendees: z.object({
technicalSales: z.object({
checked: z.boolean().default(false),
count: z.number().min(0, "참석 인원은 0명 이상이어야 합니다.").default(0),
details: z.string().optional(),
}).default({ checked: false, count: 0, details: "" }),
design: z.object({
checked: z.boolean().default(false),
count: z.number().min(0, "참석 인원은 0명 이상이어야 합니다.").default(0),
details: z.string().optional(),
}).default({ checked: false, count: 0, details: "" }),
procurement: z.object({
checked: z.boolean().default(false),
count: z.number().min(0, "참석 인원은 0명 이상이어야 합니다.").default(0),
details: z.string().optional(),
}).default({ checked: false, count: 0, details: "" }),
quality: z.object({
checked: z.boolean().default(false),
count: z.number().min(0, "참석 인원은 0명 이상이어야 합니다.").default(0),
details: z.string().optional(),
}).default({ checked: false, count: 0, details: "" }),
production: z.object({
checked: z.boolean().default(false),
count: z.number().min(0, "참석 인원은 0명 이상이어야 합니다.").default(0),
details: z.string().optional(),
}).default({ checked: false, count: 0, details: "" }),
commissioning: z.object({
checked: z.boolean().default(false),
count: z.number().min(0, "참석 인원은 0명 이상이어야 합니다.").default(0),
details: z.string().optional(),
}).default({ checked: false, count: 0, details: "" }),
other: z.object({
checked: z.boolean().default(false),
count: z.number().min(0, "참석 인원은 0명 이상이어야 합니다.").default(0),
details: z.string().optional(),
}).default({ checked: false, count: 0, details: "" }),
}),
// SHI 참석자 정보 (JSON 형태로 저장) - 기존 필드 유지
shiAttendeeDetails: z.string().optional(),
// 협력업체 요청정보 및 자료
vendorRequests: z.object({
availableDates: z.boolean().default(false),
factoryName: z.boolean().default(false),
factoryLocation: z.boolean().default(false),
factoryAddress: z.boolean().default(false),
factoryPicName: z.boolean().default(false),
factoryPicPhone: z.boolean().default(false),
factoryPicEmail: z.boolean().default(false),
factoryDirections: z.boolean().default(false),
accessProcedure: z.boolean().default(false),
other: z.boolean().default(false),
}),
// 기타 요청사항
otherVendorRequests: z.string().optional(),
// 추가 요청사항
additionalRequests: z.string().optional(),
})
type SiteVisitRequestFormValues = z.infer<typeof siteVisitRequestSchema>
interface SiteVisitDialogProps {
isOpen: boolean
onClose: () => void
onSubmit: (data: SiteVisitRequestFormValues, attachments?: File[]) => Promise<void>
investigation: {
id: number
investigationMethod?: "PURCHASE_SELF_EVAL" | "DOCUMENT_EVAL" | "PRODUCT_INSPECTION" | "SITE_VISIT_EVAL"
investigationAddress?: string
vendorName: string
vendorCode: string
projectName?: string
projectCode?: string
pqItems?: string | null
}
}
export function SiteVisitDialog({
isOpen,
onClose,
onSubmit,
investigation,
}: SiteVisitDialogProps) {
const [isPending, setIsPending] = React.useState(false)
const [selectedFiles, setSelectedFiles] = React.useState<File[]>([])
const form = useForm<SiteVisitRequestFormValues>({
resolver: zodResolver(siteVisitRequestSchema),
defaultValues: {
inspectionDuration: 1.0,
requestedStartDate: undefined,
requestedEndDate: undefined,
shiAttendees: {
technicalSales: { checked: false, count: 0, details: "" },
design: { checked: false, count: 0, details: "" },
procurement: { checked: false, count: 0, details: "" },
quality: { checked: false, count: 0, details: "" },
production: { checked: false, count: 0, details: "" },
commissioning: { checked: false, count: 0, details: "" },
other: { checked: false, count: 0, details: "" },
},
shiAttendeeDetails: "",
vendorRequests: {
availableDates: false,
factoryName: false,
factoryLocation: false,
factoryAddress: false,
factoryPicName: false,
factoryPicPhone: false,
factoryPicEmail: false,
factoryDirections: false,
accessProcedure: false,
other: false,
},
otherVendorRequests: "",
additionalRequests: "",
},
})
// Dialog가 열릴 때마다 폼 재설정 및 기존 요청 확인
React.useEffect(() => {
if (isOpen) {
// 기존 방문실사 요청이 있는지 확인
const checkExistingRequest = async () => {
try {
const existingRequest = await getSiteVisitRequestAction(investigation.id)
if (existingRequest.success && existingRequest.data) {
toast.error("이미 방문실사 요청이 존재합니다. 추가 요청은 불가능합니다.")
onClose()
return
}
} catch (error) {
console.error("방문실사 요청 상태 확인 중 오류:", error)
toast.error("방문실사 요청 상태 확인 중 오류가 발생했습니다.")
onClose()
return
}
}
checkExistingRequest()
form.reset({
inspectionDuration: 1.0,
requestedStartDate: undefined,
requestedEndDate: undefined,
shiAttendees: {
technicalSales: { checked: false, count: 0, details: "" },
design: { checked: false, count: 0, details: "" },
procurement: { checked: false, count: 0, details: "" },
quality: { checked: false, count: 0, details: "" },
production: { checked: false, count: 0, details: "" },
commissioning: { checked: false, count: 0, details: "" },
other: { checked: false, count: 0, details: "" },
},
shiAttendeeDetails: "",
vendorRequests: {
availableDates: false,
factoryName: false,
factoryLocation: false,
factoryAddress: false,
factoryPicName: false,
factoryPicPhone: false,
factoryPicEmail: false,
factoryDirections: false,
accessProcedure: false,
other: false,
},
otherVendorRequests: "",
additionalRequests: "",
})
setSelectedFiles([])
}
}, [isOpen, form, investigation.id, onClose])
async function handleSubmit(data: SiteVisitRequestFormValues) {
setIsPending(true)
try {
// 제출 전에 한 번 더 기존 요청이 있는지 확인
const existingRequest = await getSiteVisitRequestAction(investigation.id)
if (existingRequest.success && existingRequest.data) {
toast.error("이미 방문실사 요청이 존재합니다. 추가 요청은 불가능합니다.")
onClose()
return
}
await onSubmit(data, selectedFiles)
toast.success("방문실사 요청이 성공적으로 발송되었습니다.")
} catch (error) {
toast.error("방문실사 요청 발송 중 오류가 발생했습니다.")
console.error("방문실사 요청 오류:", error)
} finally {
setIsPending(false)
}
}
const handleDropAccepted = (files: File[]) => {
setSelectedFiles(prev => [...prev, ...files])
toast.success(`${files.length}개 파일이 추가되었습니다.`)
}
const handleDropRejected = (files: unknown[]) => {
toast.error(`${files.length}개 파일이 거부되었습니다. 파일 크기나 형식을 확인해주세요.`)
}
const removeFile = (index: number) => {
setSelectedFiles(prev => prev.filter((_, i) => i !== index))
}
const getInvestigationMethodLabel = (method: string) => {
switch (method) {
case "PURCHASE_SELF_EVAL":
return "구매자체평가"
case "DOCUMENT_EVAL":
return "서류평가"
case "PRODUCT_INSPECTION":
return "제품검사평가"
case "SITE_VISIT_EVAL":
return "방문실사평가"
default:
return method
}
}
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>방문실사 요청 생성</DialogTitle>
<DialogDescription>
협력업체에 방문실사 요청을 생성하고, 협력업체가 입력할 정보 항목을 설정합니다.
</DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6">
{/* 대상업체 정보 */}
<div className="grid grid-cols-2 gap-4">
<div>
<FormLabel className="text-sm font-medium">대상업체</FormLabel>
<div className="mt-1 p-3 bg-muted rounded-md">
<div className="font-medium">{investigation.vendorName}</div>
<div className="text-sm text-muted-foreground">({investigation.vendorCode})</div>
</div>
</div>
<div>
<FormLabel className="text-sm font-medium">대상품목</FormLabel>
<div className="mt-1 p-3 bg-muted rounded-md">
<div className="font-medium">{investigation.pqItems || "-"}</div>
</div>
</div>
</div>
{/* 실사방법 */}
<div>
<FormLabel className="text-sm font-medium">실사방법</FormLabel>
<div className="mt-1 p-3 bg-muted rounded-md">
<Badge variant="outline">
{getInvestigationMethodLabel(investigation.investigationMethod || "")}
</Badge>
</div>
</div>
{/* 실사기간 */}
<FormField
control={form.control}
name="inspectionDuration"
render={({ field }) => (
<FormItem>
<FormLabel>실사기간 (W/D 기준)</FormLabel>
<div className="flex items-center gap-2">
<FormControl>
<Input
type="number"
step="0.5"
min="0.5"
placeholder="1.5"
{...field}
onChange={(e) => field.onChange(parseFloat(e.target.value) || 0)}
disabled={isPending}
className="w-24"
/>
</FormControl>
<span className="text-sm text-muted-foreground">일</span>
</div>
<FormMessage />
</FormItem>
)}
/>
{/* 실사요청일 */}
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="requestedStartDate"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>실사 시작일</FormLabel>
<Popover>
<PopoverTrigger asChild>
<FormControl>
<Button
variant={"outline"}
className={`w-full pl-3 text-left font-normal ${!field.value && "text-muted-foreground"}`}
disabled={isPending}
>
{field.value ? (
format(field.value, "yyyy년 MM월 dd일")
) : (
<span>시작일을 선택하세요</span>
)}
<CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
</Button>
</FormControl>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={field.value}
onSelect={field.onChange}
disabled={(date) => date < new Date()}
initialFocus
/>
</PopoverContent>
</Popover>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="requestedEndDate"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>실사 종료일</FormLabel>
<Popover>
<PopoverTrigger asChild>
<FormControl>
<Button
variant={"outline"}
className={`w-full pl-3 text-left font-normal ${!field.value && "text-muted-foreground"}`}
disabled={isPending}
>
{field.value ? (
format(field.value, "yyyy년 MM월 dd일")
) : (
<span>종료일을 선택하세요</span>
)}
<CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
</Button>
</FormControl>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={field.value}
onSelect={field.onChange}
disabled={(date) => date < new Date()}
initialFocus
/>
</PopoverContent>
</Popover>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* SHI 실사참석 예정부문 */}
<div>
<FormLabel className="text-sm font-medium">SHI 실사참석 예정부문 ※ 필수값</FormLabel>
<div className="text-sm text-muted-foreground mb-4">
삼성중공업에 어떤 부문의 담당자가 몇 명 실사 참석 예정인지에 대한 정보를 입력하세요.
</div>
<div className="space-y-4">
{[
{ key: "technicalSales", label: "기술영업" },
{ key: "design", label: "설계" },
{ key: "procurement", label: "구매" },
{ key: "quality", label: "품질" },
{ key: "production", label: "생산" },
{ key: "commissioning", label: "시운전" },
{ key: "other", label: "기타" },
].map((item) => (
<div key={item.key} className="border rounded-lg p-4 space-y-3">
<div className="flex items-center space-x-3">
<FormField
control={form.control}
name={`shiAttendees.${item.key}.checked` as `shiAttendees.${typeof item.key}.checked`}
render={({ field }) => (
<FormItem className="flex flex-row items-center space-x-2 space-y-0">
<FormControl>
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
disabled={isPending}
/>
</FormControl>
<FormLabel className="text-sm font-medium">{item.label}</FormLabel>
</FormItem>
)}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name={`shiAttendees.${item.key}.count` as `shiAttendees.${typeof item.key}.count`}
render={({ field }) => (
<FormItem>
<FormLabel className="text-sm">참석 인원</FormLabel>
<div className="flex items-center space-x-2">
<FormControl>
<Input
type="number"
min="0"
placeholder="0"
{...field}
onChange={(e) => field.onChange(parseInt(e.target.value) || 0)}
disabled={isPending}
className="w-20"
/>
</FormControl>
<span className="text-sm text-muted-foreground">명</span>
</div>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`shiAttendees.${item.key}.details` as `shiAttendees.${typeof item.key}.details`}
render={({ field }) => (
<FormItem>
<FormLabel className="text-sm">참석자 정보</FormLabel>
<FormControl>
<Input
placeholder="부서 및 이름 등"
{...field}
disabled={isPending}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</div>
))}
</div>
{/* 전체 참석자 상세정보 */}
<FormField
control={form.control}
name="shiAttendeeDetails"
render={({ field }) => (
<FormItem className="mt-4">
<FormLabel>전체 참석자 상세정보 (선택사항)</FormLabel>
<FormControl>
<Textarea
placeholder="전체 참석 예정인력의 상세 정보를 입력하세요"
{...field}
disabled={isPending}
className="min-h-[80px]"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* 협력업체 요청정보 및 자료 */}
<div>
<FormLabel className="text-sm font-medium">협력업체 요청정보 및 자료</FormLabel>
<div className="text-sm text-muted-foreground mb-2">
협력업체에게 요청할 정보를 선택하세요. 선택된 항목들은 협력업체 정보 입력 폼에 포함됩니다.
</div>
<div className="mt-2 space-y-2">
{[
{ key: "factoryName", label: "공장명" },
{ key: "factoryLocation", label: "공장위치" },
{ key: "factoryAddress", label: "공장주소" },
{ key: "factoryPicName", label: "공장 PIC 이름" },
{ key: "factoryPicPhone", label: "공장 PIC 전화번호" },
{ key: "factoryPicEmail", label: "공장 PIC 이메일" },
{ key: "factoryDirections", label: "공장 가는 방법" },
{ key: "accessProcedure", label: "공장 출입절차" },
{ key: "other", label: "기타" },
].map((item) => (
<FormField
key={item.key}
control={form.control}
name={`vendorRequests.${item.key}` as `vendorRequests.${typeof item.key}`}
render={({ field }) => (
<FormItem className="flex flex-row items-start space-x-3 space-y-0">
<FormControl>
<Checkbox
checked={!!field.value}
onCheckedChange={field.onChange}
disabled={isPending}
/>
</FormControl>
<FormLabel className="text-sm font-normal">{item.label}</FormLabel>
</FormItem>
)}
/>
))}
</div>
<FormField
control={form.control}
name="otherVendorRequests"
render={({ field }) => (
<FormItem className="mt-4">
<FormLabel>기타 요청사항</FormLabel>
<FormControl>
<Textarea
placeholder="기타 요청사항을 입력하세요"
{...field}
disabled={isPending}
className="min-h-[60px]"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* 추가 요청사항 */}
<FormField
control={form.control}
name="additionalRequests"
render={({ field }) => (
<FormItem>
<FormLabel>추가 요청사항 (선택사항)</FormLabel>
<FormControl>
<Textarea
placeholder="추가 요청사항을 입력하세요"
{...field}
disabled={isPending}
className="min-h-[80px]"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* 첨부파일 */}
<div>
<FormLabel className="text-sm font-medium">첨부파일 (선택사항)</FormLabel>
<div className="mt-2">
<Dropzone
maxSize={6e8} // 600MB
onDropAccepted={handleDropAccepted}
onDropRejected={handleDropRejected}
>
{() => (
<FormItem>
<DropzoneZone className="flex justify-center h-24">
<FormControl>
<DropzoneInput />
</FormControl>
<div className="flex items-center gap-6">
<DropzoneUploadIcon />
<div className="grid gap-0.5">
<DropzoneTitle>파일을 여기에 드롭하세요</DropzoneTitle>
<DropzoneDescription>
최대 크기: 600MB
</DropzoneDescription>
</div>
</div>
</DropzoneZone>
<FormDescription>
또는 클릭하여 파일을 선택하세요
</FormDescription>
<FormMessage />
</FormItem>
)}
</Dropzone>
{selectedFiles.length > 0 && (
<div className="mt-2 space-y-1">
{selectedFiles.map((file, index) => (
<div key={index} className="flex items-center justify-between p-2 bg-muted rounded">
<span className="text-sm">{file.name}</span>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => removeFile(index)}
disabled={isPending}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
</div>
)}
</div>
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={onClose}
disabled={isPending}
>
취소
</Button>
<Button type="submit" disabled={isPending}>
{isPending ? "처리 중..." : "방문실사 요청 생성"}
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
)
}
|