Files
backend_vib360_laravel/app/Http/Controllers/APIS/AdminApi/AssetadmintController.php
sayaliparab ec67eca87b assignTouser
2025-04-28 12:08:04 +05:30

460 lines
18 KiB
PHP
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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 App\Models\Customer;
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(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);
// }
// }
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' => 'ASSET', // Backend defined
'createdTime' => now()->timestamp, // Backend defined
'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(),
'version' => $request->version ?? '1.0',
// 'additionalInfo' => $additionalInfo ?? ['description' => 'Default asset description'],
'additionalInfo' => $request->additionalInfo
];
$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']; // From backend
$asset->created_time = $assetData['createdTime']; // From backend
$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']);
// 'additional_info'  => json_encode($apiData['additionalInfo'] ?? []) 
$asset->save();
// Fetch only the customer name
$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);
}
}
// 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);
// }
// }
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 deleteAsset(Request $request)
{
$assetId = $request->input('assetId'); // Fetching ID from request body
if (!$assetId) {
return jsonResponseWithErrorMessage('Asset ID is required', 400);
}
try {
$response = $this->adminService->deleteAsset(['assetId' => $assetId]);
Log::info("Asset delete API response", ['response' => $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("API failed to delete asset", ['message' => $response['message']]);
return jsonResponseWithErrorMessage($response['message'], 400, $response);
}
if (empty($response)) {
Log::error("API response is empty while deleting asset");
return jsonResponseWithErrorMessage('Failed to delete asset', 400);
}
// Delete from local database
$asset = Asset::find($assetId);
if ($asset) {
$asset->delete();
} else {
Log::warning("Asset not found in DB", ['assetId' => $assetId]);
}
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);
}
}
// 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 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);
}
}
// 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);
}
}
}