A free open source IT asset/license management system
Tighten everything up, remove logging, fix last bits of functionality
Brady Wetherington9b8768dbdd3f
diff --git a/app/Http/Controllers/Assets/AssetsController.php b/app/Http/Controllers/Assets/AssetsController.phpindex dfc01bdf9a..d485fafa01 100755--- a/app/Http/Controllers/Assets/AssetsController.php+++ b/app/Http/Controllers/Assets/AssetsController.php@@ -6,7 +6,7 @@ use App\Events\CheckoutableCheckedIn;use App\Helpers\Helper;use App\Http\Controllers\Controller;use App\Http\Requests\ImageUploadRequest;-use App\Http\Requests\StoreMultipleAssetRequest;+use App\Http\Requests\CreateMultipleAssetRequest;use App\Http\Requests\UpdateAssetRequest;use App\Models\Actionlog;use App\Http\Requests\UploadFileRequest;@@ -99,7 +99,7 @@ class AssetsController extends Controller* @author [A. Gianotto] [<[email protected]>]* @since [v1.0]*/- public function store(StoreMultipleAssetRequest $request): RedirectResponse+ public function store(CreateMultipleAssetRequest $request): RedirectResponse{$this->authorize(Asset::class);@@ -136,123 +136,136 @@ class AssetsController extends Controller$successes = [];$failures = [];- for ($a = 1, $aMax = count($asset_tags); $a <= $aMax; $a++) {- $asset = new Asset();+ try {+ DB::beginTransaction();+ for ($a = 1, $aMax = count($asset_tags); $a <= $aMax; $a++) {+ $asset = new Asset();- $asset->model()->associate($model);- $asset->name = $request->input('name');+ $asset->model()->associate($model);+ $asset->name = $request->input('name');- // Check for a corresponding serial- if (($serials) && (array_key_exists($a, $serials))) {- $asset->serial = $serials[$a];- }-- if (($asset_tags) && (array_key_exists($a, $asset_tags))) {- $asset->asset_tag = $asset_tags[$a];- }+ // Check for a corresponding serial+ if (($serials) && (array_key_exists($a, $serials))) {+ $asset->serial = $serials[$a];+ }- $asset->company_id = $companyId;- $asset->model_id = $request->input('model_id');- $asset->order_number = $request->input('order_number');- $asset->notes = $request->input('notes');- $asset->created_by = auth()->id();- $asset->status_id = request('status_id');- $asset->warranty_months = request('warranty_months', null);- $asset->purchase_cost = request('purchase_cost');- $asset->purchase_date = request('purchase_date', null);- $asset->asset_eol_date = request('asset_eol_date', null);- $asset->assigned_to = request('assigned_to', null);- $asset->supplier_id = request('supplier_id', null);- $asset->requestable = request('requestable', 0);- $asset->rtd_location_id = request('rtd_location_id', null);- $asset->byod = request('byod', 0);-- if (! empty($settings->audit_interval)) {- $asset->next_audit_date = Carbon::now()->addMonths((int) $settings->audit_interval)->toDateString();- }+ if (($asset_tags) && (array_key_exists($a, $asset_tags))) {+ $asset->asset_tag = $asset_tags[$a];+ }- // Set location_id to rtd_location_id ONLY if the asset isn't being checked out- if (!request('assigned_user') && !request('assigned_asset') && !request('assigned_location')) {- $asset->location_id = $request->input('rtd_location_id', null);- }+ $asset->company_id = $companyId;+ $asset->model_id = $request->input('model_id');+ $asset->order_number = $request->input('order_number');+ $asset->notes = $request->input('notes');+ $asset->created_by = auth()->id();+ $asset->status_id = request('status_id');+ $asset->warranty_months = request('warranty_months', null);+ $asset->purchase_cost = request('purchase_cost');+ $asset->purchase_date = request('purchase_date', null);+ $asset->asset_eol_date = request('asset_eol_date', null);+ $asset->assigned_to = request('assigned_to', null);+ $asset->supplier_id = request('supplier_id', null);+ $asset->requestable = request('requestable', 0);+ $asset->rtd_location_id = request('rtd_location_id', null);+ $asset->byod = request('byod', 0);++ if (!empty($settings->audit_interval)) {+ $asset->next_audit_date = Carbon::now()->addMonths((int)$settings->audit_interval)->toDateString();+ }- if ($request->has('use_cloned_image')) {- $cloned_model_img = Asset::select('image')->find($request->input('clone_image_from_id'));- if ($cloned_model_img) {- $new_image_name = 'clone-'.date('U').'-'.$cloned_model_img->image;- $new_image = 'assets/'.$new_image_name;- Storage::disk('public')->copy('assets/'.$cloned_model_img->image, $new_image);- $asset->image = $new_image_name;+ // Set location_id to rtd_location_id ONLY if the asset isn't being checked out+ if (!request('assigned_user') && !request('assigned_asset') && !request('assigned_location')) {+ $asset->location_id = $request->input('rtd_location_id', null);}- } else {- $asset = $request->handleImages($asset);- }+ if ($request->has('use_cloned_image')) {+ $cloned_model_img = Asset::select('image')->find($request->input('clone_image_from_id'));+ if ($cloned_model_img) {+ $new_image_name = 'clone-' . date('U') . '-' . $cloned_model_img->image;+ $new_image = 'assets/' . $new_image_name;+ Storage::disk('public')->copy('assets/' . $cloned_model_img->image, $new_image);+ $asset->image = $new_image_name;+ }- // Update custom fields in the database.- // Validation for these fields is handled through the AssetRequest form request+ } else {+ $asset = $request->handleImages($asset);+ }- if (($model) && ($model->fieldset)) {- foreach ($model->fieldset->fields as $field) {- if ($field->field_encrypted == '1') {- if (Gate::allows('assets.view.encrypted_custom_fields')) {+ // Update custom fields in the database.+ // Validation for these fields is handled through the AssetRequest form request++ if (($model) && ($model->fieldset)) {+ foreach ($model->fieldset->fields as $field) {+ if ($field->field_encrypted == '1') {+ if (Gate::allows('assets.view.encrypted_custom_fields')) {+ if (is_array($request->input($field->db_column))) {+ $asset->{$field->db_column} = Crypt::encrypt(implode(', ', $request->input($field->db_column)));+ } else {+ $asset->{$field->db_column} = Crypt::encrypt($request->input($field->db_column));+ }+ }+ } else {if (is_array($request->input($field->db_column))) {- $asset->{$field->db_column} = Crypt::encrypt(implode(', ', $request->input($field->db_column)));+ $asset->{$field->db_column} = implode(', ', $request->input($field->db_column));} else {- $asset->{$field->db_column} = Crypt::encrypt($request->input($field->db_column));+ $asset->{$field->db_column} = $request->input($field->db_column);}}- } else {- if (is_array($request->input($field->db_column))) {- $asset->{$field->db_column} = implode(', ', $request->input($field->db_column));- } else {- $asset->{$field->db_column} = $request->input($field->db_column);- }}}- }- \Log::error("About to check validity and, possibly, save...");- // Validate the asset before saving- if ($asset->isValid() && $asset->save()) {- $target = null;- $location = null;+ // Validate the asset before saving+ // Note - it can be tempting to instead want to call saveOrFail(), to automatically throw when an object+ // is invalid (and can't save). But this won't work, because Custom Fields _overrides_ the save() method+ // to inject the Custom Field Rules into the $rules property right before invoking the _real_ save.+ // so, instead, we have to catch failures on the 'else' clause and throw there.+ if ($asset->isValid() && $asset->save()) {+ $target = null;+ $location = null;- if ($userId = request('assigned_user')) {- $target = User::find($userId);+ if ($userId = request('assigned_user')) {+ $target = User::find($userId);- if (!$target) {- return redirect()->back()->withInput()->with('error', trans('admin/hardware/message.create.target_not_found.user'));- }- $location = $target->location_id;+ if (!$target) {+ return redirect()->back()->withInput()->with('error', trans('admin/hardware/message.create.target_not_found.user'));+ }+ $location = $target->location_id;- } elseif ($assetId = request('assigned_asset')) {- $target = Asset::find($assetId);+ } elseif ($assetId = request('assigned_asset')) {+ $target = Asset::find($assetId);- if (!$target) {- return redirect()->back()->withInput()->with('error', trans('admin/hardware/message.create.target_not_found.asset'));- }- $location = $target->location_id;+ if (!$target) {+ return redirect()->back()->withInput()->with('error', trans('admin/hardware/message.create.target_not_found.asset'));+ }+ $location = $target->location_id;- } elseif ($locationId = request('assigned_location')) {- $target = Location::find($locationId);+ } elseif ($locationId = request('assigned_location')) {+ $target = Location::find($locationId);- if (!$target) {- return redirect()->back()->withInput()->with('error', trans('admin/hardware/message.create.target_not_found.location'));+ if (!$target) {+ return redirect()->back()->withInput()->with('error', trans('admin/hardware/message.create.target_not_found.location'));+ }+ $location = $target->id;}- $location = $target->id;- }- if (isset($target)) {- $asset->checkOut($target, auth()->user(), date('Y-m-d H:i:s'), $request->input('expected_checkin', null), 'Checked out on asset creation', $request->get('name'), $location);- }+ if (isset($target)) {+ $asset->checkOut($target, auth()->user(), date('Y-m-d H:i:s'), $request->input('expected_checkin', null), 'Checked out on asset creation', $request->get('name'), $location);+ }- $successes[] = "<a href='" . route('hardware.show', $asset) . "' style='color: white;'>" . e($asset->asset_tag) . "</a>";+ $successes[] = "<a href='" . route('hardware.show', $asset) . "' style='color: white;'>" . e($asset->asset_tag) . "</a>";- } else {- $failures[] = join(",", $asset->getErrors()->all());+ } else {+ $asset->throwValidationException(); // we have to do this for the reason listed above - can't use saveOrFail()+ $failures[] = join(",", $asset->getErrors()->all()); //TODO - this can probably go away soon+ }}+ } catch (\Throwable $e) {+ \Log::debug("Caught exception in multi-create - rolling back: " . $e->getMessage());+ DB::rollBack();+ throw $e;}+ DB::commit();+if($request->get('redirect_option') === 'back'){session()->put(['redirect_option' => 'index']);} else {diff --git a/app/Http/Requests/StoreMultipleAssetRequest.php b/app/Http/Requests/CreateMultipleAssetRequest.phpsimilarity index 86%rename from app/Http/Requests/StoreMultipleAssetRequest.phprename to app/Http/Requests/CreateMultipleAssetRequest.phpindex 92404eaa0c..0cdd2d24b7 100644--- a/app/Http/Requests/StoreMultipleAssetRequest.php+++ b/app/Http/Requests/CreateMultipleAssetRequest.php@@ -11,7 +11,7 @@ use App\Models\AssetModel;use App\Rules\UniqueUndeleted;use Illuminate\Support\Str;-class StoreMultipleAssetRequest extends ImageUploadRequest //should I extend from StoreAssetRequest? FIXME OR TODO OR THINKME+class CreateMultipleAssetRequest extends ImageUploadRequest //should I extend from StoreAssetRequest? FIXME OR TODO OR THINKME{use MayContainCustomFields;@@ -20,7 +20,7 @@ class StoreMultipleAssetRequest extends ImageUploadRequest //should I extend fro*/public function authorize(): bool{- return true; //FIXME - should I do the auth check here?+ return true; //TODO - should I do the auth check here?}/**@@ -59,8 +59,6 @@ class StoreMultipleAssetRequest extends ImageUploadRequest //should I extend fro} else {$serial_rules[] = 'nullable';}- \Log::error("Serial Rules are: " . print_r($serial_rules, true));- \Log::error("Asset Tag Rules are: " . print_r($asset_tag_rules, true));return array_merge($modelRules, ['serials.*' => $serial_rules,diff --git a/app/Http/Traits/UniqueUndeletedTrait.php b/app/Http/Traits/UniqueUndeletedTrait.phpindex a21d074573..d4c726bd73 100644--- a/app/Http/Traits/UniqueUndeletedTrait.php+++ b/app/Http/Traits/UniqueUndeletedTrait.php@@ -13,7 +13,6 @@ trait UniqueUndeletedTrait*/protected function prepareUniqueUndeletedRule($parameters, $field){- \Log::error("Preparing unique undeleted rule for $field");// Only perform a replacement if the model has been persisted.if ($this->exists) {return 'unique_undeleted:'.$this->table.','.$this->getKey();diff --git a/app/Models/Asset.php b/app/Models/Asset.phpindex a927b8eba1..46385c2330 100644--- a/app/Models/Asset.php+++ b/app/Models/Asset.php@@ -115,7 +115,7 @@ class Asset extends Depreciable'location_id' => ['nullable', 'exists:locations,id', 'fmcs_location'],'rtd_location_id' => ['nullable', 'exists:locations,id', 'fmcs_location'],'purchase_date' => ['nullable', 'date', 'date_format:Y-m-d'],- 'serial' => ['nullable', 'string', 'unique_undeleted:assets,serial'], // FIXME - doesn't this require unique serials *ALWAYS*?!?+ 'serial' => ['nullable', 'string', 'unique_undeleted:assets,serial'],'purchase_cost' => ['nullable', 'numeric', 'gte:0', 'max:99999999999999999.99'],'supplier_id' => ['nullable', 'exists:suppliers,id'],'asset_eol_date' => ['nullable', 'date'],diff --git a/app/Rules/UniqueUndeleted.php b/app/Rules/UniqueUndeleted.phpindex 3f21f027a8..9aceae5a73 100644--- a/app/Rules/UniqueUndeleted.php+++ b/app/Rules/UniqueUndeleted.php@@ -25,12 +25,11 @@ class UniqueUndeleted implements ValidationRule, ValidatorAwareRulepublic function setValidator(Validator $validator): static{-// \Log::error("Validator has been SET and it is: ".print_r(get_object_vars($validator), true));$this->validator = $validator;$this->data = $validator->getData();//TODO - can we somehow grab the ID of the route-model-bound object, and omit its ID?// to do that, we'd have to know _which_ parameter in the validator is actually the R-M-B'ed- // parameter+ // parameter. Or maybe we just change the function signature to let you specify it.return $this;}@@ -42,19 +41,16 @@ class UniqueUndeleted implements ValidationRule, ValidatorAwareRule*/public function validate(string $attribute, mixed $value, Closure $fail): void{- \Log::error("Going to validate via RULE for attribute: $attribute which has value: " . print_r($value, true));- // $this->validator->{$something} should maybe get the object?- // but, so far, we're only using this on creating a 'new thing' so there's just a simple check needed, I guess?$query = DB::table($this->table)->whereNull('deleted_at');- $query->where($this->columns[0], '!=', $value); //the first column to check+ $query->where($this->columns[0], '==', $value); //the first column to check$translation_string = 'validation.unique_undeleted'; //the normal validation string for a single-column checkforeach (array_slice($this->columns, 1) as $column) {$translation_string = 'validation.two_column_unique_undeleted';- $query->where($column, '!=', $this->data[$column]);+ $query->where($column, '==', $this->data[$column]);}-// \Log::error("Here is what you get if you ask for the ID directly: " . $this->validator->id);+if ($query->count() > 0) {- $fail()->translate($translation_string);+ $fail($translation_string)->translate();}}}diff --git a/resources/views/hardware/edit.blade.php b/resources/views/hardware/edit.blade.phpindex 47fff58358..74abb1d4d3 100755--- a/resources/views/hardware/edit.blade.php+++ b/resources/views/hardware/edit.blade.php@@ -76,9 +76,6 @@@foreach(array_keys($old_tags) as $i){{-- This is mostly stolen from the HTML that we add via javascript on the 'add_field_button' handler in the embedded JS below --}}{{-- @include ('partials.forms.edit.serial', ['fieldname'=> 'serials['.$loop->iteration.']', 'old_val_name' => 'serials.'.$loop->iteration, 'translated_serial' => trans('admin/hardware/form.serial')])--}}- @php- \Log::error("I is: $i");- @endphp<span class="fields_wrapper"><div class="form-group {{ $errors->has('asset_tags.'.$i) ? ' has-error' : '' }}"><label for="asset_tag"class="col-md-3 control-label">{{ trans('admin/hardware/form.tag') }} {{ $i }}</label>@@ -93,18 +90,6 @@</div></div>@include ('partials.forms.edit.serial', ['fieldname'=> 'serials['.$i.']', 'old_val_name' => 'serials.'.$i, 'translated_serial' => trans('admin/hardware/form.serial')])- {{-- <div class="form-group {{ $errors->has('serials.'.$i) ? ' has-error': '' }}"><label for="serial"- class="col-md-3 control-label">{{ trans('admin/hardware/form.serial') }} {{ $i }}</label>- <div class="col-md-7 col-sm-12">- <input type="text" class="form-control" name="serials[{{ $i }}]"- value="{{ old('serials.'.$i) }}">- @error('serials.'.$i )- <span class="alert-msg" aria-hidden="true">- <i class="fas fa-times" aria-hidden="true"></i> {{ $message }}- </span>- @enderror- </div>- </div> --}}</span>@endforeach</div>