summaryrefslogtreecommitdiff
path: root/components/permissions/permission-crud-manager.tsx
blob: a9b2f64e42c2ef0b6f86fb442a4cd4dd5b4ab99d (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
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
// components/permissions/permission-crud-manager.tsx

"use client";

import { useState, useEffect } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
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 { Badge } from "@/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { 
  Plus, 
  Edit, 
  Trash2, 
  MoreVertical, 
  Search,
  Filter,
  Key,
  Shield,
  Copy,
  CheckCircle,
  AlertTriangle
} from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import {
  getAllPermissions,
  createPermission,
  updatePermission,
  deletePermission,
  getPermissionCategories,
} from "@/lib/permissions/permission-settings-actions";

interface Permission {
  id: number;
  permissionKey: string;
  name: string;
  description?: string;
  permissionType: string;
  resource: string;
  action: string;
  scope: string;
  menuPath?: string;
  uiElement?: string;
  isSystem: boolean;
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}

export function PermissionCrudManager() {
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [filteredPermissions, setFilteredPermissions] = useState<Permission[]>([]);
  const [categories, setCategories] = useState<{ resource: string; count: number }[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<string>("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [loading, setLoading] = useState(false);
  const [createDialogOpen, setCreateDialogOpen] = useState(false);
  const [editingPermission, setEditingPermission] = useState<Permission | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deletingPermission, setDeletingPermission] = useState<Permission | null>(null);

  useEffect(() => {
    loadPermissions();
    loadCategories();
  }, []);

  useEffect(() => {
    filterPermissions();
  }, [permissions, selectedCategory, searchQuery]);

  const loadPermissions = async () => {
    setLoading(true);
    try {
      const data = await getAllPermissions();
      setPermissions(data);
    } catch (error) {
      toast.error("권한 목록을 불러오는데 실패했습니다.");
    } finally {
      setLoading(false);
    }
  };

  const loadCategories = async () => {
    try {
      const data = await getPermissionCategories();
      setCategories(data);
    } catch (error) {
      console.error("카테고리 로드 실패:", error);
    }
  };

  const filterPermissions = () => {
    let filtered = permissions;

    if (selectedCategory !== "all") {
      filtered = filtered.filter(p => p.resource === selectedCategory);
    }

    if (searchQuery) {
      filtered = filtered.filter(p =>
        p.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        p.permissionKey.toLowerCase().includes(searchQuery.toLowerCase()) ||
        p.description?.toLowerCase().includes(searchQuery.toLowerCase())
      );
    }

    setFilteredPermissions(filtered);
  };

  const handleDelete = async () => {
    if (!deletingPermission) return;
    
    try {
      await deletePermission(deletingPermission.id);
      toast.success("권한이 삭제되었습니다.");
      loadPermissions();
      setDeleteDialogOpen(false);
      setDeletingPermission(null);
    } catch (error) {
      toast.error("권한 삭제에 실패했습니다.");
    }
  };

  const openDeleteDialog = (permission: Permission) => {
    setDeletingPermission(permission);
    setDeleteDialogOpen(true);
  };

  return (
    <div className="space-y-6">
      {/* 헤더 및 필터 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>권한 목록</CardTitle>
              <CardDescription>
                시스템에 등록된 모든 권한을 관리합니다.
              </CardDescription>
            </div>
            <Button onClick={() => setCreateDialogOpen(true)}>
              <Plus className="mr-2 h-4 w-4" />
              권한 추가
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          <div className="flex gap-4 mb-4">
            {/* 검색 */}
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="권한명, 키로 검색..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-8"
                />
              </div>
            </div>

            {/* 카테고리 필터 */}
            <Select value={selectedCategory} onValueChange={setSelectedCategory}>
              <SelectTrigger className="w-[200px]">
                <SelectValue placeholder="카테고리 선택" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">전체 ({permissions.length})</SelectItem>
                {categories.map(cat => (
                  <SelectItem key={cat.resource} value={cat.resource}>
                    {cat.resource} ({cat.count})
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* 권한 테이블 */}
          <div className="border rounded-lg">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>권한명</TableHead>
                  <TableHead>권한 키</TableHead>
                  <TableHead>타입</TableHead>
                  <TableHead>리소스</TableHead>
                  <TableHead>액션</TableHead>
                  <TableHead>범위</TableHead>
                  <TableHead>상태</TableHead>
                  <TableHead className="text-right">작업</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredPermissions.map(permission => (
                  <TableRow key={permission.id}>
                    <TableCell>
                      <div>
                        <div className="font-medium">{permission.name}</div>
                        {permission.description && (
                          <div className="text-xs text-muted-foreground">
                            {permission.description}
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <code className="text-xs bg-muted px-1 py-0.5 rounded">
                        {permission.permissionKey}
                      </code>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{permission.permissionType}</Badge>
                    </TableCell>
                    <TableCell>{permission.resource}</TableCell>
                    <TableCell>{permission.action}</TableCell>
                    <TableCell>
                      <Badge variant="secondary">{permission.scope}</Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        {permission.isActive ? (
                          <Badge variant="success">활성</Badge>
                        ) : (
                          <Badge variant="destructive">비활성</Badge>
                        )}
                        {permission.isSystem && (
                          <Badge variant="outline">시스템</Badge>
                        )}
                      </div>
                    </TableCell>
                    <TableCell className="text-right">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" className="h-8 w-8 p-0">
                            <MoreVertical className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem
                            onClick={() => {
                              navigator.clipboard.writeText(permission.permissionKey);
                              toast.success("권한 키가 복사되었습니다.");
                            }}
                          >
                            <Copy className="mr-2 h-4 w-4" />
                            키 복사
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            onClick={() => setEditingPermission(permission)}
                          >
                            <Edit className="mr-2 h-4 w-4" />
                            수정
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem
                            onClick={() => openDeleteDialog(permission)}
                            className="text-destructive"
                            disabled={permission.isSystem}
                          >
                            <Trash2 className="mr-2 h-4 w-4" />
                            삭제
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {/* 권한 생성/수정 다이얼로그 */}
      <PermissionFormDialog
        open={createDialogOpen || !!editingPermission}
        onOpenChange={(open) => {
          if (!open) {
            setCreateDialogOpen(false);
            setEditingPermission(null);
          }
        }}
        permission={editingPermission}
        onSuccess={() => {
          setCreateDialogOpen(false);
          setEditingPermission(null);
          loadPermissions();
        }}
      />

      {/* 삭제 확인 다이얼로그 */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              <div className="flex items-center gap-2">
                <AlertTriangle className="h-5 w-5 text-destructive" />
                권한 삭제 확인
              </div>
            </AlertDialogTitle>
            <AlertDialogDescription>
              {deletingPermission && (
                <div className="space-y-4">
                  <p>
                    <span className="font-semibold">&quot;{deletingPermission.name}&quot;</span> 권한을 삭제하시겠습니까?
                  </p>
                  
                  <div className="p-3 bg-muted rounded-lg space-y-2">
                    <div className="flex items-center gap-2 text-sm">
                      <span className="text-muted-foreground min-w-[80px]">권한 키:</span>
                      <code className="px-2 py-0.5 bg-background rounded">{deletingPermission.permissionKey}</code>
                    </div>
                    <div className="flex items-center gap-2 text-sm">
                      <span className="text-muted-foreground min-w-[80px]">리소스:</span>
                      <span>{deletingPermission.resource}</span>
                    </div>
                    <div className="flex items-center gap-2 text-sm">
                      <span className="text-muted-foreground min-w-[80px]">액션:</span>
                      <span>{deletingPermission.action}</span>
                    </div>
                  </div>

                  <div className="p-3 bg-destructive/10 border border-destructive/20 rounded-lg">
                    <p className="text-sm text-destructive font-medium">
                      ⚠️ 주의: 이 작업은 되돌릴 수 없습니다
                    </p>
                    <p className="text-sm text-muted-foreground mt-1">
                      이 권한과 관련된 모든 역할 및 사용자 할당이 제거됩니다.
                    </p>
                  </div>
                </div>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setDeletingPermission(null)}>
              취소
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}

// 권한 생성/수정 폼 다이얼로그
function PermissionFormDialog({
  open,
  onOpenChange,
  permission,
  onSuccess,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  permission?: Permission | null;
  onSuccess: () => void;
}) {
  const [formData, setFormData] = useState({
    permissionKey: "",
    name: "",
    description: "",
    permissionType: "action",
    resource: "",
    action: "",
    scope: "own",
    menuPath: "",
    uiElement: "",
    isActive: true,
  });
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (permission) {
      setFormData({
        permissionKey: permission.permissionKey,
        name: permission.name,
        description: permission.description || "",
        permissionType: permission.permissionType,
        resource: permission.resource,
        action: permission.action,
        scope: permission.scope,
        menuPath: permission.menuPath || "",
        uiElement: permission.uiElement || "",
        isActive: permission.isActive,
      });
    } else {
      setFormData({
        permissionKey: "",
        name: "",
        description: "",
        permissionType: "action",
        resource: "",
        action: "",
        scope: "own",
        menuPath: "",
        uiElement: "",
        isActive: true,
      });
    }
  }, [permission]);

  const handleSubmit = async () => {
    if (!formData.permissionKey || !formData.name || !formData.resource || !formData.action) {
      toast.error("필수 항목을 입력해주세요.");
      return;
    }

    setSaving(true);
    try {
      if (permission) {
        await updatePermission(permission.id, formData);
        toast.success("권한이 수정되었습니다.");
      } else {
        await createPermission(formData);
        toast.success("권한이 생성되었습니다.");
      }
      onSuccess();
    } catch (error: any) {
      toast.error(error.message || "권한 저장에 실패했습니다.");
    } finally {
      setSaving(false);
    }
  };

  // 권한 키 자동 생성
  const generatePermissionKey = () => {
    if (formData.resource && formData.action) {
      const key = `${formData.resource}.${formData.action}`.toLowerCase().replace(/\s+/g, '_');
      setFormData({ ...formData, permissionKey: key });
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>{permission ? "권한 수정" : "권한 생성"}</DialogTitle>
          <DialogDescription>
            새로운 권한을 생성하거나 기존 권한을 수정합니다.
          </DialogDescription>
        </DialogHeader>

        <div className="grid gap-4 py-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>권한 키*</Label>
              <div className="flex gap-2">
                <Input
                  value={formData.permissionKey}
                  onChange={(e) => setFormData({ ...formData, permissionKey: e.target.value })}
                  placeholder="예: rfq.vendor.create"
                />
                {!permission && (
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={generatePermissionKey}
                  >
                    자동
                  </Button>
                )}
              </div>
            </div>
            <div>
              <Label>권한명*</Label>
              <Input
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder="예: RFQ 벤더 추가"
              />
            </div>
          </div>

          <div>
            <Label>설명</Label>
            <Textarea
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              placeholder="권한에 대한 상세 설명"
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>권한 타입*</Label>
              <Select
                value={formData.permissionType}
                onValueChange={(v) => setFormData({ ...formData, permissionType: v })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="menu_access">메뉴 접근</SelectItem>
                  <SelectItem value="action">액션 실행</SelectItem>
                  <SelectItem value="data_read">데이터 읽기</SelectItem>
                  <SelectItem value="data_write">데이터 쓰기</SelectItem>
                  <SelectItem value="data_delete">데이터 삭제</SelectItem>
                  <SelectItem value="approve">승인</SelectItem>
                  <SelectItem value="export">내보내기</SelectItem>
                  <SelectItem value="import">가져오기</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>범위*</Label>
              <Select
                value={formData.scope}
                onValueChange={(v) => setFormData({ ...formData, scope: v })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">전체</SelectItem>
                  <SelectItem value="domain">도메인</SelectItem>
                  <SelectItem value="assigned">담당</SelectItem>
                  <SelectItem value="own">본인</SelectItem>
                  <SelectItem value="department">부서</SelectItem>
                  <SelectItem value="company">회사</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>리소스*</Label>
              <Input
                value={formData.resource}
                onChange={(e) => setFormData({ ...formData, resource: e.target.value })}
                placeholder="예: rfq_vendor"
              />
            </div>
            <div>
              <Label>액션*</Label>
              <Input
                value={formData.action}
                onChange={(e) => setFormData({ ...formData, action: e.target.value })}
                placeholder="예: create"
              />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>메뉴 경로</Label>
              <Input
                value={formData.menuPath}
                onChange={(e) => setFormData({ ...formData, menuPath: e.target.value })}
                placeholder="예: /evcp/rfq-last"
              />
            </div>
            <div>
              <Label>UI 요소</Label>
              <Input
                value={formData.uiElement}
                onChange={(e) => setFormData({ ...formData, uiElement: e.target.value })}
                placeholder="예: btn-add-vendor"
              />
            </div>
          </div>

          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              id="isActive"
              checked={formData.isActive}
              onChange={(e) => setFormData({ ...formData, isActive: e.target.checked })}
            />
            <Label htmlFor="isActive">활성 상태</Label>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            취소
          </Button>
          <Button onClick={handleSubmit} disabled={saving}>
            {saving ? "저장 중..." : permission ? "수정" : "생성"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}