제품 모델 커밋

This commit is contained in:
chpark 2024-12-30 18:28:26 +09:00
parent 2efe5706d4
commit d47da1827e
2 changed files with 74 additions and 687 deletions

View File

@ -0,0 +1,74 @@
// models/ProductGroup.js
const { Model, DataTypes } = require("sequelize");
class Product extends Model {
static init(sequelize) {
super.init(
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
// 제품군 ID
product_group_id: {
type: DataTypes.UUID,
comment: "제품군 ID",
},
product_code: {
type: DataTypes.STRING(128),
allowNull: true,
comment: "제품코드",
},
product_name: {
type: DataTypes.STRING(128),
allowNull: true,
comment: "제품코드",
},
product_desc: {
type: DataTypes.STRING(128),
allowNull: true,
comment: "제품 설명",
},
writer: {
type: DataTypes.STRING(32),
allowNull: true,
comment: "작성자",
},
isActive: {
type: DataTypes.BOOLEAN,
defaultValue: true,
},
// 새로 추가할 필드들
companyId: {
type: DataTypes.UUID,
comment: "회사 ID",
},
},
{
sequelize,
modelName: 'Product',
tableName: 'product_mng1',
timestamps: true,
indexes: [
{
fields: ['id'],
},
],
}
);
return this;
}
static associate(models) {
// product가 Company에 속함
// product가 product_group에 속함
this.belongsTo(models.Company, { foreignKey: "companyId" });
this.belongsTo(models.ProductGroup, { foreignKey: "product_group_id" });
}
}
module.exports = Product;

View File

