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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
|
"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 { Calendar } from "@/components/ui/calendar"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { CalendarIcon, Check, ChevronsUpDown } from "lucide-react"
import { Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem } from "@/components/ui/command"
import { format } from "date-fns"
import { ko } from "date-fns/locale"
import { cn } from "@/lib/utils"
import { createContract, getVendors } from "@/lib/general-contracts/service"
import {
GENERAL_CONTRACT_CATEGORIES,
GENERAL_CONTRACT_TYPES,
GENERAL_EXECUTION_METHODS
} from "@/lib/general-contracts/types"
import { useSession } from "next-auth/react"
interface CreateContractForm {
contractNumber: string
name: string
category: string
type: string
executionMethod: string
vendorId: number | null
startDate: Date | undefined
endDate: Date | undefined
validityEndDate: Date | undefined
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 [vendors, setVendors] = React.useState<Array<{ id: number; vendorName: string; vendorCode: string | null }>>([])
const [vendorSearchTerm, setVendorSearchTerm] = React.useState("")
const [vendorOpen, setVendorOpen] = React.useState(false)
const [form, setForm] = React.useState<CreateContractForm>({
contractNumber: '',
name: '',
category: '',
type: '',
executionMethod: '',
vendorId: null,
startDate: undefined,
endDate: undefined,
validityEndDate: undefined,
notes: '',
})
// 업체 목록 조회
React.useEffect(() => {
const fetchData = async () => {
try {
const vendorList = await getVendors()
console.log('vendorList', vendorList)
setVendors(vendorList)
} catch (error) {
console.error('데이터 조회 오류:', error)
toast.error('데이터를 불러오는데 실패했습니다')
setVendors([])
}
}
fetchData()
}, [])
// 협력업체 검색 필터링
const filteredVendors = React.useMemo(() => {
if (!vendorSearchTerm.trim()) return vendors
const lowerSearch = vendorSearchTerm.toLowerCase()
return vendors.filter(
vendor =>
vendor.vendorName.toLowerCase().includes(lowerSearch) ||
(vendor.vendorCode && vendor.vendorCode.toLowerCase().includes(lowerSearch))
)
}, [vendors, vendorSearchTerm])
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 (!form.vendorId) 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: form.vendorId!,
startDate: form.startDate!.toISOString().split('T')[0],
endDate: form.endDate!.toISOString().split('T')[0],
validityEndDate: (form.validityEndDate || form.endDate!).toISOString().split('T')[0],
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: '',
vendorId: null,
startDate: undefined,
endDate: undefined,
validityEndDate: undefined,
notes: '',
})
}
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="계약명을 입력하세요"
/>
</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) => {
const typeLabels = {
'UP': '자재단가계약',
'LE': '임대차계약',
'IL': '개별운송계약',
'AL': '연간운송계약',
'OS': '외주용역계약',
'OW': '도급계약',
'LO': 'LOI',
'FA': 'FA',
'SC': '납품합의계약',
'OF': '클레임상계계약',
'AW': '사전작업합의',
'AD': '사전납품합의',
'SG': '임치(물품보관)계약',
'SR': '폐기물매각계약'
}
return (
<SelectItem key={type} value={type}>
{type} - {typeLabels[type as keyof typeof typeLabels]}
</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>
<Popover open={vendorOpen} onOpenChange={setVendorOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={vendorOpen}
className="w-full justify-between"
>
{form.vendorId ? (
(() => {
const selected = vendors.find(v => v.id === form.vendorId)
return selected ? `${selected.vendorName} (${selected.vendorCode || ''})` : "협력업체 선택"
})()
) : (
"협력업체 선택"
)}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[400px] p-0">
<Command>
<CommandInput
placeholder="협력업체명/코드 검색..."
onValueChange={setVendorSearchTerm}
/>
<CommandList className="max-h-[300px]">
<CommandEmpty>검색 결과가 없습니다</CommandEmpty>
<CommandGroup>
{filteredVendors.map((vendor) => (
<CommandItem
key={vendor.id}
value={`${vendor.vendorName} ${vendor.vendorCode || ''}`}
onSelect={() => {
setForm(prev => ({ ...prev, vendorId: vendor.id }))
setVendorOpen(false)
setVendorSearchTerm("")
}}
>
<Check
className={cn(
"mr-2 h-4 w-4",
form.vendorId === vendor.id ? "opacity-100" : "opacity-0"
)}
/>
<span className="font-medium">{vendor.vendorName}</span>
{vendor.vendorCode && (
<span className="ml-2 text-gray-500">({vendor.vendorCode})</span>
)}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
<div className="grid grid-cols-3 gap-4">
<div className="grid gap-2">
<Label>계약시작일 *</Label>
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
className={cn(
"justify-start text-left font-normal",
!form.startDate && "text-muted-foreground"
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{form.startDate ? format(form.startDate, "yyyy-MM-dd", { locale: ko }) : "날짜 선택"}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<Calendar
mode="single"
selected={form.startDate}
onSelect={(date) => setForm(prev => ({ ...prev, startDate: date }))}
initialFocus
/>
</PopoverContent>
</Popover>
</div>
<div className="grid gap-2">
<Label>계약종료일 *</Label>
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
className={cn(
"justify-start text-left font-normal",
!form.endDate && "text-muted-foreground"
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{form.endDate ? format(form.endDate, "yyyy-MM-dd", { locale: ko }) : "날짜 선택"}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<Calendar
mode="single"
selected={form.endDate}
onSelect={(date) => setForm(prev => ({ ...prev, endDate: date }))}
initialFocus
/>
</PopoverContent>
</Popover>
</div>
<div className="grid gap-2">
<Label>유효기간종료일</Label>
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
className={cn(
"justify-start text-left font-normal",
!form.validityEndDate && "text-muted-foreground"
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{form.validityEndDate ? format(form.validityEndDate, "yyyy-MM-dd", { locale: ko }) : "날짜 선택"}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<Calendar
mode="single"
selected={form.validityEndDate}
onSelect={(date) => setForm(prev => ({ ...prev, validityEndDate: date }))}
initialFocus
/>
</PopoverContent>
</Popover>
</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>
)
}
|