288 lines
10 KiB
PHP
288 lines
10 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use Illuminate\Support\Facades\Http;
|
|
use Illuminate\Support\Facades\Cache;
|
|
use Exception;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Str;
|
|
use App\Models\User;
|
|
use App\Models\Asset;
|
|
|
|
class AdminService
|
|
{
|
|
private $baseUrl;
|
|
private $username;
|
|
private $password;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->baseUrl = env('THINGSBOARD_URL', 'http://65.0.131.117:8080');
|
|
$this->username = env('THINGSBOARD_USERNAME', 'tenant1@thingsboard.org');
|
|
$this->password = env('THINGSBOARD_PASSWORD', 'tenant1');
|
|
}
|
|
|
|
public function getToken()
|
|
{
|
|
if (Cache::has('thingsboard_token')) {
|
|
return Cache::get('thingsboard_token');
|
|
}
|
|
|
|
$response = Http::withHeaders([
|
|
// 'accept' => 'application/json',
|
|
'Content-Type' => 'application/json',
|
|
])->post("{$this->baseUrl}/api/auth/login", [
|
|
'username' => $this->username,
|
|
'password' => $this->password,
|
|
]);
|
|
|
|
if ($response->successful()) {
|
|
$token = $response->json('token');
|
|
Cache::put('thingsboard_token', $token, now()->addMinutes(15));
|
|
return $token;
|
|
} else {
|
|
throw new Exception('Unable to authenticate with ThingsBoard: ' . $response->body());
|
|
}
|
|
}
|
|
|
|
// public function createAsset(array $data)
|
|
// {
|
|
|
|
// $token = $this->getToken();
|
|
// $payload = [
|
|
// // 'entityType' => $data['entity_type'] ?? 'ASSET',
|
|
// // 'createdTime' => $data['createdTime'] ?? now()->timestamp,
|
|
// // 'tenantId' => [
|
|
// // 'id' => $data['tenantId'] ?? Str::uuid()->toString(),
|
|
// // // 'entityType' => 'TENANT'
|
|
// // ],
|
|
// 'customerId' => [
|
|
// 'id' => $data['customerId'] ?? null,
|
|
// 'entityType' => 'CUSTOMER'
|
|
// ],
|
|
// 'name' => $data['name'] ?? 'Default Asset',
|
|
// 'type' => $data['type'] ?? 'Default Type',
|
|
// 'label' => $data['label'] ?? '',
|
|
// // 'assetProfileId' => [
|
|
// // 'id' => $data['assetProfileId'] ?? Str::uuid()->toString(),
|
|
// // // 'entityType' => 'ASSET_PROFILE'
|
|
// // ],
|
|
// // 'externalId' => [
|
|
// // 'id' => $data['externalId'] ?? Str::uuid()->toString(),
|
|
// // 'entityType' => 'ASSET'
|
|
// // ],
|
|
// 'version' => $data['version'] ?? '1.0',
|
|
// 'additionalInfo' => $data['additionalInfo'] ?? ['description' => 'Default asset description']
|
|
// ];
|
|
|
|
// $response = Http::withHeaders([
|
|
// 'Authorization' => "Bearer $token",
|
|
// 'Accept' => 'application/json',
|
|
// 'Content-Type' => 'application/json',
|
|
// ])->withBody(json_encode($payload), 'application/json')
|
|
// ->post("{$this->baseUrl}/api/asset");
|
|
// Log::error('Error in creating asset: ' . $response);
|
|
// // dd($response->json());
|
|
// if ($response->successful()) {
|
|
// return $response->json();
|
|
// } else {
|
|
// throw new Exception('Failed to create asset: ' . $response->body());
|
|
// }
|
|
// }
|
|
|
|
public function createAsset(array $data)
|
|
{
|
|
$token = $this->getToken();
|
|
|
|
$payload = [
|
|
// 'customerId' => [
|
|
// 'id' => $data['customerId'] ?? null,
|
|
// 'entityType' => 'CUSTOMER'
|
|
// ],
|
|
'name' => $data['name'] ?? 'Default Asset',
|
|
'type' => $data['type'] ?? 'Default Type',
|
|
'label' => $data['label'] ?? '',
|
|
'version' => $data['version'] ?? '1.0',
|
|
'additionalInfo' => $data['additionalInfo'] ?? ['description' => 'Default asset description']
|
|
];
|
|
|
|
// Include the IDs only if they are present
|
|
if (isset($data['id'])) {
|
|
$payload['id'] = $data['id'];
|
|
}
|
|
if (isset($data['tenantId'])) {
|
|
$payload['tenantId'] = [
|
|
'id' => $data['tenantId'],
|
|
'entityType' => 'TENANT'
|
|
];
|
|
}
|
|
// if (isset($data['assetProfileId'])) {
|
|
// $payload['assetProfileId'] = [
|
|
// 'id' => $data['assetProfileId'],
|
|
// 'entityType' => 'ASSET_PROFILE'
|
|
// ];
|
|
// }
|
|
if (isset($data['externalId'])) {
|
|
$payload['externalId'] = [
|
|
'id' => $data['externalId'],
|
|
'entityType' => 'ASSET'
|
|
];
|
|
}
|
|
|
|
Log::info('Payload being sent: ', $payload); // ✅ Log the payload for debugging
|
|
|
|
$response = Http::withHeaders([
|
|
'Authorization' => "Bearer $token",
|
|
'Accept' => 'application/json',
|
|
'Content-Type' => 'application/json',
|
|
])->withBody(json_encode($payload), 'application/json')
|
|
->post("{$this->baseUrl}/api/asset");
|
|
|
|
if ($response->successful()) {
|
|
return $response->json();
|
|
} else {
|
|
throw new Exception('Failed to create asset: ' . $response->body());
|
|
}
|
|
}
|
|
|
|
|
|
public function deleteAsset(array $data)
|
|
{
|
|
$token = $this->getToken();
|
|
|
|
if (!isset($data['assetId']) || empty($data['assetId'])) {
|
|
throw new Exception('Asset ID is required for deletion.');
|
|
}
|
|
|
|
$assetId = $data['assetId'];
|
|
$response = Http::withHeaders([
|
|
'Authorization' => "Bearer $token",
|
|
'Accept' => 'application/json',
|
|
'Content-Type' => 'application/json',
|
|
])->delete("{$this->baseUrl}/api/asset/{$assetId}");
|
|
|
|
Log::info('Asset Deletion Response: ' . $response);
|
|
|
|
if ($response->successful()) {
|
|
return [
|
|
'success' => true,
|
|
'message' => 'Asset deleted successfully.',
|
|
'data' => $response->json()
|
|
];
|
|
} else {
|
|
throw new Exception('Failed to delete asset: ' . $response->body());
|
|
}
|
|
}
|
|
|
|
// public function assignAssetToCustomer(array $data)
|
|
// {
|
|
// $token = $this->getToken();
|
|
|
|
// // Validate required parameters
|
|
// if (!isset($data['assetId']) || empty($data['assetId'])) {
|
|
// throw new Exception('Asset ID is required.');
|
|
// }
|
|
|
|
// if (!isset($data['customerId']) || empty($data['customerId'])) {
|
|
// throw new Exception('Customer ID is required.');
|
|
// }
|
|
|
|
// $assetId = $data['assetId'];
|
|
// $customerId = $data['customerId'];
|
|
|
|
// // API request to assign asset to customer
|
|
// $response = Http::withHeaders([
|
|
// 'Authorization' => "Bearer $token",
|
|
// 'Accept' => 'application/json',
|
|
// 'Content-Type' => 'application/json',
|
|
// ])->post("{$this->baseUrl}/api/customer/{$customerId}/asset/{$assetId}");
|
|
|
|
// // Log the response for debugging purposes
|
|
// Log::info('Asset Assignment Response: ' . $response->body());
|
|
|
|
// // Handle API responses
|
|
// if ($response->successful()) {
|
|
// return [
|
|
// 'success' => true,
|
|
// 'message' => 'Asset assigned to customer successfully.',
|
|
// 'data' => $response->json()
|
|
// ];
|
|
// }
|
|
// else {
|
|
// throw new Exception('Failed to delete asset: ' . $response->body());
|
|
// }
|
|
|
|
// // Handle specific API error responses
|
|
// // $statusCode = $response->status();
|
|
// // $errorMessage = $response->json()['message'] ?? 'Unknown error occurred';
|
|
|
|
// // switch ($statusCode) {
|
|
// // case 400:
|
|
// // throw new Exception("Bad Request: $errorMessage", 400);
|
|
// // case 401:
|
|
// // throw new Exception("Unauthorized: $errorMessage", 401);
|
|
// // case 403:
|
|
// // throw new Exception("Forbidden: $errorMessage", 403);
|
|
// // case 404:
|
|
// // throw new Exception("Not Found: $errorMessage", 404);
|
|
// // case 429:
|
|
// // throw new Exception("Too Many Requests: $errorMessage", 429);
|
|
// // default:
|
|
// // throw new Exception("Failed to assign asset: $errorMessage", $statusCode);
|
|
// // }
|
|
// }
|
|
|
|
public function assignAssetToUser(array $data)
|
|
{
|
|
$token = $this->getToken();
|
|
|
|
// Validate required parameters
|
|
if (!isset($data['assetId']) || empty($data['assetId'])) {
|
|
throw new Exception('Asset ID is required.');
|
|
}
|
|
|
|
if (!isset($data['userId']) || empty($data['userId'])) {
|
|
throw new Exception('User ID is required.');
|
|
}
|
|
|
|
$assetId = $data['assetId'];
|
|
$userId = $data['userId'];
|
|
// dd($data);
|
|
// Retrieve user details to get the customer ID
|
|
$user = User::find($userId);
|
|
if (!$user) {
|
|
throw new Exception('User not found.');
|
|
}
|
|
|
|
// Get the ThingsBoard customer ID linked to the user
|
|
// $customerId = $user->userId ?? null;
|
|
$customerId = $user->userId ?? null; // ✅ Use the correct column name
|
|
|
|
if (!$customerId) {
|
|
throw new Exception('User does not have an associated customer ID.');
|
|
}
|
|
|
|
// API request to assign asset to customer (based on user's customer ID)
|
|
$response = Http::withHeaders([
|
|
'Authorization' => "Bearer $token",
|
|
'Accept' => 'application/json',
|
|
'Content-Type' => 'application/json',
|
|
])->post("{$this->baseUrl}/api/customer/{$customerId}/asset/{$assetId}");
|
|
|
|
// Log the response for debugging purposes
|
|
Log::info('Asset Assignment Response: ' . $response->body());
|
|
|
|
// Handle API responses
|
|
if ($response->successful()) {
|
|
return [
|
|
'success' => true,
|
|
'message' => 'Asset assigned to user successfully.',
|
|
'data' => $response->json()
|
|
];
|
|
} else {
|
|
throw new Exception('Failed to assign asset: ' . $response->body());
|
|
}
|
|
}
|
|
}
|