SP24 BCS A Final Lab Exam
Objective:
Extend your existing Express.js, EJS, and Mongoose e-commerce application by implementing a dynamic, real-time updated Sales Dashboard (/sales). This task will test your ability to work with template engines, layouts, Mongoose aggregation or queries, API endpoints, and client-side AJAX polling using jQuery.
Problem Statement & Requirements
You are required to add a new administrative feature to your e-commerce store that allows managers to track real-time sales statistics.
1. Database & Backend Preparation (Mongoose)
- Assumed schema: You already have a
Productschema and anOrder(orSale) schema tracking purchases. - Implement a backend controller logic that calculates:
- Total Revenue generated so far.
- Total Orders placed.
- Top-Selling Product (or a list of recent transactions).
2. Server-Side Rendering (Express & EJS)
- Create a
GET /salesroute. - When a user visits this page, the server must initially render a dashboard page (
sales.ejs) utilizing theexpress-ejs-layoutsmodule to maintain the consistent look and feel of your store. - The page should initially display the sales data directly injected from the server-side EJS compilation.
3. The Live Update Endpoint (API Route)
- Create a secondary
GET /api/sales-dataroute. - This route must fetch the latest statistics from the database and respond strictly with JSON data (e.g.,
{ totalRevenue: 5000, totalOrders: 42 }).
4. Real-Time Polling (Client-Side jQuery)
- Inside your
sales.ejstemplate, write a jQuery script. - Once the DOM is ready, implement a periodic asynchronous call (
setIntervalcombined with$.ajaxor$.getJSON) to hit the/api/sales-dataendpoint. - Frequency: The page must update its stats automatically every 10 seconds without requiring a full browser reload.
- When the JSON response is received, use jQuery to dynamically update the text/values inside the dashboard DOM elements.
Expected Deliverables
- Route Updates: Cleanly structured Express routes handling both the HTML page rendering and the JSON data API.
- EJS View: A styled dashboard integrated into your master layout, featuring dedicated placeholders/cards for the metrics.
- jQuery Script: The client-side logic successfully manipulating the DOM based on the automated periodic fetch.