forked from grokability/snipe-it
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsset.php
More file actions
2555 lines (2244 loc) · 86.3 KB
/
Asset.php
File metadata and controls
2555 lines (2244 loc) · 86.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace App\Models;
use DB;
use App\Events\CheckoutableCheckedOut;
use App\Exceptions\CheckoutNotAllowed;
use App\Helpers\Helper;
use App\Http\Traits\UniqueUndeletedTrait;
use App\Models\Traits\Acceptable;
use App\Models\Traits\CompanyableTrait;
use App\Models\Traits\HasUploads;
use App\Models\Traits\Searchable;
use App\Presenters\AssetPresenter;
use App\Presenters\Presentable;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Storage;
use UnexpectedValueException;
use Watson\Validating\ValidatingTrait;
use Arr;
use Illuminate\Support\Str;
/**
* Model for Assets.
*
* @version v1.0
*/
class Asset extends Depreciable
{
protected $presenter = AssetPresenter::class;
protected $with = ['model', 'adminuser'];
use CompanyableTrait;
use HasUploads;
use HasFactory, Loggable, Requestable, Presentable, SoftDeletes, ValidatingTrait, UniqueUndeletedTrait;
public const LOCATION = 'location';
public const ASSET = 'asset';
public const USER = 'user';
use Acceptable;
/**
* Run after the checkout acceptance was declined by the user
*
* @param User $acceptedBy
* @param string $signature
*/
public function declinedCheckout(User $declinedBy, $signature)
{
$this->assigned_to = null;
$this->assigned_type = null;
$this->accepted = null;
$this->save();
}
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'assets';
/**
* Leaving this commented out, since we need to test further, but this would eager load the model relationship every single
* time the asset model is loaded.
*/
// protected $with = ['model'];
/**
* Whether the model should inject it's identifier to the unique
* validation rules before attempting validation. If this property
* is not set in the model it will default to true.
*
* @var bool
*/
protected $injectUniqueIdentifier = true;
protected $casts = [
'purchase_date' => 'date',
'eol_explicit' => 'boolean',
'last_checkout' => 'datetime',
'last_checkin' => 'datetime',
'expected_checkin' => 'datetime:m-d-Y',
'last_audit_date' => 'datetime',
'next_audit_date' => 'datetime:m-d-Y',
'model_id' => 'integer',
'status_id' => 'integer',
'company_id' => 'integer',
'location_id' => 'integer',
'rtd_company_id' => 'integer',
'supplier_id' => 'integer',
'created_at' => 'datetime',
'updated_at' => 'datetime',
'deleted_at' => 'datetime',
];
protected $rules = [
'model_id' => ['required', 'integer', 'exists:models,id,deleted_at,NULL', 'not_array'],
'status_id' => ['required', 'integer', 'exists:status_labels,id'],
'asset_tag' => ['required', 'min:1', 'max:255', 'unique_undeleted:assets,asset_tag', 'not_array'],
'name' => ['nullable', 'max:255'],
'company_id' => ['nullable', 'integer', 'exists:companies,id'],
'warranty_months' => ['nullable', 'numeric', 'digits_between:0,240'],
'last_checkout' => ['nullable', 'date_format:Y-m-d H:i:s'],
'last_checkin' => ['nullable', 'date_format:Y-m-d H:i:s'],
'expected_checkin' => ['nullable', 'date'],
'last_audit_date' => ['nullable', 'date_format:Y-m-d H:i:s'],
'next_audit_date' => ['nullable', 'date'],
'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'],
'purchase_cost' => ['nullable', 'numeric', 'gte:0', 'max:9999999999999'],
'supplier_id' => ['nullable', 'exists:suppliers,id'],
'asset_eol_date' => ['nullable', 'date'],
'eol_explicit' => ['nullable', 'boolean'],
'byod' => ['nullable', 'boolean'],
'order_number' => ['nullable', 'string', 'max:191'],
'notes' => ['nullable', 'string', 'max:65535'],
'assigned_to' => ['nullable', 'integer', 'required_with:assigned_type'],
'assigned_type' => ['nullable', 'required_with:assigned_to', 'in:' . User::class . "," . Location::class . "," . Asset::class],
'requestable' => ['nullable', 'boolean'],
'assigned_user' => ['integer', 'nullable', 'exists:users,id,deleted_at,NULL'],
'assigned_location' => ['integer', 'nullable', 'exists:locations,id,deleted_at,NULL', 'fmcs_location'],
'assigned_asset' => ['integer', 'nullable', 'exists:assets,id,deleted_at,NULL']
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'asset_tag',
'assigned_to',
'assigned_type',
'company_id',
'image',
'location_id',
'model_id',
'name',
'notes',
'order_number',
'purchase_cost',
'purchase_date',
'rtd_location_id',
'serial',
'status_id',
'supplier_id',
'warranty_months',
'requestable',
'last_checkout',
'expected_checkin',
'byod',
'asset_eol_date',
'eol_explicit',
'last_audit_date',
'next_audit_date',
'last_checkin',
'last_checkout',
];
use Searchable;
/**
* The attributes that should be included when searching the model.
*
* @var array
*/
protected $searchableAttributes = [
'name',
'asset_tag',
'serial',
'order_number',
'purchase_cost',
'notes',
'created_at',
'updated_at',
'purchase_date',
'expected_checkin',
'next_audit_date',
'last_audit_date',
'last_checkin',
'last_checkout',
'asset_eol_date',
];
/**
* The relations and their attributes that should be included when searching the model.
*
* @var array
*/
protected $searchableRelations = [
'assetstatus' => ['name'],
'supplier' => ['name'],
'company' => ['name'],
'defaultLoc' => ['name'],
'location' => ['name'],
'model' => ['name', 'model_number', 'eol'],
'model.category' => ['name'],
'model.manufacturer' => ['name'],
];
protected static function booted(): void
{
static::forceDeleted(function (Asset $asset) {
$asset->requests()->forceDelete();
});
static::softDeleted(function (Asset $asset) {
$asset->requests()->delete();
});
}
// To properly set the expected checkin as Y-m-d
public function setExpectedCheckinAttribute($value)
{
if ($value == '') {
$value = null;
}
$this->attributes['expected_checkin'] = $value;
}
public function customFieldValidationRules()
{
$customFieldValidationRules = [];
if (($this->model) && ($this->model->fieldset)) {
foreach ($this->model->fieldset->fields as $field) {
// this just casts booleans that may come through as strings to an actual boolean type
// adding !$field->field_encrypted because when the encrypted value comes through it
// screws things up for the encrypted validation rules (and the encrypted string
// is not a valid boolean type)
if ($field->format == 'BOOLEAN' && !$field->field_encrypted) {
$this->{$field->db_column} = filter_var($this->{$field->db_column}, FILTER_VALIDATE_BOOLEAN);
}
}
$customFieldValidationRules += $this->model->fieldset->validation_rules();
}
return $customFieldValidationRules;
}
/**
* This handles the custom field validation for assets
*
* @var array
*/
public function save(array $params = [])
{
$this->rules += $this->customFieldValidationRules();
return parent::save($params);
}
public function getDisplayNameAttribute()
{
return $this->present()->name();
}
/**
* Returns the warranty expiration date as Carbon object
*
* @return \Carbon\Carbon|null
*/
public function getWarrantyExpiresAttribute()
{
if (isset($this->attributes['warranty_months']) && isset($this->attributes['purchase_date'])) {
if (is_string($this->attributes['purchase_date']) || is_string($this->attributes['purchase_date'])) {
$purchase_date = \Carbon\Carbon::parse($this->attributes['purchase_date']);
} else {
$purchase_date = \Carbon\Carbon::instance($this->attributes['purchase_date']);
}
$purchase_date->setTime(0, 0, 0);
return $purchase_date->addMonths((int) $this->attributes['warranty_months']);
}
return null;
}
/**
* Establishes the asset -> company relationship
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v3.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function company()
{
return $this->belongsTo(\App\Models\Company::class, 'company_id');
}
/**
* Determines if an asset is available for checkout.
* This checks to see if it's checked out to an invalid (deleted) user
* OR if the assigned_to and deleted_at fields on the asset are empty AND
* that the status is deployable
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v3.0]
* @return bool
*/
public function availableForCheckout()
{
// This asset is not currently assigned to anyone and is not deleted...
if ((!$this->assigned_to) && (!$this->deleted_at)) {
// The asset status is not archived and is deployable
if (
($this->assetstatus) && ($this->assetstatus->archived == '0')
&& ($this->assetstatus->deployable == '1')
) {
return true;
}
}
return false;
}
/**
* Checks the asset out to the target
*
* @todo The admin parameter is never used. Can probably be removed.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param User $user
* @param User $admin
* @param Carbon $checkout_at
* @param Carbon $expected_checkin
* @param string $note
* @param null $name
* @return bool
* @since [v3.0]
* @return bool
*/
public function checkOut($target, $admin = null, $checkout_at = null, $expected_checkin = null, $note = null, $name = null, $location = null)
{
if (!$target) {
return false;
}
if ($this->is($target)) {
throw new CheckoutNotAllowed('You cannot check an asset out to itself.');
}
if ($expected_checkin) {
$this->expected_checkin = $expected_checkin;
}
$this->last_checkout = $checkout_at;
$this->name = $name;
$this->assignedTo()->associate($target);
if ($location != null) {
$this->location_id = $location;
} else {
if (isset($target->location)) {
$this->location_id = $target->location->id;
}
if ($target instanceof Location) {
$this->location_id = $target->id;
}
}
$originalValues = $this->getRawOriginal();
// attempt to detect change in value if different from today's date
if ($checkout_at && strpos($checkout_at, date('Y-m-d')) === false) {
$originalValues['action_date'] = date('Y-m-d H:i:s');
}
if ($this->save()) {
if (is_int($admin)) {
$checkedOutBy = User::findOrFail($admin);
} elseif ($admin && get_class($admin) === \App\Models\User::class) {
$checkedOutBy = $admin;
} else {
$checkedOutBy = auth()->user();
}
event(new CheckoutableCheckedOut($this, $target, $checkedOutBy, $note, $originalValues));
$this->increment('checkout_counter', 1);
return true;
}
return false;
}
/**
* Sets the detailedNameAttribute
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v3.0]
* @return string
*/
public function getDetailedNameAttribute()
{
if ($this->assignedto) {
$user_name = $this->assignedto->present()->name();
} else {
$user_name = 'Unassigned';
}
return $this->asset_tag . ' - ' . $this->name . ' (' . $user_name . ') ' . ($this->model) ? $this->model->name : '';
}
/**
* Pulls in the validation rules
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v3.0]
* @return array
*/
public function validationRules()
{
return $this->rules;
}
public function customFieldsForCheckinCheckout($checkin_checkout)
{
// Check to see if any of the custom fields were included on the form and if they have any values
if (($this->model) && ($this->model->fieldset) && ($this->model->fieldset->fields)) {
foreach ($this->model->fieldset->fields as $field) {
if (($field->{$checkin_checkout} == 1) && (request()->has($field->db_column))) {
if ($field->field_encrypted == '1') {
if (Gate::allows('assets.view.encrypted_custom_fields')) {
if (is_array(request()->input($field->db_column))) {
$this->{$field->db_column} = Crypt::encrypt(implode(', ', request()->input($field->db_column)));
} else {
$this->{$field->db_column} = Crypt::encrypt(request()->get($field->db_column));
}
}
} else {
if (is_array(request()->input($field->db_column))) {
$this->{$field->db_column} = implode(', ', request()->input($field->db_column));
} else {
$this->{$field->db_column} = request()->input($field->db_column);
}
}
}
}
}
}
/**
* Establishes the asset -> depreciation relationship
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v3.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function depreciation()
{
return $this->hasOneThrough(\App\Models\Depreciation::class, \App\Models\AssetModel::class, 'id', 'id', 'model_id', 'depreciation_id');
}
/**
* Get components assigned to this asset
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function components()
{
return $this->belongsToMany('\App\Models\Component', 'components_assets', 'asset_id', 'component_id')->withPivot('id', 'assigned_qty', 'created_at');
}
/**
* Get depreciation attribute from associated asset model
*
* @todo Is this still needed?
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function get_depreciation()
{
if (($this->model) && ($this->model->depreciation)) {
return $this->model->depreciation;
}
}
/**
* Determines whether the asset is checked out to a user
*
* Even though we allow for checkout to things beyond users
* this method is an easy way of seeing if we are checked out to a user.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
*/
public function checkedOutToUser(): bool
{
return $this->assignedType() === self::USER;
}
public function checkedOutToLocation(): bool
{
return $this->assignedType() === self::LOCATION;
}
public function checkedOutToAsset(): bool
{
return $this->assignedType() === self::ASSET;
}
/**
* Get the target this asset is checked out to
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function assignedTo()
{
return $this->morphTo('assigned', 'assigned_type', 'assigned_to')->withTrashed();
}
/**
* Gets assets assigned to this asset
*
* Sigh.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function assignedAssets()
{
return $this->morphMany(self::class, 'assigned', 'assigned_type', 'assigned_to')->withTrashed();
}
/**
* Establishes the accessory -> asset assignment relationship
*
* @author A. Gianotto <snipe@snipe.net>
* @since [v3.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function assignedAccessories()
{
return $this->morphMany(\App\Models\AccessoryCheckout::class, 'assigned', 'assigned_type', 'assigned_to');
}
/**
* Get the asset's location based on the assigned user
*
* @todo Refactor this if possible. It's awful.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @return \ArrayObject
*/
public function assetLoc($iterations = 1, $first_asset = null)
{
if (!empty($this->assignedType())) {
if ($this->assignedType() == self::ASSET) {
if (!$first_asset) {
$first_asset = $this;
}
if ($iterations > 10) {
throw new \Exception('Asset assignment Loop for Asset ID: ' . $first_asset->id);
}
$assigned_to = self::find($this->assigned_to); //have to do this this way because otherwise it errors
if ($assigned_to) {
return $assigned_to->assetLoc($iterations + 1, $first_asset);
} // Recurse until we have a final location
}
if ($this->assignedType() == self::LOCATION) {
if ($this->assignedTo) {
return $this->assignedTo;
}
}
if ($this->assignedType() == self::USER) {
if (($this->assignedTo) && $this->assignedTo->userLoc) {
return $this->assignedTo->userLoc;
}
//this makes no sense
return $this->defaultLoc;
}
}
return $this->defaultLoc;
}
/**
* Gets the lowercased name of the type of target the asset is assigned to
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @return string
*/
public function assignedType()
{
return $this->assigned_type ? strtolower(class_basename($this->assigned_type)) : null;
}
/**
* This is annoying, but because we don't say "assets" in our route names, we have to make an exception here
*
* @todo - normalize the route names - API endpoint URLS can stay the same
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v6.1.0]
* @return string
*/
public function targetShowRoute()
{
$route = str_plural($this->assignedType());
if ($route == 'assets') {
return 'hardware';
}
return $route;
}
/**
* Get the asset's location based on default RTD location
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v2.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function defaultLoc()
{
return $this->belongsTo(\App\Models\Location::class, 'rtd_location_id');
}
/**
* Get the image URL of the asset.
*
* Check first to see if there is a specific image uploaded to the asset,
* and if not, check for an image uploaded to the asset model.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v2.0]
* @return string | false
*/
public function getImageUrl()
{
if ($this->image && !empty($this->image)) {
return Storage::disk('public')->url(app('assets_upload_path') . e($this->image));
} elseif ($this->model && !empty($this->model->image)) {
return Storage::disk('public')->url(app('models_upload_path') . e($this->model->image));
} elseif ($this->model?->category && !empty($this->model->category->image)) {
return Storage::disk('public')->url(app('categories_upload_path') . e($this->model->category->image));
}
return false;
}
/**
* Get the asset's logs
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v2.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function assetlog()
{
return $this->hasMany(\App\Models\Actionlog::class, 'item_id')
->where('item_type', '=', self::class)
->orderBy('created_at', 'desc')
->withTrashed();
}
/**
* Get the list of checkouts for this asset
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v2.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function checkouts()
{
return $this->assetlog()->where('action_type', '=', 'checkout')
->orderBy('created_at', 'desc')
->withTrashed();
}
/**
* Get the list of audits for this asset
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v2.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function audits()
{
return $this->assetlog()->where('action_type', '=', 'audit')
->orderBy('created_at', 'desc')
->withTrashed();
}
/**
* Get the list of checkins for this asset
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v2.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function checkins()
{
return $this->assetlog()
->where('action_type', '=', 'checkin from')
->orderBy('created_at', 'desc')
->withTrashed();
}
/**
* Get the asset's user requests
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v2.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function userRequests()
{
return $this->assetlog()
->where('action_type', '=', 'requested')
->orderBy('created_at', 'desc')
->withTrashed();
}
/**
* Get maintenances for this asset
*
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @since 1.0
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function maintenances()
{
return $this->hasMany(\App\Models\Maintenance::class, 'asset_id')
->orderBy('created_at', 'desc');
}
/**
* Get user who created the item
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function adminuser()
{
return $this->belongsTo(\App\Models\User::class, 'created_by');
}
/**
* Establishes the asset -> status relationship
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function assetstatus()
{
return $this->belongsTo(\App\Models\Statuslabel::class, 'status_id');
}
/**
* Establishes the asset -> model relationship
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function model()
{
return $this->belongsTo(\App\Models\AssetModel::class, 'model_id')->withTrashed();
}
/**
* Return the assets with a warranty expiring within x days
*
* @param $days
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v2.0]
* @return mixed
*/
public static function getExpiringWarrantyOrEol($days = 30)
{
return self::where('archived', '=', '0')
->NotArchived()
->whereNull('deleted_at')
->where(function ($query) use ($days) {
// Check for manual asset EOL first
$query->where(function ($query) use ($days) {
$query->whereNotNull('asset_eol_date')
->whereBetween('asset_eol_date', [Carbon::now(), Carbon::now()->addDays($days)]);
// Otherwise use the warranty months + purchase date + threshold
})->orWhere(function ($query) use ($days) {
$query->whereNotNull('purchase_date')
->whereNotNull('warranty_months')
->whereBetween('purchase_date', [Carbon::now(), Carbon::now()->addMonths('assets.warranty_months')->addDays($days)]);
});
})
->orderBy('asset_eol_date', 'ASC')
->orderBy('purchase_date', 'ASC')
->get();
}
/**
* Establishes the asset -> assigned licenses relationship
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function licenses()
{
return $this->belongsToMany(\App\Models\License::class, 'license_seats', 'asset_id', 'license_id');
}
/**
* Establishes the asset -> license seats relationship
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function licenseseats()
{
return $this->hasMany(\App\Models\LicenseSeat::class, 'asset_id');
}
/**
* Establishes the asset -> aupplier relationship
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v2.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function supplier()
{
return $this->belongsTo(\App\Models\Supplier::class, 'supplier_id');
}
/**
* Establishes the asset -> location relationship
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v2.0]
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function location()
{
return $this->belongsTo(\App\Models\Location::class, 'location_id');
}
/**
* Get the next autoincremented asset tag
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @return string | false
*/
public static function autoincrement_asset(int $additional_increment = 0)
{
$settings = \App\Models\Setting::getSettings();
if ($settings->auto_increment_assets == '1') {
if ($settings->zerofill_count > 0) {
return $settings->auto_increment_prefix . self::zerofill($settings->next_auto_tag_base + $additional_increment, $settings->zerofill_count);
}
return $settings->auto_increment_prefix . ($settings->next_auto_tag_base + $additional_increment);
} else {
return false;
}
}
/**
* Get the next base number for the auto-incrementer.
*
* We'll add the zerofill and prefixes on the fly as we generate the number.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @return int
*/
public static function nextAutoIncrement($assets)
{
$max = 1;
foreach ($assets as $asset) {
$results = preg_match("/\d+$/", $asset['asset_tag'], $matches);
if ($results) {
$number = $matches[0];
if ($number > $max) {
$max = $number;
}
}
}
}
/**
* Add zerofilling based on Settings
*
* We'll add the zerofill and prefixes on the fly as we generate the number.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @return string
*/
public static function zerofill($num, $zerofill = 3)
{
return str_pad($num, $zerofill, '0', STR_PAD_LEFT);
}
/**
* Determine whether to send a checkin/checkout email based on
* asset model category
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @return bool
*/
public function checkin_email()
{
if (($this->model) && ($this->model->category)) {
return $this->model->category->checkin_email;
}
}
/**
* Determine whether this asset requires acceptance by the assigned user
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @return bool
*/
public function requireAcceptance()
{
if (($this->model) && ($this->model->category)) {
return $this->model->category->require_acceptance;
}