summaryrefslogtreecommitdiff
path: root/lib/approval-template/table/category-management-dialog.tsx
blob: 7f8b202d8e92a01895da7347404f33b402854332 (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
"use client"

import * as React from "react"
import { Loader, Plus, Settings, Trash, Edit, Eye, EyeOff } from "lucide-react"
import { toast } from "sonner"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"

import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import { Badge } from "@/components/ui/badge"

import { type ApprovalTemplateCategory } from "../category-service"
import {
  createApprovalTemplateCategory,
  updateApprovalTemplateCategory,
  deleteApprovalTemplateCategory,
  getApprovalTemplateCategoryList,
  getActiveApprovalTemplateCategories,
} from "../category-service"
import {
  createApprovalTemplateCategorySchema,
  updateApprovalTemplateCategorySchema,
  type CreateApprovalTemplateCategorySchema,
  type UpdateApprovalTemplateCategorySchema,
} from "../category-validations"

interface CategoryManagementDialogProps extends React.ComponentPropsWithRef<typeof Dialog> {
  showTrigger?: boolean
  onSuccess?: () => void
}

export function CategoryManagementDialog({
  showTrigger = true,
  onSuccess,
  ...props
}: CategoryManagementDialogProps) {
  const [categories, setCategories] = React.useState<ApprovalTemplateCategory[]>([])
  const [isLoading, setIsLoading] = React.useState(false)
  const [editingCategory, setEditingCategory] = React.useState<ApprovalTemplateCategory | null>(null)
  const [deletingCategory, setDeletingCategory] = React.useState<ApprovalTemplateCategory | null>(null)
  const [showCreateForm, setShowCreateForm] = React.useState(false)

  // 폼 상태
  const createForm = useForm<CreateApprovalTemplateCategorySchema>({
    resolver: zodResolver(createApprovalTemplateCategorySchema),
    defaultValues: {
      name: "",
      description: "",
      sortOrder: 0,
    },
  })

  const updateForm = useForm<UpdateApprovalTemplateCategorySchema>({
    resolver: zodResolver(updateApprovalTemplateCategorySchema),
    defaultValues: {
      name: "",
      description: "",
      isActive: true,
      sortOrder: 0,
    },
  })

  // 카테고리 목록 로드
  const loadCategories = React.useCallback(async () => {
    setIsLoading(true)
    try {
      const result = await getApprovalTemplateCategoryList({
        page: 1,
        perPage: 100, // 충분히 큰 수로 모든 카테고리 로드
        sort: [
          { id: 'sortOrder', desc: false },
          { id: 'name', desc: false }
        ],
      })
      setCategories(result.data)
    } catch (error) {
      toast.error("카테고리 목록을 불러오는데 실패했습니다.")
    } finally {
      setIsLoading(false)
    }
  }, [])

  React.useEffect(() => {
    if (props.open) {
      loadCategories()
    }
  }, [props.open, loadCategories])

  // 생성 핸들러
  const handleCreate = async (data: CreateApprovalTemplateCategorySchema) => {
    try {
      // 임시 사용자 ID (실제로는 세션에서 가져와야 함)
      const userId = 1 // TODO: 실제 사용자 ID로 변경

      await createApprovalTemplateCategory({
        ...data,
        createdBy: userId,
      })

      toast.success("카테고리가 생성되었습니다.")
      createForm.reset()
      setShowCreateForm(false)
      loadCategories()
      onSuccess?.()
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "카테고리 생성에 실패했습니다.")
    }
  }

  // 수정 핸들러
  const handleUpdate = async (data: UpdateApprovalTemplateCategorySchema) => {
    if (!editingCategory) return

    try {
      // 임시 사용자 ID (실제로는 세션에서 가져와야 함)
      const userId = 1 // TODO: 실제 사용자 ID로 변경

      await updateApprovalTemplateCategory(editingCategory.id, {
        ...data,
        updatedBy: userId,
      })

      toast.success("카테고리가 수정되었습니다.")
      setEditingCategory(null)
      updateForm.reset()
      loadCategories()
      onSuccess?.()
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "카테고리 수정에 실패했습니다.")
    }
  }

  // 삭제 핸들러
  const handleDelete = async () => {
    if (!deletingCategory) return

    try {
      // 임시 사용자 ID (실제로는 세션에서 가져와야 함)
      const userId = 1 // TODO: 실제 사용자 ID로 변경

      const result = await deleteApprovalTemplateCategory(deletingCategory.id, userId)
      if (result.error) {
        toast.error(result.error)
      } else {
        toast.success("카테고리가 삭제되었습니다.")
        loadCategories()
        onSuccess?.()
      }
    } catch (error) {
      toast.error("카테고리 삭제에 실패했습니다.")
    } finally {
      setDeletingCategory(null)
    }
  }

  // 수정 폼 열기
  const openEditForm = (category: ApprovalTemplateCategory) => {
    setEditingCategory(category)
    updateForm.reset({
      name: category.name,
      description: category.description || "",
      isActive: category.isActive,
      sortOrder: category.sortOrder,
    })
  }

  const trigger = showTrigger ? (
    <DialogTrigger asChild>
      <Button variant="outline" size="sm">
        <Settings className="mr-2 size-4" aria-hidden="true" />
        카테고리 관리
      </Button>
    </DialogTrigger>
  ) : null

  return (
    <>
      {trigger}
      <Dialog {...props}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>결재 템플릿 카테고리 관리</DialogTitle>
            <DialogDescription>
              결재 템플릿의 카테고리를 관리합니다. 카테고리는 부서별로 분류하여 사용하세요.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* 생성 폼 */}
            {showCreateForm && (
              <div className="border rounded-lg p-4 space-y-4">
                <h3 className="text-lg font-semibold">새 카테고리 추가</h3>
                <Form {...createForm}>
                  <form onSubmit={createForm.handleSubmit(handleCreate)} className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <FormField
                        control={createForm.control}
                        name="name"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>카테고리 이름 *</FormLabel>
                            <FormControl>
                              <Input placeholder="카테고리 이름을 입력하세요" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={createForm.control}
                        name="sortOrder"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>정렬 순서</FormLabel>
                            <FormControl>
                              <Input
                                type="number"
                                placeholder="0"
                                {...field}
                                onChange={(e) => field.onChange(parseInt(e.target.value) || 0)}
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>
                    <FormField
                      control={createForm.control}
                      name="description"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>설명</FormLabel>
                          <FormControl>
                            <Textarea
                              placeholder="카테고리에 대한 설명을 입력하세요"
                              className="min-h-[80px]"
                              {...field}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <div className="flex gap-2">
                      <Button type="submit" size="sm">
                        <Plus className="mr-2 size-4" />
                        추가
                      </Button>
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() => {
                          setShowCreateForm(false)
                          createForm.reset()
                        }}
                      >
                        취소
                      </Button>
                    </div>
                  </form>
                </Form>
              </div>
            )}

            {/* 카테고리 목록 */}
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-semibold">카테고리 목록</h3>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setShowCreateForm(!showCreateForm)}
                >
                  <Plus className="mr-2 size-4" />
                  {showCreateForm ? "취소" : "새 카테고리"}
                </Button>
              </div>

              {isLoading ? (
                <div className="flex items-center justify-center py-8">
                  <Loader className="size-4 animate-spin" />
                  <span className="ml-2">로딩 중...</span>
                </div>
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>이름</TableHead>
                      <TableHead>설명</TableHead>
                      <TableHead>정렬순서</TableHead>
                      <TableHead>상태</TableHead>
                      <TableHead className="w-[120px]">작업</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {categories.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={5} className="text-center py-8 text-muted-foreground">
                          등록된 카테고리가 없습니다.
                        </TableCell>
                      </TableRow>
                    ) : (
                      categories.map((category) => (
                        <TableRow key={category.id}>
                          <TableCell className="font-medium">{category.name}</TableCell>
                          <TableCell className="max-w-[200px] truncate">
                            {category.description || "-"}
                          </TableCell>
                          <TableCell>{category.sortOrder}</TableCell>
                          <TableCell>
                            <Badge variant={category.isActive ? "default" : "secondary"}>
                              {category.isActive ? (
                                <>
                                  <Eye className="mr-1 size-3" />
                                  활성
                                </>
                              ) : (
                                <>
                                  <EyeOff className="mr-1 size-3" />
                                  비활성
                                </>
                              )}
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <div className="flex gap-1">
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => openEditForm(category)}
                              >
                                <Edit className="size-4" />
                              </Button>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => setDeletingCategory(category)}
                              >
                                <Trash className="size-4" />
                              </Button>
                            </div>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              )}
            </div>

            {/* 수정 폼 */}
            {editingCategory && (
              <div className="border rounded-lg p-4 space-y-4">
                <h3 className="text-lg font-semibold">카테고리 수정</h3>
                <Form {...updateForm}>
                  <form onSubmit={updateForm.handleSubmit(handleUpdate)} className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <FormField
                        control={updateForm.control}
                        name="name"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>카테고리 이름 *</FormLabel>
                            <FormControl>
                              <Input placeholder="카테고리 이름을 입력하세요" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={updateForm.control}
                        name="sortOrder"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>정렬 순서</FormLabel>
                            <FormControl>
                              <Input
                                type="number"
                                placeholder="0"
                                {...field}
                                onChange={(e) => field.onChange(parseInt(e.target.value) || 0)}
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>
                    <FormField
                      control={updateForm.control}
                      name="description"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>설명</FormLabel>
                          <FormControl>
                            <Textarea
                              placeholder="카테고리에 대한 설명을 입력하세요"
                              className="min-h-[80px]"
                              {...field}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={updateForm.control}
                      name="isActive"
                      render={({ field }) => (
                        <FormItem className="flex items-center space-x-2">
                          <FormControl>
                            <input
                              type="checkbox"
                              checked={field.value}
                              onChange={field.onChange}
                              className="rounded"
                            />
                          </FormControl>
                          <FormLabel>활성 상태</FormLabel>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <div className="flex gap-2">
                      <Button type="submit" size="sm">
                        <Edit className="mr-2 size-4" />
                        수정
                      </Button>
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() => {
                          setEditingCategory(null)
                          updateForm.reset()
                        }}
                      >
                        취소
                      </Button>
                    </div>
                  </form>
                </Form>
              </div>
            )}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => props.onOpenChange?.(false)}>
              닫기
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 삭제 확인 다이얼로그 */}
      <AlertDialog open={!!deletingCategory} onOpenChange={() => setDeletingCategory(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>카테고리 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              "{deletingCategory?.name}" 카테고리를 삭제하시겠습니까?
              이 작업은 되돌릴 수 없습니다.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}