Skip to content

febriaricandra/php-router-weather

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Campus Air Quality Monitoring System

πŸ“ Struktur Folder

campus-air-quality/
β”œβ”€β”€ config/
β”‚   β”œβ”€β”€ database.php
β”‚   β”œβ”€β”€ env.php
β”‚   └── constants.php
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ Core/
β”‚   β”‚   β”œβ”€β”€ Database.php
β”‚   β”‚   β”œβ”€β”€ Router.php
β”‚   β”‚   └── Session.php
β”‚   β”œβ”€β”€ Models/
β”‚   β”‚   β”œβ”€β”€ User.php
β”‚   β”‚   β”œβ”€β”€ AirQuality.php
β”‚   β”‚   β”œβ”€β”€ Location.php
β”‚   β”‚   β”œβ”€β”€ Notification.php
β”‚   β”‚   └── Alert.php
β”‚   β”œβ”€β”€ Controllers/
β”‚   β”‚   β”œβ”€β”€ AuthController.php
β”‚   β”‚   β”œβ”€β”€ DashboardController.php
β”‚   β”‚   β”œβ”€β”€ AirQualityController.php
β”‚   β”‚   β”œβ”€β”€ LocationController.php
β”‚   β”‚   β”œβ”€β”€ UserController.php
β”‚   β”‚   β”œβ”€β”€ AnalyticsController.php
β”‚   β”‚   β”œβ”€β”€ NotificationController.php
β”‚   β”‚   └── AlertController.php
β”‚   β”œβ”€β”€ Services/
β”‚   β”‚   β”œβ”€β”€ ApiClient.php
β”‚   β”‚   β”œβ”€β”€ NinjasClient.php
β”‚   β”‚   β”œβ”€β”€ AnalyticsService.php
β”‚   β”‚   β”œβ”€β”€ CacheService.php
β”‚   β”‚   β”œβ”€β”€ NotificationService.php
β”‚   β”‚   └── WebPushService.php
β”‚   └── Helpers/
β”‚       β”œβ”€β”€ functions.php
β”‚       └── validator.php
β”œβ”€β”€ public/
β”‚   β”œβ”€β”€ index.php
β”‚   β”œβ”€β”€ assets/
β”‚   β”‚   β”œβ”€β”€ css/
β”‚   β”‚   β”œβ”€β”€ js/
β”‚   β”‚   └── images/
β”‚   β”œβ”€β”€ service-worker.js
β”‚   └── .htaccess
β”œβ”€β”€ views/
β”‚   β”œβ”€β”€ layouts/
β”‚   β”‚   └── main.php
β”‚   β”œβ”€β”€ auth/
β”‚   β”‚   β”œβ”€β”€ login.php
β”‚   β”‚   └── register.php
β”‚   β”œβ”€β”€ dashboard/
β”‚   β”‚   └── index.php
β”‚   β”œβ”€β”€ air-quality/
β”‚   β”‚   └── index.php
β”‚   β”œβ”€β”€ locations/
β”‚   β”‚   β”œβ”€β”€ index.php
β”‚   β”‚   β”œβ”€β”€ create.php
β”‚   β”‚   └── edit.php
β”‚   β”œβ”€β”€ users/
β”‚   β”‚   β”œβ”€β”€ index.php
β”‚   β”‚   β”œβ”€β”€ create.php
β”‚   β”‚   └── edit.php
β”‚   β”œβ”€β”€ alerts/
β”‚   β”‚   β”œβ”€β”€ index.php
β”‚   β”‚   β”œβ”€β”€ create.php
β”‚   β”‚   └── edit.php
β”‚   β”œβ”€β”€ notifications/
β”‚   β”‚   └── index.php
β”‚   └── analytics/
β”‚       └── index.php
β”œβ”€β”€ database/
β”‚   β”œβ”€β”€ migrations/
β”‚   β”‚   └── schema.sql
β”‚   └── seeders/
β”‚       β”œβ”€β”€ DatabaseSeeder.php
β”‚       └── run-seeder.php
β”œβ”€β”€ storage/
β”‚   β”œβ”€β”€ cache/
β”‚   └── logs/
β”œβ”€β”€ .env.example
β”œβ”€β”€ .gitignore
β”œβ”€β”€ composer.json
β”œβ”€β”€ generate-vapid.php
└── README.md

