CÁC VỊ TRÍ ĐANG TUYỂN
Đang tải dữ liệu tuyển dụng...
Không tìm thấy vị trí phù hợp với tiêu chí của bạn.
Không có phòng ban nào.
'; return; } const departments = [...new Set(jobs.map(job => job.department))].filter(Boolean).filter(dept => dept !== 'Chưa phân loại'); departmentFilterContainer.innerHTML = ''; if (departments.length === 0) { departmentFilterContainer.innerHTML = 'Chưa có phòng ban cụ thể.
'; return; } departments.sort().forEach(dept => { const div = document.createElement('div'); div.className = 'flex items-center'; div.innerHTML = ``; departmentFilterContainer.appendChild(div); }); }; const renderJobs = (jobsToRender) => { // Xóa nội dung cũ (bao gồm cả thông báo loading) jobListingsContainer.innerHTML = ''; if (!jobsToRender || jobsToRender.length === 0) { noResultsMessage.classList.remove('hidden'); } else { noResultsMessage.classList.add('hidden'); jobsToRender.forEach(job => { jobListingsContainer.innerHTML += `${job.title}
${job.department}
${job.experience}
${job.salary}
${String(job.quantity).padStart(2, '0')}
${title}${message}
`;
};
// --- DATA FETCHING & PROCESSING ---
async function callGeminiApi(content) {
const GEMINI_API_URL = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${GEMINI_API_KEY}`;
const prompt = `Trích xuất thông tin công việc từ văn bản sau và trả về dưới dạng một đối tượng JSON: {"experience": "string", "salary": "string", "quantity": number}. Nếu không tìm thấy, dùng giá trị mặc định: 'Không yêu cầu', 'Thỏa thuận', 1. Chỉ trả về JSON. Nội dung: \n\n ${content}`;
const defaults = { experience: 'Không yêu cầu', salary: 'Thỏa thuận', quantity: 1 };
try {
const response = await fetch(GEMINI_API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ contents: [{ parts: [{ text: prompt }] }] })
});
if (!response.ok) return defaults;
const data = await response.json();
const textResponse = data.candidates[0]?.content?.parts[0]?.text || '';
const jsonString = textResponse.replace(/```json|```/g, '').trim();
return { ...defaults, ...JSON.parse(jsonString) };
} catch (error) {
console.error("Gemini API Error:", error);
return defaults;
}
}
async function fetchAndProcessJobs() {
try {
// Step 1: Get the parent category by its slug to find its ID
const catResponse = await fetch(`${WP_API_URL}/categories?slug=${PARENT_CATEGORY_SLUG}`);
if (!catResponse.ok) throw new Error("Không thể tìm thấy danh mục 'tuyen-dung'. Kiểm tra lại slug.");
const categories = await catResponse.json();
if (categories.length === 0) throw new Error("Danh mục 'tuyen-dung' không tồn tại hoặc sai slug.");
const parentCategoryId = categories[0].id;
// Step 2: Get all child categories of the parent category.
const childCatResponse = await fetch(`${WP_API_URL}/categories?parent=${parentCategoryId}&per_page=100`);
if (!childCatResponse.ok) throw new Error("Không thể tải danh mục con.");
const childCategories = await childCatResponse.json();
// Create a lookup map for child categories {id: name} for efficient searching
const childCategoryMap = new Map(childCategories.map(cat => [cat.id, cat.name]));
// Step 3: Create a list of all relevant category IDs (parent + children).
const allCategoryIds = [parentCategoryId, ...childCategories.map(cat => cat.id)];
// Step 4: Fetch all posts that belong to any of these categories.
const postsResponse = await fetch(`${WP_API_URL}/posts?categories=${allCategoryIds.join(',')}&per_page=100`);
if (!postsResponse.ok) throw new Error("Không thể tải danh sách bài đăng.");
const posts = await postsResponse.json();
if (posts.length === 0) {
showErrorMessage("Không có tin tuyển dụng", "Chưa có bài viết nào trong danh mục 'Tuyển dụng' hoặc các danh mục con.");
populateDepartments([]);
return;
}
// Tối ưu hóa: Gọi API Gemini song song cho tất cả các bài viết
// và xử lý kết quả khi tất cả đã hoàn thành.
const jobPromises = posts.map(async (post) => {
const plainContent = new DOMParser().parseFromString(post.content.rendered, 'text/html').body.textContent || '';
const jobDetails = await callGeminiApi(plainContent);
let department = 'Chưa phân loại';
// The 'categories' property on a post object is an array of category IDs
for (const categoryId of post.categories) {
// Check if this ID belongs to one of our known child categories
if (childCategoryMap.has(categoryId)) {
department = childCategoryMap.get(categoryId);
break; // Found the department, no need to check further
}
}
return {
title: post.title.rendered,
url: post.link,
department: department,
experience: jobDetails.experience,
salary: jobDetails.salary,
quantity: parseInt(jobDetails.quantity, 10) || 1,
};
});
allJobs = await Promise.all(jobPromises);
populateDepartments(allJobs);
renderJobs(allJobs);
} catch (error) {
console.error("Lỗi khi tải dữ liệu:", error);
showErrorMessage('Lỗi Tải Dữ Liệu!', error.message);
}
}
document.addEventListener('DOMContentLoaded', () => {
fetchAndProcessJobs();
searchInput.addEventListener('keyup', filterJobs);
departmentFilterContainer.addEventListener('change', (event) => {
if (event.target.classList.contains('department-checkbox')) {
filterJobs();
}
});
});