summaryrefslogtreecommitdiff
path: root/lib/bidding/detail/table/bidding-detail-vendor-toolbar-actions.tsx
blob: 491f29f74bc304d4b95fd2031c391763b1ee6687 (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
"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { useTransition } from "react"
import { Button } from "@/components/ui/button"
import { Plus, Send, RotateCcw, XCircle, Trophy, FileText, DollarSign, RotateCw } from "lucide-react"
import { registerBidding, markAsDisposal, createRebidding } from "@/lib/bidding/detail/service"
import { sendBiddingBasicContracts, getSelectedVendorsForBidding } from "@/lib/bidding/pre-quote/service"
import { increaseRoundOrRebid } from "@/lib/bidding/service"

import { BiddingDetailVendorCreateDialog } from "../../../../components/bidding/manage/bidding-detail-vendor-create-dialog"
import { BiddingDocumentUploadDialog } from "./bidding-document-upload-dialog"
import { Bidding } from "@/db/schema"
import { useToast } from "@/hooks/use-toast"

interface BiddingDetailVendorToolbarActionsProps {
  biddingId: number
  bidding: Bidding
  userId: string
  onOpenAwardDialog: () => void
  onSuccess: () => void
}

export function BiddingDetailVendorToolbarActions({
  biddingId,
  bidding,
  userId,
  onOpenAwardDialog,
  onSuccess
}: BiddingDetailVendorToolbarActionsProps) {
  const router = useRouter()
  const { toast } = useToast()
  const [isPending, startTransition] = useTransition()
  const [isCreateDialogOpen, setIsCreateDialogOpen] = React.useState(false)
  const [isDocumentDialogOpen, setIsDocumentDialogOpen] = React.useState(false)
  const [isPricesDialogOpen, setIsPricesDialogOpen] = React.useState(false)
  const [isBiddingInvitationDialogOpen, setIsBiddingInvitationDialogOpen] = React.useState(false)
  const [selectedVendors, setSelectedVendors] = React.useState<any[]>([])

  // 본입찰 초대 다이얼로그가 열릴 때 선정된 업체들 조회
  React.useEffect(() => {
    if (isBiddingInvitationDialogOpen) {
      getSelectedVendors().then(vendors => {
        setSelectedVendors(vendors)
      })
    }
  }, [isBiddingInvitationDialogOpen, biddingId])

  const handleCreateVendor = () => {
    setIsCreateDialogOpen(true)
  }

  const handleDocumentUpload = () => {
    setIsDocumentDialogOpen(true)
  }

  const handleViewVendorPrices = () => {
    setIsPricesDialogOpen(true)
  }

  const handleRegister = () => {
    if (!bidding.targetPrice) {
      toast({
        title: '오류',
        description: '내정가가 산정되어야 입찰 초대를 할 수 있습니다.',
        variant: 'destructive',
      })
      return
    }
    // 본입찰 초대 다이얼로그 열기
    setIsBiddingInvitationDialogOpen(true)
  }

  // const handleBiddingInvitationSend = async (data: any) => {
  //   try {
  //     // 1. 기본계약 발송
  //     const contractResult = await sendBiddingBasicContracts(
  //       biddingId,
  //       data.vendors,
  //       data.generatedPdfs,
  //       data.message
  //     )

  //     if (!contractResult.success) {
  //       toast({
  //         title: '기본계약 발송 실패',
  //         description: contractResult.error,
  //         variant: 'destructive',
  //       })
  //       return
  //     }

  //     // 2. 입찰 등록 진행
  //     const registerResult = await registerBidding(bidding.id, userId)

  //     if (registerResult.success) {
  //       toast({
  //         title: '본입찰 초대 완료',
  //         description: '기본계약 발송 및 본입찰 초대가 완료되었습니다.',
  //       })
  //       setIsBiddingInvitationDialogOpen(false)
  //       router.refresh()
  //       onSuccess()
  //     } else {
  //       toast({
  //         title: '오류',
  //         description: registerResult.error,
  //         variant: 'destructive',
  //       })
  //     }
  //   } catch (error) {
  //     console.error('본입찰 초대 실패:', error)
  //     toast({
  //       title: '오류',
  //       description: '본입찰 초대에 실패했습니다.',
  //       variant: 'destructive',
  //     })
  //   }
  // }

  // 선정된 업체들 조회 (서버 액션 함수 사용)
  const getSelectedVendors = async () => {
    try {
      const result = await getSelectedVendorsForBidding(biddingId)
      if (result.success) {
        return result.vendors
      } else {
        console.error('선정된 업체 조회 실패:', result.error)
        return []
      }
    } catch (error) {
      console.error('선정된 업체 조회 실패:', error)
      return []
    }
  }

  const handleMarkAsDisposal = () => {
    startTransition(async () => {
      const result = await markAsDisposal(bidding.id, userId)

      if (result.success) {
        toast({
          title: result.message,
          description: result.message,
        })
        router.refresh()
      } else {
        toast({
          title: result.error,
          description: result.error,
          variant: 'destructive',
        })
      }
    })
  }

  const handleRoundIncrease = () => {
    startTransition(async () => {
      const result = await increaseRoundOrRebid(bidding.id, userId, 'round_increase')

      if (result.success) {
        toast({
          title: "성공",
          description: result.message,
        })
        router.refresh()
        onSuccess()
      } else {
        toast({
          title: "오류",
          description: result.error || "차수증가 중 오류가 발생했습니다.",
          variant: 'destructive',
        })
      }
    })
  }

  return (
    <>
      <div className="flex items-center gap-2">
        {/* 상태별 액션 버튼 */}
        {/* 차수증가: 입찰평가중 또는 입찰 진행중 상태 */}
        {(bidding.status === 'evaluation_of_bidding ' || bidding.status === 'bidding_opened') && (
          <Button
            variant="outline"
            size="sm"
            onClick={handleRoundIncrease}
            disabled={isPending}
          >
            <RotateCw className="mr-2 h-4 w-4" />
            차수증가
          </Button>
        )}

        {/* 유찰/낙찰: 입찰 진행중 상태에서만 */}
        {bidding.status === 'bidding_opened' && (
          <>
            <Button
              variant="destructive"
              size="sm"
              onClick={handleMarkAsDisposal}
              disabled={isPending}
            >
              <XCircle className="mr-2 h-4 w-4" />
              유찰
            </Button>
            <Button
              variant="default"
              size="sm"
              onClick={onOpenAwardDialog}
              disabled={isPending}
            >
              <Trophy className="mr-2 h-4 w-4" />
              낙찰
            </Button>
          </>
        )}
        {/* 구분선 */}
        {(bidding.status === 'bidding_generated' || 
          bidding.status === 'bidding_disposal') && (
          <div className="h-4 w-px bg-border mx-1" />
        )}
            <Button
              variant="outline"
              size="sm"
              onClick={handleDocumentUpload}
            >
              <FileText className="mr-2 h-4 w-4" />
              입찰문서 등록
            </Button>
          
      </div>

      <BiddingDetailVendorCreateDialog
        biddingId={biddingId}
        open={isCreateDialogOpen}
        onOpenChange={setIsCreateDialogOpen}
        onSuccess={() => {
          onSuccess()
          setIsCreateDialogOpen(false)
        }}
      />

      <BiddingDocumentUploadDialog
        open={isDocumentDialogOpen}
        onOpenChange={setIsDocumentDialogOpen}
        biddingId={biddingId}
        userId={userId}
        onSuccess={onSuccess}
      />

    </>
  )
}