summaryrefslogtreecommitdiff
path: root/lib/bidding/detail/table/bidding-detail-vendor-table.tsx
blob: 407cc51c36d14c81f76452c6ea93857909496c6f (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
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
'use client'

import * as React from 'react'
import { useSession } from 'next-auth/react'
import { type DataTableAdvancedFilterField, type DataTableFilterField } 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 { BiddingDetailVendorToolbarActions } from './bidding-detail-vendor-toolbar-actions'
import { BiddingDetailVendorEditDialog } from './bidding-detail-vendor-edit-dialog'
import { BiddingAwardDialog } from './bidding-award-dialog'
import { getBiddingDetailVendorColumns } from './bidding-detail-vendor-columns'
import { QuotationVendor } from '@/lib/bidding/detail/service'
import { Bidding } from '@/db/schema'
import { VendorPriceAdjustmentViewDialog } from './vendor-price-adjustment-view-dialog'
import { QuotationHistoryDialog } from './quotation-history-dialog'
import { ApprovalPreviewDialog } from '@/lib/approval/approval-preview-dialog'
import { ApplicationReasonDialog } from '@/lib/rfq-last/vendor/application-reason-dialog'
import { requestBiddingAwardWithApproval } from '@/lib/bidding/approval-actions'
import { useToast } from '@/hooks/use-toast'

interface BiddingDetailVendorTableContentProps {
  biddingId: number
  bidding: Bidding
  vendors: QuotationVendor[]
  onRefresh: () => void
  onOpenSelectionReasonDialog: () => void
  onViewItemDetails?: (vendor: QuotationVendor) => void
  onViewQuotationHistory?: (vendor: QuotationVendor) => void
  readOnly?: boolean
}

const filterFields: DataTableFilterField<QuotationVendor>[] = [
  {
    id: 'vendorName',
    label: '업체명',
    placeholder: '업체명으로 검색...',
  },
  {
    id: 'vendorCode',
    label: '업체코드',
    placeholder: '업체코드로 검색...',
  },
  {
    id: 'contactPerson',
    label: '담당자',
    placeholder: '담당자로 검색...',
  },
]

const advancedFilterFields: DataTableAdvancedFilterField<QuotationVendor>[] = [
  {
    id: 'vendorName',
    label: '업체명',
    type: 'text',
  },
  {
    id: 'vendorCode',
    label: '업체코드',
    type: 'text',
  },
  {
    id: 'contactPerson',
    label: '담당자',
    type: 'text',
  },
  {
    id: 'quotationAmount',
    label: '견적금액',
    type: 'number',
  },
    {
      id: 'invitationStatus',
      label: '상태',
      type: 'multi-select',
      options: [
        { label: '제출완료', value: 'bidding_submitted' },
        { label: '선정완료', value: 'bidding_accepted' },
        { label: '미제출', value: 'pending' },
      ],
    },
]

export function BiddingDetailVendorTableContent({
  biddingId,
  bidding,
  vendors,
  onRefresh,
  onViewItemDetails,
  onViewQuotationHistory,
  readOnly = false
}: BiddingDetailVendorTableContentProps) {
  const { data: session } = useSession()
  const { toast } = useToast()
  
  // 세션에서 사용자 ID 가져오기
  const userId = session?.user?.id || ''
  const [selectedVendor, setSelectedVendor] = React.useState<QuotationVendor | null>(null)
  const [isAwardDialogOpen, setIsAwardDialogOpen] = React.useState(false)
  const [isAwardRatioDialogOpen, setIsAwardRatioDialogOpen] = React.useState(false)
  const [isVendorPriceAdjustmentDialogOpen, setIsVendorPriceAdjustmentDialogOpen] = React.useState(false)
  const [quotationHistoryData, setQuotationHistoryData] = React.useState<any>(null)
  const [isQuotationHistoryDialogOpen, setIsQuotationHistoryDialogOpen] = React.useState(false)
  const [approvalPreviewData, setApprovalPreviewData] = React.useState<{
    templateName: string
    variables: Record<string, string>
    title: string
    selectionReason: string
    awardedCompanies: {
      companyId: number
      companyName: string | null
      finalQuoteAmount: number
      awardRatio: number
    }[]
  } | null>(null)
  const [isApprovalPreviewDialogOpen, setIsApprovalPreviewDialogOpen] = React.useState(false)

  const handleViewPriceAdjustment = (vendor: QuotationVendor) => {
    setSelectedVendor(vendor)
    setIsVendorPriceAdjustmentDialogOpen(true)
  }

  const handleViewQuotationHistory = async (vendor: QuotationVendor) => {
    try {
      const { getQuotationHistory } = await import('@/lib/bidding/selection/actions')
      const result = await getQuotationHistory(biddingId, vendor.vendorId)
      console.log(result)

      if (result.success) {
        setQuotationHistoryData({
          vendorName: vendor.vendorName,
          history: result.data?.history || [],
          biddingCurrency: bidding.currency || 'KRW',
          targetPrice: bidding.targetPrice ? parseFloat(bidding.targetPrice.toString()) : undefined
        })
        setSelectedVendor(vendor)
        setIsQuotationHistoryDialogOpen(true)
      } else {
        toast({
          title: '오류',
          description: result.error,
          variant: 'destructive',
        })
      }
    } catch (error) {
      console.error('Failed to load quotation history:', error)
      toast({
        title: '오류',
        description: '견적 히스토리를 불러오는데 실패했습니다.',
        variant: 'destructive',
      })
    }
  }

  const columns = React.useMemo(
    () => getBiddingDetailVendorColumns({
      onViewPriceAdjustment: handleViewPriceAdjustment,
      onViewItemDetails: onViewItemDetails,
      onViewQuotationHistory: onViewQuotationHistory || handleViewQuotationHistory,
      biddingStatus: bidding.status,
      biddingTargetPrice: bidding.targetPrice,
      biddingFinalBidPrice: bidding.finalBidPrice,
      biddingCurrency: bidding.currency || undefined
    }),
    [handleViewPriceAdjustment, onViewItemDetails, onViewQuotationHistory, handleViewQuotationHistory, bidding.status, bidding.targetPrice, bidding.finalBidPrice, bidding.currency]
  )

  const { table } = useDataTable({
    data: vendors,
    columns,
    pageCount: 1,
    filterFields,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{ id: 'vendorName', desc: false }],
      columnPinning: { right: ['actions'] },
    },
    getRowId: (originalRow) => originalRow.id.toString(),
    shallow: false,
    clearOnDefault: true,
  })

  // single select된 vendor 가져오기
  const selectedRows = table.getSelectedRowModel().rows
  const singleSelectedVendor = selectedRows.length === 1 ? selectedRows[0].original : null

  // 발주비율 산정 버튼 핸들러
  const handleOpenAwardRatioDialog = () => {
    if (singleSelectedVendor) {
      setSelectedVendor(singleSelectedVendor)
      setIsAwardRatioDialogOpen(true)
    }
  }

  // 낙찰 결재 상신 핸들러
  const handleAwardApprovalConfirm = async (data: { approvers: string[]; title: string; attachments?: File[] }) => {
    if (!session?.user?.id || !approvalPreviewData) return

    try {
      const result = await requestBiddingAwardWithApproval({
        biddingId,
        selectionReason: approvalPreviewData.selectionReason,
        awardedCompanies: approvalPreviewData.awardedCompanies,
        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)
        onRefresh()
      } else {
        toast({
          title: '오류',
          description: '낙찰 결재 상신 중 오류가 발생했습니다.',
          variant: 'destructive',
        })
      }
    } catch (error) {
      console.error('낙찰 결재 상신 실패:', error)
      toast({
        title: '오류',
        description: '낙찰 결재 상신 중 오류가 발생했습니다.',
        variant: 'destructive',
      })
    }
  }

  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <BiddingDetailVendorToolbarActions
            biddingId={biddingId}
            bidding={bidding}
            userId={userId}
            onOpenAwardDialog={() => setIsAwardDialogOpen(true)}
            onOpenAwardRatioDialog={handleOpenAwardRatioDialog}
            onSuccess={onRefresh}
            winnerVendor={vendors.find(v => v.awardRatio === 100)}
            singleSelectedVendor={singleSelectedVendor}
            readOnly={readOnly}
          />
        </DataTableAdvancedToolbar>
      </DataTable>

      {/* 발주비율 산정 Dialog */}
      <BiddingDetailVendorEditDialog
        vendor={selectedVendor}
        open={isAwardRatioDialogOpen}
        onOpenChange={setIsAwardRatioDialogOpen}
        onSuccess={onRefresh}
        biddingAwardCount={bidding.awardCount || undefined}
        biddingStatus={bidding.status}
        allVendors={vendors}
      />

      <BiddingAwardDialog
        biddingId={biddingId}
        open={isAwardDialogOpen}
        onOpenChange={setIsAwardDialogOpen}
        onSuccess={onRefresh}
        onApprovalPreview={(data) => {
          setApprovalPreviewData(data)
          setIsAwardDialogOpen(false)
          setIsApprovalPreviewDialogOpen(true)
        }}
      />

      <VendorPriceAdjustmentViewDialog
        open={isVendorPriceAdjustmentDialogOpen}
        onOpenChange={setIsVendorPriceAdjustmentDialogOpen}
        vendorName={selectedVendor?.vendorName || ''}
        priceAdjustmentResponse={selectedVendor?.priceAdjustmentResponse ?? null}
        biddingCompanyId={selectedVendor?.id || 0}
      />

      <QuotationHistoryDialog
        open={isQuotationHistoryDialogOpen}
        onOpenChange={setIsQuotationHistoryDialogOpen}
        vendorName={quotationHistoryData?.vendorName || ''}
        history={quotationHistoryData?.history || []}
        biddingCurrency={quotationHistoryData?.biddingCurrency || 'KRW'}
        targetPrice={quotationHistoryData?.targetPrice}
      />

      {/* 낙찰 결재 미리보기 다이얼로그 */}
      {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={handleAwardApprovalConfirm}
        />
      )}
    </>
  )
}