Compare commits

...
100 Commits
Author SHA1 Message Date
chanii8 bc6ee47734 feat: 이미지 뷰잉 작업 2025-04-04 18:40:30 +09:00
chanii8 b0f8638df2 feat: 사이트 반영 api 날짜 payload 수정 2025-04-04 16:24:57 +09:00
chanii8 7f4e973c5f feat: 사이트 반영 저장 api 작업 2025-04-04 15:25:34 +09:00
chanii8 528cc39831 feat: 사이트 반영 팝업 작업 2025-04-04 14:49:00 +09:00
chanii8 d84bfe2a7c fix: 스토리북 "Failed to fetch dynamically imported module" 에러 해결 2025-04-04 11:05:57 +09:00
chanii8 badb682163 refactor: 사이트 반영 폼 리팩토링 2025-04-03 18:39:54 +09:00
chanii8 e659f47d1d feat: 사이트 반영 폼 작업 2025-04-03 17:37:35 +09:00
chanii8 e3454e11d5 feat: 사이트 게시 이력 api 작업 2025-04-03 11:40:00 +09:00
chanii8 6df605a184 feat: loading ui 적용 2025-04-03 09:37:25 +09:00
chanii8 483e0b319a chore: 이미지 업로드 안내 문구 추가 2025-04-02 17:47:14 +09:00
chanii8 623b1e985e refactor: 로그인 완료 시 하위 모든 페이지 리렌더링 작업 2025-04-02 17:34:47 +09:00
chanii8 84d4635a75 feat: 상황판 페이지 추가 2025-04-02 17:34:13 +09:00
chanii8 0a51ac3f79 refactor: QueryClientProvider 선언 위치 변경 2025-04-02 17:19:16 +09:00
chanii8 4e4bd82009 refactor: menu wrapper에서 useQuery 제거 2025-04-02 15:33:51 +09:00
chanii8 a9739bdba5 feat: 이미지 등록 작업 2025-04-02 14:49:35 +09:00
chanii8 1d132a86de feat: 이미지 업데이트 및 삭제 작업 2025-04-02 14:07:36 +09:00
chanii8 6297d528fb feat: 이미지 등록 폼 작업 2025-04-02 13:22:11 +09:00
chanii8 3832adf3b0 chore: label 컴포넌트 적용 2025-04-02 10:58:02 +09:00
chanii8 60464b92b0 feat: 이미지 등록 폼 작업 2025-04-01 17:43:46 +09:00
chanii8 a912deeefb feat: 이미지 목록 페이지 작업 2025-04-01 15:40:38 +09:00
chanii8 f2954e6ebd refactor: page layout 공통 적용 2025-04-01 14:25:17 +09:00
chanii8 26854a8610 feat: 이미지 관리 페이지 생성 2025-04-01 14:14:38 +09:00
chanii8 67d57e3060 fix: getCurrentMenu 로직 수정 2025-03-31 18:23:46 +09:00
chanii8 ea319aa5ab feat: menu wrapper 생성 2025-03-31 18:03:48 +09:00
chanii8 8117ca5c2c design: 테이블 스타일 수정 2025-03-31 15:10:38 +09:00
chanii8 c3fdf92f5c feat: 사이트 등록/수정 타이틀 분기 처리 2025-03-31 13:14:18 +09:00
chanii8 7216d6a74e feat: data table에 variant props 추가 2025-03-31 13:12:42 +09:00
chanii8 0aee493d32 feat: page title 컴포넌트 생성 2025-03-31 13:09:05 +09:00
chanii8 7860345e89 feat: 사이드바 메뉴 클릭 핸들러 작업 2025-03-31 10:40:00 +09:00
chanii8 84519658c1 design: 트리 메뉴 최대 높이 지정 2025-03-28 18:50:18 +09:00
chanii8 8b9d493ccd feat: 트리 메뉴 전체 펼침/접기 기능 작업 2025-03-28 18:32:53 +09:00
chanii8 ca1c0be47f feat: 내부/외부링크 메뉴 등록 작업 2025-03-28 18:23:52 +09:00
chanii8 cd455fa343 feat: 게시판 메뉴 등록 작업 2025-03-28 18:17:13 +09:00
chanii8 701d042d4f rename: 콘텐츠 및 담당자 조회 다이얼로그 리네이밍 2025-03-28 16:44:32 +09:00
chanii8 f59320d2ff refactor: 메뉴 폼 폴더 구조 변경
rename: 다이얼로그 폴더 제거

