userAssest #105

Merged
Sayli.Parab merged 1 commits from sayali into main 2025-04-28 11:30:57 +00:00

View File

@@ -556,33 +556,79 @@ class AssetadmintController extends Controller
// }
// }
// 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',
'userAssetLinks.user:id,first_name,last_name' // eager load first_name and last_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) {
// 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
// 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', 'userAssetLinks') // remove full objects
->merge([
'customer_name' => optional($asset->customer)->name,
'assign_to_users' => $assignToUsers, // attach user_id and full_name
'assign_to_user' => $userDetails, // assign only one user
]);
});