399 lines
12 KiB
PHP
399 lines
12 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\User;
|
|
use Illuminate\Support\Facades\Http;
|
|
use Illuminate\Support\Facades\Cache;
|
|
use Exception;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Str;
|
|
|
|
|
|
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 {
|
|
Log::error("ThingsBoard Authentication Failed: " . $response->body());
|
|
throw new Exception('Unable to authenticate with ThingsBoard: ' . $response->body());
|
|
}
|
|
}
|
|
public function createOrUpdateCustomer(array $data)
|
|
{
|
|
$token = $this->getToken();
|
|
Log::info('Getting data before payload', ['data' => json_encode($data, JSON_PRETTY_PRINT)]);
|
|
|
|
$payload = [
|
|
'title' => $data['title'] ?? 'Default Title',
|
|
'email' => $data['email'] ?? 'default@example.com',
|
|
'country' => $data['country'] ?? 'India',
|
|
'state' => $data['state'] ?? 'Karnataka',
|
|
'city' => $data['city'] ?? 'Bangalore',
|
|
'zip' => $data['zip'] ?? '560001',
|
|
'name' => $data['name'] ?? 'John Doe',
|
|
'address' => $data['address'] ?? '123, 4th Cross, 5th Main',
|
|
'address2' => $data['address2'] ?? 'Near Park',
|
|
'phone' => $data['phone'] ?? '1234567890',
|
|
'version' => $data['version'] ?? '794665488',
|
|
'additionalInfo' => [
|
|
'description' => $data['description'] ?? 'User description'
|
|
],
|
|
|
|
];
|
|
|
|
|
|
|
|
if (!empty($data['id']) && is_array($data['id']) && isset($data['id']['id'])) {
|
|
$payload['id'] = [
|
|
'id' => $data['id']['id'],
|
|
'entityType' => 'CUSTOMER'
|
|
];
|
|
}
|
|
|
|
// Check if `tenantId` exists and assign correctly
|
|
if (!empty($data['tenantId']) && is_array($data['tenantId']) && isset($data['tenantId']['id'])) {
|
|
$payload['tenantId'] = [
|
|
'id' => $data['tenantId']['id'],
|
|
'entityType' => 'TENANT',
|
|
];
|
|
}
|
|
|
|
Log::info('Final Payload:', ['payload' => json_encode($payload, JSON_PRETTY_PRINT)]);
|
|
|
|
|
|
|
|
$url = "{$this->baseUrl}/api/customer";
|
|
$method = 'post';
|
|
// Send request
|
|
$response = Http::withHeaders([
|
|
'Authorization' => "Bearer $token",
|
|
'Accept' => 'application/json',
|
|
'Content-Type' => 'application/json',
|
|
])->$method($url, $payload);
|
|
if ($response->successful()) {
|
|
return $response->json();
|
|
} else {
|
|
throw new Exception('Failed to process customer: ' . $response->body());
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
public function createUser(array $data)
|
|
{
|
|
$token = $this->getToken();
|
|
|
|
|
|
$payload = [
|
|
'email' => $data['email'] ?? 'default@example.com',
|
|
'tenantId' => [
|
|
'id' => $data['tenant_id'] ?? '6e9b7fde-0ca0-4d19-9d2a-fba98e3e12a0',
|
|
'entityType' => 'TENANT'
|
|
],
|
|
'customerId' => [
|
|
'id' => $data['customerId'],
|
|
'entityType' => 'CUSTOMER'
|
|
],
|
|
'authority' => $data['authority'] ?? 'TENANT_ADMIN',
|
|
'name' => $data['name'] ?? 'John Doe',
|
|
'phone' => $data['phone'] ?? '1234567890',
|
|
'additionalInfo' => [
|
|
'description' => $data['description'] ?? 'User description'
|
|
]
|
|
];
|
|
|
|
$response = Http::withHeaders([
|
|
'Authorization' => "Bearer $token",
|
|
'accept' => 'application/json',
|
|
'Content-Type' => 'application/json',
|
|
])->withBody(json_encode($payload), 'application/json')
|
|
->post("{$this->baseUrl}/api/user");
|
|
|
|
if ($response->successful()) {
|
|
return $response->json();
|
|
} else {
|
|
throw new Exception('Failed to process customer: ' . $response->body());
|
|
}
|
|
}
|
|
|
|
|
|
public function deleteCustomer(array $data)
|
|
{
|
|
$token = $this->getToken();
|
|
|
|
|
|
$url = "{$this->baseUrl}/api/customer/{$data['customerId']}";
|
|
|
|
$response = Http::withHeaders([
|
|
'Authorization' => "Bearer $token",
|
|
'Accept' => 'application/json',
|
|
])->delete($url);
|
|
|
|
|
|
|
|
// If response body is empty, assume success
|
|
if ($response->status() === 200 && empty($response->body())) {
|
|
return ['message' => 'Customer deleted successfully'];
|
|
}
|
|
|
|
if ($response->successful()) {
|
|
return $response->json();
|
|
} else {
|
|
throw new Exception('Failed to create customer: ' . $response->body());
|
|
}
|
|
|
|
throw new Exception('Failed to create user: ' . $response->body());
|
|
}
|
|
// public function createOrUpdateUser(array $data)
|
|
// {
|
|
// $token = $this->getToken();
|
|
|
|
// // First, check if the user exists in ThingsBoard by email
|
|
// $email = $data['email'];
|
|
|
|
// // ✅ Fetch ThingsBoard ID by email
|
|
// $response = Http::withHeaders([
|
|
// 'Authorization' => "Bearer $token",
|
|
// 'accept' => 'application/json'
|
|
// ])->get("{$this->baseUrl}/api/users?pageSize=1&page=0&textSearch=$email");
|
|
|
|
// $userExists = false;
|
|
// $thingsboardUserId = null;
|
|
|
|
// if ($response->successful()) {
|
|
// $users = $response->json()['data'] ?? [];
|
|
|
|
// if (!empty($users)) {
|
|
// $userExists = true;
|
|
// $thingsboardUserId = $users[0]['id']['id'];
|
|
// }
|
|
// }
|
|
|
|
// // ✅ Prepare payload
|
|
// $payload = [
|
|
// 'email' => $data['email'] ?? 'default@example.com',
|
|
// 'tenantId' => [
|
|
// 'id' => $data['tenantId'] ?? '6e9b7fde-0ca0-4d19-9d2a-fba98e3e12a0',
|
|
// 'entityType' => 'TENANT'
|
|
// ],
|
|
// 'customerId' => [
|
|
// 'id' => $data['customerId'],
|
|
// 'entityType' => 'CUSTOMER'
|
|
// ],
|
|
// 'authority' => $data['authority'] ?? 'TENANT_ADMIN',
|
|
// 'name' => $data['name'] ?? 'John Doe',
|
|
// 'phone' => $data['phone'] ?? '1234567890',
|
|
// 'additionalInfo' => [
|
|
// 'description' => $data['description'] ?? 'User description'
|
|
// ]
|
|
// ];
|
|
|
|
// if ($userExists && $thingsboardUserId) {
|
|
// // ✅ Update existing user in ThingsBoard
|
|
// $response = Http::withHeaders([
|
|
// 'Authorization' => "Bearer $token",
|
|
// 'accept' => 'application/json',
|
|
// 'Content-Type' => 'application/json',
|
|
// ])->withBody(json_encode($payload), 'application/json')
|
|
// ->post("{$this->baseUrl}/api/user/{$thingsboardUserId}");
|
|
// } else {
|
|
// // ✅ Create new user in ThingsBoard
|
|
// $response = Http::withHeaders([
|
|
// 'Authorization' => "Bearer $token",
|
|
// 'accept' => 'application/json',
|
|
// 'Content-Type' => 'application/json',
|
|
// ])->withBody(json_encode($payload), 'application/json')
|
|
// ->post("{$this->baseUrl}/api/user");
|
|
// }
|
|
|
|
// if ($response->successful()) {
|
|
// return $response->json();
|
|
// } else {
|
|
// throw new Exception('Failed to create or update user: ' . $response->body());
|
|
// }
|
|
// }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public function listUsers()
|
|
{
|
|
$token = $this->getToken();
|
|
|
|
$response = Http::withHeaders([
|
|
'Authorization' => "Bearer $token",
|
|
'accept' => 'application/json',
|
|
])->get("{$this->baseUrl}/api/users?pageSize=100&page=0");
|
|
|
|
if ($response->successful()) {
|
|
return $response->json();
|
|
} else {
|
|
throw new Exception('Failed to fetch users: ' . $response->body());
|
|
}
|
|
}
|
|
|
|
|
|
public function deleteUser($userId)
|
|
{
|
|
try {
|
|
$token = $this->getToken();
|
|
|
|
// ✅ Make the DELETE request to ThingsBoard
|
|
$response = Http::withHeaders([
|
|
'Authorization' => "Bearer $token",
|
|
'accept' => 'application/json',
|
|
'Content-Type' => 'application/json',
|
|
])->delete("{$this->baseUrl}/api/user/{$userId}");
|
|
|
|
// ✅ Handle API response
|
|
if ($response->failed()) {
|
|
Log::error('Failed to delete user: ' . $response->body());
|
|
|
|
return response()->json([
|
|
'error' => true,
|
|
'message' => 'Failed to delete user from ThingsBoard',
|
|
'details' => $response->json()
|
|
], $response->status());
|
|
}
|
|
|
|
// ✅ Return successful response
|
|
return response()->json([
|
|
'success' => true,
|
|
'message' => 'User deleted successfully',
|
|
'data' => $response->json()
|
|
], 200);
|
|
|
|
} catch (Exception $e) {
|
|
Log::error('Exception while deleting user: ' . $e->getMessage());
|
|
|
|
return response()->json([
|
|
'error' => true,
|
|
'message' => 'An error occurred while deleting the user',
|
|
], 500);
|
|
}
|
|
}
|
|
|
|
|
|
|
|
public function activateUser(User $user, string $password, string $activateToken)
|
|
{
|
|
try {
|
|
// Prepare the payload with the token and password
|
|
$payload = [
|
|
'activateToken' => $activateToken,
|
|
'password' => $password
|
|
];
|
|
|
|
$activationUrl = "{$this->baseUrl}/api/noauth/activate";
|
|
|
|
// Send the activation request
|
|
$response = Http::withHeaders([
|
|
'Content-Type' => 'application/json',
|
|
])->post($activationUrl, $payload);
|
|
|
|
if (!$response->successful()) {
|
|
Log::error("Failed to activate user in ThingsBoard. Error: " . $response->body());
|
|
throw new Exception('Failed to activate user: ' . $response->body());
|
|
}
|
|
|
|
Log::info("User activated successfully in ThingsBoard for User ID: {$user->id}");
|
|
|
|
} catch (\Exception $e) {
|
|
Log::error("Error activating user in ThingsBoard for User ID: {$user->id}. Exception: " . $e->getMessage());
|
|
throw $e;
|
|
}
|
|
}
|
|
|
|
|
|
public function getUserByEmailThingsBoard(string $email)
|
|
{
|
|
Log::info("Fetching ThingsBoard ID by email: $email");
|
|
|
|
$token = $this->getToken();
|
|
|
|
// First, fetch the ThingsBoard ID by email
|
|
$response = Http::withHeaders([
|
|
'Authorization' => "Bearer $token",
|
|
'accept' => 'application/json'
|
|
])->get("http://65.0.131.117:8080/api/users?pageSize=1&page=0&textSearch=$email");
|
|
|
|
if ($response->successful()) {
|
|
$data = $response->json()['data'] ?? [];
|
|
|
|
if (!empty($data)) {
|
|
$thingsboardUserId = $data[0]['id']['id'];
|
|
Log::info("Found ThingsBoard ID: $thingsboardUserId");
|
|
|
|
// Now fetch user by ID
|
|
$userResponse = Http::withHeaders([
|
|
'Authorization' => "Bearer $token",
|
|
'accept' => 'application/json'
|
|
])->get("http://65.0.131.117:8080/api/user/$thingsboardUserId");
|
|
|
|
if ($userResponse->successful()) {
|
|
return [
|
|
'status' => true,
|
|
'user' => $userResponse->json(),
|
|
'dashboard_url' => 'http://65.0.131.117:8080/dashboard'
|
|
];
|
|
} else {
|
|
Log::error("Failed to fetch user by ID. Status: " . $userResponse->status());
|
|
return [
|
|
'status' => false,
|
|
'message' => 'User not found in ThingsBoard by ID.'
|
|
];
|
|
}
|
|
}
|
|
}
|
|
|
|
Log::error("Failed to fetch ThingsBoard ID. Status: " . $response->status());
|
|
return [
|
|
'status' => false,
|
|
'message' => 'User not found in ThingsBoard by email.'
|
|
];
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|