chore: 참조 경로 수정
2025-03-28 16:41:52 +09:00
chanii8 572f18cc1a feat: 콘텐츠 메뉴 등록 작업 2025-03-28 15:22:14 +09:00
chanii8 6a784cecf3 feat: 콘텐츠 검색 기능 추가 2025-03-28 10:53:16 +09:00
chanii8 cb5e90c277 rename: 폼 및 다이얼로그 폴더 구분 2025-03-28 09:22:07 +09:00
chanii8 c221a4537e feat: 콘텐츠 메뉴 등록 작업 2025-03-27 18:20:29 +09:00
chanii8 050ce81481 chore: PageableList 제너릭 타입 수정 2025-03-27 16:33:39 +09:00
chanii8 89f31c4c6b chore: 인터페이스 네이밍 규칙 변경('I' prefix 제거) 2025-03-27 16:29:40 +09:00
chanii8 e32d0ba144 feat: 메뉴 권한관리 다이얼로그 작업 2025-03-27 16:17:42 +09:00
chanii8 8b0939ff41 feat: 메뉴 타입별 폼 작업(내부링크, 외부링크, 하단메뉴) 2025-03-27 16:16:59 +09:00
chanii8 ae5597b1f3 feat: 메뉴 삭제 로직 작업 2025-03-27 15:23:01 +09:00
chanii8 0fa026e11b fix: prntMenuCd 없을 경우 null 적용 2025-03-27 14:59:16 +09:00
chanii8 5c7ab94922 feat: 트리 메뉴 추가 기능 작업 2025-03-27 14:40:35 +09:00
chanii8 c5f1718441 refactor: editable node 컴포넌트 분리 2025-03-26 18:20:33 +09:00
chanii8 73badb5ac5 Merge branch 'iipbs_cs' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into iipbs_cs 2025-03-26 17:47:15 +09:00
chanii8 e127180cb7 refactor: 트리 메뉴 순서 변경 로직 수정 2025-03-26 17:46:05 +09:00
chanii8 b26e7e3d10 feat: 메뉴 등록 및 수정 작업 2025-03-26 17:00:35 +09:00
chanii8 f03b07738e feat: 메뉴 수정 작업 2025-03-26 15:35:15 +09:00
chanii8 d4f7cf140e feat: 메뉴 저장 및 수정 작업 2025-03-26 15:07:53 +09:00
jcchoi 59c57d45d5 chore : 공통 components.css 추가가 2025-03-26 14:05:59 +09:00
chanii8 5b4e674214 rename: base bottom form 이름 변경 2025-03-26 11:00:24 +09:00
chanii8 f94b8a3f8e fix: 트리 메뉴 순서 변경 dnd 로직 수정 2025-03-26 10:09:38 +09:00
jcchoi 403bbe3647 Merge branch 'iipbs_cs' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into iipbs_cs 2025-03-25 20:20:43 +09:00
jcchoi 752b5fa789 chore: component.css 수정 2025-03-25 20:20:36 +09:00
chanii8 36c3bcb0b4 feat: 트리 메뉴 dnd 순서 변경 작업 2025-03-25 19:00:54 +09:00
jcchoi 64d336c2a4 chore: package 명령어 수정 2025-03-25 17:22:27 +09:00
chanii8 4cbead44db refactor: components.css postcss로 변경 2025-03-25 17:09:03 +09:00
chanii8 517ab0f272 chore: 컴포넌트 코드 정리 2025-03-25 16:59:54 +09:00
chanii8 5df4f6dd15 feat: icon finder 컴포넌트 수정 2025-03-25 15:06:55 +09:00
chanii8 92f67ce1a3 feat: 트리 메뉴명 수정 작업 2025-03-25 14:23:16 +09:00
chanii8 2aee109912 feat: 트리 메뉴 dnd 로직 작업 2025-03-25 10:55:15 +09:00
chanii8 8f4dc1bd34 feat: icon finder 검색 기능 추가 2025-03-25 09:48:14 +09:00
chanii8 ada14e0003 feat: 사이트 폼 도메인 작업 2025-03-24 17:52:35 +09:00
chanii8 8aa6d20c63 feat: 메뉴 유형별 폼 작업 2025-03-24 17:42:59 +09:00
chanii8 791098e0c0 feat: icon finder 컴포넌트 생성 2025-03-24 17:07:58 +09:00
chanii8 89cec5291d feat: 메뉴 폼에 '메뉴ID' 필드 추가 2025-03-24 16:32:55 +09:00
chanii8 539585f495 feat: 트리 메뉴 dnd 작업 2025-03-24 16:11:35 +09:00
chanii8 b459036a59 chore: 메뉴 관리 폼 수정 2025-03-24 10:22:54 +09:00
chanii8 f749bee140 design: 메뉴 트리 스타일 수정 2025-03-21 18:31:18 +09:00
chanii8 c4a9aabce7 feat: 메뉴 폼 작업 2025-03-21 18:22:34 +09:00
chanii8 d8d5c16d31 feat: 메뉴 관리 > 사이트별 메뉴 api 작업 2025-03-21 17:22:43 +09:00
chanii8 b1f3de08a7 refactor: query provider 구조 변경 2025-03-21 11:31:33 +09:00
chanii8 699eadb399 feat: 사이트 테마 SSR 적용 2025-03-21 09:56:25 +09:00
chanii8 580d449f3e chore: 사이트 등록 페이지 폼 기본값 수정 2025-03-20 18:59:06 +09:00
chanii8 b8e0a8a878 feat: 다크 모드 적용 2025-03-20 18:50:31 +09:00
chanii8 55ac57d73c chore: 사이트 폼 컨펌 다이얼로그 로직 수정 2025-03-20 17:38:13 +09:00
chanii8 fadb57242d feat: 도메인 관리 및 IP 관리 작업 2025-03-20 17:36:16 +09:00
chanii8 dc01c897a9 chore: 사이트 수정 폼 수정 2025-03-20 10:48:54 +09:00
chanii8 b2141d9708 refactor: ip 관리 폼 수정 2025-03-20 10:43:19 +09:00
chanii8 e49e3d3b36 feat: useAlertStore 적용 2025-03-19 18:43:58 +09:00
chanii8 915543628d feat: ip 관리 서비스 작업 2025-03-19 16:23:33 +09:00
chanii8 6f0e1a6e40 feat: 컨펌 & 얼럿 다이얼로그 스토어 생성 2025-03-19 15:54:20 +09:00
chanii8 25a2ac5716 refactor: 인증 및 로그인 로직 수정 2025-03-19 09:38:49 +09:00
chanii8 a13ea5d6e9 design: 사이트 관리 페이지 스타일 수정 2025-03-18 17:42:12 +09:00
chanii8 8f484e8425 feat: sidebar 작업 2025-03-18 14:29:40 +09:00
chanii8 8aa713e285 chore: Remove .next directory from git tracking 2025-03-17 18:47:53 +09:00
chanii8 daacb2cb25 Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into iipbs_cs 2025-03-17 18:42:35 +09:00
chanii8 d88afe7034 build: packages & cs 폴더 빌드 성공 2025-03-17 18:39:13 +09:00
chanii8 4a88315a99 chore: gitignore 수정 2025-03-17 18:28:17 +09:00
chanii8 f767d0a688 feat: sidebar 컴포넌트 생성 2025-03-17 18:28:17 +09:00
chanii8 57e9daf772 feat: user store 생성(zustand) 2025-03-17 18:28:17 +09:00
chanii8 4ed2a45486 refactor: provider 레이어 변경 & 누락된 public api 수정 2025-03-17 18:28:17 +09:00
chanii8 08e9cb98e9 Merge pull request 'iipbs_cs' (#8) from iipbs_cs into main
Reviewed-on: #8
2025-03-17 18:10:31 +09:00
chanii8 d404de4afb chore: gitignore 수정 2025-03-17 17:37:47 +09:00
chanii8 574286139c feat: sidebar 컴포넌트 생성 2025-03-17 15:24:58 +09:00
chanii8 c81735b8b8 feat: user store 생성(zustand) 2025-03-17 14:50:18 +09:00
chanii8 39bf03c4f5 refactor: provider 레이어 변경 & 누락된 public api 수정 2025-03-17 13:27:19 +09:00
554 changed files with 8620 additions and 261561 deletions
+10 -4
View File
@@ -1,13 +1,19 @@
# turbo
.turbo
.turbo/
# dependencies
node_modules
node_modules/
# build
.next/
dist/
# build
.next
dist
# misc
.DS_Store
apps/wr/.next/**/*
apps/fo/.next/**/*
# env
.env*
@@ -0,0 +1,2 @@
import { DashboardPage } from "@/pages/dashboard";
export default DashboardPage;
@@ -0,0 +1,2 @@
import { ImagePage } from "@/pages/image";
export default ImagePage;
@@ -0,0 +1,10 @@
import { ModifyPage as VModifyPage } from "@/pages/image";
export default async function ModifyPage({
params,
}: {
params: Promise<{ serial: string }>;
}) {
const { serial } = await params;
return <VModifyPage serial={serial} />;
}
@@ -0,0 +1,2 @@
import { CreatePage } from "@/pages/image";
export default CreatePage;
+25 -1
View File
@@ -1,11 +1,35 @@
"use client";
import { usePathname, useRouter } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
import type { MenuItem } from "@common/components/api";
import { BaseLayout } from "@common/components/ui";
import { useMenuStore } from "@/shared/lib";
import { PageLayout } from "@/shared/ui/page-layout";
export default function WithBaseLayout({
children,
}: {
children: React.ReactNode;
}) {
return <BaseLayout>{children}</BaseLayout>;
const router = useRouter();
const pathname = usePathname();
const queryClient = useQueryClient();
const { setCurrentMenuInfo } = useMenuStore((state) => state);
const handleMenuClick = (item: MenuItem) => {
setCurrentMenuInfo(item);
router.push(item.urlPath);
};
return (
<BaseLayout
queryClient={queryClient}
currentPath={pathname ?? ""}
handleMenuClick={handleMenuClick}
>
<PageLayout>{children}</PageLayout>
</BaseLayout>
);
}
@@ -0,0 +1,2 @@
import { SkeletonPage } from "@/shared/ui/skeleton-page";
export default SkeletonPage;
@@ -0,0 +1,2 @@
import { MenuPage } from "@/pages/menu";
export default MenuPage;
+1 -1
View File
@@ -5,7 +5,7 @@ import {
REFRESH_TOKEN,
SERVER_API_URL,
SITE_ID,
} from "@/shared/config/env";
} from "@/shared/config";
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
+5
View File
@@ -11,6 +11,11 @@ const compat = new FlatCompat({
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
{
rules: {
"react-hooks/exhaustive-deps": "off",
},
},
];
export default eslintConfig;
+23 -4
View File
@@ -1,19 +1,38 @@
import { NextRequest, NextResponse } from "next/server";
import { CLAIM_NAME, AUTH_USER_ID } from "./src/shared/config";
const serverApiUrl =
process.env.NEXT_PUBLIC_SERVER_API_URL ?? "http://localhost:3000";
export function middleware(req: NextRequest) {
const pathname = req.nextUrl.pathname;
const searchParams = req.nextUrl.searchParams;
if (pathname.startsWith("/server")) {
return NextResponse.rewrite(
`${serverApiUrl}${pathname.replace("/server", "")}`,
);
const queryParams = searchParams.toString();
const newUrl = `${serverApiUrl}${pathname.replace("/server", "")}${
queryParams ? `?${queryParams}` : ""
}`;
return NextResponse.rewrite(new URL(newUrl));
}
if (pathname.startsWith("/attach-service")) {
const requestHeaders = new Headers(req.headers);
const token = req.cookies.get(CLAIM_NAME)?.value;
const userId = req.cookies.get(AUTH_USER_ID)?.value;
const newUrl = `${serverApiUrl}${pathname}`;
if (token) requestHeaders.set(CLAIM_NAME, token);
if (userId) requestHeaders.set(AUTH_USER_ID, userId);
return NextResponse.rewrite(new URL(newUrl), {
headers: requestHeaders,
});
}
return NextResponse.next();
}
export const config = {
matcher: "/server/:path*",
matcher: ["/server/:path*", "/attach-service/:path*"],
};
+1 -34
View File
@@ -1,38 +1,5 @@
import type { NextConfig } from "next";
import webpack from "webpack";
const nextConfig: NextConfig = {
webpack: (config) => {
config.plugins.push(
new webpack.DefinePlugin({
"import.meta.env.VITE_PORT": JSON.stringify(
process.env.NEXT_PUBLIC_PORT,
),
"import.meta.env.VITE_PROXY_HOST": JSON.stringify(
process.env.NEXT_PUBLIC_PROXY_HOST,
),
"import.meta.env.VITE_SERVER_API_URL": JSON.stringify(
process.env.NEXT_PUBLIC_SERVER_API_URL,
),
"import.meta.env.VITE_SITE_ID": JSON.stringify(process.env.SITE_ID),
"import.meta.env.VITE_CLAIM_NAME": JSON.stringify(
process.env.NEXT_PUBLIC_CLAIM_NAME,
),
"import.meta.env.VITE_ACCESS_TOKEN": JSON.stringify(
process.env.NEXT_PUBLIC_ACCESS_TOKEN,
),
"import.meta.env.VITE_REFRESH_TOKEN": JSON.stringify(
process.env.NEXT_PUBLIC_REFRESH_TOKEN,
),
"import.meta.env.VITE_AUTH_USER_ID": JSON.stringify(
process.env.NEXT_PUBLIC_AUTH_USER_ID,
),
"process.env.SITE_ID": JSON.stringify(process.env.NEXT_PUBLIC_SITE_ID),
}),
);
return config;
},
};
const nextConfig: NextConfig = {};
export default nextConfig;
+6 -2
View File
@@ -3,7 +3,7 @@
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "NODE_OPTIONS='--inspect' next dev",
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
@@ -13,6 +13,7 @@
"@common/components": "workspace:*",
"@frontend-opensource/use-react-hooks": "^1.1.4",
"@hookform/resolvers": "^4.1.3",
"@minoru/react-dnd-treeview": "^3.5.0",
"@radix-ui/react-label": "^2.1.2",
"@radix-ui/react-slot": "^1.1.2",
"@tanstack/react-query": "^5.67.1",
@@ -23,9 +24,12 @@
"js-cookie": "^3.0.5",
"next": "15.1.7",
"react-chartjs-2": "^5.3.0",
"react-dnd": "^16.0.1",
"react-hook-form": "^7.54.2",
"tailwindcss-animate": "^1.0.7",
"zod": "^3.24.2"
"tus-js-client": "^4.3.1",
"zod": "^3.24.2",
"zustand": "^5.0.3"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
+6 -3
View File
@@ -1,10 +1,13 @@
import "./styles/base.css";
import "./styles/components.css";
import { AppProvider } from "@/shared/provider";
import { AppProvider } from "./providers";
import { cookies } from "next/headers";
const App = async ({ children }: Readonly<{ children: React.ReactNode }>) => {
const theme = (await cookies()).get("site-theme-key");
const App = ({ children }: Readonly<{ children: React.ReactNode }>) => {
return (
<html lang="ko">
<html lang="ko" data-theme={theme?.value}>
<body>
<AppProvider>{children}</AppProvider>
</body>
@@ -0,0 +1,28 @@
"use client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ConfirmProvider } from "@frontend-opensource/use-react-hooks";
import { AuthWrapper } from "@/entities/auth";
import { MenuWrapper } from "@/entities/menu";
import { StoreProvider } from "@/shared/providers";
import { AlertDialog } from "@/shared/ui/alert-dialog";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
const AppProvider = ({ children }: Readonly<{ children: React.ReactNode }>) => {
const queryClient = new QueryClient();
return (
<QueryClientProvider client={queryClient}>
<StoreProvider>
<ConfirmProvider>
<AuthWrapper>
<MenuWrapper>{children}</MenuWrapper>
<AlertDialog />
<ConfirmDialog />
</AuthWrapper>
</ConfirmProvider>
</StoreProvider>
</QueryClientProvider>
);
};
export { AppProvider };
+1
View File
@@ -0,0 +1 @@
export { AppProvider } from "./app-provider";
+123 -19
View File
@@ -1,25 +1,129 @@
@tailwind components;
.card {
position: relative;
margin: 0.6rem;
box-sizing: border-box;
min-height: 2rem;
border-radius: 0.5rem;
padding: 0.6rem;
font-size: 1.3rem;
color: #666;
}
@layer components {
.card {
@apply relative m-[0.6rem] box-border min-h-[2rem] rounded-[0.5rem] p-[0.6rem] text-[1.3rem] text-[#666];
}
.card_width10 {
width: calc(10% - 12px);
}
.card_width20 {
width: calc(20% - 12px);
}
.card_width25 {
width: calc(25% - 12px);
}
.card_width30 {
width: calc(30% - 12px);
}
.card_width33 {
width: calc(33.333% - 12px);
}
.card_width40 {
width: calc(40% - 12px);
}
.card_width45 {
width: calc(45% - 12px);
}
.card_width50 {
width: calc(50% - 12px);
}
.card_width60 {
width: calc(60% - 12px);
}
.card_width66 {
width: calc(66.666% - 12px);
}
.card_width70 {
width: calc(70% - 12px);
}
.card_width75 {
width: calc(75% - 12px);
}
.card_width80 {
width: calc(80% - 12px);
}
.card_width90 {
width: calc(90% - 12px);
}
.card_width100 {
width: calc(100% - 12px);
}
.card_nopadding {
padding: 0 !important;
}
.card_nomargin {
width: 100%;
margin: 0 !important;
padding: 0 !important;
}
.topline {
border-top: 1px solid #ccc;
}
.bottomline {
border-bottom: 1px solid #e6eef3;
background: #fff;
}
.card-border {
border: 1px solid #dbe2e6;
background-color: rgba(255, 255, 255, 0.6);
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.card-header {
margin-top: -0.6rem;
margin-left: -0.6rem;
margin-right: -0.6rem;
display: flex;
align-items: center;
justify-content: space-between;
border-bottom: 1px solid #e1e7eb;
padding: 1rem;
}
.card-footer {
margin-left: -0.6rem;
margin-right: -0.6rem;
margin-top: 0.5rem;
display: flex;
align-items: center;
justify-content: center;
border-top: 1px solid #e1e7eb;
padding-top: 1rem;
padding-bottom: 1rem;
}
/* 블랙 테마 */
[data-theme="black"] {
.card-border {
@apply border border-[#dbe2e6] bg-[rgba(255,255,255,0.6)] shadow-blur;
background-color: rgba(255, 255, 255, 0.065);
border-color: #38383a;
}
.card-header {
@apply -mx-[0.6rem] flex items-center justify-between border-b border-b-[#e1e7eb] p-4;
}
.card-footer {
@apply -mx-[0.6rem] mt-2 flex items-center justify-center border-t border-t-[#e1e7eb] py-4;
}
[data-mode="dark"] {
.card-border {
@apply border-[#3f4042] bg-[rgba(255,255,255,0.065)];
}
.card-header {
@apply border-b-[#3f4042];
}
border-bottom-color: #3f4042;
}
}
@@ -0,0 +1,17 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type {
Attachment,
AttachmentService,
} from "../model/attachment-interface";
export class AttachmentApiService implements AttachmentService {
public async getAttachments(atflCd: string): Promise<Attachment[]> {
const response = await client.get<Attachment[]>(
`${ENDPOINT.ATTACH_SERVICE.ATTACHMENTS}/${atflCd}`,
);
return response.data;
}
}
export const AttachmentApi = new AttachmentApiService();
+1
View File
@@ -0,0 +1 @@
export { AttachmentApi } from "./api/attachment-service";
@@ -0,0 +1,18 @@
export interface Attachment {
atflCd: string;
atflSn: number;
atflId: string;
physFileNm: string;
orgnlFileNm: string;
atflFlieSz: number;
atflType: string;
dwnldNocs: number;
delYn: string;
lnkgDmnId: string;
lnkgDmnNm: string;
regDt: string;
}
export interface AttachmentService {
getAttachments: (atflCd: string) => Promise<Attachment[]>;
}
@@ -1,6 +1,11 @@
import { AxiosError } from "axios";
import { ENDPOINT, JWT_EXPIRATION_TIME } from "@/shared/config/api";
import { ACCESS_TOKEN, AUTH_USER_ID, CLAIM_NAME } from "@/shared/config/env";
import {
ENDPOINT,
JWT_EXPIRATION_TIME,
ACCESS_TOKEN,
AUTH_USER_ID,
CLAIM_NAME,
} from "@/shared/config";
import type { LoginService, ILogin } from "../model/login-interface";
import { tokenManager } from "../lib/token-manager";
+2
View File
@@ -0,0 +1,2 @@
export { LoginApi } from "./api/login-service";
export { AuthWrapper } from "./lib/auth-wrapper";
@@ -0,0 +1,49 @@
"use client";
import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { client } from "@/shared/api";
import type { IUserInfo } from "@/shared/store";
import { getCookie, useUserStore } from "@/shared/lib";
import { ENDPOINT, AUTH_USER_ID } from "@/shared/config";
import { LoginApi } from "../api/login-service";
const AuthWrapper = ({ children }: { children: React.ReactNode }) => {
const router = useRouter();
const { userInfo, setUserInfo } = useUserStore((state) => state);
async function authCheck() {
const userId = getCookie(AUTH_USER_ID);
if (!userId) {
throw new Error("Missing required authentication tokens");
}
const response = await client.get<IUserInfo>(
`${ENDPOINT.USER_SERVICE.USERS}/${userId}`,
);
if (!userInfo) setUserInfo(response.data);
}
useEffect(() => {
(async () => {
try {
await authCheck();
} catch (error) {
console.error(error);
try {
await LoginApi.silentRefresh();
await authCheck();
} catch (refreshError) {
console.error("Token refresh failed:", refreshError);
setUserInfo(null);
router.push("/auth/login");
}
}
})();
}, []);
return <>{children}</>;
};
export { AuthWrapper };
@@ -1,5 +1,5 @@
import { AUTH_USER_ID, CLAIM_NAME } from "@/shared/config/env";
import { getCookie, setCookie, removeCookie } from "@/shared/lib/cookie";
import { AUTH_USER_ID, CLAIM_NAME } from "@/shared/config";
import { getCookie, setCookie, removeCookie } from "@/shared/lib";
export class TokenManager {
private static instance: TokenManager;
-1
View File
@@ -1 +0,0 @@
export { LoginApi } from "./api/login-service";
@@ -0,0 +1,21 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type {
BoardPopupList,
BoardPopupParams,
BoardService,
} from "../model/board-interface";
export class BoardApiService implements BoardService {
public async getBoardPopupList(
params: BoardPopupParams,
): Promise<BoardPopupList> {
const response = await client.get<BoardPopupList>(
`${ENDPOINT.BOARD_SERVICE.BBS}`,
{ params },
);
return response.data;
}
}
export const BoardApi = new BoardApiService();
+2
View File
@@ -0,0 +1,2 @@
export { BoardApi } from "./api/board-service";
export { type BoardPopup } from "./model/board-interface";
@@ -0,0 +1,42 @@
import type { PageableList, PageableParams } from "@/shared/model";
export const BOARD_TYPE = {
BBSNORMAL: "BBSNORMAL",
BBSFAQ: "BBSFAQ",
BBSIMAGE: "BBSIMAGE",
BBSMOVIE: "BBSMOVIE",
} as const;
export type BoardType = (typeof BOARD_TYPE)[keyof typeof BOARD_TYPE];
export interface BoardPopupParams extends PageableParams {
bbsNm?: string;
}
export interface BoardPopup {
bbsId: number;
bbsTypeCd: BoardType;
bbsTypeNm: string;
bbsNm: string;
bbsExpln: string;
rfrncUseYn: string;
atflUseYn: string;
atflMaxCnt: number;
atflMaxFileSz: number;
ansUseYn: string;
cmntUseYn: string;
dgstfnEvlUseYn: string;
smsUseYn: string;
upndFixUseYn: string;
pstgPrdUseYn: string;
popupUseYn: string;
delYn: string;
regDt: string;
pstCnt: number;
}
export type BoardPopupList = PageableList<BoardPopup>;
export interface BoardService {
getBoardPopupList: (params: BoardPopupParams) => Promise<BoardPopupList>;
}
@@ -1,5 +1,5 @@
import { client } from "@/shared/api/client";
import { ENDPOINT } from "@/shared/config/api";
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type { CodeService, ICode } from "../model/code-interface";
export class CodeApiService implements CodeService {
+2 -5
View File
@@ -6,15 +6,12 @@ import {
SelectTrigger,
SelectValue,
} from "@common/components";
import { ENDPOINT } from "@/shared/config/api";
import { ENDPOINT } from "@/shared/config";
import { CodeApi } from "../api/code-service";
type CodeSelectProps = {
upCd: string;
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
};
} & React.ComponentPropsWithoutRef<typeof Select>;
function CodeSelect({ upCd, defaultValue, ...props }: CodeSelectProps) {
const { data: code } = useQuery({
@@ -0,0 +1,14 @@
import { client } from "@common/components/api";
import { ENDPOINT } from "@/shared/config";
import type { MenuItem, MenuService } from "../model/menu-interface";
export class MenuApiService implements MenuService {
async getMenuRoles(siteId: string): Promise<MenuItem[]> {
const response = await client.get<MenuItem[]>(
`${ENDPOINT.CMS_SERVICE.MENU_ROLES}/${siteId}`,
);
return response.data;
}
}
export const MenuApi = new MenuApiService();
+1
View File
@@ -0,0 +1 @@
export { MenuWrapper } from "./lib/menu-wrapper";
@@ -0,0 +1,29 @@
"use client";
import { useEffect } from "react";
import { usePathname } from "next/navigation";
import { SITE_ID } from "@/shared/config";
import { useMenuStore } from "@/shared/lib";
import { MenuApi } from "../api/menu-service";
import { getCurrentMenu } from "./utils";
const MenuWrapper = ({ children }: { children: React.ReactNode }) => {
const pathname = usePathname();
const { setCurrentMenuInfo } = useMenuStore((state) => state);
useEffect(() => {
(async () => {
const menuRoles = await MenuApi.getMenuRoles(SITE_ID);
if (!menuRoles) return;
const currentMenu = getCurrentMenu(menuRoles, pathname ?? "");
if (!currentMenu) return;
setCurrentMenuInfo(currentMenu);
})();
}, []);
return <>{children}</>;
};
export { MenuWrapper };
+14
View File
@@ -0,0 +1,14 @@
import type { MenuItem } from "../model/menu-interface";
export const getCurrentMenu = (
menus: MenuItem[],
pathname: string,
): MenuItem | null => {
for (const menu of menus) {
if (menu.children) {
return getCurrentMenu(menu.children, pathname);
}
if (menu.urlPath === pathname) return menu;
}
return null;
};
@@ -0,0 +1,23 @@
export interface MenuItem {
menuCd: number;
menuKornNm: string;
menuEngNm: string;
parentId: number | null;
sortSeq: number;
iconNm?: string;
children: MenuItem[] | null;
levelNo: number;
urlPath: string;
menuLnkgTypeCd: string;
menuLnkgSn: number;
menuPath: string;
qrcd: string;
useYn: string;
otptYn: string;
newWndwYn: string;
requiredUrlPath: boolean;
}
export interface MenuService {
getMenuRoles(siteId: string): Promise<MenuItem[]>;
}
@@ -0,0 +1,31 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type { PageableList } from "@/shared/model";
import type {
PostService,
PostingParams,
Post,
WithModePost,
} from "../model/posting-interface";
export class PostingApiService implements PostService {
public async getPostingHistory(
params: PostingParams,
): Promise<PageableList<Post>> {
const response = await client.get<PageableList<Post>>(
`${ENDPOINT.CMS_SERVICE.SITE_PSTGS}`,
{ params },
);
return response.data;
}
public async requestPosting(data: WithModePost[]): Promise<Post[]> {
const response = await client.post<Post[]>(
`${ENDPOINT.CMS_SERVICE.SITE_PSTGS}`,
data,
);
return response.data;
}
}
export const PostingApi = new PostingApiService();
+7
View File
@@ -0,0 +1,7 @@
export { PostingApi } from "./api/posting-service";
export {
POSTING_TYPE,
type Post,
type WithModePost,
} from "./model/posting-interface";
export { PostingDialog } from "./ui/posting-dialog";
@@ -0,0 +1,50 @@
import type { PageableList, PageableParams } from "@/shared/model";
import { z } from "zod";
export const POSTING_TYPE = {
POPUP: "POPUP",
BANNER: "BANNER",
IMAGE: "IMAGE",
} as const;
export type PostingType = (typeof POSTING_TYPE)[keyof typeof POSTING_TYPE];
export interface PostingParams extends PageableParams {
pstgTrgtNo: number;
}
export const postSchema = z.object({
siteId: z.string(),
siteNm: z.string(),
pstgTypeCd: z.string(),
pstgTypeNm: z.string(),
pstgTrgtNo: z.number(),
pstgBgngDt: z.string().optional(),
pstgEndDt: z.string().optional(),
pstgPrdSeCd: z.string(),
pstgPrdSeNm: z.string(),
delYn: z.string(),
});
export const withModePostSchema = postSchema
.extend({
mode: z.string(),
})
.omit({
siteNm: true,
pstgTypeNm: true,
pstgPrdSeNm: true,
});
export const postingFormSchema = z.object({
pstg: z.array(withModePostSchema),
});
export type Post = z.infer<typeof postSchema>;
export type WithModePost = z.infer<typeof withModePostSchema>;
export type PostingFormData = z.infer<typeof postingFormSchema>;
export interface PostService {
getPostingHistory: (params: PostingParams) => Promise<PageableList<Post>>;
requestPosting: (data: WithModePost[]) => Promise<Post[]>;
}
@@ -0,0 +1,323 @@
import dayjs from "dayjs";
import { useState } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { useFieldArray, useForm } from "react-hook-form";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import {
Dialog,
DialogTrigger,
Button,
DialogContent,
DialogHeader,
DialogTitle,
Badge,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
Checkbox,
Select,
DateRangePicker,
DialogClose,
DialogFooter,
} from "@common/components/ui";
import { cn } from "@common/components/lib";
import { CodeSelect } from "@/entities/code";
import { SiteApi, type Site } from "@/entities/site";
import type { PageableList } from "@/shared/model";
import { ENDPOINT } from "@/shared/config";
import { PostingApi } from "../api/posting-service";
import {
postingFormSchema,
type PostingFormData,
type PostingType,
type WithModePost,
} from "../model/posting-interface";
import { useAlertStore } from "@/shared/lib/use-alert-store";
type DateRange = {
from: string;
to?: string;
};
type PostingTarget = {
pstgTrgtNm: string;
pstgTrgtNo: number;
};
type PostingDialogProps = {
postingType: PostingType;
postingTargets: PostingTarget[];
};
const POSTING_TYPE_LABEL = {
POPUP: "팝업",
BANNER: "배너",
IMAGE: "이미지",
} as const;
function PostingDialog({ postingType, postingTargets }: PostingDialogProps) {
const { confirm } = useConfirm();
const { setMessage: alert } = useAlertStore((state) => state);
const [selectedRows, setSelectedRows] = useState<number[]>([]);
const [rememberPeriodCode, setRememberPeriodCode] = useState<
Record<string, string>
>({});
const [rememberPeriodDate, setRememberPeriodDate] = useState<
Record<string, DateRange | undefined>
>({});
const { data: siteList } = useQuery<PageableList<Site>>({
queryKey: [ENDPOINT.CMS_SERVICE.SITES],
queryFn: () => SiteApi.getSiteList({}),
});
const { mutateAsync: requestPosting } = useMutation({
mutationFn: (data: WithModePost[]) => PostingApi.requestPosting(data),
onSuccess: () => {
alert("저장되었습니다.");
},
});
const form = useForm<PostingFormData>({
resolver: zodResolver(postingFormSchema),
});
const { fields, append, replace } = useFieldArray({
control: form.control,
name: "pstg",
});
const isFormValid =
fields.length && fields.every((field) => field.pstgPrdSeCd !== "");
const isAllSelected =
siteList && selectedRows.length === siteList.content.length;
const postingPeriod = (siteId: string) => {
const periodCode = Number(rememberPeriodCode[siteId]);
if (periodCode === 99) return "상시";
return `${dayjs().format("YYYY-MM-DD")} ~ ${dayjs()
.add(periodCode, "day")
.format("YYYY-MM-DD")}`;
};
const handleOpenChange = (open: boolean) => {
if (open) return true;
replace([]);
setSelectedRows([]);
setRememberPeriodCode({});
setRememberPeriodDate({});
};
const handleAppendFields = (i: number) => {
const siteId = siteList?.content[i]?.siteId ?? "";
const newFields = postingTargets.map((target) => ({
siteId,
pstgTypeCd: postingType,
pstgTrgtNo: target.pstgTrgtNo,
pstgBgngDt: rememberPeriodDate[siteId]?.from ?? "",
pstgEndDt: rememberPeriodDate[siteId]?.to ?? "",
pstgPrdSeCd: rememberPeriodCode[siteId] ?? "",
delYn: "N",
mode: "C",
}));
append(newFields);
};
const handleUpdateFields =
(siteId: string) => (obj: Record<string, unknown>) => {
const updatedFields = fields.map((field) =>
"siteId" in field && field.siteId === siteId
? { ...field, ...obj }
: field,
);
replace(updatedFields);
};
const handleRemoveFields = (siteId: string) => {
const filteredFields = fields.filter(
(field) => "siteId" in field && field.siteId !== siteId,
);
replace(filteredFields);
};
const handleSelectRow = (i: number) => {
const isSelected = selectedRows.includes(i);
setSelectedRows((prev) =>
isSelected ? prev.filter((j) => j !== i) : [...prev, i],
);
if (isSelected) {
const siteId = siteList?.content[i]?.siteId;
if (!siteId) return;
handleRemoveFields(siteId);
return;
}
handleAppendFields(i);
};
const handleSelectAll = () => {
if (selectedRows.length === (siteList?.content.length ?? 0)) {
replace([]);
setSelectedRows([]);
} else {
replace([]);
setSelectedRows(siteList?.content.map((_, i) => i) ?? []);
siteList?.content.forEach((_, i) => handleAppendFields(i));
}
};
const handlePeriodCodeChange = (siteId: string) => (value: string) => {
const from = dayjs().format("YYYY-MM-DD 00:00:00");
const to = dayjs().add(Number(value), "day").format("YYYY-MM-DD 23:59:59");
setRememberPeriodCode((prev) => ({
...prev,
[siteId]: value,
}));
setRememberPeriodDate((prev) => ({
...prev,
[siteId]: { from, to },
}));
handleUpdateFields(siteId)({
pstgPrdSeCd: value,
pstgBgngDt: from,
pstgEndDt: to,
});
};
const handlePeriodDateChange =
(siteId: string) => (value: DateRange | undefined) => {
const from = dayjs(value?.from).format("YYYY-MM-DD 00:00:00");
const to = dayjs(value?.to).format("YYYY-MM-DD 23:59:59");
setRememberPeriodDate((prev) => ({
...prev,
[siteId]: { from, to },
}));
handleUpdateFields(siteId)({
pstgBgngDt: from,
pstgEndDt: to,
});
};
const handleSave = async () => {
if (await confirm("저장하시겠습니까?")) {
const data = form.getValues("pstg");
await requestPosting(data);
}
};
return (
<Dialog onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button color="emerald" disabled={!postingTargets.length}>
<i className="diveicon di-layer" />
사이트반영
</Button>
</DialogTrigger>
<DialogContent className="max-w-[68rem]" aria-describedby={undefined}>
<DialogHeader>
<DialogTitle>사이트 반영</DialogTitle>
</DialogHeader>
<div className="card bg-accent !p-4">
<h3 className="font-semibold">
선택된 {POSTING_TYPE_LABEL[postingType]}
</h3>
<div className="mt-4 flex flex-wrap gap-3">
{postingTargets.map((target) => (
<Badge key={target.pstgTrgtNo}>
<span className="text-xl">{target.pstgTrgtNm}</span>
</Badge>
))}
</div>
</div>
<div className="m-2 max-h-[30rem] overflow-auto">
<Table variant="secondary">
<colgroup>
<col width="10%" />
<col width="25%" />
<col width="65%" />
</colgroup>
<TableHeader className="sticky top-0 z-10 bg-accent">
<TableRow>
<TableHead className="!px-0">
<Checkbox
checked={isAllSelected}
onCheckedChange={handleSelectAll}
/>
</TableHead>
<TableHead>사이트명</TableHead>
<TableHead>게시 구분</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{siteList?.content.map((site, i) => (
<TableRow key={site.siteId}>
<TableCell align="center" className="!px-0">
<Checkbox
checked={selectedRows.includes(i)}
onCheckedChange={() => handleSelectRow(i)}
/>
</TableCell>
<TableCell align="center">{site.siteNm}</TableCell>
<TableCell align="left">
<div className="flex items-center gap-4">
<PostingPeriodSelect
onValueChange={handlePeriodCodeChange(site.siteId)}
disabled={!selectedRows.includes(i)}
/>
{!!Number(rememberPeriodCode[site.siteId]) && (
<span
className={cn(
"text-lg text-label",
!selectedRows.includes(i) && "text-muted",
)}
>
게시 기간: <u>{postingPeriod(site.siteId)}</u>
</span>
)}
{Number(rememberPeriodCode[site.siteId]) === 0 && (
<DateRangePicker
handleDateChange={(date) =>
handlePeriodDateChange(site.siteId)(
date as DateRange | undefined,
)
}
disabled={!selectedRows.includes(i)}
/>
)}
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
<DialogFooter className="!justify-center">
<Button size="lg" onClick={handleSave} disabled={!isFormValid}>
저장
</Button>
<DialogClose asChild>
<Button size="lg" color="white">
취소
</Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
function PostingPeriodSelect({
...props
}: React.ComponentPropsWithoutRef<typeof Select>) {
return <CodeSelect upCd="PSTGPRDCD" {...props} />;
}
export { PostingDialog };
+10 -10
View File
@@ -1,25 +1,25 @@
import { client } from "@/shared/api/client";
import { ENDPOINT } from "@/shared/config/api";
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import {
siteFormSchema,
type ISiteInfo,
type SiteService,
type ISiteDetail,
type ISiteParams,
type SiteList,
type SiteDetail,
type SiteParams,
type SiteFormData,
} from "../model/site-interface";
export class SiteApiService implements SiteService {
public async siteInfo(params: ISiteParams): Promise<ISiteInfo> {
const response = await client.get<ISiteInfo>(
public async getSiteList(params?: SiteParams): Promise<SiteList> {
const response = await client.get<SiteList>(
`${ENDPOINT.CMS_SERVICE.SITES}`,
{ params },
);
return response.data;
}
public async siteDetail(siteId: string): Promise<ISiteDetail> {
const response = await client.get<ISiteDetail>(
public async siteDetail(siteId: string): Promise<SiteDetail> {
const response = await client.get<SiteDetail>(
`${ENDPOINT.CMS_SERVICE.SITES}/${siteId}`,
);
return response.data;
@@ -34,7 +34,7 @@ export class SiteApiService implements SiteService {
return response.data;
}
public async modifySite(siteId: string, data: SiteFormData): Promise<void> {
public async updateSite(siteId: string, data: SiteFormData): Promise<void> {
const validatedData = siteFormSchema.parse(data);
const response = await client.put<void>(
`${ENDPOINT.CMS_SERVICE.SITES}/${siteId}`,
+6 -1
View File
@@ -1,2 +1,7 @@
export { SiteApi } from "./api/site-service";
export * from "./model/site-interface";
export {
siteFormSchema,
type SiteParams,
type Site,
type SiteFormData,
} from "./model/site-interface";
@@ -1,15 +1,13 @@
import { z } from "zod";
import type { PageableParams, PageableList } from "@/shared/model";
export interface ISiteParams {
siteNm: string;
siteKndCd: string;
useYn: string;
page: number;
size: number;
sort: string[];
export interface SiteParams extends PageableParams {
siteNm?: string;
siteKndCd?: string;
useYn?: string;
}
export interface ISite {
export interface Site {
siteId: string;
siteNm: string;
siteKindCode: string;
@@ -18,38 +16,10 @@ export interface ISite {
useYn: string;
regDt: string;
rgTrNm: string;
dmnAddr: string;
}
export interface ISiteInfo {
totalPages: number;
totalElements: number;
number: number;
sort: {
empty: boolean;
sorted: boolean;
unsorted: boolean;
};
size: number;
content: ISite[];
pageable: {
sort: {
empty: boolean;
sorted: boolean;
unsorted: boolean;
};
offset: number;
pageNumber: number;
pageSize: number;
paged: boolean;
unpaged: boolean;
};
numberOfElements: number;
first: boolean;
last: boolean;
empty: boolean;
}
export interface ISiteDetail extends SiteFormData {
export interface SiteDetail extends SiteFormData {
siteId: string;
siteKindNm: string;
basicSiteYn: string;
@@ -59,29 +29,31 @@ export interface ISiteDetail extends SiteFormData {
mdfcnDt: string;
mdFr: string;
rgTrNm: string;
mdFrNm: string;
mdfrNm: string;
}
export const siteFormSchema = z.object({
siteId: z.string().max(2).nonempty(),
siteNm: z.string().max(100).nonempty(),
siteExpln: z.string().max(1000).optional(),
siteExpln: z.string().max(1000).nullable(),
siteKndCd: z.string().max(10).nonempty(),
siteAddr: z.string().max(2000).optional(),
faxNo: z.string().max(100).optional(),
telNo: z.string().max(1000).optional(),
lwndCn: z.string().max(2000).optional(),
siteAddr: z.string().max(2000).nullable(),
faxNo: z.string().max(100).nullable(),
telNo: z.string().max(1000).nullable(),
lwndCn: z.string().max(2000).nullable(),
bscSiteYn: z.string(),
bkmkIcon: z.string().max(100).optional(),
bkmkIcon: z.string().max(100).nullable(),
useYn: z.string(),
siteSkn: z.string().max(10).optional(),
siteSkn: z.string().max(10).nullable(),
dmnAddr: z.string().nullable(),
});
export type SiteFormData = z.infer<typeof siteFormSchema>;
export type SiteList = PageableList<Site>;
export interface SiteService {
siteInfo(query: ISiteParams): Promise<ISiteInfo>;
siteDetail(siteId: string): Promise<ISiteDetail>;
modifySite(siteId: string, data: SiteFormData): Promise<void>;
getSiteList(params: SiteParams): Promise<SiteList>;
siteDetail(siteId: string): Promise<SiteDetail>;
updateSite(siteId: string, data: SiteFormData): Promise<void>;
createSite(data: SiteFormData): Promise<void>;
}
@@ -1,15 +0,0 @@
import { client } from "@/shared/api/client";
import { ENDPOINT } from "@/shared/config/api";
import type { IUser, IUserInfo, UserService } from "../model/user-interface";
export class UsersApiService implements UserService {
public async userInfo(payload: IUser): Promise<IUserInfo> {
const response = await client.get<IUserInfo>(
`${ENDPOINT.USER_SERVICE.USERS}/${payload.userUniqId}`,
);
return response.data;
}
}
export const UserApi = new UsersApiService();
-1
View File
@@ -1 +0,0 @@
export { useUser } from "./lib/use-user";
-20
View File
@@ -1,20 +0,0 @@
import { useQuery } from "@tanstack/react-query";
import { ENDPOINT } from "@/shared/config/api";
import { AUTH_USER_ID } from "@/shared/config/env";
import { useCookie } from "@/shared/provider";
import { UserApi } from "../api/user-service";
const useUser = () => {
const { getCookie } = useCookie();
const { data } = useQuery({
queryKey: [ENDPOINT.USER_SERVICE.USERS],
queryFn: () =>
UserApi.userInfo({
userUniqId: getCookie(AUTH_USER_ID) ?? "",
}),
});
return { userInfo: data };
};
export { useUser };
@@ -2,7 +2,7 @@
import Image from "next/image";
import { images } from "@common/assets";
import { LoginApi } from "@/entities/auth/login";
import { LoginApi } from "@/entities/auth";
import "./login.css";
function LoginPage() {
@@ -13,7 +13,8 @@ function LoginPage() {
const userId = formData.get("id") as string;
const password = formData.get("password") as string;
LoginApi.login({ userId, password });
await LoginApi.login({ userId, password });
window.location.href = "/dashboard";
};
return (
+1
View File
@@ -0,0 +1 @@
export { DashboardPage } from "./ui/dashboard-page";
@@ -0,0 +1,5 @@
function DashboardPage() {
return <></>;
}
export { DashboardPage };
@@ -0,0 +1,47 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type {
Image,
ImageFormData,
ImageList,
ImageParams,
ImageService,
} from "../model/image-interface";
export class ImageApiService implements ImageService {
public async getImageList(params: ImageParams): Promise<ImageList> {
const response = await client.get<ImageList>(
`${ENDPOINT.CMS_SERVICE.IMAGES}`,
{
params,
},
);
return response.data;
}
public async getImageInfo(imgSn: string): Promise<Image> {
const response = await client.get<Image>(
`${ENDPOINT.CMS_SERVICE.IMAGES}/${imgSn}`,
);
return response.data;
}
public async createImage(data: ImageFormData): Promise<void> {
const response = await client.post<void>(ENDPOINT.CMS_SERVICE.IMAGES, data);
return response.data;
}
public async updateImage(imgSn: string, data: ImageFormData): Promise<void> {
const response = await client.put<void>(
`${ENDPOINT.CMS_SERVICE.IMAGES}/${imgSn}`,
data,
);
return response.data;
}
public async deleteImage(imgSn: string): Promise<void> {
await client.delete(`${ENDPOINT.CMS_SERVICE.IMAGES}/${imgSn}`);
}
}
export const ImageApi = new ImageApiService();
+3
View File
@@ -0,0 +1,3 @@
export { CreatePage } from "./ui/create-page";
export { ModifyPage } from "./ui/modify-page";
export { ImagePage } from "./ui/image-page";
+61
View File
@@ -0,0 +1,61 @@
import { Upload, type HttpResponse } from "tus-js-client";
import { getCookie, setCookie } from "@/shared/lib";
import { AUTH_USER_ID, CLAIM_NAME, ENDPOINT } from "@/shared/config";
type UploadOptions = {
handleUploadStart?: (upload: Upload) => void;
handleProgress?: (percentage: string) => void;
handleSuccess?: (upload: Upload) => void;
handleResponse?: (res: HttpResponse) => void;
};
export const handleUpload = (files: FileList, options?: UploadOptions) => {
let metadata = {};
const file = files.item(0);
if (!file) return;
metadata = {
filename: file.name,
filetype: file.type,
};
const atflCd = getCookie("atfl-cd-key");
if (atflCd) {
metadata = {
...metadata,
atflCd,
};
}
const upload = new Upload(file, {
endpoint: `${ENDPOINT.ATTACH_SERVICE.TUS_UPLOAD}`,
chunkSize: 10 * 1024 * 1024,
headers: {
[CLAIM_NAME]: getCookie(CLAIM_NAME) ?? "",
[AUTH_USER_ID]: getCookie(AUTH_USER_ID) ?? "",
},
metadata,
onError(error) {
console.error(`Failed because: ${error}`);
},
onProgress(bytesUploaded, bytesTotal) {
const percentage = ((bytesUploaded / bytesTotal) * 100).toFixed(2);
options?.handleProgress?.(percentage);
},
onAfterResponse(req, res) {
const fileInfo = res.getHeader("X-File-Info");
if (fileInfo === undefined || fileInfo === null) return;
setCookie("atfl-cd-key", JSON.parse(fileInfo)?.atflCd ?? "");
options?.handleResponse?.(res);
},
onSuccess() {
options?.handleSuccess?.(upload);
},
});
upload.start();
options?.handleUploadStart?.(upload);
console.log("upload start >>>>>", upload);
};
@@ -0,0 +1,52 @@
import { z } from "zod";
import type { PageableList, PageableParams } from "@/shared/model";
export const IMAGE_TYPE = {
IMGSUB: "IMGSUB",
IMGMAIN: "IMGMAIN",
IMGLOGIN: "IMGLOGIN",
} as const;
export type ImageType = (typeof IMAGE_TYPE)[keyof typeof IMAGE_TYPE];
export interface ImageParams extends PageableParams {
keyword: string;
imgTypeCd?: string;
useYn?: string;
}
export interface Image {
imgSn: number;
imgTypeCd: string;
imgTypeNm: string;
imgTtl: string;
lnkgUrlAddr: string;
atflYn: string;
sortSeq: number;
atflCd: string;
useYn: string;
mdfcnDt: string;
mdFr: string;
mdfrNm: string;
}
export const imageFormSchema = z.object({
imgTtl: z.string(),
sortSeq: z.number(),
imgTypeCd: z.string(),
atflYn: z.string(),
atflCd: z.string().nullish(),
lnkgUrlAddr: z.string().nullish(),
useYn: z.string(),
});
export type ImageFormData = z.infer<typeof imageFormSchema>;
export type ImageList = PageableList<Image>;
export interface ImageService {
getImageList: (params: ImageParams) => Promise<ImageList>;
getImageInfo: (imgSn: string) => Promise<Image>;
createImage: (data: ImageFormData) => Promise<void>;
updateImage: (imgSn: string, data: ImageFormData) => Promise<void>;
deleteImage: (imgSn: string) => Promise<void>;
}
@@ -0,0 +1,74 @@
"use client";
import dayjs from "dayjs";
import { type ColumnDef } from "@tanstack/react-table";
import { Checkbox } from "@common/components/ui";
import { type Image } from "./image-interface";
import { IMAGE_TYPE } from "./image-interface";
export const columns: ColumnDef<Image>[] = [
{
id: "select",
header: ({ table }) => (
<Checkbox
checked={table.getIsAllPageRowsSelected()}
onClick={(e) => e.stopPropagation()}
onCheckedChange={(checked) =>
table.toggleAllPageRowsSelected(!!checked)
}
className="h-4 w-4 rounded border-gray-300"
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onClick={(e) => e.stopPropagation()}
onCheckedChange={(checked) => row.toggleSelected(!!checked)}
className="h-4 w-4 rounded border-gray-300"
/>
),
},
{
accessorKey: "imgSn",
header: "NO",
cell: ({ row }) => row.index + 1,
},
{
accessorKey: "imgTypeCd",
header: "이미지구분",
cell: ({ row }) => {
const type = row.getValue("imgTypeCd") as string;
switch (type) {
case IMAGE_TYPE.IMGSUB:
return "서브이미지";
case IMAGE_TYPE.IMGMAIN:
return "메인이미지";
case IMAGE_TYPE.IMGLOGIN:
return "로그인이미지";
default:
return type;
}
},
},
{
accessorKey: "imgTtl",
header: "이미지명",
},
{
accessorKey: "useYn",
header: "사용여부",
cell: ({ row }) => (row.getValue("useYn") === "Y" ? "사용" : "미사용"),
},
{
accessorKey: "mdfrNm",
header: "최종수정자",
},
{
accessorKey: "mdfcnDt",
header: "최종수정일",
cell: ({ row }) => {
const date = row.getValue("mdfcnDt") as string;
return date ? dayjs(date).format("YYYY-MM-DD") : "";
},
},
];
@@ -0,0 +1,44 @@
"use client";
import dayjs from "dayjs";
import type { ColumnDef } from "@tanstack/react-table";
import { Checkbox } from "@common/components/ui";
import type { Post } from "@/entities/posting";
export const columns: ColumnDef<Post>[] = [
{
id: "select",
header: ({ table }) => (
<Checkbox
checked={table.getIsAllPageRowsSelected()}
onClick={(e) => e.stopPropagation()}
onCheckedChange={(checked) =>
table.toggleAllPageRowsSelected(!!checked)
}
className="h-4 w-4 rounded border-gray-300"
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onClick={(e) => e.stopPropagation()}
onCheckedChange={(checked) => row.toggleSelected(!!checked)}
className="h-4 w-4 rounded border-gray-300"
/>
),
},
{
accessorKey: "siteNm",
header: "사이트",
},
{
accessorKey: "pstgPrdSeNm",
header: "게시기간",
cell: ({ row }) => {
const pstgPrdSeNm = row.original.pstgPrdSeNm;
const pstgBgngDt = row.original.pstgBgngDt;
const pstgEndDt = row.original.pstgEndDt;
return `${pstgPrdSeNm} (${dayjs(pstgBgngDt).format("YYYY-MM-DD")} ~ ${dayjs(pstgEndDt).format("YYYY-MM-DD")})`;
},
},
];
@@ -0,0 +1,40 @@
"use client";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation } from "@tanstack/react-query";
import { useAlertStore } from "@/shared/lib/use-alert-store";
import { imageFormSchema, type ImageFormData } from "../model/image-interface";
import { ImageApi } from "../api/image-service";
import { ImageForm } from "./image-form";
function CreatePage() {
const router = useRouter();
const { setMessage: alert } = useAlertStore((state) => state);
const { mutateAsync: createImage } = useMutation({
mutationFn: (data: ImageFormData) => ImageApi.createImage(data),
onSuccess: () => {
alert("등록되었습니다.", router.back);
},
});
const form = useForm<ImageFormData>({
resolver: zodResolver(imageFormSchema),
defaultValues: {
atflYn: "Y",
},
});
return (
<div className="card card-border !mt-6">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">이미지 등록</h3>
</div>
<ImageForm form={form} handleSave={createImage} />
</div>
);
}
export { CreatePage };
+341
View File
@@ -0,0 +1,341 @@
"use client";
import Image from "next/image";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import type { UseFormReturn } from "react-hook-form";
import type { HttpResponse, Upload } from "tus-js-client";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import {
Button,
FileUploader,
Input,
Label,
Progress,
RadioGroup,
RadioGroupItem,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
} from "@common/components";
import { CodeSelect } from "@/entities/code";
import { AttachmentApi } from "@/entities/attachment";
import { ENDPOINT } from "@/shared/config";
import { Form, FormControl, FormField, FormItem } from "@/shared/ui/form";
import type { ImageFormData } from "../model/image-interface";
import { handleUpload } from "../lib/utils";
type ImageFormProps = {
form: UseFormReturn<ImageFormData>;
imgSn?: string;
handleSave: (data: ImageFormData) => Promise<void>;
handleDelete?: () => Promise<void>;
};
function ImageForm({ form, imgSn, handleSave, handleDelete }: ImageFormProps) {
const isModifyMode = !!imgSn;
const atflYn = form.watch("atflYn");
const router = useRouter();
const { confirm } = useConfirm();
const [attachmentFileId, setAttachmentFileId] = useState("");
const [upload, setUpload] = useState<Upload | null>(null);
const [progress, setProgress] = useState(0);
const { data: atflId } = useQuery({
queryKey: [ENDPOINT.ATTACH_SERVICE.ATTACHMENTS],
queryFn: () => AttachmentApi.getAttachments(form.getValues("atflCd")!),
enabled: !!form.getValues("atflCd"),
select: (data) => data?.[data.length - 1]?.atflId,
});
const onSubmit = async (data: ImageFormData) => {
const confirmMessage = isModifyMode
? "수정하시겠습니까?"
: "저장하시겠습니까?";
if (await confirm(confirmMessage)) {
await handleSave(data);
}
};
const onDelete = async () => {
if (await confirm("삭제하시겠습니까?")) {
await handleDelete?.();
}
};
const handleProgress = (percentage: string) => {
setProgress(Number(percentage));
};
const handleUploadResponse = async (res: HttpResponse) => {
const fileInfo = res.getHeader("X-File-Info");
if (fileInfo === undefined || fileInfo === null) return;
const { atflCd, atflId } = JSON.parse(fileInfo) ?? {};
if (atflCd) form.setValue("atflCd", atflCd);
if (atflId) setAttachmentFileId(atflId);
};
useEffect(() => {
if (atflId) setAttachmentFileId(atflId);
}, [atflId]);
return (
<>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<div className="card">
<Table variant="secondary">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<TableBody>
<TableRow>
<TableHead>이미지명</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="imgTtl"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="이미지명을 입력해주세요"
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>정렬순서</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="sortSeq"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
type="number"
min={0}
value={field.value ?? ""}
onChange={(e) => {
const value = e.target.value;
if (isNaN(Number(value))) return;
field.onChange(Number(value));
}}
className="w-[12rem] !text-[1.3rem]"
placeholder="정렬순서를 입력해주세요"
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>이미지유형</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="imgTypeCd"
render={({ field }) => (
<FormItem>
<FormControl>
<CodeSelect
{...field}
value={field.value ?? ""}
upCd="IMGTYPE"
onValueChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>첨부파일</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="atflYn"
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
{...field}
name="atflYn"
onValueChange={field.onChange}
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="Y" id="atflY" />
<Label htmlFor="atflY">이미지파일</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="N" id="atflN" />
<Label htmlFor="atflN">외부링크</Label>
</div>
</RadioGroup>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
{atflYn === "Y" && (
<TableRow>
<TableHead>이미지파일</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="atflCd"
render={() => (
<FormItem className="flex flex-col">
<FormControl>
<FileUploader
id="atflCd"
className="!h-auto !max-w-none flex-col !items-start"
accept=".jpeg,.jpg,.png"
onUpload={(e) => {
const files = e.target.files;
if (!files) return;
handleUpload(files, {
handleUploadStart: setUpload,
handleProgress,
handleSuccess: setUpload,
handleResponse: handleUploadResponse,
});
}}
customPreview={
<>
<Label htmlFor="atflCd">
<div className="relative h-[27rem] w-[48rem] overflow-hidden rounded-sm border border-border bg-accent">
<p className="absolute bottom-3 left-0 p-2 text-base leading-none">
{(upload?.file as File)?.name}
</p>
<div className="relative h-full w-full">
{attachmentFileId && (
<Image
src={`${ENDPOINT.ATTACH_SERVICE.IMAGES}/${attachmentFileId}`}
alt="업로드된 이미지"
fill
objectFit="contain"
/>
)}
</div>
<Progress
value={progress}
className="absolute bottom-0 left-0"
/>
</div>
</Label>
<div className="mb-2 text-lg font-medium text-label">
<ul className="ml-10 list-disc">
<li>권장 사이즈: 1920x500</li>
<li>파일 최대 크기: 2MB</li>
<li>확장자: jpg, jpeg, png 가능</li>
</ul>
</div>
</>
}
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
)}
{atflYn === "N" && (
<TableRow>
<TableHead>외부링크</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="lnkgUrlAddr"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="외부링크를 입력해주세요"
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
)}
<TableRow>
<TableHead>사용여부</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="useYn"
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
{...field}
name="useYn"
onValueChange={field.onChange}
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="Y" id="useY" />
<Label htmlFor="useY">사용</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="N" id="useN" />
<Label htmlFor="useN">미사용</Label>
</div>
</RadioGroup>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
<div className="flex justify-center gap-4 pb-12 pt-10">
<Button
size="lg"
color="white"
type="button"
onClick={() => router.back()}
>
목록
</Button>
<Button size="lg" type="submit">
저장
</Button>
{isModifyMode && (
<Button size="lg" color="red" type="button" onClick={onDelete}>
삭제
</Button>
)}
</div>
</form>
</Form>
</>
);
}
export { ImageForm };
+118
View File
@@ -0,0 +1,118 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import {
getCoreRowModel,
useReactTable,
type RowSelectionState,
} from "@tanstack/react-table";
import { Button, DataTable, Input, Label } from "@common/components";
import { POSTING_TYPE, PostingDialog } from "@/entities/posting";
import { ENDPOINT } from "@/shared/config";
import { ImageApi } from "../api/image-service";
import { columns } from "../model/image-table-columns";
import { type Image, type ImageParams } from "../model/image-interface";
type PostingTarget = {
pstgTrgtNm: string;
pstgTrgtNo: number;
};
function ImagePage() {
const router = useRouter();
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const [postingTargets, setPostingTargets] = useState<PostingTarget[]>([]);
const [imageQuery, setImageQuery] = useState<ImageParams>({ keyword: "" });
const { data: imageList, refetch } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.IMAGES],
queryFn: () => ImageApi.getImageList(imageQuery),
enabled: false,
});
const table = useReactTable({
data: imageList?.content ?? [],
columns,
state: {
rowSelection,
},
enableMultiRowSelection: true,
getCoreRowModel: getCoreRowModel(),
onRowSelectionChange: setRowSelection,
});
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
refetch();
};
const handleRowClick = (row: Image) => {
router.push(`/image/register/${row.imgSn}`);
};
useEffect(() => {
const postingTargets = table
.getFilteredSelectedRowModel()
.rows.map((row) => ({
pstgTrgtNm: row.original.imgTtl,
pstgTrgtNo: row.original.imgSn,
}));
if (!postingTargets.length) {
setPostingTargets([]);
return;
}
setPostingTargets(postingTargets);
}, [rowSelection]);
useEffect(() => {
refetch();
}, []);
return (
<div className="card card-border !mt-6">
<div className="card card-border">
<form onSubmit={handleSubmit} className="flex items-center gap-2 p-2">
<Label htmlFor="" className="mr-2 text-label">
이미지명
</Label>
<Input
className="h-[3.2rem] w-[24rem] rounded-sm !text-[1.3rem]"
value={imageQuery.keyword}
onChange={(e) =>
setImageQuery({ ...imageQuery, keyword: e.target.value })
}
/>
<Button className="h-[3.2rem]" type="submit">
조회
</Button>
</form>
</div>
<div className="card card-border">
<div className="card-header">
<div className="flex w-full items-center justify-between">
<h3 className="text-2xl font-medium text-label">이미지 목록</h3>
<div className="flex gap-2">
<PostingDialog
postingType={POSTING_TYPE.IMAGE}
postingTargets={postingTargets}
/>
<Button onClick={() => router.push("/image/register")}>
등록
</Button>
</div>
</div>
</div>
<div className="card !m-[1.2rem] h-[49rem] overflow-auto !p-0">
<DataTable table={table} onRowClick={handleRowClick} />
</div>
</div>
</div>
);
}
export { ImagePage };
+137
View File
@@ -0,0 +1,137 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
getCoreRowModel,
useReactTable,
type RowSelectionState,
} from "@tanstack/react-table";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { Button, DataTable } from "@common/components/ui";
import { PostingApi, type WithModePost } from "@/entities/posting";
import { useAlertStore } from "@/shared/lib/use-alert-store";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
import { ENDPOINT } from "@/shared/config";
import { imageFormSchema, type ImageFormData } from "../model/image-interface";
import { columns } from "../model/posting-table-columns";
import { ImageApi } from "../api/image-service";
import { ImageForm } from "./image-form";
function ModifyPage({ serial }: { serial: string }) {
const router = useRouter();
const { confirm } = useConfirm();
const queryClient = useQueryClient();
const { setMessage: alert } = useAlertStore((state) => state);
const [onConfirm, setOnConfirm] = useState(false);
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const { data: imageDetail } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.IMAGES, serial],
queryFn: () => ImageApi.getImageInfo(serial),
});
const { data: postHistory } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.SITE_PSTGS, serial],
queryFn: () => PostingApi.getPostingHistory({ pstgTrgtNo: Number(serial) }),
});
const { mutateAsync: updateImage } = useMutation({
mutationFn: (data: ImageFormData) => ImageApi.updateImage(serial, data),
onSuccess: () => {
alert("수정되었습니다.");
},
});
const { mutateAsync: deleteImage } = useMutation({
mutationFn: () => ImageApi.deleteImage(serial),
onSuccess: () => {
alert("삭제되었습니다.", router.back);
},
});
const { mutateAsync: requestPosting } = useMutation({
mutationFn: (data: WithModePost[]) => PostingApi.requestPosting(data),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: [ENDPOINT.CMS_SERVICE.SITE_PSTGS, serial],
});
},
});
const form = useForm<ImageFormData>({
resolver: zodResolver(imageFormSchema),
values: imageDetail,
});
const table = useReactTable({
data: postHistory?.content ?? [],
columns,
state: {
rowSelection,
},
enableMultiRowSelection: true,
getCoreRowModel: getCoreRowModel(),
onRowSelectionChange: setRowSelection,
});
const handleDeletePostingHistory = async () => {
const data = table.getFilteredSelectedRowModel().rows.map((row) => ({
...row.original,
mode: "D",
}));
setOnConfirm(true);
if (await confirm("삭제하시겠습니까?")) {
setOnConfirm(false);
await requestPosting(data);
alert("삭제되었습니다.");
}
setOnConfirm(false);
};
return (
<>
<div className="mt-6 flex flex-col">
<div className="card card-border">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">이미지 수정</h3>
</div>
<ImageForm
form={form}
imgSn={serial}
handleSave={updateImage}
handleDelete={deleteImage}
/>
</div>
<div className="card card-border">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">
사이트 게시 이력
</h3>
</div>
<div className="card">
<div className="mb-4 flex justify-end">
<Button
size="sm"
color="red"
disabled={!table.getFilteredSelectedRowModel().rows.length}
onClick={handleDeletePostingHistory}
>
이력삭제
</Button>
</div>
<DataTable table={table} />
</div>
</div>
</div>
<ConfirmDialog open={onConfirm} />
</>
);
}
export { ModifyPage };
@@ -0,0 +1,19 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type {
ContentService,
ContentParams,
ContentList,
} from "../model/content-interface";
export class ContentApiService implements ContentService {
public async getContentList(params: ContentParams): Promise<ContentList> {
const response = await client.get<ContentList>(
`${ENDPOINT.CMS_SERVICE.CONTENTS}`,
{ params },
);
return response.data;
}
}
export const ContentApi = new ContentApiService();
@@ -0,0 +1,68 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type {
Menu,
MenuFormData,
MenuService,
TreeMenu,
TreeNode,
} from "../model/menu-interface";
export class MenuApiService implements MenuService {
public async getMenuInfo(menuCd: number): Promise<Menu> {
const response = await client.get<Menu>(
`${ENDPOINT.CMS_SERVICE.MENUS}/${menuCd}`,
);
return response.data;
}
public async createMenu(data: MenuFormData): Promise<void> {
const response = await client.post<void>(
`${ENDPOINT.CMS_SERVICE.MENUS}`,
data,
);
return response.data;
}
public async updateMenu(
menuCd: number,
data: Omit<MenuFormData, "siteId">,
): Promise<void> {
const response = await client.put<void>(
`${ENDPOINT.CMS_SERVICE.MENUS}/${menuCd}`,
data,
);
return response.data;
}
public async deleteMenu(menuCd: number): Promise<void> {
const response = await client.delete<void>(
`${ENDPOINT.CMS_SERVICE.MENUS}/${menuCd}`,
);
return response.data;
}
public async getTreeMenuList(siteId: string): Promise<TreeMenu[]> {
const response = await client.get<TreeMenu[]>(
`${ENDPOINT.CMS_SERVICE.MENUS}/${siteId}/tree`,
);
return response.data;
}
public async updateTreeMenu(siteId: string, data: TreeNode[]): Promise<void> {
const response = await client.put<void>(
`${ENDPOINT.CMS_SERVICE.MENUS}/${siteId}/tree`,
data,
);
return response.data;
}
public async updateMenuName(menuCd: number, name: string): Promise<void> {
const response = await client.put<void>(
`${ENDPOINT.CMS_SERVICE.MENUS}/${menuCd}/${name}`,
);
return response.data;
}
}
export const MenuApi = new MenuApiService();
@@ -0,0 +1,17 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type {
Organization,
OrganizationService,
} from "../model/organization-interface";
export class OrganizationApiService implements OrganizationService {
public async getOrganizationUserTreeList(): Promise<Organization[]> {
const response = await client.get<Organization[]>(
`${ENDPOINT.CMS_SERVICE.USER_OGNZ}/treeuser`,
);
return response.data;
}
}
export const OrganizationApi = new OrganizationApiService();
+1
View File
@@ -0,0 +1 @@
export { MenuPage } from "./ui/menu-page";
+165
View File
@@ -0,0 +1,165 @@
import type { DropOptions, NodeModel } from "@minoru/react-dnd-treeview";
import type { TreeMenu, TreeNode } from "../model/menu-interface";
import type { Organization, User } from "../model/organization-interface";
export const generateMenuTreeData = (
data: TreeMenu[],
): NodeModel<TreeMenu>[] => {
return data.reduce<NodeModel<TreeMenu>[]>((acc, menu) => {
const node: NodeModel<TreeMenu> = {
id: menu.menuCd ?? 0,
parent: menu.parentId ?? 0,
text: menu.menuKornNm,
droppable: true,
data: menu,
};
acc.push(node);
if (menu.children?.length) {
acc.push(...generateMenuTreeData(menu.children));
}
return acc;
}, []);
};
export const generateNewMenuTreeData = (
treeData: NodeModel<TreeMenu>[],
options: DropOptions<TreeMenu>,
): TreeNode | null => {
const { dragSourceId, dragSource, dropTargetId, dropTarget } = options;
if (!dragSource?.data) return null;
const siblings = treeData.filter((node) => node.parent === dropTargetId);
const dragSourceIndex = siblings.findIndex(
(node) => node.id === dragSourceId,
);
const prevSibling = siblings[dragSourceIndex - 1];
const newSortSeq =
dragSourceIndex === 0 ? 1 : (prevSibling?.data?.sortSeq ?? 0) + 1;
const childNodes = treeData.filter(
(node) => node.parent === dragSourceId && node.data,
);
const baseNode = (node: NodeModel<TreeMenu>): TreeNode => {
if (!node.data) return {};
return {
menuCd: node.data?.menuCd,
name: node.data?.menuKornNm,
icon: node.data?.iconNm,
};
};
const treeNode: TreeNode = {
...baseNode(dragSource),
parentId: dropTargetId === 0 ? null : (dropTargetId as number),
sortSeq: newSortSeq,
levelNo: (dropTarget?.data?.levelNo ?? 0) + 1,
};
const result: TreeNode = {
...treeNode,
children: childNodes.map((child) => ({
...baseNode(child),
parentId: child.data?.parentId === 0 ? null : (dropTargetId as number),
sortSeq: child.data?.sortSeq,
levelNo: (treeNode?.levelNo ?? 0) + 1,
})),
};
return result;
};
export const handleSelectNode =
(callback: (node: NodeModel<TreeMenu>) => void) =>
(node: NodeModel<TreeMenu>) => {
callback(node);
};
export const handleDropNode =
(callback: (newTree: TreeNode) => void) =>
(newTree: NodeModel<TreeMenu>[], options: DropOptions<TreeMenu>) => {
const newTreeData = generateNewMenuTreeData(newTree, options);
if (!newTreeData) return;
callback(newTreeData);
};
export const handleNodeTextChange =
(treeData: NodeModel<TreeMenu>[]) =>
(callback: (newTree: NodeModel<TreeMenu>[]) => void) =>
(id: NodeModel["id"], value: string) => {
const newTree = treeData.map((node) => {
if (node.id === id) {
return {
...node,
text: value,
};
}
return node;
});
callback(newTree);
};
export const generateOrganizationTreeData = (
organizations: Organization[],
): NodeModel<Organization | User>[] => {
return organizations.reduce<NodeModel<Organization | User>[]>((acc, org) => {
const orgNode: NodeModel<Organization> = {
id: org.ognzId,
parent: org.upOgnzId ?? 0,
text: org.ognzNm,
data: org,
droppable: false,
};
acc.push(orgNode);
if (org.children?.length) {
acc.push(...generateOrganizationTreeData(org.children));
}
if (org.users?.length) {
acc.push(
...org.users.map((user) => ({
id: user.userUnqId,
parent: org.ognzId,
text: user.userNm,
data: user,
droppable: false,
})),
);
}
return acc;
}, []);
};
export const filterOrganizationTreeDataByKeyword = (
treeData: NodeModel<Organization | User>[],
keyword: string,
): NodeModel<Organization | User>[] => {
return Array.from(
treeData.reduce((matchedNodes, node) => {
if (!node.text.includes(keyword)) return matchedNodes;
matchedNodes.add(node);
let parentId = node.parent;
while (parentId) {
const parentNode = treeData.find((n) => n.id === parentId);
if (!parentNode) break;
matchedNodes.add(parentNode);
parentId = parentNode.parent;
}
return matchedNodes;
}, new Set<NodeModel<Organization | User>>()),
);
};
@@ -0,0 +1,43 @@
import { createColumnHelper } from "@tanstack/react-table";
import { Checkbox } from "@common/components/ui";
import type { BoardPopup } from "@/entities/board";
const columnHelper = createColumnHelper<BoardPopup>();
const columns = [
columnHelper.accessor((_, index) => index + 1, {
id: "no",
header: "NO",
}),
columnHelper.accessor("bbsNm", {
id: "bbsNm",
header: "게시판명",
}),
columnHelper.accessor("bbsTypeNm", {
id: "bbsTypeNm",
header: "게시판유형",
}),
columnHelper.accessor("regDt", {
id: "regDt",
header: "최초생성일",
}),
columnHelper.accessor("pstCnt", {
id: "pstCnt",
header: "게시물건수",
}),
columnHelper.display({
id: "select",
header: "선택",
cell: ({ row }) => {
return (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={row.getToggleSelectedHandler()}
className="mx-4 flex justify-center"
/>
);
},
}),
];
export { columns };
@@ -0,0 +1,22 @@
import type { PageableList, PageableParams } from "@/shared/model";
export interface ContentParams extends PageableParams {
contsTtl?: string;
aprvContsVer?: number;
useYn?: string;
}
export interface Content {
contsSn: number;
contsTtl: string;
aprvContsVer: number;
useYn: string;
rgtr: string;
regDt: string;
}
export type ContentList = PageableList<Content>;
export interface ContentService {
getContentList(params: ContentParams): Promise<ContentList>;
}
@@ -0,0 +1,32 @@
import { createColumnHelper } from "@tanstack/react-table";
import { Checkbox } from "@common/components/ui";
import type { Content } from "./content-interface";
const columnHelper = createColumnHelper<Content>();
const columns = [
columnHelper.accessor((_, index) => index + 1, {
id: "no",
header: "NO",
}),
columnHelper.accessor("contsTtl", {
id: "contsTtl",
header: "콘텐츠명",
}),
// TODO: 최종수정자, 최종수정일, 승인일시 추가
columnHelper.display({
id: "select",
header: "선택",
cell: ({ row }) => {
return (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={row.getToggleSelectedHandler()}
className="mx-4 flex justify-center"
/>
);
},
}),
];
export { columns };
@@ -0,0 +1,86 @@
import { z } from "zod";
export const MENU_TYPE = {
EMPTY: "EMPTY",
CONTENTS: "CONTENTS",
BOARD: "BOARD",
INSIDE: "INSIDE",
OUTSIDE: "OUTSIDE",
BOTTOM: "BOTTOM",
} as const;
export type MenuType = (typeof MENU_TYPE)[keyof typeof MENU_TYPE];
export interface TreeNode {
menuCd?: number;
name?: string;
sortSeq?: number;
parentId?: number | null;
levelNo?: number;
icon?: string;
children?: TreeNode[];
}
export interface TreeMenu extends Omit<TreeNode, "name" | "icon" | "children"> {
menuKornNm: string;
menuEngNm?: string;
iconNm?: string;
children?: TreeMenu[];
urlPath?: string;
menuLnkgTypeCd: string;
menuLnkgSn?: number;
qrcd?: string;
useYn: string;
otptYn: string;
requiredUrlPath?: boolean;
}
export const menuFormSchema = z.object({
siteId: z.string(),
menuKornNm: z.string(),
menuSubKornNm: z.string().nullish(),
menuEngNm: z.string().nullish(),
menuSubEngNm: z.string().nullish(),
levelNo: z.number(),
urlPath: z.string().nullish(),
iconNm: z.string().nullish(),
menuLnkgTypeCd: z.enum([
MENU_TYPE.EMPTY,
MENU_TYPE.CONTENTS,
MENU_TYPE.BOARD,
MENU_TYPE.INSIDE,
MENU_TYPE.OUTSIDE,
MENU_TYPE.BOTTOM,
]),
menuLnkgSn: z.number().nullish(),
otptYn: z.string().default("Y"),
prntMenuCd: z.number().nullish(),
sortSeq: z.number(),
evlUseYn: z.string().default("Y"),
qrcd: z.string().nullish(),
useYn: z.string().default("Y"),
newWndwYn: z.string().nullish(),
menuLnkgSnNm: z.string().nullish(),
menuPicUserUnqId: z.string().nullish(),
menuPicUserUnqIdNm: z.string().nullish(),
menuPicDsgnYmd: z.string().nullish(),
});
export type MenuFormData = z.infer<typeof menuFormSchema>;
export type Menu = Omit<MenuFormData, "iconNm"> & {
menuCd: number;
iconName?: string;
};
export interface MenuService {
getMenuInfo: (menuCd: number) => Promise<Menu>;
createMenu: (data: MenuFormData) => Promise<void>;
updateMenu: (
menuCd: number,
data: Omit<MenuFormData, "siteId">,
) => Promise<void>;
deleteMenu: (menuCd: number) => Promise<void>;
getTreeMenuList: (siteId: string) => Promise<TreeMenu[]>;
updateTreeMenu: (siteId: string, data: TreeNode[]) => Promise<void>;
updateMenuName: (menuCd: number, name: string) => Promise<void>;
}
@@ -0,0 +1,18 @@
export interface User {
userUnqId: string;
userNm: string;
jbpsSeCd: string;
jbgdSeCd: string;
}
export interface Organization {
ognzId: string;
upOgnzId: string;
ognzNm: string;
users: User[];
children: Organization[];
}
export interface OrganizationService {
getOrganizationUserTreeList(): Promise<Organization[]>;
}
@@ -0,0 +1,124 @@
import { type UseFormReturn } from "react-hook-form";
import {
Input,
Label,
RadioGroup,
RadioGroupItem,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
} from "@common/components";
import { FormItem, FormControl, FormField } from "@/shared/ui/form";
import { MENU_TYPE, type MenuFormData } from "../model/menu-interface";
interface BaseMenuFormProps {
form: UseFormReturn<MenuFormData>;
menuCd?: number;
}
function BaseMenuForm({ form, menuCd }: BaseMenuFormProps) {
return (
<Table variant="secondary">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<TableBody>
{menuCd && (
<TableRow>
<TableHead>메뉴ID</TableHead>
<TableCell className="border">
<div className="h-[3.2rem] w-[21.5rem] cursor-not-allowed rounded-md border border-input bg-form px-3 py-2 text-[1.3rem] opacity-50">
{menuCd}
</div>
</TableCell>
</TableRow>
)}
<TableRow>
<TableHead>메뉴명</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="menuKornNm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="메뉴명을 입력하십시오."
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>메뉴 영문명</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="menuEngNm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="메뉴 영문명을 입력하십시오."
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>메뉴 유형</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="menuLnkgTypeCd"
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
value={field.value}
onValueChange={field.onChange}
>
<div className="flex items-center space-x-4">
{Object.entries(MENU_TYPE).map(([key, value]) => (
<div
key={key}
className="flex items-center space-x-2"
>
<RadioGroupItem value={value} id={key} />
<Label htmlFor={key}>
{key === "EMPTY" && "빈메뉴"}
{key === "CONTENTS" && "콘텐츠"}
{key === "BOARD" && "게시판"}
{key === "INSIDE" && "내부링크"}
{key === "OUTSIDE" && "외부링크"}
{key === "BOTTOM" && "하단메뉴"}
</Label>
</div>
))}
</div>
</RadioGroup>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
</TableBody>
</Table>
);
}
export { BaseMenuForm };
@@ -0,0 +1,95 @@
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
getCoreRowModel,
useReactTable,
type RowSelectionState,
} from "@tanstack/react-table";
import {
Button,
DataTable,
Dialog,
DialogTrigger,
DialogContent,
DialogHeader,
DialogTitle,
Input,
} from "@common/components/ui";
import { ENDPOINT } from "@/shared/config";
import { BoardApi, type BoardPopup } from "@/entities/board";
import { columns } from "../model/board-table-columns";
type BoardSearchDialogProps = {
handleBoardSelect: (board: BoardPopup) => void;
} & React.ComponentProps<typeof Dialog>;
function BoardSearchDialog({
handleBoardSelect,
...props
}: BoardSearchDialogProps) {
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const [bbsNm, setBbsNm] = useState("");
const { data: boardList, refetch } = useQuery({
queryKey: [ENDPOINT.BOARD_SERVICE.BBS],
queryFn: () => BoardApi.getBoardPopupList({ bbsNm }),
enabled: false,
});
const table = useReactTable({
data: boardList?.content ?? [],
columns,
state: {
rowSelection,
},
enableMultiRowSelection: false,
getCoreRowModel: getCoreRowModel(),
onRowSelectionChange: setRowSelection,
});
useEffect(() => {
const boardData = table.getSelectedRowModel().rows[0]
?.original as BoardPopup;
if (!boardData) return;
handleBoardSelect(boardData);
}, [table.getSelectedRowModel().rows]);
useEffect(() => {
refetch();
}, []);
return (
<Dialog {...props}>
<DialogTrigger asChild>
<Button className="gap-3">
<i className="diveicon di-search" />
조회
</Button>
</DialogTrigger>
<DialogContent className="max-w-[60rem]" aria-describedby={undefined}>
<DialogHeader>
<DialogTitle>게시판 조회</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-4">
<div className="card card-border !m-0 flex w-full items-center gap-2">
<Input
placeholder="검색어를 입력하세요."
className="!text-[1.3rem]"
value={bbsNm}
onChange={(e) => setBbsNm(e.target.value)}
/>
<Button onClick={() => refetch()}>
<i className="diveicon di-search" />
조회
</Button>
</div>
<div className="h-[40rem] w-full overflow-y-auto">
<DataTable table={table} />
</div>
</div>
</DialogContent>
</Dialog>
);
}
export { BoardSearchDialog };
@@ -0,0 +1,96 @@
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
getCoreRowModel,
useReactTable,
type RowSelectionState,
} from "@tanstack/react-table";
import {
Button,
DataTable,
Dialog,
DialogTrigger,
DialogContent,
DialogHeader,
DialogTitle,
Input,
} from "@common/components/ui";
import { ENDPOINT } from "@/shared/config";
import { ContentApi } from "../api/content-service";
import type { Content } from "../model/content-interface";
import { columns } from "../model/content-table-colums";
type ContentSearchDialogProps = {
handleContentSelect: (content: Content) => void;
} & React.ComponentProps<typeof Dialog>;
function ContentSearchDialog({
handleContentSelect,
...props
}: ContentSearchDialogProps) {
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const [contsTtl, setContsTtl] = useState("");
const { data: contentList, refetch } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.CONTENTS],
queryFn: () => ContentApi.getContentList({ contsTtl }),
enabled: false,
});
const table = useReactTable({
data: contentList?.content ?? [],
columns,
state: {
rowSelection,
},
enableMultiRowSelection: false,
getCoreRowModel: getCoreRowModel(),
onRowSelectionChange: setRowSelection,
});
useEffect(() => {
const contentData = table.getSelectedRowModel().rows[0]
?.original as Content;
if (!contentData) return;
handleContentSelect(contentData);
}, [table.getSelectedRowModel().rows]);
useEffect(() => {
refetch();
}, []);
return (
<Dialog {...props}>
<DialogTrigger asChild>
<Button className="gap-3">
<i className="diveicon di-search" />
조회
</Button>
</DialogTrigger>
<DialogContent className="max-w-[60rem]" aria-describedby={undefined}>
<DialogHeader>
<DialogTitle>콘텐츠 조회</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-4">
<div className="card card-border !m-0 flex w-full items-center gap-2">
<Input
placeholder="검색어를 입력하세요."
className="!text-[1.3rem]"
value={contsTtl}
onChange={(e) => setContsTtl(e.target.value)}
/>
<Button onClick={() => refetch()}>
<i className="diveicon di-search" />
조회
</Button>
</div>
<div className="h-[40rem] w-full overflow-y-auto">
<DataTable table={table} />
</div>
</div>
</DialogContent>
</Dialog>
);
}
export { ContentSearchDialog };
@@ -0,0 +1,44 @@
import type { ComponentProps } from "react";
import { Button, Input } from "@common/components/ui";
type EditableNodeProps = {
depth?: number;
onSave: () => void;
onCancel: () => void;
} & ComponentProps<typeof Input>;
function EditableNode({
depth,
onSave,
onCancel,
...props
}: EditableNodeProps) {
return (
<div
className="flex items-center gap-2 rounded-sm bg-accent p-2"
style={{ marginInlineStart: !depth ? 0 : depth * 5 + 5 }}
>
<Input {...props} className="h-[2.5rem] !text-[1.3rem] text-foreground" />
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
className="size-8 !bg-transparent"
onClick={onSave}
>
<i className="diveicon di-check text-2xl" />
</Button>
<Button
variant="ghost"
size="icon"
className="size-8 !bg-transparent"
onClick={onCancel}
>
<i className="diveicon di-x" />
</Button>
</div>
</div>
);
}
export { EditableNode };
+115
View File
@@ -0,0 +1,115 @@
import { useState } from "react";
import type { UseFormReturn } from "react-hook-form";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { Button } from "@common/components";
import { Form } from "@/shared/ui/form";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
import type { MenuFormData } from "../model/menu-interface";
import { BaseMenuForm } from "./base-menu-form";
import { TypeMenuForm } from "./type-menu-form";
import { PermissionsManagementDialog } from "./permissions-management-dialog";
interface MenuFormProps {
form: UseFormReturn<MenuFormData>;
menuCd?: number;
handleCreate: (data: MenuFormData) => void;
handleUpdate: ({
menuCd,
data,
}: {
menuCd: number;
data: Omit<MenuFormData, "siteId">;
}) => void;
handleDelete?: (menuCd: number) => void;
}
function MenuForm({
form,
menuCd,
handleCreate,
handleUpdate,
handleDelete,
}: MenuFormProps) {
const isModifyMode = !!menuCd;
const { confirm } = useConfirm();
const [onConfirm, setOnConfirm] = useState(false);
const handleConfirm = async (callback: () => Promise<void>) => {
setOnConfirm(true);
await callback();
setOnConfirm(false);
};
const onSubmit = async (data: MenuFormData) => {
if (isModifyMode) {
await onUpdate(data);
} else {
await onCreate(data);
}
};
const onCreate = async (data: MenuFormData) => {
await handleConfirm(async () => {
if (await confirm("저장하시겠습니까?")) {
setOnConfirm(false);
handleCreate(data);
}
});
};
const onUpdate = async (data: MenuFormData) => {
await handleConfirm(async () => {
if (await confirm("수정하시겠습니까?")) {
setOnConfirm(false);
handleUpdate({ menuCd: menuCd!, data });
}
});
};
const onDelete = () => {
handleConfirm(async () => {
if (await confirm("삭제하시겠습니까?")) {
setOnConfirm(false);
handleDelete?.(menuCd!);
}
});
};
const menuType = form.watch("menuLnkgTypeCd");
const isSubmitDisabled = !form.watch("siteId");
return (
<>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<div className="card card-border">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">
{isModifyMode ? "메뉴 수정" : "메뉴 등록"}
</h3>
<PermissionsManagementDialog menuCd={menuCd} />
</div>
<div className="card">
<BaseMenuForm form={form} menuCd={menuCd} />
<TypeMenuForm form={form} menuType={menuType} />
</div>
</div>
<div className="flex justify-center gap-4 pb-12 pt-10">
<Button size="lg" type="submit" disabled={isSubmitDisabled}>
저장
</Button>
{isModifyMode && (
<Button size="lg" color="red" type="button" onClick={onDelete}>
삭제
</Button>
)}
</div>
</form>
</Form>
<ConfirmDialog open={onConfirm} />
</>
);
}
export { MenuForm };
+115
View File
@@ -0,0 +1,115 @@
import { useEffect, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { NodeModel, TreeMethods } from "@minoru/react-dnd-treeview";
import { Button } from "@common/components/ui";
import { cn } from "@common/components/lib";
import { ENDPOINT } from "@/shared/config";
import { MenuApi } from "../api/menu-service";
import type { TreeMenu } from "../model/menu-interface";
import { EditableNode } from "./editable-node";
type MenuNodeProps = {
node: NodeModel<TreeMenu>;
depth: number;
isOpen: boolean;
isSelected: boolean;
isAdditionalParent: boolean;
treeMethods: TreeMethods | null;
onToggle: (id: NodeModel["id"]) => void;
onSelect: (node: NodeModel<TreeMenu>) => void;
};
function MenuNode({
node,
depth,
isOpen,
isSelected,
isAdditionalParent,
treeMethods,
onToggle,
onSelect,
}: MenuNodeProps) {
const { id, text, data } = node;
const indent = depth * 10 + 5;
const queryClient = useQueryClient();
const { mutateAsync: updateMenuName } = useMutation({
mutationFn: (nodeName: string) => {
const encodedName = encodeURIComponent(nodeName);
return MenuApi.updateMenuName(id as number, encodedName);
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: [ENDPOINT.CMS_SERVICE.MENUS],
});
},
});
const [editMode, setEditMode] = useState(false);
const [nodeName, setNodeName] = useState(text);
const handleToggle = () => onToggle(id);
const handleSelect = () => onSelect(node);
const handleSave = async () => {
await updateMenuName(nodeName);
setEditMode(false);
};
const handleCancel = () => {
setEditMode(false);
setNodeName(text);
};
useEffect(() => {
if (isAdditionalParent) treeMethods?.open(id);
}, [isAdditionalParent]);
return (
<div
style={{ paddingInlineStart: indent }}
className={cn(
"group flex cursor-pointer items-center justify-between gap-2 rounded-sm p-2 hover:bg-accent",
isSelected && "!bg-[rgba(32,148,250,0.2)]",
)}
>
{editMode ? (
<EditableNode
value={nodeName}
onChange={(e) => setNodeName(e.target.value)}
onSave={handleSave}
onCancel={handleCancel}
/>
) : (
<>
<div className="flex items-center" onClick={handleSelect}>
{data?.children?.length && (
<i
className={cn(
"diveicon di-arrow-forward mr-2 text-base text-label",
isOpen && "rotate-90",
)}
onClick={(e) => {
e.stopPropagation();
handleToggle();
}}
/>
)}
<span className="text-[1.4rem] font-medium text-label">{text}</span>
</div>
<Button
variant="ghost"
size="icon"
className="invisible !bg-transparent group-hover:visible"
onClick={() => setEditMode(true)}
>
<i className="diveicon di-pencil" />
</Button>
</>
)}
</div>
);
}
export { MenuNode };
+264
View File
@@ -0,0 +1,264 @@
"use client";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import type { NodeModel } from "@minoru/react-dnd-treeview";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
Button,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@common/components/ui";
import { SiteApi } from "@/entities/site";
import { ENDPOINT } from "@/shared/config";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
import { useAlertStore } from "@/shared/lib/use-alert-store";
import type { TreeMenu } from "../model/menu-interface";
import { MenuApi } from "../api/menu-service";
import {
MENU_TYPE,
menuFormSchema,
type MenuFormData,
} from "../model/menu-interface";
import { MenuTree } from "./menu-tree";
import { MenuForm } from "./menu-form";
import { generateMenuTreeData } from "../lib/utils";
function MenuPage() {
const queryClient = useQueryClient();
const { setMessage: alert } = useAlertStore((state) => state);
const { confirm } = useConfirm();
const [siteId, setSiteId] = useState("");
const [onConfirm, setOnConfirm] = useState(false);
const [selectedMenu, setSelectedMenu] = useState<TreeMenu | null>(null);
const [additionalNode, setAdditionalNode] =
useState<NodeModel<TreeMenu> | null>(null);
const { data: menuInfo } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.MENUS, selectedMenu?.menuCd],
queryFn: () => MenuApi.getMenuInfo(selectedMenu?.menuCd ?? 0),
enabled: !!selectedMenu?.menuCd,
});
const { data: treeData } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.MENUS, siteId],
queryFn: () => MenuApi.getTreeMenuList(siteId),
select: (data) => {
const treeData = generateMenuTreeData(data);
const defaultSortSeq =
treeData.filter((node) => node.data?.levelNo === 1).length + 1;
form.setValue("sortSeq", defaultSortSeq);
return treeData;
},
enabled: !!siteId,
});
const { data: options } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.SITES],
queryFn: () => SiteApi.getSiteList(),
select: (data) =>
data.content.map((site) => ({
label: site.siteNm,
value: site.siteId,
})),
});
const { mutateAsync: createMenu } = useMutation({
mutationFn: (data: MenuFormData) => MenuApi.createMenu(data),
onSuccess: () => {
alert("저장되었습니다.");
queryClient.invalidateQueries({
queryKey: [ENDPOINT.CMS_SERVICE.MENUS, siteId],
});
},
});
const { mutate: updateMenu } = useMutation({
mutationFn: ({
menuCd,
data,
}: {
menuCd: number;
data: Omit<MenuFormData, "siteId">;
}) => MenuApi.updateMenu(menuCd, data),
onSuccess: () => {
alert("수정되었습니다.");
queryClient.invalidateQueries({
queryKey: [ENDPOINT.CMS_SERVICE.MENUS, siteId],
});
},
});
const { mutate: deleteMenu } = useMutation({
mutationFn: (menuCd: number) => MenuApi.deleteMenu(menuCd),
onSuccess: () => {
alert("삭제되었습니다.");
queryClient.invalidateQueries({
queryKey: [ENDPOINT.CMS_SERVICE.MENUS, siteId],
});
},
});
const form = useForm<MenuFormData>({
resolver: zodResolver(menuFormSchema),
defaultValues: {
menuLnkgTypeCd: MENU_TYPE.EMPTY,
},
values: {
...menuInfo,
siteId,
levelNo: menuInfo?.levelNo ?? 1,
sortSeq: menuInfo?.sortSeq ?? 1,
menuKornNm: menuInfo?.menuKornNm ?? "",
menuLnkgTypeCd: menuInfo?.menuLnkgTypeCd ?? MENU_TYPE.EMPTY,
iconNm: menuInfo?.iconName,
otptYn: menuInfo?.otptYn ?? "Y",
evlUseYn: menuInfo?.evlUseYn ?? "Y",
useYn: menuInfo?.useYn ?? "Y",
},
});
const additionalNodeForm = useForm<MenuFormData>({
resolver: zodResolver(menuFormSchema),
defaultValues: {
menuLnkgTypeCd: MENU_TYPE.EMPTY,
levelNo: 1,
sortSeq: 1,
otptYn: "Y",
evlUseYn: "Y",
useYn: "Y",
},
});
const handleAdditionalNodeSave = async () => {
const prntMenuCd = !additionalNode?.parent
? null
: (additionalNode?.parent as number);
await createMenu({
...additionalNodeForm.getValues(),
prntMenuCd,
});
resetAdditionalNode();
};
const resetAdditionalNode = () => {
additionalNodeForm.setValue("menuKornNm", "");
setAdditionalNode(null);
};
const handleSiteIdChange = (value: string) => {
form.setValue("siteId", value);
additionalNodeForm.setValue("siteId", value);
setSiteId(value);
setSelectedMenu(null);
};
const handleNodeSelect = (node: NodeModel<TreeMenu>) => {
if (!node.data) return;
if (node.data.menuCd === selectedMenu?.menuCd) {
setSelectedMenu(null);
additionalNodeForm.setValue("levelNo", 1);
return;
}
setSelectedMenu(node.data);
additionalNodeForm.setValue("levelNo", (node.data.levelNo ?? 0) + 1);
};
const handleNodeDelete = async () => {
setOnConfirm(true);
if (await confirm("삭제하시겠습니까?")) {
setOnConfirm(false);
deleteMenu(selectedMenu!.menuCd!);
}
setOnConfirm(false);
};
const handleAddMenu = () => {
if (additionalNode) return;
setAdditionalNode({
id: -1,
parent: selectedMenu?.menuCd ?? 0,
text: "",
});
};
const tree = additionalNode
? [...(additionalNode ? [additionalNode] : []), ...(treeData ?? [])]
: (treeData ?? []);
return (
<>
<div className="card !mb-0 flex !min-h-[calc(100vh-16.8rem)] gap-2">
<div className="card card-border w-[24rem]">
<Select value={siteId} onValueChange={handleSiteIdChange}>
<SelectTrigger>
<SelectValue placeholder="선택하세요" />
</SelectTrigger>
<SelectContent>
{options?.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
{siteId && (
<>
<div className="my-4 flex gap-2">
<Button
size="sm"
color="primary"
className="flex-1"
onClick={handleAddMenu}
>
메뉴 추가
</Button>
<Button
size="sm"
color="red"
className="flex-1"
onClick={handleNodeDelete}
disabled={!selectedMenu}
>
메뉴 삭제
</Button>
</div>
<div className="card card-border !mx-0">
<MenuTree
tree={tree}
siteId={siteId}
selectedMenu={selectedMenu}
additionalNodeForm={additionalNodeForm}
onSelectNode={handleNodeSelect}
onAdditionalNodeSave={handleAdditionalNodeSave}
onAdditionalNodeCancel={resetAdditionalNode}
/>
</div>
</>
)}
</div>
<div className="card card-border flex-1">
<MenuForm
form={form}
menuCd={selectedMenu?.menuCd}
handleCreate={createMenu}
handleUpdate={updateMenu}
handleDelete={deleteMenu}
/>
</div>
</div>
<ConfirmDialog open={onConfirm} />
</>
);
}
export { MenuPage };
+151
View File
@@ -0,0 +1,151 @@
"use client";
import { useRef } from "react";
import { DndProvider } from "react-dnd";
import type { UseFormReturn } from "react-hook-form";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
Tree,
MultiBackend,
getBackendOptions,
type NodeModel,
type TreeMethods,
} from "@minoru/react-dnd-treeview";
import { Button } from "@common/components/ui";
import { ENDPOINT } from "@/shared/config";
import { MenuApi } from "../api/menu-service";
import type { MenuFormData, TreeMenu, TreeNode } from "../model/menu-interface";
import { handleDropNode, handleSelectNode } from "../lib/utils";
import { MenuNode } from "./menu-node";
import { EditableNode } from "./editable-node";
type MenuTreeProps = {
tree: NodeModel<TreeMenu>[];
siteId: string;
selectedMenu: TreeMenu | null;
additionalNodeForm: UseFormReturn<MenuFormData>;
onSelectNode: (node: NodeModel<TreeMenu>) => void;
onAdditionalNodeSave: () => void;
onAdditionalNodeCancel: () => void;
};
function MenuTree({
tree,
siteId,
selectedMenu,
additionalNodeForm,
onSelectNode,
onAdditionalNodeSave,
onAdditionalNodeCancel,
}: MenuTreeProps) {
const queryClient = useQueryClient();
const treeMethods = useRef<TreeMethods>(null);
const { mutate: updateTreeMenu } = useMutation({
mutationFn: (newTree: TreeNode) =>
MenuApi.updateTreeMenu(siteId, [newTree]),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: [ENDPOINT.CMS_SERVICE.MENUS],
});
},
});
const additionalNode = tree.find((n) => n.id === -1);
const isAdditionalParent = (node: NodeModel<TreeMenu>): boolean => {
if (!additionalNode) return false;
return additionalNode?.parent === node.id;
};
return (
<>
<div className="max-h-[calc(100vh-33.5rem)] overflow-auto">
<DndProvider backend={MultiBackend} options={getBackendOptions()}>
<Tree
tree={tree}
rootId={0}
ref={treeMethods}
render={(
node: NodeModel<TreeMenu>,
{ depth, isOpen, onToggle },
) => {
if (node.id === -1) {
return (
<EditableNode
value={additionalNodeForm.watch("menuKornNm") ?? ""}
onChange={(e) =>
additionalNodeForm.setValue("menuKornNm", e.target.value)
}
depth={depth}
onSave={onAdditionalNodeSave}
onCancel={onAdditionalNodeCancel}
/>
);
}
return (
<MenuNode
node={node}
depth={depth}
treeMethods={treeMethods.current}
isOpen={isOpen}
isSelected={selectedMenu?.menuCd === node.id}
isAdditionalParent={isAdditionalParent(node)}
onToggle={onToggle}
onSelect={handleSelectNode(onSelectNode)}
/>
);
}}
onDrop={handleDropNode(updateTreeMenu)}
classes={{
root: "p-4",
container: "flex flex-col",
dropTarget: "!bg-[rgba(32,148,250,0.5)] rounded-sm",
placeholder: "relative",
}}
sort={false}
dropTargetOffset={5}
insertDroppableFirst={false}
canDrop={(_, { dragSource, dropTargetId }) => {
if (dragSource?.parent === dropTargetId) {
return true;
}
}}
placeholderRender={(_, { depth }) => {
return (
<div
className="absolute right-0 top-0 h-[0.2rem] bg-primary"
style={{ left: depth * 10 + 5 }}
/>
);
}}
/>
</DndProvider>
</div>
<div className="flex gap-2">
<Button
color="lightGray"
className="flex-1 items-center px-0"
onClick={() => {
treeMethods.current?.openAll();
}}
>
<i className="diveicon di-arrows-angle-expand" />
전체펼침
</Button>
<Button
color="lightGray"
className="flex-1 items-center px-0"
onClick={() => {
treeMethods.current?.closeAll();
}}
>
<i className="diveicon di-arrows-angle-contract" />
전체접기
</Button>
</div>
</>
);
}
export { MenuTree };
@@ -0,0 +1,184 @@
"use client";
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { DndProvider } from "react-dnd";
import {
Tree,
MultiBackend,
getBackendOptions,
type NodeModel,
} from "@minoru/react-dnd-treeview";
import {
Button,
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
Input,
} from "@common/components/ui";
import { cn } from "@common/components/lib";
import { ENDPOINT } from "@/shared/config";
import { OrganizationApi } from "../api/organization-service";
import type { Organization, User } from "../model/organization-interface";
import {
filterOrganizationTreeDataByKeyword,
generateOrganizationTreeData,
} from "../lib/utils";
type TreeModel = Organization | User;
interface OrganizationSearchDialogProps {
handleUserSelect: (user: User) => void;
}
function OrganizationSearchDialog({
handleUserSelect,
}: OrganizationSearchDialogProps) {
const [keyword, setKeyword] = useState("");
const [tree, setTree] = useState<NodeModel<TreeModel>[]>([]);
const [selectedNode, setSelectedNode] = useState<NodeModel<TreeModel> | null>(
null,
);
const { data: treeData } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.USER_OGNZ],
queryFn: () => OrganizationApi.getOrganizationUserTreeList(),
select: (data) => generateOrganizationTreeData(data),
});
const handleSelectNode = (node: NodeModel<TreeModel>) => {
setSelectedNode(node);
handleUserSelect(node.data as User);
};
useEffect(() => {
setTree(treeData ?? []);
}, [treeData]);
return (
<Dialog>
<DialogTrigger asChild>
<Button className="gap-3">
<i className="diveicon di-search" />
조회
</Button>
</DialogTrigger>
<DialogContent className="max-w-[30rem]" aria-describedby={undefined}>
<DialogHeader>
<DialogTitle>담당자 조회</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-4">
<div className="card card-border !m-0 flex w-full items-center gap-2">
<Input
className="h-[2.5rem] !text-[1.3rem]"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
/>
<Button
size="sm"
onClick={() =>
setTree(filterOrganizationTreeDataByKeyword(tree, keyword))
}
>
<i className="diveicon di-search text-base" />
조회
</Button>
</div>
<div className="h-[36rem] overflow-auto">
<DndProvider backend={MultiBackend} options={getBackendOptions()}>
<Tree
tree={tree}
rootId={0}
render={(
node: NodeModel<TreeModel>,
{ depth, isOpen, onToggle },
) => (
<TreeNode
node={node}
depth={depth}
isOpen={isOpen}
selectedNode={selectedNode}
onToggle={onToggle}
onSelect={handleSelectNode}
/>
)}
classes={{
container: "flex flex-col",
}}
sort={false}
onDrop={() => {}}
/>
</DndProvider>
</div>
</div>
</DialogContent>
</Dialog>
);
}
interface TreeNodeProps {
node: NodeModel<TreeModel>;
depth: number;
isOpen: boolean;
selectedNode: NodeModel<TreeModel> | null;
onToggle: (id: NodeModel["id"]) => void;
onSelect: (node: NodeModel<TreeModel>) => void;
}
const ORGANIZATION_PREFIX = "OGNZ";
function TreeNode({
node,
depth,
isOpen,
selectedNode,
onToggle,
onSelect,
}: TreeNodeProps) {
const { id, text, data } = node;
const indent = depth * 15 + 5;
const handleToggle = () => onToggle(id);
const handleSelect = () => {
if (id.toString().startsWith(ORGANIZATION_PREFIX)) return;
onSelect(node);
};
const isSelected = selectedNode?.id === id;
return (
<div
style={{ paddingInlineStart: indent }}
className="group flex cursor-pointer items-center justify-between gap-2 rounded-sm p-2 hover:bg-accent"
onClick={handleSelect}
>
<div className="flex w-full items-center justify-between">
<div>
{data && ("children" in data || "users" in data) && (
<Button
size="icon"
className="h-6 w-6 !bg-transparent"
onClick={(e) => {
e.stopPropagation();
handleToggle();
}}
>
<i
className={cn(
"diveicon di-arrow-forward mr-2 text-base text-label",
isOpen && "rotate-90",
)}
/>
</Button>
)}
<span className="text-[1.4rem] font-medium text-label">{text}</span>
</div>
{isSelected && <i className="diveicon di-check text-xl text-primary" />}
</div>
</div>
);
}
export { OrganizationSearchDialog };
@@ -0,0 +1,22 @@
import { Button, Dialog, DialogTrigger } from "@common/components/ui";
type PermissionsManagementDialogProps = {
menuCd?: number;
} & React.ComponentProps<typeof Dialog>;
function PermissionsManagementDialog({
...props
}: PermissionsManagementDialogProps) {
return (
<Dialog {...props}>
<DialogTrigger asChild>
<Button className="gap-3">
<i className="diveicon di-personal-information" />
권한관리
</Button>
</DialogTrigger>
</Dialog>
);
}
export { PermissionsManagementDialog };
@@ -0,0 +1,368 @@
import dayjs from "dayjs";
import { type UseFormReturn } from "react-hook-form";
import {
DatePicker,
IconFinder,
Input,
Label,
RadioGroup,
RadioGroupItem,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
} from "@common/components";
import { FormItem, FormControl, FormField } from "@/shared/ui/form";
import type { BoardPopup } from "@/entities/board";
import type { Content } from "../model/content-interface";
import type { User } from "../model/organization-interface";
import type { MenuFormData, MenuType } from "../model/menu-interface";
import { OrganizationSearchDialog } from "./organization-search-dialog";
import { ContentSearchDialog } from "./content-search-dialog";
import { BoardSearchDialog } from "./board-search-dialog";
type TypeMenuFormProps = {
form: UseFormReturn<MenuFormData>;
menuType: MenuType;
};
function TypeMenuForm({ form, menuType }: TypeMenuFormProps) {
const handleIconClick = (icon: string) => {
form.setValue("iconNm", icon);
};
const handleContentSelect = (content: Content) => {
form.setValue("menuLnkgSn", content.contsSn);
form.setValue("menuLnkgSnNm", content.contsTtl);
};
const handleUserSelect = (user: User) => {
form.setValue("menuPicUserUnqId", user.userUnqId);
form.setValue("menuPicUserUnqIdNm", user.userNm);
};
const handleBoardSelect = (board: BoardPopup) => {
form.setValue("menuLnkgSn", board.bbsId);
form.setValue("menuLnkgSnNm", board.bbsNm);
};
const handleDateSelect = (date: Date | undefined) => {
if (!date) return;
form.setValue("menuPicDsgnYmd", dayjs(date).format("YYYYMMDD"));
};
return (
<Table variant="secondary" className="-mt-[0.1rem]">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<TableBody>
{menuType === "CONTENTS" && (
<TableRow>
<TableHead>콘텐츠</TableHead>
<TableCell className="border">
<div className="flex items-center gap-2">
<div className="h-[3.2rem] w-1/2 cursor-not-allowed overflow-hidden whitespace-nowrap break-keep rounded-md border border-input bg-form px-3 py-2 text-[1.3rem] opacity-50">
{!form.watch("menuLnkgSnNm") &&
"메뉴에 표시될 콘텐츠를 조회 후 선택하십시오."}
{form.watch("menuLnkgSnNm")}
</div>
<ContentSearchDialog
handleContentSelect={handleContentSelect}
/>
</div>
</TableCell>
</TableRow>
)}
{menuType === "BOARD" && (
<TableRow>
<TableHead>게시판</TableHead>
<TableCell className="border">
<div className="flex items-center gap-2">
<div className="h-[3.2rem] w-1/2 cursor-not-allowed overflow-hidden whitespace-nowrap break-keep rounded-md border border-input bg-form px-3 py-2 text-[1.3rem] opacity-50">
{!form.watch("menuLnkgSnNm") &&
"메뉴에 표시될 게시판을 조회 후 선택하십시오."}
{form.watch("menuLnkgSnNm")}
</div>
<BoardSearchDialog handleBoardSelect={handleBoardSelect} />
</div>
</TableCell>
</TableRow>
)}
{(menuType === "INSIDE" || menuType === "OUTSIDE") && (
<TableRow>
<TableHead>연결 URL</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="urlPath"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder={
menuType === "INSIDE"
? "메뉴에 연결된 페이지의 경로를 입력하십시오."
: "'http://' 또는 'https://'를 포함하여 입력하십시오."
}
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
)}
{(menuType === "CONTENTS" ||
menuType === "BOARD" ||
menuType === "INSIDE" ||
menuType === "OUTSIDE") && (
<TableRow>
<TableHead>연결 형태</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="newWndwYn"
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
value={field.value ?? ""}
onValueChange={field.onChange}
>
<div className="flex items-center space-x-4">
<div className="flex items-center space-x-2">
<RadioGroupItem value="Y" id="newWndwY" />
<Label htmlFor="newWndwY">새창</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="N" id="newWndwN" />
<Label htmlFor="newWndwN">현재창</Label>
</div>
</div>
</RadioGroup>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
)}
{(menuType === "CONTENTS" || menuType === "BOARD") && (
<TableRow>
<TableHead>메뉴 평가 사용 여부</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="evlUseYn"
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
value={field.value ?? ""}
onValueChange={field.onChange}
>
<div className="flex items-center space-x-4">
<div className="flex items-center space-x-2">
<RadioGroupItem value="Y" id="evlUseY" />
<Label htmlFor="evlUseY">사용</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="N" id="evlUseN" />
<Label htmlFor="evlUseN">사용안함</Label>
</div>
</div>
</RadioGroup>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
)}
{/* 메뉴 유형 공통 폼 S */}
<TableRow>
<TableHead>메뉴 서브명</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="menuSubKornNm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="사이트맵에서 다른 이름으로 사용할 경우 입력하십시오."
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>메뉴 아이콘</TableHead>
<TableCell className="border">
<div className="flex gap-2">
<div className="h-[3.2rem] w-[21.5rem] cursor-not-allowed rounded-md border border-input bg-form px-3 py-2 text-[1.3rem] opacity-50">
{!form.watch("iconNm") && "아이콘을 조회 후 선택하십시오."}
{form.watch("iconNm")}
</div>
<IconFinder handleClick={handleIconClick} />
</div>
</TableCell>
</TableRow>
<TableRow>
<TableHead>출력 여부</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="otptYn"
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
{...field}
value={field.value ?? ""}
onValueChange={field.onChange}
>
<div className="flex items-center space-x-4">
<div className="flex items-center space-x-2">
<RadioGroupItem value="Y" id="otptY" />
<Label htmlFor="otptY">출력</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="N" id="otptN" />
<Label htmlFor="otptN">출력안함</Label>
</div>
</div>
</RadioGroup>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사용 여부</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="useYn"
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
{...field}
value={field.value ?? ""}
onValueChange={field.onChange}
>
<div className="flex items-center space-x-4">
<div className="flex items-center space-x-2">
<RadioGroupItem value="Y" id="useY" />
<Label htmlFor="useY">사용</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="N" id="useN" />
<Label htmlFor="useN">사용안함</Label>
</div>
</div>
</RadioGroup>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
{/* 메뉴 유형 공통 폼 E */}
{(menuType === "CONTENTS" || menuType === "BOARD") && (
<>
<TableRow>
<TableHead>QR코드</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="qrcd"
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
value={field.value ?? ""}
onValueChange={field.onChange}
>
<div className="flex items-center space-x-4">
<div className="flex items-center space-x-2">
<RadioGroupItem value="Y" id="qrcdY" />
<Label htmlFor="qrcdY">사용</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="N" id="qrcdN" />
<Label htmlFor="qrcdN">사용안함</Label>
</div>
</div>
</RadioGroup>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>담당자</TableHead>
<TableCell className="border">
<div className="flex items-center gap-6">
<div className="flex items-center gap-2">
<div className="h-[3.2rem] w-[21.5rem] cursor-not-allowed rounded-md border border-input bg-form px-3 py-2 text-[1.3rem] opacity-50">
{!form.watch("menuPicUserUnqIdNm") &&
"메뉴 담당자를 조회 후 선택하십시오."}
{form.watch("menuPicUserUnqIdNm")}
</div>
<OrganizationSearchDialog
handleUserSelect={handleUserSelect}
/>
</div>
<div className="flex items-center gap-2">
<b>지정일:</b>
<FormField
control={form.control}
name="menuPicDsgnYmd"
render={({ field }) => (
<FormItem>
<FormControl>
<DatePicker
mode="single"
selected={
field.value
? dayjs(field.value).toDate()
: undefined
}
onSelect={(date) => {
field.onChange(date);
handleDateSelect(date);
}}
/>
</FormControl>
</FormItem>
)}
/>
</div>
</div>
</TableCell>
</TableRow>
</>
)}
</TableBody>
</Table>
);
}
export { TypeMenuForm };
@@ -0,0 +1,28 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type {
Domain,
DomainService,
DomainList,
DomainParams,
} from "../model/domain-interface";
export class DomainApiService implements DomainService {
public async getDomainList(params: DomainParams): Promise<DomainList> {
const response = await client.get<DomainList>(
`${ENDPOINT.CMS_SERVICE.DOMAINS}`,
{ params },
);
return response.data;
}
public async saveDomainList(body: Domain[]): Promise<void> {
const response = await client.post<void>(
`${ENDPOINT.CMS_SERVICE.DOMAINS}`,
body,
);
return response.data;
}
}
export const DomainApi = new DomainApiService();
+22
View File
@@ -0,0 +1,22 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type { IpParams, IP, IpList, IpService } from "../model/ip-interface";
export class IpApiService implements IpService {
public async getIpList(params: IpParams): Promise<IpList> {
const response = await client.get<IpList>(`${ENDPOINT.CMS_SERVICE.IPS}`, {
params,
});
return response.data;
}
public async saveIpList(body: IP[]): Promise<void> {
const response = await client.post<void>(
`${ENDPOINT.CMS_SERVICE.IPS}`,
body,
);
return response.data;
}
}
export const IpApi = new IpApiService();
@@ -0,0 +1,31 @@
import { z } from "zod";
import type { PageableParams, PageableList } from "@/shared/model";
export interface DomainParams extends PageableParams {
keywordType?: string;
keyword?: string;
siteId?: string;
useYn?: string;
}
export const domainSchema = z.object({
siteDmnNo: z.number().nullish(),
siteId: z.string(),
dmnAddr: z.string().nonempty(),
useYn: z.string(),
rprsDmnYn: z.string(),
mode: z.string(),
});
export const domainFormSchema = z.object({
domains: z.array(domainSchema),
});
export type Domain = z.infer<typeof domainSchema>;
export type DomainFormData = z.infer<typeof domainFormSchema>;
export type DomainList = PageableList<Domain>;
export interface DomainService {
getDomainList(params: DomainParams): Promise<DomainList>;
saveDomainList(body: Domain[]): Promise<void>;
}
@@ -0,0 +1,29 @@
import { z } from "zod";
import type { PageableParams, PageableList } from "@/shared/model";
export interface IpParams extends PageableParams {
siteId: string;
ipAddr?: string;
prmYn?: string;
}
export const ipSchema = z.object({
mngNo: z.number().nullish(),
siteId: z.string(),
ipAddr: z.string().nonempty(),
prmYn: z.string(),
mode: z.string(),
});
export const ipFormSchema = z.object({
ips: z.array(ipSchema),
});
export type IP = z.infer<typeof ipSchema>;
export type IPFormData = z.infer<typeof ipFormSchema>;
export type IpList = PageableList<IP>;
export interface IpService {
getIpList(params: IpParams): Promise<IpList>;
saveIpList(body: IP[]): Promise<void>;
}
@@ -1,8 +1,8 @@
import dayjs from "dayjs";
import { createColumnHelper } from "@tanstack/react-table";
import type { ISite } from "@/entities/site/model/site-interface";
import type { Site } from "@/entities/site";
const columnHelper = createColumnHelper<ISite>();
const columnHelper = createColumnHelper<Site>();
const columns = [
columnHelper.accessor((_, index) => index + 1, {
@@ -17,8 +17,8 @@ const columns = [
id: "siteNm",
header: "사이트명",
}),
columnHelper.accessor("siteAddr", {
id: "siteAddr",
columnHelper.accessor("dmnAddr", {
id: "dmnAddr",
header: "대표 URL",
}),
columnHelper.accessor("bscSiteYn", {
+22 -26
View File
@@ -1,52 +1,48 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { useMutation } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";
import { SiteApi, siteFormSchema, type SiteFormData } from "@/entities/site";
import { SitePageLayout } from "./layout";
import { useAlertStore } from "@/shared/lib/use-alert-store";
import { SiteForm } from "./site-form";
import {
Button,
Dialog,
DialogClose,
DialogContent,
DialogFooter,
} from "@common/components/ui";
function CreatePage() {
const router = useRouter();
const { setMessage: alert } = useAlertStore((state) => state);
const { mutateAsync: createSite } = useMutation({
mutationFn: (data: SiteFormData) => SiteApi.createSite(data),
onSuccess: () => {
setIsCreateSuccess(true);
alert("등록되었습니다.", router.back);
},
});
const [isCreateSuccess, setIsCreateSuccess] = useState(false);
const form = useForm<SiteFormData>({
resolver: zodResolver(siteFormSchema),
defaultValues: {
siteId: "",
siteNm: "",
siteExpln: "",
siteKndCd: "",
siteAddr: "",
faxNo: "",
telNo: "",
lwndCn: "",
bscSiteYn: "",
bkmkIcon: "",
useYn: "",
siteSkn: "",
},
});
return (
<SitePageLayout>
<div className="card card-border !mb-0 !mt-6">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">사이트 등록</h3>
</div>
<SiteForm form={form} handleSave={createSite} />
<Dialog open={isCreateSuccess} onOpenChange={() => router.back()}>
<DialogContent aria-describedby={undefined}>
<div className="py-10">
<p className="text-center text-[1.4rem]">등록되었습니다.</p>
</div>
<DialogFooter className="!justify-center">
<DialogClose asChild>
<Button>확인</Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
</SitePageLayout>
</div>
);
}
@@ -1,4 +1,8 @@
import { useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { useForm, useFieldArray } from "react-hook-form";
import {
Dialog,
DialogTrigger,
@@ -13,197 +17,296 @@ import {
TableHeader,
TableRow,
Input,
Checkbox,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
RadioGroup,
RadioGroupItem,
DialogFooter,
DialogClose,
Checkbox,
Label,
} from "@common/components";
export type Domain = {
id: number;
domainUrl: string;
isRepresentative: boolean;
isActive: "true" | "false";
};
import { Form, FormControl, FormField, FormItem } from "@/shared/ui/form";
import { ENDPOINT } from "@/shared/config";
import { DomainApi } from "../api/domain-service";
import {
domainFormSchema,
type Domain,
type DomainFormData,
} from "../model/domain-interface";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
import { useAlertStore } from "@/shared/lib/use-alert-store";
type DomainManagementDialogProps = {
triggerDisabled?: boolean;
handleSave: (rows: Domain[]) => void;
siteId: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
handleSaveDomain?: (rows: Domain[]) => void;
};
function DomainManagementDialog({
triggerDisabled,
handleSave,
siteId,
handleSaveDomain,
...props
}: DomainManagementDialogProps) {
const [rows, setRows] = useState<Domain[]>([]);
const [rowSelection, setRowSelection] = useState<Domain["id"][]>([]);
const { confirm } = useConfirm();
const { setMessage: alert } = useAlertStore((state) => state);
const onSave = () => {
handleSave(rows);
const { data: domainList } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.DOMAINS, props.open],
queryFn: () => DomainApi.getDomainList({ siteId }),
select: (data) => {
const domains = data.content.map((item) => ({
...item,
mode: "U",
}));
initialForm();
return domains;
},
});
const { mutateAsync } = useMutation({
mutationFn: (body: Domain[]) => DomainApi.saveDomainList(body),
});
const form = useForm<DomainFormData>({
resolver: zodResolver(domainFormSchema),
values: {
domains: domainList ?? [],
},
});
const { fields, append, remove, update } = useFieldArray({
control: form.control,
name: "domains",
});
const [onConfirm, setOnConfirm] = useState(false);
const [selectedRows, setSelectedRows] = useState<number[]>([]);
const initialForm = () => {
form.reset();
setSelectedRows([]);
};
const onSubmit = async (data: DomainFormData) => {
setOnConfirm(true);
if (await confirm("저장하시겠습니까?")) {
setOnConfirm(false);
await mutateAsync(data.domains);
handleSaveDomain?.(data.domains);
alert("저장되었습니다.");
}
setOnConfirm(false);
};
const handleAddDomain = () => {
const newDomain: Domain = {
id: Date.now(),
domainUrl: "",
isRepresentative: rows.length === 0,
isActive: "true",
};
setRows([...rows, newDomain]);
};
const handleDeleteDomain = () => {
const filteredRows = rows.filter((row) => !rowSelection.includes(row.id));
const hasRepresentative = filteredRows.some((row) => row.isRepresentative);
let updatedRows = filteredRows;
if (!hasRepresentative && filteredRows.length > 0) {
updatedRows = filteredRows.map((row, index) =>
index === 0 ? { ...row, isRepresentative: true } : row,
);
}
setRows(updatedRows);
setRowSelection([]);
};
const handleDomainUrlChange = (id: number, value: string) => {
setRows(
rows.map((row) => (row.id === id ? { ...row, domainUrl: value } : row)),
);
};
const handleRepresentativeChange = (id: number) => {
setRows(
rows.map((row) => ({
...row,
isRepresentative: row.id === id,
})),
);
};
const handleActiveChange = (id: number, value: "true" | "false") => {
setRows(
rows.map((row) => (row.id === id ? { ...row, isActive: value } : row)),
);
};
const toggleRowSelection = (id: number) => {
setRowSelection((prev) => {
if (prev.includes(id)) {
return prev.filter((item) => item !== id);
} else {
return [...prev, id];
}
append({
siteDmnNo: null,
siteId,
dmnAddr: "",
useYn: "Y",
rprsDmnYn: "N",
mode: "C",
});
};
const handleSelectAll = () => {
if (selectedRows.length === fields.length) {
setSelectedRows([]);
} else {
setSelectedRows(fields.map((_, index) => index));
}
};
const handleSelectRow = (i: number) => {
setSelectedRows((prev) =>
prev.includes(i) ? prev.filter((j) => j !== i) : [...prev, i],
);
};
const handleDeleteDomain = async () => {
if (selectedRows.length === 0) return;
const sortedIndices = [...selectedRows].sort((a, b) => b - a);
sortedIndices.forEach((i) => {
const field = fields[i];
if (field?.siteDmnNo) {
update(i, {
...field,
mode: "D",
});
} else {
remove(i);
}
});
setSelectedRows([]);
};
const handleChangeRprsDmnYn = (i: number) => {
fields.forEach((_, j) => {
if (j === i) return;
form.setValue(`domains.${j}.rprsDmnYn`, "N");
});
};
const isAllSelected =
fields.length > 0 && selectedRows.length === fields.length;
return (
<Dialog>
<DialogTrigger asChild>
<Button disabled={triggerDisabled}>도메인 관리</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[60rem]">
<DialogHeader>
<DialogTitle>도메인 관리</DialogTitle>
</DialogHeader>
<div className="mb-4 flex justify-end gap-2">
<Button size="sm" color="white" onClick={handleAddDomain}>
항목 추가
</Button>
<Button
size="sm"
color="red"
onClick={handleDeleteDomain}
disabled={rowSelection.length === 0}
>
항목 삭제
</Button>
</div>
<div className="card card-border">
<Table variant="secondary">
<colgroup>
<col width="8%" />
<col width="12%" />
<col width="40%" />
<col width="20%" />
<col width="20%" />
</colgroup>
<TableHeader>
<TableRow>
<TableHead>NO</TableHead>
<TableHead>선택</TableHead>
<TableHead>도메인URL</TableHead>
<TableHead>대표URL</TableHead>
<TableHead>사용여부</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map((row, idx) => (
<TableRow key={row.id}>
<TableCell align="center">{idx + 1}</TableCell>
<TableCell align="center">
<Checkbox
checked={rowSelection.includes(row.id)}
onCheckedChange={() => toggleRowSelection(row.id)}
className="cursor-pointer"
/>
</TableCell>
<TableCell align="center">
<Input
value={row.domainUrl}
onChange={(e) =>
handleDomainUrlChange(row.id, e.target.value)
}
className="!text-[1.3rem]"
/>
</TableCell>
<TableCell align="center">
<Checkbox
checked={row.isRepresentative}
onCheckedChange={() => handleRepresentativeChange(row.id)}
className="cursor-pointer"
/>
</TableCell>
<TableCell align="center">
<Select
value={row.isActive}
onValueChange={(value: "true" | "false") =>
handleActiveChange(row.id, value)
}
>
<SelectTrigger className="mx-auto w-[10rem]">
<SelectValue placeholder="선택" />
</SelectTrigger>
<SelectContent>
<SelectItem value="true">예</SelectItem>
<SelectItem value="false">아니오</SelectItem>
</SelectContent>
</Select>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
<DialogFooter className="!justify-center">
<DialogClose asChild>
<Button size="lg" onClick={onSave}>
저장
</Button>
</DialogClose>
<DialogClose asChild>
<Button size="lg" color="white">
취소
</Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
<>
<Dialog {...props}>
<DialogTrigger asChild>
<Button>도메인 관리</Button>
</DialogTrigger>
<DialogContent className="max-w-[60rem]" aria-describedby={undefined}>
<DialogHeader>
<DialogTitle>도메인 관리</DialogTitle>
</DialogHeader>
<Form {...form}>
<form
onSubmit={(e) => {
e.preventDefault();
e.stopPropagation();
form.handleSubmit(onSubmit)(e);
}}
>
<div className="mb-4 flex justify-end gap-2">
<Button type="button" size="sm" onClick={handleAddDomain}>
항목 추가
</Button>
<Button
type="button"
size="sm"
color="red"
onClick={handleDeleteDomain}
disabled={selectedRows.length === 0}
>
항목 삭제
</Button>
</div>
<div className="card card-border max-h-[28.5rem] overflow-auto">
<Table variant="secondary">
<colgroup>
<col width="10%" />
<col width="auto" />
<col width="15%" />
<col width="25%" />
</colgroup>
<TableHeader className="sticky -top-[0.6rem]">
<TableRow>
<TableHead className="!px-0">
<Checkbox
checked={isAllSelected}
onCheckedChange={handleSelectAll}
/>
</TableHead>
<TableHead>도메인 주소</TableHead>
<TableHead>대표 URL</TableHead>
<TableHead>사용여부</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{fields.map((field, i) => {
if (field.mode === "D") return null;
return (
<TableRow key={field.id}>
<TableCell align="center" className="!px-0">
<Checkbox
checked={selectedRows.includes(i)}
onCheckedChange={() => handleSelectRow(i)}
/>
</TableCell>
<TableCell align="center">
<FormField
control={form.control}
name={`domains.${i}.dmnAddr`}
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
className="!text-[1.3rem]"
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
<TableCell align="center">
<FormField
control={form.control}
name={`domains.${i}.rprsDmnYn`}
render={({ field }) => (
<FormItem>
<FormControl>
<Checkbox
checked={field.value === "Y"}
onCheckedChange={(checked) => {
field.onChange(checked ? "Y" : "N");
handleChangeRprsDmnYn(i);
}}
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
<TableCell align="center">
<FormField
control={form.control}
name={`domains.${i}.useYn`}
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
value={field.value}
onValueChange={field.onChange}
className="flex justify-center"
>
<div className="flex items-center space-x-2">
<RadioGroupItem
value="Y"
id={`useY-${i}`}
/>
<Label htmlFor={`useY-${i}`}>예</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem
value="N"
id={`useN-${i}`}
/>
<Label htmlFor={`useN-${i}`}>
아니오
</Label>
</div>
</RadioGroup>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
<DialogFooter className="!justify-center">
<Button type="submit" size="lg">
저장
</Button>
<DialogClose asChild>
<Button type="button" size="lg" color="white">
취소
</Button>
</DialogClose>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
<ConfirmDialog open={onConfirm} />
</>
);
}
+243 -141
View File
@@ -1,4 +1,8 @@
import { useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { useForm, useFieldArray } from "react-hook-form";
import {
Dialog,
DialogTrigger,
@@ -15,162 +19,260 @@ import {
Input,
RadioGroup,
RadioGroupItem,
Checkbox,
DialogFooter,
DialogClose,
Checkbox,
Label,
} from "@common/components";
type IP = {
id: number;
ipAddress: string;
allowed: boolean;
};
import { Form, FormControl, FormField, FormItem } from "@/shared/ui/form";
import { ENDPOINT } from "@/shared/config";
import { IpApi } from "../api/ip-service";
import { ipFormSchema, type IP, type IPFormData } from "../model/ip-interface";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
import { useAlertStore } from "@/shared/lib/use-alert-store";
type IPManagementDialogProps = {
siteId: string;
triggerDisabled?: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
};
function IPManagementDialog({ triggerDisabled }: IPManagementDialogProps) {
const [rows, setRows] = useState<IP[]>([]);
const [rowSelection, setRowSelection] = useState<IP["id"][]>([]);
function IPManagementDialog({
siteId,
triggerDisabled,
...props
}: IPManagementDialogProps) {
const { confirm } = useConfirm();
const { setMessage: alert } = useAlertStore((state) => state);
const onSave = () => {};
const { data: ipList } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.IPS, props.open],
queryFn: () => IpApi.getIpList({ siteId, sort: [] }),
select: (data) => {
const ips = data.content.map((item) => ({
...item,
mode: "U",
}));
initialForm();
return ips;
},
});
const { mutateAsync } = useMutation({
mutationFn: (body: IP[]) => IpApi.saveIpList(body),
});
const form = useForm<IPFormData>({
resolver: zodResolver(ipFormSchema),
values: {
ips: ipList ?? [],
},
});
const { fields, append, remove, update } = useFieldArray({
control: form.control,
name: "ips",
});
const [onConfirm, setOnConfirm] = useState(false);
const [selectedRows, setSelectedRows] = useState<number[]>([]);
const initialForm = () => {
form.reset();
setSelectedRows([]);
};
const onSubmit = async (data: IPFormData) => {
setOnConfirm(true);
if (await confirm("저장하시겠습니까?")) {
setOnConfirm(false);
await mutateAsync(data.ips);
alert("저장되었습니다.");
}
setOnConfirm(false);
};
const handleAddIP = () => {
const newIP: IP = {
id: Date.now(),
ipAddress: "",
allowed: true,
};
setRows([...rows, newIP]);
};
const handleDeleteIP = () => {
const filteredRows = rows.filter((row) => !rowSelection.includes(row.id));
setRows(filteredRows);
setRowSelection([]);
};
const handleIPAddressChange = (id: number, value: string) => {
setRows(
rows.map((row) => (row.id === id ? { ...row, ipAddress: value } : row)),
);
};
const handleAllowedChange = (id: number, value: boolean) => {
setRows(
rows.map((row) => (row.id === id ? { ...row, allowed: value } : row)),
);
};
const toggleRowSelection = (id: number) => {
setRowSelection((prev) => {
if (prev.includes(id)) {
return prev.filter((item) => item !== id);
} else {
return [...prev, id];
}
append({
mngNo: null,
siteId,
ipAddr: "",
prmYn: "Y",
mode: "C",
});
};
const handleSelectAll = () => {
if (selectedRows.length === fields.length) {
setSelectedRows([]);
} else {
setSelectedRows(fields.map((_, index) => index));
}
};
const handleSelectRow = (i: number) => {
setSelectedRows((prev) =>
prev.includes(i) ? prev.filter((j) => j !== i) : [...prev, i],
);
};
const handleDeleteIP = async () => {
if (selectedRows.length === 0) return;
const sortedIndices = [...selectedRows].sort((a, b) => b - a);
sortedIndices.forEach((i) => {
const field = fields[i];
if (field?.mngNo) {
update(i, {
...field,
mode: "D",
});
} else {
remove(i);
}
});
setSelectedRows([]);
};
const isAllSelected =
fields.length > 0 && selectedRows.length === fields.length;
return (
<Dialog>
<DialogTrigger asChild>
<Button disabled={triggerDisabled}>IP 관리</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[60rem]">
<DialogHeader>
<DialogTitle>IP 관리</DialogTitle>
</DialogHeader>
<div className="mb-4 flex justify-end gap-2">
<Button size="sm" color="green">
엑셀 업로드
</Button>
<Button size="sm" color="white" onClick={handleAddIP}>
항목 추가
</Button>
<Button
size="sm"
color="red"
onClick={handleDeleteIP}
disabled={rowSelection.length === 0}
>
항목 삭제
</Button>
</div>
<div className="card card-border">
<Table variant="secondary">
<colgroup>
<col width="10%" />
<col width="10%" />
<col width="55%" />
<col width="25%" />
</colgroup>
<TableHeader>
<TableRow>
<TableHead>NO</TableHead>
<TableHead>선택</TableHead>
<TableHead>IP 주소</TableHead>
<TableHead>허용여부</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map((row, idx) => (
<TableRow key={row.id}>
<TableCell align="center">{idx + 1}</TableCell>
<TableCell align="center">
<Checkbox
checked={rowSelection.includes(row.id)}
onCheckedChange={() => toggleRowSelection(row.id)}
className="cursor-pointer"
/>
</TableCell>
<TableCell align="center">
<Input
value={row.ipAddress}
onChange={(e) =>
handleIPAddressChange(row.id, e.target.value)
}
className="!text-[1.3rem]"
/>
</TableCell>
<TableCell align="center">
<RadioGroup
value={row.allowed ? "true" : "false"}
onValueChange={(value) =>
handleAllowedChange(row.id, value === "true")
}
className="flex justify-center"
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="true" id={`allow-${row.id}`} />
<label htmlFor={`allow-${row.id}`}>예</label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="false" id={`deny-${row.id}`} />
<label htmlFor={`deny-${row.id}`}>아니오</label>
</div>
</RadioGroup>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
<DialogFooter className="!justify-center">
<DialogClose asChild>
<Button size="lg" onClick={onSave}>
저장
</Button>
</DialogClose>
<DialogClose asChild>
<Button size="lg" color="white">
취소
</Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
<>
<Dialog {...props}>
<DialogTrigger asChild>
<Button disabled={triggerDisabled}>IP 관리</Button>
</DialogTrigger>
<DialogContent className="max-w-[60rem]" aria-describedby={undefined}>
<DialogHeader>
<DialogTitle>IP 관리</DialogTitle>
</DialogHeader>
<Form {...form}>
<form
onSubmit={(e) => {
e.preventDefault();
e.stopPropagation();
form.handleSubmit(onSubmit)(e);
}}
>
<div className="mb-4 flex justify-end gap-2">
<Button type="button" size="sm" onClick={handleAddIP}>
항목 추가
</Button>
<Button
type="button"
size="sm"
color="red"
onClick={handleDeleteIP}
disabled={selectedRows.length === 0}
>
항목 삭제
</Button>
</div>
<div className="card card-border max-h-[28.5rem] overflow-auto">
<Table variant="secondary">
<colgroup>
<col width="10%" />
<col width="65%" />
<col width="25%" />
</colgroup>
<TableHeader className="sticky -top-[0.6rem]">
<TableRow>
<TableHead className="!px-0">
<Checkbox
checked={isAllSelected}
onCheckedChange={handleSelectAll}
/>
</TableHead>
<TableHead>IP 주소</TableHead>
<TableHead>허용여부</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{fields.map((field, i) => {
if (field.mode === "D") return null;
return (
<TableRow key={field.id}>
<TableCell align="center" className="!px-0">
<Checkbox
checked={selectedRows.includes(i)}
onCheckedChange={() => handleSelectRow(i)}
/>
</TableCell>
<TableCell align="center">
<FormField
control={form.control}
name={`ips.${i}.ipAddr`}
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
className="!text-[1.3rem]"
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
<TableCell align="center">
<FormField
control={form.control}
name={`ips.${i}.prmYn`}
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
value={field.value}
onValueChange={field.onChange}
className="flex justify-center"
>
<div className="flex items-center space-x-2">
<RadioGroupItem
value="Y"
id={`prmY-${i}`}
/>
<Label htmlFor={`prmY-${i}`}>예</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem
value="N"
id={`prmN-${i}`}
/>
<Label htmlFor={`prmN-${i}`}>
아니오
</Label>
</div>
</RadioGroup>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
<DialogFooter className="!justify-center">
<Button type="submit" size="lg">
저장
</Button>
<DialogClose asChild>
<Button type="button" size="lg" color="white">
취소
</Button>
</DialogClose>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
<ConfirmDialog open={onConfirm} />
</>
);
}
-12
View File
@@ -1,12 +0,0 @@
function SitePageLayout({ children }: { children: React.ReactNode }) {
return (
<div className="h-auto min-h-full bg-container">
<h2 className="px-[1.8rem] pt-[2rem] text-[2.4rem] font-semibold text-title">
사이트 관리
</h2>
{children}
</div>
);
}
export { SitePageLayout };
+34 -57
View File
@@ -1,94 +1,71 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { useMutation, useQuery } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";
import {
SiteApi,
siteFormSchema,
type ISiteDetail,
type SiteFormData,
} from "@/entities/site";
import { ENDPOINT } from "@/shared/config/api";
import { SitePageLayout } from "./layout";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { SiteApi, siteFormSchema, type SiteFormData } from "@/entities/site";
import { ENDPOINT } from "@/shared/config";
import { useAlertStore } from "@/shared/lib/use-alert-store";
import { SiteForm } from "./site-form";
import {
Button,
Dialog,
DialogClose,
DialogContent,
DialogFooter,
} from "@common/components/ui";
function ModifyPage({ siteId }: { siteId: string }) {
const isModifyMode = !!siteId;
const router = useRouter();
const queryClient = useQueryClient();
const { setMessage: alert } = useAlertStore((state) => state);
const { data: siteDetail } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.SITES, siteId],
queryFn: () => SiteApi.siteDetail(siteId),
select: (data) => ({
...data,
faxNo: data.faxNumber,
bscSiteYn: data.basicSiteYn,
}),
enabled: isModifyMode,
select: (data) => {
const keys = Object.keys(siteFormSchema.shape);
const filteredData = Object.fromEntries(
Object.entries(data).filter(([key]) => keys.includes(key)),
);
return {
...filteredData,
faxNo: data.faxNumber,
bscSiteYn: data.basicSiteYn,
};
},
enabled: !!siteId,
});
const { mutateAsync: modifySite } = useMutation({
mutationFn: (data: SiteFormData) => SiteApi.modifySite(siteId, data),
const { mutateAsync: updateSite } = useMutation({
mutationFn: (data: SiteFormData) => SiteApi.updateSite(siteId, data),
onSuccess: () => {
setMessage("수정되었습니다.");
alert("수정되었습니다.", () => {
queryClient.invalidateQueries({
queryKey: [ENDPOINT.CMS_SERVICE.SITES],
});
});
},
});
const { mutateAsync: deleteSite } = useMutation({
mutationFn: () => SiteApi.deleteSite(siteId),
onSuccess: () => {
setMessage("삭제되었습니다.");
alert("삭제되었습니다.", router.back);
},
});
const [message, setMessage] = useState("");
const form = useForm<SiteFormData>({
resolver: zodResolver(siteFormSchema),
values: siteDetail as SiteFormData,
});
useEffect(() => {
if (!siteDetail) return;
const keys = Object.keys(siteFormSchema.shape);
for (const key of keys) {
form.setValue(
key as keyof SiteFormData,
siteDetail[key as keyof ISiteDetail] ?? "",
);
}
}, [siteDetail]);
return (
<SitePageLayout>
<div className="card card-border !mb-0 !mt-6">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">사이트 수정</h3>
</div>
<SiteForm
form={form}
siteId={siteId}
handleSave={modifySite}
handleSave={updateSite}
handleDelete={deleteSite}
/>
<Dialog open={!!message} onOpenChange={() => router.back()}>
<DialogContent aria-describedby={undefined}>
<div className="py-10">
<p className="text-center text-[1.4rem]">{message}</p>
</div>
<DialogFooter className="!justify-center">
<DialogClose asChild>
<Button>확인</Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
</SitePageLayout>
</div>
);
}
+325 -346
View File
@@ -4,10 +4,6 @@ import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { type UseFormReturn } from "react-hook-form";
import {
Button,
Dialog,
DialogClose,
DialogContent,
DialogFooter,
Input,
Label,
RadioGroup,
@@ -19,371 +15,372 @@ import {
TableRow,
} from "@common/components";
import { CodeSelect } from "@/entities/code";
import { type ISiteDetail, type SiteFormData } from "@/entities/site";
import {
FormItem,
FormControl,
FormField,
Form,
FormMessage,
} from "@/shared/ui/form";
import type { SiteFormData } from "@/entities/site";
import { FormItem, FormControl, FormField, Form } from "@/shared/ui/form";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
import type { Domain } from "../model/domain-interface";
import { IPManagementDialog } from "./ip-management-dialog";
import {
DomainManagementDialog,
type Domain,
} from "./domain-management-dialog";
import { DomainManagementDialog } from "./domain-management-dialog";
type SiteFormProps = {
form: UseFormReturn<SiteFormData>;
siteId?: string;
handleSave: (data: SiteFormData) => void;
handleDelete: () => void;
handleSave: (data: SiteFormData) => Promise<void>;
handleDelete?: () => Promise<void>;
};
function SiteForm({ form, siteId, handleSave, handleDelete }: SiteFormProps) {
const router = useRouter();
const { message, confirm, onConfirm, onCancel } = useConfirm();
const [viewState, setViewState] = useState<Partial<ISiteDetail>>({});
const [representativeDomain, setRepresentativeDomain] = useState<string>("");
const isModifyMode = !!siteId;
const handleViewStateChange = (key: keyof ISiteDetail) => (value: string) => {
setViewState({ ...viewState, [key]: value });
const router = useRouter();
const { confirm } = useConfirm();
const [onConfirm, setOnConfirm] = useState(false);
const [isIpManagementOpen, setIsIpManagementOpen] = useState(false);
const [isDomainManagementOpen, setIsDomainManagementOpen] = useState(false);
const handleConfirm = async (callback: () => Promise<void>) => {
setOnConfirm(true);
await callback();
setOnConfirm(false);
};
const handleDomainSave = (rows: Domain[]) => {
setRepresentativeDomain(
rows.find((row) => row.isRepresentative)?.domainUrl || "",
const handleSaveDomain = (rows: Domain[]) => {
form.setValue(
"dmnAddr",
rows.find((row) => row.rprsDmnYn === "Y")?.dmnAddr || "",
);
};
const onSubmit = (data: SiteFormData) => {
handleSave(data);
const onSubmit = async (data: SiteFormData) => {
const confirmMessage = isModifyMode
? "수정하시겠습니까?"
: "저장하시겠습니까?";
await handleConfirm(async () => {
if (await confirm(confirmMessage)) {
setOnConfirm(false);
handleSave(data);
}
});
};
const onDelete = async () => {
if (await confirm("정말 삭제하시겠습니까?")) {
handleDelete();
}
await handleConfirm(async () => {
if (await confirm("삭제하시겠습니까?")) {
setOnConfirm(false);
handleDelete?.();
}
});
};
return (
<>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<div className="card card-border !mt-6">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">
사이트 등록/수정
</h3>
</div>
<div className="card">
<Table variant="secondary">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<TableBody>
<TableRow>
<TableHead>사이트 코드</TableHead>
<TableCell className="border">
<div className="card">
<Table variant="secondary">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<TableBody>
<TableRow>
<TableHead>사이트 코드</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="siteId"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="w-[12rem] !text-[1.3rem]"
disabled={isModifyMode}
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 구분</TableHead>
<TableCell className="border">
<div className="flex gap-2">
<FormField
control={form.control}
name="siteId"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
className="w-[12rem] !text-[1.3rem]"
disabled={isModifyMode}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 구분</TableHead>
<TableCell className="border">
<div className="flex gap-2">
<FormField
control={form.control}
name="siteKndCd"
render={({ field }) => (
<FormItem>
<FormControl>
<CodeSelect
{...field}
upCd="SITEKNDCD"
onValueChange={(value) => {
handleViewStateChange("siteKndCd")(value);
field.onChange(value);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{isModifyMode && (
<IPManagementDialog
triggerDisabled={viewState.siteKndCd === "O"}
/>
)}
</div>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 디자인</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="siteSkn"
name="siteKndCd"
render={({ field }) => (
<FormItem>
<FormControl>
<CodeSelect
{...field}
upCd="SITESKINCD"
upCd="SITEKNDCD"
onValueChange={field.onChange}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
{isModifyMode && (
<IPManagementDialog
siteId={siteId}
triggerDisabled={form.watch("siteKndCd") === "O"}
open={isIpManagementOpen}
onOpenChange={setIsIpManagementOpen}
/>
)}
</div>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 디자인</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="siteSkn"
render={({ field }) => (
<FormItem>
<FormControl>
<CodeSelect
{...field}
value={field.value ?? ""}
upCd="SITESKINCD"
onValueChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트명</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="siteNm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="사이트명을 입력하십시오."
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 설명</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="siteExpln"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="사이트 설명을 입력하십시오."
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
{isModifyMode && (
<TableRow>
<TableHead>사이트명</TableHead>
<TableHead>사이트 도메인</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="siteNm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
className="!text-[1.3rem]"
placeholder="사이트명을 입력하십시오."
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 설명</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="siteExpln"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
className="!text-[1.3rem]"
placeholder="사이트 설명을 입력하십시오."
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
{isModifyMode && (
<TableRow>
<TableHead>사이트 도메인</TableHead>
<TableCell className="border">
<div className="flex gap-2">
<div className="h-[3.2rem] w-[21.5rem] cursor-not-allowed rounded-md border border-input bg-form px-3 py-2 text-[1.3rem] opacity-50">
{representativeDomain}
</div>
<DomainManagementDialog
handleSave={handleDomainSave}
/>
<div className="flex gap-2">
<div className="h-[3.2rem] w-[21.5rem] cursor-not-allowed rounded-md border border-input bg-form px-3 py-2 text-[1.3rem] opacity-50">
{form.watch("dmnAddr")}
</div>
</TableCell>
</TableRow>
)}
<TableRow>
<TableHead>사이트 하단 표기 주소</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="siteAddr"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
className="!text-[1.3rem]"
placeholder="사이트 하단 주소를 입력하십시오."
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<DomainManagementDialog
siteId={siteId}
open={isDomainManagementOpen}
onOpenChange={setIsDomainManagementOpen}
handleSaveDomain={handleSaveDomain}
/>
</div>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 하단 표기 전화번호</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="telNo"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
className="!text-[1.3rem]"
placeholder="사이트 하단 전화번호를 입력하십시오."
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 하단 표기 팩스번호</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="faxNo"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
className="!text-[1.3rem]"
placeholder="사이트 하단 팩스번호를 입력하십시오."
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 하단 표기 내용</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="lwndCn"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
className="!text-[1.3rem]"
placeholder="사이트 표기 내용을 입력하십시오. (ex. COPYRIGHT c 2013 KECO. ALL RIGHTS RESERVED.)"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>북마크 아이콘</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="bkmkIcon"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
className="!text-[1.3rem]"
placeholder="아이콘 파일 경로 및 파일명을 입력하여 주십시오."
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>기본 사이트 여부</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="bscSiteYn"
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
{...field}
name="bscSiteYn"
onValueChange={field.onChange}
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="Y" id="bscSiteY" />
<Label htmlFor="bscSiteY">예</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="N" id="bscSiteN" />
<Label htmlFor="bscSiteN">아니오</Label>
</div>
</RadioGroup>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사용 여부</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="useYn"
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
{...field}
name="useYn"
onValueChange={field.onChange}
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="Y" id="useY" />
<Label htmlFor="useY">사용</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="N" id="useN" />
<Label htmlFor="useN">사용안함</Label>
</div>
</RadioGroup>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
)}
<TableRow>
<TableHead>사이트 하단 표기 주소</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="siteAddr"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="사이트 하단 주소를 입력하십시오."
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 하단 표기 전화번호</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="telNo"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="사이트 하단 전화번호를 입력하십시오."
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 하단 표기 팩스번호</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="faxNo"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="사이트 하단 팩스번호를 입력하십시오."
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 하단 표기 내용</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="lwndCn"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="사이트 표기 내용을 입력하십시오. (ex. COPYRIGHT c 2013 KECO. ALL RIGHTS RESERVED.)"
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>북마크 아이콘</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="bkmkIcon"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="아이콘 파일 경로 및 파일명을 입력하여 주십시오."
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>기본 사이트 여부</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="bscSiteYn"
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
{...field}
name="bscSiteYn"
onValueChange={field.onChange}
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="Y" id="bscSiteY" />
<Label htmlFor="bscSiteY">예</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="N" id="bscSiteN" />
<Label htmlFor="bscSiteN">아니오</Label>
</div>
</RadioGroup>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사용 여부</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="useYn"
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
{...field}
name="useYn"
onValueChange={field.onChange}
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="Y" id="useY" />
<Label htmlFor="useY">사용</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="N" id="useN" />
<Label htmlFor="useN">사용안함</Label>
</div>
</RadioGroup>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
<div className="flex justify-center gap-4 pb-12 pt-10">
<Button
@@ -405,25 +402,7 @@ function SiteForm({ form, siteId, handleSave, handleDelete }: SiteFormProps) {
</div>
</form>
</Form>
<Dialog open={!!message} onOpenChange={onCancel}>
<DialogContent aria-describedby={undefined}>
<div className="py-10">
<p className="text-center text-[1.4rem]">{message}</p>
</div>
<DialogFooter className="!justify-center">
<DialogClose asChild>
<Button color="red" onClick={onConfirm}>
삭제
</Button>
</DialogClose>
<DialogClose asChild>
<Button color="white" onClick={onCancel}>
취소
</Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
<ConfirmDialog open={onConfirm} />
</>
);
}
+33 -45
View File
@@ -2,36 +2,29 @@
import "@common/assets/styles/grid.css";
import { type ISite, type ISiteParams } from "@/entities/site";
import { SiteApi } from "@/entities/site/api/site-service";
import { ENDPOINT } from "@/shared/config/api";
import { Button, DataTable, Input } from "@common/components";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { getCoreRowModel, useReactTable } from "@tanstack/react-table";
import { useRouter } from "next/router";
import { useState } from "react";
import { Button, DataTable, Input, Label } from "@common/components";
import { SiteApi, type Site, type SiteParams } from "@/entities/site";
import { ENDPOINT } from "@/shared/config";
import { columns } from "../model/table-columns";
import { SitePageLayout } from "./layout";
function SitePage() {
const router = useRouter();
const { data: siteInfo, refetch } = useQuery({
const { data: siteList, refetch } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.SITES],
queryFn: () => SiteApi.siteInfo(siteQuery),
queryFn: () => SiteApi.getSiteList(siteQuery),
enabled: false,
});
const [siteQuery, setSiteQuery] = useState<ISiteParams>({
const [siteQuery, setSiteQuery] = useState<SiteParams>({
siteNm: "",
siteKndCd: "",
useYn: "",
page: 0,
size: 0,
sort: [],
});
const table = useReactTable({
data: siteInfo?.content ?? [],
data: siteList?.content ?? [],
columns,
getCoreRowModel: getCoreRowModel(),
});
@@ -41,46 +34,41 @@ function SitePage() {
refetch();
};
const handleRowClick = (row: ISite) => {
const handleRowClick = (row: Site) => {
router.push(`/site/register/${row.siteId}`);
};
useEffect(() => {
refetch();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<SitePageLayout>
<div className="card card-border !mt-6">
<div className="card card-border !border-[#dbe2e6] !bg-[#eef7ff]">
<form onSubmit={handleSubmit} className="flex items-center gap-2 p-2">
<label htmlFor="" className="mr-2 text-[#657481]">
사이트명
</label>
<Input
className="h-[3.2rem] w-[24rem] rounded-sm !text-[1.3rem]"
value={siteQuery.siteNm}
onChange={(e) =>
setSiteQuery({ ...siteQuery, siteNm: e.target.value })
}
/>
<Button className="h-[3.2rem]" type="submit">
조회
</Button>
</form>
<div className="card card-border !mt-6">
<div className="card card-border">
<form onSubmit={handleSubmit} className="flex items-center gap-2 p-2">
<Label htmlFor="" className="mr-2 text-label">
사이트명
</Label>
<Input
className="h-[3.2rem] w-[24rem] rounded-sm !text-[1.3rem]"
value={siteQuery.siteNm}
onChange={(e) => setSiteQuery({ siteNm: e.target.value })}
/>
<Button className="h-[3.2rem]" type="submit">
조회
</Button>
</form>
</div>
<div className="card card-border">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">사이트 목록</h3>
<Button onClick={() => router.push("/site/register")}>등록</Button>
</div>
<div className="card card-border">
<div className="card-header">
<h3 className="text-2xl font-medium text-[#666]">사이트 목록</h3>
<Button onClick={() => router.push("/site/register")}>등록</Button>
</div>
<div className="card !m-[1.2rem] h-[49rem] overflow-auto !p-0">
<DataTable table={table} onRowClick={handleRowClick} />
</div>
<div className="card !m-[1.2rem] h-[49rem] overflow-auto !p-0">
<DataTable table={table} onRowClick={handleRowClick} />
</div>
</div>
</SitePageLayout>
</div>
);
}
+1
View File
@@ -0,0 +1 @@
export { client } from "./client";
+16
View File
@@ -3,6 +3,11 @@ import { PROXY_HOST } from "./env";
export const BASE_URL = `${PROXY_HOST}/server`;
export const ENDPOINT = {
ATTACH_SERVICE: {
TUS_UPLOAD: "/attach-service/api/v1/tus/upload",
IMAGES: "/attach-service/api/v1/images",
ATTACHMENTS: "/attach-service/api/v1/atfl/attachments",
},
USER_SERVICE: {
LOGIN: "/user-service/login",
USERS: "/user-service/api/v1/users",
@@ -11,6 +16,17 @@ export const ENDPOINT = {
CMS_SERVICE: {
SITES: "/cms-service/api/v1/sites",
CODE: "/cms-service/api/v1/code/cache",
IPS: "/cms-service/api/v1/site-ips",
DOMAINS: "/cms-service/api/v1/site-dmns",
MENUS: "/cms-service/api/v1/menus",
MENU_ROLES: "/cms-service/api/v1/menu-roles",
CONTENTS: "/cms-service/api/v1/contents",
USER_OGNZ: "/cms-service/api/v1/user-ognz",
IMAGES: "/cms-service/api/v1/images",
SITE_PSTGS: "/cms-service/api/v1/site-pstgs",
},
BOARD_SERVICE: {
BBS: "/board-service/api/v1/bbs",
},
};
+2
View File
@@ -0,0 +1,2 @@
export * from "./api";
export * from "./env";
+3
View File
@@ -0,0 +1,3 @@
export { getCookie, setCookie, removeCookie } from "./cookie";
export { useMenuStore } from "./use-menu-store";
export { useUserStore } from "./use-user-store";
+14
View File
@@ -0,0 +1,14 @@
import { useStore } from "zustand";
import { useContext } from "react";
import type { AlertStore } from "../store/alert-store";
import { StoreContext } from "../providers/store-provider";
export const useAlertStore = <T>(selector: (store: AlertStore) => T): T => {
const storeContext = useContext(StoreContext);
if (!storeContext) {
throw new Error("useAlertStore must be used within StoreProvider");
}
return useStore(storeContext.alertStore, selector);
};
+14
View File
@@ -0,0 +1,14 @@
import { useStore } from "zustand";
import { useContext } from "react";
import type { MenuStore } from "../store/menu-store";
import { StoreContext } from "../providers/store-provider";
export const useMenuStore = <T>(selector: (store: MenuStore) => T): T => {
const storeContext = useContext(StoreContext);
if (!storeContext) {
throw new Error("useMenuStore must be used within StoreProvider");
}
return useStore(storeContext.menuStore, selector);
};
+14
View File
@@ -0,0 +1,14 @@
import { useStore } from "zustand";
import { useContext } from "react";
import type { UserStore } from "../store/user-store";
import { StoreContext } from "../providers/store-provider";
export const useUserStore = <T>(selector: (store: UserStore) => T): T => {
const storeContext = useContext(StoreContext);
if (!storeContext) {
throw new Error("useUserStore must be used within StoreProvider");
}
return useStore(storeContext.userStore, selector);
};
+34
View File
@@ -0,0 +1,34 @@
interface SortConfig {
empty: boolean;
sorted: boolean;
unsorted: boolean;
}
interface PageableConfig {
sort: SortConfig;
offset: number;
pageNumber: number;
pageSize: number;
paged: boolean;
unpaged: boolean;
}
export interface PageableList<T> {
content: T[];
pageable: PageableConfig;
sort: SortConfig;
totalPages: number;
totalElements: number;
number: number;
numberOfElements: number;
size: number;
first: boolean;
last: boolean;
empty: boolean;
}
export interface PageableParams {
page?: number;
size?: number;
sort?: string[];
}

Some files were not shown because too many files have changed in this diff Show More