62 lines
2.0 KiB
PHP
62 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api;
|
|
|
|
use App\Services\Posts\NotificationDigestService;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
use App\Http\Controllers\Controller;
|
|
|
|
/**
|
|
* GET /api/notifications — digestd notification list
|
|
* POST /api/notifications/read-all — mark all unread as read
|
|
* POST /api/notifications/{id}/read — mark single as read
|
|
*/
|
|
class NotificationController extends Controller
|
|
{
|
|
public function __construct(private NotificationDigestService $digest) {}
|
|
|
|
public function index(Request $request): JsonResponse
|
|
{
|
|
$user = $request->user();
|
|
$page = max(1, (int) $request->query('page', 1));
|
|
|
|
$notifications = $user->notifications()
|
|
->latest()
|
|
->limit(200) // aggregate from last 200 raw notifs
|
|
->get();
|
|
|
|
$digested = $this->digest->aggregate($notifications);
|
|
|
|
// Simple manual pagination on the digested array
|
|
$perPage = 20;
|
|
$total = count($digested);
|
|
$sliced = array_slice($digested, ($page - 1) * $perPage, $perPage);
|
|
$unread = $user->unreadNotifications()->count();
|
|
|
|
return response()->json([
|
|
'data' => array_values($sliced),
|
|
'unread_count' => $unread,
|
|
'meta' => [
|
|
'total' => $total,
|
|
'current_page' => $page,
|
|
'last_page' => (int) ceil($total / $perPage) ?: 1,
|
|
'per_page' => $perPage,
|
|
],
|
|
]);
|
|
}
|
|
|
|
public function readAll(Request $request): JsonResponse
|
|
{
|
|
$request->user()->unreadNotifications()->update(['read_at' => now()]);
|
|
return response()->json(['message' => 'All notifications marked as read.']);
|
|
}
|
|
|
|
public function markRead(Request $request, string $id): JsonResponse
|
|
{
|
|
$notif = $request->user()->notifications()->findOrFail($id);
|
|
$notif->markAsRead();
|
|
return response()->json(['message' => 'Notification marked as read.']);
|
|
}
|
|
}
|