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

import * as React from '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 { BiddingDetailVendorCreateDialog } from './bidding-detail-vendor-create-dialog'
import { BiddingDetailVendorEditDialog } from './bidding-detail-vendor-edit-dialog'
import { getBiddingDetailVendorColumns } from './bidding-detail-vendor-columns'
import { QuotationVendor } from '@/lib/bidding/detail/service'
import {
  deleteQuotationVendor,
  selectWinner
} from '@/lib/bidding/detail/service'
import { selectWinnerSchema } from '@/lib/bidding/validation'
import { useToast } from '@/hooks/use-toast'
import { useTransition } from 'react'

interface BiddingDetailVendorTableContentProps {
  biddingId: number
  vendors: QuotationVendor[]
  onRefresh: () => void
  onOpenItemsDialog: () => void
  onOpenTargetPriceDialog: () => void
  onOpenSelectionReasonDialog: () => void
  onEdit?: (vendor: QuotationVendor) => void
  onDelete?: (vendor: QuotationVendor) => void
  onSelectWinner?: (vendor: QuotationVendor) => void
}

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: 'status',
    label: '상태',
    type: 'multi-select',
    options: [
      { label: '제출완료', value: 'submitted' },
      { label: '선정완료', value: 'selected' },
      { label: '미제출', value: 'pending' },
    ],
  },
]

export function BiddingDetailVendorTableContent({
  biddingId,
  vendors,
  onRefresh,
  onOpenItemsDialog,
  onOpenTargetPriceDialog,
  onOpenSelectionReasonDialog,
  onEdit,
  onDelete,
  onSelectWinner
}: BiddingDetailVendorTableContentProps) {
  const { toast } = useToast()
  const [isPending, startTransition] = useTransition()
  const [selectedVendor, setSelectedVendor] = React.useState<QuotationVendor | null>(null)
  const [isEditDialogOpen, setIsEditDialogOpen] = React.useState(false)

  const handleDelete = (vendor: QuotationVendor) => {
    if (!confirm(`${vendor.vendorName} 업체를 삭제하시겠습니까?`)) return

    startTransition(async () => {
      const response = await deleteQuotationVendor(vendor.id)

      if (response.success) {
        toast({
          title: '성공',
          description: response.message,
        })
        onRefresh()
      } else {
        toast({
          title: '오류',
          description: response.error,
          variant: 'destructive',
        })
      }
    })
  }

  const handleSelectWinner = (vendor: QuotationVendor) => {
    if (!vendor.awardRatio || vendor.awardRatio <= 0) {
      toast({
        title: '오류',
        description: '발주비율을 먼저 설정해주세요.',
        variant: 'destructive',
      })
      return
    }

    if (!confirm(`${vendor.vendorName} 업체를 낙찰자로 선정하시겠습니까?`)) return

    startTransition(async () => {
      const result = selectWinnerSchema.safeParse({
        biddingId,
        vendorId: vendor.id,
        awardRatio: vendor.awardRatio,
      })

      if (!result.success) {
        toast({
          title: '유효성 오류',
          description: result.error.issues[0]?.message || '입력값을 확인해주세요.',
          variant: 'destructive',
        })
        return
      }

      const response = await selectWinner(biddingId, vendor.id, vendor.awardRatio, 'current-user')

      if (response.success) {
        toast({
          title: '성공',
          description: response.message,
        })
        onRefresh()
      } else {
        toast({
          title: '오류',
          description: response.error,
          variant: 'destructive',
        })
      }
    })
  }

  const handleEdit = (vendor: QuotationVendor) => {
    setSelectedVendor(vendor)
    setIsEditDialogOpen(true)
  }

  const columns = React.useMemo(
    () => getBiddingDetailVendorColumns({
      onEdit: onEdit || handleEdit,
      onDelete: onDelete || handleDelete,
      onSelectWinner: onSelectWinner || handleSelectWinner
    }),
    [onEdit, onDelete, onSelectWinner, handleEdit, handleDelete, handleSelectWinner]
  )

  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,
  })

  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <BiddingDetailVendorToolbarActions
            table={table}
            biddingId={biddingId}
            onOpenItemsDialog={onOpenItemsDialog}
            onOpenTargetPriceDialog={onOpenTargetPriceDialog}
            onOpenSelectionReasonDialog={onOpenSelectionReasonDialog}

            onSuccess={onRefresh}
          />
        </DataTableAdvancedToolbar>
      </DataTable>

      <BiddingDetailVendorEditDialog
        vendor={selectedVendor}
        open={isEditDialogOpen}
        onOpenChange={setIsEditDialogOpen}
        onSuccess={onRefresh}
      />
    </>
  )
}