Version 1.0 upload

This commit is contained in:
2025-04-08 00:05:15 +08:00
parent 2eff273486
commit 35378d17d0
38 changed files with 2096 additions and 598 deletions

157
src/api/api.ts Normal file
View File

@@ -0,0 +1,157 @@
// api/api.ts
import { updateLoggedInState } from '../utils/utils';
// --- Define API Response Interfaces ---
export interface LoginResponseData { // Exported
userId: string;
fullName: string;
profilePicture: string;
schoolId: string;
birthdate: string;
token: string;
}
export interface ApiResponse<T> { // Exported
success: boolean;
data?: T;
message?: string;
}
export interface ProfileResponseData extends LoginResponseData { // Exported
posts: { id: number; content: string }[];
}
export interface AdminDashboardData { // Exported
studentsCount: number;
teachersCount: number;
}
export interface StudentListData { // Exported
id: number;
name: string;
yearLevel: string;
courses: string[];
}
export interface StudentFinancialData {
tuitionFee: string;
miscellaneousFee: string;
labFee: string;
currentAccount: string;
downPayment: string;
midtermPayment: string;
prefinalPayment: string;
finalPayment: string;
}
// --- Mock API Endpoints ---
const mockAPI = {
login: async (credentials: any): Promise<ApiResponse<LoginResponseData>> => { // Explicit return type, parameter type remains 'any' as per original spec
return new Promise((resolve, reject) => {
setTimeout(() => {
if (credentials.userId === '123456' && credentials.password === 'password') {
const userData: LoginResponseData = {
userId: generateMockUserId(), // Mock User ID
fullName: 'John Doe',
profilePicture: 'path/to/profile.jpg', // Placeholder
schoolId: '123456',
birthdate: '2000-01-01',
token: 'mock-user-token-123', // Mock token
};
resolve({ success: true, data: userData });
updateLoggedInState(true, userData.token); // Update login state on successful login
} else {
reject({ success: false, message: 'Invalid credentials' });
}
}, 1000); // Simulate API latency
});
},
logout: async (): Promise<ApiResponse<void>> => {
return new Promise(resolve => {
setTimeout(() => {
updateLoggedInState(false, null);
resolve({ success: true });
}, 500);
});
},
getProfile: async (userId: string): Promise<ApiResponse<ProfileResponseData>> => {
return new Promise(resolve => {
setTimeout(() => {
const profileData: ProfileResponseData = {
userId: userId,
fullName: 'John Doe',
profilePicture: 'path/to/profile.jpg', // Placeholder
schoolId: '123456',
birthdate: '2000-01-01',
token: 'mock-user-token-123', // Added token here to match ProfileResponseData interface
posts: [
{ id: 1, content: 'First post on profile!' },
{ id: 2, content: 'Another profile post.' }
]
};
resolve({ success: true, data: profileData });
}, 500);
});
},
updateAccountSettings: async (userId: string, settings: any): Promise<ApiResponse<void>> => { // parameter type remains 'any'
return new Promise(resolve => {
setTimeout(() => {
console.log('Account settings updated for user:', userId, settings);
resolve({ success: true });
}, 500);
});
},
getAdminDashboardData: async (): Promise<ApiResponse<AdminDashboardData>> => {
return new Promise(resolve => {
setTimeout(() => {
const dashboardData: AdminDashboardData = {
studentsCount: 150,
teachersCount: 30,
};
resolve({ success: true, data: dashboardData });
}, 500);
});
},
getStudentList: async (): Promise<ApiResponse<StudentListData[]>> => {
return new Promise(resolve => {
setTimeout(() => {
const studentList: StudentListData[] = [
{ id: 1, name: 'Alice Smith', yearLevel: '1', courses: ['Math', 'Science'] },
{ id: 2, name: 'Bob Johnson', yearLevel: '2', courses: ['History', 'English'] },
];
resolve({ success: true, data: studentList });
}, 500);
});
},
getStudentFinancialData: async (_studentId: string): Promise<ApiResponse<StudentFinancialData>> => { // parameter type remains 'string', unused parameter prefixed with _
return new Promise(resolve => {
setTimeout(() => {
const financialData: StudentFinancialData = {
tuitionFee: '5000',
miscellaneousFee: '500',
labFee: '200',
currentAccount: '-100',
downPayment: '2000',
midtermPayment: '1500',
prefinalPayment: '1000',
finalPayment: '500',
};
resolve({ success: true, data: financialData });
}, 500);
});
}
};
let mockUserIdCounter = 100000;
const generateMockUserId = () => {
return String(mockUserIdCounter++);
};
declare global {
interface Window {
globalAPI: typeof mockAPI;
}
}
export const setupGlobalAPI = () => {
window.globalAPI = mockAPI;
};
export const globalAPI = mockAPI;

BIN
src/assets/bg1.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 274 KiB

BIN
src/assets/bg2.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 537 KiB

1
src/assets/vite.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,30 @@
// components/MergedWidget.ts
import { Widget } from './Widget';
export class MergedWidget extends Widget {
private children: Widget[] = [];
constructor(sizeType: 'default' | 'icon' = 'default') {
super(sizeType);
}
addWidget(widget: Widget): void {
this.children.push(widget);
}
render(): HTMLElement {
// Clear current container contents (in case render is called more than once)
this.container.innerHTML = '';
for (const widget of this.children) {
const rendered = widget.render();
// Move child nodes (not the container itself)
while (rendered.firstChild) {
this.container.appendChild(rendered.firstChild);
}
}
return this.container;
}
}

56
src/components/Modal.ts Normal file
View File

@@ -0,0 +1,56 @@
// components/Modal.ts
import { createElement } from '../utils/utils';
import { Widget } from './Widget';
export class Modal {
private modalOverlay: HTMLDivElement;
private modalContent: HTMLDivElement;
private widget: Widget | null = null;
private isVisible: boolean = false;
constructor() {
this.modalOverlay = createElement('div') as HTMLDivElement;
this.modalOverlay.classList.add('modal-overlay');
this.modalOverlay.style.display = 'none'; // Initially hidden
this.modalOverlay.addEventListener('click', (event) => {
if (event.target === this.modalOverlay) {
this.hide(); // Close modal if clicked outside content
}
});
this.modalContent = createElement('div') as HTMLDivElement;
this.modalContent.classList.add('modal-content');
this.modalOverlay.appendChild(this.modalContent);
document.body.appendChild(this.modalOverlay); // Append to body once
}
setWidget(widget: Widget): void {
this.widget = widget;
this.modalContent.innerHTML = ''; // Clear previous content
this.modalContent.appendChild(widget.render());
}
show(): void {
if (this.widget) {
this.modalOverlay.style.display = 'flex';
this.isVisible = true;
}
}
hide(): void {
this.modalOverlay.style.display = 'none';
this.isVisible = false;
}
isVisibleModal(): boolean {
return this.isVisible;
}
getContainer(): HTMLDivElement {
return this.modalOverlay;
}
getModalContentContainer(): HTMLDivElement {
return this.modalContent;
}
}

176
src/components/TopBar.ts Normal file
View File

