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
|
/**
* 결재 템플릿 유틸리티 함수
*
* 기능:
* - 템플릿 이름으로 조회
* - 변수 치환 ({{변수명}})
* - HTML 변환 유틸리티 (테이블, 리스트)
*/
'use server';
import db from '@/db/db';
import { eq } from 'drizzle-orm';
import { approvalTemplates } from '@/db/schema/knox/approvals';
/**
* 템플릿 이름으로 조회
*
* @param name - 템플릿 이름 (한국어)
* @returns 템플릿 객체 또는 null
*/
export async function getApprovalTemplateByName(name: string) {
try {
const [template] = await db
.select()
.from(approvalTemplates)
.where(eq(approvalTemplates.name, name))
.limit(1);
return template || null;
} catch (error) {
console.error(`[Template Utils] Failed to get template: ${name}`, error);
return null;
}
}
/**
* 템플릿 변수 치환
*
* {{변수명}} 형태의 변수를 실제 값으로 치환
*
* @param content - 템플릿 HTML 내용
* @param variables - 변수 매핑 객체
* @returns 치환된 HTML
*
* @example
* ```typescript
* const content = "<p>{{이름}}님, 안녕하세요</p>";
* const variables = { "이름": "홍길동" };
* const result = await replaceTemplateVariables(content, variables);
* // "<p>홍길동님, 안녕하세요</p>"
* ```
*/
export async function replaceTemplateVariables(
content: string,
variables: Record<string, string>
): Promise<string> {
let result = content;
Object.entries(variables).forEach(([key, value]) => {
// {{변수명}} 패턴을 전역으로 치환
const pattern = new RegExp(`\\{\\{${escapeRegex(key)}\\}\\}`, 'g');
result = result.replace(pattern, value);
});
// 치환되지 않은 변수 로그 (디버깅용)
const remainingVariables = result.match(/\{\{[^}]+\}\}/g);
if (remainingVariables && remainingVariables.length > 0) {
console.warn(
'[Template Utils] Unmatched variables found:',
remainingVariables
);
}
return result;
}
/**
* 정규식 특수문자 이스케이프
*/
function escapeRegex(str: string): string {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/**
* 배열 데이터를 HTML 테이블로 변환 (공통 유틸)
*
* @param data - 테이블 데이터 배열
* @param columns - 컬럼 정의 (키, 라벨)
* @returns HTML 테이블 문자열
*
* @example
* ```typescript
* const data = [
* { name: "홍길동", age: 30 },
* { name: "김철수", age: 25 }
* ];
* const columns = [
* { key: "name", label: "이름" },
* { key: "age", label: "나이" }
* ];
* const html = await htmlTableConverter(data, columns);
* ```
*/
export async function htmlTableConverter(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
data: Array<Record<string, any>>,
columns: Array<{ key: string; label: string }>
): Promise<string> {
if (!data || data.length === 0) {
return '<p style="color: #6b7280;">데이터가 없습니다.</p>';
}
const headerRow = columns
.map(
(col) =>
`<th style="border: 1px solid #d1d5db; padding: 8px 16px; background-color: #f3f4f6; font-weight: 600; text-align: left;">${col.label}</th>`
)
.join('');
const bodyRows = data
.map((row) => {
const cells = columns
.map((col) => {
const value = row[col.key];
const displayValue =
value !== undefined && value !== null ? String(value) : '-';
return `<td style="border: 1px solid #d1d5db; padding: 8px 16px;">${displayValue}</td>`;
})
.join('');
return `<tr>${cells}</tr>`;
})
.join('');
return `
<table style="width: 100%; border-collapse: collapse; border: 1px solid #d1d5db; margin: 16px 0;">
<thead>
<tr>${headerRow}</tr>
</thead>
<tbody>
${bodyRows}
</tbody>
</table>
`;
}
/**
* 배열을 HTML 리스트로 변환
*
* @param items - 리스트 아이템 배열
* @param ordered - 순서 있는 리스트 여부 (기본: false)
* @returns HTML 리스트 문자열
*
* @example
* ```typescript
* const items = ["첫 번째", "두 번째", "세 번째"];
* const html = await htmlListConverter(items, true);
* ```
*/
export async function htmlListConverter(
items: string[],
ordered: boolean = false
): Promise<string> {
if (!items || items.length === 0) {
return '<p style="color: #6b7280;">항목이 없습니다.</p>';
}
const listItems = items
.map((item) => `<li style="margin-bottom: 4px;">${item}</li>`)
.join('');
const tag = ordered ? 'ol' : 'ul';
const listStyle = ordered
? 'list-style-type: decimal; list-style-position: inside; margin: 16px 0; padding-left: 20px;'
: 'list-style-type: disc; list-style-position: inside; margin: 16px 0; padding-left: 20px;';
return `<${tag} style="${listStyle}">${listItems}</${tag}>`;
}
/**
* 키-값 쌍을 HTML 정의 목록으로 변환
*
* @param items - 키-값 쌍 배열
* @returns HTML dl 태그
*
* @example
* ```typescript
* const items = [
* { label: "협력업체명", value: "ABC 주식회사" },
* { label: "사업자등록번호", value: "123-45-67890" }
* ];
* const html = await htmlDescriptionList(items);
* ```
*/
export async function htmlDescriptionList(
items: Array<{ label: string; value: string }>
): Promise<string> {
if (!items || items.length === 0) {
return '<p style="color: #6b7280;">정보가 없습니다.</p>';
}
const listItems = items
.map(
(item) => `
<div style="display: flex; border-bottom: 1px solid #e5e7eb; padding: 8px 0;">
<dt style="width: 33.333%; font-weight: 600; color: #374151;">${item.label}</dt>
<dd style="width: 66.667%; color: #111827;">${item.value}</dd>
</div>
`
)
.join('');
return `<dl style="margin: 16px 0;">${listItems}</dl>`;
}
|