summaryrefslogtreecommitdiff
path: root/lib/bidding/vendor/partners-bidding-attendance-dialog.tsx
blob: d0ef97f188b2ef127f297d6934aea48a1a389cb9 (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
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
'use client'

import * as React from 'react'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { ScrollArea } from '@/components/ui/scroll-area'
import {
  Calendar,
  Users,
  Clock,
  CheckCircle,
  XCircle,
  Download,
} from 'lucide-react'

import { formatDate } from '@/lib/utils'
import { updatePartnerAttendance, getSpecificationMeetingForPartners } from '../detail/service'
import { useToast } from '@/hooks/use-toast'
import { useTransition } from 'react'
import { useRouter } from 'next/navigation'

interface PartnersSpecificationMeetingDialogProps {
  biddingDetail: {
    id: number
    biddingNumber: string
    title: string
    preQuoteDate: string | null
    biddingRegistrationDate: string | null
    evaluationDate: string | null
    hasSpecificationMeeting?: boolean // 사양설명회 여부 추가
  } | null
  biddingCompanyId: number
  isAttending: boolean | null
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function PartnersSpecificationMeetingDialog({
  biddingDetail,
  biddingCompanyId,
  isAttending,
  open,
  onOpenChange,
}: PartnersSpecificationMeetingDialogProps) {
  const { toast } = useToast()
  const [isPending, startTransition] = useTransition()
  const [isLoading, setIsLoading] = React.useState(false)
  const [meetingData, setMeetingData] = React.useState<any>(null)
  const router = useRouter()
  // 폼 상태
  const [attendance, setAttendance] = React.useState<string>('')
  const [attendeeCount, setAttendeeCount] = React.useState<string>('')
  const [representativeName, setRepresentativeName] = React.useState<string>('')
  const [representativePhone, setRepresentativePhone] = React.useState<string>('')

  // 사양설명회 정보 가져오기
  React.useEffect(() => {
    if (open && biddingDetail) {
      fetchMeetingData()
    }
  }, [open, biddingDetail])

  const fetchMeetingData = async () => {
    if (!biddingDetail) return
    
    setIsLoading(true)
    try {
      const result = await getSpecificationMeetingForPartners(biddingDetail.id)
      if (result.success) {
        setMeetingData(result.data)
      } else {
        toast({
          title: '오류',
          description: result.error,
          variant: 'destructive',
        })
      }
    } catch (error) {
      console.error('사양설명회 정보를 불러오는데 실패했습니다.', error)
      toast({
        title: '오류',
        description: '사양설명회 정보를 불러오는데 실패했습니다.',
        variant: 'destructive',
      })
    } finally {
      setIsLoading(false)
    }
  }

  // 다이얼로그 열릴 때 기존 값으로 초기화
  React.useEffect(() => {
    if (open) {
      if (isAttending === true) {
        setAttendance('attending')
      } else if (isAttending === false) {
        setAttendance('not_attending')
      } else {
        setAttendance('')
      }
      setAttendeeCount('')
      setRepresentativeName('')
      setRepresentativePhone('')
    }
  }, [open, isAttending])

  const handleSubmit = () => {
    if (!attendance) {
      toast({
        title: '선택 필요',
        description: '참석 여부를 선택해주세요.',
        variant: 'destructive',
      })
      return
    }

    // 참석하는 경우 필수 정보 체크
    if (attendance === 'attending') {
      if (!attendeeCount || !representativeName || !representativePhone) {
        toast({
          title: '필수 정보 누락',
          description: '참석인원수, 참석자 대표 이름, 연락처를 모두 입력해주세요.',
          variant: 'destructive',
        })
        return
      }

      const countNum = parseInt(attendeeCount)
      if (isNaN(countNum) || countNum < 1) {
        toast({
          title: '잘못된 입력',
          description: '참석인원수는 1 이상의 숫자를 입력해주세요.',
          variant: 'destructive',
        })
        return
      }
    }

    startTransition(async () => {
      const attendanceData = {
        isAttending: attendance === 'attending',
        attendeeCount: attendance === 'attending' ? parseInt(attendeeCount) : undefined,
        representativeName: attendance === 'attending' ? representativeName : undefined,
        representativePhone: attendance === 'attending' ? representativePhone : undefined,
      }

      const result = await updatePartnerAttendance(
        biddingCompanyId,
        attendanceData
      )

      if (result.success) {
        toast({
          title: '성공',
          description: result.message,
        })
        
        // 참석하는 경우 이메일 발송 알림
        if (attendance === 'attending' && result.data) {
          toast({
            title: '참석 알림 발송',
            description: '사양설명회 담당자에게 참석 알림이 발송되었습니다.',
          })
        }
        
        router.refresh()
        onOpenChange(false)
      } else {
        toast({
          title: '오류',
          description: result.error,
          variant: 'destructive',
        })
      }
    })
  }

  const handleFileDownload = async (filePath: string, fileName: string) => {
    try {
      const { downloadFile } = await import('@/lib/file-download')
      await downloadFile(filePath, fileName)
    } catch (error) {
      console.error('파일 다운로드 실패:', error)
      toast({
        title: '다운로드 실패',
        description: '파일 다운로드 중 오류가 발생했습니다.',
        variant: 'destructive',
      })
    }
  }

  if (!biddingDetail) return null

  // 사양설명회가 없는 경우
  if (biddingDetail.hasSpecificationMeeting === false) {
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Users className="w-5 h-5" />
              사양설명회 정보
            </DialogTitle>
          </DialogHeader>
          
          <div className="py-6 text-center">
            <XCircle className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
            <h3 className="text-lg font-medium mb-2">사양설명회 없음</h3>
            <p className="text-muted-foreground">
              해당 입찰 건은 사양설명회가 없습니다.
            </p>
          </div>

          <DialogFooter>
            <Button onClick={() => onOpenChange(false)}>
              확인
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    )
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Users className="w-5 h-5" />
            사양설명회
          </DialogTitle>
          <DialogDescription>
            {biddingDetail.title}의 사양설명회 정보 및 참석 여부를 확인해주세요.
          </DialogDescription>
        </DialogHeader>

        <ScrollArea className="max-h-[75vh]">
          {isLoading ? (
            <div className="flex items-center justify-center py-6">
              <div className="text-center">
                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary mx-auto mb-2"></div>
                <p className="text-sm text-muted-foreground">로딩 중...</p>
              </div>
            </div>
          ) : (
            <div className="space-y-6">
              {/* 사양설명회 기본 정보 */}
              {meetingData && (
                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-base flex items-center gap-2">
                      <Calendar className="w-4 h-4" />
                      설명회 정보
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="pt-0">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div>
                        <div className="text-sm space-y-2">
                          <div>
                            <span className="font-medium">설명회 일정:</span> 
                            <span className="ml-2">
                              {meetingData.meetingDate ? formatDate(meetingData.meetingDate, 'KR') : '미정'}
                            </span>
                          </div>
                          <div>
                            <span className="font-medium">설명회 담당자:</span>
                            <div className="ml-2 text-muted-foreground">
                              {meetingData.contactPerson && (
                                <div>{meetingData.contactPerson}</div>
                              )}
                              {meetingData.contactEmail && (
                                <div>{meetingData.contactEmail}</div>
                              )}
                              {meetingData.contactPhone && (
                                <div>{meetingData.contactPhone}</div>
                              )}
                            </div>
                          </div>
                        </div>
                      </div>
                      
                      <div>
                        <div className="text-sm">
                          <span className="font-medium">설명회 자료:</span>
                          <div className="mt-2 space-y-1">
                            {meetingData.documents && meetingData.documents.length > 0 ? (
                              meetingData.documents.map((doc: any) => (
                                <Button
                                  key={doc.id}
                                  variant="outline"
                                  size="sm"
                                  onClick={() => handleFileDownload(doc.filePath, doc.originalFileName)}
                                  className="flex items-center gap-2 h-8 text-xs"
                                >
                                  <Download className="w-3 h-3" />
                                  {doc.originalFileName}
                                </Button>
                              ))
                            ) : (
                              <span className="text-muted-foreground">첨부파일 없음</span>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )}

              {/* 참석 여부 입력 폼 */}
              <Card>
                <CardHeader className="pb-3">
                  <CardTitle className="text-base">참석 여부</CardTitle>
                </CardHeader>
                <CardContent className="pt-0 space-y-4">
                  <RadioGroup
                    value={attendance}
                    onValueChange={setAttendance}
                    className="space-y-3"
                  >
                    <div className="flex items-start space-x-3 p-3 border rounded-lg hover:bg-muted/50 transition-colors">
                      <RadioGroupItem value="attending" id="attending" className="mt-1" />
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-3">
                          <CheckCircle className="w-5 h-5 text-green-600" />
                          <Label htmlFor="attending" className="font-medium cursor-pointer">
                            Y (참석)
                          </Label>
                        </div>
                        
                        {attendance === 'attending' && (
                          <div className="space-y-3 mt-3 pl-2">
                            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                              <div>
                                <Label htmlFor="attendeeCount" className="text-xs">참석인원수</Label>
                                <Input
                                  id="attendeeCount"
                                  type="number"
                                  min="1"
                                  value={attendeeCount}
                                  onChange={(e) => setAttendeeCount(e.target.value)}
                                  placeholder="명"
                                  className="h-8 text-sm"
                                />
                              </div>
                              <div>
                                <Label htmlFor="representativeName" className="text-xs">참석자 대표(이름)</Label>
                                <Input
                                  id="representativeName"
                                  value={representativeName}
                                  onChange={(e) => setRepresentativeName(e.target.value)}
                                  placeholder="홍길동 과장"
                                  className="h-8 text-sm"
                                />
                              </div>
                              <div>
                                <Label htmlFor="representativePhone" className="text-xs">참석자 대표(연락처)</Label>
                                <Input
                                  id="representativePhone"
                                  value={representativePhone}
                                  onChange={(e) => setRepresentativePhone(e.target.value)}
                                  placeholder="010-0000-0000"
                                  className="h-8 text-sm"
                                />
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                    
                    <div className="flex items-center space-x-3 p-3 border rounded-lg hover:bg-muted/50 transition-colors">
                      <RadioGroupItem value="not_attending" id="not_attending" />
                      <div className="flex items-center gap-2 flex-1">
                        <XCircle className="w-5 h-5 text-red-600" />
                        <Label htmlFor="not_attending" className="font-medium cursor-pointer">
                          N (불참)
                        </Label>
                      </div>
                    </div>
                  </RadioGroup>
                </CardContent>
              </Card>

              {/* 현재 상태 표시 */}
              {isAttending !== null && (
                <Card>
                  <CardContent className="pt-6">
                    <div className="flex items-center gap-2 text-blue-800">
                      <Clock className="w-4 h-4" />
                      <span className="text-sm">
                        현재 상태: {isAttending ? '참석' : '불참'} ({formatDate(new Date().toISOString(), 'KR')} 기준)
                      </span>
                    </div>
                  </CardContent>
                </Card>
              )}
            </div>
          )}
        </ScrollArea>

        <DialogFooter className="flex gap-2">
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isPending}
          >
            취소
          </Button>
          <Button
            onClick={handleSubmit}
            disabled={isPending || !attendance || isLoading}
            className="min-w-[100px]"
          >
            {isPending ? '저장 중...' : '확인'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}