CoreLink-tech/HallMonitor

HallMonitor Documentation

Generated May 15, 2026View repository ↗

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:

CategoryTechnologyPurpose
DatabaseSupabaseStores and manages the state of the application
Front-end FrameworkCustom JavaScript implementationHandles user interactions and updates the UI
State ManagementCustom store and state management systemManages the application's state and data
StylingCustom CSS implementationHandles the visual styling and layout of the application
UtilitiesVarious JavaScript libraries and utilitiesProvides 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

CategorySub-folderKey Responsibility
Authenticationadmin/adminnHandles login functionality for admin and superadmin
UI ComponentsadminContains HTML files for admin and superadmin dashboards and login pages
UI Componentsassets/cssHolds CSS stylesheets for various interfaces (admin, student, superadmin)
UI Componentsassets/jsContains JavaScript files for handling UI interactions and data storage
API/Servicesassets/jsUtilizes Supabase client and config for database interactions
Database ModelssupabaseDefines the database schema using SQL
DocumentationrootProvides setup instructions for Supabase
State Managementassets/jsManages 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.sql file 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 the supabase-client.js and supabase-config.js files, and update the UI accordingly.
  • 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.

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:

  1. Separate Concerns: Refactor JavaScript files to have single, well-defined responsibilities, reducing duplication and improving modularity.
  2. Consistent Naming Conventions: Establish a consistent naming convention throughout the codebase to enhance readability and maintainability.
  3. 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:

LayerResponsibilityKey Components
Frontend (UI Layer)Rendering UI, handling user interactions, and managing local stateHTML/CSS/JS files (index.html, admin-dashboard.js, student.js, etc.)
State ManagementCentralized state storage, synchronization with Supabase, and reactivityassets/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.js exports a single HallMonitorStore instance 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).
  • 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.
  • Why?
    • Enables collaborative editing (e.g., multiple admins viewing the same dashboard).
    • Reduces polling overhead (vs. traditional setInterval fetches).

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.adminRole to redirect users (e.g., admin-dashboard.js redirects non-admins to login.html).
    • Database Policies: supabase/schema.sql defines Row-Level Security (RLS) policies (e.g., only superadmin can modify certain rows).
  • 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:
      1. Initialize (fetch state, set up event listeners).
      2. Render (populate DOM with state data).
      3. Update (re-render when state changes).
    • Shared logic (e.g., formatStatusBadge, toTextDate) is reused across components.
  • Why?
    • Promotes DRY (Don’t Repeat Yourself) code.
    • Makes components easier to maintain.

1.2.5 Observer Pattern (State Changes)

  • Pattern: Observer
  • Implementation:
    • The HallMonitorStore notifies subscribers when state changes (e.g., via store.subscribe()).
    • UI components register callbacks to re-render when relevant state updates.
  • Why?
    • Enables reactive UI updates without manual DOM manipulation.
    • Decouples state management from UI rendering.

1.3 Module Interactions

1.3.1 State Flow

  1. Initialization:

    • User loads a page (e.g., admin-dashboard.html).
    • assets/js/data-store.js initializes HallMonitorStore.
    • HallMonitorStore.ensureState():
      • Loads state from localStorage (if available).
      • Fetches state from Supabase (public.hallmonitor_state where id = 'global').
      • Merges local and remote state (local state takes precedence).
      • Sets up Supabase Realtime listener for future updates.
  2. User Interaction:

    • User performs an action (e.g., updates hall status).
    • HallMonitorStore updates its in-memory state.
    • HallMonitorStore syncs to Supabase (via supabase-client.js).
    • Supabase broadcasts the change to all connected clients (via Realtime).
    • Other clients receive the update and re-render their UIs.
  3. UI Rendering:

    • Components (e.g., admin-dashboard.js) subscribe to state changes.
    • When state updates, components re-render with the new data.

1.3.2 Authentication Flow

  1. Login:

    • User submits credentials to adminn/login.html or superadmin-login.html.
    • supabase-client.js authenticates via Supabase Auth.
    • On success, a session token is stored in localStorage.
    • User is redirected to the appropriate dashboard (admin-dashboard.html or superadmin-dashboard.html).
  2. Session Validation:

    • Dashboards check store.getAdminSession() to verify the user’s role.
    • If invalid, the user is redirected to the login page.

