add api headermenu and crud management

This commit is contained in:
2026-02-05 00:01:58 +07:00
parent befe6b30aa
commit f25f6b9156
29 changed files with 2058 additions and 634 deletions

View File

@@ -0,0 +1,127 @@
/**
* CMS Component: Buttons
* Overrides Bootstrap buttons to match CMS design language
*/
.btn {
border-radius: var(--border-radius);
font-weight: var(--font-weight-medium);
padding: 0.5rem 1.25rem;
transition: var(--transition-base);
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
height: 42px; /* Standardize height */
}
.btn-sm {
padding: 0.25rem 0.75rem;
font-size: var(--font-size-sm);
height: 32px;
}
.btn-lg {
padding: 0.75rem 1.5rem;
font-size: var(--font-size-lg);
height: 52px;
}
/* Primary Button */
.btn-primary {
background-color: var(--primary-color);
border-color: var(--primary-color);
color: var(--text-white);
}
.btn-primary:hover, .btn-primary:focus {
background-color: var(--primary-dark);
border-color: var(--primary-dark);
color: var(--text-white);
transform: translateY(-1px);
box-shadow: var(--shadow-md);
}
/* Outline Primary */
.btn-outline-primary {
color: var(--primary-color);
border-color: var(--primary-color);
}
.btn-outline-primary:hover {
background-color: var(--primary-color);
color: var(--text-white);
}
/* White / Icon Button */
.btn-white {
background-color: var(--bg-card);
border: 1px solid var(--border-color);
color: var(--text-main);
}
.btn-white:hover {
background-color: #f8f9fa;
border-color: #dee2e6;
box-shadow: var(--shadow-sm);
}
/* Special Button Effects (Shine effect from main.ejs) */
.btn-shine {
position: relative;
overflow: hidden;
}
.btn-shine::after {
content: "";
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
transition: all 0.5s ease;
}
.btn-shine:hover::after {
left: 100%;
}
/* Action Button Group (Like Topbar screenshot) */
.btn-group-action {
background-color: #fff;
border: 1px solid var(--border-color);
border-radius: var(--border-radius-lg);
box-shadow: var(--shadow-sm);
overflow: hidden;
display: inline-flex;
}
.btn-group-action .btn {
border: none;
border-radius: 0;
padding: 0.5rem 0.85rem;
background: transparent;
height: 38px;
width: 42px;
}
.btn-group-action .btn:not(:last-child) {
border-right: 1px solid var(--border-color);
}
.btn-group-action .btn:hover {
background-color: #f8f9fa;
transform: none;
box-shadow: none;
}
/* Icon alignment inside buttons */
.btn i {
font-size: 0.9em;
}
/* Icon specific colors for actions */
.text-action-add { color: #0d6efd !important; }
.text-action-edit { color: #ffc107 !important; }
.text-action-delete { color: #dc3545 !important; }

View File

@@ -0,0 +1,39 @@
/**
* CMS Component: Cards
* Standardizes administrative dashboard cards
*/
.card {
border: 1px solid var(--border-color);
border-radius: var(--border-radius);
box-shadow: var(--shadow-sm);
transition: var(--transition-base);
overflow: hidden;
}
.card:hover {
box-shadow: var(--shadow-md);
}
.card-header {
background-color: #fff;
border-bottom: 1px solid var(--border-color);
padding: var(--spacing-3) var(--spacing-4);
font-weight: var(--font-weight-bold);
}
.card-title {
margin-bottom: 0;
font-size: 1.1rem;
color: var(--text-main);
}
.card-body {
padding: var(--spacing-4);
}
.card-footer {
background-color: #fcfcfc;
border-top: 1px solid var(--border-color);
padding: var(--spacing-2) var(--spacing-4);
}

View File

@@ -0,0 +1,50 @@
/**
* CMS Component: Forms
* Standardizes inputs, labels and validation messages
*/
.form-label {
font-weight: var(--font-weight-medium);
margin-bottom: var(--spacing-2);
color: var(--text-main);
font-size: var(--font-size-sm);
}
.form-control, .form-select {
border-radius: var(--border-radius);
border: 1px solid var(--border-color);
padding: 0.6rem 1rem;
font-size: var(--font-size-base);
transition: var(--transition-base);
}
.form-control:focus, .form-select:focus {
border-color: var(--primary-color);
box-shadow: 0 0 0 0.2rem rgba(188, 159, 105, 0.15);
outline: none;
}
.input-group-text {
background-color: #f8f9fa;
border-color: var(--border-color);
color: var(--text-muted);
}
/* Form Helper Text */
.form-text {
font-size: var(--font-size-xs);
color: var(--text-muted);
margin-top: var(--spacing-1);
}
/* Validation Styles */
.invalid-feedback {
font-size: var(--font-size-xs);
font-weight: var(--font-weight-medium);
}
/* Custom Checkbox/Radio */
.form-check-input:checked {
background-color: var(--primary-color);
border-color: var(--primary-color);
}

View File

@@ -0,0 +1,45 @@
/**
* CMS Component: Modals
* Standardizes modal spacing and appearance
*/
.modal-content {
border: none;
border-radius: var(--border-radius-lg);
box-shadow: var(--shadow-lg);
}
.modal-header {
border-bottom: 1px solid var(--border-color);
padding: var(--spacing-4);
background-color: #fff;
border-radius: var(--border-radius-lg) var(--border-radius-lg) 0 0;
}
.modal-title {
font-weight: var(--font-weight-bold);
color: var(--text-main);
font-size: 1.15rem;
}
.modal-body {
padding: var(--spacing-4);
}
.modal-footer {
border-top: 1px solid var(--border-color);
padding: var(--spacing-3) var(--spacing-4);
gap: var(--spacing-2);
}
/* Modal sizing standards */
.modal-dialog-centered {
display: flex;
align-items: center;
min-height: calc(100% - var(--bs-modal-margin) * 2);
}
/* Fix for backdrop issue reported in previous conversations */
.modal-backdrop.show {
opacity: 0.5;
}

View File

@@ -0,0 +1,41 @@
/**
* CMS Component: Tables
* Standardizes data tables listing
*/
.table {
margin-bottom: 0;
}
.table thead th {
background-color: #f8f9fa;
border-bottom: 2px solid var(--border-color);
color: var(--text-muted);
font-weight: var(--font-weight-bold);
font-size: var(--font-size-xs);
text-transform: uppercase;
letter-spacing: 0.025em;
padding: var(--spacing-3) var(--spacing-4);
}
.table tbody td {
padding: var(--spacing-3) var(--spacing-4);
vertical-align: middle;
border-bottom: 1px solid var(--border-color);
}
.table-hover tbody tr:hover {
background-color: rgba(188, 159, 105, 0.05);
}
/* Badge in table */
.badge {
padding: 0.4em 0.6em;
border-radius: var(--border-radius-sm);
font-weight: var(--font-weight-medium);
}
.bg-soft-success { background-color: var(--success-soft); color: var(--success-color); border: 1px solid rgba(40, 167, 69, 0.2); }
.bg-soft-danger { background-color: var(--danger-soft); color: var(--danger-color); border: 1px solid rgba(220, 53, 69, 0.2); }
.bg-soft-warning { background-color: var(--warning-soft); color: var(--warning-color); border: 1px solid rgba(255, 193, 7, 0.2); }
.bg-soft-info { background-color: var(--info-soft); color: var(--info-color); border: 1px solid rgba(23, 162, 184, 0.2); }

101
assets/css/layout.css Normal file
View File

@@ -0,0 +1,101 @@
/**
* CMS Global Layout
* Navbar, Footer, and Page structures
*/
body {
font-family: var(--font-family);
background-color: var(--bg-body);
min-height: 100vh;
display: flex;
flex-direction: column;
color: var(--text-main);
}
main {
flex: 1;
padding: var(--spacing-4) 0;
}
/* Navbar Customization */
.navbar {
background-color: rgba(255, 255, 255, 0.95);
box-shadow: var(--shadow-header);
padding: 0.75rem 0;
transition: var(--transition-base);
}
.navbar-brand {
font-weight: var(--font-weight-bold);
color: var(--primary-color) !important;
}
.nav-link {
color: var(--text-main);
font-weight: var(--font-weight-medium);
padding: 0.5rem 1rem;
transition: var(--transition-base);
font-size: 0.95rem;
}
.nav-link:hover, .nav-link.active {
color: var(--primary-color) !important;
}
/* Page Containers */
.page-header {
margin-bottom: var(--spacing-4);
}
.page-content {
background-color: var(--bg-card);
padding: var(--spacing-4);
border-radius: var(--border-radius);
box-shadow: var(--shadow-sm);
}
/* Footer Customization */
footer {
background: linear-gradient(90deg, var(--primary-dark), var(--primary-color), var(--primary-light), #d4c4a8);
color: var(--text-white);
margin-top: auto;
padding: var(--spacing-4) 0;
}
footer a {
color: rgba(255, 255, 255, 0.8) !important;
text-decoration: none;
transition: var(--transition-base);
}
footer a:hover {
color: var(--text-white) !important;
}
/* Utility: Fixed Bottom Actions (for Forms/Modals) */
.fixed-bottom-buttons {
position: fixed;
bottom: 0;
right: 0;
padding: var(--spacing-3);
z-index: 1000;
display: flex;
gap: var(--spacing-2);
}
/* Dropdown Customization */
.dropdown-menu {
border: none;
box-shadow: var(--shadow-lg);
border-radius: var(--border-radius);
margin-top: 0.5rem;
}
.dropdown-item:hover {
background-color: var(--primary-soft);
}
.dropdown-item.active {
background-color: var(--primary-color);
color: var(--text-white);
}

67
assets/css/variables.css Normal file
View File

@@ -0,0 +1,67 @@
/**
* CMS Design System Variables
* Standardized colors, spacing, and typography
*/
:root {
/* Primary Colors (Gold/Cinnamon) */
--primary-color: #bc9f69;
--primary-rgb: 188, 159, 105;
--primary-light: #d4c4a8;
--primary-dark: #a68b58;
--primary-soft: rgba(188, 159, 105, 0.1);
/* Secondary Colors */
--secondary-color: #6c757d;
--secondary-soft: rgba(108, 117, 125, 0.1);
/* Status Colors */
--success-color: #28a745;
--success-soft: rgba(40, 167, 69, 0.1);
--warning-color: #ffc107;
--warning-soft: rgba(255, 193, 7, 0.1);
--danger-color: #dc3545;
--danger-soft: rgba(220, 53, 69, 0.1);
--info-color: #17a2b8;
--info-soft: rgba(23, 162, 184, 0.1);
/* Neutral Colors / Backgrounds */
--bg-body: #f5f7fa;
--bg-card: #ffffff;
--bg-header: #ffffff;
--border-color: #e9ecef;
--text-main: #333333;
--text-muted: #6c757d;
--text-white: #ffffff;
/* Typography */
--font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
--font-size-base: 1rem;
--font-size-sm: 0.875rem;
--font-size-xs: 0.75rem;
--font-size-lg: 1.25rem;
--font-weight-normal: 400;
--font-weight-medium: 500;
--font-weight-bold: 700;
/* Spacing & Borders */
--spacing-1: 0.25rem;
--spacing-2: 0.5rem;
--spacing-3: 1rem;
--spacing-4: 1.5rem;
--spacing-5: 3rem;
--border-radius: 8px;
--border-radius-sm: 4px;
--border-radius-lg: 12px;
--border-radius-full: 50px;
/* Shadows & Elevation */
--shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.08);
--shadow-md: 0 4px 6px rgba(0, 0, 0, 0.05);
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
--shadow-header: 0 2px 10px rgba(0, 0, 0, 0.05);
/* Transitions */
--transition-base: all 0.2s ease-in-out;
}

View File

@@ -1,4 +1,24 @@
const Header = require("../models/header");
const HeaderMenu = require("../models/HeaderMenu");
/**
* Helper function to build a tree structure (Mirroring logic in headerMenuController)
*/
const buildTree = (items, parentId = null) => {
const branch = [];
const children = items.filter(item =>
String(item.parentId) === String(parentId) || (item.parentId === null && parentId === null)
);
for (const child of children) {
const item = child.toObject ? child.toObject() : { ...child };
const subChildren = buildTree(items, item._id);
item.children = subChildren.length > 0 ? subChildren : [];
branch.push(item);
}
return branch.sort((a, b) => a.order - b.order);
};
// Admin: Render header management page
exports.index = async (req, res) => {
@@ -30,11 +50,23 @@ exports.index = async (req, res) => {
logo: "",
};
const activeTab = req.query.tab || "topbar";
// Always fetch menu items to ensure they are available even if the user
// switches tabs client-side
const items = await HeaderMenu.find().sort({ order: 1 });
const menuData = {
flat: items,
tree: buildTree(items)
};
res.render("admin/header/index", {
layout: "layouts/main",
title: "Header Management",
user: req.session.user,
user: req.session.user || null,
data: data,
activeTab: activeTab,
menuData: menuData
});
} catch (error) {
console.error("Error loading header management:", error);

View File

@@ -0,0 +1,175 @@
const HeaderMenu = require("../models/HeaderMenu");
const slugify = require("slugify");
/**
* Helper: Build tree structure from flat array
*/
const buildMenuTree = (items, parentId = null, isPublic = false) => {
const branch = [];
const children = items.filter(item =>
String(item.parentId) === String(parentId) || (item.parentId === null && parentId === null)
);
for (const child of children) {
const item = child.toObject ? child.toObject() : { ...child };
// Clean data for public API if requested
let cleanItem = item;
if (isPublic) {
cleanItem = {
id: item._id,
title: item.title,
url: item.url,
type: item.type
};
}
const subChildren = buildMenuTree(items, item._id, isPublic);
cleanItem.children = subChildren.length > 0 ? subChildren : [];
branch.push(cleanItem);
}
return branch.sort((a, b) => a.order - b.order);
};
/**
* Helper: Recursive delete children
*/
const deleteRecursive = async (parentId) => {
const children = await HeaderMenu.find({ parentId });
for (const child of children) {
await deleteRecursive(child._id);
await HeaderMenu.findByIdAndDelete(child._id);
}
};
// 1. Render Menu Tab logic (called from Header index or directly if route allows)
exports.renderMenuTab = async (req, res) => {
try {
const items = await HeaderMenu.find().sort({ order: 1 });
const menuTree = buildMenuTree(items);
return { menuTree, flatItems: items };
} catch (error) {
console.error("Error fetching menu items:", error);
throw error;
}
};
// 2. Create Menu Item
exports.createMenu = async (req, res) => {
try {
console.log('=== BACKEND: createMenu hit ===');
console.log('Body:', req.body);
const { title, url, parentId, order, status, type } = req.body;
const slug = slugify(title, { lower: true, strict: true });
const newItem = new HeaderMenu({
title,
slug,
url,
parentId: parentId || null,
order: order || 0,
status: status || "active",
type: type || "internal"
});
const savedItem = await newItem.save();
console.log('=== MENU CREATED ===', savedItem);
req.flash("success_msg", "Menu item created successfully");
res.redirect("/admin/header?tab=menu");
} catch (error) {
console.error('=== CREATE MENU ERROR ===', error);
req.flash("error_msg", "Failed to create menu item: " + error.message);
res.redirect("/admin/header?tab=menu");
}
};
// 3. Update Menu Item
exports.updateMenu = async (req, res) => {
try {
const { id } = req.params;
console.log('=== BACKEND: updateMenu hit ===', { id });
console.log('Body:', req.body);
const { title, url, parentId, order, status, type } = req.body;
const updateData = {
url,
parentId: parentId || null,
order,
status,
type
};
if (title) {
updateData.title = title;
updateData.slug = slugify(title, { lower: true, strict: true });
}
const updated = await HeaderMenu.findByIdAndUpdate(id, updateData, { new: true });
if (!updated) {
console.log('=== UPDATE MENU NOT FOUND ===', id);
req.flash("error_msg", "Menu item not found");
} else {
console.log('=== MENU UPDATED ===', updated);
req.flash("success_msg", "Menu item updated successfully");
}
res.redirect("/admin/header?tab=menu");
} catch (error) {
console.error('=== UPDATE MENU ERROR ===', error);
req.flash("error_msg", "Update failed: " + error.message);
res.redirect("/admin/header?tab=menu");
}
};
// 4. Delete Menu Item (Cascade delete children)
exports.deleteMenu = async (req, res) => {
try {
const { id } = req.body;
const menuId = id || req.params.id;
console.log('=== BACKEND: deleteMenu hit ===', { menuId, body: req.body });
await deleteRecursive(menuId);
await HeaderMenu.findByIdAndDelete(menuId);
console.log('=== MENU DELETED ===', menuId);
req.flash("success_msg", "Menu item and its sub-menu deleted successfully");
res.redirect("/admin/header?tab=menu");
} catch (error) {
console.error('=== DELETE MENU ERROR ===', error);
req.flash("error_msg", "Delete failed: " + error.message);
res.redirect("/admin/header?tab=menu");
}
};
// 5. Reorder Menu
exports.reorderMenu = async (req, res) => {
try {
const { items } = req.body; // Array of { id, order, parentId }
if (items && Array.isArray(items)) {
const bulkOps = items.map(item => ({
updateOne: {
filter: { _id: item.id },
update: { order: item.order, parentId: item.parentId || null }
}
}));
await HeaderMenu.bulkWrite(bulkOps);
return res.json({ success: true, message: "Reordered successfully" });
}
res.status(400).json({ success: false, message: "Invalid data" });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
};
// Public API: Get active menu as clean tree
exports.api = async (req, res) => {
try {
const items = await HeaderMenu.find({ status: "active" }).sort({ order: 1 });
const tree = buildMenuTree(items, null, true);
res.json({ success: true, data: tree });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
};

184
data/header-menu.json Normal file
View File

@@ -0,0 +1,184 @@
[
{
"label": "Home",
"slug": "home",
"href": "/",
"type": "internal",
"order": 1,
"isActive": true,
"children": []
},
{
"label": "About Us",
"slug": "about-us",
"href": "/about",
"type": "internal",
"order": 2,
"isActive": true,
"children": []
},
{
"label": "Pages",
"slug": "pages",
"href": "#",
"type": "internal",
"order": 3,
"isActive": true,
"children": [
{
"label": "Services",
"slug": "services",
"href": "/services",
"type": "internal",
"order": 1,
"isActive": true,
"children": [
{
"label": "Service List",
"slug": "service-list",
"href": "/service",
"type": "internal",
"order": 1,
"isActive": true
},
{
"label": "Service Details",
"slug": "service-details",
"href": "/service-details",
"type": "internal",
"order": 2,
"isActive": true
}
]
},
{
"label": "Country List",
"slug": "country-list",
"href": "/country-list",
"type": "internal",
"order": 2,
"isActive": true,
"children": [
{
"label": "Country List",
"slug": "country-list-all",
"href": "/country-list",
"type": "internal",
"order": 1,
"isActive": true
},
{
"label": "Country Details",
"slug": "country-details",
"href": "/country-details",
"type": "internal",
"order": 2,
"isActive": true
}
]
},
{
"label": "Our Pricing",
"slug": "pricing",
"href": "/pricing",
"type": "internal",
"order": 3,
"isActive": true
},
{
"label": "Appointment",
"slug": "appointment",
"href": "/appointment",
"type": "internal",
"order": 4,
"isActive": true
},
{
"label": "FAQ",
"slug": "faq",
"href": "/faq",
"type": "internal",
"order": 5,
"isActive": true
}
]
},
{
"label": "VISA",
"slug": "visa",
"href": "#",
"type": "internal",
"order": 4,
"isActive": true,
"children": [
{
"label": "Visa List",
"slug": "visa-list",
"href": "/visa-list",
"type": "internal",
"order": 1,
"isActive": true
},
{
"label": "Visa Details",
"slug": "visa-details",
"href": "/visa-details",
"type": "internal",
"order": 2,
"isActive": true
}
]
},
{
"label": "Blog",
"slug": "blog",
"href": "#",
"type": "internal",
"order": 5,
"isActive": true,
"children": [
{
"label": "Blog Grid",
"slug": "blog-grid",
"href": "/blog-grid",
"type": "internal",
"order": 1,
"isActive": true
},
{
"label": "Blog Standard",
"slug": "blog-standard",
"href": "/blog",
"type": "internal",
"order": 2,
"isActive": true
},
{
"label": "Blog Details",
"slug": "blog-details",
"href": "/blog-details",
"type": "internal",
"order": 3,
"isActive": true
}
]
},
{
"label": "Contact Us",
"slug": "contact-us",
"href": "/contact",
"type": "internal",
"order": 6,
"isActive": true,
"children": []
},
{
"label": "External Portal",
"slug": "external-portal",
"href": "https://partner.hailearning.edu.vn",
"type": "external",
"order": 7,
"isActive": false,
"children": []
}
]

View File

@@ -48,95 +48,5 @@
"workingHours": "Mod-Friday, 09am - 05pm",
"phone": "+09 378 357 5222"
}
},
"menu": [
{
"label": "Home",
"href": "/",
"children": []
},
{
"label": "About Us",
"href": "/about",
"children": []
},
{
"label": "Pages",
"href": "#",
"children": [
{
"label": "Service",
"href": "/service",
"children": [
{
"label": "Service",
"href": "/service"
},
{
"label": "Service Details",
"href": "/service-details"
}
]
},
{
"label": "Country List",
"href": "/country-list",
"children": [
{
"label": "Country List",
"href": "/country-list"
},
{
"label": "Country Details",
"href": "/country-details"
}
]
},
{
"label": "Our Pricing",
"href": "/pricing"
},
{
"label": "Appointment",
"href": "/appointment"
}
]
},
{
"label": "VISA",
"href": "#",
"children": [
{
"label": "Visa List",
"href": "/visa-list"
},
{
"label": "Visa Details",
"href": "/visa-details"
}
]
},
{
"label": "Blog",
"href": "#",
"children": [
{
"label": "Blog Grid",
"href": "/blog-grid"
},
{
"label": "Blog Standard",
"href": "/blog"
},
{
"label": "Blog Details",
"href": "/blog-details"
}
]
},
{
"label": "Contact Us",
"href": "/contact"
}
]
}

48
models/HeaderMenu.js Normal file
View File

@@ -0,0 +1,48 @@
const mongoose = require('mongoose');
const HeaderMenuSchema = new mongoose.Schema({
title: {
type: String,
required: true,
trim: true
},
slug: {
type: String,
required: true,
trim: true,
lowercase: true
},
url: {
type: String,
required: true,
trim: true
},
parentId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'HeaderMenu',
default: null
},
order: {
type: Number,
default: 0
},
status: {
type: String,
enum: ['active', 'inactive'],
default: 'active'
},
type: {
type: String,
enum: ['internal', 'external'],
default: 'internal'
}
}, {
timestamps: true
});
// Indexes for optimization
HeaderMenuSchema.index({ order: 1 });
HeaderMenuSchema.index({ status: 1 });
HeaderMenuSchema.index({ parentId: 1, order: 1 }); // Useful for fetching children in order
module.exports = mongoose.model('HeaderMenu', HeaderMenuSchema);

Binary file not shown.

After

Width:  |  Height:  |  Size: 331 KiB

BIN
public/img/Logo_round.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 331 KiB

31
public/js/custom-modal.js Normal file
View File

@@ -0,0 +1,31 @@
/**
* Custom Modal Utilities
*/
// Global function to clean up any stuck modal backdrops
window.forceCleanupModals = function() {
document.body.classList.remove('modal-open');
document.body.style.overflow = '';
document.body.style.paddingRight = '';
const backdrops = document.querySelectorAll('.modal-backdrop, .overlay, .loading');
if (backdrops.length > 0) {
console.warn('Cleanup: Removing backdrops:', backdrops.length);
backdrops.forEach(el => el.remove());
}
};
// Auto-cleanup on hide
document.addEventListener('hidden.bs.modal', () => {
setTimeout(forceCleanupModals, 100);
});
// Watchdog
setInterval(() => {
if (document.querySelectorAll('.modal.show').length === 0) {
if (document.querySelectorAll('.modal-backdrop').length > 0) {
forceCleanupModals();
}
}
}, 2000);
window.addEventListener('load', forceCleanupModals);

View File

@@ -0,0 +1,27 @@
/**
* Flash Message Handler
* Displays server-side flash messages using showToast
*/
document.addEventListener('DOMContentLoaded', () => {
const flashDataEl = document.getElementById('flash-messages-data');
if (flashDataEl) {
try {
const messages = JSON.parse(flashDataEl.textContent);
if (messages.success_msg) {
showToast('Success', messages.success_msg, 'success');
}
if (messages.error_msg) {
showToast('Error', messages.error_msg, 'error');
}
if (messages.error) {
showToast('Error', messages.error, 'error');
}
} catch (e) {
console.error('Error parsing flash messages data:', e);
}
}
});

56
public/js/main.js Normal file
View File

@@ -0,0 +1,56 @@
/**
* Global Admin Scripts
*/
console.log('CMS Admin Main JS loaded');
// Helper to handle AJAX form submissions with confirmation or loading state
window.handleFormAjax = async (formEl, options = {}) => {
const {
confirmMessage = null,
onSuccess = null,
onError = null,
loaderBtn = null
} = options;
if (confirmMessage && !confirm(confirmMessage)) {
return false;
}
const formData = new FormData(formEl);
const data = Object.fromEntries(formData.entries());
const originalBtnHtml = loaderBtn ? loaderBtn.innerHTML : null;
try {
if (loaderBtn) {
loaderBtn.disabled = true;
loaderBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Processing...';
}
const response = await fetch(formEl.action, {
method: formEl.method || 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const result = await response.json();
if (result.success) {
if (onSuccess) onSuccess(result);
else showToast('Success', result.message || 'Operation successful', 'success');
} else {
if (onError) onError(result);
else showToast('Error', result.message || 'Operation failed', 'error');
}
} catch (error) {
console.error('AJAX Error:', error);
showToast('Error', 'A network error occurred', 'error');
} finally {
if (loaderBtn) {
loaderBtn.disabled = false;
loaderBtn.innerHTML = originalBtnHtml;
}
}
};

74
public/js/toast.js Normal file
View File

@@ -0,0 +1,74 @@
/**
* Toast Notification System
* Requires Bootstrap 5 JS
*/
function showToast(title, message, type = 'info') {
// Create container if not exists
let toastContainer = document.getElementById('toast-container');
if (!toastContainer) {
toastContainer = document.createElement('div');
toastContainer.id = 'toast-container';
toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
toastContainer.style.zIndex = '1100';
document.body.appendChild(toastContainer);
}
// Inject CSS for transition if not already present
if (!document.getElementById('toast-animation-styles')) {
const style = document.createElement('style');
style.id = 'toast-animation-styles';
style.innerHTML = `
@keyframes slideInRight {
from { transform: translateX(100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
.toast-slide-in {
animation: slideInRight 0.3s ease-out forwards;
}
`;
document.head.appendChild(style);
}
// Map type to Bootstrap color class
const bgClass = type === 'success' ? 'bg-success' : (type === 'error' || type === 'danger' ? 'bg-danger' : 'bg-info');
// Create toast element
const toastEl = document.createElement('div');
toastEl.className = `toast align-items-center text-white ${bgClass} border-0 mb-2 toast-slide-in`;
toastEl.setAttribute('role', 'alert');
toastEl.setAttribute('aria-live', 'assertive');
toastEl.setAttribute('aria-atomic', 'true');
toastEl.innerHTML = `
<div class="d-flex">
<div class="toast-body">
<div class="d-flex align-items-center">
<i class="fas ${type === 'success' ? 'fa-check-circle' : (type === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle')} me-2"></i>
<div>
<strong class="me-auto">${title}</strong><br>
${message}
</div>
</div>
</div>
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
`;
toastContainer.appendChild(toastEl);
// Initialize and show
const bsToast = new bootstrap.Toast(toastEl, { autohide: true, delay: 5000 });
bsToast.show();
// Remove from DOM when hidden
toastEl.addEventListener('hidden.bs.toast', () => {
toastEl.remove();
});
}
// Map showNotification to showToast for backward compatibility
window.showNotification = function(message, type) {
const title = type === 'success' ? 'Success' : (type === 'error' ? 'Error' : 'Notification');
showToast(title, message, type);
};

View File

@@ -24,6 +24,7 @@ const insuranceController = require("../controllers/insuranceController");
const activityController = require("../controllers/activityController");
const bookingSubmissionController = require("../controllers/bookingSubmissionController");
const serviceController = require("../controllers/serviceController");
const headerMenuController = require("../controllers/headerMenuController");
// Blog controllers
const blogController = require("../controllers/blogController");
@@ -75,6 +76,7 @@ router.post("/upload/video", ensureAuthenticated, uploadVideo.single("video"), u
router.post("/upload/update-path", ensureAuthenticated, uploadController.updateImagePath);
router.post("/upload/delete", ensureAuthenticated, uploadController.deleteImage);
// Header routes
// Header routes
router.get("/header", ensureAuthenticated, headerController.index);
router.post("/header/update", ensureAuthenticated, headerController.update);
@@ -86,6 +88,12 @@ router.get("/header/data", ensureAuthenticated, headerController.getHeaderData);
router.patch("/header/:id/status", ensureAuthenticated, headerController.updateStatus);
router.delete("/header/:id", ensureAuthenticated, headerController.destroy);
// Header Menu INTEGRATED routes
router.post("/header/menu/create", ensureAuthenticated, headerMenuController.createMenu);
router.post("/header/menu/update/:id", ensureAuthenticated, headerMenuController.updateMenu);
router.post("/header/menu/delete", ensureAuthenticated, headerMenuController.deleteMenu);
router.post("/header/menu/reorder", ensureAuthenticated, headerMenuController.reorderMenu);
// Footer routes
router.get("/footer", ensureAuthenticated, footerController.index);
router.post("/footer/update", ensureAuthenticated, footerController.update);

View File

@@ -10,6 +10,7 @@ const footerController = require("../controllers/footerController");
const contactController = require("../controllers/contactController");
const faqController = require("../controllers/faqController");
const visaController = require("../controllers/visaController");
const headerMenuController = require("../controllers/headerMenuController");
const safetyController = require("../controllers/safetyController");
const campLocationController = require("../controllers/campLocationController");
// Booking flow removed
@@ -51,6 +52,9 @@ router.get("/api/header", headerController.api);
// Menu Tree API route (for frontend)
router.get("/api/menu-tree", headerController.getMenuTreeAPI);
// Header Menu New Module API
router.get("/api/header-menu", headerMenuController.api);
// Social Links API routes
router.get("/api/social-links", socialLinkController.getAll);
router.get("/api/social-links/:platform", socialLinkController.show);

View File

@@ -0,0 +1,69 @@
const mongoose = require('mongoose');
const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');
const HeaderMenu = require('../models/HeaderMenu');
dotenv.config();
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/SIMS';
async function connectDB() {
try {
await mongoose.connect(MONGODB_URI);
console.log('✅ MongoDB Connected for Migration');
} catch (err) {
console.error('❌ MongoDB Connection Error:', err);
process.exit(1);
}
}
const processMenuItems = async (items, parentId = null) => {
for (const item of items) {
console.log(` > Importing: ${item.label}`);
const menuDoc = {
title: item.label,
slug: item.slug,
url: item.href,
parentId: parentId,
order: item.order || 0,
status: item.isActive === false ? "inactive" : "active",
type: item.type === "external" ? "external" : "internal"
};
const createdItem = await HeaderMenu.create(menuDoc);
if (item.children && item.children.length > 0) {
await processMenuItems(item.children, createdItem._id);
}
}
};
async function migrate() {
await connectDB();
try {
console.log('--- Starting Header Menu Migration ---');
// 1. Clear existing menu items
await HeaderMenu.deleteMany({});
console.log('🗑️ Cleared existing HeaderMenu collection');
// 2. Read JSON data
const dataPath = path.join(__dirname, '../data/header-menu.json');
const fileData = fs.readFileSync(dataPath, 'utf8');
const menuItems = JSON.parse(fileData);
// 3. Recursive import
await processMenuItems(menuItems);
console.log('--- Migration Completed Successfully ---');
process.exit(0);
} catch (error) {
console.error('❌ Migration Failed:', error);
process.exit(1);
}
}
migrate();

View File

@@ -44,6 +44,9 @@ app.use(
express.static(path.join(__dirname, "assets")),
);
// Serve public folder at root (for /js, /img, etc.)
app.use(express.static(path.join(__dirname, "public")));
// Serve uploads folder
app.use(
"/uploads",

View File

@@ -8,6 +8,7 @@
</div>
<div class="card-body p-0">
<div class="row g-0">
<!-- Home -->
<div class="col-md-4 border-end">
<div class="p-4">
<div class="d-flex align-items-center mb-3">
@@ -26,6 +27,7 @@
</div>
</div>
<!-- Header & Menu -->
<div class="col-md-4 border-end">
<div class="p-4">
<div class="d-flex align-items-center mb-3">
@@ -44,6 +46,7 @@
</div>
</div>
<!-- Footer -->
<div class="col-md-4">
<div class="p-4">
<div class="d-flex align-items-center mb-3">
@@ -62,6 +65,7 @@
</div>
</div>
<!-- About Us -->
<div class="col-md-4 border-end border-top">
<div class="p-4">
<div class="d-flex align-items-center mb-3">
@@ -80,6 +84,7 @@
</div>
</div>
<!-- Contact -->
<div class="col-md-4 border-end border-top">
<div class="p-4">
<div class="d-flex align-items-center mb-3">
@@ -98,6 +103,7 @@
</div>
</div>
<!-- FAQ -->
<div class="col-md-4 border-top">
<div class="p-4">
<div class="d-flex align-items-center mb-3">
@@ -116,6 +122,7 @@
</div>
</div>
<!-- Appointment -->
<div class="col-md-4 border-end border-top">
<div class="p-4">
<div class="d-flex align-items-center mb-3">
@@ -134,6 +141,7 @@
</div>
</div>
<!-- Pricing -->
<div class="col-md-4 border-end border-top">
<div class="p-4">
<div class="d-flex align-items-center mb-3">
@@ -152,7 +160,8 @@
</div>
</div>
<div class="col-md-4 border-end border-top">
<!-- Terms & Conditions -->
<div class="col-md-4 border-top">
<div class="p-4">
<div class="d-flex align-items-center mb-3">
<div class="rounded-circle d-flex align-items-center justify-content-center me-3"
@@ -164,15 +173,13 @@
<p class="text-muted mb-0 small">Manage terms</p>
</div>
</div>
<a
href="/admin/terms-conditions"
class="btn btn-sm btn-primary w-100 mt-2"
>
<a href="/admin/terms-conditions" class="btn btn-sm btn-primary w-100 mt-2">
<i class="fas fa-edit me-2"></i>Edit
</a>
</div>
</div>
<!-- Travel -->
<div class="col-md-4 border-end border-top">
<div class="p-4">
<div class="d-flex align-items-center mb-3">
@@ -191,7 +198,8 @@
</div>
</div>
<div class="col-md-4 border-top">
<!-- Safety -->
<div class="col-md-4 border-end border-top">
<div class="p-4">
<div class="d-flex align-items-center mb-3">
<div class="rounded-circle d-flex align-items-center justify-content-center me-3"
@@ -209,7 +217,8 @@
</div>
</div>
<div class="col-md-4 border-end border-top">
<!-- Camp Location -->
<div class="col-md-4 border-top">
<div class="p-4">
<div class="d-flex align-items-center mb-3">
<div class="rounded-circle d-flex align-items-center justify-content-center me-3"
@@ -221,16 +230,14 @@
<p class="text-muted mb-0 small">Manage camp location</p>
</div>
</div>
<a
href="/admin/camp-location"
class="btn btn-sm btn-primary w-100 mt-2"
>
<a href="/admin/camp-location" class="btn btn-sm btn-primary w-100 mt-2">
<i class="fas fa-edit me-2"></i>Edit
</a>
</div>
</div>
<div class="col-md-4 border-top">
<!-- Activities -->
<div class="col-md-4 border-end border-top">
<div class="p-4">
<div class="d-flex align-items-center mb-3">
<div class="rounded-circle d-flex align-items-center justify-content-center me-3"
@@ -247,21 +254,14 @@
</a>
</div>
</div>
<!-- Services -->
<div class="col-md-4 border-end border-top">
<div class="p-4">
<div class="d-flex align-items-center mb-3">
<div
class="rounded-circle d-flex align-items-center justify-content-center me-3"
style="
width: 50px;
height: 50px;
background-color: rgba(184, 183, 106, 0.1);
"
>
<i
class="fas fa-running fa-lg"
style="color: var(--primary-color)"
></i>
<div class="rounded-circle d-flex align-items-center justify-content-center me-3"
style="width: 50px; height: 50px; background-color: rgba(184, 183, 106, 0.1);">
<i class="fas fa-concierge-bell fa-lg" style="color: var(--primary-color);"></i>
</div>
<div>
<h5 class="mb-0">Services</h5>
@@ -273,6 +273,8 @@
</a>
</div>
</div>
<!-- Blog -->
<div class="col-md-4 border-top">
<div class="p-4">
<div class="d-flex align-items-center mb-3">
@@ -638,12 +640,12 @@
<div class="d-flex align-items-center">
<div class="rounded-circle d-flex align-items-center justify-content-center me-2"
style="width: 32px; height: 32px; background-color: rgba(184, 183, 106, 0.1);">
<i class="fas fa-campground" style="color: var(--primary-color);"></i>
<i class="fas fa-blog" style="color: var(--primary-color);"></i>
</div>
<span>Camp Location API</span>
<span>Blog API</span>
</div>
</td>
<td><code>/api/camp-location</code></td>
<td><code>/api/blog</code></td>
<td>
<span
class="badge"
@@ -651,10 +653,10 @@
>GET</span
>
</td>
<td>API to get camp location data</td>
<td>API to get blog posts</td>
<td>
<a
href="/api/camp-location"
href="/api/blog"
class="btn btn-sm btn-outline-primary"
target="_blank"
>
@@ -687,6 +689,7 @@
style="width: 40px; height: 40px; background-color: rgba(184, 183, 106, 0.1);">
<i class="fas fa-info-circle" style="color: var(--primary-color);"></i>
</div>
</div>
<div>
<div class="text-muted small">Version</div>
<div class="fw-bold" style="color: var(--primary-color)">

View File

@@ -196,7 +196,7 @@
<div class="card border shadow-sm">
<div class="card-header bg-light d-flex justify-content-between align-items-center">
<h6 class="mb-0">Footer Columns</h6>
<button type="button" class="btn btn-outline-primary btn-sm" id="addColumn">
<button type="button" class="btn btn-primary btn-sm" id="addColumn">
<i class="fas fa-plus me-1"></i>Add Column
</button>
</div>
@@ -208,12 +208,13 @@
<div class="d-flex justify-content-between align-items-center">
<h6 class="mb-0">Column <%= columnIndex + 1 %>
</h6>
<button type="button" class="btn btn-outline-danger btn-sm remove-column"
data-column-index="<%= columnIndex %>">
<i class="fas fa-trash"></i>
<div class="btn-group-action">
<button type="button" class="btn btn-sm remove-column" data-column-index="<%= columnIndex %>">
<i class="fas fa-trash text-action-delete"></i>
</button>
</div>
</div>
</div>
<div class="card-body">
<div class="row mb-3">
<div class="col-md-6">
@@ -244,20 +245,20 @@
name="columns[<%= columnIndex %>][links][<%= linkIndex %>][url]"
value="<%= link.url %>" placeholder="/about-us/" />
</div>
<div class="col-md-1">
<label class="form-label form-label-sm">&nbsp;</label>
<button type="button"
class="btn btn-outline-danger btn-sm w-100 remove-link"
<div class="col-md-1 d-flex justify-content-end align-items-end">
<div class="btn-group-action">
<button type="button" class="btn btn-sm remove-link"
data-column-index="<%= columnIndex %>" data-link-index="<%= linkIndex %>">
<i class="fas fa-trash"></i>
<i class="fas fa-trash text-action-delete"></i>
</button>
</div>
</div>
</div>
</div>
</div>
<% }); %>
</div>
<button type="button" class="btn btn-outline-primary btn-sm add-link"
<button type="button" class="btn btn-primary btn-sm add-link"
data-column-index="<%= columnIndex %>">
<i class="fas fa-plus me-1"></i>Add Link
</button>
@@ -276,7 +277,7 @@
<div class="card border shadow-sm">
<div class="card-header bg-light d-flex justify-content-between align-items-center">
<h6 class="mb-0">Social Media Links</h6>
<button type="button" class="btn btn-outline-primary btn-sm" id="addSocialLink">
<button type="button" class="btn btn-primary btn-sm" id="addSocialLink">
<i class="fas fa-plus me-1"></i>Add Social Link
</button>
</div>
@@ -301,16 +302,17 @@
<input type="text" class="form-control" name="social[links][<%= index %>][icon]"
value="<%= link.icon %>" />
</div>
<div class="col-md-1">
<label class="form-label">&nbsp;</label>
<button type="button" class="btn btn-outline-danger btn-sm w-100 remove-social-link"
<div class="col-md-1 d-flex justify-content-end align-items-end">
<div class="btn-group-action">
<button type="button" class="btn btn-sm remove-social-link"
data-social-index="<%= index %>">
<i class="fas fa-trash"></i>
<i class="fas fa-trash text-action-delete"></i>
</button>
</div>
</div>
</div>
</div>
</div>
<% }); %>
</div>
</div>
@@ -341,13 +343,11 @@
<!-- Move buttons to fixed bottom -->
<div class="fixed-bottom-buttons">
<button type="reset" class="btn btn-secondary">
<i class="fas fa-undo"></i>
<span>Reset</span>
<button type="reset" class="btn btn-secondary px-4">
<i class="fas fa-undo me-1"></i>Reset
</button>
<button type="submit" class="btn btn-primary">
<i class="fas fa-save"></i>
<span>Save Changes</span>
<button type="submit" class="btn btn-primary px-4">
<i class="fas fa-save me-1"></i>Save Changes
</button>
</div>
</form>
@@ -433,11 +433,13 @@
<div class="card-header bg-light">
<div class="d-flex justify-content-between align-items-center">
<h6 class="mb-0">Column ${columnIndex + 1}</h6>
<button type="button" class="btn btn-outline-danger btn-sm remove-column" data-column-index="${columnIndex}">
<i class="fas fa-trash"></i>
<div class="btn-group-action">
<button type="button" class="btn btn-sm remove-column" data-column-index="${columnIndex}">
<i class="fas fa-trash text-action-delete"></i>
</button>
</div>
</div>
</div>
<div class="card-body">
<div class="row mb-3">
<div class="col-md-6">
@@ -451,7 +453,7 @@
<h6 class="fw-medium mb-3">Links</h6>
<div class="column-links-container" data-column-index="${columnIndex}">
</div>
<button type="button" class="btn btn-outline-primary btn-sm add-link" data-column-index="${columnIndex}">
<button type="button" class="btn btn-primary btn-sm add-link" data-column-index="${columnIndex}">
<i class="fas fa-plus me-1"></i>Add Link
</button>
</div>
@@ -485,14 +487,15 @@
<label class="form-label fw-medium">Icon Class</label>
<input type="text" class="form-control" name="social[links][${socialLinkIndex}][icon]" value="">
</div>
<div class="col-md-1">
<label class="form-label">&nbsp;</label>
<button type="button" class="btn btn-outline-danger btn-sm w-100 remove-social-link" data-social-index="${socialLinkIndex}">
<i class="fas fa-trash"></i>
<div class="col-md-1 d-flex justify-content-end align-items-end">
<div class="btn-group-action">
<button type="button" class="btn btn-sm remove-social-link" data-social-index="${socialLinkIndex}">
<i class="fas fa-trash text-action-delete"></i>
</button>
</div>
</div>
</div>
</div>
`;
container.appendChild(newLink);
socialLinkIndex++;
@@ -535,14 +538,15 @@
<label class="form-label form-label-sm">URL</label>
<input type="text" class="form-control form-control-sm" name="columns[${columnIndex}][links][${linkIndex}][url]" value="" placeholder="/about-us/">
</div>
<div class="col-md-1">
<label class="form-label form-label-sm">&nbsp;</label>
<button type="button" class="btn btn-outline-danger btn-sm w-100 remove-link" data-column-index="${columnIndex}" data-link-index="${linkIndex}">
<i class="fas fa-trash"></i>
<div class="col-md-1 d-flex justify-content-end align-items-end">
<div class="btn-group-action">
<button type="button" class="btn btn-sm remove-link" data-column-index="${columnIndex}" data-link-index="${linkIndex}">
<i class="fas fa-trash text-action-delete"></i>
</button>
</div>
</div>
</div>
</div>
`;
container.appendChild(newLink);
}

View File

@@ -10,12 +10,7 @@
<div class="row">
<div class="col-12">
<form
action="/admin/header/update"
method="POST"
class="content-with-fixed-buttons"
id="headerForm"
>
<div class="content-with-fixed-buttons">
<!-- Hidden inputs for JSON data -->
<input type="hidden" name="topbarJson" id="topbarJson" />
<input type="hidden" name="logo" id="logoInput" />
@@ -28,7 +23,7 @@
<ul class="nav nav-tabs card-header-tabs" role="tablist">
<li class="nav-item">
<a
class="nav-link active"
class="nav-link <%= activeTab === 'topbar' ? 'active' : '' %>"
data-bs-toggle="tab"
href="#topbar"
role="tab"
@@ -38,7 +33,7 @@
</li>
<li class="nav-item">
<a
class="nav-link"
class="nav-link <%= activeTab === 'logo' ? 'active' : '' %>"
data-bs-toggle="tab"
href="#logo"
role="tab"
@@ -48,7 +43,7 @@
</li>
<li class="nav-item">
<a
class="nav-link"
class="nav-link <%= activeTab === 'menu' ? 'active' : '' %>"
data-bs-toggle="tab"
href="#menu"
role="tab"
@@ -62,7 +57,7 @@
<div class="card-body">
<div class="tab-content">
<!-- Topbar Tab -->
<div class="tab-pane fade show active" id="topbar" role="tabpanel">
<div class="tab-pane fade <%= activeTab === 'topbar' ? 'show active' : '' %>" id="topbar" role="tabpanel">
<div class="row g-4">
<!-- Contact Information -->
<div class="col-md-12">
@@ -112,23 +107,22 @@
<!-- Social Links -->
<div class="col-md-12">
<div class="card border shadow-sm">
<div class="card-header bg-white">
<div class="card-header bg-white d-flex justify-content-between align-items-center">
<h6 class="mb-0">
<i class="fas fa-share-alt me-2"></i>Social Media Links
<small class="text-muted ms-2">(Drag to reorder)</small>
</h6>
<button
type="button"
class="btn btn-primary btn-sm"
id="addSocialLink"
>
<i class="fas fa-plus me-1"></i>Add Social Link
</button>
</div>
<div class="card-body">
<div id="socialLinksContainer" class="social-links-sortable">
<!-- Social links will be populated here -->
</div>
<button
type="button"
class="btn btn-outline-primary btn-sm"
id="addSocialLink"
>
<i class="fas fa-plus me-1"></i>Add Social Link
</button>
</div>
</div>
</div>
@@ -136,7 +130,7 @@
</div>
<!-- Logo Tab -->
<div class="tab-pane fade" id="logo" role="tabpanel">
<div class="tab-pane fade <%= activeTab === 'logo' ? 'show active' : '' %>" id="logo" role="tabpanel">
<div class="row g-4">
<div class="col-md-12">
<div class="card border shadow-sm">
@@ -186,66 +180,22 @@
</div>
<!-- Menu Structure Tab -->
<div class="tab-pane fade" id="menu" role="tabpanel">
<div class="row g-4">
<div class="col-md-12">
<div class="card border shadow-sm">
<div class="card-header bg-white d-flex justify-content-between align-items-center">
<h6 class="mb-0">
<i class="fas fa-sitemap me-2"></i>Menu Structure
</h6>
<div>
<button
type="button"
class="btn btn-outline-success btn-sm me-2"
id="saveMenuChanges"
style="display: none"
>
<i class="fas fa-save me-1"></i>Save Changes
</button>
<button
type="button"
class="btn btn-outline-primary btn-sm"
id="refreshMenuTree"
>
<i class="fas fa-sync-alt me-1"></i>Refresh
</button>
</div>
</div>
<div class="card-body">
<div class="alert alert-info">
<i class="fas fa-info-circle me-2"></i>
Click "Save Changes" to apply menu structure updates.
</div>
<div id="menuTreeContainer">
<div class="text-center">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p class="mt-2">Loading menu structure...</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane fade <%= activeTab === 'menu' ? 'show active' : '' %>" id="menu" role="tabpanel">
<%- include('menu') %>
</div>
</div>
</div>
<!-- Move buttons to fixed bottom -->
<div class="fixed-bottom-buttons">
<button type="reset" class="btn btn-secondary">
<i class="fas fa-undo"></i>
<span>Reset</span>
<!-- Fixed actions for ALL tabs -->
<div class="card-footer bg-light d-flex justify-content-end py-3 gap-2">
<button type="button" class="btn btn-outline-secondary px-4" id="headerResetBtn">
<i class="fas fa-undo me-1"></i>Reset
</button>
<button type="submit" class="btn btn-primary">
<i class="fas fa-save"></i>
<span>Save Changes</span>
<button type="button" id="saveHeaderBtn" class="btn btn-outline-primary px-4">
<i class="fas fa-save me-1"></i>Save Changes
</button>
</div>
</form>
</div>
</div>
</div>
</div>
@@ -258,8 +208,52 @@
initializeSocialLinks();
updateHiddenInputs();
// Safely remove any lingering modal backdrops on page load/navigation
function cleanupModals() {
// Basic reset
document.body.classList.remove('modal-open');
document.body.style.overflow = '';
document.body.style.paddingRight = '';
document.body.style.pointerEvents = 'auto';
// Remove all backdrop/overlay elements
const selector = '.modal-backdrop, .overlay, .loading';
document.querySelectorAll(selector).forEach(el => {
try {
el.remove();
} catch (err) {
console.warn('Error removing overlay:', err);
}
});
// Cleanup dynamically created modals that are not shown
document.querySelectorAll('.modal.fade:not(#modalAddMenu)').forEach(m => {
if (!m.classList.contains('show')) {
m.remove();
}
});
console.log('DOM Cleaned Up: Backdrops removed, body interaction restored.');
}
// Ensure all modals are in body root (prevents stacking context issues)
function relocateModals() {
const modals = document.querySelectorAll('.modal');
modals.forEach(modal => {
if (modal.parentElement !== document.body) {
document.body.appendChild(modal);
}
});
}
window.cleanupModals = cleanupModals;
// Initial cleanup and relocation
relocateModals();
cleanupModals();
const urlParams = new URLSearchParams(window.location.search);
const activeTabObj = urlParams.get('activeTab');
const activeTabObj = urlParams.get('activeTab') || urlParams.get('tab');
if (activeTabObj) {
const tabTrigger = document.querySelector(`a[href="#${activeTabObj}"]`);
@@ -269,23 +263,62 @@
}
}
// Listen for tab changes
document.querySelectorAll('a[data-bs-toggle="tab"]').forEach(tab => {
tab.addEventListener('shown.bs.tab', function (event) {
const targetId = event.target.getAttribute('href').substring(1);
document.getElementById('activeTabInput').value = targetId;
// Only load Menu Tree if clicking on the menu tab
if (targetId === 'menu') {
loadMenuTree();
}
});
});
document.querySelector('a[href="#menu"]').addEventListener('shown.bs.tab', function () {
// Detect changes to highlight Save button
function markChanged() {
const saveBtn = document.getElementById('saveHeaderBtn');
if (saveBtn) {
saveBtn.classList.remove('btn-outline-primary');
saveBtn.classList.add('btn-primary');
}
}
// Attach listeners to all inputs for change detection
const headerInputs = document.querySelectorAll('#topbar input, #logo input');
headerInputs.forEach(input => {
input.addEventListener('input', markChanged);
input.addEventListener('change', markChanged);
});
// Reset button logic
const headerResetBtn = document.getElementById('headerResetBtn');
if (headerResetBtn) {
headerResetBtn.addEventListener('click', function() {
if (confirm('Are you sure you want to discard all unsaved changes and reset to current saved data?')) {
window.location.reload(); // Simplest and most reliable reset
}
});
}
// Exposed markChanged for other components (like menu)
window.markHeaderChanged = markChanged;
const refreshMenuTreeBtn = document.getElementById('refreshMenuTree');
if (refreshMenuTreeBtn) {
refreshMenuTreeBtn.addEventListener('click', function () {
loadMenuTree();
});
}
document.getElementById('refreshMenuTree').addEventListener('click', function () {
loadMenuTree();
});
// saveMenuChanges has its own onclick in menu.ejs, no need for redundant listener here
// But we'll keep a log to see if it's called
console.log('=== TRACE: Global click listeners initialized ===');
document.getElementById('saveMenuChanges').addEventListener('click', function () {
saveMenuChanges();
// Cleanup modals when any modal is hidden
document.addEventListener('hidden.bs.modal', function() {
cleanupModals();
});
document.querySelectorAll('.btn-upload-image').forEach(button => {
@@ -296,58 +329,55 @@
});
});
document.getElementById('headerForm').addEventListener('submit', function (e) {
e.preventDefault();
const saveHeaderBtn = document.getElementById('saveHeaderBtn');
if (saveHeaderBtn) {
saveHeaderBtn.addEventListener('click', async function (e) {
console.log('=== TRACE: saveHeaderBtn Clicked (Unified) ===');
updateHiddenInputs();
const submitBtn = this.querySelector('button[type="submit"]');
const submitBtn = this;
const originalText = submitBtn.innerHTML;
submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Đang lưu...';
submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Saving everything...';
submitBtn.disabled = true;
// Collect form data as JSON
const formData = {
try {
// 1. Collect and Save Topbar & Logo
const headerData = {
topbarJson: document.getElementById('topbarJson').value,
logo: document.getElementById('logoInput').value,
menuUpdates: document.getElementById('menuUpdates').value,
activeTab: document.getElementById('activeTabInput').value
};
console.log('=== FORM SUBMISSION ===');
console.log('Form data being sent:', formData);
console.log('topbarJson parsed:', JSON.parse(formData.topbarJson || '{}'));
// Send via AJAX with JSON
fetch('/admin/header/update', {
const headerResponse = await fetch('/admin/header/update', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => {
console.log('Response status:', response.status);
return response.json();
})
.then(result => {
console.log('Response result:', result);
if (result.success) {
showNotification('Changes saved successfully', 'success');
submitBtn.innerHTML = originalText;
submitBtn.disabled = false;
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(headerData)
});
const headerResult = await headerResponse.json();
// 2. Save Menu Structure if we have the management script loaded
let menuResult = { success: true };
if (typeof window.saveMenuChanges === 'function') {
menuResult = await window.saveMenuChanges(false); // Save without redundant notification
}
if (headerResult.success && menuResult.success) {
showNotification('All changes saved successfully', 'success');
submitBtn.classList.remove('btn-primary');
submitBtn.classList.add('btn-outline-primary');
} else {
showNotification('Error: ' + (result.message || 'Unable to save changes'), 'error');
const errorMsg = (!headerResult.success ? headerResult.message : '') || (!menuResult.success ? menuResult.message : '') || 'Unable to save some changes';
showNotification('Error: ' + errorMsg, 'error');
}
} catch (error) {
console.error('=== TRACE: Unified Save ERROR ===', error);
showNotification('Lỗi: ' + error.message, 'error');
} finally {
submitBtn.innerHTML = originalText;
submitBtn.disabled = false;
}
})
.catch(error => {
console.error('Error:', error);
showNotification('Lỗi: ' + error.message, 'error');
submitBtn.innerHTML = originalText;
submitBtn.disabled = false;
});
});
}
function updateHiddenInputs() {
const topbarData = {
@@ -401,7 +431,15 @@
function initializeSocialLinks() {
const container = document.getElementById('socialLinksContainer');
const socialLinks = <%- JSON.stringify(data.topbar.socialLinks || []) %>;
if (!container) return;
// Extract social links safely from EJS data
let socialLinks = [];
try {
socialLinks = <%- JSON.stringify(data.topbar.socialLinks || []) %>;
} catch (e) {
console.error('Error parsing social links data:', e);
}
if (socialLinks.length === 0) {
// Add default platforms if no social links exist
@@ -426,7 +464,6 @@
const container = document.getElementById('socialLinksContainer');
const socialLink = document.createElement('div');
socialLink.className = 'card mb-3 border social-link-item';
socialLink.draggable = true;
socialLink.dataset.platform = platform;
// Escape HTML to prevent XSS
@@ -498,15 +535,7 @@
const dragDropStyles = document.createElement('style');
dragDropStyles.textContent = `
.social-link-item {
transition: opacity 0.2s ease, background-color 0.2s ease;
}
.social-link-item[draggable="true"] {
cursor: grab;
}
.social-link-item[draggable="true"]:active {
cursor: grabbing;
transition: transform 0.2s ease;
}
.drag-handle {
@@ -516,6 +545,11 @@
padding: 8px;
border-radius: 4px;
transition: all 0.2s ease;
cursor: grab !important;
}
.drag-handle:active {
cursor: grabbing !important;
}
.drag-handle:hover {
@@ -523,14 +557,24 @@
color: #0d6efd;
}
.social-link-item.dragging {
opacity: 0.5;
background-color: #f8f9fa;
/* SortableJS Classes */
.social-ghost {
opacity: 0.4;
border: 2px dashed #0d6efd !important;
background-color: #f8f9fa !important;
}
.social-chosen {
background-color: #eef3ff !important;
box-shadow: 0 5px 15px rgba(0,0,0,0.1) !important;
}
.social-drag {
opacity: 0.9;
}
.social-link-item.drag-over {
border-top: 3px solid #0d6efd;
padding-top: 10px;
/* Fix Modal Freeze & Z-Index issues */
body.modal-open {
overflow: hidden !important;
padding-right: 0 !important;
}
`;
document.head.appendChild(dragDropStyles);
@@ -570,32 +614,11 @@
});
function deleteSocialLink(platform, cardElement) {
// Convert platform to lowercase
platform = platform.toLowerCase().trim();
console.log("Deleting social link:", platform);
fetch(`/api/social-links/${platform}`, {
method: 'DELETE'
})
.then(response => {
console.log("Delete response status:", response.status);
return response.json();
})
.then(result => {
console.log("Delete API response:", result);
if (result.success) {
if (confirm(`Delete ${platform} social link?`)) {
cardElement.remove();
updateHiddenInputs();
showNotification('Xóa liên kết mạng xã hội thành công', 'success');
} else {
showNotification(result.message || 'Không thể xóa liên kết mạng xã hội', 'error');
markChanged();
}
})
.catch(error => {
console.error('Error:', error);
showNotification('Lỗi xóa liên kết mạng xã hội: ' + error.message, 'error');
});
}
function showAddSocialLinkModal() {
@@ -733,167 +756,37 @@
}
function addSocialLinkViaAPI(platform, url, icon, modal, modalElement) {
console.log("Adding social link:", { platform, url, icon });
fetch('/api/social-links', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
platform,
url,
icon
})
})
.then(response => {
console.log("Response status:", response.status);
return response.json();
})
.then(result => {
console.log("API response:", result);
if (result.success) {
modal.hide();
modalElement.remove();
addSocialLinkRow(platform, url, icon, Date.now());
updateHiddenInputs();
showNotification('Thêm liên kết mạng xã hội thành công', 'success');
} else {
showNotification(result.message || 'Không thể thêm liên kết mạng xã hội', 'error');
}
})
.catch(error => {
console.error('Error:', error);
showNotification('Lỗi thêm liên kết mạng xã hội: ' + error.message, 'error');
});
markChanged();
modal.hide();
modalElement.remove();
}
function updateSocialLinkViaAPIModal(oldPlatform, newPlatform, url, icon, modal, modalElement) {
// Convert to lowercase
oldPlatform = oldPlatform.toLowerCase().trim();
newPlatform = newPlatform.toLowerCase().trim();
url = url.trim();
icon = icon ? icon.trim() : null;
console.log("Updating social link:", { oldPlatform, newPlatform, url, icon });
// If platform changed, need to delete old and create new
if (oldPlatform !== newPlatform) {
console.log("Platform changed, deleting old and creating new");
// Check if new platform already exists
const existingPlatforms = Array.from(document.querySelectorAll('.social-platform')).map(el => el.value.toLowerCase());
if (existingPlatforms.includes(newPlatform)) {
showNotification(`Nền tảng ${newPlatform} đã tồn tại`, 'error');
return;
}
// First delete old platform
fetch(`/api/social-links/${oldPlatform}`, {
method: 'DELETE'
})
.then(response => response.json())
.then(result => {
if (result.success) {
console.log("Old platform deleted, creating new");
// Then create new platform
return fetch('/api/social-links', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
platform: newPlatform,
url,
icon
})
});
} else {
throw new Error(result.message);
}
})
.then(response => response.json())
.then(result => {
console.log("Update API response:", result);
if (result.success) {
modal.hide();
modalElement.remove();
// Update the input fields
const urlInputs = document.querySelectorAll(`.social-url`);
// Update the input fields in the DOM
const platformInputs = document.querySelectorAll(`.social-platform`);
const urlInputs = document.querySelectorAll(`.social-url`);
const iconInputs = document.querySelectorAll(`.social-icon`);
let found = false;
for (let i = 0; i < platformInputs.length; i++) {
if (platformInputs[i].value.toLowerCase() === oldPlatform) {
if (platformInputs[i].value.toLowerCase() === oldPlatform.toLowerCase()) {
platformInputs[i].value = newPlatform;
urlInputs[i].value = url;
const iconInput = document.querySelector(`.social-icon[data-index="${platformInputs[i].dataset.index}"]`);
if (iconInput) {
iconInput.value = icon;
}
if (iconInputs[i]) iconInputs[i].value = icon;
found = true;
break;
}
}
updateHiddenInputs();
showNotification('Cập nhật liên kết mạng xã hội thành công', 'success');
} else {
showNotification(result.message || 'Không thể cập nhật liên kết mạng xã hội', 'error');
}
})
.catch(error => {
console.error('Error:', error);
showNotification('Lỗi cập nhật liên kết mạng xã hội: ' + error.message, 'error');
});
} else {
// Platform not changed, just update URL and icon
console.log("Platform not changed, updating URL and icon only");
fetch(`/api/social-links/${oldPlatform}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
url,
icon
})
})
.then(response => {
console.log("Update response status:", response.status);
return response.json();
})
.then(result => {
console.log("Update API response:", result);
if (result.success) {
if (found) {
modal.hide();
modalElement.remove();
// Update the input fields
const urlInputs = document.querySelectorAll(`.social-url`);
const platformInputs = document.querySelectorAll(`.social-platform`);
for (let i = 0; i < platformInputs.length; i++) {
if (platformInputs[i].value.toLowerCase() === oldPlatform) {
urlInputs[i].value = url;
const iconInput = document.querySelector(`.social-icon[data-index="${platformInputs[i].dataset.index}"]`);
if (iconInput) {
iconInput.value = icon;
}
break;
}
}
updateHiddenInputs();
showNotification('Cập nhật liên kết mạng xã hội thành công', 'success');
} else {
showNotification(result.message || 'Không thể cập nhật liên kết mạng xã hội', 'error');
}
})
.catch(error => {
console.error('Error:', error);
showNotification('Lỗi cập nhật liên kết mạng xã hội: ' + error.message, 'error');
});
markChanged();
}
}
@@ -989,7 +882,11 @@
function loadMenuTree() {
const container = document.getElementById('menuTreeContainer');
container.innerHTML = '<div class="alert alert-info"><i class="fas fa-info-circle me-2"></i>Menu structure management coming soon.</div>';
if (!container) return; // Safely return if element doesn't exist
// If container is empty (or only has the spinner), we can show a message or fetch data
// But since we use EJS for server-side rendering, we usually don't want to overwrite it
console.log("Menu tab activated");
}
function openImageUploader(targetInput, imageType) {
@@ -1040,6 +937,7 @@
input.value = result.path;
updateImagePreview(targetInput, result.url);
markChanged();
uploadBtn.disabled = false;
uploadBtn.innerHTML = originalBtnHtml;
@@ -1082,133 +980,165 @@
}
}
// ============================================
// DRAG & DROP REORDERING FUNCTIONALITY
// ============================================
let draggedElement = null;
// Initialize Sortable for Social Links
const socialLinksContainer = document.getElementById('socialLinksContainer');
const SortableLib = window.Sortable || Sortable;
// Handle drag start - user begins dragging a social link item
document.addEventListener('dragstart', function (e) {
if (e.target.closest('.social-link-item')) {
draggedElement = e.target.closest('.social-link-item');
draggedElement.style.opacity = '0.5';
draggedElement.style.cursor = 'grabbing';
e.dataTransfer.effectAllowed = 'move';
}
console.log('=== TRACE: Social Sortable Init ===', {
containerExists: !!socialLinksContainer,
sortableDefined: typeof SortableLib !== 'undefined'
});
// Handle drag over - provide visual feedback as item is dragged over other items
document.addEventListener('dragover', function (e) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
const socialItem = e.target.closest('.social-link-item');
if (socialItem && socialItem !== draggedElement) {
// Add visual feedback to show drop zone
socialItem.style.borderTop = '3px solid #0d6efd';
socialItem.style.paddingTop = '10px';
}
});
// Handle drag leave - remove visual feedback when leaving an item
document.addEventListener('dragleave', function (e) {
const socialItem = e.target.closest('.social-link-item');
if (socialItem) {
socialItem.style.borderTop = '';
socialItem.style.paddingTop = '';
}
});
// Handle drop - reorder items and persist to backend
document.addEventListener('drop', function (e) {
e.preventDefault();
const socialItem = e.target.closest('.social-link-item');
if (socialItem && socialItem !== draggedElement) {
// Reorder DOM elements
const container = document.getElementById('socialLinksContainer');
const allItems = Array.from(container.querySelectorAll('.social-link-item'));
const draggedIndex = allItems.indexOf(draggedElement);
const targetIndex = allItems.indexOf(socialItem);
if (draggedIndex < targetIndex) {
socialItem.parentNode.insertBefore(draggedElement, socialItem.nextSibling);
} else {
socialItem.parentNode.insertBefore(draggedElement, socialItem);
}
// Clear visual feedback
socialItem.style.borderTop = '';
socialItem.style.paddingTop = '';
// Persist the new order to backend
persistSocialLinksOrder();
}
});
// Handle drag end - cleanup and reset styles
document.addEventListener('dragend', function (e) {
if (draggedElement) {
draggedElement.style.opacity = '1';
draggedElement.style.cursor = 'grab';
draggedElement = null;
}
// Clear all visual feedback from all items
document.querySelectorAll('.social-link-item').forEach(item => {
item.style.borderTop = '';
item.style.paddingTop = '';
});
});
/**
* Persist the reordered social links to the backend
* Collects current order from DOM and sends to API
* Updates the order field for each social link based on new position
*/
function persistSocialLinksOrder() {
const container = document.getElementById('socialLinksContainer');
const items = container.querySelectorAll('.social-link-item');
// Build order array with platform and new order position
const socialLinks = Array.from(items).map((item, index) => {
const platform = item.dataset.platform;
const urlInput = item.querySelector('.social-url');
const iconInput = item.querySelector('.social-icon');
return {
platform: platform,
url: urlInput.value,
icon: iconInput.value,
order: index + 1 // Order starts from 1 (top to bottom)
};
});
console.log('Persisting social links order:', socialLinks);
// Send to backend via bulk-update endpoint
fetch('/api/social-links/bulk-update', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
if (socialLinksContainer && typeof SortableLib !== 'undefined') {
try {
new SortableLib(socialLinksContainer, {
animation: 150,
handle: '.drag-handle',
ghostClass: 'social-ghost',
chosenClass: 'social-chosen',
dragClass: 'social-drag',
forceFallback: true, // Use transition-based dragging for better compatibility
onStart: function() {
console.log('=== TRACE: Social Drag Started ===');
},
body: JSON.stringify({ socialLinks })
})
.then(response => response.json())
.then(result => {
if (result.success) {
console.log('Social links order updated successfully');
showNotification('Cập nhật thứ tự thành công', 'success');
onEnd: function() {
console.log('=== TRACE: Social Drag Ended ===');
updateHiddenInputs();
} else {
console.error('Failed to update order:', result.message);
showNotification('Không thể cập nhật thứ tự: ' + result.message, 'error');
markChanged();
}
})
.catch(error => {
console.error('Error persisting social links order:', error);
showNotification('Lỗi cập nhật thứ tự: ' + error.message, 'error');
});
console.log('=== TRACE: Sortable initialized for socialLinksContainer ===');
} catch (err) {
console.error('=== TRACE: Sortable Init Error ===', err);
}
} else {
console.warn('SortableJS not loaded or socialLinksContainer not found');
}
});
</script>
<!-- Modal Add/Edit Menu (Moved OUTSIDE tabs to prevent z-index/freeze issues) -->
<div class="modal fade" id="modalAddMenu" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<form id="menuForm" action="/admin/header/menu/create" method="POST" class="w-100">
<input type="hidden" name="id" id="menuId">
<input type="hidden" name="parentId" id="parentId">
<div class="modal-content border-0 shadow-lg">
<div class="modal-header bg-light border-bottom-0 py-3">
<h5 class="modal-title fw-bold" id="modalTitle">Add Menu Item</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body p-4">
<div class="mb-3">
<label class="form-label fw-medium">Menu Title</label>
<input type="text" name="title" id="formTitle" class="form-control form-control-lg fs-6" placeholder="e.g. Home, Services, About" required>
<small class="text-muted">Display text for the menu item.</small>
</div>
<div class="mb-3">
<label class="form-label fw-medium">Navigation URL</label>
<div class="input-group">
<span class="input-group-text bg-light"><i class="fas fa-link"></i></span>
<input type="text" name="url" id="formUrl" class="form-control" required placeholder="/services or https://...">
</div>
<small class="text-muted">Use relative paths for internal links.</small>
</div>
<div class="row g-3">
<div class="col-md-6 mb-3">
<label class="form-label fw-medium">Display Order</label>
<input type="number" name="order" id="formOrder" class="form-control" value="0">
</div>
<div class="col-md-6 mb-3">
<label class="form-label fw-medium">Status</label>
<select name="status" id="formStatus" class="form-select">
<option value="active">Active</option>
<option value="inactive">Inactive</option>
</select>
</div>
</div>
<div class="mb-0">
<label class="form-label fw-medium">Link Type</label>
<div class="d-flex gap-3">
<div class="form-check">
<input class="form-check-input" type="radio" name="type" id="typeInternal" value="internal" checked>
<label class="form-check-label" for="typeInternal">Internal</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="type" id="typeExternal" value="external">
<label class="form-check-label" for="typeExternal">External</label>
</div>
</div>
</div>
</div>
<div class="modal-footer bg-light border-top-0 py-3">
<button type="button" class="btn btn-white border px-4" data-bs-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary px-4" id="btnSaveMenu">
<i class="fas fa-save me-1"></i>Save Changes
</button>
</div>
</div>
</form>
</div>
</div>
<script>
// AJAX handler for menuForm
const menuForm = document.getElementById('menuForm');
if (menuForm) {
menuForm.addEventListener('submit', async function(e) {
e.preventDefault();
console.log('=== TRACE: menuForm AJAX Submission Start ===');
const submitBtn = document.getElementById('btnSaveMenu');
const originalText = submitBtn ? submitBtn.innerHTML : 'Save';
if (submitBtn) {
submitBtn.disabled = true;
submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Saving...';
}
try {
const formData = new FormData(this);
const data = {};
formData.forEach((value, key) => data[key] = value);
console.log('Sending data:', data);
const response = await axios({
method: 'POST',
url: this.action,
data: data
});
console.log('Response:', response.data);
if (response.data.success || response.status === 200) {
showToast('Success', 'Menu information has been updated', 'success');
// Hide modal
const modalElement = document.getElementById('modalAddMenu');
const modal = bootstrap.Modal.getOrCreateInstance(modalElement);
modal.hide();
// Refresh data or reload tab
setTimeout(() => window.location.reload(), 1000);
} else {
showToast('Error', response.data.message || 'Unable to save menu', 'error');
}
} catch (error) {
console.error('AJAX Error:', error);
showToast('Error', 'Server connection error: ' + (error.response?.data?.message || error.message), 'error');
} finally {
if (submitBtn) {
submitBtn.disabled = false;
submitBtn.innerHTML = originalText;
}
}
});
}
// TRACE: Click listener for btnSaveMenu
document.addEventListener('click', function(e) {
if (e.target && e.target.id === 'btnSaveMenu') {
console.log('=== TRACE: btnSaveMenu CLICKED ===');
}
});
</script>

355
views/admin/header/menu.ejs Normal file
View File

@@ -0,0 +1,355 @@
<div class="card">
<div class="card-header d-flex justify-content-between align-items-center">
<h6 class="mb-0">
<i class="fas fa-sitemap me-2"></i>Menu Structure
</h6>
<button class="btn btn-primary btn-sm" onclick="prepareAddMenu()">
<i class="fas fa-plus me-1"></i>Add Root Menu
</button>
</div>
<div class="card-body p-0">
<div id="nestedMenuContainer" class="nested-menu-container">
<ul id="menuRoot" class="list-unstyled menu-group" data-id="root">
<% function renderMenu(items) { %>
<% items.forEach(item => { %>
<li class="menu-item-wrapper mb-2" data-id="<%= item._id %>">
<div class="menu-item-row d-flex align-items-center p-3 rounded border hover-shadow-sm bg-white">
<div class="menu-drag-handle me-2 text-muted">
<i class="fas fa-grip-vertical"></i>
</div>
<div class="menu-toggle-icon me-2">
<% if (item.children && item.children.length > 0) { %>
<button class="btn btn-sm p-0 btn-toggle-nested" type="button">
<i class="fas fa-chevron-down transition-base text-muted" style="width: 12px;"></i>
</button>
<% } else { %>
<div style="width: 24px;"></div>
<% } %>
</div>
<div class="menu-icon me-3">
<i class="fas <%= (item.type === 'external' ? 'fa-external-link-alt text-info' : 'fa-link text-secondary') %>"></i>
</div>
<div class="flex-grow-1">
<div class="d-flex align-items-center">
<span class="fw-bold text-dark"><%= item.title %></span>
<% if (item.type === 'external') { %>
<span class="badge bg-light text-dark border ms-2" style="font-size: 0.7rem;">External</span>
<% } %>
<% if (item.status === 'inactive') { %>
<span class="badge bg-soft-secondary ms-2">Inactive</span>
<% } else { %>
<span class="badge bg-soft-success ms-2">Active</span>
<% } %>
</div>
<div class="text-muted small text-truncate" style="max-width: 300px;">
<i class="fas fa-link me-1" style="font-size: 0.75rem;"></i><%= item.url %>
</div>
</div>
<div class="menu-actions">
<div class="btn-group-action">
<button class="btn btn-sm btn-add-child" data-id="<%= item._id %>" title="Add Sub-menu">
<i class="fas fa-plus text-action-add"></i>
</button>
<button class="btn btn-sm btn-edit-menu" data-item='<%= JSON.stringify(item).replace(/'/g, "&apos;") %>' title="Edit">
<i class="fas fa-edit text-action-edit"></i>
</button>
<button type="button" class="btn btn-sm btn-delete-menu" data-id="<%= item._id %>" data-title="<%= item.title %>" title="Delete">
<i class="fas fa-trash text-action-delete"></i>
</button>
</div>
<form id="delete-form-<%= item._id %>" action="/admin/header/menu/delete" method="POST" class="d-none">
<input type="hidden" name="id" value="<%= item._id %>">
</form>
</div>
</div>
<ul class="list-unstyled menu-group mt-2 ps-4 ms-2 border-start nested-list" style="min-height: 5px;" data-id="<%= item._id %>">
<% if (item.children && item.children.length > 0) { %>
<% renderMenu(item.children) %>
<% } %>
</ul>
</li>
<% }) %>
<% } %>
<% if (menuData.tree && menuData.tree.length > 0) { %>
<% renderMenu(menuData.tree) %>
<% } %>
</ul>
<% if (!menuData.tree || menuData.tree.length === 0) { %>
<div class="text-center py-5">
<img src="/assets/img/icon/empty-state.svg" alt="Empty" style="width: 120px; opacity: 0.5;" class="mb-3">
<p class="text-muted">No menu items found. Start by adding a root menu.</p>
</div>
<% } %>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
console.log('Menu Tab JS Initialized');
initSortable();
function initSortable() {
const menuGroups = document.querySelectorAll('.menu-group');
menuGroups.forEach(group => {
new Sortable(group, {
group: 'nested-menu',
animation: 150,
fallbackOnBody: true,
swapThreshold: 0.65,
handle: '.menu-drag-handle',
ghostClass: 'menu-ghost',
chosenClass: 'menu-chosen',
dragClass: 'menu-dragging',
onEnd: function (evt) {
console.log('Drag ended', evt);
// Highlight that changes need saving
const saveBtn = document.getElementById('saveHeaderBtn');
if (saveBtn && typeof window.markHeaderChanged === 'function') {
window.markHeaderChanged();
}
}
});
});
}
// Bind Edit/Add/Delete buttons
bindMenuActions();
function bindMenuActions() {
// Use event delegation for better performance and to handle re-rendered items if any
const container = document.getElementById('nestedMenuContainer');
if (container) {
container.addEventListener('click', function(e) {
const editBtn = e.target.closest('.btn-edit-menu');
if (editBtn) {
try {
const item = JSON.parse(editBtn.dataset.item);
console.log('=== TRACE: Edit Menu Clicked ===', item);
prepareEditMenu(item);
} catch (e) {
console.error('Error parsing menu item data:', e);
}
return;
}
const addChildBtn = e.target.closest('.btn-add-child');
if (addChildBtn) {
const pid = addChildBtn.dataset.id;
console.log('=== TRACE: Add Child Clicked ===', { pid });
if (typeof prepareAddChild === 'function') {
prepareAddChild(pid);
} else {
console.error('prepareAddChild function not found');
}
return;
}
const deleteBtn = e.target.closest('.btn-delete-menu');
if (deleteBtn) {
const id = deleteBtn.dataset.id;
const title = deleteBtn.dataset.title;
console.log('=== TRACE: Delete Menu Clicked ===', { id, title });
if (confirm(`Are you sure you want to delete "${title}" and all its sub-menu items?`)) {
const form = document.getElementById('delete-form-' + id);
console.log('=== TRACE: Submitting Delete Form ===', form ? form.action : 'FORM NOT FOUND');
if (form) form.submit();
}
return;
}
const toggleBtn = e.target.closest('.btn-toggle-nested');
if (toggleBtn) {
const wrapper = toggleBtn.closest('.menu-item-wrapper');
const nestedUl = wrapper.querySelector('.nested-list');
const icon = toggleBtn.querySelector('i');
if (nestedUl) {
const isCollapsed = nestedUl.classList.toggle('collapsed');
if (isCollapsed) {
icon.style.transform = 'rotate(-90deg)';
} else {
icon.style.transform = 'rotate(0deg)';
}
}
}
});
}
}
});
function prepareAddMenu() {
console.log('=== TRACE: prepareAddMenu Called ===');
const form = document.getElementById('menuForm');
if (!form) return;
form.action = '/admin/header/menu/create';
document.getElementById('modalTitle').innerText = 'Add Root Menu';
document.getElementById('menuId').value = '';
document.getElementById('parentId').value = '';
document.getElementById('formTitle').value = '';
document.getElementById('formUrl').value = '';
document.getElementById('formOrder').value = '0';
document.getElementById('formStatus').value = 'active';
document.getElementById('typeInternal').checked = true;
const modalElement = document.getElementById('modalAddMenu');
const modal = bootstrap.Modal.getOrCreateInstance(modalElement);
modal.show();
}
function prepareAddChild(parentId) {
prepareAddMenu();
document.getElementById('parentId').value = parentId;
document.getElementById('modalTitle').innerText = 'Add Sub-Menu Item';
}
function prepareEditMenu(item) {
const form = document.getElementById('menuForm');
if (!form) return;
form.action = '/admin/header/menu/update/' + item._id;
document.getElementById('modalTitle').innerText = 'Edit Menu Item';
document.getElementById('menuId').value = item._id;
document.getElementById('parentId').value = item.parentId || '';
document.getElementById('formTitle').value = item.title;
document.getElementById('formUrl').value = item.url;
document.getElementById('formOrder').value = item.order;
document.getElementById('formStatus').value = item.status;
if (item.type === 'external') {
document.getElementById('typeExternal').checked = true;
} else {
document.getElementById('typeInternal').checked = true;
}
const modalElement = document.getElementById('modalAddMenu');
const modal = bootstrap.Modal.getOrCreateInstance(modalElement);
modal.show();
}
function collectMenuData() {
const items = [];
function traverse(element, parentId = null) {
const children = element.children;
for (let i = 0; i < children.length; i++) {
const li = children[i];
if (li.tagName !== 'LI') continue;
const id = li.dataset.id;
if (!id) continue;
items.push({
id: id,
order: i + 1,
parentId: parentId === 'root' ? null : parentId
});
const subUl = li.querySelector('.menu-group');
if (subUl) {
traverse(subUl, id);
}
}
}
const rootUl = document.getElementById('menuRoot');
if (rootUl) traverse(rootUl, 'root');
return items;
}
window.saveMenuChanges = function(showToastFlag = true) {
return new Promise((resolve, reject) => {
console.log('=== TRACE: saveMenuChanges Called (Reorder) ===');
const items = collectMenuData();
if (items.length === 0) {
console.warn('No menu items found to reorder');
return resolve({ success: true, message: 'No items' });
}
const saveBtn = document.getElementById('saveHeaderBtn');
const originalHtml = saveBtn ? saveBtn.innerHTML : '';
// Only manage button state if this is a direct call (not unified save)
const manageButton = showToastFlag && saveBtn;
if (manageButton) {
saveBtn.disabled = true;
saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Saving Menu...';
}
fetch('/admin/header/menu/reorder', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ items: items })
})
.then(response => response.json())
.then(data => {
if (data.success) {
if (showToastFlag) showNotification('Menu structure saved', 'success');
resolve(data);
} else {
reject(new Error(data.message));
}
})
.catch(error => reject(error))
.finally(() => {
if (manageButton) {
saveBtn.disabled = false;
saveBtn.innerHTML = originalHtml;
}
});
});
};
window.collectMenuData = collectMenuData;
// Global reset fallback
window.prepareAddMenu = prepareAddMenu;
</script>
<!-- Redundant buttons removed to use global buttons in index.ejs -->
<style>
.nested-menu-container {
padding: var(--spacing-3);
}
.menu-group {
min-height: 10px;
}
.menu-item-row {
transition: var(--transition-base);
}
.menu-drag-handle { cursor: grab; padding: 5px; }
.menu-drag-handle:active { cursor: grabbing; }
/* SortableJS Classes mapped to our variables */
.menu-ghost {
opacity: 0.4;
border: 2px dashed var(--primary-color) !important;
}
.menu-chosen {
background-color: var(--primary-soft) !important;
}
.menu-dragging {
opacity: 0.9;
}
/* Collapse/Expand Styles */
.nested-list {
overflow: hidden;
transition: all 0.3s ease;
max-height: 2000px; /* Large enough for nested items */
}
.nested-list.collapsed {
max-height: 0;
margin-top: 0 !important;
opacity: 0;
pointer-events: none;
}
.btn-toggle-nested i {
transition: transform 0.2s ease;
}
.transition-base {
transition: all 0.2s ease-in-out;
}
</style>

View File

@@ -11,7 +11,7 @@
</div>
<div class="row align-items-center">
<div class="col-lg-6">
<div class="col-lg-6 p-5">
<h1 class="fw-bold mb-4 text-white">API Management</h1>
<p class="lead mb-4 text-white-50">Simple dashboard to control your APIs</p>
<div class="d-flex gap-3">

View File

@@ -120,6 +120,39 @@
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Global function to clean up any stuck modal backdrops
function forceCleanupModals() {
document.body.classList.remove('modal-open');
document.body.style.overflow = '';
document.body.style.paddingRight = '';
const backdrops = document.querySelectorAll('.modal-backdrop, .overlay, .loading');
if (backdrops.length > 0) {
console.warn('Force removing stuck backdrops:', backdrops.length);
backdrops.forEach(el => el.remove());
}
}
// Automatically clean up on every hide event
document.addEventListener('hidden.bs.modal', function() {
// Wait a tiny bit for the animation to finish
setTimeout(forceCleanupModals, 100);
});
// Watchdog: Check if backdrops exist without a visible modal every 2 seconds
setInterval(() => {
const visibleModals = document.querySelectorAll('.modal.show');
if (visibleModals.length === 0) {
const backdrops = document.querySelectorAll('.modal-backdrop');
if (backdrops.length > 0) {
forceCleanupModals();
}
}
}, 2000);
// Clean up on page load
window.addEventListener('load', forceCleanupModals);
</script>
<%- script %>
</body>

View File

@@ -12,16 +12,18 @@
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
<!-- Custom CSS -->
<style>
:root {
--primary-color: #bc9f69;
--primary-light: #bba57c;
--primary-dark: #be9d5f;
--secondary-color: #f5f5e8;
--text-light: #black;
}
<!-- Global CSS Variables -->
<link rel="stylesheet" href="/assets/css/variables.css" />
<!-- CMS Component System -->
<link rel="stylesheet" href="/assets/css/components/button.css" />
<link rel="stylesheet" href="/assets/css/components/card.css" />
<link rel="stylesheet" href="/assets/css/components/form.css" />
<link rel="stylesheet" href="/assets/css/components/modal.css" />
<link rel="stylesheet" href="/assets/css/components/table.css" />
<!-- Layout Styles -->
<link rel="stylesheet" href="/assets/css/layout.css" />
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
position: relative;
@@ -864,16 +866,22 @@
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- Axios for API calls -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<!-- SortableJS for drag and drop -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<!-- Toast JS -->
<script src="/js/toast.js"></script>
<!-- Flash Handler JS -->
<script src="/js/flash-handler.js"></script>
<!-- Custom JS -->
<!-- Custom JS Utilities -->
<script src="/js/main.js"></script>
<!-- Custom modal -->
<!-- Custom modal enhancement -->
<script src="/js/custom-modal.js"></script>
<script>