πŸ—„οΈ Database Schema

Tabel: users

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(100) UNIQUE NOT NULL,
    email VARCHAR(150) UNIQUE NOT NULL,
    password VARCHAR(255),
    full_name VARCHAR(200),
    role ENUM('admin', 'staff', 'student') DEFAULT 'student',
    google_id VARCHAR(255) UNIQUE,
    avatar VARCHAR(255),
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

Tabel: locations

CREATE TABLE locations (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(200) NOT NULL,
    description TEXT,
    latitude DECIMAL(10, 8) NOT NULL,
    longitude DECIMAL(11, 8) NOT NULL,
    building VARCHAR(100),
    floor VARCHAR(50),
    is_active BOOLEAN DEFAULT TRUE,
    created_by INT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
);

Tabel: air_quality_records

CREATE TABLE air_quality_records (
    id INT AUTO_INCREMENT PRIMARY KEY,
    location_id INT NOT NULL,
    aqi INT NOT NULL,
    pm25 DECIMAL(10, 2),
    pm10 DECIMAL(10, 2),
    o3 DECIMAL(10, 2),
    no2 DECIMAL(10, 2),
    so2 DECIMAL(10, 2),
    co DECIMAL(10, 2),
    temperature DECIMAL(5, 2),
    humidity DECIMAL(5, 2),
    status ENUM('good', 'moderate', 'unhealthy_sensitive', 'unhealthy', 'very_unhealthy', 'hazardous'),
    api_source VARCHAR(50),
    recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (location_id) REFERENCES locations(id) ON DELETE CASCADE,
    INDEX idx_location_time (location_id, recorded_at)
);

Tabel: alerts

CREATE TABLE alerts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    location_id INT,
    alert_type ENUM('aqi_threshold', 'pm25_threshold', 'location_specific'),
    threshold_value INT,
    is_active BOOLEAN DEFAULT TRUE,
    notify_email BOOLEAN DEFAULT TRUE,
    notify_push BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (location_id) REFERENCES locations(id) ON DELETE SET NULL
);

Tabel: notifications

CREATE TABLE notifications (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    title VARCHAR(255) NOT NULL,
    message TEXT NOT NULL,
    type ENUM('email', 'push', 'both') DEFAULT 'push',
    status ENUM('pending', 'sent', 'failed') DEFAULT 'pending',
    air_quality_record_id INT,
    sent_at TIMESTAMP NULL,
    error_message TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (air_quality_record_id) REFERENCES air_quality_records(id) ON DELETE SET NULL
);

Tabel: api_cache

CREATE TABLE api_cache (
    id INT AUTO_INCREMENT PRIMARY KEY,
    cache_key VARCHAR(255) UNIQUE NOT NULL,
    cache_value TEXT NOT NULL,
    api_source VARCHAR(50),
    expires_at TIMESTAMP NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_key_expires (cache_key, expires_at)
);

Tabel: push_subscriptions

CREATE TABLE push_subscriptions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    endpoint TEXT NOT NULL,
    p256dh_key TEXT NOT NULL,
    auth_token TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

πŸ”‘ File .env.example

# Database
DB_HOST=localhost
DB_NAME=campus_air_quality
DB_USER=root
DB_PASS=

# API Keys (Hanya API Ninjas yang digunakan)
NINJAS_API_KEY=your_ninjas_key_here

# Google OAuth (Optional)
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
GOOGLE_REDIRECT_URI=http://localhost/campus-air-quality/public/auth/google-callback

