sayali #20
223
app/Http/Controllers/APIS/AdminApi/AssetadmintController.php
Normal file
223
app/Http/Controllers/APIS/AdminApi/AssetadmintController.php
Normal file
@@ -0,0 +1,223 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\APIS\AdminApi;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Http\Requests\CreateAssetRequest;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
use App\Services\AdminService;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Str;
|
||||
use App\Models\Asset;
|
||||
use App\Models\UserAssetLink;
|
||||
use Exception;
|
||||
|
||||
class AssetadmintController extends Controller
|
||||
{
|
||||
private $adminService;
|
||||
|
||||
public function __construct(AdminService $adminService)
|
||||
{
|
||||
$this->adminService = $adminService;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public function storeAssest(Request $request)
|
||||
{
|
||||
try {
|
||||
$additionalInfo = $request->has('additional_info') && is_string($request->additional_info)
|
||||
? json_decode($request->additional_info, true)
|
||||
: $request->additional_info;
|
||||
|
||||
$assetData = [
|
||||
'entity_type' => $request->entity_type,
|
||||
'createdTime' => $request->created_time ?? now()->timestamp,
|
||||
'tenantId' => $request->tenant_id ?? Str::uuid()->toString(),
|
||||
'customerId' => $request->customer_xid,
|
||||
'name' => $request->name,
|
||||
'type' => $request->type,
|
||||
'label' => $request->label,
|
||||
'assetProfileId' => $request->asset_profile_id ?? Str::uuid()->toString(),
|
||||
'externalId' => $request->external_id ?? Str::uuid()->toString(),
|
||||
'version' => $request->version ?? '1.0',
|
||||
'additionalInfo' => $additionalInfo ?? ['description' => 'Default asset description'],
|
||||
];
|
||||
|
||||
$response = $this->adminService->createAsset($assetData);
|
||||
|
||||
if (!$response) {
|
||||
throw new Exception('Failed to create asset via admin service');
|
||||
}
|
||||
|
||||
$asset = new Asset();
|
||||
$asset->id = $response['id']['id'] ?? Str::uuid()->toString();
|
||||
$asset->entity_type = $response['entityType'] ?? $assetData['entity_type'];
|
||||
$asset->created_time = $response['createdTime'] ?? $assetData['createdTime'];
|
||||
$asset->tenant_id = $assetData['tenantId'];
|
||||
$asset->customer_xid = $assetData['customerId'];
|
||||
$asset->name = $response['name'] ?? $assetData['name'];
|
||||
$asset->type = $response['type'] ?? $assetData['type'];
|
||||
$asset->label = $response['label'] ?? $assetData['label'];
|
||||
$asset->asset_profile_id = $assetData['assetProfileId'];
|
||||
$asset->external_id = $assetData['externalId'];
|
||||
$asset->version = $response['version'] ?? $assetData['version'];
|
||||
$asset->additional_info = json_encode($response['additionalInfo'] ?? $assetData['additionalInfo']);
|
||||
|
||||
$asset->save();
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Asset created successfully!',
|
||||
'data' => $asset,
|
||||
'api_response' => $response
|
||||
], 200);
|
||||
} catch (Exception $e) {
|
||||
Log::error('Error in creating asset: ' . $e->getMessage());
|
||||
return response()->json(['error' => $e->getMessage()], 500);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public function listAssest()
|
||||
{
|
||||
try {
|
||||
$assests = Asset::all();
|
||||
return jsonResponseWithSuccessMessage('Assests fetched successfully', [
|
||||
'assests' => $assests
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
Log::error("An error occurred: " . $e->getMessage());
|
||||
return jsonResponseWithErrorMessage($e->getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public function deleteAsset($assetId)
|
||||
{
|
||||
|
||||
if (!$assetId) {
|
||||
return jsonResponseWithErrorMessage('Asset ID is required', 400);
|
||||
}
|
||||
|
||||
$response = $this->adminService->deleteAsset(['assetId' => $assetId]);
|
||||
|
||||
Log::info("Response: " . json_encode($response));
|
||||
|
||||
if (!is_array($response)) {
|
||||
Log::error("Unexpected API response format.", ['response' => $response]);
|
||||
return jsonResponseWithErrorMessage('Unexpected API response format', 500);
|
||||
}
|
||||
|
||||
if (isset($response['status']) && $response['status'] === 400) {
|
||||
Log::error("Failed to delete asset: " . $response['message']);
|
||||
return jsonResponseWithErrorMessage($response['message'], 400, $response);
|
||||
}
|
||||
|
||||
if (empty($response)) {
|
||||
Log::error("API Data is empty, cannot delete asset.");
|
||||
return jsonResponseWithErrorMessage('Failed to delete asset', 400);
|
||||
}
|
||||
|
||||
$asset = Asset::where('id', $assetId)->first();
|
||||
if ($asset) {
|
||||
$asset->delete();
|
||||
}
|
||||
|
||||
return jsonResponseWithSuccessMessage('Asset deleted successfully', ['api_response' => $response]);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public function assignAssetToUser(Request $request)
|
||||
{
|
||||
|
||||
try {
|
||||
$request->validate([
|
||||
'user_id' => 'required|exists:users,id',
|
||||
'asset_id' => 'required|uuid'
|
||||
]);
|
||||
|
||||
$userId = $request->user_id;
|
||||
$assetId = $request->asset_id;
|
||||
|
||||
$userAssetLink = UserAssetLink::where('user_id', $userId)
|
||||
->where('asset_id', $assetId)
|
||||
->first();
|
||||
|
||||
if (!$userAssetLink) {
|
||||
$userAssetLink = new UserAssetLink();
|
||||
$userAssetLink->user_id = $userId;
|
||||
$userAssetLink->asset_id = $assetId;
|
||||
$userAssetLink->active = 1;
|
||||
$userAssetLink->save();
|
||||
|
||||
Log::info("Asset successfully assigned to user.", ['userId' => $userId, 'assetId' => $assetId]);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => 'Asset assigned to user successfully.',
|
||||
'data' => $userAssetLink
|
||||
], 200);
|
||||
}
|
||||
|
||||
if ($userAssetLink->active == 1) {
|
||||
$userAssetLink->active = 0;
|
||||
$userAssetLink->save();
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => 'Asset unassigned from user.',
|
||||
'data' => $userAssetLink
|
||||
], 200);
|
||||
}
|
||||
|
||||
$userAssetLink->active = 1;
|
||||
$userAssetLink->save();
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => 'Asset reassigned to user successfully.',
|
||||
'data' => $userAssetLink
|
||||
], 200);
|
||||
} catch (Exception $e) {
|
||||
Log::error("Error assigning asset: " . $e->getMessage());
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Failed to assign or unassign asset to user',
|
||||
'error' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\APIS\CustomerApi;
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Http\Requests\CreateAssetRequest;
|
||||
use App\Models\Asset;
|
||||
use App\Services\AdminService;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Str; // Import for UUID generation
|
||||
use Exception;
|
||||
|
||||
class AssetController extends Controller
|
||||
{
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
39
app/Http/Requests/CreateAssetRequest.php
Normal file
39
app/Http/Requests/CreateAssetRequest.php
Normal file
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class CreateAssetRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'id' => 'required|uuid',
|
||||
'entity_type' => 'required|string|in:ASSET',
|
||||
'created_time' => 'required|integer',
|
||||
'tenant_id' => 'required|uuid',
|
||||
'customer_xid' => 'required|uuid',
|
||||
'name' => 'required|string|max:255',
|
||||
'type' => 'required|string|max:255',
|
||||
'label' => 'nullable|string|max:255',
|
||||
'asset_profile_id' => 'required|uuid',
|
||||
'external_id' => 'nullable|uuid',
|
||||
'version' => 'nullable|integer|min:1',
|
||||
'additional_info' => 'nullable|json',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class Asset extends Model
|
||||
{
|
||||
@@ -34,10 +35,21 @@ class Asset extends Model
|
||||
'external_id' => 'string',
|
||||
'additional_info' => 'array',
|
||||
];
|
||||
public static function boot()
|
||||
{
|
||||
parent::boot();
|
||||
|
||||
static::creating(function ($model) {
|
||||
// Generate UUIDs only if they are not already provided
|
||||
$model->id = $model->id ?? Str::uuid()->toString();
|
||||
$model->tenant_id = $model->tenant_id ?? Str::uuid()->toString();
|
||||
$model->asset_profile_id = $model->asset_profile_id ?? Str::uuid()->toString();
|
||||
$model->external_id = $model->external_id ?? Str::uuid()->toString();
|
||||
});
|
||||
}
|
||||
|
||||
public function devices()
|
||||
{
|
||||
return $this->hasMany(Device::class, 'asset_id', 'id');
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ use Illuminate\Support\Facades\Cache;
|
||||
use Exception;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
use App\Models\Asset;
|
||||
|
||||
class AdminService
|
||||
{
|
||||
@@ -30,7 +30,7 @@ class AdminService
|
||||
}
|
||||
|
||||
$response = Http::withHeaders([
|
||||
'accept' => 'application/json',
|
||||
// 'accept' => 'application/json',
|
||||
'Content-Type' => 'application/json',
|
||||
])
|
||||
->post("{$this->baseUrl}/api/auth/login", [
|
||||
@@ -48,6 +48,93 @@ class AdminService
|
||||
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
|
||||
// }
|
||||
public function createOrUpdateCustomer(array $data)
|
||||
{
|
||||
$token = $this->getToken();
|
||||
@@ -148,6 +235,143 @@ class AdminService
|
||||
}
|
||||
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
public function deleteCustomer(array $data)
|
||||
{
|
||||
$token = $this->getToken();
|
||||
@@ -266,133 +490,121 @@ class AdminService
|
||||
}
|
||||
|
||||
|
||||
public function deleteUser($userId)
|
||||
{
|
||||
try {
|
||||
$token = $this->getToken();
|
||||
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}");
|
||||
// ✅ 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());
|
||||
// ✅ 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' => 'Failed to delete user from ThingsBoard',
|
||||
'details' => $response->json()
|
||||
], $response->status());
|
||||
'message' => 'An error occurred while deleting the user',
|
||||
], 500);
|
||||
}
|
||||
|
||||
// ✅ 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
|
||||
];
|
||||
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";
|
||||
$activationUrl = "{$this->baseUrl}/api/noauth/activate";
|
||||
|
||||
// Send the activation request
|
||||
// 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([
|
||||
'Content-Type' => 'application/json',
|
||||
])->post($activationUrl, $payload);
|
||||
'Authorization' => "Bearer $token",
|
||||
'accept' => 'application/json'
|
||||
])->get("http://65.0.131.117:8080/api/users?pageSize=1&page=0&textSearch=$email");
|
||||
|
||||
if (!$response->successful()) {
|
||||
Log::error("Failed to activate user in ThingsBoard. Error: " . $response->body());
|
||||
throw new Exception('Failed to activate user: ' . $response->body());
|
||||
}
|
||||
if ($response->successful()) {
|
||||
$data = $response->json()['data'] ?? [];
|
||||
|
||||
Log::info("User activated successfully in ThingsBoard for User ID: {$user->id}");
|
||||
if (!empty($data)) {
|
||||
$thingsboardUserId = $data[0]['id']['id'];
|
||||
Log::info("Found ThingsBoard ID: $thingsboardUserId");
|
||||
|
||||
} catch (\Exception $e) {
|
||||
Log::error("Error activating user in ThingsBoard for User ID: {$user->id}. Exception: " . $e->getMessage());
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
// Now fetch user by ID
|
||||
$userResponse = Http::withHeaders([
|
||||
'Authorization' => "Bearer $token",
|
||||
'accept' => 'application/json'
|
||||
])->get("http://65.0.131.117:8080/api/user/$thingsboardUserId");
|
||||
|
||||
|
||||
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.'
|
||||
];
|
||||
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.'
|
||||
];
|
||||
}
|
||||
|
||||
Log::error("Failed to fetch ThingsBoard ID. Status: " . $response->status());
|
||||
return [
|
||||
'status' => false,
|
||||
'message' => 'User not found in ThingsBoard by email.'
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
<?php
|
||||
|
||||
// use App\Http\Controllers\AssetController;
|
||||
use App\Http\Controllers\APIS\CustomerApi\CustomerController;
|
||||
use App\Http\Controllers\APIS\AdminApi\UsersController;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
|
||||
use App\Http\Controllers\APIS\AdminApi\AssetadmintController;
|
||||
Route::get('/adminapi', function () {
|
||||
return ('Welcome to admin api routes.');
|
||||
});
|
||||
|
||||
// Route::post('')
|
||||
|
||||
Route::post('/asset', [AssetadmintController::class, 'storeAssest']);
|
||||
Route::get('/list-assets', [AssetadmintController::class, 'listAssest']);
|
||||
Route::delete('/delete-assets/{assetId}', [AssetadmintController::class, 'deleteAsset']);
|
||||
Route::post('/assign-asset', [AssetadmintController::class, 'assignAssetToUser']);
|
||||
|
||||
|
||||
//******************************************************* Customer API********************************************************
|
||||
|
||||
Reference in New Issue
Block a user