107 lines
3.1 KiB
PHP
107 lines
3.1 KiB
PHP
<?php
|
|
|
|
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
|
|
{
|
|
protected $customerInfoService;
|
|
|
|
public function __construct(CustomerInfoService $customerInfoService)
|
|
{
|
|
$this->customerInfoService = $customerInfoService;
|
|
}
|
|
|
|
|
|
|
|
|
|
public function customerDeviceInfo(Request $request)
|
|
{
|
|
try {
|
|
// Extract the token payload from the request
|
|
$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);
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|