summaryrefslogtreecommitdiff
path: root/lib/email-template/editor/template-settings.tsx
blob: 99ef54431fe699017cfc71d0c33bcd905d12ff09 (plain)
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
'use client';

/* IMPORT */
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { 
  AlertTriangle, 
  Calendar,
  Copy,
  Hash,
  Info,
  Save,
  Trash2,
  User,
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { deleteTemplate, duplicateTemplate, getCurrentUserId, updateTemplateAction } from '../service';
import { getCategoryDisplayName, TEMPLATE_CATEGORY_OPTIONS } from '../validations';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import { toast } from 'sonner';
import { type TemplateWithVariables } from '@/db/schema';
import { useRouter } from 'next/navigation';
import { useState } from 'react';

// ----------------------------------------------------------------------------------------------------

/* TYPES */
interface TemplateSettingsProps {
  template: TemplateWithVariables;
  onUpdate: (template: TemplateWithVariables) => void;
}

// ----------------------------------------------------------------------------------------------------

export function TemplateSettings({ template, onUpdate }: TemplateSettingsProps) {
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);
  const [formData, setFormData] = useState({
    name: template.name,
    description: template.description || '',
    category: template.category || '',
    sampleData: JSON.stringify(template.sampleData || {}, null, 2)
  });

  // 폼 데이터 업데이트
  const updateFormData = (field: keyof typeof formData, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }))
  };

  // 기본 정보 저장
  const handleSaveBasicInfo = async () => {
    setIsLoading(true);
    try {
      // 샘플 데이터 JSON 파싱 검증
      let parsedSampleData = {};
      if (formData.sampleData.trim()) {
        try {
          parsedSampleData = JSON.parse(formData.sampleData);
        } catch (error) {
          toast.error('샘플 데이터 JSON 형식이 올바르지 않습니다.');
          setIsLoading(false);
          return;
        }
      }

      const result = await updateTemplateAction(template.slug, {
        name: formData.name,
        description: formData.description || undefined,
        category: formData.category,
        sampleData: parsedSampleData,
        updatedBy: await getCurrentUserId(),
      });

      if (result.success) {
        toast.success('템플릿 설정이 저장되었습니다.')
        onUpdate({
          ...template,
          name: formData.name,
          description: formData.description,
          category: formData.category,
          sampleData: parsedSampleData,
          version: template.version ? template.version + 1 : 1,
        });
      } else {
        toast.error(result.error || '저장에 실패했습니다.');
      }
    } catch (error) {
      toast.error('저장 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  }

  // 템플릿 복제
  const handleDuplicate = async () => {
    setIsLoading(true);
    try {
      const copyName = `${template.name} (복사본)`;
      const copySlug = `${template.slug}-copy-${Date.now()}`;
      
      const result = await duplicateTemplate(
        template.id,
        copyName,
        copySlug,
        await getCurrentUserId(),
      );

      if (result.success && result.data) {
        toast.success('템플릿이 복제되었습니다.');
        router.push(`/evcp/email-template/${result.data.slug}`);
      } else {
        toast.error(result.error || '복제에 실패했습니다.');
      }
    } catch (error) {
      toast.error('복제 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  }

  // 템플릿 삭제
  const handleDelete = async () => {
    setIsLoading(true);
    try {
      const result = await deleteTemplate(template.id);

      if (result.success) {
        toast.success('템플릿이 삭제되었습니다.');
        router.push('/evcp/email-template');
      } else {
        toast.error(result.error || '삭제에 실패했습니다.');
      }
    } catch (error) {
      toast.error('삭제 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  }

  // 샘플 데이터 포맷팅
  const formatSampleData = () => {
    try {
      const parsed = JSON.parse(formData.sampleData)
      const formatted = JSON.stringify(parsed, null, 2)
      updateFormData('sampleData', formatted)
      toast.success('JSON이 포맷팅되었습니다.')
    } catch (error) {
      toast.error('유효한 JSON이 아닙니다.')
    }
  }

  // 기본 샘플 데이터 생성
  const generateDefaultSampleData = () => {
    const defaultData: Record<string, any> = {}
    
    template.variables.forEach(variable => {
      switch (variable.variableType) {
        case 'string':
          defaultData[variable.variableName] = variable.defaultValue || `샘플 ${variable.variableName}`
          break
        case 'number':
          defaultData[variable.variableName] = variable.defaultValue ? parseFloat(variable.defaultValue) : 123
          break
        case 'boolean':
          defaultData[variable.variableName] = variable.defaultValue ? variable.defaultValue === 'true' : true
          break
        case 'date':
          defaultData[variable.variableName] = variable.defaultValue || new Date().toLocaleDateString('ko-KR')
          break
      }
    })

    const formatted = JSON.stringify(defaultData, null, 2)
    updateFormData('sampleData', formatted)
    toast.success('기본 샘플 데이터가 생성되었습니다.')
  }

  return (
    <div className="space-y-6">
      {/* 기본 정보 */}
      <Card>
        <CardHeader>
          <CardTitle>기본 정보</CardTitle>
          <CardDescription>
            템플릿의 기본 정보를 수정할 수 있습니다.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label htmlFor="name">템플릿 이름</Label>
            <Input
              id="name"
              value={formData.name}
              onChange={(e) => updateFormData('name', e.target.value)}
              placeholder="템플릿 이름을 입력하세요"
            />
          </div>
          <div>
            <Label htmlFor="description">설명</Label>
            <Textarea
              id="description"
              value={formData.description}
              onChange={(e) => updateFormData('description', e.target.value)}
              placeholder="템플릿에 대한 설명을 입력하세요"
              className="min-h-[100px]"
            />
          </div>
          <div>
            <Label htmlFor="category">카테고리</Label>
            <Select
              value={formData.category || "none"} // 빈 문자열일 때 "none"으로 표시
              onValueChange={(value) => {
                // "none"이 선택되면 빈 문자열로 변환
                updateFormData('category', value === "none" ? "" : value)
              }}
            >
              <SelectTrigger>
                <SelectValue placeholder="카테고리를 선택하세요" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="none">카테고리 없음</SelectItem> {/* ✅ "none" 사용 */}
                {TEMPLATE_CATEGORY_OPTIONS.map((option) => (
                  <SelectItem key={option.value} value={option.value}>
                    {option.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="flex justify-end">
            <Button onClick={handleSaveBasicInfo} disabled={isLoading}>
              <Save className="mr-2 h-4 w-4" />
              {isLoading ? '저장 중...' : '기본 정보 저장'}
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* 샘플 데이터 */}
      <Card>
        <CardHeader>
          <CardTitle>샘플 데이터</CardTitle>
          <CardDescription>
            미리보기에서 사용될 기본 샘플 데이터를 설정합니다.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={formatSampleData}
            >
              JSON 포맷팅
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={generateDefaultSampleData}
            >
              기본 데이터 생성
            </Button>
          </div>
          <div>
            <Label htmlFor="sampleData">샘플 데이터 (JSON)</Label>
            <Textarea
              id="sampleData"
              value={formData.sampleData}
              onChange={(e) => updateFormData('sampleData', e.target.value)}
              placeholder='{"userName": "홍길동", "email": "user@example.com"}'
              className="min-h-[200px] font-mono text-sm"
            />
          </div>
          <div className="bg-blue-50 p-3 rounded-lg">
            <p className="text-sm text-blue-800">
              <Info className="inline h-4 w-4 mr-1" />
              샘플 데이터는 템플릿 미리보기에서 기본값으로 사용됩니다.
            </p>
          </div>
        </CardContent>
      </Card>

      {/* 메타 정보 */}
      <Card>
        <CardHeader>
          <CardTitle>메타 정보</CardTitle>
          <CardDescription>
            템플릿의 상세 정보를 확인할 수 있습니다.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-3">
              <div className="flex items-center gap-2">
                <Hash className="h-4 w-4 text-muted-foreground" />
                <span className="text-sm font-medium">Slug:</span>
                <code className="text-sm bg-muted px-2 py-1 rounded">
                  {template.slug}
                </code>
              </div>
              <div className="flex items-center gap-2">
                <Badge variant="outline">버전 {template.version}</Badge>
                <Badge variant={template.category ? "default" : "secondary"}>
                  {getCategoryDisplayName(template.category)}
                </Badge>
              </div>
              <div className="flex items-center gap-2">
                <Calendar className="h-4 w-4 text-muted-foreground" />
                <span className="text-sm">
                  생성일: {new Date(template.createdAt).toLocaleString('ko-KR')}
                </span>
              </div>
              <div className="flex items-center gap-2">
                <Calendar className="h-4 w-4 text-muted-foreground" />
                <span className="text-sm">
                  수정일: {new Date(template.updatedAt).toLocaleString('ko-KR')}
                </span>
              </div>
            </div>
            <div className="space-y-3">
              <div className="flex items-center gap-2">
                <User className="h-4 w-4 text-muted-foreground" />
                <span className="text-sm">
                  생성자: {template.createdBy}
                </span>
              </div>
              <div>
                <span className="text-sm font-medium">변수 개수:</span>
                <span className="ml-2 text-sm">{template.variables.length}개</span>
              </div>
              <div>
                <span className="text-sm font-medium">필수 변수:</span>
                <span className="ml-2 text-sm">
                  {template.variables.filter(v => v.isRequired).length}개
                </span>
              </div>
              <div>
                <span className="text-sm font-medium">콘텐츠 길이:</span>
                <span className="ml-2 text-sm">{template.content.length} 문자</span>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      <Separator />

      {/* 위험한 작업 */}
      <Card className="border-destructive">
        <CardHeader>
          <CardTitle className="text-destructive">위험한 작업</CardTitle>
          <CardDescription>
            다음 작업들은 신중히 수행해주세요. 일부는 되돌릴 수 없습니다.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between p-4 border rounded-lg">
            <div>
              <h4 className="font-medium">템플릿 복제</h4>
              <p className="text-sm text-muted-foreground">
                현재 템플릿을 복사하여 새로운 템플릿을 생성합니다.
              </p>
            </div>
            <Button
              variant="outline"
              onClick={handleDuplicate}
              disabled={isLoading}
            >
              <Copy className="mr-2 h-4 w-4" />
              복제
            </Button>
          </div>

          <div className="flex items-center justify-between p-4 border border-destructive rounded-lg bg-destructive/5">
            <div>
              <h4 className="font-medium text-destructive">템플릿 삭제</h4>
              <p className="text-sm text-muted-foreground">
                이 템플릿을 완전히 삭제합니다. 이 작업은 되돌릴 수 없습니다.
              </p>
            </div>
            <AlertDialog>
              <AlertDialogTrigger asChild>
                <Button variant="destructive" disabled={isLoading}>
                  <Trash2 className="mr-2 h-4 w-4" />
                  삭제
                </Button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>템플릿 삭제 확인</AlertDialogTitle>
                  <AlertDialogDescription>
                    정말로 <strong>"{template.name}"</strong> 템플릿을 삭제하시겠습니까?
                    <br />
                    <br />
                    이 작업은 되돌릴 수 없으며, 다음 항목들이 함께 삭제됩니다:
                    <br />
                    • 템플릿 내용 및 설정
                    <br />
                    • 모든 변수 ({template.variables.length}개)
                    <br />
                    • 변경 이력
                    <br />
                    <br />
                    <span className="text-destructive font-medium">
                      삭제하려면 "영구 삭제"를 클릭하세요.
                    </span>
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>취소</AlertDialogCancel>
                  <AlertDialogAction
                    onClick={handleDelete}
                    className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                  >
                    <Trash2 className="mr-2 h-4 w-4" />
                    영구 삭제
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          </div>
        </CardContent>
      </Card>

      {/* 주의사항 */}
      <div className="bg-amber-50 border border-amber-200 p-4 rounded-lg">
        <div className="flex items-start gap-3">
          <AlertTriangle className="h-5 w-5 text-amber-600 mt-0.5" />
          <div>
            <h3 className="font-semibold text-amber-800">주의사항</h3>
            <div className="mt-2 text-sm text-amber-700 space-y-1">
              <p>• 템플릿 설정 변경 시 기존 미리보기가 무효화될 수 있습니다.</p>
              <p>• 샘플 데이터는 유효한 JSON 형식이어야 합니다.</p>
              <p>• 템플릿 삭제는 되돌릴 수 없으니 신중히 결정하세요.</p>
              <p>• 카테고리 변경 시 관련 기본 변수가 영향받을 수 있습니다.</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}