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

import * as React from "react"
import { useState } from "react"
import { Button } from "@/components/ui/button"

import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Info, Download, Edit, Loader2,Eye, EyeIcon } from "lucide-react"
import { getPageInformationDirect, getEditPermissionDirect } from "@/lib/information/service"
import { getPageNotices } from "@/lib/notice/service"
import { UpdateInformationDialog } from "@/lib/information/table/update-information-dialog"
import { NoticeViewDialog } from "@/components/notice/notice-view-dialog"
// import { PDFTronViewerDialog } from "@/components/document-viewer/pdftron-viewer-dialog" // 주석 처리 - 브라우저 내장 뷰어 사용
import type { PageInformation, InformationAttachment } from "@/db/schema/information"
import { isNoticeDontShowValid, setNoticeDontShow } from "@/lib/notice/storage-utils"
import { Checkbox } from "@/components/ui/checkbox"
import { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator"
import { ScrollArea } from "@/components/ui/scroll-area"
import { AlertCircle, Calendar, Clock, User } from "lucide-react"
import { toast } from "sonner"

type PageInformationWithUpdatedBy = PageInformation & {
  updatedByName?: string | null
  updatedByEmail?: string | null
}
import type { Notice } from "@/db/schema/notice"
import { useSession } from "next-auth/react"
import { formatDate } from "@/lib/utils"
import prettyBytes from "pretty-bytes"
// downloadFile은 동적으로 import

interface InformationButtonProps {
  pagePath: string
  className?: string
  variant?: "default" | "outline" | "ghost" | "secondary"
  size?: "default" | "sm" | "lg" | "icon"
}

type NoticeWithAuthor = Notice & {
  authorName: string | null
  authorEmail: string | null
  isPopup?: boolean
}

export function InformationButton({
  pagePath,
  className,
  variant = "ghost",
  size = "icon"
}: InformationButtonProps) {
  const { data: session } = useSession()
  const [isOpen, setIsOpen] = useState(false)
  const [information, setInformation] = useState<PageInformationWithUpdatedBy & { attachments: InformationAttachment[] } | null>(null)
  const [notices, setNotices] = useState<NoticeWithAuthor[]>([])
  const [hasEditPermission, setHasEditPermission] = useState(false)
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
  const [selectedNotice, setSelectedNotice] = useState<NoticeWithAuthor | null>(null)
  const [isNoticeViewDialogOpen, setIsNoticeViewDialogOpen] = useState(false)
  const [dataLoaded, setDataLoaded] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [retryCount, setRetryCount] = useState(0)

  // 강제 모달 관련 상태
  const [forceModalNotice, setForceModalNotice] = useState<NoticeWithAuthor | null>(null)
  const [isForceModalOpen, setIsForceModalOpen] = useState(false)
  const [forceModalDontShow, setForceModalDontShow] = useState(false)
  // const [viewerDialogOpen, setViewerDialogOpen] = useState(false) // 주석 처리 - 브라우저 내장 뷰어 사용
  // const [selectedFile, setSelectedFile] = useState<InformationAttachment | null>(null) // 주석 처리 - 브라우저 내장 뷰어 사용

  // 데이터 로드 함수
  const loadData = React.useCallback(async () => {
    if (dataLoaded) return
    
    setIsLoading(true)
    try {
      // 경로 정규화 - 더 안전한 방식
      let normalizedPath = pagePath
      if (normalizedPath.startsWith('/')) {
        normalizedPath = normalizedPath.slice(1)
      }
      // 빈 문자열이면 기본값 설정
      if (!normalizedPath) {
        normalizedPath = 'home'
      }
      
      // 약간의 지연 추가 (프로덕션에서 DB 연결 안정성)
      if (retryCount > 0) {
        await new Promise(resolve => setTimeout(resolve, 500 * retryCount))
      }
      
      // 순차적으로 데이터 조회 (프로덕션 안정성)
      const infoResult = await getPageInformationDirect(normalizedPath)
      const noticesResult = await getPageNotices(normalizedPath)

      setInformation(infoResult)
      setNotices(noticesResult)
      setDataLoaded(true)
      setRetryCount(0) // 성공시 재시도 횟수 리셋

      // 강제 모달을 띄워야 할 공지사항 확인
      checkForceModalNotices(noticesResult)
      
      // 권한 확인 - 세션이 확실히 있을 때만
      if (session?.user?.id && infoResult) {
        try {
          const hasPermission = await getEditPermissionDirect(normalizedPath, session.user.id)
          setHasEditPermission(hasPermission)
        } catch (permError) {
          setHasEditPermission(false)
        }
      }
    } catch (error) {
      // 재시도 로직
      if (retryCount < 2) {
        setRetryCount(prev => prev + 1)
        setIsLoading(false)
        return
      }
      
      // 최대 재시도 후 기본값 설정
      setInformation(null)
      setNotices([])
      setHasEditPermission(false)
      setDataLoaded(true)
      setRetryCount(0)
    } finally {
      setIsLoading(false)
    }
  }, [pagePath, session?.user?.id, dataLoaded, retryCount])

  // 세션이 준비되면 자동으로 데이터 로드 (버튼 클릭 시)
  React.useEffect(() => {
    if (!dataLoaded && session !== undefined) {
      loadData()
    }
  }, [isOpen, dataLoaded, session])

  // 재시도 처리
  React.useEffect(() => {
    if (retryCount > 0 && retryCount <= 2) {
      const timer = setTimeout(() => {
        setDataLoaded(false) // 재시도를 위해 리셋
      }, 500 * retryCount)
      return () => clearTimeout(timer)
    }
  }, [retryCount])

  // 강제 모달을 띄워야 할 공지사항 확인 함수
  const checkForceModalNotices = React.useCallback((noticesList: NoticeWithAuthor[]) => {
    // 여기서 유효기간 필터까지 처리
    if (!noticesList || noticesList.length === 0) return

    const now = new Date()

    for (const notice of noticesList) {
      // 팝업 공지사항이 아니면 건너뛰기
      if (!notice.isPopup) continue

      // 유효기간 필터링: startAt과 endAt이 모두 null이거나, 현재가 범위 내에 있어야
      const validStart = !notice.startAt || new Date(notice.startAt) <= now
      const validEnd = !notice.endAt || new Date(notice.endAt) >= now
      if (!(validStart && validEnd)) continue

      // '다시 보지 않기' 설정 확인 (영구 설정만 확인)
      const dontShowNever = isNoticeDontShowValid({
        noticeId: notice.id,
        duration: 'never'
      })

      // '다시 보지 않기' 설정이 없고, 현재 유효한 팝업 공지사항이면 강제 모달 표시
      if (!dontShowNever) {
        setForceModalNotice(notice)
        setIsForceModalOpen(true)
        setForceModalDontShow(false)
        break // 첫 번째 강제 모달 대상만 처리
      }
    }
  }, [])

  // 강제 모달 닫기 핸들러
  const handleForceModalClose = React.useCallback(() => {
    if (forceModalDontShow && forceModalNotice) {
      // '다시 보지 않기' 체크했으면 설정 저장 (영구로 설정)
      setNoticeDontShow({
        noticeId: forceModalNotice.id,
        duration: 'never'
      })
      toast.success("설정이 저장되었습니다.")
    }

    setIsForceModalOpen(false)
    setForceModalNotice(null)
    setForceModalDontShow(false)
  }, [forceModalDontShow, forceModalNotice])

  // 강제 모달에서 '다시 보지 않기' 체크박스 변경 핸들러
  const handleForceModalDontShowChange = React.useCallback((checked: boolean) => {
    setForceModalDontShow(checked)
  }, [])

  // 다이얼로그 열기
  const handleDialogOpen = (open: boolean) => {
    setIsOpen(open)
    // useEffect에서 데이터 로딩 처리하므로 여기서는 제거
  }

  // 편집 관련 핸들러
  const handleEditClick = () => {
    setIsEditDialogOpen(true)
  }

  const handleEditSuccess = () => {
    setIsEditDialogOpen(false)
    // 편집 후 데이터 다시 로드
    setDataLoaded(false)
    setRetryCount(0)
  }

  // 공지사항 클릭 핸들러
  const handleNoticeClick = (notice: NoticeWithAuthor) => {
    setSelectedNotice(notice)
    setIsNoticeViewDialogOpen(true)
  }

  // 파일 확장자 확인 함수
  const getFileExtension = (fileName: string): string => {
    return fileName.split('.').pop()?.toLowerCase() || ''
  }

  // 뷰어 지원 파일 형식 확인
  const isViewerSupported = (fileName: string): boolean => {
    const extension = getFileExtension(fileName)
    return ['pdf', 'docx', 'doc'].includes(extension)
  }

  // 파일 클릭 핸들러 (뷰어 또는 다운로드)
  const handleFileClick = async (attachment: InformationAttachment) => {
    if (isViewerSupported(attachment.fileName)) {
      // PDF/DOCX 파일은 브라우저 내장 뷰어로 열기
      // 동적으로 quickPreview 함수 import
      const { quickPreview } = await import('@/lib/file-download')
      await quickPreview(attachment.filePath, attachment.fileName)
    } else {
      // 기타 파일은 다운로드
      await handleDownload(attachment)
    }
  }

  // 파일 다운로드 핸들러
  const handleDownload = async (attachment: InformationAttachment) => {
    try {
      // 동적으로 downloadFile 함수 import
      const { downloadFile } = await import('@/lib/file-download')
      
      await downloadFile(
        attachment.filePath,
        attachment.fileName,
        {
          action: 'download',
          showToast: true,
          showSuccessToast: true
        }
      )
    } catch (error) {
      console.error('파일 다운로드 실패:', error)
    }
  }




  
  return (
    <>
      <Dialog open={isOpen} onOpenChange={handleDialogOpen}>
        <DialogTrigger asChild>
          <Button 
            variant={variant} 
            size={size} 
            className={className}
            title="안내사항"
          >
            <Info className="h-4 w-4" />
            {size !== "icon" && <span className="ml-1">안내사항</span>}
          </Button>
        </DialogTrigger>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <div>
                  <DialogTitle></DialogTitle>
                </div>
              </div>
            </div>
          </DialogHeader>
          
          <div className="mt-4">
            {isLoading ? (
              <div className="flex items-center justify-center py-12">
                <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
                <span className="ml-2 text-muted-foreground">정보를 불러오는 중...</span>
              </div>
            ) : (
              <div className="space-y-6">
                {/* 공지사항 섹션 */}
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <h4 className="font-semibold">공지사항</h4>
                    {notices.length > 0 && (
                      <span className="text-xs text-muted-foreground">{notices.length}개</span>
                    )}
                  </div>
                  {notices.length > 0 ? (
                    <div className="max-h-60 overflow-y-auto border rounded-lg bg-muted/50 p-2">
                      <div className="space-y-2">
                        {notices.map((notice) => (
                          <div
                            key={notice.id}
                            className="p-3 bg-white border rounded-lg hover:bg-muted/50 cursor-pointer transition-colors"
                            onClick={() => handleNoticeClick(notice)}
                          >
                            <div className="space-y-1">
                              <h5 className="font-medium text-sm line-clamp-2">
                                {notice.title}
                              </h5>
                              <div className="flex items-center gap-3 text-xs text-muted-foreground">
                                <span>{formatDate(notice.createdAt, "KR")}</span>
                                {notice.authorName && (
                                  <span>{notice.authorName}</span>
                                )}
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  ) : (
                    <div className="bg-muted/50 border rounded-lg p-4">
                      <div className="text-center text-muted-foreground">
                        공지사항이 없습니다
                      </div>
                    </div>
                  )}
                </div>

                {/* 안내사항 컨텐츠 */}
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <h4 className="font-semibold">안내사항</h4>
                    {hasEditPermission && information && (
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={handleEditClick}
                        className="flex items-center gap-2 mr-2"
                      >
                        <Edit className="h-4 w-4" />
                        편집
                      </Button>
                    )}
                  </div>
                  <div className="bg-muted/50 border rounded-lg p-4">
                    {information?.informationContent ? (
                      <div className="space-y-3">
                        <div className="text-sm text-muted-foreground whitespace-pre-wrap max-h-40 overflow-y-auto">
                          {information.informationContent}
                        </div>
                        <div className="flex items-center justify-between text-xs text-muted-foreground border-t pt-2">
                          <div className="flex items-center gap-4">
                            <span>
                              <strong>수정자:</strong> {information.updatedByName || '시스템'}
                            </span>
                            <span>
                              <strong>수정일:</strong> {formatDate(information.updatedAt, "KR")}
                            </span>
                          </div>
                        </div>
                      </div>
                    ) : (
                      <div className="text-center text-muted-foreground">
                        안내사항이 없습니다
                      </div>
                    )}
                  </div>
                </div>

                {/* 첨부파일 */}
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <h4 className="font-semibold">첨부파일</h4>
                    {information?.attachments && information.attachments.length > 0 && (
                      <span className="text-xs text-muted-foreground">{information.attachments.length}개</span>
                    )}
                  </div>
                  <div className="bg-muted/50 border rounded-lg p-4">
                    {information?.attachments && information.attachments.length > 0 ? (
                      <div className="space-y-3">
                        {information.attachments.map((attachment) => (
                          <div 
                            key={attachment.id} 
                            className="flex items-center justify-between p-3 bg-white rounded border"
                          >
                            <div 
                              className="flex-1"
                            >
                              <div className="text-sm font-medium flex items-center gap-2">
                                {attachment.fileName}
                              
                              </div>
                              {attachment.fileSize && (
                                <div className="text-xs text-muted-foreground mt-1">
                                  {prettyBytes(Number(attachment.fileSize))}
                                </div>
                              )}
                            </div>
                            <div className="flex gap-2">
                              {isViewerSupported(attachment.fileName) && (
                                <Button
                                  size="sm"
                                  variant="outline"
                                  onClick={() => handleFileClick(attachment)}
                                  className="flex items-center gap-1"
                                >
                                  <EyeIcon className="h-3 w-3" />
                                  미리보기
                                </Button>
                              )}
                            <Button
                              size="sm"
                              variant="outline"
                              
                              onClick={() => handleDownload(attachment)}
                              className="flex items-center gap-1"
                            >
                              <Download className="h-3 w-3" />
                              다운로드
                            </Button>
                            </div>
                          </div>
                        ))}
                      </div>
                    ) : (
                      <div className="text-center text-muted-foreground">
                        첨부파일이 없습니다
                      </div>
                    )}
                  </div>
                </div>
              </div>
            )}
          </div>
        </DialogContent>
      </Dialog>

      {/* 공지사항 보기 다이얼로그 */}
      <NoticeViewDialog
        open={isNoticeViewDialogOpen}
        onOpenChange={setIsNoticeViewDialogOpen}
        notice={selectedNotice}
      />

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

      {/* 강제 모달 공지사항 다이얼로그 */}
      <Dialog open={isForceModalOpen} onOpenChange={handleForceModalClose}>
        <DialogContent className="max-w-2xl max-h-[80vh]">
          <DialogHeader>
            <div className="flex items-center gap-2">
              <AlertCircle className="h-5 w-5 text-blue-500" />
              <DialogTitle className="text-xl">
                공지사항
              </DialogTitle>
              <Badge variant="outline">
                필독
              </Badge>
            </div>
            <DialogDescription>
              중요한 공지사항을 확인해주세요.
            </DialogDescription>
          </DialogHeader>

          {forceModalNotice && (
            <div className="space-y-4">
              {/* 공지사항 정보 헤더 */}
              <div className="bg-muted/50 rounded-lg p-4">
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <h3 className="font-semibold text-lg mb-2">
                      {forceModalNotice.title}
                    </h3>
                    <div className="flex items-center gap-4 text-sm text-muted-foreground">
                      <div className="flex items-center gap-1">
                        <User className="h-4 w-4" />
                        {forceModalNotice.authorName || "알 수 없음"}
                      </div>
                      <div className="flex items-center gap-1">
                        <Calendar className="h-4 w-4" />
                        {formatDate(forceModalNotice.createdAt, "KR")}
                      </div>
                      {forceModalNotice.pagePath && (
                        <Badge variant="secondary" className="text-xs">
                          {forceModalNotice.pagePath}
                        </Badge>
                      )}
                    </div>
                  </div>
                </div>
              </div>

              <Separator />

              {/* 공지사항 내용 */}
              <ScrollArea className="h-[300px] w-full">
                <div
                  className="prose prose-sm max-w-none"
                  dangerouslySetInnerHTML={{
                    __html: forceModalNotice.content || ""
                  }}
                />
              </ScrollArea>

              {/* 유효기간 정보 */}
              {(forceModalNotice.startAt || forceModalNotice.endAt) && (
                <>
                  <Separator />
                  <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <Clock className="h-4 w-4" />
                    <span>유효기간:</span>
                    {forceModalNotice.startAt && (
                      <span>{formatDate(forceModalNotice.startAt, "KR")}</span>
                    )}
                    {forceModalNotice.startAt && forceModalNotice.endAt && <span> ~ </span>}
                    {forceModalNotice.endAt && (
                      <span>{formatDate(forceModalNotice.endAt, "KR")}</span>
                    )}
                  </div>
                </>
              )}

              {/* '다시 보지 않기' 설정 */}
              <div className="flex items-center space-x-2 p-4 bg-muted/30 rounded-lg">
                <Checkbox
                  id="forceModalDontShow"
                  checked={forceModalDontShow}
                  onCheckedChange={handleForceModalDontShowChange}
                />
                <label
                  htmlFor="forceModalDontShow"
                  className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                >
                  다시 보지 않기
                </label>
              </div>
            </div>
          )}

          {/* 하단 버튼들 */}
          <div className="flex items-center justify-end pt-4">
            <Button onClick={handleForceModalClose}>
              확인
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* PDFTron 뷰어 다이얼로그 - 주석 처리 (브라우저 내장 뷰어 사용) */}
      {/* <PDFTronViewerDialog
        open={viewerDialogOpen}
        onOpenChange={setViewerDialogOpen}
        fileUrl={selectedFile?.filePath}
        fileName={selectedFile?.fileName}
      /> */}
    </>
  )
}