summaryrefslogtreecommitdiff
path: root/lib/bidding/list/biddings-transmission-dialog.tsx
blob: 7eb7ffd12a6b88695eca213c333f7f7786bdb0d5 (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
"use client"

import * as React from "react"
import {
  Send, CheckCircle, FileText, Truck, Calculator, Package
} from "lucide-react"
import { toast } from "sonner"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import { BiddingListItem } from "@/db/schema"
import { transmitToContract, transmitToPO, getWinnerDetails } from "@/lib/bidding/actions"

interface TransmissionDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  bidding: BiddingListItem | undefined
  userId: number
}

interface WinnerDetail {
  id: number
  companyId: number
  vendorName: string | null
  vendorCode: string | null
  awardRatio: number
  totalFinalAmount: number
  items: Array<{
    prItemId: number
    proposedDeliveryDate: string | null
    bidUnitPrice: string | null
    bidAmount: string | null
    currency: string | null
    itemNumber: string | null
    itemInfo: string | null
    materialDescription: string | null
    quantity: string | null
    quantityUnit: string | null
    finalQuantity: number
    finalWeight: number
    finalAmount: number
    awardRatio: number
  }>
}

export function TransmissionDialog({ open, onOpenChange, bidding, userId }: TransmissionDialogProps) {
  const [isLoading, setIsLoading] = React.useState(false)
  const [winnerDetails, setWinnerDetails] = React.useState<WinnerDetail[]>([])
  const [isLoadingDetails, setIsLoadingDetails] = React.useState(false)

  // 낙찰 업체 상세 정보 로드
  const loadWinnerDetails = React.useCallback(async () => {
    if (!bidding) return

    try {
      setIsLoadingDetails(true)
      const result = await getWinnerDetails(bidding.id)
      if (result.success) {
        setWinnerDetails(result.data || [])
      } else {
        toast.error(result.error || '낙찰 업체 정보를 불러오는데 실패했습니다.')
      }
    } catch (error) {
      console.error('Failed to load winner details:', error)
      toast.error('낙찰 업체 정보를 불러오는데 실패했습니다.')
    } finally {
      setIsLoadingDetails(false)
    }
  }, [bidding])

  React.useEffect(() => {
    if (open && bidding) {
      loadWinnerDetails()
    }
  }, [open, bidding, loadWinnerDetails])

  if (!bidding) return null

  // 업체선정이 완료되지 않은 경우 에러 표시
  if (bidding.status !== 'vendor_selected') {
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-[400px]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-red-600">
              <Send className="w-5 h-5" />
              전송 불가
            </DialogTitle>
            <DialogDescription>
              업체선정이 완료된 입찰만 전송할 수 있습니다.
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
            <div className="text-center">
              <p className="text-sm text-muted-foreground">
                현재 상태: <span className="font-medium">{bidding.status}</span>
              </p>
              <p className="text-xs text-muted-foreground mt-2">
                업체선정이 완료된 후 다시 시도해주세요.
              </p>
            </div>
          </div>
          <DialogFooter>
            <Button onClick={() => onOpenChange(false)}>
              확인
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    )
  }

  const handleToContract = async () => {
    try {
      setIsLoading(true)
      console.log('bidding.id', bidding.id)
      console.log('userId', userId)
      await transmitToContract(bidding.id, userId)
      toast.success('계약서 생성이 완료되었습니다.')
      onOpenChange(false)
    } catch (error) {
      toast.error(`계약서 생성에 실패했습니다: ${error}`)
    } finally {
      setIsLoading(false)
    }
  }

  const handleToPO = async () => {
    try {
      setIsLoading(true)
      await transmitToPO(bidding.id)
      toast.success('PO 전송이 완료되었습니다.')
      onOpenChange(false)
    } catch (error) {
      toast.error(`PO 전송에 실패했습니다: ${error}`)
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Send className="w-5 h-5" />
            입찰 전송
          </DialogTitle>
          <DialogDescription>
            선택된 입찰을 계약서 또는 PO로 전송합니다.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6">
          {/* 입찰 정보 */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">입찰 정보</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-sm font-medium">입찰번호</Label>
                  <p className="text-sm text-muted-foreground">{bidding.biddingNumber}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium">입찰명</Label>
                  <p className="text-sm text-muted-foreground">{bidding.title}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium">계약구분</Label>
                  <p className="text-sm text-muted-foreground">{bidding.contractType}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium">예산</Label>
                  <p className="text-sm text-muted-foreground">
                    {bidding.budget ? `${bidding.budget.toLocaleString()} ${bidding.currency}` : '-'}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 선정된 업체 상세 정보 */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base flex items-center gap-2">
                <CheckCircle className="w-4 h-4 text-green-600" />
                선정된 업체 ({winnerDetails.length}개)
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {isLoadingDetails ? (
                <div className="text-center py-4">
                  <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary mx-auto"></div>
                  <p className="text-sm text-muted-foreground mt-2">업체 정보를 불러오는 중...</p>
                </div>
              ) : winnerDetails.length === 0 ? (
                <p className="text-sm text-muted-foreground">선정된 업체가 없습니다.</p>
              ) : (
                winnerDetails.map((winner) => (
                  <div key={winner.id} className="border rounded-lg p-4 space-y-3">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <Package className="w-4 h-4 text-primary" />
                        <span className="font-medium">{winner.vendorName || `업체 ${winner.companyId}`}</span>
                        <Badge variant="outline">{winner.vendorCode}</Badge>
                      </div>
                      <div className="text-right">
                        <div className="text-sm font-medium">
                          발주비율: {winner.awardRatio.toFixed(1)}%
                        </div>
                        <div className="text-sm text-muted-foreground">
                          최종 견적가: {winner.totalFinalAmount.toLocaleString()} {winner.items[0]?.currency || 'KRW'}
                        </div>
                      </div>
                    </div>

                    <Separator />

                    <div className="space-y-2">
                      <div className="text-sm font-medium flex items-center gap-2">
                        <Calculator className="w-4 h-4" />
                        품목별 상세 ({winner.items.length}개 품목)
                      </div>

                      <div className="space-y-2 max-h-40 overflow-y-auto">
                        {winner.items.map((item, itemIndex) => (
                          <div key={itemIndex} className="bg-muted/50 rounded p-2 text-xs">
                            <div className="grid grid-cols-2 gap-2">
                              <div>
                                <span className="font-medium">품목:</span> {item.itemInfo || item.itemNumber}
                              </div>
                              <div>
                                <span className="font-medium">규격:</span> {item.materialDescription}
                              </div>
                              <div>
                                <span className="font-medium">원래 수량:</span> {Number(item.quantity).toLocaleString()} {item.quantityUnit}
                              </div>
                              <div>
                                <span className="font-medium">발주 수량:</span> {item.finalQuantity.toLocaleString()} {item.quantityUnit}
                              </div>
                              <div>
                                <span className="font-medium">단가:</span> {Number(item.bidUnitPrice).toLocaleString()} {item.currency}
                              </div>
                              <div>
                                <span className="font-medium">최종 금액:</span> {item.finalAmount.toLocaleString()} {item.currency}
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                ))
              )}
            </CardContent>
          </Card>
        </div>

        <DialogFooter className="flex gap-2">
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            취소
          </Button>
          <Button
            variant="outline"
            onClick={handleToContract}
            disabled={isLoading}
            className="gap-2"
          >
            <FileText className="w-4 h-4" />
            TO Contract
          </Button>
          {bidding.ANFNR ? (
            <Button
              onClick={handleToPO}
              disabled={isLoading}
              className="gap-2"
            >
              <Truck className="w-4 h-4" />
              TO PO
            </Button>
          ) : (
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <div>
                    <Button
                      disabled
                      className="gap-2 opacity-50"
                    >
                      <Truck className="w-4 h-4" />
                      TO PO
                    </Button>
                  </div>
                </TooltipTrigger>
                <TooltipContent>
                  <p>해당 입찰은 SAP TO PO가 불가능합니다.</p>
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}