# Community App Ecosystem — Comprehensive Technical Documentation

Welcome to the **Community App Ecosystem** documentation. This repository contains a full-stack community management platform, Progressive Web Application (PWA), real-time Socket.io discussion forum, Web Push notification server, Events management module, and React Native mobile client application.

---

## 1. System Architecture & Overview

The ecosystem comprises two main sub-systems:
1. **Admin Dashboard, Web Push, Events & Discussion Server (`/Admin`)**: Native Python backend providing dual HTTP/HTTPS protocols, SQLite3 database, thread-safe atomic JSON data store, Web Push VAPID alerts, Socket.io real-time WebSocket forum, and Vanilla JS SPA frontend. Zero Node.js runtime dependency.
2. **Mobile Client Application (`/src`)**: React Native application providing native notification handling and member screens.

```
                               ┌──────────────────────────────────────────┐
                               │          Google FCM / VAPID Push         │
                               └────────────────────▲─────────────────────┘
                                                    │
┌─────────────────────────┐                         │                         ┌─────────────────────────┐
│   Admin PWA Frontend    ├─────────────────────────┼────────────────────────►│  Python Backend Server  │
│  (Vanilla HTML/CSS/JS)  │◄════════════════════════╪════════════════════════►│  (HTTP:8080/HTTPS:8443)│
└─────────────────────────┘      Socket.io WebSockets │                         └────────────┬────────────┘
                                                    │                                      │
┌─────────────────────────┐                         │                                      ▼
│ React Native Mobile App │─────────────────────────┘                         ┌─────────────────────────┐
│      (iOS / Android)    │                                                   │ SQLite3 DB & JSON Store │
└─────────────────────────┘                                                   └─────────────────────────┘
```

---

## 2. Technology Stack

### Backend & Server Infrastructure (`/Admin`)
- **Core Runtime**: Python 3.10+ utilizing ASGI / Uvicorn and Starlette (Dual-protocol server running on ports `8080` for HTTP and `8443` for HTTPS with SSL TLS `cert.pem` & `key.pem`).
- **Real-Time WebSockets Engine**: `python-socketio` for live multi-user discussions, comment threads, topic likes, and @-mention searches.
- **Push Notification Engine**: `pywebpush` library using VAPID (Voluntary Application Server Identification) protocol integrated with Google Firebase Cloud Messaging (FCM).
- **Database & Data Storage**:
  - **SQLite3 (`sqlite3`)**: Relational database (`community.db`) storing member application records, topics, and threaded comments.
  - **JSON File DataStore (`data_store.py`)**: Atomic file-backed persistent storage (`data/members_store.json`, `data/events_store.json`, `data/notifications_store.json`, `data/audit_log.json`, `subscriptions.json`) with in-memory caching and lock-free temp file writes.
- **Role-Based Access Control**: `role_manager.py` with authoritative server-side role resolution from `user_roles.json`.

### Frontend Web Platform (`/Admin`)
- **Core Framework**: Vanilla HTML5 Single Page Application (SPA) with view routing, zero external framework overhead for ultra-fast performance.
- **Styling & UI**: Custom CSS3 design system using HSL color tokens, dark mode UI theme (`#141416` base), glassmorphism, Plus Jakarta Sans typography, and flex/grid responsive layouts.
- **Service Worker (`sw.js`)**: Offline caching, PWA installation lifecycle handling, and OS-level Push Event listener.
- **Security Protections**: HTML entity escaping (`escapeHtml`) on all user inputs (preventing XSS) and path traversal protection on static file resolution.

### Mobile Client Application (`/src`)
- **Framework**: React Native.
- **State Management**: Reactive Singleton Observer store (`notificationHandler.js`).
- **Styling**: React Native `StyleSheet` API.

---

## 3. Completed Modules & Features

### ✅ Module A: Authentication & Membership System (`/Admin`)
- **Tabbed Auth Interface (`.auth-card`)**:
  1. **Member Login**: Phone number & password authentication for approved community members (`POST /api/members/login-check`).
  2. **Admin Login**: Administrator credentials sign-in (`POST /api/admin/login`).
  3. **Sign Up / Register**: Public registration application form (`POST /api/member/register`).
- **Profile Photo Canvas Processing**: Client-side canvas downsampling (max 400px dimension) with Base64 encoding and server storage under `/uploads/`.
- **Application Status Tracker (`#application-status`)**: Real-time status lookup (`PENDING`, `ACCEPTED`, `REJECTED`, `SUSPENDED`) by phone number or email.

### ✅ Module B: Administrator Dashboard & Governance (`/Admin`)
- **Pending Member Requests (`#admin-member-requests`)**: Real-time queue displaying applications awaiting review.
- **Member Inspector (`#admin-member-details`)**: Deep inspection view displaying profile avatars, reference contact details, registration timestamps, and contact links.
- **Soft Color Action Buttons System**:
  - **Approve / Reactivate (`.btn-approve`)**: Soft Emerald button.
  - **Reject Request (`.btn-reject`)**: Soft Rose button.
  - **Suspend Member (`.btn-suspend`)**: Soft Amber button.
  - **Delete Member Permanently (`.btn-delete`)**: Soft Crimson button.
- **A-Z Community Member Directory (`#admin-member-directory`)**: Full directory with instant multi-field search across names, phone numbers, and companies.

### ✅ Module C: Events Management Module (`/Admin/events.js`)
- **Community Events Grid**: Responsive cards grid displaying upcoming events, dates, times, locations, and coordinator contacts.
- **Admin 3-Column Event Creator/Editor (`#events-screen-form`)**:
  - **Left Column**: Main Event Banner upload dropzone & 4-image Attachment Grid with upload/remove buttons.
  - **Middle Column**: Title, Description, Coordinator, Contact Number, Date, Time, Location, and Google Maps URL fields with red dot indicators.
  - **Right Column**: Members Invite Checklist with quick search filter and "Select All / Deselect All" toggle.
