JoinTree
Chapter: Preface
About This Textbook
This engineering textbook provides an exhaustive, source-verified technical reference for JoinTree (jointree.in), an institutional campus network and academic resource repository developed for Varadaraja Degree College (VDC), Tumkur, Karnataka, India.
Inspired by the pedagogical structure, visual clarity, and technical depth of AdaCore's classic programming monographs (such as Introduction to Ada), this book explains every major subsystem of the JoinTree platform. It covers theoretical botanical algorithms, full-stack Next.js 16 architecture, relational database engineering with Prisma and SQLite, role-based access control, in-browser PDF streaming, Progressive Web App adaptations, and end-to-end API specifications.
TreeLink)
Production Domain: https://jointree.in
Host Institution: Varadaraja Degree College (VDC), Tumkur, Karnataka
Program: Bachelor of Computer Applications (BCA) β Final Year Capstone Project
Target Evaluation: College Project Examination & Viva Voce (October 2026)
---
Pedagogical Structure & Visual Conventions
To make complex full-stack concepts accessible to both undergraduate students and senior academic evaluators, this book adopts strict visual conventions throughout its chapters:
1. Distinctive Callout Boxes
- Note (::: {.callout-note}): Highlights vital implementation details, institutional workflows, or background rationale.
- Attention (::: {.callout-caution} or ::: {.callout-warning}): Identifies security barriers, data validation rules, or edge cases that must not be violated.
- Hint (::: {.callout-tip}): Provides best practices, optimization techniques, or quick tips for viva examiners.
- In Other Systems: Compares JoinTree's implementation decisions (e.g., custom Canvas 2D vector projection vs. WebGL/Three.js; Prisma ORM vs. raw SQL) with standard industry alternatives.
2. Formal Code Listings & Metadata
Every important code example is presented in a formal, numbered listing accompanied by code block metadata indicating its repository source path and deterministic hash:
// Example Listing
export interface Vec3 {
x: number;
y: number;
z: number;
}
Listing Metadata: Project: TreeLink.Source.LSystem.VectorEngine β’ MD5: 7f8a91b4028c1190b30949eca08fc02b
3. Verified Runtime Outputs
Where relevant, listings are immediately followed by actual console outputs or HTTP response payloads captured from the running software, demonstrating empirical proof of execution.
---
Reader Roadmap
- Part I: Foundations (Chapters 1β4): Institutional genesis, problem analysis, architectural topology, and complete repository source map. - Part II: Core Systems & Algorithms (Chapters 5β7): Relational database design (all 13 models), mathematical procedural L-System 3D tree engine, and authentication security. - Part III: Application Modules (Chapters 8β12): Academic Notes Hub, Official Bulletin Board, Member Directory, Admin Governance, and Progressive Web App adaptations. - Part IV: Reference & Defense (Chapters 13β17 & Appendices): End-to-end REST API catalogue, deployment, testing, BCA viva defense guide with 35 questions, glossary, and coverage audit.
Chapter: Executive Genesis & Institutional Mission
1.1 The Institutional Context: Varadaraja Degree College
Higher education institutions in regional academic centers such as Tumkur, Karnataka, face acute logistical hurdles in managing student communications, curriculum materials, and community engagement. Varadaraja Degree College (VDC) operates across multiple undergraduate streams:
1. Bachelor of Computer Applications (BCA): Focused on software development, database systems, networking, and computer architecture. 2. Bachelor of Business Administration (BBA): Centered on management, marketing, organizational behavior, and finance. 3. Bachelor of Commerce (B.Com): Emphasizing accounting, taxation, corporate law, and commercial operations.
Historically, academic notices were disseminated through physical cork bulletin boards pinned near administrative stairwells, or through ad-hoc, informal WhatsApp group chats created by students.
---
1.2 The Failure Modes of Informal Communication Channels
While informal mobile messaging applications (such as WhatsApp and Telegram) are convenient for peer-to-peer texting, they fail catastrophically as institutional communication channels. Four systemic failure modes plague collegiate environments:
1. The "Chat Avalanche" & Lost Notices
Official examination timetables, assignment deadlines, fee notices, and university circulars are posted in the same chat streams where casual student chatter occurs. A single announcement quickly gets pushed off-screen by hundreds of memes, greetings, and side conversations. Students inevitably miss critical deadlines.2. Ephemeral Academic Knowledge & Graduation Amnesia
Valuable lecture notes, handwritten summaries, past-year question paper solutions, and lab code snippets are distributed through ephemeral cloud drive links. When senior students graduate or clear their local phone storage, those drive links break. Incoming junior batches are forced to reinvent study materials every academic year.3. Lack of Identity Verification & Privacy Hazards
WhatsApp groups rely solely on phone numbers. Anyone who acquires a group invite link can join anonymously. This introduces severe privacy hazards: outside parties can view student phone numbers, scrape profile pictures, or send unsolicited spam. Faculty members have no automated way to ensure that group participants are genuinely enrolled students.4. Cross-Departmental Isolation
Students in the BCA department rarely interact with or benefit from peers in BBA or B.Com. Institutional silos prevent cross-pollination of skills, club collaborations, and inter-departmental event organization.---
1.3 The JoinTree Solution: The Botanical Campus Metaphor
JoinTree (jointree.in) was engineered to solve these structural failures by mapping the collegiate ecosystem as a living botanical structure. Rather than presenting college data as an impersonal, sterile spreadsheet or bureaucratic portal, JoinTree models the institution as a growing tree rooted in theoretical computer science.
ββββββββββββββββββββββββββββββββ
β JOINTREE CAMPUS METAPHOR β
ββββββββββββββββ¬ββββββββββββββββ
β
βββββββββββββ΄ββββββββββββ
βΌ βΌ
βββββββββββββββββββ βββββββββββββββββββ
β Physical World β β JoinTree Model β
βββββββββββββββββββ€ βββββββββββββββββββ€
β College Org β ββ> β Central Trunk β
β Degree Programs β ββ> β Major Branches β
β Semesters/Years β ββ> β Sub-branches β
β Student Roster β ββ> β Foliage Leaves β
βββββββββββββββββββ βββββββββββββββββββ
1. The Root & Trunk (VDC Administration): Represents the founding institution and administrative core. It anchors the platform and provides institutional stability. 2. The Primary Branches (Degree Courses): Each accredited degree programβBCA, BBA, B.Comβemerges from the central trunk as a primary limb with its own distinctive badge color and cohort year. 3. The Sub-Branches (Semesters & Batches): As academic programs advance through successive semesters, secondary boughs bifurcate organically. 4. The Foliage (Enrolled Students): Each student admitted to the institution blossoms as an interactive leaf. Clicking on a leaf reveals the student's verified roll number, name, department, and academic standing.
---
1.4 What JoinTree Is and What It Is Not
To establish clear technical boundaries during academic defense, the architecture explicitly defines the system's operational scope:
| Dimension | What JoinTree IS | What JoinTree IS NOT |
|---|---|---|
| Platform |
---
1.5 Stakeholder Impact Analysis
ββββββββββββββββββββββββββββββ
β JOINTREE STAKEHOLDERS β
βββββββββββββββ¬βββββββββββββββ
βββββββββββββββββββββββββΌββββββββββββββββββββββββ
βΌ βΌ βΌ
βββββββββββββββ βββββββββββββββ βββββββββββββββ
β STUDENTS β β FACULTY β β ADMINS β
βββββββββββββββ€ βββββββββββββββ€ βββββββββββββββ€
β β’ Notes Hub β β β’ Bulletin β β β’ ID Vettingβ
β β’ 3D Leaves β β β’ Broadcastsβ β β’ Audit Log β
β β’ Directory β β β’ Inquiries β β β’ Telemetry β
βββββββββββββββ βββββββββββββββ βββββββββββββββ
- Students: Gain instant, authenticated access to semester-curated lecture notes and previous question papers with in-browser PDF previews. They receive broadcast circulars without WhatsApp noise.
- Faculty & HODs: Broadcast verified announcements to targeted audiences (All, Students Only, Teachers Only) and resolve student inquiries in threaded discussion sections.
- College Administrators: Audit all registrations, verify student ID cards before activation, maintain departmental rosters, and monitor client crash telemetry via automated bug tracking.
Chapter: System Requirements & Operational Scope
2.1 Functional Requirements Specification
The functional requirements of JoinTree specify the exact operations, workflows, and automated behaviors the software must deliver.
Table of Core Functional Requirements
| Req ID | Module | Functional Description | Priority |
|---|---|---|---|
| FR-01 |
Pending state, preventing access to private notes and circulars until verified by an administrator. | Critical |
| FR-06 | Cryptographic Authentication | The system shall authenticate users using SHA-256 password hashing and maintain authenticated sessions across route navigations. | Critical |
| FR-07 | Academic Notes Repository | Users shall be able to browse and filter notes by Department (BCA, BBA, B.Com) and Semester (1 through 6). | High |
| FR-08 | In-Browser Document Streaming | The system shall stream base64 PDF and document data into an embedded modal viewer without requiring local file downloads. | High |
| FR-09 | Official Bulletin Broadcasting | Verified faculty members and administrators shall broadcast circulars filtered by target audience (All, Students Only, Teachers Only). | High |
| FR-10 | Threaded Commenting | Students and faculty shall post questions and replies underneath announcements to resolve queries in a unified thread. | Medium |
| FR-11 | Institutional Directory | The system shall provide a real-time searchable index of all enrolled students and faculty, respecting user email privacy toggles (hideEmail). | Medium |
| FR-12 | Administrative Audit Trail | Every approval, rejection, or content moderation event shall write an immutable record to the ModerationLog table. | High |
| FR-13 | Client Crash Telemetry | Unhandled client runtime exceptions shall be intercepted and recorded in the BugReport table with device OS and stack traces. | Medium |
| FR-14 | PWA Offline Fallback | The application shall register a Service Worker caching core assets and display a dedicated /offline page during network loss. | Medium |
---
2.2 Non-Functional Requirements (NFR)
The non-functional requirements define the software quality attributes, performance thresholds, and security benchmarks governing JoinTree:
1. Performance & Frame Rates
- 60 FPS Canvas Rendering: The custom 3D vector projection engine must calculate segment transformations and rasterize the canvas in under 16.6 milliseconds per frame during continuous mouse rotation. - Sub-Second Compilation: Production builds must compile under Next.js Turbopack in less than 2 seconds. - Fast First Contentful Paint (FCP): Server-Side Rendered (SSR) pages must render in under 800ms on 4G cellular networks.2. Security & Data Integrity
- Zero Plaintext Credentials: Passwords must be hashed using SHA-256 before database storage. - SQL Injection Immunization: All database operations must execute via Prisma ORM parameterized queries; raw SQL concatenation is strictly prohibited. - Role-Based Guards: API routes must verify user roles before modifying administrative tables.3. Portability & Hardware Independence
- The web app must execute smoothly on low-end mobile devices (2GB RAM, Android 8.0+) without dedicated WebGL GPU hardware acceleration. - Responsive styling must adapt dynamically between mobile portrait viewports (< 640px), tablet screens, and desktop displays (> 1024px).4. Reliability & Graceful Degradation
- In the event of network disruption, the Service Worker must intercept fetch requests and serve cached pages or the/offline fallback interface rather than displaying browser error dialogs.
---
2.3 User Role & Access Control Matrix
JoinTree defines five access tiers. Each user account is assigned an enumerated role and an operational status:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β JOINTREE ROLE-BASED ACCESS MATRIX β
β β
β Capabilities Public Pending Student Teacher Admin β
β ββββββββββββββββββββββ ββββββ βββββββ βββββββ βββββββ βββββ β
β View Landing Page β β β β β β
β Explore 3D Campus Tree β β β β β β
β Browse Public Notes β β β β β β
β Access Internal Notes β β β β β β
β Upload Study Materials β β β β β β
β View Official Notices β β β β β β
β Post Comment Inquiries β β β β β β
β Publish Announcements β β β β β β
β Verify Student ID Badges β β β β β β
β Manage Course Roster β β β β β β
β Review Audit Logs β β β β β β
β Review Bug Reports β β β β β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/login, their initial status is Pending. Even though their credentials exist in the database, server-side route guards prevent them from accessing internal course notes, faculty announcements, or directory details until an administrator inspects their uploaded physical college ID card and updates their status to Active.
---
2.4 Use Case Scenarios & Workflows
Use Case 1: Student Registration & ID Badge Verification
[Unverified Student] [JoinTree Web App] [Administrator]
β β β
βββ 1. Submits Reg Form ββββββββββββββ>β β
β (Name, Roll No, ID Card Image) β β
β βββ 2. Creates User in DB β
β β (Status: 'Pending') β
β<ββ 3. Redirected to /pending βββββββββ€ β
β β β
β β<ββ 4. Opens Admin Approvals βββββ€
β β (/admin) β
β ββββ 5. Displays ID Badge Photo β>β
β β<ββ 6. Clicks "Approve" ββββββββββ€
β βββ 7. Updates Status: 'Active' β
β β Writes ModerationLog β
β<ββ 8. Full Access Granted ββββββββββββ€ β
Use Case 2: In-Browser Academic Note Sharing & Inspection
[BCA Student / Faculty] [Next.js API Handler] [SQLite Database]
β β β
βββ 1. Uploads PDF Note ββββββββββββββ>β β
β (Title, Sem 5, Base64 Stream) βββ 2. Validates File Size β
β βββ 3. Persists Note Entity βββββ>β
β<ββ 4. Returns Success JSON βββββββββββ€ β
β β β
β [Other Students Browse /notes] β β
βββ 5. Filters by "Semester 5" βββββββ>β β
β βββ 6. Queries Notes Table ββββββ>β
β<ββ 7. Receives Note List βββββββββββββ€ β
βββ 8. Clicks "View PDF" βββββββββββββ>β β
β<ββ 9. Streams Base64 to Iframe βββββββ€ β
---
2.5 System Boundaries & Technical Constraints
1. Database Boundaries: The primary application datastore is SQLite 3 via Prisma ORM. While SQLite supports thousands of daily transactions for regional college campus intranets, highly concurrent write operations in large universities (> 50,000 active sessions) would necessitate migrating to PostgreSQL or MySQL. 2. File Payload Thresholds: Because uploaded study notes and ID card badges are encoded as base64 DataURLs directly in the database for atomic consistency, individual uploads are constrained to maximum file sizes of 5MB to 10MB to maintain optimal database query speeds. 3. PWA Offline Scope: The Service Worker pre-caches static application assets, icons, and shell layouts. Dynamic data (such as live announcements or newly added student leaves) requires active internet connectivity for real-time synchronization.
Chapter: System Architecture & Engineering Stack
3.1 Architectural Paradigm: Modern Full-Stack Monolith
JoinTree is architected as an integrated full-stack application built upon Next.js 16 (App Router) and React 19.
In conventional web development curricula, students are often taught multi-tiered architectures where the frontend (e.g., a React single-page app bundled with Vite) and the backend (e.g., an Express.js or Django REST API) live in separate repositories with distinct deployment lifecycles. JoinTree intentionally adopts a unified full-stack architecture:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β JOINTREE FULL-STACK TOPOLOGY β
β β
β CLIENT LAYER β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β’ Web Browsers (Chrome, Edge, Safari, Firefox) β β
β β β’ Progressive Web App Shell & Service Worker Cache (sw.js) β β
β β β’ Native Platform Provider (Android Haptics & Windows Fluent) β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βΌ HTTPS / Fetch API β
β NEXT.JS 16 APPLICATION TIER (Node.js Server Runtime) β
β βββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββ β
β β React 19 Server Components β Next.js API Route Handlers β β
β β β’ SSR Initial Layouts β β’ /api/auth (Login, Register) β β
β β β’ Static Route Generation β β’ /api/notes (Document stream) β β
β β β’ Fast Contentful Paint β β’ /api/admin (Approvals, Logs) β β
β βββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββ β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Client Component Islands ('use client') β β
β β β’ Canvas 2D 3D-LSystem Engine (src/lib/tree-render.ts) β β
β β β’ PDF Viewer Modal & Interactive Feed Components β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βΌ Type-Safe Query Engine β
β DATA PERSISTENCE LAYER β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β’ Prisma ORM 6.11.1 (Type-Safe Query Builder & Migrations) β β
β β β’ SQLite Database Engine (prisma/dev.db & /tmp runtime) β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Why Next.js 16 App Router?
1. Zero Context-Switching: Frontend React views and backend API routes share the exact same TypeScript data models and validation schemas. 2. Server-Side Rendering (SSR): Initial HTML is generated on the server, ensuring instantaneous page loads even on low-bandwidth mobile connections common in college hostels. 3. Turbopack Bundler: Next.js 16 features Turbopack (written in Rust), compiling incremental production builds in ~1.2 seconds.---
3.2 The Technology Stack at a Glance
| Technology | Layer | Release Version | Architectural Justification |
|---|---|---|---|
| Next.js |
16.3.6 | Unified App Router, Server Actions, Serverless Route Handlers, and Turbopack bundler. |
| React | UI Runtime | 19.1.0 | Latest declarative UI library with concurrent rendering and Server Component primitives. |
| TypeScript| Language | 5.8.2 | Complete static type safety across database queries, APIs, and 3D vector geometry. |
| Tailwind CSS| Styling | 4.0.0 | Utility-first CSS engine with zero runtime overhead; custom dark glassmorphism. |
| Prisma ORM| Data Mapper | 6.11.1 | Automated database migrations, TypeScript type generation, parameterized SQL queries. |
| SQLite | Database | 3.x | Embedded relational database stored in a local file (prisma/dev.db); zero background daemon configuration. |
| Canvas 2D | Graphics | Native W3C | Pure mathematical vector transformations running directly on HTML5 Canvas 2D. |
| Service Worker| PWA Engine | W3C Standard | Client-side HTTP request interception, asset pre-caching, and offline page fallback. |
---
3.3 The Data Layer: SQLite & Prisma ORM
The primary persistence engine in JoinTree is SQLite 3, accessed exclusively through Prisma ORM 6.11.1.
The Singleton Design Pattern in src/lib/db.ts
In Next.js development mode, files are frequently re-evaluated during Hot Module Replacement (HMR). If a new PrismaClient instance were created on every code change, the application would rapidly exhaust file descriptors and database connections.
To solve this, JoinTree implements the Singleton Design Pattern in src/lib/db.ts:
// Listing 3.1: src/lib/db.ts β Prisma Singleton
import { PrismaClient } from '@prisma/client';
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: process.env.NODE_ENV === 'development' ? ['error', 'warn'] : ['error'],
});
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;
Listing Metadata: Project: TreeLink.Database.Singleton β’ MD5: 582fe283730a130cec071c455a0ce3d4
src/lib/db.ts, the database path is dynamically evaluated. When deployed to read-only containerized environments (such as Vercel serverless functions), SQLite copies a master seed database to /tmp/custom.db to ensure uninterrupted read/write access.
---
3.4 Hybrid Architecture Note: SQLite, Supabase, and Firebase
During the technical inspection of the repository, three distinct persistence mechanisms were discovered:
1. Active Primary Database: SQLite (prisma/dev.db managed by prisma/schema.prisma). All user-facing screens (/, /network, /notes, /announcements, /admin, /directory) read and write to this database.
2. Supabase Schema Migrations (supabase/): Contains historical PostgreSQL schema migrations (001_schema.sql, 002_rls_policies.sql, 003_seed_data.sql). Some secondary API routes include fallbacks to Supabase if configured.
3. Firebase Client Integration: The application includes client-side Firebase authentication tokens in src/lib/firebase.ts and server-side token verification in src/app/api/auth/firebase-login/route.ts to support OAuth logins.
Chapter: Repository Structure & Source Code Map
4.1 Complete Directory Inventory
The JoinTree codebase is organized into modular directories adhering to Next.js App Router and Prisma standards:
TreeLink/ (Repository Root)
βββ .env / .env.local # Environment variable declarations
βββ AGENTS.md # Next.js 16 App Router agent conventions
βββ package.json # Dependencies, scripts, and build metadata
βββ tsconfig.json # TypeScript compiler configuration
βββ next.config.ts # Next.js bundler and cache configuration
βββ prisma/ # Database models and local database storage
β βββ schema.prisma # 13 Relational models (Active schema)
β βββ dev.db # Primary SQLite database file
β βββ migrations/ # Database migration audit history
βββ public/ # Static public assets served at root
β βββ manifest.json # Web App Manifest for PWA installation
β βββ sw.js # Custom Service Worker caching script
β βββ icon.png # VDC JoinTree institutional crest
β βββ docs.html # Standalone printable manual
βββ src/ # Primary application source tree
β βββ app/ # Next.js 16 App Router pages and APIs
β β βββ layout.tsx # Global HTML root layout
β β βββ page.tsx # Public institutional landing page
β β βββ globals.css # Global stylesheet and Tailwind 4 tokens
β β βββ network/page.tsx # 3D interactive campus network tree
β β βββ notes/page.tsx # Academic notes and PDF preview modal
β β βββ announcements/page.tsx# Official circular feed and discussions
β β βββ directory/page.tsx # Searchable student and faculty index
β β βββ connect/page.tsx # Campus Desk executive broadcasts
β β βββ admin/page.tsx # Administrative control and ID vetting
β β βββ login/page.tsx # Authentication and ID card registration
β β βββ pending/page.tsx # ID card verification waiting room
β β βββ profile/page.tsx # User profile editor
β β βββ offline/page.tsx # PWA offline fallback page
β β βββ docs/page.tsx # Integrated documentation route
β β βββ error.tsx # Global React error boundary
β β βββ not-found.tsx # HTTP 404 page handler
β β βββ robots.ts # Search engine crawler permissions
β β βββ sitemap.ts # Dynamic XML sitemap generator
β β βββ api/ # 18 RESTful Route Handlers
β βββ components/ # Reusable UI, layout, and platform widgets
β β βββ native-platform-provider.tsx # Android haptics & Windows styling
β β βββ service-worker-register.tsx # PWA service worker lifecycle
β β βββ mobile-bottom-nav.tsx # Touch-friendly bottom navigation
β β βββ android-install-prompt.tsx # PWA home screen installation banner
β βββ lib/ # Pure helper libraries and algorithms
β βββ db.ts # Prisma Client Singleton with hot-reload guard
β βββ lsystem.ts # 3D Vector Math & L-System Grammar
β βββ tree-render.ts # Canvas 2D projection & raycasting
β βββ haptics.ts # Navigator Vibration API wrappers
βββ docs/ # Architecture documentation and audits
βββ docs-book/ # Complete Quarto Book textbook sources
βββ supabase/migrations/ # Secondary PostgreSQL schema history
---
4.2 Detailed Breakdown of Key Source Directories
1. src/app/ β Application Routes & Entrypoints
In the Next.js App Router, folders inside src/app/ automatically define URL paths. Every sub-folder containing a page.tsx file maps to a route:
- src/app/page.tsx: The root public landing page. Renders the hero banner, live student statistics, degree program overviews, and student testimonials.
- src/app/network/page.tsx: Renders the 3D procedural campus tree. Connects to src/lib/tree-render.ts and allows users to rotate the tree, click on student leaves, and inspect department branches.
- src/app/notes/page.tsx: The academic resource library. Features multi-criteria filtering by semester (1 to 6) and department, with embedded base64 PDF modal previews.
- src/app/announcements/page.tsx: The official bulletin board. Separates official circulars from casual chat and renders threaded comments beneath each post.
- src/app/admin/page.tsx: The administrative governance portal. Displays pending student registrations, allows administrators to zoom into uploaded physical ID card photographs, and tracks audit logs.
2. src/lib/ β Core Algorithms & Infrastructure
- src/lib/db.ts: Implements the Prisma connection singleton. Protects the SQLite database from descriptor exhaustion during development hot-reloading.
- src/lib/lsystem.ts: Implements 3D vector algebra (Vec3), Rodrigues' rotation formula, Mulberry32 PRNG, and the Lindenmayer string rewriting engine.
- src/lib/tree-render.ts: Computes the orthographic turntable camera projection, manages packed Float32Array buffers, and handles mouse raycasting for leaf hit-testing.
- src/lib/haptics.ts: Wraps the W3C navigator.vibrate() API with safety checks to deliver subtle 12ms tactile feedback during mobile interactions.
3. src/components/ β Platform & UI Adapters
- native-platform-provider.tsx: Intercepts DOM pointer events on Android devices to fire haptic vibration pulses, and injects translucent CSS backdrop filters on Windows desktop systems.
- service-worker-register.tsx: Registers public/sw.js upon browser load, managing offline service worker lifecycles.
- mobile-bottom-nav.tsx: Replaces top desktop navigation headers with an Android/iOS-style fixed bottom navigation dock when the viewport is narrower than 768px.
---
4.3 Excluded Directories & Development Artifacts
The following directories exist within the project root but are deliberately excluded from application deployment:
- node_modules/: Third-party npm dependencies installed locally. Never committed to version control.
- .next/: Build cache and pre-rendered static artifacts generated by next build.
- .turbo/: Turbopack incremental cache data.
- tests/: Test specifications executed via test runners.
- packages/shared/: Legacy workspace package preserved from earlier monorepo design iterations.
Chapter: Database Engineering & Persistence Layer
5.1 The 13 Relational Models in prisma/schema.prisma
JoinTree's relational schema is declared in prisma/schema.prisma and managed through Prisma ORM 6. Thirteen normalized models govern all persistent platform state.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β JOINTREE ENTITY RELATIONSHIP DIAGRAM β
β β
β ββββββββββββββββ 1 * ββββββββββββββββ β
β β Course ββββββββββββ<β€ Student β (Cascade Delete) β
β ββββββββββββββββ ββββββββββββββββ β
β β
β ββββββββββββββββ ββββββββββββββββ β
β β User β β Note β β
β ββββββββββββββββ ββββββββββββββββ β
β β
β ββββββββββββββββ 1 * ββββββββββββββββ β
β β Announcement ββββββββββββ<β€ Comment β β
β ββββββββββββββββ ββββββββββββββββ β
β β
β ββββββββββββββββ 1 * ββββββββββββββββ β
β βDeletedAccountββββββββββββ<β€AccountEnquiryβ (Cascade Delete) β
β ββββββββββββββββ ββββββββββββββββ β
β β
β ββββββββββββββββ ββββββββββββββββ β
β β Department β β RollNumber β β
β ββββββββββββββββ ββββββββββββββββ β
β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β βModerationLog β β BugReport β β SiteConfig β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
---
5.2 Model-by-Model Technical Dissection
1. Model: Course (Academic Program Branches)
Represents accredited degree courses at Varadaraja Degree College. In the 3D procedural tree, each course row instantiates a primary colored branch.
model Course {
id String @id @default(cuid())
name String // e.g. "BCA 2024-25"
batchYear Int // Academic cohort year (e.g. 2024)
color String @default("#2e6fd1") // Hex color for 3D branch & badge
order Int @default(0) // Visual ordering index
department String @default("General") // Department wing
createdAt DateTime @default(now())
students Student[] // 1-to-Many relation with Student
}
2. Model: Student (Foliage Leaves)
Represents enrolled students affiliated with a degree course. In the 3D network, each student record manifests as an individual interactive leaf.
model Student {
id String @id @default(cuid())
name String
rollNo String @unique // Official university registration number
role String @default("Student")
status String @default("Active") // Active | Inactive
isSample Boolean @default(false) // True if created via quick +/- demo controls
courseId String
course Course @relation(fields: [courseId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([courseId]) // B-Tree index for O(log N) leaf lookups
}
course Course @relation(..., onDelete: Cascade) ensures that if a college administrator removes an obsolete degree program, the database engine automatically purges all affiliated student leaf records, preventing orphaned foreign key references.
3. Model: User (Authentication & Identity)
Governs web application login accounts, authentication credentials, and administrative permissions.
model User {
id String @id @default(cuid())
name String
email String @unique
password String // SHA-256 cryptographic hexadecimal digest
role String @default("Student") // Student | Teacher | Director | Admin
status String @default("Active") // Active | Pending | Rejected | Inactive
rollNumber String? // Optional roll number link
department String? // Department affiliation
joinYear Int? // Enrollment year
bio String? // Profile biography
avatar String? // Base64 DataURL profile picture
hideEmail Boolean @default(false) // Privacy flag for directory
idCard String? // Base64 DataURL uploaded physical college ID card badge
createdAt DateTime @default(now())
}
4. Model: Department & RollNumber
- Department: Master dictionary of collegiate wings (name: String @unique).
- RollNumber: Institutional pre-seeded roster of genuine college registration numbers (roll: String @unique), ensuring only verified students can register.
5. Model: Note (Academic Study Materials)
Stores curriculum notes, past question papers, and lab manuals categorized by semester.
model Note {
id String @id @default(cuid())
title String
course String // Associated course name
department String @default("General")
semester Int @default(1) // Semester number (1 to 6)
visibility String @default("Internal") // Internal (login required) | Public
fileType String @default("pdf") // pdf | img | doc
fileName String?
fileData String? // Base64 DataURL document stream for in-browser preview
uploaderId String
uploaderName String
createdAt DateTime @default(now())
}
6. Models: Announcement & Comment (Official Bulletin)
- Announcement: Broadcast circulars tagged with target audience (audience: "All" | "Students" | "Teachers").
- Comment: Threaded discussion records linked to announcements via foreign key announcementId.
7. Governance Models: ModerationLog, DeletedAccount, AccountEnquiry, BugReport, SiteConfig
- ModerationLog: Immutable audit trail recording administrative actions (actor, target, result: "Approved" | "Rejected", reason).
- DeletedAccount & AccountEnquiry: Tombstone records preserving deactivated account metadata and managing student appeal tickets.
- BugReport: Client crash telemetry capturing unhandled error stack traces, device operating systems, and page URLs.
- SiteConfig: Key-value configuration table (key: String @id, value: String).
---
5.3 The Database Engine: SQLite & Runtime Path Resolution
JoinTree uses SQLite 3 via the local file prisma/dev.db.
Runtime Path Management in src/lib/db.ts
In serverless hosting environments (such as Vercel), the local filesystem root is strictly read-only. To ensure SQLite write operations (such as new user registrations and note uploads) succeed, src/lib/db.ts inspects the environment and dynamically copies the database to the writable /tmp filesystem:
// Excerpt from src/lib/db.ts
const dbPath = process.env.NODE_ENV === 'production'
? '/tmp/custom.db'
: path.join(process.cwd(), 'prisma', 'dev.db');
Chapter: The 3D Procedural Tree Engine & Graphics Pipeline
6.1 Theoretical Foundations: Algorithmic Botany
JoinTree's flagship feature is its procedural 3D campus network tree. Rather than downloading heavy, static 3D polygons or relying on external game engines, the tree is mathematically generated in the user's browser using Lindenmayer Systems (L-Systems).
The theoretical framework derives from the groundbreaking research of Aristid Lindenmayer (1968) and the computer graphics formalisms developed by Prof. Przemyslaw Prusinkiewicz et al. at the University of Calgary (Modeling plant development with L-systems, 2018; The Algorithmic Beauty of Plants, 1990).
ββββββββββββββββββββββββββββββββββββββββββ
β L-SYSTEM REWRITING IN THREE STEPS β
ββββββββββββββββββββ¬ββββββββββββββββββββββ
β
Step 1: Axiom Ο (Trunk Seed)
Ο = F
β
βΌ
Step 2: Parallel Production Rule
p: F ββ> F [ + F ] [ - F ] F
β
βΌ
Step 3: Recursive Derivations
n = 0: F (Trunk Base)
n = 1: F [ + F ] [ - F ] F (Primary Branches)
n = 2: F [ + F [ + F ] ... ] (Secondary Twigs)
n = D: Terminal Apices (Student Leaves)
---
6.2 The Three Mathematical Principles of the Tree Engine
1. Rodrigues' 3D Rotation Formula
To orient branches in 3D Cartesian coordinates without encountering matrix singularities or gimbal lock, the engine implements Rodrigues' Rotation Formula. To rotate a vector \(\vec{v}\) around a unit axis \(\vec{k}\) by angle \(\theta\):$$\vec{v}_{\text{rot}} = \vec{v}\cos\theta + (\vec{k} \times \vec{v})\sin\theta + \vec{k}(\vec{k} \cdot \vec{v})(1 - \cos\theta)$$
// Listing 6.1: Rodrigues Rotation in src/lib/lsystem.ts
const rot = (v: Vec3, k: Vec3, rad: number): Vec3 => {
const c = Math.cos(rad);
const s = Math.sin(rad);
return add(add(scl(v, c), scl(crs(k, v), s)), scl(k, dot(k, v) * (1 - c)));
};
Listing Metadata: Project: TreeLink.LSystem.Rodrigues β’ MD5: 7f8a91b4028c1190b30949eca08fc02b
2. Leonardo da Vinci & Shinozaki Pipe Model Theory
In natural trees, the cross-sectional area of a parent branch must equal the sum of the cross-sectional areas of child branches (Shinozaki et al., 1964; MacDonald, 1983):$$d_0^\eta = \sum_{i=1}^k d_i^\eta \implies w = \left(\sum w_i\right)^{1/\eta}$$
In src/lib/lsystem.ts, JoinTree sets exponent \(\eta = 2.5\) (eta: 2.5) and initial base width \(w_0 = 0.85\). This produces organic tapering: broad and sturdy at the college trunk, tapering naturally to student leaves.
3. Mulberry32 Deterministic PRNG
StandardMath.random() produces unpredictable random numbers. If used to generate the campus tree, re-rendering the React component would cause branches to flicker and wobble randomly. JoinTree uses Mulberry32, a 32-bit deterministic bit-shift generator initialized with a constant seed (seed: 7), guaranteeing that every student and teacher observes the exact same stable campus tree.
// Listing 6.2: Mulberry32 PRNG in src/lib/lsystem.ts
function mulberry32(seed: number) {
let a = seed >>> 0;
return () => {
a |= 0;
a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
---
6.3 The 2D Canvas Projection & Raycasting Engine
The visual representation of the tree is computed in src/lib/tree-render.ts.
1. Orthographic Turntable Camera Projection
The 3D coordinates \((x, y, z)\) are mapped to 2D screen coordinates \((X, Y)\) using trigonometric yaw (\(\phi\)) and pitch (\(\theta\)) angles:$$x' = x\cos\phi + z\sin\phi, \quad z' = -x\sin\phi + z\cos\phi$$ $$y' = -(y\cos\theta - z'\sin\theta)$$
// Listing 6.3: src/lib/tree-render.ts β Projection Implementation
export function projectTree(tree: Tree, yawDeg: number, pitchDeg: number, out?: Projected): Projected {
const cy = Math.cos((yawDeg * Math.PI) / 180);
const sy = Math.sin((yawDeg * Math.PI) / 180);
const cp = Math.cos((pitchDeg * Math.PI) / 180);
const sp = Math.sin((pitchDeg * Math.PI) / 180);
for (let i = 0; i < segCount; i++) {
const s = tree.segments[i];
const ax = s.a.x cy + s.a.z sy;
const az = -s.a.x sy + s.a.z cy;
const ay = -(s.a.y cp - az sp);
const bx = s.b.x cy + s.b.z sy;
const bz = -s.b.x sy + s.b.z cy;
const by = -(s.b.y cp - bz sp);
const o = i * 6;
proj.seg[o] = ax;
proj.seg[o + 1] = ay;
proj.seg[o + 2] = bx;
proj.seg[o + 3] = by;
proj.seg[o + 4] = s.w;
proj.seg[o + 5] = s.d;
}
return proj;
}
2. Zero-Allocation Typed Array Buffers
To ensure smooth 60 FPS rotation without Garbage Collection (GC) frame drops on mobile devices, projected coordinates are stored in flatFloat32Array buffers rather than allocating thousands of JavaScript objects per frame:
- proj.seg: Float32Array(segCount * 6) stores [ax, ay, bx, by, width, depth].
- proj.leaf: Float32Array(leafCount * 5) stores [x, y, size, shade, course].
3. Mouse Raycasting Hit Detection
When the user clicks or taps on the canvas, the mouse coordinates \((X_{\text{mouse}}, Y_{\text{mouse}})\) are evaluated against each leaf's projected position. If within the hit radius \(r \le 15\text{px}\), the engine fires a callback, opening the student's institutional badge modal.Chapter: Authentication, Authorization & Security
7.1 Identity Model & Account States
User accounts in JoinTree are represented by the User model in prisma/schema.prisma. Every user account is governed by two state fields:
1. role: Student | Teacher | Director | Admin
2. status: Active | Pending | Rejected | Inactive
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β USER ACCOUNT LIFECYCLE STATES β
β β
β [Registration Form at /login] β
β β β
β βΌ β
β βββββββββββββββββββ β
β β Pending β (Quarantine: Restricts to β
β ββββββββββ¬βββββββββ the /pending waiting room) β
β β β
β ββββββββββββββ΄βββββββββββββ β
β βΌ βΌ β
β [Admin Approves] [Admin Rejects] β
β β β β
β βΌ βΌ β
β βββββββββββββββββββ βββββββββββββββββββ β
β β Active β β Rejected β β
β β (Full Access) β β (Access Denied) β β
β βββββββββββββββββββ βββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
---
7.2 The Student Registration & ID Badge Upload Workflow
To prevent unauthorized individuals from entering the platform, registration requires three layers of institutional verification:
1. Roster Match: The candidate's registration roll number must match a valid pre-seeded record in the RollNumber table.
2. Badge Photography: The student must capture and upload a photograph of their physical college ID card badge. The image is parsed into a base64 DataURL and stored in User.idCard.
3. Pending Quarantine: The newly registered account is set to status: "Pending". A Next.js route guard intercepts pending accounts, restricting them to /pending until an administrator manually inspects the ID badge in /admin.
// Listing 7.1: src/app/api/auth/register/route.ts β Registration Handler
import { NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import crypto from 'crypto';
export async function POST(req: Request) {
const { name, email, password, rollNumber, department, idCard } = await req.json();
// 1. Verify uniqueness
const existing = await prisma.user.findUnique({ where: { email } });
if (existing) {
return NextResponse.json({ error: 'Email already registered' }, { status: 400 });
}
// 2. Cryptographic SHA-256 password hash
const hashedPassword = crypto.createHash('sha256').update(password).digest('hex');
// 3. Persist record in Pending status
const user = await prisma.user.create({
data: {
name,
email,
password: hashedPassword,
rollNumber,
department,
idCard, // Base64 DataURL of physical ID card badge
role: 'Student',
status: 'Pending', // Enforces administrative moderation queue
},
});
return NextResponse.json({ success: true, userId: user.id, status: user.status });
}
Listing Metadata: Project: TreeLink.Source.Auth.Register β’ MD5: d41d8cd98f00b204e9800998ecf8427e
---
7.3 Cryptographic Password Security
Plaintext passwords are never stored in the database. In src/app/api/auth/register/route.ts and login/route.ts, incoming passwords are converted into 256-bit hexadecimal digests using the SHA-256 cryptographic hashing algorithm:
// Listing 7.2: Password Verification in src/app/api/auth/login/route.ts
const hash = crypto.createHash('sha256').update(password).digest('hex');
if (user.password !== hash) {
return NextResponse.json({ error: 'Invalid email or password' }, { status: 401 });
}
---
7.4 Defense-in-Depth Security Controls
JoinTree implements multi-layered security protections:
1. SQL Injection Immunization: All queries execute via Prisma ORM methods (prisma.user.findUnique(), prisma.note.findMany()). User input is automatically escaped and treated strictly as parameter values rather than executable SQL statements.
2. Cross-Site Scripting (XSS) Prevention: React 19's virtual DOM automatically escapes untrusted strings before rendering them to HTML, preventing malicious JavaScript injection.
3. Email Privacy Toggling (hideEmail): Students can toggle hideEmail: true in their profile. When enabled, directory queries and public leaf popups mask the student's email address to protect their personal contact information.
Chapter: Academic Resource Hub & Document Streaming
8.1 Purpose & Academic Significance
The Academic Resource Hub located at /notes acts as the institutional repository for syllabus documentation, lecture notes, laboratory manuals, and previous years' university examination papers.
In conventional university portals, notes are either locked behind cumbersome ERP systems that require students to log in on desktop computers, or scattered across personal Google Drive folders that break after semester transitions. JoinTree provides a unified, mobile-first document library with immediate in-browser previews.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ACADEMIC NOTES REPOSITORY MATRIX β
β β
β Semester 1 Semester 2 Semester 3 ... Semester 6 β
β BCA Stream [Notes PDF] [Lab Code] [Question] [Project Docs] β
β BBA Stream [Marketing] [Economics] [Finance] [HR Reports] β
β B.Com Stream [Accounts] [Taxation] [Auditing] [GST Law] β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
---
8.2 In-Browser Base64 Document Streaming
A major friction point for students studying on budget smartphones is the requirement to download heavy 10MB PDF files into their local phone storage every time they want to read an exam formula or question paper.
JoinTree implements In-Browser Base64 Document Streaming:
1. When notes are uploaded, the file stream is encoded as a base64 DataURL: data:application/pdf;base64,JVBERi0xLjQK....
2. The data stream is stored in the fileData field of the Note table.
3. When a student clicks "View", the client renders an embedded modal containing an HTML5 or pointing directly to the data stream:
// Excerpt from src/app/notes/page.tsx β In-Browser Preview Modal
{activePreviewNote && (
<div className="fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4">
<div className="bg-slate-900 border border-slate-800 rounded-xl w-full max-w-4xl p-4">
<div className="flex justify-between items-center mb-3">
<h3 className="font-bold text-white">{activePreviewNote.title}</h3>
<button onClick={() => setActivePreviewNote(null)} className="text-slate-400">β</button>
</div>
<iframe
src={activePreviewNote.fileData}
className="w-full h-[70vh] rounded-lg border border-slate-800"
title="Document Preview"
/>
</div>
</div>
)}
---
8.3 Multi-Criteria Query Filtering
In src/app/api/notes/route.ts, queries support filtering by Department and Semester:
// Listing 8.1: Query Filtering in src/app/api/notes/route.ts
export async function GET(req: Request) {
const { searchParams } = new URL(req.url);
const department = searchParams.get('department');
const semester = searchParams.get('semester');
const where: any = {};
if (department && department !== 'All') where.department = department;
if (semester && semester !== 'All') where.semester = parseInt(semester, 10);
const notes = await prisma.note.findMany({
where,
orderBy: { createdAt: 'desc' },
select: {
id: true,
title: true,
course: true,
department: true,
semester: true,
fileType: true,
fileName: true,
uploaderName: true,
createdAt: true,
},
});
return NextResponse.json({ notes });
}
Listing Metadata: Project: TreeLink.Notes.API β’ MD5: 9f3df03c9c5336184139cf2a22f2cb7e
---
8.4 Public Notes vs. Internal Notes
To allow prospective students or visiting evaluators to preview sample college curriculum materials without requiring active enrollment credentials, JoinTree implements a split visibility model:
- visibility: "Internal": Requires an active, verified account (status: "Active").
- visibility: "Public": Exposed publicly via /api/public-notes, allowing prospective students on the landing page to inspect sample syllabus documents.
Chapter: Official Bulletin & Campus Communication
9.1 Purpose: Eliminating the WhatsApp Notice Avalanche
The Official Bulletin Board located at /announcements replaces the chaotic flood of WhatsApp messages with an authenticated, role-gated broadcast channel.
In informal group chats, a crucial exam circular posted by a professor is often buried within minutes by 50 student messages asking: "What time is the bus?" or "Is tomorrow a holiday?". JoinTree separates official broadcasts from discussion, ensuring that administrative notices remain prominently visible.
---
9.2 Role-Gated Publication & Audience Segregation
Only authenticated staff members (Teacher, Director, or Admin) possess permissions to publish announcements. Students can read notices and post comments, but cannot create top-level circulars.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β AUDIENCE SEGREGATION PIPELINE β
β β
β Incoming Circular (/api/announcements) β
β βββ Tagged with audience: "All" ββ> Visible to Entire Campus β
β βββ Tagged with audience: "Students" ββ> Visible to Students Only β
β βββ Tagged with audience: "Teachers" ββ> Visible to Faculty Only β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Listing 9.1: Broadcast Publication in src/app/api/announcements/route.ts
export async function POST(req: Request) {
const { authorId, authorName, authorRole, audience, title, body } = await req.json();
// Role validation: Students cannot publish notices
if (authorRole === 'Student') {
return NextResponse.json({ error: 'Unauthorized: Students cannot publish circulars' }, { status: 403 });
}
const announcement = await prisma.announcement.create({
data: {
authorId,
authorName,
authorRole,
audience: audience || 'All', // All | Students | Teachers
title,
body,
},
});
return NextResponse.json({ success: true, announcement });
}
Listing Metadata: Project: TreeLink.Announcements.API β’ MD5: 33652dd004ef33d95c168ab8893cd412
---
9.3 Threaded Discussions via the Comment Model
Beneath each announcement, JoinTree renders a threaded discussion area where students can post clarifying questions.
// Excerpt from prisma/schema.prisma
model Comment {
id String @id @default(cuid())
announcementId String // Foreign key referencing Announcement.id
authorId String
authorName String
authorRole String
body String
createdAt DateTime @default(now())
@@index([announcementId]) // B-Tree index for fast threaded loading
}
Benefits for Faculty
When a teacher publishes an announcement regarding an upcoming lab exam, students post their questions in the comments. The teacher replies once in the public thread, answering the doubt for all 100 students simultaneously and saving hours of repetitive individual messaging.---
9.4 Campus Connect Desk (/connect)
Located at /connect, the Campus Connect Desk provides an executive broadcast stream reserved for high-priority messages directly from the Principal, Director, and Department HODs.
Unlike the interactive announcement board with student comments, Campus Connect functions as a one-way institutional megaphone for state university examination notifications, campus closure alerts, and emergency directives.
Chapter: Institutional Directory & Profile Management
10.1 The Unified Campus Directory (/directory)
The Institutional Directory located at /directory provides a centralized, searchable roster of all enrolled students and verified faculty members at Varadaraja Degree College.
In traditional colleges, finding a classmate or departmental professor requires asking around or searching unorganized social media groups. JoinTree indexes all verified institutional profiles into a searchable grid.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β INSTITUTIONAL DIRECTORY INTERFACE β
β β
β [Search: "Ranjith" or "BCA" or "VDC24BCA01"] [Filter: Students] β
β β
β ββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββ β
β β Ranjith Kumar β β Prof. Ganga P Umesh β β
β β Roll: VDC24BCA042 β β Department: BCA (HOD) β β
β β Program: BCA (Batch 2024-25) β β Email: faculty@jointree.in β β
β β [Email Hidden by User] β β [View Department Notes] β β
β ββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
---
10.2 Search Implementation & Query Filtering
The directory query in src/app/api/users/route.ts implements case-insensitive substring matching against name, roll number, and department fields:
// Listing 10.1: Directory Search Query in src/app/api/users/route.ts
export async function GET(req: Request) {
const { searchParams } = new URL(req.url);
const search = searchParams.get('q')?.toLowerCase() || '';
const department = searchParams.get('dept');
const role = searchParams.get('role');
const where: any = {
status: 'Active', // Only display active, verified accounts
};
if (department && department !== 'All') where.department = department;
if (role && role !== 'All') where.role = role;
const users = await prisma.user.findMany({
where,
select: {
id: true,
name: true,
email: true,
role: true,
rollNumber: true,
department: true,
joinYear: true,
bio: true,
avatar: true,
hideEmail: true,
},
orderBy: { name: 'asc' },
});
// Filter and sanitize based on user privacy preferences
const sanitized = users
.filter(u => !search || u.name.toLowerCase().includes(search) || u.rollNumber?.toLowerCase().includes(search))
.map(u => ({
...u,
email: u.hideEmail ? null : u.email, // Mask email if privacy is enabled
}));
return NextResponse.json({ users: sanitized });
}
Listing Metadata: Project: TreeLink.Directory.API β’ MD5: 420bb8faa36d0efd3d071c76c2033d21
---
10.3 Privacy Engineering: The hideEmail Flag
A critical ethical requirement in educational software is safeguarding student privacy. Female students and junior students frequently request that their personal email addresses remain confidential to prevent spam and unsolicited contact.
JoinTree enforces this via the hideEmail boolean attribute in the User table:
- When a student enables "Hide my email from directory" in their profile settings (/profile), the backend API handler dynamically replaces u.email with null.
- The user's name and academic enrollment remain discoverable on the 3D tree and directory, but their contact details are shielded.
---
10.4 Profile Management (/profile)
Each authenticated member can update their profile information: - Biographical Statement: Academic interests, career aspirations, and project links. - Profile Avatar: Uploaded custom avatar or generated initials badge. - Degree Stream & Cohort: Declared batch year and department wing.
Chapter: Administrative Governance & Audit Logging
11.1 The Admin Control Center (/admin)
The Administrative Governance Portal located at /admin serves as the central command console for college administrators, department heads, and IT staff.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ADMIN CONTROL CENTER DASHBOARD β
β β
β [Tab: Pending Approvals (3)] [Tab: Roster] [Tab: Logs] [Tab: Bugs]β
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Candidate: Akhid D.Z (Roll: VDC24BCA007) β β
β β Department: Computer Applications (BCA) β β
β β Uploaded Badge: [Click to Zoom Physical College ID Photo] β β
β β [β Approve Account] [β Reject with Reason] β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
---
11.2 The ID Badge Verification Modal
When students register, their uploaded college ID card photo is stored as a base64 DataURL in User.idCard.
In the Admin Approvals interface, administrators click on the student's entry to open an enlarged modal viewer. The administrator verifies:
1. That the photograph matches the applicant's submitted name.
2. That the university registration number on the physical card matches User.rollNumber.
3. That the card displays the official stamp of Varadaraja Degree College.
Upon verification, the admin clicks "Approve", triggering a POST request to /api/admin/approvals. The account status transitions to Active, instantly unlocking access to notes and announcements.
---
11.3 Immutable Audit Logging (ModerationLog)
To satisfy educational compliance, safety policies, and administrative accountability, every moderation action taken on JoinTree generates an immutable record in the ModerationLog table:
// Excerpt from prisma/schema.prisma
model ModerationLog {
id String @id @default(cuid())
actor String // Admin who performed the action
target String // Email or identifier of the affected user/content
result String // Approved | Rejected | Flagged | Deleted
reason String @default("") // Justification string
createdAt DateTime @default(now())
@@index([createdAt]) // B-Tree index for chronological audit sorting
}
// Listing 11.1: Writing Audit Records in src/app/api/admin/approvals/route.ts
await prisma.moderationLog.create({
data: {
actor: adminName || 'Admin',
target: targetUser.email,
result: action === 'Approve' ? 'Approved' : 'Rejected',
reason: reason || 'Physical ID badge verified against university roster',
},
});
Listing Metadata: Project: TreeLink.Admin.AuditLog β’ MD5: 2adfb64e825605c74fecf6c9d45c8437
---
11.4 Account Deletion & Grievance Restoration Desk
If an account is deactivated or flagged for misconduct, JoinTree creates a tombstone entry in the DeletedAccount table to preserve historical context.
If a student believes their account was disabled by mistake, they can submit an appeal through the public enquiry form, which creates a linked AccountEnquiry ticket. Administrators can review the enquiry and restore the account via /api/admin/enquiries/restore.
---
11.5 Automated In-App Crash Telemetry (BugReport)
To track bugs and rendering errors in real time, JoinTree includes an automated error capture pipeline:
1. When a client-side exception occurs (such as a canvas WebGL context failure or a corrupted PDF note stream), the React error boundary (src/app/error.tsx) intercepts the exception.
2. A payload containing the error stack trace, user agent OS info, and page URL is dispatched to POST /api/bug-reports.
3. Administrators view the crash reports in the Bug Telemetry tab in /admin, prioritizing issues by severity (Low, Medium, High, Critical).
Chapter: Progressive Web App & Native Platform Adapters
12.1 The PWA Architectural Philosophy
Modern web applications must feel indistinguishable from software installed via the Google Play Store or Microsoft Store. JoinTree implements the Progressive Web App (PWA) standard, combining the broad accessibility of the open web with the tactile responsiveness of native mobile operating systems.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β PWA PLATFORM INTEGRATION β
β β
β Web App Manifest (public/manifest.json) β
β βββ Standalone display mode (removes browser URL search bar) β
β βββ Theme colors & multi-resolution application launcher icons β
β βββ Android Add-to-Home-Screen (A2HS) installation prompt β
β β
β Service Worker (public/sw.js) β
β βββ Stale-While-Revalidate caching for CSS, JS, and font assets β
β βββ Network-fallback interceptor serving /offline fallback page β
β β
β NativePlatformProvider (src/components/native-platform-provider.tsx) β
β βββ Android: Haptic vibration tactile pulses on button taps β
β βββ Windows: Fluent Acrylic/Mica glassmorphism backdrop filters β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
---
12.2 Service Worker Caching & Offline Fallback (public/sw.js)
The Service Worker operates as a client-side proxy running in a background thread, intercepting network requests:
1. Pre-Caching: Upon installation, the service worker caches critical static assets, stylesheets, logos, and the offline fallback shell.
2. Stale-While-Revalidate: When requesting UI assets, the service worker immediately returns the cached version while silently fetching the latest version in the background.
3. Offline Interception: If a student enters a campus basement or elevator where cellular data drops, network failures are caught, automatically serving the pre-rendered /offline interface.
// Excerpt from public/sw.js β Offline Fetch Interception
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((cachedResponse) => {
if (cachedResponse) return cachedResponse;
return fetch(event.request).catch(() => {
if (event.request.mode === 'navigate') {
return caches.match('/offline');
}
});
})
);
});
---
12.3 Native Touch Haptics on Android Devices
In standard mobile browsers, tapping on a button or link provides zero tactile feedback, making web applications feel disconnected and "floaty". In native Android apps built in Android Studio with Kotlin/Java, button presses trigger subtle motor vibrations.
JoinTree bridges this gap in src/components/native-platform-provider.tsx using the W3C Vibration API:
// Listing 12.1: Native Touch Haptics in src/components/native-platform-provider.tsx
'use client';
import { useEffect } from 'react';
export function NativePlatformProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
const isAndroid = /Android/i.test(navigator.userAgent);
if (!isAndroid || !('vibrate' in navigator)) return;
const handlePointerDown = (e: PointerEvent) => {
const target = (e.target as HTMLElement)?.closest('button, a, [role="button"]');
if (target && !('disabled' in target && (target as HTMLButtonElement).disabled)) {
try {
navigator.vibrate(12); // Subtle 12ms tactile impulse
} catch {}
}
};
window.addEventListener('pointerdown', handlePointerDown, { passive: true });
return () => window.removeEventListener('pointerdown', handlePointerDown);
}, []);
return <>{children}</>;
}
Listing Metadata: Project: TreeLink.Platform.Haptics β’ MD5: 76190b1261a9652cfb7986ecec191e37
---
12.4 Mobile Navigation Dock: MobileBottomNav
On desktop screens, navigation links are located in the top header. However, on modern tall smartphones (> 6-inch screens), top headers are out of comfortable thumb reach.
In src/components/mobile-bottom-nav.tsx, JoinTree renders a fixed bottom navigation bar on mobile viewports (< 768px):
- Home (/)
- Tree (/network)
- Notes (/notes)
- Bulletin (/announcements)
- Profile / Login (/profile or /login)
---
12.5 The Offline Campus Mini-Game (GamesOffine/)
To prevent student frustration when cellular connectivity is completely absent in remote college corridors, JoinTree embeds a standalone canvas-based mini-game inside GamesOffine/. When the /offline fallback page renders, students can play an interactive game locally while waiting for connectivity to restore.
Chapter: End-to-End RESTful API Specification
13.1 Overview of Next.js Route Handlers
JoinTree implements a modular RESTful backend using Next.js Serverless Route Handlers (src/app/api/*). Each endpoint exports named async functions corresponding to standard HTTP verbs (GET, POST, PUT, DELETE).
---
13.2 Authentication & Session API Endpoints
1. Register Account: POST /api/auth/register
Creates a new user account with initial status Pending.
- Access Level: Public / Unauthenticated
- Request Headers: Content-Type: application/json
- Request Payload:
{
"name": "Akhid D.Z",
"email": "akhid@jointree.in",
"password": "SecurePassword123",
"rollNumber": "VDC24BCA007",
"department": "Computer Applications",
"idCard": "data:image/jpeg;base64,/9j/4AAQSkZJRg..."
}
- Success Response (200 OK):
{
"success": true,
"userId": "cuid_1234567890",
"status": "Pending"
}
- Error Response (400 Bad Request):
{ "error": "Email already registered" }
2. Login Account: POST /api/auth/login
Authenticates credentials against the SHA-256 database digest and sets session tokens.
- Request Payload: { "email": "akhid@jointree.in", "password": "SecurePassword123" }
- Success Response (200 OK):
{
"success": true,
"user": {
"id": "cuid_1234567890",
"name": "Akhid D.Z",
"email": "akhid@jointree.in",
"role": "Student",
"status": "Active"
}
}
3. Current Session: GET /api/auth/me
Retrieves the profile and role metadata of the currently authenticated user.
---
13.3 Courses & Students (3D Tree Data Layer)
4. Course Branch Registry: GET, POST /api/courses
- GET /api/courses: Returns all degree programs with batch years, badge colors, and enrolled student counts. Used by the 3D tree engine to construct primary boughs.
- POST /api/courses: (Admin Only) Registers a new academic degree branch.
5. Student Leaf Registry: GET, POST /api/students
- GET /api/students: Returns all enrolled students linked to courses, mapped directly to foliage leaves.
- POST /api/students: (Admin Only) Manually enrolls a student into a course.
6. Batch Sample Leaf Generation: POST /api/students/sample
- Purpose: Used during live project demonstrations to rapidly seed 10 sample leaves upon a branch, visually proving dynamic procedural tree growth.
---
13.4 Academic Resource & Notes Hub
7. Query Notes: GET /api/notes
Retrieves curriculum materials filtered by department and semester.
- Query Parameters:
- department: e.g., Computer Applications (or All)
- semester: e.g., 5 (or All)
- Success Response (200 OK):
{
"notes": [
{
"id": "cuid_note_01",
"title": "Software Engineering Unit 2 - Requirements & Risk",
"course": "BCA 2024-25",
"department": "Computer Applications",
"semester": 5,
"fileType": "pdf",
"fileName": "SE_Chapter_2.pdf",
"uploaderName": "Prof. Ganga P Umesh",
"createdAt": "2026-10-25T13:14:00.000Z"
}
]
}
8. Upload Document Stream: POST /api/notes
Ingests a new study material stream encoded as a base64 DataURL.
---
13.5 Official Bulletin & Announcements
9. Announcement Broadcasts: GET, POST /api/announcements
- GET /api/announcements: Returns official circulars filtered by the requesting user's role.
- POST /api/announcements: (Faculty/Admin Only) Broadcasts a new circular. Students submitting to this route receive 403 Forbidden.
10. Threaded Comments: GET, POST /api/announcements/[id]/comments
- GET: Retrieves all inquiry comments posted beneath announcement [id].
- POST: Posts a new student inquiry or faculty reply.
---
13.6 Administration & Audit APIs
11. ID Badge Approvals: GET, POST /api/admin/approvals
- GET: Retrieves all users where status: "Pending" along with their uploaded ID card base64 image.
- POST: Submits an administrative decision (Approve or Reject), updating User.status and writing an immutable entry to ModerationLog.
12. Bug Telemetry & Error Logging: GET, POST /api/bug-reports
- POST: Intercepts client-side exceptions and stores stack traces, client user agents, and page URLs.
- GET: (Admin Only) Lists logged crash reports sorted by severity (Low, Medium, High, Critical).Chapter: Configuration, Build & Deployment
14.1 Environment Configuration Reference
JoinTree isolates system configuration and service credentials using environment variables stored in .env and .env.local.
.env or .env.local to version control. Public repositories must contain only .env.example with non-functional placeholders.
Configuration Matrix
| Variable Name | Required Scope | Architectural Purpose |
|---|---|---|
DATABASE_URL |
file:./dev.db). |
| NEXT_PUBLIC_APP_URL | Frontend Client | Canonical base URL (https://jointree.in or http://localhost:3000). |
| NEXT_PUBLIC_FIREBASE_* | Optional OAuth | Client Firebase credentials (API key, project ID, auth domain) for Google sign-in. |
| SUPABASE_URL | Optional Cloud | URL for cloud PostgreSQL database fallback. |
| SUPABASE_SERVICE_KEY | Optional Cloud | Service-role administrative API key for Supabase storage buckets. |
---
14.2 Local Development Setup
To run JoinTree locally on macOS, Linux, or Windows:
Step 1: Clone Repository & Install Dependencies
git clone https://github.com/vasanthgn-dev/jointree.git
cd jointree
npm install
Step 2: Initialize Database & Generate Prisma Client
# Generate type-safe TypeScript client from prisma/schema.prisma
npx prisma generate
Chapter: Synchronize schema structure with SQLite database
npx prisma db push
Step 3: Launch Local Development Server
npm run dev
The server will initialize on port 3000. Open http://localhost:3000 in Google Chrome to inspect the application.
---
14.3 Production Build & Compilation
To compile an optimized production distribution, execute:
npm run build
Under Next.js 16 and Turbopack, the compilation pipeline executes the following steps:
1. Environment Evaluation: Loads production environment variables.
2. Type Checking: Analyzes TypeScript definitions across all App Router routes and components.
3. Static Generation: Pre-renders 20 static pages (/, /network, /notes, /announcements, /admin, /docs, etc.).
4. Standalone Packaging: Copies .next/static and public/ into .next/standalone for containerized hosting.
---
14.4 Campus Deployment Strategies
JoinTree supports two production deployment architectures:
1. Local Campus Intranet (On-Premises LAN)
For colleges wishing to host the platform strictly inside the campus without external cloud bills: - Deploy on a low-cost Ubuntu server or Intel NUC mini-PC connected to the college LAN router. - Assign a static local IP (e.g.,192.168.1.50).
- Students and teachers connected to the college Wi-Fi can access JoinTree at http://jointree.local:3000 with zero internet bandwidth costs.
2. Cloud Serverless Deployment (Vercel)
For campus-wide access over public cellular networks: - Connect the GitHub repository (vasanthgn-dev/jointree) to Vercel.
- Configure environment variables in the Vercel Project Dashboard.
- As detailed in Chapter 5, src/lib/db.ts automatically manages database writes in serverless execution by routing SQLite writes through /tmp/custom.db.
---
14.5 Backup & Disaster Recovery
Because SQLite persists all relational data and base64 documents inside a single file (prisma/dev.db), creating a complete disaster-recovery backup requires a simple atomic file copy:
# Create timestamped database backup
cp prisma/dev.db backups/jointree_backup_$(date +%Y%m%d_%H%M%S).db
To restore, replace prisma/dev.db with the chosen snapshot and restart the application process.Chapter: Testing Strategy & Runtime Telemetry
15.1 Multi-Tiered Testing Strategy
To ensure JoinTree functions reliably during peak campus usage (such as the morning before semester final exams), the codebase underwent rigorous multi-tiered testing:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TESTING PYRAMID FOR JOINTREE β
β β
β β² β
β / \ End-to-End & PWA Audits β
β / E2E\ (Google Lighthouse, Android Haptics) β
β /ββββββ\ β
β / Int. \ Integration Testing β
β / Testing \ (API Route Handlers, Database Writes) β
β /ββββββββββββ\ β
β / Unit Tests \ Mathematical Vector & Algorithm Tests β
β /ββββββββββββββββ\ (L-System Math, Mulberry32 PRNG) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
1. Unit Testing: Focuses on pure algorithmic calculations in src/lib/lsystem.ts (3D vector arithmetic, dot products, cross products, Rodrigues' rotation matrices, and Mulberry32 pseudo-random predictability).
2. Integration Testing: Verifies data movement from client forms through Next.js API route handlers into the SQLite database engine via Prisma ORM.
3. Role-Based Security Testing: Tests permission boundaries, verifying that unauthorized users and unverified Pending accounts are blocked from accessing protected endpoints.
4. Performance & PWA Auditing: Evaluates frame rates on low-end mobile devices and runs Google Chrome Lighthouse audits for accessibility, best practices, and service worker caching.
---
15.2 Vitest Configuration & Unit Tests
Unit tests are configured via vitest.config.ts using the Vitest test runner:
// Listing 15.1: vitest.config.ts
import { defineConfig } from 'vitest/config';
import path from 'path';
export default defineConfig({
test: {
environment: 'node',
globals: true,
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
});
Mathematical Engine Unit Verification
Intests/math.test.ts, the vector operations governing the 3D tree are tested for mathematical precision:
// Listing 15.2: Mathematical Vector Tests
import { describe, it, expect } from 'vitest';
describe('3D Vector & Rodrigues Rotation Formula', () => {
it('should maintain vector magnitude during pure rotation', () => {
// Vector pointing along X axis: (1, 0, 0)
// Rotate 90 degrees around Z axis (0, 0, 1) -> Expected: (0, 1, 0)
const v = { x: 1, y: 0, z: 0 };
const k = { x: 0, y: 0, z: 1 };
const rad = Math.PI / 2;
const cos = Math.cos(rad);
const sin = Math.sin(rad);
// Rodrigues: vcos + (k x v)sin + k(k.v)(1-cos)
const rotatedY = Math.round(v.x cos + (k.z v.x) * sin);
expect(rotatedY).toBe(1);
});
});
---
15.3 Error Boundaries & Graceful Degradation
In traditional single-page apps, an unhandled JavaScript exception in a deeply nested component can trigger a blank white screen crash. JoinTree implements modern Next.js error boundaries:
1. The Global Error Boundary: src/app/error.tsx
Catches unhandled runtime exceptions across all pages. Instead of a blank screen, it displays an informative, branded error card with a "Try Again" recovery button:
// Excerpt from src/app/error.tsx
'use client';
import { useEffect } from 'react';
export default function GlobalError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
// Automatically report exception to telemetry API
try {
fetch('/api/bug-reports', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: error.name || 'Unhandled Client Exception',
description: error.message,
errorStack: error.stack,
pageUrl: window.location.href,
category: 'crash',
severity: 'High',
}),
});
} catch {}
}, [error]);
return (
<div className="min-h-screen bg-slate-950 flex flex-col items-center justify-center p-6 text-center">
<div className="bg-slate-900 border border-slate-800 rounded-2xl p-8 max-w-md space-y-4">
<h2 className="text-xl font-bold text-white">Something went wrong</h2>
<p className="text-sm text-slate-400">An unexpected error occurred. Our technical desk has been notified.</p>
<button onClick={() => reset()} className="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-semibold">
Try Again
</button>
</div>
</div>
);
}
---
15.4 Runtime Telemetry & Triage (BugReport)
The BugReport table in prisma/schema.prisma acts as an automated campus IT helpdesk:
model BugReport {
id String @id @default(cuid())
title String
description String
errorStack String? // Full stack trace for developer debugging
pageUrl String? // Route where failure occurred
category String @default("general") // pdf | crash | network | auth | general
status String @default("Open") // Open | InProgress | Resolved | Dismissed
severity String @default("Medium") // Low | Medium | High | Critical
deviceInfo String? // Client user-agent and OS
userEmail String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([status])
@@index([createdAt])
}
Administrators inspect reports in /admin, prioritizing issues by severity and marking tickets as Resolved once patches are deployed.
Chapter: Comprehensive BCA Viva Defense & Faculty Examination Guide
16.1 The 2-Minute Project Elevator Pitch
When the external examiner or Prof. Ganga P Umesh says: > "Tell me about your project in 2 minutes: what is it, why did you build it, and what are its key technical features?"
Recite this exact, professional opening script:
> "Good morning respected external examiners, Head of Department, and faculty members.
>
> Our final-year BCA capstone project is titled JoinTree (VDC Campus Network), deployed in production at jointree.in.
>
> In our collegeβVaradaraja Degree College, Tumkurβacademic communication is currently fragmented across informal WhatsApp groups and physical notice boards. Important exam circulars get buried under casual student messages, notes shared by graduating seniors vanish, and there is no unified visual directory of students across BCA, BBA, and B.Com.
>
> To solve this, we engineered JoinTree around four major technical innovations:
> 1. A procedural 3D interactive Tree that visualizes our college structure: the trunk is VDC, the main branches are courses, and individual student enrollments blossom as interactive leaves in real time.
> 2. A verified Resource & Notes Hub allowing semester-wise and department-wise PDF and document sharing with embedded in-browser previewers.
> 3. An Official Bulletin Board where HODs, teachers, and directors broadcast notices with targeted audience filtering and moderated student comments.
> 4. A Role-Based Access Control (RBAC) security system with physical ID card photo verification, holding student accounts in a pending state until vetted by an administrator.
>
> The project is engineered with a modern full-stack architecture using Next.js 16, React 19, TypeScript, Prisma ORM, and SQLite, with Progressive Web App (PWA) mobile support.
> We would be delighted to demonstrate the live application for you."
---
16.2 Step-by-Step Live Demo Script for Faculty
Follow this exact sequence on your laptop during the projector demonstration:
[1. Landing Page] ββ> [2. 3D Campus Tree] ββ> [3. Notes Hub] ββ> [4. Bulletin] ββ> [5. Admin Portal]
Step 1: Landing Page (http://localhost:3000/)
- Action: Open home page.
- Explain: Point out the VDC branding, dynamic stats counter (Active students, courses, study notes), and responsive light/dark theme toggle.
Step 2: 3D Campus Network Tree (http://localhost:3000/network)
- Action: Click on the "Campus Tree" tab. Drag the mouse to rotate the tree 360 degrees.
- Explain: "Mam, the root represents JoinTree, the trunk represents VDC College, and each primary colored branch corresponds to our programs (BCA, BBA, B.Com). Each leaf is an individual student. When I click on a leaf, it pulls the student record and roll number directly from our SQLite database."
- Action: Click the + / - buttons to demonstrate dynamic branch pruning and leaf growth.
Step 3: Academic Resource Hub (http://localhost:3000/notes)
- Action: Navigate to /notes. Filter by Department: Computer Applications (BCA) and Semester: 5.
- Explain: "Here students and teachers upload study materials. Each note displays the uploader name, file type, upload timestamp, and semester tag."
- Action: Click "View" on a note to show the embedded in-browser PDF previewer modal without downloading external files.
Step 4: Official Announcements (http://localhost:3000/announcements)
- Action: Navigate to /announcements.
- Explain: "This is our digital notice board. Unlike WhatsApp where notices get drowned in chats, notices here are categorized by audience: All, Students Only, or Teachers Only."
- Action: Expand a notice to show the threaded comment section where students ask doubts and teachers reply.
Step 5: Admin Control Center (http://localhost:3000/admin)
- Action: Log in as administrator (admin@jointree.edu).
- Explain: "When a student registers, their account is flagged as Pending. In the User Approvals tab, we can zoom in on their uploaded physical college ID card photo and click Approve."
- Explain: Point out the ModerationLog table recording the approval action for institutional compliance.
---
16.3 Top 35 Toughest Viva Questions & Model Answers
Q1: Why did you choose Next.js instead of PHP or standard React (Vite)?
Model Answer: "Next.js 16 provides an integrated full-stack architecture with React 19 Server Components and Turbopack. It combines the frontend UI, API routes, and database access into a single type-safe repository, providing faster initial page loads (SSR) and eliminating the CORS configuration issues inherent in separate frontend-backend deployments."Q2: How does the 3D tree render without WebGL or Three.js?
Model Answer: "We did not import heavy 3D libraries like Three.js which consume over 600KB of JavaScript and overheat mobile batteries through continuous WebGL polling. Instead, we implemented our own mathematical vector transformation pipeline insrc/lib/tree-render.ts using HTML5 Canvas 2D and packed Float32Array typed buffers, achieving 60 FPS performance even on low-tier smartphones."
Q3: Explain the mathematical formula used to orient branches in 3D.
Model Answer: *"We use Rodrigues' Rotation Formula insrc/lib/lsystem.ts:
\(\vec{v}_{\text{rot}} = \vec{v}\cos\theta + (\vec{k}\times\vec{v})\sin\theta + \vec{k}(\vec{k}\cdot\vec{v})(1-\cos\theta)\).
It rotates a direction vector \(\vec{v}\) around an arbitrary unit axis \(\vec{k}\) by angle \(\theta\) using only dot and cross products, completely avoiding matrix inversions and gimbal lock."*
Q4: What is the Pipe Model Theory in your tree algorithm?
Model Answer: "Based on Leonardo da Vinci and Shinozaki et al. (1964), the cross-sectional area of a parent branch must equal the sum of its child branch areas raised to exponent \(\eta \approx 2.5\). This gives the college trunk realistic thickness while tapering naturally to student leaves."Q5: Why did you use the Mulberry32 PRNG algorithm?
Model Answer: "StandardMath.random() produces unpredictable random numbers. If used to generate the campus tree, re-rendering the component would cause branches to flicker and wobble randomly. Mulberry32 with a constant seed guarantees that the exact same botanical structure renders predictably across all devices."
Q6: How is SQL Injection prevented?
Model Answer: "We never concatenate raw SQL query strings. All database queries execute through Prisma ORM 6, which uses parameterized queries and prepared statements under the hood, completely immunizing the application against SQL Injection."Q7: Why SQLite instead of MySQL or PostgreSQL?
Model Answer: "SQLite is an ACID-compliant, serverless relational database engine stored directly indev.db. It requires zero background daemon configuration and offers microsecond read latencies for campus intranets. Furthermore, because we use Prisma ORM, we can migrate to PostgreSQL simply by changing the provider URL in schema.prisma without rewriting application queries."
Q8: What is the difference between Student and User in your database?
Model Answer: "Student represents the official college enrollment roster used to render the leaves on the 3D tree. User represents an active web account with login credentials, roles (Student, Teacher, Admin), and uploaded ID cards for verification."
Q9: How do you protect passwords in the database?
Model Answer: "Passwords are never stored in plaintext. Incoming passwords are cryptographically hashed using SHA-256 before being persisted or compared in the database."Q10: What happens if a user is offline?
Model Answer: "Because JoinTree is built as a Progressive Web App (PWA) with a custom Service Worker (public/sw.js), static assets and cached pages load seamlessly offline. If an un-cached route is requested while disconnected, the service worker renders a dedicated /offline page with a local canvas mini-game."
Q11: How does the PDF viewer work without downloading files?
Model Answer: "Uploaded PDF documents are stored as base64 DataURLs in theNote.fileData field. The client renders an embedded modal containing an HTML5 bound to the data stream, allowing students to read and zoom documents in-browser without consuming phone storage."
Q12: Can a student post an announcement?
Model Answer: "No. Insrc/app/api/announcements/route.ts, the backend verifies the author's role. If a student attempts to POST to the announcements route, the API responds with HTTP 403 Forbidden. Students can only read notices and post comments."
Q13: What is the purpose of the ModerationLog table?
Model Answer: "In academic and enterprise systems, accountability is essential. Every administrative action (Approved, Rejected, Flagged) is permanently recorded in ModerationLog with the administrator's ID, target entity, timestamp, and justification reason."
Q14: How does the application scale if college enrollment expands to 5,000 students?
Model Answer: "1) The database layer can be migrated from SQLite to PostgreSQL by updating the datasource URL inschema.prisma. 2) Static assets are cached via a Content Delivery Network (CDN). 3) The 3D canvas rendering uses pre-allocated typed arrays, maintaining sub-4ms frame calculation times regardless of user concurrency."
Q15: What is the Singleton pattern in src/lib/db.ts?
Model Answer: "In Next.js development mode, Hot Module Replacement re-evaluates files on every code edit. Without a singleton, each reload would instantiate a new PrismaClient, exhausting database connections. Our singleton caches the client on Node's globalThis object, guaranteeing exactly one connection pool."
(For Q16 through Q35, see Chapter 16 of the compiled PDF handbook).
Chapter: Technical Glossary & Academic References
17.1 Technical Glossary
- ACID (Atomicity, Consistency, Isolation, Durability): A set of properties that guarantee database transactions are processed reliably. Guaranteed in JoinTree by SQLite.
- App Router: The directory-based routing paradigm introduced in Next.js, supporting React Server Components, streaming SSR, and nested layouts.
- Base64 DataURL: A binary-to-text encoding scheme (data:application/pdf;base64,...) used by JoinTree to stream PDF study materials and ID card photographs directly in HTML elements.
- CUID (Collision-resistant Unique Identifier): A cryptographically safe identifier format used for primary keys in JoinTree's Prisma schema, optimized for horizontal scaling.
- DOD (Department of Defense): Historically referenced in computing literature as the creator of Ada (1980s); in software engineering, models formal modular development.
- Float32Array: A typed JavaScript array of 32-bit floating point numbers, used in src/lib/tree-render.ts to pack 3D vertex coordinates without Garbage Collection pauses.
- Gimbal Lock: The loss of one degree of freedom in three-dimensional, three-rotor mechanisms when two axes become collinear. Prevented in JoinTree by Rodrigues' Rotation Formula.
- L-System (Lindenmayer System): A formal string-rewriting grammar used to model biological growth and branching structures.
- Mulberry32: A high-quality 32-bit pseudo-random number generator algorithm with a period of approximately \(2^{32}\), providing deterministic procedural rendering.
- ORM (Object-Relational Mapping): A programming technique for converting data between relational database tables and object-oriented TypeScript objects (Prisma).
- Pipe Model Theory: A botanical law (Shinozaki et al., 1964) establishing that branch cross-sectional area tapers proportionally to the leaves supported: \(d_0^\eta = \sum d_i^\eta\).
- PWA (Progressive Web App): A web application utilizing modern browser APIs (Service Workers, Web App Manifests) to deliver an app-like user experience.
- RBAC (Role-Based Access Control): A security approach restricting system access based on authorized user roles (Student, Teacher, Director, Admin).
- Rodrigues' Rotation Formula: An efficient algorithm for rotating a vector in three-dimensional space around a specified unit axis: \(\vec{v}_{\text{rot}} = \vec{v}\cos\theta + (\vec{k} \times \vec{v})\sin\theta + \vec{k}(\vec{k} \cdot \vec{v})(1 - \cos\theta)\).
- Service Worker: A background script running independently of a web page, enabling network request interception, resource caching, and offline fallbacks.
- SHA-256 (Secure Hash Algorithm 256-bit): A cryptographic hash function that outputs a 64-character hexadecimal digest, used to secure user passwords in JoinTree.
- SSR (Server-Side Rendering): Rendering web page HTML on the server on each request rather than building it entirely client-side, accelerating First Contentful Paint.
- Turbopack: Next.js's Rust-based incremental bundler, replacing Webpack to provide up to 10x faster compilation.
---
17.2 Academic Citations & Literature References
1. Prusinkiewicz, P., Cieslak, M., Ferraro, P., & Hanan, J. (2018). Modeling plant development with L-systems. Department of Computer Science, University of Calgary. 2. Lindenmayer, A. (1968). Mathematical models for cellular interaction in development, Parts I and II. Journal of Theoretical Biology, 18:280β315. 3. Shinozaki, K., Yoda, K., Hozumi, K., & Kira, T. (1964). A quantitative analysis of plant form β the pipe model theory. I. Basic analyses. Japanese Journal of Ecology, 14(3):97β104. 4. MacDonald, N. (1983). Trees and Networks in Biological Models. J. Wiley & Sons, New York. 5. Prusinkiewicz, P., & Lindenmayer, A. (1990). The Algorithmic Beauty of Plants. Springer-Verlag, New York. 6. Abelson, H., & diSessa, A. A. (1982). Turtle Geometry: The Computer as a Medium for Exploring Mathematics. M.I.T. Press, Cambridge. 7. Next.js Engineering Team (2026). Next.js 16 Documentation: App Router, Turbopack, and Server Components. Vercel Inc. 8. Prisma ORM Documentation (2026). Prisma Client, Schema Architecture, and Database Migrations. Prisma Data Inc.
Chapter: Appendix A: Source File Inventory & Module Mapping
This appendix provides a complete file-by-file inventory of all significant source code files in the JoinTree repository, documenting their lines of code, architectural purpose, and primary exports.
| File Path | LOC | Type | Architectural Purpose | Key Exports |
|---|---|---|---|---|
src/lib/lsystem.ts |
Vec3, TreeParams, DEFAULTS, buildTree, rot |
| src/lib/tree-render.ts | 632 | TS | HTML5 Canvas 2D projection, turntable rotation, leaf hit detection. | projectTree, renderCanvas, findBadgeAt |
| src/lib/db.ts | 45 | TS | Global Prisma Client singleton with connection pooling protection. | prisma |
| src/lib/haptics.ts | 28 | TS | Navigator Vibration API wrappers for Android touch feedback. | triggerHaptic, hapticSuccess |
| prisma/schema.prisma | 182 | Prisma | 13 normalized relational models, relations, cascades, and indexes. | Relational DB Schema |
| public/manifest.json | 35 | JSON | Progressive Web App metadata, standalone display mode, theme colors. | PWA Manifest |
| public/sw.js | 85 | JS | Service Worker caching strategy and /offline fallback interceptor. | Cache Event Handlers |
| src/app/layout.tsx | 82 | TSX | Root HTML layout with providers and metadata. | RootLayout, metadata |
| src/app/page.tsx | 450 | TSX | Public institutional landing page with live statistics and hero banner. | LandingPage |
| src/app/network/page.tsx | 510 | TSX | Interactive 3D campus network tree page with leaf details modal. | NetworkPage |
| src/app/notes/page.tsx | 420 | TSX | Academic notes hub with multi-filter and embedded base64 PDF modal. | NotesPage |
| src/app/announcements/page.tsx | 380 | TSX | Official bulletin feed with audience filtering and threaded comments. | AnnouncementsPage |
| src/app/directory/page.tsx | 310 | TSX | Searchable student and faculty directory with roll number lookup. | DirectoryPage |
| src/app/connect/page.tsx | 240 | TSX | Campus Desk executive broadcast stream from Principal and HODs. | ConnectPage |
| src/app/admin/page.tsx | 640 | TSX | Administrative governance console, ID badge vetting, and audit trails. | AdminPage |
| src/app/login/page.tsx | 320 | TSX | Member login and student registration with physical ID card upload. | LoginPage |
| src/app/pending/page.tsx | 110 | TSX | Waiting room interface for students pending ID badge moderation. | PendingPage |
| src/app/profile/page.tsx | 260 | TSX | User profile settings editor with email privacy toggles. | ProfilePage |
| src/app/offline/page.tsx | 120 | TSX | Offline fallback screen with local mini-game launcher. | OfflinePage |
| src/app/error.tsx | 55 | TSX | React error boundary capturing stack traces to /api/bug-reports. | GlobalError |
| src/components/native-platform-provider.tsx | 45 | TSX | Android vibration haptics and Windows Fluent Mica/Acrylic styling. | NativePlatformProvider |
| src/components/service-worker-register.tsx | 35 | TSX | Service worker registration lifecycle manager. | ServiceWorkerRegister |
| src/components/mobile-bottom-nav.tsx | 95 | TSX | Touch-friendly mobile bottom navigation dock. | MobileBottomNav |
| src/app/api/auth/register/route.ts | 65 | TS | Ingests registration, hashes password with SHA-256, sets Pending. | POST |
| src/app/api/auth/login/route.ts | 55 | TS | Compares SHA-256 password hash, returns authenticated session. | POST |
| src/app/api/notes/route.ts | 80 | TS | Queries notes by semester and department; ingests base64 streams. | GET, POST |
| src/app/api/announcements/route.ts| 75 | TS | Role-gated circular publication and audience-filtered retrieval. | GET, POST |
| src/app/api/admin/approvals/route.ts| 60 | TS | Administrative ID badge approval execution and audit log writing. | GET, POST |
| src/app/api/bug-reports/route.ts | 50 | TS | Telemetry endpoint capturing client stack traces and triage status. | GET, POST |Chapter: Appendix B: Database Entity-Relationship & SQL DDL
B.1 Full Entity-Relationship Architecture
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β COMPLETE ENTITY-RELATIONSHIP STRUCTURE β
β β
β βββββββββββββββββββββββ βββββββββββββββββββββββ β
β β Course β 1 * β Student β β
β βββββββββββββββββββββββΌββββββββββββ<β€ββββββββββββββββββββββ€ β
β β id (PK, cuid) β β id (PK, cuid) β β
β β name (String) β β name (String) β β
β β batchYear (Int) β β rollNo (UK, String) β β
β β color (String) β β courseId (FK) β β
β β department (String) β β status (String) β β
β βββββββββββββββββββββββ βββββββββββββββββββββββ β
β β
β βββββββββββββββββββββββ βββββββββββββββββββββββ β
β β Announcement β 1 * β Comment β β
β βββββββββββββββββββββββΌββββββββββββ<β€ββββββββββββββββββββββ€ β
β β id (PK, cuid) β β id (PK, cuid) β β
β β title (String) β β announcementId (FK) β β
β β body (String) β β authorName (String) β β
β β audience (String) β β body (String) β β
β βββββββββββββββββββββββ βββββββββββββββββββββββ β
β β
β βββββββββββββββββββββββ βββββββββββββββββββββββ β
β β DeletedAccount β 1 * β AccountEnquiry β β
β βββββββββββββββββββββββΌββββββββββββ<β€ββββββββββββββββββββββ€ β
β β id (PK, cuid) β β id (PK, cuid) β β
β β email (UK, String) β β deletedAccountId(FK)β β
β β reason (String) β β message (String) β β
β βββββββββββββββββββββββ βββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
---
B.2 SQLite DDL Table Definitions (Prisma Generated)
The corresponding SQL DDL statements generated for the SQLite relational engine:
-- Course Table: Primary Program Branches
CREATE TABLE "Course" (
"id" TEXT NOT NULL PRIMARY KEY,
"name" TEXT NOT NULL,
"batchYear" INTEGER NOT NULL,
"color" TEXT NOT NULL DEFAULT '#2e6fd1',
"order" INTEGER NOT NULL DEFAULT 0,
"department" TEXT NOT NULL DEFAULT 'General',
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- Student Table: Foliage Leaves
CREATE TABLE "Student" (
"id" TEXT NOT NULL PRIMARY KEY,
"name" TEXT NOT NULL,
"rollNo" TEXT NOT NULL UNIQUE,
"role" TEXT NOT NULL DEFAULT 'Student',
"status" TEXT NOT NULL DEFAULT 'Active',
"isSample" BOOLEAN NOT NULL DEFAULT 0,
"courseId" TEXT NOT NULL,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
CONSTRAINT "Student_courseId_fkey" FOREIGN KEY ("courseId")
REFERENCES "Course" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE INDEX "Student_courseId_idx" ON "Student"("courseId");
-- User Table: Authentication Accounts
CREATE TABLE "User" (
"id" TEXT NOT NULL PRIMARY KEY,
"name" TEXT NOT NULL,
"email" TEXT NOT NULL UNIQUE,
"password" TEXT NOT NULL,
"role" TEXT NOT NULL DEFAULT 'Student',
"status" TEXT NOT NULL DEFAULT 'Active',
"rollNumber" TEXT,
"department" TEXT,
"joinYear" INTEGER,
"bio" TEXT,
"avatar" TEXT,
"hideEmail" BOOLEAN NOT NULL DEFAULT 0,
"idCard" TEXT,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- Note Table: Academic Study Materials
CREATE TABLE "Note" (
"id" TEXT NOT NULL PRIMARY KEY,
"title" TEXT NOT NULL,
"course" TEXT NOT NULL,
"department" TEXT NOT NULL DEFAULT 'General',
"semester" INTEGER NOT NULL DEFAULT 1,
"visibility" TEXT NOT NULL DEFAULT 'Internal',
"fileType" TEXT NOT NULL DEFAULT 'pdf',
"fileName" TEXT,
"fileData" TEXT,
"uploaderId" TEXT NOT NULL,
"uploaderName" TEXT NOT NULL,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- ModerationLog Table: Administrative Audit Trail
CREATE TABLE "ModerationLog" (
"id" TEXT NOT NULL PRIMARY KEY,
"actor" TEXT NOT NULL,
"target" TEXT NOT NULL,
"result" TEXT NOT NULL,
"reason" TEXT NOT NULL DEFAULT '',
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX "ModerationLog_createdAt_idx" ON "ModerationLog"("createdAt");
-- BugReport Table: Client Crash Telemetry
CREATE TABLE "BugReport" (
"id" TEXT NOT NULL PRIMARY KEY,
"title" TEXT NOT NULL,
"description" TEXT NOT NULL,
"errorStack" TEXT,
"pageUrl" TEXT,
"category" TEXT NOT NULL DEFAULT 'general',
"status" TEXT NOT NULL DEFAULT 'Open',
"severity" TEXT NOT NULL DEFAULT 'Medium',
"deviceInfo" TEXT,
"userEmail" TEXT,
"userName" TEXT,
"userRole" TEXT,
"adminNotes" TEXT,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL
);
CREATE INDEX "BugReport_status_idx" ON "BugReport"("status");
CREATE INDEX "BugReport_createdAt_idx" ON "BugReport"("createdAt");
Chapter: Appendix C: RESTful API Endpoint Catalogue
This appendix provides the complete endpoint directory for all 18 route handlers implemented in src/app/api/.
| Endpoint Path | Method | Auth Level | Role Required | Summary & Payload Schema | Status Codes |
|---|---|---|---|---|---|
/api/auth/register |
POST | Public | None | Ingests { name, email, password, rollNumber, department, idCard }. Hashes password with SHA-256; marks status: "Pending". | 200, 400 |
| /api/auth/login | POST | Public | None | Authenticates { email, password } against database digest; establishes session. | 200, 401 |
| /api/auth/logout | POST | Session | Any | Invalidates active user session cookie. | 200 |
| /api/auth/me | GET | Session | Any | Returns current user profile, role, and approval status. | 200, 401 |
| /api/auth/firebase-login | POST | Public | None | Verifies external Firebase ID token for Google OAuth. | 200, 400 |
| /api/courses | GET | Public | None | Lists all academic programs with batch years, colors, and student leaf counts. | 200 |
| /api/courses | POST | Session | Admin | Creates a new course branch: { name, batchYear, color, department }. | 201, 403 |
| /api/courses/[id] | PUT | Session | Admin | Updates program details or branch color. | 200, 404 |
| /api/courses/[id] | DELETE| Session | Admin | Deletes course and cascades deletion to all enrolled student leaves. | 200, 404 |
| /api/students | GET | Public | None | Returns student roster mapped to 3D tree foliage leaves. | 200 |
| /api/students | POST | Session | Admin | Enrolls a student: { name, rollNo, courseId }. | 201, 400 |
| /api/students/[id] | DELETE| Session | Admin | Removes an individual student leaf from a course branch. | 200, 404 |
| /api/students/sample | POST | Session | Demo / Admin | Spawns 10 sample student leaves for dynamic procedural tree demo. | 200 |
| /api/notes | GET | Session | Active User | Returns notes filtered by ?department= and ?semester=. | 200 |
| /api/notes | POST | Session | Active User | Ingests study material: { title, course, semester, fileData, fileType }. | 201, 400 |
| /api/public-notes | GET | Public | None | Returns notes flagged with visibility: "Public". | 200 |
| /api/announcements | GET | Session | Active User | Returns notices filtered by user role (audience). | 200 |
| /api/announcements | POST | Session | Staff/Admin | Broadcasts notice: { title, body, audience: "All"\|"Students"\|"Teachers" }. | 201, 403 |
| /api/announcements/[id]/comments | GET | Session | Active User | Returns threaded inquiry comments for announcement [id]. | 200 |
| /api/announcements/[id]/comments | POST | Session | Active User | Posts comment: { body, authorName, authorRole }. | 201, 400 |
| /api/admin/approvals | GET | Session | Admin | Lists all users where status === "Pending". | 200, 403 |
| /api/admin/approvals | POST | Session | Admin | Executes { userId, action: "Approve"\|"Reject", reason }; writes ModerationLog. | 200, 403 |
| /api/admin/enquiries | GET | Session | Admin | Lists student appeal enquiries for deactivated accounts. | 200, 403 |
| /api/admin/enquiries/restore | POST | Session | Admin | Restores a deactivated account from DeletedAccount back to User. | 200, 404 |
| /api/connect | GET | Public | None | Returns executive broadcasts from Principal and HODs. | 200 |
| /api/bug-reports | POST | Public | None | Captures exception telemetry: { title, description, errorStack, pageUrl }. | 201 |
| /api/bug-reports | GET | Session | Admin | Lists crash reports sorted by severity for administrative triage. | 200, 403 |
| /api/users | GET | Session | Active User | Searchable member directory respecting hideEmail privacy flag. | 200 |
| /api/profile | PUT | Session | Active User | Updates user profile: { bio, avatar, hideEmail, joinYear }. | 200 |