1.3.3 Data Synchronization

  • Supabase Realtime:
    • The HallMonitorStore listens for changes to public.hallmonitor_state via:
      supabase
        .channel('hallmonitor_state_changes')
        .on('postgres_changes', { event: '*', schema: 'public', table: 'hallmonitor_state' }, (payload) => {
          store.hydrateFromSupabase(); // Re-fetch state
        })
        .subscribe();
      
  • Manual Sync:
    • Components can manually trigger syncs (e.g., after a hall update):
      store.updateHall(hallId, { status: 'occupied' });
      

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 (row id = '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.

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 CONFLICT to handle race conditions.

1.4.3 Performance Optimizations

  • Debounced Syncs:
    • Throttle HallMonitorStore.syncToSupabase() to avoid excessive writes.
  • 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.

1.4.4 Security

  • Current RLS Policies (Temporary):
    • supabase/schema.sql includes 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.

2. Data Flow & State Transitions

OriginActionLogic HandlerResulting State
User loads pageInitialize HallMonitorStorestore.ensureState()Local state loaded from localStorage; remote state fetched from Supabase.
Supabase Realtime eventDatabase change detectedstore.hydrateFromSupabase()Local state updated to match Supabase; UI re-renders.
User logs inAuthenticate via Supabasesupabase.auth.signInWithPassword()Session token stored; user redirected to dashboard.
User updates hall statusstore.updateHall(hallId, newStatus)HallMonitorStore updates in-memory stateLocal state updated; sync triggered to Supabase.
Supabase sync completesRemote write succeedsSupabase Realtime broadcasts changeAll clients receive update; their UIs re-render.
User filters dashboardfilters.building = "Science"renderTable(halls)UI displays only halls in the "Science" building.
Session expiresstore.getAdminSession() returns nullDashboard redirects to login.htmlUser is logged out; session token cleared.
Hall becomes overduesessionState = "overdue"store.updateHall(hallId, { sessionState })Hall appears in "sessionAlerts"; admins are notified.

3. Mermaid.js Architecture Diagram

Diagram Explanation:

  1. Frontend Layer:

    • Static HTML/JS files (index.html, admin-dashboard.html) interact with the HallMonitorStore (data-store.js).
    • Login pages (adminn/login.html) handle authentication via admin-login.js/superadmin-login.js.
  2. State Management:

    • HallMonitorStore synchronizes between local state (localStorage) and remote state (Supabase).
    • supabase-client.js handles all Supabase interactions (Auth, Realtime, Database).
  3. 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

AspectImplementationBest Practices Followed
State ManagementSingleton HallMonitorStore with Supabase syncSingle source of truth, reactive updates
AuthenticationSupabase Auth + client-side role checksRole-based access control (RBAC)
Real-time SyncSupabase Realtime for collaborative editingEvent-driven architecture
UI RenderingTemplate method pattern for reusable componentsDRY code, modular components
SecurityTemporary open RLS policies (to be tightened)Principle of least privilege
Future ImprovementsState normalization, conflict resolution, performance optimizationsScalability, 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

Rendering diagram…

🛠️ 4. Function Breakdowns

assets/js/admin-dashboard.js

Function/Export NameParametersLogic DescriptionImpact
updateClockNoneUpdates the clock display with the current timeUpdates the UI to reflect the current time
toTextDatevalueConverts a date to a short date stringUsed to format dates for display
toLocalDatePartsisoConverts an ISO date string to local date and time partsUsed to format dates for display
combineDateAndTimedateText, timeTextCombines date and time strings into a single ISO date stringUsed to create a date object from user input
getDurationHourshallCalculates the duration hours for a hallUsed to calculate the expected end time for a hall session
syncExpectedEndPreviewNoneUpdates the expected end time preview based on user inputUpdates the UI to reflect the expected end time
getUniversitystateRetrieves the university object from the stateUsed to retrieve university information
getCoordinatorstateRetrieves the coordinator object from the stateUsed to retrieve coordinator information
getUniversityHallsstateRetrieves the list of halls for a universityUsed to retrieve hall information
isHallOwnedBySessionhallChecks if a hall is owned by the current sessionUsed to determine if a hall can be extended or released
isHallLockedByOtherhallChecks if a hall is locked by another userUsed to determine if a hall can be overridden
isStaleHallhallChecks if a hall is stale (overdue or unconfirmed)Used to determine if a hall needs attention
canExtendHallhallChecks if a hall can be extendedUsed to determine if a hall can be extended
canReleaseHallhallChecks if a hall can be releasedUsed to determine if a hall can be released
canOverrideHallhallChecks if a hall can be overriddenUsed to determine if a hall can be overridden
formatStatusBadgestatusFormats a status string into a badgeUsed to format status strings for display
formatSessionWindowhallFormats a session window stringUsed to format session window strings for display
sessionMessagehallRetrieves a message for a hall sessionUsed to display a message for a hall session
inferActivityRoleentryInfers the role of an activity entryUsed to determine the role of an activity entry
renderBuildingFilterhallsRenders the building filter optionsUpdates the UI to reflect the available buildings
matchesQueryhall, queryChecks if a hall matches a query stringUsed to filter halls based on a query string
renderStatshallsRenders the statistics for a list of hallsUpdates the UI to reflect the statistics
renderSessionAlertshallsRenders the session alerts for a list of hallsUpdates the UI to reflect the session alerts
renderTablehallsRenders the table for a list of hallsUpdates the UI to reflect the list of halls

SUPABASE_SETUP.md

Function/Export NameParametersLogic DescriptionImpact
Setup Supabase ConnectionNoneSets up the Supabase connectionEnables the application to connect to Supabase
Create State TableNoneCreates the state table in SupabaseEnables the application to store state data in Supabase
Refresh AppNoneRefreshes the applicationUpdates 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:

  1. Function length: Some functions, such as renderTable, are quite long and perform multiple tasks. Consider breaking them down into smaller, more focused functions.
  2. Variable naming: Some variable names, such as halls and hall, are not very descriptive. Consider using more descriptive names to improve code readability.
  3. Commenting: While the code has some comments, more comments can be added to explain the logic and purpose of each function.
  4. 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.
  5. 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.