Merge branch 'iipbs/common/main' into iipbs/wr/dev
iipbs_wr / build (push) Has been cancelled

This commit is contained in:
truthwing
2025-04-24 18:54:41 +09:00
308 changed files with 12762 additions and 1888 deletions
+15 -8
View File
@@ -1,20 +1,27 @@
"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 (
<StoreProvider>
<ConfirmProvider>
<AuthWrapper>
{children}
<AlertDialog />
</AuthWrapper>
</ConfirmProvider>
</StoreProvider>
<QueryClientProvider client={queryClient}>
<StoreProvider>
<ConfirmProvider>
<AuthWrapper>
<MenuWrapper>{children}</MenuWrapper>
<AlertDialog />
<ConfirmDialog />
</AuthWrapper>
</ConfirmProvider>
</StoreProvider>
</QueryClientProvider>
);
};
+62 -20
View File
@@ -9,43 +9,84 @@
color: #666;
}
.card_width10 {width:calc(10% - 12px);}
.card_width10 {
width: calc(10% - 12px);
}
.card_width20 {width:calc(20% - 12px);}
.card_width20 {
width: calc(20% - 12px);
}
.card_width25 {width:calc(25% - 12px);}
.card_width25 {
width: calc(25% - 12px);
}
.card_width30 {width:calc(30% - 12px);}
.card_width30 {
width: calc(30% - 12px);
}
.card_width33 {width:calc(33.333% - 12px);}
.card_width33 {
width: calc(33.333% - 12px);
}
.card_width40 {width:calc(40% - 12px);}
.card_width40 {
width: calc(40% - 12px);
}
.card_width45 {width:calc(45% - 12px);}
.card_width45 {
width: calc(45% - 12px);
}
.card_width50 {width:calc(50% - 12px);}
.card_width50 {
width: calc(50% - 12px);
}
.card_width60 {width:calc(60% - 12px);}
.card_width60 {
width: calc(60% - 12px);
}
.card_width66 {width:calc(66.666% - 12px);}
.card_width66 {
width: calc(66.666% - 12px);
}
.card_width70 {width:calc(70% - 12px);}
.card_width70 {
width: calc(70% - 12px);
}
.card_width75 {width:calc(75% - 12px);}
.card_width75 {
width: calc(75% - 12px);
}
.card_width80 {width:calc(80% - 12px);}
.card_width80 {
width: calc(80% - 12px);
}
.card_width90 {width:calc(90% - 12px);}
.card_width90 {
width: calc(90% - 12px);
}
.card_width100 {width:calc(100% - 12px);}
.card_width100 {
width: calc(100% - 12px);
}
.card_nopadding {padding:0 !important;}
.card_nopadding {
padding: 0 !important;
}
.card_nomargin {width:100%;margin:0 !important;padding:0 !important;}
.card_nomargin {
width: 100%;
margin: 0 !important;
padding: 0 !important;
}
.topline {border-top: 1px solid #ccc;}
.topline {
border-top: 1px solid #ccc;
}
.bottomline {border-bottom: 1px solid #e6eef3;background: #fff;}
.bottomline {
border-bottom: 1px solid #e6eef3;
background: #fff;
}
.card-border {
border: 1px solid #dbe2e6;
@@ -54,6 +95,7 @@
}
.card-header {
margin-top: -0.6rem;
margin-left: -0.6rem;
margin-right: -0.6rem;
display: flex;
@@ -78,8 +120,8 @@
/* 블랙 테마 */
[data-theme="black"] {
.card-border {
border-color: #3f4042;
background-color: rgba(255, 255, 255, 0.065);
border-color: #38383a;
}
.card-header {
border-bottom-color: #3f4042;
@@ -0,0 +1,55 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type {
Attachment,
AttachmentList,
AttachmentParams,
AttachmentService,
} from "../model/attachment-interface";
export class AttachmentApiService implements AttachmentService {
public async getAttachmentsList(
params: AttachmentParams,
): Promise<AttachmentList> {
const response = await client.get<AttachmentList>(
`${ENDPOINT.ATTACH_SERVICE.ATTACHMENTS}`,
{ params },
);
return response.data;
}
public async getAttachmentsInfo(atflCd: string): Promise<Attachment[]> {
const response = await client.get<Attachment[]>(
`${ENDPOINT.ATTACH_SERVICE.ATTACHMENTS}/${atflCd}`,
);
return response.data;
}
public async deleteAttachment(atflId: string): Promise<void> {
await client.delete(`${ENDPOINT.ATTACH_SERVICE.ATTACHMENTS}/${atflId}`);
}
public async deleteAttachmentByAtflCd(atflCd: string): Promise<void> {
await client.delete(
`${ENDPOINT.ATTACH_SERVICE.ATTACHMENTS}/atflCd/${atflCd}`,
);
}
public async getImageUrl(atflId: string): Promise<string> {
if (!atflId) return "";
const response = await fetch(`${ENDPOINT.ATTACH_SERVICE.IMAGES}/${atflId}`);
const blob = await response.blob();
return URL.createObjectURL(blob);
}
public async getImageUrlByAtflCd(atflCd: string): Promise<string> {
if (!atflCd) return "";
const response = await fetch(
`${ENDPOINT.ATTACH_SERVICE.IMAGES}/atflCd/${atflCd}`,
);
const blob = await response.blob();
return URL.createObjectURL(blob);
}
}
export const AttachmentApi = new AttachmentApiService();
+1
View File
@@ -0,0 +1 @@
export { AttachmentApi } from "./api/attachment-service";
@@ -0,0 +1,42 @@
import type { PageableList, PageableParams } from "@/shared/model";
export interface AttachmentParams extends PageableParams {
keywordType?: string;
keyword?: string;
atflCd?: string;
atflSn?: number;
atflId?: string;
orgnlFileNm?: string;
atflFlieSz?: number;
atflType?: string;
dwnldNocs?: number;
delYn?: string;
lnkgDmnId?: string;
lnkgDmnNm?: string;
}
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 type AttachmentList = PageableList<Attachment>;
export interface AttachmentService {
getAttachmentsList: (params: AttachmentParams) => Promise<AttachmentList>;
getAttachmentsInfo: (atflCd: string) => Promise<Attachment[]>;
deleteAttachment: (atflId: string) => Promise<void>;
deleteAttachmentByAtflCd: (atflCd: string) => Promise<void>;
getImageUrl: (atflId: string) => Promise<string>;
getImageUrlByAtflCd: (atflCd: string) => Promise<string>;
}
+1 -1
View File
@@ -1,2 +1,2 @@
export { LoginApi } from "./api/login-service";
export { AuthWrapper } from "./ui/auth-wrapper";
export { AuthWrapper } from "./lib/auth-wrapper";
@@ -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
View File
@@ -0,0 +1 @@
export { CodeSelect } from "../ui/code-select";
@@ -0,0 +1,51 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type {
ContentsService,
ContentsParams,
ContentsList,
Contents,
ContentsFormData,
} from "../model/contents-interface";
export class ContentsApiService implements ContentsService {
public async getContentsList(params: ContentsParams): Promise<ContentsList> {
const response = await client.get<ContentsList>(
`${ENDPOINT.CMS_SERVICE.CONTENTS}`,
{ params },
);
return response.data;
}
public async getContentsInfo(contsSn: number): Promise<Contents> {
const response = await client.get<Contents>(
`${ENDPOINT.CMS_SERVICE.CONTENTS}/${contsSn}`,
);
return response.data;
}
public async createContents(data: ContentsFormData): Promise<void> {
const response = await client.post<void>(
`${ENDPOINT.CMS_SERVICE.CONTENTS}`,
data,
);
return response.data;
}
public async updateContents(
contsSn: number,
data: ContentsFormData,
): Promise<void> {
const response = await client.put<void>(
`${ENDPOINT.CMS_SERVICE.CONTENTS}/${contsSn}`,
data,
);
return response.data;
}
public async deleteContents(contsSn: number): Promise<void> {
await client.delete(`${ENDPOINT.CMS_SERVICE.CONTENTS}/${contsSn}`);
}
}
export const ContentsApi = new ContentsApiService();
+2
View File
@@ -0,0 +1,2 @@
export { ContentsApi } from "./api/contents-service";
export type { Contents, ContentsParams } from "./model/contents-interface";
@@ -0,0 +1,37 @@
import { z } from "zod";
import type { PageableList, PageableParams } from "@/shared/model";
export interface ContentsParams extends PageableParams {
contsTtl?: string;
aprvContsVer?: number;
useYn?: string;
}
export const contentsSchema = z.object({
contsSn: z.number(),
contsTtl: z.string(),
aprvContsVer: z.number(),
useYn: z.string(),
regDt: z.string(),
mdfcnDt: z.string(),
rgTrNm: z.string(),
mdfrNm: z.string(),
});
export const contentsFormSchema = z.object({
contsTtl: z.string(),
useYn: z.string(),
rgtr: z.string().nullish(),
});
export type Contents = z.infer<typeof contentsSchema>;
export type ContentsFormData = z.infer<typeof contentsFormSchema>;
export type ContentsList = PageableList<Contents>;
export interface ContentsService {
getContentsList(params: ContentsParams): Promise<ContentsList>;
getContentsInfo(contsSn: number): Promise<Contents>;
createContents(data: ContentsFormData): Promise<void>;
updateContents(contsSn: number, data: ContentsFormData): Promise<void>;
deleteContents(contsSn: number): Promise<void>;
}
@@ -0,0 +1,19 @@
import { client } from "@/shared/api";
import type {
EditorService,
FileInfo,
UploadFile,
} from "../model/editor-interface";
import { ENDPOINT } from "@/shared/config";
export class EditorApiService implements EditorService {
async uploadImage(data: UploadFile): Promise<FileInfo> {
const response = await client.post<FileInfo>(
ENDPOINT.ATTACH_SERVICE.EDITOR_UPLOAD,
data,
);
return response.data;
}
}
export const EditorApi = new EditorApiService();
+1
View File
@@ -0,0 +1 @@
export { Editor } from "./ui/editor";
@@ -0,0 +1,10 @@
export const blobToBase64 = (blob: Blob): Promise<string> => {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = () => {
const base64 = reader.result as string;
resolve(base64.split(",")[1] || "");
};
reader.readAsDataURL(blob);
});
};
@@ -0,0 +1,16 @@
import { blobToBase64 } from "./blob-to-base64";
export const generateFileInfo = async (blobInfo: {
blob: () => Blob;
filename: () => string;
}) => {
const blob = blobInfo.blob();
const base64 = await blobToBase64(blob);
return {
fieldName: `${blob.type.split("/")[1]}`,
fileType: blob.type,
fileBase64: base64,
originalName: blobInfo.filename(),
size: blob.size,
};
};
@@ -0,0 +1,37 @@
import { SERVER_API_URL } from "@/shared/config";
export const editorBaseConfig = {
apiKey: process.env.NEXT_PUBLIC_TINY_API_KEY,
init: {
language: "ko_KR",
height: 500,
plugins: [
"advlist",
"autolink",
"lists",
"link",
"image",
"charmap",
"preview",
"anchor",
"searchreplace",
"visualblocks",
"code",
"codesample",
"fullscreen",
"insertdatetime",
"media",
"table",
"code",
"help",
"wordcount",
"save",
],
toolbar: [
"undo redo | blocks fontfamily fontsize | bold italic underline strikethrough forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist blockquote | table",
"link image",
],
images_upload_base_path: SERVER_API_URL,
file_picker_types: "image",
},
};
@@ -0,0 +1,20 @@
export interface UploadFile {
fieldName: string;
fileType: string;
fileBase64: string;
originalName: string;
size: number;
}
export interface FileInfo {
originalFileName: string;
message: string;
fileType: string;
size: number;
uploaded: number;
url: string;
}
export interface EditorService {
uploadImage(data: UploadFile): Promise<FileInfo>;
}
+60
View File
@@ -0,0 +1,60 @@
import { useRef } from "react";
import {
Editor as TinyEditor,
type Editor as TinyEditorInstance,
type IAllProps,
} from "@tinymce/tinymce-react";
import { editorBaseConfig as baseConfig } from "../model/editor-base-config";
import { generateFileInfo } from "../lib/generate-file-info";
import { EditorApi } from "../api/editor-service";
const Editor = ({ ...props }: IAllProps) => {
const editorRef = useRef<TinyEditorInstance | null>(null);
const imagesUploadHandler = (blobInfo: {
blob: () => Blob;
filename: () => string;
}) => {
return new Promise(async (resolve) => {
const fileInfo = await generateFileInfo(blobInfo);
const data = await EditorApi.uploadImage(fileInfo);
resolve(data.url);
});
};
const filePickerCallback = (
callback: (base64: string, meta: { title: string }) => void,
) => {
const input = document.createElement("input");
input.setAttribute("type", "file");
input.setAttribute("accept", "image/*");
input.onchange = async () => {
const file = input.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = async () => {
const base64 = reader.result as string;
callback(base64, { title: file.name });
};
reader.readAsDataURL(file);
};
input.click();
};
return (
<TinyEditor
{...baseConfig}
onInit={(_: unknown, editor: TinyEditorInstance) => {
editorRef.current = editor;
}}
init={{
...baseConfig.init,
images_upload_handler: imagesUploadHandler,
file_picker_callback: filePickerCallback,
}}
{...props}
/>
);
};
export { Editor };
@@ -0,0 +1,32 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type {
MenuAuthorityList,
MenuAuthorityParams,
MenuAuthorityPayloadData,
MenuAuthorityService,
} from "../model/menu-authority-interface";
export class MenuAuthorityApiService implements MenuAuthorityService {
public async getMenuAuthorityList(
params: MenuAuthorityParams,
): Promise<MenuAuthorityList> {
const response = await client.get<MenuAuthorityList>(
`${ENDPOINT.CMS_SERVICE.MENU_AUTHRTS}`,
{ params },
);
return response.data;
}
public async saveMenuAuthority(
data: MenuAuthorityPayloadData[],
): Promise<void> {
const response = await client.post<void>(
`${ENDPOINT.CMS_SERVICE.MENU_AUTHRTS}`,
data,
);
return response.data;
}
}
export const MenuAuthorityApi = new MenuAuthorityApiService();
@@ -0,0 +1 @@
export { ManagementAuthorityDialog } from "./ui/management-authority-dialog";
@@ -0,0 +1,41 @@
import { z } from "zod";
import type { PageableList, PageableParams } from "@/shared/model";
export interface MenuAuthorityParams extends PageableParams {
groupId?: string;
menuCd?: number;
useYn?: string;
}
export const menuAuthoritySchema = z.object({
groupId: z.string(),
groupNm: z.string(),
menuCd: z.number(),
mngAuthrtYn: z.string(),
inqAuthrtYn: z.string(),
regAuthrtYn: z.string(),
mdfcnAuthrtYn: z.string(),
delAuthrtYn: z.string(),
useYn: z.string(),
mode: z.string(),
});
export const menuAuthorityPayloadSchema = menuAuthoritySchema.omit({
groupNm: true,
});
export const menuAuthorityFormSchema = z.object({
menuAuthority: z.array(menuAuthorityPayloadSchema),
});
export type MenuAuthority = z.infer<typeof menuAuthoritySchema>;
export type MenuAuthorityList = PageableList<MenuAuthority>;
export type MenuAuthorityPayloadData = z.infer<
typeof menuAuthorityPayloadSchema
>;
export type MenuAuthorityFormData = z.infer<typeof menuAuthorityFormSchema>;
export interface MenuAuthorityService {
getMenuAuthorityList(params: MenuAuthorityParams): Promise<MenuAuthorityList>;
saveMenuAuthority(data: MenuAuthorityPayloadData[]): Promise<void>;
}
@@ -0,0 +1,117 @@
import type { ColumnDef } from "@tanstack/react-table";
import type { UseFormReturn } from "react-hook-form";
import { Checkbox } from "@common/components/ui";
import type {
MenuAuthority,
MenuAuthorityFormData,
MenuAuthorityPayloadData,
} from "./menu-authority-interface";
export const createColumns = (
form: UseFormReturn<MenuAuthorityFormData>,
): ColumnDef<MenuAuthority>[] => {
const getCurrentRow = (i: number) => form.watch("menuAuthority")[i];
const handleCheckedChange =
(i: number, key: keyof MenuAuthorityPayloadData) => (checked: boolean) => {
if (getCurrentRow(i)?.mode === "R") {
form.setValue(`menuAuthority.${i}.mode`, "U");
}
form.setValue(`menuAuthority.${i}.${key}`, checked ? "Y" : "N");
};
return [
{
accessorKey: "groupNm",
header: "그룹명",
},
{
accessorKey: "mngAuthrtYn",
header: "관리권한",
cell: ({ row }) => {
return (
<Checkbox
checked={getCurrentRow(row.index)?.mngAuthrtYn === "Y"}
onCheckedChange={(checked) => {
if (checked) {
handleCheckedChange(
row.index,
"regAuthrtYn",
)(checked as boolean);
handleCheckedChange(
row.index,
"mdfcnAuthrtYn",
)(checked as boolean);
handleCheckedChange(
row.index,
"delAuthrtYn",
)(checked as boolean);
handleCheckedChange(
row.index,
"inqAuthrtYn",
)(checked as boolean);
}
handleCheckedChange(row.index, "mngAuthrtYn")(checked as boolean);
}}
/>
);
},
},
{
accessorKey: "regAuthrtYn",
header: "등록권한",
cell: ({ row }) => {
return (
<Checkbox
checked={getCurrentRow(row.index)?.regAuthrtYn === "Y"}
onCheckedChange={(checked) => {
if (checked) {
handleCheckedChange(
row.index,
"inqAuthrtYn",
)(checked as boolean);
}
handleCheckedChange(row.index, "regAuthrtYn")(checked as boolean);
}}
/>
);
},
},
{
accessorKey: "mdfcnAuthrtYn",
header: "수정권한 ",
cell: ({ row }) => {
return (
<Checkbox
checked={getCurrentRow(row.index)?.mdfcnAuthrtYn === "Y"}
onCheckedChange={handleCheckedChange(row.index, "mdfcnAuthrtYn")}
/>
);
},
},
{
accessorKey: "delAuthrtYn",
header: "삭제권한",
cell: ({ row }) => {
return (
<Checkbox
checked={getCurrentRow(row.index)?.delAuthrtYn === "Y"}
onCheckedChange={handleCheckedChange(row.index, "delAuthrtYn")}
/>
);
},
},
{
accessorKey: "inqAuthrtYn",
header: "조회권한",
cell: ({ row }) => {
return (
<Checkbox
checked={getCurrentRow(row.index)?.inqAuthrtYn === "Y"}
onCheckedChange={handleCheckedChange(row.index, "inqAuthrtYn")}
/>
);
},
},
];
};
@@ -0,0 +1,101 @@
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQuery } from "@tanstack/react-query";
import { getCoreRowModel, useReactTable } from "@tanstack/react-table";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import {
Button,
DataTable,
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@common/components/ui";
import { ENDPOINT } from "@/shared/config";
import { useAlertStore } from "@/shared/lib/use-alert-store";
import {
menuAuthorityFormSchema,
type MenuAuthorityFormData,
type MenuAuthorityPayloadData,
} from "../model/menu-authority-interface";
import { createColumns } from "../model/menu-authority-table-columns";
import { MenuAuthorityApi } from "../api/menu-authority-service";
type ManagementAuthorityDialogProps = {
menuCd?: number;
} & React.ComponentProps<typeof Dialog>;
function ManagementAuthorityDialog({
menuCd,
...props
}: ManagementAuthorityDialogProps) {
const { confirm } = useConfirm();
const { setMessage: alert } = useAlertStore((state) => state);
const { data: menuAuthorityList } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.MENU_AUTHRTS, menuCd],
queryFn: () => MenuAuthorityApi.getMenuAuthorityList({ menuCd }),
enabled: !!menuCd,
});
const { mutateAsync: saveMenuAuthority } = useMutation({
mutationFn: (data: MenuAuthorityPayloadData[]) =>
MenuAuthorityApi.saveMenuAuthority(data),
onSuccess: () => {
alert("저장되었습니다.");
},
});
const form = useForm<MenuAuthorityFormData>({
resolver: zodResolver(menuAuthorityFormSchema),
values: {
menuAuthority: menuAuthorityList?.content ?? [],
},
});
const table = useReactTable({
data: menuAuthorityList?.content ?? [],
columns: createColumns(form),
getCoreRowModel: getCoreRowModel(),
});
const handleSave = async () => {
if (await confirm("저장하시겠습니까?")) {
const data = form.getValues("menuAuthority");
const filteredData = data.filter((item) => item.mode !== "R");
await saveMenuAuthority(filteredData);
}
};
return (
<Dialog {...props}>
<DialogTrigger asChild>
<Button className="gap-3" disabled={!menuCd}>
<i className="diveicon di-personal-information" />
권한관리
</Button>
</DialogTrigger>
<DialogContent className="max-w-[60rem]" aria-describedby={undefined}>
<DialogHeader>
<DialogTitle>그룹별 메뉴 권한</DialogTitle>
</DialogHeader>
<DataTable table={table} />
<DialogFooter className="!justify-center">
<Button size="lg" onClick={handleSave}>
저장
</Button>
<DialogClose asChild>
<Button size="lg" color="white">
취소
</Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
export { ManagementAuthorityDialog };
@@ -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 };
+20
View File
@@ -0,0 +1,20 @@
import type { MenuItem } from "../model/menu-interface";
export const getCurrentMenu = (
menus: MenuItem[],
pathname: string,
): MenuItem | null => {
for (const menu of menus) {
if (
menu.urlPath !== "" &&
(menu.urlPath === pathname || pathname.startsWith(menu.urlPath))
)
return menu;
if (menu.children) {
const children = getCurrentMenu(menu.children, pathname);
if (children) return children;
}
}
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,
PostPayloadData,
} 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.POSTINGS}`,
{ params },
);
return response.data;
}
public async savePosting(data: PostPayloadData[]): Promise<Post[]> {
const response = await client.post<Post[]>(
`${ENDPOINT.CMS_SERVICE.POSTINGS}`,
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 PostPayloadData,
} 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 postPayloadSchema = postSchema
.extend({
mode: z.string(),
})
.omit({
siteNm: true,
pstgTypeNm: true,
pstgPrdSeNm: true,
});
export const postingFormSchema = z.object({
pstg: z.array(postPayloadSchema),
});
export type Post = z.infer<typeof postSchema>;
export type PostPayloadData = z.infer<typeof postPayloadSchema>;
export type PostingFormData = z.infer<typeof postingFormSchema>;
export interface PostService {
getPostingHistory: (params: PostingParams) => Promise<PageableList<Post>>;
savePosting: (data: PostPayloadData[]) => 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/@x/posting";
import { SiteApi, type Site } from "@/entities/site/@x/posting";
import type { PageableList } from "@/shared/model";
import { ENDPOINT } from "@/shared/config";
import { PostingApi } from "../api/posting-service";
import {
postingFormSchema,
type PostingFormData,
type PostingType,
type PostPayloadData,
} 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: savePosting } = useMutation({
mutationFn: (data: PostPayloadData[]) => PostingApi.savePosting(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 savePosting(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 };
+2
View File
@@ -0,0 +1,2 @@
export { SiteApi } from "../api/site-service";
export type { Site } from "../model/site-interface";
+7 -10
View File
@@ -4,13 +4,13 @@ import {
siteFormSchema,
type SiteService,
type SiteList,
type ISiteDetail,
type ISiteParams,
type SiteDetail,
type SiteParams,
type SiteFormData,
} from "../model/site-interface";
export class SiteApiService implements SiteService {
public async getSiteList(params: ISiteParams): Promise<SiteList> {
public async getSiteList(params?: SiteParams): Promise<SiteList> {
const response = await client.get<SiteList>(
`${ENDPOINT.CMS_SERVICE.SITES}`,
{ params },
@@ -18,8 +18,8 @@ export class SiteApiService implements SiteService {
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}`,
@@ -44,10 +44,7 @@ export class SiteApiService implements SiteService {
}
public async deleteSite(siteId: string): Promise<void> {
const response = await client.delete<void>(
`${ENDPOINT.CMS_SERVICE.SITES}/${siteId}`,
);
return response.data;
await client.delete(`${ENDPOINT.CMS_SERVICE.SITES}/${siteId}`);
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
export { SiteApi } from "./api/site-service";
export {
siteFormSchema,
type ISiteParams,
type ISite,
type SiteParams,
type Site,
type SiteFormData,
} from "./model/site-interface";
@@ -1,13 +1,13 @@
import { z } from "zod";
import type { IPageableParams, PageableList } from "@/shared/model";
import type { PageableParams, PageableList } from "@/shared/model";
export interface ISiteParams extends IPageableParams {
export interface SiteParams extends PageableParams {
siteNm?: string;
siteKndCd?: string;
useYn?: string;
}
export interface ISite {
export interface Site {
siteId: string;
siteNm: string;
siteKindCode: string;
@@ -19,7 +19,7 @@ export interface ISite {
dmnAddr: string;
}
export interface ISiteDetail extends SiteFormData {
export interface SiteDetail extends SiteFormData {
siteId: string;
siteKindNm: string;
basicSiteYn: string;
@@ -29,31 +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).nullable(),
siteExpln: z.string().max(1000).nullish(),
siteKndCd: z.string().max(10).nonempty(),
siteAddr: z.string().max(2000).nullable(),
faxNo: z.string().max(100).nullable(),
telNo: z.string().max(1000).nullable(),
lwndCn: z.string().max(2000).nullable(),
siteAddr: z.string().max(2000).nullish(),
faxNo: z.string().max(100).nullish(),
telNo: z.string().max(1000).nullish(),
lwndCn: z.string().max(2000).nullish(),
bscSiteYn: z.string(),
bkmkIcon: z.string().max(100).nullable(),
bkmkIcon: z.string().max(100).nullish(),
useYn: z.string(),
siteSkn: z.string().max(10).nullable(),
dmnAddr: z.string().nullable(),
siteSkn: z.string().max(10).nullish(),
dmnAddr: z.string().nullish(),
});
export type SiteFormData = z.infer<typeof siteFormSchema>;
export type SiteList = PageableList<ISite[]>;
export type SiteList = PageableList<Site>;
export interface SiteService {
getSiteList(params: ISiteParams): Promise<SiteList>;
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>;
}
@@ -4,10 +4,8 @@ import Image from "next/image";
import { images } from "@common/assets";
import { LoginApi } from "@/entities/auth";
import "./login.css";
import { useRouter } from "next/navigation";
function LoginPage() {
const router = useRouter();
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
@@ -16,7 +14,7 @@ function LoginPage() {
const password = formData.get("password") as string;
await LoginApi.login({ userId, password });
router.push("/site");
window.location.href = "/dashboard";
};
return (
@@ -0,0 +1,51 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type {
BannerFormData,
BannerInfo,
BannerList,
BannerParams,
BannerService,
} from "../model/banner-interface";
export class BannerApiService implements BannerService {
public async getBannerList(params: BannerParams): Promise<BannerList> {
const response = await client.get<BannerList>(
`${ENDPOINT.CMS_SERVICE.BANNERS}`,
{ params },
);
return response.data;
}
public async getBannerInfo(bnrSn: string): Promise<BannerInfo> {
const response = await client.get<BannerInfo>(
`${ENDPOINT.CMS_SERVICE.BANNERS}/${bnrSn}`,
);
return response.data;
}
public async createBanner(data: BannerFormData): Promise<void> {
const response = await client.post<void>(
ENDPOINT.CMS_SERVICE.BANNERS,
data,
);
return response.data;
}
public async updateBanner(
bnrSn: string,
data: BannerFormData,
): Promise<void> {
const response = await client.put<void>(
`${ENDPOINT.CMS_SERVICE.BANNERS}/${bnrSn}`,
data,
);
return response.data;
}
public async deleteBanner(bnrSn: string): Promise<void> {
await client.delete(`${ENDPOINT.CMS_SERVICE.BANNERS}/${bnrSn}`);
}
}
export const BannerApi = new BannerApiService();
+3
View File
@@ -0,0 +1,3 @@
export { CreatePage } from "./ui/create-page";
export { ModifyPage } from "./ui/modify-page";
export { BannerPage } from "./ui/banner-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,57 @@
import { z } from "zod";
import type { PageableList, PageableParams } from "@/shared/model";
export const BANNER_TYPE = {
BNRMAIN: "BNRMAIN",
BNRFTER: "BNRFTER",
} as const;
export type BannerType = (typeof BANNER_TYPE)[keyof typeof BANNER_TYPE];
export interface BannerParams extends PageableParams {
bnrTypeCd?: BannerType;
bnrTtl?: string;
useYn?: string;
}
export interface Banner {
bnrSn: number;
bnrTypeCd: BannerType;
bnrTypeNm: string;
bnrTtl: string;
lnkgUrlAddr: string;
useYn: string;
atflCd: string;
mdfcnDt: string;
mdfr: string;
mdfrNm: string;
}
export interface BannerInfo extends Omit<Banner, "mdfr"> {
bnrExpln: string;
newWndwYn: string;
atflCd: string;
regDt: string;
rgTrNm: string;
}
export const bannerFormSchema = z.object({
bnrTypeCd: z.string(),
bnrTtl: z.string(),
bnrExpln: z.string().nullish(),
lnkgUrlAddr: z.string().nullish(),
newWndwYn: z.string(),
atflCd: z.string().nullish(),
useYn: z.string(),
});
export type BannerFormData = z.infer<typeof bannerFormSchema>;
export type BannerList = PageableList<Banner>;
export interface BannerService {
getBannerList: (params: BannerParams) => Promise<BannerList>;
getBannerInfo: (bnrSn: string) => Promise<BannerInfo>;
createBanner: (data: BannerFormData) => Promise<void>;
updateBanner: (bnrSn: string, data: BannerFormData) => Promise<void>;
deleteBanner: (bnrSn: string) => Promise<void>;
}
@@ -0,0 +1,100 @@
"use client";
import dayjs from "dayjs";
import Image from "next/image";
import { useQuery } from "@tanstack/react-query";
import type { ColumnDef } from "@tanstack/react-table";
import { Checkbox, Skeleton } from "@common/components/ui";
import { AttachmentApi } from "@/entities/attachment";
import { ENDPOINT } from "@/shared/config";
import type { Banner } from "./banner-interface";
export const createColumns = (
imageRefs: React.MutableRefObject<Map<number, string>>,
): ColumnDef<Banner>[] => [
{
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"
/>
),
},
{
header: "배너 이미지",
cell: ({ row }) => (
<BannerImage
atflCd={row.original.atflCd}
bnrSn={row.original.bnrSn}
imageRefs={imageRefs}
/>
),
},
{
accessorKey: "bnrTtl",
header: "배너명",
},
{
accessorKey: "bnrTypeNm",
header: "배너구분",
},
{
accessorKey: "useYn",
header: "사용여부",
},
{
accessorKey: "mdfrNm",
header: "최종수정자",
},
{
accessorKey: "mdfcnDt",
header: "최종수정일",
cell: ({ row }) => {
const date = row.getValue("mdfcnDt") as string;
return date ? dayjs(date).format("YYYY-MM-DD") : "";
},
},
];
type BannerImageProps = {
atflCd: string;
bnrSn: number;
imageRefs: React.MutableRefObject<Map<number, string>>;
};
const BannerImage = ({ atflCd, bnrSn, imageRefs }: BannerImageProps) => {
const prevImage = imageRefs.current.get(bnrSn);
const { data: imageUrl, isLoading } = useQuery({
queryKey: [ENDPOINT.ATTACH_SERVICE.IMAGES, atflCd],
queryFn: () => AttachmentApi.getImageUrlByAtflCd(atflCd),
select: (url) => {
if (url) imageRefs.current.set(bnrSn, url);
return url;
},
enabled: !prevImage && !!atflCd,
});
if (isLoading) return <Skeleton className="h-[4rem] w-[16rem]" />;
if (!imageUrl) return null;
return (
<div className="relative flex h-[4rem] w-[16rem] items-center justify-center">
<Image src={imageUrl} className="object-contain" fill alt="배너 이미지" />
</div>
);
};
@@ -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")})`;
},
},
];
+296
View File
@@ -0,0 +1,296 @@
"use client";
import Image from "next/image";
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import type { UseFormReturn } from "react-hook-form";
import type { HttpResponse, Upload } from "tus-js-client";
import {
FileUploader,
Input,
Label,
Progress,
RadioGroup,
RadioGroupItem,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Textarea,
} from "@common/components";
import { FormWrapper } from "@/widgets/form-wrapper";
import { CodeSelect } from "@/entities/code";
import { AttachmentApi } from "@/entities/attachment";
import { ENDPOINT } from "@/shared/config";
import { setCookie } from "@/shared/lib/cookie";
import { FormControl, FormField, FormItem } from "@/shared/ui/form";
import type { BannerFormData } from "../model/banner-interface";
import { handleUpload } from "../lib/utils";
type BannerFormProps = {
form: UseFormReturn<BannerFormData>;
bnrSn?: number;
handleSave: (data: BannerFormData) => Promise<void>;
handleDelete?: () => Promise<void>;
};
function BannerForm({ form, bnrSn, ...props }: BannerFormProps) {
const atflCd = form.watch("atflCd");
const [imageUrl, setImageUrl] = useState("");
const [upload, setUpload] = useState<Upload | null>(null);
const [progress, setProgress] = useState(0);
const { data: attachmentData } = useQuery({
queryKey: [ENDPOINT.ATTACH_SERVICE.ATTACHMENTS, atflCd],
queryFn: () => AttachmentApi.getAttachmentsInfo(atflCd!),
select: (data) => data?.[data.length - 1],
enabled: !!atflCd,
});
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) setImageUrl(await AttachmentApi.getImageUrl(atflId));
if (attachmentData)
await AttachmentApi.deleteAttachmentByAtflCd(attachmentData.atflCd);
};
useEffect(() => {
if (!attachmentData) return;
(async () => {
setImageUrl(await AttachmentApi.getImageUrl(attachmentData.atflId));
})();
}, [attachmentData]);
return (
<FormWrapper form={form} isModifyMode={!!bnrSn} {...props}>
<div className="card">
<Table variant="secondary">
<colgroup>
<col width="15%" />
<col width="85%" />
</colgroup>
<TableBody>
<TableRow>
<TableHead>배너명</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="bnrTtl"
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="bnrTypeCd"
render={({ field }) => (
<FormItem>
<FormControl>
<CodeSelect
{...field}
upCd="BNRTYPE"
onValueChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<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;
setCookie("atfl-cd-key", "");
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">
<div className="relative h-full w-full">
{imageUrl && (
<Image
src={imageUrl}
className="object-contain"
fill
alt="업로드된 이미지"
/>
)}
</div>
<p className="absolute bottom-3 left-0 z-10 p-2 text-base leading-none">
{(upload?.file as File)?.name}
</p>
<Progress
value={progress}
className="absolute bottom-0 left-0 z-10"
/>
</div>
</Label>
<div className="mb-2 text-lg font-medium text-label">
<ul className="ml-10 list-disc">
<li>
이미지 파일(jpg, jpeg, png, gif)만 업로드
가능합니다.
</li>
</ul>
</div>
</>
}
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>링크 URL</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="newWndwYn"
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
{...field}
name="newWndwYn"
onValueChange={field.onChange}
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="N" id="newWndwN" />
<Label htmlFor="newWndwN">현재창</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="Y" id="newWndwY" />
<Label htmlFor="newWndwY">새창</Label>
</div>
</RadioGroup>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>배너 설명</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="bnrExpln"
render={({ field }) => (
<FormItem>
<FormControl>
<Textarea
{...field}
value={field.value ?? ""}
className="!text-[1.3rem] !leading-6"
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>
</FormWrapper>
);
}
export { BannerForm };
+144
View File
@@ -0,0 +1,144 @@
"use client";
import { useEffect, useState, useRef } from "react";
import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import {
getCoreRowModel,
useReactTable,
type PaginationState,
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 { BannerApi } from "../api/banner-service";
import { createColumns } from "../model/banner-table-columns";
import { type Banner, type BannerParams } from "../model/banner-interface";
import { PreviewBannerDialog } from "./preview-banner-dialog";
type PostingTarget = {
pstgTrgtNm: string;
pstgTrgtNo: number;
};
function BannerPage() {
const router = useRouter();
const imageRefs = useRef<Map<number, string>>(new Map());
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const [postingTargets, setPostingTargets] = useState<PostingTarget[]>([]);
const [bannerQuery, setBannerQuery] = useState<BannerParams>({ bnrTtl: "" });
const [pagination, setPagination] = useState<PaginationState>({
pageIndex: 0,
pageSize: 5,
});
const { data: bannerList, refetch } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.BANNERS],
queryFn: () =>
BannerApi.getBannerList({
...bannerQuery,
page: pagination.pageIndex,
size: pagination.pageSize,
}),
enabled: false,
});
const table = useReactTable({
data: bannerList?.content ?? [],
columns: createColumns(imageRefs),
state: {
pagination,
rowSelection,
},
rowCount: bannerList?.totalElements ?? 0,
manualPagination: true,
enableMultiRowSelection: true,
getCoreRowModel: getCoreRowModel(),
onPaginationChange: setPagination,
onRowSelectionChange: setRowSelection,
});
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
refetch();
};
const handleRowClick = (row: Banner) => {
router.push(`/banner/register/${row.bnrSn}`);
};
const getSelectedBannerImages = () => {
const selectedImages: string[] = [];
table.getFilteredSelectedRowModel().rows.forEach((row) => {
const imageUrl = imageRefs.current.get(row.original.bnrSn);
if (imageUrl) selectedImages.push(imageUrl);
});
return selectedImages;
};
useEffect(() => {
const postingTargets = table
.getFilteredSelectedRowModel()
.rows.map((row) => ({
pstgTrgtNm: row.original.bnrTtl,
pstgTrgtNo: row.original.bnrSn,
}));
if (!postingTargets.length) {
setPostingTargets([]);
return;
}
setPostingTargets(postingTargets);
}, [rowSelection]);
useEffect(() => {
refetch();
}, [pagination]);
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={bannerQuery.bnrTtl}
onChange={(e) =>
setBannerQuery({ ...bannerQuery, bnrTtl: 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">
<PreviewBannerDialog images={getSelectedBannerImages()} />
<PostingDialog
postingType={POSTING_TYPE.BANNER}
postingTargets={postingTargets}
/>
<Button onClick={() => router.push("/banner/register")}>
등록
</Button>
</div>
</div>
</div>
<div className="card !m-[1.2rem] h-full overflow-auto !p-0">
<DataTable table={table} onRowClick={handleRowClick} viewPagination />
</div>
</div>
</div>
);
}
export { BannerPage };
@@ -0,0 +1,46 @@
"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 {
bannerFormSchema,
type BannerFormData,
} from "../model/banner-interface";
import { BannerApi } from "../api/banner-service";
import { BannerForm } from "./banner-form";
function CreatePage() {
const router = useRouter();
const { setMessage: alert } = useAlertStore((state) => state);
const { mutateAsync: createBanner } = useMutation({
mutationFn: (data: BannerFormData) => BannerApi.createBanner(data),
onSuccess: () => {
alert("등록되었습니다.", router.back);
},
});
const form = useForm<BannerFormData>({
resolver: zodResolver(bannerFormSchema),
defaultValues: {
newWndwYn: "N",
useYn: "Y",
},
});
console.log(form.formState.errors);
return (
<div className="card card-border !mt-6">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">배너 등록</h3>
</div>
<BannerForm form={form} handleSave={createBanner} />
</div>
);
}
export { CreatePage };
+132
View File
@@ -0,0 +1,132 @@
"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 PostPayloadData } from "@/entities/posting";
import { useAlertStore } from "@/shared/lib/use-alert-store";
import { ENDPOINT } from "@/shared/config";
import {
bannerFormSchema,
type BannerFormData,
} from "../model/banner-interface";
import { columns } from "../model/posting-table-columns";
import { BannerApi } from "../api/banner-service";
import { BannerForm } from "./banner-form";
function ModifyPage({ sequential }: { sequential: string }) {
const router = useRouter();
const { confirm } = useConfirm();
const queryClient = useQueryClient();
const { setMessage: alert } = useAlertStore((state) => state);
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const { data: bannerDetail } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.BANNERS, sequential],
queryFn: () => BannerApi.getBannerInfo(sequential),
});
const { data: postHistory } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.POSTINGS, sequential],
queryFn: () =>
PostingApi.getPostingHistory({ pstgTrgtNo: Number(sequential) }),
});
const { mutateAsync: updateBanner } = useMutation({
mutationFn: (data: BannerFormData) =>
BannerApi.updateBanner(sequential, data),
onSuccess: () => {
alert("수정되었습니다.");
},
});
const { mutateAsync: deleteBanner } = useMutation({
mutationFn: () => BannerApi.deleteBanner(sequential),
onSuccess: () => {
alert("삭제되었습니다.", router.back);
},
});
const { mutateAsync: savePosting } = useMutation({
mutationFn: (data: PostPayloadData[]) => PostingApi.savePosting(data),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: [ENDPOINT.CMS_SERVICE.POSTINGS, sequential],
});
alert("삭제되었습니다.");
},
});
const form = useForm<BannerFormData>({
resolver: zodResolver(bannerFormSchema),
values: bannerDetail,
});
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",
}));
if (await confirm("삭제하시겠습니까?")) {
savePosting(data);
}
};
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>
<BannerForm
form={form}
bnrSn={Number(sequential)}
handleSave={updateBanner}
handleDelete={deleteBanner}
/>
</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>
);
}
export { ModifyPage };
@@ -0,0 +1,60 @@
"use client";
import Image from "next/image";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
Button,
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
} from "@common/components";
type PreviewBannerDialogProps = {
images: string[];
};
function PreviewBannerDialog({ images }: PreviewBannerDialogProps) {
return (
<Dialog>
<DialogTrigger asChild>
<Button color="white" disabled={!images.length}>
<i className="diveicon di-display" />
미리보기
</Button>
</DialogTrigger>
<DialogContent className="max-w-[80rem]" aria-describedby={undefined}>
<DialogHeader>
<DialogTitle>배너 이미지 미리보기</DialogTitle>
</DialogHeader>
<div className="mt-4 px-12">
<Carousel>
<CarouselContent>
{images.map((image, i) => (
<CarouselItem key={`banner-${i}`} className="basis-1/3">
<div className="relative flex aspect-video items-center justify-center">
<Image
src={image}
className="object-contain"
fill
alt={`배너 이미지 ${i + 1}`}
/>
</div>
</CarouselItem>
))}
</CarouselContent>
<CarouselPrevious className="!bg-accent text-accent-foreground" />
<CarouselNext className="!bg-accent text-accent-foreground" />
</Carousel>
</div>
</DialogContent>
</Dialog>
);
}
export { PreviewBannerDialog };
+1
View File
@@ -0,0 +1 @@
export { ContentsPage } from "./ui/contents-page";
@@ -0,0 +1,47 @@
import dayjs from "dayjs";
import { type ColumnDef } from "@tanstack/react-table";
import type { Contents } from "@/entities/contents";
export const columns: ColumnDef<Contents>[] = [
{
id: "no",
header: "NO",
cell: ({ row }) => row.index + 1,
},
{
accessorKey: "contsTtl",
header: "콘텐츠명",
},
{
accessorKey: "aprvContsVer",
header: "승인여부",
},
{
accessorKey: "rgTrNm",
header: "승인자",
},
{
accessorKey: "regDt",
header: "승인일자",
cell: ({ row }) => {
const date = dayjs(row.original.regDt);
return date.format("YYYY-MM-DD");
},
},
{
accessorKey: "useYn",
header: "사용여부",
},
{
accessorKey: "mdfrNm",
header: "최종수정자",
},
{
accessorKey: "mdfcnDt",
header: "최종수정일",
cell: ({ row }) => {
const date = dayjs(row.original.mdfcnDt);
return date.format("YYYY-MM-DD");
},
},
];
@@ -0,0 +1,100 @@
"use client";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import {
getCoreRowModel,
useReactTable,
type PaginationState,
} from "@tanstack/react-table";
import { Button, DataTable, Input, Label } from "@common/components";
import {
ContentsApi,
type Contents,
type ContentsParams,
} from "@/entities/contents";
import { ENDPOINT } from "@/shared/config";
import { columns } from "../model/table-columns";
function ContentsPage() {
const router = useRouter();
const [contentsQuery, setContentsQuery] = useState<ContentsParams>({
contsTtl: "",
});
const [pagination, setPagination] = useState<PaginationState>({
pageIndex: 0,
pageSize: 5,
});
const { data: contentsList, refetch } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.CONTENTS],
queryFn: () =>
ContentsApi.getContentsList({
...contentsQuery,
page: pagination.pageIndex,
size: pagination.pageSize,
}),
placeholderData: keepPreviousData,
enabled: false,
});
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
refetch();
};
const handleRowClick = (row: Contents) => {
router.push(`/contents/register/${row.contsSn}`);
};
const table = useReactTable({
data: contentsList?.content ?? [],
columns,
rowCount: contentsList?.totalElements ?? 0,
state: {
pagination,
},
onPaginationChange: setPagination,
getCoreRowModel: getCoreRowModel(),
manualPagination: true,
});
useEffect(() => {
refetch();
}, [pagination]);
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={contentsQuery.contsTtl}
onChange={(e) => setContentsQuery({ contsTtl: 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("/contents/register")}>
등록
</Button>
</div>
<div className="card !m-[1.2rem] h-[29.2rem] overflow-auto !p-0">
<DataTable table={table} onRowClick={handleRowClick} viewPagination />
</div>
</div>
</div>
);
}
export { ContentsPage };
+1
View File
@@ -0,0 +1 @@
export { DashboardPage } from "./ui/dashboard-page";
@@ -0,0 +1,5 @@
function DashboardPage() {
return <></>;
}
export { DashboardPage };
+1
View File
@@ -0,0 +1 @@
export { FilePage } from "./ui/file-page";
@@ -0,0 +1,62 @@
"use client";
import dayjs from "dayjs";
import { type ColumnDef } from "@tanstack/react-table";
import { Button } from "@common/components";
import type { Attachment } from "@/entities/attachment/model/attachment-interface";
export const createColumns = (
handleDeleteAttachment: (atflId: string) => void,
): ColumnDef<Attachment>[] => [
{
id: "no",
header: "NO",
cell: (info) => info.row.index + 1,
},
{
accessorKey: "atflId",
header: "파일ID",
},
{
accessorKey: "atflSn",
header: "파일순번",
},
{
accessorKey: "orgnlFileNm",
header: "파일명",
},
{
accessorKey: "atflFlieSz",
header: "파일크기",
},
{
accessorKey: "dwnldNocs",
header: "다운로드수",
},
{
accessorKey: "regDt",
header: "등록일시",
cell: ({ row }) => {
const date = row.getValue("regDt") as string;
return date ? dayjs(date).format("YYYY-MM-DD") : "";
},
},
{
accessorKey: "delYn",
header: "삭제여부",
},
{
id: "delete",
header: "삭제",
cell: ({ row }) => (
<Button
size="sm"
color="red"
onClick={() => handleDeleteAttachment(row.original.atflId)}
>
삭제
</Button>
),
},
];
+119
View File
@@ -0,0 +1,119 @@
"use client";
import { useEffect, useState } from "react";
import { keepPreviousData, useMutation, useQuery } from "@tanstack/react-query";
import {
getCoreRowModel,
useReactTable,
type PaginationState,
} from "@tanstack/react-table";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { Button, DataTable, Input, Label } from "@common/components";
import type { AttachmentParams } from "@/entities/attachment/model/attachment-interface";
import { AttachmentApi } from "@/entities/attachment/api/attachment-service";
import { useAlertStore } from "@/shared/lib/use-alert-store";
import { ENDPOINT } from "@/shared/config";
import { createColumns } from "../model/table-columns";
function FilePage() {
const { confirm } = useConfirm();
const { setMessage: alert } = useAlertStore((state) => state);
const [attachmentQuery, setAttachmentQuery] = useState<AttachmentParams>({
keyword: "",
});
const [pagination, setPagination] = useState<PaginationState>({
pageIndex: 0,
pageSize: 10,
});
const { data: attachmentsList, refetch } = useQuery({
queryKey: [ENDPOINT.ATTACH_SERVICE.ATTACHMENTS],
queryFn: () =>
AttachmentApi.getAttachmentsList({
...attachmentQuery,
page: pagination.pageIndex,
size: pagination.pageSize,
}),
placeholderData: keepPreviousData,
enabled: false,
});
const { mutate: deleteAttachment } = useMutation({
mutationFn: (atflId: string) => AttachmentApi.deleteAttachment(atflId),
onSuccess: () => {
refetch();
alert("삭제되었습니다.");
},
});
const handleDeleteAttachment = async (atflId: string) => {
if (await confirm("삭제하시겠습니까?")) {
deleteAttachment(atflId);
}
};
const table = useReactTable({
data: attachmentsList?.content ?? [],
columns: createColumns(handleDeleteAttachment),
rowCount: attachmentsList?.totalElements ?? 0,
state: {
pagination,
},
onPaginationChange: setPagination,
getCoreRowModel: getCoreRowModel(),
manualPagination: true,
});
const handleAttachmentQueryChange =
(key: keyof AttachmentParams) => (value: string) => {
setAttachmentQuery({ ...attachmentQuery, [key]: value });
};
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
refetch();
};
useEffect(() => {
refetch();
}, [pagination]);
return (
<div className="card card-border !mt-6">
<div className="card card-border">
<form onSubmit={handleSubmit} className="flex gap-2 p-2">
<div className="flex space-x-6">
<div className="flex items-center gap-2">
<Label htmlFor="keyword" className="text-label">
파일명
</Label>
<Input
id="keyword"
className="h-[3.2rem] w-[24rem] rounded-sm !text-[1.3rem]"
value={attachmentQuery.keyword || ""}
onChange={(e) =>
handleAttachmentQueryChange("keyword")(e.target.value)
}
placeholder="파일명을 입력하세요"
/>
</div>
</div>
<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>
</div>
<div className="card !m-[1.2rem] overflow-auto !p-0">
<DataTable table={table} viewPagination />
</div>
</div>
</div>
);
}
export { FilePage };
@@ -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";
@@ -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: ImageType;
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,73 @@
"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");
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: "사용여부",
},
{
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 };
+307
View File
@@ -0,0 +1,307 @@
"use client";
import Image from "next/image";
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import type { UseFormReturn } from "react-hook-form";
import type { HttpResponse } from "tus-js-client";
import {
FileUploader,
Input,
Label,
Progress,
RadioGroup,
RadioGroupItem,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
} from "@common/components";
import { FormWrapper } from "@/widgets/form-wrapper";
import { CodeSelect } from "@/entities/code";
import { AttachmentApi } from "@/entities/attachment";
import { ENDPOINT } from "@/shared/config";
import { useTus } from "@/shared/lib/use-tus";
import { FormControl, FormField, FormItem } from "@/shared/ui/form";
import { useAttachmentStore } from "@/shared/lib/use-attachment-store";
import type { ImageFormData } from "../model/image-interface";
type ImageFormProps = {
form: UseFormReturn<ImageFormData>;
imgSn?: number;
handleSave: (data: ImageFormData) => Promise<void>;
handleDelete?: () => Promise<void>;
};
function ImageForm({ form, imgSn, ...props }: ImageFormProps) {
const atflYn = form.watch("atflYn");
const atflCd = form.watch("atflCd");
const {
file: uploadFile,
response: uploadResponse,
progress,
setFile,
} = useTus();
const { setAttachmentFileCode } = useAttachmentStore((state) => state);
const [imageUrl, setImageUrl] = useState("");
const { data: attachmentData } = useQuery({
queryKey: [ENDPOINT.ATTACH_SERVICE.ATTACHMENTS, atflCd],
queryFn: () => AttachmentApi.getAttachmentsInfo(atflCd!),
select: (data) => data?.[data.length - 1],
enabled: !!atflCd,
});
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) setImageUrl(await AttachmentApi.getImageUrl(atflId));
if (attachmentData)
await AttachmentApi.deleteAttachmentByAtflCd(attachmentData.atflCd);
};
useEffect(() => {
if (!uploadResponse) return;
handleUploadResponse(uploadResponse);
}, [uploadResponse]);
useEffect(() => {
(async () => {
setImageUrl(
await AttachmentApi.getImageUrlByAtflCd(attachmentData?.atflCd ?? ""),
);
})();
}, [attachmentData]);
return (
<FormWrapper form={form} isModifyMode={!!imgSn} {...props}>
<div className="card">
<Table variant="secondary">
<colgroup>
<col width="15%" />
<col width="85%" />
</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}
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;
setAttachmentFileCode("");
setFile(files[0] ?? null);
}}
customPreview={
<>
<Label htmlFor="atflCd">
<div className="relative h-[27rem] w-[48rem] overflow-hidden rounded-sm border border-border bg-accent">
<div className="relative h-full w-full">
{imageUrl && (
<Image
src={imageUrl}
className="object-contain"
fill
alt="업로드된 이미지"
/>
)}
</div>
<p className="absolute bottom-3 left-0 z-10 p-2 text-base leading-none">
{uploadFile?.name}
</p>
<Progress
value={progress}
className="absolute bottom-0 left-0 z-10"
/>
</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>
</FormWrapper>
);
}
export { ImageForm };
+132
View File
@@ -0,0 +1,132 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import {
getCoreRowModel,
useReactTable,
type PaginationState,
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 [pagination, setPagination] = useState<PaginationState>({
pageIndex: 0,
pageSize: 5,
});
const { data: imageList, refetch } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.IMAGES],
queryFn: () =>
ImageApi.getImageList({
...imageQuery,
page: pagination.pageIndex,
size: pagination.pageSize,
}),
enabled: false,
});
const table = useReactTable({
data: imageList?.content ?? [],
columns,
state: {
pagination,
rowSelection,
},
rowCount: imageList?.totalElements ?? 0,
manualPagination: true,
enableMultiRowSelection: true,
getCoreRowModel: getCoreRowModel(),
onPaginationChange: setPagination,
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();
}, [pagination]);
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-full overflow-auto !p-0">
<DataTable table={table} onRowClick={handleRowClick} viewPagination />
</div>
</div>
</div>
);
}
export { ImagePage };
+128
View File
@@ -0,0 +1,128 @@
"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 PostPayloadData } from "@/entities/posting";
import { useAlertStore } from "@/shared/lib/use-alert-store";
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({ sequential }: { sequential: string }) {
const router = useRouter();
const { confirm } = useConfirm();
const queryClient = useQueryClient();
const { setMessage: alert } = useAlertStore((state) => state);
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const { data: imageDetail } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.IMAGES, sequential],
queryFn: () => ImageApi.getImageInfo(sequential),
});
const { data: postHistory } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.POSTINGS, sequential],
queryFn: () =>
PostingApi.getPostingHistory({ pstgTrgtNo: Number(sequential) }),
});
const { mutateAsync: updateImage } = useMutation({
mutationFn: (data: ImageFormData) => ImageApi.updateImage(sequential, data),
onSuccess: () => {
alert("수정되었습니다.");
},
});
const { mutateAsync: deleteImage } = useMutation({
mutationFn: () => ImageApi.deleteImage(sequential),
onSuccess: () => {
alert("삭제되었습니다.", router.back);
},
});
const { mutateAsync: savePosting } = useMutation({
mutationFn: (data: PostPayloadData[]) => PostingApi.savePosting(data),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: [ENDPOINT.CMS_SERVICE.POSTINGS, sequential],
});
alert("삭제되었습니다.");
},
});
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",
}));
if (await confirm("삭제하시겠습니까?")) {
await savePosting(data);
}
};
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={Number(sequential)}
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>
);
}
export { ModifyPage };
+41 -5
View File
@@ -1,16 +1,52 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type { Menu, MenuService, TreeMenu } from "../model/menu-interface";
import type {
Menu,
MenuFormData,
MenuService,
TreeMenu,
TreeNode,
} from "../model/menu-interface";
export class MenuApiService implements MenuService {
public async getTreeMenuList(siteId: string): Promise<Menu[]> {
const response = await client.get<Menu[]>(
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> {
await client.delete(`${ENDPOINT.CMS_SERVICE.MENUS}/${menuCd}`);
}
public async getTreeMenuList(siteId: string): Promise<TreeMenu[]> {
const response = await client.get<TreeMenu[]>(
`${ENDPOINT.CMS_SERVICE.MENUS}/${siteId}/tree`,
);
return response.data;
}
public async modifyTreeMenu(siteId: string, data: TreeMenu[]): Promise<void> {
public async updateTreeMenu(siteId: string, data: TreeNode[]): Promise<void> {
const response = await client.put<void>(
`${ENDPOINT.CMS_SERVICE.MENUS}/${siteId}/tree`,
data,
@@ -18,7 +54,7 @@ export class MenuApiService implements MenuService {
return response.data;
}
public async modifyMenuName(menuCd: number, name: string): Promise<void> {
public async updateMenuName(menuCd: number, name: string): Promise<void> {
const response = await client.put<void>(
`${ENDPOINT.CMS_SERVICE.MENUS}/${menuCd}/${name}`,
);
@@ -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_ORGANIZATION}/treeuser`,
);
return response.data;
}
}
export const OrganizationApi = new OrganizationApiService();
+88 -21
View File
@@ -1,9 +1,12 @@
import type { DropOptions, NodeModel } from "@minoru/react-dnd-treeview";
import type { Menu, TreeMenu } from "../model/menu-interface";
import type { TreeMenu, TreeNode } from "../model/menu-interface";
import type { Organization, User } from "../model/organization-interface";
export const generateTreeData = (data: Menu[]): NodeModel<Menu>[] => {
return data.reduce<NodeModel<Menu>[]>((acc, menu) => {
const node: NodeModel<Menu> = {
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,
@@ -14,31 +17,37 @@ export const generateTreeData = (data: Menu[]): NodeModel<Menu>[] => {
acc.push(node);
if (menu.children?.length) {
acc.push(...generateTreeData(menu.children));
acc.push(...generateMenuTreeData(menu.children));
}
return acc;
}, []);
};
export const generateNewTreeData = (
treeData: NodeModel<Menu>[],
options: DropOptions<Menu>,
): TreeMenu | null => {
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 =
siblings.findIndex((sibling) => sibling.id === dragSourceId) + 1;
dragSourceIndex === 0 ? 1 : (prevSibling?.data?.sortSeq ?? 0) + 1;
const childNodes = treeData.filter(
(node) => node.parent === dragSourceId && node.data,
);
const baseNode = (node: NodeModel<Menu>): TreeMenu => {
const baseNode = (node: NodeModel<TreeMenu>): TreeNode => {
if (!node.data) return {};
return {
menuCd: node.data?.menuCd,
@@ -47,20 +56,20 @@ export const generateNewTreeData = (
};
};
const treeMenu: TreeMenu = {
const treeNode: TreeNode = {
...baseNode(dragSource),
parentId: dropTargetId === 0 ? null : (dropTargetId as number),
sortSeq: newSortSeq,
levelNo: (dropTarget?.data?.levelNo ?? 0) + 1,
};
const result: TreeMenu = {
...treeMenu,
const result: TreeNode = {
...treeNode,
children: childNodes.map((child) => ({
...baseNode(child),
parentId: child.data?.parentId === 0 ? null : (dropTargetId as number),
sortSeq: child.data?.sortSeq,
levelNo: (treeMenu?.levelNo ?? 0) + 1,
levelNo: (treeNode?.levelNo ?? 0) + 1,
})),
};
@@ -68,21 +77,22 @@ export const generateNewTreeData = (
};
export const handleSelectNode =
(callback: (node: NodeModel<Menu>) => void) => (node: NodeModel<Menu>) => {
(callback: (node: NodeModel<TreeMenu>) => void) =>
(node: NodeModel<TreeMenu>) => {
callback(node);
};
export const handleDropNode =
(callback: (newTree: TreeMenu) => void) =>
(newTree: NodeModel<Menu>[], options: DropOptions<Menu>) => {
const newTreeData = generateNewTreeData(newTree, options);
(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<Menu>[]) =>
(callback: (newTree: NodeModel<Menu>[]) => void) =>
(treeData: NodeModel<TreeMenu>[]) =>
(callback: (newTree: NodeModel<TreeMenu>[]) => void) =>
(id: NodeModel["id"], value: string) => {
const newTree = treeData.map((node) => {
if (node.id === id) {
@@ -96,3 +106,60 @@ export const handleNodeTextChange =
});
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,40 @@
import type { ColumnDef } from "@tanstack/react-table";
import { Checkbox } from "@common/components/ui";
import type { BoardPopup } from "@/entities/board";
export const columns: ColumnDef<BoardPopup>[] = [
{
id: "no",
header: "NO",
cell: ({ row }) => row.index + 1,
},
{
accessorKey: "bbsNm",
header: "게시판명",
},
{
accessorKey: "bbsTypeNm",
header: "게시판유형",
},
{
accessorKey: "regDt",
header: "최초생성일",
},
{
accessorKey: "pstCnt",
header: "게시물건수",
},
{
id: "select",
header: "선택",
cell: ({ row }) => {
return (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={row.getToggleSelectedHandler()}
className="mx-4 flex justify-center"
/>
);
},
},
];
@@ -0,0 +1,54 @@
import dayjs from "dayjs";
import type { ColumnDef } from "@tanstack/react-table";
import { Checkbox } from "@common/components/ui";
import type { Contents } from "@/entities/contents";
export const columns: ColumnDef<Contents>[] = [
{
id: "no",
header: "NO",
cell: ({ row }) => row.index + 1,
},
{
id: "contsTtl",
header: "콘텐츠명",
cell: ({ row }) => row.original.contsTtl,
},
{
accessorKey: "rgTrNm",
header: "승인자",
},
{
accessorKey: "regDt",
header: "승인일자",
cell: ({ row }) => {
const date = dayjs(row.original.regDt);
return date.format("YYYY-MM-DD");
},
},
{
accessorKey: "mdfrNm",
header: "최종수정자",
},
{
accessorKey: "mdfcnDt",
header: "최종수정일",
cell: ({ row }) => {
const date = dayjs(row.original.mdfcnDt);
return date.format("YYYY-MM-DD");
},
},
{
id: "select",
header: "선택",
cell: ({ row }) => {
return (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={row.getToggleSelectedHandler()}
className="mx-4 flex justify-center"
/>
);
},
},
];
+32 -16
View File
@@ -11,28 +11,28 @@ export const MENU_TYPE = {
export type MenuType = (typeof MENU_TYPE)[keyof typeof MENU_TYPE];
export interface TreeMenu {
export interface TreeNode {
menuCd?: number;
name?: string;
sortSeq?: number;
parentId?: number | null;
levelNo?: number;
icon?: string;
children?: TreeMenu[];
children?: TreeNode[];
}
export interface Menu extends Omit<TreeMenu, "name" | "icon" | "children"> {
export interface TreeMenu extends Omit<TreeNode, "name" | "icon" | "children"> {
menuKornNm: string;
menuEngNm: string;
iconNm: string;
children: Menu[];
urlPath: string;
menuEngNm?: string;
iconNm?: string;
children?: TreeMenu[];
urlPath?: string;
menuLnkgTypeCd: string;
menuLnkgSn: number;
qrcd: string;
menuLnkgSn?: number;
qrcd?: string;
useYn: string;
otptYn: string;
requiredUrlPath: boolean;
requiredUrlPath?: boolean;
}
export const menuFormSchema = z.object({
@@ -53,18 +53,34 @@ export const menuFormSchema = z.object({
MENU_TYPE.BOTTOM,
]),
menuLnkgSn: z.number().nullish(),
otptYn: z.enum(["Y", "N"]).default("Y").nullish(),
otptYn: z.string().default("Y"),
prntMenuCd: z.number().nullish(),
sortSeq: z.number(),
evlUseYn: z.enum(["Y", "N"]).nullish(),
evlUseYn: z.string().default("Y"),
qrcd: z.string().nullish(),
useYn: z.enum(["Y", "N"]).default("Y").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 {
getTreeMenuList: (siteId: string) => Promise<Menu[]>;
modifyTreeMenu: (siteId: string, data: TreeMenu[]) => Promise<void>;
modifyMenuName: (menuCd: number, name: string) => Promise<void>;
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[]>;
}
@@ -1,130 +0,0 @@
import { type UseFormReturn } from "react-hook-form";
import {
IconFinder,
Input,
Label,
RadioGroup,
RadioGroupItem,
TableCell,
TableHead,
TableRow,
} from "@common/components";
import {
FormItem,
FormControl,
FormField,
FormMessage,
} from "@/shared/ui/form";
import type { MenuFormData } from "../model/menu-interface";
export function BaseBottomMenuForm({
form,
}: {
form: UseFormReturn<MenuFormData>;
}) {
const handleIconClick = (icon: string) => {
form.setValue("iconNm", icon);
};
return (
<>
<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>
<FormMessage />
</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")}
</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>
<FormMessage />
</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>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
</>
);
}
+20 -26
View File
@@ -10,35 +10,32 @@ import {
TableHead,
TableRow,
} from "@common/components";
import {
FormItem,
FormControl,
FormField,
FormMessage,
} from "@/shared/ui/form";
import { FormItem, FormControl, FormField } from "@/shared/ui/form";
import { MENU_TYPE, type MenuFormData } from "../model/menu-interface";
interface BaseMenuFormProps {
form: UseFormReturn<MenuFormData>;
menuId?: number;
menuCd?: number;
}
export function BaseMenuForm({ form, menuId }: BaseMenuFormProps) {
function BaseMenuForm({ form, menuCd }: BaseMenuFormProps) {
return (
<Table variant="secondary">
<colgroup>
<col width="20%" />
<col width="80%" />
<col width="15%" />
<col width="85%" />
</colgroup>
<TableBody>
<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">
{menuId}
</div>
</TableCell>
</TableRow>
{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">
@@ -50,11 +47,11 @@ export function BaseMenuForm({ form, menuId }: BaseMenuFormProps) {
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="메뉴명을 입력하십시오."
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
@@ -76,7 +73,6 @@ export function BaseMenuForm({ form, menuId }: BaseMenuFormProps) {
placeholder="메뉴 영문명을 입력하십시오."
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
@@ -101,11 +97,8 @@ export function BaseMenuForm({ form, menuId }: BaseMenuFormProps) {
key={key}
className="flex items-center space-x-2"
>
<RadioGroupItem
value={value}
id={`menuType${key}`}
/>
<Label htmlFor={`menuType${key}`}>
<RadioGroupItem value={value} id={key} />
<Label htmlFor={key}>
{key === "EMPTY" && "빈메뉴"}
{key === "CONTENTS" && "콘텐츠"}
{key === "BOARD" && "게시판"}
@@ -118,7 +111,6 @@ export function BaseMenuForm({ form, menuId }: BaseMenuFormProps) {
</div>
</RadioGroup>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
@@ -128,3 +120,5 @@ export function BaseMenuForm({ form, menuId }: BaseMenuFormProps) {
</Table>
);
}
export { BaseMenuForm };
@@ -1,144 +0,0 @@
import { type UseFormReturn } from "react-hook-form";
import {
Label,
RadioGroup,
RadioGroupItem,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
} from "@common/components";
import {
FormItem,
FormControl,
FormField,
FormMessage,
} from "@/shared/ui/form";
import type { MenuFormData } from "../model/menu-interface";
import { BaseBottomMenuForm } from "./base-bottom-menu-form";
export function BoardMenuForm({ form }: { form: UseFormReturn<MenuFormData> }) {
return (
<Table variant="secondary">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<TableBody>
<TableRow>
<TableHead>게시판</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">
{form.watch("menuLnkgSn")}
</div>
</TableCell>
</TableRow>
<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="self" id="self" />
<Label htmlFor="self">현재창</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="blank" id="blank" />
<Label htmlFor="blank">새창</Label>
</div>
</div>
</RadioGroup>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<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>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<BaseBottomMenuForm form={form} />
<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>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>담당자</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">
{form.watch("menuLnkgSn")}
</div>
</TableCell>
</TableRow>
</TableBody>
</Table>
);
}
@@ -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 };
@@ -1,22 +0,0 @@
import { type UseFormReturn } from "react-hook-form";
import { Table, TableBody } from "@common/components";
import type { MenuFormData } from "../model/menu-interface";
import { BaseBottomMenuForm } from "./base-bottom-menu-form";
export function BottomMenuForm({
form,
}: {
form: UseFormReturn<MenuFormData>;
}) {
return (
<Table variant="secondary">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<TableBody>
<BaseBottomMenuForm form={form} />
</TableBody>
</Table>
);
}
@@ -1,148 +0,0 @@
import { type UseFormReturn } from "react-hook-form";
import {
Label,
RadioGroup,
RadioGroupItem,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
} from "@common/components";
import {
FormItem,
FormControl,
FormField,
FormMessage,
} from "@/shared/ui/form";
import type { MenuFormData } from "../model/menu-interface";
import { BaseBottomMenuForm } from "./base-bottom-menu-form";
export function ContentMenuForm({
form,
}: {
form: UseFormReturn<MenuFormData>;
}) {
return (
<Table variant="secondary">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<TableBody>
<TableRow>
<TableHead>콘텐츠</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">
{form.watch("menuLnkgSn")}
</div>
</TableCell>
</TableRow>
<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="self" id="self" />
<Label htmlFor="self">현재창</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="blank" id="blank" />
<Label htmlFor="blank">새창</Label>
</div>
</div>
</RadioGroup>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<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>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<BaseBottomMenuForm form={form} />
<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>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>담당자</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">
{form.watch("menuLnkgSn")}
</div>
</TableCell>
</TableRow>
</TableBody>
</Table>
);
}
@@ -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 { ContentsApi, type Contents } from "@/entities/contents";
import { columns } from "../model/content-table-colums";
type ContentSearchDialogProps = {
handleContentSelect: (content: Contents) => 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: () => ContentsApi.getContentsList({ 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 Contents;
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 };
@@ -1,18 +0,0 @@
import { type UseFormReturn } from "react-hook-form";
import { Table, TableBody } from "@common/components";
import type { MenuFormData } from "../model/menu-interface";
import { BaseBottomMenuForm } from "./base-bottom-menu-form";
export function EmptyMenuForm({ form }: { form: UseFormReturn<MenuFormData> }) {
return (
<Table variant="secondary">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<TableBody>
<BaseBottomMenuForm form={form} />
</TableBody>
</Table>
);
}
@@ -1,22 +0,0 @@
import { type UseFormReturn } from "react-hook-form";
import { Table, TableBody } from "@common/components";
import type { MenuFormData } from "../model/menu-interface";
import { BaseBottomMenuForm } from "./base-bottom-menu-form";
export function InsideMenuForm({
form,
}: {
form: UseFormReturn<MenuFormData>;
}) {
return (
<Table variant="secondary">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<TableBody>
<BaseBottomMenuForm form={form} />
</TableBody>
</Table>
);
}
+63 -80
View File
@@ -1,111 +1,94 @@
import { useState } from "react";
import type { UseFormReturn } from "react-hook-form";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { type UseFormReturn } from "react-hook-form";
import { Button } from "@common/components";
import { Form } from "@/shared/ui/form";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
import { MENU_TYPE, type MenuFormData } from "../model/menu-interface";
import { ManagementAuthorityDialog } from "@/entities/menu-authority";
import type { MenuFormData } from "../model/menu-interface";
import { BaseMenuForm } from "./base-menu-form";
import { EmptyMenuForm } from "./empty-menu-form";
import { ContentMenuForm } from "./content-menu-form";
import { BoardMenuForm } from "./board-menu-form";
import { InsideMenuForm } from "./inside-menu-form";
import { OutsideMenuForm } from "./outside-menu-form";
import { BottomMenuForm } from "./bottom-menu-form";
import { TypeMenuForm } from "./type-menu-form";
interface MenuFormProps {
form: UseFormReturn<MenuFormData>;
menuId?: number;
handleSave: (data: MenuFormData) => Promise<void>;
handleDelete?: () => Promise<void>;
menuCd?: number;
handleCreate: (data: MenuFormData) => void;
handleUpdate: ({
menuCd,
data,
}: {
menuCd: number;
data: Omit<MenuFormData, "siteId">;
}) => void;
handleDelete?: (menuCd: number) => void;
}
export function MenuForm({
function MenuForm({
form,
menuId,
handleSave,
menuCd,
handleCreate,
handleUpdate,
handleDelete,
}: MenuFormProps) {
const isModifyMode = !!menuId;
const isModifyMode = !!menuCd;
const { confirm } = useConfirm();
const [onConfirm, setOnConfirm] = useState(false);
const onSubmit = async (data: MenuFormData) => {
const confirmMessage = isModifyMode
? "수정하시겠습니까?"
: "저장하시겠습니까?";
setOnConfirm(true);
if (await confirm(confirmMessage)) {
setOnConfirm(false);
handleSave(data);
if (isModifyMode) {
await onUpdate(data);
} else {
await onCreate(data);
}
};
const onCreate = async (data: MenuFormData) => {
if (await confirm("저장하시겠습니까?")) {
handleCreate(data);
}
};
const onUpdate = async (data: MenuFormData) => {
if (await confirm("수정하시겠습니까?")) {
handleUpdate({ menuCd: menuCd!, data });
}
setOnConfirm(false);
};
const onDelete = async () => {
setOnConfirm(true);
if (await confirm("삭제하시겠습니까?")) {
setOnConfirm(false);
handleDelete?.();
handleDelete?.(menuCd!);
}
setOnConfirm(false);
};
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">
메뉴 등록/수정
</h3>
</div>
<div className="card">
<BaseMenuForm form={form} menuId={menuId} />
<div className="-mt-[0.1rem]">
{renderMenuTypeComponent(menuType, form)}
</div>
</div>
<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>
<ManagementAuthorityDialog menuCd={menuCd} />
</div>
<div className="flex justify-center gap-4 pb-12 pt-10">
<Button size="lg" type="submit">
저장
<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>
{isModifyMode && (
<Button size="lg" color="red" type="button" onClick={onDelete}>
삭제
</Button>
)}
</div>
</form>
</Form>
<ConfirmDialog open={onConfirm} />
</>
)}
</div>
</form>
</Form>
);
}
function renderMenuTypeComponent(
menuType: string,
form: UseFormReturn<MenuFormData>,
) {
switch (menuType) {
case MENU_TYPE.EMPTY:
return <EmptyMenuForm form={form} />;
case MENU_TYPE.CONTENTS:
return <ContentMenuForm form={form} />;
case MENU_TYPE.BOARD:
return <BoardMenuForm form={form} />;
case MENU_TYPE.INSIDE:
return <InsideMenuForm form={form} />;
case MENU_TYPE.OUTSIDE:
return <OutsideMenuForm form={form} />;
case MENU_TYPE.BOTTOM:
return <BottomMenuForm form={form} />;
default:
return null;
}
}
export { MenuForm };
+51 -52
View File
@@ -1,18 +1,22 @@
import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import type { NodeModel } from "@minoru/react-dnd-treeview";
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 { Button, Input } from "@common/components/ui";
import type { Menu } from "../model/menu-interface";
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<Menu>;
node: NodeModel<TreeMenu>;
depth: number;
isOpen: boolean;
isSelected: boolean;
isAdditionalParent: boolean;
treeMethods: TreeMethods | null;
onToggle: (id: NodeModel["id"]) => void;
onSelect: (node: NodeModel<Menu>) => void;
onSelect: (node: NodeModel<TreeMenu>) => void;
};
function MenuNode({
@@ -20,16 +24,25 @@ function MenuNode({
depth,
isOpen,
isSelected,
isAdditionalParent,
treeMethods,
onToggle,
onSelect,
}: MenuNodeProps) {
const { id, text, data } = node;
const indent = depth * 10 + 5;
const { mutateAsync: modifyMenuName } = useMutation({
const queryClient = useQueryClient();
const { mutateAsync: updateMenuName } = useMutation({
mutationFn: (nodeName: string) => {
const encodedName = encodeURIComponent(nodeName);
return MenuApi.modifyMenuName(id as number, encodedName);
return MenuApi.updateMenuName(id as number, encodedName);
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: [ENDPOINT.CMS_SERVICE.MENUS],
});
},
});
@@ -40,10 +53,19 @@ function MenuNode({
const handleSelect = () => onSelect(node);
const handleSave = async () => {
await modifyMenuName(nodeName);
await updateMenuName(nodeName);
setEditMode(false);
};
const handleCancel = () => {
setEditMode(false);
setNodeName(text);
};
useEffect(() => {
if (isAdditionalParent) treeMethods?.open(id);
}, [isAdditionalParent]);
return (
<div
style={{ paddingInlineStart: indent }}
@@ -51,63 +73,40 @@ function MenuNode({
"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)]",
)}
onClick={handleSelect}
>
<div className="flex items-center">
{editMode ? (
<>
<Input
value={nodeName}
onChange={(e) => setNodeName(e.target.value)}
className="h-[2.5rem] !text-[1.3rem] text-foreground"
/>
</>
) : (
<>
{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={handleToggle}
onClick={(e) => {
e.stopPropagation();
handleToggle();
}}
/>
)}
<span className="text-[1.4rem] font-medium text-label">{text}</span>
</>
)}
</div>
{editMode ? (
<div className="flex items-center gap-1">
</div>
<Button
variant="ghost"
size="icon"
className="size-8 !bg-transparent"
onClick={handleSave}
className="invisible !bg-transparent group-hover:visible"
onClick={() => setEditMode(true)}
>
<i className="diveicon di-check text-2xl" />
<i className="diveicon di-pencil" />
</Button>
<Button
variant="ghost"
size="icon"
className="size-8 !bg-transparent"
onClick={() => {
setEditMode(false);
setNodeName(text);
}}
>
<i className="diveicon di-x" />
</Button>
</div>
) : (
<Button
variant="ghost"
size="icon"
className="invisible !bg-transparent group-hover:visible"
onClick={() => setEditMode(true)}
>
<i className="diveicon di-pencil" />
</Button>
</>
)}
</div>
);
+198 -47
View File
@@ -2,8 +2,10 @@
import { useState } from "react";
import { useForm } from "react-hook-form";
import { useQuery } from "@tanstack/react-query";
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,
@@ -14,7 +16,8 @@ import {
} from "@common/components/ui";
import { SiteApi } from "@/entities/site";
import { ENDPOINT } from "@/shared/config";
import { PageLayout } from "@/shared/ui/page-layout";
import { useAlertStore } from "@/shared/lib/use-alert-store";
import type { TreeMenu } from "../model/menu-interface";
import { MenuApi } from "../api/menu-service";
import {
MENU_TYPE,
@@ -23,21 +26,41 @@ import {
} from "../model/menu-interface";
import { MenuTree } from "./menu-tree";
import { MenuForm } from "./menu-form";
import { generateTreeData } from "../lib/utils";
import { generateMenuTreeData } from "../lib/utils";
function MenuPage() {
const queryClient = useQueryClient();
const { setMessage: alert } = useAlertStore((state) => state);
const { confirm } = useConfirm();
const [siteId, setSiteId] = useState("");
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) => generateTreeData(data),
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({}),
queryFn: () => SiteApi.getSiteList(),
select: (data) =>
data.content.map((site) => ({
label: site.siteNm,
@@ -45,60 +68,188 @@ function MenuPage() {
})),
});
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 handleSave = async (data: MenuFormData) => {
console.log(data);
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 handleDelete = async () => {};
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 () => {
if (await confirm("삭제하시겠습니까?")) {
deleteMenu(selectedMenu!.menuCd!);
}
};
const handleAddMenu = () => {
if (additionalNode) return;
setAdditionalNode({
id: -1,
parent: selectedMenu?.menuCd ?? 0,
text: "",
});
};
const tree = additionalNode
? [...(additionalNode ? [additionalNode] : []), ...(treeData ?? [])]
: (treeData ?? []);
return (
<PageLayout pageTitle="메뉴 관리">
<div className="card flex gap-2">
<div className="card card-border w-[24rem]">
<Select value={siteId} onValueChange={setSiteId}>
<SelectTrigger>
<SelectValue placeholder="선택하세요" />
</SelectTrigger>
<SelectContent>
{options?.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
{treeData && (
<>
<div className="my-4 flex gap-2">
<Button size="sm" color="primary" className="flex-1">
메뉴 추가
</Button>
<Button size="sm" color="red" className="flex-1">
메뉴 삭제
</Button>
</div>
<div className="card card-border !mx-0">
<MenuTree treeData={treeData ?? []} siteId={siteId} />
</div>
</>
)}
</div>
<div className="card card-border flex-1">
<MenuForm
form={form}
handleSave={handleSave}
handleDelete={handleDelete}
/>
</div>
<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>
</PageLayout>
<div className="card card-border flex-1">
<MenuForm
form={form}
menuCd={selectedMenu?.menuCd}
handleCreate={createMenu}
handleUpdate={updateMenu}
handleDelete={deleteMenu}
/>
</div>
</div>
);
}
+116 -48
View File
@@ -1,31 +1,49 @@
"use client";
import { useState } from "react";
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 { Menu, TreeMenu } from "../model/menu-interface";
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 = {
treeData: NodeModel<Menu>[];
tree: NodeModel<TreeMenu>[];
siteId: string;
selectedMenu: TreeMenu | null;
additionalNodeForm: UseFormReturn<MenuFormData>;
onSelectNode: (node: NodeModel<TreeMenu>) => void;
onAdditionalNodeSave: () => void;
onAdditionalNodeCancel: () => void;
};
function MenuTree({ treeData, siteId }: MenuTreeProps) {
function MenuTree({
tree,
siteId,
selectedMenu,
additionalNodeForm,
onSelectNode,
onAdditionalNodeSave,
onAdditionalNodeCancel,
}: MenuTreeProps) {
const queryClient = useQueryClient();
const treeMethods = useRef<TreeMethods>(null);
const { mutate: modifyTreeMenu } = useMutation({
mutationFn: (newTree: TreeMenu) =>
MenuApi.modifyTreeMenu(siteId, [newTree]),
const { mutate: updateTreeMenu } = useMutation({
mutationFn: (newTree: TreeNode) =>
MenuApi.updateTreeMenu(siteId, [newTree]),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: [ENDPOINT.CMS_SERVICE.MENUS],
@@ -33,50 +51,100 @@ function MenuTree({ treeData, siteId }: MenuTreeProps) {
},
});
const [selectedNode, setSelectedNode] = useState<NodeModel<Menu> | null>(
null,
);
const additionalNode = tree.find((n) => n.id === -1);
const isAdditionalParent = (node: NodeModel<TreeMenu>): boolean => {
if (!additionalNode) return false;
return additionalNode?.parent === node.id;
};
return (
<DndProvider backend={MultiBackend} options={getBackendOptions()}>
<Tree
tree={treeData}
rootId={0}
render={(node: NodeModel<Menu>, { depth, isOpen, onToggle }) => (
<MenuNode
node={node}
depth={depth}
isOpen={isOpen}
isSelected={selectedNode?.id === node.id}
onToggle={onToggle}
onSelect={handleSelectNode(setSelectedNode)}
<>
<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 }}
/>
);
}}
/>
)}
onDrop={handleDropNode(modifyTreeMenu)}
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>
</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>
</>
);
}
@@ -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_ORGANIZATION],
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 };
@@ -1,22 +0,0 @@
import { type UseFormReturn } from "react-hook-form";
import { Table, TableBody } from "@common/components";
import type { MenuFormData } from "../model/menu-interface";
import { BaseBottomMenuForm } from "./base-bottom-menu-form";
export function OutsideMenuForm({
form,
}: {
form: UseFormReturn<MenuFormData>;
}) {
return (
<Table variant="secondary">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<TableBody>
<BaseBottomMenuForm form={form} />
</TableBody>
</Table>
);
}
@@ -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 { Contents } from "@/entities/contents";
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: Contents) => {
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="15%" />
<col width="85%" />
</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,53 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type {
AuthorizationsService,
AuthorizationsParams,
AuthorizationsList,
AuthorizationFormData,
WithRoleAuthorizations,
} from "../model/authorizations-interface";
export class AuthorizationsApiService implements AuthorizationsService {
public async getAuthorizationsList(
params: AuthorizationsParams,
): Promise<AuthorizationsList> {
const response = await client.get<AuthorizationsList>(
`${ENDPOINT.USER_SERVICE.AUTHORIZATIONS}`,
{ params },
);
return response.data;
}
public async getAuthorizationInfo(
authorizationNo: string,
): Promise<WithRoleAuthorizations> {
const response = await client.get<WithRoleAuthorizations>(
`${ENDPOINT.USER_SERVICE.AUTHORIZATIONS}/${authorizationNo}`,
);
return response.data;
}
public async createAuthorization(
data: AuthorizationFormData,
): Promise<WithRoleAuthorizations> {
const response = await client.post<WithRoleAuthorizations>(
`${ENDPOINT.USER_SERVICE.AUTHORIZATIONS}`,
data,
);
return response.data;
}
public async updateAuthorization(
authorizationNo: string,
data: AuthorizationFormData,
): Promise<WithRoleAuthorizations> {
const response = await client.put<WithRoleAuthorizations>(
`${ENDPOINT.USER_SERVICE.AUTHORIZATIONS}/${authorizationNo}`,
data,
);
return response.data;
}
}
export const AuthorizationsApi = new AuthorizationsApiService();
@@ -0,0 +1,43 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type {
RoleAuthorizationsService,
RoleAuthorizationsParams,
RoleAuthorizationsList,
RoleAuthorizationsData,
RoleAuthorizations,
} from "../model/role-authorizations-interface";
export class RoleAuthorizationsApiService implements RoleAuthorizationsService {
public async getRoleAuthorizationsList(
params: RoleAuthorizationsParams,
): Promise<RoleAuthorizationsList> {
const response = await client.get<RoleAuthorizationsList>(
`${ENDPOINT.USER_SERVICE.ROLE_AUTHORIZATIONS}/api`,
{ params },
);
return response.data;
}
public async createRoleAuthorizations(
data: RoleAuthorizationsData,
): Promise<RoleAuthorizations> {
const response = await client.post<RoleAuthorizations>(
`${ENDPOINT.USER_SERVICE.ROLE_AUTHORIZATIONS}`,
data,
);
return response.data;
}
public async updateRoleAuthorizations(
data: RoleAuthorizationsData,
): Promise<RoleAuthorizations> {
const response = await client.put<RoleAuthorizations>(
`${ENDPOINT.USER_SERVICE.ROLE_AUTHORIZATIONS}`,
data,
);
return response.data;
}
}
export const RoleAuthorizationsApi = new RoleAuthorizationsApiService();
+3
View File
@@ -0,0 +1,3 @@
export { ModulePage } from "./ui/module-page";
export { CreatePage } from "./ui/create-page";
export { ModifyPage } from "./ui/modify-page";
@@ -0,0 +1,62 @@
import { z } from "zod";
import type { PageableList, PageableParams } from "@/shared/model";
export interface AuthorizationsParams extends PageableParams {
keywordType?: string;
keyword?: string;
authorizationName?: string;
httpMethodCode?: string;
useYn?: string;
}
export interface Authorizations {
authorizationNo: number;
authorizationName: string;
urlPatternValue: string;
httpMethodCode: string;
sortSeq: number;
useYn: string;
mdfr: string;
mdfcnDt: string;
}
export interface RoleAuthorizations {
roleId: string;
authorizationNo: number;
authorizationName: string;
urlPatternValue: string;
httpMethodCode: string;
sortSeq: number;
createdAt: string;
}
export interface WithRoleAuthorizations extends Authorizations {
roleAuthorizations: RoleAuthorizations[];
}
export const authorizationFormSchema = z.object({
authorizationName: z.string(),
urlPatternValue: z.string(),
httpMethodCode: z.string(),
sortSeq: z.number(),
useYn: z.string(),
});
export type AuthorizationsList = PageableList<Authorizations>;
export type AuthorizationFormData = z.infer<typeof authorizationFormSchema>;
export interface AuthorizationsService {
getAuthorizationsList: (
params: AuthorizationsParams,
) => Promise<AuthorizationsList>;
getAuthorizationInfo: (
authorizationNo: string,
) => Promise<WithRoleAuthorizations>;
createAuthorization: (
data: AuthorizationFormData,
) => Promise<WithRoleAuthorizations>;
updateAuthorization: (
authorizationNo: string,
data: AuthorizationFormData,
) => Promise<WithRoleAuthorizations>;
}
@@ -0,0 +1,58 @@
import dayjs from "dayjs";
import { type ColumnDef } from "@tanstack/react-table";
import type { Authorizations } from "./authorizations-interface";
import { ManagementAuthorityDialog } from "../ui/management-authority-dialog";
export const columns: ColumnDef<Authorizations>[] = [
{
id: "no",
header: "NO",
cell: ({ row }) => row.index + 1,
},
{
accessorKey: "authorizationName",
header: "API명",
},
{
accessorKey: "urlPatternValue",
header: "API URL",
},
{
accessorKey: "httpMethodCode",
header: "요청 메소드",
},
{
accessorKey: "useYn",
header: "사용여부",
},
{
accessorKey: "mdfr",
header: "최종수정자",
},
{
accessorKey: "mdfcnDt",
header: "최종수정일",
cell: ({ row }) => {
const date = dayjs(row.original.mdfcnDt);
return date.format("YYYY-MM-DD");
},
},
{
id: "action",
header: "권한관리",
cell: ({ row }) => {
return (
<div
onClick={(e) => {
e.stopPropagation();
}}
>
<ManagementAuthorityDialog
authorizationNo={row.original.authorizationNo.toString()}
rowData={row.original}
/>
</div>
);
},
},
];
@@ -0,0 +1,45 @@
import { z } from "zod";
import type { PageableList, PageableParams } from "@/shared/model";
export interface RoleAuthorizationsParams extends PageableParams {
keywordType?: string;
keyword?: string;
authorizationNo?: string;
}
export interface RoleAuthorizations {
roleId: string;
roleName: string;
roleContent: string;
useYn: string;
authorizationNo: number;
authYn: string;
}
export const roleAuthorizationsSchema = z.object({
roleId: z.string(),
authorizationNo: z.number(),
authYn: z.string(),
});
export const roleAuthorizationsFormSchema = z.object({
roleAuthorizations: z.array(roleAuthorizationsSchema),
});
export type RoleAuthorizationsList = PageableList<RoleAuthorizations>;
export type RoleAuthorizationsData = z.infer<typeof roleAuthorizationsSchema>[];
export type RoleAuthorizationsFormData = z.infer<
typeof roleAuthorizationsFormSchema
>;
export interface RoleAuthorizationsService {
getRoleAuthorizationsList: (
params: RoleAuthorizationsParams,
) => Promise<RoleAuthorizationsList>;
createRoleAuthorizations: (
data: RoleAuthorizationsData,
) => Promise<RoleAuthorizations>;
updateRoleAuthorizations: (
data: RoleAuthorizationsData,
) => Promise<RoleAuthorizations>;
}
@@ -0,0 +1,53 @@
import { type ColumnDef } from "@tanstack/react-table";
import type { RoleAuthorizations } from "./role-authorizations-interface";
import { Checkbox } from "@common/components/ui";
import type { UseFormReturn } from "react-hook-form";
import type { RoleAuthorizationsFormData } from "./role-authorizations-interface";
export const createColumns = (
form: UseFormReturn<RoleAuthorizationsFormData>,
): ColumnDef<RoleAuthorizations>[] => [
{
id: "select",
header: ({ table }) => (
<Checkbox
checked={form
.watch("roleAuthorizations")
.every((role) => role.authYn === "Y")}
onCheckedChange={(checked) => {
table.getRowModel().rows.forEach((row, index) => {
form.setValue(
`roleAuthorizations.${index}.authYn`,
checked ? "Y" : "N",
);
});
}}
className="h-4 w-4 rounded border-gray-300"
/>
),
cell: ({ row }) => (
<Checkbox
checked={form.watch(`roleAuthorizations.${row.index}.authYn`) === "Y"}
onCheckedChange={(checked) => {
form.setValue(
`roleAuthorizations.${row.index}.authYn`,
checked ? "Y" : "N",
);
}}
className="h-4 w-4 rounded border-gray-300"
/>
),
},
{
accessorKey: "roleId",
header: "권한ID",
},
{
accessorKey: "roleName",
header: "권한명",
},
{
accessorKey: "roleContent",
header: "권한설명",
},
];
@@ -0,0 +1,45 @@
"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 {
authorizationFormSchema,
type AuthorizationFormData,
} from "../model/authorizations-interface";
import { AuthorizationsApi } from "../api/authorization-service";
import { ModuleForm } from "./module-form";
function CreatePage() {
const router = useRouter();
const { setMessage: alert } = useAlertStore((state) => state);
const { mutateAsync: createAuthorization } = useMutation({
mutationFn: (data: AuthorizationFormData) =>
AuthorizationsApi.createAuthorization(data),
onSuccess: () => {
alert("등록되었습니다.", router.back);
},
});
const form = useForm<AuthorizationFormData>({
resolver: zodResolver(authorizationFormSchema),
defaultValues: {
sortSeq: 0,
useYn: "Y",
},
});
return (
<div className="card card-border !mt-6">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">모듈API 등록</h3>
</div>
<ModuleForm form={form} handleSave={createAuthorization} />
</div>
);
}
export { CreatePage };

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