Files
backend_vib360_laravel/app/Http/Controllers/APIS/CustomerApi/CustomerDeviceInfoController.php

259 lines
7.9 KiB
PHP
Raw Normal View History

2025-03-21 12:11:20 +05:30
<?php
namespace App\Http\Controllers\APIS\CustomerApi;
use App\Http\Controllers\Controller;
use App\Models\Customer;
2025-03-26 16:49:43 +05:30
use App\Models\User;
2025-03-21 12:11:20 +05:30
use Illuminate\Http\Request;
use App\Services\CustomerInfoService;
use Illuminate\Support\Facades\Log;
2025-03-26 16:49:43 +05:30
use Tymon\JWTAuth\Facades\JWTAuth;
2025-03-21 12:11:20 +05:30
class CustomerDeviceInfoController extends Controller
{
protected $customerInfoService;
public function __construct(CustomerInfoService $customerInfoService)
{
$this->customerInfoService = $customerInfoService;
}
2025-03-27 18:54:06 +05:30
2025-03-26 16:49:43 +05:30
2025-03-28 19:40:39 +05:30
// public function customerDeviceInfo(Request $request)
// {
// try {
// $tokenPayload = getTokenFromHeader($request);
// if (isset($tokenPayload['error'])) {
// return response()->json($tokenPayload, 401);
// }
// $userId = $tokenPayload['sub'];
// // Get user with assets and devices
// $user = User::with(['assets' => function($query) {
// $query->with(['devices:id,name,asset_id']);
// }])
// ->where('id', $userId)
// ->first();
// if (!$user) {
// return response()->json(['error' => 'User not found'], 404);
// }
// try {
// // Get devices data from ThingsBoard service
// $devicesArray = $this->customerInfoService->getThingsBoardDevices($user->customer_id);
// if (!is_array($devicesArray)) {
// throw new \Exception("Invalid devices data received from service");
// }
// $thingsBoardDevices = collect($devicesArray);
// // Process devices
// $deviceDetails = $user->assets->flatMap(function ($asset) use ($thingsBoardDevices) {
// return $thingsBoardDevices->whereIn('id.id', $asset->devices->pluck('id')->toArray())
// ->map(function ($tbDevice) {
// return [
// 'device_id' => $tbDevice['id']['id'],
// 'active' => $tbDevice['active'] ?? false
// ];
// });
// });
// // Calculate counts
// $good = $deviceDetails->where('active', true)->count();
// $moderate = $deviceDetails->where('active', false)->count();
// $total_count = $good + $moderate;
// // Successful response
// return response()->json([
// 'good' => $good,
// 'moderate' => $moderate,
// 'total_count' => $total_count
// ], 200);
// } catch (\Exception $serviceException) {
// Log::error("ThingsBoard service error: " . $serviceException->getMessage());
// return response()->json([
// 'error' => 'Failed to fetch device information',
// 'details' => $serviceException->getMessage()
// ], 503);
// }
// } catch (\Exception $e) {
// Log::error("Customer device info error: " . $e->getMessage());
// return response()->json([
// 'error' => 'An unexpected error occurred',
// 'details' => $e->getMessage()
// ], 500);
// }
// }
// public function customerDeviceInfo(Request $request)
// {
// try {
// $token = readHeaderToken();
// if (!$token) {
// return response()->json([
// 'success' => false,
// 'error' => 'Authorization token required'
// ], 401);
// }
// $user = User::with(['assets.devices:id,name,asset_id'])
// ->find($token['sub']);
// if (!$user) {
// return response()->json([
// 'error' => 'user_not_found',
// 'message' => 'User not found'
// ], 404);
// }
// $devicesArray = $this->customerInfoService->getThingsBoardDevices($user->customer_id);
// if (isset($devicesArray['error'])) {
// throw new \Exception($devicesArray['message'] ?? 'Failed to fetch devices');
// }
// if (!is_array($devicesArray)) {
// throw new \Exception("Invalid devices data format received from service");
// }
// $userDeviceIds = $user->assets->flatMap->devices->pluck('id')->toArray();
// $activeCount = collect($devicesArray)
// ->whereIn('id.id', $userDeviceIds)
// ->where('active', true)
// ->count();
// $deviceIdCount = count($userDeviceIds);
// return response()->json([
// 'data' => [
// 'active_count' => $activeCount,
// 'total_count' => $deviceIdCount,
// ],
// 'success' => true
// ], 200);
// } catch (\Exception $e) {
// Log::error("Device info error: " . $e->getMessage());
// $statusCode = ($e->getMessage() === "Invalid devices data format received from service") ? 503 : 500;
// return response()->json([
// 'error' => 'server_error',
// 'message' => 'An error occurred',
// 'details' => $e->getMessage()
// ], $statusCode);
// }
// }
2025-03-26 16:49:43 +05:30
public function customerDeviceInfo(Request $request)
2025-03-21 12:11:20 +05:30
{
try {
2025-03-28 19:40:39 +05:30
$token = readHeaderToken($request);
if (!$token) {
return response()->json([
'success' => false,
'error' => 'authorization_required',
'message' => 'Authorization token required'
], 401);
2025-03-21 12:11:20 +05:30
}
2025-03-28 19:40:39 +05:30
// Get user with devices
$user = User::with(['assets.devices:id,name,asset_id'])
->find($token['sub']);
2025-03-26 16:49:43 +05:30
if (!$user) {
2025-03-28 19:40:39 +05:30
return response()->json([
'success' => false,
'error' => 'user_not_found',
'message' => 'User not found'
], 404);
2025-03-21 12:11:20 +05:30
}
2025-03-28 19:40:39 +05:30
// Get user's device IDs
$userDeviceIds = $user->assets->flatMap->devices->pluck('id')->toArray();
if (empty($userDeviceIds)) {
2025-03-21 12:11:20 +05:30
return response()->json([
2025-03-28 19:40:39 +05:30
'data' => [
'active_count' => 0,
'total_count' => 0,
'alarms_count' => 0
],
'success' => true
2025-03-21 12:11:20 +05:30
], 200);
2025-03-28 19:40:39 +05:30
}
2025-03-21 12:11:20 +05:30
2025-03-28 19:40:39 +05:30
// Get devices and alarms from service
$serviceResponse = $this->customerInfoService->getCustomerDevicesAndAlarms(
$user->customer_id,
$userDeviceIds
);
// Handle service errors
if (isset($serviceResponse['error'])) {
throw new \Exception($serviceResponse['message'] ?? 'Service request failed');
2025-03-21 12:11:20 +05:30
}
2025-03-28 19:40:39 +05:30
// Process devices
$devices = $serviceResponse['devices'] ?? [];
$activeCount = collect($devices)
->whereIn('id.id', $userDeviceIds)
->where('active', true)
->count();
// Process alarms
$alarms = $serviceResponse['alarms'] ?? [];
$recentAlarms = $this->filterRecentAlarms($alarms);
return response()->json([
'data' => [
'active_count' => $activeCount,
'total_count' => count($userDeviceIds),
'alarms_count' => count($recentAlarms),
],
'success' => true
], 200);
2025-03-21 12:11:20 +05:30
} catch (\Exception $e) {
2025-03-28 19:40:39 +05:30
Log::error("Device info error: " . $e->getMessage());
2025-03-21 12:11:20 +05:30
return response()->json([
2025-03-28 19:40:39 +05:30
'success' => false,
'error' => 'server_error',
'message' => 'An error occurred while fetching device information',
2025-03-26 16:49:43 +05:30
'details' => $e->getMessage()
2025-03-21 12:11:20 +05:30
], 500);
}
}
2025-03-28 19:40:39 +05:30
private function filterRecentAlarms(array $alarms): array
{
$twentyFourHoursAgo = (time() - 86400) * 1000;
2025-03-21 12:11:20 +05:30
2025-03-28 19:40:39 +05:30
return array_values(array_filter($alarms, function($alarm) use ($twentyFourHoursAgo) {
return ($alarm['createdTime'] ?? 0) >= $twentyFourHoursAgo;
}));
}
2025-03-21 12:11:20 +05:30
}