# Web Push VAPID
VAPID_PUBLIC_KEY=your_vapid_public_key
VAPID_PRIVATE_KEY=your_vapid_private_key
VAPID_SUBJECT=mailto:admin@campus.ac.id

# Email (PHPMailer)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your_email@gmail.com
SMTP_PASS=your_app_password
SMTP_FROM=noreply@campus.ac.id
SMTP_FROM_NAME=Campus Air Quality

# App
APP_URL=http://localhost/campus-air-quality/public
APP_NAME=Campus Air Quality Monitor
TIMEZONE=Asia/Jakarta

# Cache
CACHE_TTL=3600

πŸ“¦ composer.json

{
    "require": {
        "php": ">=7.4",
        "phpmailer/phpmailer": "^6.8",
        "web-token/jwt-framework": "^3.2",
        "minishlink/web-push": "^8.0",
        "vlucas/phpdotenv": "^5.5",
        "guzzlehttp/guzzle": "^7.5"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        },
        "files": [
            "src/Helpers/functions.php"
        ]
    }
}

πŸš€ Fitur Utama

1. Autentikasi

  • Login/Register dengan password hash
  • Google OAuth 2.0
  • Session management
  • Role-based access (admin, staff, student)

2. CRUD Entities

  • Users: Manajemen user (admin/staff only)
  • Locations: Manajemen lokasi monitoring (gedung, lantai, koordinat)
  • Air Quality Records: Data kualitas udara real-time
  • Alerts: Pengaturan notifikasi threshold
  • Notifications: History notifikasi
  • Analytics: Dashboard analitik dengan metrik & rekomendasi

3. Integrasi API Ninjas

  • API Ninjas: Data lengkap kualitas udara (PM2.5, PM10, O3, NO2, SO2, CO)
  • Perhitungan AQI otomatis dari pollutant data
  • Cache response dengan TTL (file & database)
  • API key disimpan aman di .env

4. Notifikasi

  • Web Push dengan Service Worker + VAPID
  • Email fallback (PHPMailer)
  • Log status di tabel notifications

5. Grafik & Visualisasi

  • Time-series: Tren AQI 24 jam/7 hari/30 hari
  • Bar chart: Perbandingan kualitas per lokasi
  • Pie chart: Distribusi status udara (good/moderate/unhealthy)
  • Heatmap: PM2.5 per gedung

6. Analytics Dashboard

  • Overall Statistics: AQI rata-rata, PM2.5, PM10, dan pollutant lainnya
  • Status Distribution: Pie chart distribusi kualitas udara
  • Trend Analysis: Line chart tren AQI harian dengan PM2.5
  • Location Analytics: Bar chart perbandingan AQI per lokasi
  • Peak Hours Analysis: Identifikasi jam-jam dengan polusi tertinggi
  • Pollutant Correlation: Statistik detail setiap pollutant (avg, min, max, std dev)
  • AI Recommendations: Rekomendasi otomatis berdasarkan data analitik
  • Export to CSV: Download laporan lengkap dalam format CSV
  • Period Comparison: Bandingkan perubahan kualitas udara antar periode

7. Dashboard Features

  • Real-time AQI per lokasi
  • Alert system otomatis
  • Historical data analysis
  • Export data (CSV/PDF)
  • Role-Based Access Control:
    • Admin: Full access ke semua fitur
    • Staff: Akses Locations & Users (read-only untuk Users)
    • Student: Hanya Dashboard, Air Quality, Alerts, Notifications

🎨 Frontend Stack

  • CSS Framework: Bootstrap 5 / Tailwind CSS
  • Chart Library: Chart.js
  • Icons: Font Awesome / Feather Icons
  • Maps: Leaflet.js (untuk peta lokasi)

πŸ“ Instalasi & Setup

A. Setup di Windows dengan XAMPP (Recommended untuk Windows)

1. Install XAMPP

# Download XAMPP dari: https://www.apachefriends.org/
# Install dengan komponen:
# - Apache
# - MySQL
# - PHP (minimal 7.4)
# - phpMyAdmin

