summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--app/[lng]/evcp/(evcp)/information/page.tsx45
-rw-r--r--components/information/information-button.tsx259
-rw-r--r--config/informationColumnsConfig.ts64
-rw-r--r--config/menuConfig.ts9
-rw-r--r--lib/information/repository.ts190
-rw-r--r--lib/information/service.ts343
-rw-r--r--lib/information/table/add-information-dialog.tsx329
-rw-r--r--lib/information/table/delete-information-dialog.tsx125
-rw-r--r--lib/information/table/information-table-columns.tsx248
-rw-r--r--lib/information/table/information-table-toolbar-actions.tsx25
-rw-r--r--lib/information/table/information-table.tsx148
-rw-r--r--lib/information/table/update-information-dialog.tsx376
-rw-r--r--lib/information/validations.ts89
-rw-r--r--lib/menu-list/servcie.ts5
14 files changed, 2252 insertions, 3 deletions
diff --git a/app/[lng]/evcp/(evcp)/information/page.tsx b/app/[lng]/evcp/(evcp)/information/page.tsx
new file mode 100644
index 00000000..4027ab8a
--- /dev/null
+++ b/app/[lng]/evcp/(evcp)/information/page.tsx
@@ -0,0 +1,45 @@
+import * as React from "react"
+import type { Metadata } from "next"
+import { unstable_noStore as noStore } from "next/cache"
+
+import { Shell } from "@/components/shell"
+import { getInformationLists } from "@/lib/information/service"
+import { InformationTable } from "@/lib/information/table/information-table"
+import { searchParamsInformationCache } from "@/lib/information/validations"
+import type { SearchParams } from "@/types/table"
+import { InformationButton } from "@/components/information/information-button"
+
+export const metadata: Metadata = {
+ title: "인포메이션 관리",
+ description: "페이지별 도움말 및 첨부파일을 관리합니다.",
+}
+
+interface InformationPageProps {
+ searchParams: Promise<SearchParams>
+}
+
+export default async function InformationPage({ searchParams }: InformationPageProps) {
+ noStore()
+
+ const search = await searchParamsInformationCache.parse(await searchParams)
+
+ const informationPromise = getInformationLists(search)
+
+ return (
+ <Shell className="gap-2">
+ <div className="flex items-center justify-between space-y-2">
+ <div className="flex items-center justify-between space-y-2">
+ <div>
+ <div className="flex items-center gap-2">
+ <h2 className="text-2xl font-bold tracking-tight">
+ 도움말 관리
+ </h2>
+ <InformationButton pageCode="evcp/information" />
+ </div>
+ </div>
+ </div>
+ </div>
+ <InformationTable promises={informationPromise} />
+ </Shell>
+ )
+} \ No newline at end of file
diff --git a/components/information/information-button.tsx b/components/information/information-button.tsx
new file mode 100644
index 00000000..da0de548
--- /dev/null
+++ b/components/information/information-button.tsx
@@ -0,0 +1,259 @@
+"use client"
+
+import React, { useState, useEffect } from "react"
+import { Info, Download, Edit } from "lucide-react"
+import { Button } from "@/components/ui/button"
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog"
+import { getCachedPageInformation, getCachedEditPermission } from "@/lib/information/service"
+import { UpdateInformationDialog } from "@/lib/information/table/update-information-dialog"
+import type { PageInformation } from "@/db/schema/information"
+import { useSession } from "next-auth/react"
+
+interface InformationButtonProps {
+ pageCode: string
+ className?: string
+ variant?: "default" | "outline" | "ghost" | "secondary"
+ size?: "default" | "sm" | "lg" | "icon"
+}
+
+export function InformationButton({
+ pageCode,
+ className,
+ variant = "ghost",
+ size = "icon"
+}: InformationButtonProps) {
+ const { data: session } = useSession()
+ const [information, setInformation] = useState<PageInformation | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+ const [isOpen, setIsOpen] = useState(false)
+ const [hasEditPermission, setHasEditPermission] = useState(false)
+ const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
+
+ useEffect(() => {
+ if (isOpen && !information) {
+ loadInformation()
+ }
+ }, [isOpen, information])
+
+ // 편집 권한 확인
+ useEffect(() => {
+ const checkEditPermission = async () => {
+ if (session?.user?.id) {
+ try {
+ const permission = await getCachedEditPermission(pageCode, session.user.id)
+ setHasEditPermission(permission)
+ } catch (error) {
+ console.error("Failed to check edit permission:", error)
+ setHasEditPermission(false)
+ }
+ }
+ }
+
+ checkEditPermission()
+ }, [pageCode, session?.user?.id])
+
+ const loadInformation = async () => {
+ setIsLoading(true)
+ try {
+ const data = await getCachedPageInformation(pageCode)
+ setInformation(data)
+ } catch (error) {
+ console.error("Failed to load information:", error)
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ const handleDownload = () => {
+ 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 handleEditClick = () => {
+ setIsEditDialogOpen(true)
+ }
+
+ const handleEditClose = () => {
+ setIsEditDialogOpen(false)
+ refreshInformation()
+ }
+
+ const refreshInformation = () => {
+ // 편집 후 정보 다시 로드
+ setInformation(null)
+ if (isOpen) {
+ loadInformation()
+ }
+ // 캐시 무효화를 위해 다시 확인
+ setTimeout(() => {
+ loadInformation()
+ }, 500)
+ }
+
+ // 인포메이션이 없으면 버튼을 숨김
+ const [hasInformation, setHasInformation] = useState<boolean | null>(null)
+
+ useEffect(() => {
+ const checkInformation = async () => {
+ try {
+ const data = await getCachedPageInformation(pageCode)
+ setHasInformation(!!data)
+ } catch {
+ setHasInformation(false)
+ }
+ }
+ checkInformation()
+ }, [pageCode])
+
+ // 인포메이션이 없으면 버튼을 숨김
+ if (hasInformation === false) {
+ return null
+ }
+
+ return (
+ <>
+ <Dialog open={isOpen} onOpenChange={setIsOpen}>
+ <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">
+ {/* <Info className="h-5 w-5" /> */}
+ <div>
+ <DialogTitle>{information?.title || "페이지 정보"}</DialogTitle>
+ <DialogDescription>{information?.pageName}</DialogDescription>
+ </div>
+ </div>
+ {hasEditPermission && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleEditClick}
+ className="flex items-center gap-2 mr-2"
+ >
+ <Edit className="h-4 w-4" />
+ 편집
+ </Button>
+ )}
+ </div>
+ </DialogHeader>
+
+ <div className="mt-4 space-y-6">
+ {isLoading ? (
+ <div className="flex items-center justify-center py-8">
+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
+ </div>
+ ) : information ? (
+ <>
+ {/* 공지사항 */}
+ {(information.noticeTitle || information.noticeContent) && (
+ <div className="space-y-4">
+ <div className="flex items-center gap-2">
+ <h4 className="font-semibold text-xl">공지사항</h4>
+ </div>
+ <div className="bg-blue-50 border-2 border-blue-200 rounded-xl p-6">
+ {information.noticeTitle && (
+ <div className="text-base font-semibold mb-4">
+ 제목: {information.noticeTitle}
+ </div>
+ )}
+ {information.noticeContent && (
+ <div className="bg-white border-2 border-blue-200 rounded-lg p-4 max-h-48 overflow-y-auto">
+ <div className="text-base whitespace-pre-wrap leading-relaxed">
+ {information.noticeContent}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* 페이지 정보 */}
+ <div className="space-y-3">
+ <h4 className="font-medium text-lg">도움말</h4>
+ <div className="bg-gray-50 border rounded-lg p-4">
+ <div className="text-sm text-gray-600 whitespace-pre-wrap max-h-40 overflow-y-auto">
+ {information.description || "페이지 설명이 없습니다."}
+ </div>
+ </div>
+ </div>
+
+ {/* 첨부파일 */}
+ <div className="space-y-3">
+ <h4 className="font-medium text-lg">첨부파일</h4>
+ {information.attachmentFileName ? (
+ <div className="bg-gray-50 border rounded-lg p-4">
+ <div className="flex items-center justify-between p-3 bg-white rounded border">
+ <div className="flex-1">
+ <div className="text-sm font-medium">
+ {information.attachmentFileName}
+ </div>
+ {information.attachmentFileSize && (
+ <div className="text-xs text-gray-500 mt-1">
+ {information.attachmentFileSize}
+ </div>
+ )}
+ </div>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={handleDownload}
+ className="flex items-center gap-1"
+ >
+ <Download className="h-3 w-3" />
+ 다운로드
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <div className="text-center py-6 text-gray-500 bg-gray-50 rounded-lg">
+ <Download className="h-6 w-6 mx-auto mb-2 text-gray-400" />
+ <p className="text-sm">첨부된 파일이 없습니다.</p>
+ </div>
+ )}
+ </div>
+ </>
+ ) : (
+ <div className="text-center py-8 text-gray-500">
+ 이 페이지에 대한 정보가 없습니다.
+ </div>
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
+
+ {/* 편집 다이얼로그 */}
+ {information && (
+ <UpdateInformationDialog
+ open={isEditDialogOpen}
+ onOpenChange={setIsEditDialogOpen}
+ information={information}
+ onClose={handleEditClose}
+ />
+ )}
+ </>
+ )
+} \ No newline at end of file
diff --git a/config/informationColumnsConfig.ts b/config/informationColumnsConfig.ts
new file mode 100644
index 00000000..6357cfa3
--- /dev/null
+++ b/config/informationColumnsConfig.ts
@@ -0,0 +1,64 @@
+import { PageInformation } from "@/db/schema/information"
+
+export interface InformationColumnConfig {
+ id: keyof PageInformation
+ label: string
+ group?: string
+ excelHeader?: string
+ type?: string
+}
+
+export const informationColumnsConfig: InformationColumnConfig[] = [
+ {
+ id: "pageCode",
+ label: "페이지 코드",
+ excelHeader: "페이지 코드",
+ },
+ {
+ id: "pageName",
+ label: "페이지명",
+ excelHeader: "페이지명",
+ },
+ {
+ id: "title",
+ label: "제목",
+ excelHeader: "제목",
+ },
+ {
+ id: "description",
+ label: "설명",
+ excelHeader: "설명",
+ },
+ {
+ id: "noticeTitle",
+ label: "공지사항 제목",
+ excelHeader: "공지사항 제목",
+ },
+ {
+ id: "noticeContent",
+ label: "공지사항 내용",
+ excelHeader: "공지사항 내용",
+ },
+ {
+ id: "attachmentFileName",
+ label: "첨부파일",
+ excelHeader: "첨부파일",
+ },
+ {
+ id: "isActive",
+ label: "상태",
+ excelHeader: "상태",
+ },
+ {
+ id: "createdAt",
+ label: "생성일",
+ excelHeader: "생성일",
+ type: "date",
+ },
+ {
+ id: "updatedAt",
+ label: "수정일",
+ excelHeader: "수정일",
+ type: "date",
+ },
+] \ No newline at end of file
diff --git a/config/menuConfig.ts b/config/menuConfig.ts
index 864b5dc9..d9b272e1 100644
--- a/config/menuConfig.ts
+++ b/config/menuConfig.ts
@@ -342,16 +342,21 @@ export const mainNav: MenuSection[] = [
useGrouping: true, // 그룹핑 적용
items: [
{
+ title: "인포메이션 관리",
+ href: "/evcp/information",
+ group: "정보시스템"
+ },
+ {
title: "메뉴 리스트",
href: "/evcp/menu-list",
// icon: "FileText",
- // group: "인터페이스"
+ group: "메뉴"
},
{
title: "메뉴 접근제어",
href: "/evcp/menu-access",
// icon: "FileText",
- // group: "인터페이스"
+ group: "메뉴"
},
{
title: "인터페이스 목록 관리",
diff --git a/lib/information/repository.ts b/lib/information/repository.ts
new file mode 100644
index 00000000..2a3bc1c0
--- /dev/null
+++ b/lib/information/repository.ts
@@ -0,0 +1,190 @@
+import { asc, desc, eq, ilike, and, count, sql } from "drizzle-orm"
+import db from "@/db/db"
+import { pageInformation, type PageInformation, type NewPageInformation } from "@/db/schema/information"
+import type { GetInformationSchema } from "./validations"
+import { PgTransaction } from "drizzle-orm/pg-core"
+
+// 최신 패턴: 트랜잭션을 지원하는 인포메이션 조회
+export async function selectInformationLists(
+ tx: PgTransaction<any, any, any>,
+ params: {
+ where?: ReturnType<typeof and>
+ orderBy?: (ReturnType<typeof asc> | ReturnType<typeof desc>)[]
+ offset?: number
+ limit?: number
+ }
+) {
+ const { where, orderBy, offset = 0, limit = 10 } = params
+
+ return tx
+ .select()
+ .from(pageInformation)
+ .where(where)
+ .orderBy(...(orderBy ?? [desc(pageInformation.createdAt)]))
+ .offset(offset)
+ .limit(limit)
+}
+
+// 최신 패턴: 트랜잭션을 지원하는 카운트 조회
+export async function countInformationLists(
+ tx: PgTransaction<any, any, any>,
+ where?: ReturnType<typeof and>
+) {
+ const res = await tx
+ .select({ count: count() })
+ .from(pageInformation)
+ .where(where)
+
+ return res[0]?.count ?? 0
+}
+
+// 기존 패턴 (하위 호환성을 위해 유지)
+export async function selectInformation(input: GetInformationSchema) {
+ const { page, per_page = 50, sort, pageCode, pageName, isActive, from, to } = input
+
+ const conditions = []
+
+ if (pageCode) {
+ conditions.push(ilike(pageInformation.pageCode, `%${pageCode}%`))
+ }
+
+ if (pageName) {
+ conditions.push(ilike(pageInformation.pageName, `%${pageName}%`))
+ }
+
+ if (isActive !== null) {
+ conditions.push(eq(pageInformation.isActive, isActive))
+ }
+
+ if (from) {
+ conditions.push(sql`${pageInformation.createdAt} >= ${from}`)
+ }
+
+ if (to) {
+ conditions.push(sql`${pageInformation.createdAt} <= ${to}`)
+ }
+
+ const offset = (page - 1) * per_page
+
+ // 정렬 설정
+ let orderBy = desc(pageInformation.createdAt);
+
+ if (sort && Array.isArray(sort) && sort.length > 0) {
+ const sortItem = sort[0];
+ if (sortItem.id === "createdAt") {
+ orderBy = sortItem.desc ? desc(pageInformation.createdAt) : asc(pageInformation.createdAt);
+ }
+ }
+
+ const whereClause = conditions.length > 0 ? and(...conditions) : undefined
+
+ const data = await db
+ .select()
+ .from(pageInformation)
+ .where(whereClause)
+ .orderBy(orderBy)
+ .limit(per_page)
+ .offset(offset)
+
+ return data
+}
+
+// 기존 패턴: 인포메이션 총 개수 조회
+export async function countInformation(input: GetInformationSchema) {
+ const { pageCode, pageName, isActive, from, to } = input
+
+ const conditions = []
+
+ if (pageCode) {
+ conditions.push(ilike(pageInformation.pageCode, `%${pageCode}%`))
+ }
+
+ if (pageName) {
+ conditions.push(ilike(pageInformation.pageName, `%${pageName}%`))
+ }
+
+ if (isActive !== null) {
+ conditions.push(eq(pageInformation.isActive, isActive))
+ }
+
+ if (from) {
+ conditions.push(sql`${pageInformation.createdAt} >= ${from}`)
+ }
+
+ if (to) {
+ conditions.push(sql`${pageInformation.createdAt} <= ${to}`)
+ }
+
+ const whereClause = conditions.length > 0 ? and(...conditions) : undefined
+
+ const result = await db
+ .select({ count: count() })
+ .from(pageInformation)
+ .where(whereClause)
+
+ return result[0]?.count ?? 0
+}
+
+// 페이지 코드별 인포메이션 조회 (활성화된 것만)
+export async function getInformationByPageCode(pageCode: string): Promise<PageInformation | null> {
+ const result = await db
+ .select()
+ .from(pageInformation)
+ .where(and(
+ eq(pageInformation.pageCode, pageCode),
+ eq(pageInformation.isActive, true)
+ ))
+ .limit(1)
+
+ return result[0] || null
+}
+
+// 인포메이션 생성
+export async function insertInformation(data: NewPageInformation): Promise<PageInformation> {
+ const result = await db
+ .insert(pageInformation)
+ .values(data)
+ .returning()
+
+ return result[0]
+}
+
+// 인포메이션 수정
+export async function updateInformation(id: number, data: Partial<NewPageInformation>): Promise<PageInformation | null> {
+ const result = await db
+ .update(pageInformation)
+ .set({ ...data, updatedAt: new Date() })
+ .where(eq(pageInformation.id, id))
+ .returning()
+
+ return result[0] || null
+}
+
+// 인포메이션 삭제
+export async function deleteInformationById(id: number): Promise<boolean> {
+ const result = await db
+ .delete(pageInformation)
+ .where(eq(pageInformation.id, id))
+
+ return (result.rowCount ?? 0) > 0
+}
+
+// 인포메이션 다중 삭제
+export async function deleteInformationByIds(ids: number[]): Promise<number> {
+ const result = await db
+ .delete(pageInformation)
+ .where(sql`${pageInformation.id} = ANY(${ids})`)
+
+ return result.rowCount ?? 0
+}
+
+// ID로 인포메이션 조회
+export async function getInformationById(id: number): Promise<PageInformation | null> {
+ const result = await db
+ .select()
+ .from(pageInformation)
+ .where(eq(pageInformation.id, id))
+ .limit(1)
+
+ return result[0] || null
+} \ No newline at end of file
diff --git a/lib/information/service.ts b/lib/information/service.ts
new file mode 100644
index 00000000..8f1e5679
--- /dev/null
+++ b/lib/information/service.ts
@@ -0,0 +1,343 @@
+"use server"
+
+import { revalidateTag, unstable_noStore } from "next/cache"
+import { getErrorMessage } from "@/lib/handle-error"
+import { unstable_cache } from "@/lib/unstable-cache"
+import { filterColumns } from "@/lib/filter-columns"
+import { asc, desc, ilike, and, or, eq } from "drizzle-orm"
+import db from "@/db/db"
+import { pageInformation, menuAssignments } from "@/db/schema"
+
+import type {
+ CreateInformationSchema,
+ UpdateInformationSchema,
+ GetInformationSchema
+} from "./validations"
+
+import {
+ selectInformation,
+ countInformation,
+ getInformationByPageCode,
+ insertInformation,
+ updateInformation,
+ deleteInformationById,
+ deleteInformationByIds,
+ getInformationById,
+ selectInformationLists,
+ countInformationLists
+} from "./repository"
+
+import type { PageInformation } from "@/db/schema/information"
+
+// 최신 패턴: 고급 필터링과 캐싱을 지원하는 인포메이션 목록 조회
+export async function getInformationLists(input: GetInformationSchema) {
+ return unstable_cache(
+ async () => {
+ try {
+ const offset = (input.page - 1) * input.perPage
+
+ // 고급 필터링
+ const advancedWhere = filterColumns({
+ table: pageInformation,
+ filters: input.filters,
+ joinOperator: input.joinOperator,
+ })
+
+ // 전역 검색
+ let globalWhere
+ if (input.search) {
+ const s = `%${input.search}%`
+ globalWhere = or(
+ ilike(pageInformation.pageCode, s),
+ ilike(pageInformation.pageName, s),
+ ilike(pageInformation.title, s),
+ ilike(pageInformation.description, s)
+ )
+ }
+
+ // 기본 필터들
+ let basicWhere
+ const basicConditions = []
+
+ if (input.pageCode) {
+ basicConditions.push(ilike(pageInformation.pageCode, `%${input.pageCode}%`))
+ }
+
+ if (input.pageName) {
+ basicConditions.push(ilike(pageInformation.pageName, `%${input.pageName}%`))
+ }
+
+ if (input.title) {
+ basicConditions.push(ilike(pageInformation.title, `%${input.title}%`))
+ }
+
+ if (input.isActive !== undefined && input.isActive !== null) {
+ basicConditions.push(eq(pageInformation.isActive, input.isActive))
+ }
+
+ if (basicConditions.length > 0) {
+ basicWhere = and(...basicConditions)
+ }
+
+ // 최종 where 조건
+ const finalWhere = and(
+ advancedWhere,
+ globalWhere,
+ basicWhere
+ )
+
+ // 정렬 처리
+ const orderBy = input.sort.length > 0
+ ? input.sort.map((item) => {
+ if (item.id === "createdAt") {
+ return item.desc ? desc(pageInformation.createdAt) : asc(pageInformation.createdAt)
+ } else if (item.id === "updatedAt") {
+ return item.desc ? desc(pageInformation.updatedAt) : asc(pageInformation.updatedAt)
+ } else if (item.id === "pageCode") {
+ return item.desc ? desc(pageInformation.pageCode) : asc(pageInformation.pageCode)
+ } else if (item.id === "pageName") {
+ return item.desc ? desc(pageInformation.pageName) : asc(pageInformation.pageName)
+ } else if (item.id === "title") {
+ return item.desc ? desc(pageInformation.title) : asc(pageInformation.title)
+ } else if (item.id === "isActive") {
+ return item.desc ? desc(pageInformation.isActive) : asc(pageInformation.isActive)
+ } else {
+ return desc(pageInformation.createdAt) // 기본값
+ }
+ })
+ : [desc(pageInformation.createdAt)]
+
+ // 트랜잭션 내부에서 Repository 호출
+ const { data, total } = await db.transaction(async (tx) => {
+ const data = await selectInformationLists(tx, {
+ where: finalWhere,
+ orderBy,
+ offset,
+ limit: input.perPage,
+ })
+
+ const total = await countInformationLists(tx, finalWhere)
+ return { data, total }
+ })
+
+ const pageCount = Math.ceil(total / input.perPage)
+
+ return { data, pageCount, total }
+ } catch (err) {
+ console.error("Failed to get information lists:", err)
+ // 에러 발생 시 기본값 반환
+ return { data: [], pageCount: 0, total: 0 }
+ }
+ },
+ [JSON.stringify(input)], // 캐싱 키
+ {
+ revalidate: 3600,
+ tags: ["information-lists"],
+ }
+ )()
+}
+
+// 기존 패턴 (하위 호환성을 위해 유지)
+export async function getInformationList(input: Partial<GetInformationSchema> & { page: number; per_page: number }) {
+ unstable_noStore()
+
+ try {
+ const [data, total] = await Promise.all([
+ selectInformation(input as Parameters<typeof selectInformation>[0]),
+ countInformation(input as Parameters<typeof countInformation>[0])
+ ])
+
+ const pageCount = Math.ceil(total / input.per_page)
+
+ return {
+ data,
+ pageCount,
+ total
+ }
+ } catch (error) {
+ console.error("Failed to get information list:", error)
+ throw new Error(getErrorMessage(error))
+ }
+}
+
+// 페이지별 인포메이션 조회 (일반 사용자용)
+export async function getPageInformation(pageCode: string): Promise<PageInformation | null> {
+ try {
+ return await getInformationByPageCode(pageCode)
+ } catch (error) {
+ console.error(`Failed to get information for page ${pageCode}:`, error)
+ return null
+ }
+}
+
+// 캐시된 페이지별 인포메이션 조회
+export const getCachedPageInformation = unstable_cache(
+ async (pageCode: string) => getPageInformation(pageCode),
+ ["page-information"],
+ {
+ tags: ["page-information"],
+ revalidate: 3600, // 1시간 캐시
+ }
+)
+
+// 인포메이션 생성
+export async function createInformation(input: CreateInformationSchema) {
+ try {
+ const result = await insertInformation(input)
+
+ revalidateTag("page-information")
+ revalidateTag("information-lists")
+ revalidateTag("information-edit-permission")
+
+ return {
+ success: true,
+ data: result,
+ message: "인포메이션이 성공적으로 생성되었습니다."
+ }
+ } catch (error) {
+ console.error("Failed to create information:", error)
+ return {
+ success: false,
+ message: getErrorMessage(error)
+ }
+ }
+}
+
+// 인포메이션 수정
+export async function updateInformationData(input: UpdateInformationSchema) {
+ try {
+ const { id, ...updateData } = input
+ const result = await updateInformation(id, updateData)
+
+ if (!result) {
+ return {
+ success: false,
+ message: "인포메이션을 찾을 수 없거나 수정에 실패했습니다."
+ }
+ }
+
+ revalidateTag("page-information")
+ revalidateTag("information-lists")
+ revalidateTag("information-edit-permission") // 편집 권한 캐시 무효화
+
+ return {
+ success: true,
+ message: "인포메이션이 성공적으로 수정되었습니다."
+ }
+ } catch (error) {
+ console.error("Failed to update information:", error)
+ return {
+ success: false,
+ message: getErrorMessage(error)
+ }
+ }
+}
+
+// 인포메이션 삭제
+export async function deleteInformation(id: number) {
+ try {
+ const success = await deleteInformationById(id)
+
+ if (!success) {
+ return {
+ success: false,
+ message: "인포메이션을 찾을 수 없거나 삭제에 실패했습니다."
+ }
+ }
+
+ revalidateTag("page-information")
+ revalidateTag("information-lists")
+
+ return {
+ success: true,
+ message: "인포메이션이 성공적으로 삭제되었습니다."
+ }
+ } catch (error) {
+ console.error("Failed to delete information:", error)
+ return {
+ success: false,
+ message: getErrorMessage(error)
+ }
+ }
+}
+
+// 인포메이션 다중 삭제
+export async function deleteMultipleInformation(ids: number[]) {
+ try {
+ const deletedCount = await deleteInformationByIds(ids)
+
+ revalidateTag("page-information")
+ revalidateTag("information-lists")
+
+ return {
+ success: true,
+ deletedCount,
+ message: `${deletedCount}개의 인포메이션이 성공적으로 삭제되었습니다.`
+ }
+ } catch (error) {
+ console.error("Failed to delete multiple information:", error)
+ return {
+ success: false,
+ message: getErrorMessage(error)
+ }
+ }
+}
+
+// ID로 인포메이션 조회
+export async function getInformationDetail(id: number): Promise<PageInformation | null> {
+ try {
+ return await getInformationById(id)
+ } catch (error) {
+ console.error(`Failed to get information detail for id ${id}:`, error)
+ return null
+ }
+}
+
+// 인포메이션 편집 권한 확인
+export async function checkInformationEditPermission(pageCode: string, userId: string): Promise<boolean> {
+ try {
+ // pageCode를 menuPath로 변환 (pageCode가 menuPath의 마지막 부분이라고 가정)
+ // 예: pageCode "vendor-list" -> menuPath "/evcp/vendor-list" 또는 "/partners/vendor-list"
+ const menuPathQueries = [
+ `/evcp/${pageCode}`,
+ `/partners/${pageCode}`,
+ `/${pageCode}`, // 루트 경로
+ pageCode // 정확한 매칭
+ ]
+
+ // menu_assignments에서 해당 pageCode와 매칭되는 메뉴 찾기
+ const menuAssignment = await db
+ .select()
+ .from(menuAssignments)
+ .where(
+ or(
+ ...menuPathQueries.map(path => eq(menuAssignments.menuPath, path))
+ )
+ )
+ .limit(1)
+
+ if (menuAssignment.length === 0) {
+ // 매칭되는 메뉴가 없으면 권한 없음
+ return false
+ }
+
+ const assignment = menuAssignment[0]
+ const userIdNumber = parseInt(userId)
+
+ // 현재 사용자가 manager1 또는 manager2인지 확인
+ return assignment.manager1Id === userIdNumber || assignment.manager2Id === userIdNumber
+ } catch (error) {
+ console.error("Failed to check information edit permission:", error)
+ return false
+ }
+}
+
+// 캐시된 권한 확인
+export const getCachedEditPermission = unstable_cache(
+ async (pageCode: string, userId: string) => checkInformationEditPermission(pageCode, userId),
+ ["information-edit-permission"],
+ {
+ tags: ["information-edit-permission"],
+ revalidate: 300, // 5분 캐시
+ }
+) \ No newline at end of file
diff --git a/lib/information/table/add-information-dialog.tsx b/lib/information/table/add-information-dialog.tsx
new file mode 100644
index 00000000..a879fbfe
--- /dev/null
+++ b/lib/information/table/add-information-dialog.tsx
@@ -0,0 +1,329 @@
+"use client"
+
+import * as React from "react"
+import { zodResolver } from "@hookform/resolvers/zod"
+import { useForm } from "react-hook-form"
+import { toast } from "sonner"
+import { Loader, Upload, X } from "lucide-react"
+import { useRouter } from "next/navigation"
+
+import { Button } from "@/components/ui/button"
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} 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 { Switch } from "@/components/ui/switch"
+import { createInformation } from "@/lib/information/service"
+import { createInformationSchema, type CreateInformationSchema } from "@/lib/information/validations"
+
+interface AddInformationDialogProps {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}
+
+export function AddInformationDialog({
+ open,
+ onOpenChange,
+}: AddInformationDialogProps) {
+ const router = useRouter()
+ const [isLoading, setIsLoading] = React.useState(false)
+ const [uploadedFile, setUploadedFile] = React.useState<File | null>(null)
+
+ const form = useForm<CreateInformationSchema>({
+ resolver: zodResolver(createInformationSchema),
+ defaultValues: {
+ pageCode: "",
+ pageName: "",
+ title: "",
+ description: "",
+ noticeTitle: "",
+ noticeContent: "",
+ attachmentFileName: "",
+ attachmentFilePath: "",
+ attachmentFileSize: "",
+ isActive: true,
+ },
+ })
+
+ const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
+ const file = event.target.files?.[0]
+ if (file) {
+ setUploadedFile(file)
+ // 파일 크기를 MB 단위로 변환
+ const sizeInMB = (file.size / (1024 * 1024)).toFixed(2)
+ form.setValue("attachmentFileName", file.name)
+ form.setValue("attachmentFileSize", `${sizeInMB} MB`)
+ }
+ }
+
+ const removeFile = () => {
+ setUploadedFile(null)
+ form.setValue("attachmentFileName", "")
+ form.setValue("attachmentFilePath", "")
+ form.setValue("attachmentFileSize", "")
+ }
+
+ const uploadFile = async (file: File): Promise<string> => {
+ const formData = new FormData()
+ formData.append("file", file)
+
+ const response = await fetch("/api/upload", {
+ method: "POST",
+ body: formData,
+ })
+
+ if (!response.ok) {
+ throw new Error("파일 업로드에 실패했습니다.")
+ }
+
+ const result = await response.json()
+ return result.url
+ }
+
+ const onSubmit = async (values: CreateInformationSchema) => {
+ setIsLoading(true)
+ try {
+ const finalValues = { ...values }
+
+ // 파일이 있으면 업로드
+ if (uploadedFile) {
+ const filePath = await uploadFile(uploadedFile)
+ finalValues.attachmentFilePath = filePath
+ }
+
+ const result = await createInformation(finalValues)
+
+ if (result.success) {
+ toast.success(result.message)
+ form.reset()
+ setUploadedFile(null)
+ onOpenChange(false)
+ router.refresh()
+ } else {
+ toast.error(result.message)
+ }
+ } catch (error) {
+ toast.error("인포메이션 생성에 실패했습니다.")
+ console.error(error)
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ // 다이얼로그가 닫힐 때 폼 초기화
+ React.useEffect(() => {
+ if (!open) {
+ form.reset()
+ setUploadedFile(null)
+ }
+ }, [open, form])
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>인포메이션 추가</DialogTitle>
+ <DialogDescription>
+ 새로운 페이지 인포메이션을 추가합니다.
+ </DialogDescription>
+ </DialogHeader>
+
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
+ <div className="grid grid-cols-2 gap-4">
+ <FormField
+ control={form.control}
+ name="pageCode"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>페이지 코드</FormLabel>
+ <FormControl>
+ <Input placeholder="예: vendor-list" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="pageName"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>페이지명</FormLabel>
+ <FormControl>
+ <Input placeholder="예: 협력업체 목록" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+
+ <FormField
+ control={form.control}
+ name="title"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>제목</FormLabel>
+ <FormControl>
+ <Input placeholder="인포메이션 제목을 입력하세요" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="description"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>설명</FormLabel>
+ <FormControl>
+ <Textarea
+ placeholder="페이지 설명을 입력하세요"
+ rows={4}
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="noticeTitle"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>공지사항 제목 (선택사항)</FormLabel>
+ <FormControl>
+ <Input placeholder="공지사항 제목을 입력하세요" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="noticeContent"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>공지사항 내용 (선택사항)</FormLabel>
+ <FormControl>
+ <Textarea
+ placeholder="공지사항 내용을 입력하세요"
+ rows={3}
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <div>
+ <FormLabel>첨부파일</FormLabel>
+ <div className="mt-2">
+ {uploadedFile ? (
+ <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium">{uploadedFile.name}</span>
+ <span className="text-xs text-gray-500">
+ ({(uploadedFile.size / (1024 * 1024)).toFixed(2)} MB)
+ </span>
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={removeFile}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </div>
+ ) : (
+ <div className="border-2 border-dashed border-gray-300 rounded-lg p-4">
+ <div className="text-center">
+ <Upload className="mx-auto h-8 w-8 text-gray-400" />
+ <div className="mt-2">
+ <label
+ htmlFor="file-upload"
+ className="cursor-pointer text-sm text-blue-600 hover:text-blue-500"
+ >
+ 파일을 선택하세요
+ </label>
+ <input
+ id="file-upload"
+ type="file"
+ className="hidden"
+ onChange={handleFileSelect}
+ accept=".pdf,.doc,.docx,.xlsx,.ppt,.pptx,.txt,.zip"
+ />
+ </div>
+ <p className="text-xs text-gray-500 mt-1">
+ PDF, DOC, DOCX, XLSX, PPT, PPTX, TXT, ZIP 파일만 업로드 가능
+ </p>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ <FormField
+ control={form.control}
+ name="isActive"
+ render={({ field }) => (
+ <FormItem className="flex flex-row items-center justify-between rounded-lg border p-3">
+ <div className="space-y-0.5">
+ <FormLabel className="text-base">활성 상태</FormLabel>
+ <div className="text-sm text-muted-foreground">
+ 활성화하면 해당 페이지에서 인포메이션 버튼이 표시됩니다.
+ </div>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={isLoading}
+ >
+ 취소
+ </Button>
+ <Button type="submit" disabled={isLoading}>
+ {isLoading && <Loader className="mr-2 h-4 w-4 animate-spin" />}
+ 생성
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ )
+} \ No newline at end of file
diff --git a/lib/information/table/delete-information-dialog.tsx b/lib/information/table/delete-information-dialog.tsx
new file mode 100644
index 00000000..e36d948d
--- /dev/null
+++ b/lib/information/table/delete-information-dialog.tsx
@@ -0,0 +1,125 @@
+"use client"
+
+import * as React from "react"
+import { useRouter } from "next/navigation"
+import { toast } from "sonner"
+import { Loader, Trash2 } from "lucide-react"
+
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog"
+import { deleteInformation } from "@/lib/information/service"
+import type { PageInformation } from "@/db/schema/information"
+
+interface DeleteInformationDialogProps {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ information?: PageInformation
+ onClose: () => void
+}
+
+export function DeleteInformationDialog({
+ open,
+ onOpenChange,
+ information,
+ onClose,
+}: DeleteInformationDialogProps) {
+ const router = useRouter()
+ const [isLoading, setIsLoading] = React.useState(false)
+
+ const handleDelete = async () => {
+ if (!information) return
+
+ setIsLoading(true)
+ try {
+ const result = await deleteInformation(information.id)
+
+ if (result.success) {
+ toast.success(result.message)
+ onClose()
+ router.refresh()
+ } else {
+ toast.error(result.message)
+ }
+ } catch (error) {
+ toast.error("인포메이션 삭제에 실패했습니다.")
+ console.error(error)
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ return (
+ <AlertDialog open={open} onOpenChange={onOpenChange}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle className="flex items-center gap-2">
+ <Trash2 className="h-5 w-5 text-destructive" />
+ 인포메이션 삭제
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ 다음 인포메이션을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+
+ {information && (
+ <div className="bg-muted rounded-lg p-4 my-4">
+ <div className="space-y-2">
+ <div>
+ <span className="font-medium text-sm">페이지 코드:</span>
+ <span className="ml-2 font-mono text-sm">{information.pageCode}</span>
+ </div>
+ <div>
+ <span className="font-medium text-sm">페이지명:</span>
+ <span className="ml-2 text-sm">{information.pageName}</span>
+ </div>
+ <div>
+ <span className="font-medium text-sm">제목:</span>
+ <span className="ml-2 text-sm">{information.title}</span>
+ </div>
+ {information.noticeTitle && (
+ <div>
+ <span className="font-medium text-sm">공지사항 제목:</span>
+ <span className="ml-2 text-sm">{information.noticeTitle}</span>
+ </div>
+ )}
+ {information.noticeContent && (
+ <div>
+ <span className="font-medium text-sm">공지사항 내용:</span>
+ <span className="ml-2 text-sm text-orange-600">{information.noticeContent}</span>
+ </div>
+ )}
+ {information.attachmentFileName && (
+ <div>
+ <span className="font-medium text-sm">첨부파일:</span>
+ <span className="ml-2 text-sm">{information.attachmentFileName}</span>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
+ <AlertDialogFooter>
+ <AlertDialogCancel onClick={onClose} disabled={isLoading}>
+ 취소
+ </AlertDialogCancel>
+ <AlertDialogAction
+ onClick={handleDelete}
+ disabled={isLoading}
+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
+ >
+ {isLoading && <Loader className="mr-2 h-4 w-4 animate-spin" />}
+ 삭제
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )
+} \ No newline at end of file
diff --git a/lib/information/table/information-table-columns.tsx b/lib/information/table/information-table-columns.tsx
new file mode 100644
index 00000000..f84fd2f9
--- /dev/null
+++ b/lib/information/table/information-table-columns.tsx
@@ -0,0 +1,248 @@
+"use client"
+
+import * as React from "react"
+import type { ColumnDef } from "@tanstack/react-table"
+import { Badge } from "@/components/ui/badge"
+import { Button } from "@/components/ui/button"
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu"
+import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
+import type { DataTableRowAction } from "@/types/table"
+import type { PageInformation } from "@/db/schema/information"
+import { formatDate } from "@/lib/utils"
+import { Ellipsis, FileText, Download } from "lucide-react"
+import { informationColumnsConfig } from "@/config/informationColumnsConfig"
+
+interface GetColumnsProps {
+ setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<PageInformation> | null>>
+}
+
+/**
+ * tanstack table 컬럼 정의 (중첩 헤더 버전)
+ */
+export function getInformationColumns({ setRowAction }: GetColumnsProps): ColumnDef<PageInformation>[] {
+ // // ----------------------------------------------------------------
+ // // 1) Select 컬럼 (체크박스)
+ // // ----------------------------------------------------------------
+ // const selectColumn: ColumnDef<PageInformation> = {
+ // id: "select",
+ // header: ({ table }) => (
+ // <Checkbox
+ // checked={
+ // table.getIsAllPageRowsSelected() ||
+ // (table.getIsSomePageRowsSelected() && "indeterminate")
+ // }
+ // onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
+ // aria-label="Select all"
+ // className="translate-y-0.5"
+ // />
+ // ),
+ // cell: ({ row }) => (
+ // <Checkbox
+ // checked={row.getIsSelected()}
+ // onCheckedChange={(value) => row.toggleSelected(!!value)}
+ // aria-label="Select row"
+ // className="translate-y-0.5"
+ // />
+ // ),
+ // enableSorting: false,
+ // enableHiding: false,
+ // }
+
+ // ----------------------------------------------------------------
+ // 2) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성
+ // ----------------------------------------------------------------
+ const groupMap: Record<string, ColumnDef<PageInformation>[]> = {}
+
+ informationColumnsConfig.forEach((cfg) => {
+ // 만약 group가 없으면 "_noGroup" 처리
+ const groupName = cfg.group || "_noGroup"
+
+ if (!groupMap[groupName]) {
+ groupMap[groupName] = []
+ }
+
+ // child column 정의
+ const childCol: ColumnDef<PageInformation> = {
+ accessorKey: cfg.id,
+ enableResizing: cfg.id === "description" || cfg.id === "noticeContent" ? false : true,
+ size: cfg.id === "description" || cfg.id === "noticeContent" ? 200 : undefined,
+ minSize: cfg.id === "description" || cfg.id === "noticeContent" ? 200 : undefined,
+ maxSize: cfg.id === "description" || cfg.id === "noticeContent" ? 200 : undefined,
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title={cfg.label} />
+ ),
+ meta: {
+ excelHeader: cfg.excelHeader,
+ group: cfg.group,
+ type: cfg.type,
+ },
+ cell: ({ row }) => {
+ const value = row.getValue(cfg.id)
+
+ if (cfg.id === "pageCode") {
+ return <div className=" text-sm">{value as string}</div>
+ }
+
+ if (cfg.id === "pageName") {
+ return <div className="max-w-4 truncate font-medium">{value as string}</div>
+ }
+
+ if (cfg.id === "title") {
+ return <div className="max-w-4 truncate">{value as string}</div>
+ }
+
+ if (cfg.id === "description") {
+ return (
+ <div className="truncate text-muted-foreground" style={{ width: '200px', maxWidth: '200px' }}>
+ {value as string}
+ </div>
+ )
+ }
+
+ if (cfg.id === "noticeTitle") {
+ const noticeTitle = value as string
+ if (!noticeTitle) {
+ return <span className="text-muted-foreground">-</span>
+ }
+ return <div className="max-w-xs truncate">{noticeTitle}</div>
+ }
+
+ if (cfg.id === "noticeContent") {
+ const noticeContent = value as string
+ if (!noticeContent) {
+ return <span className="text-muted-foreground">-</span>
+ }
+ return (
+ <div className="truncate text-muted-foreground" style={{ width: '200px', maxWidth: '200px' }}>
+ {noticeContent}
+ </div>
+ )
+ }
+
+ if (cfg.id === "attachmentFileName") {
+ const fileName = value as string
+ if (!fileName) {
+ return <span className="text-muted-foreground">-</span>
+ }
+ return (
+ <div className="flex items-center gap-1">
+ <FileText className="h-3 w-3" />
+ <span className="text-sm truncate max-w-32" title={fileName}>
+ {fileName}
+ </span>
+ </div>
+ )
+ }
+
+ if (cfg.id === "isActive") {
+ return (
+ <Badge variant={value ? "default" : "secondary"}>
+ {value ? "활성" : "비활성"}
+ </Badge>
+ )
+ }
+
+ if (cfg.id === "createdAt" || cfg.id === "updatedAt") {
+ const dateVal = value as Date
+ return formatDate(dateVal)
+ }
+
+ return value ?? ""
+ },
+ }
+
+ groupMap[groupName].push(childCol)
+ })
+
+ // ----------------------------------------------------------------
+ // 3) groupMap에서 실제 상위 컬럼(그룹)을 만들기
+ // ----------------------------------------------------------------
+ const nestedColumns: ColumnDef<PageInformation>[] = []
+
+ // 순서를 고정하고 싶다면 group 순서를 미리 정의하거나 sort해야 함
+ // 여기서는 그냥 Object.entries 순서
+ Object.entries(groupMap).forEach(([groupName, colDefs]) => {
+ if (groupName === "_noGroup") {
+ // 그룹 없음 → 그냥 최상위 레벨 컬럼
+ nestedColumns.push(...colDefs)
+ } else {
+ // 상위 컬럼
+ nestedColumns.push({
+ id: groupName,
+ header: groupName, // "기본 정보", "공지사항" 등
+ columns: colDefs,
+ })
+ }
+ })
+
+ // ----------------------------------------------------------------
+ // 4) Actions 컬럼
+ // ----------------------------------------------------------------
+ const actionsColumn: ColumnDef<PageInformation> = {
+ id: "actions",
+ cell: ({ row }) => (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ aria-label="Open menu"
+ variant="ghost"
+ className="flex size-8 p-0 data-[state=open]:bg-muted"
+ >
+ <Ellipsis className="size-4" aria-hidden="true" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-40">
+ <DropdownMenuItem
+ onSelect={() => setRowAction({ row, type: "update" })}
+ >
+ 수정
+ </DropdownMenuItem>
+ {row.original.attachmentFileName && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => {
+ if (row.original.attachmentFilePath) {
+ const link = document.createElement('a')
+ link.href = row.original.attachmentFilePath
+ link.download = row.original.attachmentFileName || ''
+ document.body.appendChild(link)
+ link.click()
+ document.body.removeChild(link)
+ }
+ }}
+ >
+ <Download className="mr-2 h-4 w-4" />
+ 다운로드
+ </DropdownMenuItem>
+ </>
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => setRowAction({ row, type: "delete" })}
+ className="text-destructive"
+ >
+ 삭제
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ),
+ enableSorting: false,
+ enableHiding: false,
+ }
+
+ // ----------------------------------------------------------------
+ // 5) 최종 컬럼 배열: select, nestedColumns, actions
+ // ----------------------------------------------------------------
+ return [
+ // selectColumn,
+ ...nestedColumns,
+ actionsColumn,
+ ]
+} \ No newline at end of file
diff --git a/lib/information/table/information-table-toolbar-actions.tsx b/lib/information/table/information-table-toolbar-actions.tsx
new file mode 100644
index 00000000..5d8fff3a
--- /dev/null
+++ b/lib/information/table/information-table-toolbar-actions.tsx
@@ -0,0 +1,25 @@
+"use client"
+
+import { type Table } from "@tanstack/react-table"
+import { Plus } from "lucide-react"
+
+import { Button } from "@/components/ui/button"
+import type { PageInformation } from "@/db/schema/information"
+
+interface InformationTableToolbarActionsProps {
+ table: Table<PageInformation>
+ onAdd: () => void
+}
+
+export function InformationTableToolbarActions({
+ onAdd,
+}: InformationTableToolbarActionsProps) {
+ return (
+ <div className="flex items-center gap-2">
+ <Button size="sm" onClick={onAdd}>
+ <Plus className="mr-2 size-4" aria-hidden="true" />
+ 인포메이션 추가
+ </Button>
+ </div>
+ )
+} \ No newline at end of file
diff --git a/lib/information/table/information-table.tsx b/lib/information/table/information-table.tsx
new file mode 100644
index 00000000..9fc4ec29
--- /dev/null
+++ b/lib/information/table/information-table.tsx
@@ -0,0 +1,148 @@
+"use client"
+
+import * as React from "react"
+import type {
+ DataTableAdvancedFilterField,
+ DataTableFilterField,
+ DataTableRowAction,
+} from "@/types/table"
+
+import { useDataTable } from "@/hooks/use-data-table"
+import { DataTable } from "@/components/data-table/data-table"
+import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
+import type { PageInformation } from "@/db/schema/information"
+import { getInformationColumns } from "./information-table-columns"
+import { InformationTableToolbarActions } from "./information-table-toolbar-actions"
+import { AddInformationDialog } from "./add-information-dialog"
+import { UpdateInformationDialog } from "./update-information-dialog"
+import { DeleteInformationDialog } from "./delete-information-dialog"
+
+interface InformationTableProps {
+ promises: Promise<{
+ data: PageInformation[]
+ pageCount: number
+ total: number
+ }>
+}
+
+export function InformationTable({ promises }: InformationTableProps) {
+ const [rowAction, setRowAction] = React.useState<DataTableRowAction<PageInformation> | null>(null)
+ const [showAddDialog, setShowAddDialog] = React.useState(false)
+ const [showUpdateDialog, setShowUpdateDialog] = React.useState(false)
+ const [showDeleteDialog, setShowDeleteDialog] = React.useState(false)
+
+ const { data, pageCount } = React.use(promises)
+
+ // 컬럼 설정
+ const columns = React.useMemo(
+ () => getInformationColumns({ setRowAction }),
+ [setRowAction]
+ )
+
+ const filterFields: DataTableFilterField<PageInformation>[] = []
+
+ // 고급 필터 필드 설정
+ const advancedFilterFields: DataTableAdvancedFilterField<PageInformation>[] = [
+ {
+ id: "pageCode",
+ label: "페이지 코드",
+ type: "text",
+ },
+ {
+ id: "pageName",
+ label: "페이지명",
+ type: "text",
+ },
+ {
+ id: "title",
+ label: "제목",
+ type: "text",
+ },
+ {
+ id: "isActive",
+ label: "상태",
+ type: "select",
+ options: [
+ { label: "활성", value: "true" },
+ { label: "비활성", value: "false" },
+ ],
+ },
+ {
+ id: "createdAt",
+ label: "생성일",
+ type: "date",
+ },
+ {
+ id: "updatedAt",
+ label: "수정일",
+ type: "date",
+ },
+ ]
+
+ const { table } = useDataTable({
+ data,
+ columns,
+ pageCount,
+ filterFields,
+ enablePinning: true,
+ enableAdvancedFilter: true,
+ initialState: {
+ sorting: [{ id: "createdAt", desc: true }],
+ columnPinning: { right: ["actions"] },
+ },
+ getRowId: (originalRow) => String(originalRow.id),
+ shallow: false,
+ clearOnDefault: true,
+ })
+
+ // 행 액션 처리
+ React.useEffect(() => {
+ if (rowAction?.type === "update") {
+ setShowUpdateDialog(true)
+ } else if (rowAction?.type === "delete") {
+ setShowDeleteDialog(true)
+ }
+ }, [rowAction])
+
+ return (
+ <>
+ <DataTable table={table}>
+ <DataTableAdvancedToolbar
+ table={table}
+ filterFields={advancedFilterFields}
+ shallow={false}
+ >
+ <InformationTableToolbarActions
+ table={table}
+ onAdd={() => setShowAddDialog(true)}
+ />
+ </DataTableAdvancedToolbar>
+ </DataTable>
+
+ <AddInformationDialog
+ open={showAddDialog}
+ onOpenChange={setShowAddDialog}
+ />
+
+ <UpdateInformationDialog
+ open={showUpdateDialog}
+ onOpenChange={setShowUpdateDialog}
+ information={rowAction?.row.original}
+ onClose={() => {
+ setShowUpdateDialog(false)
+ setRowAction(null)
+ }}
+ />
+
+ <DeleteInformationDialog
+ open={showDeleteDialog}
+ onOpenChange={setShowDeleteDialog}
+ information={rowAction?.row.original}
+ onClose={() => {
+ setShowDeleteDialog(false)
+ setRowAction(null)
+ }}
+ />
+ </>
+ )
+} \ No newline at end of file
diff --git a/lib/information/table/update-information-dialog.tsx b/lib/information/table/update-information-dialog.tsx
new file mode 100644
index 00000000..afa7559b
--- /dev/null
+++ b/lib/information/table/update-information-dialog.tsx
@@ -0,0 +1,376 @@
+"use client"
+
+import * as React from "react"
+import { zodResolver } from "@hookform/resolvers/zod"
+import { useForm } from "react-hook-form"
+import { toast } from "sonner"
+import { Loader, Upload, X } from "lucide-react"
+import { useRouter } from "next/navigation"
+
+import { Button } from "@/components/ui/button"
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} 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 { Switch } from "@/components/ui/switch"
+import { updateInformationData } from "@/lib/information/service"
+import { updateInformationSchema, type UpdateInformationSchema } from "@/lib/information/validations"
+import type { PageInformation } from "@/db/schema/information"
+
+interface UpdateInformationDialogProps {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ information?: PageInformation
+ onClose: () => void
+}
+
+export function UpdateInformationDialog({
+ open,
+ onOpenChange,
+ information,
+ onClose,
+}: UpdateInformationDialogProps) {
+ const router = useRouter()
+ const [isLoading, setIsLoading] = React.useState(false)
+ const [uploadedFile, setUploadedFile] = React.useState<File | null>(null)
+
+ const form = useForm<UpdateInformationSchema>({
+ resolver: zodResolver(updateInformationSchema),
+ defaultValues: {
+ id: 0,
+ pageCode: "",
+ pageName: "",
+ title: "",
+ description: "",
+ noticeTitle: "",
+ noticeContent: "",
+ isActive: true,
+ },
+ })
+
+ // 인포메이션 데이터가 변경되면 폼 업데이트
+ React.useEffect(() => {
+ if (information && open) {
+ form.reset({
+ id: information.id,
+ pageCode: information.pageCode,
+ pageName: information.pageName,
+ title: information.title,
+ description: information.description,
+ noticeTitle: information.noticeTitle || "",
+ noticeContent: information.noticeContent || "",
+ attachmentFileName: information.attachmentFileName || "",
+ attachmentFilePath: information.attachmentFilePath || "",
+ attachmentFileSize: information.attachmentFileSize || "",
+ isActive: information.isActive,
+ })
+ }
+ }, [information, open, form])
+
+ const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
+ const file = event.target.files?.[0]
+ if (file) {
+ setUploadedFile(file)
+ // 파일 크기를 MB 단위로 변환
+ const sizeInMB = (file.size / (1024 * 1024)).toFixed(2)
+ form.setValue("attachmentFileName", file.name)
+ form.setValue("attachmentFileSize", `${sizeInMB} MB`)
+ }
+ }
+
+ const removeFile = () => {
+ setUploadedFile(null)
+ form.setValue("attachmentFileName", "")
+ form.setValue("attachmentFilePath", "")
+ form.setValue("attachmentFileSize", "")
+ }
+
+ const uploadFile = async (file: File): Promise<string> => {
+ const formData = new FormData()
+ formData.append("file", file)
+
+ const response = await fetch("/api/upload", {
+ method: "POST",
+ body: formData,
+ })
+
+ if (!response.ok) {
+ throw new Error("파일 업로드에 실패했습니다.")
+ }
+
+ const result = await response.json()
+ return result.url
+ }
+
+ const onSubmit = async (values: UpdateInformationSchema) => {
+ setIsLoading(true)
+ try {
+ const finalValues = { ...values }
+
+ // 새 파일이 있으면 업로드
+ if (uploadedFile) {
+ const filePath = await uploadFile(uploadedFile)
+ finalValues.attachmentFilePath = filePath
+ }
+
+ const result = await updateInformationData(finalValues)
+
+ if (result.success) {
+ toast.success(result.message)
+ onClose()
+ router.refresh()
+ } else {
+ toast.error(result.message)
+ }
+ } catch (error) {
+ toast.error("인포메이션 수정에 실패했습니다.")
+ console.error(error)
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ const handleClose = () => {
+ setUploadedFile(null)
+ onClose()
+ }
+
+ const currentFileName = form.watch("attachmentFileName")
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>인포메이션 수정</DialogTitle>
+ <DialogDescription>
+ 페이지 인포메이션 정보를 수정합니다.
+ </DialogDescription>
+ </DialogHeader>
+
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
+ <div className="grid grid-cols-2 gap-4">
+ <FormField
+ control={form.control}
+ name="pageCode"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>페이지 코드</FormLabel>
+ <FormControl>
+ <Input placeholder="예: vendor-list" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="pageName"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>페이지명</FormLabel>
+ <FormControl>
+ <Input placeholder="예: 협력업체 목록" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+
+ <FormField
+ control={form.control}
+ name="title"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>제목</FormLabel>
+ <FormControl>
+ <Input placeholder="인포메이션 제목을 입력하세요" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="description"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>설명</FormLabel>
+ <FormControl>
+ <Textarea
+ placeholder="페이지 설명을 입력하세요"
+ rows={4}
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="noticeTitle"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>공지사항 제목 (선택사항)</FormLabel>
+ <FormControl>
+ <Input placeholder="공지사항 제목을 입력하세요" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="noticeContent"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>공지사항 내용 (선택사항)</FormLabel>
+ <FormControl>
+ <Textarea
+ placeholder="공지사항 내용을 입력하세요"
+ rows={3}
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <div>
+ <FormLabel>첨부파일</FormLabel>
+ <div className="mt-2">
+ {uploadedFile ? (
+ <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium">{uploadedFile.name}</span>
+ <span className="text-xs text-gray-500">
+ ({(uploadedFile.size / (1024 * 1024)).toFixed(2)} MB)
+ </span>
+ <span className="text-xs text-blue-600">(새 파일)</span>
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={removeFile}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </div>
+ ) : currentFileName ? (
+ <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium">{currentFileName}</span>
+ {form.watch("attachmentFileSize") && (
+ <span className="text-xs text-gray-500">
+ ({form.watch("attachmentFileSize")})
+ </span>
+ )}
+ </div>
+ <div className="flex gap-2">
+ <label
+ htmlFor="file-upload-update"
+ className="cursor-pointer text-sm text-blue-600 hover:text-blue-500"
+ >
+ 변경
+ </label>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={removeFile}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <div className="border-2 border-dashed border-gray-300 rounded-lg p-4">
+ <div className="text-center">
+ <Upload className="mx-auto h-8 w-8 text-gray-400" />
+ <div className="mt-2">
+ <label
+ htmlFor="file-upload-update"
+ className="cursor-pointer text-sm text-blue-600 hover:text-blue-500"
+ >
+ 파일을 선택하세요
+ </label>
+ </div>
+ <p className="text-xs text-gray-500 mt-1">
+ PDF, DOC, DOCX, XLSX, PPT, PPTX, TXT, ZIP 파일만 업로드 가능
+ </p>
+ </div>
+ </div>
+ )}
+ <input
+ id="file-upload-update"
+ type="file"
+ className="hidden"
+ onChange={handleFileSelect}
+ accept=".pdf,.doc,.docx,.xlsx,.ppt,.pptx,.txt,.zip"
+ />
+ </div>
+ </div>
+
+ <FormField
+ control={form.control}
+ name="isActive"
+ render={({ field }) => (
+ <FormItem className="flex flex-row items-center justify-between rounded-lg border p-3">
+ <div className="space-y-0.5">
+ <FormLabel className="text-base">활성 상태</FormLabel>
+ <div className="text-sm text-muted-foreground">
+ 활성화하면 해당 페이지에서 인포메이션 버튼이 표시됩니다.
+ </div>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={handleClose}
+ disabled={isLoading}
+ >
+ 취소
+ </Button>
+ <Button type="submit" disabled={isLoading}>
+ {isLoading && <Loader className="mr-2 h-4 w-4 animate-spin" />}
+ 수정
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ )
+} \ No newline at end of file
diff --git a/lib/information/validations.ts b/lib/information/validations.ts
new file mode 100644
index 00000000..216e3354
--- /dev/null
+++ b/lib/information/validations.ts
@@ -0,0 +1,89 @@
+import { z } from "zod"
+import {
+ createSearchParamsCache,
+ parseAsArrayOf,
+ parseAsInteger,
+ parseAsString,
+ parseAsStringEnum,
+ parseAsBoolean,
+} from "nuqs/server"
+import { getFiltersStateParser, getSortingStateParser } from "@/lib/parsers"
+import { PageInformation } from "@/db/schema/information"
+
+// 인포메이션 생성 스키마
+export const createInformationSchema = z.object({
+ pageCode: z.string().min(1, "페이지 코드를 입력해주세요"),
+ pageName: z.string().min(1, "페이지명을 입력해주세요"),
+ title: z.string().min(1, "제목을 입력해주세요"),
+ description: z.string().min(1, "설명을 입력해주세요"),
+ noticeTitle: z.string().optional(),
+ noticeContent: z.string().optional(),
+ attachmentFileName: z.string().optional(),
+ attachmentFilePath: z.string().optional(),
+ attachmentFileSize: z.string().optional(),
+ isActive: z.boolean().default(true),
+})
+
+// 인포메이션 수정 스키마
+export const updateInformationSchema = z.object({
+ id: z.number(),
+ pageCode: z.string().min(1, "페이지 코드를 입력해주세요"),
+ pageName: z.string().min(1, "페이지명을 입력해주세요"),
+ title: z.string().min(1, "제목을 입력해주세요"),
+ description: z.string().min(1, "설명을 입력해주세요"),
+ noticeTitle: z.string().optional(),
+ noticeContent: z.string().optional(),
+ attachmentFileName: z.string().optional(),
+ attachmentFilePath: z.string().optional(),
+ attachmentFileSize: z.string().optional(),
+ isActive: z.boolean().default(true),
+})
+
+// 현대적인 검색 파라미터 캐시 (프로젝트 패턴과 동일)
+export const searchParamsInformationCache = createSearchParamsCache({
+ flags: parseAsArrayOf(z.enum(["advancedTable", "floatingBar"])).withDefault([]),
+ page: parseAsInteger.withDefault(1),
+ perPage: parseAsInteger.withDefault(10),
+ sort: getSortingStateParser<PageInformation>().withDefault([
+ { id: "createdAt", desc: true },
+ ]),
+
+ // 기본 검색 필드들
+ pageCode: parseAsString.withDefault(""),
+ pageName: parseAsString.withDefault(""),
+ title: parseAsString.withDefault(""),
+ isActive: parseAsBoolean,
+
+ // 고급 필터
+ filters: getFiltersStateParser().withDefault([]),
+ joinOperator: parseAsStringEnum(["and", "or"]).withDefault("and"),
+ search: parseAsString.withDefault(""),
+
+ // 날짜 범위
+ from: parseAsString,
+ to: parseAsString,
+})
+
+// 타입 추출
+export type CreateInformationSchema = z.infer<typeof createInformationSchema>
+export type UpdateInformationSchema = z.infer<typeof updateInformationSchema>
+export type GetInformationSchema = Awaited<ReturnType<typeof searchParamsInformationCache.parse>>
+
+// 기존 스키마 (하위 호환성을 위해 유지)
+export const getInformationSchema = z.object({
+ page: z.coerce.number().default(1),
+ per_page: z.coerce.number().default(10),
+ sort: z.string().optional(),
+ pageCode: z.string().optional(),
+ pageName: z.string().optional(),
+ isActive: z.coerce.boolean().optional(),
+ from: z.string().optional(),
+ to: z.string().optional(),
+})
+
+// 페이지 코드별 인포메이션 조회 스키마
+export const getPageInformationSchema = z.object({
+ pageCode: z.string().min(1, "페이지 코드를 입력해주세요"),
+})
+
+export type GetPageInformationSchema = z.infer<typeof getPageInformationSchema> \ No newline at end of file
diff --git a/lib/menu-list/servcie.ts b/lib/menu-list/servcie.ts
index 35362e6d..8686bf43 100644
--- a/lib/menu-list/servcie.ts
+++ b/lib/menu-list/servcie.ts
@@ -5,7 +5,7 @@
import db from "@/db/db";
import { menuAssignments, users } from "@/db/schema";
import { eq, and } from "drizzle-orm";
-import { revalidatePath } from "next/cache";
+import { revalidatePath, revalidateTag } from "next/cache";
import { mainNav, mainNavVendor, additionalNav, additionalNavVendor } from "@/config/menuConfig";
// 메뉴 데이터 타입 정의
@@ -147,6 +147,9 @@ export async function updateMenuManager(
.where(eq(menuAssignments.menuPath, menuPath));
revalidatePath("/evcp/menu-list");
+ // 인포메이션 편집 권한 캐시 무효화
+ revalidateTag("information-edit-permission")
+
return { success: true, message: "담당자가 업데이트되었습니다." };
} catch (error) {
console.error("담당자 업데이트 오류:", error);