@@ -0,0 +1,176 @@
// components/TopBar.ts
import { createElement, navigateTo, isLoggedInUser } from '../utils/utils';
import { globalAPI, ApiResponse, ProfileResponseData } from '../api/api'; // Import API and types (now exported)
export class TopBar {
private container: HTMLElement;
private profileDropdownVisible: boolean = false;
private profileData: ProfileResponseData | null = null;
constructor() {
this.container = createElement('nav');
this.container.classList.add('top-bar', 'navbar', 'navbar-expand-lg', 'navbar-light', 'bg-darker', 'mb-3', 'px-4');
this.fetchProfileData();
}
async fetchProfileData() {
if (isLoggedInUser()) {
try {
const response: ApiResponse<ProfileResponseData> = await globalAPI.getProfile('mockUserId');
if (response.success && response.data) {
this.profileData = response.data;
this.render();
} else {
console.error("Failed to fetch profile data");
}
} catch (error) {
console.error("Error fetching profile data:", error);
}
}
}
render(): HTMLElement {
this.container.innerHTML = '';
const navbarBrand = createElement('a');
navbarBrand.classList.add('navbar-brand');
navbarBrand.href = '#/dashboard';
navbarBrand.textContent = 'LMS';
const navbarToggler = createElement('button');
navbarToggler.classList.add('navbar-toggler');
navbarToggler.type = 'button';
navbarToggler.setAttribute('data-bs-toggle', 'collapse');
navbarToggler.setAttribute('data-bs-target', '#navbarNav');
navbarToggler.setAttribute('aria-controls', 'navbarNav');
navbarToggler.setAttribute('aria-expanded', 'false');
navbarToggler.setAttribute('aria-label', 'Toggle navigation');
navbarToggler.innerHTML = '<span class="navbar-toggler-icon"></span>';
const navbarCollapse = createElement('div');
navbarCollapse.classList.add('collapse', 'navbar-collapse');
navbarCollapse.id = 'navbarNav';
const menuPages = createElement('ul');
menuPages.classList.add('navbar-nav', 'me-auto', 'mb-2', 'mb-lg-0');
const dashboardMenuItem = createElement('li');
dashboardMenuItem.classList.add('nav-item');
const dashboardLink = createElement('a');
dashboardLink.classList.add('nav-link');
dashboardLink.href = '#/dashboard';
dashboardLink.textContent = 'Dashboard';
dashboardMenuItem.appendChild(dashboardLink);
menuPages.appendChild(dashboardMenuItem);
const classroomsMenuItem = createElement('li');
classroomsMenuItem.classList.add('nav-item');
const classroomsLink = createElement('a');
classroomsLink.classList.add('nav-link');
classroomsLink.href = '#/classrooms';
classroomsLink.textContent = 'Classrooms';
classroomsMenuItem.appendChild(classroomsLink);
menuPages.appendChild(classroomsMenuItem);
const adminMenuItem = createElement('li');
adminMenuItem.classList.add('nav-item');
const adminLink = createElement('a');
adminLink.classList.add('nav-link');
adminLink.href = '#/admin';
adminLink.textContent = 'Admin';
adminMenuItem.appendChild(adminLink);
menuPages.appendChild(adminMenuItem);
const profileSection = createElement('div');
profileSection.classList.add('d-flex', 'align-items-center', 'ms-auto');
if (this.profileData) {
const profileButton = createElement('button');
profileButton.classList.add('btn', 'btn-dark', 'dropdown-toggle');
profileButton.type = 'button';
profileButton.id = 'profileDropdownButton';
profileButton.setAttribute('data-bs-toggle', 'dropdown');
profileButton.setAttribute('aria-expanded', String(this.profileDropdownVisible));
const profileImage = createElement('img'); // Placeholder image, replace with actual profile picture logic
profileImage.src = this.profileData.profilePicture || 'src/assets/vite.svg'; // Default placeholder if no picture
profileImage.alt = 'Profile Picture';
profileImage.style.width = '30px';
profileImage.style.height = '30px';
profileImage.style.borderRadius = '50%';
profileImage.style.marginRight = '5px';
const fullNameSpan = createElement('span');
fullNameSpan.textContent = this.profileData.fullName;
profileButton.appendChild(profileImage);
profileButton.appendChild(fullNameSpan);
const dropdownMenu = createElement('ul');
dropdownMenu.classList.add('dropdown-menu', 'dropdown-menu-end');
dropdownMenu.setAttribute('aria-labelledby', 'profileDropdownButton');
const userIdItem = createElement('li');
userIdItem.innerHTML = `<span class="dropdown-item-text">ID: ${this.profileData.schoolId}</span>`;
dropdownMenu.appendChild(userIdItem);
const divider = createElement('li');
divider.innerHTML = '<hr class="dropdown-divider">';
dropdownMenu.appendChild(divider);
const profileMenuItem = createElement('li');
const profileLink = createElement('a');
profileLink.classList.add('dropdown-item');
profileLink.href = '#/profile';
profileLink.textContent = 'Profile';
profileMenuItem.appendChild(profileLink);
dropdownMenu.appendChild(profileMenuItem);
const accountSettingsMenuItem = createElement('li');
const accountSettingsLink = createElement('a');
accountSettingsLink.classList.add('dropdown-item');
accountSettingsLink.href = '#/profile'; // Same profile page, modal will be triggered there
accountSettingsLink.setAttribute('data-action', 'open-account-settings'); // Custom attribute to trigger modal
accountSettingsLink.textContent = 'Account settings';
accountSettingsMenuItem.appendChild(accountSettingsLink);
dropdownMenu.appendChild(accountSettingsMenuItem);
const logoutMenuItem = createElement('li');
const logoutButton = createElement('button');
logoutButton.classList.add('dropdown-item');
logoutButton.textContent = 'Log out';
logoutButton.addEventListener('click', async () => {
await globalAPI.logout();
navigateTo('/login'); // Redirect to login page after logout
});
logoutMenuItem.appendChild(logoutButton);
dropdownMenu.appendChild(logoutMenuItem);
profileSection.appendChild(profileButton);
profileSection.appendChild(dropdownMenu);
} else {
// Fallback if profile data is not loaded (or not logged in, though TopBar is for logged-in users)
const loginLink = createElement('a');
loginLink.classList.add('btn', 'btn-primary');
loginLink.href = '#/login';
loginLink.textContent = 'Login';
profileSection.appendChild(loginLink);
}
navbarCollapse.appendChild(menuPages);
navbarCollapse.appendChild(profileSection);
this.container.appendChild(navbarBrand);
this.container.appendChild(navbarToggler);
this.container.appendChild(navbarCollapse);
return this.container;
}
getContainer(): HTMLElement {
return this.container;
}
}

26
src/components/Widget.ts Normal file
View File

@@ -0,0 +1,26 @@
// components/Widget.ts
import { createElement } from '../utils/utils';
export abstract class Widget {
protected container: HTMLElement;
protected sizeType: 'default' | 'icon';
constructor(sizeType: 'default' | 'icon' = 'default') {
this.container = createElement('div');
this.container.classList.add('widget');
this.sizeType = sizeType;
if (sizeType === 'icon') {
this.container.classList.add('icon-widget');
}
}
abstract render(): HTMLElement;
getSizeType(): 'default' | 'icon' {
return this.sizeType;
}
getContainer(): HTMLElement {
return this.container;
}
}

View File

@@ -1,9 +0,0 @@
export function setupCounter(element: HTMLButtonElement) {
let counter = 0
const setCounter = (count: number) => {
counter = count
element.innerHTML = `count is ${counter}`
}
element.addEventListener('click', () => setCounter(counter + 1))
setCounter(0)
}

View File

@@ -0,0 +1,23 @@
// layouts/CenteredLayout.ts
import { createElement } from '../utils/utils';
export class CenteredLayout {
private container: HTMLElement;
constructor() {
this.container = createElement('div');
this.container.classList.add('centered-layout', 'container-fluid');
}
addContent(content: HTMLElement | string): void {
if (typeof content === 'string') {
this.container.innerHTML = content;
} else {
this.container.appendChild(content);
}
}
render(): HTMLElement {
return this.container;
}
}

