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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
|
"use client"
import * as React from "react"
import { type Row } from "@tanstack/react-table"
import { Loader, Check, X } from "lucide-react"
import { toast } from "sonner"
import { useMediaQuery } from "@/hooks/use-media-query"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Drawer,
DrawerClose,
DrawerContent,
DrawerDescription,
DrawerFooter,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
} from "@/components/ui/drawer"
import { Vendor } from "@/db/schema/vendors"
import { rejectVendors } from "../service"
import { approveVendorsWithApproval, prepareVendorApprovalVariables } from "../approval-actions"
import { useSession } from "next-auth/react"
import { checkVendorsBlacklist } from "../blacklist-check"
import { ApprovalPreviewDialog } from "@/lib/approval/client"
interface VendorDecisionDialogProps
extends React.ComponentPropsWithoutRef<typeof Dialog> {
vendors: Row<Vendor>["original"][]
showTrigger?: boolean
onSuccess?: () => void
}
export function VendorDecisionDialog({
vendors,
showTrigger = true,
onSuccess,
...props
}: VendorDecisionDialogProps) {
const [isApprovePending, startApproveTransition] = React.useTransition()
const [isRejectPending, startRejectTransition] = React.useTransition()
const isDesktop = useMediaQuery("(min-width: 640px)")
const { data: session } = useSession()
// 결재 미리보기 다이얼로그 상태
const [showPreview, setShowPreview] = React.useState(false)
const [previewData, setPreviewData] = React.useState<{
variables: Record<string, string>
title: string
description: string
} | null>(null)
/**
* 승인 버튼 클릭 - 미리보기 다이얼로그 열기
*/
function onApprove() {
if (!session?.user?.id) {
toast.error("사용자 인증 정보를 찾을 수 없습니다.")
return
}
if (!session?.user?.epId) {
toast.error("Knox EP ID가 없습니다. 시스템 관리자에게 문의하세요.")
return
}
startApproveTransition(async () => {
try {
// 1. 블랙리스트 검사 (최우선 처리)
const vendorsToCheck = vendors.map(v => ({
id: String(v.id),
name: v.vendorName || '',
representativeName: v.representativeName,
representativeBirth: v.representativeBirth,
}));
const blacklistCheckResult = await checkVendorsBlacklist(vendorsToCheck);
if (!blacklistCheckResult.success) {
// 블랙리스트에 있는 벤더 목록 표시
const blacklistedNames = blacklistCheckResult.blacklistedVendors
.map(v => `• ${v.name}: ${v.message}`)
.join('\n');
toast.error(
`문제가 있는 데이터가 있습니다:\n${blacklistedNames}`,
{ duration: 10000 }
);
return;
}
// 2. 템플릿 변수 준비
const { variables, vendorRecords, vendorNames } = await prepareVendorApprovalVariables(
vendors.map(v => v.id),
session.user.email || undefined
);
// 3. 미리보기 데이터 설정
setPreviewData({
variables,
title: `벤더 가입 승인 요청 - ${vendorRecords.length}개 업체`,
description: `${vendorNames} 의 가입을 승인합니다.`,
});
// 4. 미리보기 다이얼로그 열기
setShowPreview(true);
} catch (error) {
console.error("🚨 [Vendor Decision] 미리보기 준비 실패:", error);
toast.error(error instanceof Error ? error.message : "미리보기를 준비하는 중 오류가 발생했습니다.")
}
})
}
/**
* 결재 미리보기에서 확인 클릭 - 실제 결재 상신
*/
async function handleApprovalConfirm(approvalData: {
approvers: string[]
title: string
description?: string
}) {
if (!session?.user?.id || !session?.user?.epId) {
toast.error("사용자 인증 정보가 없습니다.")
return
}
try {
const result = await approveVendorsWithApproval({
vendorIds: vendors.map((vendor) => vendor.id),
currentUser: {
id: Number(session.user.id),
epId: session.user.epId,
email: session.user.email || undefined,
},
approvers: approvalData.approvers, // 미리보기에서 설정한 결재선
})
if (!result.success) {
console.error("🚨 [Vendor Decision] 결재 상신 에러:", result.message);
toast.error(result.message || "결재 상신에 실패했습니다.")
return
}
console.log("✅ [Vendor Decision] 결재 상신 성공:", result);
// 다이얼로그 모두 닫기
setShowPreview(false)
props.onOpenChange?.(false)
toast.success(`결재가 상신되었습니다. (결재ID: ${result.approvalId})`)
onSuccess?.()
} catch (error) {
console.error("🚨 [Vendor Decision] 예상치 못한 에러:", error);
toast.error("예상치 못한 오류가 발생했습니다.")
}
}
function onReject() {
if (!session?.user?.id) {
toast.error("사용자 인증 정보를 찾을 수 없습니다.")
return
}
startRejectTransition(async () => {
try {
console.log("🔍 [DEBUG] 거절 요청 시작 - vendors:", vendors.map(v => ({ id: v.id, vendorName: v.vendorName, email: v.email })));
console.log("🔍 [DEBUG] 세션 정보:", { userId: session.user.id, userType: typeof session.user.id });
const { error } = await rejectVendors({
ids: vendors.map((vendor) => vendor.id),
userId: Number(session.user.id)
})
if (error) {
console.error("🚨 [DEBUG] 거절 처리 에러:", error);
toast.error(error)
return
}
console.log("✅ [DEBUG] 거절 처리 성공");
props.onOpenChange?.(false)
toast.success("협력업체 등록이 거절되었습니다.")
onSuccess?.()
} catch (error) {
console.error("🚨 [DEBUG] 예상치 못한 에러:", error);
toast.error("예상치 못한 오류가 발생했습니다.")
}
})
}
if (isDesktop) {
return (
<>
<Dialog {...props}>
{showTrigger ? (
<DialogTrigger asChild>
<Button variant="outline" size="sm" className="gap-2">
<Check className="size-4" aria-hidden="true" />
가입 결정 ({vendors.length})
</Button>
</DialogTrigger>
) : null}
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>협력업체 가입 결정</DialogTitle>
<DialogDescription>
선택한 <span className="font-medium">{vendors.length}</span>개 협력업체에 대한 가입 결정을 해주세요.
</DialogDescription>
</DialogHeader>
{/* 선택한 벤더 목록 표시 */}
<div className="max-h-64 overflow-y-auto border rounded-md p-4">
<h4 className="font-medium mb-2">선택된 협력업체:</h4>
<div className="space-y-2">
{vendors.map((vendor) => (
<div key={vendor.id} className="flex items-center justify-between p-2 bg-gray-50 rounded">
<div>
<div className="font-medium">{vendor.vendorName}</div>
<div className="text-sm text-gray-600">{vendor.email}</div>
</div>
<div className="text-sm text-gray-500">ID: {vendor.id}</div>
</div>
))}
</div>
</div>
<DialogFooter className="gap-2 sm:space-x-0">
<DialogClose asChild>
<Button variant="outline">취소</Button>
</DialogClose>
<Button
aria-label="Reject selected vendors"
variant="destructive"
onClick={onReject}
disabled={isRejectPending || isApprovePending}
>
{isRejectPending && (
<Loader
className="mr-2 size-4 animate-spin"
aria-hidden="true"
/>
)}
<X className="mr-2 size-4" aria-hidden="true" />
거절
</Button>
<Button
aria-label="Approve selected vendors"
variant="default"
onClick={onApprove}
disabled={isApprovePending || isRejectPending}
>
{isApprovePending && (
<Loader
className="mr-2 size-4 animate-spin"
aria-hidden="true"
/>
)}
<Check className="mr-2 size-4" aria-hidden="true" />
승인
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* 결재 미리보기 다이얼로그 */}
{previewData && session?.user?.epId && (
<ApprovalPreviewDialog
open={showPreview}
onOpenChange={setShowPreview}
templateName="벤더 가입 승인 요청"
variables={previewData.variables}
title={previewData.title}
description={previewData.description}
currentUser={{
id: Number(session.user.id),
epId: session.user.epId,
name: session.user.name || undefined,
email: session.user.email || undefined,
}}
onConfirm={handleApprovalConfirm}
/>
)}
</>
)
}
return (
<>
<Drawer {...props}>
{showTrigger ? (
<DrawerTrigger asChild>
<Button variant="outline" size="sm" className="gap-2">
<Check className="size-4" aria-hidden="true" />
가입 결정 ({vendors.length})
</Button>
</DrawerTrigger>
) : null}
<DrawerContent className="max-h-[80vh]">
<DrawerHeader>
<DrawerTitle>협력업체 가입 결정</DrawerTitle>
<DrawerDescription>
선택한 <span className="font-medium">{vendors.length}</span>개 협력업체에 대한 가입 결정을 해주세요.
</DrawerDescription>
</DrawerHeader>
{/* 선택한 벤더 목록 표시 */}
<div className="max-h-48 overflow-y-auto px-4">
<h4 className="font-medium mb-2">선택된 협력업체:</h4>
<div className="space-y-2">
{vendors.map((vendor) => (
<div key={vendor.id} className="flex items-center justify-between p-2 bg-gray-50 rounded">
<div>
<div className="font-medium">{vendor.vendorName}</div>
<div className="text-sm text-gray-600">{vendor.email}</div>
</div>
<div className="text-sm text-gray-500">ID: {vendor.id}</div>
</div>
))}
</div>
</div>
<DrawerFooter className="gap-2 sm:space-x-0">
<DrawerClose asChild>
<Button variant="outline">취소</Button>
</DrawerClose>
<Button
aria-label="Reject selected vendors"
variant="destructive"
onClick={onReject}
disabled={isRejectPending || isApprovePending}
>
{isRejectPending && (
<Loader
className="mr-2 size-4 animate-spin"
aria-hidden="true"
/>
)}
<X className="mr-2 size-4" aria-hidden="true" />
거절
</Button>
<Button
aria-label="Approve selected vendors"
variant="default"
onClick={onApprove}
disabled={isApprovePending || isRejectPending}
>
{isApprovePending && (
<Loader className="mr-2 size-4 animate-spin"
aria-hidden="true"
/>
)}
<Check className="mr-2 size-4" aria-hidden="true" />
승인
</Button>
</DrawerFooter>
</DrawerContent>
</Drawer>
{/* 결재 미리보기 다이얼로그 */}
{previewData && session?.user?.epId && (
<ApprovalPreviewDialog
open={showPreview}
onOpenChange={setShowPreview}
templateName="벤더 가입 승인 요청"
variables={previewData.variables}
title={previewData.title}
description={previewData.description}
currentUser={{
id: Number(session.user.id),
epId: session.user.epId,
name: session.user.name || undefined,
email: session.user.email || undefined,
}}
onConfirm={handleApprovalConfirm}
/>
)}
</>
)
}
|