diff --git a/.gitignore b/.gitignore index 14b9aad..fc4bc00 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ # dependencies node_modules/ +/public # environment .env @@ -21,3 +22,4 @@ pids #cursor .cursor +package-lock.json \ No newline at end of file diff --git a/controllers/blogCategoryController.js b/controllers/blogCategoryController.js index 4043d22..52f5086 100644 --- a/controllers/blogCategoryController.js +++ b/controllers/blogCategoryController.js @@ -1,4 +1,5 @@ const BlogCategory = require('../models/blogCategory'); +const slugify = require('slugify'); // -------------------- Admin Controllers -------------------- @@ -49,12 +50,11 @@ exports.store = async (req, res) => { } = req.body; // Generate slug - const slug = name - .toLowerCase() - .replace(/[^a-z0-9\s-]/g, '') - .replace(/\s+/g, '-') - .replace(/-+/g, '-') - .trim('-'); + const slug = slugify(name, { + lower: true, + strict: true, + locale: 'vi' + }); // Check if slug exists const existingCategory = await BlogCategory.findOne({ slug }); @@ -130,12 +130,11 @@ exports.update = async (req, res) => { category.isActive = isActive === 'on'; // Generate new slug if name changed - const newSlug = name - .toLowerCase() - .replace(/[^a-z0-9\s-]/g, '') - .replace(/\s+/g, '-') - .replace(/-+/g, '-') - .trim('-'); + const newSlug = slugify(name, { + lower: true, + strict: true, + locale: 'vi' + }); if (newSlug !== category.slug) { const existingCategory = await BlogCategory.findOne({ @@ -166,6 +165,14 @@ exports.destroy = async (req, res) => { const category = await BlogCategory.findById(req.params.id); if (!category) { + // Check if it's an AJAX request + const isAjax = req.xhr || req.headers['accept']?.includes('application/json') || req.headers['content-type']?.includes('application/json'); + if (isAjax) { + return res.status(404).json({ + success: false, + message: 'Category not found' + }); + } req.flash('error_msg', 'Category not found'); return res.redirect('/admin/blog/categories'); } @@ -175,16 +182,44 @@ exports.destroy = async (req, res) => { const postCount = await Blog.countDocuments({ category: { $in: [category.name] } }); if (postCount > 0) { + // Check if it's an AJAX request + const isAjax = req.xhr || req.headers['accept']?.includes('application/json') || req.headers['content-type']?.includes('application/json'); + if (isAjax) { + return res.status(400).json({ + success: false, + message: 'Cannot delete category that has blog posts' + }); + } req.flash('error_msg', 'Cannot delete category that has blog posts'); return res.redirect('/admin/blog/categories'); } await BlogCategory.findByIdAndDelete(req.params.id); + // Check if it's an AJAX request + const isAjax = req.xhr || req.headers['accept']?.includes('application/json') || req.headers['content-type']?.includes('application/json'); + if (isAjax) { + return res.json({ + success: true, + message: 'Category deleted successfully' + }); + } + req.flash('success_msg', 'Category deleted successfully'); res.redirect('/admin/blog/categories'); } catch (err) { console.error('Category delete error:', err); + + // Check if it's an AJAX request + const isAjax = req.xhr || req.headers['accept']?.includes('application/json') || req.headers['content-type']?.includes('application/json'); + if (isAjax) { + return res.status(500).json({ + success: false, + message: 'Error deleting category', + error: err.message || 'Error deleting category' + }); + } + req.flash('error_msg', 'Error deleting category'); res.redirect('/admin/blog/categories'); } @@ -202,10 +237,18 @@ exports.api = async (req, res) => { await category.updatePostCount(); } - res.json(categories); + res.json({ + success: true, + message: 'Categories fetched successfully', + data: categories + }); } catch (err) { console.error('Categories API error:', err); - res.status(500).json({ error: 'Error loading categories' }); + res.status(500).json({ + success: false, + message: 'Error loading categories', + error: err.message || 'Error loading categories' + }); } }; @@ -218,13 +261,81 @@ exports.apiShow = async (req, res) => { }).lean(); if (!category) { - return res.status(404).json({ error: 'Category not found' }); + return res.status(404).json({ + success: false, + message: 'Category not found' + }); } - res.json(category); + res.json({ + success: true, + message: 'Category fetched successfully', + data: category + }); } catch (err) { console.error('Category show API error:', err); - res.status(500).json({ error: 'Error loading category' }); + res.status(500).json({ + success: false, + message: 'Error loading category', + error: err.message || 'Error loading category' + }); + } +}; + +// Quick create category (for inline creation in blog form) +exports.quickCreate = async (req, res) => { + try { + const { name, description } = req.body; + + if (!name || !name.trim()) { + return res.status(400).json({ + success: false, + message: 'Category name is required' + }); + } + + const categoryName = name.trim(); + + // Generate slug + const slug = slugify(categoryName, { + lower: true, + strict: true, + locale: 'vi' + }); + + // Check if category already exists + let category = await BlogCategory.findOne({ slug }); + + if (category) { + return res.json({ + success: true, + message: 'Category already exists', + data: category.toObject() + }); + } + + // Create new category + category = new BlogCategory({ + name: categoryName, + slug, + description: description || '', + isActive: true + }); + + await category.save(); + + res.json({ + success: true, + message: 'Category created successfully', + data: category.toObject() + }); + } catch (err) { + console.error('Quick create category error:', err); + res.status(500).json({ + success: false, + message: 'Error creating category', + error: err.message || 'Error creating category' + }); } }; diff --git a/controllers/blogController.js b/controllers/blogController.js index bc02bc4..22ce42b 100644 --- a/controllers/blogController.js +++ b/controllers/blogController.js @@ -4,17 +4,17 @@ const BlogTag = require('../models/blogTag'); const BlogComment = require('../models/blogComment'); const RecentPost = require('../models/recentPost'); const { addBaseUrlToImages } = require('../utils/imageHelper'); +const slugify = require('slugify'); // -------------------- Helper Functions -------------------- // Generate slug from title const generateSlug = (title) => { - return title - .toLowerCase() - .replace(/[^a-z0-9\s-]/g, '') - .replace(/\s+/g, '-') - .replace(/-+/g, '-') - .trim('-'); + return slugify(title, { + lower: true, + strict: true, + locale: 'vi' + }); }; // Update category post counts @@ -69,12 +69,15 @@ exports.index = async (req, res) => { // Get categories for filter const categories = await BlogCategory.getActive(); + + const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3000'; res.render('admin/blog/index', { layout: 'layouts/main', title: 'Blog Management', blogs, categories, + frontendUrl, pagination: { current: page, total: totalPages, @@ -98,13 +101,16 @@ exports.create = async (req, res) => { const categories = await BlogCategory.getActive(); const tags = await BlogTag.getActive(); + const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3000'; + res.render('admin/blog/create', { layout: 'layouts/main', title: 'Create New Blog Post', categories, tags, currentPath: req.path, - user: req.session.user + user: req.session.user, + frontendUrl }); } catch (err) { console.error('Blog create form error:', err); @@ -125,7 +131,9 @@ exports.store = async (req, res) => { status, isFeatured, author, - galleryImages + galleryImages, + quote, + contentAfterQuote } = req.body; // Generate slug @@ -149,12 +157,14 @@ exports.store = async (req, res) => { status: status || 'published', isFeatured: isFeatured === 'on', author: author || 'Admin', - galleryImages: galleryImages ? (Array.isArray(galleryImages) ? galleryImages : [galleryImages]) : [] + galleryImages: galleryImages ? (Array.isArray(galleryImages) ? galleryImages : [galleryImages]) : [], + quote: quote || '', + contentAfterQuote: contentAfterQuote || '' }; - // Handle featured image - if (req.file) { - blogData.featuredImage = `/uploads/blog/${req.file.filename}`; + // Handle featured image - using featuredImageUrl from form (uploaded via AJAX) + if (req.body.featuredImageUrl) { + blogData.featuredImage = req.body.featuredImageUrl; } // Create blog @@ -188,6 +198,8 @@ exports.edit = async (req, res) => { const categories = await BlogCategory.getActive(); const tags = await BlogTag.getActive(); + const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3000'; + res.render('admin/blog/edit', { layout: 'layouts/main', title: 'Edit Blog Post', @@ -195,7 +207,8 @@ exports.edit = async (req, res) => { categories, tags, currentPath: req.path, - user: req.session.user + user: req.session.user, + frontendUrl }); } catch (err) { console.error('Blog edit form error:', err); @@ -223,7 +236,9 @@ exports.update = async (req, res) => { status, isFeatured, author, - galleryImages + galleryImages, + quote, + contentAfterQuote } = req.body; // Update blog data @@ -236,10 +251,12 @@ exports.update = async (req, res) => { blog.isFeatured = isFeatured === 'on'; blog.author = author || 'Admin'; blog.galleryImages = galleryImages ? (Array.isArray(galleryImages) ? galleryImages : [galleryImages]) : []; + blog.quote = quote || ''; + blog.contentAfterQuote = contentAfterQuote || ''; - // Handle featured image - if (req.file) { - blog.featuredImage = `/uploads/blog/${req.file.filename}`; + // Handle featured image - using featuredImageUrl from form (uploaded via AJAX) + if (req.body.featuredImageUrl) { + blog.featuredImage = req.body.featuredImageUrl; } // Generate new slug if title changed @@ -373,11 +390,30 @@ exports.apiShow = async (req, res) => { }); } - // Get comments for this post - const comments = await BlogComment.getApprovedByPost(blog._id); + // Get comments for this post (parent comments only) + const parentComments = await BlogComment.getApprovedByPost(blog._id); + + // Get replies for each parent comment + const commentsWithReplies = await Promise.all( + parentComments.map(async (parentComment) => { + const replies = await BlogComment.getReplies(parentComment._id); + return { + ...parentComment.toObject(), + replies: replies.map(reply => reply.toObject()) + }; + }) + ); + + // Flatten comments array (parent + replies) + const allComments = commentsWithReplies.flatMap(comment => [ + comment, + ...comment.replies + ]); // Add comments to blog - blog.comments = comments; + blog.comments = allComments; + // Keep commentsCount in sync for frontend + blog.commentsCount = allComments.length; // Add base URL to images const baseUrl = process.env.BACKEND_URL || `${req.protocol}://${req.get('host')}`; @@ -398,6 +434,72 @@ exports.apiShow = async (req, res) => { } }; +// Create a comment (no moderation for now: default approved) +exports.apiCreateComment = async (req, res) => { + try { + const { authorName, content, parentId } = req.body || {}; + + if (!authorName || !String(authorName).trim()) { + return res.status(400).json({ + success: false, + message: "authorName is required", + }); + } + + if (!content || !String(content).trim()) { + return res.status(400).json({ + success: false, + message: "content is required", + }); + } + + const blog = await Blog.findOne({ slug: req.params.slug, status: "published" }).lean(); + if (!blog) { + return res.status(404).json({ + success: false, + message: "Blog post not found", + }); + } + + // If replying, ensure parent exists and belongs to same post + let parentObjectId = null; + if (parentId) { + const parent = await BlogComment.findOne({ _id: parentId, postId: blog._id }).lean(); + if (!parent) { + return res.status(400).json({ + success: false, + message: "Invalid parentId", + }); + } + parentObjectId = parentId; + } + + const newComment = await BlogComment.create({ + postId: blog._id, + authorName: String(authorName).trim(), + content: String(content).trim(), + parentId: parentObjectId, + status: "approved", + }); + + // Keep counter roughly correct (also counts replies) + await Blog.updateOne({ _id: blog._id }, { $inc: { commentsCount: 1 } }); + + return res.json({ + success: true, + message: "Comment created successfully", + data: newComment.toJSON(), + }); + } catch (err) { + console.error("Create comment API error:", err); + return res.status(500).json({ + success: false, + message: "Error creating comment", + error: err.message || "Error creating comment", + }); + } +}; + // Get featured blogs exports.apiFeatured = async (req, res) => { try { @@ -408,7 +510,7 @@ exports.apiFeatured = async (req, res) => { .lean(); // Add base URL to images - const baseUrl = process.env.BACKEND_URL || `${req.protocol}://${req.get('host')}`; + const baseUrl = process.env.BACKEND_URL || `${req.protocol}://${req.get('port')}`; const processedBlogs = blogs.map(blog => addBaseUrlToImages(blog, baseUrl)); res.json({ diff --git a/controllers/blogTagController.js b/controllers/blogTagController.js index f4232ef..6daeb6b 100644 --- a/controllers/blogTagController.js +++ b/controllers/blogTagController.js @@ -1,4 +1,5 @@ const BlogTag = require('../models/blogTag'); +const slugify = require('slugify'); // -------------------- Admin Controllers -------------------- @@ -48,12 +49,11 @@ exports.store = async (req, res) => { } = req.body; // Generate slug - const slug = name - .toLowerCase() - .replace(/[^a-z0-9\s-]/g, '') - .replace(/\s+/g, '-') - .replace(/-+/g, '-') - .trim('-'); + const slug = slugify(name, { + lower: true, + strict: true, + locale: 'vi' + }); // Check if slug exists const existingTag = await BlogTag.findOne({ slug }); @@ -126,12 +126,11 @@ exports.update = async (req, res) => { tag.isActive = isActive === 'on'; // Generate new slug if name changed - const newSlug = name - .toLowerCase() - .replace(/[^a-z0-9\s-]/g, '') - .replace(/\s+/g, '-') - .replace(/-+/g, '-') - .trim('-'); + const newSlug = slugify(name, { + lower: true, + strict: true, + locale: 'vi' + }); if (newSlug !== tag.slug) { const existingTag = await BlogTag.findOne({ @@ -162,6 +161,14 @@ exports.destroy = async (req, res) => { const tag = await BlogTag.findById(req.params.id); if (!tag) { + // Check if it's an AJAX request + const isAjax = req.xhr || req.headers['accept']?.includes('application/json') || req.headers['content-type']?.includes('application/json'); + if (isAjax) { + return res.status(404).json({ + success: false, + message: 'Tag not found' + }); + } req.flash('error_msg', 'Tag not found'); return res.redirect('/admin/blog/tags'); } @@ -171,16 +178,44 @@ exports.destroy = async (req, res) => { const postCount = await Blog.countDocuments({ tags: { $in: [tag.name] } }); if (postCount > 0) { + // Check if it's an AJAX request + const isAjax = req.xhr || req.headers['accept']?.includes('application/json') || req.headers['content-type']?.includes('application/json'); + if (isAjax) { + return res.status(400).json({ + success: false, + message: 'Cannot delete tag that is used in blog posts' + }); + } req.flash('error_msg', 'Cannot delete tag that is used in blog posts'); return res.redirect('/admin/blog/tags'); } await BlogTag.findByIdAndDelete(req.params.id); + // Check if it's an AJAX request + const isAjax = req.xhr || req.headers['accept']?.includes('application/json') || req.headers['content-type']?.includes('application/json'); + if (isAjax) { + return res.json({ + success: true, + message: 'Tag deleted successfully' + }); + } + req.flash('success_msg', 'Tag deleted successfully'); res.redirect('/admin/blog/tags'); } catch (err) { console.error('Tag delete error:', err); + + // Check if it's an AJAX request + const isAjax = req.xhr || req.headers['accept']?.includes('application/json') || req.headers['content-type']?.includes('application/json'); + if (isAjax) { + return res.status(500).json({ + success: false, + message: 'Error deleting tag', + error: err.message || 'Error deleting tag' + }); + } + req.flash('error_msg', 'Error deleting tag'); res.redirect('/admin/blog/tags'); } @@ -198,10 +233,18 @@ exports.api = async (req, res) => { await tag.updatePostCount(); } - res.json(tags); + res.json({ + success: true, + message: 'Tags fetched successfully', + data: tags + }); } catch (err) { console.error('Tags API error:', err); - res.status(500).json({ error: 'Error loading tags' }); + res.status(500).json({ + success: false, + message: 'Error loading tags', + error: err.message || 'Error loading tags' + }); } }; @@ -210,10 +253,19 @@ exports.apiPopular = async (req, res) => { try { const limit = parseInt(req.query.limit) || 10; const tags = await BlogTag.getPopular(limit); - res.json(tags); + + res.json({ + success: true, + message: 'Popular tags fetched successfully', + data: tags + }); } catch (err) { console.error('Popular tags API error:', err); - res.status(500).json({ error: 'Error loading popular tags' }); + res.status(500).json({ + success: false, + message: 'Error loading popular tags', + error: err.message || 'Error loading popular tags' + }); } }; @@ -226,13 +278,80 @@ exports.apiShow = async (req, res) => { }).lean(); if (!tag) { - return res.status(404).json({ error: 'Tag not found' }); + return res.status(404).json({ + success: false, + message: 'Tag not found' + }); } - res.json(tag); + res.json({ + success: true, + message: 'Tag fetched successfully', + data: tag + }); } catch (err) { console.error('Tag show API error:', err); - res.status(500).json({ error: 'Error loading tag' }); + res.status(500).json({ + success: false, + message: 'Error loading tag', + error: err.message || 'Error loading tag' + }); + } +}; + +// Quick create tag (for inline creation in blog form) +exports.quickCreate = async (req, res) => { + try { + const { name } = req.body; + + if (!name || !name.trim()) { + return res.status(400).json({ + success: false, + message: 'Tag name is required' + }); + } + + const tagName = name.trim(); + + // Generate slug + const slug = slugify(tagName, { + lower: true, + strict: true, + locale: 'vi' + }); + + // Check if tag already exists + let tag = await BlogTag.findOne({ slug }); + + if (tag) { + return res.json({ + success: true, + message: 'Tag already exists', + data: tag.toObject() + }); + } + + // Create new tag + tag = new BlogTag({ + name: tagName, + slug, + isActive: true + }); + + await tag.save(); + + res.json({ + success: true, + message: 'Tag created successfully', + data: tag.toObject() + }); + } catch (err) { + console.error('Quick create tag error:', err); + res.status(500).json({ + success: false, + message: 'Error creating tag', + error: err.message || 'Error creating tag' + }); } }; diff --git a/controllers/serviceController.js b/controllers/serviceController.js new file mode 100644 index 0000000..33b36ac --- /dev/null +++ b/controllers/serviceController.js @@ -0,0 +1,360 @@ +const { getServiceData } = require("../services/service.service"); +const Service = require("../models/service"); +const { addBaseUrlToImages, getFullImageUrl } = require("../utils/imageHelper"); +const slugify = require("slugify"); + +// Admin page - Service list +exports.index = async (req, res) => { + try { + const data = await getServiceData(); + console.log(data.services.items.image); + res.render("admin/service/index", { + title: "Service Management", + data, + layout: "layouts/main", + getFullImageUrl, // Truyền helper function vào view + }); + } catch (err) { + console.error(err); + req.flash("error_msg", "Error loading service data"); + res.redirect("/admin/dashboard"); + } +}; + +// Admin page - Service edit +exports.edit = async (req, res) => { + try { + const { slug } = req.params; + const data = await getServiceData(); + + const service = data.services?.items?.find((item) => item.slug === slug); + if (!service) { + req.flash("error_msg", "Service not found"); + return res.redirect("/admin/service"); + } + + res.render("admin/service/edit", { + title: `Edit Service - ${service.name}`, + service, + layout: "layouts/main", + getFullImageUrl, + }); + } catch (err) { + console.error(err); + req.flash("error_msg", "Error loading service for editing"); + res.redirect("/admin/service"); + } +}; + +// Update single service +exports.updateService = async (req, res) => { + try { + const { slug } = req.params; + const currentData = await getServiceData(); + + const serviceIndex = currentData.services?.items?.findIndex( + (item) => item.slug === slug, + ); + if (serviceIndex === -1) { + req.flash("error_msg", "Service not found"); + return res.redirect("/admin/service"); + } + + // Update service data + const updatedData = { ...currentData.toObject?.() }; + updatedData.services.items[serviceIndex] = { + ...updatedData.services.items[serviceIndex], + name: req.body.name, + slug: req.body.slug, + description: req.body.description, + image: req.body.image, + layout: req.body.layout, + }; + + if (currentData._id) { + await Service.findByIdAndUpdate(currentData._id, updatedData); + } else { + await Service.create(updatedData); + } + + req.flash("success_msg", "Service updated successfully"); + res.redirect("/admin/service"); + } catch (err) { + console.error(err); + req.flash("error_msg", err.message); + res.redirect("/admin/service"); + } +}; + +// Admin page - Service details +exports.details = async (req, res) => { + try { + const { slug } = req.params; + const data = await getServiceData(); + + const service = data.services?.items?.find((item) => item.slug === slug); + if (!service) { + req.flash("error_msg", "Service not found"); + return res.redirect("/admin/service"); + } + + res.render("admin/service/details", { + title: `Service Details - ${service.name}`, + service, + layout: "layouts/main", + getFullImageUrl, // Truyền helper function vào view + }); + } catch (err) { + console.error(err); + req.flash("error_msg", "Error loading service details"); + res.redirect("/admin/service"); + } +}; + +// Update service list +exports.update = async (req, res) => { + try { + const currentData = await getServiceData(); + const sections = [ + "pageTitle", + "services", + "destinations", + "visas", + "reviews", + ]; + + let updatedData = { ...currentData.toObject?.() }; + let hasChanges = false; + + sections.forEach((section) => { + if (!req.body[section]) return; + + const newData = JSON.parse(req.body[section]); + if (JSON.stringify(newData) !== JSON.stringify(currentData[section])) { + updatedData[section] = newData; + hasChanges = true; + } + }); + + if (!hasChanges) { + req.flash("info_msg", "No changes were made"); + return res.redirect("/admin/service"); + } + + if (currentData._id) { + await Service.findByIdAndUpdate(currentData._id, updatedData); + } else { + await Service.create(updatedData); + } + + req.flash("success_msg", "Service updated successfully"); + res.redirect("/admin/service"); + } catch (err) { + console.error(err); + req.flash("error_msg", err.message); + res.redirect("/admin/service"); + } +}; + +// Update service details +exports.updateDetails = async (req, res) => { + try { + const { slug } = req.params; + const currentData = await getServiceData(); + + const serviceIndex = currentData.services?.items?.findIndex( + (item) => item.slug === slug, + ); + if (serviceIndex === -1) { + req.flash("error_msg", "Service not found"); + return res.redirect("/admin/service"); + } + + // Parse features and FAQ from JSON strings + const features = req.body.features ? JSON.parse(req.body.features) : []; + const faq = req.body.faq ? JSON.parse(req.body.faq) : []; + + // Update service details + const updatedData = { ...currentData.toObject?.() }; + updatedData.services.items[serviceIndex].details = { + title: req.body.title, + description: req.body.description, + mainImage: req.body.mainImage, + overviewTitle: req.body.overviewTitle, + overviewDescription: req.body.overviewDescription, + additionalDescription: req.body.additionalDescription, + keyFeaturesTitle: req.body.keyFeaturesTitle, + keyFeaturesImage: req.body.keyFeaturesImage, + features: features, + faqTitle: req.body.faqTitle, + faqImage: req.body.faqImage, + faq: faq, + }; + + if (currentData._id) { + await Service.findByIdAndUpdate(currentData._id, updatedData); + } else { + await Service.create(updatedData); + } + + req.flash("success_msg", "Service details updated successfully"); + res.redirect(`/admin/service/${slug}/details`); + } catch (err) { + console.error(err); + req.flash("error_msg", err.message); + res.redirect("/admin/service"); + } +}; + +// API endpoint +exports.api = async (req, res) => { + try { + const serviceData = await getServiceData(); + const baseUrl = + process.env.BACKEND_URL || `${req.protocol}://${req.get("host")}`; + + const processedData = addBaseUrlToImages(serviceData, baseUrl); + res.json(processedData); + } catch (err) { + res.status(500).json({ error: "Error loading service data" }); + } +}; + +/** + * Get service details by slug - API endpoint + */ +exports.getServiceBySlug = async (req, res) => { + try { + const { slug } = req.params; + + const serviceDoc = await Service.findOne().lean(); + + if (!serviceDoc) { + return res.status(404).json({ + success: false, + message: "Service data not found", + }); + } + + // Find service by slug + const service = serviceDoc.services?.items?.find( + (item) => item.slug === slug, + ); + + if (!service) { + return res.status(404).json({ + success: false, + message: `Service with slug '${slug}' not found`, + }); + } + + const baseUrl = + process.env.BACKEND_URL || `${req.protocol}://${req.get("host")}`; + + // Return service details in the expected format + const responseData = { + pageTitle: serviceDoc.pageTitle, + breadcrumb: { + ...serviceDoc.breadcrumb, + title: "Service Details", + items: [ + { label: "Home", href: "/" }, + { label: "Services", href: "/services" }, + { label: service.name, href: `/services/${slug}` }, + ], + }, + serviceDetails: { + content: service.details, + keyFeatures: { + title: service.details.keyFeaturesTitle || "Key Features", + sideImage: service.details.keyFeaturesImage || "img/default.jpg", + items: service.details.features || [], + }, + faq: { + title: service.details.faqTitle || "Frequently Asked Questions", + sideImage: service.details.faqImage || "img/default.jpg", + items: service.details.faq || [], + }, + }, + }; + + const processedData = addBaseUrlToImages(responseData, baseUrl); + res.json(processedData); + } catch (error) { + console.error("Error fetching service by slug:", error); + res.status(500).json({ + success: false, + message: "Internal server error", + error: error.message, + }); + } +}; + +/** + * Generate slug from text - API endpoint + */ +exports.generateSlug = async (req, res) => { + try { + const { text } = req.body; + + if (!text || typeof text !== "string") { + return res.status(400).json({ + success: false, + message: "Text is required", + }); + } + + // Generate slug using slugify library with Vietnamese support + const slug = slugify(text, { + lower: true, + strict: true, + locale: "vi", + }); + + res.json({ + success: true, + slug: slug, + }); + } catch (error) { + console.error("Error generating slug:", error); + res.status(500).json({ + success: false, + message: "Internal server error", + error: error.message, + }); + } +}; + +/** + * Get all service slugs - API endpoint + */ +exports.getServiceSlugs = async (req, res) => { + try { + const serviceDoc = await Service.findOne().lean(); + + if (!serviceDoc?.services?.items) { + return res.json({ + success: true, + slugs: [], + }); + } + + const slugs = serviceDoc.services.items.map((item) => ({ + slug: item.slug, + name: item.name, + id: item.id, + })); + + res.json({ + success: true, + slugs, + }); + } catch (error) { + console.error("Error fetching service slugs:", error); + res.status(500).json({ + success: false, + message: "Internal server error", + error: error.message, + }); + } +}; diff --git a/data/blog.json b/data/blog.json index e04489c..4a6b1d2 100644 --- a/data/blog.json +++ b/data/blog.json @@ -50,43 +50,53 @@ "status": "published", "publishedAt": "11 March 2025", "isFeatured": true, - "featuredImage": "/uploads/blog/work-visa-canada-main.jpg", + "featuredImage": "/assets/img/inner-page/news-details/details-1.jpg", "galleryImages": [ - "/uploads/blog/work-visa-canada-1.jpg", - "/uploads/blog/work-visa-canada-2.jpg" + "/assets/img/inner-page/news-details/details-2.jpg", + "/assets/img/inner-page/news-details/details-3.jpg" ], + "quote": "This blog really helped me understand the difference between student and work visas. The explanations were clear and practical.", + "contentAfterQuote": "
It provides access to world-class universities, cultural exposure, and global networking opportunities. With a student visa, you may also get part-time work rights, which can help support your expenses and give you valuable international work experience. However, the primary focus remains on academics and personal growth. On the other hand, a work visa is perfect for those who want to establish themselves in a career overseas.
It provides immediate access to job markets, stable income, and often a pathway to permanent residency. Work visas are suitable for skilled professionals who are ready to contribute to the global workforce and achieve long-term career goals. Ultimately, the choice comes down to your personal aspirations. If education and exploration are your priorities, a student visa is ideal. If career advancement and stability are your goals, a work visa is the right fit.
", "commentsCount": 3 }, { "title": "Top 5 Scholarship Programs For International Students", "slug": "top-5-scholarship-programs-international-students", "excerpt": "Danh sách 5 chương trình học bổng nổi bật dành cho sinh viên quốc tế với mức hỗ trợ hấp dẫn.", - "content": "Nếu bạn đang tìm kiếm học bổng để giảm chi phí du học, đây là 5 chương trình bạn không nên bỏ qua. Mỗi chương trình đều có tiêu chí xét tuyển, mức hỗ trợ và thời hạn đăng ký khác nhau.
", + "content": "Nếu bạn đang tìm kiếm học bổng để giảm chi phí du học, đây là 5 chương trình bạn không nên bỏ qua. Mỗi chương trình đều có tiêu chí xét tuyển, mức hỗ trợ và thời hạn đăng ký khác nhau.
Học bổng là một trong những cách tốt nhất để giảm gánh nặng tài chính khi du học. Các chương trình học bổng không chỉ hỗ trợ về mặt tài chính mà còn mở ra nhiều cơ hội phát triển nghề nghiệp và mở rộng mạng lưới quan hệ quốc tế.
", "category": ["Study Abroad"], "tags": ["StudentVisa", "Scholarship"], "author": "Admin", "status": "published", "publishedAt": "20 March 2025", "isFeatured": false, - "featuredImage": "/uploads/blog/scholarship-programs-main.jpg", - "galleryImages": [], - "commentsCount": 0 + "featuredImage": "/assets/img/inner-page/news-details/details-1.jpg", + "galleryImages": [ + "/assets/img/inner-page/news-details/details-2.jpg", + "/assets/img/inner-page/news-details/details-3.jpg" + ], + "quote": "These scholarship programs opened doors I never thought possible. The application process was straightforward, and the support I received was incredible.", + "contentAfterQuote": "Applying for scholarships requires careful planning and preparation. Start by researching each program's requirements, deadlines, and eligibility criteria. Make sure to prepare all necessary documents well in advance, including transcripts, recommendation letters, and personal statements. Each scholarship has its own unique focus, so tailor your application to highlight how you align with their values and goals.
Remember that scholarship applications are competitive, so it's important to stand out. Showcase your academic achievements, extracurricular activities, and community involvement. Be authentic in your personal statement and demonstrate how the scholarship will help you achieve your educational and career aspirations. With dedication and proper preparation, you can increase your chances of securing financial support for your studies abroad.
", + "commentsCount": 2 }, { "title": "10 Travel Safety Tips You Should Know Before Flying", "slug": "10-travel-safety-tips-before-flying", "excerpt": "Những lưu ý quan trọng để đảm bảo an toàn cho chuyến bay và hành trình của bạn.", - "content": "An toàn luôn là ưu tiên hàng đầu khi đi du lịch. Dưới đây là 10 tips giúp bạn yên tâm hơn trên mọi chuyến đi, từ việc chuẩn bị giấy tờ, bảo hiểm đến cách bảo vệ tài sản cá nhân.
", + "content": "An toàn luôn là ưu tiên hàng đầu khi đi du lịch. Dưới đây là 10 tips giúp bạn yên tâm hơn trên mọi chuyến đi, từ việc chuẩn bị giấy tờ, bảo hiểm đến cách bảo vệ tài sản cá nhân.
Du lịch là một trải nghiệm tuyệt vời, nhưng điều quan trọng là phải chuẩn bị kỹ lưỡng để đảm bảo an toàn. Những tips này được đúc kết từ kinh nghiệm thực tế của nhiều du khách và sẽ giúp bạn tránh được những rủi ro không đáng có.
", "category": ["Travel Tips"], "tags": ["TravelSafety"], "author": "Admin", "status": "published", "publishedAt": "05 April 2025", "isFeatured": false, - "featuredImage": "/uploads/blog/travel-safety-main.jpg", + "featuredImage": "/assets/img/inner-page/news-details/details-1.jpg", "galleryImages": [ - "/uploads/blog/travel-safety-1.jpg" + "/assets/img/inner-page/news-details/details-2.jpg", + "/assets/img/inner-page/news-details/details-3.jpg" ], + "quote": "These safety tips saved me from potential problems during my trip. I especially appreciated the advice about travel insurance and document preparation.", + "contentAfterQuote": "Before you travel, make sure to research your destination thoroughly. Understand local customs, laws, and potential safety concerns. Keep copies of important documents like your passport, visa, and travel insurance in multiple places - both physical and digital. Inform family or friends about your itinerary and check in regularly during your trip.
When packing, prioritize essential items and keep valuables secure. Use luggage locks and consider travel insurance for expensive items. Stay aware of your surroundings, especially in crowded areas, and trust your instincts if something feels off. By following these safety tips, you can focus on enjoying your journey while staying protected throughout your travels.
", "commentsCount": 1 } ], @@ -94,19 +104,19 @@ { "title": "Ultimate Guide To Getting A Work Visa In Canada", "slug": "ultimate-guide-work-visa-canada", - "thumbnail": "/uploads/blog/work-visa-canada-main.jpg", + "thumbnail": "/assets/img/inner-page/news-details/post-1.jpg", "publishedAt": "11 March 2025" }, { "title": "Top 5 Scholarship Programs For International Students", "slug": "top-5-scholarship-programs-international-students", - "thumbnail": "/uploads/blog/scholarship-programs-main.jpg", + "thumbnail": "/assets/img/inner-page/news-details/post-2.jpg", "publishedAt": "20 March 2025" }, { "title": "10 Travel Safety Tips You Should Know Before Flying", "slug": "10-travel-safety-tips-before-flying", - "thumbnail": "/uploads/blog/travel-safety-main.jpg", + "thumbnail": "/assets/img/inner-page/news-details/post-3.jpg", "publishedAt": "05 April 2025" } ], @@ -129,6 +139,24 @@ "status": "approved", "parentAuthorName": "Frank Flores" }, + { + "postSlug": "top-5-scholarship-programs-international-students", + "authorName": "Sarah Johnson", + "authorAvatar": "/assets/img/inner-page/news-details/comment-1.png", + "content": "Cảm ơn bạn đã chia sẻ thông tin về các chương trình học bổng này. Mình đã apply và đang chờ kết quả!", + "createdAt": "March 15, 2025", + "status": "approved", + "parentAuthorName": null + }, + { + "postSlug": "top-5-scholarship-programs-international-students", + "authorName": "Michael Chen", + "authorAvatar": "/assets/img/inner-page/news-details/comment-2.png", + "content": "Bài viết rất chi tiết và hữu ích. Mình đã tìm thấy một chương trình phù hợp với mình.", + "createdAt": "March 18, 2025", + "status": "approved", + "parentAuthorName": null + }, { "postSlug": "10-travel-safety-tips-before-flying", "authorName": "Jenny Wilson", diff --git a/data/service.json b/data/service.json new file mode 100644 index 0000000..0b524c7 --- /dev/null +++ b/data/service.json @@ -0,0 +1,363 @@ +{ + "pageTitle": "Visaway – Immigration & Visa Consulting HTML Template", + + "services": { + "title": { + "subTitle": "What We Offer", + "mainTitle": "Our Immigration Services" + }, + "items": [ + { + "slug": "immigration-appeal", + "name": "Immigration Appeal & Legal Support", + "description": "Our experts provide professional guidance for immigration appeals and legal matters, helping clients overcome visa rejections with personalized strategies and strong case representation.", + "image": "img/home-3/service/01.jpg", + "layout": "left", + "details": { + "title": "Immigration Appeal & Legal Support", + "description": "Our experts provide professional guidance for immigration appeals and legal matters, helping clients overcome visa rejections with personalized strategies and strong case representation. We analyze your case thoroughly and develop custom strategies to maximize your chances of success.", + "mainImage": "img/inner-page/service-details/details-1.jpg", + "overviewTitle": "Service Overview", + "overviewDescription": "Our Immigration Appeal & Legal Support service is designed to help clients navigate complex immigration challenges. We provide expert legal guidance, case analysis, and strategic representation to maximize your chances of success. With our expert consultants, personalized approach, and global network, we ensure a smooth transition for every client.", + "additionalDescription": "From start to finish, we are committed to turning your immigration challenges into success stories through professional legal representation and strategic planning.", + "keyFeaturesTitle": "Key Features", + "keyFeaturesImage": "img/inner-page/service-details/details-2.jpg", + "features": [ + { + "title": "Personalized Guidance", + "description": "Tailored support for each client's specific legal situation and requirements." + }, + { + "title": "Expert Legal Team", + "description": "Experienced immigration lawyers with proven track records in appeals." + }, + { + "title": "Case Analysis & Strategy", + "description": "Thorough case review and development of winning appeal strategies." + }, + { + "title": "Document Preparation", + "description": "Professional preparation of all legal documents and supporting evidence." + }, + { + "title": "Court Representation", + "description": "Expert representation in immigration courts and tribunals." + }, + { + "title": "Success Monitoring", + "description": "Regular updates and monitoring throughout the appeal process." + } + ], + "faqTitle": "Frequently Asked Question", + "faqImage": "img/inner-page/service-details/details-3.jpg", + "faq": [ + { + "id": "faq-appeal-1", + "question": "01. What are the chances of a successful appeal?", + "answer": "Success rates vary by case type and circumstances, but our experienced legal team significantly improves your chances through thorough case analysis and strategic representation tailored to your specific situation.", + "isExpanded": false + }, + { + "id": "faq-appeal-2", + "question": "02. How long does the appeal process take?", + "answer": "Appeal timelines vary by jurisdiction and case complexity, typically ranging from 6-18 months. We keep you informed throughout the process and work to expedite where possible.", + "isExpanded": false + }, + { + "id": "faq-appeal-3", + "question": "03. What documents do I need for an appeal?", + "answer": "Required documents vary by case but typically include the original decision, supporting evidence, and legal submissions. We provide a comprehensive checklist and assist with document preparation.", + "isExpanded": false + }, + { + "id": "faq-appeal-4", + "question": "04. Do you handle all types of immigration appeals?", + "answer": "Yes, we handle various types of immigration appeals including visa refusals, deportation orders, and residency rejections. Our team has expertise across all immigration categories.", + "isExpanded": false + } + ] + } + }, + { + "slug": "scholarship-guidance", + "name": "Scholarship & Study Grant Guidance", + "description": "We help students unlock opportunities to study abroad with the right financial support. Our expert advisors guide you in finding scholarships, grants, and funding options that match your academic background, chosen destination, and career goals.", + "image": "img/home-3/service/02.jpg", + "layout": "right", + "details": { + "title": "Scholarship & Study Grant Guidance", + "description": "We help students unlock opportunities to study abroad with the right financial support. Our expert advisors guide you in finding scholarships, grants, and funding options that match your academic background, chosen destination, and career goals. From preparing strong applications to meeting eligibility criteria, we ensure you maximize your chances of securing financial aid.", + "mainImage": "img/inner-page/service-details/details-1.jpg", + "overviewTitle": "Service Overview", + "overviewDescription": "Our Education Visa Consultancy is dedicated to guiding students in achieving their study abroad dreams. We provide complete support including university selection, application assistance, scholarship guidance, visa documentation, and interview preparation. With our expert consultants, personalized approach, and global network, we ensure a smooth transition for every student.", + "additionalDescription": "From start to finish, we are committed to turning your education journey into a successful international experience.", + "keyFeaturesTitle": "Key Features", + "keyFeaturesImage": "img/inner-page/service-details/details-2.jpg", + "features": [ + { + "title": "Personalized Guidance", + "description": "Tailored support for each student's goals and requirements." + }, + { + "title": "Target Audience & Persona Development", + "description": "Experienced team with global education and visa knowledge." + }, + { + "title": "Scholarship & Grant Assistance", + "description": "Helping students secure financial aid opportunities." + }, + { + "title": "Visa Application Support", + "description": "Step-by-step guidance for smooth visa processing." + }, + { + "title": "Interview Preparation", + "description": "Coaching for successful student visa interviews." + }, + { + "title": "Documentation Assistance", + "description": "Accurate and complete paperwork for faster approvals." + } + ], + "faqTitle": "Frequently Asked Question", + "faqImage": "img/inner-page/service-details/details-3.jpg", + "faq": [ + { + "id": "faq-scholarship-1", + "question": "01. Do you assist with university selection?", + "answer": "Absolutely! We identify suitable scholarships, guide application processes, and maximize your chances of receiving financial aid.", + "isExpanded": false + }, + { + "id": "faq-scholarship-2", + "question": "02. Can you help with scholarship applications?", + "answer": "Absolutely! We identify suitable scholarships, guide application processes, and maximize your chances of receiving financial aid.", + "isExpanded": true + }, + { + "id": "faq-scholarship-3", + "question": "03. How long does the visa process take?", + "answer": "Absolutely! We identify suitable scholarships, guide application processes, and maximize your chances of receiving financial aid.", + "isExpanded": false + }, + { + "id": "faq-scholarship-4", + "question": "04. Is post-arrival support available?", + "answer": "Absolutely! We identify suitable scholarships, guide application processes, and maximize your chances of receiving financial aid.", + "isExpanded": false + } + ] + } + }, + { + "slug": "permanent-residency", + "name": "Permanent Residency (PR) Services", + "description": "Our PR services guide clients through every step of the residency process, including documentation, eligibility assessment, and application support, ensuring a smooth and successful approval.", + "image": "img/home-3/service/03.jpg", + "layout": "left", + "details": { + "title": "Permanent Residency (PR) Services", + "description": "Our PR services guide clients through every step of the residency process, including documentation, eligibility assessment, and application support, ensuring a smooth and successful approval.", + "mainImage": "img/inner-page/service-details/details-1.jpg", + "overviewTitle": "Service Overview", + "overviewDescription": "Our Permanent Residency services provide comprehensive support for individuals seeking to establish permanent residence in their chosen country. We handle all aspects of the PR application process with expertise and care.", + "additionalDescription": "Our experienced team ensures that your PR application is handled professionally and efficiently, maximizing your chances of approval.", + "keyFeaturesTitle": "Key Features", + "keyFeaturesImage": "img/inner-page/service-details/details-2.jpg", + "features": [ + { + "title": "Eligibility Assessment", + "description": "Comprehensive evaluation of your PR eligibility and options." + }, + { + "title": "Points Calculation", + "description": "Accurate calculation and optimization of your points score." + }, + { + "title": "Document Verification", + "description": "Thorough verification and preparation of all required documents." + }, + { + "title": "Application Tracking", + "description": "Regular updates and tracking of your PR application status." + }, + { + "title": "Interview Preparation", + "description": "Coaching and preparation for PR interviews if required." + }, + { + "title": "Post-Approval Support", + "description": "Guidance on next steps after PR approval and settlement." + } + ], + "faqTitle": "Frequently Asked Question", + "faqImage": "img/inner-page/service-details/details-3.jpg", + "faq": [ + { + "id": "faq-pr-1", + "question": "01. How long does the PR process take?", + "answer": "Processing times vary by country and program, typically ranging from 12-24 months. We provide realistic timelines based on current processing standards.", + "isExpanded": false + }, + { + "id": "faq-pr-2", + "question": "02. What documents are required for PR application?", + "answer": "Document requirements vary by country but typically include educational credentials, work experience, language test results, and medical examinations. We provide a complete checklist.", + "isExpanded": true + }, + { + "id": "faq-pr-3", + "question": "03. Can I include my family in the PR application?", + "answer": "Yes, most PR programs allow you to include your spouse and dependent children. We help you understand family inclusion requirements and processes.", + "isExpanded": false + }, + { + "id": "faq-pr-4", + "question": "04. What happens if my PR application is rejected?", + "answer": "If rejected, we analyze the reasons and explore options including appeals, reapplication, or alternative immigration pathways to achieve your goals.", + "isExpanded": false + } + ] + } + }, + { + "slug": "citizenship-naturalization", + "name": "Citizenship & Naturalization Guidance", + "description": "We provide expert guidance for citizenship and naturalization processes, assisting clients with documentation, eligibility, and legal procedures to achieve a smooth and successful application.", + "image": "img/home-3/service/04.jpg", + "layout": "right", + "details": { + "title": "Citizenship & Naturalization Guidance", + "description": "We provide expert guidance for citizenship and naturalization processes, assisting clients with documentation, eligibility, and legal procedures to achieve a smooth and successful application.", + "mainImage": "img/inner-page/service-details/details-1.jpg", + "overviewTitle": "Service Overview", + "overviewDescription": "Our Citizenship & Naturalization service helps individuals navigate the complex process of becoming a citizen. We provide step-by-step guidance, documentation support, and legal expertise throughout the entire process.", + "additionalDescription": "With our comprehensive approach, we make the path to citizenship clear, manageable, and successful for every client.", + "keyFeaturesTitle": "Key Features", + "keyFeaturesImage": "img/inner-page/service-details/details-2.jpg", + "features": [ + { + "title": "Citizenship Test Preparation", + "description": "Comprehensive preparation for citizenship knowledge tests." + }, + { + "title": "Language Requirements", + "description": "Guidance on meeting language proficiency requirements." + }, + { + "title": "Residency Verification", + "description": "Assistance with proving residency and physical presence requirements." + }, + { + "title": "Application Processing", + "description": "Complete support throughout the citizenship application process." + }, + { + "title": "Interview Coaching", + "description": "Preparation and coaching for citizenship interviews." + }, + { + "title": "Ceremony Preparation", + "description": "Support and guidance for the citizenship ceremony process." + } + ], + "faqTitle": "Frequently Asked Question", + "faqImage": "img/inner-page/service-details/details-3.jpg", + "faq": [ + { + "id": "faq-citizenship-1", + "question": "What are the basic requirements for citizenship?", + "answer": "Requirements typically include permanent residency, physical presence, language proficiency, and knowledge of the country's history and government. Specific requirements vary by country.", + "isExpanded": false + }, + { + "id": "faq-citizenship-2", + "question": "How do I prepare for the citizenship test?", + "answer": "We provide comprehensive study materials, practice tests, and coaching sessions to help you prepare for both the knowledge test and language requirements.", + "isExpanded": false + }, + { + "id": "faq-citizenship-3", + "question": "How long does the citizenship process take?", + "answer": "Processing times vary by country but typically range from 12-24 months from application to ceremony. We help you understand specific timelines for your situation.", + "isExpanded": false + }, + { + "id": "faq-citizenship-4", + "question": "Can I maintain dual citizenship?", + "answer": "Dual citizenship policies vary by country. We help you understand the implications and requirements for maintaining multiple citizenships if applicable.", + "isExpanded": false + } + ] + } + } + ] + }, + + "destinations": { + "backgroundImage": "img/home-3/choose-us/bg.png", + "title": { + "subTitle": "Countries we offer", + "mainTitle": "Choose Your Immigration Destination" + } + }, + + "visas": { + "items": [ + { + "id": "family-visa", + "number": "01", + "name": "Family Visa", + "description": "Our Family Visa services help reunite loved ones by providing expert guidance.", + "buttonText": "service _ 02", + "buttonLink": "service-details.html" + }, + { + "id": "student-visa", + "number": "02", + "name": "Student Visa", + "description": "We provide expert guidance for student visa applications.", + "buttonText": "service _ 02", + "buttonLink": "service-details.html" + }, + { + "id": "work-visa", + "number": "03", + "name": "Work Visa", + "description": "Collaboratively disintermediate one to one functionalities and long term.", + "buttonText": "service _ 02", + "buttonLink": "service-details.html" + } + ] + }, + + "reviews": { + "title": { + "subTitle": "What Our Clients Say", + "mainTitle": "Immigration Success Stories" + }, + "thumb": "img/home-3/test-thumb.jpg", + "items": [ + { + "id": "client-review-1", + "rating": 5, + "content": "The team provided exceptional guidance throughout my immigration process.", + "author": { + "name": "Mohammed Ali,", + "type": "Family Visa" + }, + "icon": "fa-solid fa-quote-right" + }, + { + "id": "client-review-2", + "rating": 5, + "content": "Their expertise and personalized support ensured a smooth visa approval.", + "author": { + "name": "Sarah Johnson,", + "type": "Student Visa" + }, + "icon": "fa-solid fa-quote-right" + } + ] + } +} diff --git a/models/blog.js b/models/blog.js index 39aea69..89bf9bb 100644 --- a/models/blog.js +++ b/models/blog.js @@ -71,6 +71,20 @@ const blogSchema = new mongoose.Schema({ commentsCount: { type: Number, default: 0 + }, + + // Quote/Sidebar section + quote: { + type: String, + default: '', + trim: true + }, + + // Content after quote + contentAfterQuote: { + type: String, + default: '', + trim: true } }, { timestamps: true diff --git a/models/service.js b/models/service.js new file mode 100644 index 0000000..a1d0f2e --- /dev/null +++ b/models/service.js @@ -0,0 +1,118 @@ +const mongoose = require("mongoose"); + +// Define sub-schemas first +const authorSchema = new mongoose.Schema( + { + name: String, + type: String, + }, + { _id: false }, +); + +const clientReviewSchema = new mongoose.Schema( + { + id: String, + rating: Number, + content: String, + author: authorSchema, + icon: String, + }, + { _id: false }, +); + +const featureSchema = new mongoose.Schema( + { + title: String, + description: String, + }, + { _id: false }, +); + +const faqSchema = new mongoose.Schema( + { + id: String, + question: String, + answer: String, + isExpanded: { type: Boolean, default: false }, + }, + { _id: false }, +); + +const serviceDetailsSchema = new mongoose.Schema( + { + title: String, + description: String, + mainImage: String, + overviewTitle: String, + overviewDescription: String, + additionalDescription: String, + keyFeaturesTitle: String, + keyFeaturesImage: String, + features: [featureSchema], + faqTitle: String, + faqImage: String, + faq: [faqSchema], + }, + { _id: false }, +); + +// Main service page schema +const serviceSchema = new mongoose.Schema( + { + pageTitle: String, + + // Main services section + services: { + title: { + subTitle: String, + mainTitle: String, + }, + items: [ + { + slug: String, + name: String, + description: String, + image: String, + layout: String, + details: serviceDetailsSchema, + }, + ], + }, + + // Destination countries section + destinations: { + backgroundImage: String, + title: { + subTitle: String, + mainTitle: String, + }, + }, + + // Visa types section + visas: { + items: [ + { + id: String, + number: String, + name: String, + description: String, + buttonText: String, + buttonLink: String, + }, + ], + }, + + // Client reviews section + reviews: { + title: { + subTitle: String, + mainTitle: String, + }, + thumb: String, + items: [clientReviewSchema], + }, + }, + { timestamps: true }, +); + +module.exports = mongoose.model("Service", serviceSchema); diff --git a/public/img/default.jpg b/public/img/default.jpg new file mode 100644 index 0000000..b0e2512 Binary files /dev/null and b/public/img/default.jpg differ diff --git a/public/uploads/service/03.jpg b/public/uploads/service/03.jpg new file mode 100644 index 0000000..1b47583 Binary files /dev/null and b/public/uploads/service/03.jpg differ diff --git a/public/uploads/service/404.png b/public/uploads/service/404.png new file mode 100644 index 0000000..f7c61d3 Binary files /dev/null and b/public/uploads/service/404.png differ diff --git a/public/uploads/service/Dell_Inspiron15.webp b/public/uploads/service/Dell_Inspiron15.webp new file mode 100644 index 0000000..00b169d Binary files /dev/null and b/public/uploads/service/Dell_Inspiron15.webp differ diff --git a/public/uploads/service/intro.jpg b/public/uploads/service/intro.jpg new file mode 100644 index 0000000..2540cd4 Binary files /dev/null and b/public/uploads/service/intro.jpg differ diff --git a/public/uploads/service/iphone15.webp b/public/uploads/service/iphone15.webp new file mode 100644 index 0000000..d158840 Binary files /dev/null and b/public/uploads/service/iphone15.webp differ diff --git a/public/uploads/service/smart_samsung_55inch.jpg b/public/uploads/service/smart_samsung_55inch.jpg new file mode 100644 index 0000000..07ede78 Binary files /dev/null and b/public/uploads/service/smart_samsung_55inch.jpg differ diff --git a/routes/admin.js b/routes/admin.js index 075ee8f..9c2ecb8 100644 --- a/routes/admin.js +++ b/routes/admin.js @@ -23,6 +23,7 @@ const insuranceController = require("../controllers/insuranceController"); const activityController = require("../controllers/activityController"); const bookingSubmissionController = require("../controllers/bookingSubmissionController"); +const serviceController = require("../controllers/serviceController"); // Blog controllers const blogController = require("../controllers/blogController"); @@ -384,6 +385,35 @@ router.post( ensureAuthenticated, insuranceController.update, ); +<<<<<<< HEAD +======= + +// Service routes +router.get("/service", ensureAuthenticated, serviceController.index); +router.post("/service/update", ensureAuthenticated, serviceController.update); +router.post( + "/service/generate-slug", + ensureAuthenticated, + serviceController.generateSlug, +); +router.get("/service/:slug/edit", ensureAuthenticated, serviceController.edit); +router.post( + "/service/:slug/edit", + ensureAuthenticated, + serviceController.updateService, +); +router.get( + "/service/:slug/details", + ensureAuthenticated, + serviceController.details, +); +router.post( + "/service/:slug/details/update", + ensureAuthenticated, + serviceController.updateDetails, +); + +>>>>>>> a255d09ef0a6eb0c487595aac19cefbf729d78a2 // Test Image Paths route router.get("/test-images", ensureAuthenticated, (req, res) => { const fs = require("fs"); @@ -479,51 +509,21 @@ router.post("/blog/:id/edit", ensureAuthenticated, blogController.update); router.post("/blog/:id/delete", ensureAuthenticated, blogController.destroy); // Blog Categories Management -router.get( - "/blog/categories", - ensureAuthenticated, - blogCategoryController.index, -); -router.get( - "/blog/categories/create", - ensureAuthenticated, - blogCategoryController.create, -); -router.post( - "/blog/categories/create", - ensureAuthenticated, - blogCategoryController.store, -); -router.get( - "/blog/categories/:id/edit", - ensureAuthenticated, - blogCategoryController.edit, -); -router.post( - "/blog/categories/:id/edit", - ensureAuthenticated, - blogCategoryController.update, -); -router.post( - "/blog/categories/:id/delete", - ensureAuthenticated, - blogCategoryController.destroy, -); +router.get("/blog/categories", ensureAuthenticated, blogCategoryController.index); +router.get("/blog/categories/create", ensureAuthenticated, blogCategoryController.create); +router.post("/blog/categories/create", ensureAuthenticated, blogCategoryController.store); +router.get("/blog/categories/:id/edit", ensureAuthenticated, blogCategoryController.edit); +router.post("/blog/categories/:id/edit", ensureAuthenticated, blogCategoryController.update); +router.post("/blog/categories/:id/delete", ensureAuthenticated, blogCategoryController.destroy); +router.post("/blog/categories/quick-create", ensureAuthenticated, blogCategoryController.quickCreate); // Blog Tags Management router.get("/blog/tags", ensureAuthenticated, blogTagController.index); router.get("/blog/tags/create", ensureAuthenticated, blogTagController.create); router.post("/blog/tags/create", ensureAuthenticated, blogTagController.store); router.get("/blog/tags/:id/edit", ensureAuthenticated, blogTagController.edit); -router.post( - "/blog/tags/:id/edit", - ensureAuthenticated, - blogTagController.update, -); -router.post( - "/blog/tags/:id/delete", - ensureAuthenticated, - blogTagController.destroy, -); +router.post("/blog/tags/:id/edit", ensureAuthenticated, blogTagController.update); +router.post("/blog/tags/:id/delete", ensureAuthenticated, blogTagController.destroy); +router.post("/blog/tags/quick-create", ensureAuthenticated, blogTagController.quickCreate); module.exports = router; diff --git a/routes/index.js b/routes/index.js index f3ac6d3..daffad6 100644 --- a/routes/index.js +++ b/routes/index.js @@ -19,6 +19,7 @@ const activityController = require("../controllers/activityController"); const travelController = require("../controllers/travelController"); const bookingSubmissionController = require("../controllers/bookingSubmissionController"); +const serviceController = require("../controllers/serviceController"); // Blog controllers const blogController = require("../controllers/blogController"); const blogCategoryController = require("../controllers/blogCategoryController"); @@ -167,20 +168,26 @@ router.get("/api/blog/tags/:slug", blogTagController.apiShow); router.get("/api/blog/:id/categories", blogController.apiCategories); router.get("/api/blog/:id/tags", blogController.apiTags); +// Blog comments (must come before /api/blog/:slug) +router.post("/api/blog/:slug/comments", blogController.apiCreateComment); + // Blog detail by slug (must come last among blog routes) router.get("/api/blog/:slug", blogController.apiShow); // // API route cho blog detail // router.get('/api/blog-detail', blogDetailController.api); -// ==================== PUBLIC API ROUTES ==================== +/* CMS - Hailearning + */ +// service +router.get("/service", serviceController.index); +router.post("/service", serviceController.update); +router.get("/api/service", serviceController.api); -// 1. Đưa các route cụ thể (chi tiết nhất) lên đầu tiên -// 2. Route lấy TOÀN BỘ dữ liệu (phải nằm trên route :slug) -router.get("/api/visa", visaController.api); -router.get("/api/visa/hero", visaController.apiHero); -router.get("/api/visa/countries", visaController.apiCountries); +// Service details by slug +router.get("/api/service/:slug", serviceController.getServiceBySlug); + +// Service slugs list +router.get("/api/service-slugs", serviceController.getServiceSlugs); -// 3. Route lấy chi tiết theo slug (luôn để dưới cùng của nhóm này) -router.get("/api/visa/:slug", visaController.apiCountry); module.exports = router; diff --git a/scripts/2026_02_02_131615_service.js b/scripts/2026_02_02_131615_service.js new file mode 100644 index 0000000..af24f29 --- /dev/null +++ b/scripts/2026_02_02_131615_service.js @@ -0,0 +1,186 @@ +require("dotenv").config(); +const fs = require("fs").promises; +const path = require("path"); +const mongoose = require("mongoose"); + +const connectDB = require("../config/database"); +const Service = require("../models/service"); + +/** + * Transform service.json data to match Service schema + */ +function transformServiceData(sourceData) { + return { + pageTitle: sourceData.pageTitle || "", + + // Breadcrumb navigation section + breadcrumb: { + title: sourceData?.breadcrumb?.title || "", + backgroundImage: sourceData?.breadcrumb?.backgroundImage || "", + shape: sourceData?.breadcrumb?.shape || "", + items: Array.isArray(sourceData?.breadcrumb?.items) + ? sourceData.breadcrumb.items.map((item) => ({ + label: item.label || "", + href: item.href || "", + })) + : [], + }, + + // Main services section + services: { + title: { + subTitle: sourceData?.services?.title?.subTitle || "", + mainTitle: sourceData?.services?.title?.mainTitle || "", + }, + items: Array.isArray(sourceData?.services?.items) + ? sourceData.services.items.map((service) => ({ + slug: service.slug || "", + name: service.name || "", + description: service.description || "", + image: service.image || "", + layout: service.layout || "", + details: { + title: service.details?.title || "", + description: service.details?.description || "", + mainImage: service.details?.mainImage || "", + overviewTitle: service.details?.overviewTitle || "", + overviewDescription: service.details?.overviewDescription || "", + additionalDescription: + service.details?.additionalDescription || "", + keyFeaturesTitle: service.details?.keyFeaturesTitle || "", + keyFeaturesImage: service.details?.keyFeaturesImage || "", + features: Array.isArray(service.details?.features) + ? service.details.features.map((feature) => ({ + icon: feature.icon || "", + title: feature.title || "", + description: feature.description || "", + })) + : [], + faqTitle: service.details?.faqTitle || "", + faqImage: service.details?.faqImage || "", + faq: Array.isArray(service.details?.faq) + ? service.details.faq.map((faqItem) => ({ + id: faqItem.id || "", + question: faqItem.question || "", + answer: faqItem.answer || "", + isExpanded: faqItem.isExpanded || false, + })) + : [], + }, + })) + : [], + }, + + // Destination countries section + destinations: { + backgroundImage: sourceData?.destinations?.backgroundImage || "", + title: { + subTitle: sourceData?.destinations?.title?.subTitle || "", + mainTitle: sourceData?.destinations?.title?.mainTitle || "", + }, + items: Array.isArray(sourceData?.destinations?.items) + ? sourceData.destinations.items.map((country) => ({ + id: country.id || "", + name: country.name || "", + description: country.description || "", + image: country.image || "", + icon: country.icon || "", + link: country.link || "", + })) + : [], + }, + + // Visa types section + visas: { + items: Array.isArray(sourceData?.visas?.items) + ? sourceData.visas.items.map((visa) => ({ + id: visa.id || "", + number: visa.number || "", + name: visa.name || "", + description: visa.description || "", + buttonText: visa.buttonText || "", + buttonLink: visa.buttonLink || "", + })) + : [], + }, + + // Client reviews section + reviews: { + title: { + subTitle: sourceData?.reviews?.title?.subTitle || "", + mainTitle: sourceData?.reviews?.title?.mainTitle || "", + }, + viewAllButton: { + text: sourceData?.reviews?.viewAllButton?.text || "", + icon: sourceData?.reviews?.viewAllButton?.icon || "", + link: sourceData?.reviews?.viewAllButton?.link || "", + }, + thumb: sourceData?.reviews?.thumb || "", + items: Array.isArray(sourceData?.reviews?.items) + ? sourceData.reviews.items.map((review) => ({ + id: review.id || "", + rating: review.rating || 5, + content: review.content || "", + author: { + name: review.author?.name || "", + type: review.author?.type || "", + }, + icon: review.icon || "", + })) + : [], + navigation: { + prevButton: sourceData?.reviews?.navigation?.prevButton || "", + nextButton: sourceData?.reviews?.navigation?.nextButton || "", + prevIcon: sourceData?.reviews?.navigation?.prevIcon || "", + nextIcon: sourceData?.reviews?.navigation?.nextIcon || "", + }, + }, + + updatedAt: new Date(), + }; +} + +/** + * Migration function for service page data + */ +async function migrateServiceData() { + try { + await connectDB(); + console.log("🚀 Starting service page migration..."); + + // Clear existing service documents + await Service.deleteMany({}); + console.log("🗑️ Cleared existing service documents"); + + // Read service.json file + const serviceJsonPath = path.join(__dirname, "..", "data", "service.json"); + const rawJsonData = await fs.readFile(serviceJsonPath, "utf8"); + const sourceServiceData = JSON.parse(rawJsonData); + + // Transform data to match schema + const transformedServiceData = transformServiceData(sourceServiceData); + + // Create new service document + const newService = new Service(transformedServiceData); + const savedService = await newService.save(); + + console.log("✅ Service page migration completed successfully!"); + console.log(`📄 Service document ID: ${savedService._id}`); + + await mongoose.disconnect(); + process.exit(0); + } catch (error) { + console.error("❌ Service migration error:", error); + process.exit(1); + } +} + +// Run migration if called directly +if (require.main === module) { + migrateServiceData(); +} + +module.exports = { + migrate: migrateServiceData, + transformServiceData, +}; diff --git a/services/service.service.js b/services/service.service.js new file mode 100644 index 0000000..64483a6 --- /dev/null +++ b/services/service.service.js @@ -0,0 +1,43 @@ +const Service = require("../models/service"); + +const getServiceData = async () => { + const service = await Service.findOne().sort({ updatedAt: -1 }); + console.log("check layout", service.services.items.layout); + + if (!service) { + return { + pageTitle: "", + services: { + title: { + subTitle: "", + mainTitle: "", + }, + items: [], + }, + destinations: { + backgroundImage: "", + title: { + subTitle: "", + mainTitle: "", + }, + }, + visas: { + items: [], + }, + reviews: { + title: { + subTitle: "", + mainTitle: "", + }, + thumb: "", + items: [], + }, + }; + } + + return service; +}; + +module.exports = { + getServiceData, +}; diff --git a/utils/imageHelper.js b/utils/imageHelper.js index b772b1d..bce7697 100644 --- a/utils/imageHelper.js +++ b/utils/imageHelper.js @@ -1,37 +1,68 @@ /** * Thêm BACKEND_URL vào đường dẫn hình ảnh - * @param {Object} data - Dữ liệu cần xử lý + * @param {Object} data - Dữ liệu cần xử lý * @returns {Object} - Dữ liệu đã được xử lý với đường dẫn hình ảnh đầy đủ */ function addBaseUrlToImages(data, baseUrl) { // baseUrl can be passed explicitly (e.g., from req), otherwise fall back to env - const BACKEND_URL = baseUrl || process.env.BACKEND_URL || ''; - + const BACKEND_URL = baseUrl || process.env.BACKEND_URL || ""; + // Tạo bản sao sâu để tránh thay đổi dữ liệu gốc const processedData = JSON.parse(JSON.stringify(data)); - + // Hàm đệ quy để xử lý tất cả các URL hình ảnh trong đối tượng const processObject = (obj) => { - if (!obj || typeof obj !== 'object') return; - - Object.keys(obj).forEach(key => { + if (!obj || typeof obj !== "object") return; + + Object.keys(obj).forEach((key) => { // Kiểm tra nếu thuộc tính chứa đường dẫn hình ảnh bắt đầu bằng /uploads/ - if (typeof obj[key] === 'string' && obj[key].startsWith('/uploads/')) { + if (typeof obj[key] === "string" && obj[key].startsWith("/uploads/")) { // Thêm BACKEND_URL nếu đường dẫn chưa có http - if (!obj[key].startsWith('http')) { + if (!obj[key].startsWith("http")) { obj[key] = `${BACKEND_URL}${obj[key]}`; } - } else if (typeof obj[key] === 'object') { + } else if (typeof obj[key] === "object") { // Đệ quy xử lý các đối tượng và mảng lồng nhau processObject(obj[key]); } }); }; - + processObject(processedData); return processedData; } +/** + * Tạo full URL cho ảnh từ đường dẫn tương đối - dùng cho EJS templates + * @param {string} imagePath - Đường dẫn ảnh + * @param {string} backendUrl - Backend URL (optional, sẽ lấy từ env nếu không có) + * @returns {string} - Full URL của ảnh + */ +function getFullImageUrl(imagePath, backendUrl = null) { + if (!imagePath) return ""; + + // Nếu đã là full URL thì return luôn + if (imagePath.startsWith("http")) { + return imagePath; + } + + // Lấy backend URL + const baseUrl = ( + backendUrl || + process.env.BACKEND_URL || + "http://localhost:3001" + ).replace(/\/$/, ""); + + // Xử lý đường dẫn + let imgSrc = imagePath; + if (!imgSrc.startsWith("/")) { + imgSrc = "/" + imgSrc; + } + + return baseUrl + imgSrc; +} + module.exports = { - addBaseUrlToImages -}; \ No newline at end of file + addBaseUrlToImages, + getFullImageUrl, +}; diff --git a/views/admin/blog/create.ejs b/views/admin/blog/create.ejs new file mode 100644 index 0000000..0a839d4 --- /dev/null +++ b/views/admin/blog/create.ejs @@ -0,0 +1,1008 @@ +Create a new blog post
+Edit blog post
+Manage blog posts and articles
+| Image | +Title | +Category | +Status | +Author | +Published | +Actions | +
|---|---|---|---|---|---|---|
|
+ <% if (blog.featuredImage) { %>
+
+
+
+ <% } %>
+ |
+
+
+
+ <%= blog.title %>
+
+ <% if (blog.isFeatured) { %>
+ Featured
+ <% } %>
+
+
+ <%= blog.excerpt.substring(0, 60) %>...
+
+ |
+ + <% if (blog.category && blog.category.length> 0) { %> + <% blog.category.slice(0, 2).forEach(cat=> { %> + + <%= cat %> + + <% }); %> + <% if (blog.category.length> 2) { %> + +<%= blog.category.length - 2 %> + <% } %> + <% } else { %> + - + <% } %> + | ++ <% if (blog.status==='published' ) { %> + Published + <% } else { %> + Draft + <% } %> + | ++ <%= blog.author || 'Admin' %> + | ++ <%= blog.publishedAt || '-' %> + | ++ + | +
Manage camp location
Manage services
+/api/header/api/home/api/about/api/about-us/api/faq/api/terms/api/travel/api/safety/api/camp-location/api/menu-tree/api/contact/api/camp-locationClick the Edit button to make changes to your data.
++ Click the Edit button to make changes to your data. +
Edit detailed content for <%= service.name %> service
+Update service information and settings
+Manage services and their detailed content
+