View File

@@ -0,0 +1,55 @@
// layouts/SplitColumnLayout.ts
import { createElement } from '../utils/utils';
import { TopBar } from '../components/TopBar';
export class SplitColumnLayout {
private main: HTMLElement;
private container: HTMLElement;
private sidebar: HTMLElement;
private contentArea: HTMLElement;
private topBar: TopBar;
private isSidebarCollapsed: boolean = false;
constructor() {
this.main = createElement('div');
this.container = createElement('div');
this.container.classList.add('split-column-layout', 'container-fluid');
this.topBar = new TopBar();
this.main.appendChild(this.topBar.render());
this.sidebar = createElement('div');
this.sidebar.classList.add('sidebar'); // Bootstrap column classes for sidebar
this.contentArea = createElement('div');
this.contentArea.classList.add('content'); // Bootstrap column classes for content
this.container.appendChild(this.sidebar);
this.container.appendChild(this.contentArea);
this.main.appendChild(this.container);
}
setSidebarContent(content: HTMLElement): void {
this.sidebar.innerHTML = ''; // Clear existing content
this.sidebar.appendChild(content);
}
setContentAreaContent(content: HTMLElement): void {
this.contentArea.innerHTML = '';
this.contentArea.appendChild(content);
}
render(): HTMLElement {
return this.main;
}
toggleSidebar(): void {
this.isSidebarCollapsed = !this.isSidebarCollapsed;
if (this.isSidebarCollapsed) {
this.container.classList.add('collapsed-sidebar');
} else {
this.container.classList.remove('collapsed-sidebar');
}
}
}

View File

@@ -0,0 +1,55 @@
// layouts/ThreeColumnLayout.ts
import { createElement } from '../utils/utils';
import { TopBar } from '../components/TopBar';
export class ThreeColumnLayout {
private main: HTMLElement;
private container: HTMLElement;
private column1: HTMLElement;
private column2: HTMLElement;
private column3: HTMLElement;
private topBar: TopBar;
constructor() {
this.main = createElement('div');
this.container = createElement('div');
this.container.classList.add('three-column-layout', 'container-fluid');
this.topBar = new TopBar();
this.main.appendChild(this.topBar.render());
this.column1 = createElement('div');
this.column1.classList.add('column'); // Bootstrap column classes
this.column2 = createElement('div');
this.column2.classList.add('column');
this.column3 = createElement('div');
this.column3.classList.add('column');
this.container.appendChild(this.column1);
this.container.appendChild(this.column2);
this.container.appendChild(this.column3);
this.main.appendChild(this.container);
}
setColumn1Content(content: HTMLElement): void {
this.column1.innerHTML = ''; // Clear existing content
this.column1.appendChild(content);
}
setColumn2Content(content: HTMLElement): void {
this.column2.innerHTML = '';
this.column2.appendChild(content);
}
setColumn3Content(content: HTMLElement): void {
this.column3.innerHTML = '';
this.column3.appendChild(content);
}
render(): HTMLElement {
return this.main;
}
}

View File

@@ -1,24 +1,53 @@
import './style.css'
import typescriptLogo from './typescript.svg'
import viteLogo from '/vite.svg'
import { setupCounter } from './counter.ts'
import './style.css';
import 'bootstrap/dist/js/bootstrap.bundle.min.js'; // Bootstrap JS
import { renderLoginPage } from './pages/LoginPage';
import { renderRegisterPage } from './pages/RegisterPage';
import { renderDashboardPage } from './pages/DashboardPage';
import { renderProfilePage } from './pages/ProfilePage';
import { renderClassroomsPage } from './pages/ClassroomsPage';
import { renderAdminPage } from './pages/AdminPage';
import { renderManageStudentPage } from './pages/ManageStudentPage';
import { setupGlobalAPI } from './api/api';
import { updateLoggedInState } from './utils/utils';
document.querySelector<HTMLDivElement>('#app')!.innerHTML = `
<div>
<a href="https://vite.dev" target="_blank">
<img src="${viteLogo}" class="logo" alt="Vite logo" />
</a>
<a href="https://www.typescriptlang.org/" target="_blank">
<img src="${typescriptLogo}" class="logo vanilla" alt="TypeScript logo" />
</a>
<h1>Vite + TypeScript</h1>
<div class="card">
<button id="counter" type="button"></button>
</div>
<p class="read-the-docs">
Click on the Vite and TypeScript logos to learn more
</p>
</div>
`
const app = document.querySelector<HTMLDivElement>('#app');
if (!app) {
throw new Error("App root element not found.");
}
setupCounter(document.querySelector<HTMLButtonElement>('#counter')!)
// Initialize Global API
setupGlobalAPI();
// --- Routing and Page Rendering ---
const routes: { [key: string]: () => void } = {
'/': renderLoginPage,
'/login': renderLoginPage,
'/register': renderRegisterPage,
'/dashboard': renderDashboardPage,
'/profile': renderProfilePage,
'/classrooms': renderClassroomsPage,
'/admin': renderAdminPage,
'/manage-students': renderManageStudentPage,
};
const renderRoute = () => {
const path = window.location.hash.slice(1) || '/';
const routeRenderer = routes[path];
if (routeRenderer) {
app.innerHTML = ''; // Clear current content
routeRenderer();
} else {
app.innerHTML = '<div><h1>404 Not Found</h1></div>';
}
};
window.addEventListener('hashchange', renderRoute);
renderRoute(); // Initial render
// --- Mock Login for Prototype ---
// For demonstration, automatically log in on dashboard page load
if (window.location.hash === '#/dashboard' || window.location.hash === '#/profile' || window.location.hash === '#/admin' || window.location.hash === '#/manage-students') {
updateLoggedInState(true); // Simulate logged in state
} else {
updateLoggedInState(false);
}

17
src/pages/AdminPage.ts Normal file
View File

@@ -0,0 +1,17 @@
// pages/AdminPage.ts
import { ThreeColumnLayout } from '../layouts/ThreeColumnLayout';
import { StudentsWidget } from '../widgets/StudentsWidget';
import { TeachersWidget } from '../widgets/TeachersWidget';
export const renderAdminPage = () => {
const layout = new ThreeColumnLayout();
const studentsWidget = new StudentsWidget();
const teachersWidget = new TeachersWidget();
// Column 3 is optional for future features as per requirements
layout.setColumn1Content(studentsWidget.render());
layout.setColumn2Content(teachersWidget.render());
// Column 3 is intentionally left empty in this prototype
document.querySelector<HTMLDivElement>('#app')?.appendChild(layout.render());
};

View File

@@ -0,0 +1,12 @@
// pages/ClassroomsPage.ts
import { CenteredLayout } from '../layouts/CenteredLayout';
import { UnderConstructionWidget } from '../widgets/UnderConstructionWidget';
export const renderClassroomsPage = () => {
const layout = new CenteredLayout();
const underConstructionWidget = new UnderConstructionWidget("Classrooms is currently not yet ready for production.");
layout.addContent(underConstructionWidget.render());
document.querySelector<HTMLDivElement>('#app')?.appendChild(layout.render());
};

View File

