Project Documentation
🚀 1. Overview
Project Overview
The project appears to be a hall monitoring and management system, designed to help administrators manage the usage of halls and facilities within a university setting. The system allows administrators to view the status of various halls, book or reserve halls for specific events or activities, and manage the usage of these facilities.
The system is built using a combination of front-end and back-end technologies, with a strong emphasis on real-time data synchronization and management. The project utilizes Supabase, a PostgreSQL-based database service, to store and manage the state of the application. The front-end is built using JavaScript, with a custom implementation of a store and state management system.
Core Functionality
The core functionality of the system revolves around the management of hall usage and bookings. Administrators can view the status of various halls, including their availability, occupancy, and any pending bookings or reservations. The system also allows administrators to book or reserve halls for specific events or activities, and manage the usage of these facilities in real-time.
The system includes features such as hall filtering, sorting, and searching, as well as the ability to view detailed information about each hall, including its location, capacity, and equipment. The system also includes a notification system, which alerts administrators to any changes or updates to the hall usage or bookings.
Tech Stack
The project's tech stack is a key aspect of its architecture and functionality. The following table provides a summary of the technologies used in the project:
| Category | Technology | Purpose |
|---|---|---|
| Database | Supabase | Stores and manages the state of the application |
| Front-end Framework | Custom JavaScript implementation | Handles user interactions and updates the UI |
| State Management | Custom store and state management system | Manages the application's state and data |
| Styling | Custom CSS implementation | Handles the visual styling and layout of the application |
| Utilities | Various JavaScript libraries and utilities | Provides additional functionality and features |
| Some specific frameworks, libraries, and tools used in the project include: |
- Supabase: a PostgreSQL-based database service for storing and managing the state of the application
- JavaScript: used for building the front-end and handling user interactions
- Custom store and state management system: manages the application's state and data
- Custom CSS implementation: handles the visual styling and layout of the application
Problem Statement
The problem that this project solves is the need for a efficient and effective hall monitoring and management system within a university setting. The system provides a centralized platform for administrators to manage the usage of halls and facilities, ensuring that these resources are utilized optimally and that any issues or conflicts are resolved quickly and efficiently.
The system also helps to reduce the administrative burden associated with managing hall usage, by automating many of the tasks and processes involved. This allows administrators to focus on more strategic and high-value tasks, such as planning and optimization, rather than manual data entry and record-keeping.
Implementation Details
The implementation details of the project are complex and multifaceted, involving a range of technical and non-technical considerations. Some of the key implementation details include:
- The use of Supabase as the database service, which provides a scalable and reliable platform for storing and managing the state of the application
- The implementation of a custom store and state management system, which manages the application's state and data
- The use of JavaScript and custom CSS for building the front-end and handling user interactions
- The integration of various JavaScript libraries and utilities, which provide additional functionality and features
Overall, the project is a complex and sophisticated system that requires careful planning, design, and implementation to ensure that it meets the needs of its users and stakeholders.
📂 2. Project Structure
Codebase Analysis
The provided codebase file structure appears to be a web application with administrative interfaces, utilizing Supabase as the backend database. Below is a detailed breakdown of the file structure, grouped into logical categories.
File Structure TABLE
| Category | Sub-folder | Key Responsibility |
|---|---|---|
| Authentication | admin/adminn | Handles login functionality for admin and superadmin |
| UI Components | admin | Contains HTML files for admin and superadmin dashboards and login pages |
| UI Components | assets/css | Holds CSS stylesheets for various interfaces (admin, student, superadmin) |
| UI Components | assets/js | Contains JavaScript files for handling UI interactions and data storage |
| API/Services | assets/js | Utilizes Supabase client and config for database interactions |
| Database Models | supabase | Defines the database schema using SQL |
| Documentation | root | Provides setup instructions for Supabase |
| State Management | assets/js | Manages data storage using the data-store.js file |
Architectural Patterns
The codebase appears to follow a simplified version of the Model-View-Controller (MVC) pattern, with some elements of Event-Driven Architecture.
- MVC Pattern:
- Model: The
supabase/schema.sqlfile defines the database structure, acting as the data model. - View: The HTML files (
admin/dashboard.html,admin/adminn/login.html, etc.) represent the user interface, displaying data to the user. - Controller: The JavaScript files (
assets/js/admin-dashboard.js,assets/js/admin-login.js, etc.) handle user input, interact with the Supabase database using thesupabase-client.jsandsupabase-config.jsfiles, and update the UI accordingly.
- Model: The
- Event-Driven Architecture:
- The use of JavaScript event listeners and handlers (e.g., in
assets/js/admin-login.js) implies an event-driven approach, where user interactions trigger specific actions and updates to the application state.
- The use of JavaScript event listeners and handlers (e.g., in
However, the codebase does not strictly adhere to a single architectural pattern. The presence of multiple JavaScript files with overlapping responsibilities (e.g., admin-login.js and superadmin-login.js) suggests a need for refactoring and organization to improve maintainability and scalability.
Recommendations
To improve the codebase, consider the following:
- Separate Concerns: Refactor JavaScript files to have single, well-defined responsibilities, reducing duplication and improving modularity.
- Consistent Naming Conventions: Establish a consistent naming convention throughout the codebase to enhance readability and maintainability.
- Embrace a Single Architectural Pattern: Choose a suitable architectural pattern (e.g., MVC, Onion, Clean Architecture) and adhere to it consistently throughout the codebase to improve organization and scalability.
By addressing these recommendations, the codebase can become more maintainable, efficient, and scalable, ultimately leading to a better overall architecture.
🏗️ 3. Architecture & Data Flow
Deep-Dive Architecture Analysis: Hall Monitor System
1. Architecture Reasoning & Design Patterns
This repository represents a multi-role hall monitoring system built on Supabase for state management and authentication, with a client-side state synchronization pattern. Below is a detailed breakdown of the architectural decisions, module interactions, and design patterns employed.
1.1 Core Architectural Layers
The system can be decomposed into three primary layers:
| Layer | Responsibility | Key Components |
|---|---|---|
| Frontend (UI Layer) | Rendering UI, handling user interactions, and managing local state | HTML/CSS/JS files (index.html, admin-dashboard.js, student.js, etc.) |
| State Management | Centralized state storage, synchronization with Supabase, and reactivity | assets/js/data-store.js (HallMonitorStore), supabase-client.js |
| Backend (Supabase) | Auth, database, and real-time sync (via Supabase Realtime) | supabase/schema.sql, SUPABASE_SETUP.md, Supabase Auth & Database policies |
1.2 Key Design Patterns
1.2.1 Singleton State Store (HallMonitorStore)
- Pattern: Singleton + Observer
- Implementation:
assets/js/data-store.jsexports a singleHallMonitorStoreinstance that:- Manages local state (via
localStorage). - Hydrates from Supabase on initialization.
- Syncs updates to Supabase in real-time.
- Broadcasts changes to subscribed UI components (e.g., dashboard tables, alerts).
- Manages local state (via
- Why?
- Ensures single source of truth for the app state.
- Avoids prop drilling and simplifies state sharing across components.
1.2.2 Supabase Realtime Sync
- Pattern: Event-Driven Architecture
- Implementation:
- Supabase Realtime is used to listen for database changes (
public.hallmonitor_state). - When a change occurs (e.g., hall status update), the client re-fetches state and updates the UI.
- Supabase Realtime is used to listen for database changes (
- Why?
- Enables collaborative editing (e.g., multiple admins viewing the same dashboard).
- Reduces polling overhead (vs. traditional
setIntervalfetches).
1.2.3 Role-Based Access Control (RBAC)
- Pattern: Middleware + Policy-Based Routing
- Implementation:
- Auth: Supabase Auth manages user sessions (
admin-login.js,superadmin-login.js). - Routing: Frontend checks
session.adminRoleto redirect users (e.g.,admin-dashboard.jsredirects non-admins tologin.html). - Database Policies:
supabase/schema.sqldefines Row-Level Security (RLS) policies (e.g., onlysuperadmincan modify certain rows).
- Auth: Supabase Auth manages user sessions (
- Why?
- Ensures secure access to admin/superadmin features.
- Reduces server-side logic by offloading checks to the client.
1.2.4 Template Method Pattern (UI Components)
- Pattern: Template Method
- Implementation:
- UI components (e.g.,
admin-dashboard.js) follow a consistent lifecycle:- Initialize (fetch state, set up event listeners).
- Render (populate DOM with state data).
- Update (re-render when state changes).
- Shared logic (e.g.,
formatStatusBadge,toTextDate) is reused across components.
- UI components (e.g.,
- Why?
- Promotes DRY (Don’t Repeat Yourself) code.
- Makes components easier to maintain.
1.2.5 Observer Pattern (State Changes)
- Pattern: Observer
- Implementation:
- The
HallMonitorStorenotifies subscribers when state changes (e.g., viastore.subscribe()). - UI components register callbacks to re-render when relevant state updates.
- The
- Why?
- Enables reactive UI updates without manual DOM manipulation.
- Decouples state management from UI rendering.
1.3 Module Interactions
1.3.1 State Flow
-
Initialization:
- User loads a page (e.g.,
admin-dashboard.html). assets/js/data-store.jsinitializesHallMonitorStore.HallMonitorStore.ensureState():- Loads state from
localStorage(if available). - Fetches state from Supabase (
public.hallmonitor_statewhereid = 'global'). - Merges local and remote state (local state takes precedence).
- Sets up Supabase Realtime listener for future updates.
- Loads state from
- User loads a page (e.g.,
-
User Interaction:
- User performs an action (e.g., updates hall status).
HallMonitorStoreupdates its in-memory state.HallMonitorStoresyncs to Supabase (viasupabase-client.js).- Supabase broadcasts the change to all connected clients (via Realtime).
- Other clients receive the update and re-render their UIs.
-
UI Rendering:
- Components (e.g.,
admin-dashboard.js) subscribe to state changes. - When state updates, components re-render with the new data.
- Components (e.g.,
1.3.2 Authentication Flow
-
Login:
- User submits credentials to
adminn/login.htmlorsuperadmin-login.html. supabase-client.jsauthenticates via Supabase Auth.- On success, a session token is stored in
localStorage. - User is redirected to the appropriate dashboard (
admin-dashboard.htmlorsuperadmin-dashboard.html).
- User submits credentials to
-
Session Validation:
- Dashboards check
store.getAdminSession()to verify the user’s role. - If invalid, the user is redirected to the login page.
- Dashboards check
1.3.3 Data Synchronization
- Supabase Realtime:
- The
HallMonitorStorelistens for changes topublic.hallmonitor_statevia:supabase .channel('hallmonitor_state_changes') .on('postgres_changes', { event: '*', schema: 'public', table: 'hallmonitor_state' }, (payload) => { store.hydrateFromSupabase(); // Re-fetch state }) .subscribe();
- The
- Manual Sync:
- Components can manually trigger syncs (e.g., after a hall update):
store.updateHall(hallId, { status: 'occupied' });
- Components can manually trigger syncs (e.g., after a hall update):
1.4 Advanced Considerations
1.4.1 State Normalization (Future-Proofing)
- Current State: The entire app state is stored as a single JSON blob in
public.hallmonitor_state(rowid = 'global'). - Future Improvement:
- Split into normalized tables (e.g.,
halls,admins,universities,activity_log). - Use Supabase’s Postgres relationships (e.g.,
halls.university_id→universities.id). - Benefits:
- Reduces payload size.
- Enables granular RLS policies.
- Improves query performance.
- Split into normalized tables (e.g.,
1.4.2 Conflict Resolution
- Current Approach: Local state overwrites remote state on hydration.
- Potential Issue: If two users edit the same hall simultaneously, the last sync wins.
- Improvement:
- Implement optimistic locking (e.g., versioning in
hallmonitor_state). - Use Supabase’s
ON CONFLICTto handle race conditions.
- Implement optimistic locking (e.g., versioning in
1.4.3 Performance Optimizations
- Debounced Syncs:
- Throttle
HallMonitorStore.syncToSupabase()to avoid excessive writes.
- Throttle
- Selective Re-renders:
- Components should only re-render when relevant state changes (e.g., a hall’s status, not the entire state).
- Lazy Loading:
- Load non-critical JS (e.g.,
student.js) only when needed.
- Load non-critical JS (e.g.,
1.4.4 Security
- Current RLS Policies (Temporary):
supabase/schema.sqlincludes open policies (e.g.,CREATE POLICY "Allow all reads" ON public.hallmonitor_state FOR SELECT USING (true);).
- Production Recommendations:
- Restrict reads/writes by
admin_role:CREATE POLICY "Allow admins to read their university's halls" ON public.halls FOR SELECT USING (exists ( select 1 from public.admins where admins.id = auth.uid() and admins.uni_id = halls.university_id )); - Use JWT validation on the client to prevent tampering.
- Restrict reads/writes by
2. Data Flow & State Transitions
| Origin | Action | Logic Handler | Resulting State |
|---|---|---|---|
| User loads page | Initialize HallMonitorStore | store.ensureState() | Local state loaded from localStorage; remote state fetched from Supabase. |
| Supabase Realtime event | Database change detected | store.hydrateFromSupabase() | Local state updated to match Supabase; UI re-renders. |
| User logs in | Authenticate via Supabase | supabase.auth.signInWithPassword() | Session token stored; user redirected to dashboard. |
| User updates hall status | store.updateHall(hallId, newStatus) | HallMonitorStore updates in-memory state | Local state updated; sync triggered to Supabase. |
| Supabase sync completes | Remote write succeeds | Supabase Realtime broadcasts change | All clients receive update; their UIs re-render. |
| User filters dashboard | filters.building = "Science" | renderTable(halls) | UI displays only halls in the "Science" building. |
| Session expires | store.getAdminSession() returns null | Dashboard redirects to login.html | User is logged out; session token cleared. |
| Hall becomes overdue | sessionState = "overdue" | store.updateHall(hallId, { sessionState }) | Hall appears in "sessionAlerts"; admins are notified. |
3. Mermaid.js Architecture Diagram
Diagram Explanation:
-
Frontend Layer:
- Static HTML/JS files (
index.html,admin-dashboard.html) interact with theHallMonitorStore(data-store.js). - Login pages (
adminn/login.html) handle authentication viaadmin-login.js/superadmin-login.js.
- Static HTML/JS files (
-
State Management:
HallMonitorStoresynchronizes between local state (localStorage) and remote state (Supabase).supabase-client.jshandles all Supabase interactions (Auth, Realtime, Database).
-
Supabase Backend:
- Auth: Manages user roles (admin/superadmin).
- Database: Stores the app state in
public.hallmonitor_state. - RLS Policies: Enforce security rules (e.g., only admins can edit their university’s halls).
- Realtime: Broadcasts state changes to all connected clients.
4. Summary of Key Takeaways
| Aspect | Implementation | Best Practices Followed |
|---|---|---|
| State Management | Singleton HallMonitorStore with Supabase sync | Single source of truth, reactive updates |
| Authentication | Supabase Auth + client-side role checks | Role-based access control (RBAC) |
| Real-time Sync | Supabase Realtime for collaborative editing | Event-driven architecture |
| UI Rendering | Template method pattern for reusable components | DRY code, modular components |
| Security | Temporary open RLS policies (to be tightened) | Principle of least privilege |
| Future Improvements | State normalization, conflict resolution, performance optimizations | Scalability, robustness |
| This architecture is well-suited for a medium-sized hall monitoring system but would benefit from further normalization and security hardening before production deployment. The use of Supabase simplifies backend requirements, while the client-side state management pattern reduces server load. |
📈 System Architecture Diagram
🛠️ 4. Function Breakdowns
assets/js/admin-dashboard.js
| Function/Export Name | Parameters | Logic Description | Impact |
|---|---|---|---|
updateClock | None | Updates the clock display with the current time | Updates the UI to reflect the current time |
toTextDate | value | Converts a date to a short date string | Used to format dates for display |
toLocalDateParts | iso | Converts an ISO date string to local date and time parts | Used to format dates for display |
combineDateAndTime | dateText, timeText | Combines date and time strings into a single ISO date string | Used to create a date object from user input |
getDurationHours | hall | Calculates the duration hours for a hall | Used to calculate the expected end time for a hall session |
syncExpectedEndPreview | None | Updates the expected end time preview based on user input | Updates the UI to reflect the expected end time |
getUniversity | state | Retrieves the university object from the state | Used to retrieve university information |
getCoordinator | state | Retrieves the coordinator object from the state | Used to retrieve coordinator information |
getUniversityHalls | state | Retrieves the list of halls for a university | Used to retrieve hall information |
isHallOwnedBySession | hall | Checks if a hall is owned by the current session | Used to determine if a hall can be extended or released |
isHallLockedByOther | hall | Checks if a hall is locked by another user | Used to determine if a hall can be overridden |
isStaleHall | hall | Checks if a hall is stale (overdue or unconfirmed) | Used to determine if a hall needs attention |
canExtendHall | hall | Checks if a hall can be extended | Used to determine if a hall can be extended |
canReleaseHall | hall | Checks if a hall can be released | Used to determine if a hall can be released |
canOverrideHall | hall | Checks if a hall can be overridden | Used to determine if a hall can be overridden |
formatStatusBadge | status | Formats a status string into a badge | Used to format status strings for display |
formatSessionWindow | hall | Formats a session window string | Used to format session window strings for display |
sessionMessage | hall | Retrieves a message for a hall session | Used to display a message for a hall session |
inferActivityRole | entry | Infers the role of an activity entry | Used to determine the role of an activity entry |
renderBuildingFilter | halls | Renders the building filter options | Updates the UI to reflect the available buildings |
matchesQuery | hall, query | Checks if a hall matches a query string | Used to filter halls based on a query string |
renderStats | halls | Renders the statistics for a list of halls | Updates the UI to reflect the statistics |
renderSessionAlerts | halls | Renders the session alerts for a list of halls | Updates the UI to reflect the session alerts |
renderTable | halls | Renders the table for a list of halls | Updates the UI to reflect the list of halls |
SUPABASE_SETUP.md
| Function/Export Name | Parameters | Logic Description | Impact |
|---|---|---|---|
| Setup Supabase Connection | None | Sets up the Supabase connection | Enables the application to connect to Supabase |
| Create State Table | None | Creates the state table in Supabase | Enables the application to store state data in Supabase |
| Refresh App | None | Refreshes the application | Updates the application state and UI |
| Note: The functions and exports listed above are based on the provided code snippet and may not be exhaustive. Additional functions and exports may be present in the complete codebase. |
The code is well-structured and follows good practices. However, there are a few areas that can be improved:
- Function length: Some functions, such as
renderTable, are quite long and perform multiple tasks. Consider breaking them down into smaller, more focused functions. - Variable naming: Some variable names, such as
hallsandhall, are not very descriptive. Consider using more descriptive names to improve code readability. - Commenting: While the code has some comments, more comments can be added to explain the logic and purpose of each function.
- Error handling: The code does not seem to have explicit error handling. Consider adding try-catch blocks and error handling mechanisms to make the code more robust.
- Code organization: The code seems to be a mix of UI logic, business logic, and data access logic. Consider organizing the code into separate modules or files based on their responsibilities.
Overall, the code is well-structured, and with some improvements, it can be even more maintainable and efficient.