2. Extract Project ke XAMPP

# Copy folder project ke:
C:\xampp\htdocs\campus-air-quality

# Struktur folder:
C:\xampp\htdocs\campus-air-quality\
β”œβ”€β”€ config\
β”œβ”€β”€ src\
β”œβ”€β”€ public\
β”œβ”€β”€ views\
β”œβ”€β”€ database\
└── ...

3. Install Composer (Jika Belum Ada)

# Download Composer untuk Windows:
https://getcomposer.org/Composer-Setup.exe

# Install dan restart terminal
# Verifikasi instalasi:
composer --version

4. Install Dependencies

# Buka Command Prompt atau PowerShell
# Navigate ke folder project:
cd C:\xampp\htdocs\campus-air-quality

# Install dependencies:
composer install

5. Setup Database MySQL

# 1. Start XAMPP Control Panel
# 2. Start Apache dan MySQL
# 3. Buka browser: http://localhost/phpmyadmin

# 4. Create Database:
#    - Klik "New" di sidebar
#    - Database name: campus_air_quality
#    - Collation: utf8mb4_general_ci
#    - Klik "Create"

# 5. Import Schema:
#    - Klik database "campus_air_quality"
#    - Tab "Import"
#    - Choose file: C:\xampp\htdocs\campus-air-quality\database\migrations\schema.sql
#    - Klik "Go"

6. Run PHP Seeder

# Buka Command Prompt di folder project:
cd C:\xampp\htdocs\campus-air-quality

# Run seeder untuk generate data:
php database\seeders\run-seeder.php

# Output:
# βœ… Seeding users... Done! (5 users created)
# βœ… Seeding locations... Done! (4 locations created)
# βœ… Seeding air quality records... Done! (XX records created)
# βœ… Database seeded successfully!

7. Konfigurasi Environment

# 1. Copy .env.example ke .env:
copy .env.example .env

# 2. Edit .env dengan Notepad atau VS Code:
# Minimal configuration untuk XAMPP:

DB_HOST=localhost
DB_NAME=campus_air_quality
DB_USER=root
DB_PASS=
DB_PORT=3306

NINJAS_API_KEY=your_ninjas_key_here

APP_URL=http://localhost/campus-air-quality/public
APP_NAME=Campus Air Quality Monitor
TIMEZONE=Asia/Jakarta

CACHE_TTL=3600

8. Setup .htaccess untuk Apache

# File sudah ada di public/.htaccess
# Pastikan isinya:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

9. Enable mod_rewrite di Apache

# 1. Buka XAMPP Control Panel
# 2. Apache β†’ Config β†’ httpd.conf
# 3. Cari baris: #LoadModule rewrite_module modules/mod_rewrite.so
# 4. Hapus tanda # (uncomment)
# 5. Save file
# 6. Restart Apache di XAMPP Control Panel

10. Generate VAPID Keys (untuk Web Push)

# Di Command Prompt:
cd C:\xampp\htdocs\campus-air-quality
php generate-vapid.php

# Keys akan otomatis di-update ke .env

11. Akses Aplikasi

URL: http://localhost/campus-air-quality/public

Demo Login:
- Admin: admin@campus.ac.id / password123
- Staff: staff1@campus.ac.id / password123  
- Student: student1@campus.ac.id / password123

12. Troubleshooting Windows/XAMPP

Error: "Internal Server Error"

# 1. Check Apache error log:
C:\xampp\apache\logs\error.log

# 2. Pastikan mod_rewrite enabled
# 3. Check .htaccess di folder public/

Error: "Database connection failed"

# 1. Pastikan MySQL running di XAMPP
# 2. Check .env:
DB_HOST=localhost  # Bukan 127.0.0.1
DB_PORT=3306       # Default MySQL port
DB_USER=root
DB_PASS=           # Kosong untuk default XAMPP

Error: "Composer command not found"