@@ -0,0 +1,60 @@
// pages/DashboardPage.ts
import { ThreeColumnLayout } from '../layouts/ThreeColumnLayout';
import { Widget } from '../components/Widget';
import { createElement } from '../utils/utils';
// Dummy Widgets for Dashboard
class WelcomeWidget extends Widget {
render(): HTMLElement {
const widgetDiv = createElement('div');
widgetDiv.classList.add('widget');
widgetDiv.innerHTML = `
<div class="widget-header">Welcome to the Dashboard</div>
<div class="widget-body">
This is your dashboard. More widgets will be added here.
</div>
`;
return widgetDiv;
}
}
class QuickLinksWidget extends Widget {
render(): HTMLElement {
const widgetDiv = createElement('div');
widgetDiv.classList.add('widget');
widgetDiv.innerHTML = `
<div class="widget-header">Quick Links</div>
<div class="widget-body">
<ul class="list-unstyled">
<li><a href="#/profile">View Profile</a></li>
<li><a href="#/classrooms">Go to Classrooms</a></li>
<li><a href="#/admin">Admin Panel</a></li>
</ul>
</div>
`;
return widgetDiv;
}
}
class PlaceholderWidget extends Widget { // Corrected placeholder widget definition
render(): HTMLElement {
const div = createElement('div');
div.classList.add('widget');
div.textContent = 'Placeholder Widget';
return div;
}
}
export const renderDashboardPage = () => {
const layout = new ThreeColumnLayout();
const welcomeWidget = new WelcomeWidget();
const quickLinksWidget = new QuickLinksWidget();
const placeholderWidget = new PlaceholderWidget(); // Use the corrected PlaceholderWidget class
layout.setColumn1Content(welcomeWidget.render());
layout.setColumn2Content(quickLinksWidget.render());
layout.setColumn3Content(placeholderWidget.render());
document.querySelector<HTMLDivElement>('#app')?.appendChild(layout.render());
};

21
src/pages/LoginPage.ts Normal file
View File

@@ -0,0 +1,21 @@
// pages/LoginPage.ts
import { CenteredLayout } from '../layouts/CenteredLayout';
import { LoginWidget } from '../widgets/LoginWidget';
import { RegisterWidget } from '../widgets/RegisterWidget';
import { createElement } from '../utils/utils';
export const renderLoginPage = () => {
const layout = new CenteredLayout();
const loginWidget = new LoginWidget();
const registerWidget = new RegisterWidget();
const container = createElement('div');
container.classList.add('d-flex', 'flex-column', 'gap-3', 'p-4', 'rounded', 'shadow', 'blur'); // Bootstrap flex and styling
container.appendChild(loginWidget.render());
container.appendChild(registerWidget.render());
layout.addContent(container);
document.querySelector<HTMLDivElement>('#app')?.appendChild(layout.render());
};

View File

@@ -0,0 +1,16 @@
// pages/ManageStudentPage.ts
import { SplitColumnLayout } from '../layouts/SplitColumnLayout'; // Or ThreeColumnLayout or full width, depending on desired layout
import { StudentTableWidget } from '../widgets/StudentTableWidget';
import { createElement } from '../utils/utils';
export const renderManageStudentPage = () => {
const layout = new SplitColumnLayout(); // Using SplitColumnLayout, can be changed to ThreeColumnLayout or full width
const studentTableWidget = new StudentTableWidget();
layout.setContentAreaContent(studentTableWidget.render());
// Sidebar can be used for filters or additional admin options if needed
layout.setSidebarContent(createElement('div')); // Empty sidebar for now, or add sidebar widgets
document.querySelector<HTMLDivElement>('#app')?.appendChild(layout.render());
};

47
src/pages/ProfilePage.ts Normal file
View File

@@ -0,0 +1,47 @@
// pages/ProfilePage.ts
import { SplitColumnLayout } from '../layouts/SplitColumnLayout';
import { ProfileWidget } from '../widgets/ProfileWidget';
import { StudentFinancialWidget } from '../widgets/StudentFinancialWidget';
import { PostFeedWidget } from '../widgets/PostFeedWidget';
import { AccountSettingsWidget } from '../widgets/AccountSettingsWidget';
import { Modal } from '../components/Modal';
import { createElement } from '../utils/utils';
let accountSettingsModalInstance: Modal | null = null; // Keep track of modal instance
export const renderProfilePage = () => {
const layout = new SplitColumnLayout();
const sidebar = createElement('div');
const profileWidget = new ProfileWidget();
const financesWidget = new StudentFinancialWidget('mockUserId');
const postFeedWidget = new PostFeedWidget();
sidebar.appendChild(profileWidget.render());
sidebar.appendChild(financesWidget.render());
layout.setSidebarContent(sidebar);
layout.setContentAreaContent(postFeedWidget.render());
const appElement = document.querySelector<HTMLDivElement>('#app');
if (appElement) {
appElement.innerHTML = ''; // Clear existing content
appElement.appendChild(layout.render());
// Handle 'Account settings' link click from TopBar or ProfileWidget
const accountSettingsLinks = document.querySelectorAll('[data-action="open-account-settings"]');
accountSettingsLinks.forEach(link => {
link.addEventListener('click', (event) => {
event.preventDefault(); // Prevent default link behavior
if (!accountSettingsModalInstance) {
accountSettingsModalInstance = new Modal();
const settingsWidget = new AccountSettingsWidget(() => {
accountSettingsModalInstance?.hide(); // Callback to hide modal after settings update
});
accountSettingsModalInstance.setWidget(settingsWidget);
}
accountSettingsModalInstance.show();
});
});
}
};

21
src/pages/RegisterPage.ts Normal file
View File

@@ -0,0 +1,21 @@
// pages/RegisterPage.ts
import { CenteredLayout } from '../layouts/CenteredLayout';
import { RegisterWidget } from '../widgets/RegisterWidget';
import { BackButtonWidget } from '../widgets/BackButtonWidget';
import { createElement } from '../utils/utils';
export const renderRegisterPage = () => {
const layout = new CenteredLayout();
const registerMessageWidget = new RegisterWidget("Please contact your department head to register.");
const backButtonWidget = new BackButtonWidget('Back to Login', '#/login');
const container = createElement('div');
container.classList.add('d-flex', 'flex-column', 'gap-3', 'p-4', 'rounded', 'shadow'); // Bootstrap flex and styling
container.appendChild(registerMessageWidget.render());
container.appendChild(backButtonWidget.render());
layout.addContent(container);
document.querySelector<HTMLDivElement>('#app')?.appendChild(layout.render());
};

View File

