summaryrefslogtreecommitdiff
path: root/components/investigation/supplement-request-dialog.tsx
blob: c0af36c7fb24457e3e0cc5598eca429db0fdd1c9 (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
"use client"

import * as React from "react"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { useToast } from "@/hooks/use-toast"
import { 
  requestSupplementReinspectionAction,
  requestSupplementDocumentAction 
} from "@/lib/vendor-investigation/service"

interface SupplementRequestDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  investigationId: number
  investigationMethod: string
  vendorName: string
}

export function SupplementRequestDialog({
  open,
  onOpenChange,
  investigationId,
  investigationMethod,
  vendorName
}: SupplementRequestDialogProps) {
  const { toast } = useToast()
  const [isSubmitting, setIsSubmitting] = React.useState(false)
  const [requestType, setRequestType] = React.useState<"REINSPECT" | "DOCUMENT">("REINSPECT")
  
  // 재실사 요청 데이터
  const [reinspectData, setReinspectData] = React.useState({
    inspectionDuration: 1.0,
    requestedStartDate: "",
    requestedEndDate: "",
    additionalRequests: ""
  })
  
  // 서류제출 요청 데이터
  const [documentData, setDocumentData] = React.useState({
    requiredDocuments: [""],
    additionalRequests: ""
  })

  // 보완 요청이 가능한 실사 방법인지 확인
  const canRequestSupplement = investigationMethod === "PRODUCT_INSPECTION" || 
                               investigationMethod === "SITE_VISIT_EVAL"

  const handleSubmit = async () => {
    if (!canRequestSupplement) {
      toast({
        title: "보완 요청 불가",
        description: "현재 실사 방법에서는 보완 요청을 할 수 없습니다.",
        variant: "destructive"
      })
      return
    }

    try {
      setIsSubmitting(true)

      if (requestType === "REINSPECT") {
        const result = await requestSupplementReinspectionAction({
          investigationId,
          siteVisitData: {
            inspectionDuration: reinspectData.inspectionDuration,
            requestedStartDate: reinspectData.requestedStartDate ? new Date(reinspectData.requestedStartDate) : undefined,
            requestedEndDate: reinspectData.requestedEndDate ? new Date(reinspectData.requestedEndDate) : undefined,
            additionalRequests: reinspectData.additionalRequests
          }
        })

        if (result.success) {
          toast({
            title: "보완-재실사 요청 완료",
            description: "재실사 요청이 성공적으로 생성되었습니다.",
          })
          onOpenChange(false)
        } else {
          toast({
            title: "요청 실패",
            description: result.error || "재실사 요청 중 오류가 발생했습니다.",
            variant: "destructive"
          })
        }
      } else {
        const result = await requestSupplementDocumentAction({
          investigationId,
          documentRequests: {
            requiredDocuments: documentData.requiredDocuments.filter(doc => doc.trim() !== ""),
            additionalRequests: documentData.additionalRequests
          }
        })

        if (result.success) {
          toast({
            title: "보완-서류제출 요청 완료",
            description: "서류제출 요청이 성공적으로 생성되었습니다.",
          })
          onOpenChange(false)
        } else {
          toast({
            title: "요청 실패",
            description: result.error || "서류제출 요청 중 오류가 발생했습니다.",
            variant: "destructive"
          })
        }
      }
    } catch (error) {
      console.error("보완 요청 오류:", error)
      toast({
        title: "요청 실패",
        description: "보완 요청 중 오류가 발생했습니다.",
        variant: "destructive"
      })
    } finally {
      setIsSubmitting(false)
    }
  }

  const addDocument = () => {
    setDocumentData(prev => ({
      ...prev,
      requiredDocuments: [...prev.requiredDocuments, ""]
    }))
  }

  const removeDocument = (index: number) => {
    setDocumentData(prev => ({
      ...prev,
      requiredDocuments: prev.requiredDocuments.filter((_, i) => i !== index)
    }))
  }

  const updateDocument = (index: number, value: string) => {
    setDocumentData(prev => ({
      ...prev,
      requiredDocuments: prev.requiredDocuments.map((doc, i) => i === index ? value : doc)
    }))
  }

  if (!canRequestSupplement) {
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>보완 요청 불가</DialogTitle>
            <DialogDescription>
              현재 실사 방법({investigationMethod})에서는 보완 요청을 할 수 없습니다.
              보완 요청은 제품검사평가(PRODUCT_INSPECTION) 또는 방문실사평가(SITE_VISIT_EVAL)에서만 가능합니다.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              확인
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    )
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>보완 요청</DialogTitle>
          <DialogDescription>
            {vendorName}에 대한 보완 요청을 생성합니다.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6">
          {/* 요청 유형 선택 */}
          <div className="space-y-2">
            <Label>보완 요청 유형</Label>
            <div className="flex gap-4">
              <Button
                type="button"
                variant={requestType === "REINSPECT" ? "default" : "outline"}
                onClick={() => setRequestType("REINSPECT")}
              >
                보완-재실사
              </Button>
              <Button
                type="button"
                variant={requestType === "DOCUMENT" ? "default" : "outline"}
                onClick={() => setRequestType("DOCUMENT")}
              >
                보완-서류제출
              </Button>
            </div>
          </div>

          {/* 재실사 요청 폼 */}
          {requestType === "REINSPECT" && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="duration">실사 기간 (일)</Label>
                  <Input
                    id="duration"
                    type="number"
                    step="0.1"
                    min="0.1"
                    value={reinspectData.inspectionDuration}
                    onChange={(e) => setReinspectData(prev => ({
                      ...prev,
                      inspectionDuration: parseFloat(e.target.value) || 0
                    }))}
                  />
                </div>
                <div className="space-y-2">
                  <Label>실사 방법</Label>
                  <Badge variant="outline">
                    {investigationMethod === "PRODUCT_INSPECTION" ? "제품검사평가" : "방문실사평가"}
                  </Badge>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="startDate">요청 시작일</Label>
                  <Input
                    id="startDate"
                    type="date"
                    value={reinspectData.requestedStartDate}
                    onChange={(e) => setReinspectData(prev => ({
                      ...prev,
                      requestedStartDate: e.target.value
                    }))}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="endDate">요청 종료일</Label>
                  <Input
                    id="endDate"
                    type="date"
                    value={reinspectData.requestedEndDate}
                    onChange={(e) => setReinspectData(prev => ({
                      ...prev,
                      requestedEndDate: e.target.value
                    }))}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="reinspectRequests">추가 요청사항</Label>
                <Textarea
                  id="reinspectRequests"
                  placeholder="재실사에 대한 추가 요청사항을 입력하세요"
                  value={reinspectData.additionalRequests}
                  onChange={(e) => setReinspectData(prev => ({
                    ...prev,
                    additionalRequests: e.target.value
                  }))}
                  className="min-h-20"
                />
              </div>
            </div>
          )}

          {/* 서류제출 요청 폼 */}
          {requestType === "DOCUMENT" && (
            <div className="space-y-4">
              <div className="space-y-2">
                <Label>필요 서류 목록</Label>
                {documentData.requiredDocuments.map((doc, index) => (
                  <div key={index} className="flex gap-2">
                    <Input
                      placeholder="필요한 서류명을 입력하세요"
                      value={doc}
                      onChange={(e) => updateDocument(index, e.target.value)}
                    />
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={() => removeDocument(index)}
                      disabled={documentData.requiredDocuments.length === 1}
                    >
                      삭제
                    </Button>
                  </div>
                ))}
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={addDocument}
                >
                  서류 추가
                </Button>
              </div>

              <div className="space-y-2">
                <Label htmlFor="documentRequests">추가 요청사항</Label>
                <Textarea
                  id="documentRequests"
                  placeholder="서류제출에 대한 추가 요청사항을 입력하세요"
                  value={documentData.additionalRequests}
                  onChange={(e) => setDocumentData(prev => ({
                    ...prev,
                    additionalRequests: e.target.value
                  }))}
                  className="min-h-20"
                />
              </div>
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            취소
          </Button>
          <Button onClick={handleSubmit} disabled={isSubmitting}>
            {isSubmitting ? "요청 중..." : "보완 요청"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}