# 1. Install Composer dari https://getcomposer.org/
# 2. Restart terminal/command prompt
# 3. Verifikasi: composer --version

Error: "Class not found"

# Run composer autoload:
cd C:\xampp\htdocs\campus-air-quality
composer dump-autoload

Port 80 atau 3306 sudah digunakan

# Apache Port (80):
# - XAMPP Control Panel β†’ Apache Config β†’ httpd.conf
# - Ubah: Listen 80 β†’ Listen 8080
# - Restart Apache
# - Akses: http://localhost:8080/campus-air-quality/public

# MySQL Port (3306):
# - XAMPP Control Panel β†’ MySQL Config β†’ my.ini
# - Ubah: port=3306 β†’ port=3307
# - Update .env: DB_PORT=3307
# - Restart MySQL

B. Setup di Linux/Mac (Alternative)

1. Clone atau Download Project

cd /home/febriari/Documents/work/campus-air-quality

2. Install Dependencies

composer install

3. Setup Database

# Buat database MySQL
mysql -u root -p
CREATE DATABASE campus_air_quality;
exit;

# Import schema
mysql -u root -p campus_air_quality < database/migrations/schema.sql

# Run PHP Seeder (Recommended - Dynamic password generation)
php database/run-seeder.php

# Atau gunakan static SQL seed (Alternative)
mysql -u root -p campus_air_quality < database/seeds/seed_data.sql

Keunggulan PHP Seeder:

  • βœ… Password di-generate dinamis dengan password_hash() (bukan static)
  • βœ… Data lebih realistis dengan randomization
  • βœ… Generate data 7 hari terakhir otomatis
  • βœ… Mudah di-customize sesuai kebutuhan

4. Konfigurasi Environment

# Copy .env.example ke .env
cp .env.example .env

# Edit .env dan isi konfigurasi:
# - Database credentials
# - API Keys (AQICN, AirVisual, API Ninjas)
# - Google OAuth (optional)
# - SMTP untuk email (optional)

5. Generate VAPID Keys untuk Web Push

# Gunakan script PHP built-in
php generate-vapid.php

# Script akan otomatis:
# 1. Generate VAPID public & private keys
# 2. Update file .env dengan keys baru
# 3. Tampilkan keys untuk verifikasi

6. Setup Web Server

Untuk Apache:

<VirtualHost *:80>
    DocumentRoot "/home/febriari/Documents/work/campus-air-quality/public"
    ServerName campus-air.local
    
    <Directory "/home/febriari/Documents/work/campus-air-quality/public">
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Untuk PHP Built-in Server (Development):

cd public
php -S localhost:8000

7. Akses Aplikasi

URL: http://localhost:8000
atau http://campus-air.local (jika pakai Apache)

Demo Login:
- Admin: admin@campus.ac.id / password123
- Staff: staff1@campus.ac.id / password123  
- Student: student1@campus.ac.id / password123

πŸ”‘ Mendapatkan API Key

API Ninjas (Primary API)

  1. Daftar di: https://api-ninjas.com/
  2. Free tier: 50,000 requests/bulan
  3. Paste key ke .env: NINJAS_API_KEY=your_key
  4. API ini menyediakan data lengkap:
    • PM2.5, PM10 (Particulate Matter)
    • O3 (Ozone)
    • NO2 (Nitrogen Dioxide)
    • SO2 (Sulfur Dioxide)
    • CO (Carbon Monoxide)
    • AQI dihitung otomatis dari pollutant data

πŸ“Š Fitur yang Sudah Diimplementasikan

βœ… Teknologi Inti

  • βœ… PHP Native (Tanpa Framework)
  • βœ… OOP dengan Class & Function
  • βœ… MySQL Database
  • βœ… Bootstrap 5 untuk Frontend
  • βœ… Composer untuk library utilities

βœ… Autentikasi & Otorisasi

  • βœ… Login/Logout/Register
  • βœ… Password hashing (password_hash & password_verify)
  • βœ… Google OAuth 2.0 (Optional)
  • βœ… Session management
  • βœ… Role-based access (admin, staff, student)

