summaryrefslogtreecommitdiff
path: root/lib/po/vendor-table/vendor-po-actions.tsx
blob: e36b745bb2f42f85f82302a85abd0d697e3d70d4 (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
"use client"

import * as React from "react"
import {
  FileTextIcon,
  MoreHorizontalIcon,
  EyeIcon,
  PrinterIcon,
  FileXIcon,
  PlusIcon,
  EditIcon
} from "lucide-react"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { toast } from "sonner"
import { VendorPO, VendorPOActionType } from "./types"
import { createPcrRequest, acceptContract, rejectContract, cancelAcceptContract } from "./service"
import { ContractStatus } from "@/db/schema/contract"

interface VendorPOActionsProps {
  row: { original: VendorPO }
  setRowAction: React.Dispatch<React.SetStateAction<{ row: { original: VendorPO }, type: VendorPOActionType } | null>>
}

export function VendorPOActions({ row, setRowAction }: VendorPOActionsProps) {
  const [isLoading, setIsLoading] = React.useState(false)
  const [rejectDialogOpen, setRejectDialogOpen] = React.useState(false)
  const [rejectionReason, setRejectionReason] = React.useState("")

  // 계약 상태에 따른 버튼 활성화 조건
  const contractStatus = row.original.contractStatus
  const canCreatePcr = contractStatus === ContractStatus.CONTRACT_ACCEPT_REQUEST
  const canApprove = contractStatus === ContractStatus.CONTRACT_ACCEPT_REQUEST
  const canCancelApprove = contractStatus === ContractStatus.COMPLETE_THE_CONTRACT
  const canReject = contractStatus === ContractStatus.CONTRACT_ACCEPT_REQUEST

  // PCR 생성 핸들러
  const handlePcrCreate = async () => {
    if (isLoading) return

    try {
      setIsLoading(true)
      const result = await createPcrRequest(row.original.id)

      if (result.success) {
        toast.success(result.message)
        // 필요한 경우 테이블 리프레시 로직 추가
      }
    } catch (error) {
      console.error("PCR 생성 실패:", error)
      toast.error("PCR 생성에 실패했습니다.")
    } finally {
      setIsLoading(false)
    }
  }

  // 승인 핸들러
  const handleApprove = async () => {
    if (isLoading) return

    try {
      setIsLoading(true)
      const result = await acceptContract(row.original.id)

      if (result.success) {
        toast.success(result.message)
        // 필요한 경우 테이블 리프레시 로직 추가
      }
    } catch (error) {
      console.error("계약 승인 실패:", error)
      toast.error("계약 승인에 실패했습니다.")
    } finally {
      setIsLoading(false)
    }
  }

  // 승인 취소 핸들러
  const handleCancelApprove = async () => {
    if (isLoading) return

    try {
      setIsLoading(true)
      const result = await cancelAcceptContract(row.original.id)

      if (result.success) {
        toast.success(result.message)
        // 필요한 경우 테이블 리프레시 로직 추가
      }
    } catch (error) {
      console.error("승인 취소 실패:", error)
      toast.error("승인 취소에 실패했습니다.")
    } finally {
      setIsLoading(false)
    }
  }

  // 계약 거절 다이얼로그 열기
  const handleRejectClick = () => {
    if (isLoading || !canReject) return
    setRejectDialogOpen(true)
  }

  // 계약 거절 확인
  const handleRejectConfirm = async () => {
    if (!rejectionReason.trim()) {
      toast.error("거절 사유를 입력해주세요.")
      return
    }

    try {
      setIsLoading(true)
      setRejectDialogOpen(false)

      const result = await rejectContract(row.original.id, rejectionReason.trim())

      if (result.success) {
        toast.success(result.message)
        setRejectionReason("") // 입력값 초기화
      }
    } catch (error) {
      console.error("계약 거절 실패:", error)
      toast.error("계약 거절에 실패했습니다.")
    } finally {
      setIsLoading(false)
    }
  }

  // 계약 거절 취소
  const handleRejectCancel = () => {
    setRejectDialogOpen(false)
    setRejectionReason("")
  }

  return (
    <div className="flex justify-center">
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="ghost" className="h-8 w-8 p-0" disabled={isLoading}>
            <span className="sr-only">Open menu</span>
            <MoreHorizontalIcon className="h-4 w-4" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end">
          <DropdownMenuLabel>액션</DropdownMenuLabel>
          <DropdownMenuItem
            onClick={handlePcrCreate}
            disabled={isLoading || !canCreatePcr}
          >
            <PlusIcon className="mr-2 h-4 w-4" />
            PCR생성
          </DropdownMenuItem>

          <DropdownMenuSeparator />

          <DropdownMenuItem
            onClick={handleApprove}
            disabled={isLoading || !canApprove}
          >
            승인
          </DropdownMenuItem>

          <DropdownMenuItem
            onClick={handleCancelApprove}
            disabled={isLoading || !canCancelApprove}
          >
            승인취소
          </DropdownMenuItem>

          <DropdownMenuItem
            onClick={handleRejectClick}
            className="text-red-600"
            disabled={isLoading || !canReject}
          >
            <FileXIcon className="mr-2 h-4 w-4" />
            계약거절
          </DropdownMenuItem>

          <DropdownMenuSeparator />

          <DropdownMenuItem
            onClick={() => setRowAction({ row, type: "print-contract" })}
            disabled={isLoading}
          >
            <PrinterIcon className="mr-2 h-4 w-4" />
            발주서 출력
          </DropdownMenuItem>

          <DropdownMenuItem
            onClick={() => setRowAction({ row, type: "contract-detail" })}
            disabled={isLoading}
          >
            <EyeIcon className="mr-2 h-4 w-4" />
            계약상세
          </DropdownMenuItem>


          <DropdownMenuItem
            onClick={() => setRowAction({ row, type: "price-index" })}
            disabled={isLoading}
          >
            연동표입력
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>

      {/* 계약 거절 다이얼로그 */}
      <Dialog open={rejectDialogOpen} onOpenChange={setRejectDialogOpen}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>계약 거절</DialogTitle>
            <DialogDescription>
              계약을 거절하는 사유를 입력해주세요.
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="rejection-reason">거절 사유</Label>
              <Textarea
                id="rejection-reason"
                placeholder="거절 사유를 상세히 입력해주세요..."
                value={rejectionReason}
                onChange={(e) => setRejectionReason(e.target.value)}
                rows={4}
              />
            </div>
          </div>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={handleRejectCancel}
              disabled={isLoading}
            >
              취소
            </Button>
            <Button
              type="button"
              variant="destructive"
              onClick={handleRejectConfirm}
              disabled={isLoading || !rejectionReason.trim()}
            >
              {isLoading ? "처리 중..." : "거절하기"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}