feat: Add API endpoints for staff online status and queue monitoring.
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Admin\Staff;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use App\Repositories\Staff\StaffRepositoryInterface;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class StaffOnlineController extends Controller
|
||||
{
|
||||
private const ONLINE_THRESHOLD_SECONDS = 60;
|
||||
|
||||
public function __construct(
|
||||
private readonly StaffRepositoryInterface $staffRepository
|
||||
) {}
|
||||
|
||||
/**
|
||||
* GET /api/v1/administrator/staff-online
|
||||
* Trả về danh sách staff đang online (query từ tbl.user).
|
||||
*/
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$users = User::whereHas('staffOnline')->with('staffOnline')->get();
|
||||
|
||||
$online = $users->map(fn ($user) => [
|
||||
'user_id' => $user->id,
|
||||
'name' => trim($user->firstname . ' ' . $user->lastname),
|
||||
'username' => $user->username,
|
||||
'email' => $user->email,
|
||||
'last_visited' => $user->staffOnline?->last_visited,
|
||||
])->values();
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'data' => $online,
|
||||
'total' => $online->count(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/v1/administrator/staff-online/ping
|
||||
* Heartbeat cho JWT admin — cập nhật trạng thái online.
|
||||
*/
|
||||
public function ping(Request $request): JsonResponse
|
||||
{
|
||||
$userId = $request->user()?->id;
|
||||
|
||||
if (!$userId) {
|
||||
return response()->json(['error' => true, 'message' => 'Unauthenticated'], 401);
|
||||
}
|
||||
|
||||
$record = $this->staffRepository->getFirstBy(['user_id' => $userId]);
|
||||
|
||||
if ($record) {
|
||||
$record->last_visited = time();
|
||||
$record->save();
|
||||
} else {
|
||||
$this->staffRepository->create([
|
||||
'sessions_id' => 'jwt-' . $userId,
|
||||
'user_id' => $userId,
|
||||
'last_visited' => time(),
|
||||
]);
|
||||
}
|
||||
|
||||
$this->staffRepository->deleteRawTime(self::ONLINE_THRESHOLD_SECONDS);
|
||||
|
||||
return response()->json(['error' => false, 'message' => 'OK']);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user