- **Access Control**: `+ ADD EVENT`, Edit Event, and Delete Event buttons are restricted strictly to Administrator users.
- **Push Notification Integration**: Creating an event automatically triggers a Web Push notification (`EVENT_REMINDER`) to all target members.

### ✅ Module D: Socket.io Real-Time Discussion Forum (`/Admin/discussion.js`)
- **Category Channels**: Organized into *Economics & Finance*, *Current Affairs*, *Announcements*, and *General Discussion*.
- **Admin Topic Controls**:
  - **`+ ADD TOPIC` Header Action & FAB**: Prominent `+ ADD TOPIC` button on Discussion header and floating FAB enabled for Admin users.
  - **Admin Delete Topic**: Red `Delete` action button on topic cards and inside topic detail view allowing admins to purge topics in real time.
- **Topic Likes & Real-Time Sync**: Real-time Socket.io topic likes sync across list grid and detail views with red heart fill and scaling animation.
- **Threaded Comments & Audio Replies**: Support for nested replies, voice messages via MediaRecorder API, image file attachments, emoji picker, and `@` mention autocomplete.

### ✅ Module E: Automated & Custom Push Notification Engine (`/Admin/notifications.js`)
- **Automated System Event Notifications**:
  - **New Member Joined**: Automatically broadcasts a push notification (`MEMBER_JOINED`) when a member application is approved, plus a targeted `MEMBERSHIP_APPROVED` alert.
  - **New Event Posted**: Broadcasts `EVENT_REMINDER` to invited or all community members.
  - **New Discussion Topic**: Broadcasts `NEW_DISCUSSION_TOPIC` when a topic is created.
  - **New Message / Comment**: Broadcasts `NEW_DISCUSSION_COMMENT` with real-time text snippet.
- **Admin Custom Notification Sender**: Admin interface to send custom push notifications to *All Members*, *Admins Only*, or *Custom Selected Members* (via multi-select checklist).

---

## 4. Pending / Planned Upgrades (To Do Later)

| Feature / Upgrade | Status | Priority | Description |
| :--- | :---: | :---: | :--- |
| **Password Hashing (`bcrypt` / `argon2`)** | ⏳ Pending | Medium | Migrate plain-text database passwords to secure `bcrypt` hashes. |
| **Signed JWT Tokens** | ⏳ Pending | Medium | Replace timestamp-based session tokens with cryptographically signed JSON Web Tokens (JWT) or HTTP-Only Cookies. |
| **Login Rate Limiting** | ⏳ Pending | Medium | Add IP/Account rate-limiting on login endpoints to prevent brute-force guessing attacks. |

---

## 5. API Endpoints Directory

| Endpoint | Method | Auth Guard | Description |
| :--- | :---: | :---: | :--- |
| `/api/vapid-key` | `GET` | Public | Returns the public VAPID key for Web Push manager. |
| `/api/subscribe` | `POST` | Public | Registers a device browser push subscription. |
| `/api/send-push` | `POST` | Public | Dispatches web push payload via Google FCM VAPID. |
| `/api/member/register` | `POST` | Public | Submits new registration application with photo. |
| `/api/member/application-status` | `GET/POST` | Public | Retrieves application status for a contact number. |
| `/api/members/login-check` | `POST` | Public | Validates member credentials and approval status. |
| `/api/admin/login` | `POST` | Public | Authenticates administrator login. |
| `/api/events` | `GET` | Public | Fetches list of published community events. |
| `/api/events/:id` | `GET` | Public | Retrieves detailed event information. |
| `/api/admin/events` | `POST` | Admin | Admin creates a new event with attachments & member checklist. |
| `/api/admin/events/update` | `POST/PATCH` | Admin | Admin updates existing event details. |
| `/api/admin/events/delete` | `POST/DELETE` | Admin | Admin deletes an event record. |
| `/api/admin/send-custom-notification` | `POST` | Admin | Admin sends custom push notification to all or selected members. |
| `/api/admin/requests` | `GET` | Admin | Fetches list of pending member applications. |
| `/api/admin/requests/decision` | `POST/PATCH` | Admin | Accepts or rejects pending member application. |
| `/api/admin/members` | `GET` | Admin | Retrieves complete community directory. |
| `/api/admin/members/status` | `POST/PATCH` | Admin | Suspends or reactivates community member. |
| `/api/admin/members/delete` | `POST/DELETE` | Admin | Permanently deletes member record and uploaded media. |
| `/api/admin/counts` | `GET` | Admin | Retrieves application and membership count statistics. |

---

## 6. Execution & Local Server
 
### Running the Server Locally
1. Using the Windows Startup Script:
   ```cmd
   run_communityhub.bat
   ```
   Or navigate to `Admin` and run:
   ```cmd
   cd Admin
   run_communityhub.bat
   ```

2. Manual Startup via Python:
   ```bash
   pip install -r Admin/requirements.txt
   python -m Admin.server
   ```

3. Running Automated Tests:
   ```bash
   pytest Admin/tests -v
   ```

### Accessing the Web Application
- 🔒 **HTTPS (Secure Context required for PWA & Web Push)**: [https://localhost:8443](https://localhost:8443)
- 🌐 **HTTP Fallback**: [http://localhost:8080](http://localhost:8080)

---

*Documentation updated & maintained for CommunityApp Project Ecosystem.*
