summaryrefslogtreecommitdiff
path: root/lib/bidding/detail/table/bidding-detail-target-price-dialog.tsx
blob: a8f604d89dc9a981ef9b9a860e3bb584ec588d1c (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
'use client'

import * as React from 'react'
import { Bidding } from '@/db/schema'
import { QuotationDetails, updateTargetPrice, calculateAndUpdateTargetPrice, getPreQuoteData } from '@/lib/bidding/detail/service'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
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 {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { useToast } from '@/hooks/use-toast'
import { useTransition } from 'react'

interface BiddingDetailTargetPriceDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  quotationDetails: QuotationDetails | null
  bidding: Bidding
  onSuccess: () => void
}

export function BiddingDetailTargetPriceDialog({
  open,
  onOpenChange,
  quotationDetails,
  bidding,
  onSuccess
}: BiddingDetailTargetPriceDialogProps) {
  const { toast } = useToast()
  const [isPending, startTransition] = useTransition()
  const [targetPrice, setTargetPrice] = React.useState(
    bidding.targetPrice ? Number(bidding.targetPrice) : 0
  )
  const [calculationCriteria, setCalculationCriteria] = React.useState(
    (bidding as any).targetPriceCalculationCriteria || ''
  )
  const [preQuoteData, setPreQuoteData] = React.useState<any>(null)
  const [isAutoCalculating, setIsAutoCalculating] = React.useState(false)

  // Dialog가 열릴 때 상태 초기화 및 사전견적 데이터 로드
  React.useEffect(() => {
    if (open) {
      setTargetPrice(bidding.targetPrice ? Number(bidding.targetPrice) : 0)
      setCalculationCriteria((bidding as any).targetPriceCalculationCriteria || '')
      
      // 사전견적 데이터 로드
      const loadPreQuoteData = async () => {
        try {
          const data = await getPreQuoteData(bidding.id)
          setPreQuoteData(data)
        } catch (error) {
          console.error('Failed to load pre-quote data:', error)
        }
      }
      loadPreQuoteData()
    }
  }, [open, bidding])

  // 자동 산정 함수
  const handleAutoCalculate = () => {
    setIsAutoCalculating(true)
    
    startTransition(async () => {
      try {
        const result = await calculateAndUpdateTargetPrice(
          bidding.id
        )

        if (result.success && result.data) {
          setTargetPrice(result.data.targetPrice)
          setCalculationCriteria(result.data.criteria)
          setPreQuoteData(result.data.preQuoteData)
          
          toast({
            title: '성공',
            description: result.message,
          })
          
          onSuccess()
        } else {
          toast({
            title: '오류',
            description: result.error,
            variant: 'destructive',
          })
        }
      } catch (error) {
        toast({
          title: '오류',
          description: '내정가 자동 산정에 실패했습니다.',
          variant: 'destructive',
        })
      } finally {
        setIsAutoCalculating(false)
      }
    })
  }

  const handleSave = () => {
    // 필수값 검증
    if (targetPrice <= 0) {
      toast({
        title: '유효성 오류',
        description: '내정가는 0보다 큰 값을 입력해주세요.',
        variant: 'destructive',
      })
      return
    }

    if (!calculationCriteria.trim()) {
      toast({
        title: '유효성 오류',
        description: '내정가 산정 기준을 입력해주세요.',
        variant: 'destructive',
      })
      return
    }

    startTransition(async () => {
      const result = await updateTargetPrice(
        bidding.id,
        targetPrice,
        calculationCriteria.trim()
      )

      if (result.success) {
        toast({
          title: '성공',
          description: result.message,
        })
        onSuccess()
        onOpenChange(false)
      } else {
        toast({
          title: '오류',
          description: result.error,
          variant: 'destructive',
        })
      }
    })
  }

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('ko-KR', {
      style: 'currency',
      currency: bidding.currency || 'KRW',
    }).format(amount)
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[800px]">
        <DialogHeader>
          <DialogTitle>내정가 산정</DialogTitle>
          <DialogDescription>
            입찰번호: {bidding.biddingNumber} - 견적 통계 및 내정가 설정
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          {/* 사전견적 리스트 */}
          {preQuoteData?.quotes && preQuoteData.quotes.length > 0 && (
            <div className="mb-4">
              <h4 className="text-sm font-medium mb-2">사전견적 현황</h4>
              <div className="border rounded-lg">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>업체명</TableHead>
                      <TableHead className="text-right">사전견적가</TableHead>
                      <TableHead className="text-right">제출일</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {preQuoteData.quotes.map((quote: any) => (
                      <TableRow key={quote.id}>
                        <TableCell className="font-medium">
                          {quote.vendorName || `업체 ${quote.companyId}`}
                        </TableCell>
                        <TableCell className="text-right font-mono">
                          {formatCurrency(Number(quote.preQuoteAmount))}
                        </TableCell>
                        <TableCell className="text-right text-sm text-muted-foreground">
                          {quote.submittedAt 
                            ? new Date(quote.submittedAt).toLocaleDateString('ko-KR')
                            : '-'
                          }
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </div>
          )}
          
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[200px]">항목</TableHead>
                <TableHead>값</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {/* 사전견적 통계 정보 */}
              <TableRow>
                <TableCell className="font-medium">사전견적 수</TableCell>
                <TableCell className="font-semibold">
                  {preQuoteData?.quotationCount || 0}개
                </TableCell>
              </TableRow>
              {preQuoteData?.lowestQuote && (
                <TableRow>
                  <TableCell className="font-medium">최저 사전견적가</TableCell>
                  <TableCell className="font-semibold text-green-600">
                    {formatCurrency(preQuoteData.lowestQuote)}
                  </TableCell>
                </TableRow>
              )}
              {preQuoteData?.highestQuote && (
                <TableRow>
                  <TableCell className="font-medium">최고 사전견적가</TableCell>
                  <TableCell className="font-semibold text-blue-600">
                    {formatCurrency(preQuoteData.highestQuote)}
                  </TableCell>
                </TableRow>
              )}
              {preQuoteData?.averageQuote && (
                <TableRow>
                  <TableCell className="font-medium">평균 사전견적가</TableCell>
                  <TableCell className="font-semibold">
                    {formatCurrency(preQuoteData.averageQuote)}
                  </TableCell>
                </TableRow>
              )}
              
              {/* 입찰 유형 */}
              <TableRow>
                <TableCell className="font-medium">입찰 유형</TableCell>
                <TableCell className="font-semibold">
                  {bidding.biddingType || '-'}
                </TableCell>
              </TableRow>

              {/* 예산 정보 */}
              {bidding.budget && (
                <TableRow>
                  <TableCell className="font-medium">예산</TableCell>
                  <TableCell className="font-semibold">
                    {formatCurrency(Number(bidding.budget))}
                  </TableCell>
                </TableRow>
              )}

              {/* 최종 업데이트 시간 */}
              {quotationDetails?.lastUpdated && (
                <TableRow>
                  <TableCell className="font-medium">최종 업데이트</TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {new Date(quotationDetails.lastUpdated).toLocaleString('ko-KR')}
                  </TableCell>
                </TableRow>
              )}

              {/* 내정가 입력 */}
              <TableRow>
                <TableCell className="font-medium">
                  <Label htmlFor="targetPrice" className="text-sm font-medium">
                    내정가 *
                  </Label>
                </TableCell>
                <TableCell>
                  <div className="space-y-2">
                    <div className="flex gap-2">
                      <Input
                        id="targetPrice"
                        type="number"
                        value={targetPrice}
                        onChange={(e) => setTargetPrice(Number(e.target.value))}
                        placeholder="내정가를 입력하세요"
                        className="flex-1"
                      />
                      <Button
                        type="button"
                        variant="outline"
                        onClick={handleAutoCalculate}
                        disabled={isAutoCalculating || isPending || !preQuoteData?.quotationCount}
                        className="whitespace-nowrap"
                      >
                        {isAutoCalculating ? '산정 중...' : '자동 산정'}
                      </Button>
                    </div>
                    <div className="text-sm text-muted-foreground">
                      {targetPrice > 0 ? formatCurrency(targetPrice) : ''}
                    </div>
                    {preQuoteData?.quotationCount === 0 && (
                      <div className="text-xs text-orange-600">
                        사전견적 데이터가 없어 자동 산정이 불가능합니다.
                      </div>
                    )}
                  </div>
                </TableCell>
              </TableRow>

              {/* 내정가 산정 기준 입력 */}
              <TableRow>
                <TableCell className="font-medium align-top pt-2">
                  <Label htmlFor="calculationCriteria" className="text-sm font-medium">
                    내정가 산정 기준 *
                  </Label>
                </TableCell>
                <TableCell>
                  <Textarea
                    id="calculationCriteria"
                    value={calculationCriteria}
                    onChange={(e) => setCalculationCriteria(e.target.value)}
                    placeholder="내정가 산정 기준을 자세히 입력해주세요. 자동 산정 시 입찰유형에 따른 기준이 자동 설정됩니다."
                    className="w-full min-h-[100px]"
                    rows={4}
                  />
                  <div className="text-xs text-muted-foreground mt-1">
                    필수 입력 사항입니다. 내정가 산정에 대한 근거를 명확히 기재해주세요.
                  </div>
                </TableCell>
              </TableRow>
            </TableBody>
          </Table>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            취소
          </Button>
          <Button onClick={handleSave} disabled={isPending || isAutoCalculating}>
            저장
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}