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
456
457
|
"use client"
import * as React from "react"
import { type Row } from "@tanstack/react-table"
import { Loader, SendHorizonal } from "lucide-react"
import { toast } from "sonner"
import { useMediaQuery } from "@/hooks/use-media-query"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Drawer,
DrawerClose,
DrawerContent,
DrawerDescription,
DrawerFooter,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
} from "@/components/ui/drawer"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { Vendor } from "@/db/schema/vendors"
import { requestBasicContractInfo, requestPQVendors } from "../service"
import { getProjectsWithPQList } from "@/lib/pq/service"
import type { Project } from "@/lib/pq/service"
import { useSession } from "next-auth/react"
import { DatePicker } from "@/components/ui/date-picker"
import { getALLBasicContractTemplates } from "@/lib/basic-contract/service"
import type { BasicContractTemplate } from "@/db/schema"
interface RequestPQDialogProps extends React.ComponentPropsWithoutRef<typeof Dialog> {
vendors: Row<Vendor>["original"][]
showTrigger?: boolean
onSuccess?: () => void
}
const AGREEMENT_LIST = [
"준법서약",
"표준하도급계약",
"안전보건관리계약",
"윤리규범 준수 서약",
"동반성장협약",
"내국신용장 미개설 합의",
"기술자료 제출 기본 동의",
"GTC 합의",
]
export function RequestPQDialog({ vendors, showTrigger = true, onSuccess, ...props }: RequestPQDialogProps) {
const [isApprovePending, startApproveTransition] = React.useTransition()
const isDesktop = useMediaQuery("(min-width: 640px)")
const { data: session } = useSession()
const [type, setType] = React.useState<"GENERAL" | "PROJECT" | "NON_INSPECTION" | null>(null)
const [dueDate, setDueDate] = React.useState<string | null>(null)
const [projects, setProjects] = React.useState<Project[]>([])
const [selectedProjectId, setSelectedProjectId] = React.useState<number | null>(null)
const [agreements, setAgreements] = React.useState<Record<string, boolean>>({})
const [extraNote, setExtraNote] = React.useState<string>("")
const [pqItems, setPqItems] = React.useState<string>("")
const [isLoadingProjects, setIsLoadingProjects] = React.useState(false)
const [basicContractTemplates, setBasicContractTemplates] = React.useState<BasicContractTemplate[]>([])
const [selectedTemplateIds, setSelectedTemplateIds] = React.useState<number[]>([])
const [isLoadingTemplates, setIsLoadingTemplates] = React.useState(false)
React.useEffect(() => {
if (type === "PROJECT") {
setIsLoadingProjects(true)
getProjectsWithPQList().then(setProjects).catch(() => toast.error("프로젝트 로딩 실패"))
.finally(() => setIsLoadingProjects(false))
}
}, [type])
// 기본계약서 템플릿 로딩
React.useEffect(() => {
setIsLoadingTemplates(true)
getALLBasicContractTemplates()
.then(setBasicContractTemplates)
.catch(() => toast.error("기본계약서 템플릿 로딩 실패"))
.finally(() => setIsLoadingTemplates(false))
}, [])
React.useEffect(() => {
if (!props.open) {
setType(null)
setSelectedProjectId(null)
setAgreements({})
setDueDate(null)
setPqItems("")
setExtraNote("")
setSelectedTemplateIds([])
}
}, [props.open])
const onApprove = () => {
if (!type) return toast.error("PQ 유형을 선택하세요.")
if (type === "PROJECT" && !selectedProjectId) return toast.error("프로젝트를 선택하세요.")
if (!dueDate) return toast.error("마감일을 선택하세요.")
if (!session?.user?.id) return toast.error("인증 실패")
startApproveTransition(async () => {
try {
// 1단계: PQ 생성
console.log("🚀 1단계: PQ 생성 시작")
const { error: pqError } = await requestPQVendors({
ids: vendors.map((v) => v.id),
userId: Number(session.user.id),
agreements,
dueDate,
projectId: type === "PROJECT" ? selectedProjectId : null,
type: type || "GENERAL",
extraNote,
pqItems,
templateId: selectedTemplateIds.length > 0 ? selectedTemplateIds[0] : null,
})
if (pqError) {
toast.error(`PQ 생성 실패: ${pqError}`)
return
}
console.log("✅ 1단계: PQ 생성 완료")
// 2단계 & 3단계: 기본계약서 템플릿이 선택된 경우에만 실행 (여러 템플릿 처리)
if (selectedTemplateIds.length > 0) {
console.log(`🚀 2단계 & 3단계: ${selectedTemplateIds.length}개 템플릿 처리 시작`)
let successCount = 0
let errorCount = 0
const errors: string[] = []
// 템플릿별로 반복 처리
for (let i = 0; i < selectedTemplateIds.length; i++) {
const templateId = selectedTemplateIds[i]
const selectedTemplate = basicContractTemplates.find(t => t.id === templateId)
if (!selectedTemplate) {
console.error(`템플릿 ID ${templateId}를 찾을 수 없습니다`)
errorCount++
errors.push(`템플릿 ID ${templateId}를 찾을 수 없습니다`)
continue
}
try {
console.log(`📄 [${i+1}/${selectedTemplateIds.length}] ${selectedTemplate.templateName} - 2단계: DOCX to PDF 변환 시작`)
// 템플릿 파일을 가져와서 PDF로 변환
const formData = new FormData()
// 템플릿 파일 가져오기 (서버에서 파일 읽기)
const templateResponse = await fetch('/api/basic-contract/get-template', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ templateId })
})
if (!templateResponse.ok) {
throw new Error(`템플릿 파일을 가져올 수 없습니다: ${selectedTemplate.templateName}`)
}
console.log(`✅ [${i+1}/${selectedTemplateIds.length}] ${selectedTemplate.templateName} - 템플릿 파일 가져오기 완료`)
const templateBlob = await templateResponse.blob()
const templateFile = new File([templateBlob], selectedTemplate.fileName || 'template.docx')
// 템플릿 데이터 생성 (첫 번째 협력업체 정보 기반)
const firstVendor = vendors[0]
const templateData = {
// 영문 변수명으로 변경 (PDFTron이 한글 변수명을 지원하지 않음)
vendor_name: firstVendor?.vendorName || '협력업체명',
address: firstVendor?.address || '주소',
representative_name: firstVendor?.representativeName || '대표자명',
today_date: new Date().toLocaleDateString('ko-KR'),
}
console.log(`📝 [${i+1}/${selectedTemplateIds.length}] ${selectedTemplate.templateName} - 생성된 템플릿 데이터:`, templateData)
formData.append('templateFile', templateFile)
formData.append('outputFileName', `${selectedTemplate.templateName}_converted.pdf`)
formData.append('templateData', JSON.stringify(templateData))
// PDF 변환 호출
const pdfResponse = await fetch('/api/pdftron/createBasicContractPdf', {
method: 'POST',
body: formData,
})
console.log(`✅ [${i+1}/${selectedTemplateIds.length}] ${selectedTemplate.templateName} - PDF 변환 호출 완료`)
if (!pdfResponse.ok) {
const errorText = await pdfResponse.text()
throw new Error(`PDF 변환 실패 (${selectedTemplate.templateName}): ${errorText}`)
}
const pdfBuffer = await pdfResponse.arrayBuffer()
console.log(`✅ [${i+1}/${selectedTemplateIds.length}] ${selectedTemplate.templateName} - PDF 변환 완료`)
// 3단계: 변환된 PDF로 기본계약 생성
console.log(`📋 [${i+1}/${selectedTemplateIds.length}] ${selectedTemplate.templateName} - 3단계: 기본계약 생성 시작`)
const { error: contractError } = await requestBasicContractInfo({
vendorIds: vendors.map((v) => v.id),
requestedBy: Number(session.user.id),
templateId,
pdfBuffer: new Uint8Array(pdfBuffer), // ArrayBuffer를 Uint8Array로 변환하여 전달
})
if (contractError) {
console.error(`기본계약 생성 오류 (${selectedTemplate.templateName}):`, contractError)
errorCount++
errors.push(`${selectedTemplate.templateName}: ${contractError}`)
} else {
console.log(`✅ [${i+1}/${selectedTemplateIds.length}] ${selectedTemplate.templateName} - 3단계: 기본계약 생성 완료`)
successCount++
}
} catch (templateError) {
console.error(`템플릿 처리 오류 (${selectedTemplate.templateName}):`, templateError)
errorCount++
errors.push(`${selectedTemplate.templateName}: ${templateError instanceof Error ? templateError.message : '알 수 없는 오류'}`)
}
}
// 결과 토스트 메시지
if (successCount > 0 && errorCount === 0) {
toast.success(`PQ 요청 및 ${successCount}개 기본계약서 생성이 모두 완료되었습니다!`)
} else if (successCount > 0 && errorCount > 0) {
toast.success(`PQ는 성공적으로 요청되었습니다. ${successCount}개 기본계약서 성공, ${errorCount}개 실패`)
console.error('기본계약서 생성 오류들:', errors)
} else if (errorCount > 0) {
toast.error(`PQ는 성공적으로 요청되었지만, 모든 기본계약서 생성이 실패했습니다`)
console.error('기본계약서 생성 오류들:', errors)
}
} else {
// 기본계약서 템플릿이 선택되지 않은 경우
toast.success("PQ가 성공적으로 요청되었습니다")
}
props.onOpenChange?.(false)
onSuccess?.()
} catch (error) {
console.error('전체 프로세스 오류:', error)
toast.error(`처리 중 오류가 발생했습니다: ${error instanceof Error ? error.message : '알 수 없는 오류'}`)
}
})
}
const dialogContent = (
<div className="space-y-4 py-2">
{/* 선택된 협력업체 정보 */}
<div className="space-y-2">
<Label>선택된 협력업체 ({vendors.length}개)</Label>
<div className="max-h-40 overflow-y-auto border rounded-md p-3 space-y-2">
{vendors.map((vendor) => (
<div key={vendor.id} className="flex items-center justify-between text-sm">
<div className="flex-1">
<div className="font-medium">{vendor.vendorName}</div>
<div className="text-muted-foreground">
{vendor.vendorCode} • {vendor.email || "이메일 없음"}
</div>
</div>
</div>
))}
</div>
</div>
<div className="space-y-2">
<Label htmlFor="type">PQ 종류 선택</Label>
<Select onValueChange={(val: "GENERAL" | "PROJECT" | "NON_INSPECTION") => setType(val)} value={type ?? undefined}>
<SelectTrigger id="type"><SelectValue placeholder="PQ 종류를 선택하세요" /></SelectTrigger>
<SelectContent>
<SelectItem value="GENERAL">일반 PQ</SelectItem>
<SelectItem value="PROJECT">프로젝트 PQ</SelectItem>
<SelectItem value="NON_INSPECTION">미실사 PQ</SelectItem>
</SelectContent>
</Select>
</div>
{type === "PROJECT" && (
<div className="space-y-2">
<Label htmlFor="project">프로젝트 선택</Label>
<Select onValueChange={(val) => setSelectedProjectId(Number(val))}>
<SelectTrigger id="project">
<SelectValue placeholder="프로젝트 선택" />
</SelectTrigger>
<SelectContent>
{isLoadingProjects ? (
<SelectItem value="loading" disabled>로딩 중...</SelectItem>
) : projects.map((p) => (
<SelectItem key={p.id} value={p.id.toString()}>{p.projectCode} - {p.projectName}</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{/* 마감일 입력 */}
<div className="space-y-2">
<Label htmlFor="dueDate">PQ 제출 마감일</Label>
<DatePicker
date={dueDate ? new Date(dueDate) : undefined}
onSelect={(date?: Date) => setDueDate(date ? date.toISOString().slice(0, 10) : "")}
placeholder="마감일 선택"
/>
</div>
{/* PQ 대상품목 */}
<div className="space-y-2">
<Label htmlFor="pqItems">PQ 대상품목</Label>
<textarea
id="pqItems"
value={pqItems}
onChange={(e) => setPqItems(e.target.value)}
placeholder="PQ 대상품목을 입력하세요 (선택사항)"
className="w-full rounded-md border px-3 py-2 text-sm min-h-20 resize-none"
/>
</div>
{/* 추가 안내사항 */}
<div className="space-y-2">
<Label htmlFor="extraNote">추가 안내사항</Label>
<textarea
id="extraNote"
value={extraNote}
onChange={(e) => setExtraNote(e.target.value)}
placeholder="추가 안내사항을 입력하세요 (선택사항)"
className="w-full rounded-md border px-3 py-2 text-sm min-h-20 resize-none"
/>
</div>
{/* 기본계약서 템플릿 선택 (다중 선택) */}
<div className="space-y-2">
<Label>기본계약서 템플릿 (선택사항, 복수 선택 가능)</Label>
{isLoadingTemplates ? (
<div className="text-sm text-muted-foreground">템플릿 로딩 중...</div>
) : (
<div className="space-y-2 max-h-40 overflow-y-auto border rounded-md p-3">
{basicContractTemplates.map((template) => (
<div key={template.id} className="flex items-center gap-2">
<Checkbox
id={`template-${template.id}`}
checked={selectedTemplateIds.includes(template.id)}
onCheckedChange={(checked) => {
if (checked) {
setSelectedTemplateIds(prev => [...prev, template.id])
} else {
setSelectedTemplateIds(prev => prev.filter(id => id !== template.id))
}
}}
/>
<Label htmlFor={`template-${template.id}`} className="text-sm">
{template.templateName}
</Label>
</div>
))}
{basicContractTemplates.length === 0 && (
<div className="text-sm text-muted-foreground">사용 가능한 템플릿이 없습니다.</div>
)}
</div>
)}
{selectedTemplateIds.length > 0 && (
<div className="text-xs text-muted-foreground">
{selectedTemplateIds.length}개 템플릿이 선택되었습니다.
</div>
)}
</div>
{/* <div className="space-y-2">
<Label>계약 항목 선택</Label>
{AGREEMENT_LIST.map((label) => (
<div key={label} className="flex items-center gap-2">
<Checkbox
id={label}
checked={agreements[label] || false}
onCheckedChange={(val) =>
setAgreements((prev) => ({ ...prev, [label]: Boolean(val) }))
}
/>
<Label htmlFor={label}>{label}</Label>
</div>
))}
</div> */}
</div>
)
if (isDesktop) {
return (
<Dialog {...props}>
{showTrigger && (
<DialogTrigger asChild>
<Button variant="outline" size="sm" className="gap-2">
<SendHorizonal className="size-4" /> PQ 요청 ({vendors.length})
</Button>
</DialogTrigger>
)}
<DialogContent className="max-h-[80vh] flex flex-col">
<DialogHeader>
<DialogTitle>PQ 요청</DialogTitle>
<DialogDescription>
<span className="font-medium">{vendors.length}</span>
{vendors.length === 1 ? "개 협력업체" : "개 협력업체들"}에게 PQ를 요청합니다.
</DialogDescription>
</DialogHeader>
<div className="flex-1 overflow-y-auto">
{dialogContent}
</div>
<DialogFooter>
<DialogClose asChild><Button variant="outline">취소</Button></DialogClose>
<Button onClick={onApprove} disabled={isApprovePending || !type || (type === "PROJECT" && !selectedProjectId)}>
{isApprovePending && <Loader className="mr-2 size-4 animate-spin" />}요청하기
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
return (
<Drawer {...props}>
{showTrigger && (
<DrawerTrigger asChild>
<Button variant="outline" size="sm" className="gap-2">
<SendHorizonal className="size-4" /> PQ 요청 ({vendors.length})
</Button>
</DrawerTrigger>
)}
<DrawerContent className="max-h-[80vh] flex flex-col">
<DrawerHeader>
<DrawerTitle>PQ 요청</DrawerTitle>
<DrawerDescription>
<span className="font-medium">{vendors.length}</span>
{vendors.length === 1 ? "개 협력업체" : "개 협력업체들"}에게 PQ를 요청합니다.
</DrawerDescription>
</DrawerHeader>
<div className="flex-1 overflow-y-auto px-4">
{dialogContent}
</div>
<DrawerFooter>
<DrawerClose asChild><Button variant="outline">취소</Button></DrawerClose>
<Button onClick={onApprove} disabled={isApprovePending || !type || (type === "PROJECT" && !selectedProjectId)}>
{isApprovePending && <Loader className="mr-2 size-4 animate-spin" />}요청하기
</Button>
</DrawerFooter>
</DrawerContent>
</Drawer>
)
}
|