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
|
"use client"
import React, { useState, useEffect, useTransition } from "react"
import { 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,
Plus,
Eye,
Trash2
} from "lucide-react"
import { toast } from "sonner"
import { formatDate } from "@/lib/utils"
import { getNoticeLists, deleteNotice, getPagePathList } from "@/lib/notice/service"
import type { Notice } from "@/db/schema/notice"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { UpdateNoticeSheet } from "./notice-edit-sheet"
import { NoticeCreateDialog } from "./notice-create-dialog"
import { NoticeViewDialog } from "./notice-view-dialog"
type NoticeWithAuthor = Notice & {
authorName: string | null
authorEmail: string | null
isPopup?: boolean
}
interface NoticeClientProps {
initialData?: NoticeWithAuthor[]
currentUserId?: number
}
type SortField = "title" | "pagePath" | "createdAt"
type SortDirection = "asc" | "desc"
export function NoticeClient({ initialData = [], currentUserId }: NoticeClientProps) {
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 [notices, setNotices] = useState<NoticeWithAuthor[]>(initialData)
const [loading, setLoading] = useState(false)
const [searchQuery, setSearchQuery] = useState("")
const [sortField, setSortField] = useState<SortField>("createdAt")
const [sortDirection, setSortDirection] = useState<SortDirection>("desc")
const [, startTransition] = useTransition()
const [isEditSheetOpen, setIsEditSheetOpen] = useState(false)
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
const [isViewDialogOpen, setIsViewDialogOpen] = useState(false)
const [selectedNotice, setSelectedNotice] = useState<NoticeWithAuthor | null>(null)
const [pagePathOptions, setPagePathOptions] = useState<Array<{ value: string; label: string }>>([])
// 공지사항 목록 조회
const fetchNotices = async () => {
try {
setLoading(true)
startTransition(async () => {
const result = await getNoticeLists()
if (result?.data) {
setNotices(result.data as NoticeWithAuthor[])
} else {
toast.error("공지사항 목록을 가져오는데 실패했습니다.")
}
setLoading(false)
})
} catch (error) {
console.error("Error fetching notices:", error)
toast.error("공지사항 목록을 가져오는데 실패했습니다.")
setLoading(false)
}
}
// 검색 핸들러 (클라이언트 사이드에서 필터링하므로 별도 동작 불필요)
const handleSearch = () => {
// 클라이언트 사이드 필터링이므로 별도 서버 요청 불필요
}
// 정렬 핸들러
const handleSort = (field: SortField) => {
if (sortField === field) {
setSortDirection(sortDirection === "asc" ? "desc" : "asc")
} else {
setSortField(field)
setSortDirection("asc")
}
}
// 삭제 핸들러
const handleDelete = async (notice: NoticeWithAuthor) => {
try {
const result = await deleteNotice(notice.id)
if (result.success) {
toast.success(result.message)
setNotices(notices.filter(n => n.id !== notice.id))
} else {
toast.error(result.message)
}
} catch (error) {
console.error("Error deleting notice:", error)
toast.error("공지사항 삭제에 실패했습니다.")
}
}
// 클라이언트 사이드 필터링 및 정렬
const filteredAndSortedNotices = React.useMemo(() => {
let filtered = notices
// 검색 필터
if (searchQuery.trim()) {
const query = searchQuery.toLowerCase()
filtered = filtered.filter(notice =>
notice.title.toLowerCase().includes(query) ||
notice.pagePath.toLowerCase().includes(query) ||
notice.content.toLowerCase().includes(query) ||
(notice.authorName && notice.authorName.toLowerCase().includes(query)) ||
(notice.isPopup !== undefined && notice.isPopup ? '팝업' : '일반').toLowerCase().includes(query) ||
(notice.dontShowDuration && notice.dontShowDuration.toLowerCase().includes(query))
)
}
// 정렬
filtered = filtered.sort((a, b) => {
let aValue: string | Date
let bValue: string | Date
switch (sortField) {
case "title":
aValue = a.title
bValue = b.title
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
}, [notices, searchQuery, sortField, sortDirection])
// 페이지 경로 옵션 로딩
const loadPagePathOptions = async () => {
try {
const paths = await getPagePathList()
const options = paths.map(path => ({
value: path.pagePath,
label: path.pageName // i18n 키를 그대로 저장 (화면에서 번역)
}))
setPagePathOptions(options)
} catch (error) {
console.error("페이지 경로 로딩 실패:", error)
}
}
// View 다이얼로그 열기
const handleViewNotice = (notice: NoticeWithAuthor) => {
setSelectedNotice(notice)
setIsViewDialogOpen(true)
}
// Edit Sheet 열기
const handleEditNotice = (notice: NoticeWithAuthor) => {
setSelectedNotice(notice)
setIsEditSheetOpen(true)
}
// Create Dialog 열기
const handleCreateNotice = () => {
setIsCreateDialogOpen(true)
}
useEffect(() => {
if (initialData.length > 0) {
setNotices(initialData)
} else {
fetchNotices()
}
loadPagePathOptions()
}, [])
// 검색은 클라이언트 사이드에서 실시간으로 처리됨
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"
/>
</div>
<Button
variant="outline"
onClick={() => window.location.reload()}
>
새로고침
</Button>
</div>
<Button onClick={handleCreateNotice}>
<Plus className="h-4 w-4 mr-2" />
공지사항 추가
</Button>
</div>
{/* 공지사항 테이블 */}
<div className="bg-white rounded-lg shadow">
<Table>
<TableHeader>
<TableRow>
<TableHead>
<button
className="flex items-center gap-1 hover:text-foreground"
onClick={() => handleSort("title")}
>
제목
{sortField === "title" && (
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>작성자</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={9} className="text-center py-8">
로딩 중...
</TableCell>
</TableRow>
) : filteredAndSortedNotices.length === 0 ? (
<TableRow>
<TableCell colSpan={9} className="text-center py-8 text-gray-500">
{searchQuery.trim() ? "검색 결과가 없습니다." : "공지사항이 없습니다."}
</TableCell>
</TableRow>
) : (
filteredAndSortedNotices.map((notice) => (
<TableRow key={notice.id}>
<TableCell className="font-medium">
<div className="flex items-center gap-2">
<FileText className="h-4 w-4" />
<span className="max-w-[300px] truncate">
{notice.title}
</span>
</div>
</TableCell>
<TableCell>
<div className="max-w-[200px]">
<div className="font-mono text-xs text-muted-foreground truncate">
{notice.pagePath}
</div>
<div className="text-sm truncate">
{(() => {
const pageOption = pagePathOptions.find(opt => opt.value === notice.pagePath)
return pageOption ? safeTranslate(pageOption.label) : notice.pagePath
})()}
</div>
</div>
</TableCell>
<TableCell>
<Badge variant={notice.isPopup ? "default" : "secondary"}>
{notice.isPopup ? "팝업" : "일반"}
</Badge>
</TableCell>
<TableCell>
<div className="text-sm">
{notice.startAt && notice.endAt ? (
<div className="space-y-1">
<div className="text-xs text-muted-foreground">
시작: {formatDate(notice.startAt, "KR")}
</div>
<div className="text-xs text-muted-foreground">
종료: {formatDate(notice.endAt, "KR")}
</div>
</div>
) : (
<span className="text-xs text-muted-foreground">-</span>
)}
</div>
</TableCell>
{/* <TableCell>
<div className="text-sm">
{notice.dontShowDuration ? (
<Badge variant="outline">
{notice.dontShowDuration === 'day' ? '하루' : '영구'}
</Badge>
) : (
<span className="text-xs text-muted-foreground">-</span>
)}
</div>
</TableCell> */}
<TableCell>
<div className="flex flex-col">
<span className="font-medium text-sm">
{notice.authorName || "알 수 없음"}
</span>
{notice.authorEmail && (
<span className="text-xs text-muted-foreground">
{notice.authorEmail}
</span>
)}
</div>
</TableCell>
<TableCell>
<Badge variant={notice.isActive ? "default" : "secondary"}>
{notice.isActive ? "활성" : "비활성"}
</Badge>
</TableCell>
<TableCell>
{formatDate(notice.createdAt, "KR")}
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-2">
{/* View 버튼 - 다이얼로그 방식 */}
<Button
variant="outline"
size="sm"
onClick={() => handleViewNotice(notice)}
title="공지사항 보기 (Dialog)"
>
<Eye className="h-4 w-4" />
</Button>
{/* Edit 버튼 - 다이얼로그 방식 */}
<Button
variant="outline"
size="sm"
onClick={() => handleEditNotice(notice)}
title="공지사항 편집 (Dialog)"
>
<Edit className="h-4 w-4" />
</Button>
{/* 기존 페이지 방식 (비교용)
<Link href={`/${lng}/evcp/notice/${notice.id}/view`}>
<Button variant="outline" size="sm" title="공지사항 보기 (Page)">
<FileText className="h-4 w-4" />
</Button>
</Link> */}
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="outline" size="sm" className="text-red-600 hover:text-red-700">
<Trash2 className="h-4 w-4" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>공지사항 삭제</AlertDialogTitle>
<AlertDialogDescription>
이 공지사항을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>취소</AlertDialogCancel>
<AlertDialogAction
onClick={() => handleDelete(notice)}
className="bg-red-600 hover:bg-red-700"
>
삭제
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
{/* 다이얼로그들과 시트 - 테이블 밖에서 단일 렌더링 */}
<NoticeViewDialog
open={isViewDialogOpen}
onOpenChange={setIsViewDialogOpen}
notice={selectedNotice}
/>
<NoticeCreateDialog
open={isCreateDialogOpen}
onOpenChange={setIsCreateDialogOpen}
pagePathOptions={pagePathOptions}
currentUserId={currentUserId}
onSuccess={fetchNotices}
/>
<UpdateNoticeSheet
open={isEditSheetOpen}
onOpenChange={setIsEditSheetOpen}
notice={selectedNotice}
pagePathOptions={pagePathOptions}
onSuccess={fetchNotices}
/>
</div>
)
}
|