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

260 lines
7.6 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;
}
// public function customerDeviceInfo($customerId)
// {
// try {
// $localActiveCount = 0;
// $customer = Customer::with('users.assets.devices')
// ->findOrFail($customerId);
// foreach ($customer->users as $user) {
// foreach ($user->assets as $asset) {
// $localActiveCount += $asset->devices->where('active', true)->count();
// }
// }
// $thingsBoardActiveCount = $this->customerInfoService->getThingsBoardActiveDevicesCount($customerId);
// if ($thingsBoardActiveCount === null) {
// Log::warning("Failed to fetch ThingsBoard devices, setting count to 0.");
// $thingsBoardActiveCount = 0;
// }
// return response()->json([
// 'customer_id' => $customerId,
// 'local_active_devices_count' => $localActiveCount,
// 'thingsboard_active_devices_count' => $thingsBoardActiveCount,
// 'total_active_devices_count' => $localActiveCount + $thingsBoardActiveCount
// ]);
// } catch (\Exception $e) {
// Log::error("Error fetching active devices: " . $e->getMessage());
// return response()->json([
// 'error' => 'Failed to fetch active devices'
// ], 500);
// }
// }
2025-03-26 16:49:43 +05:30
// public function customerDeviceInfo()
// {
// // try {
// $user = readHeaderToken();
// dd($user);
// // Fetch user with assets and device counts
// $user = User::with(['assets.devices'])
// // ->where('id')
// ->first();
// if (!$user) {
// return response()->json(['error' => 'User not found'], 404);
// }
// $thingsBoardDevices = $this->customerInfoService->getThingsBoardDevices($correctCustomerId);
// if (empty($thingsBoardDevices)) {
// Log::warning("No devices found for Customer ID: $correctCustomerId");
// return response()->json([
// 'status' => 200,
// 'customer_id' => $customerId,
// 'data' => $data
// ], 200);
// }
// foreach ($customer->users as $user) {
// foreach ($user->assets as $asset) {
// $tbGood = 0;
// $tbModerate = 0;
// foreach ($thingsBoardDevices as $device) {
// $isActive = $device['active'] ?? false;
// if ($isActive) {
// $tbGood++;
// } else {
// $tbModerate++;
// }
// }
// $data[] = [
// 'customer_id' => $customerId,
// 'user_id' => $user->id,
// 'asset_id' => $asset->id,
// 'good' => $tbGood,
// 'moderate' => $tbModerate
// ];
// }
// }
// // ✅ Return Final Response
// return response()->json([
// 'status' => 200,
// 'customer_id' => $customerId,
// 'data' => $data
// ], 200);
// // } catch (\Exception $e) {
// // Log::error("Error fetching customer device info: " . $e->getMessage());
// // return response()->json([
// // 'status' => 500,
// // 'error' => 'Failed to fetch customer device info'
// // ], 500);
// // }
// }
// public function customerDeviceInfo(Request $request)
// {
// $tokenPayload = getTokenFromHeader($request);
// // dd($tokenPayload);
// if (isset($tokenPayload['error'])) {
// return response()->json($tokenPayload, 401);
// }
// $userId = $tokenPayload['sub'];
// $user = User::where('id', $userId)
// ->with(['assets' => function($query) {
// $query->with(['devices:id,name,asset_id']);
// }])
// ->first();
// if (!$user) {
// return response()->json(['error' => 'User not found'], 404);
// }
// $userData = [
// 'user_id' => $user->id,
// 'assets' => []
// ];
// foreach ($user->assets as $asset) {
// $assetData = [
// 'asset_id' => $asset->id,
// 'devices' => $asset->devices->pluck('id')
// ];
// // Add asset data to the response
// $userData['assets'][] = $assetData;
// }
// return response()->json($userData);
// }
public function customerDeviceInfo(Request $request)
2025-03-21 12:11:20 +05:30
{
try {
2025-03-26 16:49:43 +05:30
// Extract the token payload from the request
$tokenPayload = getTokenFromHeader($request);
if (isset($tokenPayload['error'])) {
return response()->json($tokenPayload, 401);
2025-03-21 12:11:20 +05:30
}
2025-03-26 16:49:43 +05:30
$userId = $tokenPayload['sub'];
2025-03-21 12:11:20 +05:30
2025-03-26 16:49:43 +05:30
// 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);
2025-03-21 12:11:20 +05:30
}
2025-03-26 16:49:43 +05:30
try {
// Get devices data from ThingsBoard service
$devicesArray = $this->customerInfoService->getThingsBoardDevices($user->customer_id);
2025-03-21 12:11:20 +05:30
2025-03-26 16:49:43 +05:30
if (!is_array($devicesArray)) {
throw new \Exception("Invalid devices data received from service");
}
2025-03-21 12:11:20 +05:30
2025-03-26 16:49:43 +05:30
$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
2025-03-21 12:11:20 +05:30
return response()->json([
2025-03-26 16:49:43 +05:30
'good' => $good,
'moderate' => $moderate,
'total_count' => $total_count
2025-03-21 12:11:20 +05:30
], 200);
2025-03-26 16:49:43 +05:30
} catch (\Exception $serviceException) {
Log::error("ThingsBoard service error: " . $serviceException->getMessage());
return response()->json([
'error' => 'Failed to fetch device information',
'details' => $serviceException->getMessage()
], 503);
2025-03-21 12:11:20 +05:30
}
} catch (\Exception $e) {
2025-03-26 16:49:43 +05:30
Log::error("Customer device info error: " . $e->getMessage());
2025-03-21 12:11:20 +05:30
return response()->json([
2025-03-26 16:49:43 +05:30
'error' => 'An unexpected error occurred',
'details' => $e->getMessage()
2025-03-21 12:11:20 +05:30
], 500);
}
}
}