βœ… Database & CRUD

  • βœ… 7 Tabel domain (users, locations, air_quality_records, alerts, notifications, api_cache, push_subscriptions)
  • βœ… Dynamic PHP Seeder dengan password_hash()
  • βœ… 3 Entitas CRUD Penuh:
    1. Locations: Create, Read, Update, Delete (Admin/Staff only)
    2. Alerts: Create, Read, Update, Delete
    3. Users: Create, Read, Update, Delete (Admin only untuk write, Staff read-only)
  • βœ… Relasi foreign key & index
  • βœ… Role-based access control pada semua CRUD

βœ… Integrasi API

  • βœ… API Ninjas: Data kualitas udara lengkap (PM2.5, PM10, O3, NO2, SO2, CO)
  • βœ… Perhitungan AQI otomatis dari pollutant data
  • βœ… API key disimpan di .env
  • βœ… Cache response (file & database) dengan TTL
  • βœ… Error handling & fallback mechanism

βœ… Notifikasi

  • βœ… Web Push (Service Worker + VAPID)
  • βœ… Email Fallback (PHPMailer)
  • βœ… Log ke tabel notifications dengan status (sent/failed)
  • βœ… Alert system otomatis berdasarkan threshold

βœ… Grafik (Chart.js)

  • βœ… Time-series: Tren AQI 7/24 jam
  • βœ… Bar Chart: Perbandingan kualitas per lokasi
  • βœ… Pie Chart: Distribusi status udara
  • βœ… Data grafik dari database sendiri

βœ… User Management

  • βœ… Admin: Full CRUD user management
  • βœ… Staff: View-only user list
  • βœ… User List: Tabel dengan role badges & status
  • βœ… Add/Edit User: Form dengan role selector
  • βœ… Toggle Status: Activate/Deactivate user
  • βœ… Prevent Self-Delete: Admin tidak bisa hapus diri sendiri
  • βœ… Statistics Dashboard: User count per role

βœ… Analytics & Reporting

  • βœ… AnalyticsService: Service untuk perhitungan metrik & statistik
  • βœ… Overall Statistics: AQI, PM2.5, PM10, dan pollutant metrics
  • βœ… Status Distribution: Pie chart distribusi kualitas udara
  • βœ… Trend Analysis: Line chart tren harian (AQI & PM2.5)
  • βœ… Location Analytics: Perbandingan kualitas per lokasi
  • βœ… Peak Hours Analysis: Identifikasi jam puncak polusi
  • βœ… Pollutant Statistics: Tabel detail avg/min/max/std dev
  • βœ… AI Recommendations: Rekomendasi otomatis berdasarkan data
  • βœ… Period Comparison: Perbandingan perubahan antar periode
  • βœ… CSV Export: Download laporan lengkap
  • βœ… Multiple Period: Filter 7/14/30 hari

βœ… Security

  • βœ… Password hashing dengan password_hash()
  • βœ… Prepared statements (SQL injection prevention)
  • βœ… CSRF token untuk forms
  • βœ… XSS filtering pada input (htmlspecialchars)
  • βœ… .env tidak di-commit ke repo
  • βœ… Session security (httponly, secure flags)

πŸš€ Cara Menggunakan

Fetch Data dari API

  1. Login ke aplikasi
  2. Klik menu "Air Quality"
  3. Klik tombol "Fetch Data" pada modal
  4. Pilih lokasi dari dropdown
  5. Data akan diambil dari API Ninjas dan tersimpan ke database
  6. Tabel akan menampilkan data dengan kolom:
    • AQI, PM2.5, PM10, O3, NO2, SO2, CO
    • Status (Good/Moderate/Unhealthy)
    • Source (API Ninjas)
    • Recorded At

