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

import React, { useState, useEffect, useTransition } from "react"
import { useRouter, useParams } from "next/navigation"
import { useTranslation } from "@/i18n/client"
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,
  Database,
  RefreshCw
} from "lucide-react"
import { toast } from "sonner"
import { formatDate } from "@/lib/utils"
import { getInformationLists, syncInformationFromMenuAssignments, getInformationDetail } 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 params = useParams()
  const lng = (params?.lng as string) || 'ko'
  const { t } = useTranslation(lng, 'menu')
  
  // 안전한 번역 함수 (키가 없을 때 원본 키 반환)
  const safeTranslate = (key: string): string => {
    try {
      const translated = t(key)
      // 번역 키가 그대로 반환되는 경우 원본 키 사용
      if (translated === key) {
        return key
      }
      return translated || key
    } catch (error) {
      console.warn(`Translation failed for key: ${key}`, error)
      return key
    }
  }
  
  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 [isSyncing, setIsSyncing] = useState(false)
  const [, startTransition] = useTransition()

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

      startTransition(async () => {
        const result = await getInformationLists()

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

  // 클라이언트 사이드 필터링 및 정렬
  const filteredAndSortedInformations = React.useMemo(() => {
    let filtered = informations

    // 검색 필터 (페이지명으로 검색)
    if (searchQuery) {
      filtered = filtered.filter(info => 
        safeTranslate(info.pageName).toLowerCase().includes(searchQuery.toLowerCase()) ||
        info.pagePath.toLowerCase().includes(searchQuery.toLowerCase())
      )
    }

    // 정렬
    filtered = filtered.sort((a, b) => {
      let aValue: string | Date
      let bValue: string | Date

      switch (sortField) {
        case "pageName":
          aValue = safeTranslate(a.pageName)
          bValue = safeTranslate(b.pageName)
          break
        case "pagePath":
          aValue = a.pagePath
          bValue = b.pagePath
          break
        case "createdAt":
          aValue = new Date(a.createdAt)
          bValue = new Date(b.createdAt)
          break
        default:
          return 0
      }

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

    return filtered
  }, [informations, searchQuery, sortField, sortDirection, safeTranslate])

  // 검색 핸들러 (클라이언트 사이드에서 필터링하므로 별도 동작 불필요)
  const handleSearch = () => {
    // 클라이언트 사이드 필터링이므로 별도 서버 요청 불필요
  }

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

      if (sortField === "pageName") {
        aValue = safeTranslate(a.pageName)
        bValue = safeTranslate(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 = async (information: PageInformation) => {
    try {
      // 첨부파일 정보까지 포함해서 가져오기
      const detailData = await getInformationDetail(information.id)
      if (detailData) {
        setEditingInformation(detailData)
      } else {
        // 실패시 기본 정보라도 사용
        setEditingInformation(information)
      }
      setIsEditDialogOpen(true)
    } catch (error) {
      console.error("Failed to load information detail:", error)
      // 에러시 기본 정보라도 사용
      setEditingInformation(information)
      setIsEditDialogOpen(true)
    }
  }

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

  // 다운로드 핸들러 (다중 첨부파일은 dialog에서 처리)
  const handleDownload = async (information: PageInformation) => {
    try {
      // 첨부파일 정보까지 포함해서 가져오기
      const detailData = await getInformationDetail(information.id)
      if (detailData) {
        setEditingInformation(detailData)
      } else {
        // 실패시 기본 정보라도 사용
        setEditingInformation(information)
      }
      setIsEditDialogOpen(true)
    } catch (error) {
      console.error("Failed to load information detail:", error)
      // 에러시 기본 정보라도 사용
      setEditingInformation(information)
      setIsEditDialogOpen(true)
    }
  }

  // 메뉴 동기화 핸들러
  const handleSync = async () => {
    setIsSyncing(true)
    try {
      const result = await syncInformationFromMenuAssignments()
      
      if (result.success) {
        toast.success(result.message)
        // 동기화 후 데이터 새로고침
        fetchInformations()
      } else {
        toast.error(result.message)
      }
    } catch (error) {
      console.error("동기화 오류:", error)
      toast.error("메뉴 동기화 중 오류가 발생했습니다.")
    } finally {
      setIsSyncing(false)
    }
  }



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

  // searchQuery 변경 시 클라이언트 사이드 필터링으로 처리되므로 useEffect 제거

  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-muted-foreground h-4 w-4" />
            <Input
              placeholder="페이지명이나 경로로 검색..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10"
              onKeyPress={(e) => e.key === "Enter"}
            />
          </div>

          <Button
            variant="outline"
            onClick={handleSync}
            disabled={isSyncing}
            className="gap-2"
          >
            <Database className={`h-4 w-4 ${isSyncing ? 'animate-pulse' : ''}`} />
            <RefreshCw className={`h-4 w-4 ${isSyncing ? 'animate-spin' : ''}`} />
            {isSyncing ? '동기화 중...' : '메뉴에서 동기화'}
          </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>
                <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>
            ) : filteredAndSortedInformations.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                  정보가 없습니다.
                </TableCell>
              </TableRow>
            ) : (
              filteredAndSortedInformations.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 as any).translatedPageName || safeTranslate(information.pageName)}
                      </span>
                    </div>
                  </TableCell>
                  <TableCell>
                    <span className="font-mono text-sm max-w-[300px] truncate block">
                      {information.pagePath}
                    </span>
                  </TableCell>
                  <TableCell>
                    <div 
                      className="max-w-[300px] text-sm text-muted-foreground line-clamp-2"
                      dangerouslySetInnerHTML={{ 
                        __html: information.informationContent?.substring(0, 100) + '...' || '' 
                      }}
                    />
                  </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>
  )
}