kontenhumas-fe/app/[locale]/(admin)/admin/settings/module-management/page.tsx

502 lines
17 KiB
TypeScript

"use client";
import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { PlusIcon, ModuleIcon, EditIcon, DeleteIcon } from "@/components/icons";
import {
MasterModule,
MasterMenu,
getMasterModules,
getMasterMenus,
getMenuModulesByModuleId,
createMasterModule,
updateMasterModule,
deleteMasterModule,
createMenuModulesBatch,
} from "@/service/menu-modules";
import SiteBreadcrumb from "@/components/site-breadcrumb";
import Swal from "sweetalert2";
import { FormField } from "@/components/form/common/FormField";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { getCookiesDecrypt } from "@/lib/utils";
export default function ModuleManagementPage() {
const router = useRouter();
const [modules, setModules] = useState<MasterModule[]>([]);
const [menus, setMenus] = useState<MasterMenu[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [editingModule, setEditingModule] = useState<MasterModule | null>(null);
const [formData, setFormData] = useState({
name: "",
description: "",
pathUrl: "",
actionType: "",
statusId: 1,
menuIds: [] as number[],
});
useEffect(() => {
// Check if user has roleId = 1
const roleId = getCookiesDecrypt("urie");
if (Number(roleId) !== 1) {
Swal.fire({
title: "Access Denied",
text: "You don't have permission to access this page",
icon: "error",
confirmButtonText: "OK",
customClass: {
popup: 'swal-z-index-9999'
}
}).then(() => {
router.push("/admin/dashboard");
});
return;
}
loadData();
}, [router]);
const loadData = async () => {
setIsLoading(true);
try {
const res = await getMasterModules({ limit: 100 });
if (!res?.error) {
setModules(res?.data?.data || []);
}
} catch (error) {
console.error("Error loading modules:", error);
} finally {
setIsLoading(false);
}
};
const loadMenus = async () => {
try {
const res = await getMasterMenus({ limit: 100 });
if (!res?.error) {
setMenus(res?.data?.data || []);
}
} catch (error) {
console.error("Error loading menus:", error);
}
};
const loadModuleMenus = async (moduleId: number) => {
try {
const res = await getMenuModulesByModuleId(moduleId);
if (!res?.error) {
const menuIds = (res?.data?.data || []).map((mm: any) => mm.menu_id || mm.menuId).filter((id: any) => id);
setFormData((prev) => ({ ...prev, menuIds }));
}
} catch (error) {
console.error("Error loading module menus:", error);
}
};
const handleOpenDialog = async (module?: MasterModule) => {
await loadMenus();
if (module) {
setEditingModule(module);
setFormData({
name: module.name,
description: module.description,
pathUrl: module.pathUrl,
actionType: module.actionType || "",
statusId: module.statusId,
menuIds: [],
});
await loadModuleMenus(module.id);
} else {
setEditingModule(null);
setFormData({
name: "",
description: "",
pathUrl: "",
actionType: "",
statusId: 1,
menuIds: [],
});
}
setIsDialogOpen(true);
};
const handleSave = async () => {
try {
const { menuIds, ...moduleData } = formData;
if (editingModule) {
const res = await updateMasterModule(editingModule.id, moduleData);
if (res?.error) {
Swal.fire({
title: "Error",
text: res?.message || "Failed to update module",
icon: "error",
confirmButtonText: "OK",
customClass: {
popup: 'swal-z-index-9999'
}
});
return;
}
// Update menu associations
if (menuIds && menuIds.length > 0) {
// Create associations for each selected menu
for (const menuId of menuIds) {
try {
await createMenuModulesBatch({
menuId,
moduleIds: [editingModule.id],
});
} catch (err) {
// Ignore duplicate errors, backend should handle it
console.log("Menu association may already exist:", err);
}
}
}
Swal.fire({
title: "Success",
text: "Module updated successfully",
icon: "success",
confirmButtonText: "OK",
customClass: {
popup: 'swal-z-index-9999'
}
});
await loadData();
setIsDialogOpen(false);
} else {
const res = await createMasterModule(moduleData);
if (res?.error) {
Swal.fire({
title: "Error",
text: res?.message || "Failed to create module",
icon: "error",
confirmButtonText: "OK",
customClass: {
popup: 'swal-z-index-9999'
}
});
return;
}
// Get the created module ID from response
const createdModuleId = res?.data?.data?.id || res?.data?.id;
// Create menu associations if menuIds provided
if (createdModuleId && menuIds && menuIds.length > 0) {
for (const menuId of menuIds) {
await createMenuModulesBatch({
menuId,
moduleIds: [createdModuleId],
});
}
}
Swal.fire({
title: "Success",
text: "Module created successfully",
icon: "success",
confirmButtonText: "OK",
customClass: {
popup: 'swal-z-index-9999'
}
});
await loadData();
setIsDialogOpen(false);
}
} catch (error) {
console.error("Error saving module:", error);
Swal.fire({
title: "Error",
text: "An unexpected error occurred",
icon: "error",
confirmButtonText: "OK",
customClass: {
popup: 'swal-z-index-9999'
}
});
}
};
const handleDelete = async (module: MasterModule) => {
const result = await Swal.fire({
title: "Delete Module?",
text: `Are you sure you want to delete "${module.name}"? This action cannot be undone.`,
icon: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete it",
cancelButtonText: "Cancel",
customClass: {
popup: 'swal-z-index-9999'
}
});
if (result.isConfirmed) {
try {
const res = await deleteMasterModule(module.id);
if (res?.error) {
Swal.fire({
title: "Error",
text: res?.message || "Failed to delete module",
icon: "error",
confirmButtonText: "OK",
customClass: {
popup: 'swal-z-index-9999'
}
});
} else {
Swal.fire({
title: "Deleted!",
text: "Module has been deleted.",
icon: "success",
confirmButtonText: "OK",
customClass: {
popup: 'swal-z-index-9999'
}
});
await loadData();
}
} catch (error) {
console.error("Error deleting module:", error);
Swal.fire({
title: "Error",
text: "An unexpected error occurred",
icon: "error",
confirmButtonText: "OK",
customClass: {
popup: 'swal-z-index-9999'
}
});
}
}
};
const roleId = getCookiesDecrypt("urie");
if (Number(roleId) !== 1) {
return null; // Will redirect in useEffect
}
return (
<>
<SiteBreadcrumb />
<div className="container mx-auto p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold text-gray-900">Module Management</h1>
<p className="text-gray-600 mt-2">
Manage system modules and their configurations
</p>
</div>
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<DialogTrigger asChild>
<Button className="flex items-center gap-2" onClick={() => handleOpenDialog()}>
<PlusIcon className="h-4 w-4" />
Create Module
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>
{editingModule ? `Edit Module: ${editingModule.name}` : "Create New Module"}
</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<FormField
label="Module Name"
name="name"
type="text"
placeholder="e.g., View Articles, Create Content"
value={formData.name}
onChange={(value) => setFormData({ ...formData, name: value })}
required
/>
<FormField
label="Description"
name="description"
type="text"
placeholder="Brief description of the module"
value={formData.description}
onChange={(value) => setFormData({ ...formData, description: value })}
required
/>
<FormField
label="Path URL"
name="pathUrl"
type="text"
placeholder="e.g., /api/articles, /api/content"
value={formData.pathUrl}
onChange={(value) => setFormData({ ...formData, pathUrl: value })}
required
/>
<FormField
label="Action Type"
name="actionType"
type="select"
placeholder="Select action type"
value={formData.actionType}
onChange={(value) => setFormData({ ...formData, actionType: value })}
options={[
{ value: "view", label: "View" },
{ value: "create", label: "Create" },
{ value: "update", label: "Update" },
{ value: "delete", label: "Delete" },
{ value: "approve", label: "Approve" },
{ value: "reject", label: "Reject" },
]}
required
/>
<div className="space-y-2">
<Label htmlFor="menuIds">Menus (Optional)</Label>
<p className="text-sm text-gray-500 mb-2">
Select which menus this module belongs to. A module can belong to multiple menus.
</p>
<div className="border rounded-md p-4 max-h-48 overflow-y-auto">
{menus.length > 0 ? (
<div className="space-y-2">
{menus.map((menu) => (
<div key={menu.id} className="flex items-center space-x-2">
<Checkbox
id={`menu-${menu.id}`}
checked={formData.menuIds.includes(menu.id)}
onCheckedChange={(checked) => {
if (checked) {
setFormData({
...formData,
menuIds: [...formData.menuIds, menu.id],
});
} else {
setFormData({
...formData,
menuIds: formData.menuIds.filter((id) => id !== menu.id),
});
}
}}
/>
<Label
htmlFor={`menu-${menu.id}`}
className="text-sm font-normal cursor-pointer"
>
{menu.name}
</Label>
</div>
))}
</div>
) : (
<p className="text-sm text-gray-500">No menus available</p>
)}
</div>
</div>
<FormField
label="Status ID"
name="statusId"
type="number"
placeholder="1"
value={formData.statusId}
onChange={(value) => setFormData({ ...formData, statusId: Number(value) || 1 })}
required
/>
<div className="flex items-center justify-end gap-2 pt-4 border-t">
<Button
variant="outline"
onClick={() => setIsDialogOpen(false)}
>
Cancel
</Button>
<Button onClick={handleSave}>
{editingModule ? "Update" : "Create"} Module
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
{isLoading ? (
<div className="text-center py-12">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
<p className="mt-4 text-gray-600">Loading modules...</p>
</div>
) : modules.length > 0 ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{modules.map((module) => (
<Card key={module.id} className="hover:shadow-lg transition-shadow">
<CardHeader>
<CardTitle className="flex items-center justify-between">
<span className="truncate">{module.name}</span>
{module.isActive ? (
<span className="px-2 py-1 text-xs bg-green-100 text-green-800 rounded-full">
Active
</span>
) : (
<span className="px-2 py-1 text-xs bg-gray-100 text-gray-800 rounded-full">
Inactive
</span>
)}
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2 mb-4">
<div className="text-sm text-gray-600">{module.description}</div>
<div className="text-xs text-gray-500 font-mono bg-gray-50 p-2 rounded">
{module.pathUrl}
</div>
<div className="flex items-center gap-2">
<span className="px-2 py-1 text-xs bg-blue-100 text-blue-800 rounded-full">
{module.actionType}
</span>
</div>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
className="flex-1"
onClick={() => handleOpenDialog(module)}
>
<EditIcon className="h-4 w-4 mr-2" />
Edit
</Button>
<Button
variant="outline"
size="sm"
className="flex-1 text-red-600 hover:text-red-700 hover:bg-red-50"
onClick={() => handleDelete(module)}
>
<DeleteIcon className="h-4 w-4 mr-2" />
Delete
</Button>
</div>
</CardContent>
</Card>
))}
</div>
) : (
<Card>
<CardContent className="flex items-center justify-center py-12">
<div className="text-center">
<ModuleIcon className="h-12 w-12 text-gray-400 mx-auto mb-4" />
<h3 className="text-lg font-medium text-gray-900 mb-2">No Modules Found</h3>
<p className="text-gray-500 mb-4">
Create your first module to define system capabilities
</p>
<Button onClick={() => handleOpenDialog()}>
<PlusIcon className="h-4 w-4 mr-2" />
Create Module
</Button>
</div>
</CardContent>
</Card>
)}
</div>
</>
);
}