@@ -1,96 +1,144 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
/* Global styles */
h1,
h2,
h3,
h4,
h5,
h6 {
margin-bottom: 0px;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
margin: 0;
padding: 0;
overflow: hidden;
font-family: sans-serif;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
.scrolling-background {
position: fixed;
top: 0;
left: 0;
width: 100%; /* Ensure it covers full width */
height: 100vh; /* Full viewport height */
background-image: url('./assets/bg1.jpg');
background-repeat: repeat-x;
background-size: auto 100%; /* Maintain width and fill height */
animation: scroll-bg 30s linear infinite;
z-index: -2;
}
#app {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vanilla:hover {
filter: drop-shadow(0 0 2em #3178c6aa);
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
@keyframes scroll-bg {
from {
background-position: 0 0;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
to {
background-position: -100% 0;
}
}
.color-overlay {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: rgba(33, 37, 41, 0.925);
z-index: -1;
}
.widget {
border: 1px solid rgb(0, 0, 0, 0.20);
background-color: rgb(31, 35, 39, 0.9);
padding: 15px;
margin-bottom: 15px;
border-radius: 5px;
}
.widget-header {
margin-bottom: 10px;
font-weight: bold;
}
.widget-body {
/* Widget body styles */
}
.icon-widget {
padding: 10px;
text-align: center;
}
/* Layout Specific Styles */
.centered-layout {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.three-column-layout {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
padding: 20px;
}
.split-column-layout {
display: grid;
grid-template-columns: 250px 1fr;
/* Sidebar and content */
gap: 20px;
padding: 20px;
}
.split-column-layout.collapsed-sidebar {
grid-template-columns: 80px 1fr;
/* Collapsed sidebar width */
}
/* Modal Styles */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
/* Semi-transparent overlay */
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
/* Ensure modal is on top */
}
.modal-content {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
width: 80%;
/* Adjust as needed */
max-width: 800px;
/* Maximum width */
}
/* Responsive adjustments (example) */
@media (max-width: 768px) {
.three-column-layout {
grid-template-columns: 1fr;
/* Stack columns on smaller screens */
}
.split-column-layout {
grid-template-columns: 1fr;
/* Stack sidebar and content */
}
.split-column-layout.collapsed-sidebar {
grid-template-columns: 1fr;
/* Stack even if collapsed */
}
}

32
src/utils/utils.ts Normal file
View File

@@ -0,0 +1,32 @@
// utils.ts
let isLoggedIn = false; // Global state for login status. In a real app, use more robust state management.
let userToken: string | null = null; // Store user token
export const updateLoggedInState = (loggedIn: boolean, token: string | null = null) => {
isLoggedIn = loggedIn;
userToken = token;
// You can add more logic here, like redirecting based on login state
};
export const isLoggedInUser = () => {
return isLoggedIn;
};
export const getUserToken = () => {
return userToken;
};
// Function to generate a random 6-digit ID
export const generateUserId = (): string => {
return String(Math.floor(100000 + Math.random() * 900000));
};
// Function to navigate to a different page (prototype routing)
export const navigateTo = (path: string) => {
window.location.hash = path;
};
// Helper function to create HTML elements
export const createElement = <K extends keyof HTMLElementTagNameMap>(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K] => {
return document.createElement(tagName, options);
};

View File

@@ -0,0 +1,119 @@
// widgets/AccountSettingsWidget.ts
import { Widget } from '../components/Widget';
import { createElement } from '../utils/utils';
import { globalAPI, ApiResponse } from '../api/api';
export class AccountSettingsWidget extends Widget {
private onSettingsUpdated: () => void;
constructor(onSettingsUpdated: () => void) {
super();
this.onSettingsUpdated = onSettingsUpdated;
}
render(): HTMLElement {
this.container.innerHTML = '';
const header = createElement('div');
header.classList.add('widget-header');
header.textContent = 'Account Settings';
this.container.appendChild(header);
const widgetBody = createElement('div');
widgetBody.classList.add('widget-body');
const form = createElement('form');
// Profile Picture Section
const profilePictureSection = createElement('div');
profilePictureSection.classList.add('mb-3');
const profilePictureLabel = createElement('label') as HTMLLabelElement; // Cast first
profilePictureLabel.classList.add('form-label');
profilePictureLabel.htmlFor = 'profilePicture'; // Set htmlFor as property
profilePictureLabel.textContent = 'Profile Picture';
const profilePictureInput = createElement('input') as HTMLInputElement;
profilePictureInput.type = 'file';
profilePictureInput.classList.add('form-control');
profilePictureInput.id = 'profilePicture';
profilePictureSection.appendChild(profilePictureLabel);
profilePictureSection.appendChild(profilePictureInput);
form.appendChild(profilePictureSection);
// Student Details Section (Read-only in prototype)
const studentDetailsSection = createElement('div');
studentDetailsSection.classList.add('mb-3');
studentDetailsSection.innerHTML = `
<div class="mb-2"><strong>Student Details</strong> <span class="text-muted">(Contact department head for corrections)</span></div>
<div class="mb-2">
<label for="fullName" class="form-label">Full Name</label>
<input type="text" class="form-control" id="fullName" value="John Doe" readonly disabled>
</div>
<div>
<label for="birthdate" class="form-label">Birthdate</label>
<input type="text" class="form-control" id="birthdate" value="2000-01-01" readonly disabled>
</div>
`;
form.appendChild(studentDetailsSection);
// Password Change Section
const passwordChangeSection = createElement('div');
passwordChangeSection.classList.add('mb-3');
passwordChangeSection.innerHTML = `
<div class="mb-2"><strong>Change Password</strong></div>
<div class="mb-2">
<label for="newPassword" class="form-label">New Password</label>
<input type="password" class="form-control" id="newPassword" placeholder="New Password">
</div>
<div>
<label for="confirmPassword" class="form-label">Confirm New Password</label>
<input type="password" class="form-control" id="confirmPassword" placeholder="Confirm New Password">
</div>
`;
form.appendChild(passwordChangeSection);
const saveButton = createElement('button');
saveButton.type = 'submit';
saveButton.classList.add('btn', 'btn-primary');
saveButton.textContent = 'Save Changes';
form.appendChild(saveButton);
form.addEventListener('submit', async (event) => {
event.preventDefault();
// In a real application, you would collect and validate form data,
// then send it to the backend API for updateAccountSettings.
// For this prototype, we'll just simulate a successful update.
const newPassword = (document.getElementById('newPassword') as HTMLInputElement).value;
const confirmPassword = (document.getElementById('confirmPassword') as HTMLInputElement).value;
if (newPassword && newPassword !== confirmPassword) {
alert('New password and confirm password do not match.');
return;
}
const settingsData = {
// profilePicture: ..., // Handle profile picture upload in real app
password: newPassword || undefined, // Send password only if changed
// ... other settings to update
};
try {
const response: ApiResponse<void> = await globalAPI.updateAccountSettings('mockUserId', settingsData); // Typed response
if (response.success) {
alert('Account settings updated successfully!');
this.onSettingsUpdated(); // Call the callback to hide the modal
} else {
alert('Failed to update account settings.');
}
} catch (error) {
console.error('Error updating account settings:', error);
alert('Error occurred while updating account settings.');
}
});
widgetBody.appendChild(form);
this.container.appendChild(widgetBody);
return this.container;
}
}

View File

@@ -0,0 +1,28 @@
// widgets/BackButtonWidget.ts
import { Widget } from '../components/Widget';
import { createElement, navigateTo } from '../utils/utils';
export class BackButtonWidget extends Widget {
private buttonText: string;
private navigatePath: string;
constructor(buttonText: string, navigatePath: string) {
super();
this.buttonText = buttonText;
this.navigatePath = navigatePath;
}
render(): HTMLElement {
this.container.innerHTML = ''; // Clear previous content
const button = createElement('button');
button.classList.add('btn', 'btn-secondary');
button.textContent = this.buttonText;
button.addEventListener('click', () => {
navigateTo(this.navigatePath);
});
this.container.appendChild(button);
return this.container;
}
}

View File

@@ -0,0 +1,78 @@
// widgets/LoginWidget.ts
import { Widget } from '../components/Widget';
import { createElement, navigateTo } from '../utils/utils';
import { globalAPI, ApiResponse, LoginResponseData } from '../api/api';
export class LoginWidget extends Widget {
constructor() {
super();
}
render(): HTMLElement {
this.container.innerHTML = '';
const header = createElement('h2');
header.classList.add('widget-header');
header.textContent = 'Login';
const form = createElement('form');
const userIdInputGroup = createElement('div');
userIdInputGroup.classList.add('mb-3');
const userIdLabel = createElement('label') as HTMLLabelElement; // Cast first
userIdLabel.classList.add('form-label');
userIdLabel.htmlFor = 'userId'; // Set htmlFor as property
userIdLabel.textContent = 'Student ID';
const userIdInput = createElement('input') as HTMLInputElement;
userIdInput.type = 'text';
userIdInput.classList.add('form-control');
userIdInput.id = 'userId';
userIdInput.placeholder = '123456';
userIdInputGroup.appendChild(userIdLabel);
userIdInputGroup.appendChild(userIdInput);
const passwordInputGroup = createElement('div');
passwordInputGroup.classList.add('mb-3');
const passwordLabel = createElement('label') as HTMLLabelElement; // Cast first
passwordLabel.classList.add('form-label');
passwordLabel.htmlFor = 'password'; // Set htmlFor as property
passwordLabel.textContent = 'Password';
const passwordInput = createElement('input') as HTMLInputElement;
passwordInput.type = 'password';
passwordInput.classList.add('form-control');
passwordInput.id = 'password';
passwordInput.placeholder = 'Password';
passwordInputGroup.appendChild(passwordLabel);
passwordInputGroup.appendChild(passwordInput);
const loginButton = createElement('button');
loginButton.type = 'submit';
loginButton.classList.add('btn', 'btn-primary');
loginButton.textContent = 'Login';
form.appendChild(userIdInputGroup);
form.appendChild(passwordInputGroup);
form.appendChild(loginButton);
form.addEventListener('submit', async (event) => {
event.preventDefault();
const userId = userIdInput.value;
const password = passwordInput.value;
try {
const response: ApiResponse<LoginResponseData> = await globalAPI.login({ userId, password });
if (response.success) {
navigateTo('/dashboard');
} else {
alert('Login failed: ' + response.message);
}
} catch (error) {
console.error('Login error:', error);
alert('Login error occurred.');
}
});
this.container.appendChild(header);
this.container.appendChild(form);
return this.container;
}
}

View File

@@ -0,0 +1,53 @@
// widgets/PostFeedWidget.ts
import { Widget } from '../components/Widget';
import { createElement } from '../utils/utils';
import { globalAPI, ApiResponse, ProfileResponseData } from '../api/api'; // Import API and types (now exported)
export class PostFeedWidget extends Widget {
private posts: { id: number; content: string }[] = [];
constructor() {
super();
this.fetchPosts();
}
async fetchPosts() {
try {
const response: ApiResponse<ProfileResponseData> = await globalAPI.getProfile('mockUserId');
if (response.success && response.data && response.data.posts) {
this.posts = response.data.posts;
this.render();
} else {
console.error("Failed to fetch posts");
}
} catch (error) {
console.error("Error fetching posts:", error);
}
}
render(): HTMLElement {
this.container.innerHTML = '';
const header = createElement('div');
header.classList.add('widget-header');
header.textContent = 'Post Feed';
this.container.appendChild(header);
const widgetBody = createElement('div');
widgetBody.classList.add('widget-body');
if (this.posts.length === 0) {
widgetBody.textContent = 'No posts yet.';
} else {
this.posts.forEach(post => {
const postDiv = createElement('div');
postDiv.classList.add('mb-2', 'p-2', 'border', 'rounded');
postDiv.textContent = post.content;
widgetBody.appendChild(postDiv);
});
}
this.container.appendChild(widgetBody);
return this.container;
}
}

View File

@@ -0,0 +1,110 @@
// widgets/ProfileWidget.ts
import { Widget } from '../components/Widget';
import { createElement } from '../utils/utils';
import { globalAPI, ApiResponse, ProfileResponseData } from '../api/api';
export class ProfileWidget extends Widget {
private profileData: ProfileResponseData | null = null;
constructor() {
super();
this.fetchProfileData();
}
async fetchProfileData() {
try {
const response: ApiResponse<ProfileResponseData> = await globalAPI.getProfile('mockUserId');
if (response.success && response.data) {
this.profileData = response.data;
this.render();
} else {
console.error("Failed to fetch profile data");
}
} catch (error) {
console.error("Error fetching profile data:", error);
}
}
render(): HTMLElement {
this.container.innerHTML = '';
if (!this.profileData) { // Null check here
this.container.textContent = 'Loading profile...';
return this.container;
}
const header = createElement('div');
header.classList.add('widget-header', 'd-flex', 'justify-content-between', 'align-items-center');
const headerText = createElement('div');
headerText.classList.add('widget-title');
headerText.textContent = 'Profile Information';
header.appendChild(headerText);
const kebabMenuButton = createElement('button');
kebabMenuButton.classList.add('btn', 'btn-outline-secondary', 'btn-sm', 'dropdown-toggle');
kebabMenuButton.type = 'button';
kebabMenuButton.id = 'profileKebabMenu';
kebabMenuButton.setAttribute('data-bs-toggle', 'dropdown');
kebabMenuButton.setAttribute('aria-expanded', 'false');
kebabMenuButton.innerHTML = '⋮'; // Kebab menu icon (vertical ellipsis)
header.appendChild(kebabMenuButton);
const dropdownMenu = createElement('ul');
dropdownMenu.classList.add('dropdown-menu', 'dropdown-menu-end');
dropdownMenu.setAttribute('aria-labelledby', 'profileKebabMenu');
const accountSettingsMenuItem = createElement('li');
const accountSettingsLink = createElement('a');
accountSettingsLink.classList.add('dropdown-item');
accountSettingsLink.href = '#/profile';
accountSettingsLink.setAttribute('data-action', 'open-account-settings');
accountSettingsLink.textContent = 'Account settings';
accountSettingsMenuItem.appendChild(accountSettingsLink);
dropdownMenu.appendChild(accountSettingsMenuItem);
header.appendChild(dropdownMenu);
this.container.appendChild(header);
const widgetBody = createElement('div');
widgetBody.classList.add('widget-body', 'row', 'g-3');
const profileImageCol = createElement('div');
profileImageCol.classList.add('col-md-4');
const profileImage = createElement('img');
if (this.profileData.profilePicture) { // Null check before accessing properties
profileImage.src = this.profileData.profilePicture;
} else {
profileImage.src = 'src/assets/vite.svg'; // Default image if no profile picture
}
profileImage.alt = 'Profile Picture';
profileImage.classList.add('img-fluid', 'rounded-circle');
profileImageCol.appendChild(profileImage);
widgetBody.appendChild(profileImageCol);
const detailsCol = createElement('div');
detailsCol.classList.add('col-md-8');
const fullNamePara = createElement('p');
if (this.profileData.fullName) { // Null check before accessing properties
fullNamePara.innerHTML = `${this.profileData.fullName}`;
} else {
fullNamePara.innerHTML = `<small>Full Name:</small><br>N/A`; // Or some default text
}
const schoolIdPara = createElement('p');
if (this.profileData.schoolId) { // Null check before accessing properties
schoolIdPara.innerHTML = `<small><strong>School ID:</small></strong><br>${this.profileData.schoolId}`;
} else {
schoolIdPara.innerHTML = `<small><strong>School ID:</strong></small><br>N/A`;
}
const birthdatePara = createElement('p');
birthdatePara.innerHTML = `<small><strong>Birthdate:</strong></small><br><span class="text-muted">(Hidden from others)</span>`;
detailsCol.appendChild(fullNamePara);
detailsCol.appendChild(schoolIdPara);
detailsCol.appendChild(birthdatePara);
widgetBody.appendChild(detailsCol);
this.container.appendChild(widgetBody);
return this.container;
}
}

View File

@@ -0,0 +1,37 @@
// widgets/RegisterMessageWidget.ts
import { Widget } from '../components/Widget';
import { createElement, navigateTo } from '../utils/utils';
export class RegisterWidget extends Widget {
private message: string;
constructor(message?: string) {
super();
this.message = message || "For registration, please contact your department head for further instructions.";
}
render(): HTMLElement {
this.container.innerHTML = ''; // Clear previous content
const header = createElement('h2');
header.classList.add('widget-header');
header.textContent = 'Register';
const messageParagraph = createElement('p');
messageParagraph.classList.add('widget-body');
messageParagraph.textContent = this.message;
const button = createElement('button');
button.classList.add('btn', 'btn-secondary');
button.textContent = 'Register';
button.disabled = true;
button.addEventListener('click', () => {
navigateTo('/register');
});
this.container.appendChild(header);
this.container.appendChild(messageParagraph);
this.container.appendChild(button);
return this.container;
}
}

View File

@@ -0,0 +1,99 @@
// widgets/StudentFinancialWidget.ts
import { Widget } from '../components/Widget';
import { createElement } from '../utils/utils';
import { globalAPI, ApiResponse, StudentFinancialData } from '../api/api'; // Import API and types
export class StudentFinancialWidget extends Widget {
private studentId: string;
private financialData: StudentFinancialData | null = null;
private isLoading: boolean = true;
private hasError: boolean = false;
constructor(studentId: string) {
super();
this.studentId = studentId;
this.fetchFinancialData();
}
async fetchFinancialData() {
this.isLoading = true;
this.hasError = false;
this.render(); // Re-render to show loading state
try {
const response: ApiResponse<StudentFinancialData> = await globalAPI.getStudentFinancialData(this.studentId);
if (response.success && response.data) {
this.financialData = response.data;
} else {
this.hasError = true;
console.error("Failed to fetch student financial data:", response.message);
}
} catch (error) {
this.hasError = true;
console.error("Error fetching student financial data:", error);
} finally {
this.isLoading = false;
this.render(); // Re-render with fetched data or error state
}
}
render(): HTMLElement {
this.container.innerHTML = ''; // Clear previous content
const widgetBody = createElement('div');
widgetBody.classList.add('widget-body');
if (this.isLoading) {
widgetBody.textContent = 'Loading financial data...';
} else if (this.hasError) {
widgetBody.textContent = 'Failed to load financial data.';
} else if (this.financialData) {
const header = createElement('div');
header.classList.add('widget-header');
header.textContent = 'Payment Information';
this.container.appendChild(header);
this.container.appendChild(header);
widgetBody.innerHTML = `
<div class="row mb-2">
<div class="col-sm-6">Tuition Fee:</div>
<div class="col-sm-6">₱ ${this.financialData.tuitionFee}</div>
</div>
<div class="row mb-2">
<div class="col-sm-6">Miscellaneous:</div>
<div class="col-sm-6">₱ ${this.financialData.miscellaneousFee}</div>
</div>
<div class="row mb-2">
<div class="col-sm-6">Lab Fee:</div>
<div class="col-sm-6">₱ ${this.financialData.labFee}</div>
</div>
<div class="row mb-2">
<div class="col-sm-6">Current:</div>
<div class="col-sm-6">₱ ${this.financialData.currentAccount}</div>
</div>
<div class="row mb-2">
<div class="col-sm-6">Down:</div>
<div class="col-sm-6">₱ ${this.financialData.downPayment}</div>
</div>
<div class="row mb-2">
<div class="col-sm-6">Midterms:</div>
<div class="col-sm-6">₱ ${this.financialData.midtermPayment}</div>
</div>
<div class="row mb-2">
<div class="col-sm-6">Prefinals:</div>
<div class="col-sm-6">₱ ${this.financialData.prefinalPayment}</div>
</div>
<div class="row mb-2">
<div class="col-sm-6">Finals:</div>
<div class="col-sm-6">₱ ${this.financialData.finalPayment}</div>
</div>
`;
} else {
widgetBody.textContent = 'No financial data available.'; // Should not usually reach here if no error but no data
}
this.container.appendChild(widgetBody);
return this.container;
}
}

View File

@@ -0,0 +1,191 @@
// widgets/StudentTableWidget.ts
import { Widget } from '../components/Widget';
import { createElement, navigateTo } from '../utils/utils';
import { globalAPI, ApiResponse, StudentListData } from '../api/api';
export class StudentTableWidget extends Widget {
private students: StudentListData[] = [];
private yearFilter: string = 'all';
private courseFilter: string = 'all';
private availableYears: string[] = ['all', '1', '2', '3', '4'];
private availableCourses: string[] = ['all', 'Math', 'Science', 'History', 'English'];
constructor() {
super();
this.fetchStudentData();
}
async fetchStudentData() {
try {
const response: ApiResponse<StudentListData[]> = await globalAPI.getStudentList();
if (response.success && response.data) {
this.students = response.data;
this.render();
} else {
console.error("Failed to fetch student list");
}
} catch (error) {
console.error("Error fetching student list:", error);
}
}
render(): HTMLElement {
this.container.innerHTML = '';
const header = createElement('div');
header.classList.add('widget-header');
header.textContent = 'Manage Students';
this.container.appendChild(header);
const widgetBody = createElement('div');
widgetBody.classList.add('widget-body');
// Filters
const filtersRow = createElement('div');
filtersRow.classList.add('row', 'mb-3', 'g-3', 'align-items-center');
// Year Level Filter
const yearFilterCol = createElement('div');
yearFilterCol.classList.add('col-auto');
const yearFilterLabel = createElement('label') as HTMLLabelElement; // Cast first
yearFilterLabel.classList.add('col-form-label', 'me-2');
yearFilterLabel.htmlFor = 'yearLevelFilter'; // Set htmlFor as property
yearFilterLabel.textContent = 'Year Level:';
const yearFilterSelect = createElement('select') as HTMLSelectElement;
yearFilterSelect.classList.add('form-select');
yearFilterSelect.id = 'yearLevelFilter';
this.availableYears.forEach(year => {
const option = createElement('option');
option.value = year;
option.textContent = year === 'all' ? 'All Years' : `Year ${year}`;
yearFilterSelect.appendChild(option);
});
yearFilterSelect.value = this.yearFilter;
yearFilterSelect.addEventListener('change', (e) => {
this.yearFilter = (e.target as HTMLSelectElement).value;
this.renderTable(widgetBody);
});
yearFilterCol.appendChild(yearFilterLabel);
yearFilterCol.appendChild(yearFilterSelect);
filtersRow.appendChild(yearFilterCol);
// Course Filter
const courseFilterCol = createElement('div');
courseFilterCol.classList.add('col-auto');
const courseFilterLabel = createElement('label') as HTMLLabelElement; // Cast first
courseFilterLabel.classList.add('col-form-label', 'me-2');
courseFilterLabel.htmlFor = 'courseFilter'; // Set htmlFor as property
courseFilterLabel.textContent = 'Course:';
const courseFilterSelect = createElement('select') as HTMLSelectElement;
courseFilterSelect.classList.add('form-select');
courseFilterSelect.id = 'courseFilter';
this.availableCourses.forEach(course => {
const option = createElement('option');
option.value = course;
option.textContent = course === 'all' ? 'All Courses' : course;
courseFilterSelect.appendChild(option);
});
courseFilterSelect.value = this.courseFilter;
courseFilterSelect.addEventListener('change', (e) => {
this.courseFilter = (e.target as HTMLSelectElement).value;
this.renderTable(widgetBody);
});
courseFilterCol.appendChild(courseFilterLabel);
courseFilterCol.appendChild(courseFilterSelect);
filtersRow.appendChild(courseFilterCol);
widgetBody.appendChild(filtersRow);
// Table Container
const tableContainer = createElement('div');
widgetBody.appendChild(tableContainer);
this.renderTable(tableContainer);
// "Add" button and Batch Add
const addButtonRow = createElement('div');
addButtonRow.classList.add('row', 'mt-3', 'justify-content-between', 'align-items-center');
const addButtonCol = createElement('div');
addButtonCol.classList.add('col-auto');
const addButton = createElement('button');
addButton.classList.add('btn', 'btn-success', 'btn-sm', 'me-2');
addButton.textContent = 'Add Student';
addButtonCol.appendChild(addButton);
addButtonRow.appendChild(addButtonCol);
const batchAddCol = createElement('div');
batchAddCol.classList.add('col-auto');
const batchAddLink = createElement('a');
batchAddLink.href = '#/batch-add-students';
batchAddLink.textContent = 'Batch Add Students';
batchAddCol.appendChild(batchAddLink);
addButtonRow.appendChild(batchAddCol);
widgetBody.appendChild(addButtonRow);
this.container.appendChild(widgetBody);
return this.container;
}
private renderTable(container: HTMLElement) {
container.innerHTML = '';
const table = createElement('table');
table.classList.add('table', 'table-striped', 'table-bordered');
const thead = createElement('thead');
thead.innerHTML = `
<tr>
<th>ID</th>
<th>Name</th>
<th>Year Level</th>
<th>Courses</th>
<th>Actions</th>
</tr>
`;
table.appendChild(thead);
const tbody = createElement('tbody');
const filteredStudents = this.students.filter(student => {
const yearMatch = this.yearFilter === 'all' || student.yearLevel === this.yearFilter;
const courseMatch = this.courseFilter === 'all' || student.courses.includes(this.courseFilter);
return yearMatch && courseMatch;
});
filteredStudents.forEach(student => {
const row = createElement('tr');
row.innerHTML = `
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.yearLevel}</td>
<td>${student.courses.join(', ')}</td>
<td>
<button class="btn btn-info btn-sm view-profile-btn" data-student-id="${student.id}">View Profile</button>
<button class="btn btn-secondary btn-sm enroll-btn" data-student-id="${student.id}">Enroll</button>
</td>
`;
tbody.appendChild(row);
});
table.appendChild(tbody);
container.appendChild(table);
this.attachTableEventListeners(table);
}
private attachTableEventListeners(table: HTMLTableElement) {
table.querySelectorAll('.view-profile-btn').forEach(button => {
button.addEventListener('click', (event) => {
const studentId = (event.target as HTMLElement).dataset.studentId;
if (studentId) {
navigateTo(`/profile?studentId=${studentId}`);
}
});
});
table.querySelectorAll('.enroll-btn').forEach(button => {
button.addEventListener('click', (event) => {
const studentId = (event.target as HTMLElement).dataset.studentId;
if (studentId) {
alert(`Enroll functionality for student ID ${studentId} - Not fully implemented in prototype.`);
}
});
});
}
}

View File

@@ -0,0 +1,54 @@
// widgets/StudentsWidget.ts
import { Widget } from '../components/Widget';
import { createElement, navigateTo } from '../utils/utils';
import { globalAPI, ApiResponse, AdminDashboardData } from '../api/api'; // Import API and types (now exported)
export class StudentsWidget extends Widget {
private studentCount: number = 0;
constructor() {
super();
this.fetchStudentCount();
}
async fetchStudentCount() {
try {
const response: ApiResponse<AdminDashboardData> = await globalAPI.getAdminDashboardData();
if (response.success && response.data) {
this.studentCount = response.data.studentsCount || 0;
this.render();
} else {
console.error("Failed to fetch admin dashboard data");
}
} catch (error) {
console.error("Error fetching admin dashboard data:", error);
}
}
render(): HTMLElement {
this.container.innerHTML = '';
const header = createElement('div');
header.classList.add('widget-header');
header.textContent = 'Students';
this.container.appendChild(header);
const widgetBody = createElement('div');
widgetBody.classList.add('widget-body', 'text-center');
const countDisplay = createElement('h3');
countDisplay.textContent = String(this.studentCount);
widgetBody.appendChild(countDisplay);
const manageButton = createElement('button');
manageButton.classList.add('btn', 'btn-primary', 'btn-sm');
manageButton.textContent = 'Manage Students';
manageButton.addEventListener('click', () => {
navigateTo('/manage-students');
});
widgetBody.appendChild(manageButton);
this.container.appendChild(widgetBody);
return this.container;
}
}

View File

@@ -0,0 +1,52 @@
// widgets/TeachersWidget.ts
import { Widget } from '../components/Widget';
import { createElement } from '../utils/utils';
import { globalAPI, ApiResponse, AdminDashboardData } from '../api/api'; // Import API and types (now exported)
export class TeachersWidget extends Widget {
private teacherCount: number = 0;
constructor() {
super();
this.fetchTeacherCount();
}
async fetchTeacherCount() {
try {
const response: ApiResponse<AdminDashboardData> = await globalAPI.getAdminDashboardData();
if (response.success && response.data) {
this.teacherCount = response.data.teachersCount || 0;
this.render();
} else {
console.error("Failed to fetch admin dashboard data");
}
} catch (error) {
console.error("Error fetching admin dashboard data:", error);
}
}
render(): HTMLElement {
this.container.innerHTML = '';
const header = createElement('div');
header.classList.add('widget-header');
header.textContent = 'Teachers';
this.container.appendChild(header);
const widgetBody = createElement('div');
widgetBody.classList.add('widget-body', 'text-center');
const countDisplay = createElement('h3');
countDisplay.textContent = String(this.teacherCount);
widgetBody.appendChild(countDisplay);
// In this prototype, teacher management page is not specified, so button is disabled or can link to a placeholder page.
const manageButton = createElement('button');
manageButton.classList.add('btn', 'btn-secondary', 'btn-sm', 'disabled'); // Disabled for prototype
manageButton.textContent = 'Manage Teachers (Coming Soon)';
widgetBody.appendChild(manageButton);
this.container.appendChild(widgetBody);
return this.container;
}
}

View File

@@ -0,0 +1,38 @@
// widgets/UnderConstructionWidget.ts
import { Widget } from '../components/Widget';
import { createElement } from '../utils/utils';
export class UnderConstructionWidget extends Widget {
private message: string;
constructor(message: string) {
super();
this.message = message;
}
render(): HTMLElement {
this.container.innerHTML = ''; // Clear previous content
const header = createElement('div');
header.classList.add('widget-header', 'text-center');
header.textContent = 'Under Construction';
this.container.appendChild(header);
const widgetBody = createElement('div');
widgetBody.classList.add('widget-body', 'text-center');
widgetBody.textContent = this.message;
this.container.appendChild(widgetBody);
const icon = createElement('i');
icon.classList.add('bi', 'bi-tools', 'd-block', 'mx-auto', 'my-3'); // Bootstrap Icons class, needs Bootstrap Icons CSS if you want to use icons.
icon.style.fontSize = '2em'; // Example icon style, can be customized.
// Note: Bootstrap Icons would need to be included in index.html if used.
// For prototype simplicity, we'll skip including Bootstrap Icons CSS.
// If you want to add Bootstrap Icons, include this in index.html <head>:
// <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
// widgetBody.appendChild(icon); // Uncomment if you decide to include Bootstrap Icons.
return this.container;
}
}