diff --git a/app/Http/Controllers/APIS/AdminApi/AssetadmintController.php b/app/Http/Controllers/APIS/AdminApi/AssetadmintController.php index 8ddc97f..36d4c01 100644 --- a/app/Http/Controllers/APIS/AdminApi/AssetadmintController.php +++ b/app/Http/Controllers/APIS/AdminApi/AssetadmintController.php @@ -82,9 +82,9 @@ class AssetadmintController extends Controller public function storeAssest(CreateAssetRequest $request) { try { - $additionalInfo = $request->has('additional_info') && is_string($request->additional_info) - ? json_decode($request->additional_info, true) - : $request->additional_info; + // $additionalInfo = $request->has('additional_info') && is_string($request->additional_info) + // ? json_decode($request->additional_info, true) + // : $request->additional_info; $assetData = [ 'entity_type' => 'ASSET', // Backend defined 'createdTime' => now()->timestamp, // Backend defined @@ -96,7 +96,8 @@ class AssetadmintController extends Controller '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'], + // 'additionalInfo' => $additionalInfo ?? ['description' => 'Default asset description'], + 'additionalInfo' => $request->additionalInfo ]; $response = $this->adminService->createAsset($assetData); if (!$response) { @@ -115,6 +116,7 @@ class AssetadmintController extends Controller $asset->external_id = $assetData['externalId']; $asset->version = $response['version'] ?? $assetData['version']; $asset->additional_info = json_encode($response['additionalInfo'] ?? $assetData['additionalInfo']); + // 'additional_info'  => json_encode($apiData['additionalInfo'] ?? [])  $asset->save(); // Fetch only the customer name $customerName = \App\Models\Customer::where('id', $assetData['customerId'])->value('name'); @@ -129,76 +131,137 @@ class AssetadmintController extends Controller return response()->json(['error' => $e->getMessage()], 500); } } - // public function storeAssest(CreateAssetRequest $request) + + + + + + // public function listAssest() // { // try { - // $additionalInfo = $request->has('additional_info') && is_string($request->additional_info) - // ? json_decode($request->additional_info, true) - // : (is_array($request->additional_info) ? $request->additional_info : ['description' => 'Default asset description']); + // $assets = Asset::with('customer')->get()->map(function ($asset) { + // $assetData = $asset->toArray(); + // unset($assetData['customer']); + // $assetData['customer_name'] = $asset->customer?->name; + // return $assetData; + // }); - // $assetData = [ - // 'entity_type' => 'ASSET', - // 'createdTime' => now()->timestamp, - // 'tenantId' => $request->tenant_id ?? Str::uuid()->toString(), - // 'customerId' => $request->customer_xid, - // 'name' => $request->name, - // 'type' => $request->type ?? 'Default Type', - // 'label' => $request->label ?? '', - // 'assetProfileId' => $request->asset_profile_id ?? Str::uuid()->toString(), - // 'externalId' => $request->external_id ?? Str::uuid()->toString(), - // 'additionalInfo' => $additionalInfo, - // ]; + // return jsonResponseWithSuccessMessage('Assets fetched successfully', [ + // 'assests' => $assets + // ]); + // } catch (Exception $e) { - // $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 = $assetData['entity_type']; - // $asset->created_time = $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'] ?? 1; - // $asset->additional_info = json_encode($response['additionalInfo'] ?? $assetData['additionalInfo']); - // $asset->save(); - - // $customerName = \App\Models\Customer::where('id', $assetData['customerId'])->value('name'); - - // return response()->json([ - // 'message' => 'Asset created successfully!', - // 'data' => $asset, - // 'customer_name' => $customerName, - // 'api_response' => $response - // ], 200); - // } catch (\Exception $e) { - // Log::error('Error in creating asset: ' . $e->getMessage()); - // return response()->json(['error' => $e->getMessage()], 500); + // Log::error("An error occurred: " . $e->getMessage()); + // return jsonResponseWithErrorMessage($e->getMessage(), 500); // } // } + // public function listAssest() + // { + // try { + // $assets = Asset::with([ + // 'customer:id,name', + // 'userAssetLinks.user:id,first_name' // eager load first_name only + // ])->get()->map(function ($asset) { + // $assetData = $asset->toArray(); + // unset($assetData['customer'], $assetData['user_asset_links']); // remove full objects + // $assetData['customer_name'] = $asset->customer?->name; + + // // Collect user first names from user_asset_links + // $userFirstNames = $asset->userAssetLinks->map(function ($userAssetLink) { + // return optional($userAssetLink->user)->first_name; + // })->filter()->values(); // remove nulls and reset keys + + // $assetData['assign_to_user'] = $userFirstNames; + + // return $assetData; + // }); + + // return jsonResponseWithSuccessMessage('Assets fetched successfully', [ + // 'assets' => $assets + // ]); + // } catch (Exception $e) { + // Log::error("An error occurred: " . $e->getMessage()); + // return jsonResponseWithErrorMessage($e->getMessage(), 500); + // } + // } + + // public function listAssest() + // { + // try { + // $assets = Asset::with([ + // 'customer:id,name', + // 'userAssetLinks.user:id,first_name,last_name' // eager load first_name and last_name + // ])->get()->map(function ($asset) { + // $assetData = $asset->toArray(); + + // unset($assetData['customer'], $assetData['user_asset_links']); // remove full objects + + // $assetData['customer_name'] = $asset->customer?->name; + + // // Collect user id and full name (first_name + last_name) from user_asset_links + // $assignToUsers = $asset->userAssetLinks->map(function ($userAssetLink) { + // $user = $userAssetLink->user; + // if ($user) { + // return [ + // 'user_id' => $user->id, + // 'full_name' => trim($user->first_name . ' ' . $user->last_name), + // ]; + // } + // return null; + // })->filter()->values(); // remove nulls and reset keys + + // $assetData['assign_to_users'] = $assignToUsers; + + // return $assetData; + // }); + + // return jsonResponseWithSuccessMessage('Assets fetched successfully', [ + // 'assets' => $assets + // ]); + // } catch (Exception $e) { + // Log::error("An error occurred: " . $e->getMessage()); + // return jsonResponseWithErrorMessage($e->getMessage(), 500); + // } + // } public function listAssest() { try { - $assets = Asset::with('customer')->get()->map(function ($asset) { + $assets = Asset::with([ + 'customer:id,name', + 'userAssetLinks' => function ($query) { + $query->where('active', 1) // Only fetch active user asset links + ->with(['user:id,first_name,last_name']); // Eager load user info + } + ])->get()->map(function ($asset) { $assetData = $asset->toArray(); - unset($assetData['customer']); + + unset($assetData['customer'], $assetData['user_asset_links']); // remove full objects + $assetData['customer_name'] = $asset->customer?->name; + + // Collect user id and full name (first_name + last_name) from active user_asset_links + $assignToUsers = $asset->userAssetLinks->map(function ($userAssetLink) { + $user = $userAssetLink->user; + if ($user) { + return [ + 'user_id' => $user->id, + 'full_name' => trim($user->first_name . ' ' . $user->last_name), + ]; + } + return null; + })->filter()->values(); // remove nulls and reset keys + + $assetData['assign_to_users'] = $assignToUsers; + return $assetData; }); return jsonResponseWithSuccessMessage('Assets fetched successfully', [ - 'assests' => $assets + 'assets' => $assets ]); } catch (Exception $e) { Log::error("An error occurred: " . $e->getMessage()); @@ -210,6 +273,9 @@ class AssetadmintController extends Controller + + + public function deleteAsset(Request $request) { $assetId = $request->input('assetId'); // Fetching ID from request body @@ -256,58 +322,152 @@ class AssetadmintController extends Controller } + // 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); + // } + // } + + // public function assignAssetToUser(Request $request) + // { + // try { + // $request->validate([ + // 'user_id' => 'required|exists:users,id', + // 'asset_id' => 'required|uuid', + // 'active' => 'required|boolean' + // ]); + + // $userId = $request->user_id; + // $assetId = $request->asset_id; + // $activeStatus = $request->active; + + // $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 = $activeStatus; + // $userAssetLink->save(); + + // $message = $activeStatus + // ? 'Asset assigned to user successfully.' + // : 'Asset unassigned from user.'; + + // Log::info($message, ['userId' => $userId, 'assetId' => $assetId]); + + // return response()->json([ + // 'success' => true, + // 'message' => $message, + // 'data' => $userAssetLink + // ], 200); + // } catch (Exception $e) { + // Log::error("Error assigning/unassigning asset: " . $e->getMessage()); + // return response()->json([ + // 'success' => false, + // 'message' => 'Failed to assign or unassign asset to user', + // 'error' => $e->getMessage() + // ], 500); + // } + // } public function assignAssetToUser(Request $request) { - try { $request->validate([ 'user_id' => 'required|exists:users,id', - 'asset_id' => 'required|uuid' + 'asset_id' => 'required|uuid', + 'active' => 'required|boolean' ]); $userId = $request->user_id; $assetId = $request->asset_id; + $activeStatus = $request->active; - $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 ($activeStatus) { + // If assigning asset, first unassign from any other users + UserAssetLink::where('asset_id', $assetId) + ->update(['active' => 0]); } - if ($userAssetLink->active == 1) { - $userAssetLink->active = 0; - $userAssetLink->save(); - return response()->json([ - 'success' => true, - 'message' => 'Asset unassigned from user.', - 'data' => $userAssetLink - ], 200); - } + // Now either update existing record or create a new one for this user and asset + $userAssetLink = UserAssetLink::firstOrNew([ + 'user_id' => $userId, + 'asset_id' => $assetId + ]); - $userAssetLink->active = 1; + $userAssetLink->active = $activeStatus; $userAssetLink->save(); + + $message = $activeStatus + ? 'Asset assigned to user successfully.' + : 'Asset unassigned from user.'; + + Log::info($message, ['userId' => $userId, 'assetId' => $assetId]); + return response()->json([ 'success' => true, - 'message' => 'Asset reassigned to user successfully.', + 'message' => $message, 'data' => $userAssetLink ], 200); } catch (Exception $e) { - Log::error("Error assigning asset: " . $e->getMessage()); + Log::error("Error assigning/unassigning asset: " . $e->getMessage()); return response()->json([ 'success' => false, 'message' => 'Failed to assign or unassign asset to user', @@ -316,6 +476,8 @@ class AssetadmintController extends Controller } } + + public function customerList() { try { @@ -331,17 +493,142 @@ class AssetadmintController extends Controller } + // public function assestlistCustomer($customerId) + // { + // try { + // $assets = Asset::with('customer:id,name') + // ->where('customer_xid', $customerId) + // ->get() + // ->map(function ($asset) { + // return collect($asset) + // ->except('customer') // remove the full customer object + // ->merge([ + // 'customer_name' => optional($asset->customer)->name, + // ]); + // }); + + // if ($assets->isEmpty()) { + // return response()->json(['message' => 'No assets found for this customer ID'], 200); + // } + + // return jsonResponseWithSuccessMessage('Assets fetched successfully', [ + // 'assets' => $assets + // ]); + // } catch (Exception $e) { + // Log::error("An error occurred in asset listing: " . $e->getMessage()); + // return jsonResponseWithErrorMessage($e->getMessage(), 500); + // } + // } + + // public function assestlistCustomer($customerId) + // { + // try { + // $assets = Asset::with([ + // 'customer:id,name', + // 'userAssetLinks.user:id,name' // eager load user through userAssetLink + // ]) + // ->where('customer_xid', $customerId) + // ->get() + // ->map(function ($asset) { + // // Get user names linked to the asset + // $userNames = $asset->userAssetLinks->map(function ($userAssetLink) { + // return optional($userAssetLink->user)->name; + // })->filter()->values(); // filter nulls and reset keys + + // return collect($asset) + // ->except('customer', 'userAssetLinks') // remove full objects + // ->merge([ + // 'customer_name' => optional($asset->customer)->name, + // 'assign_to_user' => $userNames, // attach user names + // ]); + // }); + + // if ($assets->isEmpty()) { + // return response()->json(['message' => 'No assets found for this customer ID'], 200); + // } + + // return jsonResponseWithSuccessMessage('Assets fetched successfully', [ + // 'assets' => $assets + // ]); + // } catch (Exception $e) { + // Log::error("An error occurred in asset listing: " . $e->getMessage()); + // return jsonResponseWithErrorMessage($e->getMessage(), 500); + // } + // } + + // public function assestlistCustomer($customerId) + // { + // try { + // $assets = Asset::with([ + // 'customer:id,name', + // 'userAssetLinks.user:id,first_name,last_name' // eager load first_name and last_name + // ]) + // ->where('customer_xid', $customerId) + // ->get() + // ->map(function ($asset) { + // // Get user details (id and full name) linked to the asset + // $assignToUsers = $asset->userAssetLinks->map(function ($userAssetLink) { + // $user = $userAssetLink->user; + // if ($user) { + // return [ + // 'user_id' => $user->id, + // 'full_name' => trim($user->first_name . ' ' . $user->last_name), + // ]; + // } + // return null; + // })->filter()->values(); // filter nulls and reset keys + + // return collect($asset) + // ->except('customer', 'userAssetLinks') // remove full objects + // ->merge([ + // 'customer_name' => optional($asset->customer)->name, + // 'assign_to_users' => $assignToUsers, // attach user_id and full_name + // ]); + // }); + + // if ($assets->isEmpty()) { + // return response()->json(['message' => 'No assets found for this customer ID'], 200); + // } + + // return jsonResponseWithSuccessMessage('Assets fetched successfully', [ + // 'assets' => $assets + // ]); + // } catch (Exception $e) { + // Log::error("An error occurred in asset listing: " . $e->getMessage()); + // return jsonResponseWithErrorMessage($e->getMessage(), 500); + // } + // } + + public function assestlistCustomer($customerId) { try { - $assets = Asset::with('customer:id,name') + $assets = Asset::with([ + 'customer:id,name', + 'userAssetLinks' => function ($query) { + $query->where('active', 1) // Only active links + ->with('user:id,first_name,last_name'); // Eager load user + } + ]) ->where('customer_xid', $customerId) ->get() ->map(function ($asset) { + // Since only active userAssetLinks are fetched, take the first one (only one user per asset) + $assignToUser = $asset->userAssetLinks->first(); // get first active link if exists + + $userDetails = null; + if ($assignToUser && $assignToUser->user) { + $userDetails = [ + 'user_id' => $assignToUser->user->id, + 'full_name' => trim($assignToUser->user->first_name . ' ' . $assignToUser->user->last_name), + ]; + } + return collect($asset) - ->except('customer') // remove the full customer object + ->except('customer', 'userAssetLinks') // remove full objects ->merge([ 'customer_name' => optional($asset->customer)->name, + 'assign_to_user' => $userDetails, // assign only one user ]); }); diff --git a/app/Http/Controllers/AlarmControllerCommon.php b/app/Http/Controllers/AlarmControllerCommon.php index 8456f26..915721e 100644 --- a/app/Http/Controllers/AlarmControllerCommon.php +++ b/app/Http/Controllers/AlarmControllerCommon.php @@ -108,7 +108,7 @@ class AlarmControllerCommon extends Controller public function acknowledgeAlarmById($id) { try { - $token = app('App\Services\AdminService')->getToken(); // Fetch cached token + $token = app('App\Services\AdminService')->getToken(); // Fetch cached token0 $url = env('THINGSBOARD_URL') . "/api/alarm/{$id}"; $getResponse = Http::withHeaders([ @@ -149,6 +149,8 @@ class AlarmControllerCommon extends Controller ]); } + + return jsonResponseWithErrorMessage('Failed to acknowledge alarm: ' . $ackResponse->body(), $ackResponse->status()); } catch (\Exception $e) { return jsonResponseWithErrorMessage('An error occurred: ' . $e->getMessage(), 500); @@ -200,6 +202,7 @@ class AlarmControllerCommon extends Controller ]); } + return jsonResponseWithErrorMessage('Failed to clear alarm: ' . $clearResponse->body(), $clearResponse->status()); } catch (\Exception $e) { Log::error('Error clearing alarm: ' . $e->getMessage()); diff --git a/app/Models/Asset.php b/app/Models/Asset.php index fd8dc5f..5fb248c 100644 --- a/app/Models/Asset.php +++ b/app/Models/Asset.php @@ -57,6 +57,8 @@ class Asset extends Model { return $this->hasMany(Device::class, 'asset_id', 'id'); } - - + public function userAssetLinks() + { + return $this->hasMany(UserAssetLink::class, 'asset_id', 'id'); + } } diff --git a/app/Services/AdminService.php b/app/Services/AdminService.php index e2bd58c..a6f2a16 100644 --- a/app/Services/AdminService.php +++ b/app/Services/AdminService.php @@ -93,7 +93,7 @@ class AdminService // throw new Exception('Failed to create asset: ' . $response->body()); // } // } - + // public function createAsset(array $data) // { // $token = $this->getToken(); @@ -142,7 +142,8 @@ class AdminService 'type' => $data['type'], 'label' => $data['label'], // 'version' => removed to let backend default to 1 - 'additionalInfo' => $data['additionalInfo'], + // 'additionalInfo' => $data['additionalInfo'], + 'additionalInfo' => ['description' => $data['additionalInfo'] ?? 'User description'], ]; $response = Http::withHeaders([ @@ -160,37 +161,6 @@ class AdminService } } - // public function createAsset(array $data) - // { - // $token = $this->getToken(); - - // $payload = [ - // 'entityType' => $data['entity_type'], - // 'createdTime' => $data['createdTime'], - // 'customerId' => [ - // 'id' => $data['customerId'], - // 'entityType' => 'CUSTOMER' - // ], - // 'name' => $data['name'], - // 'type' => $data['type'], - // 'label' => $data['label'], - // 'additionalInfo' => $data['additionalInfo'], // must be an array - // ]; - - // $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 { - // Log::error('Error in creating asset: ' . $response->body()); - // throw new Exception('Failed to create asset: ' . $response->body()); - // } - // } diff --git a/app/Services/AlarmService.php b/app/Services/AlarmService.php index 5b3f93e..ba28ef0 100644 --- a/app/Services/AlarmService.php +++ b/app/Services/AlarmService.php @@ -320,8 +320,7 @@ class AlarmService if (!empty($data['deviceId'])) { $deviceId = $data['deviceId']; - } - elseif (!empty($data['assetId'])) { + } elseif (!empty($data['assetId'])) { $deviceId = Device::where('asset_id', $data['assetId'])->value('id'); } @@ -387,7 +386,7 @@ class AlarmService $payload = [ 'type' => $data['type'] ?? null, 'severity' => $data['severity'] ?? null, - 'acknowledged' => $data['acknowledged'] ?? null, + 'acknowledged' => false, 'cleared' => $data['cleared'] ?? Carbon::now()->timestamp, 'startTs' => $data['startTs'] ?? Carbon::now()->timestamp, 'endTs' => $data['endTs'] ?? Carbon::now()->timestamp,