Files
backend_vib360_laravel/app/Http/Controllers/APIS/AdminApi/AssetadmintController.php

460 lines
18 KiB
PHP
Raw Normal View History

2025-03-20 11:52:34 +05:30
<?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;
2025-03-21 12:11:18 +05:30
use App\Models\Customer;
2025-03-20 11:52:34 +05:30
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;
}
2025-04-15 13:42:38 +05:30
// 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;
// $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);
// }
// }
2025-04-14 19:36:19 +05:30
2025-03-21 12:11:18 +05:30
public function storeAssest(CreateAssetRequest $request)
2025-03-20 11:52:34 +05:30
{
try {
2025-04-25 15:29:40 +05:30
// $additionalInfo = $request->has('additional_info') && is_string($request->additional_info)
// ? json_decode($request->additional_info, true)
// : $request->additional_info;
2025-03-20 11:52:34 +05:30
$assetData = [
2025-04-15 13:42:38 +05:30
'entity_type' => 'ASSET', // Backend defined
'createdTime' => now()->timestamp, // Backend defined
2025-03-20 11:52:34 +05:30
'tenantId' => $request->tenant_id ?? Str::uuid()->toString(),
'customerId' => $request->customer_xid,
'name' => $request->name,
2025-04-15 13:42:38 +05:30
'type' => $request->type ?? 'Default Type',
'label' => $request->label ?? '',
2025-03-20 11:52:34 +05:30
'assetProfileId' => $request->asset_profile_id ?? Str::uuid()->toString(),
'externalId' => $request->external_id ?? Str::uuid()->toString(),
'version' => $request->version ?? '1.0',
2025-04-25 15:29:40 +05:30
// 'additionalInfo' => $additionalInfo ?? ['description' => 'Default asset description'],
'additionalInfo' => $request->additionalInfo
2025-03-20 11:52:34 +05:30
];
$response = $this->adminService->createAsset($assetData);
if (!$response) {
2025-04-14 19:36:19 +05:30
throw new \Exception('Failed to create asset via admin service');
2025-03-20 11:52:34 +05:30
}
$asset = new Asset();
$asset->id = $response['id']['id'] ?? Str::uuid()->toString();
2025-04-15 13:42:38 +05:30
$asset->entity_type = $assetData['entity_type']; // From backend
$asset->created_time = $assetData['createdTime']; // From backend
2025-03-20 11:52:34 +05:30
$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']);
2025-04-25 15:29:40 +05:30
// 'additional_info'  => json_encode($apiData['additionalInfo'] ?? []) 
2025-03-20 11:52:34 +05:30
$asset->save();
2025-04-14 19:36:19 +05:30
// Fetch only the customer name
2025-04-15 11:29:12 +05:30
$customerName = \App\Models\Customer::where('id', $assetData['customerId'])->value('name');
2025-03-20 11:52:34 +05:30
return response()->json([
'message' => 'Asset created successfully!',
'data' => $asset,
2025-04-14 19:36:19 +05:30
'customer_name' => $customerName,
2025-03-20 11:52:34 +05:30
'api_response' => $response
], 200);
2025-04-14 19:36:19 +05:30
} catch (\Exception $e) {
2025-03-20 11:52:34 +05:30
Log::error('Error in creating asset: ' . $e->getMessage());
return response()->json(['error' => $e->getMessage()], 500);
}
}
2025-04-15 17:05:36 +05:30
2025-03-20 11:52:34 +05:30
2025-04-15 13:42:38 +05:30
2025-04-28 12:08:04 +05:30
// public function listAssest()
// {
// try {
// $assets = Asset::with('customer')->get()->map(function ($asset) {
// $assetData = $asset->toArray();
// unset($assetData['customer']);
// $assetData['customer_name'] = $asset->customer?->name;
// return $assetData;
// });
// return jsonResponseWithSuccessMessage('Assets fetched successfully', [
// 'assests' => $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,name' // eager load user names
// ])->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 names from user_asset_links
// $userNames = $asset->userAssetLinks->map(function ($userAssetLink) {
// return optional($userAssetLink->user)->name;
// })->filter()->values(); // remove nulls and reset keys
// $assetData['user_names'] = $userNames;
// return $assetData;
// });
// return jsonResponseWithSuccessMessage('Assets fetched successfully', [
// 'assets' => $assets
// ]);
// } catch (Exception $e) {
// Log::error("An error occurred: " . $e->getMessage());
// return jsonResponseWithErrorMessage($e->getMessage(), 500);
// }
// }
2025-03-20 11:52:34 +05:30
public function listAssest()
{
try {
2025-04-28 12:08:04 +05:30
$assets = Asset::with([
'customer:id,name',
'userAssetLinks.user:id,first_name' // eager load first_name only
])->get()->map(function ($asset) {
2025-04-08 12:52:01 +05:30
$assetData = $asset->toArray();
2025-04-28 12:08:04 +05:30
unset($assetData['customer'], $assetData['user_asset_links']); // remove full objects
2025-04-08 12:52:01 +05:30
$assetData['customer_name'] = $asset->customer?->name;
2025-04-28 12:08:04 +05:30
// 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;
2025-04-08 12:52:01 +05:30
return $assetData;
});
return jsonResponseWithSuccessMessage('Assets fetched successfully', [
2025-04-28 12:08:04 +05:30
'assets' => $assets
2025-03-20 11:52:34 +05:30
]);
} catch (Exception $e) {
Log::error("An error occurred: " . $e->getMessage());
return jsonResponseWithErrorMessage($e->getMessage(), 500);
}
}
2025-03-28 20:01:51 +05:30
2025-03-28 13:54:21 +05:30
2025-04-08 12:52:01 +05:30
2025-04-28 12:08:04 +05:30
2025-03-28 13:54:21 +05:30
public function deleteAsset(Request $request)
2025-03-20 11:52:34 +05:30
{
2025-03-28 13:54:21 +05:30
$assetId = $request->input('assetId'); // Fetching ID from request body
2025-03-20 11:52:34 +05:30
if (!$assetId) {
return jsonResponseWithErrorMessage('Asset ID is required', 400);
}
2025-03-28 13:54:21 +05:30
2025-04-15 19:12:46 +05:30
try {
$response = $this->adminService->deleteAsset(['assetId' => $assetId]);
Log::info("Asset delete API response", ['response' => $response]);
2025-03-28 13:54:21 +05:30
2025-04-15 19:12:46 +05:30
if (!is_array($response)) {
Log::error("Unexpected API response format", ['response' => $response]);
return jsonResponseWithErrorMessage('Unexpected API response format', 500);
}
2025-03-28 13:54:21 +05:30
2025-04-15 19:12:46 +05:30
if (isset($response['status']) && $response['status'] === 400) {
Log::error("API failed to delete asset", ['message' => $response['message']]);
return jsonResponseWithErrorMessage($response['message'], 400, $response);
}
2025-03-28 13:54:21 +05:30
2025-04-15 19:12:46 +05:30
if (empty($response)) {
Log::error("API response is empty while deleting asset");
return jsonResponseWithErrorMessage('Failed to delete asset', 400);
}
2025-03-28 13:54:21 +05:30
2025-04-15 19:12:46 +05:30
// Delete from local database
$asset = Asset::find($assetId);
if ($asset) {
$asset->delete();
} else {
Log::warning("Asset not found in DB", ['assetId' => $assetId]);
}
2025-03-28 13:54:21 +05:30
2025-04-15 19:12:46 +05:30
return jsonResponseWithSuccessMessage('Asset deleted successfully', ['api_response' => $response]);
} catch (\Exception $e) {
Log::error("Exception while deleting asset", [
'message' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
return jsonResponseWithErrorMessage('An error occurred while deleting the asset', 500);
}
2025-03-20 11:52:34 +05:30
}
2025-03-28 13:54:21 +05:30
2025-04-25 15:29:40 +05:30
// 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);
// }
// }
2025-04-15 19:12:46 +05:30
2025-03-20 11:52:34 +05:30
public function assignAssetToUser(Request $request)
{
try {
$request->validate([
'user_id' => 'required|exists:users,id',
2025-04-25 15:29:40 +05:30
'asset_id' => 'required|uuid',
'active' => 'required|boolean'
2025-03-20 11:52:34 +05:30
]);
$userId = $request->user_id;
$assetId = $request->asset_id;
2025-04-25 15:29:40 +05:30
$activeStatus = $request->active;
2025-03-20 11:52:34 +05:30
$userAssetLink = UserAssetLink::where('user_id', $userId)
->where('asset_id', $assetId)
->first();
if (!$userAssetLink) {
$userAssetLink = new UserAssetLink();
$userAssetLink->user_id = $userId;
$userAssetLink->asset_id = $assetId;
2025-04-25 15:29:40 +05:30
}
2025-03-20 11:52:34 +05:30
2025-04-25 15:29:40 +05:30
$userAssetLink->active = $activeStatus;
$userAssetLink->save();
2025-03-20 11:52:34 +05:30
2025-04-25 15:29:40 +05:30
$message = $activeStatus
? 'Asset assigned to user successfully.'
: 'Asset unassigned from user.';
2025-03-20 11:52:34 +05:30
2025-04-25 15:29:40 +05:30
Log::info($message, ['userId' => $userId, 'assetId' => $assetId]);
2025-03-20 11:52:34 +05:30
return response()->json([
'success' => true,
2025-04-25 15:29:40 +05:30
'message' => $message,
2025-03-20 11:52:34 +05:30
'data' => $userAssetLink
], 200);
} catch (Exception $e) {
2025-04-25 15:29:40 +05:30
Log::error("Error assigning/unassigning asset: " . $e->getMessage());
2025-03-20 11:52:34 +05:30
return response()->json([
'success' => false,
'message' => 'Failed to assign or unassign asset to user',
'error' => $e->getMessage()
], 500);
}
}
2025-03-21 12:11:18 +05:30
2025-04-25 15:29:40 +05:30
2025-03-21 12:11:18 +05:30
public function customerList()
{
try {
$customers = Customer::all();
return jsonResponseWithSuccessMessage('Customers fetched successfully', [
'customers' => $customers
]);
} catch (Exception $e) {
Log::error("An error occurred: " . $e->getMessage());
return jsonResponseWithErrorMessage($e->getMessage(), 500);
}
}
2025-04-28 12:08:04 +05:30
// 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);
// }
// }
2025-03-21 12:11:18 +05:30
public function assestlistCustomer($customerId)
{
try {
2025-04-28 12:08:04 +05:30
$assets = Asset::with([
'customer:id,name',
'userAssetLinks.user:id,name' // eager load user through userAssetLink
])
->where('customer_xid', $customerId)
->get()
->map(function ($asset) {
2025-04-28 12:08:04 +05:30
// 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)
2025-04-28 12:08:04 +05:30
->except('customer', 'userAssetLinks') // remove full objects
->merge([
'customer_name' => optional($asset->customer)->name,
2025-04-28 12:08:04 +05:30
'assign_to_user' => $userNames, // attach user names
]);
});
if ($assets->isEmpty()) {
2025-04-21 14:43:49 +05:30
return response()->json(['message' => 'No assets found for this customer ID'], 200);
}
2025-03-21 12:11:18 +05:30
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);
2025-03-21 12:11:18 +05:30
}
}
2025-03-20 11:52:34 +05:30
}