Shop Amazon

Wednesday, March 19, 2025

d

// script.js - Main JavaScript for Order Tracking System // Dummy order data (simulating a backend database) const orders = [ { id: "1001", customer: "Alice", item: "Laptop", status: "Completed", lastUpdate: "2025-03-18 14:00" }, { id: "1002", customer: "Alice", item: "Smartphone", status: "In Progress", lastUpdate: "2025-03-19 11:20", etaSeconds: 10 }, { id: "1003", customer: "Bob", item: "Headphones", status: "Pending", lastUpdate: "2025-03-19 09:15" }, { id: "1004", customer: "Bob", item: "Camera", status: "Canceled", lastUpdate: "2025-03-18 16:30" } ]; // Status options for dropdowns const statusOptions = ["Started", "In Progress", "Pending", "Completed", "Canceled"]; // Helper to find an order by ID function findOrderById(id) { return orders.find(order => order.id === id); } // Status-to-color mapping for badges const statusColor = { "Completed": "success", "Canceled": "danger", "In Progress": "info", "Pending": "warning", "Started": "secondary" }; document.addEventListener('DOMContentLoaded', () => { const pageId = document.body.id; /* Home Page */ if (pageId === "homePage") { const trackForm = document.getElementById('trackForm'); const orderInput = document.getElementById('orderInput'); const trackError = document.getElementById('trackError'); trackForm.addEventListener('submit', (e) => { e.preventDefault(); const orderId = orderInput.value.trim(); if (!orderId) { // Show error if input is empty trackError.style.display = 'block'; } else { trackError.style.display = 'none'; // Go to Order Status page with query parameter for order ID window.location.href = `order-status.html?order=${encodeURIComponent(orderId)}`; } }); } /* Order Status Page */ if (pageId === "statusPage") { const statusInfo = document.getElementById('statusInfo'); const statusError = document.getElementById('statusError'); const orderIdLabel = document.getElementById('orderIdLabel'); const orderStatusLabel = document.getElementById('orderStatusLabel'); const etaText = document.getElementById('etaText'); const etaValue = document.getElementById('etaValue'); const progressContainer = document.getElementById('progressContainer'); const progressBar = document.getElementById('progressBar'); const lastUpdatedText = document.getElementById('lastUpdatedText'); // Get order ID from URL query string const params = new URLSearchParams(window.location.search); const orderId = params.get('order'); const order = orderId ? findOrderById(orderId) : null; if (order) { // Display order details orderIdLabel.textContent = order.id; orderStatusLabel.textContent = order.status; // Apply color class to status text if (statusColor[order.status]) { orderStatusLabel.classList.add(`text-${statusColor[order.status]}`); } lastUpdatedText.textContent = `Last updated: ${order.lastUpdate}`; statusInfo.style.display = "block"; statusError.textContent = ""; // If the order is in progress, simulate real-time updates if (order.status === "In Progress" && order.etaSeconds !== undefined) { let remaining = order.etaSeconds; etaValue.textContent = `${remaining} sec`; etaText.style.display = "block"; progressContainer.style.display = "block"; progressBar.style.width = "0%"; const total = remaining; const intervalId = setInterval(() => { remaining -= 1; if (remaining >= 0) { // Update countdown and progress bar etaValue.textContent = `${remaining} sec`; const percent = ((total - remaining) / total) * 100; progressBar.style.width = `${percent}%`; } if (remaining <= 0) { clearInterval(intervalId); // Mark order as completed after countdown finishes orderStatusLabel.textContent = "Completed"; orderStatusLabel.classList.remove('text-info'); orderStatusLabel.classList.add('text-success'); etaText.style.display = "none"; progressContainer.style.display = "none"; lastUpdatedText.textContent = `Last updated: just now`; } }, 1000); } } else { // Invalid or missing order ID statusInfo.style.display = "none"; statusError.textContent = orderId ? `Order #${orderId} not found. Please check the number and try again.` : "No order number provided."; } } /* Customer Login Page */ if (pageId === "loginPage") { const loginForm = document.getElementById('loginForm'); const loginEmail = document.getElementById('loginEmail'); const loginPassword = document.getElementById('loginPassword'); const loginError = document.getElementById('loginError'); loginForm.addEventListener('submit', (e) => { e.preventDefault(); e.stopPropagation(); // Check HTML5 validation constraints if (!loginForm.checkValidity()) { loginForm.classList.add('was-validated'); return; } const email = loginEmail.value.trim().toLowerCase(); const pass = loginPassword.value; let validUser = false, userName = ""; // Demo credentials check (replace with server authentication in real app) if (email === "alice@example.com" && pass === "alice123") { validUser = true; userName = "Alice"; } else if (email === "bob@example.com" && pass === "bob123") { validUser = true; userName = "Bob"; } if (validUser) { // Store user info in localStorage to simulate session localStorage.setItem('userName', userName); localStorage.setItem('userEmail', email); // Redirect to user dashboard window.location.href = "dashboard.html"; } else { // Show error message loginError.textContent = "Invalid email or password."; loginError.style.display = 'block'; } }); } /* Customer Dashboard Page */ if (pageId === "dashboardPage") { const userName = localStorage.getItem('userName'); const userEmail = localStorage.getItem('userEmail'); const userGreeting = document.getElementById('userGreeting'); const orderList = document.getElementById('orderList'); const prefEmail = document.getElementById('prefEmail'); const prefSMS = document.getElementById('prefSMS'); const savePrefsBtn = document.getElementById('savePrefsBtn'); const prefSavedMsg = document.getElementById('prefSavedMsg'); const logoutLink = document.getElementById('logoutLink'); // Redirect to login if not logged in if (!userName) { window.location.href = "login.html"; return; } // Show welcome message userGreeting.textContent = `Welcome, ${userName}!`; // Populate orders list for this user orderList.innerHTML = ""; const userOrders = orders.filter(o => o.customer === userName); if (userOrders.length === 0) { orderList.innerHTML = `
  • No orders found.
  • `; } else { userOrders.forEach(order => { const li = document.createElement('li'); li.className = "list-group-item d-flex justify-content-between align-items-center"; // Determine badge color based on status const badgeColor = statusColor[order.status] || "secondary"; li.innerHTML = `
    Order #${order.id} - ${order.status}
    Track `; orderList.appendChild(li); }); } // Load saved notification preferences (if any) prefEmail.checked = localStorage.getItem('prefEmail') === 'true'; prefSMS.checked = localStorage.getItem('prefSMS') === 'true'; // Handle Save Preferences button savePrefsBtn.addEventListener('click', () => { localStorage.setItem('prefEmail', prefEmail.checked); localStorage.setItem('prefSMS', prefSMS.checked); prefSavedMsg.style.display = 'inline'; setTimeout(() => { prefSavedMsg.style.display = 'none'; }, 2000); }); // Logout link: clear session and go to Home logoutLink.addEventListener('click', (e) => { e.preventDefault(); localStorage.removeItem('userName'); localStorage.removeItem('userEmail'); window.location.href = "index.html"; }); } /* Admin Dashboard Page */ if (pageId === "adminPage") { const adminLoginSection = document.getElementById('adminLoginSection'); const adminPanelSection = document.getElementById('adminPanelSection'); const adminLoginForm = document.getElementById('adminLoginForm'); const adminUser = document.getElementById('adminUser'); const adminPass = document.getElementById('adminPass'); const adminLoginError = document.getElementById('adminLoginError'); const adminOrdersTable = document.getElementById('adminOrdersTable'); const adminLogoutLink = document.getElementById('adminLogoutLink'); let adminMsg = document.getElementById('adminMsg'); let adminMsgTimeout; // Utility to display a temporary message function showAdminMessage(text) { adminMsg.textContent = text; adminMsg.style.display = 'block'; // Hide after 3 seconds if (adminMsgTimeout) clearTimeout(adminMsgTimeout); adminMsgTimeout = setTimeout(() => { adminMsg.style.display = 'none'; }, 3000); } // Render orders table rows for admin function renderAdminTable() { adminOrdersTable.innerHTML = ""; orders.forEach(order => { // Build options for status select let optionsHTML = ""; statusOptions.forEach(status => { const selected = status === order.status ? "selected" : ""; optionsHTML += ``; }); const rowHTML = ` ${order.id} ${order.customer} ${order.item} `; adminOrdersTable.insertAdjacentHTML('beforeend', rowHTML); }); // Attach event handlers for new buttons const updateButtons = document.querySelectorAll('.updateBtn'); const notifyButtons = document.querySelectorAll('.notifyBtn'); updateButtons.forEach(btn => { btn.addEventListener('click', function() { const row = this.closest('tr'); const orderId = row.getAttribute('data-orderid'); const newStatus = row.querySelector('.status-select').value; // Update the order status in our data const order = findOrderById(orderId); if (order) order.status = newStatus; showAdminMessage(`Order #${orderId} updated to "${newStatus}".`); }); }); notifyButtons.forEach(btn => { btn.addEventListener('click', function() { const row = this.closest('tr'); const orderId = row.getAttribute('data-orderid'); showAdminMessage(`Notification sent for Order #${orderId}.`); }); }); } // Check if admin already logged in if (localStorage.getItem('adminLoggedIn') === 'true') { adminLoginSection.style.display = 'none'; adminPanelSection.style.display = 'block'; adminLogoutLink.style.display = 'list-item'; renderAdminTable(); } // Admin login form handler adminLoginForm.addEventListener('submit', (e) => { e.preventDefault(); const username = adminUser.value.trim(); const password = adminPass.value; if (!username || !password) { adminLoginError.textContent = "Please enter username and password."; adminLoginError.style.display = 'block'; return; } // Check hard-coded admin credentials (for demo purposes) if (username === "admin" && password === "admin123") { // Successful admin login localStorage.setItem('adminLoggedIn', 'true'); adminLoginError.style.display = 'none'; adminLoginSection.style.display = 'none'; adminPanelSection.style.display = 'block'; adminLogoutLink.style.display = 'list-item'; renderAdminTable(); } else { // Invalid admin credentials adminLoginError.textContent = "Incorrect credentials."; adminLoginError.style.display = 'block'; } }); // Admin logout adminLogoutLink.addEventListener('click', (e) => { e.preventDefault(); localStorage.removeItem('adminLoggedIn'); window.location.reload(); }); } });

    No comments:

    Post a Comment