summaryrefslogtreecommitdiff
path: root/lib/techsales-rfq/vendor-response/detail/quotation-response-tab.tsx
blob: 20b2703c6b327eb6329c4056706ea27d27b3ce58 (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
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
"use client"

import * as React from "react"
import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { ScrollArea } from "@/components/ui/scroll-area"
import { CalendarIcon, Send, AlertCircle, Upload, X, FileText, Download } from "lucide-react"
import { Calendar } from "@/components/ui/calendar"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { formatDate, cn } from "@/lib/utils"
import { toast } from "sonner"

interface QuotationResponseTabProps {
  quotation: {
    id: number
    status: string
    totalPrice: string | null
    currency: string | null
    validUntil: Date | null
    remark: string | null
    quotationAttachments?: Array<{
      id: number
      fileName: string
      fileSize: number
      filePath: string
      description?: string | null
    }>
    rfq: {
      id: number
      rfqCode: string | null
      materialCode: string | null
      dueDate: Date | null
      status: string | null
      item?: {
        itemName: string | null
      } | null
    } | null
    vendor: {
      vendorName: string
    } | null
  }
}

const CURRENCIES = [
  { value: "KRW", label: "KRW (원)" },
  { value: "USD", label: "USD (달러)" },
  { value: "EUR", label: "EUR (유로)" },
  { value: "JPY", label: "JPY (엔)" },
  { value: "CNY", label: "CNY (위안)" },
]

export function QuotationResponseTab({ quotation }: QuotationResponseTabProps) {
  const [totalPrice, setTotalPrice] = useState(quotation.totalPrice?.toString() || "")
  const [currency, setCurrency] = useState(quotation.currency || "KRW")
  const [validUntil, setValidUntil] = useState<Date | undefined>(
    quotation.validUntil ? new Date(quotation.validUntil) : undefined
  )
  const [remark, setRemark] = useState(quotation.remark || "")
  const [isLoading, setIsLoading] = useState(false)
  const [attachments, setAttachments] = useState<Array<{
    id?: number
    fileName: string
    fileSize: number
    filePath: string
    isNew?: boolean
    file?: File
  }>>([])
  const [isUploadingFiles, setIsUploadingFiles] = useState(false)
  const router = useRouter()

  // // 초기 첨부파일 데이터 로드
  // useEffect(() => {
  //   if (quotation.quotationAttachments) {
  //     setAttachments(quotation.quotationAttachments.map(att => ({
  //       id: att.id,
  //       fileName: att.fileName,
  //       fileSize: att.fileSize,
  //       filePath: att.filePath,
  //       isNew: false
  //     })))
  //   }
  // }, [quotation.quotationAttachments])

  const rfq = quotation.rfq
  const isDueDatePassed = rfq?.dueDate ? new Date(rfq.dueDate) < new Date() : false
  const canSubmit = !["Accepted", "Rejected"].includes(quotation.status) && !isDueDatePassed
  const canEdit = !["Accepted", "Rejected"].includes(quotation.status) && !isDueDatePassed

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

    Array.from(files).forEach(file => {
      setAttachments(prev => [
        ...prev,
        {
          fileName: file.name,
          fileSize: file.size,
          filePath: '',
          isNew: true,
          file
        }
      ])
    })
  }

  // 첨부파일 제거
  const removeAttachment = (index: number) => {
    setAttachments(prev => prev.filter((_, i) => i !== index))
  }

  // 파일 업로드 함수
  const uploadFiles = async () => {
    const newFiles = attachments.filter(att => att.isNew && att.file)
    if (newFiles.length === 0) return []

    setIsUploadingFiles(true)
    const uploadedFiles = []

    try {
      for (const attachment of newFiles) {
        const formData = new FormData()
        formData.append('file', attachment.file!)
        
        const response = await fetch('/api/upload', {
          method: 'POST',
          body: formData
        })

        if (!response.ok) throw new Error('파일 업로드 실패')
        
        const result = await response.json()
        uploadedFiles.push({
          fileName: result.fileName,
          filePath: result.url,
          fileSize: attachment.fileSize
        })
      }
      return uploadedFiles
    } catch (error) {
      console.error('파일 업로드 오류:', error)
      toast.error('파일 업로드 중 오류가 발생했습니다.')
      return []
    } finally {
      setIsUploadingFiles(false)
    }
  }

  const handleSubmit = async () => {
    if (!totalPrice || !currency || !validUntil) {
      toast.error("모든 필수 항목을 입력해주세요.")
      return
    }

    setIsLoading(true)
    try {
      // 파일 업로드 먼저 처리
      const uploadedFiles = await uploadFiles()

      const { submitTechSalesVendorQuotation } = await import("@/lib/techsales-rfq/service")
      
      const result = await submitTechSalesVendorQuotation({
        id: quotation.id,
        currency,
        totalPrice,
        validUntil: validUntil!,
        remark,
        attachments: uploadedFiles,
        updatedBy: 1 // TODO: 실제 사용자 ID로 변경
      })

      if (result.error) {
        toast.error(result.error)
      } else {
        toast.success("견적서가 제출되었습니다.")
        // // 페이지 새로고침 대신 router.refresh() 사용
        // router.refresh()
        // 페이지 새로고침
        window.location.reload()
      }
    } catch {
      toast.error("제출 중 오류가 발생했습니다.")
    } finally {
      setIsLoading(false)
    }
  }

  const getStatusBadgeVariant = (status: string) => {
    switch (status) {
      case "Draft":
        return "secondary"
      case "Submitted":
        return "default"
      case "Revised":
        return "outline"
      case "Rejected":
        return "destructive"
      case "Accepted":
        return "success"
      default:
        return "secondary"
    }
  }

  const getStatusLabel = (status: string) => {
    switch (status) {
      case "Draft":
        return "초안"
      case "Submitted":
        return "제출됨"
      case "Revised":
        return "수정됨"
      case "Rejected":
        return "반려됨"
      case "Accepted":
        return "승인됨"
      default:
        return status
    }
  }

  return (
    <ScrollArea className="h-full">
      <div className="space-y-6 p-1">
        {/* 견적서 상태 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              견적서 상태
              <Badge variant={getStatusBadgeVariant(quotation.status)}>
                {getStatusLabel(quotation.status)}
              </Badge>
            </CardTitle>
            <CardDescription>
              현재 견적서 상태 및 마감일 정보
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <div className="text-sm font-medium text-muted-foreground">견적서 상태</div>
                <div className="text-sm">{getStatusLabel(quotation.status)}</div>
              </div>
              <div className="space-y-2">
                <div className="text-sm font-medium text-muted-foreground">RFQ 마감일</div>
                <div className="text-sm">
                  {rfq?.dueDate ? formatDate(rfq.dueDate) : "N/A"}
                </div>
              </div>
              <div className="space-y-2">
                <div className="text-sm font-medium text-muted-foreground">남은 시간</div>
                <div className="text-sm">
                  {isDueDatePassed ? (
                    <span className="text-destructive">마감됨</span>
                  ) : rfq?.dueDate ? (
                    <span className="text-green-600">
                      {Math.ceil((new Date(rfq.dueDate).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24))}일
                    </span>
                  ) : (
                    "N/A"
                  )}
                </div>
              </div>
            </div>

            {isDueDatePassed && (
              <Alert>
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>
                  RFQ 마감일이 지났습니다. 견적서를 수정하거나 제출할 수 없습니다.
                </AlertDescription>
              </Alert>
            )}

            {!canEdit && !isDueDatePassed && (
              <Alert>
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>
                  현재 상태에서는 견적서를 수정할 수 없습니다.
                </AlertDescription>
              </Alert>
            )}
          </CardContent>
        </Card>

        {/* 견적 응답 폼 */}
        <Card>
          <CardHeader>
            <CardTitle>견적 응답</CardTitle>
            <CardDescription>
              총 가격, 통화, 유효기간을 입력해주세요.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* 총 가격 */}
            <div className="space-y-2">
              <Label htmlFor="totalPrice">
                총 가격 <span className="text-destructive">*</span>
              </Label>
              <Input
                id="totalPrice"
                type="number"
                placeholder="총 가격을 입력하세요"
                value={totalPrice}
                onChange={(e) => setTotalPrice(e.target.value)}
                disabled={!canEdit}
                className="text-right"
              />
            </div>

            {/* 통화 */}
            <div className="space-y-2">
              <Label htmlFor="currency">
                통화 <span className="text-destructive">*</span>
              </Label>
              <Select value={currency} onValueChange={setCurrency} disabled={!canEdit}>
                <SelectTrigger>
                  <SelectValue placeholder="통화를 선택하세요" />
                </SelectTrigger>
                <SelectContent>
                  {CURRENCIES.map((curr) => (
                    <SelectItem key={curr.value} value={curr.value}>
                      {curr.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 유효기간 */}
            <div className="space-y-2">
              <Label>
                견적 유효기간 <span className="text-destructive">*</span>
              </Label>
              <Popover>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    className={cn(
                      "w-full justify-start text-left font-normal",
                      !validUntil && "text-muted-foreground"
                    )}
                    disabled={!canEdit}
                  >
                    <CalendarIcon className="mr-2 h-4 w-4" />
                    {validUntil ? formatDate(validUntil) : "날짜를 선택하세요"}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0" align="start">
                  <Calendar
                    mode="single"
                    selected={validUntil}
                    onSelect={setValidUntil}
                    disabled={(date) => date < new Date()}
                    initialFocus
                  />
                </PopoverContent>
              </Popover>
            </div>

            {/* 비고 */}
            <div className="space-y-2">
              <Label htmlFor="remark">비고</Label>
              <Textarea
                id="remark"
                placeholder="추가 설명이나 조건을 입력하세요"
                value={remark}
                onChange={(e) => setRemark(e.target.value)}
                disabled={!canEdit}
                rows={4}
              />
            </div>

            {/* 첨부파일 */}
            <div className="space-y-4">
              <Label>첨부파일</Label>
              
              {/* 파일 업로드 버튼 */}
              {canEdit && (
                <div className="flex items-center gap-2">
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    disabled={isUploadingFiles}
                    onClick={() => document.getElementById('file-input')?.click()}
                  >
                    <Upload className="h-4 w-4 mr-2" />
                    파일 선택
                  </Button>
                  <input
                    id="file-input"
                    type="file"
                    multiple
                    onChange={handleFileSelect}
                    className="hidden"
                    accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.jpg,.jpeg,.png,.zip"
                  />
                  <span className="text-sm text-muted-foreground">
                    PDF, 문서파일, 이미지파일, 압축파일 등
                  </span>
                </div>
              )}

              {/* 첨부파일 목록 */}
              {attachments.length > 0 && (
                <div className="space-y-2">
                  {attachments.map((attachment, index) => (
                    <div
                      key={index}
                      className="flex items-center justify-between p-3 border rounded-lg bg-muted/50"
                    >
                      <div className="flex items-center gap-2">
                        <FileText className="h-4 w-4 text-muted-foreground" />
                        <div>
                          <div className="text-sm font-medium">{attachment.fileName}</div>
                          <div className="text-xs text-muted-foreground">
                            {(attachment.fileSize / 1024 / 1024).toFixed(2)} MB
                            {attachment.isNew && (
                              <Badge variant="secondary" className="ml-2">
                                새 파일
                              </Badge>
                            )}
                          </div>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        {!attachment.isNew && (
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={() => window.open(attachment.filePath, '_blank')}
                          >
                            <Download className="h-4 w-4" />
                          </Button>
                        )}
                        {canEdit && (
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={() => removeAttachment(index)}
                          >
                            <X className="h-4 w-4" />
                          </Button>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* 액션 버튼 */}
            {canEdit && canSubmit && (
              <div className="flex justify-center pt-4">
                <Button
                  onClick={handleSubmit}
                  disabled={isLoading || !totalPrice || !currency || !validUntil}
                  className="w-full "
                >
                  <Send className="mr-2 h-4 w-4" />
                  견적서 제출
                </Button>
              </div>
            )}
          </CardContent>
        </Card>

        {/* 현재 견적 정보 (읽기 전용) */}
        {quotation.totalPrice && (
          <Card>
            <CardHeader>
              <CardTitle>현재 견적 정보</CardTitle>
              <CardDescription>
                저장된 견적 정보
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="space-y-2">
                  <div className="text-sm font-medium text-muted-foreground">총 가격</div>
                  <div className="text-lg font-semibold">
                    {parseFloat(quotation.totalPrice).toLocaleString()} {quotation.currency}
                  </div>
                </div>
                <div className="space-y-2">
                  <div className="text-sm font-medium text-muted-foreground">통화</div>
                  <div className="text-sm">{quotation.currency}</div>
                </div>
                <div className="space-y-2">
                  <div className="text-sm font-medium text-muted-foreground">유효기간</div>
                  <div className="text-sm">
                    {quotation.validUntil ? formatDate(quotation.validUntil) : "N/A"}
                  </div>
                </div>
              </div>
              {quotation.remark && (
                <div className="space-y-2">
                  <div className="text-sm font-medium text-muted-foreground">비고</div>
                  <div className="text-sm p-3 bg-muted rounded-md">{quotation.remark}</div>
                </div>
              )}
            </CardContent>
          </Card>
        )}
      </div>
    </ScrollArea>
  )
}