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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
|
"use client"
import * as React from "react"
import { CalendarIcon, X, Plus, Trash2 } from "lucide-react"
import { useForm, useFieldArray } 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, getUsersForSiteVisitAction } from "@/lib/site-visit/service"
import { UserCombobox } from "./user-combobox"
import {
Dropzone,
DropzoneDescription,
DropzoneInput,
DropzoneTitle,
DropzoneUploadIcon,
DropzoneZone,
} from "@/components/ui/dropzone"
// 방문실사 요청 폼 스키마
const siteVisitRequestSchema = z.object({
// 실사 기간
inspectionDuration: z.number().int().positive("실사 기간은 1일 이상이어야 합니다."),
// 실사 요청일
requestedStartDate: z.date({
required_error: "실사 시작일을 선택해주세요.",
}),
requestedEndDate: z.date({
required_error: "실사 종료일을 선택해주세요.",
}),
// SHI 실사참석 예정부문
shiAttendees: z.object({
technicalSales: z.object({
checked: z.boolean().default(false),
attendees: z.array(z.object({
name: z.string().min(1, "이름을 입력해주세요."),
department: z.string().optional(),
email: z.string().email("유효한 이메일을 입력해주세요.").or(z.string().length(0)),
})).default([]),
}).default({ checked: false, attendees: [] }),
design: z.object({
checked: z.boolean().default(false),
attendees: z.array(z.object({
name: z.string().min(1, "이름을 입력해주세요."),
department: z.string().optional(),
email: z.string().email("유효한 이메일을 입력해주세요.").or(z.string().length(0)),
})).default([]),
}).default({ checked: false, attendees: [] }),
procurement: z.object({
checked: z.boolean().default(false),
attendees: z.array(z.object({
name: z.string().min(1, "이름을 입력해주세요."),
department: z.string().optional(),
email: z.string().email("유효한 이메일을 입력해주세요.").or(z.string().length(0)),
})).default([]),
}).default({ checked: false, attendees: [] }),
quality: z.object({
checked: z.boolean().default(false),
attendees: z.array(z.object({
name: z.string().min(1, "이름을 입력해주세요."),
department: z.string().optional(),
email: z.string().email("유효한 이메일을 입력해주세요.").or(z.string().length(0)),
})).default([]),
}).default({ checked: false, attendees: [] }),
production: z.object({
checked: z.boolean().default(false),
attendees: z.array(z.object({
name: z.string().min(1, "이름을 입력해주세요."),
department: z.string().optional(),
email: z.string().email("유효한 이메일을 입력해주세요.").or(z.string().length(0)),
})).default([]),
}).default({ checked: false, attendees: [] }),
commissioning: z.object({
checked: z.boolean().default(false),
attendees: z.array(z.object({
name: z.string().min(1, "이름을 입력해주세요."),
department: z.string().optional(),
email: z.string().email("유효한 이메일을 입력해주세요.").or(z.string().length(0)),
})).default([]),
}).default({ checked: false, attendees: [] }),
other: z.object({
checked: z.boolean().default(false),
attendees: z.array(z.object({
name: z.string().min(1, "이름을 입력해주세요."),
department: z.string().optional(),
email: z.string().email("유효한 이메일을 입력해주세요.").or(z.string().length(0)),
})).default([]),
}).default({ checked: false, attendees: [] }),
}),
// 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(),
}).refine((data) => {
// 종료일이 시작일보다 이후여야 함
if (data.requestedStartDate && data.requestedEndDate) {
return data.requestedEndDate >= data.requestedStartDate;
}
return true;
}, {
message: "종료일은 시작일보다 이후여야 합니다.",
path: ["requestedEndDate"],
}).refine((data) => {
// SHI 참석자 정보 검증: 부서 상관없이 전체 참석자가 최소 1명 이상이어야 함
const totalAttendees = Object.values(data.shiAttendees).reduce((total, attendee) => {
if (attendee.checked && attendee.attendees.length > 0) {
return total + attendee.attendees.length;
}
return total;
}, 0);
return totalAttendees >= 1;
}, {
message: "참석자는 부서 상관없이 최소 1명 이상 필수입니다.",
path: ["shiAttendees"],
})
export type SiteVisitRequestFormValues = z.infer<typeof siteVisitRequestSchema>
// 사용자 타입 정의
interface SiteVisitUser {
id: number;
name: string;
email: string;
department?: string;
}
// 참석자 섹션 컴포넌트
function AttendeeSection({
form,
itemKey,
label,
isPending,
}: {
form: ReturnType<typeof useForm<SiteVisitRequestFormValues>>
itemKey: keyof SiteVisitRequestFormValues['shiAttendees']
label: string
isPending: boolean
}) {
const { fields, append, remove } = useFieldArray({
control: form.control,
name: `shiAttendees.${itemKey}.attendees` as any,
});
const isChecked = form.watch(`shiAttendees.${itemKey}.checked`);
const [users, setUsers] = React.useState<SiteVisitUser[]>([]);
const [isLoadingUsers, setIsLoadingUsers] = React.useState(false);
const [selectedUserId, setSelectedUserId] = React.useState<number | null>(null);
// Dialog가 열릴 때 사용자 목록 로드
React.useEffect(() => {
if (isChecked && users.length === 0) {
const loadUsers = async () => {
setIsLoadingUsers(true);
try {
const result = await getUsersForSiteVisitAction();
if (result.success && result.data) {
setUsers(result.data.map((user: any) => ({
id: user.id,
name: user.name,
email: user.email,
department: user.deptName || undefined,
})));
}
} catch (error) {
console.error("사용자 목록 로드 오류:", error);
toast.error("사용자 목록을 불러오는데 실패했습니다.");
} finally {
setIsLoadingUsers(false);
}
};
loadUsers();
}
}, [isChecked, users.length]);
const handleUserSelect = (userId: number) => {
// 선택된 사용자 정보 찾기
const selectedUser = users.find(user => user.id === userId);
if (!selectedUser) return;
// 현재 폼의 attendees 값 가져오기
const currentAttendees = form.getValues(`shiAttendees.${itemKey}.attendees`) as Array<{
name: string;
department?: string;
email: string;
}> | undefined;
// undefined이거나 배열이 아닌 경우 빈 배열로 처리
const attendees = Array.isArray(currentAttendees) ? currentAttendees : [];
// 이미 선택된 사용자인지 확인 (이메일 기준)
const existingIndex = attendees.findIndex(
(attendee) => attendee.email === selectedUser.email
);
if (existingIndex >= 0) {
// 이미 선택된 경우 제거
remove(existingIndex);
} else {
// 새로 추가
append({
name: selectedUser.name,
department: selectedUser.department || "",
email: selectedUser.email,
});
}
// 선택 초기화
setSelectedUserId(null);
};
return (
<div className="border rounded-lg p-4 space-y-4">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-3">
<FormField
control={form.control}
name={`shiAttendees.${itemKey}.checked` as any}
render={({ field }) => (
<FormItem className="flex items-center space-x-2 space-y-0">
<FormControl>
<Checkbox
checked={field.value as boolean}
onCheckedChange={(checked) => {
field.onChange(checked);
// 체크 해제 시 참석자 목록 초기화
if (!checked) {
form.setValue(`shiAttendees.${itemKey}.attendees` as any, []);
}
}}
disabled={isPending}
/>
</FormControl>
<FormLabel className="font-medium text-base">{label}</FormLabel>
</FormItem>
)}
/>
</div>
{isChecked && (
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">
참석인원: {fields.length}명
</span>
</div>
)}
</div>
{isChecked && (
<div className="space-y-3">
{/* 사용자 선택 UI */}
<div className="flex items-center gap-2">
<div className="flex-1">
<UserCombobox
users={users}
value={selectedUserId}
onChange={handleUserSelect}
placeholder={isLoadingUsers ? "담당자 로딩 중..." : "담당자 선택..."}
disabled={isPending || isLoadingUsers}
/>
</div>
<Button
type="button"
variant="outline"
size="icon"
onClick={() => setSelectedUserId(null)}
disabled={isPending || !selectedUserId}
title="선택 초기화"
>
<X className="h-4 w-4" />
</Button>
</div>
{/* 선택된 사용자 목록 */}
{fields.length > 0 && (
<div className="space-y-2">
{fields.map((fieldItem, index) => {
// 폼에서 실제 값을 가져오기
const attendeesArray = form.watch(`shiAttendees.${itemKey}.attendees` as any) as Array<{
name: string;
department?: string;
email: string;
}>;
const attendee = attendeesArray[index];
if (!attendee) return null;
return (
<div
key={fieldItem.id}
className="flex items-center justify-between p-3 bg-muted/50 rounded-md"
>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="font-medium">{attendee.name}</span>
{attendee.department && (
<span className="text-sm text-muted-foreground">
({attendee.department})
</span>
)}
</div>
<div className="text-sm text-muted-foreground truncate">
{attendee.email}
</div>
</div>
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => remove(index)}
disabled={isPending}
className="h-8 w-8 flex-shrink-0"
>
<Trash2 className="h-4 w-4 text-red-500" />
</Button>
</div>
);
})}
</div>
)}
</div>
)}
</div>
);
}
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
investigationNotes?: string
vendorName: string
vendorCode: string
projectName?: string
projectCode?: string
pqItems?: Array<{itemCode: string, itemName: string}> | null
}
isReinspection?: boolean // 재실사 모드 플래그
}
export function SiteVisitDialog({
isOpen,
onClose,
onSubmit,
investigation,
isReinspection = false,
}: SiteVisitDialogProps) {
const [isPending, setIsPending] = React.useState(false)
const [selectedFiles, setSelectedFiles] = React.useState<File[]>([])
const form = useForm<SiteVisitRequestFormValues>({
resolver: zodResolver(siteVisitRequestSchema),
defaultValues: {
inspectionDuration: 1,
requestedStartDate: undefined,
requestedEndDate: undefined,
shiAttendees: {
technicalSales: { checked: false, attendees: [] },
design: { checked: false, attendees: [] },
procurement: { checked: false, attendees: [] },
quality: { checked: false, attendees: [] },
production: { checked: false, attendees: [] },
commissioning: { checked: false, attendees: [] },
other: { checked: false, attendees: [] },
},
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 loadExistingRequest = async () => {
try {
// 기존 방문실사 요청이 있는지 확인하고 최신 것을 로드
const existingRequest = await getSiteVisitRequestAction(investigation.id)
if (existingRequest.success && existingRequest.data) {
// 기존 데이터를 form에 로드
const data = existingRequest.data
form.reset({
inspectionDuration: typeof data.inspectionDuration === 'number' ? data.inspectionDuration : (parseFloat(String(data.inspectionDuration || '1')) || 1),
requestedStartDate: data.requestedStartDate ? new Date(data.requestedStartDate) : undefined,
requestedEndDate: data.requestedEndDate ? new Date(data.requestedEndDate) : undefined,
shiAttendees: (() => {
// 기존 데이터 형식 변환 (호환성 유지)
if (data.shiAttendees) {
const converted: any = {};
Object.keys(data.shiAttendees).forEach((key) => {
const oldData = (data.shiAttendees as any)[key];
if (oldData && typeof oldData === 'object') {
// 기존 형식 {checked, count, details} → 새 형식 {checked, attendees}
if (oldData.attendees && Array.isArray(oldData.attendees)) {
converted[key] = oldData; // 이미 새 형식
} else {
// 기존 형식 변환
converted[key] = {
checked: oldData.checked || false,
attendees: oldData.count > 0 && oldData.details
? [{
name: oldData.details.split('/')[0]?.trim() || '',
department: oldData.details.split('/')[1]?.trim() || '',
email: ''
}]
: []
};
}
} else {
converted[key] = { checked: false, attendees: [] };
}
});
return converted;
}
return {
technicalSales: { checked: false, attendees: [] },
design: { checked: false, attendees: [] },
procurement: { checked: false, attendees: [] },
quality: { checked: false, attendees: [] },
production: { checked: false, attendees: [] },
commissioning: { checked: false, attendees: [] },
other: { checked: false, attendees: [] },
};
})(),
shiAttendeeDetails: (data as any).shiAttendeeDetails || "",
vendorRequests: (data.vendorRequests && typeof data.vendorRequests === 'object') ? data.vendorRequests : {
availableDates: false,
factoryName: false,
factoryLocation: false,
factoryAddress: false,
factoryPicName: false,
factoryPicPhone: false,
factoryPicEmail: false,
factoryDirections: false,
accessProcedure: false,
other: false,
},
otherVendorRequests: (data as any).otherVendorRequests || "",
additionalRequests: data.additionalRequests || "",
})
return
}
// 기본값으로 폼 초기화 (기존 요청이 없는 경우)
form.reset({
inspectionDuration: 1,
requestedStartDate: undefined,
requestedEndDate: undefined,
shiAttendees: {
technicalSales: { checked: false, attendees: [] },
design: { checked: false, attendees: [] },
procurement: { checked: false, attendees: [] },
quality: { checked: false, attendees: [] },
production: { checked: false, attendees: [] },
commissioning: { checked: false, attendees: [] },
other: { checked: false, attendees: [] },
},
shiAttendeeDetails: "",
vendorRequests: {
availableDates: false,
factoryName: false,
factoryLocation: false,
factoryAddress: false,
factoryPicName: false,
factoryPicPhone: false,
factoryPicEmail: false,
factoryDirections: false,
accessProcedure: false,
other: false,
},
otherVendorRequests: "",
additionalRequests: "",
})
} catch (error) {
console.error("방문실사 요청 데이터 로드 중 오류:", error)
toast.error("방문실사 요청 데이터 로드 중 오류가 발생했습니다.")
onClose()
return
}
}
loadExistingRequest()
setSelectedFiles([])
}
}, [isOpen, form, investigation.id, onClose])
async function handleSubmit(data: SiteVisitRequestFormValues) {
setIsPending(true)
try {
await onSubmit(data, selectedFiles)
toast.success(isReinspection ? "재실사 요청이 성공적으로 발송되었습니다." : "방문실사 요청이 성공적으로 발송되었습니다.")
} catch (error) {
toast.error(isReinspection ? "재실사 요청 발송 중 오류가 발생했습니다." : "방문실사 요청 발송 중 오류가 발생했습니다.")
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>{isReinspection ? "재실사 요청 생성" : "방문실사 요청 생성"} <Badge variant="outline">
{getInvestigationMethodLabel(investigation.investigationMethod || "")}
</Badge></DialogTitle>
<DialogDescription>
{isReinspection
? "협력업체에 재실사 요청을 생성하고, 협력업체가 입력할 정보 항목을 설정합니다."
: "협력업체에 방문실사 요청을 생성하고, 협력업체가 입력할 정보 항목을 설정합니다."
}
</DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6">
{/* QM 의견 (있는 경우에만 표시) */}
<div>
<FormLabel className="text-sm font-medium">QM 의견</FormLabel>
<div className="mt-1 p-3 bg-muted rounded-md">
<p className="text-sm whitespace-pre-wrap">{investigation.investigationNotes}</p>
</div>
</div>
{/* 대상업체 정보 */}
<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 && investigation.pqItems.length > 0
? investigation.pqItems.map((item, index) => (
<div key={index} className="flex items-center gap-2">
<span className="text-xs px-2 py-1 bg-primary/10 rounded">
{item.itemCode}
</span>
<span>{item.itemName}</span>
</div>
))
: "-"
}
</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> */}
<div className="grid grid-cols-3 gap-4">
{/* 실사기간 */}
<FormField
control={form.control}
name="inspectionDuration"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>실사기간 (W/D 기준)</FormLabel>
<div className="flex items-center gap-2">
<FormControl>
<Input
type="number"
step="1"
min="1"
placeholder="1"
{...field}
value={field.value || ''}
onChange={(e) => {
const value = parseInt(e.target.value, 10);
if (Number.isNaN(value) || value < 1) {
field.onChange(1);
} else {
field.onChange(value);
// 실사 기간이 변경되면 종료일 자동 계산
const startDate = form.getValues('requestedStartDate');
if (startDate) {
const endDate = new Date(startDate);
endDate.setDate(endDate.getDate() + value - 1);
form.setValue('requestedEndDate', endDate);
}
}
}}
disabled={isPending}
className="w-24"
/>
</FormControl>
<span className="text-sm text-muted-foreground">일</span>
</div>
<FormMessage />
</FormItem>
)}
/>
{/* 실사요청일 */}
<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={(date) => {
field.onChange(date);
// 시작일이 변경되면 종료일 자동 계산
if (date) {
const duration = form.getValues('inspectionDuration') || 1;
const endDate = new Date(date);
endDate.setDate(endDate.getDate() + duration - 1);
form.setValue('requestedEndDate', endDate);
// 실사 기간도 재계산
const currentEndDate = form.getValues('requestedEndDate');
if (currentEndDate) {
const diffTime = currentEndDate.getTime() - date.getTime();
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;
if (diffDays > 0) {
form.setValue('inspectionDuration', diffDays);
}
}
}
}}
disabled={(date) => date < new Date()}
initialFocus
/>
</PopoverContent>
</Popover>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="requestedEndDate"
render={({ field }) => {
const startDate = form.watch('requestedStartDate');
return (
<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={(date) => {
field.onChange(date);
// 종료일이 변경되면 실사 기간 자동 계산
if (date && startDate) {
const diffTime = date.getTime() - startDate.getTime();
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;
if (diffDays > 0) {
form.setValue('inspectionDuration', diffDays);
}
}
}}
disabled={(date) => {
const today = new Date();
today.setHours(0, 0, 0, 0);
if (date < today) return true;
if (startDate && date < startDate) return true;
return false;
}}
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">
삼성중공업에 어떤 부문의 담당자가 몇 명 실사 참석 예정인지에 대한 정보를 입력하세요.
<br />부서 상관없이 최소 1명 이상 필수입니다.
</div>
<div className="space-y-4">
<AttendeeSection
form={form}
itemKey="technicalSales"
label="기술영업"
isPending={isPending}
/>
<AttendeeSection
form={form}
itemKey="design"
label="설계"
isPending={isPending}
/>
<AttendeeSection
form={form}
itemKey="procurement"
label="구매"
isPending={isPending}
/>
<AttendeeSection
form={form}
itemKey="quality"
label="품질"
isPending={isPending}
/>
<AttendeeSection
form={form}
itemKey="production"
label="생산"
isPending={isPending}
/>
<AttendeeSection
form={form}
itemKey="commissioning"
label="시운전"
isPending={isPending}
/>
<AttendeeSection
form={form}
itemKey="other"
label="기타"
isPending={isPending}
/>
</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>
{/* 추가 요청사항 */}
<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 ? "처리 중..." : (isReinspection ? "재실사 요청 생성" : "방문실사 요청 생성")}
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
)
}
|