Setup Alert

  1. Klik menu "Alerts" β†’ "Create Alert"
  2. Pilih tipe alert (AQI Threshold / PM2.5 / Location Specific)
  3. Set threshold value
  4. Pilih notifikasi (Email/Push/Both)
  5. Save

User Management (Admin/Staff only)

  1. Admin:
    • Klik menu "Users" β†’ "Add User"
    • Isi form (username, email, password, role)
    • Klik "Save User"
    • Edit/Delete user dari list
    • Toggle status (Active/Inactive)
  2. Staff:
    • Hanya bisa view user list
    • Tidak ada akses create/edit/delete

Analytics Dashboard

  1. Klik menu "Analytics"
  2. Pilih periode analisis (7/14/30 hari)
  3. Lihat berbagai metrik:
    • Overall Stats: Cards dengan AQI, PM2.5, max AQI, total records
    • Recommendations: Alert box berisi rekomendasi berdasarkan data
    • Status Distribution: Pie chart distribusi kualitas udara
    • Trend Analysis: Line chart tren AQI & PM2.5 harian
    • Location Analytics: Bar chart AQI per lokasi
    • Peak Hours: Bar chart jam-jam dengan polusi tertinggi
    • Pollutant Stats: Tabel detail statistik setiap pollutant
    • Location Details: Tabel lengkap analitik per lokasi
  4. Export laporan dengan klik "Export CSV"

Lihat Grafik

  1. Dashboard menampilkan:
    • Bar chart perbandingan AQI antar lokasi
    • Pie chart distribusi status kualitas udara
    • Real-time AQI cards per lokasi

πŸ“ Struktur Project Final

campus-air-quality/
β”œβ”€β”€ config/           βœ… Database, env, constants
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ Core/        βœ… Database, Router, Session
β”‚   β”œβ”€β”€ Models/      βœ… User, Location, AirQuality, Alert, Notification
β”‚   β”œβ”€β”€ Controllers/ βœ… Auth, Dashboard, Location, Alert, AirQuality, Notification, User, Analytics
β”‚   β”œβ”€β”€ Services/    βœ… API Ninjas Client, Cache, WebPush, Notification, Analytics
β”‚   └── Helpers/     βœ… Helper functions, validator
β”œβ”€β”€ public/          βœ… index.php, .htaccess, service-worker.js, assets
β”œβ”€β”€ views/           βœ… Login, Register, Dashboard, Locations, Users, Alerts, Notifications, Air Quality, Analytics
β”œβ”€β”€ database/        βœ… Schema & dynamic PHP seeder
β”œβ”€β”€ storage/         βœ… Cache & logs
β”œβ”€β”€ .env.example     βœ… Template environment
β”œβ”€β”€ composer.json    βœ… Dependencies
β”œβ”€β”€ generate-vapid.php βœ… VAPID key generator
└── README.md        βœ… Dokumentasi lengkap

Total: 45+ files PHP Native dengan OOP, Role-Based Access Control & Advanced Analytics

🎯 Cara Testing

# 1. Test login dengan berbagai role
URL: /auth/login

Admin:
Email: admin@campus.ac.id
Password: password123
Akses: Full access ke semua menu

Staff:
Email: staff1@campus.ac.id
Password: password123
Akses: Dashboard, Air Quality, Locations, Users (read-only), Alerts, Notifications

Student:
Email: student1@campus.ac.id
Password: password123
Akses: Dashboard, Air Quality, Alerts, Notifications (tidak bisa akses Locations & Users)

# 2. Test CRUD Locations (Admin/Staff only)
- Create: /locations/create
- Edit: /locations/{id}/edit
- Delete: POST /locations/{id}/delete
- Student akan di-redirect ke dashboard jika akses

# 3. Test CRUD Alerts
- Create: /alerts/create
- Edit: /alerts/{id}/edit
- Delete: POST /alerts/{id}/delete

