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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
|
"use client";
import * as React from "react";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { Save, RefreshCw, Type, FileText, AlertCircle } from "lucide-react";
import type { WebViewerInstance } from "@pdftron/webviewer";
import { Badge } from "@/components/ui/badge";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { BasicContractTemplateViewer } from "./basic-contract-template-viewer";
import { getExistingTemplateNamesById, saveTemplateFile } from "../service";
interface TemplateEditorWrapperProps {
templateId: string | number;
filePath: string;
fileName: string;
refreshAction?: () => Promise<void>;
}
const getVariablesForTemplate = (templateName: string): string[] => {
let variables: string[] = [];
// 정확한 매치 먼저 확인
if (TEMPLATE_VARIABLES_MAP[templateName as keyof typeof TEMPLATE_VARIABLES_MAP]) {
variables = [...TEMPLATE_VARIABLES_MAP[templateName as keyof typeof TEMPLATE_VARIABLES_MAP]];
} else if (templateName.includes("GTC")) {
// GTC가 포함된 경우 확인
variables = [...TEMPLATE_VARIABLES_MAP["GTC"]];
} else {
// 다른 키워드들도 포함 관계로 확인
let found = false;
for (const [key, vars] of Object.entries(TEMPLATE_VARIABLES_MAP)) {
if (templateName.includes(key)) {
variables = [...vars];
found = true;
break;
}
}
// 기본값 반환
if (!found) {
variables = ["company_name", "company_address", "representative_name", "signature_date"];
}
}
// 모든 템플릿에 서명란 텍스트 추가 (자동 서명 기능을 위해 실제 텍스트 사용)
const signatureTexts = ["협력업체_서명란", "삼성중공업_서명란"];
const allVariables = [...variables, ...signatureTexts];
return [...new Set(allVariables)]; // 중복 제거
};
// 템플릿 이름별 변수 매핑
const TEMPLATE_VARIABLES_MAP = {
"준법서약 (한글)": ["company_name", "company_address", "representative_name", "signature_date"],
"준법서약 (영문)": ["company_name", "company_address", "representative_name", "signature_date"],
"기술자료 요구서": ["company_name", "company_address", "representative_name", "signature_date", 'tax_id', 'phone_number'],
"비밀유지 계약서": ["company_name", "company_address", "representative_name", "signature_date"],
"표준하도급기본 계약서": ["company_name", "company_address", "representative_name", "signature_date"],
"GTC": ["company_name", "company_address", "representative_name", "signature_date"],
"안전보건관리 약정서": ["company_name", "company_address", "representative_name", "signature_date"],
"동반성장": ["company_name", "company_address", "representative_name", "signature_date"],
"윤리규범 준수 서약서": ["company_name", "company_address", "representative_name", "signature_date"],
"기술자료 동의서": ["company_name", "company_address", "representative_name", "signature_date", 'tax_id', 'phone_number'],
"내국신용장 미개설 합의서": ["company_name", "company_address", "representative_name", "signature_date"],
"직납자재 하도급대급등 연동제 의향서": ["company_name", "company_address", "representative_name", "signature_date"]
} as const;
// 변수별 한글 설명 매핑
const VARIABLE_DESCRIPTION_MAP = {
"company_name": "협력회사명",
"vendor_name": "협력회사명",
"company_address": "회사주소",
"address": "회사주소",
"representative_name": "대표자명",
"signature_date": "서명날짜",
"today_date": "오늘날짜",
"tax_id": "사업자등록번호",
"phone_number": "전화번호",
"phone": "전화번호",
"email": "이메일",
"협력업체_서명란": "협력업체 서명란",
"삼성중공업_서명란": "구매자 서명란"
} as const;
// 서명란 텍스트는 그대로 사용 (자동 서명 기능이 정확한 텍스트를 찾아야 함)
// 변환하지 않고 원본 텍스트를 그대로 반환
// 변수 패턴 감지를 위한 정규식
const VARIABLE_PATTERN = /\{\{([^}]+)\}\}/g;
export function TemplateEditorWrapper({
templateId,
filePath,
fileName,
refreshAction
}: TemplateEditorWrapperProps) {
const [instance, setInstance] = React.useState<WebViewerInstance | null>(null);
const [isSaving, setIsSaving] = React.useState(false);
const [documentVariables, setDocumentVariables] = React.useState<string[]>([]);
const [templateName, setTemplateName] = React.useState<string>("");
const [predefinedVariables, setPredefinedVariables] = React.useState<string[]>([]);
const [signatureVariables, setSignatureVariables] = React.useState<string[]>([]); // 서명란 변수
const [fileLoadError, setFileLoadError] = React.useState<Error | null>(null); // 파일 로드 오류
// 템플릿 이름 로드 및 변수 설정
React.useEffect(() => {
const loadTemplateInfo = async () => {
try {
const name = await getExistingTemplateNamesById(Number(templateId));
setTemplateName(name);
// 템플릿 이름에 따른 변수 설정
const variables = getVariablesForTemplate(name);
setPredefinedVariables([...variables]);
console.log("🏷️ 템플릿 이름:", name);
console.log("📝 할당된 변수들:", variables);
} catch (error) {
console.error("템플릿 정보 로드 오류:", error);
// 기본 변수 설정
setPredefinedVariables(["company_name", "company_address", "representative_name", "signature_date"]);
}
};
if (templateId) {
loadTemplateInfo();
}
}, [templateId]);
// 문서에서 변수 추출
const extractVariablesFromDocument = async () => {
if (!instance) return;
try {
const { documentViewer } = instance.Core;
const doc = documentViewer.getDocument();
if (!doc) return;
// 문서 텍스트 추출
const textContent = await doc.getDocumentCompletePromise().then(async () => {
const pageCount = doc.getPageCount();
let fullText = "";
for (let i = 1; i <= pageCount; i++) {
try {
const pageText = await doc.loadPageText(i);
fullText += pageText + " ";
} catch (error) {
console.warn(`페이지 ${i} 텍스트 추출 실패:`, error);
}
}
return fullText;
});
// 변수 패턴 매칭
const matches = textContent.match(VARIABLE_PATTERN);
const variables = matches
? [...new Set(matches.map(match => match.replace(/[{}]/g, '')))]
: [];
setDocumentVariables(variables);
if (variables.length > 0) {
console.log("🔍 발견된 변수들:", variables);
}
} catch (error) {
console.error("변수 추출 중 오류:", error);
}
};
// 인스턴스가 변경될 때마다 변수 추출
React.useEffect(() => {
if (instance) {
// 문서 로드 완료 이벤트 리스너 추가
const { documentViewer } = instance.Core;
const onDocumentLoaded = () => {
setTimeout(() => extractVariablesFromDocument(), 1000);
};
documentViewer.addEventListener("documentLoaded", onDocumentLoaded);
return () => {
documentViewer.removeEventListener("documentLoaded", onDocumentLoaded);
};
}
}, [instance]);
// 변수 삽입 함수 (한글 입력 제한 고려)
const insertVariable = async (variableName: string) => {
if (!instance) {
toast.error("뷰어가 준비되지 않았습니다.");
return;
}
try {
// 서명란 텍스트는 {{}} 없이 그대로 사용
const isSignatureText = variableName === '협력업체_서명란' || variableName === '삼성중공업_서명란';
const textToInsert = isSignatureText ? variableName : `{{${variableName}}}`;
// 1단계: 클립보드 API 시도
if (navigator.clipboard && navigator.clipboard.writeText) {
try {
await navigator.clipboard.writeText(textToInsert);
toast.success(`변수 "${textToInsert}"가 클립보드에 복사되었습니다.`, {
description: "문서에서 원하는 위치에 Ctrl+V로 붙여넣기 하세요."
});
return;
} catch (clipboardError) {
console.warn("클립보드 API 사용 실패:", clipboardError);
}
}
// 2단계: Office 편집기에 직접 삽입 시도 (실험적)
try {
const { documentViewer } = instance.Core;
const doc = documentViewer.getDocument();
if (doc && typeof doc.getOfficeEditor === 'function') {
const officeEditor = doc.getOfficeEditor();
if (officeEditor && typeof officeEditor.insertText === 'function') {
await officeEditor.insertText(textToInsert);
toast.success(`변수 "${textToInsert}"가 문서에 삽입되었습니다.`);
return;
}
}
} catch (insertError) {
console.warn("직접 삽입 실패:", insertError);
}
// 3단계: 임시 텍스트 영역을 통한 복사 (대안)
try {
const tempTextArea = document.createElement('textarea');
tempTextArea.value = textToInsert;
tempTextArea.style.position = 'fixed';
tempTextArea.style.left = '-9999px';
document.body.appendChild(tempTextArea);
tempTextArea.select();
document.execCommand('copy');
document.body.removeChild(tempTextArea);
toast.success(`변수 "${textToInsert}"가 클립보드에 복사되었습니다.`, {
description: "Office 편집기에서 한글 입력이 제한될 수 있습니다. 외부에서 작성 후 붙여넣기를 권장합니다."
});
return;
} catch (fallbackError) {
console.warn("대안 복사 실패:", fallbackError);
}
// 4단계: 수동 입력 안내
toast.info(`다음 변수를 수동으로 입력해주세요: ${textToInsert}`, {
description: "한글과 변수는 외부 에디터에서 작성 후 복사-붙여넣기를 권장합니다.",
duration: 8000,
});
} catch (error) {
console.error("변수 삽입 오류:", error);
toast.error("변수 삽입 중 오류가 발생했습니다.");
}
};
// 문서 저장
const handleSave = async () => {
if (!instance) {
toast.error("뷰어가 준비되지 않았습니다.");
return;
}
setIsSaving(true);
try {
const { documentViewer } = instance.Core;
const doc = documentViewer.getDocument();
if (!doc) {
throw new Error("문서를 찾을 수 없습니다.");
}
// Word 문서 저장
const data = await doc.getFileData({
downloadType: "office", // Word 파일로 저장
includeAnnotations: true
});
// FormData 생성하여 서버 액션에 전달
const formData = new FormData();
formData.append('file', new Blob([data], {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
}), fileName);
// 서버 액션 호출
const result = await saveTemplateFile(Number(templateId), formData);
if (result.error) {
throw new Error(result.error);
}
toast.success("템플릿이 성공적으로 저장되었습니다.");
// 변수 재추출
await extractVariablesFromDocument();
// 페이지 새로고침 (서버 액션)
if (refreshAction) {
await refreshAction();
}
} catch (error) {
console.error("저장 오류:", error);
toast.error(error instanceof Error ? error.message : "저장 중 오류가 발생했습니다.");
} finally {
setIsSaving(false);
}
};
// 문서 새로고침
const handleRefresh = () => {
window.location.reload();
};
return (
<div className="h-full flex flex-col">
{/* 상단 도구 모음 */}
<div className="border-b bg-gray-50 p-3">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-2">
<Button
variant="outline"
size="sm"
onClick={handleSave}
disabled={isSaving || !instance}
>
{isSaving ? (
<>
<RefreshCw className="mr-2 h-4 w-4 animate-spin" />
저장 중...
</>
) : (
<>
<Save className="mr-2 h-4 w-4" />
저장
</>
)}
</Button>
<Button
variant="outline"
size="sm"
onClick={handleRefresh}
>
<RefreshCw className="mr-2 h-4 w-4" />
새로고침
</Button>
</div>
<div className="flex items-center space-x-2">
<Badge variant="outline">
<FileText className="mr-1 h-3 w-3" />
{fileName}
</Badge>
{templateName && (
<Badge variant="secondary">
<Type className="mr-1 h-3 w-3" />
{templateName}
</Badge>
)}
{documentVariables.length > 0 && (
<Badge variant="secondary">
<Type className="mr-1 h-3 w-3" />
변수 {documentVariables.length}개
</Badge>
)}
</div>
</div>
{/* 변수 도구 */}
{(documentVariables.length > 0 || predefinedVariables.length > 0 || signatureVariables.length > 0) && (
<div className="mt-3 p-3 bg-white rounded border">
<div className="mb-2">
<h4 className="text-sm font-medium flex items-center">
<Type className="mr-2 h-4 w-4 text-blue-500" />
변수 관리
{templateName && (
<span className="ml-2 text-xs text-muted-foreground">
({templateName})
</span>
)}
</h4>
</div>
<div className="space-y-3">
{/* 발견된 변수들 */}
{documentVariables.length > 0 && (
<div>
<p className="text-xs text-muted-foreground mb-2">문서에서 발견된 변수:</p>
<div className="flex flex-wrap gap-1">
{documentVariables.map((variable, index) => (
<Badge key={index} variant="outline" className="text-xs">
{`{{${variable}}}`}
</Badge>
))}
</div>
</div>
)}
{/* 서명란 변수 */}
{signatureVariables.length > 0 && (
<div>
<p className="text-xs text-muted-foreground mb-2">
서명란 텍스트 (클릭하여 복사):
</p>
<TooltipProvider>
<div className="flex flex-wrap gap-1">
{signatureVariables.map((variable, index) => (
<Tooltip key={`signature-${variable}-${index}`}>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-6 px-2 text-xs hover:bg-green-50 border border-green-200"
onClick={async () => {
// 서명란 텍스트는 {{}} 없이 그대로 복사
const textToInsert = variable;
// 클립보드에 복사
if (navigator.clipboard && navigator.clipboard.writeText) {
try {
await navigator.clipboard.writeText(textToInsert);
toast.success(`"${textToInsert}"가 클립보드에 복사되었습니다.`, {
description: "문서에서 원하는 위치에 Ctrl+V로 붙여넣기 하세요."
});
} catch (clipboardError) {
console.warn("클립보드 API 사용 실패:", clipboardError);
// 대안 방법
const tempTextArea = document.createElement('textarea');
tempTextArea.value = textToInsert;
tempTextArea.style.position = 'fixed';
tempTextArea.style.left = '-9999px';
document.body.appendChild(tempTextArea);
tempTextArea.select();
document.execCommand('copy');
document.body.removeChild(tempTextArea);
toast.success(`"${textToInsert}"가 클립보드에 복사되었습니다.`);
}
}
}}
>
{variable}
</Button>
</TooltipTrigger>
<TooltipContent>
<p>{VARIABLE_DESCRIPTION_MAP[variable as keyof typeof VARIABLE_DESCRIPTION_MAP] || variable}</p>
</TooltipContent>
</Tooltip>
))}
</div>
</TooltipProvider>
</div>
)}
{/* 템플릿별 미리 정의된 변수들 */}
{predefinedVariables.length > 0 && (
<div>
<p className="text-xs text-muted-foreground mb-2">
{templateName ? `${templateName}에 권장되는 변수` : "자주 사용하는 변수"} (클릭하여 복사):
</p>
<TooltipProvider>
<div className="flex flex-wrap gap-1">
{predefinedVariables.map((variable, index) => {
// 서명란 텍스트는 {{}} 없이 표시
const isSignatureText = variable === '협력업체_서명란' || variable === '삼성중공업_서명란';
const displayText = isSignatureText ? variable : `{{${variable}}}`;
return (
<Tooltip key={index}>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="sm"
className={`h-6 px-2 text-xs ${isSignatureText ? 'hover:bg-green-50 border border-green-200' : 'hover:bg-blue-50'}`}
onClick={() => insertVariable(variable)}
>
{displayText}
</Button>
</TooltipTrigger>
<TooltipContent>
<p>{VARIABLE_DESCRIPTION_MAP[variable as keyof typeof VARIABLE_DESCRIPTION_MAP] || variable}</p>
</TooltipContent>
</Tooltip>
);
})}
</div>
</TooltipProvider>
</div>
)}
</div>
</div>
)}
</div>
{/* 뷰어 영역 (확대 문제 해결을 위한 컨테이너 격리) */}
<div className="flex-1 relative overflow-hidden">
{fileLoadError ? (
<div className="absolute inset-0 flex flex-col items-center justify-center bg-gray-50 p-8">
<div className="max-w-md text-center space-y-4">
<AlertCircle className="h-16 w-16 text-red-500 mx-auto" />
<div>
<h3 className="text-lg font-semibold text-gray-900">파일을 불러올 수 없습니다</h3>
<p className="text-sm text-gray-600 mt-2">
{fileLoadError.message}
</p>
</div>
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 text-left">
<p className="text-sm text-yellow-800">
<strong>가능한 원인:</strong>
</p>
<ul className="text-sm text-yellow-700 mt-2 space-y-1 list-disc list-inside">
<li>템플릿이 폐기되어 파일이 삭제되었습니다</li>
<li>템플릿이 DB에서 삭제되었습니다</li>
<li>파일 경로가 변경되었거나 손상되었습니다</li>
</ul>
</div>
<div className="flex gap-2 justify-center">
<Button
variant="outline"
onClick={() => window.history.back()}
>
목록으로 돌아가기
</Button>
<Button
onClick={() => {
setFileLoadError(null);
window.location.reload();
}}
>
새로고침
</Button>
</div>
</div>
</div>
) : (
<div className="absolute inset-0">
<BasicContractTemplateViewer
templateId={templateId}
filePath={filePath}
instance={instance}
setInstance={setInstance}
onSignatureFieldFound={(searchText) => {
// 서명란 발견 시 원본 텍스트를 그대로 추가 (자동 서명 기능을 위해)
setSignatureVariables(prev => {
if (!prev.includes(searchText)) {
return [...prev, searchText];
}
return prev;
});
}}
onLoadError={(error) => {
setFileLoadError(error);
}}
/>
</div>
)}
</div>
{/* 하단 안내 (한글 입력 팁 포함) */}
<div className="border-t bg-gray-50 p-2">
<div className="flex items-center justify-between text-xs text-muted-foreground">
<div className="flex items-center">
<AlertCircle className="inline h-3 w-3 mr-1" />
{'{{변수명}}'} 형식으로 변수를 삽입하면 계약서 생성 시 실제 값으로 치환됩니다.
</div>
<div className="flex items-center text-orange-600">
<AlertCircle className="inline h-3 w-3 mr-1" />
한글 입력 제한시 외부 에디터에서 작성 후 복사-붙여넣기를 사용하세요.
</div>
</div>
</div>
</div>
);
}
|