feat: realtime notifications, fix broadcasting, add notifications page

- Fix: broadcasting.php config (was missing, broadcast failed)
- Fix: Echo class global scope (window.EchoClass)
- Fix: Nginx WebSocket proxy for Reverb
- Fix: Firewall port 8087 opened
- Fix: Duplicate event listener cleanup
- Fix: Mark as read functionality
- Add: CreateViolationNotification listener
- Add: Notifications index page with pagination
- Add: Timezone Asia/Jakarta support
- Add: Real-time badge across all pages
- Remove: toOthers() so recorder also gets notification
- Update: .env.example with new variables
This commit is contained in:
Novy San87
2026-07-22 08:35:10 +07:00
parent 9670ae06d3
commit 23f124e8d5
13 changed files with 273 additions and 79 deletions
+20 -52
View File
@@ -1,65 +1,33 @@
APP_NAME=Laravel APP_NAME="Aplikasi Ketertiban"
APP_ENV=local APP_ENV=local
APP_KEY= APP_KEY=
APP_DEBUG=true APP_DEBUG=true
APP_TIMEZONE=Asia/Jakarta
APP_URL=http://localhost APP_URL=http://localhost
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database
# PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug LOG_LEVEL=debug
DB_CONNECTION=sqlite DB_CONNECTION=mysql
# DB_HOST=127.0.0.1 DB_HOST=127.0.0.1
# DB_PORT=3306 DB_PORT=3306
# DB_DATABASE=laravel DB_DATABASE=aplikasi_ketertiban
# DB_USERNAME=root DB_USERNAME=root
# DB_PASSWORD= DB_PASSWORD=
SESSION_DRIVER=database BROADCAST_CONNECTION=reverb
SESSION_LIFETIME=120 CACHE_STORE=file
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database QUEUE_CONNECTION=database
SESSION_DRIVER=file
SESSION_LIFETIME=120
CACHE_STORE=database FILESYSTEM_DISK=local
# CACHE_PREFIX=
MEMCACHED_HOST=127.0.0.1 REVERB_APP_ID=
REVERB_APP_KEY=
REVERB_APP_SECRET=
REVERB_HOST=localhost
REVERB_PORT=8080
REVERB_SCHEME=http
REDIS_CLIENT=phpredis VITE_REVERB_APP_KEY="${REVERB_APP_KEY}"
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"
@@ -72,6 +72,15 @@ class DashboardController extends Controller
return response()->json(['success' => true]); return response()->json(['success' => true]);
} }
public function notificationsIndex(Request $request): View
{
$notifications = AppNotification::where('user_id', $request->user()->id)
->latest()
->paginate(20);
return view('notifications.index', compact('notifications'));
}
public function getUnreadCount(Request $request) public function getUnreadCount(Request $request)
{ {
$count = AppNotification::where('user_id', $request->user()->id) $count = AppNotification::where('user_id', $request->user()->id)
@@ -0,0 +1,40 @@
<?php
namespace App\Listeners;
use App\Events\ViolationRecorded;
use App\Models\AppNotification;
use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
class CreateViolationNotification implements ShouldQueue
{
use InteractsWithQueue;
public function handle(ViolationRecorded $event): void
{
$violation = $event->violation;
$data = $event->data;
// Kirim notifikasi ke semua user kecuali pencatat
$users = User::where('is_active', true)
->where('id', '!=', $violation->recorded_by)
->get();
foreach ($users as $user) {
AppNotification::create([
'user_id' => $user->id,
'type' => 'violation',
'title' => 'Pelanggaran Baru: ' . ($data['student_name'] ?? ''),
'body' => ($data['violation_type'] ?? '') . ' (+' . ($data['points'] ?? 0) . ' poin)',
'icon' => 'exclamation-triangle',
'color' => $data['category_color'] ?? '#ef4444',
'action_url' => $data['url'] ?? null,
'is_read' => false,
'violation_id' => $violation->id,
'data' => $data,
]);
}
}
}
+2 -1
View File
@@ -2,6 +2,7 @@
namespace App\Providers; namespace App\Providers;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider class AppServiceProvider extends ServiceProvider
@@ -19,6 +20,6 @@ class AppServiceProvider extends ServiceProvider
*/ */
public function boot(): void public function boot(): void
{ {
// Paginator::defaultView('vendor.pagination.tailwind');
} }
} }
+1 -1
View File
@@ -127,7 +127,7 @@ class ViolationService
} }
// Broadcast via Reverb // Broadcast via Reverb
broadcast(new ViolationRecorded($violation))->toOthers(); broadcast(new ViolationRecorded($violation));
} catch (\Exception $e) { } catch (\Exception $e) {
\Illuminate\Support\Facades\Log::error('Notify realtime failed: ' . $e->getMessage()); \Illuminate\Support\Facades\Log::error('Notify realtime failed: ' . $e->getMessage());
} }
+1 -1
View File
@@ -65,7 +65,7 @@ return [
| |
*/ */
'timezone' => 'UTC', 'timezone' => env('APP_TIMEZONE', 'UTC'),
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
+56
View File
@@ -0,0 +1,56 @@
<?php
return [
'default' => env('BROADCAST_CONNECTION', 'reverb'),
'connections' => [
'reverb' => [
'driver' => 'reverb',
'key' => env('REVERB_APP_KEY'),
'secret' => env('REVERB_APP_SECRET'),
'app_id' => env('REVERB_APP_ID'),
'options' => [
'host' => env('REVERB_HOST', 'localhost'),
'port' => env('REVERB_PORT', 8087),
'scheme' => env('REVERB_SCHEME', 'http'),
'useTLS' => env('REVERB_SCHEME', 'https') === 'https',
],
'client_options' => [
// Guzzle client options
],
],
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'host' => env('PUSHER_HOST') ?: 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com',
'port' => env('PUSHER_PORT', 443),
'scheme' => env('PUSHER_SCHEME', 'https'),
'encrypted' => true,
'useTLS' => env('PUSHER_SCHEME', 'https') === 'https',
],
'client_options' => [],
],
'ably' => [
'driver' => 'ably',
'key' => env('ABLY_KEY'),
],
'log' => [
'driver' => 'log',
],
'null' => [
'driver' => 'null',
],
],
];
+1
View File
@@ -6,6 +6,7 @@ import Echo from 'laravel-echo';
import Pusher from 'pusher-js'; import Pusher from 'pusher-js';
window.Pusher = Pusher; window.Pusher = Pusher;
window.EchoClass = Echo;
// Echo will be initialized when the page has the Reverb config // Echo will be initialized when the page has the Reverb config
// The actual Echo initialization is done conditionally in the layout // The actual Echo initialization is done conditionally in the layout
+1 -1
View File
@@ -3,7 +3,7 @@
@section('title', 'Dashboard') @section('title', 'Dashboard')
@section('content') @section('content')
<div x-data="notifications()"> <div>
<div class="mb-6"> <div class="mb-6">
<h1 class="text-2xl font-bold text-gray-900">Dashboard</h1> <h1 class="text-2xl font-bold text-gray-900">Dashboard</h1>
<p class="text-sm text-gray-500">Ringkasan pelanggaran siswa</p> <p class="text-sm text-gray-500">Ringkasan pelanggaran siswa</p>
+45 -23
View File
@@ -18,7 +18,7 @@
@stack('styles') @stack('styles')
</head> </head>
<body class="h-full antialiased"> <body class="h-full antialiased">
<div x-data="{ sidebarOpen: false, showNotif: false, showUserMenu: false, notifications: [], notifCount: 0 }" class="min-h-screen flex"> <div x-data="notifications()" class="min-h-screen flex">
{{-- Sidebar --}} {{-- Sidebar --}}
<aside :class="sidebarOpen ? 'translate-x-0' : '-translate-x-full'" class="fixed inset-y-0 left-0 z-50 w-64 bg-white border-r border-gray-200 lg:translate-x-0 lg:static lg:inset-auto transition-transform duration-200 ease-in-out flex flex-col"> <aside :class="sidebarOpen ? 'translate-x-0' : '-translate-x-full'" class="fixed inset-y-0 left-0 z-50 w-64 bg-white border-r border-gray-200 lg:translate-x-0 lg:static lg:inset-auto transition-transform duration-200 ease-in-out flex flex-col">
<div class="flex items-start justify-between h-auto px-4 pt-4 pb-3 border-b border-gray-200"> <div class="flex items-start justify-between h-auto px-4 pt-4 pb-3 border-b border-gray-200">
@@ -103,7 +103,7 @@
</div> </div>
<div class="max-h-64 overflow-y-auto"> <div class="max-h-64 overflow-y-auto">
<template x-for="notif in notifications" :key="notif.id"> <template x-for="notif in notifications" :key="notif.id">
<a :href="notif.action_url || '#'" class="block px-4 py-3 hover:bg-gray-50 border-b border-gray-100 last:border-0"> <a :href="notif.action_url || '#'" @click="markAsRead(notif.id)" class="block px-4 py-3 hover:bg-gray-50 border-b border-gray-100 last:border-0">
<div class="flex items-start space-x-3"> <div class="flex items-start space-x-3">
<div :class="'flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center ' + (notif.color ? 'bg-'+notif.color+'-100' : 'bg-blue-100')"> <div :class="'flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center ' + (notif.color ? 'bg-'+notif.color+'-100' : 'bg-blue-100')">
<i class="fa-solid fa-triangle-exclamation"></i> <i class="fa-solid fa-triangle-exclamation"></i>
@@ -119,6 +119,9 @@
Tidak ada notifikasi Tidak ada notifikasi
</div> </div>
</div> </div>
<div class="px-4 py-2 border-t border-gray-100 text-center">
<a href="{{ route('notifications.index') }}" class="text-xs text-blue-600 hover:text-blue-800 font-medium">Tampilkan semua notifikasi</a>
</div>
</div> </div>
</div> </div>
@@ -199,10 +202,25 @@
@stack('scripts') @stack('scripts')
{{-- Reverb Config --}}
<script>
window.__REVERB_CONFIG = {
key: @json(config('reverb.apps.apps.0.key') ?: env('REVERB_APP_KEY')),
host: window.location.hostname,
port: parseInt(window.location.port || '80'),
};
console.log('Reverb config:', window.__REVERB_CONFIG);
</script>
{{-- Reverb + Echo for realtime --}} {{-- Reverb + Echo for realtime --}}
<script> <script>
document.addEventListener('alpine:init', () => { document.addEventListener('alpine:init', () => {
Alpine.data('notifications', () => ({ Alpine.data('notifications', () => ({
showNotif: false,
sidebarOpen: false,
showUserMenu: false,
notifications: [],
notifCount: 0,
init() { init() {
this.fetchCount(); this.fetchCount();
this.fetchNotifications(); this.fetchNotifications();
@@ -223,30 +241,34 @@
this.notifications = []; this.notifications = [];
this.notifCount = 0; this.notifCount = 0;
}, },
markAsRead(id) {
fetch('/notifications/' + id + '/read', { method: 'POST', headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content } });
this.notifications = this.notifications.filter(n => n.id !== id);
if (this.notifCount > 0) this.notifCount--;
},
connectReverb() { connectReverb() {
if (typeof Echo === 'undefined') { if (typeof window.Echo === 'undefined' || window.Echo === null) {
window.Echo = new Echo({ try {
broadcaster: 'reverb', window.Echo = new window.EchoClass({
key: import.meta.env.VITE_REVERB_APP_KEY || '"' + REVERB_APP_KEY + '", broadcaster: 'reverb',
wsHost: import.meta.env.VITE_REVERB_HOST || '"' + REVERB_HOST + '", key: window.__REVERB_CONFIG.key,
wsPort: import.meta.env.VITE_REVERB_PORT ? parseInt(import.meta.env.VITE_REVERB_PORT) : 8080, wsHost: window.__REVERB_CONFIG.host,
wssPort: 443, wsPort: window.__REVERB_CONFIG.port,
forceTLS: false, wssPort: 443,
enabledTransports: ['ws', 'wss'], forceTLS: false,
}); enabledTransports: ['ws', 'wss'],
});
console.log('Echo initialized ✅');
} catch(e) {
console.error('Echo init error:', e);
}
} }
if (typeof Echo !== 'undefined') { if (typeof window.Echo !== 'undefined') {
Echo.channel('violations') window.Echo.channel('violations')
.listen('.violation.recorded', (e) => { .listen('.violation.recorded', (e) => {
this.notifCount++; // Refresh dari database untuk hindari duplikasi
this.notifications.unshift({ this.fetchCount();
id: e.violation?.id || Date.now(), this.fetchNotifications();
title: 'Pelanggaran Baru: ' + (e.data?.student_name || ''),
body: (e.data?.violation_type || '') + ' (+' + (e.data?.points || 0) + ' poin)',
action_url: e.data?.url || '#',
color: (e.data?.category_color || '#ef4444').replace('#', ''),
});
if (this.notifications.length > 20) this.notifications.pop();
}); });
} else { } else {
// Fallback: poll every 30s if Echo not loaded // Fallback: poll every 30s if Echo not loaded
@@ -0,0 +1,45 @@
@extends('layouts.app')
@section('title', 'Semua Notifikasi')
@section('content')
<div>
<div class="mb-6">
<h1 class="text-2xl font-bold text-gray-900">Semua Notifikasi</h1>
<p class="text-sm text-gray-500">Riwayat notifikasi pelanggaran siswa</p>
</div>
<div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
@if($notifications->count() > 0)
<div class="divide-y divide-gray-100">
@foreach($notifications as $notif)
<a href="{{ $notif->action_url ?: '#' }}" onclick="event.preventDefault(); fetch('/notifications/{{ $notif->id }}/read', { method: 'POST', headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content } }).then(() => { window.location = this.href; });" class="block px-6 py-4 hover:bg-gray-50 transition-colors {{ !$notif->is_read ? 'bg-blue-50/50' : '' }}">
<div class="flex items-start space-x-3">
<div class="flex-shrink-0 w-10 h-10 rounded-full flex items-center justify-center {{ $notif->color ? 'bg-'.$notif->color.'-100' : 'bg-blue-100' }}">
<i class="fa-solid fa-bell text-gray-600"></i>
</div>
<div class="flex-1 min-w-0">
<p class="text-sm font-medium text-gray-900">{{ $notif->title }}</p>
<p class="text-sm text-gray-500">{{ $notif->body }}</p>
<p class="text-xs text-gray-400 mt-1">{{ $notif->created_at->diffForHumans() }}</p>
</div>
@if(!$notif->is_read)
<span class="flex-shrink-0 w-2 h-2 mt-2 bg-blue-500 rounded-full"></span>
@endif
</div>
</a>
@endforeach
</div>
<div class="px-6 py-4 border-t border-gray-100">
{{ $notifications->links() }}
</div>
@else
<div class="px-6 py-12 text-center">
<i class="fa-regular fa-bell text-4xl text-gray-300 mb-3"></i>
<p class="text-sm text-gray-500">Belum ada notifikasi</p>
</div>
@endif
</div>
</div>
@endsection
+51
View File
@@ -0,0 +1,51 @@
@if ($paginator->hasPages())
<nav class="flex items-center justify-between">
<div class="flex-1 flex justify-between sm:hidden">
@if ($paginator->onFirstPage())
<span class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-400 bg-white border border-gray-200 rounded-lg">Previous</span>
@else
<a href="{{ $paginator->previousPageUrl() }}" class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-200 rounded-lg hover:bg-gray-50">Previous</a>
@endif
@if ($paginator->hasMorePages())
<a href="{{ $paginator->nextPageUrl() }}" class="relative inline-flex items-center px-4 py-2 ml-3 text-sm font-medium text-gray-700 bg-white border border-gray-200 rounded-lg hover:bg-gray-50">Next</a>
@else
<span class="relative inline-flex items-center px-4 py-2 ml-3 text-sm font-medium text-gray-400 bg-white border border-gray-200 rounded-lg">Next</span>
@endif
</div>
<div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
<div>
<p class="text-sm text-gray-600">
Menampilkan <span class="font-medium">{{ $paginator->firstItem() }}</span> - <span class="font-medium">{{ $paginator->lastItem() }}</span> dari <span class="font-medium">{{ $paginator->total() }}</span> notifikasi
</p>
</div>
<div>
<span class="relative z-0 inline-flex rounded-lg shadow-sm">
@if ($paginator->onFirstPage())
<span class="relative inline-flex items-center px-3 py-2 text-sm font-medium text-gray-400 bg-white border border-gray-200 rounded-l-lg">«</span>
@else
<a href="{{ $paginator->previousPageUrl() }}" class="relative inline-flex items-center px-3 py-2 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-l-lg hover:bg-gray-50">«</a>
@endif
@foreach ($elements as $element)
@if (is_string($element))
<span class="relative inline-flex items-center px-3 py-2 text-sm font-medium text-gray-400 bg-white border border-gray-200">{{ $element }}</span>
@endif
@if (is_array($element))
@foreach ($element as $page => $url)
@if ($page == $paginator->currentPage())
<span class="relative inline-flex items-center px-3 py-2 text-sm font-medium text-white bg-blue-600 border border-blue-600">{{ $page }}</span>
@else
<a href="{{ $url }}" class="relative inline-flex items-center px-3 py-2 text-sm font-medium text-gray-600 bg-white border border-gray-200 hover:bg-gray-50">{{ $page }}</a>
@endif
@endforeach
@endif
@endforeach
@if ($paginator->hasMorePages())
<a href="{{ $paginator->nextPageUrl() }}" class="relative inline-flex items-center px-3 py-2 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-r-lg hover:bg-gray-50">»</a>
@else
<span class="relative inline-flex items-center px-3 py-2 text-sm font-medium text-gray-400 bg-white border border-gray-200 rounded-r-lg">»</span>
@endif
</span>
</div>
</div>
</nav>
@endif
+1
View File
@@ -30,6 +30,7 @@ Route::middleware('auth')->group(function () {
Route::get('/notifications/recent', [DashboardController::class, 'getRecentNotifications'])->name('notifications.recent'); Route::get('/notifications/recent', [DashboardController::class, 'getRecentNotifications'])->name('notifications.recent');
Route::post('/notifications/{id}/read', [DashboardController::class, 'markNotificationRead'])->name('notifications.read'); Route::post('/notifications/{id}/read', [DashboardController::class, 'markNotificationRead'])->name('notifications.read');
Route::post('/notifications/read-all', [DashboardController::class, 'markAllNotificationsRead'])->name('notifications.read-all'); Route::post('/notifications/read-all', [DashboardController::class, 'markAllNotificationsRead'])->name('notifications.read-all');
Route::get('/notifications', [DashboardController::class, 'notificationsIndex'])->name('notifications.index');
// Violations // Violations
Route::get('/violations', [ViolationController::class, 'index'])->name('violations.index'); Route::get('/violations', [ViolationController::class, 'index'])->name('violations.index');