# 4. Test User Management (Admin full, Staff read-only)
- Create: /users/create (Admin only)
- Edit: /users/{id}/edit (Admin only)
- Delete: POST /users/{id}/delete (Admin only)
- List: /users (Admin & Staff)
- Toggle Status: POST /users/{id}/toggle-status (Admin only)

# 5. Test API Integration
- Air Quality β†’ Pilih location β†’ "Fetch Data"
- Lihat data tersimpan di tabel dengan 11 kolom:
  AQI, PM2.5, PM10, O3, NO2, SO2, CO, Status, Source, Recorded At

# 6. Test Grafik
- Dashboard akan otomatis load:
  * Bar Chart (comparison per lokasi)
  * Pie Chart (distribution status)

# 7. Test Role-Based Access
- Login sebagai student β†’ Menu "Locations" & "Users" tidak muncul
- Login sebagai staff β†’ Menu "Users" muncul tapi hanya view
- Login sebagai admin β†’ Full access semua fitur

# 8. Test Analytics Dashboard
- Klik menu "Analytics"
- Pilih periode: 7 hari / 14 hari / 30 hari
- Verifikasi charts: Status Pie, Trend Line, Location Bar, Peak Hours Bar
- Check Recommendations Alert Box
- Verifikasi Pollutant Statistics Table
- Test Export CSV: klik "Export CSV" β†’ file downloaded
- Check Period Comparison: lihat % change (↑ atau ↓)

πŸ“ž Troubleshooting

Error: "Database connection failed"

# Cek config di .env
DB_HOST=localhost
DB_NAME=campus_air_quality
DB_USER=root
DB_PASS=

# Pastikan MySQL running
sudo systemctl start mysql

Error: "Class not found"

# Install composer dependencies
composer install

API tidak ada respon

# Pastikan API keys sudah benar di .env
# Test manual API:
curl "https://api.waqi.info/feed/jakarta/?token=YOUR_TOKEN"

πŸŽ“ Fitur Analytics (Detail)

Metrik yang Dihitung

  1. Overall Statistics:

    • Total records dalam periode
    • Average/Max/Min AQI
    • Average untuk semua pollutants (PM2.5, PM10, O3, NO2, SO2, CO)
  2. Status Distribution:

    • Persentase distribusi kualitas udara
    • Good, Moderate, Unhealthy Sensitive, Unhealthy, Very Unhealthy, Hazardous
  3. Location Analytics:

    • AQI rata-rata per lokasi
    • Jumlah kondisi "unhealthy" per lokasi
    • Identifikasi lokasi yang memerlukan perhatian khusus
  4. Trend Analysis:

    • Tren harian AQI dan PM2.5
    • Record count per hari
    • Visualisasi perubahan kualitas udara
  5. Peak Hours Analysis:

    • Identifikasi jam-jam dengan polusi tertinggi
    • Average AQI per jam
    • Rekomendasi waktu untuk aktivitas outdoor
  6. Pollutant Correlation:

    • Statistik detail: Average, Min, Max, Standard Deviation
    • Untuk semua pollutants: PM2.5, PM10, O3, NO2, SO2, CO
  7. Period Comparison:

    • Perbandingan periode saat ini vs periode sebelumnya
    • Persentase perubahan (improvement/degradation)

AI Recommendations

Sistem akan memberikan rekomendasi otomatis berdasarkan:

  • Level AQI rata-rata (Good/Moderate/Unhealthy)
  • Level PM2.5 (perbandingan dengan standar WHO 15 ΞΌg/mΒ³)
  • Lokasi dengan kualitas udara terburuk
  • Jam puncak polusi
  • Frekuensi data monitoring

Export CSV Format

Laporan CSV mencakup:

  • Header dengan metadata (tanggal generate, periode)
  • Overall Statistics (semua metrik)
  • Status Distribution (count & percentage)
  • Location Analytics (detail per lokasi)
  • Daily Trend (tren harian)
  • Recommendations (semua rekomendasi dengan priority)

πŸ“„ License

MIT License - Bebas digunakan untuk project kampus

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published