snipe-it/app/Http/Controllers/AssetModelsController.php

507 lines
18 KiB
PHP
Raw Normal View History

2016-03-25 01:18:05 -07:00
<?php
2016-03-25 01:18:05 -07:00
namespace App\Http\Controllers;
use App\Helpers\Helper;
use App\Http\Requests\ImageUploadRequest;
use App\Http\Requests\StoreAssetModelRequest;
use App\Models\Actionlog;
2016-03-25 01:18:05 -07:00
use App\Models\AssetModel;
2024-02-14 00:12:31 -08:00
use App\Models\CustomField;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
2023-07-13 16:36:14 -07:00
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use \Illuminate\Contracts\View\View;
use \Illuminate\Http\RedirectResponse;
2016-03-25 01:18:05 -07:00
/**
2016-04-07 13:21:09 -07:00
* This class controls all actions related to asset models for
* the Snipe-IT Asset Management application.
*
* @version v1.0
* @author [A. Gianotto] [<snipe@snipe.net>]
2016-03-25 01:18:05 -07:00
*/
class AssetModelsController extends Controller
{
/**
* Returns a view that invokes the ajax tables which actually contains
* the content for the accessories listing, which is generated in getDatatable.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
*/
public function index() : View
2016-03-25 01:18:05 -07:00
{
2018-01-20 04:39:31 -08:00
$this->authorize('index', AssetModel::class);
return view('models/index');
2016-03-25 01:18:05 -07:00
}
/**
* Returns a view containing the asset model creation form.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
*/
public function create() : View
2016-03-25 01:18:05 -07:00
{
2018-01-20 04:39:31 -08:00
$this->authorize('create', AssetModel::class);
return view('models/edit')->with('category_type', 'asset')
->with('depreciation_list', Helper::depreciationList())
->with('item', new AssetModel);
2016-03-25 01:18:05 -07:00
}
/**
* Validate and process the new Asset Model data.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @param ImageUploadRequest $request
*/
public function store(ImageUploadRequest $request) : RedirectResponse
2016-03-25 01:18:05 -07:00
{
2018-01-20 04:39:31 -08:00
$this->authorize('create', AssetModel::class);
2016-03-25 01:18:05 -07:00
$model = new AssetModel;
$model->eol = $request->input('eol');
$model->depreciation_id = $request->input('depreciation_id');
$model->name = $request->input('name');
$model->model_number = $request->input('model_number');
$model->min_amt = $request->input('min_amt');
$model->manufacturer_id = $request->input('manufacturer_id');
$model->category_id = $request->input('category_id');
$model->notes = $request->input('notes');
$model->user_id = Auth::id();
$model->requestable = $request->has('requestable');
if ($request->input('fieldset_id') != '') {
$model->fieldset_id = $request->input('fieldset_id');
2016-03-25 01:18:05 -07:00
}
$model = $request->handleImages($model);
2016-03-25 01:18:05 -07:00
if ($model->save()) {
if ($this->shouldAddDefaultValues($request->input())) {
if (!$this->assignCustomFieldsDefaultValues($model, $request->input('default_values'))){
return redirect()->back()->withInput()->with('error', trans('admin/custom_fields/message.fieldset_default_value.error'));
}
}
return redirect()->route('models.index')->with('success', trans('admin/models/message.create.success'));
2016-03-25 01:18:05 -07:00
}
Cleanup controller escaping (#3084) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations. * Extend Supplier phone/fax length. This catches issues found in testing with a phone number with a five digit extension. fex (356) 654-3024 x36632 Also move away from escaping all values put into eloquent. Eloquent already uses PDO parameter binding, and this was leading to names like Mr Ryan O'Malley turning into an html escaped version of that name when stored. All values should be escaped when using {{}}, we'll just have to be more cautious when we use {!!, but I think we already are? * Remove additional escaping here, like we did in suppliers controller. * No need to eager load all of these relationships when we can call the count on the querybuilder directly * Work on controller cleanup * Always start from scrach, catches more issues this way. * Update sql dump. Remove old code from permissions test. * Generate a deletable item on demand in the test, rather than relying on one existing. I think we should probably move to mock all the database stuff at some point.. * More travis related fixes * Break script into multiple functional lines * Update all controllers to use the new helper, also cleanup syntax and docblocks along the way.
2016-12-19 22:00:50 -08:00
return redirect()->back()->withInput()->withErrors($model->getErrors());
2016-03-25 01:18:05 -07:00
}
/**
* Returns a view containing the asset model edit form.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @param int $modelId
*/
public function edit($modelId = null) : View | RedirectResponse
2016-03-25 01:18:05 -07:00
{
$this->authorize('update', AssetModel::class);
2017-10-28 11:17:52 -07:00
if ($item = AssetModel::find($modelId)) {
$category_type = 'asset';
return view('models/edit', compact('item', 'category_type'))->with('depreciation_list', Helper::depreciationList());
2016-03-25 01:18:05 -07:00
}
2017-10-28 11:17:52 -07:00
return redirect()->route('models.index')->with('error', trans('admin/models/message.does_not_exist'));
2016-03-25 01:18:05 -07:00
}
/**
* Validates and processes form data from the edit
* Asset Model form based on the model ID passed.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @param ImageUploadRequest $request
* @param int $modelId
* @return \Illuminate\Http\RedirectResponse
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function update(StoreAssetModelRequest $request, $modelId) : RedirectResponse
2016-03-25 01:18:05 -07:00
{
$this->authorize('update', AssetModel::class);
2016-03-25 01:18:05 -07:00
if (is_null($model = AssetModel::find($modelId))) {
Discussion: Moving to policies for controller based authorization (#3080) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations.
2016-12-19 11:04:28 -08:00
return redirect()->route('models.index')->with('error', trans('admin/models/message.does_not_exist'));
2016-03-25 01:18:05 -07:00
}
2020-08-26 02:29:37 -07:00
$model = $request->handleImages($model);
$model->depreciation_id = $request->input('depreciation_id');
$model->eol = $request->input('eol');
$model->name = $request->input('name');
$model->model_number = $request->input('model_number');
$model->min_amt = $request->input('min_amt');
$model->manufacturer_id = $request->input('manufacturer_id');
$model->category_id = $request->input('category_id');
$model->notes = $request->input('notes');
$model->requestable = $request->input('requestable', '0');
2020-08-26 02:29:37 -07:00
$this->removeCustomFieldsDefaultValues($model);
$model->fieldset_id = $request->input('fieldset_id');
if ($this->shouldAddDefaultValues($request->input())) {
if (!$this->assignCustomFieldsDefaultValues($model, $request->input('default_values'))){
return redirect()->back()->withInput()->with('error', trans('admin/custom_fields/message.fieldset_default_value.error'));
}
2016-03-25 01:18:05 -07:00
}
2016-03-25 01:18:05 -07:00
if ($model->save()) {
2023-07-13 16:36:14 -07:00
if ($model->wasChanged('eol')) {
if ($model->eol > 0) {
$newEol = $model->eol;
$model->assets()->whereNotNull('purchase_date')->where('eol_explicit', false)
->update(['asset_eol_date' => DB::raw('DATE_ADD(purchase_date, INTERVAL ' . $newEol . ' MONTH)')]);
} elseif ($model->eol == 0) {
$model->assets()->whereNotNull('purchase_date')->where('eol_explicit', false)
->update(['asset_eol_date' => DB::raw('null')]);
}
2023-07-13 16:36:14 -07:00
}
return redirect()->route('models.index')->with('success', trans('admin/models/message.update.success'));
2016-03-25 01:18:05 -07:00
}
Cleanup controller escaping (#3084) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations. * Extend Supplier phone/fax length. This catches issues found in testing with a phone number with a five digit extension. fex (356) 654-3024 x36632 Also move away from escaping all values put into eloquent. Eloquent already uses PDO parameter binding, and this was leading to names like Mr Ryan O'Malley turning into an html escaped version of that name when stored. All values should be escaped when using {{}}, we'll just have to be more cautious when we use {!!, but I think we already are? * Remove additional escaping here, like we did in suppliers controller. * No need to eager load all of these relationships when we can call the count on the querybuilder directly * Work on controller cleanup * Always start from scrach, catches more issues this way. * Update sql dump. Remove old code from permissions test. * Generate a deletable item on demand in the test, rather than relying on one existing. I think we should probably move to mock all the database stuff at some point.. * More travis related fixes * Break script into multiple functional lines * Update all controllers to use the new helper, also cleanup syntax and docblocks along the way.
2016-12-19 22:00:50 -08:00
return redirect()->back()->withInput()->withErrors($model->getErrors());
2016-03-25 01:18:05 -07:00
}
/**
* Validate and delete the given Asset Model. An Asset Model
* cannot be deleted if there are associated assets.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @param int $modelId
*/
public function destroy($modelId) : RedirectResponse
2016-03-25 01:18:05 -07:00
{
2018-01-20 04:39:31 -08:00
$this->authorize('delete', AssetModel::class);
2016-03-25 01:18:05 -07:00
// Check if the model exists
if (is_null($model = AssetModel::find($modelId))) {
return redirect()->route('models.index')->with('error', trans('admin/models/message.does_not_exist'));
2016-03-25 01:18:05 -07:00
}
Cleanup controller escaping (#3084) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations. * Extend Supplier phone/fax length. This catches issues found in testing with a phone number with a five digit extension. fex (356) 654-3024 x36632 Also move away from escaping all values put into eloquent. Eloquent already uses PDO parameter binding, and this was leading to names like Mr Ryan O'Malley turning into an html escaped version of that name when stored. All values should be escaped when using {{}}, we'll just have to be more cautious when we use {!!, but I think we already are? * Remove additional escaping here, like we did in suppliers controller. * No need to eager load all of these relationships when we can call the count on the querybuilder directly * Work on controller cleanup * Always start from scrach, catches more issues this way. * Update sql dump. Remove old code from permissions test. * Generate a deletable item on demand in the test, rather than relying on one existing. I think we should probably move to mock all the database stuff at some point.. * More travis related fixes * Break script into multiple functional lines * Update all controllers to use the new helper, also cleanup syntax and docblocks along the way.
2016-12-19 22:00:50 -08:00
if ($model->assets()->count() > 0) {
2016-03-25 01:18:05 -07:00
// Throw an error that this model is associated with assets
2016-12-15 06:11:03 -08:00
return redirect()->route('models.index')->with('error', trans('admin/models/message.assoc_users'));
2016-03-25 01:18:05 -07:00
}
2017-10-28 05:46:43 -07:00
if ($model->image) {
try {
[WIP] Added #5957 - Flysystem support (#6262) * Added AWS url to example env * Upgrader - added check for new storage path and attempt to move * Ignore symlink * Updated paths for models * Moved copy methods * Added AWS_URL support For some reasin, Flysystem was generating the wrong AWS url (with a region included) * Switch to Flysystem for image uploads * Nicer display of image preview * Updated image preview on edit blades to use Flysystem * Twiddled some more paths * Working filesystems config * Updated Asset Models and Departments to use Flysystem * Janky workaround for differing S3/local urls/paths * Try to smartly use S3 as public disk if S3 is configured * Use public disk Storage options for public files * Additional transformer edits for Flysystem * Removed debugging * Added missing use Storage directive * Updated seeders to use Flysystem * Default logo * Set a default width We can potentially override this in settings later * Use Flysystem for logo upload * Update downloadFile to use Flysystem * Updated AssetFilesController to use Flysystem * Updated acceptance signatures to use Flysystem * Updated signature view to use Flysystem This isn’t working 100% yet * Use Flysystem facade for displaying asset image * Set assets path Should clean all these up when we’re done here * Added Rackspace support for Flysystem * Added Flysystem migrator console command * Added use Storage directive for categories * Added user avatars to Flysystem * Added profile avatar to Flysystem * Added the option to delete local files with the migrator * Added a check to prevent people from trying to move from local to local * Fixed the selectlists for Flysystem * Fixed the getImageUrl method to reflect Flysystem * Fixed AWS copy process * Fixed models path * More selectlist updates for Flysystem * Updated example .envs with updated env variable names * *sigh* * Updated non-asset getImageUrl() methods to use Flysystem * Removed S3 hardcoding * Use Flysystem in email headers * Fixed typo * Removed camera support from asset file upload We’ll find a way to add this in later (and add that support to all of the other image uploads as well) * Fixed path for categories * WIP - Switched to standard handleImages for asset upload. This is currently broken as I refact the handleImages method. Because the assets store/create methods use their own Form Request, the handleImages method doesn’t exist in that Form Request so it wil error now. * Fixed css URL error * Updated Debugbar to latest version (#6265) v3.2 adds support for Laravel 5.7 * Fixed: Missing CSS file in basic.blade.php (#6264) * Fixed missing CSS file in basic.blade.php * Added * Changed stylesheet import for authorize.blade.php * Updated composer lock * Added AWS_BUCKET_ROOT as env variable * Use nicer image preview for logo upload * Removed AssetRequest form request * Removed asset form request, moved custom field validation into model * Added additional help text for logo upload * Increased the size of the image resize - should make this a setting tho * Few more formatting tweaks to logo section of branding blade preview * Use Flysystem for asset/license file uploads * Use Flysystem for removing images from models that have been deleted * Enable backups to use Flysystem This only handles part of the problem. This just makes it so we can ship files to S3 if we want, but does not account for how we backup files that are hosted on S3 * Use Flysystem to download license files * Updated audits to use Flysystem
2018-09-29 21:33:52 -07:00
Storage::disk('public')->delete('models/'.$model->image);
2017-10-28 05:46:43 -07:00
} catch (\Exception $e) {
Log::info($e);
2017-10-28 05:46:43 -07:00
}
}
Cleanup controller escaping (#3084) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations. * Extend Supplier phone/fax length. This catches issues found in testing with a phone number with a five digit extension. fex (356) 654-3024 x36632 Also move away from escaping all values put into eloquent. Eloquent already uses PDO parameter binding, and this was leading to names like Mr Ryan O'Malley turning into an html escaped version of that name when stored. All values should be escaped when using {{}}, we'll just have to be more cautious when we use {!!, but I think we already are? * Remove additional escaping here, like we did in suppliers controller. * No need to eager load all of these relationships when we can call the count on the querybuilder directly * Work on controller cleanup * Always start from scrach, catches more issues this way. * Update sql dump. Remove old code from permissions test. * Generate a deletable item on demand in the test, rather than relying on one existing. I think we should probably move to mock all the database stuff at some point.. * More travis related fixes * Break script into multiple functional lines * Update all controllers to use the new helper, also cleanup syntax and docblocks along the way.
2016-12-19 22:00:50 -08:00
// Delete the model
$model->delete();
// Redirect to the models management page
return redirect()->route('models.index')->with('success', trans('admin/models/message.delete.success'));
2016-03-25 01:18:05 -07:00
}
/**
* Restore a given Asset Model (mark as un-deleted)
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @param int $id
*/
public function getRestore($id) : RedirectResponse
2016-03-25 01:18:05 -07:00
{
2018-01-20 04:39:31 -08:00
$this->authorize('create', AssetModel::class);
2016-03-25 01:18:05 -07:00
if ($model = AssetModel::withTrashed()->find($id)) {
if ($model->deleted_at == '') {
return redirect()->back()->with('error', trans('general.not_deleted', ['item_type' => trans('general.asset_model')]));
}
if ($model->restore()) {
$logaction = new Actionlog();
$logaction->item_type = User::class;
$logaction->item_id = $model->id;
$logaction->created_at = date('Y-m-d H:i:s');
$logaction->user_id = auth()->id();
$logaction->logaction('restore');
// Redirect them to the deleted page if there are more, otherwise the section index
$deleted_models = AssetModel::onlyTrashed()->count();
if ($deleted_models > 0) {
return redirect()->back()->with('success', trans('admin/models/message.restore.success'));
}
return redirect()->route('models.index')->with('success', trans('admin/models/message.restore.success'));
}
// Check validation
return redirect()->back()->with('error', trans('general.could_not_restore', ['item_type' => trans('general.asset_model'), 'error' => $model->getErrors()->first()]));
2016-03-25 01:18:05 -07:00
}
return redirect()->back()->with('error', trans('admin/models/message.does_not_exist'));
2016-03-25 01:18:05 -07:00
}
/**
* Get the model information to present to the model view page
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @param int $modelId
*/
public function show($modelId = null) : View | RedirectResponse
2016-03-25 01:18:05 -07:00
{
2018-01-20 04:39:31 -08:00
$this->authorize('view', AssetModel::class);
$model = AssetModel::withTrashed()->find($modelId);
2016-03-25 01:18:05 -07:00
if (isset($model->id)) {
return view('models/view', compact('model'));
2016-03-25 01:18:05 -07:00
}
2020-04-07 17:26:56 -07:00
return redirect()->route('models.index')->with('error', trans('admin/models/message.does_not_exist'));
2016-03-25 01:18:05 -07:00
}
/**
* Get the clone page to clone a model
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @param int $modelId
*/
public function getClone($modelId = null) : View | RedirectResponse
2016-03-25 01:18:05 -07:00
{
2021-12-09 05:42:18 -08:00
$this->authorize('create', AssetModel::class);
2016-03-25 01:18:05 -07:00
// Check if the model exists
if (is_null($model_to_clone = AssetModel::find($modelId))) {
Discussion: Moving to policies for controller based authorization (#3080) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations.
2016-12-19 11:04:28 -08:00
return redirect()->route('models.index')->with('error', trans('admin/models/message.does_not_exist'));
2016-03-25 01:18:05 -07:00
}
$model = clone $model_to_clone;
$model->id = null;
// Show the page
return view('models/edit')
->with('depreciation_list', Helper::depreciationList())
->with('item', $model)
->with('model_id', $model_to_clone->id)
->with('clone_model', $model_to_clone);
2016-03-25 01:18:05 -07:00
}
/**
* Get the custom fields form
*
* @author [B. Wetherington] [<uberbrady@gmail.com>]
* @since [v2.0]
* @param int $modelId
*/
public function getCustomFields($modelId) : View
2016-03-25 01:18:05 -07:00
{
return view('models.custom_fields_form')->with('model', AssetModel::find($modelId));
2016-03-25 01:18:05 -07:00
}
/**
* Returns a view that allows the user to bulk edit model attrbutes
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.7]
*/
public function postBulkEdit(Request $request) : View | RedirectResponse
{
$models_raw_array = $request->input('ids');
2017-12-12 09:10:05 -08:00
// Make sure some IDs have been selected
if ((is_array($models_raw_array)) && (count($models_raw_array) > 0)) {
2019-05-22 00:52:51 -07:00
$models = AssetModel::whereIn('id', $models_raw_array)->withCount('assets as assets_count')->orderBy('assets_count', 'ASC')->get();
2017-12-12 09:10:05 -08:00
// If deleting....
if ($request->input('bulk_actions') == 'delete') {
2017-12-12 09:10:05 -08:00
$valid_count = 0;
foreach ($models as $model) {
if ($model->assets_count == 0) {
$valid_count++;
}
}
2017-12-12 09:10:05 -08:00
return view('models/bulk-delete', compact('models'))->with('valid_count', $valid_count);
// Otherwise display the bulk edit screen
} else {
$nochange = ['NC' => 'No Change'];
$fieldset_list = $nochange + Helper::customFieldsetList();
$depreciation_list = $nochange + Helper::depreciationList();
return view('models/bulk-edit', compact('models'))
->with('fieldset_list', $fieldset_list)
->with('depreciation_list', $depreciation_list);
}
}
return redirect()->route('models.index')
->with('error', 'You must select at least one model to edit.');
}
/**
* Returns a view that allows the user to bulk edit model attrbutes
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.7]
*/
public function postBulkEditSave(Request $request) : RedirectResponse
{
$models_raw_array = $request->input('ids');
$update_array = [];
2017-12-12 09:10:05 -08:00
if (($request->filled('manufacturer_id') && ($request->input('manufacturer_id') != 'NC'))) {
$update_array['manufacturer_id'] = $request->input('manufacturer_id');
}
if (($request->filled('category_id') && ($request->input('category_id') != 'NC'))) {
$update_array['category_id'] = $request->input('category_id');
}
if ($request->input('fieldset_id') != 'NC') {
$update_array['fieldset_id'] = $request->input('fieldset_id');
}
if ($request->input('depreciation_id') != 'NC') {
$update_array['depreciation_id'] = $request->input('depreciation_id');
}
if (count($update_array) > 0) {
AssetModel::whereIn('id', $models_raw_array)->update($update_array);
return redirect()->route('models.index')
->with('success', trans('admin/models/message.bulkedit.success'));
}
return redirect()->route('models.index')
->with('warning', trans('admin/models/message.bulkedit.error'));
}
2017-12-12 09:10:05 -08:00
/**
* Validate and delete the given Asset Models. An Asset Model
* cannot be deleted if there are associated assets.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @param int $modelId
*/
public function postBulkDelete(Request $request) : RedirectResponse
2017-12-12 09:10:05 -08:00
{
$models_raw_array = $request->input('ids');
2017-12-12 09:10:05 -08:00
if ((is_array($models_raw_array)) && (count($models_raw_array) > 0)) {
2019-05-22 00:52:51 -07:00
$models = AssetModel::whereIn('id', $models_raw_array)->withCount('assets as assets_count')->get();
2017-12-12 09:10:05 -08:00
$del_error_count = 0;
$del_count = 0;
foreach ($models as $model) {
if ($model->assets_count > 0) {
$del_error_count++;
} else {
$model->delete();
$del_count++;
}
}
if ($del_error_count == 0) {
return redirect()->route('models.index')
->with('success', trans('admin/models/message.bulkdelete.success', ['success_count'=> $del_count]));
2017-12-12 09:10:05 -08:00
}
return redirect()->route('models.index')
->with('warning', trans('admin/models/message.bulkdelete.success_partial', ['fail_count'=>$del_error_count, 'success_count'=> $del_count]));
}
return redirect()->route('models.index')
->with('error', trans('admin/models/message.bulkdelete.error'));
}
/**
* Returns true if a fieldset is set, 'add default values' is ticked and if
* any default values were entered into the form.
*
* @param array $input
*/
private function shouldAddDefaultValues(array $input) : bool
{
return ! empty($input['add_default_values'])
&& ! empty($input['default_values'])
&& ! empty($input['fieldset_id']);
}
/**
* Adds default values to a model (as long as they are truthy)
*
* @param AssetModel $model
* @param array $defaultValues
*/
2024-02-14 00:12:31 -08:00
private function assignCustomFieldsDefaultValues(AssetModel $model, array $defaultValues): bool
{
$data = array();
foreach ($defaultValues as $customFieldId => $defaultValue) {
2024-02-14 00:12:31 -08:00
$customField = CustomField::find($customFieldId);
$data[$customField->db_column] = $defaultValue;
}
$fieldsets = $model->fieldset->validation_rules();
$rules = array();
foreach ($fieldsets as $fieldset => $validation){
// If the field is marked as required, eliminate the rule so it doesn't interfere with the default values
// (we are at model level, the rule still applies when creating a new asset using this model)
$index = array_search('required', $validation);
if ($index !== false){
$validation[$index] = 'nullable';
}
$rules[$fieldset] = $validation;
}
$validator = Validator::make($data, $rules);
if($validator->fails()){
return false;
}
foreach ($defaultValues as $customFieldId => $defaultValue) {
if(is_array($defaultValue)){
$model->defaultValues()->attach($customFieldId, ['default_value' => implode(', ', $defaultValue)]);
}elseif ($defaultValue) {
$model->defaultValues()->attach($customFieldId, ['default_value' => $defaultValue]);
}
}
return true;
}
/**
* Removes all default values
*
*/
private function removeCustomFieldsDefaultValues(AssetModel $model) : void
{
$model->defaultValues()->detach();
}
2016-03-25 01:18:05 -07:00
}