@ -1,687 +0,0 @@
"use client";
import React, { useState, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { api } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { useToast } from "@/hooks/use-toast";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Switch } from "@/components/ui/switch";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from "@/components/ui/dialog";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Card,
CardHeader,
CardTitle,
CardDescription,
CardContent,
} from "@/components/ui/card";
import {
Loader2,
Plus,
ChevronDown,
ChevronRight,
Trash2,
AlertCircle
} from "lucide-react";
import { cn } from "@/lib/utils";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
interface DBMenuItem {
id: string;
menu_type: string;
parent_id: string | null;
menu_name_kor: string;
menu_name_eng: string;
seq: string;
menu_url: string;
menu_desc?: string;
isActive: boolean;
children?: DBMenuItem[];
order?: string;
}
interface DBApiResponse {
success: boolean;
data: {
success: boolean;
data: DBMenuItem[];
};
}
interface MenuFormDialogProps {
isOpen: boolean;
onClose: () => void;
menuData?: DBMenuItem;
onSave: (data: DBMenuItem) => void;
menus: DBMenuItem[];
}
interface FormData {
menuNameKor: string;
menuNameEng: string;
menuUrl: string;
menuSeq: string;
menuType: string;
isActive: boolean;
parentId: string;
}
const getFlatMenuList = (menus: DBMenuItem[], depth = 0): { id: string; label: string; isChild: boolean }[] => {
return menus.flatMap((menu) => [
{
id: menu.id,
label: `${' '.repeat(depth)}${menu.menu_name_kor}`,
isChild: depth > 0, // 깊이에 따라 자식 여부 판단
},
...(menu.children ? getFlatMenuList(menu.children, depth + 1) : []),
]);
};
const MenuFormDialog = ({ isOpen, onClose, menuData, onSave, menus }: MenuFormDialogProps) => {
const [searchText, setSearchText] = useState("");
const form = useForm<FormData>({
defaultValues: {
menuNameKor: "",
menuNameEng: "",
menuUrl: "",
menuSeq: "",
menuType: "0",
isActive: true, // 기본 활성화 상태를 true로 설정
parentId: "root",
},
});
useEffect(() => {
if (menuData) {
form.reset({
menuNameKor: menuData.menu_name_kor || "",
menuNameEng: menuData.menu_name_eng || "",
menuUrl: menuData.menu_url || "",
menuSeq: menuData.seq || "",
menuType: menuData.menu_type || "0",
isActive: menuData.isActive || false,
parentId: menuData.parent_id || "root",
});
} else {
form.reset({
menuNameKor: "",
menuNameEng: "",
menuUrl: "",
menuSeq: "",
menuType: "0",
isActive: true, // 새로 추가할 때 기본 활성화
parentId: "root",
});
}
}, [menuData, form]);
const onSubmit = (data: FormData) => {
onSave({
id: menuData?.id || "",
menu_type: data.menuType,
parent_id: data.parentId === "root" ? null : data.parentId,
menu_name_kor: data.menuNameKor,
menu_name_eng: data.menuNameEng,
seq: data.menuSeq,
menu_url: data.menuUrl,
isActive: data.isActive,
children: menuData?.children || [],
});
};
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>{menuData ? "메뉴 수정" : "메뉴 추가"}</DialogTitle>
<DialogDescription>
{menuData ? "기존 메뉴의 정보를 수정합니다." : "새로운 메뉴를 시스템에 추가합니다."}
</DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="parentId"
render={({ field }) => (
<FormItem>
<FormLabel> </FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="메뉴 선택" />
</SelectTrigger>
</FormControl>
<SelectContent>
<div className="p-2">
<Input
placeholder="메뉴 검색..."
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
className="mb-2"
/>
</div>
<SelectItem value="root"></SelectItem>
<Separator className="my-2" />
{getFlatMenuList(menus)
.filter((menu) =>
menu.label.toLowerCase().includes(searchText.toLowerCase())
)
.map((menu, index, array) => (
<React.Fragment key={menu.id}>
<SelectItem
value={menu.id}
className={cn(
menu.isChild ? "pl-6" : "font-bold", // 자식 메뉴는 들여쓰기 적용
"relative"
)}
>
{menu.isChild ? `${menu.label.trim()}` : menu.label}
</SelectItem>
{array[index + 1]?.isChild === false && (
<Separator className="my-2" />
)}
</React.Fragment>
))}
</SelectContent>
</Select>
</FormItem>
)}
/>
<FormField
control={form.control}
name="menuNameKor"
render={({ field }) => (
<FormItem>
<FormLabel> ()</FormLabel>
<FormControl>
<Input {...field} placeholder="메뉴 이름을 입력하세요" />
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name="menuNameEng"
render={({ field }) => (
<FormItem>
<FormLabel> ()</FormLabel>
<FormControl>
<Input {...field} placeholder="Menu Name" />
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name="menuUrl"
render={({ field }) => (
<FormItem>
<FormLabel>URL</FormLabel>
<FormControl>
<Input {...field} placeholder="/example" />
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name="menuSeq"
render={({ field }) => (
<FormItem>
<FormLabel></FormLabel>
<FormControl>
<Input {...field} type="number" placeholder="순서를 입력하세요" />
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name="menuType"
render={({ field }) => (
<FormItem>
<FormLabel></FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="메뉴 타입 선택" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="0"> </SelectItem>
<SelectItem value="1"> </SelectItem>
</SelectContent>
</Select>
</FormItem>
)}
/>
<FormField
control={form.control}
name="isActive"
render={({ field }) => (
<FormItem>
<div className="flex items-center space-x-2">
<FormLabel></FormLabel>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</div>
</FormItem>
)}
/>
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose}>
</Button>
<Button type="submit">
{menuData ? "수정" : "추가"}
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
);
};
interface MenusTableProps {
menus: DBMenuItem[];
toggleActive: (id: string, value: boolean) => void;
openSections: { [key: string]: boolean };
toggleSection: (id: string) => void;
onMenuClick: (menu: DBMenuItem) => void;
onDelete: (id: string) => void;
}
const MenusTable = ({
menus,
toggleActive,
openSections,
toggleSection,
onMenuClick,
onDelete
}: MenusTableProps) => {
const renderMenuRow = (menu: DBMenuItem, level: number = 0) => (
<React.Fragment key={menu.id}>
<TableRow
className="hover:bg-muted/50 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
toggleSection(menu.id);
}}
>
<TableCell
style={{ paddingLeft: `${level * 20}px` }}
className="font-medium relative group"
>
<div className="flex items-center space-x-2">
{menu.children && menu.children.length > 0 ? (
<Button
variant="ghost"
size="icon"
className="h-8 w-8 p-0"
onClick={(e) => {
e.stopPropagation(); // 부모 클릭 이벤트 방지
toggleSection(menu.id);
}}
>
{openSections[menu.id] ? (
<ChevronDown className="h-4 w-4" />
) : (
<ChevronRight className="h-4 w-4" />
)}
</Button>
) : (
<span className="w-8" />
)}
<span
className="font-medium cursor-pointer hover:text-primary"
onClick={(e) => {
e.stopPropagation(); // 부모 클릭 이벤트 방지
onMenuClick(menu);
}}
>
{menu.menu_name_kor}
</span>
</div>
</TableCell>
<TableCell>{menu.menu_name_eng}</TableCell>
<TableCell className="font-mono">{menu.menu_url}</TableCell>
<TableCell className="text-center">{menu.seq}</TableCell>
<TableCell className="text-center">
<span
className={cn(
"inline-flex items-center rounded-md px-2 py-1 text-xs font-medium ring-1 ring-inset",
menu.menu_type === "0"
? "bg-blue-50 text-blue-700 ring-blue-700/10"
: "bg-green-50 text-green-700 ring-green-600/20"
)}
>
{menu.menu_type === "0" ? "관리자 메뉴" : "사용자 메뉴"}
</span>
</TableCell>
<TableCell className="text-center">
<div className="flex items-center justify-center space-x-2">
<Switch
checked={menu.isActive}
onCheckedChange={(value) => toggleActive(menu.id, value)}
/>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 p-0 hover:text-destructive"
onClick={(e) => {
e.stopPropagation(); // 부모 클릭 이벤트 방지
onDelete(menu.id);
}}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</TableCell>
</TableRow>
{menu.children &&
menu.children.length > 0 &&
openSections[menu.id] &&
menu.children.map((child) => renderMenuRow(child, level + 1))}
</React.Fragment>
);
return (
<Card>
<CardHeader>
<CardTitle> </CardTitle>
</CardHeader>
<CardContent>
<div className="rounded-md border h-[500px]">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[300px]"> </TableHead>
<TableHead> </TableHead>
<TableHead>URL</TableHead>
<TableHead className="w-[100px] text-center"></TableHead>
<TableHead className="w-[120px] text-center"></TableHead>
<TableHead className="w-[140px] text-center">/</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{menus.map((menu) => renderMenuRow(menu))}
</TableBody>
</Table>
{menus.length === 0 && (
<div className="flex items-center justify-center h-32 text-muted-foreground">
.
</div>
)}
</div>
</CardContent>
</Card>
);
};
const addMenuOrder = (menus: DBMenuItem[], parentOrder: string = ''): DBMenuItem[] => {
return menus.map((menu, index) => {
const order = parentOrder ? `${parentOrder}-${index + 1}` : `${index + 1}`;
return {
...menu,
order,
children: menu.children ? addMenuOrder(menu.children, order) : [],
};
});
};
const MenusPage = () => {
const [isOpen, setIsOpen] = useState(false);
const [selectedMenu, setSelectedMenu] = useState<DBMenuItem | null>(null);
const [openSections, setOpenSections] = useState<{ [key: string]: boolean }>({});
const [deleteAlertOpen, setDeleteAlertOpen] = useState(false);
const [menuToDelete, setMenuToDelete] = useState<string | null>(null);
const queryClient = useQueryClient();
const { toast } = useToast();
const toggleSection = (id: string) => {
setOpenSections((prev) => ({
...prev,
[id]: !prev[id],
}));
};
const { data: dbMenuData, isLoading } = useQuery<DBApiResponse>({
queryKey: ["admin-menus"],
queryFn: async () => {
const response = await api.get("/api/v1/app/common/admin/menu");
return response.data;
},
// 추가 옵션
refetchOnWindowFocus: true,
refetchOnMount: true,
refetchOnReconnect: true,
});
const saveMenuMutation = useMutation({
mutationFn: async (menuData: Omit<DBMenuItem, 'children' | 'order'>) => {
const response = await api.post("/api/v1/app/common/createmenu", menuData);
return response.data;
},
onSuccess: () => {
// 더 구체적인 refetch 처리
queryClient.invalidateQueries({ queryKey: ["admin-menus"] });
queryClient.refetchQueries({ queryKey: ["admin-menus"] });
toast({
title: "메뉴 저장 성공",
description: "메뉴가 저장되었습니다.",
});
setIsOpen(false);
},
onError: (error) => {
toast({
title: "메뉴 저장 실패",
description: "메뉴 저장 중 오류가 발생했습니다. 다시 시도해주세요.",
variant: "destructive",
});
console.error("Menu save error:", error);
},
});
const toggleActiveMutation = useMutation({
mutationFn: async ({ id, isActive }: { id: string; isActive: boolean }) => {
const response = await api.post("/api/v1/app/common/createmenu", {
id,
isActive,
});
return response.data;
},
onSuccess: () => {
// 더 구체적인 refetch 처리
queryClient.invalidateQueries({ queryKey: ["admin-menus"] });
queryClient.refetchQueries({ queryKey: ["admin-menus"] });
},
onError: (error) => {
toast({
title: "상태 변경 실패",
description: "메뉴 상태 변경 중 오류가 발생했습니다.",
variant: "destructive",
});
console.error("Toggle active error:", error);
},
});
const deleteMenuMutation = useMutation({
mutationFn: async (id: string) => {
const response = await api.delete(`/api/v1/app/common/menu/${id}`);
return response.data;
},
onSuccess: () => {
// 더 구체적인 refetch 처리
queryClient.invalidateQueries({ queryKey: ["admin-menus"] });
queryClient.refetchQueries({ queryKey: ["admin-menus"] });
toast({
title: "메뉴 삭제 성공",
description: "메뉴가 삭제되었습니다.",
});
setMenuToDelete(null);
},
onError: (error) => {
toast({
title: "메뉴 삭제 실패",
description: "메뉴 삭제 중 오류가 발생했습니다.",
variant: "destructive",
});
console.error("Delete menu error:", error);
},
});
const handleMenuSave = (menu: DBMenuItem) => {
const { children, order, ...saveData } = menu;
saveMenuMutation.mutate(saveData);
};
const handleMenuClick = (menu: DBMenuItem) => {
setSelectedMenu(menu);
setIsOpen(true);
};
const handleAddClick = () => {
setSelectedMenu(null);
setIsOpen(true);
};
const handleDeleteClick = (id: string) => {
setMenuToDelete(id);
setDeleteAlertOpen(true);
};
const handleDeleteConfirm = () => {
if (menuToDelete) {
deleteMenuMutation.mutate(menuToDelete);
}
setDeleteAlertOpen(false);
};
const toggleActive = (id: string, value: boolean) => {
toggleActiveMutation.mutate({ id, isActive: value });
};
if (isLoading) return <div>Loading...</div>;
const orderedMenus = addMenuOrder(dbMenuData?.data?.data || []);
return (
<div className="container mx-auto py-6 space-y-6">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold tracking-tight"> </h1>
<p className="text-muted-foreground">
.
</p>
</div>
<Button
onClick={handleAddClick}
disabled={saveMenuMutation.isPending}
>
{saveMenuMutation.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
</>
) : (
<>
<Plus className="mr-2 h-4 w-4" />
</>
)}
</Button>
</div>
<MenusTable
menus={orderedMenus}
toggleActive={toggleActive}
openSections={openSections}
toggleSection={toggleSection}
onMenuClick={handleMenuClick}
onDelete={handleDeleteClick}
/>
<MenuFormDialog
isOpen={isOpen}
onClose={() => setIsOpen(false)}
menuData={selectedMenu || undefined}
onSave={handleMenuSave}
menus={orderedMenus}
/>
<AlertDialog open={deleteAlertOpen} onOpenChange={setDeleteAlertOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle> </AlertDialogTitle>
<AlertDialogDescription>
? .
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={handleDeleteConfirm} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
};
export default MenusPage;