Files
backend_vib360_laravel/app/Http/Controllers/APIS/AdminApi/AssetadmintController.php
sayaliparab ed36935978 userAssets
2025-04-25 15:29:40 +05:30

347 lines
13 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 deleteAsset(Request $request)
{
$assetId = $request->input('assetId'); // Fetching ID from request body
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);
}
// Delete from local database
$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);
// }
// }
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'], 404);
}
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);
}
}
}