summaryrefslogtreecommitdiff
path: root/lib/bidding/detail/table/bidding-detail-vendor-create-dialog.tsx
blob: d0f85b140718a8a109100f5c84467008d8a454da (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
324
325
326
327
328
'use client'

import * as React from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Checkbox } from '@/components/ui/checkbox'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/components/ui/command'
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover'
import { Check, ChevronsUpDown, Search, Loader2, X, Plus } from 'lucide-react'
import { cn } from '@/lib/utils'
import { createBiddingDetailVendor } from '@/lib/bidding/detail/service'
import { searchVendorsForBidding } from '@/lib/bidding/service'
import { useToast } from '@/hooks/use-toast'
import { useTransition } from 'react'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'

interface BiddingDetailVendorCreateDialogProps {
  biddingId: number
  open: boolean
  onOpenChange: (open: boolean) => void
  onSuccess: () => void
}

interface Vendor {
  id: number
  vendorName: string
  vendorCode: string
  status: string
}

export function BiddingDetailVendorCreateDialog({
  biddingId,
  open,
  onOpenChange,
  onSuccess
}: BiddingDetailVendorCreateDialogProps) {
  const { toast } = useToast()
  const [isPending, startTransition] = useTransition()

  // Vendor 검색 상태
  const [vendorList, setVendorList] = React.useState<Vendor[]>([])
  const [selectedVendors, setSelectedVendors] = React.useState<Vendor[]>([])
  const [vendorOpen, setVendorOpen] = React.useState(false)

  // 폼 상태 (간소화 - 필수 항목만)
  const [formData, setFormData] = React.useState({
    awardRatio: 100, // 기본 100%
  })

  // 벤더 로드
  const loadVendors = React.useCallback(async () => {
    try {
      const result = await searchVendorsForBidding('', biddingId) // 빈 검색어로 모든 벤더 로드
      setVendorList(result || [])
    } catch (error) {
      console.error('Failed to load vendors:', error)
      toast({
        title: '오류',
        description: '벤더 목록을 불러오는데 실패했습니다.',
        variant: 'destructive',
      })
      setVendorList([])
    }
  }, [biddingId])

  React.useEffect(() => {
    if (open) {
      loadVendors()
    }
  }, [open, loadVendors])

  // 초기화
  React.useEffect(() => {
    if (!open) {
      setSelectedVendors([])
      setFormData({
        awardRatio: 100, // 기본 100%
      })
    }
  }, [open])

  // 벤더 추가
  const handleAddVendor = (vendor: Vendor) => {
    if (!selectedVendors.find(v => v.id === vendor.id)) {
      setSelectedVendors([...selectedVendors, vendor])
    }
    setVendorOpen(false)
  }

  // 벤더 제거
  const handleRemoveVendor = (vendorId: number) => {
    setSelectedVendors(selectedVendors.filter(v => v.id !== vendorId))
  }

  // 이미 선택된 벤더인지 확인
  const isVendorSelected = (vendorId: number) => {
    return selectedVendors.some(v => v.id === vendorId)
  }

  const handleCreate = () => {
    if (selectedVendors.length === 0) {
      toast({
        title: '오류',
        description: '업체를 선택해주세요.',
        variant: 'destructive',
      })
      return
    }

    startTransition(async () => {
      let successCount = 0
      let errorMessages: string[] = []

      for (const vendor of selectedVendors) {
        try {
          const response = await createBiddingDetailVendor(
            biddingId,
            vendor.id
          )

          if (response.success) {
            successCount++
          } else {
            errorMessages.push(`${vendor.vendorName}: ${response.error}`)
          }
        } catch (error) {
          errorMessages.push(`${vendor.vendorName}: 처리 중 오류가 발생했습니다.`)
        }
      }

      if (successCount > 0) {
        toast({
          title: '성공',
          description: `${successCount}개의 업체가 성공적으로 추가되었습니다.${errorMessages.length > 0 ? ` ${errorMessages.length}개는 실패했습니다.` : ''}`,
        })
        onOpenChange(false)
        resetForm()
        onSuccess()
      }

      if (errorMessages.length > 0 && successCount === 0) {
        toast({
          title: '오류',
          description: `업체 추가에 실패했습니다: ${errorMessages.join(', ')}`,
          variant: 'destructive',
        })
      }
    })
  }

  const resetForm = () => {
    setSelectedVendors([])
    setFormData({
      awardRatio: 100, // 기본 100%
    })
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] p-0 flex flex-col">
        {/* 헤더 */}
        <DialogHeader className="p-6 pb-0">
          <DialogTitle>협력업체 추가</DialogTitle>
          <DialogDescription>
            입찰에 참여할 업체를 선택하세요. 여러 개 선택 가능합니다.
          </DialogDescription>
        </DialogHeader>

        {/* 메인 컨텐츠 */}
        <div className="flex-1 px-6 py-4 overflow-y-auto">
          <div className="space-y-6">
            {/* 업체 선택 카드 */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">업체 선택</CardTitle>
                <CardDescription>
                  입찰에 참여할 협력업체를 선택하세요.
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {/* 업체 추가 버튼 */}
                  <Popover open={vendorOpen} onOpenChange={setVendorOpen}>
                    <PopoverTrigger asChild>
                      <Button
                        variant="outline"
                        role="combobox"
                        aria-expanded={vendorOpen}
                        className="w-full justify-between"
                        disabled={vendorList.length === 0}
                      >
                        <span className="flex items-center gap-2">
                          <Plus className="h-4 w-4" />
                          업체 선택하기
                        </span>
                        <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-[500px] p-0" align="start">
                      <Command>
                        <CommandInput placeholder="업체명 또는 코드로 검색..." />
                        <CommandList>
                          <CommandEmpty>검색 결과가 없습니다.</CommandEmpty>
                          <CommandGroup>
                            {vendorList
                              .filter(vendor => !isVendorSelected(vendor.id))
                              .map((vendor) => (
                                <CommandItem
                                  key={vendor.id}
                                  value={`${vendor.vendorCode} ${vendor.vendorName}`}
                                  onSelect={() => handleAddVendor(vendor)}
                                >
                                  <div className="flex items-center gap-2 w-full">
                                    <Badge variant="outline" className="shrink-0">
                                      {vendor.vendorCode}
                                    </Badge>
                                    <span className="truncate">{vendor.vendorName}</span>
                                  </div>
                                </CommandItem>
                              ))}
                          </CommandGroup>
                        </CommandList>
                      </Command>
                    </PopoverContent>
                  </Popover>

                  {/* 선택된 업체 목록 */}
                  {selectedVendors.length > 0 && (
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <h4 className="text-sm font-medium">선택된 업체 ({selectedVendors.length}개)</h4>
                      </div>
                      <div className="space-y-2">
                        {selectedVendors.map((vendor, index) => (
                          <div
                            key={vendor.id}
                            className="flex items-center justify-between p-3 rounded-lg bg-secondary/50"
                          >
                            <div className="flex items-center gap-3">
                              <span className="text-sm text-muted-foreground">
                                {index + 1}.
                              </span>
                              <Badge variant="outline">
                                {vendor.vendorCode}
                              </Badge>
                              <span className="text-sm font-medium">
                                {vendor.vendorName}
                              </span>
                            </div>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleRemoveVendor(vendor.id)}
                              className="h-8 w-8 p-0"
                            >
                              <X className="h-4 w-4" />
                            </Button>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {selectedVendors.length === 0 && (
                    <div className="text-center py-8 text-muted-foreground">
                      <p className="text-sm">아직 선택된 업체가 없습니다.</p>
                      <p className="text-xs mt-1">위 버튼을 클릭하여 업체를 추가하세요.</p>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </div>
        </div>

        {/* 푸터 */}
        <DialogFooter className="p-6 pt-0 border-t">
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isPending}
          >
            취소
          </Button>
          <Button
            onClick={handleCreate}
            disabled={isPending || selectedVendors.length === 0}
          >
            {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            {selectedVendors.length > 0
              ? `${selectedVendors.length}개 업체 추가`
              : '업체 추가'
            }
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}