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
|
"use client"
import * as React from "react"
import { Button } from "@/components/ui/button"
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 { Checkbox } from "@/components/ui/checkbox"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Badge } from "@/components/ui/badge"
import { Plus, Edit, Trash2, GripVertical, Copy } from "lucide-react"
import { toast } from "sonner"
import { DragDropContext, Droppable, Draggable } from "@hello-pangea/dnd"
import { type TemplateWithVariables, type TemplateVariable } from "@/db/schema"
import { addTemplateVariableAction } from "../service"
interface TemplateVariableManagerProps {
template: TemplateWithVariables
onUpdate: (template: TemplateWithVariables) => void
}
interface VariableFormData {
variableName: string
variableType: 'string' | 'number' | 'boolean' | 'date'
defaultValue: string
isRequired: boolean
description: string
}
export function TemplateVariableManager({ template, onUpdate }: TemplateVariableManagerProps) {
const [variables, setVariables] = React.useState(template.variables)
// const [isAddDialogOpen, setIsAddDialogOpen] = React.useState(false)
const [editingVariable, setEditingVariable] = React.useState<TemplateVariable | null>(null)
const [isSubmitting, setIsSubmitting] = React.useState(false)
const [isDialogOpen, setIsDialogOpen] = React.useState(false) // 이름 변경
const [formData, setFormData] = React.useState<VariableFormData>({
variableName: '',
variableType: 'string',
defaultValue: '',
isRequired: false,
description: ''
})
const isEditMode = editingVariable !== null
// 폼 초기화
const resetForm = () => {
setFormData({
variableName: '',
variableType: 'string',
defaultValue: '',
isRequired: false,
description: ''
})
setEditingVariable(null)
}
const handleEditVariable = (variable: TemplateVariable) => {
setEditingVariable(variable)
setFormData({
variableName: variable.variableName,
variableType: variable.variableType as any,
defaultValue: variable.defaultValue || '',
isRequired: variable.isRequired || false,
description: variable.description || ''
})
setIsDialogOpen(true)
}
const handleSubmitVariable = async () => {
if (!formData.variableName.trim()) {
toast.error('변수명을 입력해주세요.')
return
}
// 편집 모드가 아닐 때만 중복 검사
if (!isEditMode && variables.some(v => v.variableName === formData.variableName)) {
toast.error('이미 존재하는 변수명입니다.')
return
}
// 편집 모드일 때 다른 변수와 중복되는지 검사
if (isEditMode && variables.some(v => v.id !== editingVariable!.id && v.variableName === formData.variableName)) {
toast.error('이미 존재하는 변수명입니다.')
return
}
// 변수명 유효성 검사
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(formData.variableName)) {
toast.error('변수명은 영문자, 숫자, 언더스코어만 사용 가능하며 숫자로 시작할 수 없습니다.')
return
}
setIsSubmitting(true)
try {
if (isEditMode) {
// 편집 모드 - TODO: updateTemplateVariableAction 구현 필요
// const result = await updateTemplateVariableAction(template.slug, editingVariable!.id, formData)
// 임시로 클라이언트 사이드에서 업데이트
const updatedVariables = variables.map(v =>
v.id === editingVariable!.id
? { ...v, ...formData }
: v
)
setVariables(updatedVariables)
onUpdate({ ...template, variables: updatedVariables })
toast.success('변수가 수정되었습니다.')
} else {
// 추가 모드
const result = await addTemplateVariableAction(template.slug, {
variableName: formData.variableName,
variableType: formData.variableType,
defaultValue: formData.defaultValue || undefined,
isRequired: formData.isRequired,
description: formData.description || undefined,
})
if (result.success) {
const newVariable = result.data
const updatedVariables = [...variables, newVariable]
setVariables(updatedVariables)
onUpdate({ ...template, variables: updatedVariables })
toast.success('변수가 추가되었습니다.')
} else {
toast.error(result.error || '변수 추가에 실패했습니다.')
return
}
}
setIsDialogOpen(false)
resetForm()
} catch (error) {
toast.error(`변수 ${isEditMode ? '수정' : '추가'} 중 오류가 발생했습니다.`)
} finally {
setIsSubmitting(false)
}
}
// Dialog 닫기 처리
const handleDialogClose = (open: boolean) => {
setIsDialogOpen(open)
if (!open) {
resetForm()
}
}
// 변수 추가
// const handleAddVariable = async () => {
// if (!formData.variableName.trim()) {
// toast.error('변수명을 입력해주세요.')
// return
// }
// // 변수명 중복 검사
// if (variables.some(v => v.variableName === formData.variableName)) {
// toast.error('이미 존재하는 변수명입니다.')
// return
// }
// // 변수명 유효성 검사
// if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(formData.variableName)) {
// toast.error('변수명은 영문자, 숫자, 언더스코어만 사용 가능하며 숫자로 시작할 수 없습니다.')
// return
// }
// setIsSubmitting(true)
// try {
// const result = await addTemplateVariableAction(template.slug, {
// variableName: formData.variableName,
// variableType: formData.variableType,
// defaultValue: formData.defaultValue || undefined,
// isRequired: formData.isRequired,
// description: formData.description || undefined,
// })
// if (result.success) {
// const newVariable = result.data
// const updatedVariables = [...variables, newVariable]
// setVariables(updatedVariables)
// onUpdate({ ...template, variables: updatedVariables })
// toast.success('변수가 추가되었습니다.')
// setIsAddDialogOpen(false)
// resetForm()
// } else {
// toast.error(result.error || '변수 추가에 실패했습니다.')
// }
// } catch (error) {
// toast.error('변수 추가 중 오류가 발생했습니다.')
// } finally {
// setIsSubmitting(false)
// }
// }
// 변수 순서 변경
const handleDragEnd = (result: any) => {
if (!result.destination) return
const items = Array.from(variables)
const [reorderedItem] = items.splice(result.source.index, 1)
items.splice(result.destination.index, 0, reorderedItem)
// displayOrder 업데이트
const updatedItems = items.map((item, index) => ({
...item,
displayOrder: index
}))
setVariables(updatedItems)
onUpdate({ ...template, variables: updatedItems })
// TODO: 서버에 순서 변경 요청
toast.success('변수 순서가 변경되었습니다.')
}
// 변수 복사
const handleCopyVariable = (variable: TemplateVariable) => {
const copyName = `${variable.variableName}_copy`
setFormData({
variableName: copyName,
variableType: variable.variableType as any,
defaultValue: variable.defaultValue || '',
isRequired: variable.isRequired || false,
description: variable.description || ''
})
setIsDialogOpen(true)
}
// 변수 삭제
const handleDeleteVariable = async (variableId: string) => {
// TODO: 서버에서 변수 삭제 구현
const updatedVariables = variables.filter(v => v.id !== variableId)
setVariables(updatedVariables)
onUpdate({ ...template, variables: updatedVariables })
toast.success('변수가 삭제되었습니다.')
}
// 변수 타입에 따른 기본값 예시
const getDefaultValuePlaceholder = (type: string) => {
switch (type) {
case 'string': return '예: 홍길동'
case 'number': return '예: 123'
case 'boolean': return 'true 또는 false'
case 'date': return '예: 2025-01-01'
default: return ''
}
}
// 변수 타입별 아이콘
const getVariableTypeIcon = (type: string) => {
switch (type) {
case 'string': return '📝'
case 'number': return '🔢'
case 'boolean': return '✅'
case 'date': return '📅'
default: return '❓'
}
}
return (
<div className="space-y-6">
{/* 헤더 */}
<div className="flex items-center justify-between">
<div>
{/* <h3 className="text-lg font-semibold">변수 관리</h3> */}
<p className="text-sm text-muted-foreground">
총 {variables.length}개의 변수가 등록되어 있습니다.
</p>
</div>
<Dialog open={isDialogOpen} onOpenChange={handleDialogClose}>
<DialogTrigger asChild>
<Button onClick={() => { resetForm(); setIsDialogOpen(true) }}>
<Plus className="mr-2 h-4 w-4" />
변수 추가
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>
{isEditMode ? '변수 수정' : '새 변수 추가'}
</DialogTitle>
<DialogDescription>
{isEditMode
? '기존 변수의 정보를 수정합니다.'
: '템플릿에서 사용할 새로운 변수를 추가합니다.'
}
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="variableName">변수명</Label>
<Input
id="variableName"
value={formData.variableName}
onChange={(e) => setFormData(prev => ({ ...prev, variableName: e.target.value }))}
placeholder="예: userName, orderDate"
/>
</div>
<div>
<Label htmlFor="variableType">타입</Label>
<Select
value={formData.variableType}
onValueChange={(value) => setFormData(prev => ({ ...prev, variableType: value as any }))}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="string">📝 문자열</SelectItem>
<SelectItem value="number">🔢 숫자</SelectItem>
<SelectItem value="boolean">✅ 불린</SelectItem>
<SelectItem value="date">📅 날짜</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="defaultValue">기본값</Label>
<Input
id="defaultValue"
value={formData.defaultValue}
onChange={(e) => setFormData(prev => ({ ...prev, defaultValue: e.target.value }))}
placeholder={getDefaultValuePlaceholder(formData.variableType)}
/>
</div>
<div>
<Label htmlFor="description">설명</Label>
<Textarea
id="description"
value={formData.description}
onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
placeholder="변수에 대한 설명을 입력하세요"
className="min-h-[80px]"
/>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="isRequired"
checked={formData.isRequired}
onCheckedChange={(checked) => setFormData(prev => ({ ...prev, isRequired: !!checked }))}
/>
<Label htmlFor="isRequired">필수 변수</Label>
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => handleDialogClose(false)}
>
취소
</Button>
<Button
onClick={handleSubmitVariable}
disabled={isSubmitting}
>
{isSubmitting
? `${isEditMode ? '수정' : '추가'} 중...`
: isEditMode ? '수정' : '추가'
}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
{/* 변수 목록 */}
{variables.length === 0 ? (
<div className="text-center py-12 border border-dashed rounded-lg">
<div className="text-muted-foreground">
<Plus className="h-12 w-12 mx-auto mb-4 opacity-50" />
<p className="text-lg font-medium">등록된 변수가 없습니다</p>
<p className="text-sm">첫 번째 변수를 추가해보세요.</p>
</div>
</div>
) : (
<DragDropContext onDragEnd={handleDragEnd}>
<Droppable droppableId="variables">
{(provided) => (
<div
{...provided.droppableProps}
ref={provided.innerRef}
className="border rounded-lg"
>
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-10"></TableHead>
<TableHead>변수명</TableHead>
<TableHead>타입</TableHead>
<TableHead>기본값</TableHead>
<TableHead>필수</TableHead>
<TableHead>설명</TableHead>
<TableHead className="w-24">작업</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{variables.map((variable, index) => (
<Draggable
key={variable.id}
draggableId={variable.id}
index={index}
>
{(provided, snapshot) => (
<TableRow
ref={provided.innerRef}
{...provided.draggableProps}
className={snapshot.isDragging ? 'bg-muted' : ''}
>
<TableCell>
<div
{...provided.dragHandleProps}
className="cursor-grab hover:cursor-grabbing"
>
<GripVertical className="h-4 w-4 text-muted-foreground" />
</div>
</TableCell>
<TableCell>
<div className="font-mono text-sm">
{variable.variableName}
</div>
</TableCell>
<TableCell>
<Badge variant="outline" className="gap-1">
{getVariableTypeIcon(variable.variableType)}
{variable.variableType}
</Badge>
</TableCell>
<TableCell>
<div className="text-sm text-muted-foreground max-w-[100px] truncate">
{variable.defaultValue || '-'}
</div>
</TableCell>
<TableCell>
{variable.isRequired ? (
<Badge variant="destructive" className="text-xs">필수</Badge>
) : (
<Badge variant="secondary" className="text-xs">선택</Badge>
)}
</TableCell>
<TableCell>
<div className="text-sm text-muted-foreground max-w-[200px] truncate">
{variable.description || '-'}
</div>
</TableCell>
<TableCell>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => handleCopyVariable(variable)}
>
<Copy className="h-3 w-3" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => handleEditVariable(variable)}
>
<Edit className="h-3 w-3" />
</Button>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive hover:text-destructive"
>
<Trash2 className="h-3 w-3" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>변수 삭제</AlertDialogTitle>
<AlertDialogDescription>
정말로 '{variable.variableName}' 변수를 삭제하시겠습니까?
이 작업은 되돌릴 수 없습니다.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>취소</AlertDialogCancel>
<AlertDialogAction
onClick={() => handleDeleteVariable(variable.id)}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
삭제
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</TableCell>
</TableRow>
)}
</Draggable>
))}
{provided.placeholder}
</TableBody>
</Table>
</div>
)}
</Droppable>
</DragDropContext>
)}
{/* 도움말 */}
<div className="bg-blue-50 p-4 rounded-lg">
<h4 className="font-medium text-blue-900 mb-2">변수 사용법</h4>
<div className="text-sm text-blue-800 space-y-1">
<p>• 템플릿에서 <code className="bg-blue-100 px-1 rounded">{`{{variableName}}`}</code> 형태로 사용</p>
<p>• 드래그 앤 드롭으로 변수 순서 변경 가능</p>
<p>• 필수 변수는 반드시 값이 제공되어야 함</p>
<p>• 변수명은 영문자, 숫자, 언더스코어만 사용 가능</p>
</div>
</div>
</div>
)
}
|