summaryrefslogtreecommitdiff
path: root/lib/general-contracts/main/create-general-contract-dialog.tsx
blob: 720192d8d136e6f92612950466c6ee05188b38d0 (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
"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { Plus } from "lucide-react"
import { toast } from "sonner"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { createContract } from "@/lib/general-contracts/service"
import { 
  GENERAL_CONTRACT_CATEGORIES, 
  GENERAL_CONTRACT_TYPES,
  GENERAL_CONTRACT_TYPE_LABELS,
  GENERAL_EXECUTION_METHODS
} from "@/lib/general-contracts/types"
import { useSession } from "next-auth/react"
import { VendorSelectorDialogSingle } from "@/components/common/vendor/vendor-selector-dialog-single"
import { VendorSearchItem } from "@/components/common/vendor/vendor-service"

interface CreateContractForm {
  contractNumber: string
  name: string
  category: string
  type: string
  executionMethod: string
  startDate: string
  endDate: string
  validityEndDate: string
  notes: string
}

export function CreateGeneralContractDialog() {
  const router = useRouter()
  const { data: session } = useSession()
  const [open, setOpen] = React.useState(false)
  const [isLoading, setIsLoading] = React.useState(false)
  const [selectedVendor, setSelectedVendor] = React.useState<VendorSearchItem | null>(null)

  const [form, setForm] = React.useState<CreateContractForm>({
    contractNumber: '',
    name: '',
    category: '',
    type: '',
    executionMethod: '',
    startDate: '',
    endDate: '',
    validityEndDate: '',
    notes: '',
  })

  const handleSubmit = async () => {
    // 필수 필드 검증
    const validationErrors: string[] = []
    
    if (!form.name) validationErrors.push('계약명')
    if (!form.category) validationErrors.push('계약구분')
    if (!form.type) validationErrors.push('계약종류')
    if (!form.executionMethod) validationErrors.push('체결방식')
    if (!selectedVendor) validationErrors.push('협력업체')
    
    // AD, LO, OF 계약이 아닌 경우에만 계약기간 필수값 체크
    if (!['AD', 'LO', 'OF'].includes(form.type)) {
      if (!form.startDate) validationErrors.push('계약시작일')
      if (!form.endDate) validationErrors.push('계약종료일')
    }
    
    // LO 계약인 경우 계약체결유효기간 필수값 체크
    if (form.type === 'LO' && !form.validityEndDate) {
      validationErrors.push('유효기간')
    }
    
    if (validationErrors.length > 0) {
      toast.error(`다음 필수 항목을 입력해주세요: ${validationErrors.join(', ')}`)
      return
    }

    if (!form.validityEndDate) {
      setForm(prev => ({ ...prev, validityEndDate: form.endDate }))
    }

    try {
      setIsLoading(true)
      
      const contractData = {
        contractNumber: '',
        name: form.name,
        category: form.category,
        type: form.type,
        executionMethod: form.executionMethod,
        contractSourceType: 'manual',
        vendorId: selectedVendor!.id,
        startDate: form.startDate,
        endDate: form.endDate,
        validityEndDate: form.validityEndDate || form.endDate,
        status: 'Draft',
        registeredById: session?.user?.id || 1,
        lastUpdatedById: session?.user?.id || 1,
        notes: form.notes,
      }

      await createContract(contractData)
      
      toast.success("새 계약이 생성되었습니다.")
      setOpen(false)
      resetForm()
      
      // 상세 페이지로 이동
      router.refresh()
    } catch (error) {
      console.error('Error creating contract:', error)
      toast.error("계약 생성 중 오류가 발생했습니다.")
    } finally {
      setIsLoading(false)
    }
  }

  const resetForm = () => {
    setForm({
      contractNumber: '',
      name: '',
      category: '',
      type: '',
      executionMethod: '',
      startDate: '',
      endDate: '',
      validityEndDate: '',
      notes: '',
    })
    setSelectedVendor(null)
  }

  return (
    <Dialog open={open} onOpenChange={(newOpen) => {
      setOpen(newOpen)
      if (!newOpen) resetForm()
    }}>
      <DialogTrigger asChild>
        <Button size="sm">
          <Plus className="mr-2 h-4 w-4" />
          신규등록
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>새 계약 등록</DialogTitle>
          <DialogDescription>
            새로운 계약의 기본 정보를 입력하세요.
          </DialogDescription>
        </DialogHeader>
        
        <div className="grid gap-4 py-4">
          <div className="grid grid-cols-1 gap-4">
            <div className="grid gap-2">
              <Label htmlFor="name">계약명 *</Label>
              <Input
                id="name"
                value={form.name}
                onChange={(e) => setForm(prev => ({ ...prev, name: e.target.value }))}
                placeholder="계약명을 입력하세요"
              />
              {form.type === 'SC' && (
                <p className="text-sm text-blue-600 mt-1">
                  납품예정 품목 및 수량을 명기하세요. 납품 품목 또는 작업 내용은 구체적으로 작성하되, 수량(물량)이 정확하지 않을 경우, 상호협의하에 변경 가능하며, 수량(물량) 등은 개별계약(PO)시 명기하세요
                </p>
              )}
            </div>
          </div>

          <div className="grid grid-cols-3 gap-4">
            <div className="grid gap-2">
              <Label htmlFor="category">계약구분 *</Label>
              <Select value={form.category} onValueChange={(value) => setForm(prev => ({ ...prev, category: value }))}>
                <SelectTrigger>
                  <SelectValue placeholder="계약구분 선택" />
                </SelectTrigger>
                <SelectContent>
                  {GENERAL_CONTRACT_CATEGORIES.map((category) => {
                    const categoryLabels = {
                      'unit_price': '단가계약',
                      'general': '일반계약',
                      'sale': '매각계약'
                    }
                    return (
                    <SelectItem key={category} value={category}>
                      {category} - {categoryLabels[category as keyof typeof categoryLabels]}
                      </SelectItem>
                    )
                  })}
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="type">계약종류 *</Label>
              <Select value={form.type} onValueChange={(value) => setForm(prev => ({ ...prev, type: value }))}>
                <SelectTrigger>
                  <SelectValue placeholder="계약종류 선택" />
                </SelectTrigger>
                <SelectContent>
                  {GENERAL_CONTRACT_TYPES.map((type) => {
                    return (
                      <SelectItem key={type} value={type}>
                        {type} - {GENERAL_CONTRACT_TYPE_LABELS[type]}
                      </SelectItem>
                    )
                  })}
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="executionMethod">체결방식 *</Label>
              <Select value={form.executionMethod} onValueChange={(value) => setForm(prev => ({ ...prev, executionMethod: value }))}>
                <SelectTrigger>
                  <SelectValue placeholder="체결방식 선택" />
                </SelectTrigger>
                <SelectContent>
                  {GENERAL_EXECUTION_METHODS.map((method) => (
                    <SelectItem key={method} value={method}>
                      {method}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="grid gap-2">
            <Label htmlFor="vendor">협력업체 *</Label>
            <VendorSelectorDialogSingle
              triggerLabel="협력업체 선택"
              selectedVendor={selectedVendor}
              onVendorSelect={setSelectedVendor}
              placeholder="협력업체를 검색하세요..."
              title="협력업체 선택"
              description="계약할 협력업체를 검색하고 선택해주세요."
              triggerVariant="outline"
              statusFilter="ACTIVE"
              showInitialData={true}
            />
          </div>

          <div className="grid grid-cols-3 gap-4">
            <div className="grid gap-2">
              <Label htmlFor="startDate">
                계약시작일
                {!['AD', 'LO', 'OF'].includes(form.type) && <span className="text-red-600 ml-1">*</span>}
              </Label>
              <Input
                id="startDate"
                type="date"
                value={form.startDate}
                onChange={(e) => setForm(prev => ({ ...prev, startDate: e.target.value }))}
                min="1900-01-01"
                max="2100-12-31"
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="endDate">
                계약종료일
                {!['AD', 'LO', 'OF'].includes(form.type) && <span className="text-red-600 ml-1">*</span>}
              </Label>
              <Input
                id="endDate"
                type="date"
                value={form.endDate}
                onChange={(e) => setForm(prev => ({ ...prev, endDate: e.target.value }))}
                min="1900-01-01"
                max="2100-12-31"
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="validityEndDate">유효기간종료일</Label>
              <Input
                id="validityEndDate"
                type="date"
                value={form.validityEndDate}
                onChange={(e) => setForm(prev => ({ ...prev, validityEndDate: e.target.value }))}
                min="1900-01-01"
                max="2100-12-31"
              />
            </div>
          </div>
          <div className="grid gap-2">
            <Label htmlFor="notes">비고</Label>
            <Textarea
              id="notes"
              value={form.notes}
              onChange={(e) => setForm(prev => ({ ...prev, notes: e.target.value }))}
              placeholder="비고사항을 입력하세요"
              rows={3}
            />
          </div>
        </div>

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={() => setOpen(false)}
          >
            취소
          </Button>
          <Button
            type="button"
            onClick={handleSubmit}
            disabled={isLoading}
          >
            {isLoading ? '생성 중...' : '생성'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}