sayali #37
@@ -4,9 +4,12 @@ namespace App\Http\Controllers\APIS\CustomerApi;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Customer;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Services\CustomerInfoService;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Tymon\JWTAuth\Facades\JWTAuth;
|
||||
|
||||
|
||||
class CustomerDeviceInfoController extends Controller
|
||||
{
|
||||
@@ -56,91 +59,192 @@ class CustomerDeviceInfoController extends Controller
|
||||
// }
|
||||
// }
|
||||
|
||||
public function customerDeviceInfo($customerId)
|
||||
// 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)
|
||||
{
|
||||
try {
|
||||
$data = [];
|
||||
// Extract the token payload from the request
|
||||
$tokenPayload = getTokenFromHeader($request);
|
||||
|
||||
$customer = Customer::with('users.assets.devices')->findOrFail($customerId);
|
||||
if (isset($tokenPayload['error'])) {
|
||||
return response()->json($tokenPayload, 401);
|
||||
}
|
||||
|
||||
foreach ($customer->users as $user) {
|
||||
foreach ($user->assets as $asset) {
|
||||
$localGood = $asset->devices->where('active', true)->count();
|
||||
$localModerate = $asset->devices->where('active', false)->count();
|
||||
$userId = $tokenPayload['sub'];
|
||||
|
||||
$data[] = [
|
||||
'customer_id' => $customerId,
|
||||
'user_id' => $user->id,
|
||||
'asset_id' => $asset->id,
|
||||
'good' => $localGood,
|
||||
'moderate' => $localModerate
|
||||
];
|
||||
// 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");
|
||||
}
|
||||
}
|
||||
|
||||
// ✅ Fetch Correct Customer ID from ThingsBoard
|
||||
$correctCustomerId = $this->customerInfoService->getThingsBoardDevices('784f394c-42b6-435a-983c-b7beff2784f9');
|
||||
$thingsBoardDevices = collect($devicesArray);
|
||||
|
||||
if (!$correctCustomerId) {
|
||||
Log::warning("No valid customer ID found for Device ID.");
|
||||
// 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([
|
||||
'status' => 404,
|
||||
'error' => 'Customer ID not found for the device',
|
||||
'data' => $data
|
||||
], 404);
|
||||
}
|
||||
|
||||
// ✅ Fetch ThingsBoard Devices
|
||||
$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
|
||||
'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);
|
||||
}
|
||||
|
||||
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());
|
||||
|
||||
Log::error("Customer device info error: " . $e->getMessage());
|
||||
return response()->json([
|
||||
'status' => 500,
|
||||
'error' => 'Failed to fetch customer device info'
|
||||
'error' => 'An unexpected error occurred',
|
||||
'details' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
@@ -152,7 +256,4 @@ class CustomerDeviceInfoController extends Controller
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ class UserAssetLinkController extends Controller
|
||||
public function index()
|
||||
{
|
||||
try {
|
||||
$token = readHeaderToken();
|
||||
// $token = readHeaderToken();
|
||||
|
||||
// $token = readHeaderToken();
|
||||
|
||||
@@ -51,6 +51,7 @@ class UserAssetLinkController extends Controller
|
||||
// return response()->json($userAssetLinks);
|
||||
|
||||
$token = readHeaderToken();
|
||||
// dd($token);
|
||||
|
||||
// Fetch user with assets and device counts
|
||||
$user = User::with(['assets.devices'])
|
||||
|
||||
@@ -9,6 +9,8 @@ use Illuminate\Support\Facades\Cache;
|
||||
use Tymon\JWTAuth\Facades\JWTAuth;
|
||||
use GuzzleHttp\Client;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
|
||||
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
|
||||
|
||||
if (!function_exists('jsonResponseWithSuccessMessageApi')) {
|
||||
function jsonResponseWithSuccessMessageApi($message, $data = [], $statusCode = 200)
|
||||
@@ -127,7 +129,7 @@ if (!function_exists('readHeaderToken')) {
|
||||
function readHeaderToken()
|
||||
{
|
||||
$tokenData = Session::get('vendorToken');
|
||||
$token = JWTAuth::setToken($tokenData)->getPayload();
|
||||
$token = JWTAuth::setToken($tokenData)->getPayload();
|
||||
|
||||
// dd([
|
||||
// 'tokenData' => $tokenData,
|
||||
@@ -337,4 +339,34 @@ function getThingsboardToken()
|
||||
throw new Exception('Unable to authenticate with ThingsBoard');
|
||||
}
|
||||
}
|
||||
|
||||
if (!function_exists('getTokenFromHeader')) {
|
||||
/**
|
||||
* Function to get the token from the header and validate it.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return mixed
|
||||
*/
|
||||
function getTokenFromHeader($request)
|
||||
{
|
||||
// Extract the token from the Authorization header
|
||||
$token = $request->bearerToken();
|
||||
|
||||
if (!$token) {
|
||||
return response()->json(['error' => 'Invalid or missing token'], 401);
|
||||
}
|
||||
|
||||
// Try to parse the token and return the payload (user information)
|
||||
try {
|
||||
$payload = JWTAuth::parseToken()->getPayload(); // Get the payload of the token
|
||||
return $payload; // Return the payload (you can use this in controllers)
|
||||
} catch (TokenExpiredException $e) {
|
||||
return response()->json(['error' => 'Token expired'], 401);
|
||||
} catch (TokenInvalidException $e) {
|
||||
return response()->json(['error' => 'Token invalid'], 401);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json(['error' => 'Failed to authenticate token'], 401);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,33 +18,41 @@ class CustomerInfoService
|
||||
$this->adminService = $adminService;
|
||||
}
|
||||
|
||||
public function getThingsBoardDevices($customerId)
|
||||
{
|
||||
try {
|
||||
$token = $this->adminService->getToken();
|
||||
public function getThingsBoardDevices($customerId)
|
||||
{
|
||||
try {
|
||||
$token = $this->adminService->getToken();
|
||||
|
||||
if (!$token) {
|
||||
Log::error("Failed to authenticate with ThingsBoard.");
|
||||
return [];
|
||||
}
|
||||
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => "Bearer $token",
|
||||
'Accept' => 'application/json',
|
||||
])->get("http://65.0.131.117:8080/api/customer/{$customerId}/deviceInfos?pageSize=100&page=0");
|
||||
|
||||
if (!$response->successful()) {
|
||||
Log::error("Failed to fetch ThingsBoard devices: " . $response->body());
|
||||
return [];
|
||||
}
|
||||
|
||||
return $response->json()['data'] ?? [];
|
||||
|
||||
} catch (\Exception $e) {
|
||||
Log::error("Error fetching ThingsBoard devices: " . $e->getMessage());
|
||||
if (!$token) {
|
||||
Log::error("Failed to authenticate with ThingsBoard.");
|
||||
return [];
|
||||
}
|
||||
|
||||
// Sending the request to ThingsBoard API
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => "Bearer $token",
|
||||
'Accept' => 'application/json',
|
||||
])->get("http://65.0.131.117:8080/api/customer/{$customerId}/deviceInfos?pageSize=100&page=0");
|
||||
|
||||
// Check if the response is successful
|
||||
if (!$response->successful()) {
|
||||
Log::error("Failed to fetch ThingsBoard devices: " . $response->body());
|
||||
return [];
|
||||
}
|
||||
|
||||
// Convert the JSON response to an array by calling json()
|
||||
$data = $response->json(); // This will convert the response into an array
|
||||
|
||||
// Return only the 'data' key from the response or an empty array if it's not set
|
||||
return $data['data'] ?? [];
|
||||
} catch (\Exception $e) {
|
||||
Log::error("Error fetching ThingsBoard devices: " . $e->getMessage());
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -72,8 +80,8 @@ class CustomerInfoService
|
||||
|
||||
'keys' => $keys,
|
||||
// 'keys' => 'MechanicalHealth_valueInPercent',
|
||||
'startTs' => $startTs,
|
||||
'interval' => $endTs,
|
||||
// 'startTs' => $startTs,
|
||||
// 'interval' => $endTs,
|
||||
'limit' => 100,
|
||||
'useStrictDataTypes' => false
|
||||
]);
|
||||
@@ -109,7 +117,7 @@ class CustomerInfoService
|
||||
|
||||
public function getTelemetryDataDevice($device, $keyNames, $startTs, $endTs)
|
||||
{
|
||||
|
||||
|
||||
$token = $this->adminService->getToken();
|
||||
|
||||
if (!$token) {
|
||||
|
||||
@@ -15,7 +15,7 @@ Route::get('/customerapi', function () {
|
||||
|
||||
|
||||
Route::post('user-login', [AuthController::class, 'login']);
|
||||
Route::get('/customer-device-info/{customerId}',[CustomerDeviceInfoController::class,'customerDeviceInfo']);
|
||||
Route::get('/customer-device-info',[CustomerDeviceInfoController::class,'customerDeviceInfo']);
|
||||
Route::post('/telemetry-data-asset',[TelemetryController::class,'telemetryDataAsset']);
|
||||
Route::post('/telemetry-data-device',[TelemetryController::class,'telemetryDataDevice']);
|
||||
Route::post('/telemetry-data-device-diagnostic',[TelemetryController::class,'telemePtryDataDeviceDiagnostic']);
|
||||
|
||||
Reference in New Issue
Block a user