summaryrefslogtreecommitdiff
path: root/lib/bidding/detail/table/bidding-detail-vendor-edit-dialog.tsx
blob: 5bc85fdb0a6b54ae96c64c0ac9632ba7c0acffd2 (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
'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 {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { updateBiddingDetailVendor } from '@/lib/bidding/detail/service'
import { QuotationVendor } from '@/lib/bidding/detail/service'
import { useToast } from '@/hooks/use-toast'
import { useTransition } from 'react'

interface BiddingDetailVendorEditDialogProps {
  vendor: QuotationVendor | null
  open: boolean
  onOpenChange: (open: boolean) => void
  onSuccess: () => void
  biddingAwardCount?: string // 낙찰업체 수 정보 추가
  biddingStatus?: string // 입찰 상태 정보 추가
  allVendors?: QuotationVendor[] // 전체 벤더 목록 추가
}

export function BiddingDetailVendorEditDialog({
  vendor,
  open,
  onOpenChange,
  onSuccess,
  biddingAwardCount,
  biddingStatus,
  allVendors = []
}: BiddingDetailVendorEditDialogProps) {
  const { toast } = useToast()
  const [isPending, startTransition] = useTransition()

  // 폼 상태 (간소화 - 수정 가능한 필드만)
  const [formData, setFormData] = React.useState({
    awardRatio: 0,
  })

  // 단수낙찰의 경우 이미 100%인 벤더가 있는지 확인
  const hasWinnerWith100Percent = React.useMemo(() => {
    if (biddingAwardCount === 'single') {
      return allVendors.some(v => v.awardRatio === 100 && v.id !== vendor?.id)
    }
    return false
  }, [allVendors, biddingAwardCount, vendor?.id])

  // vendor가 변경되면 폼 데이터 업데이트
  React.useEffect(() => {
    if (vendor) {
      // 낙찰업체 수가 단수인 경우 발주비율을 100%로 자동 설정
      const defaultAwardRatio = biddingAwardCount === 'single' ? 100 : (vendor.awardRatio || 0)
      setFormData({
        awardRatio: defaultAwardRatio,
      })
    }
  }, [vendor, biddingAwardCount])

  const handleEdit = () => {
    if (!vendor) return


    startTransition(async () => {
      const response = await updateBiddingDetailVendor(
        vendor.id,
        vendor.quotationAmount, // 기존 견적금액 유지
        vendor.currency, // 기존 통화 유지
        formData.awardRatio
      )

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

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle>협력업체 발주비율 산정</DialogTitle>
          <DialogDescription>
            협력업체 발주비율을 산정해주세요.
          </DialogDescription>
        </DialogHeader>
        <div className="grid gap-4 py-4">
          {/* 읽기 전용 업체 정보 */}
          {vendor && (
            <div className="bg-muted/50 rounded-lg p-3 border">
              <h4 className="font-medium mb-2">협력업체 정보</h4>
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="text-muted-foreground">협력업체명:</span> {vendor.vendorName}
                </div>
                <div>
                  <span className="text-muted-foreground">협력업체코드:</span> {vendor.vendorCode}
                </div>
              </div>
            </div>
          )}

          {/* 수정 가능한 필드들 */}
          {vendor && vendor.isBiddingParticipated !== true && (
            <div className="bg-orange-50 border border-orange-200 rounded-lg p-3 mb-4">
              <div className="flex items-center gap-2 text-orange-800">
                <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                </svg>
                <span className="font-medium">입찰 참여 안내</span>
              </div>
              <p className="text-sm text-orange-700 mt-1">
                {vendor.isBiddingParticipated === null 
                  ? '이 업체는 아직 입찰참여 여부가 결정되지 않았습니다. 입찰에 참여한 업체만 발주비율을 설정할 수 있습니다.'
                  : '이 업체는 입찰에 참여하지 않습니다. 발주비율을 설정할 수 없습니다.'
                }
              </p>
            </div>
          )}

          <div className="space-y-2">
            <Label htmlFor="edit-awardRatio">발주비율 (%)</Label>
            <Input
              id="edit-awardRatio"
              type="number"
              min="0"
              max="100"
              value={formData.awardRatio}
              onChange={(e) => setFormData({ ...formData, awardRatio: Number(e.target.value) })}
              placeholder="발주비율을 입력하세요"
              disabled={vendor?.isBiddingParticipated !== true || biddingAwardCount === 'single' || biddingStatus === 'vendor_selected' || hasWinnerWith100Percent}
            />
            {vendor?.isBiddingParticipated !== true && (
              <p className="text-sm text-muted-foreground">
                입찰에 참여한 업체만 발주비율을 설정할 수 있습니다.
              </p>
            )}
            {biddingAwardCount === 'single' && vendor?.isBiddingParticipated === true && (
              <p className="text-sm text-blue-600">
                단수 낙찰의 경우 발주비율은 자동으로 100%로 설정됩니다.
              </p>
            )}
            {biddingStatus === 'vendor_selected' && (
              <p className="text-sm text-red-600">
                낙찰이 완료되어 발주비율을 수정할 수 없습니다.
              </p>
            )}
            {hasWinnerWith100Percent && (
              <p className="text-sm text-orange-600">
                단수 낙찰의 경우 이미 100% 발주비율이 설정된 업체가 있어 다른 업체의 발주비율을 수정할 수 없습니다.
              </p>
            )}
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            취소
          </Button>
          <Button
            onClick={handleEdit}
            disabled={isPending || vendor?.isBiddingParticipated !== true || hasWinnerWith100Percent}
          >
            산정
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}