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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
|
"use client"
import * as React from "react"
import { useRouter } from "next/navigation"
import { useSession } from "next-auth/react"
import type {
DataTableAdvancedFilterField,
DataTableFilterField,
DataTableRowAction,
} from "@/types/table"
import { useDataTable } from "@/hooks/use-data-table"
import { DataTable } from "@/components/data-table/data-table"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { getBiddingsFailureColumns } from "./biddings-failure-columns"
import { getBiddingsForFailure } from "@/lib/bidding/service"
import {
biddingStatusLabels,
contractTypeLabels,
} from "@/db/schema"
import { BiddingsClosureDialog } from "./biddings-closure-dialog"
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { FileX, RefreshCw, Undo2 } from "lucide-react"
import { bidClosureAction, cancelDisposalAction } from "@/lib/bidding/actions"
import { increaseRoundOrRebid } from "@/lib/bidding/service"
import { ApprovalPreviewDialog } from "@/lib/approval/approval-preview-dialog"
import { requestBiddingClosureWithApproval } from "@/lib/bidding/approval-actions"
import { useToast } from "@/hooks/use-toast"
type BiddingFailureItem = {
id: number
biddingNumber: string
originalBiddingNumber: string | null
title: string
status: string
contractType: string
prNumber: string | null
// 가격 정보
targetPrice: string | number | null
currency: string | null
// 일정 정보
biddingRegistrationDate: Date | null
submissionStartDate: Date | null
submissionEndDate: Date | null
// 담당자 정보
bidPicName: string | null
supplyPicName: string | null
// 유찰 정보
disposalDate: Date | null // 유찰일
disposalUpdatedAt: Date | null // 폐찰수정일
disposalUpdatedBy: string | null // 폐찰수정자
// 폐찰 정보
closureReason: string | null // 폐찰사유
closureDocuments: {
id: number
fileName: string
originalFileName: string
filePath: string
}[] // 폐찰 첨부파일들
// 기타 정보
createdBy: string | null
createdAt: Date | null
updatedAt: Date | null
updatedBy: string | null
}
interface BiddingsFailureTableProps {
promises: Promise<
[
Awaited<ReturnType<typeof getBiddingsForFailure>>
]
>
}
export function BiddingsFailureTable({ promises }: BiddingsFailureTableProps) {
const [biddingsResult] = React.use(promises)
// biddingsResult에서 data와 pageCount 추출
const { data, pageCount } = biddingsResult
const [isCompact, setIsCompact] = React.useState<boolean>(false)
const [biddingClosureDialogOpen, setBiddingClosureDialogOpen] = React.useState(false)
const [selectedBidding, setSelectedBidding] = React.useState<BiddingFailureItem | null>(null)
const [isRebidDialogOpen, setIsRebidDialogOpen] = React.useState(false)
const [selectedBiddingForRebid, setSelectedBiddingForRebid] = React.useState<BiddingFailureItem | null>(null)
const [approvalPreviewData, setApprovalPreviewData] = React.useState<{
templateName: string
variables: Record<string, string>
title: string
description: string
files?: File[]
} | null>(null)
const [isApprovalPreviewDialogOpen, setIsApprovalPreviewDialogOpen] = React.useState(false)
const { toast } = useToast()
const [rowAction, setRowAction] = React.useState<DataTableRowAction<BiddingFailureItem> | null>(null)
const router = useRouter()
const { data: session } = useSession()
const columns = React.useMemo(
() => getBiddingsFailureColumns({ setRowAction }),
[setRowAction]
)
// rowAction 변경 감지하여 해당 다이얼로그 열기
React.useEffect(() => {
if (rowAction) {
setSelectedBidding(rowAction.row.original)
switch (rowAction.type) {
case "view":
// 상세 페이지로 이동
router.push(`/evcp/bid/${rowAction.row.original.id}/info`)
break
case "rebid":
// 재입찰 팝업 열기
setSelectedBiddingForRebid(rowAction.row.original)
setIsRebidDialogOpen(true)
break
case "closure":
// 폐찰
setSelectedBidding(rowAction.row.original)
setBiddingClosureDialogOpen(true)
break
case "cancelDisposal":
// 유찰취소
handleCancelDisposal(rowAction.row.original)
break
default:
break
}
}
}, [rowAction])
const filterFields: DataTableFilterField<BiddingFailureItem>[] = [
{
id: "biddingNumber",
label: "입찰번호",
type: "text",
placeholder: "입찰번호를 입력하세요",
},
{
id: "prNumber",
label: "P/R번호",
type: "text",
placeholder: "P/R번호를 입력하세요",
},
{
id: "title",
label: "입찰명",
type: "text",
placeholder: "입찰명을 입력하세요",
},
]
const advancedFilterFields: DataTableAdvancedFilterField<BiddingFailureItem>[] = [
{ id: "title", label: "입찰명", type: "text" },
{ id: "biddingNumber", label: "입찰번호", type: "text" },
{ id: "bidPicName", label: "입찰담당자", type: "text" },
{
id: "status",
label: "진행상태",
type: "multi-select",
options: Object.entries(biddingStatusLabels).map(([value, label]) => ({
label,
value,
})),
},
{
id: "contractType",
label: "계약구분",
type: "select",
options: Object.entries(contractTypeLabels).map(([value, label]) => ({
label,
value,
})),
},
{ id: "createdAt", label: "등록일", type: "date" },
{ id: "biddingRegistrationDate", label: "입찰등록일", type: "date" },
{ id: "disposalDate", label: "유찰일", type: "date" },
{ id: "disposalUpdatedAt", label: "폐찰일", type: "date" },
]
const { table } = useDataTable({
data,
columns,
pageCount,
filterFields,
enablePinning: true,
enableAdvancedFilter: true,
enableRowSelection: true,
singleRowSelection: true,
initialState: {
sorting: [{ id: "disposalDate", desc: true }], // 유찰일 기준 최신순
columnPinning: { right: ["actions"] },
},
getRowId: (originalRow) => String(originalRow.id),
shallow: false,
clearOnDefault: true,
})
const handleCompactChange = React.useCallback((compact: boolean) => {
setIsCompact(compact)
}, [])
const handleBiddingClosureDialogClose = React.useCallback(() => {
setBiddingClosureDialogOpen(false)
setRowAction(null)
setSelectedBidding(null)
}, [])
const handleRebidWithNavigation = React.useCallback(async (bidding: BiddingFailureItem) => {
if (!session?.user?.id) {
toast({
title: "오류",
description: "사용자 정보를 찾을 수 없습니다.",
variant: "destructive",
})
return
}
try {
const result = await increaseRoundOrRebid(bidding.id, session.user.id, 'rebidding')
if (result.success) {
toast({
title: "성공",
description: (result as any).message || "재입찰이 완료되었습니다.",
})
// 새로 생성된 입찰의 상세 페이지로 이동
if ((result as any).biddingId) {
router.push(`/evcp/bid/${(result as any).biddingId}`)
} else {
router.refresh()
}
} else {
toast({
title: "오류",
description: result.error || "재입찰 중 오류가 발생했습니다.",
variant: "destructive",
})
}
} catch (error) {
console.error('재입찰 실패:', error)
toast({
title: "오류",
description: "재입찰 중 오류가 발생했습니다.",
variant: "destructive",
})
}
}, [session?.user?.id, toast, router])
const handleCancelDisposal = React.useCallback(async (bidding: BiddingFailureItem) => {
if (!session?.user?.id) {
toast({
title: "오류",
description: "사용자 정보를 찾을 수 없습니다.",
variant: "destructive",
})
return
}
try {
const result = await cancelDisposalAction(bidding.id, session.user.id)
if (result.success) {
toast({
title: "성공",
description: result.message,
})
// 페이지 새로고침
router.refresh()
} else {
toast({
title: "오류",
description: result.error || "유찰취소 중 오류가 발생했습니다.",
variant: "destructive",
})
}
} catch (error) {
console.error('유찰취소 실패:', error)
toast({
title: "오류",
description: "유찰취소 중 오류가 발생했습니다.",
variant: "destructive",
})
}
}, [session?.user?.id, toast, router])
return (
<>
<DataTable
table={table}
compact={isCompact}
>
<DataTableAdvancedToolbar
table={table}
filterFields={advancedFilterFields}
shallow={false}
enableCompactToggle={true}
compactStorageKey="biddingsFailureTableCompact"
onCompactChange={handleCompactChange}
>
{/* Toolbar 액션 버튼들 */}
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => {
const selectedRows = table.getFilteredSelectedRowModel().rows
if (selectedRows.length === 0) {
toast({
title: "선택 필요",
description: "폐찰할 입찰을 선택해주세요.",
variant: "destructive",
})
return
}
if (selectedRows.length > 1) {
toast({
title: "하나만 선택",
description: "폐찰은 한 개의 입찰만 선택해주세요.",
variant: "destructive",
})
return
}
const bidding = selectedRows[0].original
if (bidding.status !== 'bidding_disposal') {
toast({
title: "유찰 상태만 가능",
description: "유찰 상태인 입찰만 폐찰할 수 있습니다.",
variant: "destructive",
})
return
}
setSelectedBidding(bidding)
setBiddingClosureDialogOpen(true)
}}
disabled={table.getFilteredSelectedRowModel().rows.length !== 1 ||
(table.getFilteredSelectedRowModel().rows.length === 1 &&
table.getFilteredSelectedRowModel().rows[0].original.status === 'bid_closure')}
>
<FileX className="mr-2 h-4 w-4" />
폐찰
</Button>
<Button
variant="outline"
size="sm"
onClick={() => {
const selectedRows = table.getFilteredSelectedRowModel().rows
if (selectedRows.length === 0) {
toast({
title: "선택 필요",
description: "재입찰할 입찰을 선택해주세요.",
variant: "destructive",
})
return
}
if (selectedRows.length > 1) {
toast({
title: "하나만 선택",
description: "재입찰은 한 개의 입찰만 선택해주세요.",
variant: "destructive",
})
return
}
const bidding = selectedRows[0].original
setSelectedBiddingForRebid(bidding)
setIsRebidDialogOpen(true)
}}
disabled={table.getFilteredSelectedRowModel().rows.length !== 1 ||
(table.getFilteredSelectedRowModel().rows.length === 1 &&
table.getFilteredSelectedRowModel().rows[0].original.status === 'bid_closure')}
>
<RefreshCw className="mr-2 h-4 w-4" />
재입찰
</Button>
<Button
variant="outline"
size="sm"
onClick={() => {
const selectedRows = table.getFilteredSelectedRowModel().rows
if (selectedRows.length === 0) {
toast({
title: "선택 필요",
description: "유찰취소할 입찰을 선택해주세요.",
variant: "destructive",
})
return
}
if (selectedRows.length > 1) {
toast({
title: "하나만 선택",
description: "유찰취소는 한 개의 입찰만 선택해주세요.",
variant: "destructive",
})
return
}
const bidding = selectedRows[0].original
if (bidding.status !== 'bidding_disposal' && bidding.status !== 'bid_closure') {
toast({
title: "유찰/폐찰 상태만 가능",
description: "유찰 또는 폐찰 상태인 입찰만 취소할 수 있습니다.",
variant: "destructive",
})
return
}
handleCancelDisposal(bidding)
}}
disabled={table.getFilteredSelectedRowModel().rows.length !== 1 ||
(table.getFilteredSelectedRowModel().rows.length === 1 &&
table.getFilteredSelectedRowModel().rows[0].original.status === 'bid_closure')}
>
<Undo2 className="mr-2 h-4 w-4" />
유찰취소
</Button>
</div>
</DataTableAdvancedToolbar>
</DataTable>
{/* 폐찰 다이얼로그 */}
{selectedBidding && session?.user?.id && (
<BiddingsClosureDialog
open={biddingClosureDialogOpen}
onOpenChange={handleBiddingClosureDialogClose}
bidding={selectedBidding}
onSuccess={() => {
router.refresh()
handleBiddingClosureDialogClose()
}}
onApprovalPreview={(data) => {
setApprovalPreviewData(data)
setIsApprovalPreviewDialogOpen(true)
}}
/>
)}
{/* 재입찰 확인 다이얼로그 */}
<Dialog open={isRebidDialogOpen} onOpenChange={setIsRebidDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>재입찰 확인</DialogTitle>
<DialogDescription>
입찰을 재입찰 처리하시겠습니까? 재입찰 후 새로운 입찰 화면으로 이동합니다.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
variant="outline"
onClick={() => {
setIsRebidDialogOpen(false)
setSelectedBiddingForRebid(null)
}}
>
아니오
</Button>
<Button
onClick={async () => {
if (selectedBiddingForRebid) {
await handleRebidWithNavigation(selectedBiddingForRebid)
}
setIsRebidDialogOpen(false)
setSelectedBiddingForRebid(null)
}}
>
예
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* 폐찰 결재 미리보기 다이얼로그 */}
{session?.user && session.user.epId && approvalPreviewData && (
<ApprovalPreviewDialog
open={isApprovalPreviewDialogOpen}
onOpenChange={(open) => {
setIsApprovalPreviewDialogOpen(open)
if (!open) {
setApprovalPreviewData(null)
}
}}
templateName={approvalPreviewData.templateName}
variables={approvalPreviewData.variables}
title={approvalPreviewData.title}
currentUser={{
id: Number(session.user.id),
epId: session.user.epId,
name: session.user.name || undefined,
email: session.user.email || undefined
}}
onConfirm={handleClosureApprovalConfirm}
/>
)}
</>
)
// 폐찰 결재 상신 핸들러
const handleClosureApprovalConfirm = async (data: { approvers: string[]; title: string; attachments?: File[] }) => {
if (!session?.user?.id || !approvalPreviewData || !selectedBidding) return
try {
const result = await requestBiddingClosureWithApproval({
biddingId: selectedBidding.id,
description: approvalPreviewData.description,
files: approvalPreviewData.files,
currentUser: {
id: Number(session.user.id),
epId: session.user.epId || null,
email: session.user.email || undefined
},
approvers: data.approvers,
})
if (result.status === 'pending_approval') {
toast({
title: '성공',
description: `폐찰 결재가 상신되었습니다. (ID: ${result.approvalId})`,
})
setIsApprovalPreviewDialogOpen(false)
setApprovalPreviewData(null)
handleBiddingClosureDialogClose()
router.refresh()
} else {
toast({
title: '오류',
description: '폐찰 결재 상신 중 오류가 발생했습니다.',
variant: 'destructive',
})
}
} catch (error) {
console.error('폐찰 결재 상신 실패:', error)
toast({
title: '오류',
description: '폐찰 결재 상신 중 오류가 발생했습니다.',
variant: 'destructive',
})
}
}
}
|