summaryrefslogtreecommitdiff
path: root/components/information/information-client.tsx
blob: d863175f0db00d950bed035064bc09627b42c7c3 (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
"use client"

import { useState, useEffect, useTransition } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Badge } from "@/components/ui/badge"
import { 
  Search, 
  Edit, 
  FileText, 
  ChevronUp, 
  ChevronDown, 
  Download
} from "lucide-react"
import { toast } from "sonner"
import { formatDate } from "@/lib/utils"
import { getInformationLists } from "@/lib/information/service"
import type { PageInformation } from "@/db/schema/information"
import { UpdateInformationDialog } from "@/lib/information/table/update-information-dialog"

interface InformationClientProps {
  initialData?: PageInformation[]
}

type SortField = "pageName" | "pagePath" | "createdAt"
type SortDirection = "asc" | "desc"

export function InformationClient({ initialData = [] }: InformationClientProps) {
  const router = useRouter()
  const [informations, setInformations] = useState<PageInformation[]>(initialData)
  const [loading, setLoading] = useState(false)
  const [searchQuery, setSearchQuery] = useState("")
  const [sortField, setSortField] = useState<SortField>("createdAt")
  const [sortDirection, setSortDirection] = useState<SortDirection>("desc")
  const [editingInformation, setEditingInformation] = useState<PageInformation | null>(null)
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
  const [, startTransition] = useTransition()

  // 정보 목록 조회
  const fetchInformations = async () => {
    try {
      setLoading(true)
      const search = searchQuery || undefined

      startTransition(async () => {
        const result = await getInformationLists({
          page: 1,
          perPage: 50,
          search: search,
          sort: [{ id: sortField, desc: sortDirection === "desc" }],
          flags: [],
          filters: [],
          joinOperator: "and",
          pagePath: "",
          pageName: "",
          informationContent: "",
          isActive: null,
        })

        if (result?.data) {
          setInformations(result.data)
        } else {
          toast.error("정보 목록을 가져오는데 실패했습니다.")
        }
        setLoading(false)
      })
    } catch (error) {
      console.error("Error fetching informations:", error)
      toast.error("정보 목록을 가져오는데 실패했습니다.")
      setLoading(false)
    }
  }

  // 검색 핸들러
  const handleSearch = () => {
    fetchInformations()
  }

  // 정렬 함수
  const sortInformations = (informations: PageInformation[]) => {
    return [...informations].sort((a, b) => {
      let aValue: string | Date
      let bValue: string | Date

      if (sortField === "pageName") {
        aValue = a.pageName
        bValue = b.pageName
      } else if (sortField === "pagePath") {
        aValue = a.pagePath
        bValue = b.pagePath
      } else {
        aValue = new Date(a.createdAt)
        bValue = new Date(b.createdAt)
      }

      if (aValue < bValue) {
        return sortDirection === "asc" ? -1 : 1
      }
      if (aValue > bValue) {
        return sortDirection === "asc" ? 1 : -1
      }
      return 0
    })
  }

  // 정렬 핸들러
  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortDirection(sortDirection === "asc" ? "desc" : "asc")
    } else {
      setSortField(field)
      setSortDirection("asc")
    }
  }

  // 편집 핸들러
  const handleEdit = (information: PageInformation) => {
    setEditingInformation(information)
    setIsEditDialogOpen(true)
  }

  // 편집 완료 핸들러
  const handleEditClose = () => {
    setIsEditDialogOpen(false)
    setEditingInformation(null)
    // 데이터 새로고침
    fetchInformations()
  }

  // 다운로드 핸들러
  const handleDownload = (information: PageInformation) => {
    if (information.attachmentFilePath && information.attachmentFileName) {
      const link = document.createElement('a')
      link.href = information.attachmentFilePath
      link.download = information.attachmentFileName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  }

  // 정렬된 정보 목록
  const sortedInformations = sortInformations(informations)

  useEffect(() => {
    if (initialData.length > 0) {
      setInformations(initialData)
    } else {
      fetchInformations()
    }
  }, [])

  useEffect(() => {
    if (searchQuery !== "") {
      fetchInformations()
    } else if (initialData.length > 0) {
      setInformations(initialData)
    }
  }, [searchQuery])

  return (
    <div className="space-y-6">
      {/* 검색 */}
      <div className="flex items-center justify-between gap-4">
        <div className="flex items-center gap-4">
          <div className="relative flex-1 max-w-md">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
            <Input
              placeholder="페이지명이나 경로로 검색..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10"
              onKeyPress={(e) => e.key === "Enter" && handleSearch()}
            />
          </div>
          <Button onClick={handleSearch} variant="outline">
            검색
          </Button>
          <Button
            variant="outline"
            onClick={() => router.refresh()}
          >
            새로고침
          </Button>
        </div>
      </div>

      {/* 정보 테이블 */}
      <div className="bg-white rounded-lg shadow">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>
                <button
                  className="flex items-center gap-1 hover:text-foreground"
                  onClick={() => handleSort("pageName")}
                >
                  페이지명
                  {sortField === "pageName" && (
                    sortDirection === "asc" ? (
                      <ChevronUp className="h-4 w-4" />
                    ) : (
                      <ChevronDown className="h-4 w-4" />
                    )
                  )}
                </button>
              </TableHead>
              <TableHead>
                <button
                  className="flex items-center gap-1 hover:text-foreground"
                  onClick={() => handleSort("pagePath")}
                >
                  페이지 경로
                  {sortField === "pagePath" && (
                    sortDirection === "asc" ? (
                      <ChevronUp className="h-4 w-4" />
                    ) : (
                      <ChevronDown className="h-4 w-4" />
                    )
                  )}
                </button>
              </TableHead>
              <TableHead>정보 내용</TableHead>
              <TableHead>첨부파일</TableHead>
              <TableHead>상태</TableHead>
              <TableHead>
                <button
                  className="flex items-center gap-1 hover:text-foreground"
                  onClick={() => handleSort("createdAt")}
                >
                  생성일
                  {sortField === "createdAt" && (
                    sortDirection === "asc" ? (
                      <ChevronUp className="h-4 w-4" />
                    ) : (
                      <ChevronDown className="h-4 w-4" />
                    )
                  )}
                </button>
              </TableHead>
              <TableHead className="text-right">작업</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center py-8">
                  로딩 중...
                </TableCell>
              </TableRow>
            ) : informations.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center py-8 text-gray-500">
                  정보가 없습니다.
                </TableCell>
              </TableRow>
            ) : (
              sortedInformations.map((information) => (
                <TableRow key={information.id}>
                  <TableCell className="font-medium">
                    <div className="flex items-center gap-2">
                      <FileText className="h-4 w-4" />
                      <span className="max-w-[200px] truncate">
                        {information.pageName}
                      </span>
                    </div>
                  </TableCell>
                  <TableCell>
                    <span className="font-mono text-sm max-w-[200px] truncate block">
                      {information.pagePath}
                    </span>
                  </TableCell>
                  <TableCell>
                    <div 
                      className="max-w-[300px] text-sm text-gray-600 line-clamp-2"
                      dangerouslySetInnerHTML={{ 
                        __html: information.informationContent?.substring(0, 100) + '...' || '' 
                      }}
                    />
                  </TableCell>
                  <TableCell>
                    {information.attachmentFileName ? (
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleDownload(information)}
                        className="flex items-center gap-1"
                      >
                        <Download className="h-3 w-3" />
                        <span className="max-w-[100px] truncate">
                          {information.attachmentFileName}
                        </span>
                      </Button>
                    ) : (
                      <span className="text-gray-400">없음</span>
                    )}
                  </TableCell>
                  <TableCell>
                    <Badge variant={information.isActive ? "default" : "secondary"}>
                      {information.isActive ? "활성" : "비활성"}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    {formatDate(information.createdAt, "KR")}
                  </TableCell>
                  <TableCell className="text-right">
                    <Button 
                      variant="outline" 
                      size="sm"
                      onClick={() => handleEdit(information)}
                    >
                      <Edit className="h-4 w-4" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* 편집 다이얼로그 */}
      {editingInformation && (
        <UpdateInformationDialog
          open={isEditDialogOpen}
          onOpenChange={setIsEditDialogOpen}
          information={editingInformation}
          onSuccess={handleEditClose}
        />
      )}
    </div>
  )
}