moduleUtil = $moduleUtil;
$this->commonUtil = $commonUtil;
$this->assetUtil = $assetUtil;
$this->purchaseTypes = [
'owned' => __('assetmanagement::lang.owned'),
'rented' => __('assetmanagement::lang.rented'),
'leased' => __('assetmanagement::lang.leased'),
];
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index(Request $request)
{
$business_id = request()->session()->get('user.business_id');
if (! (auth()->user()->can('superadmin') || ($this->moduleUtil->hasThePermissionInSubscription($business_id, 'assetmanagement_module')))) {
abort(403, 'Unauthorized action.');
}
$purchase_types = $this->purchaseTypes;
if ($request->ajax()) {
$assets = Asset::with(['media', 'warranties', 'maintenances', 'project'])
->leftJoin('categories as CAT', 'assets.category_id',
'=', 'CAT.id')
->leftJoin('business_locations as BL', 'assets.location_id',
'=', 'BL.id')
->leftJoin('pjt_projects as PJT', 'assets.project_id', '=', 'PJT.id')
->leftJoin('asset_transactions as AT', function ($join) {
$join->on('assets.id', '=', 'AT.asset_id')
->where('transaction_type', 'allocate');
})
->where('assets.business_id', $business_id)
->select('asset_code', 'assets.name as asset', 'assets.quantity as quantity',
'model', 'purchase_date',
'unit_price', 'is_allocatable',
'CAT.name as category', 'BL.name as location',
'PJT.name as project_name',
'assets.id as id', DB::raw('SUM(COALESCE(AT.quantity, 0)) as allocated_qty'),
DB::raw('(SELECT SUM(COALESCE(AR.quantity, 0)) FROM asset_transactions AS AR WHERE(AR.asset_id=assets.id AND AR.transaction_type=\'revoke\')) as revoked_qty'),
'assets.description as description'
)
->groupBy('id');
$permitted_locations = auth()->user()->permitted_locations();
if ($permitted_locations != 'all') {
$assets->whereIn('assets.location_id', $permitted_locations);
}
if (! empty(request()->input('location_id'))) {
$assets->where('assets.location_id', request()->input('location_id'));
}
if (! empty(request()->input('category_id'))) {
$assets->where('assets.category_id', request()->input('category_id'));
}
if (! empty(request()->input('purchase_type'))) {
$assets->where('assets.purchase_type', request()->input('purchase_type'));
}
if (! empty(request()->input('is_allocatable'))) {
$assets->where('assets.is_allocatable', 1);
}
if (! empty(request()->input('project_id'))) {
$assets->where('assets.project_id', request()->input('project_id'));
}
$now = \Carbon::now();
return Datatables::of($assets)
->addColumn('action', function ($row) {
$html = '
';
}
$html .= '
';
return $html;
})
->editColumn('purchase_date', '
@if(!empty($purchase_date))
@format_date($purchase_date)
@endif
')
->editColumn('is_allocatable', function ($row) {
if ($row->is_allocatable) {
return '';
} else {
return '';
}
})
->editColumn('quantity', '
@if(!empty($quantity))
{{@format_quantity($quantity)}}
@endif
')
->editColumn('allocated_qty', '
@if(!empty($allocated_qty))
{{@format_quantity($allocated_qty - $revoked_qty)}}
@endif
')
->editColumn('unit_price', function ($row) {
return ''.$row->unit_price.'';
})
->addColumn('image', function ($row) {
$html = '';
if (! empty($row->media->first())) {
$url = $row->media->first()->display_url;
$html = '';
}
return $html;
})
->addColumn('warranty', function ($row) use ($now) {
$warranty = null;
$html = '';
foreach ($row->warranties as $w) {
$start_date = \Carbon::parse($w->start_date);
$end_date = \Carbon::parse($w->end_date);
if ($now->between($start_date, $end_date)) {
$warranty = $w;
$html = ''.__('assetmanagement::lang.in_warranty').'
';
$html .= ''.$this->commonUtil->format_date($w->start_date).' ~ '.$this->commonUtil->format_date($w->end_date).'';
$html .= '('.$now->diffInDays($end_date, false).' '.__('assetmanagement::lang.days_left').') ';
break;
}
}
if (empty($warranty)) {
$html = ''.__('assetmanagement::lang.not_in_warranty').'';
}
return $html;
})
->editColumn('asset', function ($row) {
$html = $row->asset;
foreach ($row->maintenances as $maintenance) {
if (in_array($maintenance->status, ['new', 'in_progress'])) {
$count = $row->maintenances->whereIn('status', ['new', 'in_progress'])->count();
$html .= '
'.__('assetmanagement::lang.n_in_maintenance', ['n' => $count]).'';
break;
}
}
return $html;
})
->addColumn('project', fn ($row) => $row->project_name ?? '—')
->removeColumn('id')
->removeColumn('maintenances')
->rawColumns(['action', 'is_allocatable', 'purchase_date',
'quantity', 'allocated_qty', 'unit_price', 'warranty_period', 'image', 'warranty', 'asset', ])
->make(true);
}
$business_locations = BusinessLocation::forDropdown($business_id);
$asset_category = Category::forDropdown($business_id, 'asset');
$projects = $this->assetUtil->getProjectsDropdown($business_id);
return view('assetmanagement::asset.index')
->with(compact('purchase_types', 'business_locations', 'asset_category', 'projects'));
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create(Request $request)
{
if (! auth()->user()->can('asset.create')) {
abort(403, 'Unauthorized action.');
}
$business_id = request()->session()->get('user.business_id');
if (! (auth()->user()->can('superadmin') || ($this->moduleUtil->hasThePermissionInSubscription($business_id, 'assetmanagement_module')))) {
abort(403, 'Unauthorized action.');
}
if ($request->ajax()) {
$asset_category = Category::forDropdown($business_id, 'asset');
$business_locations = BusinessLocation::forDropdown($business_id);
$purchase_types = $this->purchaseTypes;
$projects = $this->assetUtil->getProjectsDropdown($business_id);
return view('assetmanagement::asset.create')
->with(compact('asset_category', 'business_locations', 'purchase_types', 'projects'));
}
}
/**
* Store a newly created resource in storage.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
if (! auth()->user()->can('asset.create')) {
abort(403, 'Unauthorized action.');
}
$business_id = request()->session()->get('user.business_id');
if (! (auth()->user()->can('superadmin') || ($this->moduleUtil->hasThePermissionInSubscription($business_id, 'assetmanagement_module')))) {
abort(403, 'Unauthorized action.');
}
try {
$input = $request->only('asset_code', 'name', 'quantity', 'model',
'serial_no', 'category_id', 'location_id', 'project_id', 'purchase_date',
'unit_price', 'depreciation', 'is_allocatable', 'description', 'purchase_type');
$input['business_id'] = $business_id;
$input['created_by'] = request()->session()->get('user.id');
$input['is_allocatable'] = ! empty($input['is_allocatable']) ? 1 : 0;
DB::beginTransaction();
if (empty($input['asset_code'])) {
$ref_count = $this->commonUtil->setAndGetReferenceCount('asset_code', $business_id);
$asset_settings = $this->assetUtil->getAssetSettings($business_id);
$asset_code_prefix = $asset_settings['asset_code_prefix'] ?? null;
$input['asset_code'] = $this->commonUtil->generateReferenceNumber('asset_code', $ref_count, null, $asset_code_prefix);
}
if (! empty($input['quantity'])) {
$input['quantity'] = $this->commonUtil->num_uf($input['quantity']);
}
if (! empty($input['purchase_date'])) {
$input['purchase_date'] = $this->commonUtil->uf_date($input['purchase_date']);
}
if (! empty($input['unit_price'])) {
$input['unit_price'] = $this->commonUtil->num_uf($input['unit_price']);
}
if (! empty($input['depreciation'])) {
$input['depreciation'] = $this->commonUtil->num_uf($input['depreciation']);
}
$asset = Asset::create($input);
//upload media
if ($request->has('image')) {
Media::uploadMedia($business_id, $asset, $request, 'image', true);
}
$warranties = [];
if (! empty($request->input('start_dates'))) {
$months = $request->input('months');
foreach ($request->input('start_dates') as $key => $value) {
if (! empty($value) && ! empty($months[$key])) {
$start_date = $this->commonUtil->uf_date($value);
$warranties[] = [
'start_date' => $start_date,
'end_date' => \Carbon::parse($start_date)->addMonths($months[$key])->format('Y-m-d'),
'additional_cost' => $this->commonUtil->num_uf($request->input('additional_cost')[$key]),
'additional_note' => $request->input('additional_note')[$key],
];
}
}
}
if (! empty($warranties)) {
$asset->warranties()->createMany($warranties);
}
DB::commit();
$output = [
'success' => true,
'msg' => __('lang_v1.success'),
];
} catch (Exception $e) {
DB::rollBack();
\Log::emergency('File:'.$e->getFile().'Line:'.$e->getLine().'Message:'.$e->getMessage());
$output = [
'success' => false,
'msg' => __('messages.something_went_wrong'),
];
}
return redirect()
->action([\Modules\AssetManagement\Http\Controllers\AssetController::class, 'index'])
->with('status', $output);
}
/**
* Show the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
return view('assetmanagement::show');
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
if (! auth()->user()->can('asset.update')) {
abort(403, 'Unauthorized action.');
}
$business_id = request()->session()->get('user.business_id');
if (! (auth()->user()->can('superadmin') || ($this->moduleUtil->hasThePermissionInSubscription($business_id, 'assetmanagement_module')))) {
abort(403, 'Unauthorized action.');
}
if (request()->ajax()) {
$asset = Asset::with(['warranties'])
->where('business_id', $business_id)
->findOrfail($id);
$asset_category = Category::forDropdown($business_id, 'asset');
$business_locations = BusinessLocation::forDropdown($business_id);
$purchase_types = $this->purchaseTypes;
$projects = $this->assetUtil->getProjectsDropdown($business_id);
return view('assetmanagement::asset.edit')
->with(compact('asset_category', 'business_locations', 'asset', 'purchase_types', 'projects'));
}
}
/**
* Update the specified resource in storage.
*
* @param Request $request
* @param int $id
* @return Response
*/
public function update(Request $request, $id)
{
if (! auth()->user()->can('asset.update')) {
abort(403, 'Unauthorized action.');
}
$business_id = request()->session()->get('user.business_id');
if (! (auth()->user()->can('superadmin') || ($this->moduleUtil->hasThePermissionInSubscription($business_id, 'assetmanagement_module')))) {
abort(403, 'Unauthorized action.');
}
try {
$input = $request->only('name', 'quantity', 'model',
'category_id', 'location_id', 'project_id', 'purchase_date', 'unit_price', 'depreciation',
'is_allocatable', 'description', 'purchase_type', 'serial_no');
$input['is_allocatable'] = ! empty($input['is_allocatable']) ? 1 : 0;
DB::beginTransaction();
if (! empty($input['quantity'])) {
$input['quantity'] = $this->commonUtil->num_uf($input['quantity']);
}
if (! empty($input['purchase_date'])) {
$input['purchase_date'] = $this->commonUtil->uf_date($input['purchase_date']);
}
if (! empty($input['unit_price'])) {
$input['unit_price'] = $this->commonUtil->num_uf($input['unit_price']);
}
if (! empty($input['depreciation'])) {
$input['depreciation'] = $this->commonUtil->num_uf($input['depreciation']);
}
$asset = Asset::where('business_id', $business_id)
->findOrfail($id);
$asset->update($input);
//update existing warranties
$edited_warranty_ids = [];
if (! empty($request->input('edit_warranty'))) {
foreach ($request->input('edit_warranty') as $key => $value) {
$edited_warranty_ids[] = $key;
$start_date = $this->commonUtil->uf_date($value['start_date']);
AssetWarranty::where('id', $key)
->update([
'start_date' => $start_date,
'end_date' => \Carbon::parse($start_date)->addMonths($value['months'])->format('Y-m-d'),
'additional_cost' => $this->commonUtil->num_uf($value['additional_cost']),
'additional_note' => $value['additional_note'],
]);
}
}
AssetWarranty::where('asset_id', $asset->id)
->whereNotIn('id', $edited_warranty_ids)
->delete();
//add new warranties
$warranties = [];
if (! empty($request->input('start_dates'))) {
$months = $request->input('months');
foreach ($request->input('start_dates') as $key => $value) {
if (! empty($value) && ! empty($months[$key])) {
$start_date = $this->commonUtil->uf_date($value);
$warranties[] = [
'start_date' => $start_date,
'end_date' => \Carbon::parse($start_date)->addMonths($months[$key])->format('Y-m-d'),
'additional_cost' => $this->commonUtil->num_uf($request->input('additional_cost')[$key]),
'additional_note' => $request->input('additional_note')[$key],
];
}
}
}
if (! empty($warranties)) {
$asset->warranties()->createMany($warranties);
}
//upload media
if ($request->has('image')) {
Media::uploadMedia($business_id, $asset, $request, 'image', true);
}
DB::commit();
$output = [
'success' => true,
'msg' => __('lang_v1.success'),
];
} catch (Exception $e) {
DB::rollBack();
\Log::emergency('File:'.$e->getFile().'Line:'.$e->getLine().'Message:'.$e->getMessage());
$output = [
'success' => false,
'msg' => __('messages.something_went_wrong'),
];
}
return redirect()
->action([\Modules\AssetManagement\Http\Controllers\AssetController::class, 'index'])
->with('status', $output);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
if (! auth()->user()->can('asset.delete')) {
abort(403, 'Unauthorized action.');
}
$business_id = request()->session()->get('user.business_id');
if (! (auth()->user()->can('superadmin') || ($this->moduleUtil->hasThePermissionInSubscription($business_id, 'assetmanagement_module')))) {
abort(403, 'Unauthorized action.');
}
if (request()->ajax()) {
try {
$asset = Asset::where('business_id', $business_id)
->findOrfail($id);
$asset->delete();
$asset->media()->delete();
$output = [
'success' => true,
'msg' => __('lang_v1.success'),
];
} catch (Exception $e) {
\Log::emergency('File:'.$e->getFile().'Line:'.$e->getLine().'Message:'.$e->getMessage());
$output = [
'success' => false,
'msg' => __('messages.something_went_wrong'),
];
}
return $output;
}
}
public function dashboard()
{
$business_id = request()->session()->get('user.business_id');
$allocated_assets = AssetTransaction::where('receiver', auth()->user()->id)
->select(
DB::raw('SUM(quantity) as total_quantity_allocated'),
DB::raw('(SELECT SUM(quantity) FROM asset_transactions as AT WHERE
AT.parent_id = asset_transactions.id AND AT.transaction_type="revoke") as total_revoked_quantity')
)->first();
$total_assets_allocated = $allocated_assets->total_quantity_allocated - $allocated_assets->total_revoked_quantity;
$asset_allocation_by_category = AssetTransaction::where('asset_transactions.receiver',
auth()->user()->id)
->leftJoin('assets as a', 'a.id',
'=', 'asset_transactions.asset_id')
->leftJoin('categories as cat', 'a.category_id',
'=', 'cat.id')
->select(
DB::raw("SUM(COALESCE(asset_transactions.quantity, 0) - COALESCE((SELECT SUM(quantity) FROM asset_transactions as AT WHERE AT.parent_id =asset_transactions.id AND AT.transaction_type='revoke'),0)) as total_quantity_allocated"),
'cat.name as category'
)->groupBy('cat.id')->get();
$is_admin = $this->commonUtil->is_admin(auth()->user());
$total_assets = 0;
$assets_by_category = null;
$total_assets_allocated_for_all_users = 0;
$expiring_assets = null;
if ($is_admin) {
$total_assets = Asset::where('business_id', $business_id)
->select(DB::raw('SUM(quantity) as total_quantity'))
->first()->total_quantity;
$assets_by_category = Asset::where('assets.business_id', $business_id)
->leftJoin('categories as cat', 'assets.category_id', '=', 'cat.id')
->select(
DB::raw('SUM(quantity) as total_quantity'),
'cat.name as category'
)
->groupBy('cat.id')
->get();
$current_date_add30 = Carbon::now()->addDays(30)->toDateString();
$expiring_assets = Asset::where('assets.business_id', $business_id)
->leftJoin('asset_warranties as aw', 'aw.asset_id', '=', 'assets.id')
->groupBy('assets.id')
->havingRaw("MAX(aw.end_date) <= '{$current_date_add30}'")
->select('assets.name', 'assets.asset_code', \DB::raw('MAX(aw.end_date) as max_end_date'), 'assets.id')
->get();
$allocated_assets_for_all_users = AssetTransaction::where('business_id', $business_id)
->select(
DB::raw("SUM(IF(transaction_type='allocate', quantity, 0)) as total_quantity_allocated"),
DB::raw("SUM(IF(transaction_type='revoke', quantity, 0)) as total_revoked_quantity")
)->first();
$total_assets_allocated_for_all_users = $allocated_assets_for_all_users->total_quantity_allocated - $allocated_assets_for_all_users->total_revoked_quantity;
}
return view('assetmanagement::asset.dashboard')
->with(compact('total_assets_allocated', 'asset_allocation_by_category',
'is_admin', 'total_assets', 'assets_by_category', 'expiring_assets', 'total_assets_allocated_for_all_users'));
}
}