Skip to content

A free open source IT asset/license management system

Use a FormRequest to better handle multiple-asset-creation by GUI

Brady Wetheringtonfb1fde26ce47
diff --git a/app/Http/Controllers/Assets/AssetsController.php b/app/Http/Controllers/Assets/AssetsController.php
index 83c7a08ea1..dfc01bdf9a 100755
--- a/app/Http/Controllers/Assets/AssetsController.php
+++ b/app/Http/Controllers/Assets/AssetsController.php
@@ -6,6 +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\UpdateAssetRequest;
use App\Models\Actionlog;
use App\Http\Requests\UploadFileRequest;
@@ -98,7 +99,7 @@ class AssetsController extends Controller
* @author [A. Gianotto] [<[email protected]>]
* @since [v1.0]
*/
- public function store(ImageUploadRequest $request) : RedirectResponse
+ public function store(StoreMultipleAssetRequest $request): RedirectResponse
{
$this->authorize(Asset::class);
@@ -211,6 +212,7 @@ class AssetsController extends Controller
}
}
+ \Log::error("About to check validity and, possibly, save...");
// Validate the asset before saving
if ($asset->isValid() && $asset->save()) {
$target = null;
diff --git a/app/Http/Requests/StoreMultipleAssetRequest.php b/app/Http/Requests/StoreMultipleAssetRequest.php
new file mode 100644
index 0000000000..92404eaa0c
--- /dev/null
+++ b/app/Http/Requests/StoreMultipleAssetRequest.php
@@ -0,0 +1,70 @@
+<?php
+
+namespace App\Http\Requests;
+
+use App\Http\Requests\Traits\MayContainCustomFields;
+use App\Models\Asset;
+use Illuminate\Foundation\Http\FormRequest;
+use App\Helpers\Helper;
+use App\Models\Setting;
+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
+{
+ use MayContainCustomFields;
+
+ /**
+ * Determine if the user is authorized to make this request.
+ */
+ public function authorize(): bool
+ {
+ return true; //FIXME - should I do the auth check here?
+ }
+
+ /**
+ * Get the validation rules that apply to the request.
+ *
+ * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
+ */
+ public function rules(): array
+ {
+ //grab the rules for serials and asset_tags, and tweak them into an array context for multi-create usage
+ $modelRules = (new Asset)->getRules();
+ unset($modelRules['serial']);
+
+ $asset_tag_rules = $modelRules['asset_tag'];
+ unset($modelRules['asset_tag']);
+ // now we replace the 'not_array' rule with 'distinct'
+ array_splice($asset_tag_rules, array_search('not_array', $asset_tag_rules), 1, 'distinct');
+ // and replace the 'unique_undeleted' rule with the Rule object
+ foreach ($asset_tag_rules as $i => $asset_tag_rule) {
+ if (Str::startsWith($asset_tag_rule, 'unique_undeleted')) {
+ $asset_tag_rules[$i] = new UniqueUndeleted('assets', 'asset_tag');
+ }
+ }
+
+ $serials_unique = Setting::getSettings()['unique_serial'];
+ $serials_required = AssetModel::find($this?->model_id)?->require_serial;
+
+ $serial_rules = ['string'];
+ if ($serials_unique) {
+// $serial_rules[] = 'unique_undeleted:assets,serial';
+ $serial_rules[] = new UniqueUndeleted('assets', 'serial');
+ $serial_rules[] = 'distinct';
+ }
+ if ($serials_required) {
+ $serial_rules[] = 'required';
+ } 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,
+ 'asset_tags.*' => $asset_tag_rules,
+ ]);
+ }
+}
diff --git a/app/Http/Traits/UniqueUndeletedTrait.php b/app/Http/Traits/UniqueUndeletedTrait.php
index d4c726bd73..a21d074573 100644
--- a/app/Http/Traits/UniqueUndeletedTrait.php
+++ b/app/Http/Traits/UniqueUndeletedTrait.php
@@ -13,6 +13,7 @@ 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.php
index d588690ba4..fe7eaf00a0 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'],
+ 'serial' => ['nullable', 'string', 'unique_undeleted:assets,serial'], // FIXME - doesn't this require unique serials *ALWAYS*?!?
'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.php
new file mode 100644
index 0000000000..3f21f027a8
--- /dev/null
+++ b/app/Rules/UniqueUndeleted.php
@@ -0,0 +1,60 @@
+<?php
+
+namespace App\Rules;
+
+use Closure;
+use Illuminate\Contracts\Validation\ValidationRule;
+use Illuminate\Contracts\Validation\ValidatorAwareRule;
+use Illuminate\Validation\Validator;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Contracts\Validation\DataAwareRule;
+
+class UniqueUndeleted implements ValidationRule, ValidatorAwareRule
+{
+ protected ?Validator $validator = null;
+ protected array $columns = [];
+ protected $data = [];
+
+ public function __construct(
+ public string $table,
+ string ...$columns,
+ )
+ {
+ $this->columns = $columns;
+ }
+
+ public 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
+
+ return $this;
+ }
+
+ /**
+ * Run the validation rule.
+ *
+ * @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail
+ */
+ 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
+ $translation_string = 'validation.unique_undeleted'; //the normal validation string for a single-column check
+ foreach (array_slice($this->columns, 1) as $column) {
+ $translation_string = 'validation.two_column_unique_undeleted';
+ $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);
+ }
+ }
+}
diff --git a/resources/lang/en-US/validation.php b/resources/lang/en-US/validation.php
index 2d4af64fb4..7276b44586 100644
--- a/resources/lang/en-US/validation.php
+++ b/resources/lang/en-US/validation.php
@@ -230,7 +230,10 @@ return [
|
*/
- 'attributes' => [],
+ 'attributes' => [
+ 'serials.*' => 'Serial Number',
+ 'asset_tags.*' => 'Asset Tag',
+ ],
/*
|--------------------------------------------------------------------------
diff --git a/resources/views/groups/edit.blade.php b/resources/views/groups/edit.blade.php
index 8f5d6b930e..8f35bfce0c 100755
--- a/resources/views/groups/edit.blade.php
+++ b/resources/views/groups/edit.blade.php
@@ -51,9 +51,9 @@
<select class="js-data-ajax"
data-endpoint="users"
data-placeholder="{{ trans('general.select_user') }}"
- name="associated_users[]"
+ {{-- name="associated_users[]"--}}
style="width: 100%"
- id="associated_users[]"
+ id="associated_users"
aria-label="associated_users[]" multiple>
<option value="" role="option">{{ trans('general.select_user') }}</option>
@@ -67,6 +67,7 @@
@endif
</select>
</div>
+ <input type="hidden" id='calculated_users' name="associated_users" value=""/>
{!! $errors->first('associated_users', '<div class="col-md-8 col-md-offset-3"><span class="alert-msg" aria-hidden="true"><i class="fas fa-times" aria-hidden="true"></i> :message</span></div>') !!}
@@ -78,3 +79,16 @@
</div>
@stop
+@section('moar_scripts')
+ <script>
+ //window.alert('hjoi')
+ $('#create-form').on('submit', function (e) {
+ users = $('#associated_users').val();
+ console.warn("User count is: ");
+ console.dir(users);
+ console.warn(users.join("|"))
+ $('#calculated_users').val(users.join('|'));
+ return false;
+ })
+ </script>
+@endsection
diff --git a/resources/views/hardware/edit.blade.php b/resources/views/hardware/edit.blade.php
index c06a396ec1..47fff58358 100755
--- a/resources/views/hardware/edit.blade.php
+++ b/resources/views/hardware/edit.blade.php
@@ -23,7 +23,7 @@
<!-- Asset Tag -->
- <div class="form-group {{ $errors->has('asset_tag') ? ' has-error' : '' }}">
+ <div class="form-group {{ ($errors->has('asset_tag') || $errors->has('asset_tags.1')) ? ' has-error' : '' }}">
<label for="asset_tag" class="col-md-3 control-label">{{ trans('admin/hardware/form.tag') }}</label>
@@ -39,8 +39,10 @@
@else
<!-- we are creating a new asset - let people use more than one asset tag -->
<div class="col-md-7 col-sm-12">
- <input class="form-control" type="text" name="asset_tags[1]" id="asset_tag" value="{{ old('asset_tags.1', \App\Models\Asset::autoincrement_asset()) }}" required>
- {!! $errors->first('asset_tags', '<span class="alert-msg"><i class="fas fa-times"></i> :message</span>') !!}
+ <input class="form-control"
+ type="text" name="asset_tags[1]" id="asset_tag"
+ value="{{ old('asset_tags.1', \App\Models\Asset::autoincrement_asset()) }}" required>
+ {!! $errors->first('asset_tags.1', '<span class="alert-msg"><i class="fas fa-times"></i> :message</span>') !!}
{!! $errors->first('asset_tag', '<span class="alert-msg"><i class="fas fa-times"></i> :message</span>') !!}
</div>
<div class="col-md-2 col-sm-12">
@@ -57,6 +59,54 @@
@include ('partials.forms.edit.serial', ['fieldname'=> 'serials[1]', 'old_val_name' => 'serials.1', 'translated_serial' => trans('admin/hardware/form.serial')])
<div class="input_fields_wrap">
+ {{-- If we're back on this screen for an error, *and* we are doing 'create multiple', then... --}}
+ @php
+ $old_tags = old('asset_tags',[]);
+ /**
+ okay, so old() comes back as:
+ (
+ [1] => 1744410541
+ [2] => 1744410542
+ )
+ */
+ if(array_key_exists('1',$old_tags)) {
+ unset($old_tags[1]); //we already handled 'asset_tag.1' - so unset it
+ }
+ @endphp
+ @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>
+ <div class="col-md-7 col-sm-12 required">
+ <input type="text" class="form-control" name="asset_tags[{{ $i }}]"
+ value="{{ old('asset_tags.'.$i) }}"
+ required>
+ {!! $errors->first('asset_tags.'.$i, '<span class="alert-msg"><i class="fas fa-times"></i> :message</span>') !!}
+ </div>
+ <div class="col-md-2 col-sm-12">
+ <a href="#" class="remove_field btn btn-default btn-sm"><x-icon type="minus"/></a>
+ </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>
@include ('partials.forms.edit.model-select', ['translated_name' => trans('admin/hardware/form.model'), 'fieldname' => 'model_id', 'field_req' => true])
@@ -290,7 +340,7 @@
var max_fields = 100; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
- var x = 1; //initial text box count
+ var x = {{ old('asset_tags') ? count(old('asset_tags')) : 1 /* If we have old() data, use that to determine the 'next' number for 'Asset Tag 2' etc. Otherwise, use 1 */ }}; //initial text box count
@@ -314,6 +364,8 @@
x++; //text box increment
+ // NOTE - this is duplicated in the blade itself in order to re-display an attempt to insert multiple assets
+ // So if this changes, that needs to change too.
box_html += '<span class="fields_wrapper">';
box_html += '<div class="form-group"><label for="asset_tag" class="col-md-3 control-label">{{ trans('admin/hardware/form.tag') }} ' + x + '</label>';
box_html += '<div class="col-md-7 col-sm-12 required">';
@@ -322,7 +374,7 @@
box_html += '<div class="col-md-2 col-sm-12">';
box_html += '<a href="#" class="remove_field btn btn-default btn-sm"><x-icon type="minus" /></a>';
box_html += '</div>';
- box_html += '</div>';
+ // box_html += '</div>';
box_html += '</div>';
box_html += '<div class="form-group"><label for="serial" class="col-md-3 control-label">{{ trans('admin/hardware/form.serial') }} ' + x + '</label>';
box_html += '<div class="col-md-7 col-sm-12">';
diff --git a/resources/views/partials/forms/edit/serial.blade.php b/resources/views/partials/forms/edit/serial.blade.php
index 057fae0eea..391dc17af6 100644
--- a/resources/views/partials/forms/edit/serial.blade.php
+++ b/resources/views/partials/forms/edit/serial.blade.php
@@ -1,5 +1,5 @@
<!-- Serial -->
-<div class="form-group {{ $errors->has('serial') ? ' has-error' : '' }}">
+<div class="form-group {{ $errors->has($old_val_name ?? $fieldname) ? ' has-error' : '' }}">
<label for="{{ $fieldname }}" class="col-md-3 control-label">{{ trans('admin/hardware/form.serial') }} </label>
<div class="col-md-7 col-sm-12">
<input class="form-control" type="text" name="{{ $fieldname }}" id="{{ $fieldname }}" value="{{ old((isset($old_val_name) ? $old_val_name : $fieldname), $item->serial) }}" {{ (Helper::checkIfRequired($item, 'serial') || ($item->model && $item->model->require_serial)) ? ' required' : '' }} maxlength="191" />