summaryrefslogtreecommitdiff
path: root/lib/vendor-regular-registrations/table/vendor-regular-registrations-table-toolbar-actions.tsx
blob: 3a1216f27afdfe068402d9e3d142ab7d729b6e89 (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
"use client"

import { type Table } from "@tanstack/react-table"
import { toast } from "sonner"
import { useRouter } from "next/navigation"

import { Button } from "@/components/ui/button"
import { Mail, FileWarning, Scale, FileText } from "lucide-react"
import type { VendorRegularRegistration } from "@/config/vendorRegularRegistrationsColumnsConfig"
import { 
  sendMissingContractRequestEmails,
  sendAdditionalInfoRequestEmails,
  skipLegalReview,
  submitRegistrationRequest
} from "../service"
import { useState } from "react"
import { SkipReasonDialog } from "@/components/vendor-regular-registrations/skip-reason-dialog"
import { RegistrationRequestDialog } from "@/components/vendor-regular-registrations/registration-request-dialog"

interface VendorRegularRegistrationsTableToolbarActionsProps {
  table: Table<VendorRegularRegistration>
}

export function VendorRegularRegistrationsTableToolbarActions({
  table,
}: VendorRegularRegistrationsTableToolbarActionsProps) {
  const router = useRouter()
  const [syncLoading, setSyncLoading] = useState<{ 
    missingContract: boolean; 
    additionalInfo: boolean;
    legalSkip: boolean;
    registrationRequest: boolean;
  }>({
    missingContract: false,
    additionalInfo: false,
    legalSkip: false,
    registrationRequest: false,
  })

  const [skipDialogs, setSkipDialogs] = useState<{
    legalReview: boolean;
  }>({
    legalReview: false,
  })

  const [registrationRequestDialog, setRegistrationRequestDialog] = useState<{
    open: boolean;
    registration: VendorRegularRegistration | null;
  }>({
    open: false,
    registration: null,
  })

  const selectedRows = table.getFilteredSelectedRowModel().rows.map(row => row.original)



  const handleSendMissingContractRequest = async () => {
    if (selectedRows.length === 0) {
      toast.error("이메일을 발송할 업체를 선택해주세요.")
      return
    }

    setSyncLoading(prev => ({ ...prev, missingContract: true }))
    try {
      const vendorIds = selectedRows.map(row => row.vendorId)
      const result = await sendMissingContractRequestEmails(vendorIds)
      
      if (result.success) {
        toast.success(result.message)
      } else {
        toast.error(result.error)
      }
    } catch (error) {
      console.error("Error sending missing contract request:", error)
      toast.error("누락계약요청 이메일 발송 중 오류가 발생했습니다.")
    } finally {
      setSyncLoading(prev => ({ ...prev, missingContract: false }))
    }
  }

  const handleSendAdditionalInfoRequest = async () => {
    if (selectedRows.length === 0) {
      toast.error("이메일을 발송할 업체를 선택해주세요.")
      return
    }

    setSyncLoading(prev => ({ ...prev, additionalInfo: true }))
    try {
      const vendorIds = selectedRows.map(row => row.vendorId)
      const result = await sendAdditionalInfoRequestEmails(vendorIds)
      
      if (result.success) {
        toast.success(result.message)
      } else {
        toast.error(result.error)
      }
    } catch (error) {
      console.error("Error sending additional info request:", error)
      toast.error("추가정보요청 이메일 발송 중 오류가 발생했습니다.")
    } finally {
      setSyncLoading(prev => ({ ...prev, additionalInfo: false }))
    }
  }

  const handleLegalReviewSkip = async (reason: string) => {
    const cpReviewRows = selectedRows.filter(row => row.status === "cp_review");
    if (cpReviewRows.length === 0) {
      toast.error("CP검토 상태인 업체를 선택해주세요.");
      return;
    }

    setSyncLoading(prev => ({ ...prev, legalSkip: true }));
    try {
      const vendorIds = cpReviewRows.map(row => row.vendorId);
      const result = await skipLegalReview(vendorIds, reason);
      
      if (result.success) {
        toast.success(result.message);
        router.refresh();
      } else {
        toast.error(result.error);
      }
    } catch (error) {
      console.error("Error skipping legal review:", error);
      toast.error("법무검토 Skip 처리 중 오류가 발생했습니다.");
    } finally {
      setSyncLoading(prev => ({ ...prev, legalSkip: false }));
    }
  };

  // 등록요청 핸들러
  const handleRegistrationRequest = () => {
    const approvalReadyRows = selectedRows.filter(row => row.status === "approval_ready");
    
    if (approvalReadyRows.length === 0) {
      toast.error("조건충족 상태의 벤더를 선택해주세요.");
      return;
    }
    
    if (approvalReadyRows.length > 1) {
      toast.error("정규업체 등록 요청은 한 번에 하나씩만 가능합니다.");
      return;
    }

    setRegistrationRequestDialog({
      open: true,
      registration: approvalReadyRows[0],
    });
  };

  const handleRegistrationRequestSubmit = async (requestData: any) => {
    if (!registrationRequestDialog.registration) return;

    setSyncLoading(prev => ({ ...prev, registrationRequest: true }));
    try {
      const result = await submitRegistrationRequest(registrationRequestDialog.registration.id, requestData);
      if (result.success) {
        toast.success(result.message);
        setRegistrationRequestDialog({ open: false, registration: null });
        window.location.reload(); // 데이터 새로고침
      } else {
        toast.error(result.error);
      }
    } catch (error) {
      console.error("등록요청 오류:", error);
      toast.error("등록요청 중 오류가 발생했습니다.");
    } finally {
      setSyncLoading(prev => ({ ...prev, registrationRequest: false }));
    }
  };

  // CP검토 상태인 선택된 행들 개수
  const cpReviewCount = selectedRows.filter(row => row.status === "cp_review").length;
  
  // 조건충족 상태인 선택된 행들 개수
  const approvalReadyCount = selectedRows.filter(row => row.status === "approval_ready").length;

  return (
    <div className="flex items-center gap-2">
      {/* <Button
        variant="outline"
        size="sm"
        onClick={handleSyncDocuments}
        disabled={syncLoading.documents || selectedRows.length === 0}
      >
        <FileText className="mr-2 h-4 w-4" />
        {syncLoading.documents ? "동기화 중..." : "문서 동기화"}
      </Button>
      
      <Button
        variant="outline"
        size="sm"
        onClick={handleSyncAgreements}
        disabled={syncLoading.agreements || selectedRows.length === 0}
      >
        <RefreshCw className="mr-2 h-4 w-4" />
        {syncLoading.agreements ? "동기화 중..." : "계약 동기화"}
      </Button> */}

      <Button
        variant="outline"
        size="sm"
        onClick={handleSendMissingContractRequest}
        disabled={syncLoading.missingContract || selectedRows.length === 0}
      >
        <FileWarning className="mr-2 h-4 w-4" />
        {syncLoading.missingContract ? "발송 중..." : "누락계약요청"}
      </Button>

      <Button
        variant="outline"
        size="sm"
        onClick={handleSendAdditionalInfoRequest}
        disabled={syncLoading.additionalInfo || selectedRows.length === 0}
      >
        <Mail className="mr-2 h-4 w-4" />
        {syncLoading.additionalInfo ? "발송 중..." : "추가정보요청"}
      </Button>

      <Button
        variant="outline"
        size="sm"
        onClick={() => setSkipDialogs(prev => ({ ...prev, legalReview: true }))}
        disabled={syncLoading.legalSkip || cpReviewCount === 0}
      >
        <Scale className="mr-2 h-4 w-4" />
        {syncLoading.legalSkip ? "처리 중..." : "GTC Skip"}
      </Button>

      <Button
        variant="default"
        size="sm"
        onClick={handleRegistrationRequest}
        disabled={syncLoading.registrationRequest || approvalReadyCount === 0}
      >
        <FileText className="mr-2 h-4 w-4" />
        {syncLoading.registrationRequest ? "처리 중..." : "등록요청"}
      </Button>

      <SkipReasonDialog
        open={skipDialogs.legalReview}
        onOpenChange={(open) => setSkipDialogs(prev => ({ ...prev, legalReview: open }))}
        title="GTC Skip"
        description={`선택된 ${cpReviewCount}개 업체의 GTC를 Skip하고 CP완료 상태로 변경합니다. Skip 사유를 입력해주세요.`}
        onConfirm={handleLegalReviewSkip}
        loading={syncLoading.legalSkip}
      />

      <RegistrationRequestDialog
        open={registrationRequestDialog.open}
        onOpenChange={(open) => setRegistrationRequestDialog(prev => ({ ...prev, open }))}
        registration={registrationRequestDialog.registration}
        onSubmit={handleRegistrationRequestSubmit}
      />
    </div>
  )
}