diff --git a/.all-contributorsrc b/.all-contributorsrc index 5f8d82c140..d5278f911f 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -2362,6 +2362,15 @@ ] }, { + "login": "Delta5", + "name": "Evan Taylor", + "avatar_url": "https://avatars.githubusercontent.com/u/1975640?v=4", + "profile": "https://github.com/Delta5", + "contributions": [ + "code" + ] + }, + { "login": "PetriAsi", "name": "Petri Asikainen", "avatar_url": "https://avatars.githubusercontent.com/u/8735148?v=4", diff --git a/.nvmrc b/.nvmrc index 70324da038..27bbca7450 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -v10.15.1 +v12.22.1 diff --git a/Dockerfile.alpine b/Dockerfile.alpine index 5221fe3975..77cfe9a073 100644 --- a/Dockerfile.alpine +++ b/Dockerfile.alpine @@ -25,6 +25,8 @@ RUN apk add --no-cache \ php7-session \ php7-dom \ php7-xmlwriter \ + php7-xmlreader \ + php7-sodium \ curl \ wget \ vim \ diff --git a/README.md b/README.md index b4ad390ef8..ee2978e947 100644 --- a/README.md +++ b/README.md @@ -129,6 +129,7 @@ Thanks goes to all of these wonderful people ([emoji key](https://github.com/ken | [
David Valin Alonso](https://github.com/deivishome)
[💻](https://github.com/snipe/snipe-it/commits?author=deivishome "Code") | [
andreaci](https://github.com/andreaci)
[💻](https://github.com/snipe/snipe-it/commits?author=andreaci "Code") | [
Jelle Sebreghts](http://www.jellesebreghts.be)
[💻](https://github.com/snipe/snipe-it/commits?author=Jelle-S "Code") | [
Michael Pietsch](https://github.com/Skywalker-11)
| [
Masudul Haque Shihab](https://github.com/sh1hab)
[💻](https://github.com/snipe/snipe-it/commits?author=sh1hab "Code") | [
Supapong Areeprasertkul](http://www.freedomdive.com/)
[💻](https://github.com/snipe/snipe-it/commits?author=zybersup "Code") | [
Peter Sarossy](https://github.com/psarossy)
[💻](https://github.com/snipe/snipe-it/commits?author=psarossy "Code") | | [
Renee Margaret McConahy](https://github.com/nepella)
[💻](https://github.com/snipe/snipe-it/commits?author=nepella "Code") | [
JohnnyPicnic](https://github.com/JohnnyPicnic)
[💻](https://github.com/snipe/snipe-it/commits?author=JohnnyPicnic "Code") | [
markbrule](https://github.com/markbrule)
[💻](https://github.com/snipe/snipe-it/commits?author=markbrule "Code") | [
Mike Campbell](https://github.com/mikecmpbll)
[💻](https://github.com/snipe/snipe-it/commits?author=mikecmpbll "Code") | [
tbrconnect](https://github.com/tbrconnect)
[💻](https://github.com/snipe/snipe-it/commits?author=tbrconnect "Code") | [
kcoyo](https://github.com/kcoyo)
[💻](https://github.com/snipe/snipe-it/commits?author=kcoyo "Code") | [
Travis Miller](https://travismiller.com/)
[💻](https://github.com/snipe/snipe-it/commits?author=travismiller "Code") | | [
Petri Asikainen](https://github.com/PetriAsi)
[💻](https://github.com/snipe/snipe-it/commits?author=PetriAsi "Code") | [
derdeagle](https://github.com/derdeagle)
[💻](https://github.com/snipe/snipe-it/commits?author=derdeagle "Code") | [
Mike Frysinger](https://wh0rd.org/)
[💻](https://github.com/snipe/snipe-it/commits?author=vapier "Code") | +| [
Evan Taylor](https://github.com/Delta5)
[💻](https://github.com/snipe/snipe-it/commits?author=Delta5 "Code") | This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind welcome! diff --git a/app/Console/Commands/CheckinLicensesFromAllUsers.php b/app/Console/Commands/CheckinLicensesFromAllUsers.php index bcd8583eaf..5e02bffb7b 100644 --- a/app/Console/Commands/CheckinLicensesFromAllUsers.php +++ b/app/Console/Commands/CheckinLicensesFromAllUsers.php @@ -2,10 +2,10 @@ namespace App\Console\Commands; -use App\Models\LicenseSeat; -use Illuminate\Console\Command; -use App\Models\User; use App\Models\License; +use App\Models\LicenseSeat; +use App\Models\User; +use Illuminate\Console\Command; use Illuminate\Database\Eloquent\Model; class CheckinLicensesFromAllUsers extends Command @@ -41,55 +41,48 @@ class CheckinLicensesFromAllUsers extends Command */ public function handle() { - $license_id = $this->option('license_id'); $notify = $this->option('notify'); - if (!$license_id) { + if (! $license_id) { $this->error('ERROR: License ID is required.'); + return false; } - - if (!$license = License::where('id','=',$license_id)->first()) { + if (! $license = License::where('id', '=', $license_id)->first()) { $this->error('Invalid license ID'); + return false; } $this->info('Checking in ALL seats for '.$license->name); - $licenseSeats = LicenseSeat::where('license_id', '=', $license_id) ->whereNotNull('assigned_to') ->with('user') ->get(); - $this->info(' There are ' .$licenseSeats->count(). ' seats checked out: '); + $this->info(' There are '.$licenseSeats->count().' seats checked out: '); - if (!$notify) { + if (! $notify) { $this->info('No mail will be sent.'); } foreach ($licenseSeats as $seat) { - $this->info($seat->user->username .' has a license seat for '.$license->name); + $this->info($seat->user->username.' has a license seat for '.$license->name); $seat->assigned_to = null; if ($seat->save()) { // Override the email address so we don't notify on checkin - if (!$notify) { + if (! $notify) { $seat->user->email = null; } // Log the checkin $seat->logCheckin($seat->user, 'Checked in via cli tool'); } - - - - } - - } } diff --git a/app/Console/Commands/CheckoutLicenseToAllUsers.php b/app/Console/Commands/CheckoutLicenseToAllUsers.php index 0855e5d084..fab2b318c6 100644 --- a/app/Console/Commands/CheckoutLicenseToAllUsers.php +++ b/app/Console/Commands/CheckoutLicenseToAllUsers.php @@ -2,10 +2,10 @@ namespace App\Console\Commands; -use App\Models\LicenseSeat; -use Illuminate\Console\Command; -use App\Models\User; use App\Models\License; +use App\Models\LicenseSeat; +use App\Models\User; +use Illuminate\Console\Command; use Illuminate\Database\Eloquent\Model; class CheckoutLicenseToAllUsers extends Command @@ -41,18 +41,18 @@ class CheckoutLicenseToAllUsers extends Command */ public function handle() { - $license_id = $this->option('license_id'); $notify = $this->option('notify'); - if (!$license_id) { - $this->error('ERROR: License ID is required.'); - return false; + if (! $license_id) { + $this->error('ERROR: License ID is required.'); + + return false; } - - if (!$license = License::where('id','=',$license_id)->with('assignedusers')->first()) { + if (! $license = License::where('id', '=', $license_id)->with('assignedusers')->first()) { $this->error('Invalid license ID'); + return false; } @@ -64,7 +64,7 @@ class CheckoutLicenseToAllUsers extends Command $this->info('Checking out '.$users->count().' of '.$license->getAvailSeatsCountAttribute().' seats for '.$license->name); - if (!$notify) { + if (! $notify) { $this->info('No mail will be sent.'); } @@ -74,14 +74,14 @@ class CheckoutLicenseToAllUsers extends Command // to them if ($user->licenses->where('id', '=', $license_id)->count()) { - $this->info($user->username .' already has this license checked out to them. Skipping... '); + $this->info($user->username.' already has this license checked out to them. Skipping... '); continue; } - // If the license is valid, check that there is an available seat if ($license->availCount()->count() < 1) { $this->error('ERROR: No available seats'); + return false; } @@ -89,13 +89,12 @@ class CheckoutLicenseToAllUsers extends Command // Get the seat ID $licenseSeat = $license->freeSeat(); - // Update the seat with checkout info, - $licenseSeat->assigned_to = $user->id; + $licenseSeat->assigned_to = $user->id; if ($licenseSeat->save()) { // Temporarily null the user's email address so we don't send mail if we're not supposed to - if (!$notify) { + if (! $notify) { $user->email = null; } @@ -103,10 +102,6 @@ class CheckoutLicenseToAllUsers extends Command $licenseSeat->logCheckout('Checked out via cli tool', $user); $this->info('License '.$license_id.' seat '.$licenseSeat->id.' checked out to '.$user->username); } - } - - - } } diff --git a/app/Console/Commands/CreateAdmin.php b/app/Console/Commands/CreateAdmin.php index 7a2c9a1feb..a4b4b9e42c 100644 --- a/app/Console/Commands/CreateAdmin.php +++ b/app/Console/Commands/CreateAdmin.php @@ -37,7 +37,6 @@ class CreateAdmin extends Command */ public function handle() { - $first_name = $this->option('first_name'); $last_name = $this->option('last_name'); $username = $this->option('username'); @@ -45,7 +44,7 @@ class CreateAdmin extends Command $password = $this->option('password'); $show_in_list = $this->argument('show_in_list'); - if (($first_name=='') || ($last_name=='') || ($username=='') || ($email=='') || ($password=='')) { + if (($first_name == '') || ($last_name == '') || ($username == '') || ($email == '') || ($password == '')) { $this->info('ERROR: All fields are required.'); } else { $user = new \App\Models\User; @@ -68,12 +67,9 @@ class CreateAdmin extends Command $errors = $user->getErrors(); foreach ($errors->all() as $error) { - $this->info('ERROR:'. $error); + $this->info('ERROR:'.$error); } - } } - } - } diff --git a/app/Console/Commands/DisableLDAP.php b/app/Console/Commands/DisableLDAP.php index fd2f0a1070..ee707741ee 100644 --- a/app/Console/Commands/DisableLDAP.php +++ b/app/Console/Commands/DisableLDAP.php @@ -38,9 +38,7 @@ class DisableLDAP extends Command */ public function handle() { - if ($this->confirm("\n****************************************************\nThis will disable LDAP support. You will not be able \nto login with an account that does not exist \nlocally in the Snipe-IT local database. \n****************************************************\n\nDo you wish to continue? [y|N]")) { - $setting = Setting::getSettings(); $setting->ldap_enabled = 0; if ($setting->save()) { @@ -51,6 +49,5 @@ class DisableLDAP extends Command } else { $this->info('Canceled. No actions taken.'); } - } } diff --git a/app/Console/Commands/FixDoubleEscape.php b/app/Console/Commands/FixDoubleEscape.php index 64f6aad572..42a1765913 100644 --- a/app/Console/Commands/FixDoubleEscape.php +++ b/app/Console/Commands/FixDoubleEscape.php @@ -37,49 +37,43 @@ class FixDoubleEscape extends Command */ public function handle() { - $tables = [ - '\App\Models\Asset' => ['name'], - '\App\Models\License' => ['name'], - '\App\Models\Consumable' => ['name'], - '\App\Models\Accessory' => ['name'], - '\App\Models\Component' => ['name'], - '\App\Models\Company' => ['name'], - '\App\Models\Manufacturer' => ['name'], - '\App\Models\Supplier' => ['name'], - '\App\Models\Statuslabel' => ['name'], - '\App\Models\Depreciation' => ['name'], - '\App\Models\AssetModel' => ['name'], - '\App\Models\Group' => ['name'], - '\App\Models\Department' => ['name'], - '\App\Models\Location' => ['name'], - '\App\Models\User' => ['first_name', 'last_name'], + \App\Models\Asset::class => ['name'], + \App\Models\License::class => ['name'], + \App\Models\Consumable::class => ['name'], + \App\Models\Accessory::class => ['name'], + \App\Models\Component::class => ['name'], + \App\Models\Company::class => ['name'], + \App\Models\Manufacturer::class => ['name'], + \App\Models\Supplier::class => ['name'], + \App\Models\Statuslabel::class => ['name'], + \App\Models\Depreciation::class => ['name'], + \App\Models\AssetModel::class => ['name'], + \App\Models\Group::class => ['name'], + \App\Models\Department::class => ['name'], + \App\Models\Location::class => ['name'], + \App\Models\User::class => ['first_name', 'last_name'], ]; - $count = array(); + $count = []; + foreach ($tables as $classname => $fields) { + $count[$classname] = []; + $count[$classname]['classname'] = 0; + foreach ($fields as $field) { + $count[$classname]['classname']++; + $count[$classname][$field] = 0; - foreach ($tables as $classname => $fields) { - $count[$classname] = array(); - $count[$classname]['classname'] = 0; - - foreach($fields as $field) { - - $count[$classname]['classname']++; - $count[$classname][$field] = 0; - - foreach($classname::where("$field",'LIKE','%&%')->get() as $row) { - $this->info('Updating '.$field.' for '.$classname); - $row->{$field} = html_entity_decode($row->{$field},ENT_QUOTES); - $row->save(); - $count[$classname][$field]++; - - } + foreach ($classname::where("$field", 'LIKE', '%&%')->get() as $row) { + $this->info('Updating '.$field.' for '.$classname); + $row->{$field} = html_entity_decode($row->{$field}, ENT_QUOTES); + $row->save(); + $count[$classname][$field]++; } } + } $this->info('Update complete'); - } } diff --git a/app/Console/Commands/FixMismatchedAssetsAndLogs.php b/app/Console/Commands/FixMismatchedAssetsAndLogs.php index 45a1694dd7..34b6b3edfc 100644 --- a/app/Console/Commands/FixMismatchedAssetsAndLogs.php +++ b/app/Console/Commands/FixMismatchedAssetsAndLogs.php @@ -29,7 +29,6 @@ class FixMismatchedAssetsAndLogs extends Command */ private $dryrun = false; - /** * Create a new command instance. * @@ -47,30 +46,29 @@ class FixMismatchedAssetsAndLogs extends Command */ public function handle() { - if ($this->option('dryrun')) { $this->dryrun = true; } if ($this->dryrun) { - $this->info('This is a DRY RUN - no changes will be saved.' ); + $this->info('This is a DRY RUN - no changes will be saved.'); } $mismatch_count = 0; $assets = Asset::whereNotNull('assigned_to') - ->where('assigned_type', '=', 'App\\Models\\User') + ->where('assigned_type', '=', \App\Models\User::class) ->orderBy('id', 'ASC')->get(); foreach ($assets as $asset) { // get the last checkout of the asset - if ($checkout_log = Actionlog::where('target_type', '=', 'App\\Models\\User') + if ($checkout_log = Actionlog::where('target_type', '=', \App\Models\User::class) ->where('action_type', '=', 'checkout') ->where('item_id', '=', $asset->id) ->orderBy('created_at', 'DESC') ->first()) { // Now check for a subsequent checkin log - we want to ignore those - if (!$checkin_log = Actionlog::where('target_type', '=', 'App\\Models\\User') + if (! $checkin_log = Actionlog::where('target_type', '=', \App\Models\User::class) ->where('action_type', '=', 'checkin from') ->where('item_id', '=', $asset->id) ->whereDate('created_at', '>', $checkout_log->created_at) @@ -78,28 +76,24 @@ class FixMismatchedAssetsAndLogs extends Command ->first()) { //print_r($asset); - if ($checkout_log->target_id != $asset->assigned_to) { - $this->error('Log ID: '.$checkout_log->id.' -- Asset ID '. $checkout_log->item_id.' SHOULD BE checked out to User '.$checkout_log->target_id.' but its assigned_to is '.$asset->assigned_to ); + if ($checkout_log->target_id != $asset->assigned_to) { + $this->error('Log ID: '.$checkout_log->id.' -- Asset ID '.$checkout_log->item_id.' SHOULD BE checked out to User '.$checkout_log->target_id.' but its assigned_to is '.$asset->assigned_to); - if (!$this->dryrun) { - $asset->assigned_to = $checkout_log->target_id; - if ($asset->save()) { - $this->info('Asset record updated.'); - } else { - $this->error('Error updating asset: '.$asset->getErrors()); - } + if (! $this->dryrun) { + $asset->assigned_to = $checkout_log->target_id; + if ($asset->save()) { + $this->info('Asset record updated.'); + } else { + $this->error('Error updating asset: '.$asset->getErrors()); } - $mismatch_count++; } - } else { - //$this->info('Asset ID '.$asset->id.': There is a checkin '.$checkin_log->created_at.' after this checkout '.$checkout_log->created_at); - + $mismatch_count++; } - + } else { + //$this->info('Asset ID '.$asset->id.': There is a checkin '.$checkin_log->created_at.' after this checkout '.$checkout_log->created_at); + } } - } $this->info($mismatch_count.' mismatched assets.'); - } } diff --git a/app/Console/Commands/ImportLocations.php b/app/Console/Commands/ImportLocations.php index a0512aa393..3bd28f7f25 100644 --- a/app/Console/Commands/ImportLocations.php +++ b/app/Console/Commands/ImportLocations.php @@ -2,9 +2,9 @@ namespace App\Console\Commands; +use App\Models\Location; use Illuminate\Console\Command; use League\Csv\Reader; -use App\Models\Location; class ImportLocations extends Command { @@ -39,10 +39,8 @@ class ImportLocations extends Command */ public function handle() { - - - if (!ini_get("auto_detect_line_endings")) { - ini_set("auto_detect_line_endings", '1'); + if (! ini_get('auto_detect_line_endings')) { + ini_set('auto_detect_line_endings', '1'); } $filename = $this->argument('filename'); @@ -53,18 +51,17 @@ class ImportLocations extends Command // Import parent location names first if they don't exist foreach ($results as $parent_index => $parent_row) { - if (array_key_exists('Parent Name', $parent_row)) { $parent_name = trim($parent_row['Parent Name']); if (array_key_exists('Name', $parent_row)) { - $this->info('- Parent: ' . $parent_name . ' in row as: ' . trim($parent_row['Parent Name'])); + $this->info('- Parent: '.$parent_name.' in row as: '.trim($parent_row['Parent Name'])); } // Save parent location name // This creates a sort of name-stub that we'll update later on in this script - $parent_location = Location::firstOrCreate(array('name' => $parent_name)); + $parent_location = Location::firstOrCreate(['name' => $parent_name]); if (array_key_exists('Name', $parent_row)) { - $this->info('Parent for ' . $parent_row['Name'] . ' is ' . $parent_name . '. Attempting to save ' . $parent_name . '.'); + $this->info('Parent for '.$parent_row['Name'].' is '.$parent_name.'. Attempting to save '.$parent_name.'.'); } // Check if the record was updated or created. @@ -74,18 +71,15 @@ class ImportLocations extends Command } else { $this->info('- Parent location '.$parent_name.' was created.'); } - } else { $this->info('- No Parent Name provided, so no parent location will be created.'); } - } $this->info('----- Parents Created.... backfilling additional details... --------'); // Loop through ALL records and add/update them if there are additional fields // besides name foreach ($results as $index => $row) { - if (array_key_exists('Parent Name', $row)) { $parent_name = trim($row['Parent Name']); } else { @@ -94,11 +88,12 @@ class ImportLocations extends Command // Set the location attributes to save if (array_key_exists('Name', $row)) { - $location = Location::firstOrCreate(array('name' => trim($row['Name']))); + $location = Location::firstOrCreate(['name' => trim($row['Name'])]); $location->name = trim($row['Name']); $this->info('Checking location: '.$location->name); } else { $this->error('Location name is required and is missing from at least one row in this dataset. Check your CSV for extra trailing rows and try again.'); + return false; } if (array_key_exists('Currency', $row)) { @@ -126,7 +121,6 @@ class ImportLocations extends Command $location->ldap_ou = trim($row['OU']); } - // If a parent name is provided, we created it earlier in the script, // so let's grab that ID if ($parent_name) { @@ -142,21 +136,15 @@ class ImportLocations extends Command // Check if the record was updated or created. // This is mostly for clearer debugging. if ($location->exists) { - $this->info('Location ' . $location->name . ' already exists. Updating...'); + $this->info('Location '.$location->name.' already exists. Updating...'); } else { $this->info('- Location '.$location->name.' was created. '); } - // If there's a validation error, display that + // If there's a validation error, display that } else { - $this->error('- Non-parent Location '.$location->name.' could not be created: '.$location->getErrors() ); + $this->error('- Non-parent Location '.$location->name.' could not be created: '.$location->getErrors()); } - - - - } - - } } diff --git a/app/Console/Commands/LdapSync.php b/app/Console/Commands/LdapSync.php index 9e337084a4..45a9bd44a6 100755 --- a/app/Console/Commands/LdapSync.php +++ b/app/Console/Commands/LdapSync.php @@ -3,11 +3,11 @@ namespace App\Console\Commands; use App\Models\Department; -use Illuminate\Console\Command; -use App\Models\Setting; use App\Models\Ldap; -use App\Models\User; use App\Models\Location; +use App\Models\Setting; +use App\Models\User; +use Illuminate\Console\Command; use Log; class LdapSync extends Command @@ -54,7 +54,7 @@ class LdapSync extends Command $ldap_result_email = Setting::getSettings()->ldap_email; $ldap_result_phone = Setting::getSettings()->ldap_phone_field; $ldap_result_jobtitle = Setting::getSettings()->ldap_jobtitle; - $ldap_result_country = Setting::getSettings()->ldap_country; + $ldap_result_country = Setting::getSettings()->ldap_country; $ldap_result_dept = Setting::getSettings()->ldap_dept; try { @@ -62,14 +62,15 @@ class LdapSync extends Command Ldap::bindAdminToLdap($ldapconn); } catch (\Exception $e) { if ($this->option('json_summary')) { - $json_summary = [ "error" => true, "error_message" => $e->getMessage(), "summary" => [] ]; + $json_summary = ['error' => true, 'error_message' => $e->getMessage(), 'summary' => []]; $this->info(json_encode($json_summary)); } LOG::info($e); + return []; } - $summary = array(); + $summary = []; try { if ($this->option('base_dn') != '') { @@ -81,78 +82,78 @@ class LdapSync extends Command $results = Ldap::findLdapUsers($search_base); } catch (\Exception $e) { if ($this->option('json_summary')) { - $json_summary = [ "error" => true, "error_message" => $e->getMessage(), "summary" => [] ]; + $json_summary = ['error' => true, 'error_message' => $e->getMessage(), 'summary' => []]; $this->info(json_encode($json_summary)); } LOG::info($e); + return []; } /* Determine which location to assign users to by default. */ - $location = NULL; // FIXME - this would be better called "$default_location", which is more explicit about its purpose + $location = null; // FIXME - this would be better called "$default_location", which is more explicit about its purpose - if ($this->option('location')!='') { + if ($this->option('location') != '') { $location = Location::where('name', '=', $this->option('location'))->first(); LOG::debug('Location name '.$this->option('location').' passed'); LOG::debug('Importing to '.$location->name.' ('.$location->id.')'); - } elseif ($this->option('location_id')!='') { + } elseif ($this->option('location_id') != '') { $location = Location::where('id', '=', $this->option('location_id'))->first(); LOG::debug('Location ID '.$this->option('location_id').' passed'); LOG::debug('Importing to '.$location->name.' ('.$location->id.')'); } - if (!isset($location)) { + if (! isset($location)) { LOG::debug('That location is invalid or a location was not provided, so no location will be assigned by default.'); } /* Process locations with explicitly defined OUs, if doing a full import. */ - if ($this->option('base_dn')=='') { + if ($this->option('base_dn') == '') { // Retrieve locations with a mapped OU, and sort them from the shallowest to deepest OU (see #3993) $ldap_ou_locations = Location::where('ldap_ou', '!=', '')->get()->toArray(); - $ldap_ou_lengths = array(); + $ldap_ou_lengths = []; foreach ($ldap_ou_locations as $ou_loc) { - $ldap_ou_lengths[] = strlen($ou_loc["ldap_ou"]); + $ldap_ou_lengths[] = strlen($ou_loc['ldap_ou']); } array_multisort($ldap_ou_lengths, SORT_ASC, $ldap_ou_locations); - if (sizeof($ldap_ou_locations) > 0) { + if (count($ldap_ou_locations) > 0) { LOG::debug('Some locations have special OUs set. Locations will be automatically set for users in those OUs.'); } // Inject location information fields - for ($i = 0; $i < $results["count"]; $i++) { - $results[$i]["ldap_location_override"] = false; - $results[$i]["location_id"] = 0; + for ($i = 0; $i < $results['count']; $i++) { + $results[$i]['ldap_location_override'] = false; + $results[$i]['location_id'] = 0; } // Grab subsets based on location-specific DNs, and overwrite location for these users. foreach ($ldap_ou_locations as $ldap_loc) { try { - $location_users = Ldap::findLdapUsers($ldap_loc["ldap_ou"]); + $location_users = Ldap::findLdapUsers($ldap_loc['ldap_ou']); } catch (\Exception $e) { // FIXME: this is stolen from line 77 or so above if ($this->option('json_summary')) { - $json_summary = [ "error" => true, "error_message" => trans('admin/users/message.error.ldap_could_not_search')." Location: ".$ldap_loc['name']." (ID: ".$ldap_loc['id'].") cannot connect to \"".$ldap_loc["ldap_ou"]."\" - ".$e->getMessage(), "summary" => [] ]; + $json_summary = ['error' => true, 'error_message' => trans('admin/users/message.error.ldap_could_not_search').' Location: '.$ldap_loc['name'].' (ID: '.$ldap_loc['id'].') cannot connect to "'.$ldap_loc['ldap_ou'].'" - '.$e->getMessage(), 'summary' => []]; $this->info(json_encode($json_summary)); } LOG::info($e); + return []; } - $usernames = array(); - for ($i = 0; $i < $location_users["count"]; $i++) { - + $usernames = []; + for ($i = 0; $i < $location_users['count']; $i++) { if (array_key_exists($ldap_result_username, $location_users[$i])) { - $location_users[$i]["ldap_location_override"] = true; - $location_users[$i]["location_id"] = $ldap_loc["id"]; + $location_users[$i]['ldap_location_override'] = true; + $location_users[$i]['location_id'] = $ldap_loc['id']; $usernames[] = $location_users[$i][$ldap_result_username][0]; } - } // Delete located users from the general group. foreach ($results as $key => $generic_entry) { - if ((is_array($generic_entry)) && (array_key_exists($ldap_result_username, $generic_entry))) { + if ((is_array($generic_entry)) && (array_key_exists($ldap_result_username, $generic_entry))) { if (in_array($generic_entry[$ldap_result_username][0], $usernames)) { unset($results[$key]); } @@ -166,55 +167,52 @@ class LdapSync extends Command } /* Create user account entries in Snipe-IT */ - $tmp_pass = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20); + $tmp_pass = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 20); $pass = bcrypt($tmp_pass); - for ($i = 0; $i < $results["count"]; $i++) { - if (empty($ldap_result_active_flag) || $results[$i][$ldap_result_active_flag][0] == "TRUE") { - - $item = array(); - $item["username"] = isset($results[$i][$ldap_result_username][0]) ? $results[$i][$ldap_result_username][0] : ""; - $item["employee_number"] = isset($results[$i][$ldap_result_emp_num][0]) ? $results[$i][$ldap_result_emp_num][0] : ""; - $item["lastname"] = isset($results[$i][$ldap_result_last_name][0]) ? $results[$i][$ldap_result_last_name][0] : ""; - $item["firstname"] = isset($results[$i][$ldap_result_first_name][0]) ? $results[$i][$ldap_result_first_name][0] : ""; - $item["email"] = isset($results[$i][$ldap_result_email][0]) ? $results[$i][$ldap_result_email][0] : "" ; - $item["ldap_location_override"] = isset($results[$i]["ldap_location_override"]) ? $results[$i]["ldap_location_override"]:""; - $item["location_id"] = isset($results[$i]["location_id"]) ? $results[$i]["location_id"]:""; - $item["telephone"] = isset($results[$i][$ldap_result_phone][0]) ? $results[$i][$ldap_result_phone][0] : ""; - $item["jobtitle"] = isset($results[$i][$ldap_result_jobtitle][0]) ? $results[$i][$ldap_result_jobtitle][0] : ""; - $item["country"] = isset($results[$i][$ldap_result_country][0]) ? $results[$i][$ldap_result_country][0] : ""; - $item["department"] = isset($results[$i][$ldap_result_dept][0]) ? $results[$i][$ldap_result_dept][0] : ""; - + for ($i = 0; $i < $results['count']; $i++) { + if (empty($ldap_result_active_flag) || $results[$i][$ldap_result_active_flag][0] == 'TRUE') { + $item = []; + $item['username'] = isset($results[$i][$ldap_result_username][0]) ? $results[$i][$ldap_result_username][0] : ''; + $item['employee_number'] = isset($results[$i][$ldap_result_emp_num][0]) ? $results[$i][$ldap_result_emp_num][0] : ''; + $item['lastname'] = isset($results[$i][$ldap_result_last_name][0]) ? $results[$i][$ldap_result_last_name][0] : ''; + $item['firstname'] = isset($results[$i][$ldap_result_first_name][0]) ? $results[$i][$ldap_result_first_name][0] : ''; + $item['email'] = isset($results[$i][$ldap_result_email][0]) ? $results[$i][$ldap_result_email][0] : ''; + $item['ldap_location_override'] = isset($results[$i]['ldap_location_override']) ? $results[$i]['ldap_location_override'] : ''; + $item['location_id'] = isset($results[$i]['location_id']) ? $results[$i]['location_id'] : ''; + $item['telephone'] = isset($results[$i][$ldap_result_phone][0]) ? $results[$i][$ldap_result_phone][0] : ''; + $item['jobtitle'] = isset($results[$i][$ldap_result_jobtitle][0]) ? $results[$i][$ldap_result_jobtitle][0] : ''; + $item['country'] = isset($results[$i][$ldap_result_country][0]) ? $results[$i][$ldap_result_country][0] : ''; + $item['department'] = isset($results[$i][$ldap_result_dept][0]) ? $results[$i][$ldap_result_dept][0] : ''; $department = Department::firstOrCreate([ - 'name' => $item["department"], + 'name' => $item['department'], ]); - - $user = User::where('username', $item["username"])->first(); + $user = User::where('username', $item['username'])->first(); if ($user) { // Updating an existing user. - $item["createorupdate"] = 'updated'; + $item['createorupdate'] = 'updated'; } else { // Creating a new user. $user = new User; $user->password = $pass; $user->activated = 0; - $item["createorupdate"] = 'created'; + $item['createorupdate'] = 'created'; } - $user->first_name = $item["firstname"]; - $user->last_name = $item["lastname"]; - $user->username = $item["username"]; - $user->email = $item["email"]; - $user->employee_num = e($item["employee_number"]); - $user->phone = $item["telephone"]; - $user->jobtitle = $item["jobtitle"]; - $user->country = $item["country"]; + $user->first_name = $item['firstname']; + $user->last_name = $item['lastname']; + $user->username = $item['username']; + $user->email = $item['email']; + $user->employee_num = e($item['employee_number']); + $user->phone = $item['telephone']; + $user->jobtitle = $item['jobtitle']; + $user->country = $item['country']; $user->department_id = $department->id; // Sync activated state for Active Directory. - if ( array_key_exists('useraccountcontrol', $results[$i]) ) { + if (array_key_exists('useraccountcontrol', $results[$i])) { /* The following is _probably_ the correct logic, but we can't use it because some users may have been dependent upon the previous behavior, and this could cause additional access to be available to users they don't want @@ -231,7 +229,7 @@ class LdapSync extends Command } else { $user->activated = 0; } */ - $enabled_accounts = [ + $enabled_accounts = [ '512', // 0x200 NORMAL_ACCOUNT '544', // 0x220 NORMAL_ACCOUNT, PASSWD_NOTREQD '66048', // 0x10200 NORMAL_ACCOUNT, DONT_EXPIRE_PASSWORD @@ -240,27 +238,25 @@ class LdapSync extends Command '262688', // 0x40220 NORMAL_ACCOUNT, PASSWD_NOTREQD, SMARTCARD_REQUIRED '328192', // 0x50200 NORMAL_ACCOUNT, SMARTCARD_REQUIRED, DONT_EXPIRE_PASSWORD '328224', // 0x50220 NORMAL_ACCOUNT, PASSWD_NOT_REQD, SMARTCARD_REQUIRED, DONT_EXPIRE_PASSWORD - '4260352',// 0x410200 NORMAL_ACCOUNT, DONT_EXPIRE_PASSWORD, DONT_REQ_PREAUTH - '1049088',// 0x100200 NORMAL_ACCOUNT, NOT_DELEGATED + '4260352', // 0x410200 NORMAL_ACCOUNT, DONT_EXPIRE_PASSWORD, DONT_REQ_PREAUTH + '1049088', // 0x100200 NORMAL_ACCOUNT, NOT_DELEGATED ]; - $user->activated = ( in_array($results[$i]['useraccountcontrol'][0], $enabled_accounts) ) ? 1 : 0; + $user->activated = (in_array($results[$i]['useraccountcontrol'][0], $enabled_accounts)) ? 1 : 0; } // If we're not using AD, and there isn't an activated flag set, activate all users elseif (empty($ldap_result_active_flag)) { - $user->activated = 1; + $user->activated = 1; } if ($item['ldap_location_override'] == true) { $user->location_id = $item['location_id']; - } elseif ((isset($location)) && (!empty($location))) { - + } elseif ((isset($location)) && (! empty($location))) { if ((is_array($location)) && (array_key_exists('id', $location))) { $user->location_id = $location['id']; } elseif (is_object($location)) { $user->location_id = $location->id; } - } $user->ldap_import = 1; @@ -268,31 +264,30 @@ class LdapSync extends Command $errors = ''; if ($user->save()) { - $item["note"] = $item["createorupdate"]; - $item["status"]='success'; + $item['note'] = $item['createorupdate']; + $item['status'] = 'success'; } else { foreach ($user->getErrors()->getMessages() as $key => $err) { $errors .= $err[0]; } - $item["note"] = $errors; - $item["status"]='error'; + $item['note'] = $errors; + $item['status'] = 'error'; } array_push($summary, $item); } - } if ($this->option('summary')) { for ($x = 0; $x < count($summary); $x++) { - if ($summary[$x]['status']=='error') { + if ($summary[$x]['status'] == 'error') { $this->error('ERROR: '.$summary[$x]['firstname'].' '.$summary[$x]['lastname'].' (username: '.$summary[$x]['username'].') was not imported: '.$summary[$x]['note']); } else { $this->info('User '.$summary[$x]['firstname'].' '.$summary[$x]['lastname'].' (username: '.$summary[$x]['username'].') was '.strtoupper($summary[$x]['createorupdate']).'.'); } } - } else if ($this->option('json_summary')) { - $json_summary = [ "error" => false, "error_message" => "", "summary" => $summary ]; // hardcoding the error to false and the error_message to blank seems a bit weird + } elseif ($this->option('json_summary')) { + $json_summary = ['error' => false, 'error_message' => '', 'summary' => $summary]; // hardcoding the error to false and the error_message to blank seems a bit weird $this->info(json_encode($json_summary)); } else { return $summary; diff --git a/app/Console/Commands/LdapSyncNg.php b/app/Console/Commands/LdapSyncNg.php index 527a99777c..b271c6c10c 100644 --- a/app/Console/Commands/LdapSyncNg.php +++ b/app/Console/Commands/LdapSyncNg.php @@ -4,13 +4,13 @@ declare(strict_types=1); namespace App\Console\Commands; -use Log; -use Exception; +use Adldap\Models\User as AdldapUser; +use App\Models\Location; use App\Models\User; use App\Services\LdapAd; -use App\Models\Location; +use Exception; use Illuminate\Console\Command; -use Adldap\Models\User as AdldapUser; +use Log; /** * LDAP / AD sync command. @@ -96,9 +96,9 @@ class LdapSyncNg extends Command public function __construct(LdapAd $ldap) { parent::__construct(); - $this->ldap = $ldap; + $this->ldap = $ldap; $this->settings = $this->ldap->ldapSettings; - $this->summary = collect(); + $this->summary = collect(); } /** @@ -108,22 +108,21 @@ class LdapSyncNg extends Command */ public function handle() { - - $dispatcher = \Adldap\Adldap::getEventDispatcher(); + $dispatcher = \Adldap\Adldap::getEventDispatcher(); // Listen for all model events. $dispatcher->listen('Adldap\Models\Events\*', function ($eventName, array $data) { echo $eventName; // Returns 'Adldap\Models\Events\Updating' var_dump($data); // Returns [0] => (object) Adldap\Models\Events\Updating; - \Log::debug("Event: ".$eventName." data - ".print_r($data, true)); + \Log::debug('Event: '.$eventName.' data - '.print_r($data, true)); }); $dispatcher->listen('Adldap\Auth\Events\*', function ($eventName, array $data) { echo $eventName; // Returns 'Adldap\Models\Events\Updating' var_dump($data); // Returns [0] => (object) Adldap\Models\Events\Updating; - \Log::debug("Event: ".$eventName." data - ".print_r($data, true)); + \Log::debug('Event: '.$eventName.' data - '.print_r($data, true)); }); - ini_set('max_execution_time', env('LDAP_TIME_LIM', "600")); //600 seconds = 10 minutes + ini_set('max_execution_time', env('LDAP_TIME_LIM', '600')); //600 seconds = 10 minutes ini_set('memory_limit', '500M'); $old_error_reporting = error_reporting(); // grab old error_reporting .ini setting, for later re-enablement error_reporting($old_error_reporting & ~E_DEPRECATED); // disable deprecation warnings, for LDAP in PHP 7.4 (and greater) @@ -138,7 +137,7 @@ class LdapSyncNg extends Command /* * Use the default location if set, this is needed for the LDAP users sync page */ - if (!$this->option('base_dn') && null == $this->defaultLocation) { + if (! $this->option('base_dn') && null == $this->defaultLocation) { $this->getMappedLocations(); } $this->processLdapUsers(); @@ -150,6 +149,7 @@ class LdapSyncNg extends Command } error_reporting($old_error_reporting); // re-enable deprecation warnings. + return $this->getSummary(); } @@ -205,17 +205,17 @@ class LdapSyncNg extends Command 'location_id' => $user->location_id, ]; // Only update the database if is not a dry run - if (!$this->dryrun) { + if (! $this->dryrun) { if ($user->isDirty()) { //if nothing on the user changed, don't bother trying to save anything nor put anything in the summary if ($user->save()) { - $summary['note'] = ($user->wasRecentlyCreated ? 'CREATED' : 'UPDATED'); + $summary['note'] = ($user->wasRecentlyCreated ? 'CREATED' : 'UPDATED'); $summary['status'] = 'SUCCESS'; } else { $errors = ''; foreach ($user->getErrors()->getMessages() as $error) { - $errors .= implode(", ",$error); + $errors .= implode(', ', $error); } - $summary['note'] = $snipeUser->getDN().' was not imported. REASON: '.$errors; + $summary['note'] = $snipeUser->getDN().' was not imported. REASON: '.$errors; $summary['status'] = 'ERROR'; } } else { @@ -224,7 +224,7 @@ class LdapSyncNg extends Command } // $summary['note'] = ($user->getOriginal('username') ? 'UPDATED' : 'CREATED'); // this seems, kinda, like, superfluous, relative to the $summary['note'] thing above, yeah? - if($summary) { //if the $user wasn't dirty, $summary was set to null so that we will skip the following push() + if ($summary) { //if the $user wasn't dirty, $summary was set to null so that we will skip the following push() $this->summary->push($summary); } } @@ -235,14 +235,13 @@ class LdapSyncNg extends Command * @author Wes Hulette * * @since 5.0.0 - * */ private function processLdapUsers(): void { try { - \Log::debug("CAL:LING GET LDAP SUSERS"); + \Log::debug('CAL:LING GET LDAP SUSERS'); $ldapUsers = $this->ldap->getLdapUsers(); - \Log::debug("END CALLING GET LDAP USERS"); + \Log::debug('END CALLING GET LDAP USERS'); } catch (Exception $e) { $this->outputError($e); exit($e->getMessage()); diff --git a/app/Console/Commands/MergeUsersByUsername.php b/app/Console/Commands/MergeUsersByUsername.php index 95278817ea..a3eb8f2d95 100644 --- a/app/Console/Commands/MergeUsersByUsername.php +++ b/app/Console/Commands/MergeUsersByUsername.php @@ -2,10 +2,9 @@ namespace App\Console\Commands; -use Illuminate\Console\Command; use App\Models\User; use Carbon\Carbon; - +use Illuminate\Console\Command; class MergeUsersByUsername extends Command { @@ -44,7 +43,7 @@ class MergeUsersByUsername extends Command $users = User::where('username', 'LIKE', '%@%')->whereNull('deleted_at')->get(); foreach ($users as $user) { - $parts = explode("@", $user->username); + $parts = explode('@', $user->username); $bad_users = User::where('username', '=', $parts[0])->whereNull('deleted_at')->with('assets', 'manager', 'userlog', 'licenses', 'consumables', 'accessories', 'managedLocations')->get(); foreach ($bad_users as $bad_user) { @@ -52,61 +51,55 @@ class MergeUsersByUsername extends Command // Walk the list of assets foreach ($bad_user->assets as $asset) { - $this->info( 'Updating asset '.$asset->asset_tag.' '.$asset->id.' to user '.$user->id); + $this->info('Updating asset '.$asset->asset_tag.' '.$asset->id.' to user '.$user->id); $asset->assigned_to = $user->id; - if (!$asset->save()) { - $this->error( 'Could not update assigned_to field on asset '.$asset->asset_tag.' '.$asset->id.' to user '.$user->id); - $this->error( 'Error saving: '.$asset->getErrors()); + if (! $asset->save()) { + $this->error('Could not update assigned_to field on asset '.$asset->asset_tag.' '.$asset->id.' to user '.$user->id); + $this->error('Error saving: '.$asset->getErrors()); } } // Walk the list of licenses foreach ($bad_user->licenses as $license) { - $this->info( 'Updating license '.$license->name.' '.$license->id.' to user '.$user->id); + $this->info('Updating license '.$license->name.' '.$license->id.' to user '.$user->id); $bad_user->licenses()->updateExistingPivot($license->id, ['assigned_to' => $user->id]); } // Walk the list of consumables foreach ($bad_user->consumables as $consumable) { - $this->info( 'Updating consumable '.$consumable->id.' to user '.$user->id); + $this->info('Updating consumable '.$consumable->id.' to user '.$user->id); $bad_user->consumables()->updateExistingPivot($consumable->id, ['assigned_to' => $user->id]); } // Walk the list of accessories foreach ($bad_user->accessories as $accessory) { - $this->info( 'Updating accessory '.$accessory->id.' to user '.$user->id); + $this->info('Updating accessory '.$accessory->id.' to user '.$user->id); $bad_user->accessories()->updateExistingPivot($accessory->id, ['assigned_to' => $user->id]); } // Walk the list of logs foreach ($bad_user->userlog as $log) { - $this->info( 'Updating action log record '.$log->id.' to user '.$user->id); + $this->info('Updating action log record '.$log->id.' to user '.$user->id); $log->target_id = $user->id; $log->save(); } // Update any manager IDs - $this->info( 'Updating managed user records to user '.$user->id); + $this->info('Updating managed user records to user '.$user->id); User::where('manager_id', '=', $bad_user->id)->update(['manager_id' => $user->id]); - // Update location manager IDs foreach ($bad_user->managedLocations as $managedLocation) { - $this->info( 'Updating managed location record '.$managedLocation->name.' to manager '.$user->id); + $this->info('Updating managed location record '.$managedLocation->name.' to manager '.$user->id); $managedLocation->manager_id = $user->id; $managedLocation->save(); } // Mark the user as deleted - $this->info( 'Marking the user as deleted'); + $this->info('Marking the user as deleted'); $bad_user->deleted_at = Carbon::now()->timestamp; $bad_user->save(); - - } - } - - } } diff --git a/app/Console/Commands/MoveUploadsToNewDisk.php b/app/Console/Commands/MoveUploadsToNewDisk.php index 9bd3a94aba..8fa5ddafd7 100644 --- a/app/Console/Commands/MoveUploadsToNewDisk.php +++ b/app/Console/Commands/MoveUploadsToNewDisk.php @@ -2,7 +2,6 @@ namespace App\Console\Commands; - use Illuminate\Console\Command; use Illuminate\Support\Facades\Storage; @@ -39,39 +38,37 @@ class MoveUploadsToNewDisk extends Command */ public function handle() { - - if (config('filesystems.default')=='local') { + if (config('filesystems.default') == 'local') { $this->error('Your current disk is set to local so we cannot proceed.'); $this->warn("Please configure your .env settings for S3. \nChange your PUBLIC_FILESYSTEM_DISK value to 's3_public' and your PRIVATE_FILESYSTEM_DISK to s3_private."); + return false; } $delete_local = $this->argument('delete_local'); - $public_uploads['accessories'] = glob('public/accessories'."/*.*"); - $public_uploads['assets'] = glob('public/assets'."/*.*"); - $public_uploads['avatars'] = glob('public/avatars'."/*.*"); - $public_uploads['categories'] = glob('public/categories'."/*.*"); - $public_uploads['companies'] = glob('public/companies'."/*.*"); - $public_uploads['components'] = glob('public/components'."/*.*"); - $public_uploads['consumables'] = glob('public/consumables'."/*.*"); - $public_uploads['departments'] = glob('public/departments'."/*.*"); - $public_uploads['locations'] = glob('public/locations'."/*.*"); - $public_uploads['manufacturers'] = glob('public/manufacturers'."/*.*"); - $public_uploads['suppliers'] = glob('public/suppliers'."/*.*"); - $public_uploads['assetmodels'] = glob('public/models'."/*.*"); - + $public_uploads['accessories'] = glob('public/accessories'.'/*.*'); + $public_uploads['assets'] = glob('public/assets'.'/*.*'); + $public_uploads['avatars'] = glob('public/avatars'.'/*.*'); + $public_uploads['categories'] = glob('public/categories'.'/*.*'); + $public_uploads['companies'] = glob('public/companies'.'/*.*'); + $public_uploads['components'] = glob('public/components'.'/*.*'); + $public_uploads['consumables'] = glob('public/consumables'.'/*.*'); + $public_uploads['departments'] = glob('public/departments'.'/*.*'); + $public_uploads['locations'] = glob('public/locations'.'/*.*'); + $public_uploads['manufacturers'] = glob('public/manufacturers'.'/*.*'); + $public_uploads['suppliers'] = glob('public/suppliers'.'/*.*'); + $public_uploads['assetmodels'] = glob('public/models'.'/*.*'); // iterate files - foreach($public_uploads as $public_type => $public_upload) - { + foreach ($public_uploads as $public_type => $public_upload) { $type_count = 0; - $this->info("- There are ".count($public_upload).' PUBLIC '.$public_type.' files.'); + $this->info('- There are '.count($public_upload).' PUBLIC '.$public_type.' files.'); for ($i = 0; $i < count($public_upload); $i++) { $type_count++; $filename = basename($public_upload[$i]); - try { + try { Storage::disk('public')->put('uploads/'.public_type.'/'.$filename, file_get_contents($public_upload[$i])); $new_url = Storage::disk('public')->url('uploads/'.$public_type.'/'.$filename, $filename); $this->info($type_count.'. PUBLIC: '.$filename.' was copied to '.$new_url); @@ -79,13 +76,11 @@ class MoveUploadsToNewDisk extends Command \Log::debug($e); $this->error($e); } - } - } - $logos = glob("public/uploads/setting*.*"); - $this->info("- There are ".count($logos).' files that might be logos.'); + $logos = glob('public/uploads/setting*.*'); + $this->info('- There are '.count($logos).' files that might be logos.'); $type_count = 0; foreach ($logos as $logo) { @@ -96,41 +91,35 @@ class MoveUploadsToNewDisk extends Command $this->info($type_count.'. LOGO: '.$filename.' was copied to '.env('PUBLIC_AWS_URL').'/uploads/'.$filename); } - $private_uploads['assets'] = glob('storage/private_uploads/assets'."/*.*"); - $private_uploads['signatures'] = glob('storage/private_uploads/signatures'."/*.*"); - $private_uploads['audits'] = glob('storage/private_uploads/audits'."/*.*"); - $private_uploads['assetmodels'] = glob('storage/private_uploads/assetmodels'."/*.*"); - $private_uploads['imports'] = glob('storage/private_uploads/imports'."/*.*"); - $private_uploads['licenses'] = glob('storage/private_uploads/licenses'."/*.*"); - $private_uploads['users'] = glob('storage/private_uploads/users'."/*.*"); - $private_uploads['backups'] = glob('storage/private_uploads/users'."/*.*"); + $private_uploads['assets'] = glob('storage/private_uploads/assets'.'/*.*'); + $private_uploads['signatures'] = glob('storage/private_uploads/signatures'.'/*.*'); + $private_uploads['audits'] = glob('storage/private_uploads/audits'.'/*.*'); + $private_uploads['assetmodels'] = glob('storage/private_uploads/assetmodels'.'/*.*'); + $private_uploads['imports'] = glob('storage/private_uploads/imports'.'/*.*'); + $private_uploads['licenses'] = glob('storage/private_uploads/licenses'.'/*.*'); + $private_uploads['users'] = glob('storage/private_uploads/users'.'/*.*'); + $private_uploads['backups'] = glob('storage/private_uploads/users'.'/*.*'); - - foreach($private_uploads as $private_type => $private_upload) - { - $this->info("- There are ".count($private_upload).' PRIVATE '.$private_type.' files.'); + foreach ($private_uploads as $private_type => $private_upload) { + $this->info('- There are '.count($private_upload).' PRIVATE '.$private_type.' files.'); $type_count = 0; for ($x = 0; $x < count($private_upload); $x++) { $type_count++; $filename = basename($private_upload[$x]); - try { + try { Storage::put($private_type.'/'.$filename, file_get_contents($private_upload[$i])); $new_url = Storage::url($private_type.'/'.$filename, $filename); $this->info($type_count.'. PRIVATE: '.$filename.' was copied to '.$new_url); - } catch (\Exception $e) { \Log::debug($e); $this->error($e); } - } - } - - if ($delete_local=='true') { + if ($delete_local == 'true') { $public_delete_count = 0; $private_delete_count = 0; @@ -139,10 +128,8 @@ class MoveUploadsToNewDisk extends Command $this->warn("\nTHIS WILL DELETE ALL OF YOUR LOCAL UPLOADED FILES. \n\nThis cannot be undone, so you should take a backup of your system before you proceed.\n"); $this->error('!!!!!!!!!!!!!!!!!!!!!!!!!!!!! WARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'); - if ($this->confirm("Do you wish to continue?")) { - - foreach($public_uploads as $public_type => $public_upload) { - + if ($this->confirm('Do you wish to continue?')) { + foreach ($public_uploads as $public_type => $public_upload) { for ($i = 0; $i < count($public_upload); $i++) { $filename = $public_upload[$i]; try { @@ -152,13 +139,10 @@ class MoveUploadsToNewDisk extends Command \Log::debug($e); $this->error($e); } - } } - foreach($private_uploads as $private_type => $private_upload) - { - + foreach ($private_uploads as $private_type => $private_upload) { for ($i = 0; $i < count($private_upload); $i++) { $filename = $private_upload[$i]; try { @@ -168,16 +152,11 @@ class MoveUploadsToNewDisk extends Command \Log::debug($e); $this->error($e); } - } } - $this->info($public_delete_count." PUBLIC local files and ".$private_delete_count." PRIVATE local files were deleted from your filesystem."); + $this->info($public_delete_count.' PUBLIC local files and '.$private_delete_count.' PRIVATE local files were deleted from your filesystem.'); } } - - - - } } diff --git a/app/Console/Commands/ObjectImportCommand.php b/app/Console/Commands/ObjectImportCommand.php index 71c974a21d..c89018400a 100644 --- a/app/Console/Commands/ObjectImportCommand.php +++ b/app/Console/Commands/ObjectImportCommand.php @@ -1,4 +1,5 @@ setShouldNotify($this->option('send-welcome')) ->setUsernameFormat($this->option('username_format')); - // This $logFile/useFiles() bit is currently broken, so commenting it out for now // $logFile = $this->option('logfile'); // \Log::useFiles($logFile); @@ -64,29 +65,28 @@ class ObjectImportCommand extends Command $this->bar = null; - if (!empty($this->errors)) { - $this->comment("The following Errors were encountered."); + if (! empty($this->errors)) { + $this->comment('The following Errors were encountered.'); foreach ($this->errors as $asset => $error) { - $this->comment('Error: Item: ' . $asset . ' failed validation: ' . json_encode($error)); + $this->comment('Error: Item: '.$asset.' failed validation: '.json_encode($error)); } } else { - $this->comment("All Items imported successfully!"); + $this->comment('All Items imported successfully!'); } - $this->comment(""); - - return; + $this->comment(''); } public function errorCallback($item, $field, $errorString) { $this->errors[$item->name][$field] = $errorString; } + public function progress($count) { - if (!$this->bar) { + if (! $this->bar) { $this->bar = $this->output->createProgressBar($count); } - static $index =0; + static $index = 0; $index++; if ($index < $count) { $this->bar->advance(); @@ -94,12 +94,12 @@ class ObjectImportCommand extends Command $this->bar->finish(); } } + // Tracks the current item for error messages private $updating; // An array of errors encountered while parsing private $errors; - /** * Log a message to file, configurable by the --log-file parameter. * If a warning message is passed, we'll spit it to the console as well. @@ -108,7 +108,7 @@ class ObjectImportCommand extends Command * @since 3.0 * @param string $string * @param string $level - */ + */ public function log($string, $level = 'info') { if ($level === 'warning') { @@ -121,6 +121,7 @@ class ObjectImportCommand extends Command } } } + /** * Get the console command arguments. * @@ -130,12 +131,11 @@ class ObjectImportCommand extends Command */ protected function getArguments() { - return array( - array('filename', InputArgument::REQUIRED, 'File for the CSV import.'), - ); + return [ + ['filename', InputArgument::REQUIRED, 'File for the CSV import.'], + ]; } - /** * Get the console command options. * @@ -145,16 +145,15 @@ class ObjectImportCommand extends Command */ protected function getOptions() { - return array( - array('email_format', null, InputOption::VALUE_REQUIRED, 'The format of the email addresses that should be generated. Options are firstname.lastname, firstname, filastname', null), - array('username_format', null, InputOption::VALUE_REQUIRED, 'The format of the username that should be generated. Options are firstname.lastname, firstname, filastname, email', null), - array('logfile', null, InputOption::VALUE_REQUIRED, 'The path to log output to. storage/logs/importer.log by default', storage_path('logs/importer.log') ), - array('item-type', null, InputOption::VALUE_REQUIRED, 'Item Type To import. Valid Options are Asset, Consumable, Accessory, License, or User', 'Asset'), - array('web-importer', null, InputOption::VALUE_NONE, 'Internal: packages output for use with the web importer'), - array('user_id', null, InputOption::VALUE_REQUIRED, 'ID of user creating items', 1), - array('update', null, InputOption::VALUE_NONE, 'If a matching item is found, update item information'), - array('send-welcome', null, InputOption::VALUE_NONE, 'Whether to send a welcome email to any new users that are created.'), - ); - + return [ + ['email_format', null, InputOption::VALUE_REQUIRED, 'The format of the email addresses that should be generated. Options are firstname.lastname, firstname, filastname', null], + ['username_format', null, InputOption::VALUE_REQUIRED, 'The format of the username that should be generated. Options are firstname.lastname, firstname, filastname, email', null], + ['logfile', null, InputOption::VALUE_REQUIRED, 'The path to log output to. storage/logs/importer.log by default', storage_path('logs/importer.log')], + ['item-type', null, InputOption::VALUE_REQUIRED, 'Item Type To import. Valid Options are Asset, Consumable, Accessory, License, or User', 'Asset'], + ['web-importer', null, InputOption::VALUE_NONE, 'Internal: packages output for use with the web importer'], + ['user_id', null, InputOption::VALUE_REQUIRED, 'ID of user creating items', 1], + ['update', null, InputOption::VALUE_NONE, 'If a matching item is found, update item information'], + ['send-welcome', null, InputOption::VALUE_NONE, 'Whether to send a welcome email to any new users that are created.'], + ]; } } diff --git a/app/Console/Commands/Purge.php b/app/Console/Commands/Purge.php index a9f1da7374..7abd83c85c 100644 --- a/app/Console/Commands/Purge.php +++ b/app/Console/Commands/Purge.php @@ -50,7 +50,7 @@ class Purge extends Command public function handle() { $force = $this->option('force'); - if (($this->confirm("\n****************************************************\nTHIS WILL PURGE ALL SOFT-DELETED ITEMS IN YOUR SYSTEM. \nThere is NO undo. This WILL permanently destroy \nALL of your deleted data. \n****************************************************\n\nDo you wish to continue? No backsies! [y|N]")) || $force == 'true') { + if (($this->confirm("\n****************************************************\nTHIS WILL PURGE ALL SOFT-DELETED ITEMS IN YOUR SYSTEM. \nThere is NO undo. This WILL permanently destroy \nALL of your deleted data. \n****************************************************\n\nDo you wish to continue? No backsies! [y|N]")) || $force == 'true') { /** * Delete assets @@ -80,9 +80,8 @@ class Purge extends Command $location->forceDelete(); } - $accessories = Accessory::whereNotNull('deleted_at')->withTrashed()->get(); - $accessory_assoc=0; + $accessory_assoc = 0; $this->info($accessories->count().' accessories purged.'); foreach ($accessories as $accessory) { $this->info('- Accessory "'.$accessory->name.'" deleted.'); @@ -92,7 +91,6 @@ class Purge extends Command } $this->info($accessory_assoc.' corresponding log records purged.'); - $consumables = Consumable::whereNotNull('deleted_at')->withTrashed()->get(); $this->info($consumables->count().' consumables purged.'); foreach ($consumables as $consumable) { @@ -101,7 +99,6 @@ class Purge extends Command $consumable->forceDelete(); } - $components = Component::whereNotNull('deleted_at')->withTrashed()->get(); $this->info($components->count().' components purged.'); foreach ($components as $component) { @@ -126,7 +123,6 @@ class Purge extends Command $model->forceDelete(); } - $categories = Category::whereNotNull('deleted_at')->withTrashed()->get(); $this->info($categories->count().' categories purged.'); foreach ($categories as $category) { @@ -165,11 +161,8 @@ class Purge extends Command $this->info('- Status Label "'.$status_label->name.'" deleted.'); $status_label->forceDelete(); } - - } else { $this->info('Action canceled. Nothing was purged.'); } - } } diff --git a/app/Console/Commands/PurgeLoginAttempts.php b/app/Console/Commands/PurgeLoginAttempts.php index 7a7a1394d7..44e1d1bd1e 100644 --- a/app/Console/Commands/PurgeLoginAttempts.php +++ b/app/Console/Commands/PurgeLoginAttempts.php @@ -38,7 +38,7 @@ class PurgeLoginAttempts extends Command public function handle() { if ($this->confirm("\n****************************************************\nTHIS WILL DELETE ALL OF THE YOUR LOGIN ATTEMPT RECORDS. \nThere is NO undo! \n****************************************************\n\nDo you wish to continue? No backsies! [y|N]")) { - \DB::statement('delete from login_attempts'); + \DB::statement('delete from login_attempts'); } } } diff --git a/app/Console/Commands/ReEncodeCustomFieldNames.php b/app/Console/Commands/ReEncodeCustomFieldNames.php index 14276b1bd3..f89864e951 100644 --- a/app/Console/Commands/ReEncodeCustomFieldNames.php +++ b/app/Console/Commands/ReEncodeCustomFieldNames.php @@ -48,15 +48,13 @@ class ReEncodeCustomFieldNames extends Command */ public function handle() { - - if ($this->confirm('This will regenerate all of the custom field database fieldnames in your database. THIS WILL CHANGE YOUR SCHEMA AND SHOULD NOT BE DONE WITHOUT MAKING A BACKUP FIRST. Do you wish to continue?')) - { + if ($this->confirm('This will regenerate all of the custom field database fieldnames in your database. THIS WILL CHANGE YOUR SCHEMA AND SHOULD NOT BE DONE WITHOUT MAKING A BACKUP FIRST. Do you wish to continue?')) { /** Get all of the custom fields */ $fields = CustomField::get(); $asset_columns = \DB::getSchemaBuilder()->getColumnListing('assets'); - $custom_field_columns = array(); + $custom_field_columns = []; /** Loop through the columns on the assets table */ foreach ($asset_columns as $asset_column) { @@ -71,18 +69,16 @@ class ReEncodeCustomFieldNames extends Command * Then use that ID as the array key for use comparing the actual assets field name * and the db_column value from the custom fields table. */ - $last_part = substr(strrchr($asset_column, "_snipeit_"), 1); + $last_part = substr(strrchr($asset_column, '_snipeit_'), 1); $custom_field_columns[$last_part] = $asset_column; } } foreach ($fields as $field) { - - $this->info($field->name .' ('.$field->id.') column should be '. $field->convertUnicodeDbSlug().''); + $this->info($field->name.' ('.$field->id.') column should be '.$field->convertUnicodeDbSlug().''); /** The assets table has the column it should have, all is well */ - if (\Schema::hasColumn('assets', $field->convertUnicodeDbSlug())) - { + if (\Schema::hasColumn('assets', $field->convertUnicodeDbSlug())) { $this->info('-- ✓ This field exists - all good'); /** @@ -90,24 +86,23 @@ class ReEncodeCustomFieldNames extends Command * what $field->convertUnicodeDbSlug() is *now* expecting. */ } else { - $this->warn('-- X Field mismatch: updating... '); + $this->warn('-- X Field mismatch: updating... '); - /** Make sure the custom_field_columns array has the ID */ - if (array_key_exists($field->id, $custom_field_columns)) { + /** Make sure the custom_field_columns array has the ID */ + if (array_key_exists($field->id, $custom_field_columns)) { - /** - * Update the asset schema to the corrected fieldname that will be recognized by the - * system elsewhere that we use $field->convertUnicodeDbSlug() - */ - \Schema::table('assets', function($table) use ($custom_field_columns, $field) { - $table->renameColumn($custom_field_columns[$field->id], $field->convertUnicodeDbSlug()); - }); + /** + * Update the asset schema to the corrected fieldname that will be recognized by the + * system elsewhere that we use $field->convertUnicodeDbSlug() + */ + \Schema::table('assets', function ($table) use ($custom_field_columns, $field) { + $table->renameColumn($custom_field_columns[$field->id], $field->convertUnicodeDbSlug()); + }); - $this->warn('-- ✓ Field updated from '.$custom_field_columns[$field->id].' to '.$field->convertUnicodeDbSlug()); - - } else { - $this->warn('-- X WARNING: There is no field on the assets table ending in '.$field->id.'. This may require more in-depth investigation and may mean the schema was altered manually.'); - } + $this->warn('-- ✓ Field updated from '.$custom_field_columns[$field->id].' to '.$field->convertUnicodeDbSlug()); + } else { + $this->warn('-- X WARNING: There is no field on the assets table ending in '.$field->id.'. This may require more in-depth investigation and may mean the schema was altered manually.'); + } } /** Update the db_column property in the custom fields table, just in case it doesn't match the other @@ -115,12 +110,7 @@ class ReEncodeCustomFieldNames extends Command */ $field->db_column = $field->convertUnicodeDbSlug(); $field->save(); - - } - } - - } } diff --git a/app/Console/Commands/RecryptFromMcrypt.php b/app/Console/Commands/RecryptFromMcrypt.php index 6c3a962823..805774a517 100644 --- a/app/Console/Commands/RecryptFromMcrypt.php +++ b/app/Console/Commands/RecryptFromMcrypt.php @@ -44,37 +44,35 @@ class RecryptFromMcrypt extends Command public function handle() { - // Check and see if they have a legacy app key listed in their .env // If not, we can try to use the current APP_KEY if looks like it's old $legacy_key = env('LEGACY_APP_KEY'); $key_parts = explode(':', $legacy_key); $legacy_cipher = env('LEGACY_CIPHER', 'rijndael-256'); - $errors = array(); + $errors = []; - if (!$legacy_key) { + if (! $legacy_key) { $this->error('ERROR: You do not have a LEGACY_APP_KEY set in your .env file. Please locate your old APP_KEY and ADD a line to your .env file like: LEGACY_APP_KEY=YOUR_OLD_APP_KEY'); + return false; } - // Do some basic legacy app key length checks if (strlen($legacy_key) == 32) { $legacy_length_check = true; - } elseif (array_key_exists('1', $key_parts) && (strlen($key_parts[1])==44)) { - $legacy_key = base64_decode($key_parts[1],true); + } elseif (array_key_exists('1', $key_parts) && (strlen($key_parts[1]) == 44)) { + $legacy_key = base64_decode($key_parts[1], true); $legacy_length_check = true; } else { $legacy_length_check = false; } - - // Check that the app key is 32 characters if ($legacy_length_check === true) { $this->comment('INFO: Your LEGACY_APP_KEY looks correct. Okay to continue.'); } else { $this->error('ERROR: Your LEGACY_APP_KEY is not the correct length (32 characters or base64 followed by 44 characters for later versions). Please locate your old APP_KEY and use that as your LEGACY_APP_KEY in your .env file to continue.'); + return false; } @@ -84,8 +82,7 @@ class RecryptFromMcrypt extends Command $force = ($this->option('force')) ? true : false; - if ($force || ($this->confirm("Are you SURE you wish to continue?"))) { - + if ($force || ($this->confirm('Are you SURE you wish to continue?'))) { $backup_file = 'backups/env-backups/'.'app_key-'.date('Y-m-d-gis'); try { @@ -95,15 +92,14 @@ class RecryptFromMcrypt extends Command $this->info('WARNING: Could not backup app keys'); } - - if ($legacy_cipher){ - $mcrypter = new McryptEncrypter($legacy_key,$legacy_cipher); - }else{ + if ($legacy_cipher) { + $mcrypter = new McryptEncrypter($legacy_key, $legacy_cipher); + } else { $mcrypter = new McryptEncrypter($legacy_key); } $settings = Setting::getSettings(); - if ($settings->ldap_pword=='') { + if ($settings->ldap_pword == '') { $this->comment('INFO: No LDAP password found. Skipping... '); } else { $decrypted_ldap_pword = $mcrypter->decrypt($settings->ldap_pword); @@ -111,30 +107,28 @@ class RecryptFromMcrypt extends Command $settings->save(); } /** @var CustomField[] $custom_fields */ - $custom_fields = CustomField::where('field_encrypted','=', 1)->get(); + $custom_fields = CustomField::where('field_encrypted', '=', 1)->get(); $this->comment('INFO: Retrieving encrypted custom fields...'); $query = Asset::withTrashed(); foreach ($custom_fields as $custom_field) { - $this->comment('FIELD TO RECRYPT: '.$custom_field->name .' ('.$custom_field->db_column.')'); + $this->comment('FIELD TO RECRYPT: '.$custom_field->name.' ('.$custom_field->db_column.')'); $query->orWhereNotNull($custom_field->db_column); } - // Get all assets with a value in any of the fields that were encrypted /** @var Asset[] $assets */ $assets = $query->get(); $bar = $this->output->createProgressBar(count($assets)); - foreach ($assets as $asset) { foreach ($custom_fields as $encrypted_field) { $columnName = $encrypted_field->db_column; // Make sure the value isn't null - if ($asset->{$columnName}!='') { + if ($asset->{$columnName} != '') { // Try to decrypt the payload using the legacy app key try { $decrypted_field = $mcrypter->decrypt($asset->{$columnName}); @@ -144,14 +138,11 @@ class RecryptFromMcrypt extends Command $errors[] = ' - ERROR: Could not decrypt field ['.$encrypted_field->name.']: '.$e->getMessage(); } } - } $asset->save(); $bar->advance(); } - - $bar->finish(); if (count($errors) > 0) { @@ -162,6 +153,5 @@ class RecryptFromMcrypt extends Command } } } - } } diff --git a/app/Console/Commands/RegenerateAssetTags.php b/app/Console/Commands/RegenerateAssetTags.php index 2646ebeb35..94ed5ce07c 100644 --- a/app/Console/Commands/RegenerateAssetTags.php +++ b/app/Console/Commands/RegenerateAssetTags.php @@ -40,30 +40,26 @@ class RegenerateAssetTags extends Command */ public function handle() { - - if ($this->confirm('This will regenerate all of the asset tags within your system. This action is data-destructive and should be used with caution. Do you wish to continue?')) - { - + if ($this->confirm('This will regenerate all of the asset tags within your system. This action is data-destructive and should be used with caution. Do you wish to continue?')) { $output['info'] = []; $output['warn'] = []; $output['error'] = []; $settings = Setting::getSettings(); - $start_tag = ($this->option('start')) ? $this->option('start') : (($settings->next_auto_tag_base) ? Setting::getSettings()->next_auto_tag_base : 1) ; + $start_tag = ($this->option('start')) ? $this->option('start') : (($settings->next_auto_tag_base) ? Setting::getSettings()->next_auto_tag_base : 1); $this->info('Starting at '.$start_tag); - $total_assets = Asset::orderBy('id','asc')->get(); + $total_assets = Asset::orderBy('id', 'asc')->get(); $bar = $this->output->createProgressBar(count($total_assets)); - try { + try { Artisan::call('backup:run'); } catch (\Exception $e) { $output['error'][] = $e; } foreach ($total_assets as $asset) { - $start_tag++; $output['info'][] = 'Asset tag:'.$asset->asset_tag; $asset->asset_tag = $settings->auto_increment_prefix.$settings->auto_increment_prefix.$start_tag; @@ -81,24 +77,21 @@ class RegenerateAssetTags extends Command $bar->finish(); $this->info("\n"); - - if (($this->option('output')=='all') || ($this->option('output')=='info')) { + if (($this->option('output') == 'all') || ($this->option('output') == 'info')) { foreach ($output['info'] as $key => $output_text) { $this->info($output_text); } } - if (($this->option('output')=='all') || ($this->option('output')=='warn')) { + if (($this->option('output') == 'all') || ($this->option('output') == 'warn')) { foreach ($output['warn'] as $key => $output_text) { $this->warn($output_text); } } - if (($this->option('output')=='all') || ($this->option('output')=='error')) { + if (($this->option('output') == 'all') || ($this->option('output') == 'error')) { foreach ($output['error'] as $key => $output_text) { $this->error($output_text); } } } - - } } diff --git a/app/Console/Commands/RestoreDeletedUsers.php b/app/Console/Commands/RestoreDeletedUsers.php index c17c18984a..4bf26a544d 100644 --- a/app/Console/Commands/RestoreDeletedUsers.php +++ b/app/Console/Commands/RestoreDeletedUsers.php @@ -43,16 +43,15 @@ class RestoreDeletedUsers extends Command */ public function handle() { - $start_date = $this->option('start_date'); $end_date = $this->option('end_date'); $asset_totals = 0; $license_totals = 0; $user_count = 0; - - if (($start_date=='') || ($end_date=='')) { + if (($start_date == '') || ($end_date == '')) { $this->info('ERROR: All fields are required.'); + return false; } @@ -63,15 +62,15 @@ class RestoreDeletedUsers extends Command foreach ($users as $user) { $user_count++; - $user_logs = Actionlog::where('target_id', $user->id)->where('target_type',User::class) - ->where('action_type','checkout')->with('item')->get(); + $user_logs = Actionlog::where('target_id', $user->id)->where('target_type', User::class) + ->where('action_type', 'checkout')->with('item')->get(); - $this->info($user_count.'. '.$user->username.' ('.$user->id.') was deleted at '.$user->deleted_at. ' and has '.$user_logs->count().' checkouts associated.'); + $this->info($user_count.'. '.$user->username.' ('.$user->id.') was deleted at '.$user->deleted_at.' and has '.$user_logs->count().' checkouts associated.'); foreach ($user_logs as $user_log) { $this->info(' * '.$user_log->item_type.': '.$user_log->item->name.' - item_id: '.$user_log->item_id); - if ($user_log->item_type==Asset::class) { + if ($user_log->item_type == Asset::class) { $asset_totals++; DB::table('assets') @@ -79,11 +78,10 @@ class RestoreDeletedUsers extends Command ->update(['assigned_to' => $user->id, 'assigned_type'=> User::class]); $this->info(' ** Asset '.$user_log->item->id.' ('.$user_log->item->asset_tag.') restored to user '.$user->id.''); - - } elseif ($user_log->item_type==License::class) { + } elseif ($user_log->item_type == License::class) { $license_totals++; - $avail_seat = DB::table('license_seats')->where('license_id','=',$user_log->item->id) + $avail_seat = DB::table('license_seats')->where('license_id', '=', $user_log->item->id) ->whereNull('assigned_to')->whereNull('asset_id')->whereBetween('updated_at', [$start_date, $end_date])->first(); if ($avail_seat) { $this->info(' ** Allocating seat '.$avail_seat->id.' for this License'); @@ -91,27 +89,17 @@ class RestoreDeletedUsers extends Command DB::table('license_seats') ->where('id', $avail_seat->id) ->update(['assigned_to' => $user->id]); - } else { $this->warn('ERROR: No available seats for '.$user_log->item->name); } - } - } $this->warn('Restoring user '.$user->username.'!'); $user->restore(); - - } $this->info($asset_totals.' assets affected'); $this->info($license_totals.' licenses affected'); - - - } - - } diff --git a/app/Console/Commands/RestoreFromBackup.php b/app/Console/Commands/RestoreFromBackup.php index 06c99ec08c..8f8114229e 100644 --- a/app/Console/Commands/RestoreFromBackup.php +++ b/app/Console/Commands/RestoreFromBackup.php @@ -3,7 +3,6 @@ namespace App\Console\Commands; use Illuminate\Console\Command; - use ZipArchive; class RestoreFromBackup extends Command @@ -43,20 +42,20 @@ class RestoreFromBackup extends Command public function handle() { $dir = getcwd(); - print "Current working directory is: $dir\n"; + echo "Current working directory is: $dir\n"; // $filename = $this->argument('filename'); - if (!$filename) { - return $this->error("Missing required filename"); + if (! $filename) { + return $this->error('Missing required filename'); } - if (!$this->option('force') && !$this->confirm('Are you sure you wish to restore from the given backup file? This can lead to MASSIVE DATA LOSS!')) { - return $this->error("Data loss not confirmed"); + if (! $this->option('force') && ! $this->confirm('Are you sure you wish to restore from the given backup file? This can lead to MASSIVE DATA LOSS!')) { + return $this->error('Data loss not confirmed'); } if (config('database.default') != 'mysql') { - return $this->error("DB_CONNECTION must be MySQL in order to perform a restore. Detected: ".config('database.default')); + return $this->error('DB_CONNECTION must be MySQL in order to perform a restore. Detected: '.config('database.default')); } $za = new ZipArchive(); @@ -64,21 +63,20 @@ class RestoreFromBackup extends Command $errcode = $za->open($filename/* , ZipArchive::RDONLY */); // that constant only exists in PHP 7.4 and higher if ($errcode !== true) { $errors = [ - ZipArchive::ER_EXISTS => "File already exists.", - ZipArchive::ER_INCONS => "Zip archive inconsistent.", - ZipArchive::ER_INVAL => "Invalid argument.", - ZipArchive::ER_MEMORY => "Malloc failure.", - ZipArchive::ER_NOENT => "No such file.", - ZipArchive::ER_NOZIP => "Not a zip archive.", + ZipArchive::ER_EXISTS => 'File already exists.', + ZipArchive::ER_INCONS => 'Zip archive inconsistent.', + ZipArchive::ER_INVAL => 'Invalid argument.', + ZipArchive::ER_MEMORY => 'Malloc failure.', + ZipArchive::ER_NOENT => 'No such file.', + ZipArchive::ER_NOZIP => 'Not a zip archive.', ZipArchive::ER_OPEN => "Can't open file.", - ZipArchive::ER_READ => "Read error.", - ZipArchive::ER_SEEK => "Seek error." + ZipArchive::ER_READ => 'Read error.', + ZipArchive::ER_SEEK => 'Seek error.', ]; - return $this->error("Could not access file: ".$filename." - ".array_key_exists($errcode,$errors) ? $errors[$errcode] : " Unknown reason: $errcode"); + return $this->error('Could not access file: '.$filename.' - '.array_key_exists($errcode, $errors) ? $errors[$errcode] : " Unknown reason: $errcode"); } - $private_dirs = [ 'storage/private_uploads/assets', // these are asset _files_, not the pictures. 'storage/private_uploads/audits', @@ -86,11 +84,11 @@ class RestoreFromBackup extends Command 'storage/private_uploads/assetmodels', 'storage/private_uploads/users', 'storage/private_uploads/licenses', - 'storage/private_uploads/signatures' + 'storage/private_uploads/signatures', ]; $private_files = [ 'storage/oauth-private.key', - 'storage/oauth-public.key' + 'storage/oauth-public.key', ]; $public_dirs = [ 'public/uploads/companies', @@ -108,16 +106,16 @@ class RestoreFromBackup extends Command 'public/uploads/models', 'public/uploads/categories', 'public/uploads/avatars', - 'public/uploads/manufacturers' + 'public/uploads/manufacturers', ]; - + $public_files = [ 'public/uploads/logo.*', 'public/uploads/setting-email_logo*', 'public/uploads/setting-label_logo*', 'public/uploads/setting-logo*', 'public/uploads/favicon.*', - 'public/uploads/favicon-uploaded.*' + 'public/uploads/favicon-uploaded.*', ]; $all_files = $private_dirs + $public_dirs; @@ -127,64 +125,64 @@ class RestoreFromBackup extends Command $interesting_files = []; $boring_files = []; - - for ($i=0; $i<$za->numFiles;$i++) { + + for ($i = 0; $i < $za->numFiles; $i++) { $stat_results = $za->statIndex($i); // echo "index: $i\n"; // print_r($stat_results); - + $raw_path = $stat_results['name']; - if(strpos($raw_path,'\\')!==false) { //found a backslash, swap it to forward-slash - $raw_path = strtr($raw_path,'\\','/'); + if (strpos($raw_path, '\\') !== false) { //found a backslash, swap it to forward-slash + $raw_path = strtr($raw_path, '\\', '/'); //print "Translating file: ".$stat_results['name']." to: ".$raw_path."\n"; } - + // skip macOS resource fork files (?!?!?!) - if(strpos($raw_path,"__MACOSX")!==false && strpos($raw_path,"._") !== false) { + if (strpos($raw_path, '__MACOSX') !== false && strpos($raw_path, '._') !== false) { //print "SKIPPING macOS Resource fork file: $raw_path\n"; $boring_files[] = $raw_path; continue; } - if(@pathinfo($raw_path)['extension'] == "sql") { - print "Found a sql file!\n"; + if (@pathinfo($raw_path)['extension'] == 'sql') { + echo "Found a sql file!\n"; $sqlfiles[] = $raw_path; $sqlfile_indices[] = $i; continue; } - - foreach(array_merge($private_dirs,$public_dirs) as $dir) { - $last_pos = strrpos($raw_path,$dir.'/'); - if($last_pos !== false ) { + + foreach (array_merge($private_dirs, $public_dirs) as $dir) { + $last_pos = strrpos($raw_path, $dir.'/'); + if ($last_pos !== false) { //print("INTERESTING - last_pos is $last_pos when searching $raw_path for $dir - last_pos+strlen(\$dir) is: ".($last_pos+strlen($dir))." and strlen(\$rawpath) is: ".strlen($raw_path)."\n"); //print("We would copy $raw_path to $dir.\n"); //FIXME append to a path? $interesting_files[$raw_path] = ['dest' =>$dir, 'index' => $i]; continue 2; - if($last_pos + strlen($dir) +1 == strlen($raw_path)) { + if ($last_pos + strlen($dir) + 1 == strlen($raw_path)) { // we don't care about that; we just want files with the appropriate prefix //print("FOUND THE EXACT DIRECTORY: $dir AT: $raw_path!!!\n"); } } } - $good_extensions = ["png","gif","jpg","svg","jpeg","doc","docx","pdf","txt", - "zip","rar","xls","xlsx","lic","xml","rtf", "webp","key","ico"]; - foreach(array_merge($private_files, $public_files) as $file) { - $has_wildcard = (strpos($file,"*") !== false); - if($has_wildcard) { - $file = substr($file,0,-1); //trim last character (which should be the wildcard) + $good_extensions = ['png', 'gif', 'jpg', 'svg', 'jpeg', 'doc', 'docx', 'pdf', 'txt', + 'zip', 'rar', 'xls', 'xlsx', 'lic', 'xml', 'rtf', 'webp', 'key', 'ico', ]; + foreach (array_merge($private_files, $public_files) as $file) { + $has_wildcard = (strpos($file, '*') !== false); + if ($has_wildcard) { + $file = substr($file, 0, -1); //trim last character (which should be the wildcard) } - $last_pos = strrpos($raw_path,$file); // no trailing slash! - if($last_pos !== false ) { + $last_pos = strrpos($raw_path, $file); // no trailing slash! + if ($last_pos !== false) { $extension = strtolower(pathinfo($raw_path, PATHINFO_EXTENSION)); - if(!in_array($extension, $good_extensions)) { - $this->warn("Potentially unsafe file ".$raw_path." is being skipped"); + if (! in_array($extension, $good_extensions)) { + $this->warn('Potentially unsafe file '.$raw_path.' is being skipped'); $boring_files[] = $raw_path; continue 2; } //print("INTERESTING - last_pos is $last_pos when searching $raw_path for $file - last_pos+strlen(\$file) is: ".($last_pos+strlen($file))." and strlen(\$rawpath) is: ".strlen($raw_path)."\n"); //no wildcards found in $file, process 'normally' - if($last_pos + strlen($file) == strlen($raw_path) || $has_wildcard) { //again, no trailing slash. or this is a wildcard and we just take it. + if ($last_pos + strlen($file) == strlen($raw_path) || $has_wildcard) { //again, no trailing slash. or this is a wildcard and we just take it. // print("FOUND THE EXACT FILE: $file AT: $raw_path!!!\n"); //we *do* care about this, though. - $interesting_files[$raw_path] = ['dest' => dirname($file),'index' => $i]; + $interesting_files[$raw_path] = ['dest' => dirname($file), 'index' => $i]; continue 2; } } @@ -194,11 +192,11 @@ class RestoreFromBackup extends Command // print_r($interesting_files);exit(-1); - if( count($sqlfiles) != 1) { - return $this->error("There should be exactly *one* sql backup file found, found: ".( count($sqlfiles) == 0 ? "None" : implode(", ",$sqlfiles))); + if (count($sqlfiles) != 1) { + return $this->error('There should be exactly *one* sql backup file found, found: '.(count($sqlfiles) == 0 ? 'None' : implode(', ', $sqlfiles))); } - if( strpos($sqlfiles[0], "db-dumps") === false ) { + if (strpos($sqlfiles[0], 'db-dumps') === false) { //return $this->error("SQL backup file is missing 'db-dumps' component of full pathname: ".$sqlfiles[0]); //older Snipe-IT installs don't have the db-dumps subdirectory component } @@ -207,14 +205,14 @@ class RestoreFromBackup extends Command $pipes = []; $env_vars = getenv(); - $env_vars['MYSQL_PWD'] = config("database.connections.mysql.password"); - $proc_results = proc_open("mysql -h ".escapeshellarg(config('database.connections.mysql.host'))." -u ".escapeshellarg(config('database.connections.mysql.username'))." ".escapeshellarg(config('database.connections.mysql.database')), // yanked -p since we pass via ENV - [0 => ['pipe','r'],1 => ['pipe','w'],2 => ['pipe','w']], + $env_vars['MYSQL_PWD'] = config('database.connections.mysql.password'); + $proc_results = proc_open('mysql -h '.escapeshellarg(config('database.connections.mysql.host')).' -u '.escapeshellarg(config('database.connections.mysql.username')).' '.escapeshellarg(config('database.connections.mysql.database')), // yanked -p since we pass via ENV + [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, null, $env_vars); // this is not super-duper awesome-secure, but definitely more secure than showing it on the CLI, or dropping temporary files with passwords in them. - if($proc_results === false) { - return $this->error("Unable to invoke mysql via CLI"); + if ($proc_results === false) { + return $this->error('Unable to invoke mysql via CLI'); } // $this->info("Stdout says? ".fgets($pipes[1])); //FIXME: I think we might need to set non-blocking mode to use this properly? @@ -232,17 +230,19 @@ class RestoreFromBackup extends Command $this->info($stdout); $stderr = fgets($pipes[2]); $this->info($stderr); + return false; } - while(($buffer = fgets($sql_contents)) !== false ) { + while (($buffer = fgets($sql_contents)) !== false) { //$this->info("Buffer is: '$buffer'"); - $bytes_written = fwrite($pipes[0],$buffer); - if($bytes_written === false) { + $bytes_written = fwrite($pipes[0], $buffer); + if ($bytes_written === false) { $stdout = fgets($pipes[1]); $this->info($stdout); $stderr = fgets($pipes[2]); $this->info($stderr); + return false; } } @@ -257,41 +257,40 @@ class RestoreFromBackup extends Command //wait, have to do fclose() on all pipes first? $close_results = proc_close($proc_results); - if($close_results != 0) { - return $this->error("There may have been a problem with the database import: Error number ".$close_results); + if ($close_results != 0) { + return $this->error('There may have been a problem with the database import: Error number '.$close_results); } - + //and now copy the files over too (right?) //FIXME - we don't prune the filesystem space yet!!!! - if($this->option('no-progress')) { + if ($this->option('no-progress')) { $bar = null; } else { $bar = $this->output->createProgressBar(count($interesting_files)); } - foreach($interesting_files AS $pretty_file_name => $file_details) { + foreach ($interesting_files as $pretty_file_name => $file_details) { $ugly_file_name = $za->statIndex($file_details['index'])['name']; $fp = $za->getStream($ugly_file_name); //$this->info("Weird problem, here are file details? ".print_r($file_details,true)); - $migrated_file = fopen($file_details['dest']."/".basename($pretty_file_name),"w"); - while(($buffer = fgets($fp))!== false) { - fwrite($migrated_file,$buffer); + $migrated_file = fopen($file_details['dest'].'/'.basename($pretty_file_name), 'w'); + while (($buffer = fgets($fp)) !== false) { + fwrite($migrated_file, $buffer); } fclose($migrated_file); fclose($fp); //$this->info("Wrote $ugly_file_name to $pretty_file_name"); - if($bar) { + if ($bar) { $bar->advance(); } } - if($bar) { + if ($bar) { $bar->finish(); - $this->line(""); + $this->line(''); } else { - $this->info(count($interesting_files)." files were succesfully transferred"); + $this->info(count($interesting_files).' files were succesfully transferred'); } - foreach($boring_files as $boring_file) { - $this->warn($boring_file." was skipped."); + foreach ($boring_files as $boring_file) { + $this->warn($boring_file.' was skipped.'); } - } } diff --git a/app/Console/Commands/RotateAppKey.php b/app/Console/Commands/RotateAppKey.php index 51c43d4ec9..08e528e4a4 100644 --- a/app/Console/Commands/RotateAppKey.php +++ b/app/Console/Commands/RotateAppKey.php @@ -2,12 +2,12 @@ namespace App\Console\Commands; -use Illuminate\Console\Command; -use Artisan; -use App\Models\CustomField; use App\Models\Asset; +use App\Models\CustomField; use App\Models\Setting; -use \Illuminate\Encryption\Encrypter; +use Artisan; +use Illuminate\Console\Command; +use Illuminate\Encryption\Encrypter; class RotateAppKey extends Command { @@ -42,9 +42,7 @@ class RotateAppKey extends Command */ public function handle() { - if ($this->confirm("\n****************************************************\nTHIS WILL MODIFY YOUR APP_KEY AND DE-CRYPT YOUR ENCRYPTED CUSTOM FIELDS AND \nRE-ENCRYPT THEM WITH A NEWLY GENERATED KEY. \n\nThere is NO undo. \n\nMake SURE you have a database backup and a backup of your .env generated BEFORE running this command. \n\nIf you do not save the newly generated APP_KEY to your .env in this process, \nyour encrypted data will no longer be decryptable. \n\nAre you SURE you wish to continue, and have confirmed you have a database backup and an .env backup? ")) { - - + if ($this->confirm("\n****************************************************\nTHIS WILL MODIFY YOUR APP_KEY AND DE-CRYPT YOUR ENCRYPTED CUSTOM FIELDS AND \nRE-ENCRYPT THEM WITH A NEWLY GENERATED KEY. \n\nThere is NO undo. \n\nMake SURE you have a database backup and a backup of your .env generated BEFORE running this command. \n\nIf you do not save the newly generated APP_KEY to your .env in this process, \nyour encrypted data will no longer be decryptable. \n\nAre you SURE you wish to continue, and have confirmed you have a database backup and an .env backup? ")) { // Get the existing app_key and ciphers // We put them in a variable since we clear the cache partway through here. @@ -73,33 +71,26 @@ class RotateAppKey extends Command $fields = CustomField::where('field_encrypted', '1')->get(); - foreach ($fields as $field) { - $assets = Asset::whereNotNull($field->db_column)->get(); foreach ($assets as $asset) { - $asset->{$field->db_column} = $oldEncrypter->decrypt($asset->{$field->db_column}); - $this->line('DECRYPTED: '. $field->db_column); + $this->line('DECRYPTED: '.$field->db_column); $asset->{$field->db_column} = $newEncrypter->encrypt($asset->{$field->db_column}); $this->line('ENCRYPTED: '.$field->db_column); $asset->save(); - } - } // Handle the LDAP password if one is provided $setting = Setting::first(); - if ($setting->ldap_pword!='') { - $setting->ldap_pword = $oldEncrypter->decrypt($setting->ldap_pword); - $setting->ldap_pword = $newEncrypter->encrypt($setting->ldap_pword); + if ($setting->ldap_pword != '') { + $setting->ldap_pword = $oldEncrypter->decrypt($setting->ldap_pword); + $setting->ldap_pword = $newEncrypter->encrypt($setting->ldap_pword); $setting->save(); $this->warn('LDAP password has been re-encrypted.'); } - - } else { $this->info('This operation has been canceled. No changes have been made.'); } @@ -113,7 +104,6 @@ class RotateAppKey extends Command */ protected function writeNewEnvironmentFileWith($key) { - file_put_contents($this->laravel->environmentFilePath(), preg_replace( $this->keyReplacementPattern(), 'APP_KEY='.$key, @@ -129,7 +119,7 @@ class RotateAppKey extends Command protected function keyReplacementPattern() { $escaped = preg_quote('='.$this->laravel['config']['app.key'], '/'); + return "/^APP_KEY{$escaped}/m"; } - } diff --git a/app/Console/Commands/SendCurrentInventoryToUsers.php b/app/Console/Commands/SendCurrentInventoryToUsers.php index 9f1fe0f761..74acc9cc0f 100644 --- a/app/Console/Commands/SendCurrentInventoryToUsers.php +++ b/app/Console/Commands/SendCurrentInventoryToUsers.php @@ -39,22 +39,16 @@ class SendCurrentInventoryToUsers extends Command */ public function handle() { - $users = User::whereNull('deleted_at')->whereNotNull('email')->with('assets', 'accessories', 'licenses')->get(); $count = 0; foreach ($users as $user) { - - if (($user->assets->count() > 0) || ($user->accessories->count() > 0) || ($user->licenses->count() > 0)) - { + if (($user->assets->count() > 0) || ($user->accessories->count() > 0) || ($user->licenses->count() > 0)) { $count++; $user->notify((new CurrentInventory($user))); } - } $this->info($count.' users notified.'); - - } } diff --git a/app/Console/Commands/SendExpectedCheckinAlerts.php b/app/Console/Commands/SendExpectedCheckinAlerts.php index b0cbb1f518..83a93a8a6b 100644 --- a/app/Console/Commands/SendExpectedCheckinAlerts.php +++ b/app/Console/Commands/SendExpectedCheckinAlerts.php @@ -3,12 +3,12 @@ namespace App\Console\Commands; use App\Models\Asset; +use App\Models\Recipients\AlertRecipient; use App\Models\Setting; use App\Notifications\ExpectedCheckinAdminNotification; use App\Notifications\ExpectedCheckinNotification; use Carbon\Carbon; use Illuminate\Console\Command; -use App\Models\Recipients\AlertRecipient; class SendExpectedCheckinAlerts extends Command { @@ -41,12 +41,12 @@ class SendExpectedCheckinAlerts extends Command */ public function handle() { - $settings = Setting::getSettings(); + $settings = Setting::getSettings(); $whenNotify = Carbon::now()->addDays(7); - $assets = Asset::with('assignedTo')->whereNotNull('assigned_to')->whereNotNull('expected_checkin')->where('expected_checkin', '<=', $whenNotify)->get(); + $assets = Asset::with('assignedTo')->whereNotNull('assigned_to')->whereNotNull('expected_checkin')->where('expected_checkin', '<=', $whenNotify)->get(); - $this->info($whenNotify . ' is deadline'); - $this->info($assets->count() . ' assets'); + $this->info($whenNotify.' is deadline'); + $this->info($assets->count().' assets'); foreach ($assets as $asset) { if ($asset->assigned && $asset->checkedOutToUser()) { diff --git a/app/Console/Commands/SendExpirationAlerts.php b/app/Console/Commands/SendExpirationAlerts.php index f88c345669..025ba2ce23 100644 --- a/app/Console/Commands/SendExpirationAlerts.php +++ b/app/Console/Commands/SendExpirationAlerts.php @@ -41,7 +41,7 @@ class SendExpirationAlerts extends Command */ public function handle() { - $settings = Setting::getSettings(); + $settings = Setting::getSettings(); $threshold = $settings->alert_interval; if (($settings->alert_email != '') && ($settings->alerts_enabled == 1)) { diff --git a/app/Console/Commands/SendUpcomingAuditReport.php b/app/Console/Commands/SendUpcomingAuditReport.php index bac5a21698..e9cba106c6 100644 --- a/app/Console/Commands/SendUpcomingAuditReport.php +++ b/app/Console/Commands/SendUpcomingAuditReport.php @@ -4,13 +4,13 @@ namespace App\Console\Commands; use App\Models\Asset; use App\Models\License; +use App\Models\Recipients; use App\Models\Setting; use App\Notifications\ExpiringAssetsNotification; -use App\Models\Recipients; -use DB; -use Illuminate\Console\Command; use App\Notifications\SendUpcomingAuditNotification; use Carbon\Carbon; +use DB; +use Illuminate\Console\Command; class SendUpcomingAuditReport extends Command { @@ -54,7 +54,6 @@ class SendUpcomingAuditReport extends Command return new \App\Models\Recipients\AlertRecipient($item); }); - // Assets due for auditing $assets = Asset::whereNotNull('next_audit_date') @@ -62,7 +61,6 @@ class SendUpcomingAuditReport extends Command ->orderBy('last_audit_date', 'asc')->get(); if ($assets->count() > 0) { - $this->info(trans_choice('mail.upcoming-audits', $assets->count(), ['count' => $assets->count(), 'threshold' => $settings->audit_warning_days])); \Notification::send($recipients, new SendUpcomingAuditNotification($assets, $settings->audit_warning_days)); @@ -70,14 +68,11 @@ class SendUpcomingAuditReport extends Command } else { $this->info('No assets to be audited. No report sent.'); } - - - - } elseif ($settings->alert_email=='') { + } elseif ($settings->alert_email == '') { $this->error('Could not send email. No alert email configured in settings'); - } elseif (!$settings->audit_warning_days) { + } elseif (! $settings->audit_warning_days) { $this->error('No audit warning days set in Admin Notifications. No mail will be sent.'); - } elseif ($settings->alerts_enabled!=1) { + } elseif ($settings->alerts_enabled != 1) { $this->info('Alerts are disabled in the settings. No mail will be sent'); } else { $this->error('Something went wrong. :( '); @@ -85,7 +80,5 @@ class SendUpcomingAuditReport extends Command $this->error('Admin Audit Warning Setting: '.$settings->audit_warning_days); $this->error('Admin Alerts Emnabled: '.$settings->alerts_enabled); } - - } } diff --git a/app/Console/Commands/SyncAssetCounters.php b/app/Console/Commands/SyncAssetCounters.php index 33104818e1..ab88168218 100644 --- a/app/Console/Commands/SyncAssetCounters.php +++ b/app/Console/Commands/SyncAssetCounters.php @@ -45,14 +45,14 @@ class SyncAssetCounters extends Command if ($assets) { if ($assets->count() > 0) { $bar = $this->output->createProgressBar($assets->count()); - + foreach ($assets as $asset) { $asset->checkin_counter = (int) $asset->checkins_count; $asset->checkout_counter = (int) $asset->checkouts_count; $asset->requests_counter = (int) $asset->user_requests_count; $asset->unsetEventDispatcher(); $asset->save(); - $output['info'][] = 'Asset: ' . $asset->id . ' has ' . $asset->checkin_counter . ' checkins, ' . $asset->checkout_counter . ' checkouts, and ' . $asset->requests_counter . ' requests'; + $output['info'][] = 'Asset: '.$asset->id.' has '.$asset->checkin_counter.' checkins, '.$asset->checkout_counter.' checkouts, and '.$asset->requests_counter.' requests'; $bar->advance(); } $bar->finish(); @@ -62,15 +62,10 @@ class SyncAssetCounters extends Command } $time_elapsed_secs = microtime(true) - $start; - $this->info('Sync executed in ' . $time_elapsed_secs . ' seconds'); - + $this->info('Sync executed in '.$time_elapsed_secs.' seconds'); } else { $this->info('No assets to sync'); } - } - - - } } diff --git a/app/Console/Commands/SyncAssetLocations.php b/app/Console/Commands/SyncAssetLocations.php index b5d3cd33e0..f510176bce 100644 --- a/app/Console/Commands/SyncAssetLocations.php +++ b/app/Console/Commands/SyncAssetLocations.php @@ -38,7 +38,6 @@ class SyncAssetLocations extends Command */ public function handle() { - $output['info'] = []; $output['warn'] = []; $output['error'] = []; @@ -51,96 +50,89 @@ class SyncAssetLocations extends Command $output['info'][] = 'There are '.$rtd_assets->count().' unassigned assets.'; foreach ($rtd_assets as $rtd_asset) { - $output['info'][] = 'Setting Unassigned Asset ' . $rtd_asset->id . ' ('.$rtd_asset->asset_tag.') to location: ' . $rtd_asset->rtd_location_id . " because their default location is: " . $rtd_asset->rtd_location_id; - $rtd_asset->location_id=$rtd_asset->rtd_location_id; + $output['info'][] = 'Setting Unassigned Asset '.$rtd_asset->id.' ('.$rtd_asset->asset_tag.') to location: '.$rtd_asset->rtd_location_id.' because their default location is: '.$rtd_asset->rtd_location_id; + $rtd_asset->location_id = $rtd_asset->rtd_location_id; $rtd_asset->unsetEventDispatcher(); $rtd_asset->save(); $bar->advance(); } - $assigned_user_assets = Asset::where('assigned_type','App\Models\User')->whereNotNull('assigned_to')->whereNull('deleted_at')->get(); + $assigned_user_assets = Asset::where('assigned_type', \App\Models\User::class)->whereNotNull('assigned_to')->whereNull('deleted_at')->get(); $output['info'][] = 'There are '.$assigned_user_assets->count().' assets checked out to users.'; foreach ($assigned_user_assets as $assigned_user_asset) { if (($assigned_user_asset->assignedTo) && ($assigned_user_asset->assignedTo->userLoc)) { $new_location = $assigned_user_asset->assignedTo->userLoc->id; - $output['info'][] ='Setting User Asset ' . $assigned_user_asset->id . ' ('.$assigned_user_asset->asset_tag.') to ' . $assigned_user_asset->assignedTo->userLoc->name . ' which is id: ' . $new_location; + $output['info'][] = 'Setting User Asset '.$assigned_user_asset->id.' ('.$assigned_user_asset->asset_tag.') to '.$assigned_user_asset->assignedTo->userLoc->name.' which is id: '.$new_location; } else { - $output['warn'][] ='Asset ' . $assigned_user_asset->id . ' ('.$assigned_user_asset->asset_tag.') still has no location! '; + $output['warn'][] = 'Asset '.$assigned_user_asset->id.' ('.$assigned_user_asset->asset_tag.') still has no location! '; $new_location = $assigned_user_asset->rtd_location_id; } - $assigned_user_asset->location_id=$new_location; + $assigned_user_asset->location_id = $new_location; $assigned_user_asset->unsetEventDispatcher(); $assigned_user_asset->save(); $bar->advance(); - } - $assigned_location_assets = Asset::where('assigned_type','App\Models\Location') + $assigned_location_assets = Asset::where('assigned_type', \App\Models\Location::class) ->whereNotNull('assigned_to')->whereNull('deleted_at')->get(); $output['info'][] = 'There are '.$assigned_location_assets->count().' assets checked out to locations.'; foreach ($assigned_location_assets as $assigned_location_asset) { if ($assigned_location_asset->assignedTo) { $assigned_location_asset->location_id = $assigned_location_asset->assignedTo->id; - $output['info'][] ='Setting Location Assigned asset ' . $assigned_location_asset->id . ' ('.$assigned_location_asset->asset_tag.') that is checked out to '.$assigned_location_asset->assignedTo->name.' (#'.$assigned_location_asset->assignedTo->id.') to location: ' . $assigned_location_asset->assetLoc()->id; + $output['info'][] = 'Setting Location Assigned asset '.$assigned_location_asset->id.' ('.$assigned_location_asset->asset_tag.') that is checked out to '.$assigned_location_asset->assignedTo->name.' (#'.$assigned_location_asset->assignedTo->id.') to location: '.$assigned_location_asset->assetLoc()->id; $assigned_location_asset->unsetEventDispatcher(); $assigned_location_asset->save(); } else { - $output['warn'][] ='Asset ' . $assigned_location_asset->id . ' ('.$assigned_location_asset->asset_tag.') did not return a valid associated location - perhaps it was deleted?'; + $output['warn'][] = 'Asset '.$assigned_location_asset->id.' ('.$assigned_location_asset->asset_tag.') did not return a valid associated location - perhaps it was deleted?'; } $bar->advance(); - } - // Assigned to assets - $assigned_asset_assets = Asset::where('assigned_type','App\Models\Asset') + $assigned_asset_assets = Asset::where('assigned_type', \App\Models\Asset::class) ->whereNotNull('assigned_to')->whereNull('deleted_at')->get(); - $output['info'][] ='Asset-assigned assets: '.$assigned_asset_assets->count(); + $output['info'][] = 'Asset-assigned assets: '.$assigned_asset_assets->count(); - foreach ($assigned_asset_assets as $assigned_asset_asset) { + foreach ($assigned_asset_assets as $assigned_asset_asset) { // Check to make sure there aren't any invalid relationships - if ($assigned_asset_asset->assetLoc()) { - $assigned_asset_asset->location_id = $assigned_asset_asset->assetLoc()->id; - $output['info'][] ='Setting Asset Assigned asset ' . $assigned_asset_asset->assetLoc()->id. ' ('.$assigned_asset_asset->asset_tag.') location to: ' . $assigned_asset_asset->assetLoc()->id; - $assigned_asset_asset->unsetEventDispatcher(); - $assigned_asset_asset->save(); - } else { - $output['warn'][] ='Asset Assigned asset ' . $assigned_asset_asset->id. ' ('.$assigned_asset_asset->asset_tag.') does not seem to have a valid location'; - } - - $bar->advance(); - + if ($assigned_asset_asset->assetLoc()) { + $assigned_asset_asset->location_id = $assigned_asset_asset->assetLoc()->id; + $output['info'][] = 'Setting Asset Assigned asset '.$assigned_asset_asset->assetLoc()->id.' ('.$assigned_asset_asset->asset_tag.') location to: '.$assigned_asset_asset->assetLoc()->id; + $assigned_asset_asset->unsetEventDispatcher(); + $assigned_asset_asset->save(); + } else { + $output['warn'][] = 'Asset Assigned asset '.$assigned_asset_asset->id.' ('.$assigned_asset_asset->asset_tag.') does not seem to have a valid location'; } - $unlocated_assets = Asset::whereNull("location_id")->whereNull('deleted_at')->get(); - $output['info'][] ='Assets still without a location: '.$unlocated_assets->count(); - foreach($unlocated_assets as $unlocated_asset) { - $output['warn'][] ='Asset: '.$unlocated_asset->id.' still has no location. '; + $bar->advance(); + } + + $unlocated_assets = Asset::whereNull('location_id')->whereNull('deleted_at')->get(); + $output['info'][] = 'Assets still without a location: '.$unlocated_assets->count(); + foreach ($unlocated_assets as $unlocated_asset) { + $output['warn'][] = 'Asset: '.$unlocated_asset->id.' still has no location. '; $bar->advance(); } $bar->finish(); $this->info("\n"); - - if (($this->option('output')=='all') || ($this->option('output')=='info')) { + if (($this->option('output') == 'all') || ($this->option('output') == 'info')) { foreach ($output['info'] as $key => $output_text) { $this->info($output_text); } } - if (($this->option('output')=='all') || ($this->option('output')=='warn')) { + if (($this->option('output') == 'all') || ($this->option('output') == 'warn')) { foreach ($output['warn'] as $key => $output_text) { $this->warn($output_text); } } - if (($this->option('output')=='all') || ($this->option('output')=='error')) { + if (($this->option('output') == 'all') || ($this->option('output') == 'error')) { foreach ($output['error'] as $key => $output_text) { $this->error($output_text); } } - - } } diff --git a/app/Console/Commands/SystemBackup.php b/app/Console/Commands/SystemBackup.php index 2e4965c28b..b7ca526052 100644 --- a/app/Console/Commands/SystemBackup.php +++ b/app/Console/Commands/SystemBackup.php @@ -6,7 +6,6 @@ use Illuminate\Console\Command; class SystemBackup extends Command { - /** * The console command name. * @@ -40,6 +39,5 @@ class SystemBackup extends Command { // $this->call('backup:run'); - } } diff --git a/app/Console/Commands/Version.php b/app/Console/Commands/Version.php index e73b6aae5e..0a10f4f541 100644 --- a/app/Console/Commands/Version.php +++ b/app/Console/Commands/Version.php @@ -37,7 +37,6 @@ class Version extends Command */ public function handle() { - $use_branch = $this->option('branch'); $use_type = $this->option('type'); $git_branch = trim(shell_exec('git rev-parse --abbrev-ref HEAD')); @@ -54,72 +53,66 @@ class Version extends Command $this->line('Type is: '.$use_type); $this->line('Current version is: '.$full_hash_version); - if (count($version)==3) { + if (count($version) == 3) { $this->line('This does not look like an alpha/beta release.'); } else { - if (array_key_exists('3',$version)) { + if (array_key_exists('3', $version)) { $this->line('The current version looks like a beta release.'); $prerelease_version = $version[1]; $hash_version = $version[3]; } } - $app_version_raw = explode('.', $app_version); $maj = str_replace('v', '', $app_version_raw[0]); $min = $app_version_raw[1]; $patch = ''; - - // This is a major release that might not have a third .0 if (array_key_exists(2, $app_version_raw)) { $patch = $app_version_raw[2]; } - if ($use_type=='major') { - $app_version = "v".($maj + 1).".$min.$patch"; - } elseif ($use_type=='minor') { - $app_version = "v"."$maj.".($min + 1).".$patch"; - } elseif ($use_type=='pre') { - $pre_raw = str_replace('beta','', $prerelease_version); - $pre_raw = str_replace('alpha','', $pre_raw); - $pre_raw = str_ireplace('rc','', $pre_raw); + if ($use_type == 'major') { + $app_version = 'v'.($maj + 1).".$min.$patch"; + } elseif ($use_type == 'minor') { + $app_version = 'v'."$maj.".($min + 1).".$patch"; + } elseif ($use_type == 'pre') { + $pre_raw = str_replace('beta', '', $prerelease_version); + $pre_raw = str_replace('alpha', '', $pre_raw); + $pre_raw = str_ireplace('rc', '', $pre_raw); $pre_raw = $pre_raw++; - $this->line('Setting the pre-release to '. $prerelease_version.'-'.$pre_raw); - $app_version = "v"."$maj.".($min + 1).".$patch"; - } elseif ($use_type=='patch') { - $app_version = "v" . "$maj.$min." . ($patch + 1); + $this->line('Setting the pre-release to '.$prerelease_version.'-'.$pre_raw); + $app_version = 'v'."$maj.".($min + 1).".$patch"; + } elseif ($use_type == 'patch') { + $app_version = 'v'."$maj.$min.".($patch + 1); // If nothing is passed, leave the version as it is, just increment the build } else { - $app_version = "v" . "$maj.$min." . $patch; + $app_version = 'v'."$maj.$min.".$patch; } // Determine if this tag already exists, or if this prior to a release $this->line('Running: git rev-parse master '.$current_app_version); // $pre_release = trim(shell_exec('git rev-parse '.$use_branch.' '.$current_app_version.' 2>&1 1> /dev/null')); - if ($use_branch=='develop') { + if ($use_branch == 'develop') { $app_version = $app_version.'-pre'; } $full_app_version = $app_version.' - build '.$build_version.'-'.$hash_version; - $array = var_export( - array( + [ 'app_version' => $app_version, 'full_app_version' => $full_app_version, 'build_version' => $build_version, 'prerelease_version' => $prerelease_version, 'hash_version' => $hash_version, 'full_hash' => $full_hash_version, - 'branch' => $git_branch), + 'branch' => $git_branch, ], true ); - - // Construct our file content $content = <<info('Setting NEW version: '. $full_app_version.' ('.$git_branch.')'); + $this->info('Setting NEW version: '.$full_app_version.' ('.$git_branch.')'); } - } diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 1dcac211b2..9a5294c2d2 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -10,7 +10,6 @@ use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { - /** * Define the application's command schedule. * diff --git a/app/Events/CheckoutAccepted.php b/app/Events/CheckoutAccepted.php index 5146b32ee9..cd5ee19776 100644 --- a/app/Events/CheckoutAccepted.php +++ b/app/Events/CheckoutAccepted.php @@ -18,6 +18,6 @@ class CheckoutAccepted */ public function __construct(CheckoutAcceptance $acceptance) { - $this->acceptance = $acceptance; + $this->acceptance = $acceptance; } } diff --git a/app/Events/CheckoutDeclined.php b/app/Events/CheckoutDeclined.php index 44f399423f..01d84b30f3 100644 --- a/app/Events/CheckoutDeclined.php +++ b/app/Events/CheckoutDeclined.php @@ -10,7 +10,7 @@ use Illuminate\Queue\SerializesModels; class CheckoutDeclined { use Dispatchable, SerializesModels; - + /** * Create a new event instance. * @@ -18,6 +18,6 @@ class CheckoutDeclined */ public function __construct(CheckoutAcceptance $acceptance) { - $this->acceptance = $acceptance; + $this->acceptance = $acceptance; } } diff --git a/app/Events/CheckoutableCheckedIn.php b/app/Events/CheckoutableCheckedIn.php index 54e3db6abc..9609f7d415 100644 --- a/app/Events/CheckoutableCheckedIn.php +++ b/app/Events/CheckoutableCheckedIn.php @@ -25,8 +25,8 @@ class CheckoutableCheckedIn { $this->checkoutable = $checkoutable; $this->checkedOutTo = $checkedOutTo; - $this->checkedInBy = $checkedInBy; - $this->note = $note; - $this->action_date = $action_date ?? date('Y-m-d'); + $this->checkedInBy = $checkedInBy; + $this->note = $note; + $this->action_date = $action_date ?? date('Y-m-d'); } } diff --git a/app/Events/CheckoutableCheckedOut.php b/app/Events/CheckoutableCheckedOut.php index 5e6ffd243a..30f70ca0d8 100644 --- a/app/Events/CheckoutableCheckedOut.php +++ b/app/Events/CheckoutableCheckedOut.php @@ -25,6 +25,6 @@ class CheckoutableCheckedOut $this->checkoutable = $checkoutable; $this->checkedOutTo = $checkedOutTo; $this->checkedOutBy = $checkedOutBy; - $this->note = $note; + $this->note = $note; } } diff --git a/app/Exceptions/CheckoutNotAllowed.php b/app/Exceptions/CheckoutNotAllowed.php index 6fe2c1d484..172f072aee 100644 --- a/app/Exceptions/CheckoutNotAllowed.php +++ b/app/Exceptions/CheckoutNotAllowed.php @@ -6,17 +6,17 @@ use Exception; class CheckoutNotAllowed extends Exception { - private $errorMessage; - function __construct($errorMessage = null) + public function __construct($errorMessage = null) { $this->errorMessage = $errorMessage; parent::__construct($errorMessage); } + public function __toString() { - return is_null($this->errorMessage) ? "A checkout is not allowed under these circumstances" : $this->errorMessage; + return is_null($this->errorMessage) ? 'A checkout is not allowed under these circumstances' : $this->errorMessage; } } diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index de890d3e4d..17a3682885 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -2,30 +2,22 @@ namespace App\Exceptions; -use Exception; -use Illuminate\Auth\AuthenticationException; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use App\Helpers\Helper; use Illuminate\Validation\ValidationException; use Log; +use Throwable; class Handler extends ExceptionHandler { /** - * A list of the exception types that should not be reported. + * A list of the exception types that are not reported. * * @var array */ protected $dontReport = [ - \Illuminate\Auth\AuthenticationException::class, - \Illuminate\Auth\Access\AuthorizationException::class, - \Symfony\Component\HttpKernel\Exception\HttpException::class, - \Illuminate\Database\Eloquent\ModelNotFoundException::class, - \Illuminate\Session\TokenMismatchException::class, - \Illuminate\Validation\ValidationException::class, - \Intervention\Image\Exception\NotSupportedException::class, - \League\OAuth2\Server\Exception\OAuthServerException::class, + // ]; /** @@ -33,25 +25,26 @@ class Handler extends ExceptionHandler * * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * - * @param \Exception $exception + * @param \Throwable $exception * @return void */ - public function report(Exception $exception) + public function report(Throwable $exception) { if ($this->shouldReport($exception)) { - \Log::error($exception); + Log::error($exception); return parent::report($exception); } } /** * Render an exception into an HTTP response. + * * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ - public function render($request, Exception $e) + public function render($request, Throwable $e) { @@ -96,31 +89,26 @@ class Handler extends ExceptionHandler } - /** - * Convert an authentication exception into an unauthenticated response. + /** + * A list of the inputs that are never flashed for validation exceptions. * - * @param \Illuminate\Http\Request $request - * @param \Illuminate\Auth\AuthenticationException $exception - * @return \Illuminate\Http\Response + * @var array */ - protected function unauthenticated($request, AuthenticationException $exception) - { - if ($request->expectsJson()) { - return response()->json(['error' => 'Unauthorized or unauthenticated.'], 401); - } - - return redirect()->guest('login'); - } + protected $dontFlash = [ + 'current_password', + 'password', + 'password_confirmation', + ]; /** - * Convert a validation exception into a JSON response. + * Register the exception handling callbacks for the application. * - * @param \Illuminate\Http\Request $request - * @param \Illuminate\Validation\ValidationException $exception - * @return \Illuminate\Http\JsonResponse + * @return void */ - protected function invalidJson($request, ValidationException $exception) + public function register() { - return response()->json(Helper::formatStandardApiResponse('error', null, $exception->errors(), 400)); + $this->reportable(function (Throwable $e) { + // + }); } } diff --git a/app/Helpers/Helper.php b/app/Helpers/Helper.php index d331ea36f5..f67f676313 100644 --- a/app/Helpers/Helper.php +++ b/app/Helpers/Helper.php @@ -1,4 +1,5 @@ ] * @since [v2.0] - * @return String + * @return string */ public static function parseEscapedMarkedown($str) { @@ -33,7 +32,6 @@ class Helper } } - /** * The importer has formatted number strings since v3, * so the value might be a string, or an integer. @@ -41,11 +39,12 @@ class Helper * * @author [A. Gianotto] [] * @since [v2.0] - * @return String + * @return string */ public static function formatCurrencyOutput($cost) { if (is_numeric($cost)) { + if (Setting::getSettings()->digit_separator=='1.234,56') { return number_format($cost, 2, ',', '.'); } @@ -61,283 +60,282 @@ class Helper * * @author [A. Gianotto] [] * @since [v3.3] - * @return Array + * @return array */ public static function defaultChartColors($index = 0) { $colors = [ - "#008941", - "#FF851B", - "#006FA6", - "#A30059", - "#1CE6FF", - "#FFDBE5", - "#7A4900", - "#0000A6", - "#63FFAC", - "#B79762", - "#004D43", - "#8FB0FF", - "#997D87", - "#5A0007", - "#809693", - "#FEFFE6", - "#1B4400", - "#4FC601", - "#3B5DFF", - "#4A3B53", - "#FF2F80", - "#61615A", - "#BA0900", - "#6B7900", - "#00C2A0", - "#FFAA92", - "#FF90C9", - "#B903AA", - "#D16100", - "#DDEFFF", - "#000035", - "#7B4F4B", - "#A1C299", - "#300018", - "#0AA6D8", - "#013349", - "#00846F", - "#372101", - "#FFB500", - "#C2FFED", - "#A079BF", - "#CC0744", - "#C0B9B2", - "#C2FF99", - "#001E09", - "#00489C", - "#6F0062", - "#0CBD66", - "#EEC3FF", - "#456D75", - "#B77B68", - "#7A87A1", - "#788D66", - "#885578", - "#FAD09F", - "#FF8A9A", - "#D157A0", - "#BEC459", - "#456648", - "#0086ED", - "#886F4C", - "#34362D", - "#B4A8BD", - "#00A6AA", - "#452C2C", - "#636375", - "#A3C8C9", - "#FF913F", - "#938A81", - "#575329", - "#00FECF", - "#B05B6F", - "#8CD0FF", - "#3B9700", - "#04F757", - "#C8A1A1", - "#1E6E00", - "#7900D7", - "#A77500", - "#6367A9", - "#A05837", - "#6B002C", - "#772600", - "#D790FF", - "#9B9700", - "#549E79", - "#FFF69F", - "#201625", - "#72418F", - "#BC23FF", - "#99ADC0", - "#3A2465", - "#922329", - "#5B4534", - "#FDE8DC", - "#404E55", - "#0089A3", - "#CB7E98", - "#A4E804", - "#324E72", - "#6A3A4C", - "#83AB58", - "#001C1E", - "#D1F7CE", - "#004B28", - "#C8D0F6", - "#A3A489", - "#806C66", - "#222800", - "#BF5650", - "#E83000", - "#66796D", - "#DA007C", - "#FF1A59", - "#8ADBB4", - "#1E0200", - "#5B4E51", - "#C895C5", - "#320033", - "#FF6832", - "#66E1D3", - "#CFCDAC", - "#D0AC94", - "#7ED379", - "#012C58", - "#7A7BFF", - "#D68E01", - "#353339", - "#78AFA1", - "#FEB2C6", - "#75797C", - "#837393", - "#943A4D", - "#B5F4FF", - "#D2DCD5", - "#9556BD", - "#6A714A", - "#001325", - "#02525F", - "#0AA3F7", - "#E98176", - "#DBD5DD", - "#5EBCD1", - "#3D4F44", - "#7E6405", - "#02684E", - "#962B75", - "#8D8546", - "#9695C5", - "#E773CE", - "#D86A78", - "#3E89BE", - "#CA834E", - "#518A87", - "#5B113C", - "#55813B", - "#E704C4", - "#00005F", - "#A97399", - "#4B8160", - "#59738A", - "#FF5DA7", - "#F7C9BF", - "#643127", - "#513A01", - "#6B94AA", - "#51A058", - "#A45B02", - "#1D1702", - "#E20027", - "#E7AB63", - "#4C6001", - "#9C6966", - "#64547B", - "#97979E", - "#006A66", - "#391406", - "#F4D749", - "#0045D2", - "#006C31", - "#DDB6D0", - "#7C6571", - "#9FB2A4", - "#00D891", - "#15A08A", - "#BC65E9", - "#FFFFFE", - "#C6DC99", - "#203B3C", - "#671190", - "#6B3A64", - "#F5E1FF", - "#FFA0F2", - "#CCAA35", - "#374527", - "#8BB400", - "#797868", - "#C6005A", - "#3B000A", - "#C86240", - "#29607C", - "#402334", - "#7D5A44", - "#CCB87C", - "#B88183", - "#AA5199", - "#B5D6C3", - "#A38469", - "#9F94F0", - "#A74571", - "#B894A6", - "#71BB8C", - "#00B433", - "#789EC9", - "#6D80BA", - "#953F00", - "#5EFF03", - "#E4FFFC", - "#1BE177", - "#BCB1E5", - "#76912F", - "#003109", - "#0060CD", - "#D20096", - "#895563", - "#29201D", - "#5B3213", - "#A76F42", - "#89412E", - "#1A3A2A", - "#494B5A", - "#A88C85", - "#F4ABAA", - "#A3F3AB", - "#00C6C8", - "#EA8B66", - "#958A9F", - "#BDC9D2", - "#9FA064", - "#BE4700", - "#658188", - "#83A485", - "#453C23", - "#47675D", - "#3A3F00", - "#061203", - "#DFFB71", - "#868E7E", - "#98D058", - "#6C8F7D", - "#D7BFC2", - "#3C3E6E", - "#D83D66", - "#2F5D9B", - "#6C5E46", - "#D25B88", - "#5B656C", - "#00B57F", - "#545C46", - "#866097", - "#365D25", - "#252F99", - "#00CCFF", - "#674E60", - "#FC009C", - "#92896B", + '#008941', + '#FF4A46', + '#006FA6', + '#A30059', + '#1CE6FF', + '#FFDBE5', + '#7A4900', + '#0000A6', + '#63FFAC', + '#B79762', + '#004D43', + '#8FB0FF', + '#997D87', + '#5A0007', + '#809693', + '#FEFFE6', + '#1B4400', + '#4FC601', + '#3B5DFF', + '#4A3B53', + '#FF2F80', + '#61615A', + '#BA0900', + '#6B7900', + '#00C2A0', + '#FFAA92', + '#FF90C9', + '#B903AA', + '#D16100', + '#DDEFFF', + '#000035', + '#7B4F4B', + '#A1C299', + '#300018', + '#0AA6D8', + '#013349', + '#00846F', + '#372101', + '#FFB500', + '#C2FFED', + '#A079BF', + '#CC0744', + '#C0B9B2', + '#C2FF99', + '#001E09', + '#00489C', + '#6F0062', + '#0CBD66', + '#EEC3FF', + '#456D75', + '#B77B68', + '#7A87A1', + '#788D66', + '#885578', + '#FAD09F', + '#FF8A9A', + '#D157A0', + '#BEC459', + '#456648', + '#0086ED', + '#886F4C', + '#34362D', + '#B4A8BD', + '#00A6AA', + '#452C2C', + '#636375', + '#A3C8C9', + '#FF913F', + '#938A81', + '#575329', + '#00FECF', + '#B05B6F', + '#8CD0FF', + '#3B9700', + '#04F757', + '#C8A1A1', + '#1E6E00', + '#7900D7', + '#A77500', + '#6367A9', + '#A05837', + '#6B002C', + '#772600', + '#D790FF', + '#9B9700', + '#549E79', + '#FFF69F', + '#201625', + '#72418F', + '#BC23FF', + '#99ADC0', + '#3A2465', + '#922329', + '#5B4534', + '#FDE8DC', + '#404E55', + '#0089A3', + '#CB7E98', + '#A4E804', + '#324E72', + '#6A3A4C', + '#83AB58', + '#001C1E', + '#D1F7CE', + '#004B28', + '#C8D0F6', + '#A3A489', + '#806C66', + '#222800', + '#BF5650', + '#E83000', + '#66796D', + '#DA007C', + '#FF1A59', + '#8ADBB4', + '#1E0200', + '#5B4E51', + '#C895C5', + '#320033', + '#FF6832', + '#66E1D3', + '#CFCDAC', + '#D0AC94', + '#7ED379', + '#012C58', + '#7A7BFF', + '#D68E01', + '#353339', + '#78AFA1', + '#FEB2C6', + '#75797C', + '#837393', + '#943A4D', + '#B5F4FF', + '#D2DCD5', + '#9556BD', + '#6A714A', + '#001325', + '#02525F', + '#0AA3F7', + '#E98176', + '#DBD5DD', + '#5EBCD1', + '#3D4F44', + '#7E6405', + '#02684E', + '#962B75', + '#8D8546', + '#9695C5', + '#E773CE', + '#D86A78', + '#3E89BE', + '#CA834E', + '#518A87', + '#5B113C', + '#55813B', + '#E704C4', + '#00005F', + '#A97399', + '#4B8160', + '#59738A', + '#FF5DA7', + '#F7C9BF', + '#643127', + '#513A01', + '#6B94AA', + '#51A058', + '#A45B02', + '#1D1702', + '#E20027', + '#E7AB63', + '#4C6001', + '#9C6966', + '#64547B', + '#97979E', + '#006A66', + '#391406', + '#F4D749', + '#0045D2', + '#006C31', + '#DDB6D0', + '#7C6571', + '#9FB2A4', + '#00D891', + '#15A08A', + '#BC65E9', + '#FFFFFE', + '#C6DC99', + '#203B3C', + '#671190', + '#6B3A64', + '#F5E1FF', + '#FFA0F2', + '#CCAA35', + '#374527', + '#8BB400', + '#797868', + '#C6005A', + '#3B000A', + '#C86240', + '#29607C', + '#402334', + '#7D5A44', + '#CCB87C', + '#B88183', + '#AA5199', + '#B5D6C3', + '#A38469', + '#9F94F0', + '#A74571', + '#B894A6', + '#71BB8C', + '#00B433', + '#789EC9', + '#6D80BA', + '#953F00', + '#5EFF03', + '#E4FFFC', + '#1BE177', + '#BCB1E5', + '#76912F', + '#003109', + '#0060CD', + '#D20096', + '#895563', + '#29201D', + '#5B3213', + '#A76F42', + '#89412E', + '#1A3A2A', + '#494B5A', + '#A88C85', + '#F4ABAA', + '#A3F3AB', + '#00C6C8', + '#EA8B66', + '#958A9F', + '#BDC9D2', + '#9FA064', + '#BE4700', + '#658188', + '#83A485', + '#453C23', + '#47675D', + '#3A3F00', + '#061203', + '#DFFB71', + '#868E7E', + '#98D058', + '#6C8F7D', + '#D7BFC2', + '#3C3E6E', + '#D83D66', + '#2F5D9B', + '#6C5E46', + '#D25B88', + '#5B656C', + '#00B57F', + '#545C46', + '#866097', + '#365D25', + '#252F99', + '#00CCFF', + '#674E60', + '#FC009C', + '#92896B', ]; return $colors[$index]; - } /** @@ -348,33 +346,33 @@ class Helper * * @return string */ - public static function adjustBrightness($hexCode, $adjustPercent) { + public static function adjustBrightness($hexCode, $adjustPercent) + { $hexCode = ltrim($hexCode, '#'); if (strlen($hexCode) == 3) { - $hexCode = $hexCode[0] . $hexCode[0] . $hexCode[1] . $hexCode[1] . $hexCode[2] . $hexCode[2]; + $hexCode = $hexCode[0].$hexCode[0].$hexCode[1].$hexCode[1].$hexCode[2].$hexCode[2]; } $hexCode = array_map('hexdec', str_split($hexCode, 2)); - foreach ($hexCode as & $color) { + foreach ($hexCode as &$color) { $adjustableLimit = $adjustPercent < 0 ? $color : 255 - $color; $adjustAmount = ceil($adjustableLimit * $adjustPercent); $color = str_pad(dechex($color + $adjustAmount), 2, '0', STR_PAD_LEFT); } - return '#' . implode($hexCode); + return '#'.implode($hexCode); } - /** * Static background (highlight) colors for pie charts * This is inelegant, and could be refactored later. * * @author [A. Gianotto] [] * @since [v3.2] - * @return Array + * @return array */ public static function chartBackgroundColors() { @@ -390,6 +388,7 @@ class Helper '#3c8dbc', ]; + return $colors; } @@ -399,13 +398,13 @@ class Helper * * @author [A. Gianotto] [] * @since [v2.7] - * @return String + * @return string */ public static function ParseFloat($floatString) { $LocaleInfo = localeconv(); - $floatString = str_replace(",", "", $floatString); - $floatString = str_replace($LocaleInfo["decimal_point"], ".", $floatString); + $floatString = str_replace(',', '', $floatString); + $floatString = str_replace($LocaleInfo['decimal_point'], '.', $floatString); // Strip Currency symbol // If no currency symbol is set, default to $ because Murica $currencySymbol = $LocaleInfo['currency_symbol']; @@ -414,6 +413,7 @@ class Helper } $floatString = str_replace($currencySymbol, '', $floatString); + return floatval($floatString); } @@ -422,12 +422,13 @@ class Helper * * @author [A. Gianotto] [] * @since [v2.5] - * @return Array + * @return array */ public static function statusLabelList() { - $statuslabel_list = array('' => trans('general.select_statuslabel')) + Statuslabel::orderBy('default_label', 'desc')->orderBy('name','asc')->orderBy('deployable','desc') + $statuslabel_list = ['' => trans('general.select_statuslabel')] + Statuslabel::orderBy('default_label', 'desc')->orderBy('name', 'asc')->orderBy('deployable', 'desc') ->pluck('name', 'id')->toArray(); + return $statuslabel_list; } @@ -440,14 +441,15 @@ class Helper * * @author [A. Gianotto] [] * @since [v5.1.0] - * @return Array + * @return array */ public static function deployableStatusLabelList() { - $statuslabel_list = Statuslabel::where('deployable', '=', '1')->orderBy('default_label', 'desc') - ->orderBy('name','asc') - ->orderBy('deployable','desc') + $statuslabel_list = Statuslabel::where('deployable', '=', '1')->orderBy('default_label', 'desc') + ->orderBy('name', 'asc') + ->orderBy('deployable', 'desc') ->pluck('name', 'id')->toArray(); + return $statuslabel_list; } @@ -456,16 +458,17 @@ class Helper * * @author [A. Gianotto] [] * @since [v2.5] - * @return Array + * @return array */ public static function statusTypeList() { $statuslabel_types = - array('' => trans('admin/hardware/form.select_statustype')) - + array('deployable' => trans('admin/hardware/general.deployable')) - + array('pending' => trans('admin/hardware/general.pending')) - + array('undeployable' => trans('admin/hardware/general.undeployable')) - + array('archived' => trans('admin/hardware/general.archived')); + ['' => trans('admin/hardware/form.select_statustype')] + + ['deployable' => trans('admin/hardware/general.deployable')] + + ['pending' => trans('admin/hardware/general.pending')] + + ['undeployable' => trans('admin/hardware/general.undeployable')] + + ['archived' => trans('admin/hardware/general.archived')]; + return $statuslabel_types; } @@ -474,12 +477,13 @@ class Helper * * @author [A. Gianotto] [] * @since [v2.5] - * @return Array + * @return array */ public static function depreciationList() { $depreciation_list = ['' => 'Do Not Depreciate'] + Depreciation::orderBy('name', 'asc') ->pluck('name', 'id')->toArray(); + return $depreciation_list; } @@ -488,18 +492,19 @@ class Helper * * @author [A. Gianotto] [] * @since [v2.5] - * @return Array + * @return array */ public static function categoryTypeList() { - $category_types = array( + $category_types = [ '' => '', 'accessory' => 'Accessory', 'asset' => 'Asset', 'consumable' => 'Consumable', 'component' => 'Component', - 'license' => 'License' - ); + 'license' => 'License', + ]; + return $category_types; } @@ -508,11 +513,12 @@ class Helper * * @author [A. Gianotto] [] * @since [v2.5] - * @return Array + * @return array */ public static function customFieldsetList() { - $customfields = array('' => trans('admin/models/general.no_custom_field')) + CustomFieldset::pluck('name', 'id')->toArray(); + $customfields = ['' => trans('admin/models/general.no_custom_field')] + CustomFieldset::pluck('name', 'id')->toArray(); + return $customfields; } @@ -521,7 +527,7 @@ class Helper * * @author [A. Gianotto] [] * @since [v3.4] - * @return Array + * @return array */ public static function predefined_formats() { @@ -536,7 +542,7 @@ class Helper * * @author [A. Gianotto] [] * @since [v3.3] - * @return Array + * @return array */ public static function barcodeDimensions($barcode_type = 'QRCODE') { @@ -550,6 +556,7 @@ class Helper $size['height'] = '-3'; $size['width'] = '-3'; } + return $size; } @@ -558,7 +565,7 @@ class Helper * * @author [A. Gianotto] [] * @since [v3.0] - * @return Array + * @return array */ public static function generateRandomString($length = 10) { @@ -568,17 +575,17 @@ class Helper for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } + return $randomString; } - /** * This nasty little method gets the low inventory info for the * alert dropdown * * @author [A. Gianotto] [] * @since [v3.0] - * @return Array + * @return array */ public static function checkLowInventory() { @@ -587,7 +594,7 @@ class Helper $components = Component::withCount('assets as assets_count')->whereNotNull('min_amt')->get(); $avail_consumables = 0; - $items_array = array(); + $items_array = []; $all_count = 0; foreach ($consumables as $consumable) { @@ -604,17 +611,14 @@ class Helper $items_array[$all_count]['type'] = 'consumables'; $items_array[$all_count]['percent'] = $percent; $items_array[$all_count]['remaining'] = $avail; - $items_array[$all_count]['min_amt']=$consumable->min_amt; + $items_array[$all_count]['min_amt'] = $consumable->min_amt; $all_count++; } - - } foreach ($accessories as $accessory) { $avail = $accessory->qty - $accessory->users_count; if ($avail < ($accessory->min_amt) + \App\Models\Setting::getSettings()->alert_threshold) { - if ($accessory->qty > 0) { $percent = number_format((($avail / $accessory->qty) * 100), 0); } else { @@ -626,10 +630,9 @@ class Helper $items_array[$all_count]['type'] = 'accessories'; $items_array[$all_count]['percent'] = $percent; $items_array[$all_count]['remaining'] = $avail; - $items_array[$all_count]['min_amt']=$accessory->min_amt; + $items_array[$all_count]['min_amt'] = $accessory->min_amt; $all_count++; } - } foreach ($components as $component) { @@ -646,27 +649,21 @@ class Helper $items_array[$all_count]['type'] = 'components'; $items_array[$all_count]['percent'] = $percent; $items_array[$all_count]['remaining'] = $avail; - $items_array[$all_count]['min_amt']=$component->min_amt; + $items_array[$all_count]['min_amt'] = $component->min_amt; $all_count++; } - } - - return $items_array; - - } - /** * Check if the file is an image, so we can show a preview * * @author [A. Gianotto] [] * @since [v3.0] * @param File $file - * @return String | Boolean + * @return string | Boolean */ public static function checkUploadIsImage($file) { @@ -674,7 +671,7 @@ class Helper $filetype = @finfo_file($finfo, $file); finfo_close($finfo); - if (($filetype=="image/jpeg") || ($filetype=="image/jpg") || ($filetype=="image/png") || ($filetype=="image/bmp") || ($filetype=="image/gif")) { + if (($filetype == 'image/jpeg') || ($filetype == 'image/jpg') || ($filetype == 'image/png') || ($filetype == 'image/bmp') || ($filetype == 'image/gif')) { return $filetype; } @@ -696,21 +693,17 @@ class Helper * @param array $permissions * @param array $selected_arr * @since [v1.0] - * @return Array + * @return array */ - public static function selectedPermissionsArray($permissions, $selected_arr = array()) + public static function selectedPermissionsArray($permissions, $selected_arr = []) { - - - $permissions_arr = array(); + $permissions_arr = []; foreach ($permissions as $permission) { - for ($x = 0; $x < count($permission); $x++) { $permission_name = $permission[$x]['permission']; if ($permission[$x]['display'] === true) { - if ($selected_arr) { if (array_key_exists($permission_name, $selected_arr)) { $permissions_arr[$permission_name] = $selected_arr[$permission_name]; @@ -721,11 +714,7 @@ class Helper $permissions_arr[$permission_name] = '0'; } } - - } - - } return $permissions_arr; @@ -741,7 +730,7 @@ class Helper * * @author [A. Gianotto] [] * @since [v3.0] - * @return boolean + * @return bool */ public static function checkIfRequired($class, $field) { @@ -753,12 +742,10 @@ class Helper } else { return true; } - } } } - /** * Check to see if the given key exists in the array, and trim excess white space before returning it * @@ -772,9 +759,9 @@ class Helper public static function array_smart_fetch(array $array, $key, $default = '') { array_change_key_case($array, CASE_LOWER); - return array_key_exists(strtolower($key), array_change_key_case($array)) ? e(trim($array[ $key ])) : $default; - } + return array_key_exists(strtolower($key), array_change_key_case($array)) ? e(trim($array[$key])) : $default; + } /** * Gracefully handle decrypting encrypted fields (custom fields, etc). @@ -784,52 +771,47 @@ class Helper * @author A. Gianotto * @since 3.6 * @param CustomField $field - * @param String $string + * @param string $string * @return string */ public static function gracefulDecrypt(CustomField $field, $string) { - if ($field->isFieldDecryptable($string)) { - try { Crypt::decrypt($string); - return Crypt::decrypt($string); + return Crypt::decrypt($string); } catch (DecryptException $e) { return 'Error Decrypting: '.$e->getMessage(); } + } - } return $string; - } + public static function formatStandardApiResponse($status, $payload = null, $messages = null) - - - public static function formatStandardApiResponse($status, $payload = null, $messages = null) { - + { $array['status'] = $status; $array['messages'] = $messages; - if (($messages) && (is_array($messages)) && (count($messages) > 0)) { + if (($messages) && (is_array($messages)) && (count($messages) > 0)) { $array['messages'] = $messages; } ($payload) ? $array['payload'] = $payload : $array['payload'] = null; + return $array; } - /* Possible solution for unicode fieldnames */ - public static function make_slug($string) { + public static function make_slug($string) + { return preg_replace('/\s+/u', '_', trim($string)); } - - public static function getFormattedDateObject($date, $type = 'datetime', $array = true) { - - if ($date=='') { + public static function getFormattedDateObject($date, $type = 'datetime', $array = true) + { + if ($date == '') { return null; } @@ -838,7 +820,7 @@ class Helper if ($type == 'datetime') { $dt['datetime'] = $tmp_date->format('Y-m-d H:i:s'); - $dt['formatted'] = $tmp_date->format($settings->date_display_format .' '. $settings->time_display_format); + $dt['formatted'] = $tmp_date->format($settings->date_display_format.' '.$settings->time_display_format); } else { $dt['date'] = $tmp_date->format('Y-m-d'); $dt['formatted'] = $tmp_date->format($settings->date_display_format); @@ -847,28 +829,28 @@ class Helper if ($array == 'true') { return $dt; } + return $dt['formatted']; - } - // Nicked from Drupal :) // Returns a file size limit in bytes based on the PHP upload_max_filesize // and post_max_size - public static function file_upload_max_size() { + public static function file_upload_max_size() + { static $max_size = -1; if ($max_size < 0) { // Start with post_max_size. - $post_max_size = Helper::parse_size(ini_get('post_max_size')); + $post_max_size = self::parse_size(ini_get('post_max_size')); if ($post_max_size > 0) { $max_size = $post_max_size; } // If upload_max_size is less, then reduce. Except if upload_max_size is // zero, which indicates no limit. - $upload_max = Helper::parse_size(ini_get('upload_max_filesize')); + $upload_max = self::parse_size(ini_get('upload_max_filesize')); if ($upload_max > 0 && $upload_max < $max_size) { $max_size = $upload_max; } @@ -877,43 +859,44 @@ class Helper return $max_size; } - public static function file_upload_max_size_readable() { + public static function file_upload_max_size_readable() + { static $max_size = -1; if ($max_size < 0) { // Start with post_max_size. - $post_max_size = Helper::parse_size(ini_get('post_max_size')); + $post_max_size = self::parse_size(ini_get('post_max_size')); if ($post_max_size > 0) { $max_size = ini_get('post_max_size'); } // If upload_max_size is less, then reduce. Except if upload_max_size is // zero, which indicates no limit. - $upload_max = Helper::parse_size(ini_get('upload_max_filesize')); + $upload_max = self::parse_size(ini_get('upload_max_filesize')); if ($upload_max > 0 && $upload_max < $post_max_size) { $max_size = ini_get('upload_max_filesize'); } } + return $max_size; } - public static function parse_size($size) { + public static function parse_size($size) + { $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size. $size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size. if ($unit) { // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by. return round($size * pow(1024, stripos('bkmgtpezy', $unit[0]))); - } - else { + } else { return round($size); } } - - public static function filetype_icon($filename) { - - $extension = substr(strrchr($filename,'.'),1); + public static function filetype_icon($filename) + { + $extension = substr(strrchr($filename, '.'), 1); $allowedExtensionMap = [ // Images @@ -942,12 +925,13 @@ class Helper if ($extension && array_key_exists($extension, $allowedExtensionMap)) { return $allowedExtensionMap[$extension]; } - return "fa fa-file-o"; + + return 'fa fa-file-o'; } - public static function show_file_inline($filename) { - - $extension = substr(strrchr($filename,'.'),1); + public static function show_file_inline($filename) + { + $extension = substr(strrchr($filename, '.'), 1); if ($extension) { switch ($extension) { @@ -961,6 +945,7 @@ class Helper return false; } } + return false; } @@ -975,7 +960,7 @@ class Helper */ public static function generateEncyrptedPassword(): string { - return bcrypt(Helper::generateUnencryptedPassword()); + return bcrypt(self::generateUnencryptedPassword()); } /** @@ -992,9 +977,10 @@ class Helper $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $password = ''; - for ( $i = 0; $i < 20; $i++ ) { - $password .= substr( $chars, random_int( 0, strlen( $chars ) - 1 ), 1 ); + for ($i = 0; $i < 20; $i++) { + $password .= substr($chars, random_int(0, strlen($chars) - 1), 1); } + return $password; } @@ -1005,7 +991,8 @@ class Helper * @param string $save_path path to a folder where the image should be saved * @return string path to uploaded image or false if something went wrong */ - public static function processUploadedImage(String $image_data, String $save_path) { + public static function processUploadedImage(String $image_data, String $save_path) + { if ($image_data == null || $save_path == null) { return false; } @@ -1014,15 +1001,15 @@ class Helper // data:image/jpeg;base64,; This causes the image library to be unhappy, so we need to remove it. $header = explode(';', $image_data, 2)[0]; // Grab the image type from the header while we're at it. - $extension = substr($header, strpos($header, '/')+1); + $extension = substr($header, strpos($header, '/') + 1); // Start reading the image after the first comma, postceding the base64. - $image = substr($image_data, strpos($image_data, ',')+1); + $image = substr($image_data, strpos($image_data, ',') + 1); - $file_name = str_random(25).".".$extension; + $file_name = str_random(25).'.'.$extension; - $directory= public_path($save_path); + $directory = public_path($save_path); // Check if the uploads directory exists. If not, try to create it. - if (!file_exists($directory)) { + if (! file_exists($directory)) { mkdir($directory, 0755, true); } @@ -1039,5 +1026,4 @@ class Helper return $file_name; } - } diff --git a/app/Helpers/StorageHelper.php b/app/Helpers/StorageHelper.php index c5e084fa68..94dfe62c76 100644 --- a/app/Helpers/StorageHelper.php +++ b/app/Helpers/StorageHelper.php @@ -1,15 +1,17 @@ download(Storage::disk($disk)->path($filename)); //works for PRIVATE or public?! @@ -20,4 +22,4 @@ class StorageHelper return Storage::disk($disk)->download($filename); } } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Accessories/AccessoriesController.php b/app/Http/Controllers/Accessories/AccessoriesController.php index a96859d928..256634f891 100755 --- a/app/Http/Controllers/Accessories/AccessoriesController.php +++ b/app/Http/Controllers/Accessories/AccessoriesController.php @@ -1,4 +1,5 @@ authorize('index', Accessory::class); + return view('accessories/index'); } - /** * Returns a view with a form to create a new Accessory. * @@ -45,11 +46,11 @@ class AccessoriesController extends Controller { $this->authorize('create', Accessory::class); $category_type = 'accessory'; + return view('accessories/edit')->with('category_type', $category_type) ->with('item', new Accessory); } - /** * Validate and save new Accessory from form post * @@ -65,27 +66,28 @@ class AccessoriesController extends Controller $accessory = new Accessory(); // Update the accessory data - $accessory->name = request('name'); - $accessory->category_id = request('category_id'); - $accessory->location_id = request('location_id'); - $accessory->min_amt = request('min_amt'); - $accessory->company_id = Company::getIdForCurrentUser(request('company_id')); - $accessory->order_number = request('order_number'); - $accessory->manufacturer_id = request('manufacturer_id'); - $accessory->model_number = request('model_number'); - $accessory->purchase_date = request('purchase_date'); - $accessory->purchase_cost = Helper::ParseFloat(request('purchase_cost')); - $accessory->qty = request('qty'); - $accessory->user_id = Auth::user()->id; - $accessory->supplier_id = request('supplier_id'); + $accessory->name = request('name'); + $accessory->category_id = request('category_id'); + $accessory->location_id = request('location_id'); + $accessory->min_amt = request('min_amt'); + $accessory->company_id = Company::getIdForCurrentUser(request('company_id')); + $accessory->order_number = request('order_number'); + $accessory->manufacturer_id = request('manufacturer_id'); + $accessory->model_number = request('model_number'); + $accessory->purchase_date = request('purchase_date'); + $accessory->purchase_cost = Helper::ParseFloat(request('purchase_cost')); + $accessory->qty = request('qty'); + $accessory->user_id = Auth::user()->id; + $accessory->supplier_id = request('supplier_id'); $accessory = $request->handleImages($accessory); - + // Was the accessory created? if ($accessory->save()) { // Redirect to the new accessory page return redirect()->route('accessories.index')->with('success', trans('admin/accessories/message.create.success')); } + return redirect()->back()->withInput()->withErrors($accessory->getErrors()); } @@ -99,17 +101,15 @@ class AccessoriesController extends Controller */ public function edit($accessoryId = null) { - if ($item = Accessory::find($accessoryId)) { $this->authorize($item); + return view('accessories/edit', compact('item'))->with('category_type', 'accessory'); } return redirect()->route('accessories.index')->with('error', trans('admin/accessories/message.does_not_exist')); - } - /** * Save edited Accessory from form post * @@ -128,18 +128,18 @@ class AccessoriesController extends Controller $this->authorize($accessory); // Update the accessory data - $accessory->name = request('name'); - $accessory->location_id = request('location_id'); - $accessory->min_amt = request('min_amt'); - $accessory->category_id = request('category_id'); - $accessory->company_id = Company::getIdForCurrentUser(request('company_id')); - $accessory->manufacturer_id = request('manufacturer_id'); - $accessory->order_number = request('order_number'); - $accessory->model_number = request('model_number'); - $accessory->purchase_date = request('purchase_date'); - $accessory->purchase_cost = request('purchase_cost'); - $accessory->qty = request('qty'); - $accessory->supplier_id = request('supplier_id'); + $accessory->name = request('name'); + $accessory->location_id = request('location_id'); + $accessory->min_amt = request('min_amt'); + $accessory->category_id = request('category_id'); + $accessory->company_id = Company::getIdForCurrentUser(request('company_id')); + $accessory->manufacturer_id = request('manufacturer_id'); + $accessory->order_number = request('order_number'); + $accessory->model_number = request('model_number'); + $accessory->purchase_date = request('purchase_date'); + $accessory->purchase_cost = request('purchase_cost'); + $accessory->qty = request('qty'); + $accessory->supplier_id = request('supplier_id'); $accessory = $request->handleImages($accessory); @@ -147,6 +147,7 @@ class AccessoriesController extends Controller if ($accessory->save()) { return redirect()->route('accessories.index')->with('success', trans('admin/accessories/message.update.success')); } + return redirect()->back()->withInput()->withErrors($accessory->getErrors()); } @@ -166,13 +167,12 @@ class AccessoriesController extends Controller $this->authorize($accessory); - if ($accessory->hasUsers() > 0) { - return redirect()->route('accessories.index')->with('error', trans('admin/accessories/message.assoc_users', array('count'=> $accessory->hasUsers()))); + return redirect()->route('accessories.index')->with('error', trans('admin/accessories/message.assoc_users', ['count'=> $accessory->hasUsers()])); } if ($accessory->image) { - try { + try { Storage::disk('public')->delete('accessories'.'/'.$accessory->image); } catch (\Exception $e) { \Log::debug($e); @@ -180,10 +180,10 @@ class AccessoriesController extends Controller } $accessory->delete(); + return redirect()->route('accessories.index')->with('success', trans('admin/accessories/message.delete.success')); } - /** * Returns a view that invokes the ajax table which contains * the content for the accessory detail view, which is generated in getDataView. @@ -202,6 +202,7 @@ class AccessoriesController extends Controller if (isset($accessory->id)) { return view('accessories/view', compact('accessory')); } + return redirect()->route('accessories.index')->with('error', trans('admin/accessories/message.does_not_exist', ['id' => $accessoryID])); } } diff --git a/app/Http/Controllers/Accessories/AccessoryCheckinController.php b/app/Http/Controllers/Accessories/AccessoryCheckinController.php index 1cfbaec1b4..3424c2aa13 100644 --- a/app/Http/Controllers/Accessories/AccessoryCheckinController.php +++ b/app/Http/Controllers/Accessories/AccessoryCheckinController.php @@ -17,7 +17,7 @@ class AccessoryCheckinController extends Controller * * @author [A. Gianotto] [] * @param Request $request - * @param integer $accessoryUserId + * @param int $accessoryUserId * @param string $backto * @return View * @internal param int $accessoryId @@ -33,6 +33,7 @@ class AccessoryCheckinController extends Controller $accessory = Accessory::find($accessory_user->accessory_id); $this->authorize('checkin', $accessory); + return view('accessories/checkin', compact('accessory'))->with('backto', $backto); } @@ -49,7 +50,7 @@ class AccessoryCheckinController extends Controller */ public function store(Request $request, $accessoryUserId = null, $backto = null) { - // Check if the accessory exists + // Check if the accessory exists if (is_null($accessory_user = DB::table('accessories_users')->find($accessoryUserId))) { // Redirect to the accessory management page with error return redirect()->route('accessories.index')->with('error', trans('admin/accessories/message.does_not_exist')); @@ -60,7 +61,7 @@ class AccessoryCheckinController extends Controller $this->authorize('checkin', $accessory); $checkin_at = date('Y-m-d'); - if($request->filled('checkin_at')){ + if ($request->filled('checkin_at')) { $checkin_at = $request->input('checkin_at'); } @@ -70,7 +71,7 @@ class AccessoryCheckinController extends Controller event(new CheckoutableCheckedIn($accessory, User::find($return_to), Auth::user(), $request->input('note'), $checkin_at)); - return redirect()->route("accessories.show", $accessory->id)->with('success', trans('admin/accessories/message.checkin.success')); + return redirect()->route('accessories.show', $accessory->id)->with('success', trans('admin/accessories/message.checkin.success')); } // Redirect to the accessory management page with error return redirect()->route('accessories.index')->with('error', trans('admin/accessories/message.checkin.error')); diff --git a/app/Http/Controllers/Accessories/AccessoryCheckoutController.php b/app/Http/Controllers/Accessories/AccessoryCheckoutController.php index 656a040a55..7eb9b39a46 100644 --- a/app/Http/Controllers/Accessories/AccessoryCheckoutController.php +++ b/app/Http/Controllers/Accessories/AccessoryCheckoutController.php @@ -14,7 +14,6 @@ use Illuminate\Support\Facades\Input; class AccessoryCheckoutController extends Controller { - /** * Return the form to checkout an Accessory to a user. * @@ -32,7 +31,6 @@ class AccessoryCheckoutController extends Controller } if ($accessory->category) { - $this->authorize('checkout', $accessory); // Get the dropdown of users and then pass it to the checkout view @@ -56,7 +54,7 @@ class AccessoryCheckoutController extends Controller */ public function store(Request $request, $accessoryId) { - // Check if the accessory exists + // Check if the accessory exists if (is_null($accessory = Accessory::find($accessoryId))) { // Redirect to the accessory management page with error return redirect()->route('accessories.index')->with('error', trans('admin/accessories/message.user_not_found')); @@ -64,11 +62,11 @@ class AccessoryCheckoutController extends Controller $this->authorize('checkout', $accessory); - if (!$user = User::find($request->input('assigned_to'))) { + if (! $user = User::find($request->input('assigned_to'))) { return redirect()->route('checkout/accessory', $accessory->id)->with('error', trans('admin/accessories/message.checkout.user_does_not_exist')); } - // Update the accessory data + // Update the accessory data $accessory->assigned_to = e($request->input('assigned_to')); $accessory->users()->attach($accessory->id, [ @@ -76,14 +74,14 @@ class AccessoryCheckoutController extends Controller 'created_at' => Carbon::now(), 'user_id' => Auth::id(), 'assigned_to' => $request->get('assigned_to'), - 'note' => $request->input('note') + 'note' => $request->input('note'), ]); DB::table('accessories_users')->where('assigned_to', '=', $accessory->assigned_to)->where('accessory_id', '=', $accessory->id)->first(); event(new CheckoutableCheckedOut($accessory, $user, Auth::user(), $request->input('note'))); - // Redirect to the new accessory page + // Redirect to the new accessory page return redirect()->route('accessories.index')->with('success', trans('admin/accessories/message.checkout.success')); } } diff --git a/app/Http/Controllers/Account/AcceptanceController.php b/app/Http/Controllers/Account/AcceptanceController.php index 6502196b25..b25a8df45b 100644 --- a/app/Http/Controllers/Account/AcceptanceController.php +++ b/app/Http/Controllers/Account/AcceptanceController.php @@ -1,4 +1,5 @@ -pending()->get(); return view('account/accept.index', compact('acceptances')); @@ -29,12 +31,12 @@ class AcceptanceController extends Controller { /** * Shows a form to either accept or decline the checkout acceptance - * + * * @param int $id * @return mixed */ - public function create($id) { - + public function create($id) + { $acceptance = CheckoutAcceptance::find($id); if (is_null($acceptance)) { @@ -43,28 +45,28 @@ class AcceptanceController extends Controller { if (! $acceptance->isPending()) { return redirect()->route('account.accept')->with('error', trans('admin/users/message.error.asset_already_accepted')); - } + } if (! $acceptance->isCheckedOutTo(Auth::user())) { return redirect()->route('account.accept')->with('error', trans('admin/users/message.error.incorrect_user_accepted')); } - if (!Company::isCurrentUserHasAccess($acceptance->checkoutable)) { + if (! Company::isCurrentUserHasAccess($acceptance->checkoutable)) { return redirect()->route('account.accept')->with('error', trans('general.insufficient_permissions')); - } + } return view('account/accept.create', compact('acceptance')); - } + } /** * Stores the accept/decline of the checkout acceptance - * + * * @param Request $request * @param int $id * @return Redirect */ - public function store(Request $request, $id) { - + public function store(Request $request, $id) + { $acceptance = CheckoutAcceptance::find($id); if (is_null($acceptance)) { @@ -73,55 +75,50 @@ class AcceptanceController extends Controller { if (! $acceptance->isPending()) { return redirect()->route('account.accept')->with('error', trans('admin/users/message.error.asset_already_accepted')); - } + } if (! $acceptance->isCheckedOutTo(Auth::user())) { return redirect()->route('account.accept')->with('error', trans('admin/users/message.error.incorrect_user_accepted')); } - if (!Company::isCurrentUserHasAccess($acceptance->checkoutable)) { + if (! Company::isCurrentUserHasAccess($acceptance->checkoutable)) { return redirect()->route('account.accept')->with('error', trans('general.insufficient_permissions')); - } + } - if (!$request->filled('asset_acceptance')) { + if (! $request->filled('asset_acceptance')) { return redirect()->back()->with('error', trans('admin/users/message.error.accept_or_decline')); } /** * Get the signature and save it */ - - if (!Storage::exists('private_uploads/signatures')) Storage::makeDirectory('private_uploads/signatures', 775); - + if (! Storage::exists('private_uploads/signatures')) { + Storage::makeDirectory('private_uploads/signatures', 775); + } $sig_filename = ''; if ($request->filled('signature_output')) { - $sig_filename = "siglog-" .Str::uuid() . '-'.date('Y-m-d-his').".png"; + $sig_filename = 'siglog-'.Str::uuid().'-'.date('Y-m-d-his').'.png'; $data_uri = e($request->input('signature_output')); - $encoded_image = explode(",", $data_uri); + $encoded_image = explode(',', $data_uri); $decoded_image = base64_decode($encoded_image[1]); - Storage::put('private_uploads/signatures/'.$sig_filename, (string)$decoded_image); + Storage::put('private_uploads/signatures/'.$sig_filename, (string) $decoded_image); } - if ($request->input('asset_acceptance') == 'accepted') { - $acceptance->accept($sig_filename); event(new CheckoutAccepted($acceptance)); $return_msg = trans('admin/users/message.accepted'); - } else { - - $acceptance->decline($sig_filename); + $acceptance->decline($sig_filename); event(new CheckoutDeclined($acceptance)); $return_msg = trans('admin/users/message.declined'); - } return redirect()->to('account/accept')->with('success', $return_msg); - } + } } diff --git a/app/Http/Controllers/ActionlogController.php b/app/Http/Controllers/ActionlogController.php index f0d4faad2f..31ac13dab5 100644 --- a/app/Http/Controllers/ActionlogController.php +++ b/app/Http/Controllers/ActionlogController.php @@ -10,9 +10,10 @@ class ActionlogController extends Controller public function displaySig($filename) { $this->authorize('view', \App\Models\Asset::class); - $file = config('app.private_uploads') . '/signatures/' . $filename; + $file = config('app.private_uploads').'/signatures/'.$filename; $filetype = Helper::checkUploadIsImage($file); $contents = file_get_contents($file); + return Response::make($contents)->header('Content-Type', $filetype); } } diff --git a/app/Http/Controllers/Api/AccessoriesController.php b/app/Http/Controllers/Api/AccessoriesController.php index 5ff8622f41..4ff90b837b 100644 --- a/app/Http/Controllers/Api/AccessoriesController.php +++ b/app/Http/Controllers/Api/AccessoriesController.php @@ -9,8 +9,8 @@ use App\Http\Transformers\SelectlistTransformer; use App\Models\Accessory; use App\Models\Company; use App\Models\User; -use Carbon\Carbon; use Auth; +use Carbon\Carbon; use DB; use Illuminate\Http\Request; use App\Http\Requests\ImageUploadRequest; @@ -27,6 +27,7 @@ class AccessoriesController extends Controller public function index(Request $request) { $this->authorize('view', Accessory::class); + $allowed_columns = ['id', 'name', 'model_number', 'eol', 'notes', 'created_at', 'min_amt', 'company_id']; // This array is what determines which fields should be allowed to be sorted on ON the table itself, no relations // Relations will be handled in query scopes a little further down. @@ -50,19 +51,19 @@ class AccessoriesController extends Controller } if ($request->filled('company_id')) { - $accessories->where('company_id','=',$request->input('company_id')); + $accessories->where('company_id', '=', $request->input('company_id')); } if ($request->filled('category_id')) { - $accessories->where('category_id','=',$request->input('category_id')); + $accessories->where('category_id', '=', $request->input('category_id')); } if ($request->filled('manufacturer_id')) { - $accessories->where('manufacturer_id','=',$request->input('manufacturer_id')); + $accessories->where('manufacturer_id', '=', $request->input('manufacturer_id')); } if ($request->filled('supplier_id')) { - $accessories->where('supplier_id','=',$request->input('supplier_id')); + $accessories->where('supplier_id', '=', $request->input('supplier_id')); } if ($request->filled('location_id')) { @@ -100,10 +101,10 @@ class AccessoriesController extends Controller $accessories = $accessories->orderBy($column_sort, $order); break; } - - + $total = $accessories->count(); $accessories = $accessories->skip($offset)->take($limit)->get(); + return (new AccessoriesTransformer)->transformAccessories($accessories, $total); } @@ -126,6 +127,7 @@ class AccessoriesController extends Controller if ($accessory->save()) { return response()->json(Helper::formatStandardApiResponse('success', $accessory, trans('admin/accessories/message.create.success'))); } + return response()->json(Helper::formatStandardApiResponse('error', null, $accessory->getErrors())); } @@ -142,6 +144,7 @@ class AccessoriesController extends Controller { $this->authorize('view', Accessory::class); $accessory = Accessory::findOrFail($id); + return (new AccessoriesTransformer)->transformAccessory($accessory); } @@ -158,6 +161,7 @@ class AccessoriesController extends Controller { $this->authorize('view', Accessory::class); $accessory = Accessory::findOrFail($id); + return (new AccessoriesTransformer)->transformAccessory($accessory); } @@ -175,7 +179,7 @@ class AccessoriesController extends Controller $this->authorize('view', Accessory::class); $accessory = Accessory::with('lastCheckout')->findOrFail($id); - if (!Company::isCurrentUserHasAccess($accessory)) { + if (! Company::isCurrentUserHasAccess($accessory)) { return ['total' => 0, 'rows' => []]; } @@ -185,7 +189,7 @@ class AccessoriesController extends Controller $accessory_users = $accessory->users; $total = $accessory_users->count(); - if($total < $offset){ + if ($total < $offset) { $offset = 0; } @@ -245,12 +249,12 @@ class AccessoriesController extends Controller $this->authorize($accessory); if ($accessory->hasUsers() > 0) { - return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/accessories/message.assoc_users', array('count'=> $accessory->hasUsers())))); + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/accessories/message.assoc_users', ['count'=> $accessory->hasUsers()]))); } $accessory->delete(); - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/accessories/message.delete.success'))); + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/accessories/message.delete.success'))); } @@ -276,7 +280,7 @@ class AccessoriesController extends Controller if ($accessory->numRemaining() > 0) { - if (!$user = User::find($request->input('assigned_to'))) { + if (! $user = User::find($request->input('assigned_to'))) { return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/accessories/message.checkout.user_does_not_exist'))); } @@ -288,12 +292,12 @@ class AccessoriesController extends Controller 'created_at' => Carbon::now(), 'user_id' => Auth::id(), 'assigned_to' => $request->get('assigned_to'), - 'note' => $request->get('note') + 'note' => $request->get('note'), ]); $accessory->logCheckout($request->input('note'), $user); - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/accessories/message.checkout.success'))); + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/accessories/message.checkout.success'))); } return response()->json(Helper::formatStandardApiResponse('error', null, 'No accessories remaining')); @@ -306,7 +310,7 @@ class AccessoriesController extends Controller * @uses Accessory::checkin_email() to determine if an email can and should be sent * @author [A. Gianotto] [] * @param Request $request - * @param integer $accessoryUserId + * @param int $accessoryUserId * @param string $backto * @return Redirect * @internal param int $accessoryId @@ -324,7 +328,7 @@ class AccessoriesController extends Controller // Was the accessory updated? if (DB::table('accessories_users')->where('id', '=', $accessory_user->id)->delete()) { - if (!is_null($accessory_user->assigned_to)) { + if (! is_null($accessory_user->assigned_to)) { $user = User::find($accessory_user->assigned_to); } @@ -339,7 +343,7 @@ class AccessoriesController extends Controller return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/accessories/message.checkin.success'))); } - return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/accessories/message.checkin.error'))); + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/accessories/message.checkin.error'))); } @@ -355,7 +359,7 @@ class AccessoriesController extends Controller $accessories = Accessory::select([ 'accessories.id', - 'accessories.name' + 'accessories.name', ]); if ($request->filled('search')) { @@ -364,10 +368,7 @@ class AccessoriesController extends Controller $accessories = $accessories->orderBy('name', 'ASC')->paginate(50); - return (new SelectlistTransformer)->transformSelectlist($accessories); } - - } diff --git a/app/Http/Controllers/Api/AssetMaintenancesController.php b/app/Http/Controllers/Api/AssetMaintenancesController.php index 519c7c0737..2d694df021 100644 --- a/app/Http/Controllers/Api/AssetMaintenancesController.php +++ b/app/Http/Controllers/Api/AssetMaintenancesController.php @@ -1,4 +1,5 @@ * @version v1.0 * @since [v1.8] - * @return String JSON + * @return string JSON */ public function index(Request $request) { - $maintenances = AssetMaintenance::with('asset', 'asset.model','asset.location', 'supplier', 'asset.company', 'admin'); + $maintenances = AssetMaintenance::with('asset', 'asset.model', 'asset.location', 'supplier', 'asset.company', 'admin'); if ($request->filled('search')) { $maintenances = $maintenances->TextSearch($request->input('search')); @@ -50,7 +49,6 @@ class AssetMaintenancesController extends Controller // Check to make sure the limit is not higher than the max allowed ((config('app.max_results') >= $request->input('limit')) && ($request->filled('limit'))) ? $limit = $request->input('limit') : $limit = config('app.max_results'); - $allowed_columns = [ 'id', 'title', @@ -62,7 +60,7 @@ class AssetMaintenancesController extends Controller 'notes', 'asset_tag', 'asset_name', - 'user_id' + 'user_id', ]; $order = $request->input('order') === 'asc' ? 'asc' : 'desc'; $sort = in_array($request->input('sort'), $allowed_columns) ? e($request->input('sort')) : 'created_at'; @@ -84,12 +82,10 @@ class AssetMaintenancesController extends Controller $total = $maintenances->count(); $maintenances = $maintenances->skip($offset)->take($limit)->get(); + return (new AssetMaintenancesTransformer())->transformAssetMaintenances($maintenances, $total); - - } - /** * Validates and stores the new asset maintenance * @@ -97,7 +93,7 @@ class AssetMaintenancesController extends Controller * @author Vincent Sposato * @version v1.0 * @since [v1.8] - * @return String JSON + * @return string JSON */ public function store(Request $request) { @@ -105,42 +101,39 @@ class AssetMaintenancesController extends Controller $assetMaintenance = new AssetMaintenance(); $assetMaintenance->supplier_id = $request->input('supplier_id'); $assetMaintenance->is_warranty = $request->input('is_warranty'); - $assetMaintenance->cost = e($request->input('cost')); + $assetMaintenance->cost = e($request->input('cost')); $assetMaintenance->notes = e($request->input('notes')); $asset = Asset::find(e($request->input('asset_id'))); - if (!Company::isCurrentUserHasAccess($asset)) { + if (! Company::isCurrentUserHasAccess($asset)) { return response()->json(Helper::formatStandardApiResponse('error', null, 'You cannot add a maintenance for that asset')); } // Save the asset maintenance data - $assetMaintenance->asset_id = $request->input('asset_id'); + $assetMaintenance->asset_id = $request->input('asset_id'); $assetMaintenance->asset_maintenance_type = $request->input('asset_maintenance_type'); - $assetMaintenance->title = $request->input('title'); - $assetMaintenance->start_date = $request->input('start_date'); - $assetMaintenance->completion_date = $request->input('completion_date'); - $assetMaintenance->user_id = Auth::id(); + $assetMaintenance->title = $request->input('title'); + $assetMaintenance->start_date = $request->input('start_date'); + $assetMaintenance->completion_date = $request->input('completion_date'); + $assetMaintenance->user_id = Auth::id(); - if (( $assetMaintenance->completion_date !== null ) - && ( $assetMaintenance->start_date !== "" ) - && ( $assetMaintenance->start_date !== "0000-00-00" ) + if (($assetMaintenance->completion_date !== null) + && ($assetMaintenance->start_date !== '') + && ($assetMaintenance->start_date !== '0000-00-00') ) { - $startDate = Carbon::parse($assetMaintenance->start_date); - $completionDate = Carbon::parse($assetMaintenance->completion_date); + $startDate = Carbon::parse($assetMaintenance->start_date); + $completionDate = Carbon::parse($assetMaintenance->completion_date); $assetMaintenance->asset_maintenance_time = $completionDate->diffInDays($startDate); } // Was the asset maintenance created? if ($assetMaintenance->save()) { return response()->json(Helper::formatStandardApiResponse('success', $assetMaintenance, trans('admin/asset_maintenances/message.create.success'))); - } return response()->json(Helper::formatStandardApiResponse('error', null, $assetMaintenance->getErrors())); - } - /** * Validates and stores an update to an asset maintenance * @@ -149,59 +142,58 @@ class AssetMaintenancesController extends Controller * @param int $request * @version v1.0 * @since [v4.0] - * @return String JSON + * @return string JSON */ public function update(Request $request, $assetMaintenanceId = null) { // Check if the asset maintenance exists $assetMaintenance = AssetMaintenance::findOrFail($assetMaintenanceId); - if (!Company::isCurrentUserHasAccess($assetMaintenance->asset)) { + if (! Company::isCurrentUserHasAccess($assetMaintenance->asset)) { return response()->json(Helper::formatStandardApiResponse('error', null, 'You cannot edit a maintenance for that asset')); } $assetMaintenance->supplier_id = e($request->input('supplier_id')); $assetMaintenance->is_warranty = e($request->input('is_warranty')); - $assetMaintenance->cost = Helper::ParseFloat(e($request->input('cost'))); + $assetMaintenance->cost = Helper::ParseFloat(e($request->input('cost'))); $assetMaintenance->notes = e($request->input('notes')); $asset = Asset::find(request('asset_id')); - if (!Company::isCurrentUserHasAccess($asset)) { + if (! Company::isCurrentUserHasAccess($asset)) { return response()->json(Helper::formatStandardApiResponse('error', null, 'You cannot edit a maintenance for that asset')); } // Save the asset maintenance data - $assetMaintenance->asset_id = $request->input('asset_id'); + $assetMaintenance->asset_id = $request->input('asset_id'); $assetMaintenance->asset_maintenance_type = $request->input('asset_maintenance_type'); - $assetMaintenance->title = $request->input('title'); - $assetMaintenance->start_date = $request->input('start_date'); - $assetMaintenance->completion_date = $request->input('completion_date'); + $assetMaintenance->title = $request->input('title'); + $assetMaintenance->start_date = $request->input('start_date'); + $assetMaintenance->completion_date = $request->input('completion_date'); - if (( $assetMaintenance->completion_date == null ) + if (($assetMaintenance->completion_date == null) ) { - if (( $assetMaintenance->asset_maintenance_time !== 0 ) - || ( !is_null($assetMaintenance->asset_maintenance_time) ) + if (($assetMaintenance->asset_maintenance_time !== 0) + || (! is_null($assetMaintenance->asset_maintenance_time)) ) { $assetMaintenance->asset_maintenance_time = null; } } - if (( $assetMaintenance->completion_date !== null ) - && ( $assetMaintenance->start_date !== "" ) - && ( $assetMaintenance->start_date !== "0000-00-00" ) + if (($assetMaintenance->completion_date !== null) + && ($assetMaintenance->start_date !== '') + && ($assetMaintenance->start_date !== '0000-00-00') ) { - $startDate = Carbon::parse($assetMaintenance->start_date); - $completionDate = Carbon::parse($assetMaintenance->completion_date); + $startDate = Carbon::parse($assetMaintenance->start_date); + $completionDate = Carbon::parse($assetMaintenance->completion_date); $assetMaintenance->asset_maintenance_time = $completionDate->diffInDays($startDate); } // Was the asset maintenance created? if ($assetMaintenance->save()) { - return response()->json(Helper::formatStandardApiResponse('success', $assetMaintenance, trans('admin/asset_maintenances/message.edit.success'))); - } + return response()->json(Helper::formatStandardApiResponse('error', null, $assetMaintenance->getErrors())); } @@ -212,22 +204,20 @@ class AssetMaintenancesController extends Controller * @param int $assetMaintenanceId * @version v1.0 * @since [v4.0] - * @return String JSON + * @return string JSON */ public function destroy($assetMaintenanceId) { // Check if the asset maintenance exists $assetMaintenance = AssetMaintenance::findOrFail($assetMaintenanceId); - if (!Company::isCurrentUserHasAccess($assetMaintenance->asset)) { + if (! Company::isCurrentUserHasAccess($assetMaintenance->asset)) { return response()->json(Helper::formatStandardApiResponse('error', null, 'You cannot delete a maintenance for that asset')); } $assetMaintenance->delete(); return response()->json(Helper::formatStandardApiResponse('success', $assetMaintenance, trans('admin/asset_maintenances/message.delete.success'))); - - } /** @@ -237,15 +227,15 @@ class AssetMaintenancesController extends Controller * @param int $assetMaintenanceId * @version v1.0 * @since [v4.0] - * @return String JSON + * @return string JSON */ public function show($assetMaintenanceId) { $assetMaintenance = AssetMaintenance::findOrFail($assetMaintenanceId); - if (!Company::isCurrentUserHasAccess($assetMaintenance->asset)) { + if (! Company::isCurrentUserHasAccess($assetMaintenance->asset)) { return response()->json(Helper::formatStandardApiResponse('error', null, 'You cannot view a maintenance for that asset')); } - return (new AssetMaintenancesTransformer())->transformAssetMaintenance($assetMaintenance); + return (new AssetMaintenancesTransformer())->transformAssetMaintenance($assetMaintenance); } } diff --git a/app/Http/Controllers/Api/AssetModelsController.php b/app/Http/Controllers/Api/AssetModelsController.php index 9bc3e46cfe..82e792d559 100644 --- a/app/Http/Controllers/Api/AssetModelsController.php +++ b/app/Http/Controllers/Api/AssetModelsController.php @@ -1,4 +1,5 @@ with('category','depreciation', 'manufacturer','fieldset') + ->with('category', 'depreciation', 'manufacturer', 'fieldset') ->withCount('assets as assets_count'); - - if ($request->filled('status')) { $assetmodels->onlyTrashed(); } @@ -99,10 +98,10 @@ class AssetModelsController extends Controller $total = $assetmodels->count(); $assetmodels = $assetmodels->skip($offset)->take($limit)->get(); + return (new AssetModelsTransformer)->transformAssetModels($assetmodels, $total); } - /** * Store a newly created resource in storage. * @@ -121,8 +120,8 @@ class AssetModelsController extends Controller if ($assetmodel->save()) { return response()->json(Helper::formatStandardApiResponse('success', $assetmodel, trans('admin/models/message.create.success'))); } - return response()->json(Helper::formatStandardApiResponse('error', null, $assetmodel->getErrors())); + return response()->json(Helper::formatStandardApiResponse('error', null, $assetmodel->getErrors())); } /** @@ -137,6 +136,7 @@ class AssetModelsController extends Controller { $this->authorize('view', AssetModel::class); $assetmodel = AssetModel::withCount('assets as assets_count')->findOrFail($id); + return (new AssetModelsTransformer)->transformAssetModel($assetmodel); } @@ -151,11 +151,11 @@ class AssetModelsController extends Controller public function assets($id) { $this->authorize('view', AssetModel::class); - $assets = Asset::where('model_id','=',$id)->get(); + $assets = Asset::where('model_id', '=', $id)->get(); + return (new AssetsTransformer)->transformAssets($assets, $assets->count()); } - /** * Update the specified resource in storage. * @@ -181,10 +181,9 @@ class AssetModelsController extends Controller * it, but I'll be damned if I can think of one. - snipe */ if ($request->filled('custom_fieldset_id')) { - $assetmodel->fieldset_id = $request->get("custom_fieldset_id"); + $assetmodel->fieldset_id = $request->get('custom_fieldset_id'); } - if ($assetmodel->save()) { return response()->json(Helper::formatStandardApiResponse('success', $assetmodel, trans('admin/models/message.update.success'))); } @@ -207,11 +206,11 @@ class AssetModelsController extends Controller $this->authorize('delete', $assetmodel); if ($assetmodel->assets()->count() > 0) { - return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/models/message.assoc_users'))); + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/models/message.assoc_users'))); } if ($assetmodel->image) { - try { + try { Storage::disk('public')->delete('assetmodels/'.$assetmodel->image); } catch (\Exception $e) { \Log::info($e); @@ -219,8 +218,8 @@ class AssetModelsController extends Controller } $assetmodel->delete(); - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/models/message.delete.success'))); + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/models/message.delete.success'))); } /** @@ -229,11 +228,9 @@ class AssetModelsController extends Controller * @author [A. Gianotto] [] * @since [v4.0.16] * @see \App\Http\Transformers\SelectlistTransformer - * */ public function selectlist(Request $request) { - $assetmodels = AssetModel::select([ 'models.id', 'models.name', @@ -241,7 +238,7 @@ class AssetModelsController extends Controller 'models.model_number', 'models.manufacturer_id', 'models.category_id', - ])->with('manufacturer','category'); + ])->with('manufacturer', 'category'); $settings = \App\Models\Setting::getSettings(); @@ -252,7 +249,6 @@ class AssetModelsController extends Controller $assetmodels = $assetmodels->OrderCategory('ASC')->OrderManufacturer('ASC')->orderby('models.name', 'asc')->orderby('models.model_number', 'asc')->paginate(50); foreach ($assetmodels as $assetmodel) { - $assetmodel->use_text = ''; if ($settings->modellistCheckedValue('category')) { @@ -263,10 +259,10 @@ class AssetModelsController extends Controller $assetmodel->use_text .= (($assetmodel->manufacturer) ? $assetmodel->manufacturer->name.' ' : ''); } - $assetmodel->use_text .= $assetmodel->name; + $assetmodel->use_text .= $assetmodel->name; - if (($settings->modellistCheckedValue('model_number')) && ($assetmodel->model_number!='')) { - $assetmodel->use_text .= ' (#'.$assetmodel->model_number.')'; + if (($settings->modellistCheckedValue('model_number')) && ($assetmodel->model_number != '')) { + $assetmodel->use_text .= ' (#'.$assetmodel->model_number.')'; } $assetmodel->use_image = ($settings->modellistCheckedValue('image') && ($assetmodel->image)) ? Storage::disk('public')->url('models/'.e($assetmodel->image)) : null; @@ -274,5 +270,4 @@ class AssetModelsController extends Controller return (new SelectlistTransformer)->transformSelectlist($assetmodels); } - } diff --git a/app/Http/Controllers/Api/AssetsController.php b/app/Http/Controllers/Api/AssetsController.php index 7a333e7086..f03f242a50 100644 --- a/app/Http/Controllers/Api/AssetsController.php +++ b/app/Http/Controllers/Api/AssetsController.php @@ -1,4 +1,5 @@ filled('filter')) { $filter = json_decode($request->input('filter'), true); @@ -111,13 +111,12 @@ class AssetsController extends Controller $all_custom_fields = CustomField::all(); //used as a 'cache' of custom fields throughout this page load foreach ($all_custom_fields as $field) { - $allowed_columns[]=$field->db_column_name(); + $allowed_columns[] = $field->db_column_name(); } - $assets = Company::scopeCompanyables(Asset::select('assets.*'),"company_id","assets") + $assets = Company::scopeCompanyables(Asset::select('assets.*'), 'company_id', 'assets') ->with('location', 'assetstatus', 'assetlog', 'company', 'defaultLoc','assignedTo', - 'model.category', 'model.manufacturer', 'model.fieldset','supplier'); - + 'model.category', 'model.manufacturer', 'model.fieldset', 'supplier'); // These are used by the API to query against specific ID numbers. // They are also used by the individual searches on detail pages like @@ -126,7 +125,7 @@ class AssetsController extends Controller $assets->where('assets.status_id', '=', $request->input('status_id')); } - if ($request->input('requestable')=='true') { + if ($request->input('requestable') == 'true') { $assets->where('assets.requestable', '=', '1'); } @@ -173,7 +172,6 @@ class AssetsController extends Controller // case we override with the actual count, so we should return 0 items. $offset = (($assets) && ($request->get('offset') > $assets->count())) ? $assets->count() : $request->get('offset', 0); - // Check to make sure the limit is not higher than the max allowed ((config('app.max_results') >= $request->input('limit')) && ($request->filled('limit'))) ? $limit = $request->input('limit') : $limit = config('app.max_results'); @@ -181,7 +179,6 @@ class AssetsController extends Controller // This is used by the audit reporting routes if (Gate::allows('audit', Asset::class)) { - switch ($audit) { case 'due': $assets->DueOrOverdueForAudit($settings); @@ -192,8 +189,6 @@ class AssetsController extends Controller } } - - // This is used by the sidenav, mostly // We switched from using query scopes here because of a Laravel bug @@ -204,19 +199,19 @@ class AssetsController extends Controller $assets->onlyTrashed(); break; case 'Pending': - $assets->join('status_labels AS status_alias',function ($join) { - $join->on('status_alias.id', "=", "assets.status_id") - ->where('status_alias.deployable','=',0) - ->where('status_alias.pending','=',1) + $assets->join('status_labels AS status_alias', function ($join) { + $join->on('status_alias.id', '=', 'assets.status_id') + ->where('status_alias.deployable', '=', 0) + ->where('status_alias.pending', '=', 1) ->where('status_alias.archived', '=', 0); }); break; case 'RTD': $assets->whereNull('assets.assigned_to') - ->join('status_labels AS status_alias',function ($join) { - $join->on('status_alias.id', "=", "assets.status_id") - ->where('status_alias.deployable','=',1) - ->where('status_alias.pending','=',0) + ->join('status_labels AS status_alias', function ($join) { + $join->on('status_alias.id', '=', 'assets.status_id') + ->where('status_alias.deployable', '=', 1) + ->where('status_alias.pending', '=', 0) ->where('status_alias.archived', '=', 0); }); break; @@ -224,19 +219,19 @@ class AssetsController extends Controller $assets->Undeployable(); break; case 'Archived': - $assets->join('status_labels AS status_alias',function ($join) { - $join->on('status_alias.id', "=", "assets.status_id") - ->where('status_alias.deployable','=',0) - ->where('status_alias.pending','=',0) + $assets->join('status_labels AS status_alias', function ($join) { + $join->on('status_alias.id', '=', 'assets.status_id') + ->where('status_alias.deployable', '=', 0) + ->where('status_alias.pending', '=', 0) ->where('status_alias.archived', '=', 1); }); break; case 'Requestable': $assets->where('assets.requestable', '=', 1) - ->join('status_labels AS status_alias',function ($join) { - $join->on('status_alias.id', "=", "assets.status_id") - ->where('status_alias.deployable','=',1) - ->where('status_alias.pending','=',0) + ->join('status_labels AS status_alias', function ($join) { + $join->on('status_alias.id', '=', 'assets.status_id') + ->where('status_alias.deployable', '=', 1) + ->where('status_alias.pending', '=', 0) ->where('status_alias.archived', '=', 0); }); @@ -247,24 +242,24 @@ class AssetsController extends Controller break; default: - if ((!$request->filled('status_id')) && ($settings->show_archived_in_list!='1')) { + if ((! $request->filled('status_id')) && ($settings->show_archived_in_list != '1')) { // terrible workaround for complex-query Laravel bug in fulltext - $assets->join('status_labels AS status_alias',function ($join) { - $join->on('status_alias.id', "=", "assets.status_id") + $assets->join('status_labels AS status_alias', function ($join) { + $join->on('status_alias.id', '=', 'assets.status_id') ->where('status_alias.archived', '=', 0); }); // If there is a status ID, don't take show_archived_in_list into consideration } else { - $assets->join('status_labels AS status_alias',function ($join) { - $join->on('status_alias.id', "=", "assets.status_id"); + $assets->join('status_labels AS status_alias', function ($join) { + $join->on('status_alias.id', '=', 'assets.status_id'); }); } } - if ((!is_null($filter)) && (count($filter)) > 0) { + if ((! is_null($filter)) && (count($filter)) > 0) { $assets->ByFilter($filter); } elseif ($request->filled('search')) { $assets->TextSearch($request->input('search')); @@ -274,7 +269,7 @@ class AssetsController extends Controller // This is kinda gross, but we need to do this because the Bootstrap Tables // API passes custom field ordering as custom_fields.fieldname, and we have to strip // that out to let the default sorter below order them correctly on the assets table. - $sort_override = str_replace('custom_fields.','', $request->input('sort')) ; + $sort_override = str_replace('custom_fields.', '', $request->input('sort')); // This handles all of the pivot sorting (versus the assets.* fields // in the allowed_columns array) @@ -327,7 +322,6 @@ class AssetsController extends Controller return (new $transformer)->transformAssets($assets, $total); } - /** * Returns JSON with information about an asset (by tag) for detail view. * @@ -338,12 +332,13 @@ class AssetsController extends Controller */ public function showByTag($tag) { - if ($asset = Asset::with('assetstatus')->with('assignedTo')->where('asset_tag',$tag)->first()) { + if ($asset = Asset::with('assetstatus')->with('assignedTo')->where('asset_tag', $tag)->first()) { $this->authorize('view', $asset); + return (new AssetsTransformer)->transformAsset($asset); } - return response()->json(Helper::formatStandardApiResponse('error', null, 'Asset not found'), 200); + return response()->json(Helper::formatStandardApiResponse('error', null, 'Asset not found'), 200); } /** @@ -358,11 +353,11 @@ class AssetsController extends Controller { $this->authorize('index', Asset::class); if ($assets = Asset::with('assetstatus')->with('assignedTo') - ->withTrashed()->where('serial',$serial)->get()) { + ->withTrashed()->where('serial', $serial)->get()) { return (new AssetsTransformer)->transformAssets($assets, $assets->count()); } - return response()->json(Helper::formatStandardApiResponse('error', null, 'Asset not found'), 200); + return response()->json(Helper::formatStandardApiResponse('error', null, 'Asset not found'), 200); } @@ -379,17 +374,20 @@ class AssetsController extends Controller if ($asset = Asset::with('assetstatus')->with('assignedTo')->withTrashed() ->withCount('checkins as checkins_count', 'checkouts as checkouts_count', 'userRequests as user_requests_count')->findOrFail($id)) { $this->authorize('view', $asset); + return (new AssetsTransformer)->transformAsset($asset); } } + public function licenses($id) { $this->authorize('view', Asset::class); $this->authorize('view', License::class); $asset = Asset::where('id', $id)->withTrashed()->first(); $licenses = $asset->licenses()->get(); + return (new LicensesTransformer())->transformLicenses($licenses, $licenses->count()); } @@ -412,7 +410,7 @@ class AssetsController extends Controller 'assets.model_id', 'assets.assigned_to', 'assets.assigned_type', - 'assets.status_id' + 'assets.status_id', ])->with('model', 'assetstatus', 'assignedTo')->NotArchived(), 'company_id', 'assets'); if ($request->filled('assetStatusType') && $request->input('assetStatusType') === 'RTD') { @@ -439,18 +437,16 @@ class AssetsController extends Controller } - if ($asset->assetstatus->getStatuslabelType()=='pending') { - $asset->use_text .= '('.$asset->assetstatus->getStatuslabelType().')'; + if ($asset->assetstatus->getStatuslabelType() == 'pending') { + $asset->use_text .= '('.$asset->assetstatus->getStatuslabelType().')'; } $asset->use_image = ($asset->getImageUrl()) ? $asset->getImageUrl() : null; } return (new SelectlistTransformer)->transformSelectlist($assets); - } - /** * Accepts a POST request to create a new asset * @@ -461,32 +457,31 @@ class AssetsController extends Controller */ public function store(ImageUploadRequest $request) { - $this->authorize('create', Asset::class); $asset = new Asset(); $asset->model()->associate(AssetModel::find((int) $request->get('model_id'))); - $asset->name = $request->get('name'); - $asset->serial = $request->get('serial'); - $asset->company_id = Company::getIdForCurrentUser($request->get('company_id')); - $asset->model_id = $request->get('model_id'); - $asset->order_number = $request->get('order_number'); - $asset->notes = $request->get('notes'); - $asset->asset_tag = $request->get('asset_tag', Asset::autoincrement_asset()); - $asset->user_id = Auth::id(); - $asset->archived = '0'; - $asset->physical = '1'; - $asset->depreciate = '0'; - $asset->status_id = $request->get('status_id', 0); - $asset->warranty_months = $request->get('warranty_months', null); - $asset->purchase_cost = Helper::ParseFloat($request->get('purchase_cost')); - $asset->purchase_date = $request->get('purchase_date', null); - $asset->assigned_to = $request->get('assigned_to', null); - $asset->supplier_id = $request->get('supplier_id', 0); - $asset->requestable = $request->get('requestable', 0); - $asset->rtd_location_id = $request->get('rtd_location_id', null); - $asset->location_id = $request->get('rtd_location_id', null); + $asset->name = $request->get('name'); + $asset->serial = $request->get('serial'); + $asset->company_id = Company::getIdForCurrentUser($request->get('company_id')); + $asset->model_id = $request->get('model_id'); + $asset->order_number = $request->get('order_number'); + $asset->notes = $request->get('notes'); + $asset->asset_tag = $request->get('asset_tag', Asset::autoincrement_asset()); + $asset->user_id = Auth::id(); + $asset->archived = '0'; + $asset->physical = '1'; + $asset->depreciate = '0'; + $asset->status_id = $request->get('status_id', 0); + $asset->warranty_months = $request->get('warranty_months', null); + $asset->purchase_cost = Helper::ParseFloat($request->get('purchase_cost')); + $asset->purchase_date = $request->get('purchase_date', null); + $asset->assigned_to = $request->get('assigned_to', null); + $asset->supplier_id = $request->get('supplier_id', 0); + $asset->requestable = $request->get('requestable', 0); + $asset->rtd_location_id = $request->get('rtd_location_id', null); + $asset->location_id = $request->get('rtd_location_id', null); /** * this is here just legacy reasons. Api\AssetController @@ -516,13 +511,12 @@ class AssetsController extends Controller // if the field is set to encrypted, make sure we encrypt the value if ($field->field_encrypted == '1') { - \Log::debug('This model field is encrypted in this fieldset.'); if (Gate::allows('admin')) { // If input value is null, use custom field's default value - if (($field_val == null) && ($request->has('model_id')!='')){ + if (($field_val == null) && ($request->has('model_id') != '')) { $field_val = \Crypt::encrypt($field->defaultValue($request->get('model_id'))); } else { $field_val = \Crypt::encrypt($request->input($field->convertUnicodeDbSlug())); @@ -532,12 +526,10 @@ class AssetsController extends Controller $asset->{$field->convertUnicodeDbSlug()} = $field_val; - } } if ($asset->save()) { - if ($request->get('assigned_user')) { $target = User::find(request('assigned_user')); } elseif ($request->get('assigned_asset')) { @@ -559,7 +551,6 @@ class AssetsController extends Controller return response()->json(Helper::formatStandardApiResponse('error', null, $asset->getErrors()), 200); } - /** * Accepts a POST request to update an asset * @@ -599,7 +590,7 @@ class AssetsController extends Controller if (($model = AssetModel::find($asset->model_id)) && (isset($model->fieldset))) { foreach ($model->fieldset->fields as $field) { if ($request->has($field->convertUnicodeDbSlug())) { - if ($field->field_encrypted=='1') { + if ($field->field_encrypted == '1') { if (Gate::allows('admin')) { $asset->{$field->convertUnicodeDbSlug()} = \Crypt::encrypt($request->input($field->convertUnicodeDbSlug())); } @@ -612,15 +603,13 @@ class AssetsController extends Controller if ($asset->save()) { - if (($request->filled('assigned_user')) && ($target = User::find($request->get('assigned_user')))) { $location = $target->location_id; } elseif (($request->filled('assigned_asset')) && ($target = Asset::find($request->get('assigned_asset')))) { $location = $target->location_id; - Asset::where('assigned_type', '\\App\\Models\\Asset')->where('assigned_to', $id) + Asset::where('assigned_type', \App\Models\Asset::class)->where('assigned_to', $id) ->update(['location_id' => $target->location_id]); - } elseif (($request->filled('assigned_location')) && ($target = Location::find($request->get('assigned_location')))) { $location = $target->id; } @@ -635,8 +624,10 @@ class AssetsController extends Controller return response()->json(Helper::formatStandardApiResponse('success', $asset, trans('admin/hardware/message.update.success'))); } + return response()->json(Helper::formatStandardApiResponse('error', null, $asset->getErrors()), 200); } + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.does_not_exist')), 200); } @@ -654,12 +645,11 @@ class AssetsController extends Controller $this->authorize('delete', Asset::class); if ($asset = Asset::find($id)) { - $this->authorize('delete', $asset); DB::table('assets') ->where('id', $asset->id) - ->update(array('assigned_to' => null)); + ->update(['assigned_to' => null]); $asset->delete(); @@ -669,8 +659,6 @@ class AssetsController extends Controller return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.does_not_exist')), 200); } - - /** * Restore a soft-deleted asset. * @@ -717,7 +705,7 @@ class AssetsController extends Controller $this->authorize('checkout', Asset::class); $asset = Asset::findOrFail($asset_id); - if (!$asset->availableForCheckout()) { + if (! $asset->availableForCheckout()) { return response()->json(Helper::formatStandardApiResponse('error', ['asset'=> e($asset->asset_tag)], trans('admin/hardware/message.checkout.not_available'))); } @@ -731,21 +719,21 @@ class AssetsController extends Controller // This item is checked out to a location - if (request('checkout_to_type')=='location') { + if (request('checkout_to_type') == 'location') { $target = Location::find(request('assigned_location')); $asset->location_id = ($target) ? $target->id : ''; $error_payload['target_id'] = $request->input('assigned_location'); $error_payload['target_type'] = 'location'; - } elseif (request('checkout_to_type')=='asset') { - $target = Asset::where('id','!=',$asset_id)->find(request('assigned_asset')); + } elseif (request('checkout_to_type') == 'asset') { + $target = Asset::where('id', '!=', $asset_id)->find(request('assigned_asset')); $asset->location_id = $target->rtd_location_id; // Override with the asset's location_id if it has one $asset->location_id = (($target) && (isset($target->location_id))) ? $target->location_id : ''; $error_payload['target_id'] = $request->input('assigned_asset'); $error_payload['target_type'] = 'asset'; - } elseif (request('checkout_to_type')=='user') { + } elseif (request('checkout_to_type') == 'user') { // Fetch the target and set the asset's new location_id $target = User::find(request('assigned_user')); $asset->location_id = (($target) && (isset($target->location_id))) ? $target->location_id : ''; @@ -755,13 +743,13 @@ class AssetsController extends Controller - if (!isset($target)) { + if (! isset($target)) { return response()->json(Helper::formatStandardApiResponse('error', $error_payload, 'Checkout target for asset '.e($asset->asset_tag).' is invalid - '.$error_payload['target_type'].' does not exist.')); } - $checkout_at = request('checkout_at', date("Y-m-d H:i:s")); + $checkout_at = request('checkout_at', date('Y-m-d H:i:s')); $expected_checkin = request('expected_checkin', null); $note = request('note', null); $asset_name = request('name', null); @@ -815,14 +803,14 @@ class AssetsController extends Controller $asset->name = $request->input('name'); } - $asset->location_id = $asset->rtd_location_id; + $asset->location_id = $asset->rtd_location_id; if ($request->filled('location_id')) { - $asset->location_id = $request->input('location_id'); + $asset->location_id = $request->input('location_id'); } if ($request->has('status_id')) { - $asset->status_id = $request->input('status_id'); + $asset->status_id = $request->input('status_id'); } if ($asset->save()) { @@ -843,15 +831,16 @@ class AssetsController extends Controller * @since [v4.0] * @return JsonResponse */ - public function audit(Request $request) { + public function audit(Request $request) + { $this->authorize('audit', Asset::class); - $rules = array( + $rules = [ 'asset_tag' => 'required', 'location_id' => 'exists:locations,id|nullable|numeric', - 'next_audit_date' => 'date|nullable' - ); + 'next_audit_date' => 'date|nullable', + ]; $validator = Validator::make($request->all(), $rules); if ($validator->fails()) { @@ -861,7 +850,7 @@ class AssetsController extends Controller $settings = Setting::getSettings(); $dt = Carbon::now()->addMonths($settings->audit_interval)->toDateString(); - $asset = Asset::where('asset_tag','=', $request->input('asset_tag'))->first(); + $asset = Asset::where('asset_tag', '=', $request->input('asset_tag'))->first(); if ($asset) { @@ -875,18 +864,19 @@ class AssetsController extends Controller // Check to see if they checked the box to update the physical location, // not just note it in the audit notes - if ($request->input('update_location')=='1') { + if ($request->input('update_location') == '1') { $asset->location_id = $request->input('location_id'); } $asset->last_audit_date = date('Y-m-d H:i:s'); if ($asset->save()) { - $log = $asset->logAudit(request('note'),request('location_id')); + $log = $asset->logAudit(request('note'), request('location_id')); + return response()->json(Helper::formatStandardApiResponse('success', [ 'asset_tag'=> e($asset->asset_tag), 'note'=> e($request->input('note')), - 'next_audit_date' => Helper::getFormattedDateObject($asset->next_audit_date) + 'next_audit_date' => Helper::getFormattedDateObject($asset->next_audit_date), ], trans('admin/hardware/message.audit.success'))); } } @@ -912,9 +902,9 @@ class AssetsController extends Controller { $this->authorize('viewRequestable', Asset::class); - $assets = Company::scopeCompanyables(Asset::select('assets.*'),"company_id","assets") + $assets = Company::scopeCompanyables(Asset::select('assets.*'), 'company_id', 'assets') ->with('location', 'assetstatus', 'assetlog', 'company', 'defaultLoc','assignedTo', - 'model.category', 'model.manufacturer', 'model.fieldset','supplier')->where('assets.requestable', '=', '1'); + 'model.category', 'model.manufacturer', 'model.fieldset', 'supplier')->where('assets.requestable', '=', '1'); $offset = request('offset', 0); $limit = $request->input('limit', 50); @@ -939,9 +929,9 @@ class AssetsController extends Controller break; } - $total = $assets->count(); $assets = $assets->skip($offset)->take($limit)->get(); + return (new AssetsTransformer)->transformRequestedAssets($assets, $total); } } diff --git a/app/Http/Controllers/Api/CategoriesController.php b/app/Http/Controllers/Api/CategoriesController.php index 9b4fa51349..b1e36b29e0 100644 --- a/app/Http/Controllers/Api/CategoriesController.php +++ b/app/Http/Controllers/Api/CategoriesController.php @@ -23,10 +23,10 @@ class CategoriesController extends Controller public function index(Request $request) { $this->authorize('view', Category::class); - $allowed_columns = ['id', 'name','category_type', 'category_type','use_default_eula','eula_text', 'require_acceptance','checkin_email', 'assets_count', 'accessories_count', 'consumables_count', 'components_count','licenses_count', 'image']; + $allowed_columns = ['id', 'name', 'category_type', 'category_type', 'use_default_eula', 'eula_text', 'require_acceptance', 'checkin_email', 'assets_count', 'accessories_count', 'consumables_count', 'components_count', 'licenses_count', 'image']; - $categories = Category::select(['id', 'created_at', 'updated_at', 'name','category_type','use_default_eula','eula_text', 'require_acceptance','checkin_email','image']) - ->withCount('assets as assets_count', 'accessories as accessories_count', 'consumables as consumables_count', 'components as components_count','licenses as licenses_count'); + $categories = Category::select(['id', 'created_at', 'updated_at', 'name', 'category_type', 'use_default_eula', 'eula_text', 'require_acceptance', 'checkin_email', 'image']) + ->withCount('assets as assets_count', 'accessories as accessories_count', 'consumables as consumables_count', 'components as components_count', 'licenses as licenses_count'); if ($request->filled('search')) { $categories = $categories->TextSearch($request->input('search')); @@ -45,11 +45,11 @@ class CategoriesController extends Controller $total = $categories->count(); $categories = $categories->skip($offset)->take($limit)->get(); + return (new CategoriesTransformer)->transformCategories($categories, $total); } - /** * Store a newly created resource in storage. * @@ -69,8 +69,8 @@ class CategoriesController extends Controller if ($category->save()) { return response()->json(Helper::formatStandardApiResponse('success', $category, trans('admin/categories/message.create.success'))); } - return response()->json(Helper::formatStandardApiResponse('error', null, $category->getErrors())); + return response()->json(Helper::formatStandardApiResponse('error', null, $category->getErrors())); } /** @@ -85,11 +85,10 @@ class CategoriesController extends Controller { $this->authorize('view', Category::class); $category = Category::findOrFail($id); + return (new CategoriesTransformer)->transformCategory($category); - } - /** * Update the specified resource in storage. * @@ -127,28 +126,25 @@ class CategoriesController extends Controller $this->authorize('delete', Category::class); $category = Category::findOrFail($id); - if (!$category->isDeletable()) { + if (! $category->isDeletable()) { return response()->json( - Helper::formatStandardApiResponse('error', null, trans('admin/categories/message.assoc_items', ['asset_type'=>$category->category_type])) + Helper::formatStandardApiResponse('error', null, trans('admin/categories/message.assoc_items', ['asset_type'=>$category->category_type])) ); } $category->delete(); - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/categories/message.delete.success'))); + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/categories/message.delete.success'))); } - /** * Gets a paginated collection for the select2 menus * * @author [A. Gianotto] [] * @since [v4.0.16] * @see \App\Http\Transformers\SelectlistTransformer - * */ public function selectlist(Request $request, $category_type = 'asset') { - $categories = Category::select([ 'id', 'name', @@ -169,7 +165,5 @@ class CategoriesController extends Controller } return (new SelectlistTransformer)->transformSelectlist($categories); - } - } diff --git a/app/Http/Controllers/Api/CompaniesController.php b/app/Http/Controllers/Api/CompaniesController.php index 8b471f27b3..6e53ad068e 100644 --- a/app/Http/Controllers/Api/CompaniesController.php +++ b/app/Http/Controllers/Api/CompaniesController.php @@ -37,7 +37,7 @@ class CompaniesController extends Controller 'components_count', ]; - $companies = Company::withCount('assets as assets_count','licenses as licenses_count','accessories as accessories_count','consumables as consumables_count','components as components_count','users as users_count'); + $companies = Company::withCount('assets as assets_count', 'licenses as licenses_count', 'accessories as accessories_count', 'consumables as consumables_count', 'components as components_count', 'users as users_count'); if ($request->filled('search')) { $companies->TextSearch($request->input('search')); @@ -56,11 +56,10 @@ class CompaniesController extends Controller $total = $companies->count(); $companies = $companies->skip($offset)->take($limit)->get(); + return (new CompaniesTransformer)->transformCompanies($companies, $total); - } - /** * Store a newly created resource in storage. * @@ -79,9 +78,9 @@ class CompaniesController extends Controller if ($company->save()) { return response()->json(Helper::formatStandardApiResponse('success', (new CompaniesTransformer)->transformCompany($company), trans('admin/companies/message.create.success'))); } + return response() ->json(Helper::formatStandardApiResponse('error', null, $company->getErrors())); - } /** @@ -96,11 +95,10 @@ class CompaniesController extends Controller { $this->authorize('view', Company::class); $company = Company::findOrFail($id); + return (new CompaniesTransformer)->transformCompany($company); - } - /** * Update the specified resource in storage. * @@ -140,13 +138,14 @@ class CompaniesController extends Controller $company = Company::findOrFail($id); $this->authorize('delete', $company); - if ( !$company->isDeletable() ) { + if (! $company->isDeletable()) { return response() - ->json(Helper::formatStandardApiResponse('error', null, trans('admin/companies/message.assoc_users'))); + ->json(Helper::formatStandardApiResponse('error', null, trans('admin/companies/message.assoc_users'))); } $company->delete(); + return response() - ->json(Helper::formatStandardApiResponse('success', null, trans('admin/companies/message.delete.success'))); + ->json(Helper::formatStandardApiResponse('success', null, trans('admin/companies/message.delete.success'))); } /** @@ -155,11 +154,9 @@ class CompaniesController extends Controller * @author [A. Gianotto] [] * @since [v4.0.16] * @see \App\Http\Transformers\SelectlistTransformer - * */ public function selectlist(Request $request) { - $companies = Company::select([ 'companies.id', 'companies.name', diff --git a/app/Http/Controllers/Api/ComponentsController.php b/app/Http/Controllers/Api/ComponentsController.php index ccd23570ed..b9712b2788 100644 --- a/app/Http/Controllers/Api/ComponentsController.php +++ b/app/Http/Controllers/Api/ComponentsController.php @@ -51,15 +51,15 @@ class ComponentsController extends Controller } if ($request->filled('company_id')) { - $components->where('company_id','=',$request->input('company_id')); + $components->where('company_id', '=', $request->input('company_id')); } if ($request->filled('category_id')) { - $components->where('category_id','=',$request->input('category_id')); + $components->where('category_id', '=', $request->input('category_id')); } if ($request->filled('location_id')) { - $components->where('location_id','=',$request->input('location_id')); + $components->where('location_id', '=', $request->input('location_id')); } // Set the offset to the API call's offset, unless the offset is higher than the actual count of items in which @@ -91,6 +91,7 @@ class ComponentsController extends Controller $total = $components->count(); $components = $components->skip($offset)->take($limit)->get(); + return (new ComponentsTransformer)->transformComponents($components, $total); } @@ -113,6 +114,7 @@ class ComponentsController extends Controller if ($component->save()) { return response()->json(Helper::formatStandardApiResponse('success', $component, trans('admin/components/message.create.success'))); } + return response()->json(Helper::formatStandardApiResponse('error', null, $component->getErrors())); } @@ -133,7 +135,6 @@ class ComponentsController extends Controller } } - /** * Update the specified resource in storage. * @@ -172,6 +173,7 @@ class ComponentsController extends Controller $component = Component::findOrFail($id); $this->authorize('delete', $component); $component->delete(); + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/components/message.delete.success'))); } @@ -195,6 +197,7 @@ class ComponentsController extends Controller $limit = $request->input('limit', 50); $total = $assets->count(); $assets = $assets->skip($offset)->take($limit)->get(); + return (new ComponentsTransformer)->transformCheckedoutComponents($assets, $total); } diff --git a/app/Http/Controllers/Api/ConsumablesController.php b/app/Http/Controllers/Api/ConsumablesController.php index 913bc1bd51..032cc402c0 100644 --- a/app/Http/Controllers/Api/ConsumablesController.php +++ b/app/Http/Controllers/Api/ConsumablesController.php @@ -55,11 +55,11 @@ class ConsumablesController extends Controller } if ($request->filled('company_id')) { - $consumables->where('company_id','=',$request->input('company_id')); + $consumables->where('company_id', '=', $request->input('company_id')); } if ($request->filled('category_id')) { - $consumables->where('category_id','=',$request->input('category_id')); + $consumables->where('category_id', '=', $request->input('category_id')); } if ($request->filled('model_number')) { @@ -67,7 +67,7 @@ class ConsumablesController extends Controller } if ($request->filled('manufacturer_id')) { - $consumables->where('manufacturer_id','=',$request->input('manufacturer_id')); + $consumables->where('manufacturer_id', '=', $request->input('manufacturer_id')); } if ($request->filled('location_id')) { @@ -82,7 +82,7 @@ class ConsumablesController extends Controller // Check to make sure the limit is not higher than the max allowed ((config('app.max_results') >= $request->input('limit')) && ($request->filled('limit'))) ? $limit = $request->input('limit') : $limit = config('app.max_results'); - + $allowed_columns = ['id', 'name', 'order_number', 'min_amt', 'purchase_date', 'purchase_cost', 'company', 'category', 'model_number', 'item_no', 'manufacturer', 'location', 'qty', 'image']; $order = $request->input('order') === 'asc' ? 'asc' : 'desc'; $sort_override = $request->input('sort'); @@ -107,15 +107,12 @@ class ConsumablesController extends Controller break; } - - $total = $consumables->count(); $consumables = $consumables->skip($offset)->take($limit)->get(); + return (new ConsumablesTransformer)->transformConsumables($consumables, $total); - } - /** * Store a newly created resource in storage. * @@ -134,6 +131,7 @@ class ConsumablesController extends Controller if ($consumable->save()) { return response()->json(Helper::formatStandardApiResponse('success', $consumable, trans('admin/consumables/message.create.success'))); } + return response()->json(Helper::formatStandardApiResponse('error', null, $consumable->getErrors())); } @@ -148,10 +146,10 @@ class ConsumablesController extends Controller { $this->authorize('view', Consumable::class); $consumable = Consumable::findOrFail($id); + return (new ConsumablesTransformer)->transformConsumable($consumable); } - /** * Update the specified resource in storage. * @@ -189,7 +187,8 @@ class ConsumablesController extends Controller $consumable = Consumable::findOrFail($id); $this->authorize('delete', $consumable); $consumable->delete(); - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/consumables/message.delete.success'))); + + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/consumables/message.delete.success'))); } /** @@ -203,21 +202,20 @@ class ConsumablesController extends Controller */ public function getDataView($consumableId) { - $consumable = Consumable::with(array('consumableAssignments'=> - function ($query) { + $consumable = Consumable::with(['consumableAssignments'=> function ($query) { $query->orderBy($query->getModel()->getTable().'.created_at', 'DESC'); }, 'consumableAssignments.admin'=> function ($query) { }, 'consumableAssignments.user'=> function ($query) { }, - ))->find($consumableId); + ])->find($consumableId); - if (!Company::isCurrentUserHasAccess($consumable)) { + if (! Company::isCurrentUserHasAccess($consumable)) { return ['total' => 0, 'rows' => []]; } $this->authorize('view', Consumable::class); - $rows = array(); + $rows = []; foreach ($consumable->consumableAssignments as $consumable_assignment) { $rows[] = [ @@ -228,7 +226,8 @@ class ConsumablesController extends Controller } $consumableCount = $consumable->users->count(); - $data = array('total' => $consumableCount, 'rows' => $rows); + $data = ['total' => $consumableCount, 'rows' => $rows]; + return $data; } @@ -264,7 +263,7 @@ class ConsumablesController extends Controller $consumable->users()->attach($consumable->id, [ 'consumable_id' => $consumable->id, 'user_id' => $user->id, - 'assigned_to' => $assigned_to + 'assigned_to' => $assigned_to, ]); // Log checkout event @@ -277,7 +276,7 @@ class ConsumablesController extends Controller $data['note'] = $logaction->note; $data['require_acceptance'] = $consumable->requireAcceptance(); - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/consumables/message.checkout.success'))); + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/consumables/message.checkout.success'))); } return response()->json(Helper::formatStandardApiResponse('error', null, 'No consumables remaining')); @@ -287,14 +286,12 @@ class ConsumablesController extends Controller * Gets a paginated collection for the select2 menus * * @see \App\Http\Transformers\SelectlistTransformer - * */ public function selectlist(Request $request) { - $consumables = Consumable::select([ 'consumables.id', - 'consumables.name' + 'consumables.name', ]); if ($request->filled('search')) { @@ -303,7 +300,6 @@ class ConsumablesController extends Controller $consumables = $consumables->orderBy('name', 'ASC')->paginate(50); - return (new SelectlistTransformer)->transformSelectlist($consumables); } } diff --git a/app/Http/Controllers/Api/CustomFieldsController.php b/app/Http/Controllers/Api/CustomFieldsController.php index c42e68b677..d137164956 100644 --- a/app/Http/Controllers/Api/CustomFieldsController.php +++ b/app/Http/Controllers/Api/CustomFieldsController.php @@ -18,26 +18,26 @@ class CustomFieldsController extends Controller * @author [Brady Wetherington] [] * @param int $id * @since [v3.0] - * @return Array + * @return array */ - public function index() { $this->authorize('index', CustomField::class); $fields = CustomField::get(); + return (new CustomFieldsTransformer)->transformCustomFields($fields, $fields->count()); } /** - * Shows the given field - * @author [V. Cordes] [] - * @param int $id - * @since [v4.1.10] - * @return View - */ + * Shows the given field + * @author [V. Cordes] [] + * @param int $id + * @since [v4.1.10] + * @return View + */ public function show($id) { - $this->authorize('view', CustomField::class); + $this->authorize('view', CustomField::class); if ($field = CustomField::find($id)) { return (new CustomFieldsTransformer)->transformCustomField($field); } @@ -45,7 +45,7 @@ class CustomFieldsController extends Controller return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/custom_fields/message.field.invalid')), 200); } - /** + /** * Update the specified field * * @author [V. Cordes] [] @@ -80,7 +80,6 @@ class CustomFieldsController extends Controller return response()->json(Helper::formatStandardApiResponse('error', null, $field->getErrors())); } - /** * Store a newly created field. * @@ -96,9 +95,9 @@ class CustomFieldsController extends Controller $data = $request->all(); $regex_format = null; - - if (str_contains($data["format"], "regex:")){ - $regex_format = $data["format"]; + + if (str_contains($data['format'], 'regex:')) { + $regex_format = $data['format']; } $validator = Validator::make($data, $field->validationRules($regex_format)); @@ -111,8 +110,8 @@ class CustomFieldsController extends Controller if ($field->save()) { return response()->json(Helper::formatStandardApiResponse('success', $field, trans('admin/custom_fields/message.field.create.success'))); } - return response()->json(Helper::formatStandardApiResponse('error', null, $field->getErrors())); + return response()->json(Helper::formatStandardApiResponse('error', null, $field->getErrors())); } public function postReorder(Request $request, $id) @@ -121,8 +120,8 @@ class CustomFieldsController extends Controller $this->authorize('update', $fieldset); - $fields = array(); - $order_array = array(); + $fields = []; + $order_array = []; $items = $request->input('item'); @@ -135,7 +134,6 @@ class CustomFieldsController extends Controller } return $fieldset->fields()->sync($fields); - } public function associate(Request $request, $field_id) @@ -152,7 +150,8 @@ class CustomFieldsController extends Controller } $fieldset = CustomFieldset::findOrFail($fieldset_id); - $fieldset->fields()->attach($field->id, ["required" => ($request->input('required') == "on"), "order" => $request->input('order', $fieldset->fields->count())]); + $fieldset->fields()->attach($field->id, ['required' => ($request->input('required') == 'on'), 'order' => $request->input('order', $fieldset->fields->count())]); + return response()->json(Helper::formatStandardApiResponse('success', $fieldset, trans('admin/custom_fields/message.fieldset.update.success'))); } @@ -166,10 +165,12 @@ class CustomFieldsController extends Controller foreach ($field->fieldset as $fieldset) { if ($fieldset->id == $fieldset_id) { $fieldset->fields()->detach($field->id); + return response()->json(Helper::formatStandardApiResponse('success', $fieldset, trans('admin/custom_fields/message.fieldset.update.success'))); } } $fieldset = CustomFieldset::findOrFail($fieldset_id); + return response()->json(Helper::formatStandardApiResponse('success', $fieldset, trans('admin/custom_fields/message.fieldset.update.success'))); } @@ -186,13 +187,12 @@ class CustomFieldsController extends Controller $this->authorize('delete', $field); - if ($field->fieldset->count() >0) { + if ($field->fieldset->count() > 0) { return response()->json(Helper::formatStandardApiResponse('error', null, 'Field is in use.')); } $field->delete(); - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/custom_fields/message.field.delete.success'))); + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/custom_fields/message.field.delete.success'))); } - } diff --git a/app/Http/Controllers/Api/CustomFieldsetsController.php b/app/Http/Controllers/Api/CustomFieldsetsController.php index 321959b9fd..18da1b67c2 100644 --- a/app/Http/Controllers/Api/CustomFieldsetsController.php +++ b/app/Http/Controllers/Api/CustomFieldsetsController.php @@ -1,4 +1,5 @@ ] * @author [Josh Gibson] */ - class CustomFieldsetsController extends Controller { - /** - * Shows the given fieldset and its fields - * @author [A. Gianotto] [] - * @author [Josh Gibson] - * @param int $id - * @since [v1.8] - * @return View - */ + * Shows the given fieldset and its fields + * @author [A. Gianotto] [] + * @author [Josh Gibson] + * @param int $id + * @since [v1.8] + * @return View + */ public function index() { $this->authorize('index', CustomFieldset::class); $fieldsets = CustomFieldset::withCount('fields as fields_count', 'models as models_count')->get(); - return (new CustomFieldsetsTransformer)->transformCustomFieldsets($fieldsets, $fieldsets->count()); + return (new CustomFieldsetsTransformer)->transformCustomFieldsets($fieldsets, $fieldsets->count()); } /** - * Shows the given fieldset and its fields - * @author [A. Gianotto] [] - * @author [Josh Gibson] - * @param int $id - * @since [v1.8] - * @return View - */ + * Shows the given fieldset and its fields + * @author [A. Gianotto] [] + * @author [Josh Gibson] + * @param int $id + * @since [v1.8] + * @return View + */ public function show($id) { - $this->authorize('view', CustomFieldset::class); + $this->authorize('view', CustomFieldset::class); if ($fieldset = CustomFieldset::find($id)) { return (new CustomFieldsetsTransformer)->transformCustomFieldset($fieldset); } return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/custom_fields/message.fieldset.does_not_exist')), 200); - } - - /** + /** * Update the specified resource in storage. * * @author [A. Gianotto] [] @@ -82,7 +79,6 @@ class CustomFieldsetsController extends Controller return response()->json(Helper::formatStandardApiResponse('error', null, $fieldset->getErrors())); } - /** * Store a newly created resource in storage. * @@ -100,11 +96,10 @@ class CustomFieldsetsController extends Controller if ($fieldset->save()) { return response()->json(Helper::formatStandardApiResponse('success', $fieldset, trans('admin/custom_fields/message.fieldset.create.success'))); } + return response()->json(Helper::formatStandardApiResponse('error', null, $fieldset->getErrors())); - } - /** * Delete a custom fieldset. * @@ -120,18 +115,15 @@ class CustomFieldsetsController extends Controller $modelsCount = $fieldset->models->count(); $fieldsCount = $fieldset->fields->count(); - if (($modelsCount > 0) || ($fieldsCount > 0) ){ + if (($modelsCount > 0) || ($fieldsCount > 0)) { return response()->json(Helper::formatStandardApiResponse('error', null, 'Fieldset is in use.')); } - if ($fieldset->delete()) { - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/custom_fields/message.fieldset.delete.success'))); - } + if ($fieldset->delete()) { + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/custom_fields/message.fieldset.delete.success'))); + } return response()->json(Helper::formatStandardApiResponse('error', null, 'Unspecified error')); - - - } /** @@ -147,6 +139,7 @@ class CustomFieldsetsController extends Controller $this->authorize('view', CustomFieldset::class); $set = CustomFieldset::findOrFail($id); $fields = $set->fields; + return (new CustomFieldsTransformer)->transformCustomFields($fields, $fields->count()); } diff --git a/app/Http/Controllers/Api/DepartmentsController.php b/app/Http/Controllers/Api/DepartmentsController.php index 04b806d406..21c2ac114e 100644 --- a/app/Http/Controllers/Api/DepartmentsController.php +++ b/app/Http/Controllers/Api/DepartmentsController.php @@ -24,7 +24,7 @@ class DepartmentsController extends Controller public function index(Request $request) { $this->authorize('view', Department::class); - $allowed_columns = ['id','name','image','users_count']; + $allowed_columns = ['id', 'name', 'image', 'users_count']; $departments = Department::select([ 'departments.id', @@ -34,7 +34,7 @@ class DepartmentsController extends Controller 'departments.manager_id', 'departments.created_at', 'departments.updated_at', - 'departments.image' + 'departments.image', ])->with('users')->with('location')->with('manager')->with('company')->withCount('users as users_count'); if ($request->filled('search')) { @@ -65,8 +65,8 @@ class DepartmentsController extends Controller $total = $departments->count(); $departments = $departments->skip($offset)->take($limit)->get(); - return (new DepartmentsTransformer)->transformDepartments($departments, $total); + return (new DepartmentsTransformer)->transformDepartments($departments, $total); } /** @@ -85,13 +85,13 @@ class DepartmentsController extends Controller $department = $request->handleImages($department); $department->user_id = Auth::user()->id; - $department->manager_id = ($request->filled('manager_id' ) ? $request->input('manager_id') : null); + $department->manager_id = ($request->filled('manager_id') ? $request->input('manager_id') : null); if ($department->save()) { return response()->json(Helper::formatStandardApiResponse('success', $department, trans('admin/departments/message.create.success'))); } - return response()->json(Helper::formatStandardApiResponse('error', null, $department->getErrors())); + return response()->json(Helper::formatStandardApiResponse('error', null, $department->getErrors())); } /** @@ -106,6 +106,7 @@ class DepartmentsController extends Controller { $this->authorize('view', Department::class); $department = Department::findOrFail($id); + return (new DepartmentsTransformer)->transformDepartment($department); } @@ -132,8 +133,6 @@ class DepartmentsController extends Controller return response()->json(Helper::formatStandardApiResponse('error', null, $department->getErrors())); } - - /** * Validates and deletes selected department. * @@ -153,8 +152,8 @@ class DepartmentsController extends Controller } $department->delete(); - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/departments/message.delete.success'))); + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/departments/message.delete.success'))); } /** @@ -163,11 +162,9 @@ class DepartmentsController extends Controller * @author [A. Gianotto] [] * @since [v4.0.16] * @see \App\Http\Transformers\SelectlistTransformer - * */ public function selectlist(Request $request) { - $departments = Department::select([ 'id', 'name', @@ -188,7 +185,5 @@ class DepartmentsController extends Controller } return (new SelectlistTransformer)->transformSelectlist($departments); - } - } diff --git a/app/Http/Controllers/Api/DepreciationsController.php b/app/Http/Controllers/Api/DepreciationsController.php index 12c2a9ac9b..2dd6b9d8e5 100644 --- a/app/Http/Controllers/Api/DepreciationsController.php +++ b/app/Http/Controllers/Api/DepreciationsController.php @@ -41,10 +41,10 @@ class DepreciationsController extends Controller $total = $depreciations->count(); $depreciations = $depreciations->skip($offset)->take($limit)->get(); + return (new DepreciationsTransformer)->transformDepreciations($depreciations, $total); } - /** * Store a newly created resource in storage. * @@ -62,8 +62,8 @@ class DepreciationsController extends Controller if ($depreciation->save()) { return response()->json(Helper::formatStandardApiResponse('success', $depreciation, trans('admin/depreciations/message.create.success'))); } - return response()->json(Helper::formatStandardApiResponse('error', null, $depreciation->getErrors())); + return response()->json(Helper::formatStandardApiResponse('error', null, $depreciation->getErrors())); } /** @@ -78,10 +78,10 @@ class DepreciationsController extends Controller { $this->authorize('view', Depreciation::class); $depreciation = Depreciation::findOrFail($id); + return (new DepreciationsTransformer)->transformDepreciation($depreciation); } - /** * Update the specified resource in storage. * @@ -123,10 +123,7 @@ class DepreciationsController extends Controller } $depreciation->delete(); - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/depreciations/message.delete.success'))); + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/depreciations/message.delete.success'))); } - - - } diff --git a/app/Http/Controllers/Api/GroupsController.php b/app/Http/Controllers/Api/GroupsController.php index 120dbfe3bd..5a3fe0642d 100644 --- a/app/Http/Controllers/Api/GroupsController.php +++ b/app/Http/Controllers/Api/GroupsController.php @@ -20,9 +20,9 @@ class GroupsController extends Controller public function index(Request $request) { $this->authorize('view', Group::class); - $allowed_columns = ['id','name','created_at', 'users_count']; + $allowed_columns = ['id', 'name', 'created_at', 'users_count']; - $groups = Group::select('id','name','permissions','created_at','updated_at')->withCount('users as users_count'); + $groups = Group::select('id', 'name', 'permissions', 'created_at', 'updated_at')->withCount('users as users_count'); if ($request->filled('search')) { $groups = $groups->TextSearch($request->input('search')); @@ -41,10 +41,10 @@ class GroupsController extends Controller $total = $groups->count(); $groups = $groups->skip($offset)->take($limit)->get(); + return (new GroupsTransformer)->transformGroups($groups, $total); } - /** * Store a newly created resource in storage. * @@ -62,8 +62,8 @@ class GroupsController extends Controller if ($group->save()) { return response()->json(Helper::formatStandardApiResponse('success', $group, trans('admin/groups/message.create.success'))); } - return response()->json(Helper::formatStandardApiResponse('error', null, $group->getErrors())); + return response()->json(Helper::formatStandardApiResponse('error', null, $group->getErrors())); } /** @@ -78,10 +78,10 @@ class GroupsController extends Controller { $this->authorize('view', Group::class); $group = Group::findOrFail($id); + return (new GroupsTransformer)->transformGroup($group); } - /** * Update the specified resource in storage. * @@ -118,9 +118,7 @@ class GroupsController extends Controller $group = Group::findOrFail($id); $this->authorize('delete', $group); $group->delete(); - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/groups/message.delete.success'))); + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/groups/message.delete.success'))); } - - } diff --git a/app/Http/Controllers/Api/ImportController.php b/app/Http/Controllers/Api/ImportController.php index 682f18d72b..0e8d969815 100644 --- a/app/Http/Controllers/Api/ImportController.php +++ b/app/Http/Controllers/Api/ImportController.php @@ -27,8 +27,8 @@ class ImportController extends Controller { $this->authorize('import'); $imports = Import::latest()->get(); - return (new ImportsTransformer)->transformImports($imports); + return (new ImportsTransformer)->transformImports($imports); } /** @@ -40,27 +40,28 @@ class ImportController extends Controller public function store() { $this->authorize('import'); - if (!config('app.lock_passwords')) { + if (! config('app.lock_passwords')) { $files = Request::file('files'); $path = config('app.private_uploads').'/imports'; $results = []; $import = new Import; foreach ($files as $file) { - if (!in_array($file->getMimeType(), array( + if (! in_array($file->getMimeType(), [ 'application/vnd.ms-excel', 'text/csv', 'application/csv', 'text/x-Algol68', // because wtf CSV files? 'text/plain', 'text/comma-separated-values', - 'text/tsv'))) { - $results['error']='File type must be CSV. Uploaded file is '.$file->getMimeType(); + 'text/tsv', ])) { + $results['error'] = 'File type must be CSV. Uploaded file is '.$file->getMimeType(); + return response()->json(Helper::formatStandardApiResponse('error', null, $results['error']), 500); } //TODO: is there a lighter way to do this? - if (! ini_get("auto_detect_line_endings")) { - ini_set("auto_detect_line_endings", '1'); + if (! ini_get('auto_detect_line_endings')) { + ini_set('auto_detect_line_endings', '1'); } $reader = Reader::createFromFileObject($file->openFile('r')); //file pointer leak? $import->header_row = $reader->fetchOne(0); @@ -68,20 +69,20 @@ class ImportController extends Controller //duplicate headers check $duplicate_headers = []; - for($i = 0; $iheader_row); $i++) { + for ($i = 0; $i < count($import->header_row); $i++) { $header = $import->header_row[$i]; - if(in_array($header, $import->header_row)) { + if (in_array($header, $import->header_row)) { $found_at = array_search($header, $import->header_row); - if($i > $found_at) { + if ($i > $found_at) { //avoid reporting duplicates twice, e.g. "1 is same as 17! 17 is same as 1!!!" //as well as "1 is same as 1!!!" (which is always true) //has to be > because otherwise the first result of array_search will always be $i itself(!) - array_push($duplicate_headers,"Duplicate header '$header' detected, first at column: ".($found_at+1).", repeats at column: ".($i+1)); + array_push($duplicate_headers, "Duplicate header '$header' detected, first at column: ".($found_at + 1).', repeats at column: '.($i + 1)); } } } - if(count($duplicate_headers) > 0) { - return response()->json(Helper::formatStandardApiResponse('error',null, implode("; ",$duplicate_headers)), 500); //should this be '4xx'? + if (count($duplicate_headers) > 0) { + return response()->json(Helper::formatStandardApiResponse('error', null, implode('; ', $duplicate_headers)), 500); //should this be '4xx'? } // Grab the first row to display via ajax as the user picks fields @@ -92,10 +93,11 @@ class ImportController extends Controller try { $file->move($path, $date.'-'.$fixed_filename); } catch (FileException $exception) { - $results['error']=trans('admin/hardware/message.upload.error'); + $results['error'] = trans('admin/hardware/message.upload.error'); if (config('app.debug')) { - $results['error'].= ' ' . $exception->getMessage(); + $results['error'] .= ' '.$exception->getMessage(); } + return response()->json(Helper::formatStandardApiResponse('error', null, $results['error']), 500); } $file_name = date('Y-m-d-his').'-'.$fixed_filename; @@ -105,12 +107,15 @@ class ImportController extends Controller $results[] = $import; } $results = (new ImportsTransformer)->transformImports($results); + return [ 'files' => $results, ]; } + return response()->json(Helper::formatStandardApiResponse('error', null, trans('general.feature_disabled')), 500); } + /** * Processes the specified Import. * @@ -130,25 +135,25 @@ class ImportController extends Controller } $errors = $request->import(Import::find($import_id)); - $redirectTo = "hardware.index"; + $redirectTo = 'hardware.index'; switch ($request->get('import-type')) { - case "asset": - $redirectTo = "hardware.index"; + case 'asset': + $redirectTo = 'hardware.index'; break; - case "accessory": - $redirectTo = "accessories.index"; + case 'accessory': + $redirectTo = 'accessories.index'; break; - case "consumable": - $redirectTo = "consumables.index"; + case 'consumable': + $redirectTo = 'consumables.index'; break; - case "component": - $redirectTo = "components.index"; + case 'component': + $redirectTo = 'components.index'; break; - case "license": - $redirectTo = "licenses.index"; + case 'license': + $redirectTo = 'licenses.index'; break; - case "user": - $redirectTo = "users.index"; + case 'user': + $redirectTo = 'users.index'; break; } @@ -157,8 +162,8 @@ class ImportController extends Controller } //Flash message before the redirect Session::flash('success', trans('admin/hardware/message.import.success')); - return response()->json(Helper::formatStandardApiResponse('success', null, ['redirect_url' => route($redirectTo)])); + return response()->json(Helper::formatStandardApiResponse('success', null, ['redirect_url' => route($redirectTo)])); } /** @@ -170,20 +175,20 @@ class ImportController extends Controller public function destroy($import_id) { $this->authorize('create', Asset::class); - + if ($import = Import::find($import_id)) { try { // Try to delete the file Storage::delete('imports/'.$import->file_path); $import->delete(); - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/hardware/message.import.file_delete_success'))); + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/hardware/message.import.file_delete_success'))); } catch (\Exception $e) { // If the file delete didn't work, remove it from the database anyway and return a warning $import->delete(); + return response()->json(Helper::formatStandardApiResponse('warning', null, trans('admin/hardware/message.import.file_not_deleted_warning'))); } } - } } diff --git a/app/Http/Controllers/Api/LicenseSeatsController.php b/app/Http/Controllers/Api/LicenseSeatsController.php index f86856718d..0dd1c1fbd6 100644 --- a/app/Http/Controllers/Api/LicenseSeatsController.php +++ b/app/Http/Controllers/Api/LicenseSeatsController.php @@ -32,7 +32,7 @@ class LicenseSeatsController extends Controller $order = $request->input('order') === 'asc' ? 'asc' : 'desc'; - if ($request->input('sort')=='department') { + if ($request->input('sort') == 'department') { $seats->OrderDepartments($order); } else { $seats->orderBy('id', $order); @@ -41,7 +41,7 @@ class LicenseSeatsController extends Controller $total = $seats->count(); $offset = (($seats) && (request('offset') > $total)) ? 0 : request('offset', 0); $limit = request('limit', 50); - + $seats = $seats->skip($offset)->take($limit)->get(); if ($seats) { @@ -65,13 +65,14 @@ class LicenseSeatsController extends Controller $this->authorize('view', License::class); // sanity checks: // 1. does the license seat exist? - if (!$licenseSeat = LicenseSeat::find($seatId)) { + if (! $licenseSeat = LicenseSeat::find($seatId)) { return response()->json(Helper::formatStandardApiResponse('error', null, 'Seat not found')); } // 2. does the seat belong to the specified license? - if (!$license = $licenseSeat->license()->first() || $license->id != intval($licenseId)) { + if (! $license = $licenseSeat->license()->first() || $license->id != intval($licenseId)) { return response()->json(Helper::formatStandardApiResponse('error', null, 'Seat does not belong to the specified license')); } + return (new LicenseSeatsTransformer)->transformLicenseSeat($licenseSeat); } @@ -89,11 +90,11 @@ class LicenseSeatsController extends Controller // sanity checks: // 1. does the license seat exist? - if (!$licenseSeat = LicenseSeat::find($seatId)) { + if (! $licenseSeat = LicenseSeat::find($seatId)) { return response()->json(Helper::formatStandardApiResponse('error', null, 'Seat not found')); } // 2. does the seat belong to the specified license? - if (!$license = $licenseSeat->license()->first() || $license->id != intval($licenseId)) { + if (! $license = $licenseSeat->license()->first() || $license->id != intval($licenseId)) { return response()->json(Helper::formatStandardApiResponse('error', null, 'Seat does not belong to the specified license')); } @@ -103,14 +104,14 @@ class LicenseSeatsController extends Controller // attempt to update the license seat $licenseSeat->fill($request->all()); $licenseSeat->user_id = Auth::user()->id; - + // check if this update is a checkin operation // 1. are relevant fields touched at all? $touched = $licenseSeat->isDirty('assigned_to') || $licenseSeat->isDirty('asset_id'); // 2. are they cleared? if yes then this is a checkin operation $is_checkin = ($touched && $licenseSeat->assigned_to === null && $licenseSeat->asset_id === null); - if (!$touched) { + if (! $touched) { // nothing to update return response()->json(Helper::formatStandardApiResponse('success', $licenseSeat, trans('admin/licenses/message.update.success'))); } @@ -128,11 +129,13 @@ class LicenseSeatsController extends Controller if ($is_checkin) { $licenseSeat->logCheckin($target, $request->input('note')); + return response()->json(Helper::formatStandardApiResponse('success', $licenseSeat, trans('admin/licenses/message.update.success'))); } // in this case, relevant fields are touched but it's not a checkin operation. so it must be a checkout operation. $licenseSeat->logCheckout($request->input('note'), $target); + return response()->json(Helper::formatStandardApiResponse('success', $licenseSeat, trans('admin/licenses/message.update.success'))); } diff --git a/app/Http/Controllers/Api/LicensesController.php b/app/Http/Controllers/Api/LicensesController.php index 268248ab77..b8ea3b03e3 100644 --- a/app/Http/Controllers/Api/LicensesController.php +++ b/app/Http/Controllers/Api/LicensesController.php @@ -26,63 +26,60 @@ class LicensesController extends Controller public function index(Request $request) { $this->authorize('view', License::class); - $licenses = Company::scopeCompanyables(License::with('company', 'manufacturer', 'freeSeats', 'supplier','category')->withCount('freeSeats as free_seats_count')); - + $licenses = Company::scopeCompanyables(License::with('company', 'manufacturer', 'freeSeats', 'supplier', 'category')->withCount('freeSeats as free_seats_count')); if ($request->filled('company_id')) { - $licenses->where('company_id','=',$request->input('company_id')); + $licenses->where('company_id', '=', $request->input('company_id')); } if ($request->filled('name')) { - $licenses->where('licenses.name','=',$request->input('name')); + $licenses->where('licenses.name', '=', $request->input('name')); } if ($request->filled('product_key')) { - $licenses->where('licenses.serial','=',$request->input('product_key')); + $licenses->where('licenses.serial', '=', $request->input('product_key')); } if ($request->filled('order_number')) { - $licenses->where('order_number','=',$request->input('order_number')); + $licenses->where('order_number', '=', $request->input('order_number')); } if ($request->filled('purchase_order')) { - $licenses->where('purchase_order','=',$request->input('purchase_order')); + $licenses->where('purchase_order', '=', $request->input('purchase_order')); } if ($request->filled('license_name')) { - $licenses->where('license_name','=',$request->input('license_name')); + $licenses->where('license_name', '=', $request->input('license_name')); } if ($request->filled('license_email')) { - $licenses->where('license_email','=',$request->input('license_email')); + $licenses->where('license_email', '=', $request->input('license_email')); } if ($request->filled('manufacturer_id')) { - $licenses->where('manufacturer_id','=',$request->input('manufacturer_id')); + $licenses->where('manufacturer_id', '=', $request->input('manufacturer_id')); } if ($request->filled('supplier_id')) { - $licenses->where('supplier_id','=',$request->input('supplier_id')); + $licenses->where('supplier_id', '=', $request->input('supplier_id')); } if ($request->filled('category_id')) { - $licenses->where('category_id','=',$request->input('category_id')); + $licenses->where('category_id', '=', $request->input('category_id')); } if ($request->filled('depreciation_id')) { - $licenses->where('depreciation_id','=',$request->input('depreciation_id')); + $licenses->where('depreciation_id', '=', $request->input('depreciation_id')); } if ($request->filled('supplier_id')) { - $licenses->where('supplier_id','=',$request->input('supplier_id')); + $licenses->where('supplier_id', '=', $request->input('supplier_id')); } - if ($request->filled('search')) { $licenses = $licenses->TextSearch($request->input('search')); } - // Set the offset to the API call's offset, unless the offset is higher than the actual count of items in which // case we override with the actual count, so we should return 0 items. $offset = (($licenses) && ($request->get('offset') > $licenses->count())) ? $licenses->count() : $request->get('offset', 0); @@ -92,7 +89,6 @@ class LicensesController extends Controller $order = $request->input('order') === 'asc' ? 'asc' : 'desc'; - switch ($request->input('sort')) { case 'manufacturer': $licenses = $licenses->leftJoin('manufacturers', 'licenses.manufacturer_id', '=', 'manufacturers.id')->orderBy('manufacturers.name', $order); @@ -128,25 +124,20 @@ class LicensesController extends Controller 'free_seats_count', 'seats', 'termination_date', - 'depreciation_id' + 'depreciation_id', ]; $sort = in_array($request->input('sort'), $allowed_columns) ? e($request->input('sort')) : 'created_at'; $licenses = $licenses->orderBy($sort, $order); break; } - - $total = $licenses->count(); $licenses = $licenses->skip($offset)->take($limit)->get(); + return (new LicensesTransformer)->transformLicenses($licenses, $total); - } - - - /** * Store a newly created resource in storage. * @@ -162,9 +153,10 @@ class LicensesController extends Controller $license = new License; $license->fill($request->all()); - if($license->save()) { + if ($license->save()) { return response()->json(Helper::formatStandardApiResponse('success', $license, trans('admin/licenses/message.create.success'))); } + return response()->json(Helper::formatStandardApiResponse('error', null, $license->getErrors())); } @@ -180,10 +172,10 @@ class LicensesController extends Controller $this->authorize('view', License::class); $license = License::withCount('freeSeats')->findOrFail($id); $license = $license->load('assignedusers', 'licenseSeats.user', 'licenseSeats.asset'); + return (new LicensesTransformer)->transformLicense($license); } - /** * Update the specified resource in storage. * @@ -222,22 +214,23 @@ class LicensesController extends Controller $license = License::findOrFail($id); $this->authorize('delete', $license); - if($license->assigned_seats_count == 0) { + if ($license->assigned_seats_count == 0) { // Delete the license and the associated license seats DB::table('license_seats') ->where('id', $license->id) - ->update(array('assigned_to' => null,'asset_id' => null)); + ->update(['assigned_to' => null, 'asset_id' => null]); $licenseSeats = $license->licenseseats(); $licenseSeats->delete(); $license->delete(); // Redirect to the licenses management page - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/licenses/message.delete.success'))); + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/licenses/message.delete.success'))); } + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/licenses/message.assoc_users'))); } - + /** * Gets a paginated collection for the select2 menus * @@ -245,10 +238,9 @@ class LicensesController extends Controller */ public function selectlist(Request $request) { - $licenses = License::select([ 'licenses.id', - 'licenses.name' + 'licenses.name', ]); if ($request->filled('search')) { @@ -257,9 +249,6 @@ class LicensesController extends Controller $licenses = $licenses->orderBy('name', 'ASC')->paginate(50); - return (new SelectlistTransformer)->transformSelectlist($licenses); } - - } diff --git a/app/Http/Controllers/Api/LocationsController.php b/app/Http/Controllers/Api/LocationsController.php index 6d70e7aaf1..0bcc01b37f 100644 --- a/app/Http/Controllers/Api/LocationsController.php +++ b/app/Http/Controllers/Api/LocationsController.php @@ -2,13 +2,14 @@ namespace App\Http\Controllers\Api; -use Illuminate\Http\Request; +use App\Helpers\Helper; use App\Http\Requests\ImageUploadRequest; use App\Http\Controllers\Controller; -use App\Helpers\Helper; -use App\Models\Location; use App\Http\Transformers\LocationsTransformer; use App\Http\Transformers\SelectlistTransformer; +use App\Models\Location; +use Illuminate\Http\Request; +use App\Http\Requests\ImageUploadRequest; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection; @@ -25,9 +26,9 @@ class LocationsController extends Controller { $this->authorize('view', Location::class); $allowed_columns = [ - 'id','name','address','address2','city','state','country','zip','created_at', - 'updated_at','manager_id','image', - 'assigned_assets_count','users_count','assets_count','currency','ldap_ou']; + 'id', 'name', 'address', 'address2', 'city', 'state', 'country', 'zip', 'created_at', + 'updated_at', 'manager_id', 'image', + 'assigned_assets_count', 'users_count', 'assets_count', 'currency', 'ldap_ou', ]; $locations = Location::with('parent', 'manager', 'children')->select([ 'locations.id', @@ -44,7 +45,7 @@ class LocationsController extends Controller 'locations.updated_at', 'locations.image', 'locations.ldap_ou', - 'locations.currency' + 'locations.currency', ])->withCount('assignedAssets as assigned_assets_count') ->withCount('assets as assets_count') ->withCount('users as users_count'); @@ -53,8 +54,6 @@ class LocationsController extends Controller $locations = $locations->TextSearch($request->input('search')); } - - $offset = (($locations) && (request('offset') > $locations->count())) ? $locations->count() : request('offset', 0); // Check to make sure the limit is not higher than the max allowed @@ -75,9 +74,9 @@ class LocationsController extends Controller break; } - $total = $locations->count(); $locations = $locations->skip($offset)->take($limit)->get(); + return (new LocationsTransformer)->transformLocations($locations, $total); } @@ -100,6 +99,7 @@ class LocationsController extends Controller if ($location->save()) { return response()->json(Helper::formatStandardApiResponse('success', (new LocationsTransformer)->transformLocation($location), trans('admin/locations/message.create.success'))); } + return response()->json(Helper::formatStandardApiResponse('error', null, $location->getErrors())); } @@ -129,15 +129,15 @@ class LocationsController extends Controller 'locations.created_at', 'locations.updated_at', 'locations.image', - 'locations.currency' + 'locations.currency', ]) ->withCount('assignedAssets as assigned_assets_count') ->withCount('assets as assets_count') ->withCount('users as users_count')->findOrFail($id); + return (new LocationsTransformer)->transformLocation($location); } - /** * Update the specified resource in storage. * @@ -156,8 +156,8 @@ class LocationsController extends Controller $location = $request->handleImages($location); if ($location->isValid()) { - $location->save(); + return response()->json( Helper::formatStandardApiResponse( 'success', @@ -182,12 +182,13 @@ class LocationsController extends Controller { $this->authorize('delete', Location::class); $location = Location::findOrFail($id); - if(!$location->isDeletable()) { + if (! $location->isDeletable()) { return response() - ->json(Helper::formatStandardApiResponse('error', null, trans('admin/companies/message.assoc_users'))); + ->json(Helper::formatStandardApiResponse('error', null, trans('admin/companies/message.assoc_users'))); } $this->authorize('delete', $location); $location->delete(); + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/locations/message.delete.success'))); } @@ -218,11 +219,9 @@ class LocationsController extends Controller * @author [A. Gianotto] [] * @since [v4.0.16] * @see \App\Http\Transformers\SelectlistTransformer - * */ public function selectlist(Request $request) { - $locations = Location::select([ 'locations.id', 'locations.name', @@ -244,26 +243,22 @@ class LocationsController extends Controller $locations_with_children = []; foreach ($locations as $location) { - if (!array_key_exists($location->parent_id, $locations_with_children)) { + if (! array_key_exists($location->parent_id, $locations_with_children)) { $locations_with_children[$location->parent_id] = []; } $locations_with_children[$location->parent_id][] = $location; } if ($request->filled('search')) { - $locations_formatted = $locations; + $locations_formatted = $locations; } else { $location_options = Location::indenter($locations_with_children); $locations_formatted = new Collection($location_options); - } - $paginated_results = new LengthAwarePaginator($locations_formatted->forPage($page, 500), $locations_formatted->count(), 500, $page, []); + $paginated_results = new LengthAwarePaginator($locations_formatted->forPage($page, 500), $locations_formatted->count(), 500, $page, []); //return []; return (new SelectlistTransformer)->transformSelectlist($paginated_results); - } - - } diff --git a/app/Http/Controllers/Api/ManufacturersController.php b/app/Http/Controllers/Api/ManufacturersController.php index 0301ae587c..5392c1d217 100644 --- a/app/Http/Controllers/Api/ManufacturersController.php +++ b/app/Http/Controllers/Api/ManufacturersController.php @@ -23,13 +23,13 @@ class ManufacturersController extends Controller public function index(Request $request) { $this->authorize('view', Manufacturer::class); - $allowed_columns = ['id','name','url','support_url','support_email','support_phone','created_at','updated_at','image', 'assets_count', 'consumables_count', 'components_count', 'licenses_count']; + $allowed_columns = ['id', 'name', 'url', 'support_url', 'support_email', 'support_phone', 'created_at', 'updated_at', 'image', 'assets_count', 'consumables_count', 'components_count', 'licenses_count']; $manufacturers = Manufacturer::select( - array('id','name','url','support_url','support_email','support_phone','created_at','updated_at','image', 'deleted_at') + ['id', 'name', 'url', 'support_url', 'support_email', 'support_phone', 'created_at', 'updated_at', 'image', 'deleted_at'] )->withCount('assets as assets_count')->withCount('licenses as licenses_count')->withCount('consumables as consumables_count')->withCount('accessories as accessories_count'); - if ($request->input('deleted')=='true') { + if ($request->input('deleted') == 'true') { $manufacturers->onlyTrashed(); } @@ -37,7 +37,6 @@ class ManufacturersController extends Controller $manufacturers = $manufacturers->TextSearch($request->input('search')); } - // Set the offset to the API call's offset, unless the offset is higher than the actual count of items in which // case we override with the actual count, so we should return 0 items. $offset = (($manufacturers) && ($request->get('offset') > $manufacturers->count())) ? $manufacturers->count() : $request->get('offset', 0); @@ -51,10 +50,10 @@ class ManufacturersController extends Controller $total = $manufacturers->count(); $manufacturers = $manufacturers->skip($offset)->take($limit)->get(); + return (new ManufacturersTransformer)->transformManufacturers($manufacturers, $total); } - /** * Store a newly created resource in storage. * @@ -73,8 +72,8 @@ class ManufacturersController extends Controller if ($manufacturer->save()) { return response()->json(Helper::formatStandardApiResponse('success', $manufacturer, trans('admin/manufacturers/message.create.success'))); } - return response()->json(Helper::formatStandardApiResponse('error', null, $manufacturer->getErrors())); + return response()->json(Helper::formatStandardApiResponse('error', null, $manufacturer->getErrors())); } /** @@ -89,10 +88,10 @@ class ManufacturersController extends Controller { $this->authorize('view', Manufacturer::class); $manufacturer = Manufacturer::withCount('assets as assets_count')->withCount('licenses as licenses_count')->withCount('consumables as consumables_count')->withCount('accessories as accessories_count')->findOrFail($id); + return (new ManufacturersTransformer)->transformManufacturer($manufacturer); } - /** * Update the specified resource in storage. * @@ -126,22 +125,17 @@ class ManufacturersController extends Controller */ public function destroy($id) { - $this->authorize('delete', Manufacturer::class); $manufacturer = Manufacturer::findOrFail($id); $this->authorize('delete', $manufacturer); if ($manufacturer->isDeletable()) { $manufacturer->delete(); - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/manufacturers/message.delete.success'))); + + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/manufacturers/message.delete.success'))); } - return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/manufacturers/message.assoc_users'))); - - - - - + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/manufacturers/message.assoc_users'))); } /** @@ -150,11 +144,9 @@ class ManufacturersController extends Controller * @author [A. Gianotto] [] * @since [v4.0.16] * @see \App\Http\Transformers\SelectlistTransformer - * */ public function selectlist(Request $request) { - $manufacturers = Manufacturer::select([ 'id', 'name', @@ -176,6 +168,5 @@ class ManufacturersController extends Controller } return (new SelectlistTransformer)->transformSelectlist($manufacturers); - } } diff --git a/app/Http/Controllers/Api/PredefinedKitsController.php b/app/Http/Controllers/Api/PredefinedKitsController.php index 6d6f2797f1..97514850f6 100644 --- a/app/Http/Controllers/Api/PredefinedKitsController.php +++ b/app/Http/Controllers/Api/PredefinedKitsController.php @@ -37,11 +37,10 @@ class PredefinedKitsController extends Controller $total = $kits->count(); $kits = $kits->skip($offset)->take($limit)->get(); + return (new PredefinedKitsTransformer)->transformPredefinedKits($kits, $total); - } - /** * Store a newly created resource in storage. * @@ -57,8 +56,8 @@ class PredefinedKitsController extends Controller if ($kit->save()) { return response()->json(Helper::formatStandardApiResponse('success', $kit, trans('admin/kits/general.create_success'))); } - return response()->json(Helper::formatStandardApiResponse('error', null, $kit->getErrors())); + return response()->json(Helper::formatStandardApiResponse('error', null, $kit->getErrors())); } /** @@ -71,10 +70,10 @@ class PredefinedKitsController extends Controller { $this->authorize('view', PredefinedKit::class); $kit = PredefinedKit::findOrFail($id); + return (new PredefinedKitsTransformer)->transformPredefinedKit($kit); } - /** * Update the specified resource in storage. * @@ -113,23 +112,20 @@ class PredefinedKitsController extends Controller $kit->accessories()->detach(); $kit->delete(); - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/kits/general.delete_success'))); // TODO: trans + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/kits/general.delete_success'))); // TODO: trans } - /** * Gets a paginated collection for the select2 menus * * @see \App\Http\Transformers\SelectlistTransformer - * */ public function selectlist(Request $request) { - $kits = PredefinedKit::select([ 'id', - 'name' + 'name', ]); if ($request->filled('search')) { @@ -139,7 +135,6 @@ class PredefinedKitsController extends Controller $kits = $kits->orderBy('name', 'ASC')->paginate(50); return (new SelectlistTransformer)->transformSelectlist($kits); - } /** @@ -148,38 +143,40 @@ class PredefinedKitsController extends Controller * @param int $id * @return \Illuminate\Http\Response */ - public function indexLicenses($kit_id) { + public function indexLicenses($kit_id) + { $this->authorize('view', PredefinedKit::class); $kit = PredefinedKit::findOrFail($kit_id); $licenses = $kit->licenses; + return (new PredefinedKitsTransformer)->transformElements($licenses, $licenses->count()); } - /** * Store the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ - public function storeLicense(Request $request, $kit_id) - { - $this->authorize('update', PredefinedKit::class); - - $kit = PredefinedKit::findOrFail($kit_id); - $quantity = $request->input('quantity', 1); - if( $quantity < 1) { - $quantity = 1; - } + public function storeLicense(Request $request, $kit_id) + { + $this->authorize('update', PredefinedKit::class); - $license_id = $request->get('license'); - $relation = $kit->licenses(); - if( $relation->find($license_id) ) { - return response()->json(Helper::formatStandardApiResponse('error', null, ['license' => 'License already attached to kit'])); - } + $kit = PredefinedKit::findOrFail($kit_id); + $quantity = $request->input('quantity', 1); + if ($quantity < 1) { + $quantity = 1; + } - $relation->attach( $license_id, ['quantity' => $quantity]); - return response()->json(Helper::formatStandardApiResponse('success', $kit, 'License added successfull')); // TODO: trans + $license_id = $request->get('license'); + $relation = $kit->licenses(); + if ($relation->find($license_id)) { + return response()->json(Helper::formatStandardApiResponse('error', null, ['license' => 'License already attached to kit'])); + } + + $relation->attach($license_id, ['quantity' => $quantity]); + + return response()->json(Helper::formatStandardApiResponse('success', $kit, 'License added successfull')); // TODO: trans } /** @@ -189,20 +186,20 @@ class PredefinedKitsController extends Controller * @param int $kit_id * @return \Illuminate\Http\Response */ - public function updateLicense(Request $request, $kit_id, $license_id) - { - $this->authorize('update', PredefinedKit::class); - $kit = PredefinedKit::findOrFail($kit_id); - $quantity = $request->input('quantity', 1); - if( $quantity < 1) { - $quantity = 1; - } - $kit->licenses()->syncWithoutDetaching([$license_id => ['quantity' => $quantity]]); - - return response()->json(Helper::formatStandardApiResponse('success', $kit, 'License updated')); // TODO: trans - } + public function updateLicense(Request $request, $kit_id, $license_id) + { + $this->authorize('update', PredefinedKit::class); + $kit = PredefinedKit::findOrFail($kit_id); + $quantity = $request->input('quantity', 1); + if ($quantity < 1) { + $quantity = 1; + } + $kit->licenses()->syncWithoutDetaching([$license_id => ['quantity' => $quantity]]); - /** + return response()->json(Helper::formatStandardApiResponse('success', $kit, 'License updated')); // TODO: trans + } + + /** * Remove the specified resource from storage. * * @param int $kit_id @@ -214,48 +211,49 @@ class PredefinedKitsController extends Controller $kit = PredefinedKit::findOrFail($kit_id); $kit->licenses()->detach($license_id); - return response()->json(Helper::formatStandardApiResponse('success', $kit, trans('admin/kits/general.delete_success'))); + + return response()->json(Helper::formatStandardApiResponse('success', $kit, trans('admin/kits/general.delete_success'))); } - + /** * Display the specified resource. * * @param int $kit_id * @return \Illuminate\Http\Response */ - public function indexModels($kit_id) { + public function indexModels($kit_id) + { $this->authorize('view', PredefinedKit::class); $kit = PredefinedKit::findOrFail($kit_id); $models = $kit->models; + return (new PredefinedKitsTransformer)->transformElements($models, $models->count()); } - + /** * Store the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ - public function storeModel(Request $request, $kit_id) - { - - + public function storeModel(Request $request, $kit_id) + { $this->authorize('update', PredefinedKit::class); - - $kit = PredefinedKit::findOrFail($kit_id); - + + $kit = PredefinedKit::findOrFail($kit_id); + $model_id = $request->get('model'); $quantity = $request->input('quantity', 1); - if( $quantity < 1) { + if ($quantity < 1) { $quantity = 1; } - + $relation = $kit->models(); - if( $relation->find($model_id) ) { + if ($relation->find($model_id)) { return response()->json(Helper::formatStandardApiResponse('error', null, ['model' => 'Model already attached to kit'])); } $relation->attach($model_id, ['quantity' => $quantity]); - + return response()->json(Helper::formatStandardApiResponse('success', $kit, 'Model added successfull')); } @@ -266,20 +264,20 @@ class PredefinedKitsController extends Controller * @param int $kit_id * @return \Illuminate\Http\Response */ - public function updateModel(Request $request, $kit_id, $model_id) - { - $this->authorize('update', PredefinedKit::class); - $kit = PredefinedKit::findOrFail($kit_id); - $quantity = $request->input('quantity', 1); - if( $quantity < 1) { - $quantity = 1; - } - $kit->models()->syncWithoutDetaching([$model_id => ['quantity' => $quantity]]); - - return response()->json(Helper::formatStandardApiResponse('success', $kit, 'License updated')); // TODO: trans - } + public function updateModel(Request $request, $kit_id, $model_id) + { + $this->authorize('update', PredefinedKit::class); + $kit = PredefinedKit::findOrFail($kit_id); + $quantity = $request->input('quantity', 1); + if ($quantity < 1) { + $quantity = 1; + } + $kit->models()->syncWithoutDetaching([$model_id => ['quantity' => $quantity]]); - /** + return response()->json(Helper::formatStandardApiResponse('success', $kit, 'License updated')); // TODO: trans + } + + /** * Remove the specified resource from storage. * * @param int $kit_id @@ -291,49 +289,50 @@ class PredefinedKitsController extends Controller $kit = PredefinedKit::findOrFail($kit_id); $kit->models()->detach($model_id); - return response()->json(Helper::formatStandardApiResponse('success', $kit, trans('admin/kits/general.model_removed_success'))); + + return response()->json(Helper::formatStandardApiResponse('success', $kit, trans('admin/kits/general.model_removed_success'))); } - - /** * Display the specified resource. * * @param int $kit_id * @return \Illuminate\Http\Response */ - public function indexConsumables($kit_id) { + public function indexConsumables($kit_id) + { $this->authorize('view', PredefinedKit::class); $kit = PredefinedKit::findOrFail($kit_id); $consumables = $kit->consumables; + return (new PredefinedKitsTransformer)->transformElements($consumables, $consumables->count()); } - /** * Store the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ - public function storeConsumable(Request $request, $kit_id) - { - $this->authorize('update', PredefinedKit::class); - - $kit = PredefinedKit::findOrFail($kit_id); - $quantity = $request->input('quantity', 1); - if( $quantity < 1) { - $quantity = 1; - } + public function storeConsumable(Request $request, $kit_id) + { + $this->authorize('update', PredefinedKit::class); - $consumable_id = $request->get('consumable'); - $relation = $kit->consumables(); - if( $relation->find($consumable_id) ) { - return response()->json(Helper::formatStandardApiResponse('error', null, ['consumable' => 'Consumable already attached to kit'])); - } + $kit = PredefinedKit::findOrFail($kit_id); + $quantity = $request->input('quantity', 1); + if ($quantity < 1) { + $quantity = 1; + } - $relation->attach( $consumable_id, ['quantity' => $quantity]); - return response()->json(Helper::formatStandardApiResponse('success', $kit, 'Consumable added successfull')); // TODO: trans + $consumable_id = $request->get('consumable'); + $relation = $kit->consumables(); + if ($relation->find($consumable_id)) { + return response()->json(Helper::formatStandardApiResponse('error', null, ['consumable' => 'Consumable already attached to kit'])); + } + + $relation->attach($consumable_id, ['quantity' => $quantity]); + + return response()->json(Helper::formatStandardApiResponse('success', $kit, 'Consumable added successfull')); // TODO: trans } /** @@ -343,20 +342,20 @@ class PredefinedKitsController extends Controller * @param int $kit_id * @return \Illuminate\Http\Response */ - public function updateConsumable(Request $request, $kit_id, $consumable_id) - { - $this->authorize('update', PredefinedKit::class); - $kit = PredefinedKit::findOrFail($kit_id); - $quantity = $request->input('quantity', 1); - if( $quantity < 1) { - $quantity = 1; - } - $kit->consumables()->syncWithoutDetaching([$consumable_id => ['quantity' => $quantity]]); - - return response()->json(Helper::formatStandardApiResponse('success', $kit, 'Consumable updated')); // TODO: trans - } + public function updateConsumable(Request $request, $kit_id, $consumable_id) + { + $this->authorize('update', PredefinedKit::class); + $kit = PredefinedKit::findOrFail($kit_id); + $quantity = $request->input('quantity', 1); + if ($quantity < 1) { + $quantity = 1; + } + $kit->consumables()->syncWithoutDetaching([$consumable_id => ['quantity' => $quantity]]); - /** + return response()->json(Helper::formatStandardApiResponse('success', $kit, 'Consumable updated')); // TODO: trans + } + + /** * Remove the specified resource from storage. * * @param int $kit_id @@ -368,48 +367,50 @@ class PredefinedKitsController extends Controller $kit = PredefinedKit::findOrFail($kit_id); $kit->consumables()->detach($consumable_id); - return response()->json(Helper::formatStandardApiResponse('success', $kit, 'Delete was successfull')); // TODO: trans + + return response()->json(Helper::formatStandardApiResponse('success', $kit, 'Delete was successfull')); // TODO: trans } - /** * Display the specified resource. * * @param int $kit_id * @return \Illuminate\Http\Response */ - public function indexAccessories($kit_id) { + public function indexAccessories($kit_id) + { $this->authorize('view', PredefinedKit::class); $kit = PredefinedKit::findOrFail($kit_id); $accessories = $kit->accessories; + return (new PredefinedKitsTransformer)->transformElements($accessories, $accessories->count()); } - /** * Store the specified resource. * * @param int $kit_id * @return \Illuminate\Http\Response */ - public function storeAccessory(Request $request, $kit_id) - { - $this->authorize('update', PredefinedKit::class); - - $kit = PredefinedKit::findOrFail($kit_id); - $quantity = $request->input('quantity', 1); - if( $quantity < 1) { - $quantity = 1; - } + public function storeAccessory(Request $request, $kit_id) + { + $this->authorize('update', PredefinedKit::class); - $accessory_id = $request->get('accessory'); - $relation = $kit->accessories(); - if( $relation->find($accessory_id) ) { - return response()->json(Helper::formatStandardApiResponse('error', null, ['accessory' => 'Accessory already attached to kit'])); - } + $kit = PredefinedKit::findOrFail($kit_id); + $quantity = $request->input('quantity', 1); + if ($quantity < 1) { + $quantity = 1; + } - $relation->attach( $accessory_id, ['quantity' => $quantity]); - return response()->json(Helper::formatStandardApiResponse('success', $kit, 'Accessory added successfull')); // TODO: trans + $accessory_id = $request->get('accessory'); + $relation = $kit->accessories(); + if ($relation->find($accessory_id)) { + return response()->json(Helper::formatStandardApiResponse('error', null, ['accessory' => 'Accessory already attached to kit'])); + } + + $relation->attach($accessory_id, ['quantity' => $quantity]); + + return response()->json(Helper::formatStandardApiResponse('success', $kit, 'Accessory added successfull')); // TODO: trans } /** @@ -419,20 +420,20 @@ class PredefinedKitsController extends Controller * @param int $kit_id * @return \Illuminate\Http\Response */ - public function updateAccessory(Request $request, $kit_id, $accessory_id) - { - $this->authorize('update', PredefinedKit::class); - $kit = PredefinedKit::findOrFail($kit_id); - $quantity = $request->input('quantity', 1); - if( $quantity < 1) { - $quantity = 1; - } - $kit->accessories()->syncWithoutDetaching([$accessory_id => ['quantity' => $quantity]]); - - return response()->json(Helper::formatStandardApiResponse('success', $kit, 'Accessory updated')); // TODO: trans - } + public function updateAccessory(Request $request, $kit_id, $accessory_id) + { + $this->authorize('update', PredefinedKit::class); + $kit = PredefinedKit::findOrFail($kit_id); + $quantity = $request->input('quantity', 1); + if ($quantity < 1) { + $quantity = 1; + } + $kit->accessories()->syncWithoutDetaching([$accessory_id => ['quantity' => $quantity]]); - /** + return response()->json(Helper::formatStandardApiResponse('success', $kit, 'Accessory updated')); // TODO: trans + } + + /** * Remove the specified resource from storage. * * @param int $kit_id @@ -444,6 +445,7 @@ class PredefinedKitsController extends Controller $kit = PredefinedKit::findOrFail($kit_id); $kit->accessories()->detach($accessory_id); - return response()->json(Helper::formatStandardApiResponse('success', $kit, 'Delete was successfull')); // TODO: trans + + return response()->json(Helper::formatStandardApiResponse('success', $kit, 'Delete was successfull')); // TODO: trans } } diff --git a/app/Http/Controllers/Api/ProfileController.php b/app/Http/Controllers/Api/ProfileController.php index f6c31d5db1..fd98225320 100644 --- a/app/Http/Controllers/Api/ProfileController.php +++ b/app/Http/Controllers/Api/ProfileController.php @@ -15,7 +15,7 @@ class ProfileController extends Controller * @author [A. Gianotto] [] * @since [v4.3.0] * - * @return Array + * @return array */ public function requestedAssets() { @@ -24,7 +24,6 @@ class ProfileController extends Controller $results = []; $results['total'] = $checkoutRequests->count(); - foreach ($checkoutRequests as $checkoutRequest) { // Make sure the asset and request still exist @@ -39,10 +38,8 @@ class ProfileController extends Controller 'request_date' => Helper::getFormattedDateObject($checkoutRequest->created_at, 'datetime'), ]; } - } + return $results; } - - } diff --git a/app/Http/Controllers/Api/ReportsController.php b/app/Http/Controllers/Api/ReportsController.php index ba88d6acc3..1406dba791 100644 --- a/app/Http/Controllers/Api/ReportsController.php +++ b/app/Http/Controllers/Api/ReportsController.php @@ -19,25 +19,25 @@ class ReportsController extends Controller public function index(Request $request) { $this->authorize('reports.view'); - - $actionlogs = Actionlog::with('item', 'user', 'target','location'); + + $actionlogs = Actionlog::with('item', 'user', 'target', 'location'); if ($request->filled('search')) { $actionlogs = $actionlogs->TextSearch(e($request->input('search'))); } - if (($request->filled('target_type')) && ($request->filled('target_id'))) { - $actionlogs = $actionlogs->where('target_id','=',$request->input('target_id')) - ->where('target_type','=',"App\\Models\\".ucwords($request->input('target_type'))); + if (($request->filled('target_type')) && ($request->filled('target_id'))) { + $actionlogs = $actionlogs->where('target_id', '=', $request->input('target_id')) + ->where('target_type', '=', 'App\\Models\\'.ucwords($request->input('target_type'))); } - if (($request->filled('item_type')) && ($request->filled('item_id'))) { - $actionlogs = $actionlogs->where('item_id','=',$request->input('item_id')) - ->where('item_type','=',"App\\Models\\".ucwords($request->input('item_type'))); + if (($request->filled('item_type')) && ($request->filled('item_id'))) { + $actionlogs = $actionlogs->where('item_id', '=', $request->input('item_id')) + ->where('item_type', '=', 'App\\Models\\'.ucwords($request->input('item_type'))); } if ($request->filled('action_type')) { - $actionlogs = $actionlogs->where('action_type','=',$request->input('action_type'))->orderBy('created_at', 'desc'); + $actionlogs = $actionlogs->where('action_type', '=', $request->input('action_type'))->orderBy('created_at', 'desc'); } if ($request->filled('uploads')) { @@ -51,9 +51,9 @@ class ReportsController extends Controller 'user_id', 'accept_signature', 'action_type', - 'note' + 'note', ]; - + $sort = in_array($request->input('sort'), $allowed_columns) ? e($request->input('sort')) : 'created_at'; $order = ($request->input('order') == 'asc') ? 'asc' : 'desc'; $offset = request('offset', 0); @@ -62,6 +62,5 @@ class ReportsController extends Controller $actionlogs = $actionlogs->orderBy($sort, $order)->skip($offset)->take($limit)->get(); return response()->json((new ActionlogsTransformer)->transformActionlogs($actionlogs, $total), 200, ['Content-Type' => 'application/json;charset=utf8'], JSON_UNESCAPED_UNICODE); - } } diff --git a/app/Http/Controllers/Api/SettingsController.php b/app/Http/Controllers/Api/SettingsController.php index 462c685361..852530c207 100644 --- a/app/Http/Controllers/Api/SettingsController.php +++ b/app/Http/Controllers/Api/SettingsController.php @@ -4,60 +4,59 @@ namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use App\Http\Transformers\LoginAttemptsTransformer; +use App\Models\Ldap; use App\Models\Setting; use App\Notifications\MailTest; use App\Services\LdapAd; +use GuzzleHttp\Client; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Notification; -use GuzzleHttp\Client; use Illuminate\Support\Facades\Storage; -use Illuminate\Support\Facades\Validator; -use App\Models\Ldap; // forward-port of v4 LDAP model for Sync - +use Illuminate\Support\Facades\Validator; // forward-port of v4 LDAP model for Sync class SettingsController extends Controller { - /** * Test the ldap settings - * + * * @author Wes Hulette - * + * * @since 5.0.0 - * + * * @param App\Models\LdapAd $ldap - * + * * @return \Illuminate\Http\JsonResponse */ public function ldapAdSettingsTest(LdapAd $ldap): JsonResponse { - if(!$ldap->init()) { + if (! $ldap->init()) { Log::info('LDAP is not enabled so we cannot test.'); + return response()->json(['message' => 'LDAP is not enabled, cannot test.'], 400); } // The connect, bind and resulting users message $message = []; - // This is all kinda fucked right now. The connection test doesn't actually do what you think, // // and the way we parse the errors - // on the JS side is horrible. + // on the JS side is horrible. Log::info('Preparing to test LDAP user login'); // Test user can connect to the LDAP server try { $ldap->testLdapAdUserConnection(); $message['login'] = [ - 'message' => 'Successfully connected to LDAP server.' + 'message' => 'Successfully connected to LDAP server.', ]; } catch (\Exception $ex) { - \Log::debug('Connection to LDAP server '.Setting::getSettings()->ldap_server.' failed. Please check your LDAP settings and try again. Server Responded with error: ' . $ex->getMessage()); + \Log::debug('Connection to LDAP server '.Setting::getSettings()->ldap_server.' failed. Please check your LDAP settings and try again. Server Responded with error: '.$ex->getMessage()); + return response()->json( - ['message' => 'Connection to LDAP server '.Setting::getSettings()->ldap_server." failed. Verify that the LDAP hostname is entered correctly and that it can be reached from this web server. \n\nServer Responded with error: " . $ex->getMessage() + ['message' => 'Connection to LDAP server '.Setting::getSettings()->ldap_server." failed. Verify that the LDAP hostname is entered correctly and that it can be reached from this web server. \n\nServer Responded with error: ".$ex->getMessage(), ], 400); } @@ -68,15 +67,15 @@ class SettingsController extends Controller Log::info('Testing Bind'); $ldap->testLdapAdBindConnection(); $message['bind'] = [ - 'message' => 'Successfully bound to LDAP server.' + 'message' => 'Successfully bound to LDAP server.', ]; } catch (\Exception $ex) { Log::info('LDAP Bind failed'); - return response()->json(['message' => 'Connection to LDAP successful, but we were unable to Bind the LDAP user '.Setting::getSettings()->ldap_uname.". Verify your that your LDAP Bind username and password are correct. \n\nServer Responded with error: " . $ex->getMessage() + + return response()->json(['message' => 'Connection to LDAP successful, but we were unable to Bind the LDAP user '.Setting::getSettings()->ldap_uname.". Verify your that your LDAP Bind username and password are correct. \n\nServer Responded with error: ".$ex->getMessage(), ], 400); } - Log::info('Preparing to get sample user set from LDAP directory'); // Get a sample of 10 users so user can verify the data is correct $settings = Setting::getSettings(); @@ -96,21 +95,22 @@ class SettingsController extends Controller ]; }); if ($users->count() > 0) { - $message['user_sync'] = [ - 'users' => $users + $message['user_sync'] = [ + 'users' => $users, ]; } else { - $message['user_sync'] = [ - 'message' => 'Connection to LDAP was successful, however there were no users returned from your query. You should confirm the Base Bind DN above.' + $message['user_sync'] = [ + 'message' => 'Connection to LDAP was successful, however there were no users returned from your query. You should confirm the Base Bind DN above.', ]; + return response()->json($message, 400); } - } catch (\Exception $ex) { Log::info('LDAP sync failed'); - $message['user_sync'] = [ - 'message' => 'Error getting users from LDAP directory, error: ' . $ex->getMessage() + $message['user_sync'] = [ + 'message' => 'Error getting users from LDAP directory, error: '.$ex->getMessage(), ]; + return response()->json($message, 400); } @@ -119,25 +119,24 @@ class SettingsController extends Controller public function ldaptestlogin(Request $request, LdapAd $ldap) { - - if (Setting::getSettings()->ldap_enabled!='1') { + if (Setting::getSettings()->ldap_enabled != '1') { \Log::debug('LDAP is not enabled. Cannot test.'); + return response()->json(['message' => 'LDAP is not enabled, cannot test.'], 400); } - - $rules = array( + $rules = [ 'ldaptest_user' => 'required', - 'ldaptest_password' => 'required' - ); + 'ldaptest_password' => 'required', + ]; $validator = Validator::make($request->all(), $rules); if ($validator->fails()) { \Log::debug('LDAP Validation test failed.'); - $validation_errors = implode(' ',$validator->errors()->all()); + $validation_errors = implode(' ', $validator->errors()->all()); + return response()->json(['message' => $validator->errors()->all()], 400); } - \Log::debug('Preparing to test LDAP login'); try { @@ -147,52 +146,48 @@ class SettingsController extends Controller // can't do this because that's a protected property. $results = $ldap->ldapLogin($request->input('ldaptest_user'), $request->input('ldaptest_password')); // this would normally create a user on success (if they didn't already exist), but for the transaction - if($results) { - return response()->json(['message' => 'It worked! '. $request->input('ldaptest_user').' successfully binded to LDAP.'], 200); + if ($results) { + return response()->json(['message' => 'It worked! '.$request->input('ldaptest_user').' successfully binded to LDAP.'], 200); } else { - return response()->json(['message' => 'Login Failed. '. $request->input('ldaptest_user').' did not successfully bind to LDAP.'], 400); + return response()->json(['message' => 'Login Failed. '.$request->input('ldaptest_user').' did not successfully bind to LDAP.'], 400); } } catch (\Exception $e) { \Log::debug('Connection failed'); + return response()->json(['message' => $e->getMessage()], 400); } finally { DB::rollBack(); // ALWAYS rollback, whether success or failure } - - } public function slacktest(Request $request) { - $slack = new Client([ 'base_url' => e($request->input('slack_endpoint')), 'defaults' => [ - 'exceptions' => false - ] + 'exceptions' => false, + ], ]); - $payload = json_encode( [ 'channel' => e($request->input('slack_channel')), 'text' => trans('general.slack_test_msg'), 'username' => e($request->input('slack_botname')), - 'icon_emoji' => ':heart:' + 'icon_emoji' => ':heart:', ]); try { - $slack->post($request->input('slack_endpoint'),['body' => $payload]); + $slack->post($request->input('slack_endpoint'), ['body' => $payload]); + return response()->json(['message' => 'Success'], 200); } catch (\Exception $e) { return response()->json(['message' => 'Oops! Please check the channel name and webhook endpoint URL. Slack responded with: '.$e->getMessage()], 400); } return response()->json(['message' => 'Something went wrong :( '], 400); - } - /** * Test the email configuration * @@ -202,19 +197,19 @@ class SettingsController extends Controller */ public function ajaxTestEmail() { - if (!config('app.lock_passwords')) { + if (! config('app.lock_passwords')) { try { Notification::send(Setting::first(), new MailTest()); + return response()->json(['message' => 'Mail sent to '.config('mail.reply_to.address')], 200); } catch (\Exception $e) { return response()->json(['message' => $e->getMessage()], 500); } } + return response()->json(['message' => 'Mail would have been sent, but this application is in demo mode! '], 200); - } - /** * Delete server-cached barcodes * @@ -224,23 +219,20 @@ class SettingsController extends Controller */ public function purgeBarcodes() { - $file_count = 0; $files = Storage::disk('public')->files('barcodes'); foreach ($files as $file) { // iterate files - $file_parts = explode(".", $file); + $file_parts = explode('.', $file); $extension = end($file_parts); \Log::debug($extension); // Only generated barcodes would have a .png file extension - if ($extension =='png') { - + if ($extension == 'png') { \Log::debug('Deleting: '.$file); - - try { + try { Storage::disk('public')->delete($file); \Log::debug('Deleting: '.$file); $file_count++; @@ -248,17 +240,11 @@ class SettingsController extends Controller \Log::debug($e); } } - } return response()->json(['message' => 'Deleted '.$file_count.' barcodes'], 200); - } - - - - /** * Get a list of login attempts * @@ -269,20 +255,16 @@ class SettingsController extends Controller */ public function showLoginAttempts(Request $request) { - $allowed_columns = ['id', 'username', 'remote_ip', 'user_agent','successful','created_at']; + $allowed_columns = ['id', 'username', 'remote_ip', 'user_agent', 'successful', 'created_at']; - $login_attempts = DB::table('login_attempts'); + $login_attempts = DB::table('login_attempts'); $order = $request->input('order') === 'asc' ? 'asc' : 'desc'; $sort = in_array($request->get('sort'), $allowed_columns) ? $request->get('sort') : 'created_at'; $total = $login_attempts->count(); $login_attempts->orderBy($sort, $order); - $login_attempt_results = $login_attempts->skip(request('offset', 0))->take(request('limit', 20))->get(); + $login_attempt_results = $login_attempts->skip(request('offset', 0))->take(request('limit', 20))->get(); return (new LoginAttemptsTransformer)->transformLoginAttempts($login_attempt_results, $total); - } - - - } diff --git a/app/Http/Controllers/Api/StatuslabelsController.php b/app/Http/Controllers/Api/StatuslabelsController.php index 534c49a568..91fe02b803 100644 --- a/app/Http/Controllers/Api/StatuslabelsController.php +++ b/app/Http/Controllers/Api/StatuslabelsController.php @@ -22,7 +22,7 @@ class StatuslabelsController extends Controller public function index(Request $request) { $this->authorize('view', Statuslabel::class); - $allowed_columns = ['id','name','created_at', 'assets_count','color', 'notes','default_label']; + $allowed_columns = ['id', 'name', 'created_at', 'assets_count', 'color', 'notes', 'default_label']; $statuslabels = Statuslabel::withCount('assets as assets_count'); @@ -43,6 +43,7 @@ class StatuslabelsController extends Controller $total = $statuslabels->count(); $statuslabels = $statuslabels->skip($offset)->take($limit)->get(); + return (new StatuslabelsTransformer)->transformStatuslabels($statuslabels, $total); } @@ -58,19 +59,19 @@ class StatuslabelsController extends Controller public function store(Request $request) { $this->authorize('create', Statuslabel::class); - $request->except('deployable', 'pending','archived'); + $request->except('deployable', 'pending', 'archived'); - if (!$request->filled('type')) { - return response()->json(Helper::formatStandardApiResponse('error', null, ["type" => ["Status label type is required."]]),500); + if (! $request->filled('type')) { + return response()->json(Helper::formatStandardApiResponse('error', null, ['type' => ['Status label type is required.']]), 500); } $statuslabel = new Statuslabel; $statuslabel->fill($request->all()); $statusType = Statuslabel::getStatuslabelTypesForDB($request->input('type')); - $statuslabel->deployable = $statusType['deployable']; - $statuslabel->pending = $statusType['pending']; - $statuslabel->archived = $statusType['archived']; + $statuslabel->deployable = $statusType['deployable']; + $statuslabel->pending = $statusType['pending']; + $statuslabel->archived = $statusType['archived']; $statuslabel->color = $request->input('color'); $statuslabel->show_in_nav = $request->input('show_in_nav', 0); $statuslabel->default_label = $request->input('default_label'); @@ -79,8 +80,8 @@ class StatuslabelsController extends Controller if ($statuslabel->save()) { return response()->json(Helper::formatStandardApiResponse('success', $statuslabel, trans('admin/statuslabels/message.create.success'))); } - return response()->json(Helper::formatStandardApiResponse('error', null, $statuslabel->getErrors())); + return response()->json(Helper::formatStandardApiResponse('error', null, $statuslabel->getErrors())); } /** @@ -95,10 +96,10 @@ class StatuslabelsController extends Controller { $this->authorize('view', Statuslabel::class); $statuslabel = Statuslabel::findOrFail($id); + return (new StatuslabelsTransformer)->transformStatuslabel($statuslabel); } - /** * Update the specified resource in storage. * @@ -113,16 +114,18 @@ class StatuslabelsController extends Controller $this->authorize('update', Statuslabel::class); $statuslabel = Statuslabel::findOrFail($id); - $request->except('deployable', 'pending','archived'); - + $request->except('deployable', 'pending', 'archived'); + if (! $request->filled('type')) { + return response()->json(Helper::formatStandardApiResponse('error', null, 'Status label type is required.')); + } $statuslabel->fill($request->all()); $statusType = Statuslabel::getStatuslabelTypesForDB($request->input('type')); - $statuslabel->deployable = $statusType['deployable']; - $statuslabel->pending = $statusType['pending']; - $statuslabel->archived = $statusType['archived']; + $statuslabel->deployable = $statusType['deployable']; + $statuslabel->pending = $statusType['pending']; + $statuslabel->archived = $statusType['archived']; $statuslabel->color = $request->input('color'); $statuslabel->show_in_nav = $request->input('show_in_nav'); $statuslabel->default_label = $request->input('default_label'); @@ -151,15 +154,13 @@ class StatuslabelsController extends Controller // Check that there are no assets associated if ($statuslabel->assets()->count() == 0) { $statuslabel->delete(); - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/statuslabels/message.delete.success'))); + + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/statuslabels/message.delete.success'))); } return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/statuslabels/message.assoc_assets'))); - } - - /** * Show a count of assets by status label for pie chart * @@ -167,24 +168,23 @@ class StatuslabelsController extends Controller * @since [v3.0] * @return \Illuminate\Http\Response */ - public function getAssetCountByStatuslabel() { $this->authorize('view', Statuslabel::class); $statuslabels = Statuslabel::withCount('assets')->get(); - $labels=[]; - $points=[]; + $labels = []; + $points = []; $default_color_count = 0; - $colors_array = array(); + $colors_array = []; foreach ($statuslabels as $statuslabel) { if ($statuslabel->assets_count > 0) { - $labels[]=$statuslabel->name. ' ('.number_format($statuslabel->assets_count).')'; - $points[]=$statuslabel->assets_count; + $labels[] = $statuslabel->name.' ('.number_format($statuslabel->assets_count).')'; + $points[] = $statuslabel->assets_count; - if ($statuslabel->color!='') { + if ($statuslabel->color != '') { $colors_array[] = $statuslabel->color; } else { $colors_array[] = Helper::defaultChartColors($default_color_count); @@ -193,14 +193,15 @@ class StatuslabelsController extends Controller } } - $result= [ - "labels" => $labels, - "datasets" => [ [ - "data" => $points, - "backgroundColor" => $colors_array, - "hoverBackgroundColor" => $colors_array - ]] + $result = [ + 'labels' => $labels, + 'datasets' => [[ + 'data' => $points, + 'backgroundColor' => $colors_array, + 'hoverBackgroundColor' => $colors_array, + ]], ]; + return $result; } @@ -216,7 +217,7 @@ class StatuslabelsController extends Controller { $this->authorize('view', Statuslabel::class); $this->authorize('index', Asset::class); - $assets = Asset::where('status_id','=',$id)->with('assignedTo'); + $assets = Asset::where('status_id', '=', $id)->with('assignedTo'); $allowed_columns = [ 'id', @@ -246,11 +247,12 @@ class StatuslabelsController extends Controller * * @author [A. Gianotto] [] * @since [v4.0] - * @return Bool + * @return bool */ - public function checkIfDeployable($id) { + public function checkIfDeployable($id) + { $statuslabel = Statuslabel::findOrFail($id); - if ($statuslabel->getStatuslabelType()=='deployable') { + if ($statuslabel->getStatuslabelType() == 'deployable') { return '1'; } diff --git a/app/Http/Controllers/Api/SuppliersController.php b/app/Http/Controllers/Api/SuppliersController.php index 54784a4e37..e5668b6baa 100644 --- a/app/Http/Controllers/Api/SuppliersController.php +++ b/app/Http/Controllers/Api/SuppliersController.php @@ -23,10 +23,10 @@ class SuppliersController extends Controller public function index(Request $request) { $this->authorize('view', Supplier::class); - $allowed_columns = ['id','name','address','phone','contact','fax','email','image','assets_count','licenses_count', 'accessories_count','url']; + $allowed_columns = ['id', 'name', 'address', 'phone', 'contact', 'fax', 'email', 'image', 'assets_count', 'licenses_count', 'accessories_count', 'url']; $suppliers = Supplier::select( - array('id','name','address','address2','city','state','country','fax', 'phone','email','contact','created_at','updated_at','deleted_at','image','notes') + ['id', 'name', 'address', 'address2', 'city', 'state', 'country', 'fax', 'phone', 'email', 'contact', 'created_at', 'updated_at', 'deleted_at', 'image', 'notes'] )->withCount('assets as assets_count')->withCount('licenses as licenses_count')->withCount('accessories as accessories_count'); @@ -47,6 +47,7 @@ class SuppliersController extends Controller $total = $suppliers->count(); $suppliers = $suppliers->skip($offset)->take($limit)->get(); + return (new SuppliersTransformer)->transformSuppliers($suppliers, $total); } @@ -69,8 +70,8 @@ class SuppliersController extends Controller if ($supplier->save()) { return response()->json(Helper::formatStandardApiResponse('success', $supplier, trans('admin/suppliers/message.create.success'))); } - return response()->json(Helper::formatStandardApiResponse('error', null, $supplier->getErrors())); + return response()->json(Helper::formatStandardApiResponse('error', null, $supplier->getErrors())); } /** @@ -85,10 +86,10 @@ class SuppliersController extends Controller { $this->authorize('view', Supplier::class); $supplier = Supplier::findOrFail($id); + return (new SuppliersTransformer)->transformSupplier($supplier); } - /** * Update the specified resource in storage. * @@ -123,16 +124,15 @@ class SuppliersController extends Controller public function destroy($id) { $this->authorize('delete', Supplier::class); - $supplier = Supplier::with('asset_maintenances', 'assets', 'licenses')->withCount('asset_maintenances as asset_maintenances_count','assets as assets_count', 'licenses as licenses_count')->findOrFail($id); + $supplier = Supplier::with('asset_maintenances', 'assets', 'licenses')->withCount('asset_maintenances as asset_maintenances_count', 'assets as assets_count', 'licenses as licenses_count')->findOrFail($id); $this->authorize('delete', $supplier); - if ($supplier->assets_count > 0) { - return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/suppliers/message.delete.assoc_assets', ['asset_count' => (int) $supplier->assets_count]))); + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/suppliers/message.delete.assoc_assets', ['asset_count' => (int) $supplier->assets_count]))); } if ($supplier->asset_maintenances_count > 0) { - return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/suppliers/message.delete.assoc_maintenances', ['asset_maintenances_count' => $supplier->asset_maintenances_count]))); + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/suppliers/message.delete.assoc_maintenances', ['asset_maintenances_count' => $supplier->asset_maintenances_count]))); } if ($supplier->licenses_count > 0) { @@ -140,8 +140,8 @@ class SuppliersController extends Controller } $supplier->delete(); - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/suppliers/message.delete.success'))); + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/suppliers/message.delete.success'))); } /** @@ -150,11 +150,9 @@ class SuppliersController extends Controller * @author [A. Gianotto] [] * @since [v4.0.16] * @see \App\Http\Transformers\SelectlistTransformer - * */ public function selectlist(Request $request) { - $suppliers = Supplier::select([ 'id', 'name', @@ -176,7 +174,5 @@ class SuppliersController extends Controller } return (new SelectlistTransformer)->transformSelectlist($suppliers); - } - } diff --git a/app/Http/Controllers/Api/UsersController.php b/app/Http/Controllers/Api/UsersController.php index 6893480466..ed6ab5bd62 100644 --- a/app/Http/Controllers/Api/UsersController.php +++ b/app/Http/Controllers/Api/UsersController.php @@ -64,14 +64,13 @@ class UsersController extends Controller 'users.zip', 'users.ldap_import', - ])->with('manager', 'groups', 'userloc', 'company', 'department','assets','licenses','accessories','consumables') - ->withCount('assets as assets_count','licenses as licenses_count','accessories as accessories_count','consumables as consumables_count'); + ])->with('manager', 'groups', 'userloc', 'company', 'department', 'assets', 'licenses', 'accessories', 'consumables') + ->withCount('assets as assets_count', 'licenses as licenses_count', 'accessories as accessories_count', 'consumables as consumables_count'); $users = Company::scopeCompanyables($users); - - if (($request->filled('deleted')) && ($request->input('deleted')=='true')) { + if (($request->filled('deleted')) && ($request->input('deleted') == 'true')) { $users = $users->onlyTrashed(); - } elseif (($request->filled('all')) && ($request->input('all')=='true')) { + } elseif (($request->filled('all')) && ($request->input('all') == 'true')) { $users = $users->withTrashed(); } @@ -124,7 +123,7 @@ class UsersController extends Controller } if ($request->filled('department_id')) { - $users = $users->where('users.department_id','=',$request->input('department_id')); + $users = $users->where('users.department_id', '=', $request->input('department_id')); } if ($request->filled('manager_id')) { @@ -145,7 +144,6 @@ class UsersController extends Controller // Check to make sure the limit is not higher than the max allowed ((config('app.max_results') >= $request->input('limit')) && ($request->filled('limit'))) ? $limit = $request->input('limit') : $limit = config('app.max_results'); - switch ($request->input('sort')) { case 'manager': $users = $users->OrderManager($order); @@ -162,11 +160,11 @@ class UsersController extends Controller default: $allowed_columns = [ - 'last_name','first_name','email','jobtitle','username','employee_num', - 'assets','accessories', 'consumables','licenses','groups','activated','created_at', - 'two_factor_enrolled','two_factor_optin','last_login', 'assets_count', 'licenses_count', + 'last_name', 'first_name', 'email', 'jobtitle', 'username', 'employee_num', + 'assets', 'accessories', 'consumables', 'licenses', 'groups', 'activated', 'created_at', + 'two_factor_enrolled', 'two_factor_optin', 'last_login', 'assets_count', 'licenses_count', 'consumables_count', 'accessories_count', 'phone', 'address', 'city', 'state', - 'country', 'zip', 'id', 'ldap_import' + 'country', 'zip', 'id', 'ldap_import', ]; $sort = in_array($request->get('sort'), $allowed_columns) ? $request->get('sort') : 'first_name'; @@ -174,24 +172,21 @@ class UsersController extends Controller break; } - $total = $users->count(); $users = $users->skip($offset)->take($limit)->get(); + return (new UsersTransformer)->transformUsers($users, $total); } - /** * Gets a paginated collection for the select2 menus * * @author [A. Gianotto] [] * @since [v4.0.16] * @see \App\Http\Transformers\SelectlistTransformer - * */ public function selectlist(Request $request) { - $users = User::select( [ 'users.id', @@ -218,16 +213,16 @@ class UsersController extends Controller foreach ($users as $user) { $name_str = ''; - if ($user->last_name!='') { + if ($user->last_name != '') { $name_str .= $user->last_name.', '; } $name_str .= $user->first_name; - if ($user->username!='') { + if ($user->username != '') { $name_str .= ' ('.$user->username.')'; } - if ($user->employee_num!='') { + if ($user->employee_num != '') { $name_str .= ' - #'.$user->employee_num; } @@ -236,11 +231,8 @@ class UsersController extends Controller } return (new SelectlistTransformer)->transformSelectlist($users); - } - - /** * Store a newly created resource in storage. * @@ -257,17 +249,16 @@ class UsersController extends Controller $user->fill($request->all()); if ($request->has('permissions')) { - $permissions_array = $request->input('permissions'); // Strip out the superuser permission if the API user isn't a superadmin - if (!Auth::user()->isSuperUser()) { + if (! Auth::user()->isSuperUser()) { unset($permissions_array['superuser']); } - $user->permissions = $permissions_array; + $user->permissions = $permissions_array; } - $tmp_pass = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20); + $tmp_pass = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 20); $user->password = bcrypt($request->get('password', $tmp_pass)); app('App\Http\Requests\ImageUploadRequest')->handleImages($user, 600, 'image', 'avatars', 'avatar'); @@ -276,11 +267,12 @@ class UsersController extends Controller if ($request->filled('groups')) { $user->groups()->sync($request->input('groups')); } else { - $user->groups()->sync(array()); + $user->groups()->sync([]); } - + return response()->json(Helper::formatStandardApiResponse('success', (new UsersTransformer)->transformUser($user), trans('admin/users/message.success.create'))); } + return response()->json(Helper::formatStandardApiResponse('error', null, $user->getErrors())); } @@ -294,11 +286,11 @@ class UsersController extends Controller public function show($id) { $this->authorize('view', User::class); - $user = User::withCount('assets as assets_count','licenses as licenses_count','accessories as accessories_count','consumables as consumables_count')->findOrFail($id); + $user = User::withCount('assets as assets_count', 'licenses as licenses_count', 'accessories as accessories_count', 'consumables as consumables_count')->findOrFail($id); + return (new UsersTransformer)->transformUser($user); } - /** * Update the specified resource in storage. * @@ -328,7 +320,6 @@ class UsersController extends Controller return response()->json(Helper::formatStandardApiResponse('error', null, 'Permission denied. You cannot update user information via API on the demo.')); } - $user->fill($request->all()); if ($user->id == $request->input('manager_id')) { @@ -343,19 +334,15 @@ class UsersController extends Controller // here because we need to overwrite permissions // if someone needs to null them out if ($request->has('permissions')) { - $permissions_array = $request->input('permissions'); // Strip out the superuser permission if the API user isn't a superadmin - if (!Auth::user()->isSuperUser()) { + if (! Auth::user()->isSuperUser()) { unset($permissions_array['superuser']); } - $user->permissions = $permissions_array; + $user->permissions = $permissions_array; } - - - // Update the location of any assets checked out to this user Asset::where('assigned_type', User::class) ->where('assigned_to', $user->id)->update(['location_id' => $request->input('location_id', null)]); @@ -375,11 +362,10 @@ class UsersController extends Controller if ($request->filled('groups')) { $user->groups()->sync($request->input('groups')); // The groups field has been passed but it is null, so we should blank it out - } elseif ($request->has('groups')) { - $user->groups()->sync(array()); + } elseif ($request->has('groups')) { + $user->groups()->sync([]); } - return response()->json(Helper::formatStandardApiResponse('success', (new UsersTransformer)->transformUser($user), trans('admin/users/message.success.update'))); } @@ -400,36 +386,37 @@ class UsersController extends Controller $user = User::findOrFail($id); $this->authorize('delete', $user); - if (($user->assets) && ($user->assets->count() > 0)) { - return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/users/message.error.delete_has_assets'))); + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/users/message.error.delete_has_assets'))); } if (($user->licenses) && ($user->licenses->count() > 0)) { - return response()->json(Helper::formatStandardApiResponse('error', null, 'This user still has ' . $user->licenses->count() . ' license(s) associated with them and cannot be deleted.')); + return response()->json(Helper::formatStandardApiResponse('error', null, 'This user still has '.$user->licenses->count().' license(s) associated with them and cannot be deleted.')); } if (($user->accessories) && ($user->accessories->count() > 0)) { - return response()->json(Helper::formatStandardApiResponse('error', null, 'This user still has ' . $user->accessories->count() . ' accessories associated with them.')); + return response()->json(Helper::formatStandardApiResponse('error', null, 'This user still has '.$user->accessories->count().' accessories associated with them.')); } if (($user->managedLocations()) && ($user->managedLocations()->count() > 0)) { - return response()->json(Helper::formatStandardApiResponse('error', null, 'This user still has ' . $user->managedLocations()->count() . ' locations that they manage.')); + return response()->json(Helper::formatStandardApiResponse('error', null, 'This user still has '.$user->managedLocations()->count().' locations that they manage.')); } if ($user->delete()) { // Remove the user's avatar if they have one if (Storage::disk('public')->exists('avatars/'.$user->avatar)) { - try { + try { Storage::disk('public')->delete('avatars/'.$user->avatar); } catch (\Exception $e) { \Log::debug($e); - } + } } - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/users/message.success.delete'))); + + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/users/message.success.delete'))); } - return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/users/message.error.delete'))); + + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/users/message.error.delete'))); } /** @@ -445,6 +432,7 @@ class UsersController extends Controller $this->authorize('view', User::class); $this->authorize('view', Asset::class); $assets = Asset::where('assigned_to', '=', $id)->where('assigned_type', '=', User::class)->with('model')->get(); + return (new AssetsTransformer)->transformAssets($assets, $assets->count()); } @@ -462,6 +450,7 @@ class UsersController extends Controller $user = User::findOrFail($id); $this->authorize('view', Accessory::class); $accessories = $user->accessories; + return (new AccessoriesTransformer)->transformAccessories($accessories, $accessories->count()); } @@ -479,12 +468,11 @@ class UsersController extends Controller $this->authorize('view', License::class); $user = User::where('id', $id)->withTrashed()->first(); $licenses = $user->licenses()->get(); + return (new LicensesTransformer())->transformLicenses($licenses, $licenses->count()); } /** - - * Reset the user's two-factor status * * @author [A. Gianotto] [] @@ -494,7 +482,6 @@ class UsersController extends Controller */ public function postTwoFactorReset(Request $request) { - $this->authorize('update', User::class); if ($request->filled('id')) { @@ -503,13 +490,14 @@ class UsersController extends Controller $user->two_factor_secret = null; $user->two_factor_enrolled = 0; $user->save(); + return response()->json(['message' => trans('admin/settings/general.two_factor_reset_success')], 200); } catch (\Exception $e) { return response()->json(['message' => trans('admin/settings/general.two_factor_reset_error')], 500); } } - return response()->json(['message' => 'No ID provided'], 500); + return response()->json(['message' => 'No ID provided'], 500); } /** @@ -524,4 +512,28 @@ class UsersController extends Controller { return (new UsersTransformer)->transformUser($request->user()); } + + /** + * Restore a soft-deleted user. + * + * @author [E. Taylor] [] + * @param int $userId + * @since [v6.0.0] + * @return JsonResponse + */ + public function restore($userId = null) + { + // Get asset information + $user = User::withTrashed()->find($userId); + $this->authorize('delete', $user); + if (isset($user->id)) { + // Restore the user + User::withTrashed()->where('id', $userId)->restore(); + + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/users/message.success.restored'))); + } + + $id = $userId; + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/users/message.user_not_found', compact('id'))), 200); + } } diff --git a/app/Http/Controllers/AssetMaintenancesController.php b/app/Http/Controllers/AssetMaintenancesController.php index c9fb3340ee..b1c28ea26a 100644 --- a/app/Http/Controllers/AssetMaintenancesController.php +++ b/app/Http/Controllers/AssetMaintenancesController.php @@ -1,4 +1,5 @@ supplier_id = $request->input('supplier_id'); $assetMaintenance->is_warranty = $request->input('is_warranty'); - $assetMaintenance->cost = $request->input('cost'); + $assetMaintenance->cost = $request->input('cost'); $assetMaintenance->notes = $request->input('notes'); $asset = Asset::find($request->input('asset_id')); - if ((!Company::isCurrentUserHasAccess($asset)) && ($asset!=null)) { + if ((! Company::isCurrentUserHasAccess($asset)) && ($asset != null)) { return static::getInsufficientPermissionsRedirect(); } // Save the asset maintenance data - $assetMaintenance->asset_id = $request->input('asset_id'); + $assetMaintenance->asset_id = $request->input('asset_id'); $assetMaintenance->asset_maintenance_type = $request->input('asset_maintenance_type'); - $assetMaintenance->title = $request->input('title'); - $assetMaintenance->start_date = $request->input('start_date'); - $assetMaintenance->completion_date = $request->input('completion_date'); - $assetMaintenance->user_id = Auth::id(); + $assetMaintenance->title = $request->input('title'); + $assetMaintenance->start_date = $request->input('start_date'); + $assetMaintenance->completion_date = $request->input('completion_date'); + $assetMaintenance->user_id = Auth::id(); - if (( $assetMaintenance->completion_date !== null ) - && ( $assetMaintenance->start_date !== "" ) - && ( $assetMaintenance->start_date !== "0000-00-00" ) + if (($assetMaintenance->completion_date !== null) + && ($assetMaintenance->start_date !== '') + && ($assetMaintenance->start_date !== '0000-00-00') ) { - $startDate = Carbon::parse($assetMaintenance->start_date); - $completionDate = Carbon::parse($assetMaintenance->completion_date); + $startDate = Carbon::parse($assetMaintenance->start_date); + $completionDate = Carbon::parse($assetMaintenance->completion_date); $assetMaintenance->asset_maintenance_time = $completionDate->diffInDays($startDate); } @@ -133,7 +131,6 @@ class AssetMaintenancesController extends Controller } return redirect()->back()->withInput()->withErrors($assetMaintenance->getErrors()); - } /** @@ -153,11 +150,10 @@ class AssetMaintenancesController extends Controller // Redirect to the improvement management page return redirect()->route('maintenances.index') ->with('error', trans('admin/asset_maintenances/message.not_found')); - } elseif (!$assetMaintenance->asset) { + } elseif (! $assetMaintenance->asset) { return redirect()->route('maintenances.index') ->with('error', 'The asset associated with this maintenance does not exist.'); - - } elseif (!Company::isCurrentUserHasAccess($assetMaintenance->asset)) { + } elseif (! Company::isCurrentUserHasAccess($assetMaintenance->asset)) { return static::getInsufficientPermissionsRedirect(); } @@ -184,7 +180,6 @@ class AssetMaintenancesController extends Controller ->with('selectedAsset', null) ->with('assetMaintenanceType', $assetMaintenanceType) ->with('item', $assetMaintenance); - } /** @@ -205,7 +200,7 @@ class AssetMaintenancesController extends Controller // Redirect to the asset maintenance management page return redirect()->route('maintenances.index') ->with('error', trans('admin/asset_maintenances/message.not_found')); - } elseif (!Company::isCurrentUserHasAccess($assetMaintenance->asset)) { + } elseif (! Company::isCurrentUserHasAccess($assetMaintenance->asset)) { return static::getInsufficientPermissionsRedirect(); } @@ -216,32 +211,32 @@ class AssetMaintenancesController extends Controller $asset = Asset::find(request('asset_id')); - if (!Company::isCurrentUserHasAccess($asset)) { + if (! Company::isCurrentUserHasAccess($asset)) { return static::getInsufficientPermissionsRedirect(); } // Save the asset maintenance data - $assetMaintenance->asset_id = $request->input('asset_id'); + $assetMaintenance->asset_id = $request->input('asset_id'); $assetMaintenance->asset_maintenance_type = $request->input('asset_maintenance_type'); - $assetMaintenance->title = $request->input('title'); - $assetMaintenance->start_date = $request->input('start_date'); - $assetMaintenance->completion_date = $request->input('completion_date'); + $assetMaintenance->title = $request->input('title'); + $assetMaintenance->start_date = $request->input('start_date'); + $assetMaintenance->completion_date = $request->input('completion_date'); - if (( $assetMaintenance->completion_date == null ) + if (($assetMaintenance->completion_date == null) ) { - if (( $assetMaintenance->asset_maintenance_time !== 0 ) - || ( !is_null($assetMaintenance->asset_maintenance_time) ) + if (($assetMaintenance->asset_maintenance_time !== 0) + || (! is_null($assetMaintenance->asset_maintenance_time)) ) { $assetMaintenance->asset_maintenance_time = null; } } - if (( $assetMaintenance->completion_date !== null ) - && ( $assetMaintenance->start_date !== "" ) - && ( $assetMaintenance->start_date !== "0000-00-00" ) + if (($assetMaintenance->completion_date !== null) + && ($assetMaintenance->start_date !== '') + && ($assetMaintenance->start_date !== '0000-00-00') ) { - $startDate = Carbon::parse($assetMaintenance->start_date); - $completionDate = Carbon::parse($assetMaintenance->completion_date); + $startDate = Carbon::parse($assetMaintenance->start_date); + $completionDate = Carbon::parse($assetMaintenance->completion_date); $assetMaintenance->asset_maintenance_time = $completionDate->diffInDays($startDate); } @@ -252,6 +247,7 @@ class AssetMaintenancesController extends Controller return redirect()->route('maintenances.index') ->with('success', trans('admin/asset_maintenances/message.edit.success')); } + return redirect()->back()->withInput()->withErrors($assetMaintenance->getErrors()); } @@ -271,7 +267,7 @@ class AssetMaintenancesController extends Controller // Redirect to the asset maintenance management page return redirect()->route('maintenances.index') ->with('error', trans('admin/asset_maintenances/message.not_found')); - } elseif (!Company::isCurrentUserHasAccess($assetMaintenance->asset)) { + } elseif (! Company::isCurrentUserHasAccess($assetMaintenance->asset)) { return static::getInsufficientPermissionsRedirect(); } @@ -299,7 +295,7 @@ class AssetMaintenancesController extends Controller // Redirect to the asset maintenance management page return redirect()->route('maintenances.index') ->with('error', trans('admin/asset_maintenances/message.not_found')); - } elseif (!Company::isCurrentUserHasAccess($assetMaintenance->asset)) { + } elseif (! Company::isCurrentUserHasAccess($assetMaintenance->asset)) { return static::getInsufficientPermissionsRedirect(); } diff --git a/app/Http/Controllers/AssetModelsController.php b/app/Http/Controllers/AssetModelsController.php index 29914b40a2..1afc9d8a60 100755 --- a/app/Http/Controllers/AssetModelsController.php +++ b/app/Http/Controllers/AssetModelsController.php @@ -1,4 +1,5 @@ authorize('index', AssetModel::class); + return view('models/index'); } @@ -48,12 +49,12 @@ class AssetModelsController extends Controller public function create() { $this->authorize('create', AssetModel::class); + return view('models/edit')->with('category_type', 'asset') ->with('depreciation_list', Helper::depreciationList()) ->with('item', new AssetModel); } - /** * Validate and process the new Asset Model data. * @@ -65,7 +66,6 @@ class AssetModelsController extends Controller */ public function store(ImageUploadRequest $request) { - $this->authorize('create', AssetModel::class); // Create a new asset model $model = new AssetModel; @@ -73,29 +73,30 @@ class AssetModelsController extends Controller // Save the model data $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->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'); + $model->name = $request->input('name'); + $model->model_number = $request->input('model_number'); + $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('custom_fieldset')!='') { + if ($request->input('custom_fieldset') != '') { $model->fieldset_id = e($request->input('custom_fieldset')); } $model = $request->handleImages($model); - // Was it created? + // Was it created? if ($model->save()) { if ($this->shouldAddDefaultValues($request->input())) { $this->assignCustomFieldsDefaultValues($model, $request->input('default_values')); } // Redirect to the new model page - return redirect()->route("models.index")->with('success', trans('admin/models/message.create.success')); + return redirect()->route('models.index')->with('success', trans('admin/models/message.create.success')); } + return redirect()->back()->withInput()->withErrors($model->getErrors()); } @@ -113,16 +114,15 @@ class AssetModelsController extends Controller $this->authorize('update', AssetModel::class); if ($item = AssetModel::find($modelId)) { $category_type = 'asset'; - $view = View::make('models/edit', compact('item','category_type')); + $view = View::make('models/edit', compact('item', 'category_type')); $view->with('depreciation_list', Helper::depreciationList()); + return $view; } return redirect()->route('models.index')->with('error', trans('admin/models/message.does_not_exist')); - } - /** * Validates and processes form data from the edit * Asset Model form based on the model ID passed. @@ -145,20 +145,18 @@ class AssetModelsController extends Controller $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->manufacturer_id = $request->input('manufacturer_id'); - $model->category_id = $request->input('category_id'); - $model->notes = $request->input('notes'); - $model->requestable = $request->input('requestable', '0'); - - + $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->manufacturer_id = $request->input('manufacturer_id'); + $model->category_id = $request->input('category_id'); + $model->notes = $request->input('notes'); + $model->requestable = $request->input('requestable', '0'); $this->removeCustomFieldsDefaultValues($model); - if ($request->input('custom_fieldset')=='') { + if ($request->input('custom_fieldset') == '') { $model->fieldset_id = null; } else { $model->fieldset_id = $request->input('custom_fieldset'); @@ -168,10 +166,10 @@ class AssetModelsController extends Controller } } - if ($model->save()) { - return redirect()->route("models.index")->with('success', trans('admin/models/message.update.success')); + return redirect()->route('models.index')->with('success', trans('admin/models/message.update.success')); } + return redirect()->back()->withInput()->withErrors($model->getErrors()); } @@ -199,7 +197,7 @@ class AssetModelsController extends Controller } if ($model->image) { - try { + try { Storage::disk('public')->delete('models/'.$model->image); } catch (\Exception $e) { \Log::info($e); @@ -213,7 +211,6 @@ class AssetModelsController extends Controller return redirect()->route('models.index')->with('success', trans('admin/models/message.delete.success')); } - /** * Restore a given Asset Model (mark as un-deleted) * @@ -231,13 +228,13 @@ class AssetModelsController extends Controller if (isset($model->id)) { $model->restore(); + return redirect()->route('models.index')->with('success', trans('admin/models/message.restore.success')); } + return redirect()->back()->with('error', trans('admin/models/message.not_found')); - } - /** * Get the model information to present to the model view page * @@ -260,13 +257,13 @@ class AssetModelsController extends Controller } /** - * Get the clone page to clone a model - * - * @author [A. Gianotto] [] - * @since [v1.0] - * @param int $modelId - * @return View - */ + * Get the clone page to clone a model + * + * @author [A. Gianotto] [] + * @since [v1.0] + * @param int $modelId + * @return View + */ public function getClone($modelId = null) { // Check if the model exists @@ -284,23 +281,19 @@ class AssetModelsController extends Controller ->with('clone_model', $model_to_clone); } - /** - * Get the custom fields form - * - * @author [B. Wetherington] [] - * @since [v2.0] - * @param int $modelId - * @return View - */ + * Get the custom fields form + * + * @author [B. Wetherington] [] + * @since [v2.0] + * @param int $modelId + * @return View + */ public function getCustomFields($modelId) { - return view("models.custom_fields_form")->with("model", AssetModel::find($modelId)); + return view('models.custom_fields_form')->with('model', AssetModel::find($modelId)); } - - - /** * Returns a view that allows the user to bulk edit model attrbutes * @@ -310,28 +303,25 @@ class AssetModelsController extends Controller */ public function postBulkEdit(Request $request) { - $models_raw_array = $request->input('ids'); // Make sure some IDs have been selected if ((is_array($models_raw_array)) && (count($models_raw_array) > 0)) { - - $models = AssetModel::whereIn('id', $models_raw_array)->withCount('assets as assets_count')->orderBy('assets_count', 'ASC')->get(); // If deleting.... - if ($request->input('bulk_actions')=='delete') { + if ($request->input('bulk_actions') == 'delete') { $valid_count = 0; foreach ($models as $model) { if ($model->assets_count == 0) { $valid_count++; } } + 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(); @@ -340,16 +330,12 @@ class AssetModelsController extends Controller ->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 * @@ -359,35 +345,31 @@ class AssetModelsController extends Controller */ public function postBulkEditSave(Request $request) { - $models_raw_array = $request->input('ids'); - $update_array = array(); + $update_array = []; - - if (($request->filled('manufacturer_id') && ($request->input('manufacturer_id')!='NC'))) { + 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'))) { + if (($request->filled('category_id') && ($request->input('category_id') != 'NC'))) { $update_array['category_id'] = $request->input('category_id'); } - if ($request->input('fieldset_id')!='NC') { + if ($request->input('fieldset_id') != 'NC') { $update_array['fieldset_id'] = $request->input('fieldset_id'); } - if ($request->input('depreciation_id')!='NC') { + 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')); - } /** @@ -404,7 +386,6 @@ class AssetModelsController extends Controller $models_raw_array = $request->input('ids'); if ((is_array($models_raw_array)) && (count($models_raw_array) > 0)) { - $models = AssetModel::whereIn('id', $models_raw_array)->withCount('assets as assets_count')->get(); $del_error_count = 0; @@ -426,7 +407,7 @@ class AssetModelsController extends Controller if ($del_error_count == 0) { return redirect()->route('models.index') - ->with('success', trans('admin/models/message.bulkdelete.success',['success_count'=> $del_count] )); + ->with('success', trans('admin/models/message.bulkdelete.success', ['success_count'=> $del_count])); } return redirect()->route('models.index') @@ -435,7 +416,6 @@ class AssetModelsController extends Controller return redirect()->route('models.index') ->with('error', trans('admin/models/message.bulkdelete.error')); - } /** @@ -443,13 +423,13 @@ class AssetModelsController extends Controller * any default values were entered into the form. * * @param array $input - * @return boolean + * @return bool */ private function shouldAddDefaultValues(array $input) { - return !empty($input['add_default_values']) - && !empty($input['default_values']) - && !empty($input['custom_fieldset']); + return ! empty($input['add_default_values']) + && ! empty($input['default_values']) + && ! empty($input['custom_fieldset']); } /** diff --git a/app/Http/Controllers/Assets/AssetCheckinController.php b/app/Http/Controllers/Assets/AssetCheckinController.php index ec0ef1c365..2c34bc5c9c 100644 --- a/app/Http/Controllers/Assets/AssetCheckinController.php +++ b/app/Http/Controllers/Assets/AssetCheckinController.php @@ -13,7 +13,6 @@ use Illuminate\Support\Facades\View; class AssetCheckinController extends Controller { - /** * Returns a view that presents a form to check an asset back into inventory. * @@ -33,6 +32,7 @@ class AssetCheckinController extends Controller } $this->authorize('checkin', $asset); + return view('hardware/checkin', compact('asset'))->with('statusLabel_list', Helper::statusLabelList())->with('backto', $backto); } @@ -73,7 +73,7 @@ class AssetCheckinController extends Controller $asset->name = $request->get('name'); if ($request->filled('status_id')) { - $asset->status_id = e($request->get('status_id')); + $asset->status_id = e($request->get('status_id')); } // This is just meant to correct legacy issues where some user data would have 0 @@ -81,14 +81,14 @@ class AssetCheckinController extends Controller // rules, so it's necessary to fix this for long-time users. It's kinda gross, but will help // people (and their data) in the long run - if ($asset->rtd_location_id=='0') { + if ($asset->rtd_location_id == '0') { \Log::debug('Manually override the RTD location IDs'); \Log::debug('Original RTD Location ID: '.$asset->rtd_location_id); $asset->rtd_location_id = ''; \Log::debug('New RTD Location ID: '.$asset->rtd_location_id); } - if ($asset->location_id=='0') { + if ($asset->location_id == '0') { \Log::debug('Manually override the location IDs'); \Log::debug('Original Location ID: '.$asset->location_id); $asset->location_id = ''; @@ -99,14 +99,13 @@ class AssetCheckinController extends Controller \Log::debug('After Location ID: '.$asset->location_id); \Log::debug('After RTD Location ID: '.$asset->rtd_location_id); - if ($request->filled('location_id')) { \Log::debug('NEW Location ID: '.$request->get('location_id')); - $asset->location_id = e($request->get('location_id')); + $asset->location_id = e($request->get('location_id')); } $checkin_at = date('Y-m-d'); - if($request->filled('checkin_at')){ + if ($request->filled('checkin_at')) { $checkin_at = $request->input('checkin_at'); } @@ -114,12 +113,13 @@ class AssetCheckinController extends Controller if ($asset->save()) { event(new CheckoutableCheckedIn($asset, $target, Auth::user(), $request->input('note'), $checkin_at)); - if ((isset($user)) && ($backto =='user')) { - return redirect()->route("users.show", $user->id)->with('success', trans('admin/hardware/message.checkin.success')); + if ((isset($user)) && ($backto == 'user')) { + return redirect()->route('users.show', $user->id)->with('success', trans('admin/hardware/message.checkin.success')); } - return redirect()->route("hardware.index")->with('success', trans('admin/hardware/message.checkin.success')); + + return redirect()->route('hardware.index')->with('success', trans('admin/hardware/message.checkin.success')); } // Redirect to the asset management page with error - return redirect()->route("hardware.index")->with('error', trans('admin/hardware/message.checkin.error').$asset->getErrors()); + return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.checkin.error').$asset->getErrors()); } } diff --git a/app/Http/Controllers/Assets/AssetCheckoutController.php b/app/Http/Controllers/Assets/AssetCheckoutController.php index dcb5154cfc..dc4ea8fb50 100644 --- a/app/Http/Controllers/Assets/AssetCheckoutController.php +++ b/app/Http/Controllers/Assets/AssetCheckoutController.php @@ -2,7 +2,6 @@ namespace App\Http\Controllers\Assets; - use App\Exceptions\CheckoutNotAllowed; use App\Helpers\Helper; use App\Http\Controllers\CheckInOutRequest; @@ -15,15 +14,16 @@ use Illuminate\Support\Facades\Auth; class AssetCheckoutController extends Controller { use CheckInOutRequest; + /** - * Returns a view that presents a form to check an asset out to a - * user. - * - * @author [A. Gianotto] [] - * @param int $assetId - * @since [v1.0] - * @return View - */ + * Returns a view that presents a form to check an asset out to a + * user. + * + * @author [A. Gianotto] [] + * @param int $assetId + * @since [v1.0] + * @return View + */ public function create($assetId) { // Check if the asset exists @@ -37,9 +37,8 @@ class AssetCheckoutController extends Controller return view('hardware/checkout', compact('asset')) ->with('statusLabel_list', Helper::deployableStatusLabelList()); } + return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.checkout.not_available')); - - } /** @@ -55,9 +54,9 @@ class AssetCheckoutController extends Controller { try { // Check if the asset exists - if (!$asset = Asset::find($assetId)) { + if (! $asset = Asset::find($assetId)) { return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.does_not_exist')); - } elseif (!$asset->availableForCheckout()) { + } elseif (! $asset->availableForCheckout()) { return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.checkout.not_available')); } $this->authorize('checkout', $asset); @@ -67,8 +66,8 @@ class AssetCheckoutController extends Controller $asset = $this->updateAssetLocation($asset, $target); - $checkout_at = date("Y-m-d H:i:s"); - if (($request->filled('checkout_at')) && ($request->get('checkout_at')!= date("Y-m-d"))) { + $checkout_at = date('Y-m-d H:i:s'); + if (($request->filled('checkout_at')) && ($request->get('checkout_at') != date('Y-m-d'))) { $checkout_at = $request->get('checkout_at'); } @@ -82,7 +81,7 @@ class AssetCheckoutController extends Controller } if ($asset->checkOut($target, $admin, $checkout_at, $expected_checkin, e($request->get('note')), $request->get('name'))) { - return redirect()->route("hardware.index")->with('success', trans('admin/hardware/message.checkout.success')); + return redirect()->route('hardware.index')->with('success', trans('admin/hardware/message.checkout.success')); } // Redirect to the asset management page with error @@ -93,5 +92,4 @@ class AssetCheckoutController extends Controller return redirect()->back()->with('error', $e->getMessage()); } } - } diff --git a/app/Http/Controllers/Assets/AssetFilesController.php b/app/Http/Controllers/Assets/AssetFilesController.php index 7cdd075ab9..276705b46a 100644 --- a/app/Http/Controllers/Assets/AssetFilesController.php +++ b/app/Http/Controllers/Assets/AssetFilesController.php @@ -2,14 +2,13 @@ namespace App\Http\Controllers\Assets; - +use App\Helpers\StorageHelper; use App\Http\Controllers\Controller; use App\Http\Requests\AssetFileRequest; use App\Models\Actionlog; use App\Models\Asset; use Illuminate\Support\Facades\Response; use Illuminate\Support\Facades\Storage; -use App\Helpers\StorageHelper; class AssetFilesController extends Controller { @@ -25,15 +24,16 @@ class AssetFilesController extends Controller */ public function store(AssetFileRequest $request, $assetId = null) { - if (!$asset = Asset::find($assetId)) { + if (! $asset = Asset::find($assetId)) { return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.does_not_exist')); } $this->authorize('update', $asset); if ($request->hasFile('file')) { - - if (!Storage::exists('private_uploads/assets')) Storage::makeDirectory('private_uploads/assets', 775); + if (! Storage::exists('private_uploads/assets')) { + Storage::makeDirectory('private_uploads/assets', 775); + } foreach ($request->file('file') as $file) { $extension = $file->getClientOriginalExtension(); @@ -41,6 +41,7 @@ class AssetFilesController extends Controller Storage::put('private_uploads/assets/'.$file_name, file_get_contents($file)); $asset->logUpload($file_name, e($request->get('notes'))); } + return redirect()->back()->with('success', trans('admin/hardware/message.upload.success')); } @@ -64,7 +65,7 @@ class AssetFilesController extends Controller if (isset($asset->id)) { $this->authorize('view', $asset); - if (!$log = Actionlog::find($fileId)) { + if (! $log = Actionlog::find($fileId)) { return response('No matching record for that asset/file', 500) ->header('Content-Type', 'text/plain'); } @@ -72,21 +73,23 @@ class AssetFilesController extends Controller $file = 'private_uploads/assets/'.$log->filename; \Log::debug('Checking for '.$file); - if ($log->action_type =='audit') { + if ($log->action_type == 'audit') { $file = 'private_uploads/audits/'.$log->filename; } - if (!Storage::exists($file)) { + if (! Storage::exists($file)) { return response('File '.$file.' not found on server', 404) ->header('Content-Type', 'text/plain'); } if ($download != 'true') { - if ($contents = file_get_contents(Storage::url($file))) { - return Response::make(Storage::url($file)->header('Content-Type', mime_content_type($file))); - } - return JsonResponse::create(["error" => "Failed validation: "], 500); + if ($contents = file_get_contents(Storage::url($file))) { + return Response::make(Storage::url($file)->header('Content-Type', mime_content_type($file))); + } + + return JsonResponse::create(['error' => 'Failed validation: '], 500); } + return StorageHelper::downloader($file); } // Prepare the error message @@ -117,13 +120,15 @@ class AssetFilesController extends Controller $this->authorize('update', $asset); $log = Actionlog::find($fileId); if ($log) { - if (Storage::exists($rel_path.'/'.$log->filename)) { - Storage::delete($rel_path.'/'.$log->filename); + if (Storage::exists($rel_path.'/'.$log->filename)) { + Storage::delete($rel_path.'/'.$log->filename); } $log->delete(); + return redirect()->back()->with('success', trans('admin/hardware/message.deletefile.success')); } $log->delete(); + return redirect()->back() ->with('success', trans('admin/hardware/message.deletefile.success')); } diff --git a/app/Http/Controllers/Assets/AssetsController.php b/app/Http/Controllers/Assets/AssetsController.php index 8fed678d40..b4ea12b6f1 100755 --- a/app/Http/Controllers/Assets/AssetsController.php +++ b/app/Http/Controllers/Assets/AssetsController.php @@ -1,4 +1,5 @@ 3.5, 'width' => 3.5); - protected $barCodeDimensions = array( 'height' => 2, 'width' => 22); - + protected $qrCodeDimensions = ['height' => 3.5, 'width' => 3.5]; + protected $barCodeDimensions = ['height' => 2, 'width' => 22]; public function __construct() { @@ -65,6 +65,7 @@ class AssetsController extends Controller { $this->authorize('index', Asset::class); $company = Company::find($request->input('company_id')); + return view('hardware/index')->with('company', $company); } @@ -89,6 +90,7 @@ class AssetsController extends Controller $selected_model = AssetModel::find($request->input('model_id')); $view->with('selected_model', $selected_model); } + return $view; } @@ -114,42 +116,41 @@ class AssetsController extends Controller $serials = $request->input('serials'); for ($a = 1; $a <= count($asset_tags); $a++) { - $asset = new Asset(); $asset->model()->associate(AssetModel::find($request->input('model_id'))); - $asset->name = $request->input('name'); + $asset->name = $request->input('name'); // Check for a corresponding serial if (($serials) && (array_key_exists($a, $serials))) { - $asset->serial = $serials[$a]; + $asset->serial = $serials[$a]; } if (($asset_tags) && (array_key_exists($a, $asset_tags))) { - $asset->asset_tag = $asset_tags[$a]; + $asset->asset_tag = $asset_tags[$a]; } - $asset->company_id = Company::getIdForCurrentUser($request->input('company_id')); - $asset->model_id = $request->input('model_id'); - $asset->order_number = $request->input('order_number'); - $asset->notes = $request->input('notes'); - $asset->user_id = Auth::id(); - $asset->archived = '0'; - $asset->physical = '1'; - $asset->depreciate = '0'; - $asset->status_id = request('status_id', 0); - $asset->warranty_months = request('warranty_months', null); - $asset->purchase_cost = Helper::ParseFloat($request->get('purchase_cost')); - $asset->purchase_date = request('purchase_date', null); - $asset->assigned_to = request('assigned_to', null); - $asset->supplier_id = request('supplier_id', 0); - $asset->requestable = request('requestable', 0); - $asset->rtd_location_id = request('rtd_location_id', null); + $asset->company_id = Company::getIdForCurrentUser($request->input('company_id')); + $asset->model_id = $request->input('model_id'); + $asset->order_number = $request->input('order_number'); + $asset->notes = $request->input('notes'); + $asset->user_id = Auth::id(); + $asset->archived = '0'; + $asset->physical = '1'; + $asset->depreciate = '0'; + $asset->status_id = request('status_id', 0); + $asset->warranty_months = request('warranty_months', null); + $asset->purchase_cost = Helper::ParseFloat($request->get('purchase_cost')); + $asset->purchase_date = request('purchase_date', null); + $asset->assigned_to = request('assigned_to', null); + $asset->supplier_id = request('supplier_id', 0); + $asset->requestable = request('requestable', 0); + $asset->rtd_location_id = request('rtd_location_id', null); - if (!empty($settings->audit_interval)) { - $asset->next_audit_date = Carbon::now()->addMonths($settings->audit_interval)->toDateString(); + if (! empty($settings->audit_interval)) { + $asset->next_audit_date = Carbon::now()->addMonths($settings->audit_interval)->toDateString(); } - if ($asset->assigned_to=='') { + if ($asset->assigned_to == '') { $asset->location_id = $request->input('rtd_location_id', null); } @@ -164,17 +165,18 @@ class AssetsController extends Controller if (($model) && ($model->fieldset)) { foreach ($model->fieldset->fields as $field) { - if ($field->field_encrypted=='1') { + if ($field->field_encrypted == '1') { if (Gate::allows('admin')) { - if(is_array($request->input($field->convertUnicodeDbSlug()))){ + if (is_array($request->input($field->convertUnicodeDbSlug()))) { $asset->{$field->convertUnicodeDbSlug()} = \Crypt::encrypt(e(implode(', ', $request->input($field->convertUnicodeDbSlug())))); - }else{ + } else { $asset->{$field->convertUnicodeDbSlug()} = \Crypt::encrypt(e($request->input($field->convertUnicodeDbSlug()))); - } } + } + } } else { - if(is_array($request->input($field->convertUnicodeDbSlug()))){ + if (is_array($request->input($field->convertUnicodeDbSlug()))) { $asset->{$field->convertUnicodeDbSlug()} = implode(', ', $request->input($field->convertUnicodeDbSlug())); - }else{ + } else { $asset->{$field->convertUnicodeDbSlug()} = $request->input($field->convertUnicodeDbSlug()); } } @@ -183,7 +185,6 @@ class AssetsController extends Controller // Validate the asset before saving if ($asset->isValid() && $asset->save()) { - if (request('assigned_user')) { $target = User::find(request('assigned_user')); $location = $target->location_id; @@ -200,10 +201,7 @@ class AssetsController extends Controller } $success = true; - - } - } if ($success) { @@ -213,7 +211,6 @@ class AssetsController extends Controller } return redirect()->back()->withInput()->withErrors($asset->getErrors()); - } /** @@ -226,7 +223,7 @@ class AssetsController extends Controller */ public function edit($assetId = null) { - if (!$item = Asset::find($assetId)) { + if (! $item = Asset::find($assetId)) { // Redirect to the asset management page with error return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.does_not_exist')); } @@ -238,7 +235,6 @@ class AssetsController extends Controller ->with('statuslabel_types', Helper::statusTypeList()); } - /** * Returns a view that presents information about an asset for detail view. * @@ -262,17 +258,17 @@ class AssetsController extends Controller if ($asset->location) { $use_currency = $asset->location->currency; } else { - if ($settings->default_currency!='') { + if ($settings->default_currency != '') { $use_currency = $settings->default_currency; } else { $use_currency = trans('general.currency'); } } - $qr_code = (object) array( + $qr_code = (object) [ 'display' => $settings->qr_code == '1', - 'url' => route('qr_code/hardware', $asset->id) - ); + 'url' => route('qr_code/hardware', $asset->id), + ]; return view('hardware/view', compact('asset', 'qr_code', 'settings')) ->with('use_currency', $use_currency)->with('audit_log', $audit_log); @@ -281,7 +277,6 @@ class AssetsController extends Controller return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.does_not_exist')); } - /** * Validate and process asset edit form. * @@ -290,11 +285,10 @@ class AssetsController extends Controller * @since [v1.0] * @return Redirect */ - public function update(ImageUploadRequest $request, $assetId = null) { // Check if the asset exists - if (!$asset = Asset::find($assetId)) { + if (! $asset = Asset::find($assetId)) { // Redirect to the asset management page with error return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.does_not_exist')); } @@ -311,11 +305,10 @@ class AssetsController extends Controller $asset->requestable = $request->filled('requestable'); $asset->rtd_location_id = $request->input('rtd_location_id', null); - if ($asset->assigned_to=='') { + if ($asset->assigned_to == '') { $asset->location_id = $request->input('rtd_location_id', null); } - if ($request->filled('image_delete')) { try { unlink(public_path().'/uploads/assets/'.$asset->image); @@ -323,21 +316,19 @@ class AssetsController extends Controller } catch (\Exception $e) { \Log::info($e); } - } - // Update the asset data - $asset_tag = $request->input('asset_tags'); - $serial = $request->input('serials'); - $asset->name = $request->input('name'); - $asset->serial = $serial[1]; - $asset->company_id = Company::getIdForCurrentUser($request->input('company_id')); - $asset->model_id = $request->input('model_id'); + $asset_tag = $request->input('asset_tags'); + $serial = $request->input('serials'); + $asset->name = $request->input('name'); + $asset->serial = $serial[1]; + $asset->company_id = Company::getIdForCurrentUser($request->input('company_id')); + $asset->model_id = $request->input('model_id'); $asset->order_number = $request->input('order_number'); - $asset->asset_tag = $asset_tag[1]; - $asset->notes = $request->input('notes'); - $asset->physical = '1'; + $asset->asset_tag = $asset_tag[1]; + $asset->notes = $request->input('notes'); + $asset->physical = '1'; $asset = $request->handleImages($asset); @@ -348,27 +339,26 @@ class AssetsController extends Controller $model = AssetModel::find($request->get('model_id')); if (($model) && ($model->fieldset)) { foreach ($model->fieldset->fields as $field) { - if ($field->field_encrypted=='1') { + if ($field->field_encrypted == '1') { if (Gate::allows('admin')) { - if(is_array($request->input($field->convertUnicodeDbSlug()))){ + if (is_array($request->input($field->convertUnicodeDbSlug()))) { $asset->{$field->convertUnicodeDbSlug()} = \Crypt::encrypt(e(implode(', ', $request->input($field->convertUnicodeDbSlug())))); - }else{ + } else { $asset->{$field->convertUnicodeDbSlug()} = \Crypt::encrypt(e($request->input($field->convertUnicodeDbSlug()))); } } } else { - if(is_array($request->input($field->convertUnicodeDbSlug()))){ + if (is_array($request->input($field->convertUnicodeDbSlug()))) { $asset->{$field->convertUnicodeDbSlug()} = implode(', ', $request->input($field->convertUnicodeDbSlug())); - }else{ + } else { $asset->{$field->convertUnicodeDbSlug()} = $request->input($field->convertUnicodeDbSlug()); } } } } - if ($asset->save()) { - return redirect()->route("hardware.show", $assetId) + return redirect()->route('hardware.show', $assetId) ->with('success', trans('admin/hardware/message.update.success')); } @@ -395,10 +385,10 @@ class AssetsController extends Controller DB::table('assets') ->where('id', $asset->id) - ->update(array('assigned_to' => null)); + ->update(['assigned_to' => null]); if ($asset->image) { - try { + try { Storage::disk('public')->delete('assets'.'/'.$asset->image); } catch (\Exception $e) { \Log::debug($e); @@ -410,8 +400,6 @@ class AssetsController extends Controller return redirect()->route('hardware.index')->with('success', trans('admin/hardware/message.delete.success')); } - - /** * Searches the assets table by asset tag, and redirects if it finds one * @@ -421,14 +409,16 @@ class AssetsController extends Controller */ public function getAssetByTag(Request $request) { - $topsearch = ($request->get('topsearch')=="true"); + $topsearch = ($request->get('topsearch') == 'true'); - if (!$asset = Asset::where('asset_tag', '=', $request->get('assetTag'))->first()) { + if (! $asset = Asset::where('asset_tag', '=', $request->get('assetTag'))->first()) { return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.does_not_exist')); } $this->authorize('view', $asset); + return redirect()->route('hardware.show', $asset->id)->with('topsearch', $topsearch); } + /** * Return a QR code for the asset * @@ -450,20 +440,22 @@ class AssetsController extends Controller if (isset($asset->id, $asset->asset_tag)) { if (file_exists($qr_file)) { $header = ['Content-type' => 'image/png']; + return response()->file($qr_file, $header); } else { $barcode = new \Com\Tecnick\Barcode\Barcode(); - $barcode_obj = $barcode->getBarcodeObj($settings->barcode_type, route('hardware.show', $asset->id), $size['height'], $size['width'], 'black', array(-2, -2, -2, -2)); + $barcode_obj = $barcode->getBarcodeObj($settings->barcode_type, route('hardware.show', $asset->id), $size['height'], $size['width'], 'black', [-2, -2, -2, -2]); file_put_contents($qr_file, $barcode_obj->getPngData()); + return response($barcode_obj->getPngData())->header('Content-type', 'image/png'); } } } + return 'That asset is invalid'; } } - /** * Return a 2D barcode for the asset * @@ -481,6 +473,7 @@ class AssetsController extends Controller if (isset($asset->id, $asset->asset_tag)) { if (file_exists($barcode_file)) { $header = ['Content-type' => 'image/png']; + return response()->file($barcode_file, $header); } else { // Calculate barcode width in pixel based on label width (inch) @@ -488,20 +481,19 @@ class AssetsController extends Controller $barcode = new \Com\Tecnick\Barcode\Barcode(); try { - $barcode_obj = $barcode->getBarcodeObj($settings->alt_barcode,$asset->asset_tag,($barcode_width < 300 ? $barcode_width : 300),50); + $barcode_obj = $barcode->getBarcodeObj($settings->alt_barcode, $asset->asset_tag, ($barcode_width < 300 ? $barcode_width : 300), 50); file_put_contents($barcode_file, $barcode_obj->getPngData()); + return response($barcode_obj->getPngData())->header('Content-type', 'image/png'); - } catch(\Exception $e) { + } catch (\Exception $e) { \Log::debug('The barcode format is invalid.'); + return response(file_get_contents(public_path('uploads/barcodes/invalid_barcode.gif')))->header('Content-type', 'image/gif'); } - - } } } - /** * Return a label for an individual asset. * @@ -523,7 +515,6 @@ class AssetsController extends Controller } } - /** * Returns a view that presents a form to clone an asset. * @@ -564,6 +555,7 @@ class AssetsController extends Controller public function getImportHistory() { $this->authorize('admin'); + return view('hardware/history'); } @@ -572,49 +564,48 @@ class AssetsController extends Controller * * This needs a LOT of love. It's done very inelegantly right now, and there are * a ton of optimizations that could (and should) be done. - * + * * Updated to respect checkin dates: * No checkin column, assume all items are checked in (todays date) * Checkin date in the past, update history. * Checkin date in future or empty, check the item out to the user. - * + * * @author [A. Gianotto] [] * @since [v3.3] * @return View */ public function postImportHistory(Request $request) { - - if (!$request->hasFile('user_import_csv')) { + if (! $request->hasFile('user_import_csv')) { return back()->with('error', 'No file provided. Please select a file for import and try again. '); } - if (!ini_get("auto_detect_line_endings")) { - ini_set("auto_detect_line_endings", '1'); + if (! ini_get('auto_detect_line_endings')) { + ini_set('auto_detect_line_endings', '1'); } $csv = Reader::createFromPath($request->file('user_import_csv')); $csv->setHeaderOffset(0); $header = $csv->getHeader(); - $isCheckinHeaderExplicit = in_array("checkin date", (array_map('strtolower', $header))); + $isCheckinHeaderExplicit = in_array('checkin date', (array_map('strtolower', $header))); $results = $csv->getRecords(); - $item = array(); - $status = array(); - $status['error'] = array(); - $status['success'] = array(); + $item = []; + $status = []; + $status['error'] = []; + $status['success'] = []; foreach ($results as $row) { if (is_array($row)) { $row = array_change_key_case($row, CASE_LOWER); - $asset_tag = Helper::array_smart_fetch($row, "asset tag"); - if (!array_key_exists($asset_tag, $item)) { - $item[$asset_tag] = array(); + $asset_tag = Helper::array_smart_fetch($row, 'asset tag'); + if (! array_key_exists($asset_tag, $item)) { + $item[$asset_tag] = []; } $batch_counter = count($item[$asset_tag]); - $item[$asset_tag][$batch_counter]['checkout_date'] = Carbon::parse(Helper::array_smart_fetch($row, "checkout date"))->format('Y-m-d H:i:s'); - - if ($isCheckinHeaderExplicit){ + $item[$asset_tag][$batch_counter]['checkout_date'] = Carbon::parse(Helper::array_smart_fetch($row, 'checkout date'))->format('Y-m-d H:i:s'); + + if ($isCheckinHeaderExplicit) { //checkin date not empty, assume past transaction or future checkin date (expected) - if (!empty(Helper::array_smart_fetch($row, "checkin date"))) { - $item[$asset_tag][$batch_counter]['checkin_date'] = Carbon::parse(Helper::array_smart_fetch($row, "checkin date"))->format('Y-m-d H:i:s'); + if (! empty(Helper::array_smart_fetch($row, 'checkin date'))) { + $item[$asset_tag][$batch_counter]['checkin_date'] = Carbon::parse(Helper::array_smart_fetch($row, 'checkin date'))->format('Y-m-d H:i:s'); } else { $item[$asset_tag][$batch_counter]['checkin_date'] = ''; } @@ -623,44 +614,44 @@ class AssetsController extends Controller $item[$asset_tag][$batch_counter]['checkin_date'] = Carbon::parse(now())->format('Y-m-d H:i:s'); } - $item[$asset_tag][$batch_counter]['asset_tag'] = Helper::array_smart_fetch($row, "asset tag"); - $item[$asset_tag][$batch_counter]['name'] = Helper::array_smart_fetch($row, "name"); - $item[$asset_tag][$batch_counter]['email'] = Helper::array_smart_fetch($row, "email"); + $item[$asset_tag][$batch_counter]['asset_tag'] = Helper::array_smart_fetch($row, 'asset tag'); + $item[$asset_tag][$batch_counter]['name'] = Helper::array_smart_fetch($row, 'name'); + $item[$asset_tag][$batch_counter]['email'] = Helper::array_smart_fetch($row, 'email'); if ($asset = Asset::where('asset_tag', '=', $asset_tag)->first()) { $item[$asset_tag][$batch_counter]['asset_id'] = $asset->id; $base_username = User::generateFormattedNameFromFullName(Setting::getSettings()->username_format, $item[$asset_tag][$batch_counter]['name']); $user = User::where('username', '=', $base_username['username']); $user_query = ' on username '.$base_username['username']; - if ($request->input('match_firstnamelastname')=='1') { + if ($request->input('match_firstnamelastname') == '1') { $firstnamedotlastname = User::generateFormattedNameFromFullName('firstname.lastname', $item[$asset_tag][$batch_counter]['name']); $item[$asset_tag][$batch_counter]['username'][] = $firstnamedotlastname['username']; $user->orWhere('username', '=', $firstnamedotlastname['username']); $user_query .= ', or on username '.$firstnamedotlastname['username']; } - if ($request->input('match_flastname')=='1') { + if ($request->input('match_flastname') == '1') { $flastname = User::generateFormattedNameFromFullName('filastname', $item[$asset_tag][$batch_counter]['name']); $item[$asset_tag][$batch_counter]['username'][] = $flastname['username']; $user->orWhere('username', '=', $flastname['username']); $user_query .= ', or on username '.$flastname['username']; } - if ($request->input('match_firstname')=='1') { + if ($request->input('match_firstname') == '1') { $firstname = User::generateFormattedNameFromFullName('firstname', $item[$asset_tag][$batch_counter]['name']); $item[$asset_tag][$batch_counter]['username'][] = $firstname['username']; $user->orWhere('username', '=', $firstname['username']); $user_query .= ', or on username '.$firstname['username']; } - if ($request->input('match_email')=='1') { - if ($item[$asset_tag][$batch_counter]['name']=='') { + if ($request->input('match_email') == '1') { + if ($item[$asset_tag][$batch_counter]['name'] == '') { $item[$asset_tag][$batch_counter]['username'][] = $user_email = User::generateEmailFromFullName($item[$asset_tag][$batch_counter]['name']); $user->orWhere('username', '=', $user_email); $user_query .= ', or on username '.$user_email; } } - if ($request->input('match_username') == '1'){ + if ($request->input('match_username') == '1') { // Added #8825: add explicit username lookup - $raw_username = $item[$asset_tag][$batch_counter]['name']; - $user->orWhere('username', '=', $raw_username); - $user_query .= ', or on username ' . $raw_username; + $raw_username = $item[$asset_tag][$batch_counter]['name']; + $user->orWhere('username', '=', $raw_username); + $user_query .= ', or on username '.$raw_username; } // A matching user was found @@ -668,7 +659,7 @@ class AssetsController extends Controller //$user is now matched user from db $item[$asset_tag][$batch_counter]['user_id'] = $user->id; - Actionlog::firstOrCreate(array( + Actionlog::firstOrCreate([ 'item_id' => $asset->id, 'item_type' => Asset::class, 'user_id' => Auth::user()->id, @@ -677,7 +668,7 @@ class AssetsController extends Controller 'target_type' => User::class, 'created_at' => $item[$asset_tag][$batch_counter]['checkout_date'], 'action_type' => 'checkout', - )); + ]); $checkin_date = $item[$asset_tag][$batch_counter]['checkin_date']; @@ -685,7 +676,7 @@ class AssetsController extends Controller //if checkin date header exists, assume that empty or future date is still checked out //if checkin is before todays date, assume it's checked in and do not assign user ID, if checkin date is in the future or blank, this is the expected checkin date, items is checked out - + if ((strtotime($checkin_date) > strtotime(Carbon::now())) || (empty($checkin_date)) ) { //only do this if item is checked out @@ -694,29 +685,27 @@ class AssetsController extends Controller } } - if (!empty($checkin_date)) { + if (! empty($checkin_date)) { //only make a checkin there is a valid checkin date or we created one on import. - Actionlog::firstOrCreate(array( - 'item_id' => - $item[$asset_tag][$batch_counter]['asset_id'], + Actionlog::firstOrCreate([ + 'item_id' => $item[$asset_tag][$batch_counter]['asset_id'], 'item_type' => Asset::class, 'user_id' => Auth::user()->id, - 'note' => 'Checkin imported by ' . Auth::user()->present()->fullName() . ' from history importer', + 'note' => 'Checkin imported by '.Auth::user()->present()->fullName().' from history importer', 'target_id' => null, 'created_at' => $checkin_date, - 'action_type' => 'checkin' - )); - + 'action_type' => 'checkin', + ]); } - + if ($asset->save()) { - $status['success'][]['asset'][$asset_tag]['msg'] = 'Asset successfully matched for '.Helper::array_smart_fetch($row, "name").$user_query.' on '.$item[$asset_tag][$batch_counter]['checkout_date']; + $status['success'][]['asset'][$asset_tag]['msg'] = 'Asset successfully matched for '.Helper::array_smart_fetch($row, 'name').$user_query.' on '.$item[$asset_tag][$batch_counter]['checkout_date']; } else { $status['error'][]['asset'][$asset_tag]['msg'] = 'Asset and user was matched but could not be saved.'; } } else { $item[$asset_tag][$batch_counter]['user_id'] = null; - $status['error'][]['user'][Helper::array_smart_fetch($row, "name")]['msg'] = 'User does not exist so no checkin log was created.'; + $status['error'][]['user'][Helper::array_smart_fetch($row, 'name')]['msg'] = 'User does not exist so no checkin log was created.'; } } else { $item[$asset_tag][$batch_counter]['asset_id'] = null; @@ -724,6 +713,7 @@ class AssetsController extends Controller } } } + return view('hardware/history')->with('status', $status); } @@ -752,12 +742,13 @@ class AssetsController extends Controller $logaction = new Actionlog(); $logaction->item_type = Asset::class; $logaction->item_id = $asset->id; - $logaction->created_at = date("Y-m-d H:i:s"); + $logaction->created_at = date('Y-m-d H:i:s'); $logaction->user_id = Auth::user()->id; $logaction->logaction('restored'); return redirect()->route('hardware.index')->with('success', trans('admin/hardware/message.restore.success')); } + return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.does_not_exist')); } @@ -765,41 +756,42 @@ class AssetsController extends Controller { $this->authorize('audit', Asset::class); $dt = Carbon::now()->addMonths(12)->toDateString(); + return view('hardware/quickscan')->with('next_audit_date', $dt); } - - public function audit($id) { $settings = Setting::getSettings(); $this->authorize('audit', Asset::class); $dt = Carbon::now()->addMonths($settings->audit_interval)->toDateString(); $asset = Asset::findOrFail($id); + return view('hardware/audit')->with('asset', $asset)->with('next_audit_date', $dt)->with('locations_list'); } public function dueForAudit() { $this->authorize('audit', Asset::class); + return view('hardware/audit-due'); } public function overdueForAudit() { $this->authorize('audit', Asset::class); + return view('hardware/audit-overdue'); } - public function auditStore(Request $request, $id) { $this->authorize('audit', Asset::class); - $rules = array( + $rules = [ 'location_id' => 'exists:locations,id|nullable|numeric', - 'next_audit_date' => 'date|nullable' - ); + 'next_audit_date' => 'date|nullable', + ]; $validator = \Validator::make($request->all(), $rules); @@ -817,27 +809,28 @@ class AssetsController extends Controller // Check to see if they checked the box to update the physical location, // not just note it in the audit notes - if ($request->input('update_location')=='1') { + if ($request->input('update_location') == '1') { \Log::debug('update location in audit'); $asset->location_id = $request->input('location_id'); } - if ($asset->save()) { $file_name = ''; // Upload an image, if attached if ($request->hasFile('image')) { $path = 'private_uploads/audits'; - if (!Storage::exists($path)) Storage::makeDirectory($path, 775); + if (! Storage::exists($path)) { + Storage::makeDirectory($path, 775); + } $upload = $image = $request->file('image'); $ext = $image->getClientOriginalExtension(); $file_name = 'audit-'.str_random(18).'.'.$ext; Storage::putFileAs($path, $upload, $file_name); } - $asset->logAudit($request->input('note'), $request->input('location_id'), $file_name); - return redirect()->to("hardware")->with('success', trans('admin/hardware/message.audit.success')); + + return redirect()->to('hardware')->with('success', trans('admin/hardware/message.audit.success')); } } @@ -853,5 +846,4 @@ class AssetsController extends Controller return view('hardware/requested', compact('requestedItems')); } - } diff --git a/app/Http/Controllers/Assets/BulkAssetsController.php b/app/Http/Controllers/Assets/BulkAssetsController.php index 1a6da89c96..ebc2b08738 100644 --- a/app/Http/Controllers/Assets/BulkAssetsController.php +++ b/app/Http/Controllers/Assets/BulkAssetsController.php @@ -28,14 +28,14 @@ class BulkAssetsController extends Controller { $this->authorize('update', Asset::class); - if (!$request->filled('ids')) { + if (! $request->filled('ids')) { return redirect()->back()->with('error', 'No assets selected'); } $asset_ids = array_keys($request->input('ids')); if ($request->filled('bulk_actions')) { - switch($request->input('bulk_actions')) { + switch ($request->input('bulk_actions')) { case 'labels': return view('hardware/labels') ->with('assets', Asset::find($asset_ids)) @@ -47,6 +47,7 @@ class BulkAssetsController extends Controller $assets->each(function ($asset) { $this->authorize('delete', $asset); }); + return view('hardware/bulk-delete')->with('assets', $assets); case 'edit': return view('hardware/bulk') @@ -54,6 +55,7 @@ class BulkAssetsController extends Controller ->with('statuslabel_list', Helper::statusLabelList()); } } + return redirect()->back()->with('error', 'No action selected'); } @@ -71,8 +73,8 @@ class BulkAssetsController extends Controller \Log::debug($request->input('ids')); - if(!$request->filled('ids') || count($request->input('ids')) <= 0) { - return redirect()->route("hardware.index")->with('warning', trans('No assets selected, so nothing was updated.')); + if (! $request->filled('ids') || count($request->input('ids')) <= 0) { + return redirect()->route('hardware.index')->with('warning', trans('No assets selected, so nothing was updated.')); } $assets = array_keys($request->input('ids')); @@ -102,12 +104,12 @@ class BulkAssetsController extends Controller ->conditionallyAddItem('warranty_months'); if ($request->filled('purchase_cost')) { - $this->update_array['purchase_cost'] = Helper::ParseFloat($request->input('purchase_cost')); + $this->update_array['purchase_cost'] = Helper::ParseFloat($request->input('purchase_cost')); } if ($request->filled('company_id')) { - $this->update_array['company_id'] = $request->input('company_id'); - if ($request->input('company_id')=="clear") { + $this->update_array['company_id'] = $request->input('company_id'); + if ($request->input('company_id') == 'clear') { $this->update_array['company_id'] = null; } } @@ -123,29 +125,31 @@ class BulkAssetsController extends Controller ->where('id', $assetId) ->update($this->update_array); } // endforeach - return redirect()->route("hardware.index")->with('success', trans('admin/hardware/message.update.success')); - // no values given, nothing to update - } - return redirect()->route("hardware.index")->with('warning', trans('admin/hardware/message.update.nothing_updated')); + return redirect()->route('hardware.index')->with('success', trans('admin/hardware/message.update.success')); + // no values given, nothing to update + } + + return redirect()->route('hardware.index')->with('warning', trans('admin/hardware/message.update.nothing_updated')); } /** * Array to store update data per item - * @var Array + * @var array */ private $update_array; /** * Adds parameter to update array for an item if it exists in request - * @param String $field field name + * @param string $field field name * @return BulkAssetsController Model for Chaining */ protected function conditionallyAddItem($field) { - if(request()->filled($field)) { + if (request()->filled($field)) { $this->update_array[$field] = request()->input($field); } + return $this; } @@ -173,10 +177,12 @@ class BulkAssetsController extends Controller ->where('id', $asset->id) ->update($update_array); } // endforeach - return redirect()->to("hardware")->with('success', trans('admin/hardware/message.delete.success')); + + return redirect()->to('hardware')->with('success', trans('admin/hardware/message.delete.success')); // no values given, nothing to update } - return redirect()->to("hardware")->with('info', trans('admin/hardware/message.delete.nothing_updated')); + + return redirect()->to('hardware')->with('info', trans('admin/hardware/message.delete.nothing_updated')); } /** @@ -202,21 +208,21 @@ class BulkAssetsController extends Controller $target = $this->determineCheckoutTarget(); - if (!is_array($request->get('selected_assets'))) { + if (! is_array($request->get('selected_assets'))) { return redirect()->route('hardware/bulkcheckout')->withInput()->with('error', trans('admin/hardware/message.checkout.no_assets_selected')); } $asset_ids = array_filter($request->get('selected_assets')); - if(request('checkout_to_type') =='asset') { + if (request('checkout_to_type') == 'asset') { foreach ($asset_ids as $asset_id) { - if ($target->id == $asset_id) { + if ($target->id == $asset_id) { return redirect()->back()->with('error', 'You cannot check an asset out to itself.'); } } } - $checkout_at = date("Y-m-d H:i:s"); - if (($request->filled('checkout_at')) && ($request->get('checkout_at')!= date("Y-m-d"))) { + $checkout_at = date('Y-m-d H:i:s'); + if (($request->filled('checkout_at')) && ($request->get('checkout_at') != date('Y-m-d'))) { $checkout_at = e($request->get('checkout_at')); } @@ -228,13 +234,12 @@ class BulkAssetsController extends Controller $errors = []; DB::transaction(function () use ($target, $admin, $checkout_at, $expected_checkin, $errors, $asset_ids, $request) { - foreach ($asset_ids as $asset_id) { $asset = Asset::findOrFail($asset_id); $this->authorize('checkout', $asset); $error = $asset->checkOut($target, $admin, $checkout_at, $expected_checkin, e($request->get('note')), null); - if ($target->location_id!='') { + if ($target->location_id != '') { $asset->location_id = $target->location_id; $asset->unsetEventDispatcher(); $asset->save(); @@ -246,14 +251,14 @@ class BulkAssetsController extends Controller } }); - if (!$errors) { - // Redirect to the new asset page - return redirect()->to("hardware")->with('success', trans('admin/hardware/message.checkout.success')); + if (! $errors) { + // Redirect to the new asset page + return redirect()->to('hardware')->with('success', trans('admin/hardware/message.checkout.success')); } // Redirect to the asset management page with error - return redirect()->to("hardware/bulk-checkout")->with('error', trans('admin/hardware/message.checkout.error'))->withErrors($errors); + return redirect()->to('hardware/bulk-checkout')->with('error', trans('admin/hardware/message.checkout.error'))->withErrors($errors); } catch (ModelNotFoundException $e) { - return redirect()->to("hardware/bulk-checkout")->with('error', $e->getErrors()); + return redirect()->to('hardware/bulk-checkout')->with('error', $e->getErrors()); } } } diff --git a/app/Http/Controllers/Auth/ForgotPasswordController.php b/app/Http/Controllers/Auth/ForgotPasswordController.php index 7c0348c194..4f7e40998a 100644 --- a/app/Http/Controllers/Auth/ForgotPasswordController.php +++ b/app/Http/Controllers/Auth/ForgotPasswordController.php @@ -41,8 +41,6 @@ class ForgotPasswordController extends Controller return property_exists($this, 'subject') ? $this->subject : \Lang::get('mail.reset_link'); } - - /** * Send a reset link to the given user. * @@ -57,13 +55,10 @@ class ForgotPasswordController extends Controller * buffer overflow issues with attackers sending very large * payloads through. */ - $request->validate([ 'username' => ['required', 'max:255'], ]); - - /** * If we find a matching email with an activated user, we will * send the password reset link to the user. @@ -93,7 +88,6 @@ class ForgotPasswordController extends Controller \Log::info('Password reset attempt: User matching username '.$request->input('username').' NOT FOUND or user is inactive'); } - /** * If an error was returned by the password broker, we will get this message * translated so we can notify a user of the problem. We'll redirect back @@ -109,8 +103,6 @@ class ForgotPasswordController extends Controller // Regardless of response, we do not want to disclose the status of a user account, // so we give them a generic "If this exists, we're TOTALLY gonna email you" response - return redirect()->route('login')->with('success',trans('passwords.sent')); + return redirect()->route('login')->with('success', trans('passwords.sent')); } - - } diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index 101a55bc80..b7bbe45365 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -27,7 +27,6 @@ use Redirect; */ class LoginController extends Controller { - use ThrottlesLogins; // This tells the auth controller to use username instead of email address @@ -61,13 +60,13 @@ class LoginController extends Controller public function __construct(/*LdapAd $ldap, */ Saml $saml) { parent::__construct(); - $this->middleware('guest', ['except' => ['logout','postTwoFactorAuth','getTwoFactorAuth','getTwoFactorEnroll']]); + $this->middleware('guest', ['except' => ['logout', 'postTwoFactorAuth', 'getTwoFactorAuth', 'getTwoFactorEnroll']]); Session::put('backUrl', \URL::previous()); // $this->ldap = $ldap; $this->saml = $saml; } - function showLoginForm(Request $request) + public function showLoginForm(Request $request) { $this->loginViaRemoteUser($request); $this->loginViaSaml($request); @@ -75,11 +74,11 @@ class LoginController extends Controller return redirect()->intended('/'); } - if ($this->saml->isEnabled() && Setting::getSettings()->saml_forcelogin == "1" && !($request->has('nosaml') || $request->session()->has('error'))) { + if ($this->saml->isEnabled() && Setting::getSettings()->saml_forcelogin == '1' && ! ($request->has('nosaml') || $request->session()->has('error'))) { return redirect()->route('saml.login'); } - if (Setting::getSettings()->login_common_disabled == "1") { + if (Setting::getSettings()->login_common_disabled == '1') { return view('errors.403'); } @@ -88,26 +87,26 @@ class LoginController extends Controller /** * Log in a user by SAML - * + * * @author Johnson Yi - * + * * @since 5.0.0 * * @param Request $request - * + * * @return User - * + * * @throws \Exception */ private function loginViaSaml(Request $request) { $saml = $this->saml; $samlData = $request->session()->get('saml_login'); - if ($saml->isEnabled() && !empty($samlData)) { + if ($saml->isEnabled() && ! empty($samlData)) { try { - Log::debug("Attempting to log user in by SAML authentication."); + Log::debug('Attempting to log user in by SAML authentication.'); $user = $saml->samlLogin($samlData); - if(!is_null($user)) { + if (! is_null($user)) { Auth::login($user); } else { $username = $saml->getUsername(); @@ -121,7 +120,7 @@ class LoginController extends Controller $user->save(); } } catch (\Exception $e) { - \Log::warning("There was an error authenticating the SAML user: " . $e->getMessage()); + \Log::warning('There was an error authenticating the SAML user: '.$e->getMessage()); throw new \Exception($e->getMessage()); } } @@ -129,24 +128,24 @@ class LoginController extends Controller /** * Log in a user by LDAP - * + * * @author Wes Hulette - * + * * @since 5.0.0 * * @param Request $request - * + * * @return User - * + * * @throws \Exception */ private function loginViaLdap(Request $request): User { - $ldap = \App::make( LdapAd::class); + $ldap = \App::make(LdapAd::class); try { return $ldap->ldapLogin($request->input('username'), $request->input('password')); } catch (\Exception $ex) { - LOG::debug("LDAP user login: " . $ex->getMessage()); + LOG::debug('LDAP user login: '.$ex->getMessage()); throw new \Exception($ex->getMessage()); } } @@ -155,7 +154,7 @@ class LoginController extends Controller { $header_name = Setting::getSettings()->login_remote_user_header_name ?: 'REMOTE_USER'; $remote_user = $request->server($header_name); - if (Setting::getSettings()->login_remote_user_enabled == "1" && isset($remote_user) && !empty($remote_user)) { + if (Setting::getSettings()->login_remote_user_enabled == '1' && isset($remote_user) && ! empty($remote_user)) { Log::debug("Authenticating via HTTP header $header_name."); $strip_prefixes = [ @@ -170,7 +169,7 @@ class LoginController extends Controller $pos = 0; foreach ($strip_prefixes as $needle) { - if (($pos = strpos($remote_user, $needle)) !== FALSE) { + if (($pos = strpos($remote_user, $needle)) !== false) { $pos += strlen($needle); break; } @@ -178,14 +177,16 @@ class LoginController extends Controller if ($pos > 0) { $remote_user = substr($remote_user, $pos); - }; - + } + try { $user = User::where('username', '=', $remote_user)->whereNull('deleted_at')->where('activated', '=', '1')->first(); - Log::debug("Remote user auth lookup complete"); - if(!is_null($user)) Auth::login($user, $request->input('remember')); - } catch(Exception $e) { - Log::debug("There was an error authenticating the Remote user: " . $e->getMessage()); + Log::debug('Remote user auth lookup complete'); + if (! is_null($user)) { + Auth::login($user, $request->input('remember')); + } + } catch (Exception $e) { + Log::debug('There was an error authenticating the Remote user: '.$e->getMessage()); } } } @@ -197,7 +198,7 @@ class LoginController extends Controller */ public function login(Request $request) { - if (Setting::getSettings()->login_common_disabled == "1") { + if (Setting::getSettings()->login_common_disabled == '1') { return view('errors.403'); } @@ -212,6 +213,7 @@ class LoginController extends Controller if ($lockedOut = $this->hasTooManyLoginAttempts($request)) { $this->fireLockoutEvent($request); + return $this->sendLockoutResponse($request); } @@ -219,34 +221,33 @@ class LoginController extends Controller // Should we even check for LDAP users? if (Setting::getSettings()->ldap_enabled) { // avoid hitting the $this->ldap - LOG::debug("LDAP is enabled."); + LOG::debug('LDAP is enabled.'); try { - LOG::debug("Attempting to log user in by LDAP authentication."); + LOG::debug('Attempting to log user in by LDAP authentication.'); $user = $this->loginViaLdap($request); Auth::login($user, $request->input('remember')); - // If the user was unable to login via LDAP, log the error and let them fall through to + // If the user was unable to login via LDAP, log the error and let them fall through to // local authentication. } catch (\Exception $e) { - Log::debug("There was an error authenticating the LDAP user: ".$e->getMessage()); + Log::debug('There was an error authenticating the LDAP user: '.$e->getMessage()); } } // If the user wasn't authenticated via LDAP, skip to local auth - if (!$user) { - Log::debug("Authenticating user against database."); - // Try to log the user in - if (!Auth::attempt(['username' => $request->input('username'), 'password' => $request->input('password'), 'activated' => 1], $request->input('remember'))) { - - if (!$lockedOut) { + if (! $user) { + Log::debug('Authenticating user against database.'); + // Try to log the user in + if (! Auth::attempt(['username' => $request->input('username'), 'password' => $request->input('password'), 'activated' => 1], $request->input('remember'))) { + if (! $lockedOut) { $this->incrementLoginAttempts($request); } - Log::debug("Local authentication failed."); + Log::debug('Local authentication failed.'); + return redirect()->back()->withInput()->with('error', trans('auth/message.account_not_found')); } else { - - $this->clearLoginAttempts($request); + $this->clearLoginAttempts($request); } } @@ -259,7 +260,6 @@ class LoginController extends Controller return redirect()->intended()->with('success', trans('auth/message.signin.success')); } - /** * Two factor enrollment page * @@ -269,11 +269,10 @@ class LoginController extends Controller { // Make sure the user is logged in - if (!Auth::check()) { + if (! Auth::check()) { return redirect()->route('login')->with('error', trans('auth/general.login_prompt')); } - $settings = Setting::getSettings(); $user = Auth::user(); @@ -283,7 +282,7 @@ class LoginController extends Controller // While you can access this page directly, enrolling a device when 2FA isn't enforced // won't cause any harm. - if (($user->two_factor_secret!='') && ($user->two_factor_enrolled==1)) { + if (($user->two_factor_secret != '') && ($user->two_factor_enrolled == 1)) { return redirect()->route('two-factor')->with('error', trans('auth/message.two_factor.already_enrolled')); } @@ -310,7 +309,6 @@ class LoginController extends Controller return view('auth.two_factor_enroll')->with('barcode_obj', $barcode_obj); } - /** * Two factor code form page * @@ -319,7 +317,7 @@ class LoginController extends Controller public function getTwoFactorAuth() { // Check that the user is logged in - if (!Auth::check()) { + if (! Auth::check()) { return redirect()->route('login')->with('error', trans('auth/general.login_prompt')); } @@ -328,7 +326,7 @@ class LoginController extends Controller // Check whether there is a device enrolled. // This *should* be handled via the \App\Http\Middleware\CheckForTwoFactor middleware // but we're just making sure (in case someone edited the database directly, etc) - if (($user->two_factor_secret=='') || ($user->two_factor_enrolled!=1)) { + if (($user->two_factor_secret == '') || ($user->two_factor_enrolled != 1)) { return redirect()->route('two-factor-enroll'); } @@ -344,16 +342,15 @@ class LoginController extends Controller */ public function postTwoFactorAuth(Request $request) { - - if (!Auth::check()) { + if (! Auth::check()) { return redirect()->route('login')->with('error', trans('auth/general.login_prompt')); } - if (!$request->filled('two_factor_secret')) { + if (! $request->filled('two_factor_secret')) { return redirect()->route('two-factor')->with('error', trans('auth/message.two_factor.code_required')); } - if (!$request->has('two_factor_secret')) { + if (! $request->has('two_factor_secret')) { return redirect()->route('two-factor')->with('error', 'Two-factor code is required.'); } @@ -364,15 +361,13 @@ class LoginController extends Controller $user->two_factor_enrolled = 1; $user->save(); $request->session()->put('2fa_authed', 'true'); + return redirect()->route('home')->with('success', 'You are logged in!'); } return redirect()->route('two-factor')->with('error', trans('auth/message.two_factor.invalid_code')); - - } - /** * Logout page. * @@ -390,15 +385,15 @@ class LoginController extends Controller if ($saml->isEnabled()) { $auth = $saml->getAuth(); $sloRedirectUrl = $request->session()->get('saml_slo_redirect_url'); - - if (!empty($auth->getSLOurl()) && $settings->saml_slo == '1' && $saml->isAuthenticated() && empty($sloRedirectUrl)) { - $sloRequestUrl = $auth->logout(null, array(), $saml->getNameId(), $saml->getSessionIndex(), true, $saml->getNameIdFormat(), $saml->getNameIdNameQualifier(), $saml->getNameIdSPNameQualifier()); + + if (! empty($auth->getSLOurl()) && $settings->saml_slo == '1' && $saml->isAuthenticated() && empty($sloRedirectUrl)) { + $sloRequestUrl = $auth->logout(null, [], $saml->getNameId(), $saml->getSessionIndex(), true, $saml->getNameIdFormat(), $saml->getNameIdNameQualifier(), $saml->getNameIdSPNameQualifier()); } $saml->clearData(); } - if (!empty($sloRequestUrl)) { + if (! empty($sloRequestUrl)) { return redirect()->away($sloRequestUrl); } @@ -407,11 +402,11 @@ class LoginController extends Controller $request->session()->regenerate(true); Auth::logout(); - if (!empty($sloRedirectUrl)) { + if (! empty($sloRedirectUrl)) { return redirect()->away($sloRedirectUrl); } - $customLogoutUrl = $settings->login_remote_user_custom_logout_url ; + $customLogoutUrl = $settings->login_remote_user_custom_logout_url; if ($settings->login_remote_user_enabled == '1' && $customLogoutUrl != '') { return redirect()->away($customLogoutUrl); } @@ -419,7 +414,6 @@ class LoginController extends Controller return redirect()->route('login')->with(['success' => trans('auth/message.logout.success'), 'loggedout' => true]); } - /** * Get a validator for an incoming registration request. * @@ -434,7 +428,6 @@ class LoginController extends Controller ]); } - public function username() { return 'username'; @@ -461,7 +454,6 @@ class LoginController extends Controller ->withErrors([$this->username() => $message]); } - /** * Override the lockout time and duration * @@ -480,13 +472,13 @@ class LoginController extends Controller ); } - public function legacyAuthRedirect() { + public function legacyAuthRedirect() + { return redirect()->route('login'); } public function redirectTo() { - return Session::get('backUrl') ? Session::get('backUrl') : $this->redirectTo; + return Session::get('backUrl') ? Session::get('backUrl') : $this->redirectTo; } - } diff --git a/app/Http/Controllers/Auth/RegisterController.php b/app/Http/Controllers/Auth/RegisterController.php index 901af3e2d0..1a188b51e1 100644 --- a/app/Http/Controllers/Auth/RegisterController.php +++ b/app/Http/Controllers/Auth/RegisterController.php @@ -6,17 +6,18 @@ use App\Http\Controllers\Controller; class RegisterController extends Controller { - public function __construct() { $this->middleware('guest'); } - public function showRegistrationForm() { - abort(404,'Page not found'); + public function showRegistrationForm() + { + abort(404, 'Page not found'); } - - public function register() { - abort(404,'Page not found'); + + public function register() + { + abort(404, 'Page not found'); } } diff --git a/app/Http/Controllers/Auth/ResetPasswordController.php b/app/Http/Controllers/Auth/ResetPasswordController.php index 92b86fd737..95700e2992 100644 --- a/app/Http/Controllers/Auth/ResetPasswordController.php +++ b/app/Http/Controllers/Auth/ResetPasswordController.php @@ -54,29 +54,25 @@ class ResetPasswordController extends Controller ]; } - protected function credentials(Request $request) { return $request->only( 'username', 'password', 'password_confirmation', 'token' ); } - public function showResetForm(Request $request, $token = null) { return view('auth.passwords.reset')->with( [ 'token' => $token, - 'username' => $request->input('username') + 'username' => $request->input('username'), ] ); } - public function reset(Request $request) { - $messages = [ 'password.not_in' => trans('validation.disallow_same_pwd_as_user_fields'), ]; @@ -87,15 +83,13 @@ class ResetPasswordController extends Controller $user = User::where('username', '=', $request->input('username'))->first(); $broker = $this->broker(); - if (strpos(Setting::passwordComplexityRulesSaving('store'), 'disallow_same_pwd_as_user_fields') !== FALSE) { + if (strpos(Setting::passwordComplexityRulesSaving('store'), 'disallow_same_pwd_as_user_fields') !== false) { $request->validate( [ - 'password' => 'required|notIn:["'.$user->email.'","'.$user->username.'","'.$user->first_name.'","'.$user->last_name.'"' + 'password' => 'required|notIn:["'.$user->email.'","'.$user->username.'","'.$user->first_name.'","'.$user->last_name.'"', ], $messages); - } - $response = $broker->reset( $this->credentials($request), function ($user, $password) { $this->resetPassword($user, $password); @@ -107,14 +101,10 @@ class ResetPasswordController extends Controller : $this->sendResetFailedResponse($request, $response); } - protected function sendResetFailedResponse(Request $request, $response) { return redirect()->back() ->withInput(['username'=> $request->input('username')]) ->withErrors(['username' => trans($response), 'password' => trans($response)]); } - - - } diff --git a/app/Http/Controllers/Auth/SamlController.php b/app/Http/Controllers/Auth/SamlController.php index 5a2075daed..41eda91d9c 100644 --- a/app/Http/Controllers/Auth/SamlController.php +++ b/app/Http/Controllers/Auth/SamlController.php @@ -2,9 +2,9 @@ namespace App\Http\Controllers\Auth; -use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Services\Saml; +use Illuminate\Http\Request; use Log; /** @@ -30,20 +30,20 @@ class SamlController extends Controller { $this->saml = $saml; - $this->middleware('guest', ['except' => ['metadata','sls']]); + $this->middleware('guest', ['except' => ['metadata', 'sls']]); } /** * Return SAML SP metadata for Snipe-IT - * + * * /saml/metadata - * + * * @author Johnson Yi - * + * * @since 5.0.0 * * @param Request $request - * + * * @return Response */ public function metadata(Request $request) @@ -53,7 +53,7 @@ class SamlController extends Controller if (empty($metadata)) { return response()->view('errors.403', [], 403); } - + return response()->streamDownload(function () use ($metadata) { echo $metadata; }, 'snipe-it-metadata.xml', ['Content-Type' => 'text/xml']); @@ -61,36 +61,37 @@ class SamlController extends Controller /** * Begin the SP-Initiated SSO by sending AuthN to the IdP. - * + * * /login/saml - * + * * @author Johnson Yi - * + * * @since 5.0.0 * * @param Request $request - * + * * @return Redirect */ public function login(Request $request) { $auth = $this->saml->getAuth(); - $ssoUrl = $auth->login(null, array(), false, false, false, false); + $ssoUrl = $auth->login(null, [], false, false, false, false); + return redirect()->away($ssoUrl); } /** * Receives, parses the assertion from IdP and flashes SAML data * back to the LoginController for authentication. - * + * * /saml/acs - * + * * @author Johnson Yi - * + * * @since 5.0.0 * * @param Request $request - * + * * @return Redirect */ public function acs(Request $request) @@ -100,9 +101,10 @@ class SamlController extends Controller $auth->processResponse(); $errors = $auth->getErrors(); - if (!empty($errors)) { - Log::error("There was an error with SAML ACS: " . implode(', ', $errors)); - Log::error("Reason: " . $auth->getLastErrorReason()); + if (! empty($errors)) { + Log::error('There was an error with SAML ACS: '.implode(', ', $errors)); + Log::error('Reason: '.$auth->getLastErrorReason()); + return redirect()->route('login')->with('error', trans('auth/message.signin.error')); } @@ -114,15 +116,15 @@ class SamlController extends Controller /** * Receives LogoutRequest/LogoutResponse from IdP and flashes * back to the LoginController for logging out. - * + * * /saml/sls - * + * * @author Johnson Yi - * + * * @since 5.0.0 * * @param Request $request - * + * * @return Redirect */ public function sls(Request $request) @@ -131,10 +133,11 @@ class SamlController extends Controller $retrieveParametersFromServer = $this->saml->getSetting('retrieveParametersFromServer', false); $sloUrl = $auth->processSLO(true, null, $retrieveParametersFromServer, null, true); $errors = $auth->getErrors(); - - if (!empty($errors)) { - Log::error("There was an error with SAML SLS: " . implode(', ', $errors)); - Log::error("Reason: " . $auth->getLastErrorReason()); + + if (! empty($errors)) { + Log::error('There was an error with SAML SLS: '.implode(', ', $errors)); + Log::error('Reason: '.$auth->getLastErrorReason()); + return view('errors.403'); } diff --git a/app/Http/Controllers/BulkAssetModelsController.php b/app/Http/Controllers/BulkAssetModelsController.php index 088e8da509..19cd7f11d8 100644 --- a/app/Http/Controllers/BulkAssetModelsController.php +++ b/app/Http/Controllers/BulkAssetModelsController.php @@ -10,7 +10,7 @@ use Illuminate\Support\Facades\Redirect; class BulkAssetModelsController extends Controller { - /** + /** * Returns a view that allows the user to bulk edit model attrbutes * * @author [A. Gianotto] [] @@ -24,26 +24,27 @@ class BulkAssetModelsController extends Controller // Make sure some IDs have been selected if ((is_array($models_raw_array)) && (count($models_raw_array) > 0)) { - $models = AssetModel::whereIn('id', $models_raw_array) ->withCount('assets as assets_count') ->orderBy('assets_count', 'ASC') ->get(); // If deleting.... - if ($request->input('bulk_actions')=='delete') { + if ($request->input('bulk_actions') == 'delete') { $valid_count = 0; foreach ($models as $model) { if ($model->assets_count == 0) { $valid_count++; } } + return view('models/bulk-delete', compact('models'))->with('valid_count', $valid_count); - // Otherwise display the bulk edit screen + // Otherwise display the bulk edit screen } $nochange = ['NC' => 'No Change']; + return view('models/bulk-edit', compact('models')) ->with('fieldset_list', $nochange + Helper::customFieldsetList()) ->with('depreciation_list', $nochange + Helper::depreciationList()); @@ -63,34 +64,31 @@ class BulkAssetModelsController extends Controller */ public function update(Request $request) { - $models_raw_array = $request->input('ids'); - $update_array = array(); + $update_array = []; - if (($request->filled('manufacturer_id') && ($request->input('manufacturer_id')!='NC'))) { + 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'))) { + if (($request->filled('category_id') && ($request->input('category_id') != 'NC'))) { $update_array['category_id'] = $request->input('category_id'); } - if ($request->input('fieldset_id')!='NC') { + if ($request->input('fieldset_id') != 'NC') { $update_array['fieldset_id'] = $request->input('fieldset_id'); } - if ($request->input('depreciation_id')!='NC') { + 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')); - } /** @@ -106,7 +104,6 @@ class BulkAssetModelsController extends Controller $models_raw_array = $request->input('ids'); if ((is_array($models_raw_array)) && (count($models_raw_array) > 0)) { - $models = AssetModel::whereIn('id', $models_raw_array)->withCount('assets as assets_count')->get(); $del_error_count = 0; @@ -123,7 +120,7 @@ class BulkAssetModelsController extends Controller if ($del_error_count == 0) { return redirect()->route('models.index') - ->with('success', trans('admin/models/message.bulkdelete.success',['success_count'=> $del_count] )); + ->with('success', trans('admin/models/message.bulkdelete.success', ['success_count'=> $del_count])); } return redirect()->route('models.index') @@ -132,7 +129,5 @@ class BulkAssetModelsController extends Controller return redirect()->route('models.index') ->with('error', trans('admin/models/message.bulkdelete.error')); - } - } diff --git a/app/Http/Controllers/CategoriesController.php b/app/Http/Controllers/CategoriesController.php index 244a687ede..5844b54dc8 100755 --- a/app/Http/Controllers/CategoriesController.php +++ b/app/Http/Controllers/CategoriesController.php @@ -1,4 +1,5 @@ authorize('view', Category::class); + return view('categories/index'); } - /** * Returns a form view to create a new category. * @@ -49,11 +49,11 @@ class CategoriesController extends Controller { // Show the page $this->authorize('create', Category::class); + return view('categories/edit')->with('item', new Category) ->with('category_types', Helper::categoryTypeList()); } - /** * Validates and stores the new category data. * @@ -68,13 +68,13 @@ class CategoriesController extends Controller { $this->authorize('create', Category::class); $category = new Category(); - $category->name = $request->input('name'); - $category->category_type = $request->input('category_type'); - $category->eula_text = $request->input('eula_text'); - $category->use_default_eula = $request->input('use_default_eula', '0'); - $category->require_acceptance = $request->input('require_acceptance', '0'); - $category->checkin_email = $request->input('checkin_email', '0'); - $category->user_id = Auth::id(); + $category->name = $request->input('name'); + $category->category_type = $request->input('category_type'); + $category->eula_text = $request->input('eula_text'); + $category->use_default_eula = $request->input('use_default_eula', '0'); + $category->require_acceptance = $request->input('require_acceptance', '0'); + $category->checkin_email = $request->input('checkin_email', '0'); + $category->user_id = Auth::id(); $category = $request->handleImages($category); if ($category->save()) { @@ -100,11 +100,11 @@ class CategoriesController extends Controller if (is_null($item = Category::find($categoryId))) { return redirect()->route('categories.index')->with('error', trans('admin/categories/message.does_not_exist')); } + return view('categories/edit', compact('item')) ->with('category_types', Helper::categoryTypeList()); } - /** * Validates and stores the updated category data. * @@ -125,15 +125,14 @@ class CategoriesController extends Controller } // Update the category data - $category->name = $request->input('name'); + $category->name = $request->input('name'); // If the item count is > 0, we disable the category type in the edit. Disabled items // don't POST, so if the category_type is blank we just set it to the default. - $category->category_type = $request->input('category_type', $category->category_type); - $category->eula_text = $request->input('eula_text'); - $category->use_default_eula = $request->input('use_default_eula', '0'); - $category->require_acceptance = $request->input('require_acceptance', '0'); - $category->checkin_email = $request->input('checkin_email', '0'); - + $category->category_type = $request->input('category_type', $category->category_type); + $category->eula_text = $request->input('eula_text'); + $category->use_default_eula = $request->input('use_default_eula', '0'); + $category->require_acceptance = $request->input('require_acceptance', '0'); + $category->checkin_email = $request->input('checkin_email', '0'); $category = $request->handleImages($category); @@ -162,8 +161,8 @@ class CategoriesController extends Controller return redirect()->route('categories.index')->with('error', trans('admin/categories/message.not_found')); } - if (!$category->isDeletable()) { - return redirect()->route('categories.index')->with('error', trans('admin/categories/message.assoc_items', ['asset_type'=> $category->category_type ])); + if (! $category->isDeletable()) { + return redirect()->route('categories.index')->with('error', trans('admin/categories/message.assoc_items', ['asset_type'=> $category->category_type])); } Storage::disk('public')->delete('categories'.'/'.$category->image); @@ -172,7 +171,6 @@ class CategoriesController extends Controller return redirect()->route('categories.index')->with('success', trans('admin/categories/message.delete.success')); } - /** * Returns a view that invokes the ajax tables which actually contains * the content for the categories detail view, which is generated in getDataView. @@ -188,20 +186,20 @@ class CategoriesController extends Controller { $this->authorize('view', Category::class); if ($category = Category::find($id)) { - - if ($category->category_type=='asset') { + if ($category->category_type == 'asset') { $category_type = 'hardware'; $category_type_route = 'assets'; - } elseif ($category->category_type=='accessory') { + } elseif ($category->category_type == 'accessory') { $category_type = 'accessories'; $category_type_route = 'accessories'; } else { $category_type = $category->category_type; $category_type_route = $category->category_type.'s'; } + return view('categories/view', compact('category')) - ->with('category_type',$category_type) - ->with('category_type_route',$category_type_route); + ->with('category_type', $category_type) + ->with('category_type_route', $category_type_route); } return redirect()->route('categories.index')->with('error', trans('admin/categories/message.does_not_exist')); diff --git a/app/Http/Controllers/CheckInOutRequest.php b/app/Http/Controllers/CheckInOutRequest.php index f080dac4e3..c521c7a3ef 100644 --- a/app/Http/Controllers/CheckInOutRequest.php +++ b/app/Http/Controllers/CheckInOutRequest.php @@ -1,4 +1,5 @@ location_id = $target->id; break; case 'asset': $asset->location_id = $target->rtd_location_id; // Override with the asset's location_id if it has one - if ($target->location_id!='') { + if ($target->location_id != '') { $asset->location_id = $target->location_id; } break; @@ -51,6 +51,7 @@ trait CheckInOutRequest $asset->location_id = $target->location_id; break; } + return $asset; } } diff --git a/app/Http/Controllers/CompaniesController.php b/app/Http/Controllers/CompaniesController.php index fbb5754a51..396ec5ef68 100644 --- a/app/Http/Controllers/CompaniesController.php +++ b/app/Http/Controllers/CompaniesController.php @@ -1,4 +1,5 @@ route('companies.index') ->with('success', trans('admin/companies/message.create.success')); } + return redirect()->back()->withInput()->withErrors($company->getErrors()); } - /** * Return form to edit existing company. * @@ -113,14 +112,13 @@ final class CompaniesController extends Controller $company->name = $request->input('name'); - $company = $request->handleImages($company); - if ($company->save()) { return redirect()->route('companies.index') ->with('success', trans('admin/companies/message.update.success')); } + return redirect()->route('companies.edit', ['company' => $companyId]) ->with('error', trans('admin/companies/message.update.error')); } @@ -142,13 +140,13 @@ final class CompaniesController extends Controller } $this->authorize('delete', $company); - if(!$company->isDeletable()) { + if (! $company->isDeletable()) { return redirect()->route('companies.index') ->with('error', trans('admin/companies/message.assoc_users')); } if ($company->image) { - try { + try { Storage::disk('public')->delete('companies'.'/'.$company->image); } catch (\Exception $e) { \Log::debug($e); @@ -156,11 +154,13 @@ final class CompaniesController extends Controller } $company->delete(); + return redirect()->route('companies.index') ->with('success', trans('admin/companies/message.delete.success')); } - public function show($id) { + public function show($id) + { $this->authorize('view', Company::class); if (is_null($company = Company::find($id))) { @@ -168,6 +168,6 @@ final class CompaniesController extends Controller ->with('error', trans('admin/companies/message.not_found')); } - return view('companies/view')->with('company',$company); + return view('companies/view')->with('company', $company); } } diff --git a/app/Http/Controllers/Components/ComponentCheckinController.php b/app/Http/Controllers/Components/ComponentCheckinController.php index eee0f15827..09acee0277 100644 --- a/app/Http/Controllers/Components/ComponentCheckinController.php +++ b/app/Http/Controllers/Components/ComponentCheckinController.php @@ -15,7 +15,6 @@ use Illuminate\Support\Facades\Validator; class ComponentCheckinController extends Controller { - /** * Returns a view that allows the checkin of a component from an asset. * @@ -39,14 +38,13 @@ class ComponentCheckinController extends Controller trans('admin/components/message.not_found')); } $this->authorize('checkin', $component); - return view('components/checkin', compact('component_assets','component','asset')); + + return view('components/checkin', compact('component_assets', 'component', 'asset')); } return redirect()->route('components.index')->with('error', trans('admin/components/messages.not_found')); - } - /** * Validate and store checkin data. * @@ -66,12 +64,11 @@ class ComponentCheckinController extends Controller trans('admin/components/message.not_found')); } - $this->authorize('checkin', $component); $max_to_checkin = $component_assets->assigned_qty; $validator = Validator::make($request->all(), [ - "checkin_qty" => "required|numeric|between:1,$max_to_checkin" + 'checkin_qty' => "required|numeric|between:1,$max_to_checkin", ]); if ($validator->fails()) { @@ -81,7 +78,7 @@ class ComponentCheckinController extends Controller } // Validation passed, so let's figure out what we have to do here. - $qty_remaining_in_checkout = ($component_assets->assigned_qty - (int)$request->input('checkin_qty')); + $qty_remaining_in_checkout = ($component_assets->assigned_qty - (int) $request->input('checkin_qty')); // We have to modify the record to reflect the new qty that's // actually checked out. @@ -102,7 +99,7 @@ class ComponentCheckinController extends Controller return redirect()->route('components.index')->with('success', trans('admin/components/message.checkin.success')); } + return redirect()->route('components.index')->with('error', trans('admin/components/message.does_not_exist')); } - } diff --git a/app/Http/Controllers/Components/ComponentCheckoutController.php b/app/Http/Controllers/Components/ComponentCheckoutController.php index 4ae37dbd0a..ffeaf1b829 100644 --- a/app/Http/Controllers/Components/ComponentCheckoutController.php +++ b/app/Http/Controllers/Components/ComponentCheckoutController.php @@ -32,6 +32,7 @@ class ComponentCheckoutController extends Controller return redirect()->route('components.index')->with('error', trans('admin/components/message.not_found')); } $this->authorize('checkout', $component); + return view('components/checkout', compact('component')); } @@ -58,8 +59,8 @@ class ComponentCheckoutController extends Controller $max_to_checkout = $component->numRemaining(); $validator = Validator::make($request->all(), [ - "asset_id" => "required", - "assigned_qty" => "required|numeric|between:1,$max_to_checkout" + 'asset_id' => 'required', + 'assigned_qty' => "required|numeric|between:1,$max_to_checkout", ]); if ($validator->fails()) { @@ -78,14 +79,14 @@ class ComponentCheckoutController extends Controller } // Update the component data - $component->asset_id = $asset_id; + $component->asset_id = $asset_id; $component->assets()->attach($component->id, [ 'component_id' => $component->id, 'user_id' => $admin_user->id, 'created_at' => date('Y-m-d H:i:s'), 'assigned_qty' => $request->input('assigned_qty'), - 'asset_id' => $asset_id + 'asset_id' => $asset_id, ]); event(new CheckoutableCheckedOut($component, $asset, Auth::user(), $request->input('note'))); diff --git a/app/Http/Controllers/Components/ComponentsController.php b/app/Http/Controllers/Components/ComponentsController.php index 16dc081342..95bb8c5e07 100644 --- a/app/Http/Controllers/Components/ComponentsController.php +++ b/app/Http/Controllers/Components/ComponentsController.php @@ -1,4 +1,5 @@ authorize('view', Component::class); + return view('components/index'); } - /** * Returns a form to create a new component. * @@ -47,11 +48,11 @@ class ComponentsController extends Controller public function create() { $this->authorize('create', Component::class); + return view('components/edit')->with('category_type', 'component') ->with('item', new Component); } - /** * Validate and store data for new component. * @@ -66,23 +67,24 @@ class ComponentsController extends Controller { $this->authorize('create', Component::class); $component = new Component(); - $component->name = $request->input('name'); - $component->category_id = $request->input('category_id'); - $component->location_id = $request->input('location_id'); - $component->company_id = Company::getIdForCurrentUser($request->input('company_id')); - $component->order_number = $request->input('order_number', null); - $component->min_amt = $request->input('min_amt', null); - $component->serial = $request->input('serial', null); - $component->purchase_date = $request->input('purchase_date', null); - $component->purchase_cost = $request->input('purchase_cost', null); - $component->qty = $request->input('qty'); - $component->user_id = Auth::id(); + $component->name = $request->input('name'); + $component->category_id = $request->input('category_id'); + $component->location_id = $request->input('location_id'); + $component->company_id = Company::getIdForCurrentUser($request->input('company_id')); + $component->order_number = $request->input('order_number', null); + $component->min_amt = $request->input('min_amt', null); + $component->serial = $request->input('serial', null); + $component->purchase_date = $request->input('purchase_date', null); + $component->purchase_cost = $request->input('purchase_cost', null); + $component->qty = $request->input('qty'); + $component->user_id = Auth::id(); $component = $request->handleImages($component); if ($component->save()) { return redirect()->route('components.index')->with('success', trans('admin/components/message.create.success')); } + return redirect()->back()->withInput()->withErrors($component->getErrors()); } @@ -100,12 +102,13 @@ class ComponentsController extends Controller { if ($item = Component::find($componentId)) { $this->authorize('update', $item); + return view('components/edit', compact('item'))->with('category_type', 'component'); } + return redirect()->route('components.index')->with('error', trans('admin/components/message.does_not_exist')); } - /** * Return a view to edit a component. * @@ -124,7 +127,7 @@ class ComponentsController extends Controller } $min = $component->numCHeckedOut(); $validator = Validator::make($request->all(), [ - "qty" => "required|numeric|min:$min" + 'qty' => "required|numeric|min:$min", ]); if ($validator->fails()) { @@ -136,22 +139,23 @@ class ComponentsController extends Controller $this->authorize('update', $component); // Update the component data - $component->name = $request->input('name'); - $component->category_id = $request->input('category_id'); - $component->location_id = $request->input('location_id'); - $component->company_id = Company::getIdForCurrentUser($request->input('company_id')); - $component->order_number = $request->input('order_number'); - $component->min_amt = $request->input('min_amt'); - $component->serial = $request->input('serial'); - $component->purchase_date = $request->input('purchase_date'); - $component->purchase_cost = request('purchase_cost'); - $component->qty = $request->input('qty'); + $component->name = $request->input('name'); + $component->category_id = $request->input('category_id'); + $component->location_id = $request->input('location_id'); + $component->company_id = Company::getIdForCurrentUser($request->input('company_id')); + $component->order_number = $request->input('order_number'); + $component->min_amt = $request->input('min_amt'); + $component->serial = $request->input('serial'); + $component->purchase_date = $request->input('purchase_date'); + $component->purchase_cost = request('purchase_cost'); + $component->qty = $request->input('qty'); $component = $request->handleImages($component); if ($component->save()) { return redirect()->route('components.index')->with('success', trans('admin/components/message.update.success')); } + return redirect()->back()->withInput()->withErrors($component->getErrors()); } @@ -174,7 +178,7 @@ class ComponentsController extends Controller // Remove the image if one exists if (Storage::disk('public')->exists('components/'.$component->image)) { - try { + try { Storage::disk('public')->delete('components/'.$component->image); } catch (\Exception $e) { \Log::debug($e); @@ -182,6 +186,7 @@ class ComponentsController extends Controller } $component->delete(); + return redirect()->route('components.index')->with('success', trans('admin/components/message.delete.success')); } @@ -201,6 +206,7 @@ class ComponentsController extends Controller if (isset($component->id)) { $this->authorize('view', $component); + return view('components/view', compact('component')); } // Redirect to the user management page diff --git a/app/Http/Controllers/Consumables/ConsumableCheckoutController.php b/app/Http/Controllers/Consumables/ConsumableCheckoutController.php index 8dc43b54c1..03ca2f2052 100644 --- a/app/Http/Controllers/Consumables/ConsumableCheckoutController.php +++ b/app/Http/Controllers/Consumables/ConsumableCheckoutController.php @@ -12,7 +12,6 @@ use Illuminate\Support\Facades\Input; class ConsumableCheckoutController extends Controller { - /** * Return a view to checkout a consumable to a user. * @@ -29,6 +28,7 @@ class ConsumableCheckoutController extends Controller return redirect()->route('consumables.index')->with('error', trans('admin/consumables/message.does_not_exist')); } $this->authorize('checkout', $consumable); + return view('consumables/checkout', compact('consumable')); } @@ -65,13 +65,12 @@ class ConsumableCheckoutController extends Controller $consumable->users()->attach($consumable->id, [ 'consumable_id' => $consumable->id, 'user_id' => $admin_user->id, - 'assigned_to' => e($request->input('assigned_to')) + 'assigned_to' => e($request->input('assigned_to')), ]); event(new CheckoutableCheckedOut($consumable, $user, Auth::user(), $request->input('note'))); // Redirect to the new consumable page return redirect()->route('consumables.index')->with('success', trans('admin/consumables/message.checkout.success')); - } } diff --git a/app/Http/Controllers/Consumables/ConsumablesController.php b/app/Http/Controllers/Consumables/ConsumablesController.php index 69987f1570..7b3947cabf 100644 --- a/app/Http/Controllers/Consumables/ConsumablesController.php +++ b/app/Http/Controllers/Consumables/ConsumablesController.php @@ -30,10 +30,10 @@ class ConsumablesController extends Controller public function index() { $this->authorize('index', Consumable::class); + return view('consumables/index'); } - /** * Return a view to display the form view to create a new consumable * @@ -46,11 +46,11 @@ class ConsumablesController extends Controller public function create() { $this->authorize('create', Consumable::class); + return view('consumables/edit')->with('category_type', 'consumable') ->with('item', new Consumable); } - /** * Validate and store new consumable data. * @@ -65,20 +65,19 @@ class ConsumablesController extends Controller { $this->authorize('create', Consumable::class); $consumable = new Consumable(); - $consumable->name = $request->input('name'); - $consumable->category_id = $request->input('category_id'); - $consumable->location_id = $request->input('location_id'); - $consumable->company_id = Company::getIdForCurrentUser($request->input('company_id')); - $consumable->order_number = $request->input('order_number'); - $consumable->min_amt = $request->input('min_amt'); - $consumable->manufacturer_id = $request->input('manufacturer_id'); - $consumable->model_number = $request->input('model_number'); - $consumable->item_no = $request->input('item_no'); - $consumable->purchase_date = $request->input('purchase_date'); - $consumable->purchase_cost = Helper::ParseFloat($request->input('purchase_cost')); - $consumable->qty = $request->input('qty'); - $consumable->user_id = Auth::id(); - + $consumable->name = $request->input('name'); + $consumable->category_id = $request->input('category_id'); + $consumable->location_id = $request->input('location_id'); + $consumable->company_id = Company::getIdForCurrentUser($request->input('company_id')); + $consumable->order_number = $request->input('order_number'); + $consumable->min_amt = $request->input('min_amt'); + $consumable->manufacturer_id = $request->input('manufacturer_id'); + $consumable->model_number = $request->input('model_number'); + $consumable->item_no = $request->input('item_no'); + $consumable->purchase_date = $request->input('purchase_date'); + $consumable->purchase_cost = Helper::ParseFloat($request->input('purchase_cost')); + $consumable->qty = $request->input('qty'); + $consumable->user_id = Auth::id(); $consumable = $request->handleImages($consumable); @@ -87,7 +86,6 @@ class ConsumablesController extends Controller } return redirect()->back()->withInput()->withErrors($consumable->getErrors()); - } /** @@ -104,14 +102,13 @@ class ConsumablesController extends Controller { if ($item = Consumable::find($consumableId)) { $this->authorize($item); + return view('consumables/edit', compact('item'))->with('category_type', 'consumable'); } return redirect()->route('consumables.index')->with('error', trans('admin/consumables/message.does_not_exist')); - } - /** * Returns a form view to edit a consumable. * @@ -131,24 +128,25 @@ class ConsumablesController extends Controller $this->authorize($consumable); - $consumable->name = $request->input('name'); - $consumable->category_id = $request->input('category_id'); - $consumable->location_id = $request->input('location_id'); - $consumable->company_id = Company::getIdForCurrentUser($request->input('company_id')); - $consumable->order_number = $request->input('order_number'); - $consumable->min_amt = $request->input('min_amt'); - $consumable->manufacturer_id = $request->input('manufacturer_id'); - $consumable->model_number = $request->input('model_number'); - $consumable->item_no = $request->input('item_no'); - $consumable->purchase_date = $request->input('purchase_date'); - $consumable->purchase_cost = Helper::ParseFloat($request->input('purchase_cost')); - $consumable->qty = Helper::ParseFloat($request->input('qty')); + $consumable->name = $request->input('name'); + $consumable->category_id = $request->input('category_id'); + $consumable->location_id = $request->input('location_id'); + $consumable->company_id = Company::getIdForCurrentUser($request->input('company_id')); + $consumable->order_number = $request->input('order_number'); + $consumable->min_amt = $request->input('min_amt'); + $consumable->manufacturer_id = $request->input('manufacturer_id'); + $consumable->model_number = $request->input('model_number'); + $consumable->item_no = $request->input('item_no'); + $consumable->purchase_date = $request->input('purchase_date'); + $consumable->purchase_cost = Helper::ParseFloat($request->input('purchase_cost')); + $consumable->qty = Helper::ParseFloat($request->input('qty')); $consumable = $request->handleImages($consumable); if ($consumable->save()) { return redirect()->route('consumables.index')->with('success', trans('admin/consumables/message.update.success')); } + return redirect()->back()->withInput()->withErrors($consumable->getErrors()); } @@ -189,8 +187,8 @@ class ConsumablesController extends Controller if (isset($consumable->id)) { return view('consumables/view', compact('consumable')); } + return redirect()->route('consumables.index') ->with('error', trans('admin/consumables/message.does_not_exist')); } - } diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 14f56d0d05..96d761ef5b 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -19,6 +19,7 @@ * etc have been included in this documentation (excluding vendors, Laravel core, etc) * for simplicity. */ + namespace App\Http\Controllers; use Auth; diff --git a/app/Http/Controllers/CustomFieldsController.php b/app/Http/Controllers/CustomFieldsController.php index a8be424841..8c7b7a2b64 100644 --- a/app/Http/Controllers/CustomFieldsController.php +++ b/app/Http/Controllers/CustomFieldsController.php @@ -1,4 +1,5 @@ ] */ - class CustomFieldsController extends Controller { - /** * Returns a view with a listing of custom fields. * @@ -33,13 +32,12 @@ class CustomFieldsController extends Controller { $this->authorize('view', CustomField::class); - $fieldsets = CustomFieldset::with("fields", "models")->get(); - $fields = CustomField::with("fieldset")->get(); + $fieldsets = CustomFieldset::with('fields', 'models')->get(); + $fields = CustomField::with('fieldset')->get(); - return view("custom_fields.index")->with("custom_fieldsets", $fieldsets)->with("custom_fields", $fields); + return view('custom_fields.index')->with('custom_fieldsets', $fieldsets)->with('custom_fields', $fields); } - /** * Just redirect the user back if they try to view the details of a field. * We already show those details on the listing page. @@ -50,14 +48,11 @@ class CustomFieldsController extends Controller * @return Redirect * @throws \Illuminate\Auth\Access\AuthorizationException */ - public function show() { - return redirect()->route("fields.index"); - + return redirect()->route('fields.index'); } - /** * Returns a view with a form to create a new custom field. * @@ -71,13 +66,12 @@ class CustomFieldsController extends Controller { $this->authorize('create', CustomField::class); - return view("custom_fields.fields.edit",[ + return view('custom_fields.fields.edit', [ 'predefinedFormats' => Helper::predefined_formats(), - 'customFormat' => '' + 'customFormat' => '', ])->with('field', new CustomField()); } - /** * Validates and stores a new custom field. * @@ -92,33 +86,29 @@ class CustomFieldsController extends Controller $this->authorize('create', CustomField::class); $field = new CustomField([ - "name" => $request->get("name"), - "element" => $request->get("element"), - "help_text" => $request->get("help_text"), - "field_values" => $request->get("field_values"), - "field_encrypted" => $request->get("field_encrypted", 0), - "show_in_email" => $request->get("show_in_email", 0), - "user_id" => Auth::id() + 'name' => $request->get('name'), + 'element' => $request->get('element'), + 'help_text' => $request->get('help_text'), + 'field_values' => $request->get('field_values'), + 'field_encrypted' => $request->get('field_encrypted', 0), + 'show_in_email' => $request->get('show_in_email', 0), + 'user_id' => Auth::id(), ]); - - if ($request->filled("custom_format")) { - $field->format = e($request->get("custom_format")); + if ($request->filled('custom_format')) { + $field->format = e($request->get('custom_format')); } else { - $field->format = e($request->get("format")); + $field->format = e($request->get('format')); } if ($field->save()) { - - return redirect()->route("fields.index")->with("success", trans('admin/custom_fields/message.field.create.success')); + return redirect()->route('fields.index')->with('success', trans('admin/custom_fields/message.field.create.success')); } return redirect()->back()->withInput() ->with('error', trans('admin/custom_fields/message.field.create.error')); - } - /** * Detach a custom field from a fieldset. * @@ -135,10 +125,10 @@ class CustomFieldsController extends Controller if ($field->fieldset()->detach($fieldset_id)) { return redirect()->route('fieldsets.show', ['fieldset' => $fieldset_id]) - ->with("success", trans('admin/custom_fields/message.field.delete.success')); + ->with('success', trans('admin/custom_fields/message.field.delete.success')); } - return redirect()->back()->withErrors(['message' => "Field is in-use"]); + return redirect()->back()->withErrors(['message' => 'Field is in-use']); } /** @@ -152,21 +142,20 @@ class CustomFieldsController extends Controller public function destroy($field_id) { if ($field = CustomField::find($field_id)) { - $this->authorize('delete', $field); if (($field->fieldset) && ($field->fieldset->count() > 0)) { - return redirect()->back()->withErrors(['message' => "Field is in-use"]); + return redirect()->back()->withErrors(['message' => 'Field is in-use']); } $field->delete(); - return redirect()->route("fields.index") - ->with("success", trans('admin/custom_fields/message.field.delete.success')); + + return redirect()->route('fields.index') + ->with('success', trans('admin/custom_fields/message.field.delete.success')); } - return redirect()->back()->withErrors(['message' => "Field does not exist"]); + return redirect()->back()->withErrors(['message' => 'Field does not exist']); } - /** * Return a view to edit a custom field * @@ -183,18 +172,17 @@ class CustomFieldsController extends Controller $this->authorize('update', $field); $customFormat = ''; - if((stripos($field->format, 'regex') === 0) && ($field->format !== CustomField::PREDEFINED_FORMATS['MAC'])) { + if ((stripos($field->format, 'regex') === 0) && ($field->format !== CustomField::PREDEFINED_FORMATS['MAC'])) { $customFormat = $field->format; } - return view("custom_fields.fields.edit",[ + return view('custom_fields.fields.edit', [ 'field' => $field, 'customFormat' => $customFormat, - 'predefinedFormats' => Helper::predefined_formats() + 'predefinedFormats' => Helper::predefined_formats(), ]); } - /** * Store the updated field * @@ -208,30 +196,27 @@ class CustomFieldsController extends Controller */ public function update(CustomFieldRequest $request, $id) { - $field = CustomField::find($id); - + $field = CustomField::find($id); + $this->authorize('update', $field); - $field->name = e($request->get("name")); - $field->element = e($request->get("element")); - $field->field_values = e($request->get("field_values")); - $field->user_id = Auth::id(); - $field->help_text = $request->get("help_text"); - $field->show_in_email = $request->get("show_in_email", 0); + $field->name = e($request->get('name')); + $field->element = e($request->get('element')); + $field->field_values = e($request->get('field_values')); + $field->user_id = Auth::id(); + $field->help_text = $request->get('help_text'); + $field->show_in_email = $request->get('show_in_email', 0); if ($request->get('format') == 'CUSTOM REGEX') { - $field->format = e($request->get("custom_format")); + $field->format = e($request->get('custom_format')); } else { - $field->format = e($request->get("format")); + $field->format = e($request->get('format')); } if ($field->save()) { - return redirect()->route("fields.index")->with("success", trans('admin/custom_fields/message.field.update.success')); + return redirect()->route('fields.index')->with('success', trans('admin/custom_fields/message.field.update.success')); } return redirect()->back()->withInput()->with('error', trans('admin/custom_fields/message.field.update.error')); } - - - } diff --git a/app/Http/Controllers/CustomFieldsetsController.php b/app/Http/Controllers/CustomFieldsetsController.php index f484931325..3d072dbcfd 100644 --- a/app/Http/Controllers/CustomFieldsetsController.php +++ b/app/Http/Controllers/CustomFieldsetsController.php @@ -1,4 +1,5 @@ ] */ - class CustomFieldsetsController extends Controller { - /** * Validates and stores a new custom field. * @@ -40,28 +39,25 @@ class CustomFieldsetsController extends Controller $this->authorize('view', $cfset); if ($cfset) { - $custom_fields_list = ["" => "Add New Field to Fieldset"] + CustomField::pluck("name", "id")->toArray(); - + $custom_fields_list = ['' => 'Add New Field to Fieldset'] + CustomField::pluck('name', 'id')->toArray(); $maxid = 0; foreach ($cfset->fields as $field) { if ($field->pivot->order > $maxid) { - $maxid=$field->pivot->order; + $maxid = $field->pivot->order; } if (isset($custom_fields_list[$field->id])) { unset($custom_fields_list[$field->id]); } } - return view("custom_fields.fieldsets.view")->with("custom_fieldset", $cfset)->with("maxid", $maxid+1)->with("custom_fields_list", $custom_fields_list); + return view('custom_fields.fieldsets.view')->with('custom_fieldset', $cfset)->with('maxid', $maxid + 1)->with('custom_fields_list', $custom_fields_list); } - return redirect()->route("fields.index") - ->with("error", trans('admin/custom_fields/message.fieldset.does_not_exist')); - + return redirect()->route('fields.index') + ->with('error', trans('admin/custom_fields/message.fieldset.does_not_exist')); } - /** * Returns a view with a form for creating a new custom fieldset. * @@ -74,10 +70,9 @@ class CustomFieldsetsController extends Controller { $this->authorize('create', CustomFieldset::class); - return view("custom_fields.fieldsets.edit"); + return view('custom_fields.fieldsets.edit'); } - /** * Validates and stores a new custom fieldset. * @@ -92,52 +87,49 @@ class CustomFieldsetsController extends Controller $this->authorize('create', CustomFieldset::class); $cfset = new CustomFieldset([ - "name" => e($request->get("name")), - "user_id" => Auth::user()->id + 'name' => e($request->get('name')), + 'user_id' => Auth::user()->id, ]); $validator = Validator::make($request->all(), $cfset->rules); if ($validator->passes()) { $cfset->save(); - return redirect()->route("fieldsets.show", [$cfset->id]) + + return redirect()->route('fieldsets.show', [$cfset->id]) ->with('success', trans('admin/custom_fields/message.fieldset.create.success')); } + return redirect()->back()->withInput()->withErrors($validator); } - - - /** - * What the actual fuck, Brady? - * - * @todo Uhh, build this? - * @author [Brady Wetherington] [] - * @param int $id - * @since [v1.8] - * @return Fuckall - */ + * What the actual fuck, Brady? + * + * @todo Uhh, build this? + * @author [Brady Wetherington] [] + * @param int $id + * @since [v1.8] + * @return Fuckall + */ public function edit($id) { // } - /** - * GET IN THE SEA BRADY. - * - * @todo Uhh, build this too? - * @author [Brady Wetherington] [] - * @param int $id - * @since [v1.8] - * @return Fuckall - */ + * GET IN THE SEA BRADY. + * + * @todo Uhh, build this too? + * @author [Brady Wetherington] [] + * @param int $id + * @since [v1.8] + * @return Fuckall + */ public function update($id) { // } - /** * Validates a custom fieldset and then deletes if it has no models associated. * @@ -154,30 +146,28 @@ class CustomFieldsetsController extends Controller $this->authorize('delete', $fieldset); if ($fieldset) { - $models = AssetModel::where("fieldset_id", "=", $id); + $models = AssetModel::where('fieldset_id', '=', $id); if ($models->count() == 0) { $fieldset->delete(); - return redirect()->route("fields.index")->with("success", trans('admin/custom_fields/message.fieldset.delete.success')); + + return redirect()->route('fields.index')->with('success', trans('admin/custom_fields/message.fieldset.delete.success')); } - return redirect()->route("fields.index")->with("error", trans('admin/custom_fields/message.fieldset.delete.in_use')); + + return redirect()->route('fields.index')->with('error', trans('admin/custom_fields/message.fieldset.delete.in_use')); } - return redirect()->route("fields.index")->with("error", trans('admin/custom_fields/message.fieldset.does_not_exist')); - - + return redirect()->route('fields.index')->with('error', trans('admin/custom_fields/message.fieldset.does_not_exist')); } - /** - * Associate the custom field with a custom fieldset. - * - * @author [Brady Wetherington] [] - * @since [v1.8] - * @return View - */ + * Associate the custom field with a custom fieldset. + * + * @author [Brady Wetherington] [] + * @since [v1.8] + * @return View + */ public function associate(Request $request, $id) { - $set = CustomFieldset::find($id); $this->authorize('update', $set); @@ -185,17 +175,16 @@ class CustomFieldsetsController extends Controller if ($request->filled('field_id')) { foreach ($set->fields as $field) { if ($field->id == $request->input('field_id')) { - return redirect()->route("fieldsets.show", [$id])->withInput()->withErrors(['field_id' => trans('admin/custom_fields/message.field.already_added')]); + return redirect()->route('fieldsets.show', [$id])->withInput()->withErrors(['field_id' => trans('admin/custom_fields/message.field.already_added')]); } } - $results = $set->fields()->attach($request->input('field_id'), ["required" => ($request->input('required') == "on"),"order" => $request->input('order', 1)]); + $results = $set->fields()->attach($request->input('field_id'), ['required' => ($request->input('required') == 'on'), 'order' => $request->input('order', 1)]); - return redirect()->route("fieldsets.show", [$id])->with("success", trans('admin/custom_fields/message.field.create.assoc_success')); + return redirect()->route('fieldsets.show', [$id])->with('success', trans('admin/custom_fields/message.field.create.assoc_success')); } - return redirect()->route("fieldsets.show", [$id])->with("error", 'No field selected.'); - + return redirect()->route('fieldsets.show', [$id])->with('error', 'No field selected.'); } /** @@ -206,7 +195,6 @@ class CustomFieldsetsController extends Controller */ public function makeFieldRequired($fieldset_id, $field_id) { - $this->authorize('update', CustomFieldset::class); $field = CustomField::findOrFail($field_id); $fieldset = CustomFieldset::findOrFail($fieldset_id); @@ -214,8 +202,7 @@ class CustomFieldsetsController extends Controller $fieldset->fields()->syncWithoutDetaching($fields); return redirect()->route('fieldsets.show', ['fieldset' => $fieldset_id]) - ->with("success", trans('Field successfully set to required')); - + ->with('success', trans('Field successfully set to required')); } /** @@ -233,7 +220,6 @@ class CustomFieldsetsController extends Controller $fieldset->fields()->syncWithoutDetaching($fields); return redirect()->route('fieldsets.show', ['fieldset' => $fieldset_id]) - ->with("success", trans('Field successfully set to optional')); - + ->with('success', trans('Field successfully set to optional')); } } diff --git a/app/Http/Controllers/DashboardController.php b/app/Http/Controllers/DashboardController.php index e6ad988c45..bd527f7643 100755 --- a/app/Http/Controllers/DashboardController.php +++ b/app/Http/Controllers/DashboardController.php @@ -1,47 +1,50 @@ + * @version v1.0 */ class DashboardController extends Controller { /** - * Check authorization and display admin dashboard, otherwise display - * the user's checked-out assets. - * - * @author [A. Gianotto] [] - * @since [v1.0] - * @return View - */ - public function getIndex() + * Check authorization and display admin dashboard, otherwise display + * the user's checked-out assets. + * + * @author [A. Gianotto] [] + * @since [v1.0] + * @return View + */ + public function index() { // Show the page if (Auth::user()->hasAccess('admin')) { - - $asset_stats=null; + $asset_stats = null; $counts['asset'] = \App\Models\Asset::count(); $counts['accessory'] = \App\Models\Accessory::count(); $counts['license'] = \App\Models\License::assetcount(); $counts['consumable'] = \App\Models\Consumable::count(); - $counts['grand_total'] = $counts['asset'] + $counts['accessory'] + $counts['license'] + $counts['consumable']; + $counts['component'] = \App\Models\Component::count(); + $counts['user'] = \App\Models\User::count(); + $counts['grand_total'] = $counts['asset'] + $counts['accessory'] + $counts['license'] + $counts['consumable']; - if ((!file_exists(storage_path().'/oauth-private.key')) || (!file_exists(storage_path().'/oauth-public.key'))) { - \Artisan::call('migrate', ['--force' => true]); + if ((! file_exists(storage_path().'/oauth-private.key')) || (! file_exists(storage_path().'/oauth-public.key'))) { + Artisan::call('migrate', ['--force' => true]); \Artisan::call('passport:install'); } return view('dashboard')->with('asset_stats', $asset_stats)->with('counts', $counts); } else { - // Redirect to the profile page + // Redirect to the profile page return redirect()->intended('account/view-assets'); } } diff --git a/app/Http/Controllers/DepartmentsController.php b/app/Http/Controllers/DepartmentsController.php index b0d7768b0f..920cc1f2b4 100644 --- a/app/Http/Controllers/DepartmentsController.php +++ b/app/Http/Controllers/DepartmentsController.php @@ -34,10 +34,10 @@ class DepartmentsController extends Controller if ($request->filled('company_id')) { $company = Company::find($request->input('company_id')); } + return view('departments/index')->with('company', $company); } - /** * Store a newly created resource in storage. * @@ -53,13 +53,14 @@ class DepartmentsController extends Controller $department = new Department; $department->fill($request->all()); $department->user_id = Auth::user()->id; - $department->manager_id = ($request->filled('manager_id' ) ? $request->input('manager_id') : null); + $department->manager_id = ($request->filled('manager_id') ? $request->input('manager_id') : null); $department = $request->handleImages($department); if ($department->save()) { - return redirect()->route("departments.index")->with('success', trans('admin/departments/message.create.success')); + return redirect()->route('departments.index')->with('success', trans('admin/departments/message.create.success')); } + return redirect()->back()->withInput()->withErrors($department->getErrors()); } @@ -82,10 +83,10 @@ class DepartmentsController extends Controller if (isset($department->id)) { return view('departments/view', compact('department')); } + return redirect()->route('departments.index')->with('error', trans('admin/departments/message.does_not_exist')); } - /** * Returns a form view used to create a new department. * @@ -102,7 +103,6 @@ class DepartmentsController extends Controller return view('departments/edit')->with('item', new Department); } - /** * Validates and deletes selected department. * @@ -125,7 +125,7 @@ class DepartmentsController extends Controller } if ($department->image) { - try { + try { Storage::disk('public')->delete('departments'.'/'.$department->image); } catch (\Exception $e) { \Log::debug($e); @@ -134,7 +134,6 @@ class DepartmentsController extends Controller $department->delete(); return redirect()->back()->with('success', trans('admin/departments/message.delete.success')); - } /** @@ -158,8 +157,8 @@ class DepartmentsController extends Controller return view('departments/edit', compact('item')); } - public function update(ImageUploadRequest $request, $id) { - + public function update(ImageUploadRequest $request, $id) + { if (is_null($department = Department::find($id))) { return redirect()->route('departments.index')->with('error', trans('admin/departments/message.does_not_exist')); } @@ -167,13 +166,14 @@ class DepartmentsController extends Controller $this->authorize('update', $department); $department->fill($request->all()); - $department->manager_id = ($request->filled('manager_id' ) ? $request->input('manager_id') : null); + $department->manager_id = ($request->filled('manager_id') ? $request->input('manager_id') : null); $department = $request->handleImages($department); - + if ($department->save()) { - return redirect()->route("departments.index")->with('success', trans('admin/departments/message.update.success')); + return redirect()->route('departments.index')->with('success', trans('admin/departments/message.update.success')); } + return redirect()->back()->withInput()->withErrors($department->getErrors()); } } diff --git a/app/Http/Controllers/DepreciationsController.php b/app/Http/Controllers/DepreciationsController.php index 8e610a8a03..70bfb78cb5 100755 --- a/app/Http/Controllers/DepreciationsController.php +++ b/app/Http/Controllers/DepreciationsController.php @@ -1,4 +1,5 @@ with('item', new Depreciation); } - /** * Validates and stores the new depreciation data. * @@ -67,16 +66,17 @@ class DepreciationsController extends Controller // create a new instance $depreciation = new Depreciation(); // Depreciation data - $depreciation->name = $request->input('name'); - $depreciation->months = $request->input('months'); - $depreciation->depreciation_min= $request->input('depreciation_min'); - $depreciation->user_id = Auth::id(); + $depreciation->name = $request->input('name'); + $depreciation->months = $request->input('months'); + $depreciation->user_id = Auth::id(); + $depreciation->depreciation_min = $request->input('depreciation_min'); // Was the asset created? if ($depreciation->save()) { // Redirect to the new depreciation page return redirect()->route('depreciations.index')->with('success', trans('admin/depreciations/message.create.success')); } + return redirect()->back()->withInput()->withErrors($depreciation->getErrors()); } @@ -103,7 +103,6 @@ class DepreciationsController extends Controller return view('depreciations/edit', compact('item')); } - /** * Validates and stores the updated depreciation data. * @@ -133,8 +132,9 @@ class DepreciationsController extends Controller // Was the asset created? if ($depreciation->save()) { // Redirect to the depreciation page - return redirect()->route("depreciations.index")->with('success', trans('admin/depreciations/message.update.success')); + return redirect()->route('depreciations.index')->with('success', trans('admin/depreciations/message.update.success')); } + return redirect()->back()->withInput()->withErrors($depreciation->getErrors()); } @@ -145,7 +145,7 @@ class DepreciationsController extends Controller * * @author [A. Gianotto] [permissions = json_encode($request->input('permission')); if ($group->save()) { - return redirect()->route("groups.index")->with('success', trans('admin/groups/message.success.create')); + return redirect()->route('groups.index')->with('success', trans('admin/groups/message.success.create')); } + return redirect()->back()->withInput()->withErrors($group->getErrors()); } /** - * Returns a view that presents a form to edit a User Group. - * - * @author [A. Gianotto] [decodePermissions(); $selected_array = Helper::selectedPermissionsArray($permissions, $groupPermissions); + return view('groups.edit', compact('group', 'permissions', 'selected_array', 'groupPermissions')); } @@ -94,28 +96,30 @@ class GroupsController extends Controller } /** - * Validates and stores the updated User Group data. - * - * @author [A. Gianotto] [route('groups.index')->with('error', trans('admin/groups/message.group_not_found', compact('id'))); } $group->name = $request->input('name'); $group->permissions = json_encode($request->input('permission')); - if (!config('app.lock_passwords')) { + if (! config('app.lock_passwords')) { if ($group->save()) { return redirect()->route('groups.index')->with('success', trans('admin/groups/message.success.update')); } + return redirect()->back()->withInput()->withErrors($group->getErrors()); } + return redirect()->route('groups.index')->with('error', trans('general.feature_disabled')); } @@ -131,14 +135,15 @@ class GroupsController extends Controller */ public function destroy($id = null) { - if (!config('app.lock_passwords')) { - if (!$group = Group::find($id)) { + if (! config('app.lock_passwords')) { + if (! $group = Group::find($id)) { return redirect()->route('groups.index')->with('error', trans('admin/groups/message.group_not_found', compact('id'))); } $group->delete(); // Redirect to the group management page return redirect()->route('groups.index')->with('success', trans('admin/groups/message.success.delete')); } + return redirect()->route('groups.index')->with('error', trans('general.feature_disabled')); } @@ -161,5 +166,4 @@ class GroupsController extends Controller return redirect()->route('groups.index')->with('error', trans('admin/groups/message.group_not_found', compact('id'))); } - } diff --git a/app/Http/Controllers/HealthController.php b/app/Http/Controllers/HealthController.php index 5fc2c70f4e..456f6b6f94 100644 --- a/app/Http/Controllers/HealthController.php +++ b/app/Http/Controllers/HealthController.php @@ -1,9 +1,9 @@ json([ - "status" => "ok" + 'status' => 'ok', ]); } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/ImportsController.php b/app/Http/Controllers/ImportsController.php index 46954303c5..5c2ca6175b 100644 --- a/app/Http/Controllers/ImportsController.php +++ b/app/Http/Controllers/ImportsController.php @@ -16,6 +16,7 @@ class ImportsController extends Controller { $this->authorize('import'); $imports = (new ImportsTransformer)->transformImports(Import::latest()->get()); + return view('importer/import')->with('imports', $imports); } } diff --git a/app/Http/Controllers/Kits/CheckoutKitController.php b/app/Http/Controllers/Kits/CheckoutKitController.php index 0d99560751..2ff79d0d6b 100644 --- a/app/Http/Controllers/Kits/CheckoutKitController.php +++ b/app/Http/Controllers/Kits/CheckoutKitController.php @@ -1,4 +1,5 @@ ] * @return View View to checkout */ @@ -39,6 +39,7 @@ class CheckoutKitController extends Controller $this->authorize('checkout', Asset::class); $kit = PredefinedKit::findOrFail($kit_id); + return view('kits/checkout')->with('kit', $kit); } @@ -59,13 +60,13 @@ class CheckoutKitController extends Controller $kit->id = $kit_id; $checkout_result = $this->kitService->checkout($request, $kit, $user); - if (Arr::has($checkout_result, 'errors') && count($checkout_result['errors']) > 0 ) { + if (Arr::has($checkout_result, 'errors') && count($checkout_result['errors']) > 0) { return redirect()->back()->with('error', 'Checkout error')->with('error_messages', $checkout_result['errors']); // TODO: trans } + return redirect()->back()->with('success', 'Checkout was successful') ->with('assets', Arr::get($checkout_result, 'assets', null)) ->with('accessories', Arr::get($checkout_result, 'accessories', null)) ->with('consumables', Arr::get($checkout_result, 'consumables', null)); // TODO: trans - } } diff --git a/app/Http/Controllers/Kits/PredefinedKitsController.php b/app/Http/Controllers/Kits/PredefinedKitsController.php index 79c76f887d..66c4c3f4ee 100644 --- a/app/Http/Controllers/Kits/PredefinedKitsController.php +++ b/app/Http/Controllers/Kits/PredefinedKitsController.php @@ -1,4 +1,5 @@ authorize('index', PredefinedKit::class); + return view('kits/index'); } /** * Returns a form view to create a new kit. - * + * * @author [D. Minaev] [] * @throws \Illuminate\Auth\Access\AuthorizationException * @return mixed @@ -37,6 +39,7 @@ class PredefinedKitsController extends Controller public function create() { $this->authorize('create', PredefinedKit::class); + return view('kits/create')->with('item', new PredefinedKit); } @@ -53,14 +56,15 @@ class PredefinedKitsController extends Controller $kit = new PredefinedKit; $kit->name = $request->input('name'); - if (!$kit->save()) { + if (! $kit->save()) { return redirect()->back()->withInput()->withErrors($kit->getErrors()); } $success = $kit->save(); - if (!$success) { + if (! $success) { return redirect()->back()->withInput()->withErrors($kit->getErrors()); } - return redirect()->route("kits.index")->with('success', 'Kit was successfully created.'); // TODO: trans() + + return redirect()->route('kits.index')->with('success', 'Kit was successfully created.'); // TODO: trans() } /** @@ -71,7 +75,7 @@ class PredefinedKitsController extends Controller * @param int $kit_id * @return View */ - public function edit($kit_id=null) + public function edit($kit_id = null) { $this->authorize('update', PredefinedKit::class); if ($kit = PredefinedKit::find($kit_id)) { @@ -80,10 +84,10 @@ class PredefinedKitsController extends Controller ->with('models', $kit->models) ->with('licenses', $kit->licenses); } + return redirect()->route('kits.index')->with('error', 'Kit does not exist'); // TODO: trans } - /** * Validates and processes form data from the edit * Predefined Kit form based on the kit ID passed. @@ -93,7 +97,7 @@ class PredefinedKitsController extends Controller * @param int $kit_id * @return Redirect */ - public function update(ImageUploadRequest $request, $kit_id=null) + public function update(ImageUploadRequest $request, $kit_id = null) { $this->authorize('update', PredefinedKit::class); // Check if the kit exists @@ -105,8 +109,9 @@ class PredefinedKitsController extends Controller $kit->name = $request->input('name'); if ($kit->save()) { - return redirect()->route("kits.index")->with('success', 'Kit was successfully updated'); // TODO: trans + return redirect()->route('kits.index')->with('success', 'Kit was successfully updated'); // TODO: trans } + return redirect()->back()->withInput()->withErrors($kit->getErrors()); } @@ -147,12 +152,11 @@ class PredefinedKitsController extends Controller * @param int $modelId * @return View */ - public function show($kit_id=null) + public function show($kit_id = null) { return $this->edit($kit_id); } - /** * Returns a view containing the Predefined Kit edit form. * @@ -165,13 +169,13 @@ class PredefinedKitsController extends Controller $this->authorize('update', PredefinedKit::class); if (($kit = PredefinedKit::find($kit_id)) && ($model = $kit->models()->find($model_id))) { - return view('kits/model-edit', [ 'kit' => $kit, 'model' => $model, - 'item' => $model->pivot + 'item' => $model->pivot, ]); } + return redirect()->route('kits.index')->with('error', 'Kit does not exist'); // TODO: trans } @@ -184,7 +188,6 @@ class PredefinedKitsController extends Controller */ public function updateModel(Request $request, $kit_id, $model_id) { - $this->authorize('update', PredefinedKit::class); if (is_null($kit = PredefinedKit::find($kit_id))) { // Redirect to the kits management page @@ -223,7 +226,7 @@ class PredefinedKitsController extends Controller // Delete childs $kit->models()->detach($model_id); - + // Redirect to the kit management page return redirect()->route('kits.edit', $kit_id)->with('success', 'Model was successfully detached'); // TODO: trans } @@ -239,17 +242,17 @@ class PredefinedKitsController extends Controller public function editLicense($kit_id, $license_id) { $this->authorize('update', PredefinedKit::class); - if (!($kit = PredefinedKit::find($kit_id))) { + if (! ($kit = PredefinedKit::find($kit_id))) { return redirect()->route('kits.index')->with('error', 'Kit does not exist'); // TODO: trans } - if (!($license = $kit->licenses()->find($license_id))) { + if (! ($license = $kit->licenses()->find($license_id))) { return redirect()->route('kits.index')->with('error', 'License does not exist'); // TODO: trans } return view('kits/license-edit', [ 'kit' => $kit, 'license' => $license, - 'item' => $license->pivot + 'item' => $license->pivot, ]); } @@ -263,7 +266,6 @@ class PredefinedKitsController extends Controller */ public function updateLicense(Request $request, $kit_id, $license_id) { - $this->authorize('update', PredefinedKit::class); if (is_null($kit = PredefinedKit::find($kit_id))) { // Redirect to the kits management page @@ -287,7 +289,7 @@ class PredefinedKitsController extends Controller /** * Remove the license from set - * + * * @author [D. Minaev] [] * @param int $kit_id * @param int $license_id @@ -303,12 +305,11 @@ class PredefinedKitsController extends Controller // Delete childs $kit->licenses()->detach($license_id); - + // Redirect to the kit management page return redirect()->route('kits.edit', $kit_id)->with('success', 'License was successfully detached'); // TODO: trans } - /** * Returns a view containing attached accessory edit form. * @@ -320,23 +321,23 @@ class PredefinedKitsController extends Controller public function editAccessory($kit_id, $accessory_id) { $this->authorize('update', PredefinedKit::class); - if (!($kit = PredefinedKit::find($kit_id))) { + if (! ($kit = PredefinedKit::find($kit_id))) { return redirect()->route('kits.index')->with('error', 'Kit does not exist'); // TODO: trans } - if (!($accessory = $kit->accessories()->find($accessory_id))) { + if (! ($accessory = $kit->accessories()->find($accessory_id))) { return redirect()->route('kits.index')->with('error', 'Accessory does not exist'); // TODO: trans } return view('kits/accessory-edit', [ 'kit' => $kit, 'accessory' => $accessory, - 'item' => $accessory->pivot + 'item' => $accessory->pivot, ]); } /** * Update attached accessory - * + * * @author [D. Minaev] [] * @param int $kit_id * @param int $accessory_id @@ -344,7 +345,6 @@ class PredefinedKitsController extends Controller */ public function updateAccessory(Request $request, $kit_id, $accessory_id) { - $this->authorize('update', PredefinedKit::class); if (is_null($kit = PredefinedKit::find($kit_id))) { // Redirect to the kits management page @@ -383,7 +383,7 @@ class PredefinedKitsController extends Controller // Delete childs $kit->accessories()->detach($accessory_id); - + // Redirect to the kit management page return redirect()->route('kits.edit', $kit_id)->with('success', 'Accessory was successfully detached'); // TODO: trans } @@ -399,17 +399,17 @@ class PredefinedKitsController extends Controller public function editConsumable($kit_id, $consumable_id) { $this->authorize('update', PredefinedKit::class); - if (!($kit = PredefinedKit::find($kit_id))) { + if (! ($kit = PredefinedKit::find($kit_id))) { return redirect()->route('kits.index')->with('error', 'Kit does not exist'); // TODO: trans } - if (!($consumable = $kit->consumables()->find($consumable_id))) { + if (! ($consumable = $kit->consumables()->find($consumable_id))) { return redirect()->route('kits.index')->with('error', 'Consumable does not exist'); // TODO: trans } return view('kits/consumable-edit', [ 'kit' => $kit, 'consumable' => $consumable, - 'item' => $consumable->pivot + 'item' => $consumable->pivot, ]); } @@ -423,7 +423,6 @@ class PredefinedKitsController extends Controller */ public function updateConsumable(Request $request, $kit_id, $consumable_id) { - $this->authorize('update', PredefinedKit::class); if (is_null($kit = PredefinedKit::find($kit_id))) { // Redirect to the kits management page @@ -462,7 +461,7 @@ class PredefinedKitsController extends Controller // Delete childs $kit->consumables()->detach($consumable_id); - + // Redirect to the kit management page return redirect()->route('kits.edit', $kit_id)->with('success', 'Consumable was successfully detached'); // TODO: trans } diff --git a/app/Http/Controllers/Licenses/LicenseCheckinController.php b/app/Http/Controllers/Licenses/LicenseCheckinController.php index 7fa7bb8136..d585e6714c 100644 --- a/app/Http/Controllers/Licenses/LicenseCheckinController.php +++ b/app/Http/Controllers/Licenses/LicenseCheckinController.php @@ -16,7 +16,6 @@ use Illuminate\Support\Facades\Validator; class LicenseCheckinController extends Controller { - /** * Makes the form view to check a license seat back into inventory. * @@ -36,10 +35,10 @@ class LicenseCheckinController extends Controller } $this->authorize('checkout', $license); + return view('licenses/checkin', compact('licenseSeat'))->with('backto', $backTo); } - /** * Validates and stores the license checkin action. * @@ -62,9 +61,10 @@ class LicenseCheckinController extends Controller $license = License::find($licenseSeat->license_id); $this->authorize('checkout', $license); - if (!$license->reassignable) { + if (! $license->reassignable) { // Not allowed to checkin Session::flash('error', 'License not reassignable.'); + return redirect()->back()->withInput(); } @@ -89,21 +89,21 @@ class LicenseCheckinController extends Controller } // Update the asset data - $licenseSeat->assigned_to = null; - $licenseSeat->asset_id = null; + $licenseSeat->assigned_to = null; + $licenseSeat->asset_id = null; // Was the asset updated? if ($licenseSeat->save()) { event(new CheckoutableCheckedIn($licenseSeat, $return_to, Auth::user(), $request->input('note'))); - if ($backTo=='user') { - return redirect()->route("users.show", $return_to->id)->with('success', trans('admin/licenses/message.checkin.success')); + if ($backTo == 'user') { + return redirect()->route('users.show', $return_to->id)->with('success', trans('admin/licenses/message.checkin.success')); } - return redirect()->route("licenses.show", $licenseSeat->license_id)->with('success', trans('admin/licenses/message.checkin.success')); + + return redirect()->route('licenses.show', $licenseSeat->license_id)->with('success', trans('admin/licenses/message.checkin.success')); } // Redirect to the license page with error - return redirect()->route("licenses.index")->with('error', trans('admin/licenses/message.checkin.error')); + return redirect()->route('licenses.index')->with('error', trans('admin/licenses/message.checkin.error')); } - } diff --git a/app/Http/Controllers/Licenses/LicenseCheckoutController.php b/app/Http/Controllers/Licenses/LicenseCheckoutController.php index 8edbc2e664..e5a3b98947 100644 --- a/app/Http/Controllers/Licenses/LicenseCheckoutController.php +++ b/app/Http/Controllers/Licenses/LicenseCheckoutController.php @@ -37,10 +37,10 @@ class LicenseCheckoutController extends Controller } $this->authorize('checkout', $license); + return view('licenses/checkout', compact('license')); } - /** * Validates and stores the license checkout action. * @@ -51,10 +51,9 @@ class LicenseCheckoutController extends Controller * @return \Illuminate\Http\RedirectResponse * @throws \Illuminate\Auth\Access\AuthorizationException */ - public function store(LicenseCheckoutRequest $request, $licenseId, $seatId = null) { - if (!$license = License::find($licenseId)) { + if (! $license = License::find($licenseId)) { return redirect()->route('licenses.index')->with('error', trans('admin/licenses/message.not_found')); } @@ -65,24 +64,25 @@ class LicenseCheckoutController extends Controller $checkoutMethod = 'checkoutTo'.ucwords(request('checkout_to_type')); if ($this->$checkoutMethod($licenseSeat)) { - return redirect()->route("licenses.index")->with('success', trans('admin/licenses/message.checkout.success')); + return redirect()->route('licenses.index')->with('success', trans('admin/licenses/message.checkout.success')); } - return redirect()->route("licenses.index")->with('error', trans('Something went wrong handling this checkout.')); + return redirect()->route('licenses.index')->with('error', trans('Something went wrong handling this checkout.')); } protected function findLicenseSeatToCheckout($license, $seatId) { $licenseSeat = LicenseSeat::find($seatId) ?? $license->freeSeat(); - if (!$licenseSeat) { + if (! $licenseSeat) { if ($seatId) { return redirect()->route('licenses.index')->with('error', 'This Seat is not available for checkout.'); } + return redirect()->route('licenses.index')->with('error', 'There are no available seats for this license'); } - if(!$licenseSeat->license->is($license)) { + if (! $licenseSeat->license->is($license)) { return redirect()->route('licenses.index')->with('error', 'The license seat provided does not match the license.'); } @@ -98,14 +98,14 @@ class LicenseCheckoutController extends Controller // Override asset's assigned user if available if ($target->checkedOutToUser()) { - $licenseSeat->assigned_to = $target->assigned_to; + $licenseSeat->assigned_to = $target->assigned_to; } if ($licenseSeat->save()) { - event(new CheckoutableCheckedOut($licenseSeat, $target, Auth::user(), request('note'))); return true; } + return false; } @@ -118,11 +118,11 @@ class LicenseCheckoutController extends Controller $licenseSeat->assigned_to = request('assigned_to'); if ($licenseSeat->save()) { - event(new CheckoutableCheckedOut($licenseSeat, $target, Auth::user(), request('note'))); return true; } + return false; } } diff --git a/app/Http/Controllers/Licenses/LicenseFilesController.php b/app/Http/Controllers/Licenses/LicenseFilesController.php index 33f47d1238..e93aaf2be2 100644 --- a/app/Http/Controllers/Licenses/LicenseFilesController.php +++ b/app/Http/Controllers/Licenses/LicenseFilesController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\Licenses; +use App\Helpers\StorageHelper; use App\Http\Controllers\Controller; use App\Http\Requests\AssetFileRequest; use App\Models\Actionlog; @@ -10,11 +11,9 @@ use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Response; use Illuminate\Support\Facades\Storage; use Symfony\Component\HttpFoundation\JsonResponse; -use App\Helpers\StorageHelper; class LicenseFilesController extends Controller { - /** * Validates and stores files associated with a license. * @@ -34,16 +33,14 @@ class LicenseFilesController extends Controller $this->authorize('update', $license); if ($request->hasFile('file')) { - - if (!Storage::exists('private_uploads/licenses')) Storage::makeDirectory('private_uploads/licenses', 775); + if (! Storage::exists('private_uploads/licenses')) { + Storage::makeDirectory('private_uploads/licenses', 775); + } $upload_success = false; foreach ($request->file('file') as $file) { - - $file_name = 'license-'.$license->id.'-'.str_random(8).'-'.str_slug(basename($file->getClientOriginalName(), '.'.$file->getClientOriginalExtension())).'.'.$file->getClientOriginalExtension(); - $upload_success = $file->storeAs('private_uploads/licenses', $file_name); // $upload_success = $file->storeAs('private_uploads/licenses/'.$file_name, $file); @@ -58,8 +55,10 @@ class LicenseFilesController extends Controller if ($upload_success) { return redirect()->route('licenses.show', $license->id)->with('success', trans('admin/licenses/message.upload.success')); } + return redirect()->route('licenses.show', $license->id)->with('error', trans('admin/licenses/message.upload.error')); } + return redirect()->route('licenses.show', $license->id)->with('error', trans('admin/licenses/message.upload.nofiles')); } // Prepare the error message @@ -67,7 +66,6 @@ class LicenseFilesController extends Controller ->with('error', trans('admin/licenses/message.does_not_exist')); } - /** * Deletes the selected license file. * @@ -89,7 +87,7 @@ class LicenseFilesController extends Controller // Remove the file if one exists if (Storage::exists('licenses/'.$log->filename)) { - try { + try { Storage::delete('licenses/'.$log->filename); } catch (\Exception $e) { \Log::debug($e); @@ -97,6 +95,7 @@ class LicenseFilesController extends Controller } $log->delete(); + return redirect()->back() ->with('success', trans('admin/hardware/message.deletefile.success')); } @@ -105,8 +104,6 @@ class LicenseFilesController extends Controller return redirect()->route('licenses.index')->with('error', trans('admin/licenses/message.does_not_exist')); } - - /** * Allows the selected file to be viewed. * @@ -119,25 +116,24 @@ class LicenseFilesController extends Controller */ public function show($licenseId = null, $fileId = null, $download = true) { - - \Log::info('Private filesystem is: '.config('filesystems.default') ); + \Log::info('Private filesystem is: '.config('filesystems.default')); $license = License::find($licenseId); // the license is valid if (isset($license->id)) { $this->authorize('view', $license); - if (!$log = Actionlog::find($fileId)) { + if (! $log = Actionlog::find($fileId)) { return response('No matching record for that asset/file', 500) ->header('Content-Type', 'text/plain'); } $file = 'private_uploads/licenses/'.$log->filename; - if (Storage::missing($file)) { \Log::debug('NOT EXISTS for '.$file); \Log::debug('NOT EXISTS URL should be '.Storage::url($file)); + return response('File '.$file.' ('.Storage::url($file).') not found on server', 404) ->header('Content-Type', 'text/plain'); } else { @@ -152,20 +148,15 @@ class LicenseFilesController extends Controller if ($contents = file_get_contents(Storage::url($file))) { // TODO - this will fail on private S3 files or large public ones return Response::make(Storage::url($file)->header('Content-Type', mime_content_type($file))); } - return JsonResponse::create(["error" => "Failed validation: "], 500); + + return JsonResponse::create(['error' => 'Failed validation: '], 500); } return StorageHelper::downloader($file); } - } - - } + return redirect()->route('license.index')->with('error', trans('admin/licenses/message.does_not_exist', ['id' => $fileId])); - } - - - } diff --git a/app/Http/Controllers/Licenses/LicensesController.php b/app/Http/Controllers/Licenses/LicensesController.php index 428dfa4f4f..2d1eca6969 100755 --- a/app/Http/Controllers/Licenses/LicensesController.php +++ b/app/Http/Controllers/Licenses/LicensesController.php @@ -1,4 +1,5 @@ authorize('view', License::class); + return view('licenses/index'); } - /** * Returns a form view that allows an admin to create a new licence. * @@ -50,17 +50,15 @@ class LicensesController extends Controller $maintained_list = [ '' => 'Maintained', '1' => 'Yes', - '0' => 'No' + '0' => 'No', ]; return view('licenses/edit') ->with('depreciation_list', Helper::depreciationList()) ->with('maintained_list', $maintained_list) ->with('item', new License); - } - /** * Validates and stores the license form data submitted from the new * license form. @@ -78,31 +76,32 @@ class LicensesController extends Controller // create a new model instance $license = new License(); // Save the license data - $license->company_id = Company::getIdForCurrentUser($request->input('company_id')); - $license->depreciation_id = $request->input('depreciation_id'); - $license->expiration_date = $request->input('expiration_date'); - $license->license_email = $request->input('license_email'); - $license->license_name = $request->input('license_name'); - $license->maintained = $request->input('maintained', 0); - $license->manufacturer_id = $request->input('manufacturer_id'); - $license->name = $request->input('name'); - $license->notes = $request->input('notes'); - $license->order_number = $request->input('order_number'); - $license->purchase_cost = $request->input('purchase_cost'); - $license->purchase_date = $request->input('purchase_date'); - $license->purchase_order = $request->input('purchase_order'); - $license->purchase_order = $request->input('purchase_order'); - $license->reassignable = $request->input('reassignable', 0); - $license->seats = $request->input('seats'); - $license->serial = $request->input('serial'); - $license->supplier_id = $request->input('supplier_id'); - $license->category_id = $request->input('category_id'); - $license->termination_date = $request->input('termination_date'); - $license->user_id = Auth::id(); + $license->company_id = Company::getIdForCurrentUser($request->input('company_id')); + $license->depreciation_id = $request->input('depreciation_id'); + $license->expiration_date = $request->input('expiration_date'); + $license->license_email = $request->input('license_email'); + $license->license_name = $request->input('license_name'); + $license->maintained = $request->input('maintained', 0); + $license->manufacturer_id = $request->input('manufacturer_id'); + $license->name = $request->input('name'); + $license->notes = $request->input('notes'); + $license->order_number = $request->input('order_number'); + $license->purchase_cost = $request->input('purchase_cost'); + $license->purchase_date = $request->input('purchase_date'); + $license->purchase_order = $request->input('purchase_order'); + $license->purchase_order = $request->input('purchase_order'); + $license->reassignable = $request->input('reassignable', 0); + $license->seats = $request->input('seats'); + $license->serial = $request->input('serial'); + $license->supplier_id = $request->input('supplier_id'); + $license->category_id = $request->input('category_id'); + $license->termination_date = $request->input('termination_date'); + $license->user_id = Auth::id(); if ($license->save()) { - return redirect()->route("licenses.index")->with('success', trans('admin/licenses/message.create.success')); + return redirect()->route('licenses.index')->with('success', trans('admin/licenses/message.create.success')); } + return redirect()->back()->withInput()->withErrors($license->getErrors()); } @@ -127,7 +126,7 @@ class LicensesController extends Controller $maintained_list = [ '' => 'Maintained', '1' => 'Yes', - '0' => 'No' + '0' => 'No', ]; return view('licenses/edit', compact('item')) @@ -135,7 +134,6 @@ class LicensesController extends Controller ->with('maintained_list', $maintained_list); } - /** * Validates and stores the license form data submitted from the edit * license form. @@ -156,25 +154,25 @@ class LicensesController extends Controller $this->authorize('update', $license); - $license->company_id = Company::getIdForCurrentUser($request->input('company_id')); - $license->depreciation_id = $request->input('depreciation_id'); - $license->expiration_date = $request->input('expiration_date'); - $license->license_email = $request->input('license_email'); - $license->license_name = $request->input('license_name'); - $license->maintained = $request->input('maintained',0); - $license->name = $request->input('name'); - $license->notes = $request->input('notes'); - $license->order_number = $request->input('order_number'); - $license->purchase_cost = $request->input('purchase_cost'); - $license->purchase_date = $request->input('purchase_date'); - $license->purchase_order = $request->input('purchase_order'); - $license->reassignable = $request->input('reassignable', 0); - $license->serial = $request->input('serial'); - $license->termination_date = $request->input('termination_date'); - $license->seats = e($request->input('seats')); - $license->manufacturer_id = $request->input('manufacturer_id'); - $license->supplier_id = $request->input('supplier_id'); - $license->category_id = $request->input('category_id'); + $license->company_id = Company::getIdForCurrentUser($request->input('company_id')); + $license->depreciation_id = $request->input('depreciation_id'); + $license->expiration_date = $request->input('expiration_date'); + $license->license_email = $request->input('license_email'); + $license->license_name = $request->input('license_name'); + $license->maintained = $request->input('maintained', 0); + $license->name = $request->input('name'); + $license->notes = $request->input('notes'); + $license->order_number = $request->input('order_number'); + $license->purchase_cost = $request->input('purchase_cost'); + $license->purchase_date = $request->input('purchase_date'); + $license->purchase_order = $request->input('purchase_order'); + $license->reassignable = $request->input('reassignable', 0); + $license->serial = $request->input('serial'); + $license->termination_date = $request->input('termination_date'); + $license->seats = e($request->input('seats')); + $license->manufacturer_id = $request->input('manufacturer_id'); + $license->supplier_id = $request->input('supplier_id'); + $license->category_id = $request->input('category_id'); if ($license->save()) { return redirect()->route('licenses.show', ['license' => $licenseId])->with('success', trans('admin/licenses/message.update.success')); @@ -207,7 +205,7 @@ class LicensesController extends Controller // Delete the license and the associated license seats DB::table('license_seats') ->where('id', $license->id) - ->update(array('assigned_to' => null,'asset_id' => null)); + ->update(['assigned_to' => null, 'asset_id' => null]); $licenseSeats = $license->licenseseats(); $licenseSeats->delete(); @@ -219,10 +217,8 @@ class LicensesController extends Controller } // There are still licenses in use. return redirect()->route('licenses.index')->with('error', trans('admin/licenses/message.assoc_users')); - } - /** * Makes the license detail page. * @@ -234,17 +230,17 @@ class LicensesController extends Controller */ public function show($licenseId = null) { - $license = License::with('assignedusers', 'licenseSeats.user', 'licenseSeats.asset')->find($licenseId); if ($license) { $this->authorize('view', $license); + return view('licenses/view', compact('license')); } + return redirect()->route('licenses.index') ->with('error', trans('admin/licenses/message.does_not_exist')); } - public function getClone($licenseId = null) { @@ -257,7 +253,7 @@ class LicensesController extends Controller $maintained_list = [ '' => 'Maintained', '1' => 'Yes', - '0' => 'No' + '0' => 'No', ]; //clone the orig $license = clone $license_to_clone; diff --git a/app/Http/Controllers/LocationsController.php b/app/Http/Controllers/LocationsController.php index 7a112656d4..668b8190b2 100755 --- a/app/Http/Controllers/LocationsController.php +++ b/app/Http/Controllers/LocationsController.php @@ -1,12 +1,12 @@ authorize('create', Location::class); + return view('locations/edit') ->with('item', new Location); } - /** * Validates and stores a new location. * @@ -69,28 +67,28 @@ class LocationsController extends Controller { $this->authorize('create', Location::class); $location = new Location(); - $location->name = $request->input('name'); - $location->parent_id = $request->input('parent_id', null); - $location->currency = $request->input('currency', '$'); - $location->address = $request->input('address'); - $location->address2 = $request->input('address2'); - $location->city = $request->input('city'); - $location->state = $request->input('state'); - $location->country = $request->input('country'); - $location->zip = $request->input('zip'); - $location->ldap_ou = $request->input('ldap_ou'); - $location->manager_id = $request->input('manager_id'); - $location->user_id = Auth::id(); + $location->name = $request->input('name'); + $location->parent_id = $request->input('parent_id', null); + $location->currency = $request->input('currency', '$'); + $location->address = $request->input('address'); + $location->address2 = $request->input('address2'); + $location->city = $request->input('city'); + $location->state = $request->input('state'); + $location->country = $request->input('country'); + $location->zip = $request->input('zip'); + $location->ldap_ou = $request->input('ldap_ou'); + $location->manager_id = $request->input('manager_id'); + $location->user_id = Auth::id(); $location = $request->handleImages($location); if ($location->save()) { - return redirect()->route("locations.index")->with('success', trans('admin/locations/message.create.success')); + return redirect()->route('locations.index')->with('success', trans('admin/locations/message.create.success')); } + return redirect()->back()->withInput()->withErrors($location->getErrors()); } - /** * Makes a form view to edit location information. * @@ -109,11 +107,9 @@ class LocationsController extends Controller return redirect()->route('locations.index')->with('error', trans('admin/locations/message.does_not_exist')); } - return view('locations/edit', compact('item')); } - /** * Validates and stores updated location data from edit form. * @@ -134,24 +130,24 @@ class LocationsController extends Controller } // Update the location data - $location->name = $request->input('name'); - $location->parent_id = $request->input('parent_id', null); - $location->currency = $request->input('currency', '$'); - $location->address = $request->input('address'); - $location->address2 = $request->input('address2'); - $location->city = $request->input('city'); - $location->state = $request->input('state'); - $location->country = $request->input('country'); - $location->zip = $request->input('zip'); - $location->ldap_ou = $request->input('ldap_ou'); - $location->manager_id = $request->input('manager_id'); + $location->name = $request->input('name'); + $location->parent_id = $request->input('parent_id', null); + $location->currency = $request->input('currency', '$'); + $location->address = $request->input('address'); + $location->address2 = $request->input('address2'); + $location->city = $request->input('city'); + $location->state = $request->input('state'); + $location->country = $request->input('country'); + $location->zip = $request->input('zip'); + $location->ldap_ou = $request->input('ldap_ou'); + $location->manager_id = $request->input('manager_id'); $location = $request->handleImages($location); - if ($location->save()) { - return redirect()->route("locations.index")->with('success', trans('admin/locations/message.update.success')); + return redirect()->route('locations.index')->with('success', trans('admin/locations/message.update.success')); } + return redirect()->back()->withInput()->withInput()->withErrors($location->getErrors()); } @@ -182,25 +178,25 @@ class LocationsController extends Controller } if ($location->image) { - try { + try { Storage::disk('public')->delete('locations/'.$location->image); } catch (\Exception $e) { \Log::error($e); } } $location->delete(); + return redirect()->to(route('locations.index'))->with('success', trans('admin/locations/message.delete.success')); } - /** - * Returns a view that invokes the ajax tables which actually contains - * the content for the locations detail page. - * - * @author [A. Gianotto] [] - * @param int $id - * @since [v1.0] - * @return \Illuminate\Contracts\View\View + * Returns a view that invokes the ajax tables which actually contains + * the content for the locations detail page. + * + * @author [A. Gianotto] [] + * @param int $id + * @since [v1.0] + * @return \Illuminate\Contracts\View\View */ public function show($id = null) { @@ -212,29 +208,26 @@ class LocationsController extends Controller return redirect()->route('locations.index')->with('error', trans('admin/locations/message.does_not_exist')); } - -public function print_assigned($id) - { - $location = Location::where('id',$id)->first(); - $parent = Location::where('id',$location->parent_id)->first(); - $manager = User::where('id',$location->manager_id)->first(); + public function print_assigned($id) + { + $location = Location::where('id', $id)->first(); + $parent = Location::where('id', $location->parent_id)->first(); + $manager = User::where('id', $location->manager_id)->first(); $users = User::where('location_id', $id)->with('company', 'department', 'location')->get(); $assets = Asset::where('assigned_to', $id)->where('assigned_type', Location::class)->with('model', 'model.category')->get(); - return view('locations/print')->with('assets', $assets)->with('users',$users)->with('location', $location)->with('parent', $parent)->with('manager', $manager); + return view('locations/print')->with('assets', $assets)->with('users', $users)->with('location', $location)->with('parent', $parent)->with('manager', $manager); } - + public function print_all_assigned($id) { - - $location = Location::where('id',$id)->first(); - $parent = Location::where('id',$location->parent_id)->first(); - $manager = User::where('id',$location->manager_id)->first(); + $location = Location::where('id', $id)->first(); + $parent = Location::where('id', $location->parent_id)->first(); + $manager = User::where('id', $location->manager_id)->first(); $users = User::where('location_id', $id)->with('company', 'department', 'location')->get(); $assets = Asset::where('location_id', $id)->with('model', 'model.category')->get(); - return view('locations/print')->with('assets', $assets)->with('users',$users)->with('location', $location)->with('parent', $parent)->with('manager', $manager); + return view('locations/print')->with('assets', $assets)->with('users', $users)->with('location', $location)->with('parent', $parent)->with('manager', $manager); } - -} \ No newline at end of file +} diff --git a/app/Http/Controllers/ManufacturersController.php b/app/Http/Controllers/ManufacturersController.php index 1943300e30..1f7d2f2c07 100755 --- a/app/Http/Controllers/ManufacturersController.php +++ b/app/Http/Controllers/ManufacturersController.php @@ -1,4 +1,5 @@ authorize('index', Manufacturer::class); + return view('manufacturers/index'); } - /** * Returns a view that displays a form to create a new manufacturer. * @@ -45,10 +46,10 @@ class ManufacturersController extends Controller public function create() { $this->authorize('create', Manufacturer::class); + return view('manufacturers/edit')->with('item', new Manufacturer); } - /** * Validates and stores the data for a new manufacturer. * @@ -61,22 +62,20 @@ class ManufacturersController extends Controller */ public function store(ImageUploadRequest $request) { - $this->authorize('create', Manufacturer::class); $manufacturer = new Manufacturer; - $manufacturer->name = $request->input('name'); - $manufacturer->user_id = Auth::id(); - $manufacturer->url = $request->input('url'); - $manufacturer->support_url = $request->input('support_url'); - $manufacturer->support_phone = $request->input('support_phone'); - $manufacturer->support_email = $request->input('support_email'); + $manufacturer->name = $request->input('name'); + $manufacturer->user_id = Auth::id(); + $manufacturer->url = $request->input('url'); + $manufacturer->support_url = $request->input('support_url'); + $manufacturer->support_phone = $request->input('support_phone'); + $manufacturer->support_email = $request->input('support_email'); $manufacturer = $request->handleImages($manufacturer); - - if ($manufacturer->save()) { return redirect()->route('manufacturers.index')->with('success', trans('admin/manufacturers/message.create.success')); } + return redirect()->back()->withInput()->withErrors($manufacturer->getErrors()); } @@ -96,7 +95,7 @@ class ManufacturersController extends Controller $this->authorize('update', Manufacturer::class); // Check if the manufacturer exists - if (!$item = Manufacturer::find($manufacturerId)) { + if (! $item = Manufacturer::find($manufacturerId)) { return redirect()->route('manufacturers.index')->with('error', trans('admin/manufacturers/message.does_not_exist')); } @@ -104,7 +103,6 @@ class ManufacturersController extends Controller return view('manufacturers/edit', compact('item')); } - /** * Validates and stores the updated manufacturer data. * @@ -126,11 +124,11 @@ class ManufacturersController extends Controller } // Save the data - $manufacturer->name = $request->input('name'); - $manufacturer->url = $request->input('url'); - $manufacturer->support_url = $request->input('support_url'); - $manufacturer->support_phone = $request->input('support_phone'); - $manufacturer->support_email = $request->input('support_email'); + $manufacturer->name = $request->input('name'); + $manufacturer->url = $request->input('url'); + $manufacturer->support_url = $request->input('support_url'); + $manufacturer->support_phone = $request->input('support_phone'); + $manufacturer->support_email = $request->input('support_email'); // Set the model's image property to null if the image is being deleted if ($request->input('image_delete') == 1) { @@ -139,10 +137,10 @@ class ManufacturersController extends Controller $manufacturer = $request->handleImages($manufacturer); - if ($manufacturer->save()) { return redirect()->route('manufacturers.index')->with('success', trans('admin/manufacturers/message.update.success')); } + return redirect()->back()->withInput()->withErrors($manufacturer->getErrors()); } @@ -162,12 +160,12 @@ class ManufacturersController extends Controller return redirect()->route('manufacturers.index')->with('error', trans('admin/manufacturers/message.not_found')); } - if (!$manufacturer->isDeletable()) { + if (! $manufacturer->isDeletable()) { return redirect()->route('manufacturers.index')->with('error', trans('admin/manufacturers/message.assoc_users')); } if ($manufacturer->image) { - try { + try { Storage::disk('public')->delete('manufacturers/'.$manufacturer->image); } catch (\Exception $e) { \Log::info($e); @@ -175,7 +173,7 @@ class ManufacturersController extends Controller } // Soft delete the manufacturer if active, permanent delete if is already deleted - if($manufacturer->deleted_at === NULL) { + if ($manufacturer->deleted_at === null) { $manufacturer->delete(); } else { $manufacturer->forceDelete(); @@ -221,7 +219,7 @@ class ManufacturersController extends Controller public function restore($manufacturers_id) { $this->authorize('create', Manufacturer::class); - $manufacturer = Manufacturer::onlyTrashed()->where('id',$manufacturers_id)->first(); + $manufacturer = Manufacturer::onlyTrashed()->where('id', $manufacturers_id)->first(); if ($manufacturer) { @@ -230,9 +228,10 @@ class ManufacturersController extends Controller if ($manufacturer->restore()) { return redirect()->route('manufacturers.index')->with('success', trans('admin/manufacturers/message.restore.success')); } + return redirect()->back()->with('error', 'Could not restore.'); } - return redirect()->back()->with('error', trans('admin/manufacturers/message.does_not_exist')); + return redirect()->back()->with('error', trans('admin/manufacturers/message.does_not_exist')); } } diff --git a/app/Http/Controllers/ModalController.php b/app/Http/Controllers/ModalController.php index 61a3cf10b6..05f2b280d5 100644 --- a/app/Http/Controllers/ModalController.php +++ b/app/Http/Controllers/ModalController.php @@ -6,15 +6,17 @@ use App\Helpers\Helper; class ModalController extends Controller { - function show($type, $itemId = null) { + public function show($type, $itemId = null) + { $view = view("modals.${type}"); - if($type == "statuslabel") { + if ($type == 'statuslabel') { $view->with('statuslabel_types', Helper::statusTypeList()); } - if(in_array($type, ['kit-model', 'kit-license', 'kit-consumable', 'kit-accessory'])) { + if (in_array($type, ['kit-model', 'kit-license', 'kit-consumable', 'kit-accessory'])) { $view->with('kitId', $itemId); } + return $view; } } diff --git a/app/Http/Controllers/ProfileController.php b/app/Http/Controllers/ProfileController.php index c43317fd79..ef6c00a54a 100755 --- a/app/Http/Controllers/ProfileController.php +++ b/app/Http/Controllers/ProfileController.php @@ -1,4 +1,5 @@ ] - * @since [v1.0] - * @return \Illuminate\Contracts\View\View + * Returns a view with the user's profile form for editing + * + * @author [A. Gianotto] [] + * @since [v1.0] + * @return \Illuminate\Contracts\View\View */ public function getIndex() { $user = Auth::user(); + return view('account/profile', compact('user')); } /** - * Validates and stores the user's update data. - * - * @author [A. Gianotto] [] - * @since [v1.0] - * @return \Illuminate\Http\RedirectResponse + * Validates and stores the user's update data. + * + * @author [A. Gianotto] [] + * @since [v1.0] + * @return \Illuminate\Http\RedirectResponse */ public function postIndex(ImageUploadRequest $request) { - $user = Auth::user(); $user->first_name = $request->input('first_name'); - $user->last_name = $request->input('last_name'); - $user->website = $request->input('website'); - $user->gravatar = $request->input('gravatar'); - $user->skin = $request->input('skin'); - $user->phone = $request->input('phone'); + $user->last_name = $request->input('last_name'); + $user->website = $request->input('website'); + $user->gravatar = $request->input('gravatar'); + $user->skin = $request->input('skin'); + $user->phone = $request->input('phone'); - if (!config('app.lock_passwords')) { + if (! config('app.lock_passwords')) { $user->locale = $request->input('locale', 'en'); } - if ((Gate::allows('self.two_factor')) && ((Setting::getSettings()->two_factor_enabled=='1') && (!config('app.lock_passwords')))) { + if ((Gate::allows('self.two_factor')) && ((Setting::getSettings()->two_factor_enabled == '1') && (! config('app.lock_passwords')))) { $user->two_factor_optin = $request->input('two_factor_optin', '0'); } - if (Gate::allows('self.edit_location') && (!config('app.lock_passwords'))) { - $user->location_id = $request->input('location_id'); + if (Gate::allows('self.edit_location') && (! config('app.lock_passwords'))) { + $user->location_id = $request->input('location_id'); } - if ($request->input('avatar_delete') == 1) { $user->avatar = null; } - if ($request->hasFile('avatar')) { $path = 'avatars'; - if(!Storage::disk('public')->exists($path)) Storage::disk('public')->makeDirectory($path, 775); + if (! Storage::disk('public')->exists($path)) { + Storage::disk('public')->makeDirectory($path, 775); + } $upload = $image = $request->file('avatar'); $ext = $image->getClientOriginalExtension(); $file_name = 'avatar-'.str_random(18).'.'.$ext; - if ($image->getClientOriginalExtension()!='svg') { - $upload = Image::make($image->getRealPath())->resize(84, 84); + if ($image->getClientOriginalExtension() != 'svg') { + $upload = Image::make($image->getRealPath())->resize(84, 84); } // This requires a string instead of an object, so we use ($string) - Storage::disk('public')->put($path.'/'.$file_name, (string)$upload->encode()); + Storage::disk('public')->put($path.'/'.$file_name, (string) $upload->encode()); // Remove Current image if exists if (($user->avatar) && (Storage::disk('public')->exists($path.'/'.$user->avatar))) { @@ -93,15 +94,13 @@ class ProfileController extends Controller $user->avatar = $file_name; } - - if ($user->save()) { return redirect()->route('profile')->with('success', 'Account successfully updated'); } + return redirect()->back()->withInput()->withErrors($user->getErrors()); } - /** * Returns a page with the API token generation interface. * @@ -112,7 +111,8 @@ class ProfileController extends Controller * @since [v4.0] * @return View */ - public function api() { + public function api() + { return view('account/api'); } @@ -124,6 +124,7 @@ class ProfileController extends Controller public function password() { $user = Auth::user(); + return view('account/change-password', compact('user')); } @@ -134,25 +135,23 @@ class ProfileController extends Controller */ public function passwordSave(Request $request) { - if (config('app.lock_passwords')) { return redirect()->route('account.password.index')->with('error', trans('admin/users/table.lock_passwords')); } $user = Auth::user(); - if ($user->ldap_import=='1') { + if ($user->ldap_import == '1') { return redirect()->route('account.password.index')->with('error', trans('admin/users/message.error.password_ldap')); } - $rules = array( + $rules = [ 'current_password' => 'required', 'password' => Setting::passwordComplexityRulesSaving('store').'|confirmed', - ); + ]; $validator = \Validator::make($request->all(), $rules); - $validator->after(function($validator) use ($request, $user) { - - if (!Hash::check($request->input('current_password'), $user->password)) { + $validator->after(function ($validator) use ($request, $user) { + if (! Hash::check($request->input('current_password'), $user->password)) { $validator->errors()->add('current_password', trans('validation.hashed_pass')); } @@ -165,30 +164,24 @@ class ProfileController extends Controller // There may be a more elegant way to do this in the future. // First let's see if that option is enabled in the settings - if (strpos(Setting::passwordComplexityRulesSaving('store'), 'disallow_same_pwd_as_user_fields') !== FALSE) { + if (strpos(Setting::passwordComplexityRulesSaving('store'), 'disallow_same_pwd_as_user_fields') !== false) { if (($request->input('password') == $user->username) || ($request->input('password') == $user->email) || ($request->input('password') == $user->first_name) || - ($request->input('password') == $user->last_name)) - { + ($request->input('password') == $user->last_name)) { $validator->errors()->add('password', trans('validation.disallow_same_pwd_as_user_fields')); } } - - - - }); - if (!$validator->fails()) { + if (! $validator->fails()) { $user->password = Hash::make($request->input('password')); $user->save(); + return redirect()->route('account.password.index')->with('success', 'Password updated!'); - } + return redirect()->back()->withInput()->withErrors($validator); - - } /** @@ -202,14 +195,12 @@ class ProfileController extends Controller * @since [v4.0] * @return View */ - - public function getMenuState(Request $request) { - if ($request->input('state')=='open') { + public function getMenuState(Request $request) + { + if ($request->input('state') == 'open') { $request->session()->put('menu_state', 'open'); } else { $request->session()->put('menu_state', 'closed'); } } - - } diff --git a/app/Http/Controllers/ReportsController.php b/app/Http/Controllers/ReportsController.php index a8c38d77ab..fac4699bba 100644 --- a/app/Http/Controllers/ReportsController.php +++ b/app/Http/Controllers/ReportsController.php @@ -1,4 +1,5 @@ authorize('reports.view'); $accessories = Accessory::orderBy('created_at', 'DESC')->with('company')->get(); + return view('reports/accessories', compact('accessories')); } @@ -62,19 +65,19 @@ class ReportsController extends Controller $this->authorize('reports.view'); $accessories = Accessory::orderBy('created_at', 'DESC')->get(); - $rows = array(); - $header = array( + $rows = []; + $header = [ trans('admin/accessories/table.title'), trans('admin/accessories/general.accessory_category'), trans('admin/accessories/general.total'), - trans('admin/accessories/general.remaining') - ); + trans('admin/accessories/general.remaining'), + ]; $header = array_map('trim', $header); $rows[] = implode($header, ', '); // Row per accessory foreach ($accessories as $accessory) { - $row = array(); + $row = []; $row[] = e($accessory->accessory_name); $row[] = e($accessory->accessory_category); $row[] = e($accessory->total); @@ -123,7 +126,7 @@ class ReportsController extends Controller $csv = \League\Csv\Writer::createFromFileObject(new \SplTempFileObject()); $csv->setOutputBOM(Reader::BOM_UTF16_BE); - $rows = [ ]; + $rows = []; // Create the header row $header = [ @@ -135,7 +138,7 @@ class ReportsController extends Controller trans('admin/hardware/table.purchase_date'), trans('admin/hardware/table.purchase_cost'), trans('admin/hardware/table.book_value'), - trans('admin/hardware/table.diff') + trans('admin/hardware/table.diff'), ]; //we insert the CSV header @@ -143,7 +146,7 @@ class ReportsController extends Controller // Create a row per asset foreach ($assets as $asset) { - $row = [ ]; + $row = []; $row[] = e($asset->asset_tag); $row[] = e($asset->name); $row[] = e($asset->serial); @@ -154,9 +157,9 @@ class ReportsController extends Controller $row[] = ''; // Empty string if unassigned } - if (( $asset->assigned_to > 0 ) && ( $location = $asset->location )) { + if (($asset->assigned_to > 0) && ($location = $asset->location)) { if ($location->city) { - $row[] = e($location->city) . ', ' . e($location->state); + $row[] = e($location->city).', '.e($location->state); } elseif ($location->name) { $row[] = e($location->name); } else { @@ -173,15 +176,14 @@ class ReportsController extends Controller } $row[] = $asset->purchase_date; - $row[] = $currency . Helper::formatCurrencyOutput($asset->purchase_cost); - $row[] = $currency . Helper::formatCurrencyOutput($asset->getDepreciatedValue()); - $row[] = $currency . Helper::formatCurrencyOutput(( $asset->purchase_cost - $asset->getDepreciatedValue() )); + $row[] = $currency.Helper::formatCurrencyOutput($asset->purchase_cost); + $row[] = $currency.Helper::formatCurrencyOutput($asset->getDepreciatedValue()); + $row[] = $currency.Helper::formatCurrencyOutput(($asset->purchase_cost - $asset->getDepreciatedValue())); $csv->insertOne($row); } - $csv->output('depreciation-report-' . date('Y-m-d') . '.csv'); + $csv->output('depreciation-report-'.date('Y-m-d').'.csv'); die; - } @@ -195,6 +197,7 @@ class ReportsController extends Controller public function audit() { $this->authorize('reports.view'); + return view('reports/audit'); } @@ -209,10 +212,10 @@ class ReportsController extends Controller public function getActivityReport() { $this->authorize('reports.view'); + return view('reports/activity'); } - /** * Exports the activity report to CSV * @@ -227,7 +230,6 @@ class ReportsController extends Controller \Debugbar::disable(); $response = new StreamedResponse(function () { - \Log::debug('Starting streamed response'); // Open output stream @@ -245,28 +247,26 @@ class ReportsController extends Controller 'Changed', ]; - $executionTime = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]; + $executionTime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']; \Log::debug('Starting headers: '.$executionTime); fputcsv($handle, $header); - $executionTime = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]; + $executionTime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']; \Log::debug('Added headers: '.$executionTime); - $actionlogs = Actionlog::with('item', 'user', 'target','location') + $actionlogs = Actionlog::with('item', 'user', 'target', 'location') ->orderBy('created_at', 'DESC') - ->chunk(20, function($actionlogs) use($handle) { - - $executionTime = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]; + ->chunk(20, function ($actionlogs) use ($handle) { + $executionTime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']; \Log::debug('Walking results: '.$executionTime); $count = 0; foreach ($actionlogs as $actionlog) { - $count++; $target_name = ''; if ($actionlog->target) { - if ($actionlog->targetType()=='user') { - $target_name = $actionlog->target->getFullNameAttribute(); + if ($actionlog->targetType() == 'user') { + $target_name = $actionlog->target->getFullNameAttribute(); } else { $target_name = $actionlog->target->getDisplayNameAttribute(); } @@ -278,31 +278,26 @@ class ReportsController extends Controller ($actionlog->user) ? e($actionlog->user->getFullNameAttribute()) : '', $actionlog->present()->actionType(), e($actionlog->itemType()), - ($actionlog->itemType()=='user') ? $actionlog->filename : e($actionlog->item->getDisplayNameAttribute()), + ($actionlog->itemType() == 'user') ? $actionlog->filename : e($actionlog->item->getDisplayNameAttribute()), $target_name, - ($actionlog->note) ? e($actionlog->note): '', + ($actionlog->note) ? e($actionlog->note) : '', $actionlog->log_meta, ]; fputcsv($handle, $row); - } }); // Close the output stream fclose($handle); - $executionTime = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]; - \Log::debug('-- SCRIPT COMPLETED IN '. $executionTime); - + $executionTime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']; + \Log::debug('-- SCRIPT COMPLETED IN '.$executionTime); }, 200, [ 'Content-Type' => 'text/csv', - 'Content-Disposition' - => 'attachment; filename="activity-report-'.date('Y-m-d-his').'.csv"', + 'Content-Disposition' => 'attachment; filename="activity-report-'.date('Y-m-d-his').'.csv"', ]); return $response; - - } @@ -336,8 +331,8 @@ class ReportsController extends Controller $this->authorize('reports.view'); $licenses = License::orderBy('created_at', 'DESC')->get(); - $rows = [ ]; - $header = [ + $rows = []; + $header = [ trans('admin/licenses/table.title'), trans('admin/licenses/table.serial'), trans('admin/licenses/form.seats'), @@ -345,7 +340,7 @@ class ReportsController extends Controller trans('admin/licenses/form.expiration'), trans('general.purchase_date'), trans('general.depreciation'), - trans('general.purchase_cost') + trans('general.purchase_cost'), ]; $header = array_map('trim', $header); @@ -353,20 +348,20 @@ class ReportsController extends Controller // Row per license foreach ($licenses as $license) { - $row = [ ]; + $row = []; $row[] = e($license->name); $row[] = e($license->serial); $row[] = e($license->seats); $row[] = $license->remaincount(); $row[] = $license->expiration_date; $row[] = $license->purchase_date; - $row[] = ($license->depreciation!='') ? '' : e($license->depreciation->name); - $row[] = '"' . Helper::formatCurrencyOutput($license->purchase_cost) . '"'; + $row[] = ($license->depreciation != '') ? '' : e($license->depreciation->name); + $row[] = '"'.Helper::formatCurrencyOutput($license->purchase_cost).'"'; $rows[] = implode($row, ','); } - $csv = implode($rows, "\n"); + $csv = implode($rows, "\n"); $response = Response::make($csv, 200); $response->header('Content-Type', 'text/csv'); $response->header('Content-disposition', 'attachment;filename=report.csv'); @@ -386,6 +381,7 @@ class ReportsController extends Controller { $this->authorize('reports.view'); $customfields = CustomField::get(); + return view('reports/custom')->with('customfields', $customfields); } @@ -402,11 +398,9 @@ class ReportsController extends Controller ini_set('max_execution_time', env('REPORT_TIME_LIMIT', 12000)); //12000 seconds = 200 minutes $this->authorize('reports.view'); - \Debugbar::disable(); $customfields = CustomField::get(); $response = new StreamedResponse(function () use ($customfields, $request) { - \Log::debug('Starting streamed response'); // Open output stream @@ -414,7 +408,7 @@ class ReportsController extends Controller stream_set_timeout($handle, 2000); if ($request->filled('use_bom')) { - fprintf($handle, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fprintf($handle, chr(0xEF).chr(0xBB).chr(0xBF)); } $header = []; @@ -452,7 +446,7 @@ class ReportsController extends Controller $header[] = trans('admin/hardware/table.purchase_date'); } - if (($request->filled('purchase_cost')) || ($request->filled('depreciation'))) { + if (($request->filled('purchase_cost')) || ($request->filled('depreciation'))) { $header[] = trans('admin/hardware/table.purchase_cost'); } @@ -564,16 +558,15 @@ class ReportsController extends Controller } } - $executionTime = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]; + $executionTime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']; \Log::debug('Starting headers: '.$executionTime); fputcsv($handle, $header); - $executionTime = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]; + $executionTime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']; \Log::debug('Added headers: '.$executionTime); - $assets = \App\Models\Company::scopeCompanyables(Asset::select('assets.*'))->with( - 'location', 'assetstatus', 'assetlog', 'company', 'defaultLoc','assignedTo', - 'model.category', 'model.manufacturer','supplier'); + 'location', 'assetstatus', 'assetlog', 'company', 'defaultLoc', 'assignedTo', + 'model.category', 'model.manufacturer', 'supplier'); if ($request->filled('by_location_id')) { $assets->where('assets.location_id', $request->input('by_location_id')); @@ -636,10 +629,9 @@ class ReportsController extends Controller if (($request->filled('next_audit_start')) && ($request->filled('next_audit_end'))) { $assets->whereBetween('assets.next_audit_date', [$request->input('next_audit_start'), $request->input('next_audit_end')]); } + $assets->orderBy('assets.id', 'ASC')->chunk(20, function ($assets) use ($handle, $customfields, $request) { - $assets->orderBy('assets.id', 'ASC')->chunk(20, function($assets) use($handle, $customfields, $request) { - - $executionTime = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]; + $executionTime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']; \Log::debug('Walking results: '.$executionTime); $count = 0; foreach ($assets as $asset) { @@ -684,7 +676,7 @@ class ReportsController extends Controller } if ($request->filled('eol')) { - $row[] = ($asset->purchase_date!='') ? $asset->present()->eol_date() : ''; + $row[] = ($asset->purchase_date != '') ? $asset->present()->eol_date() : ''; } if ($request->filled('order')) { @@ -695,7 +687,6 @@ class ReportsController extends Controller $row[] = ($asset->supplier) ? $asset->supplier->name : ''; } - if ($request->filled('location')) { $row[] = ($asset->location) ? $asset->location->present()->name() : ''; } @@ -722,7 +713,6 @@ class ReportsController extends Controller $row[] = ($asset->defaultLoc) ? $asset->defaultLoc->zip : ''; } - if ($request->filled('assigned_to')) { $row[] = ($asset->checkedOutToUser() && $asset->assigned) ? $asset->assigned->getFullNameAttribute() : ($asset->assigned ? $asset->assigned->display_name : ''); $row[] = ($asset->checkedOutToUser() && $asset->assigned) ? 'user' : $asset->assignedType(); @@ -754,7 +744,6 @@ class ReportsController extends Controller } } - if ($request->filled('department')) { if ($asset->checkedOutToUser()) { $row[] = (($asset->assignedto) && ($asset->assignedto->department)) ? $asset->assignedto->department->name : ''; @@ -767,19 +756,17 @@ class ReportsController extends Controller $row[] = ($asset->assetstatus) ? $asset->assetstatus->name.' ('.$asset->present()->statusMeta.')' : ''; } - if ($request->filled('warranty')) { $row[] = ($asset->warranty_months) ? $asset->warranty_months : ''; $row[] = $asset->present()->warrantee_expires(); } - if ($request->filled('depreciation')) { $depreciation = $asset->getDepreciatedValue(); $diff = ($asset->purchase_cost - $depreciation); - $row[] = Helper::formatCurrencyOutput($depreciation); - $row[] = Helper::formatCurrencyOutput($diff); - $row[] = ($asset->depreciation) ? $asset->depreciated_date()->format('Y-m-d') : ''; + $row[] = Helper::formatCurrencyOutput($depreciation); + $row[] = Helper::formatCurrencyOutput($diff); + $row[] = ($asset->depreciation) ? $asset->depreciated_date()->format('Y-m-d') : ''; } if ($request->filled('checkout_date')) { @@ -817,30 +804,23 @@ class ReportsController extends Controller } } fputcsv($handle, $row); - $executionTime = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]; - \Log::debug('-- Record '.$count.' Asset ID:' .$asset->id. ' in '. $executionTime); - + $executionTime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']; + \Log::debug('-- Record '.$count.' Asset ID:'.$asset->id.' in '.$executionTime); } }); // Close the output stream fclose($handle); - $executionTime = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]; - \Log::debug('-- SCRIPT COMPLETED IN '. $executionTime); - + $executionTime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']; + \Log::debug('-- SCRIPT COMPLETED IN '.$executionTime); }, 200, [ 'Content-Type' => 'text/csv', - 'Content-Disposition' - => 'attachment; filename="custom-assets-report-'.date('Y-m-d-his').'.csv"', + 'Content-Disposition' => 'attachment; filename="custom-assets-report-'.date('Y-m-d-his').'.csv"', ]); - return $response; - - } - /** * getImprovementsReport * @@ -857,7 +837,6 @@ class ReportsController extends Controller ->get(); return view('reports/asset_maintenances', compact('assetMaintenances')); - } /** @@ -875,7 +854,7 @@ class ReportsController extends Controller ->orderBy('created_at', 'DESC') ->get(); - $rows = [ ]; + $rows = []; $header = [ trans('admin/hardware/table.asset_tag'), @@ -886,14 +865,14 @@ class ReportsController extends Controller trans('admin/asset_maintenances/form.start_date'), trans('admin/asset_maintenances/form.completion_date'), trans('admin/asset_maintenances/form.asset_maintenance_time'), - trans('admin/asset_maintenances/form.cost') + trans('admin/asset_maintenances/form.cost'), ]; $header = array_map('trim', $header); $rows[] = implode($header, ','); foreach ($assetMaintenances as $assetMaintenance) { - $row = [ ]; + $row = []; $row[] = str_replace(',', '', e($assetMaintenance->asset->asset_tag)); $row[] = str_replace(',', '', e($assetMaintenance->asset->name)); $row[] = str_replace(',', '', e($assetMaintenance->supplier->name)); @@ -907,13 +886,13 @@ class ReportsController extends Controller } else { $improvementTime = intval($assetMaintenance->asset_maintenance_time); } - $row[] = $improvementTime; - $row[] = trans('general.currency') . Helper::formatCurrencyOutput($assetMaintenance->cost); + $row[] = $improvementTime; + $row[] = trans('general.currency').Helper::formatCurrencyOutput($assetMaintenance->cost); $rows[] = implode($row, ','); } // spit out a csv - $csv = implode($rows, "\n"); + $csv = implode($rows, "\n"); $response = Response::make($csv, 200); $response->header('Content-Type', 'text/csv'); $response->header('Content-disposition', 'attachment;filename=report.csv'); @@ -935,14 +914,13 @@ class ReportsController extends Controller /** * Get all assets with pending checkout acceptances */ - $acceptances = CheckoutAcceptance::pending()->get(); $assetsForReport = $acceptances - ->filter(function($acceptance) { - return $acceptance->checkoutable_type == 'App\Models\Asset'; + ->filter(function ($acceptance) { + return $acceptance->checkoutable_type == \App\Models\Asset::class; }) - ->map(function($acceptance) { + ->map(function ($acceptance) { return $acceptance->checkoutable; }); @@ -963,7 +941,7 @@ class ReportsController extends Controller $assetsForReport = Actionlog::whereIn('id', $this->getAssetsNotAcceptedYet()) ->get(); - $rows = [ ]; + $rows = []; $header = [ trans('general.category'), @@ -977,23 +955,22 @@ class ReportsController extends Controller $rows[] = implode($header, ','); foreach ($assetsForReport as $assetItem) { - $row = [ ]; - $row[] = str_replace(',', '', e($assetItem->assetlog->model->category->name)); - $row[] = str_replace(',', '', e($assetItem->assetlog->model->name)); - $row[] = str_replace(',', '', e($assetItem->assetlog->present()->name())); - $row[] = str_replace(',', '', e($assetItem->assetlog->asset_tag)); - $row[] = str_replace(',', '', e($assetItem->assetlog->assignedTo->present()->name())); + $row = []; + $row[] = str_replace(',', '', e($assetItem->assetlog->model->category->name)); + $row[] = str_replace(',', '', e($assetItem->assetlog->model->name)); + $row[] = str_replace(',', '', e($assetItem->assetlog->present()->name())); + $row[] = str_replace(',', '', e($assetItem->assetlog->asset_tag)); + $row[] = str_replace(',', '', e($assetItem->assetlog->assignedTo->present()->name())); $rows[] = implode($row, ','); } // spit out a csv - $csv = implode($rows, "\n"); + $csv = implode($rows, "\n"); $response = Response::make($csv, 200); $response->header('Content-Type', 'text/csv'); $response->header('Content-disposition', 'attachment;filename=report.csv'); return $response; - } /** @@ -1028,6 +1005,7 @@ class ReportsController extends Controller protected function getModelsInCategoriesThatRequireAcceptance($assetCategoriesRequiringAcceptance) { $this->authorize('reports.view'); + return array_pluck(Model::inCategory($assetCategoriesRequiringAcceptance) ->select('id') ->get() @@ -1044,6 +1022,7 @@ class ReportsController extends Controller protected function getCategoriesThatRequireAcceptance() { $this->authorize('reports.view'); + return array_pluck(Category::requiresAcceptance() ->select('id') ->get() @@ -1060,6 +1039,7 @@ class ReportsController extends Controller protected function getAssetsCheckedOutRequiringAcceptance() { $this->authorize('reports.view'); + return $this->getCheckedOutAssetsRequiringAcceptance( $this->getModelsInCategoriesThatRequireAcceptance($this->getCategoriesThatRequireAcceptance()) ); @@ -1075,6 +1055,7 @@ class ReportsController extends Controller protected function getAssetsNotAcceptedYet() { $this->authorize('reports.view'); + return Asset::unaccepted(); } } diff --git a/app/Http/Controllers/SettingsController.php b/app/Http/Controllers/SettingsController.php index 090883b502..a52598592f 100755 --- a/app/Http/Controllers/SettingsController.php +++ b/app/Http/Controllers/SettingsController.php @@ -2,8 +2,8 @@ namespace App\Http\Controllers; -use enshrined\svgSanitize\Sanitizer; use App\Helpers\Helper; +use App\Helpers\StorageHelper; use App\Http\Requests\ImageUploadRequest; use App\Http\Requests\SettingsSamlRequest; use App\Http\Requests\SetupUserRequest; @@ -15,13 +15,13 @@ use Artisan; use Auth; use Crypt; use DB; +use enshrined\svgSanitize\Sanitizer; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Image; use Input; use Redirect; use Response; -use App\Helpers\StorageHelper; /** * This controller handles all actions related to Settings for @@ -46,17 +46,17 @@ class SettingsController extends Controller $start_settings['php_version_min'] = false; if (version_compare(PHP_VERSION, config('app.min_php'), '<')) { - return response('

This software requires PHP version ' . config('app.min_php') . ' or greater. This server is running ' . PHP_VERSION . '.

Please upgrade PHP on this server and try again.

', 500); + return response('

This software requires PHP version '.config('app.min_php').' or greater. This server is running '.PHP_VERSION.'.

Please upgrade PHP on this server and try again.

', 500); } try { - $conn = DB::select('select 2 + 2'); - $start_settings['db_conn'] = true; - $start_settings['db_name'] = DB::connection()->getDatabaseName(); + $conn = DB::select('select 2 + 2'); + $start_settings['db_conn'] = true; + $start_settings['db_name'] = DB::connection()->getDatabaseName(); $start_settings['db_error'] = null; } catch (\PDOException $e) { - $start_settings['db_conn'] = false; - $start_settings['db_name'] = config('database.connections.mysql.database'); + $start_settings['db_conn'] = false; + $start_settings['db_name'] = config('database.connections.mysql.database'); $start_settings['db_error'] = $e->getMessage(); } @@ -65,23 +65,23 @@ class SettingsController extends Controller $host = array_key_exists('SERVER_NAME', $_SERVER) ? $_SERVER['SERVER_NAME'] : null; $port = array_key_exists('SERVER_PORT', $_SERVER) ? $_SERVER['SERVER_PORT'] : null; if (('http://' === $protocol && '80' != $port) || ('https://' === $protocol && '443' != $port)) { - $host .= ':' . $port; + $host .= ':'.$port; } - $pageURL = $protocol . $host . $_SERVER['REQUEST_URI']; + $pageURL = $protocol.$host.$_SERVER['REQUEST_URI']; - $start_settings['url_valid'] = (url('/') . '/setup' === $pageURL); + $start_settings['url_valid'] = (url('/').'/setup' === $pageURL); - $start_settings['url_config'] = url('/'); - $start_settings['real_url'] = $pageURL; + $start_settings['url_config'] = url('/'); + $start_settings['real_url'] = $pageURL; $start_settings['php_version_min'] = true; // Curl the .env file to make sure it's not accessible via a browser - $ch = curl_init($protocol . $host . '/.env'); + $ch = curl_init($protocol.$host.'/.env'); curl_setopt($ch, CURLOPT_HEADER, true); // we want headers curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); - $output = curl_exec($ch); + $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); @@ -99,15 +99,15 @@ class SettingsController extends Controller $environment = app()->environment(); if ('production' != $environment) { - $start_settings['env'] = $environment; + $start_settings['env'] = $environment; $start_settings['prod'] = false; } else { - $start_settings['env'] = $environment; + $start_settings['env'] = $environment; $start_settings['prod'] = true; } if (function_exists('posix_getpwuid')) { // Probably Linux - $owner = posix_getpwuid(fileowner($_SERVER['SCRIPT_FILENAME'])); + $owner = posix_getpwuid(fileowner($_SERVER['SCRIPT_FILENAME'])); $start_settings['owner'] = $owner['name']; } else { // Windows // TODO: Is there a way of knowing if a windows user has elevated permissions @@ -123,11 +123,11 @@ class SettingsController extends Controller } if ((is_writable(storage_path())) - && (is_writable(storage_path() . '/framework')) - && (is_writable(storage_path() . '/framework/cache')) - && (is_writable(storage_path() . '/framework/sessions')) - && (is_writable(storage_path() . '/framework/views')) - && (is_writable(storage_path() . '/logs')) + && (is_writable(storage_path().'/framework')) + && (is_writable(storage_path().'/framework/cache')) + && (is_writable(storage_path().'/framework/sessions')) + && (is_writable(storage_path().'/framework/views')) + && (is_writable(storage_path().'/logs')) ) { $start_settings['writable'] = true; } else { @@ -153,32 +153,32 @@ class SettingsController extends Controller */ public function postSaveFirstAdmin(SetupUserRequest $request) { - $user = new User(); - $user->first_name = $data['first_name'] = $request->input('first_name'); - $user->last_name = $request->input('last_name'); - $user->email = $data['email'] = $request->input('email'); - $user->activated = 1; - $permissions = ['superuser' => 1]; + $user = new User(); + $user->first_name = $data['first_name'] = $request->input('first_name'); + $user->last_name = $request->input('last_name'); + $user->email = $data['email'] = $request->input('email'); + $user->activated = 1; + $permissions = ['superuser' => 1]; $user->permissions = json_encode($permissions); - $user->username = $data['username'] = $request->input('username'); - $user->password = bcrypt($request->input('password')); - $data['password'] = $request->input('password'); + $user->username = $data['username'] = $request->input('username'); + $user->password = bcrypt($request->input('password')); + $data['password'] = $request->input('password'); - $settings = new Setting(); + $settings = new Setting(); $settings->full_multiple_companies_support = $request->input('full_multiple_companies_support', 0); - $settings->site_name = $request->input('site_name'); - $settings->alert_email = $request->input('email'); - $settings->alerts_enabled = 1; - $settings->pwd_secure_min = 10; - $settings->brand = 1; - $settings->locale = $request->input('locale', 'en'); - $settings->default_currency = $request->input('default_currency', 'USD'); - $settings->user_id = 1; - $settings->email_domain = $request->input('email_domain'); - $settings->email_format = $request->input('email_format'); - $settings->next_auto_tag_base = 1; - $settings->auto_increment_assets = $request->input('auto_increment_assets', 0); - $settings->auto_increment_prefix = $request->input('auto_increment_prefix'); + $settings->site_name = $request->input('site_name'); + $settings->alert_email = $request->input('email'); + $settings->alerts_enabled = 1; + $settings->pwd_secure_min = 10; + $settings->brand = 1; + $settings->locale = $request->input('locale', 'en'); + $settings->default_currency = $request->input('default_currency', 'USD'); + $settings->user_id = 1; + $settings->email_domain = $request->input('email_domain'); + $settings->email_format = $request->input('email_format'); + $settings->next_auto_tag_base = 1; + $settings->auto_increment_assets = $request->input('auto_increment_assets', 0); + $settings->auto_increment_prefix = $request->input('auto_increment_prefix'); if ((! $user->isValid()) || (! $settings->isValid())) { return redirect()->back()->withInput()->withErrors($user->getErrors())->withErrors($settings->getErrors()); @@ -188,12 +188,12 @@ class SettingsController extends Controller $settings->save(); if ($request->input('email_creds') == '1') { - $data = []; - $data['email'] = $user->email; - $data['username'] = $user->username; + $data = []; + $data['email'] = $user->email; + $data['username'] = $user->username; $data['first_name'] = $user->first_name; - $data['last_name'] = $user->last_name; - $data['password'] = $request->input('password'); + $data['last_name'] = $user->last_name; + $data['password'] = $request->input('password'); $user->notify(new FirstAdminNotification($data)); } @@ -246,8 +246,7 @@ class SettingsController extends Controller public function getSetupMigrate() { Artisan::call('migrate', ['--force' => true]); - if ((! file_exists(storage_path() . '/oauth-private.key')) || (! file_exists(storage_path() . '/oauth-public.key'))) { - + if ((! file_exists(storage_path().'/oauth-private.key')) || (! file_exists(storage_path().'/oauth-public.key'))) { Artisan::call('migrate', ['--path' => 'vendor/laravel/passport/database/migrations', '--force' => true]); Artisan::call('passport:install'); } @@ -323,27 +322,26 @@ class SettingsController extends Controller $setting->modellist_displays = ''; - if (($request->filled('show_in_model_list')) && (count($request->input('show_in_model_list')) > 0)) - { + if (($request->filled('show_in_model_list')) && (count($request->input('show_in_model_list')) > 0)) { $setting->modellist_displays = implode(',', $request->input('show_in_model_list')); } $setting->full_multiple_companies_support = $request->input('full_multiple_companies_support', '0'); - $setting->unique_serial = $request->input('unique_serial', '0'); - $setting->show_images_in_email = $request->input('show_images_in_email', '0'); - $setting->show_archived_in_list = $request->input('show_archived_in_list', '0'); - $setting->dashboard_message = $request->input('dashboard_message'); - $setting->email_domain = $request->input('email_domain'); - $setting->email_format = $request->input('email_format'); - $setting->username_format = $request->input('username_format'); - $setting->require_accept_signature = $request->input('require_accept_signature'); - $setting->show_assigned_assets = $request->input('show_assigned_assets', '0'); + $setting->unique_serial = $request->input('unique_serial', '0'); + $setting->show_images_in_email = $request->input('show_images_in_email', '0'); + $setting->show_archived_in_list = $request->input('show_archived_in_list', '0'); + $setting->dashboard_message = $request->input('dashboard_message'); + $setting->email_domain = $request->input('email_domain'); + $setting->email_format = $request->input('email_format'); + $setting->username_format = $request->input('username_format'); + $setting->require_accept_signature = $request->input('require_accept_signature'); + $setting->show_assigned_assets = $request->input('show_assigned_assets', '0'); if (! config('app.lock_passwords')) { $setting->login_note = $request->input('login_note'); } - $setting->default_eula_text = $request->input('default_eula_text'); - $setting->thumbnail_max_h = $request->input('thumbnail_max_h'); + $setting->default_eula_text = $request->input('default_eula_text'); + $setting->thumbnail_max_h = $request->input('thumbnail_max_h'); $setting->privacy_policy_link = $request->input('privacy_policy_link'); $setting->depreciation_method = $request->input('depreciation_method'); @@ -394,60 +392,55 @@ class SettingsController extends Controller return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } - $setting->brand = $request->input('brand', '1'); - $setting->header_color = $request->input('header_color'); - $setting->support_footer = $request->input('support_footer'); - $setting->version_footer = $request->input('version_footer'); - $setting->footer_text = $request->input('footer_text'); - $setting->skin = $request->input('skin'); - $setting->allow_user_skin = $request->input('allow_user_skin'); + $setting->brand = $request->input('brand', '1'); + $setting->header_color = $request->input('header_color'); + $setting->support_footer = $request->input('support_footer'); + $setting->version_footer = $request->input('version_footer'); + $setting->footer_text = $request->input('footer_text'); + $setting->skin = $request->input('skin'); + $setting->allow_user_skin = $request->input('allow_user_skin'); $setting->show_url_in_emails = $request->input('show_url_in_emails', '0'); - $setting->logo_print_assets = $request->input('logo_print_assets', '0'); + $setting->logo_print_assets = $request->input('logo_print_assets', '0'); // Only allow the site name and CSS to be changed if lock_passwords is false // Because public demos make people act like dicks if (! config('app.lock_passwords')) { - $setting->site_name = $request->input('site_name'); + $setting->site_name = $request->input('site_name'); $setting->custom_css = $request->input('custom_css'); } - $setting = $request->handleImages($setting,600,'logo','', 'logo'); - + $setting = $request->handleImages($setting, 600, 'logo', '', 'logo'); if ('1' == $request->input('clear_logo')) { Storage::disk('public')->delete($setting->logo); - $setting->logo = null; + $setting->logo = null; $setting->brand = 1; } - - $setting = $request->handleImages($setting,600,'email_logo','', 'email_logo'); + $setting = $request->handleImages($setting, 600, 'email_logo', '', 'email_logo'); if ('1' == $request->input('clear_email_logo')) { Storage::disk('public')->delete($setting->email_logo); - $setting->email_logo = null; + $setting->email_logo = null; // If they are uploading an image, validate it and upload it } - - $setting = $request->handleImages($setting,600,'label_logo','', 'label_logo'); - + $setting = $request->handleImages($setting, 600, 'label_logo', '', 'label_logo'); if ('1' == $request->input('clear_label_logo')) { Storage::disk('public')->delete($setting->label_logo); - $setting->label_logo = null; - + $setting->label_logo = null; } // If the user wants to clear the favicon... if ($request->hasFile('favicon')) { - $favicon_image = $favicon_upload = $request->file('favicon'); - $favicon_ext = $favicon_image->getClientOriginalExtension(); - $setting->favicon = $favicon_file_name = 'favicon-uploaded.' . $favicon_ext; + $favicon_image = $favicon_upload = $request->file('favicon'); + $favicon_ext = $favicon_image->getClientOriginalExtension(); + $setting->favicon = $favicon_file_name = 'favicon-uploaded.'.$favicon_ext; - if (($favicon_image->getClientOriginalExtension()!='ico') && ($favicon_image->getClientOriginalExtension()!='svg')) { + if (($favicon_image->getClientOriginalExtension() != 'ico') && ($favicon_image->getClientOriginalExtension() != 'svg')) { $favicon_upload = Image::make($favicon_image->getRealPath())->resize(null, 36, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); @@ -466,7 +459,7 @@ class SettingsController extends Controller } } elseif ('1' == $request->input('clear_favicon')) { Storage::disk('public')->delete($setting->clear_favicon); - $setting->favicon = null; + $setting->favicon = null; // If they are uploading an image, validate it and upload it } @@ -479,7 +472,6 @@ class SettingsController extends Controller return redirect()->back()->withInput()->withErrors($setting->getErrors()); } - /** * Return a form to allow a super admin to update settings. * @@ -511,7 +503,6 @@ class SettingsController extends Controller return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } if (! config('app.lock_passwords')) { - if ('' == $request->input('two_factor_enabled')) { $setting->two_factor_enabled = null; } else { @@ -519,19 +510,19 @@ class SettingsController extends Controller } // remote user login - $setting->login_remote_user_enabled = (int) $request->input('login_remote_user_enabled'); - $setting->login_common_disabled = (int) $request->input('login_common_disabled'); + $setting->login_remote_user_enabled = (int) $request->input('login_remote_user_enabled'); + $setting->login_common_disabled = (int) $request->input('login_common_disabled'); $setting->login_remote_user_custom_logout_url = $request->input('login_remote_user_custom_logout_url'); $setting->login_remote_user_header_name = $request->input('login_remote_user_header_name'); } - $setting->pwd_secure_uncommon = (int) $request->input('pwd_secure_uncommon'); - $setting->pwd_secure_min = (int) $request->input('pwd_secure_min'); + $setting->pwd_secure_uncommon = (int) $request->input('pwd_secure_uncommon'); + $setting->pwd_secure_min = (int) $request->input('pwd_secure_min'); $setting->pwd_secure_complexity = ''; if ($request->filled('pwd_secure_complexity')) { - $setting->pwd_secure_complexity = implode('|', $request->input('pwd_secure_complexity')); + $setting->pwd_secure_complexity = implode('|', $request->input('pwd_secure_complexity')); } if ($setting->save()) { @@ -576,7 +567,7 @@ class SettingsController extends Controller if (! config('app.lock_passwords')) { $setting->locale = $request->input('locale', 'en'); } - $setting->default_currency = $request->input('default_currency', '$'); + $setting->default_currency = $request->input('default_currency', '$'); $setting->date_display_format = $request->input('date_display_format'); $setting->time_display_format = $request->input('time_display_format'); $setting->digit_separator = $request->input('digit_separator'); @@ -620,18 +611,18 @@ class SettingsController extends Controller return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } - $alert_email = rtrim($request->input('alert_email'), ','); - $alert_email = trim($alert_email); + $alert_email = rtrim($request->input('alert_email'), ','); + $alert_email = trim($alert_email); $admin_cc_email = rtrim($request->input('admin_cc_email'), ','); $admin_cc_email = trim($admin_cc_email); - $setting->alert_email = $alert_email; - $setting->admin_cc_email = $admin_cc_email; - $setting->alerts_enabled = $request->input('alerts_enabled', '0'); - $setting->alert_interval = $request->input('alert_interval'); - $setting->alert_threshold = $request->input('alert_threshold'); - $setting->audit_interval = $request->input('audit_interval'); - $setting->audit_warning_days = $request->input('audit_warning_days'); + $setting->alert_email = $alert_email; + $setting->admin_cc_email = $admin_cc_email; + $setting->alerts_enabled = $request->input('alerts_enabled', '0'); + $setting->alert_interval = $request->input('alert_interval'); + $setting->alert_threshold = $request->input('alert_threshold'); + $setting->audit_interval = $request->input('audit_interval'); + $setting->audit_warning_days = $request->input('audit_warning_days'); $setting->show_alerts_in_menu = $request->input('show_alerts_in_menu', '0'); if ($setting->save()) { @@ -677,13 +668,10 @@ class SettingsController extends Controller 'slack_channel' => 'regex:/(?slack_endpoint = $request->input('slack_endpoint'); $setting->slack_channel = $request->input('slack_channel'); $setting->slack_botname = $request->input('slack_botname'); - } if ($setting->save()) { @@ -727,8 +715,8 @@ class SettingsController extends Controller $setting->auto_increment_prefix = $request->input('auto_increment_prefix'); $setting->auto_increment_assets = $request->input('auto_increment_assets', '0'); - $setting->zerofill_count = $request->input('zerofill_count'); - $setting->next_auto_tag_base = $request->input('next_auto_tag_base'); + $setting->zerofill_count = $request->input('zerofill_count'); + $setting->next_auto_tag_base = $request->input('next_auto_tag_base'); if ($setting->save()) { return redirect()->route('settings.index') @@ -749,7 +737,7 @@ class SettingsController extends Controller */ public function getBarcodes() { - $setting = Setting::getSettings(); + $setting = Setting::getSettings(); $is_gd_installed = extension_loaded('gd'); return view('settings.barcodes', compact('setting'))->with('is_gd_installed', $is_gd_installed); @@ -770,11 +758,11 @@ class SettingsController extends Controller return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } - $setting->qr_code = $request->input('qr_code', '0'); - $setting->alt_barcode = $request->input('alt_barcode'); + $setting->qr_code = $request->input('qr_code', '0'); + $setting->alt_barcode = $request->input('alt_barcode'); $setting->alt_barcode_enabled = $request->input('alt_barcode_enabled', '0'); - $setting->barcode_type = $request->input('barcode_type'); - $setting->qr_text = $request->input('qr_text'); + $setting->barcode_type = $request->input('barcode_type'); + $setting->qr_text = $request->input('qr_text'); if ($setting->save()) { return redirect()->route('settings.index') @@ -833,23 +821,21 @@ class SettingsController extends Controller if (is_null($setting = Setting::getSettings())) { return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } - $setting->labels_per_page = $request->input('labels_per_page'); - $setting->labels_width = $request->input('labels_width'); - $setting->labels_height = $request->input('labels_height'); - $setting->labels_pmargin_left = $request->input('labels_pmargin_left'); - $setting->labels_pmargin_right = $request->input('labels_pmargin_right'); - $setting->labels_pmargin_top = $request->input('labels_pmargin_top'); - $setting->labels_pmargin_bottom = $request->input('labels_pmargin_bottom'); - $setting->labels_display_bgutter = $request->input('labels_display_bgutter'); - $setting->labels_display_sgutter = $request->input('labels_display_sgutter'); - $setting->labels_fontsize = $request->input('labels_fontsize'); - $setting->labels_pagewidth = $request->input('labels_pagewidth'); - $setting->labels_pageheight = $request->input('labels_pageheight'); + $setting->labels_per_page = $request->input('labels_per_page'); + $setting->labels_width = $request->input('labels_width'); + $setting->labels_height = $request->input('labels_height'); + $setting->labels_pmargin_left = $request->input('labels_pmargin_left'); + $setting->labels_pmargin_right = $request->input('labels_pmargin_right'); + $setting->labels_pmargin_top = $request->input('labels_pmargin_top'); + $setting->labels_pmargin_bottom = $request->input('labels_pmargin_bottom'); + $setting->labels_display_bgutter = $request->input('labels_display_bgutter'); + $setting->labels_display_sgutter = $request->input('labels_display_sgutter'); + $setting->labels_fontsize = $request->input('labels_fontsize'); + $setting->labels_pagewidth = $request->input('labels_pagewidth'); + $setting->labels_pageheight = $request->input('labels_pageheight'); $setting->labels_display_company_name = $request->input('labels_display_company_name', '0'); $setting->labels_display_company_name = $request->input('labels_display_company_name', '0'); - - if ($request->filled('labels_display_name')) { $setting->labels_display_name = 1; } else { @@ -919,34 +905,34 @@ class SettingsController extends Controller return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } - if (!config('app.lock_passwords')===true) { - $setting->ldap_enabled = $request->input('ldap_enabled', '0'); - $setting->ldap_server = $request->input('ldap_server'); + if (! config('app.lock_passwords') === true) { + $setting->ldap_enabled = $request->input('ldap_enabled', '0'); + $setting->ldap_server = $request->input('ldap_server'); $setting->ldap_server_cert_ignore = $request->input('ldap_server_cert_ignore', false); - $setting->ldap_uname = $request->input('ldap_uname'); + $setting->ldap_uname = $request->input('ldap_uname'); if ($request->filled('ldap_pword')) { $setting->ldap_pword = Crypt::encrypt($request->input('ldap_pword')); } - $setting->ldap_basedn = $request->input('ldap_basedn'); - $setting->ldap_filter = $request->input('ldap_filter'); - $setting->ldap_username_field = $request->input('ldap_username_field'); - $setting->ldap_lname_field = $request->input('ldap_lname_field'); - $setting->ldap_fname_field = $request->input('ldap_fname_field'); + $setting->ldap_basedn = $request->input('ldap_basedn'); + $setting->ldap_filter = $request->input('ldap_filter'); + $setting->ldap_username_field = $request->input('ldap_username_field'); + $setting->ldap_lname_field = $request->input('ldap_lname_field'); + $setting->ldap_fname_field = $request->input('ldap_fname_field'); $setting->ldap_auth_filter_query = $request->input('ldap_auth_filter_query'); - $setting->ldap_version = $request->input('ldap_version'); - $setting->ldap_active_flag = $request->input('ldap_active_flag'); - $setting->ldap_emp_num = $request->input('ldap_emp_num'); - $setting->ldap_email = $request->input('ldap_email'); - $setting->ad_domain = $request->input('ad_domain'); - $setting->is_ad = $request->input('is_ad', '0'); - $setting->ad_append_domain = $request->input('ad_append_domain', '0'); - $setting->ldap_tls = $request->input('ldap_tls', '0'); - $setting->ldap_pw_sync = $request->input('ldap_pw_sync', '0'); + $setting->ldap_version = $request->input('ldap_version'); + $setting->ldap_active_flag = $request->input('ldap_active_flag'); + $setting->ldap_emp_num = $request->input('ldap_emp_num'); + $setting->ldap_email = $request->input('ldap_email'); + $setting->ad_domain = $request->input('ad_domain'); + $setting->is_ad = $request->input('is_ad', '0'); + $setting->ad_append_domain = $request->input('ad_append_domain', '0'); + $setting->ldap_tls = $request->input('ldap_tls', '0'); + $setting->ldap_pw_sync = $request->input('ldap_pw_sync', '0'); $setting->custom_forgot_pass_url = $request->input('custom_forgot_pass_url'); - $setting->ldap_phone_field = $request->input('ldap_phone'); - $setting->ldap_jobtitle = $request->input('ldap_jobtitle'); - $setting->ldap_country = $request->input('ldap_country'); - $setting->ldap_dept = $request->input('ldap_dept'); + $setting->ldap_phone_field = $request->input('ldap_phone'); + $setting->ldap_jobtitle = $request->input('ldap_jobtitle'); + $setting->ldap_country = $request->input('ldap_country'); + $setting->ldap_dept = $request->input('ldap_dept'); $setting->ldap_client_tls_cert = $request->input('ldap_client_tls_cert'); $setting->ldap_client_tls_key = $request->input('ldap_client_tls_key'); @@ -993,21 +979,21 @@ class SettingsController extends Controller return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error')); } - $setting->saml_enabled = $request->input('saml_enabled', '0'); - $setting->saml_idp_metadata = $request->input('saml_idp_metadata'); - $setting->saml_attr_mapping_username = $request->input('saml_attr_mapping_username'); - $setting->saml_forcelogin = $request->input('saml_forcelogin', '0'); - $setting->saml_slo = $request->input('saml_slo', '0'); - if (!empty($request->input('saml_sp_privatekey'))) { - $setting->saml_sp_x509cert = $request->input('saml_sp_x509cert'); - $setting->saml_sp_privatekey = $request->input('saml_sp_privatekey'); + $setting->saml_enabled = $request->input('saml_enabled', '0'); + $setting->saml_idp_metadata = $request->input('saml_idp_metadata'); + $setting->saml_attr_mapping_username = $request->input('saml_attr_mapping_username'); + $setting->saml_forcelogin = $request->input('saml_forcelogin', '0'); + $setting->saml_slo = $request->input('saml_slo', '0'); + if (! empty($request->input('saml_sp_privatekey'))) { + $setting->saml_sp_x509cert = $request->input('saml_sp_x509cert'); + $setting->saml_sp_privatekey = $request->input('saml_sp_privatekey'); } - if (!empty($request->input('saml_sp_x509certNew'))) { - $setting->saml_sp_x509certNew = $request->input('saml_sp_x509certNew'); + if (! empty($request->input('saml_sp_x509certNew'))) { + $setting->saml_sp_x509certNew = $request->input('saml_sp_x509certNew'); } else { - $setting->saml_sp_x509certNew = ""; + $setting->saml_sp_x509certNew = ''; } - $setting->saml_custom_settings = $request->input('saml_custom_settings'); + $setting->saml_custom_settings = $request->input('saml_custom_settings'); if ($setting->save()) { return redirect()->route('settings.saml.index') @@ -1028,26 +1014,21 @@ class SettingsController extends Controller */ public function getBackups() { - - $path = 'app/backups'; + $path = 'app/backups'; $backup_files = Storage::files($path); - $files_raw = []; + $files_raw = []; if (count($backup_files) > 0) { - for ($f = 0; $f < count($backup_files); ++$f) { + for ($f = 0; $f < count($backup_files); $f++) { // Skip dotfiles like .gitignore and .DS_STORE if ((substr(basename($backup_files[$f]), 0, 1) != '.')) { - $files_raw[] = [ 'filename' => basename($backup_files[$f]), 'filesize' => Setting::fileSizeConvert(Storage::size($backup_files[$f])), 'modified' => Storage::lastModified($backup_files[$f]), ]; - } - - } } @@ -1079,7 +1060,7 @@ class SettingsController extends Controller } $formatted_output = str_replace('Backup completed!', '', $output); - $output_split = explode('...', $formatted_output); + $output_split = explode('...', $formatted_output); if (array_key_exists(2, $output_split)) { return redirect()->route('settings.backups.index')->with('error', $output_split[2]); @@ -1105,8 +1086,8 @@ class SettingsController extends Controller $path = 'app/backups'; if (! config('app.lock_passwords')) { - if (Storage::exists($path . '/' . $filename)) { - return StorageHelper::downloader($path . '/' . $filename); + if (Storage::exists($path.'/'.$filename)) { + return StorageHelper::downloader($path.'/'.$filename); } else { // Redirect to the backup page return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.backup.file_not_found')); @@ -1131,9 +1112,10 @@ class SettingsController extends Controller if (! config('app.lock_passwords')) { $path = 'app/backups'; - if (Storage::exists($path . '/' . $filename)) { + if (Storage::exists($path.'/'.$filename)) { try { - Storage::delete($path . '/' . $filename); + Storage::delete($path.'/'.$filename); + return redirect()->route('settings.backups.index')->with('success', trans('admin/settings/message.backup.file_deleted')); } catch (\Exception $e) { \Log::debug($e); @@ -1158,6 +1140,7 @@ class SettingsController extends Controller public function getPurge() { \Log::warning('User ID '.Auth::user()->id.' is attempting a PURGE'); + return view('settings.purge-form'); } @@ -1174,7 +1157,6 @@ class SettingsController extends Controller { if (! config('app.lock_passwords')) { if ('DELETE' == $request->input('confirm_purge')) { - \Log::warning('User ID '.Auth::user()->id.' initiated a PURGE!'); // Run a backup immediately before processing Artisan::call('backup:run'); diff --git a/app/Http/Controllers/StatuslabelsController.php b/app/Http/Controllers/StatuslabelsController.php index e1b7ffe0ef..0c559560e0 100755 --- a/app/Http/Controllers/StatuslabelsController.php +++ b/app/Http/Controllers/StatuslabelsController.php @@ -1,10 +1,11 @@ authorize('view', Statuslabel::class); + return view('statuslabels.index'); } @@ -37,7 +38,6 @@ class StatuslabelsController extends Controller return redirect()->route('statuslabels.index')->with('error', trans('admin/statuslabels/message.does_not_exist')); } - /** * Statuslabel create. * @@ -54,7 +54,6 @@ class StatuslabelsController extends Controller ->with('statuslabel_types', Helper::statusTypeList()); } - /** * Statuslabel create form processing. * @@ -64,7 +63,6 @@ class StatuslabelsController extends Controller */ public function store(Request $request) { - $this->authorize('create', Statuslabel::class); // create a new model instance $statusLabel = new Statuslabel(); @@ -76,21 +74,21 @@ class StatuslabelsController extends Controller $statusType = Statuslabel::getStatuslabelTypesForDB($request->input('statuslabel_types')); // Save the Statuslabel data - $statusLabel->name = $request->input('name'); - $statusLabel->user_id = Auth::id(); - $statusLabel->notes = $request->input('notes'); - $statusLabel->deployable = $statusType['deployable']; - $statusLabel->pending = $statusType['pending']; - $statusLabel->archived = $statusType['archived']; - $statusLabel->color = $request->input('color'); - $statusLabel->show_in_nav = $request->input('show_in_nav', 0); - $statusLabel->default_label = $request->input('default_label', 0); - + $statusLabel->name = $request->input('name'); + $statusLabel->user_id = Auth::id(); + $statusLabel->notes = $request->input('notes'); + $statusLabel->deployable = $statusType['deployable']; + $statusLabel->pending = $statusType['pending']; + $statusLabel->archived = $statusType['archived']; + $statusLabel->color = $request->input('color'); + $statusLabel->show_in_nav = $request->input('show_in_nav', 0); + $statusLabel->default_label = $request->input('default_label', 0); if ($statusLabel->save()) { // Redirect to the new Statuslabel page return redirect()->route('statuslabels.index')->with('success', trans('admin/statuslabels/message.create.success')); } + return redirect()->back()->withInput()->withErrors($statusLabel->getErrors()); } @@ -112,12 +110,11 @@ class StatuslabelsController extends Controller $use_statuslabel_type = $item->getStatuslabelType(); - $statuslabel_types = array('' => trans('admin/hardware/form.select_statustype')) + array('undeployable' => trans('admin/hardware/general.undeployable')) + array('pending' => trans('admin/hardware/general.pending')) + array('archived' => trans('admin/hardware/general.archived')) + array('deployable' => trans('admin/hardware/general.deployable')); + $statuslabel_types = ['' => trans('admin/hardware/form.select_statustype')] + ['undeployable' => trans('admin/hardware/general.undeployable')] + ['pending' => trans('admin/hardware/general.pending')] + ['archived' => trans('admin/hardware/general.archived')] + ['deployable' => trans('admin/hardware/general.deployable')]; return view('statuslabels/edit', compact('item', 'statuslabel_types'))->with('use_statuslabel_type', $use_statuslabel_type); } - /** * Statuslabel update form processing page. * @@ -134,28 +131,27 @@ class StatuslabelsController extends Controller return redirect()->route('statuslabels.index')->with('error', trans('admin/statuslabels/message.does_not_exist')); } - if (!$request->filled('statuslabel_types')) { + if (! $request->filled('statuslabel_types')) { return redirect()->back()->withInput()->withErrors(['statuslabel_types' => trans('validation.statuslabel_type')]); } - // Update the Statuslabel data - $statustype = Statuslabel::getStatuslabelTypesForDB($request->input('statuslabel_types')); - $statuslabel->name = $request->input('name'); - $statuslabel->notes = $request->input('notes'); - $statuslabel->deployable = $statustype['deployable']; - $statuslabel->pending = $statustype['pending']; - $statuslabel->archived = $statustype['archived']; - $statuslabel->color = $request->input('color'); - $statuslabel->show_in_nav = $request->input('show_in_nav', 0); - $statuslabel->default_label = $request->input('default_label', 0); - + $statustype = Statuslabel::getStatuslabelTypesForDB($request->input('statuslabel_types')); + $statuslabel->name = $request->input('name'); + $statuslabel->notes = $request->input('notes'); + $statuslabel->deployable = $statustype['deployable']; + $statuslabel->pending = $statustype['pending']; + $statuslabel->archived = $statustype['archived']; + $statuslabel->color = $request->input('color'); + $statuslabel->show_in_nav = $request->input('show_in_nav', 0); + $statuslabel->default_label = $request->input('default_label', 0); // Was the asset created? if ($statuslabel->save()) { // Redirect to the saved Statuslabel page - return redirect()->route("statuslabels.index")->with('success', trans('admin/statuslabels/message.update.success')); + return redirect()->route('statuslabels.index')->with('success', trans('admin/statuslabels/message.update.success')); } + return redirect()->back()->withInput()->withErrors($statuslabel->getErrors()); } @@ -177,10 +173,10 @@ class StatuslabelsController extends Controller // Check that there are no assets associated if ($statuslabel->assets()->count() == 0) { $statuslabel->delete(); + return redirect()->route('statuslabels.index')->with('success', trans('admin/statuslabels/message.delete.success')); } return redirect()->route('statuslabels.index')->with('error', trans('admin/statuslabels/message.assoc_assets')); } - } diff --git a/app/Http/Controllers/SuppliersController.php b/app/Http/Controllers/SuppliersController.php index 41ff456791..c36bc34505 100755 --- a/app/Http/Controllers/SuppliersController.php +++ b/app/Http/Controllers/SuppliersController.php @@ -1,4 +1,5 @@ authorize('create', Supplier::class); + return view('suppliers/edit')->with('item', new Supplier); } - /** * Supplier create form processing. * @@ -55,26 +55,26 @@ class SuppliersController extends Controller // Create a new supplier $supplier = new Supplier; // Save the location data - $supplier->name = request('name'); - $supplier->address = request('address'); - $supplier->address2 = request('address2'); - $supplier->city = request('city'); - $supplier->state = request('state'); - $supplier->country = request('country'); - $supplier->zip = request('zip'); - $supplier->contact = request('contact'); - $supplier->phone = request('phone'); - $supplier->fax = request('fax'); - $supplier->email = request('email'); - $supplier->notes = request('notes'); - $supplier->url = $supplier->addhttp(request('url')); - $supplier->user_id = Auth::id(); + $supplier->name = request('name'); + $supplier->address = request('address'); + $supplier->address2 = request('address2'); + $supplier->city = request('city'); + $supplier->state = request('state'); + $supplier->country = request('country'); + $supplier->zip = request('zip'); + $supplier->contact = request('contact'); + $supplier->phone = request('phone'); + $supplier->fax = request('fax'); + $supplier->email = request('email'); + $supplier->notes = request('notes'); + $supplier->url = $supplier->addhttp(request('url')); + $supplier->user_id = Auth::id(); $supplier = $request->handleImages($supplier); - if ($supplier->save()) { return redirect()->route('suppliers.index')->with('success', trans('admin/suppliers/message.create.success')); } + return redirect()->back()->withInput()->withErrors($supplier->getErrors()); } @@ -98,7 +98,6 @@ class SuppliersController extends Controller return view('suppliers/edit', compact('item')); } - /** * Supplier update form processing page. * @@ -116,19 +115,19 @@ class SuppliersController extends Controller } // Save the data - $supplier->name = request('name'); - $supplier->address = request('address'); - $supplier->address2 = request('address2'); - $supplier->city = request('city'); - $supplier->state = request('state'); - $supplier->country = request('country'); - $supplier->zip = request('zip'); - $supplier->contact = request('contact'); - $supplier->phone = request('phone'); - $supplier->fax = request('fax'); - $supplier->email = request('email'); - $supplier->url = $supplier->addhttp(request('url')); - $supplier->notes = request('notes'); + $supplier->name = request('name'); + $supplier->address = request('address'); + $supplier->address2 = request('address2'); + $supplier->city = request('city'); + $supplier->state = request('state'); + $supplier->country = request('country'); + $supplier->zip = request('zip'); + $supplier->contact = request('contact'); + $supplier->phone = request('phone'); + $supplier->fax = request('fax'); + $supplier->email = request('email'); + $supplier->url = $supplier->addhttp(request('url')); + $supplier->notes = request('notes'); $supplier = $request->handleImages($supplier); if ($supplier->save()) { @@ -136,7 +135,6 @@ class SuppliersController extends Controller } return redirect()->back()->withInput()->withErrors($supplier->getErrors()); - } /** @@ -149,11 +147,10 @@ class SuppliersController extends Controller public function destroy($supplierId) { $this->authorize('delete', Supplier::class); - if (is_null($supplier = Supplier::with('asset_maintenances', 'assets', 'licenses')->withCount('asset_maintenances as asset_maintenances_count','assets as assets_count','licenses as licenses_count')->find($supplierId))) { + if (is_null($supplier = Supplier::with('asset_maintenances', 'assets', 'licenses')->withCount('asset_maintenances as asset_maintenances_count', 'assets as assets_count', 'licenses as licenses_count')->find($supplierId))) { return redirect()->route('suppliers.index')->with('error', trans('admin/suppliers/message.not_found')); } - if ($supplier->assets_count > 0) { return redirect()->route('suppliers.index')->with('error', trans('admin/suppliers/message.delete.assoc_assets', ['asset_count' => (int) $supplier->assets_count])); } @@ -167,14 +164,12 @@ class SuppliersController extends Controller } $supplier->delete(); + return redirect()->route('suppliers.index')->with('success', trans('admin/suppliers/message.delete.success') ); - - } - /** * Get the asset information to present to the supplier view page * @@ -187,10 +182,9 @@ class SuppliersController extends Controller $supplier = Supplier::find($supplierId); if (isset($supplier->id)) { - return view('suppliers/view', compact('supplier')); + return view('suppliers/view', compact('supplier')); } return redirect()->route('suppliers.index')->with('error', trans('admin/suppliers/message.does_not_exist')); } - } diff --git a/app/Http/Controllers/Users/BulkUsersController.php b/app/Http/Controllers/Users/BulkUsersController.php index 7bda003802..9f41448d3b 100644 --- a/app/Http/Controllers/Users/BulkUsersController.php +++ b/app/Http/Controllers/Users/BulkUsersController.php @@ -17,7 +17,6 @@ use Illuminate\Support\Facades\Password; class BulkUsersController extends Controller { - /** * Returns a view that confirms the user's a bulk delete will be applied to. * @@ -40,30 +39,25 @@ class BulkUsersController extends Controller if ($request->input('bulk_actions') == 'edit') { return view('users/bulk-edit', compact('users')) ->with('groups', Group::pluck('name', 'id')); - } elseif ($request->input('bulk_actions') == 'delete') { - return view('users/confirm-bulk-delete')->with('users', $users)->with('statuslabel_list', Helper::statusLabelList()); - - + return view('users/confirm-bulk-delete')->with('users', $users)->with('statuslabel_list', Helper::statusLabelList()); } elseif ($request->input('bulk_actions') == 'bulkpasswordreset') { foreach ($users as $user) { - if (($user->activated=='1') && ($user->email!='')) { + if (($user->activated == '1') && ($user->email != '')) { $credentials = ['email' => $user->email]; Password::sendResetLink($credentials, function (Message $message) { $message->subject($this->getEmailSubject()); }); } } + return redirect()->back()->with('success', trans('admin/users/message.password_resets_sent')); - } - } return redirect()->back()->with('error', 'No users selected'); } - /** * Save bulk-edited users * @@ -77,7 +71,7 @@ class BulkUsersController extends Controller { $this->authorize('update', User::class); - if((!$request->filled('ids')) || $request->input('ids') <= 0) { + if ((! $request->filled('ids')) || $request->input('ids') <= 0) { return redirect()->back()->with('error', 'No users selected'); } $user_raw_array = $request->input('ids'); @@ -88,28 +82,25 @@ class BulkUsersController extends Controller $users = User::whereIn('id', $user_raw_array)->where('id', '!=', Auth::user()->id)->get(); $return_array = [ - 'success' => trans('admin/users/message.success.update_bulk') + 'success' => trans('admin/users/message.success.update_bulk'), ]; - $this->conditionallyAddItem('location_id') ->conditionallyAddItem('department_id') ->conditionallyAddItem('company_id') ->conditionallyAddItem('locale') - ->conditionallyAddItem('activated') -; + ->conditionallyAddItem('activated'); // If the manager_id is one of the users being updated, generate a warning. if (array_search($request->input('manager_id'), $user_raw_array)) { $manager_conflict = true; $return_array = [ - 'warning' => trans('admin/users/message.bulk_manager_warn') + 'warning' => trans('admin/users/message.bulk_manager_warn'), ]; } - if (!$manager_conflict) { + if (! $manager_conflict) { $this->conditionallyAddItem('manager_id'); } - // Save the updated info User::whereIn('id', $user_raw_array) ->where('id', '!=', Auth::id())->update($this->update_array); @@ -127,20 +118,21 @@ class BulkUsersController extends Controller /** * Array to store update data per item - * @var Array + * @var array */ private $update_array = []; /** * Adds parameter to update array for an item if it exists in request - * @param String $field field name + * @param string $field field name * @return BulkUsersController Model for Chaining */ protected function conditionallyAddItem($field) { - if(request()->filled($field)) { + if (request()->filled($field)) { $this->update_array[$field] = request()->input($field); } + return $this; } @@ -157,10 +149,10 @@ class BulkUsersController extends Controller { $this->authorize('update', User::class); - if ((!$request->filled('ids')) || (count($request->input('ids')) == 0)) { + if ((! $request->filled('ids')) || (count($request->input('ids')) == 0)) { return redirect()->back()->with('error', 'No users selected'); } - if ((!$request->filled('status_id')) || ($request->input('status_id')=='')) { + if ((! $request->filled('status_id')) || ($request->input('status_id') == '')) { return redirect()->route('users.index')->with('error', 'No status selected'); } @@ -174,11 +166,10 @@ class BulkUsersController extends Controller } $users = User::whereIn('id', $user_raw_array)->get(); - $assets = Asset::whereIn('assigned_to', $user_raw_array)->where('assigned_type', 'App\Models\User')->get(); + $assets = Asset::whereIn('assigned_to', $user_raw_array)->where('assigned_type', \App\Models\User::class)->get(); $accessories = DB::table('accessories_users')->whereIn('assigned_to', $user_raw_array)->get(); $licenses = DB::table('license_seats')->whereIn('assigned_to', $user_raw_array)->get(); - $this->logItemCheckinAndDelete($assets, Asset::class); $this->logItemCheckinAndDelete($accessories, Accessory::class); $this->logItemCheckinAndDelete($licenses, LicenseSeat::class); @@ -189,7 +180,6 @@ class BulkUsersController extends Controller 'assigned_type' => null, ]); - LicenseSeat::whereIn('id', $licenses->pluck('id'))->update(['assigned_to' => null]); foreach ($users as $user) { @@ -205,9 +195,9 @@ class BulkUsersController extends Controller * @param $items * @param $itemType string name of items being passed. */ - protected function logItemCheckinAndDelete($items, $itemType) { - - foreach($items as $item) { + protected function logItemCheckinAndDelete($items, $itemType) + { + foreach ($items as $item) { $logAction = new Actionlog(); $logAction->item_id = $item->id; // We can't rely on get_class here because the licenses/accessories fetched above are not eloquent models, but simply arrays. @@ -219,7 +209,4 @@ class BulkUsersController extends Controller $logAction->logaction('checkin from'); } } - - - } diff --git a/app/Http/Controllers/Users/LDAPImportController.php b/app/Http/Controllers/Users/LDAPImportController.php index 337a43bc36..a204581eb6 100644 --- a/app/Http/Controllers/Users/LDAPImportController.php +++ b/app/Http/Controllers/Users/LDAPImportController.php @@ -3,10 +3,10 @@ namespace App\Http\Controllers\Users; use App\Http\Controllers\Controller; +use App\Models\User; use App\Services\LdapAd; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Artisan; -use App\Models\User; // Note that this is awful close to 'Users' the namespace above; be careful +use Illuminate\Support\Facades\Artisan; // Note that this is awful close to 'Users' the namespace above; be careful class LDAPImportController extends Controller { diff --git a/app/Http/Controllers/Users/UserFilesController.php b/app/Http/Controllers/Users/UserFilesController.php index 61a195012a..9599f9c66c 100644 --- a/app/Http/Controllers/Users/UserFilesController.php +++ b/app/Http/Controllers/Users/UserFilesController.php @@ -26,7 +26,7 @@ class UserFilesController extends Controller public function store(AssetFileRequest $request, $userId = null) { $user = User::find($userId); - $destinationPath = config('app.private_uploads') . '/users'; + $destinationPath = config('app.private_uploads').'/users'; if (isset($user->id)) { $this->authorize('update', $user); @@ -34,14 +34,14 @@ class UserFilesController extends Controller $logActions = []; $files = $request->file('file'); - if (is_null($files)){ + if (is_null($files)) { return redirect()->back()->with('error', trans('admin/users/message.upload.nofiles')); } - foreach($files as $file) { + foreach ($files as $file) { $extension = $file->getClientOriginalExtension(); - $filename = 'user-' . $user->id . '-' . str_random(8); - $filename .= '-' . str_slug($file->getClientOriginalName()) . '.' . $extension; - if (!$file->move($destinationPath, $filename)) { + $filename = 'user-'.$user->id.'-'.str_random(8); + $filename .= '-'.str_slug($file->getClientOriginalName()).'.'.$extension; + if (! $file->move($destinationPath, $filename)) { return redirect()->back()->with('error', trans('admin/users/message.upload.invalidfiles')); } //Log the uploaded file to the log @@ -51,24 +51,22 @@ class UserFilesController extends Controller $logAction->user_id = Auth::id(); $logAction->note = $request->input('notes'); $logAction->target_id = null; - $logAction->created_at = date("Y-m-d H:i:s"); + $logAction->created_at = date('Y-m-d H:i:s'); $logAction->filename = $filename; $logAction->action_type = 'uploaded'; - if (!$logAction->save()) { - return JsonResponse::create(["error" => "Failed validation: " . print_r($logAction->getErrors(), true)], 500); - + if (! $logAction->save()) { + return JsonResponse::create(['error' => 'Failed validation: '.print_r($logAction->getErrors(), true)], 500); } $logActions[] = $logAction; } // dd($logActions); return redirect()->back()->with('success', trans('admin/users/message.upload.success')); } + return redirect()->back()->with('error', trans('admin/users/message.upload.nofiles')); - } - /** * Delete file * @@ -87,18 +85,18 @@ class UserFilesController extends Controller if (isset($user->id)) { $this->authorize('update', $user); $log = Actionlog::find($fileId); - $full_filename = $destinationPath . '/' . $log->filename; + $full_filename = $destinationPath.'/'.$log->filename; if (file_exists($full_filename)) { - unlink($destinationPath . '/' . $log->filename); + unlink($destinationPath.'/'.$log->filename); } $log->delete(); + return redirect()->back()->with('success', trans('admin/users/message.deletefile.success')); } // Prepare the error message $error = trans('admin/users/message.user_not_found', ['id' => $userId]); // Redirect to the licence management page return redirect()->route('users.index')->with('error', $error); - } /** @@ -121,6 +119,7 @@ class UserFilesController extends Controller $log = Actionlog::find($fileId); $file = $log->get_src('users'); + return Response::download($file); //FIXME this doesn't use the new StorageHelper yet, but it's complicated... } // Prepare the error message @@ -129,5 +128,4 @@ class UserFilesController extends Controller // Redirect to the licence management page return redirect()->route('users.index')->with('error', $error); } - } diff --git a/app/Http/Controllers/Users/UsersController.php b/app/Http/Controllers/Users/UsersController.php index 227260369e..018624d22f 100755 --- a/app/Http/Controllers/Users/UsersController.php +++ b/app/Http/Controllers/Users/UsersController.php @@ -1,11 +1,12 @@ authorize('index', User::class); + return view('users/index'); } @@ -72,7 +69,7 @@ class UsersController extends Controller } $permissions = config('permissions'); - $userPermissions = Helper::selectedPermissionsArray($permissions, $request->old('permissions', array())); + $userPermissions = Helper::selectedPermissionsArray($permissions, $request->old('permissions', [])); $permissions = $this->filterDisplayable($permissions); $user = new User; @@ -96,7 +93,7 @@ class UsersController extends Controller $this->authorize('create', User::class); $user = new User; //Username, email, and password need to be handled specially because the need to respect config values on an edit. - $user->email = e($request->input('email')); + $user->email = e($request->input('email')); $user->username = e($request->input('username')); if ($request->filled('password')) { $user->password = bcrypt($request->input('password')); @@ -122,25 +119,24 @@ class UsersController extends Controller // Strip out the superuser permission if the user isn't a superadmin $permissions_array = $request->input('permission'); - if (!Auth::user()->isSuperUser()) { + if (! Auth::user()->isSuperUser()) { unset($permissions_array['superuser']); } - $user->permissions = json_encode($permissions_array); - + $user->permissions = json_encode($permissions_array); // we have to invoke the - app('App\Http\Requests\ImageUploadRequest')->handleImages($user, 600, 'image', 'avatars', 'avatar'); + app(\App\Http\Requests\ImageUploadRequest::class)->handleImages($user, 600, 'image', 'avatars', 'avatar'); if ($user->save()) { if ($request->filled('groups')) { $user->groups()->sync($request->input('groups')); } else { - $user->groups()->sync(array()); + $user->groups()->sync([]); } if (($request->input('email_user') == 1) && ($request->filled('email'))) { // Send the credentials through email - $data = array(); + $data = []; $data['email'] = e($request->input('email')); $data['username'] = e($request->input('username')); $data['first_name'] = e($request->input('first_name')); @@ -149,13 +145,13 @@ class UsersController extends Controller $user->notify(new WelcomeNotification($data)); } + return redirect::route('users.index')->with('success', trans('admin/users/message.success.create')); } + return redirect()->back()->withInput()->withErrors($user->getErrors()); } - - private function filterDisplayable($permissions) { $output = null; @@ -164,6 +160,7 @@ class UsersController extends Controller return $p['display'] === true; }); } + return $output; } @@ -179,7 +176,7 @@ class UsersController extends Controller */ public function edit($id) { - if ($user = User::find($id)) { + if ($user = User::find($id)) { $this->authorize('update', $user); $permissions = config('permissions'); @@ -194,6 +191,7 @@ class UsersController extends Controller } $error = trans('admin/users/message.user_not_found', compact('id')); + return redirect()->route('users.index')->with('error', $error); } @@ -212,7 +210,7 @@ class UsersController extends Controller // We need to reverse the UI specific logic for our // permissions here before we update the user. - $permissions = $request->input('permissions', array()); + $permissions = $request->input('permissions', []); app('request')->request->set('permissions', $permissions); // This is a janky hack to prevent people from changing admin demo user data on the public demo. @@ -245,7 +243,6 @@ class UsersController extends Controller $user->groups()->sync($request->input('groups')); } - // Update the user if ($request->filled('username')) { $user->username = $request->input('username'); @@ -271,7 +268,6 @@ class UsersController extends Controller $user->activated = $request->input('activated', 0); $user->zip = $request->input('zip', null); - // Update the location of any assets checked out to this user Asset::where('assigned_type', User::class) ->where('assigned_to', $user->id) @@ -285,16 +281,15 @@ class UsersController extends Controller $permissions_array = $request->input('permission'); // Strip out the superuser permission if the user isn't a superadmin - if (!Auth::user()->isSuperUser()) { + if (! Auth::user()->isSuperUser()) { unset($permissions_array['superuser']); $permissions_array['superuser'] = $orig_superuser; } - $user->permissions = json_encode($permissions_array); + $user->permissions = json_encode($permissions_array); // Handle uploaded avatar - app('App\Http\Requests\ImageUploadRequest')->handleImages($user, 600, 'avatar', 'avatars', 'avatar'); - + app(\App\Http\Requests\ImageUploadRequest::class)->handleImages($user, 600, 'avatar', 'avatars', 'avatar'); //\Log::debug(print_r($user, true)); @@ -304,6 +299,7 @@ class UsersController extends Controller return redirect()->route('users.index') ->with('success', trans('admin/users/message.success.update')); } + return redirect()->back()->withInput()->withErrors($user->getErrors()); } @@ -334,25 +330,25 @@ class UsersController extends Controller if (($user->assets()) && (($assetsCount = $user->assets()->count()) > 0)) { // Redirect to the user management page return redirect()->route('users.index') - ->with('error', 'This user still has ' . $assetsCount . ' assets associated with them.'); + ->with('error', 'This user still has '.$assetsCount.' assets associated with them.'); } if (($user->licenses()) && (($licensesCount = $user->licenses()->count())) > 0) { // Redirect to the user management page return redirect()->route('users.index') - ->with('error', 'This user still has ' . $licensesCount . ' licenses associated with them.'); + ->with('error', 'This user still has '.$licensesCount.' licenses associated with them.'); } if (($user->accessories()) && (($accessoriesCount = $user->accessories()->count()) > 0)) { // Redirect to the user management page return redirect()->route('users.index') - ->with('error', 'This user still has ' . $accessoriesCount . ' accessories associated with them.'); + ->with('error', 'This user still has '.$accessoriesCount.' accessories associated with them.'); } if (($user->managedLocations()) && (($managedLocationsCount = $user->managedLocations()->count())) > 0) { // Redirect to the user management page return redirect()->route('users.index') - ->with('error', 'This user still has ' . $managedLocationsCount . ' locations that they manage.'); + ->with('error', 'This user still has '.$managedLocationsCount.' locations that they manage.'); } // Delete the user @@ -382,7 +378,7 @@ class UsersController extends Controller { $this->authorize('update', User::class); // Get user information - if (!User::onlyTrashed()->find($id)) { + if (! User::onlyTrashed()->find($id)) { return redirect()->route('users.index')->with('error', trans('admin/users/messages.user_not_found')); } @@ -390,10 +386,10 @@ class UsersController extends Controller if (User::withTrashed()->where('id', $id)->restore()) { return redirect()->route('users.index')->with('success', trans('admin/users/message.success.restored')); } + return redirect()->route('users.index')->with('error', 'User could not be restored.'); } - /** * Return a view with user detail * @@ -405,7 +401,7 @@ class UsersController extends Controller */ public function show($userId = null) { - if (!$user = User::with('assets', 'assets.model', 'consumables', 'accessories', 'licenses', 'userloc')->withTrashed()->find($userId)) { + if (! $user = User::with('assets', 'assets.model', 'consumables', 'accessories', 'licenses', 'userloc')->withTrashed()->find($userId)) { // Redirect to the user management page return redirect()->route('users.index') ->with('error', trans('admin/users/message.user_not_found', ['id' => $userId])); @@ -414,6 +410,7 @@ class UsersController extends Controller $userlog = $user->userlog->load('item'); $this->authorize('view', $user); + return view('users/view', compact('user', 'userlog')) ->with('settings', Setting::getSettings()); } @@ -443,7 +440,7 @@ class UsersController extends Controller } // Do we have permission to unsuspend this user? - if ($user->isSuperUser() && !Auth::user()->isSuperUser()) { + if ($user->isSuperUser() && ! Auth::user()->isSuperUser()) { // Redirect to the user management page return redirect()->route('users.index')->with('error', 'Insufficient permissions!'); } @@ -457,7 +454,6 @@ class UsersController extends Controller } } - /** * Return a view containing a pre-populated new user form, * populated with some fields from an existing user. @@ -473,10 +469,9 @@ class UsersController extends Controller $this->authorize('create', User::class); // We need to reverse the UI specific logic for our // permissions here before we update the user. - $permissions = $request->input('permissions', array()); + $permissions = $request->input('permissions', []); app('request')->request->set('permissions', $permissions); - try { // Get the user information $user_to_clone = User::withTrashed()->find($id); @@ -509,7 +504,6 @@ class UsersController extends Controller } } - /** * Exports users to CSV * @@ -530,7 +524,7 @@ class UsersController extends Controller User::with('assets', 'accessories', 'consumables', 'department', 'licenses', 'manager', 'groups', 'userloc', 'company') ->orderBy('created_at', 'DESC') ->chunk(500, function ($users) use ($handle) { - $headers=[ + $headers = [ // strtolower to prevent Excel from trying to open it as a SYLK file strtolower(trans('general.id')), trans('admin/companies/table.title'), @@ -549,7 +543,7 @@ class UsersController extends Controller trans('admin/users/table.groups'), trans('general.notes'), trans('admin/users/table.activated'), - trans('general.created_at') + trans('general.created_at'), ]; fputcsv($handle, $headers); @@ -579,7 +573,7 @@ class UsersController extends Controller $user->consumables->count(), $user_groups, $user->notes, - ($user->activated=='1') ? trans('general.yes') : trans('general.no'), + ($user->activated == '1') ? trans('general.yes') : trans('general.no'), $user->created_at, ]; @@ -611,6 +605,7 @@ class UsersController extends Controller $assets = Asset::where('assigned_to', $id)->where('assigned_type', User::class)->with('model', 'model.category')->get(); $accessories = $show_user->accessories()->get(); $consumables = $show_user->consumables()->get(); + return view('users/print')->with('assets', $assets) ->with('licenses', $show_user->licenses()->get()) ->with('accessories', $accessories) @@ -619,7 +614,6 @@ class UsersController extends Controller ->with('settings', Setting::getSettings()); } - /** * Send individual password reset email * @@ -627,22 +621,22 @@ class UsersController extends Controller * @since [v5.0.15] * @return \Illuminate\Http\RedirectResponse */ - public function sendPasswordReset($id) { - - if (($user = User::find($id)) && ($user->activated == '1') && ($user->email!='') && ($user->ldap_import == '0')) { + public function sendPasswordReset($id) + { + if (($user = User::find($id)) && ($user->activated == '1') && ($user->email != '') && ($user->ldap_import == '0')) { $credentials = ['email' => $user->email]; try { \Password::sendResetLink($credentials, function (Message $message) use ($user) { $message->subject($this->getEmailSubject()); }); - return redirect()->back()->with('success', trans('admin/users/message.password_reset_sent', ['email' => $user->email])); + return redirect()->back()->with('success', trans('admin/users/message.password_reset_sent', ['email' => $user->email])); } catch (\Exception $e) { return redirect()->back()->with('error', ' Error sending email. :( '); } - } + return redirect()->back()->with('error', 'User is not activated, is LDAP synced, or does not have an email address '); } } diff --git a/app/Http/Controllers/ViewAssetsController.php b/app/Http/Controllers/ViewAssetsController.php index 1525e73dbb..e5e66c7027 100755 --- a/app/Http/Controllers/ViewAssetsController.php +++ b/app/Http/Controllers/ViewAssetsController.php @@ -1,4 +1,5 @@ withTrashed()->find(Auth::user()->id); - $userlog = $user->userlog->load('item', 'user', 'target'); if (isset($user->id)) { @@ -50,42 +49,36 @@ class ViewAssetsController extends Controller // Redirect to the user management page return redirect()->route('users.index') ->with('error', trans('admin/users/message.user_not_found', $user->id)); - } - /** * Returns view of requestable items for a user. * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function getRequestableIndex() { - $assets = Asset::with('model', 'defaultLoc', 'location', 'assignedTo', 'requests')->Hardware()->RequestableAssets()->get(); $models = AssetModel::with('category', 'requests', 'assets')->RequestableModels()->get(); return view('account/requestable-assets', compact('assets', 'models')); } - - public function getRequestItem(Request $request, $itemType, $itemId = null) { $item = null; - $fullItemType = 'App\\Models\\' . studly_case($itemType); + $fullItemType = 'App\\Models\\'.studly_case($itemType); - if ($itemType == "asset_model") { - $itemType = "model"; + if ($itemType == 'asset_model') { + $itemType = 'model'; } - $item = call_user_func(array($fullItemType, 'find'), $itemId); + $item = call_user_func([$fullItemType, 'find'], $itemId); $user = Auth::user(); - $logaction = new Actionlog(); $logaction->item_id = $data['asset_id'] = $item->id; $logaction->item_type = $fullItemType; - $logaction->created_at = $data['requested_date'] = date("Y-m-d H:i:s"); + $logaction->created_at = $data['requested_date'] = date('Y-m-d H:i:s'); if ($user->location_id) { $logaction->location_id = $user->location_id; @@ -99,41 +92,35 @@ class ViewAssetsController extends Controller $data['item_type'] = $itemType; $data['target'] = Auth::user(); - if ($fullItemType == Asset::class) { $data['item_url'] = route('hardware.show', $item->id); } else { $data['item_url'] = route("view/${itemType}", $item->id); - } $settings = Setting::getSettings(); if ($item_request = $item->isRequestedBy($user)) { - $item->cancelRequest(); - $data['item_quantity'] = $item_request->qty; - $logaction->logaction('request_canceled'); + $item->cancelRequest(); + $data['item_quantity'] = $item_request->qty; + $logaction->logaction('request_canceled'); - if (($settings->alert_email!='') && ($settings->alerts_enabled=='1') && (!config('app.lock_passwords'))) { + if (($settings->alert_email != '') && ($settings->alerts_enabled == '1') && (! config('app.lock_passwords'))) { $settings->notify(new RequestAssetCancelation($data)); } return redirect()->route('requestable-assets')->with('success')->with('success', trans('admin/hardware/message.requests.canceled')); - } else { $item->request(); - if (($settings->alert_email!='') && ($settings->alerts_enabled=='1') && (!config('app.lock_passwords'))) { + if (($settings->alert_email != '') && ($settings->alerts_enabled == '1') && (! config('app.lock_passwords'))) { $logaction->logaction('requested'); $settings->notify(new RequestAssetNotification($data)); } - - return redirect()->route('requestable-assets')->with('success')->with('success', trans('admin/hardware/message.requests.success')); } } - /** * Process a specific requested asset * @param null $assetId @@ -141,7 +128,6 @@ class ViewAssetsController extends Controller */ public function getRequestAsset($assetId = null) { - $user = Auth::user(); // Check if the asset exists and is requestable @@ -149,20 +135,20 @@ class ViewAssetsController extends Controller return redirect()->route('requestable-assets') ->with('error', trans('admin/hardware/message.does_not_exist_or_not_requestable')); } - if (!Company::isCurrentUserHasAccess($asset)) { + if (! Company::isCurrentUserHasAccess($asset)) { return redirect()->route('requestable-assets') ->with('error', trans('general.insufficient_permissions')); } $data['item'] = $asset; - $data['target'] = Auth::user(); + $data['target'] = Auth::user(); $data['item_quantity'] = 1; $settings = Setting::getSettings(); $logaction = new Actionlog(); $logaction->item_id = $data['asset_id'] = $asset->id; $logaction->item_type = $data['item_type'] = Asset::class; - $logaction->created_at = $data['requested_date'] = date("Y-m-d H:i:s"); + $logaction->created_at = $data['requested_date'] = date('Y-m-d H:i:s'); if ($user->location_id) { $logaction->location_id = $user->location_id; @@ -170,14 +156,14 @@ class ViewAssetsController extends Controller $logaction->target_id = $data['user_id'] = Auth::user()->id; $logaction->target_type = User::class; - // If it's already requested, cancel the request. if ($asset->isRequestedBy(Auth::user())) { $asset->cancelRequest(); $asset->decrement('requests_counter', 1); - + $logaction->logaction('request canceled'); $settings->notify(new RequestAssetCancelation($data)); + return redirect()->route('requestable-assets') ->with('success')->with('success', trans('admin/hardware/message.requests.cancel-success')); } @@ -187,10 +173,7 @@ class ViewAssetsController extends Controller $asset->increment('requests_counter', 1); $settings->notify(new RequestAssetNotification($data)); - return redirect()->route('requestable-assets')->with('success')->with('success', trans('admin/hardware/message.requests.success')); - - } public function getRequestedAssets() @@ -198,37 +181,33 @@ class ViewAssetsController extends Controller return view('account/requested'); } - // Get the acceptance screen public function getAcceptAsset($logID = null) { - $findlog = Actionlog::where('id', $logID)->first(); - if (!$findlog) { + if (! $findlog) { return redirect()->to('account/view-assets')->with('error', 'No matching record.'); } - if ($findlog->accepted_id!='') { + if ($findlog->accepted_id != '') { return redirect()->to('account/view-assets')->with('error', trans('admin/users/message.error.asset_already_accepted')); } $user = Auth::user(); - // TODO - Fix this for non-assets - if (($findlog->item_type==Asset::class) && ($user->id != $findlog->item->assigned_to)) { + if (($findlog->item_type == Asset::class) && ($user->id != $findlog->item->assigned_to)) { return redirect()->to('account/view-assets')->with('error', trans('admin/users/message.error.incorrect_user_accepted')); } - $item = $findlog->item; // Check if the asset exists if (is_null($item)) { // Redirect to the asset management page return redirect()->to('account')->with('error', trans('admin/hardware/message.does_not_exist')); - } elseif (!Company::isCurrentUserHasAccess($item)) { + } elseif (! Company::isCurrentUserHasAccess($item)) { return redirect()->route('requestable-assets')->with('error', trans('general.insufficient_permissions')); } else { return view('account/accept-asset', compact('item'))->with('findlog', $findlog)->with('item', $item); @@ -245,8 +224,7 @@ class ViewAssetsController extends Controller return redirect()->to('account/view-assets')->with('error', trans('admin/hardware/message.does_not_exist')); } - - if ($findlog->accepted_id!='') { + if ($findlog->accepted_id != '') { // Redirect to the asset management page return redirect()->to('account/view-assets')->with('error', trans('admin/users/message.error.asset_already_accepted')); } @@ -257,48 +235,46 @@ class ViewAssetsController extends Controller $user = Auth::user(); - if (($findlog->item_type==Asset::class) && ($user->id != $findlog->item->assigned_to)) { + if (($findlog->item_type == Asset::class) && ($user->id != $findlog->item->assigned_to)) { return redirect()->to('account/view-assets')->with('error', trans('admin/users/message.error.incorrect_user_accepted')); } if ($request->filled('signature_output')) { $path = config('app.private_uploads').'/signatures'; - $sig_filename = "siglog-".$findlog->id.'-'.date('Y-m-d-his').".png"; + $sig_filename = 'siglog-'.$findlog->id.'-'.date('Y-m-d-his').'.png'; $data_uri = e($request->get('signature_output')); - $encoded_image = explode(",", $data_uri); + $encoded_image = explode(',', $data_uri); $decoded_image = base64_decode($encoded_image[1]); - file_put_contents($path."/".$sig_filename, $decoded_image); + file_put_contents($path.'/'.$sig_filename, $decoded_image); } - $logaction = new Actionlog(); - if ($request->input('asset_acceptance')=='accepted') { - $logaction_msg = 'accepted'; - $accepted="accepted"; + if ($request->input('asset_acceptance') == 'accepted') { + $logaction_msg = 'accepted'; + $accepted = 'accepted'; $return_msg = trans('admin/users/message.accepted'); } else { $logaction_msg = 'declined'; - $accepted="rejected"; + $accepted = 'rejected'; $return_msg = trans('admin/users/message.declined'); } - $logaction->item_id = $findlog->item_id; - $logaction->item_type = $findlog->item_type; + $logaction->item_id = $findlog->item_id; + $logaction->item_type = $findlog->item_type; // Asset - if (($findlog->item_id!='') && ($findlog->item_type==Asset::class)) { - if ($request->input('asset_acceptance')!='accepted') { + if (($findlog->item_id != '') && ($findlog->item_type == Asset::class)) { + if ($request->input('asset_acceptance') != 'accepted') { DB::table('assets') ->where('id', $findlog->item_id) - ->update(array('assigned_to' => null)); + ->update(['assigned_to' => null]); } } $logaction->target_id = $findlog->target_id; $logaction->target_type = User::class; $logaction->note = e($request->input('note')); - $logaction->updated_at = date("Y-m-d H:i:s"); - + $logaction->updated_at = date('Y-m-d H:i:s'); if (isset($sig_filename)) { $logaction->accept_signature = $sig_filename; @@ -307,9 +283,9 @@ class ViewAssetsController extends Controller $update_checkout = DB::table('action_logs') ->where('id', $findlog->id) - ->update(array('accepted_id' => $logaction->id)); + ->update(['accepted_id' => $logaction->id]); - if (($findlog->item_id!='') && ($findlog->item_type==Asset::class)) { + if (($findlog->item_id != '') && ($findlog->item_type == Asset::class)) { $affected_asset = $logaction->item; $affected_asset->accepted = $accepted; $affected_asset->save(); @@ -317,7 +293,6 @@ class ViewAssetsController extends Controller if ($update_checkout) { return redirect()->to('account/view-assets')->with('success', $return_msg); - } else { return redirect()->to('account/view-assets')->with('error', 'Something went wrong '); } diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index bedb8bcca5..dc698142ce 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -15,7 +15,7 @@ class Kernel extends HttpKernel */ protected $middleware = [ \App\Http\Middleware\NoSessionStore::class, - \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, + \Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \Fideloper\Proxy\TrustProxies::class, @@ -43,7 +43,7 @@ class Kernel extends HttpKernel ], 'api' => [ - \Barryvdh\Cors\HandleCors::class, + \Fruitcake\Cors\HandleCors::class, 'throttle:120,1', 'auth:api', ], diff --git a/app/Http/Livewire/CustomFieldSetDefaultValuesForModel.php b/app/Http/Livewire/CustomFieldSetDefaultValuesForModel.php new file mode 100644 index 0000000000..685d400bec --- /dev/null +++ b/app/Http/Livewire/CustomFieldSetDefaultValuesForModel.php @@ -0,0 +1,41 @@ +fieldset_id = AssetModel::find($this->model_id)->fieldset_id; + \Log::error("Mount at least fired, that's got to count for something, yeah?"); //WORKS! YAY! + + } + + public function render() + { + // return 'fart
Hi: {{ $this->add_default_values }} yeah?
'; + return view('livewire.custom-field-set-default-values-for-model'); + } +} diff --git a/app/Http/Livewire/CustomFieldsForFieldset.php b/app/Http/Livewire/CustomFieldsForFieldset.php new file mode 100644 index 0000000000..46d302c396 --- /dev/null +++ b/app/Http/Livewire/CustomFieldsForFieldset.php @@ -0,0 +1,21 @@ +fieldset_id) { + $this->fields = CustomFieldset::find($this->fieldset_id)->fields()->get(); + } + return view('livewire.custom-fields-for-fieldset'); + } +} diff --git a/app/Http/Livewire/LoginForm.php b/app/Http/Livewire/LoginForm.php new file mode 100644 index 0000000000..7d10cb78ae --- /dev/null +++ b/app/Http/Livewire/LoginForm.php @@ -0,0 +1,72 @@ + + * @version v6.0 + * @return Array + */ + public function rules() + { + return [ + 'username' => 'required|string|max:255', + 'password' => 'required', + ]; + } + + /** + * Perform the validation + * + * @author A. Gianotto + * @version v6.0 + */ + public function updated($fields) + { + + if (is_null($fields) || empty($fields)) { + $this->can_submit = false; + } + + $this->validateOnly($fields); + + $this->can_submit = true; + + + } + + /** + * Actually do the login thing + * + * @todo fix missing LDAP stuff maybe? Not sure if it + * makes sense to even do this via LiveWire, since + * our login system is pretty complicated. + * + * @author A. Gianotto + * @version v6.0 + */ + public function submitForm() + { + + $this->can_submit = true; + + if (auth()->attempt($this->validate())) { + return redirect()->intended('/'); + } else { + return session()->flash('error', trans('auth/message.account_not_found')); + } + + } + + +} diff --git a/app/Http/Middleware/AssetCountForSidebar.php b/app/Http/Middleware/AssetCountForSidebar.php index ac14f8f8d2..414c10e8a1 100644 --- a/app/Http/Middleware/AssetCountForSidebar.php +++ b/app/Http/Middleware/AssetCountForSidebar.php @@ -2,8 +2,8 @@ namespace App\Http\Middleware; -use Auth; use App\Models\Asset; +use Auth; use Closure; class AssetCountForSidebar @@ -17,8 +17,7 @@ class AssetCountForSidebar */ public function handle($request, Closure $next) { - try - { + try { $total_rtd_sidebar = Asset::RTD()->count(); view()->share('total_rtd_sidebar', $total_rtd_sidebar); } catch (\Exception $e) { diff --git a/app/Http/Middleware/CheckForDebug.php b/app/Http/Middleware/CheckForDebug.php index 923b76b1c6..6b6bd6ba8b 100644 --- a/app/Http/Middleware/CheckForDebug.php +++ b/app/Http/Middleware/CheckForDebug.php @@ -18,7 +18,7 @@ class CheckForDebug { view()->share('debug_in_production', false); - if (((Auth::check() && (Auth::user()->isSuperUser()))) && (app()->environment()=='production') && (config('app.warn_debug')===true) && (config('app.debug')===true)) { + if (((Auth::check() && (Auth::user()->isSuperUser()))) && (app()->environment() == 'production') && (config('app.warn_debug') === true) && (config('app.debug') === true)) { view()->share('debug_in_production', true); } diff --git a/app/Http/Middleware/CheckForSetup.php b/app/Http/Middleware/CheckForSetup.php index aa21f649fa..b4beb70588 100644 --- a/app/Http/Middleware/CheckForSetup.php +++ b/app/Http/Middleware/CheckForSetup.php @@ -19,22 +19,17 @@ class CheckForSetup } if (Setting::setupCompleted()) { - if ($request->is('setup*')) { return redirect(url('/')); } else { return $next($request); } - } else { - if (!($request->is('setup*')) && !($request->is('.env')) && !($request->is('health'))) { + if (! ($request->is('setup*')) && ! ($request->is('.env')) && ! ($request->is('health'))) { return redirect(url('/').'/setup'); } return $next($request); - } - - } } diff --git a/app/Http/Middleware/CheckPermissions.php b/app/Http/Middleware/CheckPermissions.php index a0b5be6ad6..48df11ba51 100644 --- a/app/Http/Middleware/CheckPermissions.php +++ b/app/Http/Middleware/CheckPermissions.php @@ -7,31 +7,25 @@ use Gate; class CheckPermissions { - /** - * Handle the ACLs for permissions. - * - * The $section variable is passed via the route middleware, - * 'middleware' => [authorize:superadmin'] - * - * @param \Illuminate\Http\Request $request - * @param \Closure $next - * @param string|null $section - * @return mixed - */ + /** + * Handle the ACLs for permissions. + * + * The $section variable is passed via the route middleware, + * 'middleware' => [authorize:superadmin'] + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @param string|null $section + * @return mixed + */ public function handle($request, Closure $next, $section = null) { - - if (Gate::allows($section)) { return $next($request); } return response()->view('layouts/basic', [ - 'content' => view('errors/403') + 'content' => view('errors/403'), ]); - - - - } } diff --git a/app/Http/Middleware/EncryptCookies.php b/app/Http/Middleware/EncryptCookies.php index 7817127da3..5f4c62723a 100644 --- a/app/Http/Middleware/EncryptCookies.php +++ b/app/Http/Middleware/EncryptCookies.php @@ -6,7 +6,6 @@ use Illuminate\Cookie\Middleware\EncryptCookies as BaseEncrypter; class EncryptCookies extends BaseEncrypter { - /** * The names of the cookies that should not be encrypted. * @@ -22,6 +21,4 @@ class EncryptCookies extends BaseEncrypter * @var bool */ protected static $serialize = true; - - } diff --git a/app/Http/Middleware/NoSessionStore.php b/app/Http/Middleware/NoSessionStore.php index 86706a0974..c445d4e7f8 100644 --- a/app/Http/Middleware/NoSessionStore.php +++ b/app/Http/Middleware/NoSessionStore.php @@ -7,7 +7,7 @@ use Closure; class NoSessionStore { protected $except = [ - 'health' + 'health', ]; /** @@ -24,6 +24,7 @@ class NoSessionStore config()->set('session.driver', 'array'); } } + return $next($request); } -} \ No newline at end of file +} diff --git a/app/Http/Middleware/PreventRequestsDuringMaintenance.php b/app/Http/Middleware/PreventRequestsDuringMaintenance.php new file mode 100644 index 0000000000..e4956d0bb9 --- /dev/null +++ b/app/Http/Middleware/PreventRequestsDuringMaintenance.php @@ -0,0 +1,17 @@ +headers->set('Feature-Policy', $feature_policy); - - // Defaults to same-origin if REFERRER_POLICY is not set in the .env $response->headers->set('Referrer-Policy', config('app.referrer_policy')); @@ -86,7 +84,6 @@ class SecurityHeaders $response->headers->set('X-Frame-Options', 'DENY'); } - // This defaults to false to maintain backwards compatibility for // people who are not running Snipe-IT over TLS (shame, shame, shame!) // Seriously though, please run Snipe-IT over TLS. Let's Encrypt is free. @@ -99,15 +96,15 @@ class SecurityHeaders // We have to exclude debug mode here because debugbar pulls from a CDN or two // and it will break things. - if ((config('app.debug')!='true') && (config('app.enable_csp')=='true')) { + if ((config('app.debug') != 'true') && (config('app.enable_csp') == 'true')) { $csp_policy[] = "default-src 'self'"; $csp_policy[] = "style-src 'self' 'unsafe-inline'"; $csp_policy[] = "script-src 'self' 'unsafe-inline' 'unsafe-eval'"; $csp_policy[] = "connect-src 'self'"; $csp_policy[] = "object-src 'none'"; $csp_policy[] = "font-src 'self' data:"; - $csp_policy[] = "img-src 'self' data: ".config('app.url')." ".env('PUBLIC_AWS_URL')." https://secure.gravatar.com http://gravatar.com maps.google.com maps.gstatic.com *.googleapis.com"; - $csp_policy = join(';', $csp_policy); + $csp_policy[] = "img-src 'self' data: ".config('app.url').' '.env('PUBLIC_AWS_URL').' https://secure.gravatar.com http://gravatar.com maps.google.com maps.gstatic.com *.googleapis.com'; + $csp_policy = implode(';', $csp_policy); $response->headers->set('Content-Security-Policy', $csp_policy); } @@ -116,7 +113,8 @@ class SecurityHeaders private function removeUnwantedHeaders($headerList) { - foreach ($headerList as $header) + foreach ($headerList as $header) { header_remove($header); + } } } diff --git a/app/Http/Middleware/TrimStrings.php b/app/Http/Middleware/TrimStrings.php new file mode 100644 index 0000000000..a8a252df4c --- /dev/null +++ b/app/Http/Middleware/TrimStrings.php @@ -0,0 +1,19 @@ +allSubdomainsOfApplicationUrl(), + ]; + } +} diff --git a/app/Http/Middleware/TrustProxies.php b/app/Http/Middleware/TrustProxies.php new file mode 100644 index 0000000000..a3b6aef90b --- /dev/null +++ b/app/Http/Middleware/TrustProxies.php @@ -0,0 +1,23 @@ + 'required_without_all:assigned_asset,assigned_location', - "assigned_asset" => 'required_without_all:assigned_user,assigned_location', - "assigned_location" => 'required_without_all:assigned_user,assigned_asset', - "checkout_to_type" => 'required|in:asset,location,user' + 'assigned_user' => 'required_without_all:assigned_asset,assigned_location', + 'assigned_asset' => 'required_without_all:assigned_user,assigned_location', + 'assigned_location' => 'required_without_all:assigned_user,assigned_asset', + 'checkout_to_type' => 'required|in:asset,location,user', ]; - return $rules; } } diff --git a/app/Http/Requests/AssetFileRequest.php b/app/Http/Requests/AssetFileRequest.php index de012afeb1..f8631f23ba 100644 --- a/app/Http/Requests/AssetFileRequest.php +++ b/app/Http/Requests/AssetFileRequest.php @@ -2,7 +2,6 @@ namespace App\Http\Requests; - class AssetFileRequest extends Request { /** @@ -23,6 +22,7 @@ class AssetFileRequest extends Request public function rules() { $max_file_size = \App\Helpers\Helper::file_upload_max_size(); + return [ 'file.*' => 'required|mimes:png,gif,jpg,svg,jpeg,doc,docx,pdf,txt,zip,rar,xls,xlsx,lic,xml,rtf,webp|max:'.$max_file_size, ]; diff --git a/app/Http/Requests/CustomFieldRequest.php b/app/Http/Requests/CustomFieldRequest.php index cc7749f27f..7c6ba1e97e 100644 --- a/app/Http/Requests/CustomFieldRequest.php +++ b/app/Http/Requests/CustomFieldRequest.php @@ -24,28 +24,26 @@ class CustomFieldRequest extends FormRequest */ public function rules(Request $request) { - $rules = []; - switch($this->method()) - { + switch ($this->method()) { // Brand new case 'POST': { - $rules['name'] = "required|unique:custom_fields"; + $rules['name'] = 'required|unique:custom_fields'; break; } // Save all fields case 'PUT': - $rules['name'] = "required"; + $rules['name'] = 'required'; break; // Save only what's passed case 'PATCH': { - $rules['name'] = "required"; + $rules['name'] = 'required'; break; } diff --git a/app/Http/Requests/ImageUploadRequest.php b/app/Http/Requests/ImageUploadRequest.php index 0ed4561ae6..c492011110 100644 --- a/app/Http/Requests/ImageUploadRequest.php +++ b/app/Http/Requests/ImageUploadRequest.php @@ -3,8 +3,8 @@ namespace App\Http\Requests; use App\Models\SnipeModel; -use Intervention\Image\Facades\Image; use enshrined\svgSanitize\Sanitizer; +use Intervention\Image\Facades\Image; use App\Http\Traits\ConvertsBase64ToFiles; use Illuminate\Http\UploadedFile; use Storage; @@ -60,23 +60,22 @@ class ImageUploadRequest extends Request /** * Handle and store any images attached to request * @param SnipeModel $item Item the image is associated with - * @param String $path location for uploaded images, defaults to uploads/plural of item type. + * @param string $path location for uploaded images, defaults to uploads/plural of item type. * @return SnipeModel Target asset is being checked out to. */ public function handleImages($item, $w = 600, $form_fieldname = null, $path = null, $db_fieldname = 'image') { - $type = strtolower(class_basename(get_class($item))); if (is_null($path)) { $path = str_plural($type); if ($type == 'assetmodel') { - $path = 'models'; + $path = 'models'; } if ($type == 'user') { - $path = 'avatars'; + $path = 'avatars'; } } @@ -91,7 +90,6 @@ class ImageUploadRequest extends Request $use_db_field = $db_fieldname; } - \Log::info('Image path is: '.$path); \Log::debug('Type is: '.$type); \Log::debug('Form fieldname is: '.$form_fieldname); @@ -117,9 +115,9 @@ class ImageUploadRequest extends Request $file_name = $type.'-'.$form_fieldname.'-'.str_random(10).'.'.$ext; \Log::info('File name will be: '.$file_name); - \Log::debug('File extension is: '. $ext); + \Log::debug('File extension is: '.$ext); - if (($image->getClientOriginalExtension()!=='webp') && ($image->getClientOriginalExtension()!=='svg')) { + if (($image->getClientOriginalExtension() !== 'webp') && ($image->getClientOriginalExtension() !== 'svg')) { \Log::debug('Not an SVG or webp - resize'); \Log::debug('Trying to upload to: '.$path.'/'.$file_name); $upload = Image::make($image->getRealPath())->resize(null, $w, function ($constraint) { @@ -128,17 +126,15 @@ class ImageUploadRequest extends Request }); // This requires a string instead of an object, so we use ($string) - Storage::disk('public')->put($path.'/'.$file_name, (string)$upload->encode()); - + Storage::disk('public')->put($path.'/'.$file_name, (string) $upload->encode()); } else { // If the file is a webp, we need to just move it since webp support // needs to be compiled into gd for resizing to be available - if ($image->getClientOriginalExtension()=='webp') { + if ($image->getClientOriginalExtension() == 'webp') { \Log::debug('This is a webp, just move it'); Storage::disk('public')->put($path.'/'.$file_name, file_get_contents($image)); // If the file is an SVG, we need to clean it and NOT encode it } else { - \Log::debug('This is an SVG'); $sanitizer = new Sanitizer(); $dirtySVG = file_get_contents($image->getRealPath()); @@ -154,43 +150,34 @@ class ImageUploadRequest extends Request } } - // Remove Current image if exists if (Storage::disk('public')->exists($path.'/'.$item->{$use_db_field})) { - \Log::debug('A file already exists that we are replacing - we should delete the old one.'); try { Storage::disk('public')->delete($path.'/'.$item->{$use_db_field}); \Log::debug('Old file '.$path.'/'.$file_name.' has been deleted.'); } catch (\Exception $e) { \Log::debug('Could not delete old file. '.$path.'/'.$file_name.' does not exist?'); - } } $item->{$use_db_field} = $file_name; - } // If the user isn't uploading anything new but wants to delete their old image, do so } else { \Log::debug('No file passed for '.$form_fieldname); - if ($this->input('image_delete')=='1') { - + if ($this->input('image_delete') == '1') { \Log::debug('Deleting image'); try { - - Storage::disk('public')->delete($path . '/' . $item->{$use_db_field}); + Storage::disk('public')->delete($path.'/'.$item->{$use_db_field}); $item->{$use_db_field} = null; - } catch (\Exception $e) { \Log::debug($e); } } - } - return $item; } diff --git a/app/Http/Requests/ItemImportRequest.php b/app/Http/Requests/ItemImportRequest.php index b9c12d3459..fbf36bf65f 100644 --- a/app/Http/Requests/ItemImportRequest.php +++ b/app/Http/Requests/ItemImportRequest.php @@ -34,30 +34,30 @@ class ItemImportRequest extends FormRequest { ini_set('max_execution_time', env('IMPORT_TIME_LIMIT', 600)); //600 seconds = 10 minutes ini_set('memory_limit', env('IMPORT_MEMORY_LIMIT', '500M')); - - $filename = config('app.private_uploads') . '/imports/' . $import->file_path; + + $filename = config('app.private_uploads').'/imports/'.$import->file_path; $import->import_type = $this->input('import-type'); $class = title_case($import->import_type); $classString = "App\\Importer\\{$class}Importer"; $importer = new $classString($filename); - $import->field_map = request('column-mappings'); + $import->field_map = request('column-mappings'); $import->save(); - $fieldMappings=[]; + $fieldMappings = []; if ($import->field_map) { foreach ($import->field_map as $field => $fieldValue) { $errorMessage = null; - if(is_null($fieldValue)){ + if (is_null($fieldValue)) { $errorMessage = trans('validation.import_field_empty'); $this->errorCallback($import, $field, $errorMessage); - + return $this->errors; } } // We submit as csv field: column, but the importer is happier if we flip it here. $fieldMappings = array_change_key_case(array_flip($import->field_map), CASE_LOWER); - // dd($fieldMappings); + // dd($fieldMappings); } $importer->setCallbacks([$this, 'log'], [$this, 'progress'], [$this, 'errorCallback']) ->setUserId(Auth::id()) @@ -68,19 +68,20 @@ class ItemImportRequest extends FormRequest // $logFile = storage_path('logs/importer.log'); // \Log::useFiles($logFile); $importer->import(); + return $this->errors; } public function log($string) { - \Log::Info($string); + \Log::Info($string); } public function progress($count) { // Open for future - return; } + public function errorCallback($item, $field, $errorString) { $this->errors[$item->name][$field] = $errorString; diff --git a/app/Http/Requests/Request.php b/app/Http/Requests/Request.php index 35bfcdee93..ff8f123b3d 100644 --- a/app/Http/Requests/Request.php +++ b/app/Http/Requests/Request.php @@ -1,6 +1,7 @@ ajax() || $this->wantsJson()) - { + if ($this->ajax() || $this->wantsJson()) { return Helper::formatStandardApiResponse('error', null, $errors); } diff --git a/app/Http/Requests/SaveUserRequest.php b/app/Http/Requests/SaveUserRequest.php index 3c706e854a..b6e44c3f44 100644 --- a/app/Http/Requests/SaveUserRequest.php +++ b/app/Http/Requests/SaveUserRequest.php @@ -3,9 +3,9 @@ namespace App\Http\Requests; use App\Models\Setting; -use Illuminate\Http\Exceptions\HttpResponseException; -use Illuminate\Foundation\Http\FormRequest; use Illuminate\Contracts\Validation\Validator; +use Illuminate\Foundation\Http\FormRequest; +use Illuminate\Http\Exceptions\HttpResponseException; class SaveUserRequest extends FormRequest { @@ -24,7 +24,6 @@ class SaveUserRequest extends FormRequest return $this->redirector->back()->withInput()->withErrors($errors, $this->errorBag); } - /** * Get the validation rules that apply to the request. * @@ -32,21 +31,18 @@ class SaveUserRequest extends FormRequest */ public function rules() { - $rules = [ - 'manager_id' => "nullable|exists:users,id" + 'manager_id' => 'nullable|exists:users,id', ]; - switch($this->method()) - { + switch ($this->method()) { // Brand new user case 'POST': { $rules['first_name'] = 'required|string|min:1'; $rules['username'] = 'required_unless:ldap_import,1|string|min:1'; - if ($this->request->get('ldap_import') == false) - { + if ($this->request->get('ldap_import') == false) { $rules['password'] = Setting::passwordComplexityRulesSaving('store').'|confirmed'; } break; @@ -68,9 +64,7 @@ class SaveUserRequest extends FormRequest default:break; } - + return $rules; - } - } diff --git a/app/Http/Requests/SettingsLdapRequest.php b/app/Http/Requests/SettingsLdapRequest.php index 33da10fd65..234903cba4 100644 --- a/app/Http/Requests/SettingsLdapRequest.php +++ b/app/Http/Requests/SettingsLdapRequest.php @@ -24,20 +24,19 @@ class SettingsLdapRequest extends Request public function rules() { $rules = [ - "ldap_server" => 'sometimes|required_if:ldap_enabled,1|url|nullable', - "ldap_uname" => 'sometimes|required_if:ldap_enabled,1|nullable', - "ldap_basedn" => 'sometimes|required_if:ldap_enabled,1|nullable', - "ldap_filter" => 'sometimes|required_if:ldap_enabled,1|nullable', - "ldap_username_field" => 'sometimes|required_if:ldap_enabled,1|nullable', - "ldap_fname_field" => 'sometimes|required_if:ldap_enabled,1|nullable', - "ldap_lname_field" => 'sometimes|required_if:ldap_enabled,1|nullable', - "ldap_auth_filter_query" => 'sometimes|required_if:ldap_enabled,1|nullable', - "ldap_version" => 'sometimes|required_if:ldap_enabled,1|nullable', - "ad_domain" => 'sometimes|required_if:is_ad,1|nullable', + 'ldap_server' => 'sometimes|required_if:ldap_enabled,1|url|nullable', + 'ldap_uname' => 'sometimes|required_if:ldap_enabled,1|nullable', + 'ldap_basedn' => 'sometimes|required_if:ldap_enabled,1|nullable', + 'ldap_filter' => 'sometimes|required_if:ldap_enabled,1|nullable', + 'ldap_username_field' => 'sometimes|required_if:ldap_enabled,1|nullable', + 'ldap_fname_field' => 'sometimes|required_if:ldap_enabled,1|nullable', + 'ldap_lname_field' => 'sometimes|required_if:ldap_enabled,1|nullable', + 'ldap_auth_filter_query' => 'sometimes|required_if:ldap_enabled,1|nullable', + 'ldap_version' => 'sometimes|required_if:ldap_enabled,1|nullable', + 'ad_domain' => 'sometimes|required_if:is_ad,1|nullable', ]; return $rules; - } public function response(array $errors) @@ -45,6 +44,7 @@ class SettingsLdapRequest extends Request $this->session()->flash('errors', Session::get('errors', new \Illuminate\Support\ViewErrorBag) ->put('default', new \Illuminate\Support\MessageBag($errors))); \Input::flash(); + return parent::response($errors); } } diff --git a/app/Http/Requests/SettingsSamlRequest.php b/app/Http/Requests/SettingsSamlRequest.php index 74cdaf39da..8f02d64f03 100644 --- a/app/Http/Requests/SettingsSamlRequest.php +++ b/app/Http/Requests/SettingsSamlRequest.php @@ -2,10 +2,10 @@ namespace App\Http\Requests; +use App\Models\Setting; use Illuminate\Foundation\Http\FormRequest; use OneLogin\Saml2\IdPMetadataParser as OneLogin_Saml2_IdPMetadataParser; use OneLogin\Saml2\Utils as OneLogin_Saml2_Utils; -use App\Models\Setting; /** * This handles validating and cleaning SAML settings provided by the user. @@ -42,9 +42,8 @@ class SettingsSamlRequest extends FormRequest { $validator->after(function ($validator) { if ($this->input('saml_enabled') == '1') { - $idpMetadata = $this->input('saml_idp_metadata'); - if (!empty($idpMetadata)) { + if (! empty($idpMetadata)) { try { if (filter_var($idpMetadata, FILTER_VALIDATE_URL)) { $metadataInfo = OneLogin_Saml2_IdPMetadataParser::parseRemoteXML($idpMetadata); @@ -59,21 +58,21 @@ class SettingsSamlRequest extends FormRequest $was_custom_x509cert = strpos(Setting::getSettings()->saml_custom_settings, 'sp_x509cert') !== false; - $custom_x509cert=''; - $custom_privateKey=''; - $custom_x509certNew=''; - if (!empty($this->input('saml_custom_settings'))) { + $custom_x509cert = ''; + $custom_privateKey = ''; + $custom_x509certNew = ''; + if (! empty($this->input('saml_custom_settings'))) { $req_custom_settings = preg_split('/\r\n|\r|\n/', $this->input('saml_custom_settings')); $custom_settings = []; - + foreach ($req_custom_settings as $custom_setting) { $split = explode('=', $custom_setting, 2); - + if (count($split) == 2) { $split[0] = trim($split[0]); $split[1] = trim($split[1]); - - if (!empty($split[0])) { + + if (! empty($split[0])) { $custom_settings[] = implode('=', $split); } if ($split[0] == 'sp_x509cert') { @@ -86,37 +85,36 @@ class SettingsSamlRequest extends FormRequest } } } - - $this->merge(['saml_custom_settings' => implode(PHP_EOL, $custom_settings) . PHP_EOL]); + + $this->merge(['saml_custom_settings' => implode(PHP_EOL, $custom_settings).PHP_EOL]); } - $cert_updated=false; - if (!empty($custom_x509cert) && !empty($custom_privateKey)) { + $cert_updated = false; + if (! empty($custom_x509cert) && ! empty($custom_privateKey)) { // custom certificate and private key are defined - $cert_updated=true; + $cert_updated = true; $x509 = openssl_x509_read($custom_x509cert); $pkey = openssl_pkey_get_private($custom_privateKey); - } elseif ($this->input('saml_sp_regenerate_keypair') == '1' || !$this->has('saml_sp_x509cert') || $was_custom_x509cert) { + } elseif ($this->input('saml_sp_regenerate_keypair') == '1' || ! $this->has('saml_sp_x509cert') || $was_custom_x509cert) { // key regeneration requested, no certificate defined yet or previous custom certicate was removed -error_log("regen"); - $cert_updated=true; + error_log('regen'); + $cert_updated = true; $dn = [ - "countryName" => "US", - "stateOrProvinceName" => "N/A", - "localityName" => "N/A", - "organizationName" => "Snipe-IT", - "commonName" => "Snipe-IT", + 'countryName' => 'US', + 'stateOrProvinceName' => 'N/A', + 'localityName' => 'N/A', + 'organizationName' => 'Snipe-IT', + 'commonName' => 'Snipe-IT', ]; $pkey = openssl_pkey_new([ - "private_key_bits" => 2048, - "private_key_type" => OPENSSL_KEYTYPE_RSA, + 'private_key_bits' => 2048, + 'private_key_type' => OPENSSL_KEYTYPE_RSA, ]); - + $csr = openssl_csr_new($dn, $pkey, ['digest_alg' => 'sha256']); if ($csr) { - $x509 = openssl_csr_sign($csr, null, $pkey, 3650, ['digest_alg' => 'sha256']); openssl_x509_export($x509, $x509cert); @@ -126,8 +124,8 @@ error_log("regen"); while (($error = openssl_error_string() !== false)) { $errors[] = $error; } - - if (!(empty($x509cert) && empty($privateKey))) { + + if (! (empty($x509cert) && empty($privateKey))) { $this->merge([ 'saml_sp_x509cert' => $x509cert, 'saml_sp_privatekey' => $privateKey, @@ -146,14 +144,14 @@ error_log("regen"); $errors[] = $error; } - if (!empty($x509certNew)) { + if (! empty($x509certNew)) { $this->merge([ - 'saml_sp_x509certNew' => $x509certNew + 'saml_sp_x509certNew' => $x509certNew, ]); } } else { $this->merge([ - 'saml_sp_x509certNew' => "" + 'saml_sp_x509certNew' => '', ]); } }); diff --git a/app/Http/Traits/UniqueUndeletedTrait.php b/app/Http/Traits/UniqueUndeletedTrait.php index 63a3740b54..d4c726bd73 100644 --- a/app/Http/Traits/UniqueUndeletedTrait.php +++ b/app/Http/Traits/UniqueUndeletedTrait.php @@ -1,21 +1,21 @@ exists) { - return 'unique_undeleted:'.$this->table.','. $this->getKey(); + return 'unique_undeleted:'.$this->table.','.$this->getKey(); } return 'unique_undeleted:'.$this->table.',0'; diff --git a/app/Http/Transformers/AccessoriesTransformer.php b/app/Http/Transformers/AccessoriesTransformer.php index d40642d875..d8858f91b8 100644 --- a/app/Http/Transformers/AccessoriesTransformer.php +++ b/app/Http/Transformers/AccessoriesTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } - public function transformAccessory (Accessory $accessory) + public function transformAccessory(Accessory $accessory) { $array = [ 'id' => $accessory->id, 'name' => e($accessory->name), 'image' => ($accessory->image) ? Storage::disk('public')->url('accessories/'.e($accessory->image)) : null, - 'company' => ($accessory->company) ? ['id' => $accessory->company->id,'name'=> e($accessory->company->name)] : null, - 'manufacturer' => ($accessory->manufacturer) ? ['id' => $accessory->manufacturer->id,'name'=> e($accessory->manufacturer->name)] : null, - 'supplier' => ($accessory->supplier) ? ['id' => $accessory->supplier->id,'name'=> e($accessory->supplier->name)] : null, + 'company' => ($accessory->company) ? ['id' => $accessory->company->id, 'name'=> e($accessory->company->name)] : null, + 'manufacturer' => ($accessory->manufacturer) ? ['id' => $accessory->manufacturer->id, 'name'=> e($accessory->manufacturer->name)] : null, + 'supplier' => ($accessory->supplier) ? ['id' => $accessory->supplier->id, 'name'=> e($accessory->supplier->name)] : null, 'model_number' => ($accessory->model_number) ? e($accessory->model_number) : null, - 'category' => ($accessory->category) ? ['id' => $accessory->category->id,'name'=> e($accessory->category->name)] : null, - 'location' => ($accessory->location) ? ['id' => $accessory->location->id,'name'=> e($accessory->location->name)] : null, + 'category' => ($accessory->category) ? ['id' => $accessory->category->id, 'name'=> e($accessory->category->name)] : null, + 'location' => ($accessory->location) ? ['id' => $accessory->location->id, 'name'=> e($accessory->location->name)] : null, 'notes' => ($accessory->notes) ? e($accessory->notes) : null, 'qty' => ($accessory->qty) ? (int) $accessory->qty : null, 'purchase_date' => ($accessory->purchase_date) ? Helper::getFormattedDateObject($accessory->purchase_date, 'date') : null, @@ -47,7 +48,7 @@ class AccessoriesTransformer $permissions_array['available_actions'] = [ 'checkout' => Gate::allows('checkout', Accessory::class), 'checkin' => false, - 'update' => Gate::allows('update', Accessory::class) , + 'update' => Gate::allows('update', Accessory::class), 'delete' => Gate::allows('delete', Accessory::class), ]; @@ -62,13 +63,9 @@ class AccessoriesTransformer return $array; } - - public function transformCheckedoutAccessory ($accessory, $accessory_users, $total) + public function transformCheckedoutAccessory($accessory, $accessory_users, $total) { - - - $array = array(); - + $array = []; foreach ($accessory_users as $user) { \Log::debug(print_r($user->pivot, true)); @@ -85,14 +82,10 @@ class AccessoriesTransformer 'checkout_notes' => $user->pivot->note, 'last_checkout' => Helper::getFormattedDateObject($user->pivot->created_at, 'datetime'), 'type' => 'user', - 'available_actions' => ['checkin' => true] + 'available_actions' => ['checkin' => true], ]; - } return (new DatatablesTransformer)->transformDatatables($array, $total); } - - - } diff --git a/app/Http/Transformers/ActionlogsTransformer.php b/app/Http/Transformers/ActionlogsTransformer.php index 9618624ae0..8b8a260eb2 100644 --- a/app/Http/Transformers/ActionlogsTransformer.php +++ b/app/Http/Transformers/ActionlogsTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } - public function transformActionlog (Actionlog $actionlog, $settings = null) + public function transformActionlog(Actionlog $actionlog, $settings = null) { $icon = $actionlog->present()->icon(); - if ($actionlog->filename!='') { - $icon = e(\App\Helpers\Helper::filetype_icon($actionlog->filename)); + if ($actionlog->filename != '') { + $icon = e(\App\Helpers\Helper::filetype_icon($actionlog->filename)); } // This is necessary since we can't escape special characters within a JSON object - if (($actionlog->log_meta) && ($actionlog->log_meta!='')) { + if (($actionlog->log_meta) && ($actionlog->log_meta != '')) { $meta_array = json_decode($actionlog->log_meta); if ($meta_array) { foreach ($meta_array as $key => $value) { foreach ($value as $meta_key => $meta_value) { - if (is_array($meta_value)) { foreach ($meta_value as $meta_value_key => $meta_value_value) { $clean_meta[$key][$meta_value_key] = e($meta_value_value); @@ -50,9 +50,7 @@ class ActionlogsTransformer // so we have to walk down that next level if (is_object($meta_value)) { - foreach ($meta_value as $meta_value_key => $meta_value_value) { - if ($meta_value_key == 'value') { $clean_meta[$key]['old'] = null; $clean_meta[$key]['new'] = e($meta_value->value); @@ -61,25 +59,19 @@ class ActionlogsTransformer $clean_meta[$meta_value_key]['new'] = e($meta_value_value); } } - - - } else { $clean_meta[$key][$meta_key] = e($meta_value); } } - } } - } } - $array = [ 'id' => (int) $actionlog->id, 'icon' => $icon, - 'file' => ($actionlog->filename!='') ? + 'file' => ($actionlog->filename != '') ? [ 'url' => route('show/assetfile', ['assetId' => $actionlog->item->id, 'fileId' => $actionlog->id]), 'filename' => $actionlog->filename, @@ -88,27 +80,27 @@ class ActionlogsTransformer 'item' => ($actionlog->item) ? [ 'id' => (int) $actionlog->item->id, - 'name' => ($actionlog->itemType()=='user') ? $actionlog->filename : e($actionlog->item->getDisplayNameAttribute()), + 'name' => ($actionlog->itemType() == 'user') ? $actionlog->filename : e($actionlog->item->getDisplayNameAttribute()), 'type' => e($actionlog->itemType()), ] : null, 'location' => ($actionlog->location) ? [ 'id' => (int) $actionlog->location->id, - 'name' => e($actionlog->location->name) + 'name' => e($actionlog->location->name), ] : null, 'created_at' => Helper::getFormattedDateObject($actionlog->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($actionlog->updated_at, 'datetime'), - 'next_audit_date' => ($actionlog->itemType()=='asset') ? Helper::getFormattedDateObject($actionlog->calcNextAuditDate(null, $actionlog->item), 'date'): null, + 'next_audit_date' => ($actionlog->itemType() == 'asset') ? Helper::getFormattedDateObject($actionlog->calcNextAuditDate(null, $actionlog->item), 'date') : null, 'days_to_next_audit' => $actionlog->daysUntilNextAudit($settings->audit_interval, $actionlog->item), 'action_type' => $actionlog->present()->actionType(), 'admin' => ($actionlog->user) ? [ 'id' => (int) $actionlog->user->id, 'name' => e($actionlog->user->getFullNameAttribute()), 'first_name'=> e($actionlog->user->first_name), - 'last_name'=> e($actionlog->user->last_name) + 'last_name'=> e($actionlog->user->last_name), ] : null, 'target' => ($actionlog->target) ? [ 'id' => (int) $actionlog->target->id, - 'name' => ($actionlog->targetType()=='user') ? e($actionlog->target->getFullNameAttribute()) : e($actionlog->target->getDisplayNameAttribute()), + 'name' => ($actionlog->targetType() == 'user') ? e($actionlog->target->getFullNameAttribute()) : e($actionlog->target->getDisplayNameAttribute()), 'type' => e($actionlog->targetType()), ] : null, @@ -122,18 +114,13 @@ class ActionlogsTransformer return $array; } - - - public function transformCheckedoutActionlog (Collection $accessories_users, $total) + public function transformCheckedoutActionlog(Collection $accessories_users, $total) { - - $array = array(); + $array = []; foreach ($accessories_users as $user) { $array[] = (new UsersTransformer)->transformUser($user); } + return (new DatatablesTransformer)->transformDatatables($array, $total); } - - - } diff --git a/app/Http/Transformers/AssetMaintenancesTransformer.php b/app/Http/Transformers/AssetMaintenancesTransformer.php index 49c1b38b65..72ec786f68 100644 --- a/app/Http/Transformers/AssetMaintenancesTransformer.php +++ b/app/Http/Transformers/AssetMaintenancesTransformer.php @@ -1,57 +1,58 @@ transformDatatables($array, $total); } - public function transformAssetMaintenance (AssetMaintenance $assetmaintenance) + public function transformAssetMaintenance(AssetMaintenance $assetmaintenance) { $array = [ 'id' => (int) $assetmaintenance->id, 'asset' => ($assetmaintenance->asset) ? [ 'id' => (int) $assetmaintenance->asset->id, 'name'=> ($assetmaintenance->asset->name) ? e($assetmaintenance->asset->name) : null, - 'asset_tag'=> e($assetmaintenance->asset->asset_tag) + 'asset_tag'=> e($assetmaintenance->asset->asset_tag), - ] : null, + ] : null, 'model' => (($assetmaintenance->asset) && ($assetmaintenance->asset->model)) ? [ 'id' => (int) $assetmaintenance->asset->model->id, - 'name'=> ($assetmaintenance->asset->model->name) ? e($assetmaintenance->asset->model->name).' '.e($assetmaintenance->asset->model->model_number) : null - ] : null, + 'name'=> ($assetmaintenance->asset->model->name) ? e($assetmaintenance->asset->model->name).' '.e($assetmaintenance->asset->model->model_number) : null, + ] : null, 'company' => (($assetmaintenance->asset) && ($assetmaintenance->asset->company)) ? [ 'id' => (int) $assetmaintenance->asset->company->id, 'name'=> ($assetmaintenance->asset->company->name) ? e($assetmaintenance->asset->company->name) : null, - ] : null, + ] : null, 'title' => ($assetmaintenance->title) ? e($assetmaintenance->title) : null, 'location' => (($assetmaintenance->asset) && ($assetmaintenance->asset->location)) ? [ 'id' => (int) $assetmaintenance->asset->location->id, 'name'=> e($assetmaintenance->asset->location->name), - ] : null, + ] : null, 'notes' => ($assetmaintenance->notes) ? e($assetmaintenance->notes) : null, - 'supplier' => ($assetmaintenance->supplier) ? ['id' => $assetmaintenance->supplier->id,'name'=> e($assetmaintenance->supplier->name)] : null, + 'supplier' => ($assetmaintenance->supplier) ? ['id' => $assetmaintenance->supplier->id, 'name'=> e($assetmaintenance->supplier->name)] : null, 'cost' => Helper::formatCurrencyOutput($assetmaintenance->cost), 'asset_maintenance_type' => e($assetmaintenance->asset_maintenance_type), 'start_date' => Helper::getFormattedDateObject($assetmaintenance->start_date, 'date'), 'asset_maintenance_time' => $assetmaintenance->asset_maintenance_time, 'completion_date' => Helper::getFormattedDateObject($assetmaintenance->completion_date, 'date'), - 'user_id' => ($assetmaintenance->admin) ? ['id' => $assetmaintenance->admin->id,'name'=> e($assetmaintenance->admin->getFullNameAttribute())] : null, + 'user_id' => ($assetmaintenance->admin) ? ['id' => $assetmaintenance->admin->id, 'name'=> e($assetmaintenance->admin->getFullNameAttribute())] : null, 'created_at' => Helper::getFormattedDateObject($assetmaintenance->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($assetmaintenance->updated_at, 'datetime'), @@ -66,9 +67,4 @@ class AssetMaintenancesTransformer return $array; } - - - - - } diff --git a/app/Http/Transformers/AssetModelsTransformer.php b/app/Http/Transformers/AssetModelsTransformer.php index 3f561b7b9f..528df3b146 100644 --- a/app/Http/Transformers/AssetModelsTransformer.php +++ b/app/Http/Transformers/AssetModelsTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } - public function transformAssetModel (AssetModel $assetmodel) + public function transformAssetModel(AssetModel $assetmodel) { - $array = [ 'id' => (int) $assetmodel->id, 'name' => e($assetmodel->name), 'manufacturer' => ($assetmodel->manufacturer) ? [ 'id' => (int) $assetmodel->manufacturer->id, - 'name'=> e($assetmodel->manufacturer->name) - ] : null, - 'image' => ($assetmodel->image!='') ? Storage::disk('public')->url('models/'.e($assetmodel->image)) : null, + 'name'=> e($assetmodel->manufacturer->name), + ] : null, + 'image' => ($assetmodel->image != '') ? Storage::disk('public')->url('models/'.e($assetmodel->image)) : null, 'model_number' => e($assetmodel->model_number), 'depreciation' => ($assetmodel->depreciation) ? [ 'id' => (int) $assetmodel->depreciation->id, - 'name'=> e($assetmodel->depreciation->name) - ] : null, + 'name'=> e($assetmodel->depreciation->name), + ] : null, 'assets_count' => (int) $assetmodel->assets_count, 'category' => ($assetmodel->category) ? [ 'id' => (int) $assetmodel->category->id, - 'name'=> e($assetmodel->category->name) - ] : null, + 'name'=> e($assetmodel->category->name), + ] : null, 'fieldset' => ($assetmodel->fieldset) ? [ 'id' => (int) $assetmodel->fieldset->id, - 'name'=> e($assetmodel->fieldset->name) - ] : null, - 'eol' => ($assetmodel->eol > 0) ? $assetmodel->eol .' months': 'None', - 'requestable' => ($assetmodel->requestable =='1') ? true : false, + 'name'=> e($assetmodel->fieldset->name), + ] : null, + 'eol' => ($assetmodel->eol > 0) ? $assetmodel->eol.' months' : 'None', + 'requestable' => ($assetmodel->requestable == '1') ? true : false, 'notes' => e($assetmodel->notes), 'created_at' => Helper::getFormattedDateObject($assetmodel->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($assetmodel->updated_at, 'datetime'), @@ -54,20 +54,19 @@ class AssetModelsTransformer ]; $permissions_array['available_actions'] = [ - 'update' => (Gate::allows('update', AssetModel::class) && ($assetmodel->deleted_at=='')), - 'delete' => (Gate::allows('delete', AssetModel::class) && ($assetmodel->assets_count==0)), - 'clone' => (Gate::allows('create', AssetModel::class) && ($assetmodel->deleted_at=='')), - 'restore' => (Gate::allows('create', AssetModel::class) && ($assetmodel->deleted_at!='')), + 'update' => (Gate::allows('update', AssetModel::class) && ($assetmodel->deleted_at == '')), + 'delete' => (Gate::allows('delete', AssetModel::class) && ($assetmodel->assets_count == 0)), + 'clone' => (Gate::allows('create', AssetModel::class) && ($assetmodel->deleted_at == '')), + 'restore' => (Gate::allows('create', AssetModel::class) && ($assetmodel->deleted_at != '')), ]; $array += $permissions_array; + return $array; } - - public function transformAssetModelsDatatable($assetmodels) { + public function transformAssetModelsDatatable($assetmodels) + { return (new DatatablesTransformer)->transformDatatables($assetmodels); } - - } diff --git a/app/Http/Transformers/AssetsTransformer.php b/app/Http/Transformers/AssetsTransformer.php index 400a5dd111..1936764464 100644 --- a/app/Http/Transformers/AssetsTransformer.php +++ b/app/Http/Transformers/AssetsTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } - public function transformAsset(Asset $asset) { $array = [ @@ -27,10 +28,10 @@ class AssetsTransformer 'serial' => e($asset->serial), 'model' => ($asset->model) ? [ 'id' => (int) $asset->model->id, - 'name'=> e($asset->model->name) + 'name'=> e($asset->model->name), ] : null, 'model_number' => (($asset->model) && ($asset->model->model_number)) ? e($asset->model->model_number) : null, - 'eol' => ($asset->purchase_date!='') ? Helper::getFormattedDateObject($asset->present()->eol_date(), 'date') : null , + 'eol' => ($asset->purchase_date != '') ? Helper::getFormattedDateObject($asset->present()->eol_date(), 'date') : null, 'status_label' => ($asset->assetstatus) ? [ 'id' => (int) $asset->assetstatus->id, 'name'=> e($asset->assetstatus->name), @@ -39,34 +40,34 @@ class AssetsTransformer ] : null, 'category' => (($asset->model) && ($asset->model->category)) ? [ 'id' => (int) $asset->model->category->id, - 'name'=> e($asset->model->category->name) - ] : null, + 'name'=> e($asset->model->category->name), + ] : null, 'manufacturer' => (($asset->model) && ($asset->model->manufacturer)) ? [ 'id' => (int) $asset->model->manufacturer->id, - 'name'=> e($asset->model->manufacturer->name) + 'name'=> e($asset->model->manufacturer->name), ] : null, 'supplier' => ($asset->supplier) ? [ 'id' => (int) $asset->supplier->id, - 'name'=> e($asset->supplier->name) - ] : null, + 'name'=> e($asset->supplier->name), + ] : null, 'notes' => ($asset->notes) ? e($asset->notes) : null, 'order_number' => ($asset->order_number) ? e($asset->order_number) : null, 'company' => ($asset->company) ? [ 'id' => (int) $asset->company->id, - 'name'=> e($asset->company->name) + 'name'=> e($asset->company->name), ] : null, 'location' => ($asset->location) ? [ 'id' => (int) $asset->location->id, - 'name'=> e($asset->location->name) - ] : null, + 'name'=> e($asset->location->name), + ] : null, 'rtd_location' => ($asset->defaultLoc) ? [ 'id' => (int) $asset->defaultLoc->id, - 'name'=> e($asset->defaultLoc->name) - ] : null, + 'name'=> e($asset->defaultLoc->name), + ] : null, 'image' => ($asset->getImageUrl()) ? $asset->getImageUrl() : null, 'assigned_to' => $this->transformAssignedTo($asset), - 'warranty_months' => ($asset->warranty_months > 0) ? e($asset->warranty_months . ' ' . trans('admin/hardware/form.months')) : null, - 'warranty_expires' => ($asset->warranty_months > 0) ? Helper::getFormattedDateObject($asset->warranty_expires, 'date') : null, + 'warranty_months' => ($asset->warranty_months > 0) ? e($asset->warranty_months.' '.trans('admin/hardware/form.months')) : null, + 'warranty_expires' => ($asset->warranty_months > 0) ? Helper::getFormattedDateObject($asset->warranty_expires, 'date') : null, 'created_at' => Helper::getFormattedDateObject($asset->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($asset->updated_at, 'datetime'), 'last_audit_date' => Helper::getFormattedDateObject($asset->last_audit_date, 'datetime'), @@ -82,14 +83,12 @@ class AssetsTransformer 'user_can_checkout' => (bool) $asset->availableForCheckout(), ]; - if (($asset->model) && ($asset->model->fieldset) && ($asset->model->fieldset->fields->count() > 0)) { - $fields_array = array(); + $fields_array = []; foreach ($asset->model->fieldset->fields as $field) { - if ($field->isFieldDecryptable($asset->{$field->convertUnicodeDbSlug()})) { - $decrypted = \App\Helpers\Helper::gracefulDecrypt($field,$asset->{$field->convertUnicodeDbSlug()}); + $decrypted = \App\Helpers\Helper::gracefulDecrypt($field, $asset->{$field->convertUnicodeDbSlug()}); $value = (Gate::allows('superadmin')) ? $decrypted : strtoupper(trans('admin/custom_fields/general.encrypted')); $fields_array[$field->name] = [ @@ -97,20 +96,17 @@ class AssetsTransformer 'value' => $value, 'field_format' => $field->format, ]; - } else { $fields_array[$field->name] = [ 'field' => $field->convertUnicodeDbSlug(), 'value' => $asset->{$field->convertUnicodeDbSlug()}, 'field_format' => $field->format, ]; - - } $array['custom_fields'] = $fields_array; } } else { - $array['custom_fields'] = array(); + $array['custom_fields'] = []; } $permissions_array['available_actions'] = [ @@ -119,10 +115,10 @@ class AssetsTransformer 'clone' => Gate::allows('create', Asset::class), 'restore' => false, 'update' => (bool) Gate::allows('update', Asset::class), - 'delete' => ($asset->assigned_to=='' && Gate::allows('delete', Asset::class)), + 'delete' => ($asset->assigned_to == '' && Gate::allows('delete', Asset::class)), ]; - if ($asset->deleted_at!='') { + if ($asset->deleted_at != '') { $permissions_array['available_actions'] = [ 'checkout' => true, 'checkin' => false, @@ -133,8 +129,8 @@ class AssetsTransformer ]; } - $array += $permissions_array; + return $array; } @@ -153,27 +149,29 @@ class AssetsTransformer 'first_name'=> e($asset->assigned->first_name), 'last_name'=> ($asset->assigned->last_name) ? e($asset->assigned->last_name) : null, 'employee_number' => ($asset->assigned->employee_num) ? e($asset->assigned->employee_num) : null, - 'type' => 'user' + 'type' => 'user', ] : null; } + return $asset->assigned ? [ 'id' => $asset->assigned->id, 'name' => $asset->assigned->display_name, - 'type' => $asset->assignedType() + 'type' => $asset->assignedType(), ] : null; } - public function transformRequestedAssets(Collection $assets, $total) { - $array = array(); + $array = []; foreach ($assets as $asset) { $array[] = self::transformRequestedAsset($asset); } + return (new DatatablesTransformer)->transformDatatables($array, $total); } - public function transformRequestedAsset(Asset $asset) { + public function transformRequestedAsset(Asset $asset) + { $array = [ 'id' => (int) $asset->id, 'name' => e($asset->name), @@ -193,8 +191,8 @@ class AssetsTransformer ]; - $array += $permissions_array; - return $array; + $array += $permissions_array; + return $array; } } diff --git a/app/Http/Transformers/CategoriesTransformer.php b/app/Http/Transformers/CategoriesTransformer.php index 0ecdb923d6..427cfaa299 100644 --- a/app/Http/Transformers/CategoriesTransformer.php +++ b/app/Http/Transformers/CategoriesTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } - public function transformCategory (Category $category = null) + public function transformCategory(Category $category = null) { if ($category) { - $array = [ 'id' => (int) $category->id, 'name' => e($category->name), @@ -31,7 +31,7 @@ class CategoriesTransformer 'has_eula' => ($category->getEula() ? true : false), 'use_default_eula' => ($category->use_default_eula=='1' ? true : false), 'eula' => ($category->getEula()), - 'checkin_email' => ($category->checkin_email =='1'), + 'checkin_email' => ($category->checkin_email == '1'), 'require_acceptance' => ($category->require_acceptance == '1'), 'item_count' => (int) $category->itemCount(), 'assets_count' => (int) $category->assets_count, @@ -52,10 +52,5 @@ class CategoriesTransformer return $array; } - - } - - - } diff --git a/app/Http/Transformers/CompaniesTransformer.php b/app/Http/Transformers/CompaniesTransformer.php index 4460b30c14..bafe1f9f68 100644 --- a/app/Http/Transformers/CompaniesTransformer.php +++ b/app/Http/Transformers/CompaniesTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } - public function transformCompany (Company $company = null) + public function transformCompany(Company $company = null) { if ($company) { - $array = [ 'id' => (int) $company->id, 'name' => e($company->name), 'image' => ($company->image) ? Storage::disk('public')->url('companies/'.e($company->image)) : null, - "created_at" => Helper::getFormattedDateObject($company->created_at, 'datetime'), - "updated_at" => Helper::getFormattedDateObject($company->updated_at, 'datetime'), - "assets_count" => (int) $company->assets_count, - "licenses_count" => (int) $company->licenses_count, - "accessories_count" => (int) $company->accessories_count, - "consumables_count" => (int) $company->consumables_count, - "components_count" => (int) $company->components_count, - "users_count" => (int) $company->users_count + 'created_at' => Helper::getFormattedDateObject($company->created_at, 'datetime'), + 'updated_at' => Helper::getFormattedDateObject($company->updated_at, 'datetime'), + 'assets_count' => (int) $company->assets_count, + 'licenses_count' => (int) $company->licenses_count, + 'accessories_count' => (int) $company->accessories_count, + 'consumables_count' => (int) $company->consumables_count, + 'components_count' => (int) $company->components_count, + 'users_count' => (int) $company->users_count, ]; $permissions_array['available_actions'] = [ 'update' => Gate::allows('update', Company::class), - 'delete' => $company->isDeletable() + 'delete' => $company->isDeletable(), ]; $array += $permissions_array; return $array; } - - } - - - } diff --git a/app/Http/Transformers/ComponentsAssetsTransformer.php b/app/Http/Transformers/ComponentsAssetsTransformer.php index 8ce3a8600d..1c288bfc9a 100644 --- a/app/Http/Transformers/ComponentsAssetsTransformer.php +++ b/app/Http/Transformers/ComponentsAssetsTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } - - public function transformAsset (Asset $asset) + public function transformAsset(Asset $asset) { $array = [ 'id' => $asset->id, @@ -34,8 +35,6 @@ class ComponentsAssetsTransformer 'delete' => Gate::allows('delete', Asset::class), ]; - - $array += $permissions_array; if ($asset->model->fieldset) { @@ -43,12 +42,13 @@ class ComponentsAssetsTransformer $fields_array = [$field->name => $asset->{$field->convertUnicodeDbSlug()}]; $array += $fields_array; } - } + } return $array; } - public function transformAssetsDatatable ($assets) { + public function transformAssetsDatatable($assets) + { return (new DatatablesTransformer)->transformDatatables($assets); } } diff --git a/app/Http/Transformers/ComponentsTransformer.php b/app/Http/Transformers/ComponentsTransformer.php index c27deb2a1f..c43c2d5bdc 100644 --- a/app/Http/Transformers/ComponentsTransformer.php +++ b/app/Http/Transformers/ComponentsTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } @@ -27,13 +29,13 @@ class ComponentsTransformer 'serial' => ($component->serial) ? e($component->serial) : null, 'location' => ($component->location) ? [ 'id' => (int) $component->location->id, - 'name' => e($component->location->name) + 'name' => e($component->location->name), ] : null, - 'qty' => ($component->qty!='') ? (int) $component->qty : null, - 'min_amt' => ($component->min_amt!='') ? (int) $component->min_amt : null, + 'qty' => ($component->qty != '') ? (int) $component->qty : null, + 'min_amt' => ($component->min_amt != '') ? (int) $component->min_amt : null, 'category' => ($component->category) ? [ 'id' => (int) $component->category->id, - 'name' => e($component->category->name) + 'name' => e($component->category->name), ] : null, 'order_number' => e($component->order_number), 'purchase_date' => Helper::getFormattedDateObject($component->purchase_date, 'date'), @@ -41,7 +43,7 @@ class ComponentsTransformer 'remaining' => (int) $component->numRemaining(), 'company' => ($component->company) ? [ 'id' => (int) $component->company->id, - 'name' => e($component->company->name) + 'name' => e($component->company->name), ] : null, 'created_at' => Helper::getFormattedDateObject($component->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($component->updated_at, 'datetime'), @@ -59,21 +61,19 @@ class ComponentsTransformer return $array; } - public function transformCheckedoutComponents(Collection $components_assets, $total) { - $array = array(); + $array = []; foreach ($components_assets as $asset) { $array[] = [ 'assigned_pivot_id' => $asset->pivot->id, 'id' => (int) $asset->id, - 'name' => e($asset->model->present()->name) .' '.e($asset->present()->name), + 'name' => e($asset->model->present()->name).' '.e($asset->present()->name), 'qty' => $asset->pivot->assigned_qty, 'type' => 'asset', 'created_at' => Helper::getFormattedDateObject($asset->pivot->created_at, 'datetime'), - 'available_actions' => ['checkin' => true] + 'available_actions' => ['checkin' => true], ]; - } return (new DatatablesTransformer)->transformDatatables($array, $total); diff --git a/app/Http/Transformers/ConsumablesTransformer.php b/app/Http/Transformers/ConsumablesTransformer.php index c82299de98..abc1fc42ee 100644 --- a/app/Http/Transformers/ConsumablesTransformer.php +++ b/app/Http/Transformers/ConsumablesTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } - public function transformConsumable (Consumable $consumable) + public function transformConsumable(Consumable $consumable) { $array = [ 'id' => (int) $consumable->id, @@ -31,7 +32,7 @@ class ConsumablesTransformer 'location' => ($consumable->location) ? ['id' => (int) $consumable->location->id, 'name' => e($consumable->location->name)] : null, 'manufacturer' => ($consumable->manufacturer) ? ['id' => (int) $consumable->manufacturer->id, 'name' => e($consumable->manufacturer->name)] : null, 'min_amt' => (int) $consumable->min_amt, - 'model_number' => ($consumable->model_number!='') ? e($consumable->model_number) : null, + 'model_number' => ($consumable->model_number != '') ? e($consumable->model_number) : null, 'remaining' => $consumable->numRemaining(), 'order_number' => e($consumable->order_number), 'purchase_cost' => Helper::formatCurrencyOutput($consumable->purchase_cost), @@ -54,20 +55,17 @@ class ConsumablesTransformer 'delete' => Gate::allows('delete', Consumable::class), ]; $array += $permissions_array; + return $array; } - - public function transformCheckedoutConsumables (Collection $consumables_users, $total) + public function transformCheckedoutConsumables(Collection $consumables_users, $total) { - - $array = array(); + $array = []; foreach ($consumables_users as $user) { $array[] = (new UsersTransformer)->transformUser($user); } + return (new DatatablesTransformer)->transformDatatables($array, $total); } - - - } diff --git a/app/Http/Transformers/CustomFieldsTransformer.php b/app/Http/Transformers/CustomFieldsTransformer.php index 1ef6904de8..81135de13c 100644 --- a/app/Http/Transformers/CustomFieldsTransformer.php +++ b/app/Http/Transformers/CustomFieldsTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } @@ -24,7 +25,7 @@ class CustomFieldsTransformer * @param int $total * @return array */ - public function transformCustomFieldsWithDefaultValues (Collection $fields, $modelId, $total) + public function transformCustomFieldsWithDefaultValues(Collection $fields, $modelId, $total) { $array = []; @@ -35,20 +36,21 @@ class CustomFieldsTransformer return (new DatatablesTransformer)->transformDatatables($array, $total); } - public function transformCustomField (CustomField $field) + public function transformCustomField(CustomField $field) { $array = [ 'id' => $field->id, 'name' => e($field->name), 'db_column_name' => e($field->db_column_name()), 'format' => e($field->format), - 'field_values' => ($field->field_values) ? e($field->field_values) : null, - 'field_values_array' => ($field->field_values) ? explode("\r\n", e($field->field_values)) : null, + 'field_values' => ($field->field_values) ? e($field->field_values) : null, + 'field_values_array' => ($field->field_values) ? explode("\r\n", e($field->field_values)) : null, 'type' => e($field->element), 'required' => $field->pivot ? $field->pivot->required : false, 'created_at' => Helper::getFormattedDateObject($field->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($field->updated_at, 'datetime'), ]; + return $array; } @@ -60,13 +62,13 @@ class CustomFieldsTransformer * @param int $modelId * @return array */ - public function transformCustomFieldWithDefaultValue (CustomField $field, $modelId) + public function transformCustomFieldWithDefaultValue(CustomField $field, $modelId) { return [ 'id' => $field->id, 'name' => e($field->name), 'type' => e($field->element), - 'field_values_array' => ($field->field_values) ? explode("\r\n", e($field->field_values)) : null, + 'field_values_array' => ($field->field_values) ? explode("\r\n", e($field->field_values)) : null, 'default_value' => $field->defaultValue($modelId), ]; } diff --git a/app/Http/Transformers/CustomFieldsetsTransformer.php b/app/Http/Transformers/CustomFieldsetsTransformer.php index 260164ef8c..61e42486ab 100644 --- a/app/Http/Transformers/CustomFieldsetsTransformer.php +++ b/app/Http/Transformers/CustomFieldsetsTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } - public function transformCustomFieldset (CustomFieldset $fieldset) + public function transformCustomFieldset(CustomFieldset $fieldset) { $fields = $fieldset->fields; $models = $fieldset->models; - $modelsArray = array(); + $modelsArray = []; - foreach ($models as $model) - { + foreach ($models as $model) { $modelsArray[] = [ 'id' => $model->id, - 'name' => e($model->name) + 'name' => e($model->name), ]; } @@ -39,6 +39,7 @@ class CustomFieldsetsTransformer 'created_at' => Helper::getFormattedDateObject($fieldset->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($fieldset->updated_at, 'datetime'), ]; + return $array; } } diff --git a/app/Http/Transformers/DatatablesTransformer.php b/app/Http/Transformers/DatatablesTransformer.php index 0fc90bec8c..0e69109391 100644 --- a/app/Http/Transformers/DatatablesTransformer.php +++ b/app/Http/Transformers/DatatablesTransformer.php @@ -1,13 +1,14 @@ transformDatatables($array, $total); } - public function transformDepartment (Department $department = null) + public function transformDepartment(Department $department = null) { if ($department) { - $array = [ 'id' => (int) $department->id, 'name' => e($department->name), 'image' => ($department->image) ? Storage::disk('public')->url(app('departments_upload_url').e($department->image)) : null, 'company' => ($department->company) ? [ 'id' => (int) $department->company->id, - 'name'=> e($department->company->name) + 'name'=> e($department->company->name), ] : null, 'manager' => ($department->manager) ? [ 'id' => (int) $department->manager->id, 'name' => e($department->manager->getFullNameAttribute()), 'first_name'=> e($department->manager->first_name), - 'last_name'=> e($department->manager->last_name) + 'last_name'=> e($department->manager->last_name), ] : null, 'location' => ($department->location) ? [ 'id' => (int) $department->location->id, - 'name' => e($department->location->name) + 'name' => e($department->location->name), ] : null, 'users_count' => e($department->users_count), 'created_at' => Helper::getFormattedDateObject($department->created_at, 'datetime'), @@ -48,17 +48,12 @@ class DepartmentsTransformer $permissions_array['available_actions'] = [ 'update' => Gate::allows('update', Department::class), - 'delete' => (Gate::allows('delete', Department::class) && ($department->users_count==0)), + 'delete' => (Gate::allows('delete', Department::class) && ($department->users_count == 0)), ]; $array += $permissions_array; return $array; } - - } - - - } diff --git a/app/Http/Transformers/DepreciationsTransformer.php b/app/Http/Transformers/DepreciationsTransformer.php index bd391adf6b..abfbf151c6 100644 --- a/app/Http/Transformers/DepreciationsTransformer.php +++ b/app/Http/Transformers/DepreciationsTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array); } - public function transformDepreciation (Depreciation $depreciation) + public function transformDepreciation(Depreciation $depreciation) { $array = [ 'id' => (int) $depreciation->id, 'name' => e($depreciation->name), - 'months' => $depreciation->months . ' '. trans('general.months'), + 'months' => $depreciation->months.' '.trans('general.months'), 'depreciation_min' => $depreciation->depreciation_min, 'created_at' => Helper::getFormattedDateObject($depreciation->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($depreciation->updated_at, 'datetime'), + 'depreciation_min' =>($depreciation->depreciation_min), ]; $permissions_array['available_actions'] = [ @@ -38,7 +40,4 @@ class DepreciationsTransformer return $array; } - - - } diff --git a/app/Http/Transformers/GroupsTransformer.php b/app/Http/Transformers/GroupsTransformer.php index 8f116aad76..93511ce9ff 100644 --- a/app/Http/Transformers/GroupsTransformer.php +++ b/app/Http/Transformers/GroupsTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array); } - public function transformGroup (Group $group) + public function transformGroup(Group $group) { $array = [ 'id' => (int) $group->id, @@ -38,7 +39,4 @@ class GroupsTransformer return $array; } - - - } diff --git a/app/Http/Transformers/ImportsTransformer.php b/app/Http/Transformers/ImportsTransformer.php index 813819c193..486c18f28c 100644 --- a/app/Http/Transformers/ImportsTransformer.php +++ b/app/Http/Transformers/ImportsTransformer.php @@ -1,4 +1,5 @@ (int) $import->id, + 'id' => (int) $import->id, 'file_path' => e($import->file_path), 'filesize' => Setting::fileSizeConvert($import->filesize), 'name' => e($import->name), diff --git a/app/Http/Transformers/LicenseSeatsTransformer.php b/app/Http/Transformers/LicenseSeatsTransformer.php index c8454d06e7..126361b17a 100644 --- a/app/Http/Transformers/LicenseSeatsTransformer.php +++ b/app/Http/Transformers/LicenseSeatsTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } - public function transformLicenseSeat (LicenseSeat $seat, $seat_count=0) + public function transformLicenseSeat(LicenseSeat $seat, $seat_count = 0) { $array = [ 'id' => (int) $seat->id, @@ -28,27 +29,26 @@ class LicenseSeatsTransformer 'assigned_user' => ($seat->user) ? [ 'id' => (int) $seat->user->id, 'name'=> e($seat->user->present()->fullName), - 'department'=> - ($seat->user->department) ? + 'department'=> ($seat->user->department) ? [ - "id" => (int) $seat->user->department->id, - "name" => e($seat->user->department->name) + 'id' => (int) $seat->user->department->id, + 'name' => e($seat->user->department->name), - ] : null + ] : null, ] : null, 'assigned_asset' => ($seat->asset) ? [ 'id' => (int) $seat->asset->id, - 'name'=> e($seat->asset->present()->fullName) + 'name'=> e($seat->asset->present()->fullName), ] : null, 'location' => ($seat->location()) ? [ 'id' => (int) $seat->location()->id, - 'name'=> e($seat->location()->name) + 'name'=> e($seat->location()->name), ] : null, 'reassignable' => (bool) $seat->license->reassignable, - 'user_can_checkout' => (($seat->assigned_to=='') && ($seat->asset_id=='')), + 'user_can_checkout' => (($seat->assigned_to == '') && ($seat->asset_id == '')), ]; - if($seat_count != 0) { + if ($seat_count != 0) { $array['name'] = 'Seat '.$seat_count; } @@ -64,9 +64,4 @@ class LicenseSeatsTransformer return $array; } - - - - - } diff --git a/app/Http/Transformers/LicensesTransformer.php b/app/Http/Transformers/LicensesTransformer.php index 48d5152688..51b193a76a 100644 --- a/app/Http/Transformers/LicensesTransformer.php +++ b/app/Http/Transformers/LicensesTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } - public function transformLicense (License $license) + public function transformLicense(License $license) { $array = [ 'id' => (int) $license->id, 'name' => e($license->name), - 'company' => ($license->company) ? ['id' => (int) $license->company->id,'name'=> e($license->company->name)] : null, - 'manufacturer' => ($license->manufacturer) ? ['id' => (int) $license->manufacturer->id,'name'=> e($license->manufacturer->name)] : null, + 'company' => ($license->company) ? ['id' => (int) $license->company->id, 'name'=> e($license->company->name)] : null, + 'manufacturer' => ($license->manufacturer) ? ['id' => (int) $license->manufacturer->id, 'name'=> e($license->manufacturer->name)] : null, 'product_key' => (Gate::allows('viewKeys', License::class)) ? e($license->serial) : '------------', 'order_number' => e($license->order_number), 'purchase_order' => e($license->purchase_order), 'purchase_date' => Helper::getFormattedDateObject($license->purchase_date, 'date'), 'termination_date' => Helper::getFormattedDateObject($license->termination_date, 'date'), - 'depreciation' => ($license->depreciation) ? ['id' => (int) $license->depreciation->id,'name'=> e($license->depreciation->name)] : null, + 'depreciation' => ($license->depreciation) ? ['id' => (int) $license->depreciation->id, 'name'=> e($license->depreciation->name)] : null, 'purchase_cost' => e($license->purchase_cost), 'notes' => e($license->notes), 'expiration_date' => Helper::getFormattedDateObject($license->expiration_date, 'date'), @@ -40,8 +41,8 @@ class LicensesTransformer 'license_email' => e($license->license_email), 'reassignable' => ($license->reassignable == 1) ? true : false, 'maintained' => ($license->maintained == 1) ? true : false, - 'supplier' => ($license->supplier) ? ['id' => (int) $license->supplier->id,'name'=> e($license->supplier->name)] : null, - 'category' => ($license->category) ? ['id' => (int) $license->category->id,'name'=> e($license->category->name)] : null, + 'supplier' => ($license->supplier) ? ['id' => (int) $license->supplier->id, 'name'=> e($license->supplier->name)] : null, + 'category' => ($license->category) ? ['id' => (int) $license->category->id, 'name'=> e($license->category->name)] : null, 'created_at' => Helper::getFormattedDateObject($license->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($license->updated_at, 'datetime'), 'user_can_checkout' => (bool) ($license->free_seats_count > 0), @@ -60,10 +61,8 @@ class LicensesTransformer return $array; } - public function transformAssetsDatatable($licenses) { + public function transformAssetsDatatable($licenses) + { return (new DatatablesTransformer)->transformDatatables($licenses); } - - - } diff --git a/app/Http/Transformers/LocationsTransformer.php b/app/Http/Transformers/LocationsTransformer.php index 2f7013b21a..78d8cc8096 100644 --- a/app/Http/Transformers/LocationsTransformer.php +++ b/app/Http/Transformers/LocationsTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } public function transformLocation(Location $location = null) { if ($location) { - $children_arr = []; - if(!is_null($location->children)){ - foreach($location->children as $child) { + if (! is_null($location->children)) { + foreach ($location->children as $child) { $children_arr[] = [ 'id' => (int) $child->id, - 'name' => $child->name + 'name' => $child->name, ]; } } @@ -52,11 +52,10 @@ class LocationsTransformer 'updated_at' => Helper::getFormattedDateObject($location->updated_at, 'datetime'), 'parent' => ($location->parent) ? [ 'id' => (int) $location->parent->id, - 'name'=> e($location->parent->name) + 'name'=> e($location->parent->name), ] : null, 'manager' => ($location->manager) ? (new UsersTransformer)->transformUser($location->manager) : null, - 'children' => $children_arr, ]; @@ -69,10 +68,5 @@ class LocationsTransformer return $array; } - - } - - - } diff --git a/app/Http/Transformers/LoginAttemptsTransformer.php b/app/Http/Transformers/LoginAttemptsTransformer.php index a0af36d121..cc1c512fbb 100644 --- a/app/Http/Transformers/LoginAttemptsTransformer.php +++ b/app/Http/Transformers/LoginAttemptsTransformer.php @@ -1,15 +1,14 @@ (int) $login_attempt->id, 'username' => e($login_attempt->username), 'user_agent' => e($login_attempt->user_agent), - 'remote_ip' => (!config('app.lock_passwords')) ? e($login_attempt->remote_ip) : '--', + 'remote_ip' => (! config('app.lock_passwords')) ? e($login_attempt->remote_ip) : '--', 'successful' => e($login_attempt->successful), 'created_at' => Helper::getFormattedDateObject($login_attempt->created_at, 'datetime'), ]; + return $array; } - - } - - - } diff --git a/app/Http/Transformers/ManufacturersTransformer.php b/app/Http/Transformers/ManufacturersTransformer.php index 1cdf5dd3fe..a7ac0e6a42 100644 --- a/app/Http/Transformers/ManufacturersTransformer.php +++ b/app/Http/Transformers/ManufacturersTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } - public function transformManufacturer (Manufacturer $manufacturer = null) + public function transformManufacturer(Manufacturer $manufacturer = null) { if ($manufacturer) { - $array = [ 'id' => (int) $manufacturer->id, 'name' => e($manufacturer->name), @@ -41,8 +41,8 @@ class ManufacturersTransformer ]; $permissions_array['available_actions'] = [ - 'update' => (($manufacturer->deleted_at=='') && (Gate::allows('update', Manufacturer::class))), - 'restore' => (($manufacturer->deleted_at!='') && (Gate::allows('create', Manufacturer::class))), + 'update' => (($manufacturer->deleted_at == '') && (Gate::allows('update', Manufacturer::class))), + 'restore' => (($manufacturer->deleted_at != '') && (Gate::allows('create', Manufacturer::class))), 'delete' => $manufacturer->isDeletable(), ]; @@ -50,10 +50,5 @@ class ManufacturersTransformer return $array; } - - } - - - } diff --git a/app/Http/Transformers/PredefinedKitsTransformer.php b/app/Http/Transformers/PredefinedKitsTransformer.php index 57e3aa62f4..ebd91aef0c 100644 --- a/app/Http/Transformers/PredefinedKitsTransformer.php +++ b/app/Http/Transformers/PredefinedKitsTransformer.php @@ -1,4 +1,5 @@ ] * @return array */ class PredefinedKitsTransformer { - - public function transformPredefinedKits (Collection $kits, $total) + public function transformPredefinedKits(Collection $kits, $total) { - $array = array(); + $array = []; foreach ($kits as $kit) { $array[] = self::transformPredefinedKit($kit); } + return (new DatatablesTransformer)->transformDatatables($array, $total); } - public function transformPredefinedKit (PredefinedKit $kit) + public function transformPredefinedKit(PredefinedKit $kit) { $array = [ 'id' => (int) $kit->id, - 'name' => e($kit->name) + 'name' => e($kit->name), ]; $permissions_array['available_actions'] = [ @@ -40,28 +41,32 @@ class PredefinedKitsTransformer ]; $array['user_can_checkout'] = true; $array += $permissions_array; + return $array; } /** - * transform collection of any elemets attached to kit + * transform collection of any elemets attached to kit * @return array */ - public function transformElements(Collection $elements, $total) { - $array = array(); + public function transformElements(Collection $elements, $total) + { + $array = []; foreach ($elements as $element) { $array[] = self::transformElement($element); } + return (new DatatablesTransformer)->transformDatatables($array, $total); } - public function transformElement(SnipeModel $element) { + public function transformElement(SnipeModel $element) + { $array = [ 'id' => (int) $element->id, 'pivot_id' => (int) $element->pivot->id, 'owner_id' => (int) $element->pivot->kit_id, 'quantity' => (int) $element->pivot->quantity, - 'name' => e($element->name) + 'name' => e($element->name), ]; $permissions_array['available_actions'] = [ @@ -70,12 +75,12 @@ class PredefinedKitsTransformer ]; $array += $permissions_array; + return $array; } - public function transformPredefinedKitsDatatable($kits) { + public function transformPredefinedKitsDatatable($kits) + { return (new DatatablesTransformer)->transformDatatables($kits); } - - } diff --git a/app/Http/Transformers/SelectlistTransformer.php b/app/Http/Transformers/SelectlistTransformer.php index 6b0d8caee3..363d92126a 100644 --- a/app/Http/Transformers/SelectlistTransformer.php +++ b/app/Http/Transformers/SelectlistTransformer.php @@ -1,5 +1,7 @@ ] * @since [v4.0.16] * @return \Illuminate\Http\Response */ - class SelectlistTransformer { - - public function transformSelectlist (LengthAwarePaginator $select_items) + public function transformSelectlist(LengthAwarePaginator $select_items) { - $items_array=[]; + $items_array = []; // Loop through the paginated collection to set the array values foreach ($select_items as $select_item) { - $items_array[]= [ + $items_array[] = [ 'id' => (int) $select_item->id, 'text' => ($select_item->use_text) ? $select_item->use_text : $select_item->name, - 'image' => ($select_item->use_image) ? $select_item->use_image : null, + 'image' => ($select_item->use_image) ? $select_item->use_image : null, ]; - } $results = [ 'results' => $items_array, - 'pagination' => - [ + 'pagination' => [ 'more' => ($select_items->currentPage() >= $select_items->lastPage()) ? false : true, - 'per_page' => $select_items->perPage() + 'per_page' => $select_items->perPage(), ], 'total_count' => $select_items->total(), 'page' => $select_items->currentPage(), - 'page_count' => $select_items->lastPage() + 'page_count' => $select_items->lastPage(), ]; return $results; - } - } diff --git a/app/Http/Transformers/StatuslabelsTransformer.php b/app/Http/Transformers/StatuslabelsTransformer.php index b320129f37..cc229a590f 100644 --- a/app/Http/Transformers/StatuslabelsTransformer.php +++ b/app/Http/Transformers/StatuslabelsTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } - public function transformStatuslabel (Statuslabel $statuslabel) + public function transformStatuslabel(Statuslabel $statuslabel) { $array = [ 'id' => (int) $statuslabel->id, 'name' => e($statuslabel->name), 'type' => $statuslabel->getStatuslabelType(), 'color' => ($statuslabel->color) ? e($statuslabel->color) : null, - 'show_in_nav' => ($statuslabel->show_in_nav=='1') ? true : false, - 'default_label' => ($statuslabel->default_label =='1') ? true : false, + 'show_in_nav' => ($statuslabel->show_in_nav == '1') ? true : false, + 'default_label' => ($statuslabel->default_label == '1') ? true : false, 'assets_count' => (int) $statuslabel->assets_count, 'notes' => e($statuslabel->notes), 'created_at' => Helper::getFormattedDateObject($statuslabel->created_at, 'datetime'), @@ -41,7 +42,4 @@ class StatuslabelsTransformer return $array; } - - - } diff --git a/app/Http/Transformers/SuppliersTransformer.php b/app/Http/Transformers/SuppliersTransformer.php index e24e399bd1..76b2a01514 100644 --- a/app/Http/Transformers/SuppliersTransformer.php +++ b/app/Http/Transformers/SuppliersTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } - public function transformSupplier (Supplier $supplier = null) + public function transformSupplier(Supplier $supplier = null) { if ($supplier) { - $array = [ 'id' => (int) $supplier->id, 'name' => e($supplier->name), @@ -49,17 +49,12 @@ class SuppliersTransformer $permissions_array['available_actions'] = [ 'update' => Gate::allows('update', Supplier::class), - 'delete' => (Gate::allows('delete', Supplier::class) && ($supplier->assets_count == 0) && ($supplier->licenses_count == 0) && ($supplier->accessories_count == 0)), + 'delete' => (Gate::allows('delete', Supplier::class) && ($supplier->assets_count == 0) && ($supplier->licenses_count == 0) && ($supplier->accessories_count == 0)), ]; $array += $permissions_array; return $array; } - - } - - - } diff --git a/app/Http/Transformers/UsersTransformer.php b/app/Http/Transformers/UsersTransformer.php index f2d1c795fa..49aea90a1d 100644 --- a/app/Http/Transformers/UsersTransformer.php +++ b/app/Http/Transformers/UsersTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); } - public function transformUser (User $user) + public function transformUser(User $user) { $array = [ 'id' => (int) $user->id, @@ -31,8 +32,8 @@ class UsersTransformer 'employee_num' => e($user->employee_num), 'manager' => ($user->manager) ? [ 'id' => (int) $user->manager->id, - 'name'=> e($user->manager->username) - ] : null, + 'name'=> e($user->manager->username), + ] : null, 'jobtitle' => ($user->jobtitle) ? e($user->jobtitle) : null, 'phone' => ($user->phone) ? e($user->phone) : null, 'website' => ($user->website) ? e($user->website) : null, @@ -44,61 +45,57 @@ class UsersTransformer 'email' => e($user->email), 'department' => ($user->department) ? [ 'id' => (int) $user->department->id, - 'name'=> e($user->department->name) - ] : null, + 'name'=> e($user->department->name), + ] : null, 'location' => ($user->userloc) ? [ 'id' => (int) $user->userloc->id, - 'name'=> e($user->userloc->name) - ] : null, + 'name'=> e($user->userloc->name), + ] : null, 'notes'=> e($user->notes), 'permissions' => $user->decodePermissions(), - 'activated' => ($user->activated =='1') ? true : false, - 'ldap_import' => ($user->ldap_import =='1') ? true : false, + 'activated' => ($user->activated == '1') ? true : false, + 'ldap_import' => ($user->ldap_import == '1') ? true : false, 'two_factor_activated' => ($user->two_factor_active()) ? true : false, 'two_factor_enrolled' => ($user->two_factor_active_and_enrolled()) ? true : false, 'assets_count' => (int) $user->assets_count, 'licenses_count' => (int) $user->licenses_count, 'accessories_count' => (int) $user->accessories_count, 'consumables_count' => (int) $user->consumables_count, - 'company' => ($user->company) ? ['id' => (int) $user->company->id,'name'=> e($user->company->name)] : null, + 'company' => ($user->company) ? ['id' => (int) $user->company->id, 'name'=> e($user->company->name)] : null, 'created_at' => Helper::getFormattedDateObject($user->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($user->updated_at, 'datetime'), 'last_login' => Helper::getFormattedDateObject($user->last_login, 'datetime'), - 'deleted_at' => ($user->deleted_at) ? Helper::getFormattedDateObject($user->deleted_at, 'datetime') : null, + 'deleted_at' => ($user->deleted_at) ? Helper::getFormattedDateObject($user->deleted_at, 'datetime') : null, ]; $permissions_array['available_actions'] = [ - 'update' => (Gate::allows('update', User::class) && ($user->deleted_at=='')), - 'delete' => (Gate::allows('delete', User::class) && ($user->assets_count == 0) && ($user->licenses_count == 0) && ($user->accessories_count == 0) && ($user->consumables_count == 0)), - 'clone' => (Gate::allows('create', User::class) && ($user->deleted_at=='')) , - 'restore' => (Gate::allows('create', User::class) && ($user->deleted_at!='')), + 'update' => (Gate::allows('update', User::class) && ($user->deleted_at == '')), + 'delete' => (Gate::allows('delete', User::class) && ($user->assets_count == 0) && ($user->licenses_count == 0) && ($user->accessories_count == 0) && ($user->consumables_count == 0)), + 'clone' => (Gate::allows('create', User::class) && ($user->deleted_at == '')), + 'restore' => (Gate::allows('create', User::class) && ($user->deleted_at != '')), ]; $array += $permissions_array; - $numGroups = $user->groups->count(); - if($numGroups > 0) - { - $groups["total"] = $numGroups; - foreach($user->groups as $group) - { - $groups["rows"][] = [ + if ($numGroups > 0) { + $groups['total'] = $numGroups; + foreach ($user->groups as $group) { + $groups['rows'][] = [ 'id' => (int) $group->id, - 'name' => e($group->name) + 'name' => e($group->name), ]; } - $array["groups"] = $groups; - } - else { - $array["groups"] = null; + $array['groups'] = $groups; + } else { + $array['groups'] = null; } return $array; } - public function transformUsersDatatable($users) { + public function transformUsersDatatable($users) + { return (new DatatablesTransformer)->transformDatatables($users); } - } diff --git a/app/Importer/AccessoryImporter.php b/app/Importer/AccessoryImporter.php index 324d27e9e2..f9c871fa7c 100644 --- a/app/Importer/AccessoryImporter.php +++ b/app/Importer/AccessoryImporter.php @@ -27,8 +27,9 @@ class AccessoryImporter extends ItemImporter { $accessory = Accessory::where('name', $this->item['name'])->first(); if ($accessory) { - if (!$this->updating) { - $this->log('A matching Accessory ' . $this->item["name"] . ' already exists. '); + if (! $this->updating) { + $this->log('A matching Accessory '.$this->item['name'].' already exists. '); + return; } @@ -36,9 +37,10 @@ class AccessoryImporter extends ItemImporter $this->item['model_number'] = $this->findCsvMatch($row, "model_number"); $accessory->update($this->sanitizeItemForUpdating($accessory)); $accessory->save(); + return; } - $this->log("No Matching Accessory, Creating a new one"); + $this->log('No Matching Accessory, Creating a new one'); $accessory = new Accessory(); $this->item['model_number'] = $this->findCsvMatch($row, "model_number"); $accessory->fill($this->sanitizeItemForStoring($accessory)); @@ -47,7 +49,8 @@ class AccessoryImporter extends ItemImporter // $accessory->unsetEventDispatcher(); if ($accessory->save()) { $accessory->logCreate('Imported using CSV Importer'); - $this->log('Accessory ' . $this->item["name"] . ' was created'); + $this->log('Accessory '.$this->item['name'].' was created'); + return; } $this->logError($accessory, 'Accessory'); diff --git a/app/Importer/AssetImporter.php b/app/Importer/AssetImporter.php index be117d6fae..8e6781db7d 100644 --- a/app/Importer/AssetImporter.php +++ b/app/Importer/AssetImporter.php @@ -21,20 +21,17 @@ class AssetImporter extends ItemImporter parent::handle($row); if ($this->customFields) { - foreach ($this->customFields as $customField) { $customFieldValue = $this->array_smart_custom_field_fetch($row, $customField); if ($customFieldValue) { - if ($customField->field_encrypted == 1) { $this->item['custom_fields'][$customField->db_column_name()] = \Crypt::encrypt($customFieldValue); - $this->log('Custom Field '. $customField->name.': '.\Crypt::encrypt($customFieldValue)); + $this->log('Custom Field '.$customField->name.': '.\Crypt::encrypt($customFieldValue)); } else { $this->item['custom_fields'][$customField->db_column_name()] = $customFieldValue; - $this->log('Custom Field '. $customField->name.': '.$customFieldValue); + $this->log('Custom Field '.$customField->name.': '.$customFieldValue); } - } else { // Clear out previous data. $this->item['custom_fields'][$customField->db_column_name()] = null; @@ -42,7 +39,6 @@ class AssetImporter extends ItemImporter } } - $this->createAssetIfNotExists($row); } @@ -57,30 +53,31 @@ class AssetImporter extends ItemImporter public function createAssetIfNotExists(array $row) { $editingAsset = false; - $asset_tag = $this->findCsvMatch($row, "asset_tag"); + $asset_tag = $this->findCsvMatch($row, 'asset_tag'); $asset = Asset::where(['asset_tag'=> $asset_tag])->first(); if ($asset) { - if (!$this->updating) { - $this->log('A matching Asset ' . $asset_tag . ' already exists'); + if (! $this->updating) { + $this->log('A matching Asset '.$asset_tag.' already exists'); + return; } - $this->log("Updating Asset"); + $this->log('Updating Asset'); $editingAsset = true; } else { - $this->log("No Matching Asset, Creating a new one"); + $this->log('No Matching Asset, Creating a new one'); $asset = new Asset; } - $this->item['image'] = $this->findCsvMatch($row, "image"); - $this->item['requestable'] = $this->fetchHumanBoolean($this->findCsvMatch($row, "requestable"));; - $asset->requestable = $this->fetchHumanBoolean($this->findCsvMatch($row, "requestable")); - $this->item['warranty_months'] = intval($this->findCsvMatch($row, "warranty_months")); + $this->item['image'] = $this->findCsvMatch($row, 'image'); + $this->item['requestable'] = $this->fetchHumanBoolean($this->findCsvMatch($row, 'requestable')); + $asset->requestable = $this->fetchHumanBoolean($this->findCsvMatch($row, 'requestable')); + $this->item['warranty_months'] = intval($this->findCsvMatch($row, 'warranty_months')); $this->item['model_id'] = $this->createOrFetchAssetModel($row); // If no status ID is found - if (!array_key_exists('status_id', $this->item) && !$editingAsset) { - $this->log("No status field found, defaulting to first status."); + if (! array_key_exists('status_id', $this->item) && ! $editingAsset) { + $this->log('No status field found, defaulting to first status.'); $this->item['status_id'] = $this->defaultStatusLabelId; } @@ -88,18 +85,17 @@ class AssetImporter extends ItemImporter // We need to save the user if it exists so that we can checkout to user later. // Sanitizing the item will remove it. - if(array_key_exists('checkout_target', $this->item)) { + if (array_key_exists('checkout_target', $this->item)) { $target = $this->item['checkout_target']; } $item = $this->sanitizeItemForStoring($asset, $editingAsset); // The location id fetched by the csv reader is actually the rtd_location_id. // This will also set location_id, but then that will be overridden by the // checkout method if necessary below. - if (isset($this->item["location_id"])) { + if (isset($this->item['location_id'])) { $item['rtd_location_id'] = $this->item['location_id']; } - if ($editingAsset) { $asset->update($item); } else { @@ -117,16 +113,17 @@ class AssetImporter extends ItemImporter // $asset->unsetEventDispatcher(); if ($asset->save()) { $asset->logCreate('Imported using csv importer'); - $this->log('Asset ' . $this->item["name"] . ' with serial number ' . $this->item['serial'] . ' was created'); + $this->log('Asset '.$this->item['name'].' with serial number '.$this->item['serial'].' was created'); // If we have a target to checkout to, lets do so. //-- user_id is a property of the abstract class Importer, which this class inherits from and it's setted by //-- the class that needs to use it (command importer or GUI importer inside the project). - if(isset($target)) { + if (isset($target)) { $asset->fresh()->checkOut($target, $this->user_id); } + return; } - $this->logError($asset, 'Asset "' . $this->item['name'].'"'); + $this->logError($asset, 'Asset "'.$this->item['name'].'"'); } } diff --git a/app/Importer/ComponentImporter.php b/app/Importer/ComponentImporter.php index a12828f5d5..de3ee14d1c 100644 --- a/app/Importer/ComponentImporter.php +++ b/app/Importer/ComponentImporter.php @@ -27,30 +27,32 @@ class ComponentImporter extends ItemImporter public function createComponentIfNotExists() { $component = null; - $this->log("Creating Component"); + $this->log('Creating Component'); $component = Component::where('name', $this->item['name']) ->where('serial', $this->item['serial']) ->first(); if ($component) { - $this->log('A matching Component ' . $this->item["name"] . ' with serial ' .$this->item['serial'].' already exists. '); - if (!$this->updating) { - $this->log("Skipping Component"); + $this->log('A matching Component '.$this->item['name'].' with serial '.$this->item['serial'].' already exists. '); + if (! $this->updating) { + $this->log('Skipping Component'); + return; } - $this->log("Updating Component"); + $this->log('Updating Component'); $component->update($this->sanitizeItemForUpdating($component)); $component->save(); + return; } - $this->log("No matching component, creating one"); + $this->log('No matching component, creating one'); $component = new Component; $component->fill($this->sanitizeItemForStoring($component)); //FIXME: this disables model validation. Need to find a way to avoid double-logs without breaking everything. $component->unsetEventDispatcher(); if ($component->save()) { $component->logCreate('Imported using CSV Importer'); - $this->log("Component " . $this->item["name"] . ' was created'); + $this->log('Component '.$this->item['name'].' was created'); // If we have an asset tag, checkout to that asset. if (isset($this->item['asset_tag']) && ($asset = Asset::where('asset_tag', $this->item['asset_tag'])->first())) { @@ -59,9 +61,10 @@ class ComponentImporter extends ItemImporter 'user_id' => $this->user_id, 'created_at' => date('Y-m-d H:i:s'), 'assigned_qty' => 1, // Only assign the first one to the asset - 'asset_id' => $asset->id + 'asset_id' => $asset->id, ]); } + return; } $this->logError($component, 'Component'); diff --git a/app/Importer/ConsumableImporter.php b/app/Importer/ConsumableImporter.php index e7972bb2cd..cc24daa930 100644 --- a/app/Importer/ConsumableImporter.php +++ b/app/Importer/ConsumableImporter.php @@ -28,28 +28,30 @@ class ConsumableImporter extends ItemImporter { $consumable = Consumable::where('name', $this->item['name'])->first(); if ($consumable) { - if (!$this->updating) { - $this->log('A matching Consumable ' . $this->item["name"] . ' already exists. '); + if (! $this->updating) { + $this->log('A matching Consumable '.$this->item['name'].' already exists. '); + return; } $this->log('Updating Consumable'); $consumable->update($this->sanitizeItemForUpdating($consumable)); $consumable->save(); + return; } - $this->log("No matching consumable, creating one"); + $this->log('No matching consumable, creating one'); $consumable = new Consumable(); - $this->item['model_number'] = $this->findCsvMatch($row, "model_number");; - $this->item['item_no'] = $this->findCsvMatch($row, "item_number"); + $this->item['model_number'] = $this->findCsvMatch($row, 'model_number'); + $this->item['item_no'] = $this->findCsvMatch($row, 'item_number'); $consumable->fill($this->sanitizeItemForStoring($consumable)); //FIXME: this disables model validation. Need to find a way to avoid double-logs without breaking everything. $consumable->unsetEventDispatcher(); if ($consumable->save()) { $consumable->logCreate('Imported using CSV Importer'); - $this->log("Consumable " . $this->item["name"] . ' was created'); + $this->log('Consumable '.$this->item['name'].' was created'); + return; } $this->logError($consumable, 'Consumable'); - return; } } diff --git a/app/Importer/Importer.php b/app/Importer/Importer.php index 6466c3b2d1..f80b869d54 100644 --- a/app/Importer/Importer.php +++ b/app/Importer/Importer.php @@ -1,13 +1,14 @@ 'checkout location', 'company' => 'company', 'item_name' => 'item name', - 'item_number' => "item number", + 'item_number' => 'item number', 'image' => 'image', 'expiration_date' => 'expiration date', 'location' => 'location', 'notes' => 'notes', 'license_email' => 'licensed to email', - 'license_name' => "licensed to name", + 'license_name' => 'licensed to name', 'maintained' => 'maintained', 'manufacturer' => 'manufacturer', - 'asset_model' => "model name", + 'asset_model' => 'model name', 'model_number' => 'model number', 'order_number' => 'order number', 'purchase_cost' => 'purchase cost', @@ -106,8 +107,8 @@ abstract class Importer public function __construct($file) { $this->fieldMap = $this->defaultFieldMap; - if (! ini_get("auto_detect_line_endings")) { - ini_set("auto_detect_line_endings", '1'); + if (! ini_get('auto_detect_line_endings')) { + ini_set('auto_detect_line_endings', '1'); } // By default the importer passes a url to the file. // However, for testing we also support passing a string directly @@ -116,8 +117,9 @@ abstract class Importer } else { $this->csv = Reader::createFromString($file); } - $this->tempPassword = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20); + $this->tempPassword = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 20); } + // Cached Values for import lookups protected $customFields; @@ -138,7 +140,7 @@ abstract class Importer DB::transaction(function () use (&$results) { Model::unguard(); - $resultsCount = sizeof($results); + $resultsCount = count($results); foreach ($results as $row) { $this->handle($row); if ($this->progressCallback) { @@ -150,7 +152,6 @@ abstract class Importer }); } - abstract protected function handle($row); /** @@ -166,6 +167,7 @@ abstract class Importer // This 'inverts' the fields such that we have a collection of fields indexed by name. $this->customFields = CustomField::All()->reduce(function ($nameLookup, $field) { $nameLookup[$field['name']] = $field; + return $nameLookup; }); // Remove any custom fields that do not exist in the header row. This prevents nulling out values that shouldn't exist. @@ -177,8 +179,8 @@ abstract class Importer array_change_key_case(array_flip($headerRow)) ); } - } + /** * Check to see if the given key exists in the array, and trim excess white space before returning it * @@ -191,13 +193,12 @@ abstract class Importer */ public function findCsvMatch(array $array, $key, $default = null) { - $val = $default; $key = $this->lookupCustomKey($key); // $this->log("Custom Key: ${key}"); if (array_key_exists($key, $array)) { - $val = Encoding::toUTF8(trim($array[ $key ])); + $val = Encoding::toUTF8(trim($array[$key])); } // $this->log("${key}: ${val}"); return $val; @@ -222,7 +223,7 @@ abstract class Importer /** * Used to lowercase header values to ensure we're comparing values properly. - * + * * @param $results * @return array */ @@ -232,8 +233,10 @@ abstract class Importer foreach ($results as $index => $arrayToNormalize) { $newArray[$index] = array_change_key_case($arrayToNormalize); } + return $newArray; } + /** * Figure out the fieldname of the custom field * @@ -245,6 +248,7 @@ abstract class Importer public function array_smart_custom_field_fetch(array $array, $key) { $index_name = strtolower($key->name); + return array_key_exists($index_name, $array) ? trim($array[$index_name]) : false; } @@ -277,34 +281,36 @@ abstract class Importer protected function createOrFetchUser($row) { $user_array = [ - 'full_name' => $this->findCsvMatch($row, "full_name"), - 'email' => $this->findCsvMatch($row, "email"), + 'full_name' => $this->findCsvMatch($row, 'full_name'), + 'email' => $this->findCsvMatch($row, 'email'), 'manager_id'=> '', 'department_id' => '', - 'username' => $this->findCsvMatch($row, "username"), + 'username' => $this->findCsvMatch($row, 'username'), 'activated' => $this->fetchHumanBoolean($this->findCsvMatch($row, 'activated')), ]; // Maybe we're lucky and the user already exists. - if($user = User::where('username', $user_array['username'])->first()) { + if ($user = User::where('username', $user_array['username'])->first()) { $this->log('User '.$user_array['username'].' already exists'); + return $user; } // If the full name is empty, bail out--we need this to extract first name (at the very least) - if(empty($user_array['full_name'])) { + if (empty($user_array['full_name'])) { $this->log('Insufficient user data provided (Full name is required)- skipping user creation, just adding asset'); + return false; } // Is the user actually an ID? - if($user = $this->findUserByNumber($user_array['full_name'])) { + if ($user = $this->findUserByNumber($user_array['full_name'])) { return $user; } $this->log('User does not appear to be an id with number: '.$user_array['full_name'].'. Continuing through our processes'); // Populate email if it does not exist. - if(empty($user_array['email'])) { + if (empty($user_array['email'])) { $user_array['email'] = User::generateEmailFromFullName($user_array['full_name']); } @@ -314,7 +320,7 @@ abstract class Importer if (empty($user_array['username'])) { $user_array['username'] = $user_formatted_array['username']; - if ($this->usernameFormat =='email') { + if ($this->usernameFormat == 'email') { $user_array['username'] = $user_array['email']; } } @@ -323,32 +329,35 @@ abstract class Importer // Check for a matching user after trying to guess username. if ($user = User::where('username', $user_array['username'])->first()) { $this->log('User '.$user_array['username'].' already exists'); + return $user; } // If at this point we have not found a username or first name, bail out in shame. - if(empty($user_array['username']) || empty($user_array['first_name'])) { + if (empty($user_array['username']) || empty($user_array['first_name'])) { return false; } // No Luck, let's create one. $user = new User; - $user->first_name = $user_array['first_name']; - $user->last_name = $user_array['last_name']; - $user->username = $user_array['username']; - $user->email = $user_array['email']; - $user->manager_id = $user_array['manager_id'] ?? null; + $user->first_name = $user_array['first_name']; + $user->last_name = $user_array['last_name']; + $user->username = $user_array['username']; + $user->email = $user_array['email']; + $user->manager_id = $user_array['manager_id'] ?? null; $user->department_id = $user_array['department_id'] ?? null; - $user->activated = 1; - $user->password = $this->tempPassword; + $user->activated = 1; + $user->password = $this->tempPassword; \Log::debug('Creating a user with the following attributes: '.print_r($user_array, true)); if ($user->save()) { $this->log('User '.$user_array['username'].' created'); + return $user; } - $this->logError($user, 'User "' . $user_array['username'] . '" was not able to be created.'); + $this->logError($user, 'User "'.$user_array['username'].'" was not able to be created.'); + return false; } @@ -362,6 +371,7 @@ abstract class Importer // A number was given instead of a name if (is_numeric($user_name)) { $this->log('User '.$user_name.' is a number - lets see if it matches a user id'); + return User::find($user_name); } } @@ -442,6 +452,7 @@ abstract class Importer return $this; } + /** * Sets the value of usernameFormat. * @@ -458,7 +469,7 @@ abstract class Importer public function fetchHumanBoolean($value) { - return (int) filter_var($value, FILTER_VALIDATE_BOOLEAN); + return (int) filter_var($value, FILTER_VALIDATE_BOOLEAN); } /** @@ -471,11 +482,12 @@ abstract class Importer */ public function createOrFetchDepartment($user_department_name) { - if ($user_department_name!='') { + if ($user_department_name != '') { $department = Department::where('name', '=', $user_department_name)->first(); if ($department) { - $this->log('A matching Department ' . $user_department_name . ' already exists'); + $this->log('A matching Department '.$user_department_name.' already exists'); + return $department->id; } @@ -483,7 +495,8 @@ abstract class Importer $department->name = $user_department_name; if ($department->save()) { - $this->log('Department ' . $user_department_name . ' was created'); + $this->log('Department '.$user_department_name.' was created'); + return $department->id; } $this->logError($department, 'Department'); @@ -505,10 +518,12 @@ abstract class Importer $manager = User::where('first_name', '=', $user_manager_first_name) ->where('last_name', '=', $user_manager_last_name)->first(); if ($manager) { - $this->log('A matching Manager ' . $user_manager_first_name . ' '. $user_manager_last_name . ' already exists'); + $this->log('A matching Manager '.$user_manager_first_name.' '.$user_manager_last_name.' already exists'); + return $manager->id; } - $this->log('No matching Manager ' . $user_manager_first_name . ' '. $user_manager_last_name . ' found. If their user account is being created through this import, you should re-process this file again. '); + $this->log('No matching Manager '.$user_manager_first_name.' '.$user_manager_last_name.' found. If their user account is being created through this import, you should re-process this file again. '); + return null; } } diff --git a/app/Importer/ItemImporter.php b/app/Importer/ItemImporter.php index 7ff568a429..1584539ee2 100644 --- a/app/Importer/ItemImporter.php +++ b/app/Importer/ItemImporter.php @@ -14,6 +14,7 @@ use App\Models\User; class ItemImporter extends Importer { protected $item; + public function __construct($filename) { parent::__construct($filename); @@ -24,67 +25,67 @@ class ItemImporter extends Importer // Need to reset this between iterations or we'll have stale data. $this->item = []; - $item_category = $this->findCsvMatch($row, "category"); + $item_category = $this->findCsvMatch($row, 'category'); if ($this->shouldUpdateField($item_category)) { - $this->item["category_id"] = $this->createOrFetchCategory($item_category); + $this->item['category_id'] = $this->createOrFetchCategory($item_category); } - $item_company_name = $this->findCsvMatch($row, "company"); + $item_company_name = $this->findCsvMatch($row, 'company'); if ($this->shouldUpdateField($item_company_name)) { - $this->item["company_id"] = $this->createOrFetchCompany($item_company_name); + $this->item['company_id'] = $this->createOrFetchCompany($item_company_name); } - $item_location = $this->findCsvMatch($row, "location"); + $item_location = $this->findCsvMatch($row, 'location'); if ($this->shouldUpdateField($item_location)) { - $this->item["location_id"] = $this->createOrFetchLocation($item_location); + $this->item['location_id'] = $this->createOrFetchLocation($item_location); } - $item_manufacturer = $this->findCsvMatch($row, "manufacturer"); + $item_manufacturer = $this->findCsvMatch($row, 'manufacturer'); if ($this->shouldUpdateField($item_manufacturer)) { - $this->item["manufacturer_id"] = $this->createOrFetchManufacturer($item_manufacturer); + $this->item['manufacturer_id'] = $this->createOrFetchManufacturer($item_manufacturer); } - $item_status_name = $this->findCsvMatch($row, "status"); + $item_status_name = $this->findCsvMatch($row, 'status'); if ($this->shouldUpdateField($item_status_name)) { - $this->item["status_id"] = $this->createOrFetchStatusLabel($item_status_name); + $this->item['status_id'] = $this->createOrFetchStatusLabel($item_status_name); } - $item_supplier = $this->findCsvMatch($row, "supplier"); + $item_supplier = $this->findCsvMatch($row, 'supplier'); if ($this->shouldUpdateField($item_supplier)) { $this->item['supplier_id'] = $this->createOrFetchSupplier($item_supplier); } - $item_department = $this->findCsvMatch($row, "department"); + $item_department = $this->findCsvMatch($row, 'department'); if ($this->shouldUpdateField($item_department)) { $this->item['department_id'] = $this->createOrFetchDepartment($item_department); } - $item_manager_first_name = $this->findCsvMatch($row, "manage_first_name"); - $item_manager_last_name = $this->findCsvMatch($row, "manage_last_name"); + $item_manager_first_name = $this->findCsvMatch($row, 'manage_first_name'); + $item_manager_last_name = $this->findCsvMatch($row, 'manage_last_name'); if ($this->shouldUpdateField($item_manager_first_name)) { $this->item['manager_id'] = $this->fetchManager($item_manager_first_name, $item_manager_last_name); } - $this->item["name"] = $this->findCsvMatch($row, "item_name"); - $this->item["notes"] = $this->findCsvMatch($row, "notes"); - $this->item["order_number"] = $this->findCsvMatch($row, "order_number"); - $this->item["purchase_cost"] = $this->findCsvMatch($row, "purchase_cost"); + $this->item['name'] = $this->findCsvMatch($row, 'item_name'); + $this->item['notes'] = $this->findCsvMatch($row, 'notes'); + $this->item['order_number'] = $this->findCsvMatch($row, 'order_number'); + $this->item['purchase_cost'] = $this->findCsvMatch($row, 'purchase_cost'); - $this->item["purchase_date"] = null; - if ($this->findCsvMatch($row, "purchase_date")!='') { - $this->item["purchase_date"] = date("Y-m-d 00:00:01", strtotime($this->findCsvMatch($row, "purchase_date"))); + $this->item['purchase_date'] = null; + if ($this->findCsvMatch($row, 'purchase_date') != '') { + $this->item['purchase_date'] = date('Y-m-d 00:00:01', strtotime($this->findCsvMatch($row, 'purchase_date'))); } - $this->item["qty"] = $this->findCsvMatch($row, "quantity"); - $this->item["requestable"] = $this->findCsvMatch($row, "requestable"); - $this->item["user_id"] = $this->user_id; - $this->item['serial'] = $this->findCsvMatch($row, "serial"); + $this->item['qty'] = $this->findCsvMatch($row, 'quantity'); + $this->item['requestable'] = $this->findCsvMatch($row, 'requestable'); + $this->item['user_id'] = $this->user_id; + $this->item['serial'] = $this->findCsvMatch($row, 'serial'); // NO need to call this method if we're running the user import. // TODO: Merge these methods. - $this->item['checkout_class'] = $this->findCsvMatch($row, "checkout_class"); - if(get_class($this) !== UserImporter::class) { + $this->item['checkout_class'] = $this->findCsvMatch($row, 'checkout_class'); + if (get_class($this) !== UserImporter::class) { // $this->item["user"] = $this->createOrFetchUser($row); - $this->item["checkout_target"] = $this->determineCheckout($row); + $this->item['checkout_target'] = $this->determineCheckout($row); } } @@ -92,11 +93,11 @@ class ItemImporter extends Importer * Parse row to determine what (if anything) we should checkout to. * @param array $row CSV Row being parsed * @return SnipeModel Model to be checked out to - */ + */ protected function determineCheckout($row) { // We only support checkout-to-location for asset, so short circuit otherwise. - if(get_class($this) != AssetImporter::class) { + if (get_class($this) != AssetImporter::class) { return $this->createOrFetchUser($row); } @@ -105,7 +106,6 @@ class ItemImporter extends Importer } return $this->createOrFetchUser($row); - } /** @@ -119,7 +119,6 @@ class ItemImporter extends Importer * @param $updating boolean Should we remove blank values? * @return array */ - protected function sanitizeItemForStoring($model, $updating = false) { // Create a collection for all manipulations to come. @@ -138,10 +137,10 @@ class ItemImporter extends Importer } /** - * Convenience function for updating that strips the empty values. + * Convenience function for updating that strips the empty values. * @param $model SnipeModel Model that's being updated. * @return array - */ + */ protected function sanitizeItemForUpdating($model) { return $this->sanitizeItemForStoring($model, true); @@ -156,15 +155,17 @@ class ItemImporter extends Importer * @author Daniel Melzter * @since 4.0 * @param $field string - * @return boolean + * @return bool */ protected function shouldUpdateField($field) { if (empty($field)) { return false; } - return !($this->updating && empty($field)); + + return ! ($this->updating && empty($field)); } + /** * Select the asset model if it exists, otherwise create it. * @@ -177,36 +178,37 @@ class ItemImporter extends Importer */ public function createOrFetchAssetModel(array $row) { - - $asset_model_name = $this->findCsvMatch($row, "asset_model"); - $asset_modelNumber = $this->findCsvMatch($row, "model_number"); + $asset_model_name = $this->findCsvMatch($row, 'asset_model'); + $asset_modelNumber = $this->findCsvMatch($row, 'model_number'); // TODO: At the moment, this means we can't update the model number if the model name stays the same. - if (!$this->shouldUpdateField($asset_model_name)) { + if (! $this->shouldUpdateField($asset_model_name)) { return; } - if ((empty($asset_model_name)) && (!empty($asset_modelNumber))) { + if ((empty($asset_model_name)) && (! empty($asset_modelNumber))) { $asset_model_name = $asset_modelNumber; - } elseif ((empty($asset_model_name)) && (empty($asset_modelNumber))) { - $asset_model_name ='Unknown'; + } elseif ((empty($asset_model_name)) && (empty($asset_modelNumber))) { + $asset_model_name = 'Unknown'; } $editingModel = $this->updating; $asset_model = AssetModel::where(['name' => $asset_model_name, 'model_number' => $asset_modelNumber])->first(); if ($asset_model) { - if (!$this->updating) { - $this->log("A matching model already exists, returning it."); + if (! $this->updating) { + $this->log('A matching model already exists, returning it.'); + return $asset_model->id; } - $this->log("Matching Model found, updating it."); + $this->log('Matching Model found, updating it.'); $item = $this->sanitizeItemForStoring($asset_model, $editingModel); $item['name'] = $asset_model_name; $item['model_number'] = $asset_modelNumber; $asset_model->update($item); $asset_model->save(); - $this->log("Asset Model Updated"); + $this->log('Asset Model Updated'); + return $asset_model->id; } - $this->log("No Matching Model, Creating a new one"); + $this->log('No Matching Model, Creating a new one'); $asset_model = new AssetModel(); $item = $this->sanitizeItemForStoring($asset_model, $editingModel); @@ -217,10 +219,12 @@ class ItemImporter extends Importer $item = null; if ($asset_model->save()) { - $this->log('Asset Model ' . $asset_model_name . ' with model number ' . $asset_modelNumber . ' was created'); + $this->log('Asset Model '.$asset_model_name.' with model number '.$asset_modelNumber.' was created'); + return $asset_model->id; } - $this->logError($asset_model, 'Asset Model "' . $asset_model_name . '"'); + $this->logError($asset_model, 'Asset Model "'.$asset_model_name.'"'); + return null; } @@ -245,7 +249,8 @@ class ItemImporter extends Importer $category = Category::where(['name' => $asset_category, 'category_type' => $item_type])->first(); if ($category) { - $this->log("A matching category: " . $asset_category . " already exists"); + $this->log('A matching category: '.$asset_category.' already exists'); + return $category->id; } @@ -255,11 +260,13 @@ class ItemImporter extends Importer $category->user_id = $this->user_id; if ($category->save()) { - $this->log('Category ' . $asset_category . ' was created'); + $this->log('Category '.$asset_category.' was created'); + return $category->id; } - $this->logError($category, 'Category "'. $asset_category. '"'); + $this->logError($category, 'Category "'.$asset_category.'"'); + return null; } @@ -275,22 +282,23 @@ class ItemImporter extends Importer { $company = Company::where(['name' => $asset_company_name])->first(); if ($company) { - $this->log('A matching Company ' . $asset_company_name . ' already exists'); + $this->log('A matching Company '.$asset_company_name.' already exists'); + return $company->id; } $company = new Company(); $company->name = $asset_company_name; if ($company->save()) { - $this->log('Company ' . $asset_company_name . ' was created'); + $this->log('Company '.$asset_company_name.' was created'); + return $company->id; } $this->logError($company, 'Company'); + return null; } - - /** * Fetch an existing manager * @@ -304,14 +312,15 @@ class ItemImporter extends Importer $manager = User::where('first_name', '=', $user_manager_first_name) ->where('last_name', '=', $user_manager_last_name)->first(); if ($manager) { - $this->log('A matching Manager ' . $user_manager_first_name . ' '. $user_manager_last_name . ' already exists'); + $this->log('A matching Manager '.$user_manager_first_name.' '.$user_manager_last_name.' already exists'); + return $manager->id; } - $this->log('No matching Manager ' . $user_manager_first_name . ' '. $user_manager_last_name . ' found. If their user account is being created through this import, you should re-process this file again. '); + $this->log('No matching Manager '.$user_manager_first_name.' '.$user_manager_last_name.' found. If their user account is being created through this import, you should re-process this file again. '); + return null; } - /** * Fetch the existing status label or create new if it doesn't exist. * @@ -322,17 +331,17 @@ class ItemImporter extends Importer */ public function createOrFetchStatusLabel($asset_statuslabel_name) { - if (empty($asset_statuslabel_name)) { return null; } $status = Statuslabel::where(['name' => $asset_statuslabel_name])->first(); if ($status) { - $this->log('A matching Status ' . $asset_statuslabel_name . ' already exists'); + $this->log('A matching Status '.$asset_statuslabel_name.' already exists'); + return $status->id; } - $this->log("Creating a new status"); + $this->log('Creating a new status'); $status = new Statuslabel(); $status->name = $asset_statuslabel_name; @@ -341,11 +350,13 @@ class ItemImporter extends Importer $status->archived = 0; if ($status->save()) { - $this->log('Status ' . $asset_statuslabel_name . ' was created'); + $this->log('Status '.$asset_statuslabel_name.' was created'); + return $status->id; } - $this->logError($status, 'Status "'. $asset_statuslabel_name . '"'); + $this->logError($status, 'Status "'.$asset_statuslabel_name.'"'); + return null; } @@ -357,17 +368,16 @@ class ItemImporter extends Importer * @param $item_manufacturer string * @return Manufacturer */ - public function createOrFetchManufacturer($item_manufacturer) { - if (empty($item_manufacturer)) { - $item_manufacturer='Unknown'; + $item_manufacturer = 'Unknown'; } $manufacturer = Manufacturer::where(['name'=> $item_manufacturer])->first(); if ($manufacturer) { - $this->log('Manufacturer ' . $item_manufacturer . ' already exists') ; + $this->log('Manufacturer '.$item_manufacturer.' already exists'); + return $manufacturer->id; } @@ -377,10 +387,12 @@ class ItemImporter extends Importer $manufacturer->user_id = $this->user_id; if ($manufacturer->save()) { - $this->log('Manufacturer ' . $manufacturer->name . ' was created'); + $this->log('Manufacturer '.$manufacturer->name.' was created'); + return $manufacturer->id; } - $this->logError($manufacturer, 'Manufacturer "'. $manufacturer->name . '"'); + $this->logError($manufacturer, 'Manufacturer "'.$manufacturer->name.'"'); + return null; } @@ -396,12 +408,14 @@ class ItemImporter extends Importer { if (empty($asset_location)) { $this->log('No location given, so none created.'); + return null; } $location = Location::where(['name' => $asset_location])->first(); if ($location) { - $this->log('Location ' . $asset_location . ' already exists'); + $this->log('Location '.$asset_location.' already exists'); + return $location->id; } // No matching locations in the collection, create a new one. @@ -414,10 +428,12 @@ class ItemImporter extends Importer $location->user_id = $this->user_id; if ($location->save()) { - $this->log('Location ' . $asset_location . ' was created'); + $this->log('Location '.$asset_location.' was created'); + return $location->id; } $this->logError($location, 'Location'); + return null; } @@ -432,13 +448,14 @@ class ItemImporter extends Importer public function createOrFetchSupplier($item_supplier) { if (empty($item_supplier)) { - $item_supplier='Unknown'; + $item_supplier = 'Unknown'; } - $supplier = Supplier::where(['name' => $item_supplier ])->first(); + $supplier = Supplier::where(['name' => $item_supplier])->first(); if ($supplier) { - $this->log('Supplier ' . $item_supplier . ' already exists'); + $this->log('Supplier '.$item_supplier.' already exists'); + return $supplier->id; } @@ -447,10 +464,12 @@ class ItemImporter extends Importer $supplier->user_id = $this->user_id; if ($supplier->save()) { - $this->log('Supplier ' . $item_supplier . ' was created'); + $this->log('Supplier '.$item_supplier.' was created'); + return $supplier->id; } $this->logError($supplier, 'Supplier'); + return null; } } diff --git a/app/Importer/LicenseImporter.php b/app/Importer/LicenseImporter.php index f9bc1d825b..627e6ae5f1 100644 --- a/app/Importer/LicenseImporter.php +++ b/app/Importer/LicenseImporter.php @@ -35,21 +35,22 @@ class LicenseImporter extends ItemImporter ->where('serial', $this->item['serial']) ->first(); if ($license) { - if (!$this->updating) { - $this->log('A matching License ' . $this->item['name'] . 'with serial ' . $this->item['serial'] . ' already exists'); + if (! $this->updating) { + $this->log('A matching License '.$this->item['name'].'with serial '.$this->item['serial'].' already exists'); + return; } - $this->log("Updating License"); + $this->log('Updating License'); $editingLicense = true; } else { - $this->log("No Matching License, Creating a new one"); + $this->log('No Matching License, Creating a new one'); $license = new License; } $asset_tag = $this->item['asset_tag'] = $this->findCsvMatch($row, 'asset_tag'); // used for checkout out to an asset. $this->item['expiration_date'] = $this->findCsvMatch($row, 'expiration_date'); - $this->item['license_email'] = $this->findCsvMatch($row, "license_email"); - $this->item['license_name'] = $this->findCsvMatch($row, "license_name"); + $this->item['license_email'] = $this->findCsvMatch($row, 'license_email'); + $this->item['license_name'] = $this->findCsvMatch($row, 'license_name'); $this->item['maintained'] = $this->findCsvMatch($row, 'maintained'); $this->item['purchase_order'] = $this->findCsvMatch($row, 'purchase_order'); $this->item['reassignable'] = $this->findCsvMatch($row, 'reassignable'); @@ -65,7 +66,7 @@ class LicenseImporter extends ItemImporter // $license->unsetEventDispatcher(); if ($license->save()) { $license->logCreate('Imported using csv importer'); - $this->log('License ' . $this->item["name"] . ' with serial number ' . $this->item['serial'] . ' was created'); + $this->log('License '.$this->item['name'].' with serial number '.$this->item['serial'].' was created'); // Lets try to checkout seats if the fields exist and we have seats. if ($license->seats > 0) { @@ -85,8 +86,9 @@ class LicenseImporter extends ItemImporter $targetLicense->save(); } } + return; } - $this->logError($license, 'License "' . $this->item['name'].'"'); + $this->logError($license, 'License "'.$this->item['name'].'"'); } } diff --git a/app/Importer/UserImporter.php b/app/Importer/UserImporter.php index 7adaa3a086..37d95688bf 100644 --- a/app/Importer/UserImporter.php +++ b/app/Importer/UserImporter.php @@ -12,8 +12,6 @@ use App\Notifications\WelcomeNotification; * App\Importer.php. [ALG] * * Class UserImporter - * @package App\Importer - * */ class UserImporter extends ItemImporter { @@ -52,20 +50,21 @@ class UserImporter extends ItemImporter $this->item['city'] = $this->findCsvMatch($row, 'city'); $this->item['state'] = $this->findCsvMatch($row, 'state'); $this->item['country'] = $this->findCsvMatch($row, 'country'); - $this->item['activated'] = ($this->fetchHumanBoolean($this->findCsvMatch($row, 'activated')) == 1) ? '1' : 0; + $this->item['activated'] = ($this->fetchHumanBoolean($this->findCsvMatch($row, 'activated')) == 1) ? '1' : 0; $this->item['employee_num'] = $this->findCsvMatch($row, 'employee_num'); $this->item['department_id'] = $this->createOrFetchDepartment($this->findCsvMatch($row, 'department')); $this->item['manager_id'] = $this->fetchManager($this->findCsvMatch($row, 'manager_first_name'), $this->findCsvMatch($row, 'manager_last_name')); $user_department = $this->findCsvMatch($row, 'department'); if ($this->shouldUpdateField($user_department)) { - $this->item["department_id"] = $this->createOrFetchDepartment($user_department); + $this->item['department_id'] = $this->createOrFetchDepartment($user_department); } $user = User::where('username', $this->item['username'])->first(); if ($user) { - if (!$this->updating) { - $this->log('A matching User ' . $this->item["name"] . ' already exists. '); - \Log::debug('A matching User ' . $this->item["name"] . ' already exists. '); + if (! $this->updating) { + $this->log('A matching User '.$this->item['name'].' already exists. '); + \Log::debug('A matching User '.$this->item['name'].' already exists. '); + return; } $this->log('Updating User'); @@ -75,21 +74,19 @@ class UserImporter extends ItemImporter return; } - - // This needs to be applied after the update logic, otherwise we'll overwrite user passwords // Issue #5408 $this->item['password'] = bcrypt($this->tempPassword); - $this->log("No matching user, creating one"); + $this->log('No matching user, creating one'); $user = new User(); $user->fill($this->sanitizeItemForStoring($user)); if ($user->save()) { // $user->logCreate('Imported using CSV Importer'); - $this->log("User " . $this->item["name"] . ' was created'); + $this->log('User '.$this->item['name'].' was created'); - if(($user->email) && ($user->activated=='1')) { + if (($user->email) && ($user->activated == '1')) { $data = [ 'email' => $user->email, 'username' => $user->username, @@ -104,14 +101,14 @@ class UserImporter extends ItemImporter } $user = null; $this->item = null; + return; } $this->logError($user, 'User'); - return; } - /** + /** * Fetch an existing department, or create new if it doesn't exist * * @author Daniel Melzter @@ -123,7 +120,8 @@ class UserImporter extends ItemImporter { $department = Department::where(['name' => $department_name])->first(); if ($department) { - $this->log('A matching department ' . $department_name . ' already exists'); + $this->log('A matching department '.$department_name.' already exists'); + return $department->id; } @@ -132,15 +130,18 @@ class UserImporter extends ItemImporter $department->user_id = $this->user_id; if ($department->save()) { - $this->log('department ' . $department_name . ' was created'); + $this->log('department '.$department_name.' was created'); + return $department->id; } $this->logError($department, 'Department'); + return null; } - public function sendWelcome($send = true) { + public function sendWelcome($send = true) + { $this->send_welcome = $send; } } diff --git a/app/Listeners/CheckoutableListener.php b/app/Listeners/CheckoutableListener.php index ba21790f94..c8acd65f11 100644 --- a/app/Listeners/CheckoutableListener.php +++ b/app/Listeners/CheckoutableListener.php @@ -23,15 +23,15 @@ use Illuminate\Support\Facades\Notification; class CheckoutableListener { - /** * Notify the user about the checked out checkoutable */ - public function onCheckedOut($event) { + public function onCheckedOut($event) + { /** * When the item wasn't checked out to a user, we can't send notifications */ - if(! $event->checkedOutTo instanceof User) { + if (! $event->checkedOutTo instanceof User) { return; } @@ -40,7 +40,7 @@ class CheckoutableListener */ $acceptance = $this->getCheckoutAcceptance($event); - if(!$event->checkedOutTo->locale){ + if (! $event->checkedOutTo->locale) { Notification::locale(Setting::getSettings()->locale)->send( $this->getNotifiables($event), $this->getCheckoutNotification($event, $acceptance) @@ -56,15 +56,16 @@ class CheckoutableListener /** * Notify the user about the checked in checkoutable */ - public function onCheckedIn($event) { - + public function onCheckedIn($event) + { \Log::debug('checkin fired'); /** * When the item wasn't checked out to a user, we can't send notifications */ - if(!$event->checkedOutTo instanceof User) { + if (! $event->checkedOutTo instanceof User) { \Log::debug('checked out to not a user'); + return; } @@ -81,7 +82,7 @@ class CheckoutableListener } } \Log::debug('checked out to a user'); - if(!$event->checkedOutTo->locale){ + if (! $event->checkedOutTo->locale) { \Log::debug('Use default settings locale'); Notification::locale(Setting::getSettings()->locale)->send( $this->getNotifiables($event), @@ -102,8 +103,9 @@ class CheckoutableListener * @param Event $event * @return mixed */ - private function getCheckoutAcceptance($event) { - if (!$event->checkoutable->requireAcceptance()) { + private function getCheckoutAcceptance($event) + { + if (! $event->checkoutable->requireAcceptance()) { return null; } @@ -121,7 +123,8 @@ class CheckoutableListener * @param Event $event * @return Collection */ - private function getNotifiables($event) { + private function getNotifiables($event) + { $notifiables = collect(); /** @@ -145,7 +148,8 @@ class CheckoutableListener * @param CheckoutableCheckedIn $event * @return Notification */ - private function getCheckinNotification($event) { + private function getCheckinNotification($event) + { // $model = get_class($event->checkoutable); @@ -166,6 +170,7 @@ class CheckoutableListener } \Log::debug('Notification class: '.$notificationClass); + return new $notificationClass($event->checkoutable, $event->checkedOutTo, $event->checkedInBy, $event->note); } @@ -176,7 +181,8 @@ class CheckoutableListener * @param CheckoutAcceptance $acceptance * @return Notification */ - private function getCheckoutNotification($event, $acceptance) { + private function getCheckoutNotification($event, $acceptance) + { $notificationClass = null; switch (get_class($event->checkoutable)) { @@ -205,14 +211,13 @@ class CheckoutableListener public function subscribe($events) { $events->listen( - 'App\Events\CheckoutableCheckedIn', + \App\Events\CheckoutableCheckedIn::class, 'App\Listeners\CheckoutableListener@onCheckedIn' ); $events->listen( - 'App\Events\CheckoutableCheckedOut', + \App\Events\CheckoutableCheckedOut::class, 'App\Listeners\CheckoutableListener@onCheckedOut' ); } - -} \ No newline at end of file +} diff --git a/app/Listeners/LogFailedLogin.php b/app/Listeners/LogFailedLogin.php index 663b4559c1..9ce326219d 100644 --- a/app/Listeners/LogFailedLogin.php +++ b/app/Listeners/LogFailedLogin.php @@ -40,6 +40,5 @@ class LogFailedLogin } catch (\Exception $e) { \Log::debug($e); } - } } diff --git a/app/Listeners/LogListener.php b/app/Listeners/LogListener.php index 5e9445183f..f337df60f5 100644 --- a/app/Listeners/LogListener.php +++ b/app/Listeners/LogListener.php @@ -22,16 +22,18 @@ use App\Models\LicenseSeat; class LogListener { - - public function onCheckoutableCheckedIn(CheckoutableCheckedIn $event) { + public function onCheckoutableCheckedIn(CheckoutableCheckedIn $event) + { $event->checkoutable->logCheckin($event->checkedOutTo, $event->note, $event->action_date); } - public function onCheckoutableCheckedOut(CheckoutableCheckedOut $event) { + public function onCheckoutableCheckedOut(CheckoutableCheckedOut $event) + { $event->checkoutable->logCheckout($event->note, $event->checkedOutTo, $event->checkoutable->last_checkout); - } + } - public function onCheckoutAccepted(CheckoutAccepted $event) { + public function onCheckoutAccepted(CheckoutAccepted $event) + { $logaction = new Actionlog(); $logaction->item()->associate($event->acceptance->checkoutable); @@ -40,14 +42,15 @@ class LogListener $logaction->action_type = 'accepted'; // TODO: log the actual license seat that was checked out - if($event->acceptance->checkoutable instanceof LicenseSeat) { + if ($event->acceptance->checkoutable instanceof LicenseSeat) { $logaction->item()->associate($event->acceptance->checkoutable->license); } - - $logaction->save(); - } - public function onCheckoutDeclined(CheckoutDeclined $event) { + $logaction->save(); + } + + public function onCheckoutDeclined(CheckoutDeclined $event) + { $logaction = new Actionlog(); $logaction->item()->associate($event->acceptance->checkoutable); $logaction->target()->associate($event->acceptance->assignedTo); @@ -55,12 +58,12 @@ class LogListener $logaction->action_type = 'declined'; // TODO: log the actual license seat that was checked out - if($event->acceptance->checkoutable instanceof LicenseSeat) { + if ($event->acceptance->checkoutable instanceof LicenseSeat) { $logaction->item()->associate($event->acceptance->checkoutable->license); } - $logaction->save(); - } + $logaction->save(); + } /** * Register the listeners for the subscriber. @@ -73,15 +76,14 @@ class LogListener 'CheckoutableCheckedIn', 'CheckoutableCheckedOut', 'CheckoutAccepted', - 'CheckoutDeclined', + 'CheckoutDeclined', ]; - foreach($list as $event) { + foreach ($list as $event) { $events->listen( - 'App\Events\\' . $event, - 'App\Listeners\LogListener@on' . $event + 'App\Events\\'.$event, + 'App\Listeners\LogListener@on'.$event ); - } + } } - } diff --git a/app/Listeners/LogSuccessfulLogin.php b/app/Listeners/LogSuccessfulLogin.php index 0fab5d00f6..3bfb3b6ffe 100644 --- a/app/Listeners/LogSuccessfulLogin.php +++ b/app/Listeners/LogSuccessfulLogin.php @@ -29,7 +29,6 @@ class LogSuccessfulLogin $now = new Carbon(); try { - DB::table('login_attempts')->insert( [ 'username' => $event->user->username, @@ -42,7 +41,5 @@ class LogSuccessfulLogin } catch (\Exception $e) { \Log::debug($e); } - - } } diff --git a/app/Models/Accessory.php b/app/Models/Accessory.php index 1abac4f68c..bbb0917e5d 100755 --- a/app/Models/Accessory.php +++ b/app/Models/Accessory.php @@ -1,9 +1,11 @@ 'boolean' - ]; + 'purchase_date' => 'datetime', + 'requestable' => 'boolean', ]; use Searchable; - use Acceptable; /** @@ -47,28 +49,27 @@ class Accessory extends SnipeModel 'company' => ['name'], 'manufacturer' => ['name'], 'supplier' => ['name'], - 'location' => ['name'] + 'location' => ['name'], ]; /** * Accessory validation rules */ - public $rules = array( + public $rules = [ 'name' => 'required|min:3|max:255', 'qty' => 'required|integer|min:1', 'category_id' => 'required|integer|exists:categories,id', 'company_id' => 'integer|nullable', 'min_amt' => 'integer|min:0|nullable', 'purchase_cost' => 'numeric|nullable', - ); - + ]; /** * 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 boolean + * @var bool */ protected $injectUniqueIdentifier = true; use ValidatingTrait; @@ -92,7 +93,7 @@ class Accessory extends SnipeModel 'image', 'qty', 'min_amt', - 'requestable' + 'requestable', ]; @@ -106,10 +107,9 @@ class Accessory extends SnipeModel */ public function supplier() { - return $this->belongsTo('\App\Models\Supplier', 'supplier_id'); + return $this->belongsTo(\App\Models\Supplier::class, 'supplier_id'); } - /** * Sets the requestable attribute on the accessory * @@ -123,7 +123,6 @@ class Accessory extends SnipeModel $value = null; } $this->attributes['requestable'] = filter_var($value, FILTER_VALIDATE_BOOLEAN); - return; } /** @@ -135,7 +134,7 @@ class Accessory extends SnipeModel */ public function company() { - return $this->belongsTo('\App\Models\Company', 'company_id'); + return $this->belongsTo(\App\Models\Company::class, 'company_id'); } /** @@ -147,7 +146,7 @@ class Accessory extends SnipeModel */ public function location() { - return $this->belongsTo('\App\Models\Location', 'location_id'); + return $this->belongsTo(\App\Models\Location::class, 'location_id'); } /** @@ -159,7 +158,7 @@ class Accessory extends SnipeModel */ public function category() { - return $this->belongsTo('\App\Models\Category', 'category_id')->where('category_type', '=', 'accessory'); + return $this->belongsTo(\App\Models\Category::class, 'category_id')->where('category_type', '=', 'accessory'); } /** @@ -171,7 +170,7 @@ class Accessory extends SnipeModel */ public function assetlog() { - return $this->hasMany('\App\Models\Actionlog', 'item_id')->where('item_type', Accessory::class)->orderBy('created_at', 'desc')->withTrashed(); + return $this->hasMany(\App\Models\Actionlog::class, 'item_id')->where('item_type', self::class)->orderBy('created_at', 'desc')->withTrashed(); } /** @@ -199,11 +198,10 @@ class Accessory extends SnipeModel * @since v5.0.0 * * @see \App\Http\Controllers\Api\AccessoriesController\checkedout() - * */ public function lastCheckout() { - return $this->assetlog()->where('action_type','=','checkout')->take(1); + return $this->assetlog()->where('action_type', '=', 'checkout')->take(1); } @@ -217,12 +215,13 @@ class Accessory extends SnipeModel * @since [v3.0] * @return string */ - public function getImageUrl() { + public function getImageUrl() + { if ($this->image) { return Storage::disk('public')->url(app('accessories_upload_path').$this->image); } - return false; + return false; } /** @@ -232,10 +231,9 @@ class Accessory extends SnipeModel * @since [v3.0] * @return \Illuminate\Database\Eloquent\Relations\Relation */ - public function users() { - return $this->belongsToMany('\App\Models\User', 'accessories_users', 'accessory_id', 'assigned_to')->withPivot('id', 'created_at', 'note')->withTrashed(); + return $this->belongsToMany(\App\Models\User::class, 'accessories_users', 'accessory_id', 'assigned_to')->withPivot('id', 'created_at', 'note')->withTrashed(); } /** @@ -247,7 +245,7 @@ class Accessory extends SnipeModel */ public function hasUsers() { - return $this->belongsToMany('\App\Models\User', 'accessories_users', 'accessory_id', 'assigned_to')->count(); + return $this->belongsToMany(\App\Models\User::class, 'accessories_users', 'accessory_id', 'assigned_to')->count(); } /** @@ -259,7 +257,7 @@ class Accessory extends SnipeModel */ public function manufacturer() { - return $this->belongsTo('\App\Models\Manufacturer', 'manufacturer_id'); + return $this->belongsTo(\App\Models\Manufacturer::class, 'manufacturer_id'); } /** @@ -268,7 +266,7 @@ class Accessory extends SnipeModel * * @author [A. Gianotto] [] * @since [v3.0] - * @return boolean + * @return bool */ public function checkin_email() { @@ -281,7 +279,7 @@ class Accessory extends SnipeModel * * @author [A. Gianotto] [] * @since [v3.0] - * @return boolean + * @return bool */ public function requireAcceptance() { @@ -298,14 +296,14 @@ class Accessory extends SnipeModel */ public function getEula() { - $Parsedown = new \Parsedown(); if ($this->category->eula_text) { return $Parsedown->text(e($this->category->eula_text)); - } elseif ((Setting::getSettings()->default_eula_text) && ($this->category->use_default_eula=='1')) { + } elseif ((Setting::getSettings()->default_eula_text) && ($this->category->use_default_eula == '1')) { return $Parsedown->text(e(Setting::getSettings()->default_eula_text)); } + return null; } @@ -321,6 +319,7 @@ class Accessory extends SnipeModel $checkedout = $this->users->count(); $total = $this->qty; $remaining = $total - $checkedout; + return $remaining; } diff --git a/app/Models/Actionlog.php b/app/Models/Actionlog.php index 7540568387..edbc9d9eef 100755 --- a/app/Models/Actionlog.php +++ b/app/Models/Actionlog.php @@ -1,8 +1,11 @@ ['name'] + 'company' => ['name'], ]; /** @@ -51,7 +55,7 @@ class Actionlog extends SnipeModel public static function boot() { parent::boot(); - static::creating(function (Actionlog $actionlog) { + static::creating(function (self $actionlog) { // If the admin is a superadmin, let's see if the target instead has a company. if (Auth::user() && Auth::user()->isSuperUser()) { if ($actionlog->target) { @@ -65,7 +69,6 @@ class Actionlog extends SnipeModel }); } - /** * Establishes the actionlog -> item relationship * @@ -87,7 +90,7 @@ class Actionlog extends SnipeModel */ public function company() { - return $this->hasMany('\App\Models\Company', 'id', 'company_id'); + return $this->hasMany(\App\Models\Company::class, 'id', 'company_id'); } /** @@ -99,10 +102,10 @@ class Actionlog extends SnipeModel */ public function itemType() { - if ($this->item_type == AssetModel::class) { - return "model"; + return 'model'; } + return camel_case(class_basename($this->item_type)); } @@ -116,12 +119,12 @@ class Actionlog extends SnipeModel public function targetType() { if ($this->target_type == User::class) { - return "user"; + return 'user'; } + return camel_case(class_basename($this->target_type)); } - /** * Establishes the actionlog -> uploads relationship * @@ -180,11 +183,11 @@ class Actionlog extends SnipeModel * @since [v3.0] * @return \Illuminate\Database\Eloquent\Relations\Relation */ - public function location() { - return $this->belongsTo('\App\Models\Location', 'location_id' )->withTrashed(); + public function location() + { + return $this->belongsTo(\App\Models\Location::class, 'location_id')->withTrashed(); } - /** * Check if the file exists, and if it does, force a download * @@ -194,25 +197,24 @@ class Actionlog extends SnipeModel */ public function get_src($type = 'assets', $fieldname = 'filename') { - if ($this->filename!='') { - $file = config('app.private_uploads') . '/' . $type . '/' . $this->{$fieldname}; + if ($this->filename != '') { + $file = config('app.private_uploads').'/'.$type.'/'.$this->{$fieldname}; + return $file; } + return false; } - - /** * Saves the log record with the action type * * @author [A. Gianotto] [] * @since [v3.0] - * @return boolean + * @return bool */ public function logaction($actiontype) { - $this->action_type = $actiontype; if ($this->save()) { @@ -229,8 +231,8 @@ class Actionlog extends SnipeModel * @since [v4.0] * @return int */ - public function daysUntilNextAudit($monthInterval = 12, $asset = null) { - + public function daysUntilNextAudit($monthInterval = 12, $asset = null) + { $now = Carbon::now(); $last_audit_date = $this->created_at; $next_audit = $last_audit_date->addMonth($monthInterval); @@ -252,8 +254,8 @@ class Actionlog extends SnipeModel * @since [v4.0] * @return \Datetime */ - public function calcNextAuditDate($monthInterval = 12, $asset = null) { - + public function calcNextAuditDate($monthInterval = 12, $asset = null) + { $last_audit_date = Carbon::parse($this->created_at); // If there is an asset-specific next date already given, if (($asset) && ($asset->next_audit_date)) { @@ -272,7 +274,6 @@ class Actionlog extends SnipeModel */ public function getListingOfActionLogsChronologicalOrder() { - return $this->all() ->where('action_type', '!=', 'uploaded') ->orderBy('item_id', 'asc') diff --git a/app/Models/Asset.php b/app/Models/Asset.php index fa506de7d9..8ed9ac3782 100644 --- a/app/Models/Asset.php +++ b/app/Models/Asset.php @@ -1,4 +1,5 @@ assigned_to = null; $this->assigned_type = null; $this->accepted = null; $this->save(); } - /** * The database table used by the model. * @@ -61,24 +63,18 @@ class Asset extends Depreciable * validation rules before attempting validation. If this property * is not set in the model it will default to true. * - * @var boolean + * @var bool */ protected $injectUniqueIdentifier = true; // We set these as protected dates so that they will be easily accessible via Carbon - protected $dates = [ - 'created_at', - 'updated_at', - 'deleted_at', - 'purchase_date', - 'last_checkout', - 'expected_checkin', - 'last_audit_date', - 'next_audit_date' - ]; - protected $casts = [ + 'purchase_date' => 'datetime', + 'last_checkout' => 'datetime', + 'expected_checkin' => 'datetime', + 'last_audit_date' => 'datetime', + 'next_audit_date' => 'datetime', 'model_id' => 'integer', 'status_id' => 'integer', 'company_id' => 'integer', @@ -154,7 +150,7 @@ class Asset extends Depreciable 'purchase_date', 'expected_checkin', 'next_audit_date', - 'last_audit_date' + 'last_audit_date', ]; /** @@ -173,7 +169,6 @@ class Asset extends Depreciable 'model.manufacturer' => ['name'], ]; - /** * This handles the custom field validation for assets * @@ -181,7 +176,7 @@ class Asset extends Depreciable */ public function save(array $params = []) { - if($this->model_id != '') { + if ($this->model_id != '') { $model = AssetModel::find($this->model_id); if (($model) && ($model->fieldset)) { @@ -192,7 +187,6 @@ class Asset extends Depreciable return parent::save($params); } - public function getDisplayNameAttribute() { return $this->present()->name(); @@ -211,6 +205,7 @@ class Asset extends Depreciable $purchase_date = \Carbon\Carbon::instance($this->attributes['purchase_date']); } $purchase_date->setTime(0, 0, 0); + return $purchase_date->addMonths((int) $this->attributes['warranty_months']); } @@ -227,7 +222,7 @@ class Asset extends Depreciable */ public function company() { - return $this->belongsTo('\App\Models\Company', 'company_id'); + return $this->belongsTo(\App\Models\Company::class, 'company_id'); } /** @@ -238,27 +233,24 @@ class Asset extends Depreciable * * @author [A. Gianotto] [] * @since [v3.0] - * @return boolean + * @return bool */ public function availableForCheckout() { // This asset is not currently assigned to anyone and is not deleted... - if ((!$this->assigned_to) && (!$this->deleted_at)) { + 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')) - { - + && ($this->assetstatus->deployable == '1')) { return true; } - } + return false; } - /** * Checks the asset out to the target * @@ -273,11 +265,11 @@ class Asset extends Depreciable * @param null $name * @return bool * @since [v3.0] - * @return boolean + * @return bool */ public function checkOut($target, $admin = null, $checkout_at = null, $expected_checkin = null, $note = null, $name = null, $location = null) { - if (!$target) { + if (! $target) { return false; } if ($this->is($target)) { @@ -292,7 +284,6 @@ class Asset extends Depreciable $this->assignedTo()->associate($target); - if ($name != null) { $this->name = $name; } @@ -309,9 +300,9 @@ class Asset extends Depreciable } if ($this->save()) { - if (is_integer($admin)){ + if (is_int($admin)) { $checkedOutBy = User::findOrFail($admin); - } elseif (get_class($admin) === 'App\Models\User') { + } elseif (get_class($admin) === \App\Models\User::class) { $checkedOutBy = $admin; } else { $checkedOutBy = Auth::user(); @@ -319,8 +310,10 @@ class Asset extends Depreciable event(new CheckoutableCheckedOut($this, $target, $checkedOutBy, $note)); $this->increment('checkout_counter', 1); + return true; } + return false; } @@ -336,9 +329,10 @@ class Asset extends Depreciable if ($this->assignedto) { $user_name = $this->assignedto->present()->name(); } else { - $user_name = "Unassigned"; + $user_name = 'Unassigned'; } - return $this->asset_tag . ' - ' . $this->name . ' (' . $user_name . ') ' . ($this->model) ? $this->model->name: ''; + + return $this->asset_tag.' - '.$this->name.' ('.$user_name.') '.($this->model) ? $this->model->name : ''; } /** @@ -363,7 +357,7 @@ class Asset extends Depreciable */ public function depreciation() { - return $this->model->belongsTo('\App\Models\Depreciation', 'depreciation_id'); + return $this->model->belongsTo(\App\Models\Depreciation::class, 'depreciation_id'); } @@ -376,10 +370,9 @@ class Asset extends Depreciable */ public function components() { - return $this->belongsToMany('\App\Models\Component', 'components_assets', 'asset_id', 'component_id')->withPivot('id', 'assigned_qty')->withTrashed(); + return $this->belongsToMany(\App\Models\Component::class, 'components_assets', 'asset_id', 'component_id')->withPivot('id', 'assigned_qty')->withTrashed(); } - /** * Get depreciation attribute from associated asset model * @@ -406,14 +399,13 @@ class Asset extends Depreciable */ public function uploads() { - return $this->hasMany('\App\Models\Actionlog', 'item_id') - ->where('item_type', '=', Asset::class) + return $this->hasMany(\App\Models\Actionlog::class, 'item_id') + ->where('item_type', '=', self::class) ->where('action_type', '=', 'uploaded') ->whereNotNull('filename') ->orderBy('created_at', 'desc'); } - /** * Determines whether the asset is checked out to a user * @@ -422,7 +414,7 @@ class Asset extends Depreciable * * @author [A. Gianotto] [] * @since [v4.0] - * @return boolean + * @return bool */ public function checkedOutToUser() { @@ -452,10 +444,9 @@ class Asset extends Depreciable */ public function assignedAssets() { - return $this->morphMany('App\Models\Asset', 'assigned', 'assigned_type', 'assigned_to')->withTrashed(); + return $this->morphMany(self::class, 'assigned', 'assigned_type', 'assigned_to')->withTrashed(); } - /** * Get the asset's location based on the assigned user * @@ -465,17 +456,17 @@ class Asset extends Depreciable * @since [v4.0] * @return \ArrayObject */ - public function assetLoc($iterations = 1,$first_asset = null) + public function assetLoc($iterations = 1, $first_asset = null) { - if (!empty($this->assignedType())) { + if (! empty($this->assignedType())) { if ($this->assignedType() == self::ASSET) { - if(!$first_asset) { - $first_asset=$this; + if (! $first_asset) { + $first_asset = $this; } - if($iterations>10) { - throw new \Exception("Asset assignment Loop for Asset ID: ".$first_asset->id); + if ($iterations > 10) { + throw new \Exception('Asset assignment Loop for Asset ID: '.$first_asset->id); } - $assigned_to=Asset::find($this->assigned_to); //have to do this this way because otherwise it errors + $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 @@ -484,7 +475,6 @@ class Asset extends Depreciable if ($this->assignedTo) { return $this->assignedTo; } - } if ($this->assignedType() == self::USER) { if (($this->assignedTo) && $this->assignedTo->userLoc) { @@ -492,10 +482,9 @@ class Asset extends Depreciable } //this makes no sense return $this->defaultLoc; - + } } - } return $this->defaultLoc; } @@ -520,7 +509,7 @@ class Asset extends Depreciable */ public function defaultLoc() { - return $this->belongsTo('\App\Models\Location', 'rtd_location_id'); + return $this->belongsTo(\App\Models\Location::class, 'rtd_location_id'); } /** @@ -535,15 +524,15 @@ class Asset extends Depreciable */ public function getImageUrl() { - if ($this->image && !empty($this->image)) { + 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)) { + } elseif ($this->model && ! empty($this->model->image)) { return Storage::disk('public')->url(app('models_upload_path').e($this->model->image)); } + return false; } - /** * Get the asset's logs * @@ -553,8 +542,8 @@ class Asset extends Depreciable */ public function assetlog() { - return $this->hasMany('\App\Models\Actionlog', 'item_id') - ->where('item_type', '=', Asset::class) + return $this->hasMany(\App\Models\Actionlog::class, 'item_id') + ->where('item_type', '=', self::class) ->orderBy('created_at', 'desc') ->withTrashed(); } @@ -603,7 +592,6 @@ class Asset extends Depreciable ->withTrashed(); } - /** * Get maintenances for this asset * @@ -613,7 +601,7 @@ class Asset extends Depreciable */ public function assetmaintenances() { - return $this->hasMany('\App\Models\AssetMaintenance', 'asset_id') + return $this->hasMany(\App\Models\AssetMaintenance::class, 'asset_id') ->orderBy('created_at', 'desc'); } @@ -626,11 +614,9 @@ class Asset extends Depreciable */ public function adminuser() { - return $this->belongsTo('\App\Models\User', 'user_id'); + return $this->belongsTo(\App\Models\User::class, 'user_id'); } - - /** * Establishes the asset -> status relationship * @@ -640,7 +626,7 @@ class Asset extends Depreciable */ public function assetstatus() { - return $this->belongsTo('\App\Models\Statuslabel', 'status_id'); + return $this->belongsTo(\App\Models\Statuslabel::class, 'status_id'); } /** @@ -652,7 +638,7 @@ class Asset extends Depreciable */ public function model() { - return $this->belongsTo('\App\Models\AssetModel', 'model_id')->withTrashed(); + return $this->belongsTo(\App\Models\AssetModel::class, 'model_id')->withTrashed(); } /** @@ -665,18 +651,17 @@ class Asset extends Depreciable */ public static function getExpiringWarrantee($days = 30) { - return Asset::where('archived', '=', '0') + return self::where('archived', '=', '0') ->whereNotNull('warranty_months') ->whereNotNull('purchase_date') ->whereNull('deleted_at') ->whereRaw(\DB::raw('DATE_ADD(`purchase_date`,INTERVAL `warranty_months` MONTH) <= DATE(NOW() + INTERVAL ' - . $days - . ' DAY) AND DATE_ADD(`purchase_date`,INTERVAL `warranty_months` MONTH) > NOW()')) + .$days + .' DAY) AND DATE_ADD(`purchase_date`,INTERVAL `warranty_months` MONTH) > NOW()')) ->orderBy('purchase_date', 'ASC') ->get(); } - /** * Establishes the asset -> assigned licenses relationship * @@ -686,7 +671,7 @@ class Asset extends Depreciable */ public function licenses() { - return $this->belongsToMany('\App\Models\License', 'license_seats', 'asset_id', 'license_id'); + return $this->belongsToMany(\App\Models\License::class, 'license_seats', 'asset_id', 'license_id'); } /** @@ -698,7 +683,7 @@ class Asset extends Depreciable */ public function licenseseats() { - return $this->hasMany('\App\Models\LicenseSeat', 'asset_id'); + return $this->hasMany(\App\Models\LicenseSeat::class, 'asset_id'); } /** @@ -710,7 +695,7 @@ class Asset extends Depreciable */ public function supplier() { - return $this->belongsTo('\App\Models\Supplier', 'supplier_id'); + return $this->belongsTo(\App\Models\Supplier::class, 'supplier_id'); } /** @@ -722,11 +707,9 @@ class Asset extends Depreciable */ public function location() { - return $this->belongsTo('\App\Models\Location', 'location_id'); + return $this->belongsTo(\App\Models\Location::class, 'location_id'); } - - /** * Get the next autoincremented asset tag * @@ -738,7 +721,6 @@ class Asset extends Depreciable { $settings = \App\Models\Setting::getSettings(); - if ($settings->auto_increment_assets == '1') { $temp_asset_tag = \DB::table('assets') ->where('physical', '=', '1') @@ -748,8 +730,9 @@ class Asset extends Depreciable $asset_tag = preg_replace('/^0*/', '', $asset_tag_digits); if ($settings->zerofill_count > 0) { - return $settings->auto_increment_prefix.Asset::zerofill($settings->next_auto_tag_base, $settings->zerofill_count); + return $settings->auto_increment_prefix.self::zerofill($settings->next_auto_tag_base, $settings->zerofill_count); } + return $settings->auto_increment_prefix.$settings->next_auto_tag_base; } else { return false; @@ -768,28 +751,23 @@ class Asset extends Depreciable */ public static function nextAutoIncrement($assets) { - $max = 1; foreach ($assets as $asset) { - $results = preg_match ( "/\d+$/" , $asset['asset_tag'], $matches); + $results = preg_match("/\d+$/", $asset['asset_tag'], $matches); - if ($results) - { + if ($results) { $number = $matches[0]; - if ($number > $max) - { + if ($number > $max) { $max = $number; } } } + return $max + 1; - } - - /** * Add zerofilling based on Settings * @@ -810,7 +788,7 @@ class Asset extends Depreciable * * @author [A. Gianotto] [] * @since [v4.0] - * @return boolean + * @return bool */ public function checkin_email() { @@ -822,14 +800,13 @@ class Asset extends Depreciable * * @author [A. Gianotto] [] * @since [v4.0] - * @return boolean + * @return bool */ public function requireAcceptance() { if (($this->model) && ($this->model->category)) { return $this->model->category->require_acceptance; } - } /** @@ -853,10 +830,10 @@ class Asset extends Depreciable return false; } } + return false; } - /** * ----------------------------------------------- * BEGIN QUERY SCOPES @@ -870,58 +847,52 @@ class Asset extends Depreciable * @param array $terms The search terms * @return \Illuminate\Database\Eloquent\Builder */ - public function advancedTextSearch(Builder $query, array $terms) { + public function advancedTextSearch(Builder $query, array $terms) + { /** * Assigned user */ - $query = $query->leftJoin('users as assets_users',function ($leftJoin) { - $leftJoin->on("assets_users.id", "=", "assets.assigned_to") - ->where("assets.assigned_type", "=", User::class); + $query = $query->leftJoin('users as assets_users', function ($leftJoin) { + $leftJoin->on('assets_users.id', '=', 'assets.assigned_to') + ->where('assets.assigned_type', '=', User::class); }); - foreach($terms as $term) { - + foreach ($terms as $term) { $query = $query ->orWhere('assets_users.first_name', 'LIKE', '%'.$term.'%') ->orWhere('assets_users.last_name', 'LIKE', '%'.$term.'%') ->orWhere('assets_users.username', 'LIKE', '%'.$term.'%') ->orWhereRaw('CONCAT('.DB::getTablePrefix().'assets_users.first_name," ",'.DB::getTablePrefix().'assets_users.last_name) LIKE ?', ["%$term%"]); - } /** * Assigned location */ - $query = $query->leftJoin('locations as assets_locations',function ($leftJoin) { - $leftJoin->on("assets_locations.id","=","assets.assigned_to") - ->where("assets.assigned_type","=",Location::class); + $query = $query->leftJoin('locations as assets_locations', function ($leftJoin) { + $leftJoin->on('assets_locations.id', '=', 'assets.assigned_to') + ->where('assets.assigned_type', '=', Location::class); }); - foreach($terms as $term) { - + foreach ($terms as $term) { $query = $query->orWhere('assets_locations.name', 'LIKE', '%'.$term.'%'); - } /** * Assigned assets */ - $query = $query->leftJoin('assets as assigned_assets',function ($leftJoin) { + $query = $query->leftJoin('assets as assigned_assets', function ($leftJoin) { $leftJoin->on('assigned_assets.id', '=', 'assets.assigned_to') - ->where('assets.assigned_type', '=', Asset::class); + ->where('assets.assigned_type', '=', self::class); }); - foreach($terms as $term) { - + foreach ($terms as $term) { $query = $query->orWhere('assigned_assets.name', 'LIKE', '%'.$term.'%'); - } return $query; } - /** * Query builder scope for hardware * @@ -929,7 +900,6 @@ class Asset extends Depreciable * * @return \Illuminate\Database\Query\Builder Modified query builder */ - public function scopeHardware($query) { return $query->where('physical', '=', '1'); @@ -942,7 +912,6 @@ class Asset extends Depreciable * * @return \Illuminate\Database\Query\Builder Modified query builder */ - public function scopePending($query) { return $query->whereHas('assetstatus', function ($query) { @@ -952,7 +921,6 @@ class Asset extends Depreciable }); } - /** * Query builder scope for searching location * @@ -960,20 +928,19 @@ class Asset extends Depreciable * * @return \Illuminate\Database\Query\Builder Modified query builder */ - public function scopeAssetsByLocation($query, $location) { return $query->where(function ($query) use ($location) { $query->whereHas('assignedTo', function ($query) use ($location) { $query->where([ ['users.location_id', '=', $location->id], - ['assets.assigned_type', '=', User::class] + ['assets.assigned_type', '=', User::class], ])->orWhere([ ['locations.id', '=', $location->id], - ['assets.assigned_type', '=', Location::class] + ['assets.assigned_type', '=', Location::class], ])->orWhere([ ['assets.rtd_location_id', '=', $location->id], - ['assets.assigned_type', '=', Asset::class] + ['assets.assigned_type', '=', self::class], ]); })->orWhere(function ($query) use ($location) { $query->where('assets.rtd_location_id', '=', $location->id); @@ -982,7 +949,6 @@ class Asset extends Depreciable }); } - /** * Query builder scope for RTD assets * @@ -990,7 +956,6 @@ class Asset extends Depreciable * * @return \Illuminate\Database\Query\Builder Modified query builder */ - public function scopeRTD($query) { return $query->whereNull('assets.assigned_to') @@ -1008,7 +973,6 @@ class Asset extends Depreciable * * @return \Illuminate\Database\Query\Builder Modified query builder */ - public function scopeUndeployable($query) { return $query->whereHas('assetstatus', function ($query) { @@ -1025,7 +989,6 @@ class Asset extends Depreciable * * @return \Illuminate\Database\Query\Builder Modified query builder */ - public function scopeNotArchived($query) { return $query->whereHas('assetstatus', function ($query) { @@ -1055,7 +1018,6 @@ class Asset extends Depreciable * * @return \Illuminate\Database\Query\Builder Modified query builder */ - public function scopeDueForAudit($query, $settings) { $interval = $settings->audit_warning_days ?? 0; @@ -1080,7 +1042,6 @@ class Asset extends Depreciable * * @return \Illuminate\Database\Query\Builder Modified query builder */ - public function scopeOverdueForAudit($query) { return $query->whereNotNull('assets.next_audit_date') @@ -1102,18 +1063,16 @@ class Asset extends Depreciable * * @return \Illuminate\Database\Query\Builder Modified query builder */ - public function scopeDueOrOverdueForAudit($query, $settings) { $interval = $settings->audit_warning_days ?? 0; return $query->whereNotNull('assets.next_audit_date') - ->whereRaw("DATE_SUB(".DB::getTablePrefix()."assets.next_audit_date, INTERVAL $interval DAY) <= '".Carbon::now()."'") + ->whereRaw('DATE_SUB('.DB::getTablePrefix()."assets.next_audit_date, INTERVAL $interval DAY) <= '".Carbon::now()."'") ->where('assets.archived', '=', 0) ->NotArchived(); } - /** * Query builder scope for Archived assets * @@ -1121,7 +1080,6 @@ class Asset extends Depreciable * * @return \Illuminate\Database\Query\Builder Modified query builder */ - public function scopeArchived($query) { return $query->whereHas('assetstatus', function ($query) { @@ -1138,7 +1096,6 @@ class Asset extends Depreciable * * @return \Illuminate\Database\Query\Builder Modified query builder */ - public function scopeDeployed($query) { return $query->where('assigned_to', '>', '0'); @@ -1151,7 +1108,6 @@ class Asset extends Depreciable * * @return \Illuminate\Database\Query\Builder Modified query builder */ - public function scopeRequestableAssets($query) { return Company::scopeCompanyables($query->where('requestable', '=', 1)) @@ -1162,7 +1118,6 @@ class Asset extends Depreciable }); } - /** * scopeInModelList * Get all assets in the provided listing of model ids @@ -1188,7 +1143,7 @@ class Asset extends Depreciable */ public function scopeNotYetAccepted($query) { - return $query->where("accepted", "=", "pending"); + return $query->where('accepted', '=', 'pending'); } /** @@ -1200,10 +1155,9 @@ class Asset extends Depreciable */ public function scopeRejected($query) { - return $query->where("accepted", "=", "rejected"); + return $query->where('accepted', '=', 'rejected'); } - /** * Query builder scope to get accepted assets * @@ -1213,7 +1167,7 @@ class Asset extends Depreciable */ public function scopeAccepted($query) { - return $query->where("accepted", "=", "accepted"); + return $query->where('accepted', '=', 'accepted'); } /** @@ -1228,15 +1182,15 @@ class Asset extends Depreciable { $search = explode(' OR ', $search); - return $query->leftJoin('users as assets_users',function ($leftJoin) { - $leftJoin->on("assets_users.id", "=", "assets.assigned_to") - ->where("assets.assigned_type", "=", User::class); - })->leftJoin('locations as assets_locations',function ($leftJoin) { - $leftJoin->on("assets_locations.id","=","assets.assigned_to") - ->where("assets.assigned_type","=",Location::class); - })->leftJoin('assets as assigned_assets',function ($leftJoin) { + return $query->leftJoin('users as assets_users', function ($leftJoin) { + $leftJoin->on('assets_users.id', '=', 'assets.assigned_to') + ->where('assets.assigned_type', '=', User::class); + })->leftJoin('locations as assets_locations', function ($leftJoin) { + $leftJoin->on('assets_locations.id', '=', 'assets.assigned_to') + ->where('assets.assigned_type', '=', Location::class); + })->leftJoin('assets as assigned_assets', function ($leftJoin) { $leftJoin->on('assigned_assets.id', '=', 'assets.assigned_to') - ->where('assets.assigned_type', '=', Asset::class); + ->where('assets.assigned_type', '=', self::class); })->where(function ($query) use ($search) { foreach ($search as $search) { $query->whereHas('model', function ($query) use ($search) { @@ -1266,8 +1220,7 @@ class Asset extends Depreciable ->orWhere('assets.order_number', 'LIKE', '%'.$search.'%') ->orWhere('assets.notes', 'LIKE', '%'.$search.'%'); } - - })->withTrashed()->whereNull("assets.deleted_at"); //workaround for laravel bug + })->withTrashed()->whereNull('assets.deleted_at'); //workaround for laravel bug } /** @@ -1281,17 +1234,14 @@ class Asset extends Depreciable */ public function scopeCheckedOutToTargetInDepartment($query, $search) { - return $query->leftJoin('users as assets_dept_users',function ($leftJoin) { - $leftJoin->on("assets_dept_users.id", "=", "assets.assigned_to") - ->where("assets.assigned_type", "=", User::class); + return $query->leftJoin('users as assets_dept_users', function ($leftJoin) { + $leftJoin->on('assets_dept_users.id', '=', 'assets.assigned_to') + ->where('assets.assigned_type', '=', User::class); })->where(function ($query) use ($search) { $query->where('assets_dept_users.department_id', '=', $search); - - })->withTrashed()->whereNull("assets.deleted_at"); //workaround for laravel bug + })->withTrashed()->whereNull('assets.deleted_at'); //workaround for laravel bug } - - /** * Query builder scope to search on text filters for complex Bootstrap Tables API * @@ -1304,60 +1254,59 @@ class Asset extends Depreciable { return $query->where(function ($query) use ($filter) { foreach ($filter as $key => $search_val) { + $fieldname = str_replace('custom_fields.', '', $key); - $fieldname = str_replace('custom_fields.','', $key) ; - - if ($fieldname =='asset_tag') { + if ($fieldname == 'asset_tag') { $query->where('assets.asset_tag', 'LIKE', '%'.$search_val.'%'); } - if ($fieldname =='name') { + if ($fieldname == 'name') { $query->where('assets.name', 'LIKE', '%'.$search_val.'%'); } - if ($fieldname =='product_key') { + if ($fieldname == 'product_key') { $query->where('assets.serial', 'LIKE', '%'.$search_val.'%'); } - if ($fieldname =='purchase_date') { + if ($fieldname == 'purchase_date') { $query->where('assets.purchase_date', 'LIKE', '%'.$search_val.'%'); } - if ($fieldname =='purchase_cost') { + if ($fieldname == 'purchase_cost') { $query->where('assets.purchase_cost', 'LIKE', '%'.$search_val.'%'); } - if ($fieldname =='notes') { + if ($fieldname == 'notes') { $query->where('assets.notes', 'LIKE', '%'.$search_val.'%'); } - if ($fieldname =='order_number') { + if ($fieldname == 'order_number') { $query->where('assets.order_number', 'LIKE', '%'.$search_val.'%'); } - if ($fieldname =='status_label') { + if ($fieldname == 'status_label') { $query->whereHas('assetstatus', function ($query) use ($search_val) { - $query->where('status_labels.name', 'LIKE', '%' . $search_val . '%'); + $query->where('status_labels.name', 'LIKE', '%'.$search_val.'%'); }); } - if ($fieldname =='location') { + if ($fieldname == 'location') { $query->whereHas('location', function ($query) use ($search_val) { - $query->where('locations.name', 'LIKE', '%' . $search_val . '%'); + $query->where('locations.name', 'LIKE', '%'.$search_val.'%'); }); } - if ($fieldname =='checkedout_to') { + if ($fieldname == 'checkedout_to') { $query->whereHas('assigneduser', function ($query) use ($search_val) { $query->where(function ($query) use ($search_val) { - $query->where('users.first_name', 'LIKE', '%' . $search_val . '%') - ->orWhere('users.last_name', 'LIKE', '%' . $search_val . '%'); + $query->where('users.first_name', 'LIKE', '%'.$search_val.'%') + ->orWhere('users.last_name', 'LIKE', '%'.$search_val.'%'); }); }); } - if ($fieldname =='manufacturer') { + if ($fieldname == 'manufacturer') { $query->whereHas('model', function ($query) use ($search_val) { $query->whereHas('manufacturer', function ($query) use ($search_val) { $query->where(function ($query) use ($search_val) { @@ -1367,47 +1316,46 @@ class Asset extends Depreciable }); } - if ($fieldname =='category') { + if ($fieldname == 'category') { $query->whereHas('model', function ($query) use ($search_val) { $query->whereHas('category', function ($query) use ($search_val) { $query->where(function ($query) use ($search_val) { - $query->where('categories.name', 'LIKE', '%' . $search_val . '%') - ->orWhere('models.name', 'LIKE', '%' . $search_val . '%') - ->orWhere('models.model_number', 'LIKE', '%' . $search_val . '%'); + $query->where('categories.name', 'LIKE', '%'.$search_val.'%') + ->orWhere('models.name', 'LIKE', '%'.$search_val.'%') + ->orWhere('models.model_number', 'LIKE', '%'.$search_val.'%'); }); }); }); } - if ($fieldname =='model') { + if ($fieldname == 'model') { $query->where(function ($query) use ($search_val) { $query->whereHas('model', function ($query) use ($search_val) { - $query->where('models.name', 'LIKE', '%' . $search_val . '%'); + $query->where('models.name', 'LIKE', '%'.$search_val.'%'); }); }); } - if ($fieldname =='model_number') { + if ($fieldname == 'model_number') { $query->where(function ($query) use ($search_val) { $query->whereHas('model', function ($query) use ($search_val) { - $query->where('models.model_number', 'LIKE', '%' . $search_val . '%'); + $query->where('models.model_number', 'LIKE', '%'.$search_val.'%'); }); }); } - - if ($fieldname =='company') { + if ($fieldname == 'company') { $query->where(function ($query) use ($search_val) { $query->whereHas('company', function ($query) use ($search_val) { - $query->where('companies.name', 'LIKE', '%' . $search_val . '%'); + $query->where('companies.name', 'LIKE', '%'.$search_val.'%'); }); }); } - if ($fieldname =='supplier') { + if ($fieldname == 'supplier') { $query->where(function ($query) use ($search_val) { $query->whereHas('supplier', function ($query) use ($search_val) { - $query->where('suppliers.name', 'LIKE', '%' . $search_val . '%'); + $query->where('suppliers.name', 'LIKE', '%'.$search_val.'%'); }); }); } @@ -1433,21 +1381,14 @@ class Asset extends Depreciable * against those relationships earlier in this method. * * - snipe - * */ - if (($fieldname!='category') && ($fieldname!='model_number') && ($fieldname!='rtd_location') && ($fieldname!='location') && ($fieldname!='supplier') - && ($fieldname!='status_label') && ($fieldname!='model') && ($fieldname!='company') && ($fieldname!='manufacturer')) { - $query->orWhere('assets.'.$fieldname, 'LIKE', '%' . $search_val . '%'); + if (($fieldname != 'category') && ($fieldname != 'model_number') && ($fieldname != 'rtd_location') && ($fieldname != 'location') && ($fieldname != 'supplier') + && ($fieldname != 'status_label') && ($fieldname != 'model') && ($fieldname != 'company') && ($fieldname != 'manufacturer')) { + $query->orWhere('assets.'.$fieldname, 'LIKE', '%'.$search_val.'%'); } - - - - }); - } - /** * Query builder scope to order on model * @@ -1474,7 +1415,6 @@ class Asset extends Depreciable return $query->join('models', 'assets.model_id', '=', 'models.id')->orderBy('models.model_number', $order); } - /** * Query builder scope to order on assigned user * @@ -1514,7 +1454,6 @@ class Asset extends Depreciable return $query->leftJoin('companies as company_sort', 'assets.company_id', '=', 'company_sort.id')->orderBy('company_sort.name', $order); } - /** * Query builder scope to return results of a category * @@ -1543,8 +1482,6 @@ class Asset extends Depreciable ->join('manufacturers', 'models.manufacturer_id', '=', 'manufacturers.id')->where('models.manufacturer_id', '=', $manufacturer_id); } - - /** * Query builder scope to order on category * @@ -1560,7 +1497,6 @@ class Asset extends Depreciable ->orderBy('category_order.name', $order); } - /** * Query builder scope to order on manufacturer * @@ -1601,7 +1537,6 @@ class Asset extends Depreciable return $query->leftJoin('locations as rtd_asset_locations', 'rtd_asset_locations.id', '=', 'assets.rtd_location_id')->orderBy('rtd_asset_locations.name', $order); } - /** * Query builder scope to order on supplier name * @@ -1630,10 +1565,8 @@ class Asset extends Depreciable $query->where('locations.id', '=', $search); }); }); - } - /** * Query builder scope to search on depreciation name * @param \Illuminate\Database\Query\Builder $query Query builder instance @@ -1645,8 +1578,5 @@ class Asset extends Depreciable { return $query->join('models', 'assets.model_id', '=', 'models.id') ->join('depreciations', 'models.depreciation_id', '=', 'depreciations.id')->where('models.depreciation_id', '=', $search); - } - - } diff --git a/app/Models/AssetMaintenance.php b/app/Models/AssetMaintenance.php index 580aa18e04..27273eefc4 100644 --- a/app/Models/AssetMaintenance.php +++ b/app/Models/AssetMaintenance.php @@ -1,8 +1,10 @@ 'datetime', + 'completion_date' => 'datetime', + ]; protected $table = 'asset_maintenances'; protected $rules = [ 'asset_id' => 'required|integer', @@ -30,21 +34,21 @@ class AssetMaintenance extends Model implements ICompanyableChild 'start_date' => 'required|date', 'completion_date' => 'nullable|date', 'notes' => 'string|nullable', - 'cost' => 'numeric|nullable' + 'cost' => 'numeric|nullable', ]; use Searchable; - + /** * The attributes that should be included when searching the model. - * + * * @var array */ protected $searchableAttributes = ['title', 'notes', 'asset_maintenance_type', 'cost', 'start_date', 'completion_date']; /** * The relations and their attributes that should be included when searching the model. - * + * * @var array */ protected $searchableRelations = [ @@ -52,22 +56,20 @@ class AssetMaintenance extends Model implements ICompanyableChild 'asset.model' => ['name', 'model_number'], ]; - public function getCompanyableParents() { - return [ 'asset' ]; + return ['asset']; } /** - * getImprovementOptions - * - * @return array - * @author Vincent Sposato - * @version v1.0 - */ + * getImprovementOptions + * + * @return array + * @author Vincent Sposato + * @version v1.0 + */ public static function getImprovementOptions() { - return [ trans('admin/asset_maintenances/general.maintenance') => trans('admin/asset_maintenances/general.maintenance'), trans('admin/asset_maintenances/general.repair') => trans('admin/asset_maintenances/general.repair'), @@ -92,7 +94,7 @@ class AssetMaintenance extends Model implements ICompanyableChild */ public function setCostAttribute($value) { - $value = Helper::ParseFloat($value); + $value = Helper::ParseFloat($value); if ($value == '0.0') { $value = null; } @@ -115,24 +117,23 @@ class AssetMaintenance extends Model implements ICompanyableChild */ public function setCompletionDateAttribute($value) { - if ($value == '' || $value == "0000-00-00") { + if ($value == '' || $value == '0000-00-00') { $value = null; } $this->attributes['completion_date'] = $value; } /** - * asset - * Get asset for this improvement - * - * @return mixed - * @author Vincent Sposato - * @version v1.0 - */ + * asset + * Get asset for this improvement + * + * @return mixed + * @author Vincent Sposato + * @version v1.0 + */ public function asset() { - - return $this->belongsTo('\App\Models\Asset', 'asset_id') + return $this->belongsTo(\App\Models\Asset::class, 'asset_id') ->withTrashed(); } @@ -145,25 +146,21 @@ class AssetMaintenance extends Model implements ICompanyableChild */ public function admin() { - - return $this->belongsTo('\App\Models\User', 'user_id') + return $this->belongsTo(\App\Models\User::class, 'user_id') ->withTrashed(); } public function supplier() { - - return $this->belongsTo('\App\Models\Supplier', 'supplier_id') + return $this->belongsTo(\App\Models\Supplier::class, 'supplier_id') ->withTrashed(); } - /** - * ----------------------------------------------- - * BEGIN QUERY SCOPES - * ----------------------------------------------- - **/ - + * ----------------------------------------------- + * BEGIN QUERY SCOPES + * ----------------------------------------------- + **/ /** * Query builder scope to order on admin user @@ -207,6 +204,4 @@ class AssetMaintenance extends Model implements ICompanyableChild return $query->leftJoin('assets', 'asset_maintenances.asset_id', '=', 'assets.id') ->orderBy('assets.name', $order); } - - } diff --git a/app/Models/AssetModel.php b/app/Models/AssetModel.php index 1bb7902fda..7968f84085 100755 --- a/app/Models/AssetModel.php +++ b/app/Models/AssetModel.php @@ -1,8 +1,10 @@ 'required|min:1|max:255', 'model_number' => 'max:255|nullable', 'category_id' => 'required|integer|exists:categories,id', 'manufacturer_id' => 'required|integer|exists:manufacturers,id', 'eol' => 'integer:min:0|max:240|nullable', - ); + ]; /** - * 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 boolean - */ + * 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; use ValidatingTrait; @@ -49,6 +52,7 @@ class AssetModel extends SnipeModel $this->attributes['eol'] = $value; } + /** * The attributes that are mass assignable. * @@ -68,17 +72,17 @@ class AssetModel extends SnipeModel ]; use Searchable; - + /** * The attributes that should be included when searching the model. - * + * * @var array */ protected $searchableAttributes = ['name', 'model_number', 'notes', 'eol']; /** * The relations and their attributes that should be included when searching the model. - * + * * @var array */ protected $searchableRelations = [ @@ -87,7 +91,6 @@ class AssetModel extends SnipeModel 'manufacturer' => ['name'], ]; - /** * Establishes the model -> assets relationship * @@ -97,7 +100,7 @@ class AssetModel extends SnipeModel */ public function assets() { - return $this->hasMany('\App\Models\Asset', 'model_id'); + return $this->hasMany(\App\Models\Asset::class, 'model_id'); } /** @@ -109,7 +112,7 @@ class AssetModel extends SnipeModel */ public function category() { - return $this->belongsTo('\App\Models\Category', 'category_id'); + return $this->belongsTo(\App\Models\Category::class, 'category_id'); } /** @@ -121,10 +124,9 @@ class AssetModel extends SnipeModel */ public function depreciation() { - return $this->belongsTo('\App\Models\Depreciation', 'depreciation_id'); + return $this->belongsTo(\App\Models\Depreciation::class, 'depreciation_id'); } - /** * Establishes the model -> manufacturer relationship * @@ -134,7 +136,7 @@ class AssetModel extends SnipeModel */ public function manufacturer() { - return $this->belongsTo('\App\Models\Manufacturer', 'manufacturer_id'); + return $this->belongsTo(\App\Models\Manufacturer::class, 'manufacturer_id'); } /** @@ -146,7 +148,7 @@ class AssetModel extends SnipeModel */ public function fieldset() { - return $this->belongsTo('\App\Models\CustomFieldset', 'fieldset_id'); + return $this->belongsTo(\App\Models\CustomFieldset::class, 'fieldset_id'); } /** @@ -158,10 +160,9 @@ class AssetModel extends SnipeModel */ public function defaultValues() { - return $this->belongsToMany('\App\Models\CustomField', 'models_custom_fields')->withPivot('default_value'); + return $this->belongsToMany(\App\Models\CustomField::class, 'models_custom_fields')->withPivot('default_value'); } - /** * Gets the full url for the image * @@ -171,19 +172,20 @@ class AssetModel extends SnipeModel * @since [v2.0] * @return \Illuminate\Database\Eloquent\Relations\Relation */ - public function getImageUrl() { + public function getImageUrl() + { if ($this->image) { return Storage::disk('public')->url(app('models_upload_path').$this->image); } + return false; } /** - * ----------------------------------------------- - * BEGIN QUERY SCOPES - * ----------------------------------------------- - **/ - + * ----------------------------------------------- + * BEGIN QUERY SCOPES + * ----------------------------------------------- + **/ /** * scopeInCategory @@ -198,7 +200,6 @@ class AssetModel extends SnipeModel */ public function scopeInCategory($query, array $categoryIdListing) { - return $query->whereIn('category_id', $categoryIdListing); } @@ -214,9 +215,8 @@ class AssetModel extends SnipeModel */ public function scopeRequestableModels($query) { - return $query->where('requestable', '1'); - } + } /** * Query builder scope to search on text, including catgeory and manufacturer name @@ -228,7 +228,6 @@ class AssetModel extends SnipeModel */ public function scopeSearchByManufacturerOrCat($query, $search) { - return $query->where('models.name', 'LIKE', "%$search%") ->orWhere('model_number', 'LIKE', "%$search%") ->orWhere(function ($query) use ($search) { @@ -241,7 +240,6 @@ class AssetModel extends SnipeModel $query->where('manufacturers.name', 'LIKE', '%'.$search.'%'); }); }); - } /** @@ -269,6 +267,4 @@ class AssetModel extends SnipeModel { return $query->leftJoin('categories', 'models.category_id', '=', 'categories.id')->orderBy('categories.name', $order); } - - } diff --git a/app/Models/Category.php b/app/Models/Category.php index ad21f15b48..36cad63ec7 100755 --- a/app/Models/Category.php +++ b/app/Models/Category.php @@ -1,9 +1,11 @@ 'integer', ]; - /** - * Category validation rules - */ - public $rules = array( + * Category validation rules + */ + public $rules = [ 'user_id' => 'numeric|nullable', 'name' => 'required|min:1|max:255|unique_undeleted', 'require_acceptance' => 'boolean', 'use_default_eula' => 'boolean', 'category_type' => 'required|in:asset,accessory,consumable,component,license', - ); + ]; /** - * 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 boolean - */ + * 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; use ValidatingTrait; use UniqueUndeletedTrait; - /** * The attributes that are mass assignable. * @@ -85,7 +86,6 @@ class Category extends SnipeModel */ protected $searchableRelations = []; - /** * Checks if category can be deleted * @@ -95,8 +95,8 @@ class Category extends SnipeModel */ public function isDeletable() { - return (Gate::allows('delete', $this) - && ($this->itemCount() == 0)); + return Gate::allows('delete', $this) + && ($this->itemCount() == 0); } /** @@ -108,7 +108,7 @@ class Category extends SnipeModel */ public function accessories() { - return $this->hasMany('\App\Models\Accessory'); + return $this->hasMany(\App\Models\Accessory::class); } /** @@ -120,7 +120,7 @@ class Category extends SnipeModel */ public function licenses() { - return $this->hasMany('\App\Models\License'); + return $this->hasMany(\App\Models\License::class); } /** @@ -132,7 +132,7 @@ class Category extends SnipeModel */ public function consumables() { - return $this->hasMany('\App\Models\Consumable'); + return $this->hasMany(\App\Models\Consumable::class); } /** @@ -144,7 +144,7 @@ class Category extends SnipeModel */ public function components() { - return $this->hasMany('\App\Models\Component'); + return $this->hasMany(\App\Models\Component::class); } /** @@ -168,6 +168,7 @@ class Category extends SnipeModel case 'license': return $this->licenses()->count(); } + return '0'; } @@ -180,7 +181,7 @@ class Category extends SnipeModel */ public function assets() { - return $this->hasManyThrough('\App\Models\Asset', '\App\Models\AssetModel', 'category_id', 'model_id'); + return $this->hasManyThrough(\App\Models\Asset::class, \App\Models\AssetModel::class, 'category_id', 'model_id'); } /** @@ -192,7 +193,7 @@ class Category extends SnipeModel */ public function models() { - return $this->hasMany('\App\Models\AssetModel', 'category_id'); + return $this->hasMany(\App\Models\AssetModel::class, 'category_id'); } /** @@ -205,20 +206,17 @@ class Category extends SnipeModel */ public function getEula() { - $Parsedown = new \Parsedown(); if ($this->eula_text) { return $Parsedown->text(e($this->eula_text)); - } elseif ((Setting::getSettings()->default_eula_text) && ($this->use_default_eula=='1')) { + } elseif ((Setting::getSettings()->default_eula_text) && ($this->use_default_eula == '1')) { return $Parsedown->text(e(Setting::getSettings()->default_eula_text)); } else { return null; } - } - /** * ----------------------------------------------- * BEGIN QUERY SCOPES @@ -233,10 +231,8 @@ class Category extends SnipeModel * @param \Illuminate\Database\Query\Builder $query Query builder instance * @return \Illuminate\Database\Query\Builder Modified query builder */ - public function scopeRequiresAcceptance($query) { - return $query->where('require_acceptance', '=', true); } } diff --git a/app/Models/CheckoutAcceptance.php b/app/Models/CheckoutAcceptance.php index 4bbe0af164..cc6ca37fd4 100644 --- a/app/Models/CheckoutAcceptance.php +++ b/app/Models/CheckoutAcceptance.php @@ -8,80 +8,79 @@ use Illuminate\Database\Eloquent\SoftDeletes; class CheckoutAcceptance extends Model { + use SoftDeletes; - use SoftDeletes; - - /** - * The attributes that should be mutated to dates. - * - * @var array - */ - protected $dates = [ - 'accepted_at', - 'declined_at', - 'deleted_at' + protected $casts = [ + 'accepted_at' => 'datetime', + 'declined_at' => 'datetime', ]; /** * The resource that was is out - * + * * @return Illuminate\Database\Eloquent\Relations\MorphTo */ - public function checkoutable() { - return $this->morphTo(); + public function checkoutable() + { + return $this->morphTo(); } /** * The user that the checkoutable was checked out to - * + * * @return Illuminate\Database\Eloquent\Relations\BelongsTo */ - public function assignedTo() { - return $this->belongsTo(User::class); + public function assignedTo() + { + return $this->belongsTo(User::class); } /** * Is this checkout acceptance pending? - * - * @return boolean + * + * @return bool */ - public function isPending() { + public function isPending() + { return $this->accepted_at == null && $this->declined_at == null; } /** * Was the checkoutable checked out to this user? - * + * * @param User $user - * @return boolean + * @return bool */ - public function isCheckedOutTo(User $user) { + public function isCheckedOutTo(User $user) + { return $this->assignedTo->is($user); } /** * Accept the checkout acceptance - * + * * @param string $signature_filename */ - public function accept($signature_filename) { - $this->accepted_at = now(); + public function accept($signature_filename) + { + $this->accepted_at = now(); $this->signature_filename = $signature_filename; $this->save(); /** * Update state for the checked out item */ - $this->checkoutable->acceptedCheckout($this->assignedTo, $signature_filename); + $this->checkoutable->acceptedCheckout($this->assignedTo, $signature_filename); } /** * Decline the checkout acceptance - * + * * @param string $signature_filename */ - public function decline($signature_filename) { - $this->declined_at = now(); + public function decline($signature_filename) + { + $this->declined_at = now(); $this->signature_filename = $signature_filename; $this->save(); @@ -89,7 +88,7 @@ class CheckoutAcceptance extends Model * Update state for the checked out item */ $this->checkoutable->declinedCheckout($this->assignedTo, $signature_filename); - } + } /** * Filter checkout acceptences by the user @@ -97,7 +96,8 @@ class CheckoutAcceptance extends Model * @param User $user * @return \Illuminate\Database\Eloquent\Builder */ - public function scopeForUser(Builder $query, User $user) { + public function scopeForUser(Builder $query, User $user) + { return $query->where('assigned_to_id', $user->id); } @@ -106,7 +106,8 @@ class CheckoutAcceptance extends Model * @param Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ - public function scopePending(Builder $query) { + public function scopePending(Builder $query) + { return $query->whereNull('accepted_at')->whereNull('declined_at'); } } diff --git a/app/Models/CheckoutRequest.php b/app/Models/CheckoutRequest.php index 462af447e9..26abdd301e 100644 --- a/app/Models/CheckoutRequest.php +++ b/app/Models/CheckoutRequest.php @@ -1,6 +1,7 @@ itemType() == "asset") { + if ($this->itemType() == 'asset') { return $this->itemRequested()->present()->name(); } - return $this->itemRequested()->name; + return $this->itemRequested()->name; } } diff --git a/app/Models/Company.php b/app/Models/Company.php index 99f6e3851d..fadc2a1974 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -1,10 +1,12 @@ 'required|min:1|max:255|unique:companies,name' + 'name' => 'required|min:1|max:255|unique:companies,name', ]; - protected $presenter = 'App\Presenters\CompanyPresenter'; + protected $presenter = \App\Presenters\CompanyPresenter::class; use Presentable; /** @@ -30,11 +34,10 @@ final class Company extends SnipeModel * validation rules before attempting validation. If this property * is not set in the model it will default to true. * - * @var boolean + * @var bool */ protected $injectUniqueIdentifier = true; use ValidatingTrait; - use Searchable; /** @@ -70,7 +73,7 @@ final class Company extends SnipeModel } } - private static function scopeCompanyablesDirectly($query, $column = 'company_id', $table_name = null ) + private static function scopeCompanyablesDirectly($query, $column = 'company_id', $table_name = null) { if (Auth::user()) { $company_id = Auth::user()->company_id; @@ -80,7 +83,7 @@ final class Company extends SnipeModel $table = ($table_name) ? $table_name."." : $query->getModel()->getTable()."."; - if(\Schema::hasColumn($query->getModel()->getTable(), $column)){ + if (\Schema::hasColumn($query->getModel()->getTable(), $column)) { return $query->where($table.$column, '=', $company_id); } else { return $query->join('users as users_comp', 'users_comp.id', 'user_id')->where('users_comp.company_id', '=', $company_id); @@ -100,7 +103,7 @@ final class Company extends SnipeModel public static function getIdForCurrentUser($unescaped_input) { - if (!static::isFullMultipleCompanySupportEnabled()) { + if (! static::isFullMultipleCompanySupportEnabled()) { return static::getIdFromInput($unescaped_input); } else { $current_user = Auth::user(); @@ -115,7 +118,6 @@ final class Company extends SnipeModel return static::getIdFromInput($unescaped_input); } } - } } @@ -123,27 +125,27 @@ final class Company extends SnipeModel { if (is_null($companyable)) { return false; - } elseif (!static::isFullMultipleCompanySupportEnabled()) { + } elseif (! static::isFullMultipleCompanySupportEnabled()) { return true; } else { if (Auth::user()) { $current_user_company_id = Auth::user()->company_id; $companyable_company_id = $companyable->company_id; - return ($current_user_company_id == null || $current_user_company_id == $companyable_company_id || Auth::user()->isSuperUser()); - } + return $current_user_company_id == null || $current_user_company_id == $companyable_company_id || Auth::user()->isSuperUser(); + } } } public static function isCurrentUserAuthorized() { - return ((!static::isFullMultipleCompanySupportEnabled()) || (Auth::user()->isSuperUser())); + return (! static::isFullMultipleCompanySupportEnabled()) || (Auth::user()->isSuperUser()); } public static function canManageUsersCompanies() { - return (!static::isFullMultipleCompanySupportEnabled() || Auth::user()->isSuperUser() || - Auth::user()->company_id == null); + return ! static::isFullMultipleCompanySupportEnabled() || Auth::user()->isSuperUser() || + Auth::user()->company_id == null; } /** @@ -153,7 +155,8 @@ final class Company extends SnipeModel * @since [v5.0] * @return bool */ - public function isDeletable() { + public function isDeletable() + { return Gate::allows('delete', $this) && ($this->assets()->count() === 0) && ($this->accessories()->count() === 0) @@ -164,17 +167,17 @@ final class Company extends SnipeModel public static function getIdForUser($unescaped_input) { - if (!static::isFullMultipleCompanySupportEnabled() || Auth::user()->isSuperUser()) { + if (! static::isFullMultipleCompanySupportEnabled() || Auth::user()->isSuperUser()) { return static::getIdFromInput($unescaped_input); } else { return static::getIdForCurrentUser($unescaped_input); } } - public static function scopeCompanyables($query, $column = 'company_id', $table_name = null ) + public static function scopeCompanyables($query, $column = 'company_id', $table_name = null) { // If not logged in and hitting this, assume we are on the command line and don't scope?' - if (!static::isFullMultipleCompanySupportEnabled() || (Auth::check() && Auth::user()->isSuperUser()) || (!Auth::check())) { + if (! static::isFullMultipleCompanySupportEnabled() || (Auth::check() && Auth::user()->isSuperUser()) || (! Auth::check())) { return $query; } else { return static::scopeCompanyablesDirectly($query, $column, $table_name); @@ -185,7 +188,7 @@ final class Company extends SnipeModel { if (count($companyable_names) == 0) { throw new Exception('No Companyable Children to scope'); - } elseif (!static::isFullMultipleCompanySupportEnabled() || (Auth::check() && Auth::user()->isSuperUser())) { + } elseif (! static::isFullMultipleCompanySupportEnabled() || (Auth::check() && Auth::user()->isSuperUser())) { return $query; } else { $f = function ($q) { @@ -199,6 +202,7 @@ final class Company extends SnipeModel $q2 = $q2->orWhereHas($companyable_names[$i], $f); } }); + return $q; } } @@ -217,6 +221,7 @@ final class Company extends SnipeModel { return $this->hasMany(License::class, 'company_id'); } + public function accessories() { return $this->hasMany(Accessory::class, 'company_id'); diff --git a/app/Models/CompanyableChildScope.php b/app/Models/CompanyableChildScope.php index e83eb18ed8..4077ebd596 100644 --- a/app/Models/CompanyableChildScope.php +++ b/app/Models/CompanyableChildScope.php @@ -1,4 +1,5 @@ getModel(); + return Company::scopeCompanyableChildren($model->getCompanyableParents(), $builder); } diff --git a/app/Models/CompanyableChildTrait.php b/app/Models/CompanyableChildTrait.php index 02682d0bab..1158c70e98 100644 --- a/app/Models/CompanyableChildTrait.php +++ b/app/Models/CompanyableChildTrait.php @@ -1,4 +1,5 @@ 'datetime', + ]; protected $table = 'components'; /** - * Category validation rules - */ - public $rules = array( + * Category validation rules + */ + public $rules = [ 'name' => 'required|min:3|max:255', 'qty' => 'required|integer|min:1', 'category_id' => 'required|integer|exists:categories,id', @@ -32,15 +37,15 @@ class Component extends SnipeModel 'min_amt' => 'integer|min:0|nullable', 'purchase_date' => 'date|nullable', 'purchase_cost' => 'numeric|nullable', - ); + ]; /** - * 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 boolean - */ + * 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; use ValidatingTrait; @@ -63,17 +68,17 @@ class Component extends SnipeModel ]; use Searchable; - + /** * The attributes that should be included when searching the model. - * + * * @var array */ protected $searchableAttributes = ['name', 'order_number', 'serial', 'purchase_cost', 'purchase_date']; /** * The relations and their attributes that should be included when searching the model. - * + * * @var array */ protected $searchableRelations = [ @@ -91,7 +96,7 @@ class Component extends SnipeModel */ public function location() { - return $this->belongsTo('\App\Models\Location', 'location_id'); + return $this->belongsTo(\App\Models\Location::class, 'location_id'); } /** @@ -103,7 +108,7 @@ class Component extends SnipeModel */ public function assets() { - return $this->belongsToMany('\App\Models\Asset', 'components_assets')->withPivot('id', 'assigned_qty', 'created_at', 'user_id'); + return $this->belongsToMany(\App\Models\Asset::class, 'components_assets')->withPivot('id', 'assigned_qty', 'created_at', 'user_id'); } /** @@ -117,7 +122,7 @@ class Component extends SnipeModel */ public function admin() { - return $this->belongsTo('\App\Models\User', 'user_id'); + return $this->belongsTo(\App\Models\User::class, 'user_id'); } /** @@ -129,7 +134,7 @@ class Component extends SnipeModel */ public function company() { - return $this->belongsTo('\App\Models\Company', 'company_id'); + return $this->belongsTo(\App\Models\Company::class, 'company_id'); } /** @@ -141,7 +146,7 @@ class Component extends SnipeModel */ public function category() { - return $this->belongsTo('\App\Models\Category', 'category_id'); + return $this->belongsTo(\App\Models\Category::class, 'category_id'); } /** @@ -153,7 +158,7 @@ class Component extends SnipeModel */ public function assetlog() { - return $this->hasMany('\App\Models\Actionlog', 'item_id')->where('item_type', Component::class)->orderBy('created_at', 'desc')->withTrashed(); + return $this->hasMany(\App\Models\Actionlog::class, 'item_id')->where('item_type', self::class)->orderBy('created_at', 'desc')->withTrashed(); } /** @@ -186,40 +191,39 @@ class Component extends SnipeModel } /** - * Query builder scope to order on company - * - * @param \Illuminate\Database\Query\Builder $query Query builder instance - * @param string $order Order - * - * @return \Illuminate\Database\Query\Builder Modified query builder - */ + * Query builder scope to order on company + * + * @param \Illuminate\Database\Query\Builder $query Query builder instance + * @param string $order Order + * + * @return \Illuminate\Database\Query\Builder Modified query builder + */ public function scopeOrderCategory($query, $order) { return $query->join('categories', 'components.category_id', '=', 'categories.id')->orderBy('categories.name', $order); } /** - * Query builder scope to order on company - * - * @param \Illuminate\Database\Query\Builder $query Query builder instance - * @param string $order Order - * - * @return \Illuminate\Database\Query\Builder Modified query builder - */ + * Query builder scope to order on company + * + * @param \Illuminate\Database\Query\Builder $query Query builder instance + * @param string $order Order + * + * @return \Illuminate\Database\Query\Builder Modified query builder + */ public function scopeOrderLocation($query, $order) { return $query->leftJoin('locations', 'components.location_id', '=', 'locations.id')->orderBy('locations.name', $order); } - /** - * Query builder scope to order on company - * - * @param \Illuminate\Database\Query\Builder $query Query builder instance - * @param string $order Order - * - * @return \Illuminate\Database\Query\Builder Modified query builder - */ + * Query builder scope to order on company + * + * @param \Illuminate\Database\Query\Builder $query Query builder instance + * @param string $order Order + * + * @return \Illuminate\Database\Query\Builder Modified query builder + */ public function scopeOrderCompany($query, $order) { return $query->leftJoin('companies', 'components.company_id', '=', 'companies.id')->orderBy('companies.name', $order); diff --git a/app/Models/Consumable.php b/app/Models/Consumable.php index 65214961fc..2d456e12c4 100644 --- a/app/Models/Consumable.php +++ b/app/Models/Consumable.php @@ -1,53 +1,53 @@ 'datetime', 'requestable' => 'boolean', 'category_id' => 'integer', 'company_id' => 'integer', 'qty' => 'integer', - 'min_amt' => 'integer', - ]; - - + 'min_amt' => 'integer', ]; /** - * Category validation rules - */ - public $rules = array( + * Category validation rules + */ + public $rules = [ 'name' => 'required|min:3|max:255', 'qty' => 'required|integer|min:0', 'category_id' => 'required|integer', 'company_id' => 'integer|nullable', 'min_amt' => 'integer|min:0|nullable', 'purchase_cost' => 'numeric|nullable', - ); + ]; /** - * 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 boolean - */ + * 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; use ValidatingTrait; @@ -68,27 +68,27 @@ class Consumable extends SnipeModel 'purchase_cost', 'purchase_date', 'qty', - 'requestable' + 'requestable', ]; use Searchable; - + /** * The attributes that should be included when searching the model. - * + * * @var array */ protected $searchableAttributes = ['name', 'order_number', 'purchase_cost', 'purchase_date', 'item_no', 'model_number']; /** * The relations and their attributes that should be included when searching the model. - * + * * @var array */ protected $searchableRelations = [ 'category' => ['name'], 'company' => ['name'], - 'location' => ['name'], + 'location' => ['name'], 'manufacturer' => ['name'], ]; @@ -111,7 +111,6 @@ class Consumable extends SnipeModel $value = null; } $this->attributes['requestable'] = filter_var($value, FILTER_VALIDATE_BOOLEAN); - return; } /** @@ -123,7 +122,7 @@ class Consumable extends SnipeModel */ public function admin() { - return $this->belongsTo('\App\Models\User', 'user_id'); + return $this->belongsTo(\App\Models\User::class, 'user_id'); } /** @@ -135,7 +134,7 @@ class Consumable extends SnipeModel */ public function consumableAssignments() { - return $this->hasMany('\App\Models\ConsumableAssignment'); + return $this->hasMany(\App\Models\ConsumableAssignment::class); } /** @@ -147,7 +146,7 @@ class Consumable extends SnipeModel */ public function company() { - return $this->belongsTo('\App\Models\Company', 'company_id'); + return $this->belongsTo(\App\Models\Company::class, 'company_id'); } /** @@ -159,7 +158,7 @@ class Consumable extends SnipeModel */ public function manufacturer() { - return $this->belongsTo('\App\Models\Manufacturer', 'manufacturer_id'); + return $this->belongsTo(\App\Models\Manufacturer::class, 'manufacturer_id'); } /** @@ -171,7 +170,7 @@ class Consumable extends SnipeModel */ public function location() { - return $this->belongsTo('\App\Models\Location', 'location_id'); + return $this->belongsTo(\App\Models\Location::class, 'location_id'); } /** @@ -183,10 +182,9 @@ class Consumable extends SnipeModel */ public function category() { - return $this->belongsTo('\App\Models\Category', 'category_id'); + return $this->belongsTo(\App\Models\Category::class, 'category_id'); } - /** * Establishes the component -> action logs relationship * @@ -196,7 +194,7 @@ class Consumable extends SnipeModel */ public function assetlog() { - return $this->hasMany('\App\Models\Actionlog', 'item_id')->where('item_type', Consumable::class)->orderBy('created_at', 'desc')->withTrashed(); + return $this->hasMany(\App\Models\Actionlog::class, 'item_id')->where('item_type', self::class)->orderBy('created_at', 'desc')->withTrashed(); } /** @@ -206,12 +204,13 @@ class Consumable extends SnipeModel * @since [v3.0] * @return string | false */ - public function getImageUrl() { + public function getImageUrl() + { if ($this->image) { return Storage::disk('public')->url(app('consumables_upload_path').$this->image); } - return false; + return false; } /** @@ -223,17 +222,16 @@ class Consumable extends SnipeModel */ public function users() { - return $this->belongsToMany('\App\Models\User', 'consumables_users', 'consumable_id', 'assigned_to')->withPivot('user_id')->withTrashed()->withTimestamps(); + return $this->belongsToMany(\App\Models\User::class, 'consumables_users', 'consumable_id', 'assigned_to')->withPivot('user_id')->withTrashed()->withTimestamps(); } - /** * Determine whether to send a checkin/checkout email based on * asset model category * * @author [A. Gianotto] [] * @since [v4.0] - * @return boolean + * @return bool */ public function checkin_email() { @@ -245,7 +243,7 @@ class Consumable extends SnipeModel * * @author [A. Gianotto] [] * @since [v4.0] - * @return boolean + * @return bool */ public function requireAcceptance() { @@ -262,17 +260,15 @@ class Consumable extends SnipeModel */ public function getEula() { - $Parsedown = new \Parsedown(); if ($this->category->eula_text) { return $Parsedown->text(e($this->category->eula_text)); - } elseif ((Setting::getSettings()->default_eula_text) && ($this->category->use_default_eula=='1')) { + } elseif ((Setting::getSettings()->default_eula_text) && ($this->category->use_default_eula == '1')) { return $Parsedown->text(e(Setting::getSettings()->default_eula_text)); } else { return null; } - } /** @@ -287,30 +283,31 @@ class Consumable extends SnipeModel $checkedout = $this->users->count(); $total = $this->qty; $remaining = $total - $checkedout; + return $remaining; } /** - * Query builder scope to order on company - * - * @param \Illuminate\Database\Query\Builder $query Query builder instance - * @param string $order Order - * - * @return \Illuminate\Database\Query\Builder Modified query builder - */ + * Query builder scope to order on company + * + * @param \Illuminate\Database\Query\Builder $query Query builder instance + * @param string $order Order + * + * @return \Illuminate\Database\Query\Builder Modified query builder + */ public function scopeOrderCategory($query, $order) { return $query->join('categories', 'consumables.category_id', '=', 'categories.id')->orderBy('categories.name', $order); } /** - * Query builder scope to order on location - * - * @param \Illuminate\Database\Query\Builder $query Query builder instance - * @param text $order Order - * - * @return \Illuminate\Database\Query\Builder Modified query builder - */ + * Query builder scope to order on location + * + * @param \Illuminate\Database\Query\Builder $query Query builder instance + * @param text $order Order + * + * @return \Illuminate\Database\Query\Builder Modified query builder + */ public function scopeOrderLocation($query, $order) { return $query->leftJoin('locations', 'consumables.location_id', '=', 'locations.id')->orderBy('locations.name', $order); @@ -329,15 +326,14 @@ class Consumable extends SnipeModel return $query->leftJoin('manufacturers', 'consumables.manufacturer_id', '=', 'manufacturers.id')->orderBy('manufacturers.name', $order); } - /** - * Query builder scope to order on company - * - * @param \Illuminate\Database\Query\Builder $query Query builder instance - * @param string $order Order - * - * @return \Illuminate\Database\Query\Builder Modified query builder - */ + * Query builder scope to order on company + * + * @param \Illuminate\Database\Query\Builder $query Query builder instance + * @param string $order Order + * + * @return \Illuminate\Database\Query\Builder Modified query builder + */ public function scopeOrderCompany($query, $order) { return $query->leftJoin('companies', 'consumables.company_id', '=', 'companies.id')->orderBy('companies.name', $order); diff --git a/app/Models/ConsumableAssignment.php b/app/Models/ConsumableAssignment.php index d8d684ca27..1e21a7f7d2 100644 --- a/app/Models/ConsumableAssignment.php +++ b/app/Models/ConsumableAssignment.php @@ -1,4 +1,5 @@ belongsTo('\App\Models\Consumable'); + return $this->belongsTo(\App\Models\Consumable::class); } public function user() { - return $this->belongsTo('\App\Models\User', 'assigned_to'); + return $this->belongsTo(\App\Models\User::class, 'assigned_to'); } public function admin() { - return $this->belongsTo('\App\Models\User', 'user_id'); + return $this->belongsTo(\App\Models\User::class, 'user_id'); } } diff --git a/app/Models/CustomField.php b/app/Models/CustomField.php index 76ae0dd0f1..0f58055254 100644 --- a/app/Models/CustomField.php +++ b/app/Models/CustomField.php @@ -1,8 +1,10 @@ ] * @since [v3.0] */ - public static $table_name = "assets"; + public static $table_name = 'assets'; /** * Convert the custom field's name property to a db-safe string. @@ -81,11 +84,11 @@ class CustomField extends Model * * @author [A. Gianotto] [] * @since [v3.4] - * @return String + * @return string */ public static function name_to_db_name($name) { - return "_snipeit_" . preg_replace("/[^a-zA-Z0-9]/", "_", strtolower($name)); + return '_snipeit_'.preg_replace('/[^a-zA-Z0-9]/', '_', strtolower($name)); } /** @@ -98,7 +101,7 @@ class CustomField extends Model * * @author [A. Gianotto] [] * @since [v3.4] - * @return Boolean + * @return bool */ public static function boot() { @@ -107,12 +110,12 @@ class CustomField extends Model // Column already exists on the assets table - nothing to do here. // This *shouldn't* happen in the wild. - if (Schema::hasColumn(CustomField::$table_name, $custom_field->convertUnicodeDbSlug())) { + if (Schema::hasColumn(self::$table_name, $custom_field->convertUnicodeDbSlug())) { return false; } // Update the column name in the assets table - Schema::table(CustomField::$table_name, function ($table) use ($custom_field) { + Schema::table(self::$table_name, function ($table) use ($custom_field) { $table->text($custom_field->convertUnicodeDbSlug())->nullable(); }); @@ -121,13 +124,11 @@ class CustomField extends Model $custom_field->save(); }); - self::updating(function ($custom_field) { // Column already exists on the assets table - nothing to do here. - if ($custom_field->isDirty("name")) { - - if (Schema::hasColumn(CustomField::$table_name, $custom_field->convertUnicodeDbSlug())) { + if ($custom_field->isDirty('name')) { + if (Schema::hasColumn(self::$table_name, $custom_field->convertUnicodeDbSlug())) { return true; } @@ -137,8 +138,8 @@ class CustomField extends Model $platform->registerDoctrineTypeMapping('enum', 'string'); // Rename the field if the name has changed - Schema::table(CustomField::$table_name, function ($table) use ($custom_field) { - $table->renameColumn($custom_field->convertUnicodeDbSlug($custom_field->getOriginal("name")), $custom_field->convertUnicodeDbSlug()); + Schema::table(self::$table_name, function ($table) use ($custom_field) { + $table->renameColumn($custom_field->convertUnicodeDbSlug($custom_field->getOriginal('name')), $custom_field->convertUnicodeDbSlug()); }); // Save the updated column name to the custom fields table @@ -147,13 +148,13 @@ class CustomField extends Model return true; } + return true; }); - // Drop the assets column if we've deleted it from custom fields self::deleting(function ($custom_field) { - return Schema::table(CustomField::$table_name, function ($table) use ($custom_field) { + return Schema::table(self::$table_name, function ($table) use ($custom_field) { $table->dropColumn($custom_field->convertUnicodeDbSlug()); }); }); @@ -168,7 +169,7 @@ class CustomField extends Model */ public function fieldset() { - return $this->belongsToMany('\App\Models\CustomFieldset'); + return $this->belongsToMany(\App\Models\CustomFieldset::class); } /** @@ -180,7 +181,7 @@ class CustomField extends Model */ public function user() { - return $this->belongsTo('\App\Models\User'); + return $this->belongsTo(\App\Models\User::class); } /** @@ -192,7 +193,7 @@ class CustomField extends Model */ public function defaultValues() { - return $this->belongsToMany('\App\Models\AssetModel', 'models_custom_fields')->withPivot('default_value'); + return $this->belongsToMany(\App\Models\AssetModel::class, 'models_custom_fields')->withPivot('default_value'); } /** @@ -217,11 +218,11 @@ class CustomField extends Model * @author [A. Gianotto] [] * @param $value string * @since [v3.0] - * @return boolean + * @return bool */ public function check_format($value) { - return preg_match('/^'.$this->attributes['format'].'$/', $value)===1; + return preg_match('/^'.$this->attributes['format'].'$/', $value) === 1; } /** @@ -270,9 +271,9 @@ class CustomField extends Model public function setFormatAttribute($value) { if (isset(self::PREDEFINED_FORMATS[$value])) { - $this->attributes['format']=self::PREDEFINED_FORMATS[$value]; + $this->attributes['format'] = self::PREDEFINED_FORMATS[$value]; } else { - $this->attributes['format']=$value; + $this->attributes['format'] = $value; } } @@ -286,17 +287,16 @@ class CustomField extends Model public function formatFieldValuesAsArray() { $result = []; - $arr = preg_split("/\\r\\n|\\r|\\n/", $this->field_values); + $arr = preg_split('/\\r\\n|\\r|\\n/', $this->field_values); - if (($this->element!='checkbox') && ($this->element!='radio')) { + if (($this->element != 'checkbox') && ($this->element != 'radio')) { $result[''] = 'Select '.strtolower($this->format); } - for ($x = 0; $x < count($arr); $x++) { $arr_parts = explode('|', $arr[$x]); - if ($arr_parts[0]!='') { - if (key_exists('1', $arr_parts)) { + if ($arr_parts[0] != '') { + if (array_key_exists('1', $arr_parts)) { $result[$arr_parts[0]] = $arr_parts[1]; } else { $result[$arr_parts[0]] = $arr_parts[0]; @@ -304,7 +304,6 @@ class CustomField extends Model } } - return $result; } @@ -313,17 +312,17 @@ class CustomField extends Model * * @author [A. Gianotto] [] * @since [v3.4] - * @return boolean + * @return bool */ public function isFieldDecryptable($string) { - if (($this->field_encrypted=='1') && ($string!='')) { + if (($this->field_encrypted == '1') && ($string != '')) { return true; } + return false; } - /** * Convert non-UTF-8 or weirdly encoded text into something that * won't break the database. @@ -337,52 +336,52 @@ class CustomField extends Model $name = $original ? $original : $this->name; $id = $this->id ? $this->id : 'xx'; - if (!function_exists('transliterator_transliterate')) { - $long_slug = '_snipeit_' . str_slug(\Patchwork\Utf8::utf8_encode(trim($name)), '_'); + if (! function_exists('transliterator_transliterate')) { + $long_slug = '_snipeit_'.str_slug(\Patchwork\Utf8::utf8_encode(trim($name)), '_'); } else { - $long_slug = '_snipeit_' . Utf8Slugger::slugify($name, '_'); + $long_slug = '_snipeit_'.Utf8Slugger::slugify($name, '_'); } - return substr($long_slug, 0, 50) . '_' . $id; + return substr($long_slug, 0, 50).'_'.$id; } /** - * Get validation rules for custom fields to use with Validator - * @author [V. Cordes] [] - * @param int $id - * @since [v4.1.10] - * @return array - */ + * Get validation rules for custom fields to use with Validator + * @author [V. Cordes] [] + * @param int $id + * @since [v4.1.10] + * @return array + */ public function validationRules($regex_format = null) { return [ - "name" => "required|unique:custom_fields", - "element" => [ - "required", - Rule::in(['text', 'listbox', 'textarea', 'checkbox', 'radio']) + 'name' => 'required|unique:custom_fields', + 'element' => [ + 'required', + Rule::in(['text', 'listbox', 'textarea', 'checkbox', 'radio']), ], 'format' => [ - Rule::in(array_merge(array_keys(CustomField::PREDEFINED_FORMATS), CustomField::PREDEFINED_FORMATS, [$regex_format])) + Rule::in(array_merge(array_keys(self::PREDEFINED_FORMATS), self::PREDEFINED_FORMATS, [$regex_format])), ], - 'field_encrypted' => "nullable|boolean" + 'field_encrypted' => 'nullable|boolean', ]; } /** * Check to see if there is a custom regex format type * @see https://github.com/snipe/snipe-it/issues/5896 - * - * @author Wes Hulette - * + * + * @author Wes Hulette + * * @since 5.0.0 - * + * * @return string */ public function getFormatType() { - if(stripos($this->format,'regex') === 0 && ($this->format !== self::PREDEFINED_FORMATS['MAC'])) { - return 'CUSTOM REGEX'; - } + if (stripos($this->format, 'regex') === 0 && ($this->format !== self::PREDEFINED_FORMATS['MAC'])) { + return 'CUSTOM REGEX'; + } return $this->format; } diff --git a/app/Models/CustomFieldset.php b/app/Models/CustomFieldset.php index 157c193b41..bcbe0b81d9 100644 --- a/app/Models/CustomFieldset.php +++ b/app/Models/CustomFieldset.php @@ -1,22 +1,25 @@ "required|unique:custom_fieldsets" + 'name' => 'required|unique:custom_fieldsets', ]; /** @@ -24,11 +27,10 @@ class CustomFieldset extends Model * validation rules before attempting validation. If this property * is not set in the model it will default to true. * - * @var boolean + * @var bool */ protected $injectUniqueIdentifier = true; - /** * Establishes the fieldset -> field relationship * @@ -38,7 +40,7 @@ class CustomFieldset extends Model */ public function fields() { - return $this->belongsToMany('\App\Models\CustomField')->withPivot(["required","order"])->orderBy("pivot_order"); + return $this->belongsToMany(\App\Models\CustomField::class)->withPivot(['required', 'order'])->orderBy('pivot_order'); } /** @@ -50,7 +52,7 @@ class CustomFieldset extends Model */ public function models() { - return $this->hasMany('\App\Models\AssetModel', "fieldset_id"); + return $this->hasMany(\App\Models\AssetModel::class, 'fieldset_id'); } /** @@ -62,7 +64,7 @@ class CustomFieldset extends Model */ public function user() { - return $this->belongsTo('\App\Models\User'); //WARNING - not all CustomFieldsets have a User!! + return $this->belongsTo(\App\Models\User::class); //WARNING - not all CustomFieldsets have a User!! } /** @@ -75,18 +77,19 @@ class CustomFieldset extends Model */ public function validation_rules() { - $rules=[]; + $rules = []; foreach ($this->fields as $field) { $rule = []; - if (($field->field_encrypted!='1') || - (($field->field_encrypted =='1') && (Gate::allows('admin')) )) { - $rule[] = ($field->pivot->required=='1') ? "required" : "nullable"; + if (($field->field_encrypted != '1') || + (($field->field_encrypted == '1') && (Gate::allows('admin')))) { + $rule[] = ($field->pivot->required == '1') ? 'required' : 'nullable'; } array_push($rule, $field->attributes['format']); - $rules[$field->db_column_name()]=$rule; + $rules[$field->db_column_name()] = $rule; } + return $rules; } } diff --git a/app/Models/Department.php b/app/Models/Department.php index 96aa4dd860..7be99d097b 100644 --- a/app/Models/Department.php +++ b/app/Models/Department.php @@ -4,16 +4,19 @@ namespace App\Models; use App\Http\Traits\UniqueUndeletedTrait; use App\Models\Traits\Searchable; +use Illuminate\Database\Eloquent\Factories\HasFactory; use Watson\Validating\ValidatingTrait; class Department extends SnipeModel { + use HasFactory; + /** * 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 boolean + * @var bool */ protected $injectUniqueIdentifier = true; @@ -47,17 +50,17 @@ class Department extends SnipeModel ]; use Searchable; - + /** * The attributes that should be included when searching the model. - * + * * @var array */ protected $searchableAttributes = ['name', 'notes']; /** * The relations and their attributes that should be included when searching the model. - * + * * @var array */ protected $searchableRelations = []; @@ -71,10 +74,9 @@ class Department extends SnipeModel */ public function company() { - return $this->belongsTo('\App\Models\Company', 'company_id'); + return $this->belongsTo(\App\Models\Company::class, 'company_id'); } - /** * Establishes the department -> users relationship * @@ -84,10 +86,9 @@ class Department extends SnipeModel */ public function users() { - return $this->hasMany('\App\Models\User', 'department_id'); + return $this->hasMany(\App\Models\User::class, 'department_id'); } - /** * Establishes the department -> manager relationship * @@ -97,7 +98,7 @@ class Department extends SnipeModel */ public function manager() { - return $this->belongsTo('\App\Models\User', 'manager_id'); + return $this->belongsTo(\App\Models\User::class, 'manager_id'); } /** @@ -109,9 +110,9 @@ class Department extends SnipeModel */ public function location() { - return $this->belongsTo('\App\Models\Location', 'location_id'); + return $this->belongsTo(\App\Models\Location::class, 'location_id'); } - + /** * Query builder scope to order on location name * @@ -137,6 +138,4 @@ class Department extends SnipeModel { return $query->leftJoin('users as department_user', 'departments.manager_id', '=', 'department_user.id')->orderBy('department_user.first_name', $order)->orderBy('department_user.last_name', $order); } - - } diff --git a/app/Models/Depreciable.php b/app/Models/Depreciable.php index fde9530c45..35f494233b 100644 --- a/app/Models/Depreciable.php +++ b/app/Models/Depreciable.php @@ -1,11 +1,12 @@ belongsTo('\App\Models\Depreciation', 'depreciation_id'); + return $this->belongsTo(\App\Models\Depreciation::class, 'depreciation_id'); } public function get_depreciation() @@ -35,10 +36,9 @@ class Depreciable extends SnipeModel /** * @return float|int */ - public function getDepreciatedValue() { - if (!$this->get_depreciation()) { // will never happen + if (! $this->get_depreciation()) { // will never happen return $this->purchase_cost; } @@ -47,11 +47,11 @@ class Depreciable extends SnipeModel } $depreciation = 0; $setting = Setting::getSettings(); - switch($setting->depreciation_method) { + switch ($setting->depreciation_method) { case 'half_1': $depreciation = $this->getHalfYearDepreciatedValue(true); break; - + case 'half_2': $depreciation = $this->getHalfYearDepreciatedValue(false); break; @@ -59,22 +59,27 @@ class Depreciable extends SnipeModel default: $depreciation = $this->getLinearDepreciatedValue(); } + return $depreciation; } /** * @return float|int */ - public function getLinearDepreciatedValue() { // fraction of value left - $months_remaining = $this->time_until_depreciated()->m + 12*$this->time_until_depreciated()->y; //UGlY - $current_value = round(($months_remaining/ $this->get_depreciation()->months) * $this->purchase_cost, 2); + $months_remaining = $this->time_until_depreciated()->m + 12 * $this->time_until_depreciated()->y; //UGlY + $current_value = round(($months_remaining / $this->get_depreciation()->months) * $this->purchase_cost, 2); + if($this->get_depreciation()->depreciation_min > $current_value) { + + $current_value=$this->get_depreciation()->depreciation_min; + } if ($current_value < 0) { $current_value = 0; } + return $current_value; } @@ -82,55 +87,56 @@ class Depreciable extends SnipeModel * @param onlyHalfFirstYear Boolean always applied only second half of the first year * @return float|int */ - public function getHalfYearDepreciatedValue($onlyHalfFirstYear = false) + public function getHalfYearDepreciatedValue($onlyHalfFirstYear = false) { // @link http://www.php.net/manual/en/class.dateinterval.php $current_date = $this->getDateTime(); $purchase_date = date_create($this->purchase_date); - $currentYear = $this->get_fiscal_year( $current_date ); - $purchaseYear = $this->get_fiscal_year( $purchase_date ); + $currentYear = $this->get_fiscal_year($current_date); + $purchaseYear = $this->get_fiscal_year($purchase_date); $yearsPast = $currentYear - $purchaseYear; $deprecationYears = ceil($this->get_depreciation()->months / 12); - if( $onlyHalfFirstYear ) { + if ($onlyHalfFirstYear) { + $yearsPast -= 0.5; + } elseif (! $this->is_first_half_of_year($purchase_date)) { $yearsPast -= 0.5; } - else if( !$this->is_first_half_of_year($purchase_date) ) { - $yearsPast -= 0.5; - } - if( !$this->is_first_half_of_year($current_date) ) { + if (! $this->is_first_half_of_year($current_date)) { $yearsPast += 0.5; } - if($yearsPast >= $deprecationYears) { + if ($yearsPast >= $deprecationYears) { $yearsPast = $deprecationYears; - } - else if($yearsPast < 0) { + } elseif ($yearsPast < 0) { $yearsPast = 0; } + return round($yearsPast / $deprecationYears * $this->purchase_cost, 2); } - + /** - * @param \DateTime $date - * @return int - */ - protected function get_fiscal_year($date) { + * @param \DateTime $date + * @return int + */ + protected function get_fiscal_year($date) + { $year = intval($date->format('Y')); // also, maybe it'll have to set fiscal year date - if($date->format('nj') === '1231') { + if ($date->format('nj') === '1231') { return $year; - } - else { + } else { return $year - 1; } } /** - * @param \DateTime $date - * @return bool - */ - protected function is_first_half_of_year($date) { + * @param \DateTime $date + * @return bool + */ + protected function is_first_half_of_year($date) + { $date0m0d = intval($date->format('md')); + return ($date0m0d < 601) || ($date0m0d >= 1231); } @@ -142,22 +148,23 @@ class Depreciable extends SnipeModel // @link http://www.php.net/manual/en/class.dateinterval.php $interval = $d1->diff($d2); - if (!$interval->invert) { + if (! $interval->invert) { return $interval; } else { - return new \DateInterval("PT0S"); //null interval (zero seconds from now) + return new \DateInterval('PT0S'); //null interval (zero seconds from now) } } public function depreciated_date() { $date = date_create($this->purchase_date); - date_add($date, date_interval_create_from_date_string($this->get_depreciation()->months . ' months')); + date_add($date, date_interval_create_from_date_string($this->get_depreciation()->months.' months')); + return $date; //date_format($date, 'Y-m-d'); //don't bake-in format, for internationalization } // it's necessary for unit tests - protected function getDateTime($time = null) + protected function getDateTime($time = null) { return new \DateTime($time); } diff --git a/app/Models/Depreciation.php b/app/Models/Depreciation.php index c706f2f1e7..39fb935494 100755 --- a/app/Models/Depreciation.php +++ b/app/Models/Depreciation.php @@ -1,27 +1,31 @@ 'required|min:3|max:255|unique:depreciations,name', 'months' => 'required|max:3600|integer', - ); + ]; /** - * 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 boolean - */ + * 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; use ValidatingTrait; @@ -30,20 +34,20 @@ class Depreciation extends SnipeModel * * @var array */ - protected $fillable = ['name','months']; + protected $fillable = ['name', 'months']; use Searchable; - + /** * The attributes that should be included when searching the model. - * + * * @var array */ protected $searchableAttributes = ['name', 'months']; /** * The relations and their attributes that should be included when searching the model. - * + * * @var array */ protected $searchableRelations = []; @@ -57,10 +61,9 @@ class Depreciation extends SnipeModel */ public function models() { - return $this->hasMany('\App\Models\AssetModel', 'depreciation_id'); + return $this->hasMany(\App\Models\AssetModel::class, 'depreciation_id'); } - /** * Establishes the depreciation -> licenses relationship * @@ -70,6 +73,6 @@ class Depreciation extends SnipeModel */ public function licenses() { - return $this->hasMany('\App\Models\License', 'depreciation_id'); - } + return $this->hasMany(\App\Models\License::class, 'depreciation_id'); + } } diff --git a/app/Models/Group.php b/app/Models/Group.php index 25c2505101..a68579adac 100755 --- a/app/Models/Group.php +++ b/app/Models/Group.php @@ -1,39 +1,42 @@ 'required|min:2|max:255', - ); + ]; /** - * 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 boolean - */ + * 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; use ValidatingTrait; - use Searchable; - + /** * The attributes that should be included when searching the model. - * + * * @var array */ protected $searchableAttributes = ['name', 'created_at']; /** * The relations and their attributes that should be included when searching the model. - * + * * @var array */ protected $searchableRelations = []; @@ -47,7 +50,7 @@ class Group extends SnipeModel */ public function users() { - return $this->belongsToMany('\App\Models\User', 'users_groups'); + return $this->belongsToMany(\App\Models\User::class, 'users_groups'); } /** diff --git a/app/Models/ICompanyableChild.php b/app/Models/ICompanyableChild.php index 0f24598ec9..b435ee00a4 100644 --- a/app/Models/ICompanyableChild.php +++ b/app/Models/ICompanyableChild.php @@ -1,4 +1,5 @@ 'array', 'first_row' => 'array', - 'field_map' => 'json' + 'field_map' => 'json', ]; } diff --git a/app/Models/Ldap.php b/app/Models/Ldap.php index 619f083b06..6b23fd54ec 100644 --- a/app/Models/Ldap.php +++ b/app/Models/Ldap.php @@ -1,16 +1,16 @@ Settings. * @@ -18,29 +18,27 @@ class Ldap extends Model * @since [v3.0] * @return connection */ - public static function connectToLdap() { - - $ldap_host = Setting::getSettings()->ldap_server; + $ldap_host = Setting::getSettings()->ldap_server; $ldap_version = Setting::getSettings()->ldap_version; $ldap_server_cert_ignore = Setting::getSettings()->ldap_server_cert_ignore; $ldap_use_tls = Setting::getSettings()->ldap_tls; // If we are ignoring the SSL cert we need to setup the environment variable // before we create the connection - if ($ldap_server_cert_ignore=='1') { + if ($ldap_server_cert_ignore == '1') { putenv('LDAPTLS_REQCERT=never'); } // If the user specifies where CA Certs are, make sure to use them - if (env("LDAPTLS_CACERT")) { - putenv("LDAPTLS_CACERT=".env("LDAPTLS_CACERT")); + if (env('LDAPTLS_CACERT')) { + putenv('LDAPTLS_CACERT='.env('LDAPTLS_CACERT')); } $connection = @ldap_connect($ldap_host); - if (!$connection) { + if (! $connection) { throw new Exception('Could not connect to LDAP server at '.$ldap_host.'. Please check your LDAP server name and port number in your settings.'); } @@ -74,61 +72,55 @@ class Ldap extends Model * @return bool true if the username and/or password provided are valid * false if the username and/or password provided are invalid * array of ldap_attributes if $user is true - * */ - static function findAndBindUserLdap($username, $password) + public static function findAndBindUserLdap($username, $password) { $settings = Setting::getSettings(); - $connection = Ldap::connectToLdap(); - $ldap_username_field = $settings->ldap_username_field; - $baseDn = $settings->ldap_basedn; - $userDn = $ldap_username_field.'='.$username.','.$settings->ldap_basedn; + $connection = self::connectToLdap(); + $ldap_username_field = $settings->ldap_username_field; + $baseDn = $settings->ldap_basedn; + $userDn = $ldap_username_field.'='.$username.','.$settings->ldap_basedn; - if ($settings->is_ad =='1') { + if ($settings->is_ad == '1') { // Check if they are using the userprincipalname for the username field. // If they are, we can skip building the UPN to authenticate against AD - if ($ldap_username_field=='userprincipalname') { + if ($ldap_username_field == 'userprincipalname') { $userDn = $username; } else { // In case they haven't added an AD domain - $userDn = ($settings->ad_domain != '') ? $username.'@'.$settings->ad_domain : $username.'@'.$settings->email_domain; + $userDn = ($settings->ad_domain != '') ? $username.'@'.$settings->ad_domain : $username.'@'.$settings->email_domain; } - } \Log::debug('Attempting to login using distinguished name:'.$userDn); - - $filterQuery = $settings->ldap_auth_filter_query . $username; + $filterQuery = $settings->ldap_auth_filter_query.$username; $filter = Setting::getSettings()->ldap_filter; $filterQuery = "({$filter}({$filterQuery}))"; \Log::debug('Filter query: '.$filterQuery); - - if (!$ldapbind = @ldap_bind($connection, $userDn, $password)) { - if(!$ldapbind = Ldap::bindAdminToLdap($connection)){ + if (! $ldapbind = @ldap_bind($connection, $userDn, $password)) { + if (! $ldapbind = self::bindAdminToLdap($connection)) { return false; } } - if (!$results = ldap_search($connection, $baseDn, $filterQuery)) { + if (! $results = ldap_search($connection, $baseDn, $filterQuery)) { throw new Exception('Could not search LDAP: '); } - if (!$entry = ldap_first_entry($connection, $results)) { + if (! $entry = ldap_first_entry($connection, $results)) { return false; } - if (!$user = ldap_get_attributes($connection, $entry)) { + if (! $user = ldap_get_attributes($connection, $entry)) { return false; } return array_change_key_case($user); - } - /** * Binds/authenticates an admin to LDAP for LDAP searching/syncing. * Here we also return a better error if the app key is donked. @@ -138,26 +130,23 @@ class Ldap extends Model * @param bool|false $user * @return bool true if the username and/or password provided are valid * false if the username and/or password provided are invalid - * */ - static function bindAdminToLdap($connection) + public static function bindAdminToLdap($connection) { + $ldap_username = Setting::getSettings()->ldap_uname; $ldap_username = Setting::getSettings()->ldap_uname; // Lets return some nicer messages for users who donked their app key, and disable LDAP try { - $ldap_pass = \Crypt::decrypt(Setting::getSettings()->ldap_pword); + $ldap_pass = \Crypt::decrypt(Setting::getSettings()->ldap_pword); } catch (Exception $e) { - throw new Exception('Your app key has changed! Could not decrypt LDAP password using your current app key, so LDAP authentication has been disabled. Login with a local account, update the LDAP password and re-enable it in Admin > Settings.'); } - - if (!$ldapbind = @ldap_bind($connection, $ldap_username, $ldap_pass)) { + if (! $ldapbind = @ldap_bind($connection, $ldap_username, $ldap_pass)) { throw new Exception('Could not bind to LDAP: '.ldap_error($connection)); } - } @@ -170,7 +159,7 @@ class Ldap extends Model * @param $ldapatttibutes * @return array|bool */ - static function parseAndMapLdapAttributes($ldapattributes) + public static function parseAndMapLdapAttributes($ldapattributes) { //Get LDAP attribute config $ldap_result_username = Setting::getSettings()->ldap_username_field; @@ -180,22 +169,21 @@ class Ldap extends Model $ldap_result_email = Setting::getSettings()->ldap_email; $ldap_result_phone = Setting::getSettings()->ldap_phone; $ldap_result_jobtitle = Setting::getSettings()->ldap_jobtitle; - $ldap_result_country = Setting::getSettings()->ldap_country; + $ldap_result_country = Setting::getSettings()->ldap_country; $ldap_result_dept = Setting::getSettings()->ldap_dept; // Get LDAP user data - $item = array(); - $item["username"] = isset($ldapattributes[$ldap_result_username][0]) ? $ldapattributes[$ldap_result_username][0] : ""; - $item["employee_number"] = isset($ldapattributes[$ldap_result_emp_num][0]) ? $ldapattributes[$ldap_result_emp_num][0] : ""; - $item["lastname"] = isset($ldapattributes[$ldap_result_last_name][0]) ? $ldapattributes[$ldap_result_last_name][0] : ""; - $item["firstname"] = isset($ldapattributes[$ldap_result_first_name][0]) ? $ldapattributes[$ldap_result_first_name][0] : ""; - $item["email"] = isset($ldapattributes[$ldap_result_email][0]) ? $ldapattributes[$ldap_result_email][0] : "" ; - $item["telephone"] = isset($ldapattributes[$ldap_result_phone][0]) ?$ldapattributes[$ldap_result_phone][0] : ""; - $item["jobtitle"] = isset($ldapattributes[$ldap_result_jobtitle][0]) ? $ldapattributes[$ldap_result_jobtitle][0] : ""; - $item["country"] = isset($ldapattributes[$ldap_result_country][0]) ? $ldapattributes[$ldap_result_country][0] : ""; - $item["department"] = isset($ldapattributes[$ldap_result_dept][0]) ? $ldapattributes[$ldap_result_dept][0] : ""; + $item = []; + $item['username'] = isset($ldapattributes[$ldap_result_username][0]) ? $ldapattributes[$ldap_result_username][0] : ''; + $item['employee_number'] = isset($ldapattributes[$ldap_result_emp_num][0]) ? $ldapattributes[$ldap_result_emp_num][0] : ''; + $item['lastname'] = isset($ldapattributes[$ldap_result_last_name][0]) ? $ldapattributes[$ldap_result_last_name][0] : ''; + $item['firstname'] = isset($ldapattributes[$ldap_result_first_name][0]) ? $ldapattributes[$ldap_result_first_name][0] : ''; + $item['email'] = isset($ldapattributes[$ldap_result_email][0]) ? $ldapattributes[$ldap_result_email][0] : ''; + $item['telephone'] = isset($ldapattributes[$ldap_result_phone][0]) ? $ldapattributes[$ldap_result_phone][0] : ''; + $item['jobtitle'] = isset($ldapattributes[$ldap_result_jobtitle][0]) ? $ldapattributes[$ldap_result_jobtitle][0] : ''; + $item['country'] = isset($ldapattributes[$ldap_result_country][0]) ? $ldapattributes[$ldap_result_country][0] : ''; + $item['department'] = isset($ldapattributes[$ldap_result_dept][0]) ? $ldapattributes[$ldap_result_dept][0] : ''; + return $item; - - } /** @@ -206,23 +194,22 @@ class Ldap extends Model * @param $ldapatttibutes * @return array|bool */ - static function createUserFromLdap($ldapatttibutes) + public static function createUserFromLdap($ldapatttibutes) { - $item = Ldap::parseAndMapLdapAttributes($ldapatttibutes); - + $item = self::parseAndMapLdapAttributes($ldapatttibutes); // Create user from LDAP data - if (!empty($item["username"])) { + if (! empty($item['username'])) { $user = new User; - $user->first_name = $item["firstname"]; - $user->last_name = $item["lastname"]; - $user->username = $item["username"]; - $user->email = $item["email"]; + $user->first_name = $item['firstname']; + $user->last_name = $item['lastname']; + $user->username = $item['username']; + $user->email = $item['email']; - if (Setting::getSettings()->ldap_pw_sync=='1') { - $user->password = bcrypt(Input::get("password")); + if (Setting::getSettings()->ldap_pw_sync == '1') { + $user->password = bcrypt(Input::get('password')); } else { - $pass = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 25); + $pass = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 25); $user->password = bcrypt($pass); } @@ -234,12 +221,11 @@ class Ldap extends Model return $user; } else { LOG::debug('Could not create user.'.$user->getErrors()); - throw new Exception("Could not create user: ".$user->getErrors()); + throw new Exception('Could not create user: '.$user->getErrors()); } } return false; - } /** @@ -251,11 +237,10 @@ class Ldap extends Model * @param $base_dn * @return array|bool */ - static function findLdapUsers($base_dn = null) + public static function findLdapUsers($base_dn = null) { - - $ldapconn = Ldap::connectToLdap(); - $ldap_bind = Ldap::bindAdminToLdap($ldapconn); + $ldapconn = self::connectToLdap(); + $ldap_bind = self::bindAdminToLdap($ldapconn); // Default to global base DN if nothing else is provided. if (is_null($base_dn)) { $base_dn = Setting::getSettings()->ldap_basedn; @@ -265,33 +250,32 @@ class Ldap extends Model // Set up LDAP pagination for very large databases $page_size = 500; $cookie = ''; - $result_set = array(); + $result_set = []; $global_count = 0; // Perform the search do { // Paginate (non-critical, if not supported by server) - if (!$ldap_paging = @ldap_control_paged_result($ldapconn, $page_size, false, $cookie)) { + if (! $ldap_paging = @ldap_control_paged_result($ldapconn, $page_size, false, $cookie)) { throw new Exception('Problem with your LDAP connection. Try checking the Use TLS setting in Admin > Settings. '); } if ($filter != '' && substr($filter, 0, 1) != '(') { // wrap parens around NON-EMPTY filters that DON'T have them, for back-compatibility with AdLdap2-based filters $filter = "($filter)"; } elseif ($filter == '') { - $filter = "(cn=*)"; + $filter = '(cn=*)'; } - $search_results = ldap_search($ldapconn, $base_dn, $filter); - if (!$search_results) { + if (! $search_results) { return redirect()->route('users.index')->with('error', trans('admin/users/message.error.ldap_could_not_search').ldap_error($ldapconn)); // FIXME this is never called in any routed context - only from the Artisan command. So this redirect will never work. } // Get results from page $results = ldap_get_entries($ldapconn, $search_results); - if (!$results) { + if (! $results) { return redirect()->route('users.index')->with('error', trans('admin/users/message.error.ldap_could_not_get_entries').ldap_error($ldapconn)); // FIXME this is never called in any routed context - only from the Artisan command. So this redirect will never work. } @@ -300,17 +284,13 @@ class Ldap extends Model $result_set = array_merge($result_set, $results); @ldap_control_paged_result_response($ldapconn, $search_results, $cookie); - } while ($cookie !== null && $cookie != ''); - // Clean up after search $result_set['count'] = $global_count; $results = $result_set; @ldap_control_paged_result($ldapconn, 0); return $results; - - } } diff --git a/app/Models/License.php b/app/Models/License.php index 8f0fbdfaab..21af9549cb 100755 --- a/app/Models/License.php +++ b/app/Models/License.php @@ -1,10 +1,12 @@ 'datetime', + 'expiration_date' => 'datetime', + 'termination_date' => 'datetime', 'seats' => 'integer', 'category_id' => 'integer', 'company_id' => 'integer', ]; - protected $rules = array( + protected $rules = [ 'name' => 'required|string|min:3|max:255', 'seats' => 'required|min:1|max:999|integer', 'license_email' => 'email|nullable|max:120', @@ -51,13 +48,13 @@ class License extends Depreciable 'notes' => 'string|nullable', 'category_id' => 'required|exists:categories,id', 'company_id' => 'integer|nullable', - ); + ]; - /** - * The attributes that are mass assignable. - * - * @var array - */ + /** + * The attributes that are mass assignable. + * + * @var array + */ protected $fillable = [ 'company_id', 'depreciation_id', @@ -82,26 +79,26 @@ class License extends Depreciable ]; use Searchable; - + /** * The attributes that should be included when searching the model. - * + * * @var array */ protected $searchableAttributes = [ - 'name', - 'serial', - 'notes', - 'order_number', - 'purchase_order', - 'purchase_cost', + 'name', + 'serial', + 'notes', + 'order_number', + 'purchase_order', + 'purchase_cost', 'purchase_date', 'expiration_date', ]; /** * The relations and their attributes that should be included when searching the model. - * + * * @var array */ protected $searchableRelations = [ @@ -123,12 +120,14 @@ class License extends Depreciable // We need to listen for created for the initial setup so that we have a license ID. static::created(function ($license) { $newSeatCount = $license->getAttributes()['seats']; + return static::adjustSeatCount($license, $oldSeatCount = 0, $newSeatCount); }); // However, we listen for updating to be able to prevent the edit if we cannot delete enough seats. static::updating(function ($license) { $newSeatCount = $license->getAttributes()['seats']; $oldSeatCount = isset($license->getOriginal()['seats']) ? $license->getOriginal()['seats'] : 0; + return static::adjustSeatCount($license, $oldSeatCount, $newSeatCount); }); } @@ -143,7 +142,7 @@ class License extends Depreciable public static function adjustSeatCount($license, $oldSeats, $newSeats) { // If the seats haven't changed, continue on happily. - if ($oldSeats==$newSeats) { + if ($oldSeats == $newSeats) { return true; } // On Create, we just make one for each of the seats. @@ -153,24 +152,26 @@ class License extends Depreciable // Need to delete seats... lets see if if we have enough. $seatsAvailableForDelete = $license->licenseseats->reject(function ($seat) { - return (!! $seat->assigned_to) || (!! $seat->asset_id); + return ((bool) $seat->assigned_to) || ((bool) $seat->asset_id); }); if ($change > $seatsAvailableForDelete->count()) { Session::flash('error', trans('admin/licenses/message.assoc_users')); + return false; } - for ($i=1; $i <= $change; $i++) { + for ($i = 1; $i <= $change; $i++) { $seatsAvailableForDelete->pop()->delete(); } // Log Deletion of seats. $logAction = new Actionlog; - $logAction->item_type = License::class; + $logAction->item_type = self::class; $logAction->item_id = $license->id; $logAction->user_id = Auth::id() ?: 1; // We don't have an id while running the importer from CLI. $logAction->note = "deleted ${change} seats"; - $logAction->target_id = null; + $logAction->target_id = null; $logAction->logaction('delete seats'); + return true; } // Else we're adding seats. @@ -183,13 +184,14 @@ class License extends Depreciable if ($license->id) { //Log the addition of license to the log. $logAction = new Actionlog(); - $logAction->item_type = License::class; + $logAction->item_type = self::class; $logAction->item_id = $license->id; $logAction->user_id = Auth::id() ?: 1; // Importer. $logAction->note = "added ${change} seats"; - $logAction->target_id = null; + $logAction->target_id = null; $logAction->logaction('add seats'); } + return true; } @@ -226,7 +228,6 @@ class License extends Depreciable */ public function setExpirationDateAttribute($value) { - if ($value == '' || $value == '0000-00-00') { $value = null; } else { @@ -261,7 +262,7 @@ class License extends Depreciable */ public function company() { - return $this->belongsTo('\App\Models\Company', 'company_id'); + return $this->belongsTo(\App\Models\Company::class, 'company_id'); } /** @@ -273,7 +274,7 @@ class License extends Depreciable */ public function category() { - return $this->belongsTo('\App\Models\Category', 'category_id'); + return $this->belongsTo(\App\Models\Category::class, 'category_id'); } /** @@ -285,7 +286,7 @@ class License extends Depreciable */ public function manufacturer() { - return $this->belongsTo('\App\Models\Manufacturer', 'manufacturer_id'); + return $this->belongsTo(\App\Models\Manufacturer::class, 'manufacturer_id'); } /** @@ -293,7 +294,7 @@ class License extends Depreciable * * @author A. Gianotto * @since [v2.0] - * @return boolean + * @return bool */ public function checkin_email() { @@ -305,7 +306,7 @@ class License extends Depreciable * * @author A. Gianotto * @since [v4.0] - * @return boolean + * @return bool */ public function requireAcceptance() { @@ -342,7 +343,7 @@ class License extends Depreciable */ public function assignedusers() { - return $this->belongsToMany('\App\Models\User', 'license_seats', 'assigned_to', 'license_id'); + return $this->belongsToMany(\App\Models\User::class, 'license_seats', 'assigned_to', 'license_id'); } /** @@ -354,8 +355,8 @@ class License extends Depreciable */ public function assetlog() { - return $this->hasMany('\App\Models\Actionlog', 'item_id') - ->where('item_type', '=', License::class) + return $this->hasMany(\App\Models\Actionlog::class, 'item_id') + ->where('item_type', '=', self::class) ->orderBy('created_at', 'desc'); } @@ -368,14 +369,13 @@ class License extends Depreciable */ public function uploads() { - return $this->hasMany('\App\Models\Actionlog', 'item_id') - ->where('item_type', '=', License::class) + return $this->hasMany(\App\Models\Actionlog::class, 'item_id') + ->where('item_type', '=', self::class) ->where('action_type', '=', 'uploaded') ->whereNotNull('filename') ->orderBy('created_at', 'desc'); } - /** * Establishes the license -> admin user relationship * @@ -385,7 +385,7 @@ class License extends Depreciable */ public function adminuser() { - return $this->belongsTo('\App\Models\User', 'user_id'); + return $this->belongsTo(\App\Models\User::class, 'user_id'); } /** @@ -403,7 +403,6 @@ class License extends Depreciable ->count(); } - /** * Return the number of seats for this asset * @@ -538,8 +537,9 @@ class License extends Depreciable public function remaincount() { $total = $this->licenseSeatsCount; - $taken = $this->assigned_seats_count; - $diff = ($total - $taken); + $taken = $this->assigned_seats_count; + $diff = ($total - $taken); + return $diff; } @@ -552,9 +552,10 @@ class License extends Depreciable */ public function totalcount() { - $avail = $this->availSeatsCount; - $taken = $this->assignedcount(); - $diff = ($avail + $taken); + $avail = $this->availSeatsCount; + $taken = $this->assignedcount(); + $diff = ($avail + $taken); + return $diff; } @@ -567,7 +568,7 @@ class License extends Depreciable */ public function licenseseats() { - return $this->hasMany('\App\Models\LicenseSeat'); + return $this->hasMany(\App\Models\LicenseSeat::class); } /** @@ -579,10 +580,9 @@ class License extends Depreciable */ public function supplier() { - return $this->belongsTo('\App\Models\Supplier', 'supplier_id'); + return $this->belongsTo(\App\Models\Supplier::class, 'supplier_id'); } - /** * Gets the next available free seat - used by * the API to populate next_seat @@ -603,7 +603,6 @@ class License extends Depreciable ->first(); } - /** * Establishes the license -> free seats relationship * @@ -613,7 +612,7 @@ class License extends Depreciable */ public function freeSeats() { - return $this->hasMany('\App\Models\LicenseSeat')->whereNull('assigned_to')->whereNull('deleted_at')->whereNull('asset_id'); + return $this->hasMany(\App\Models\LicenseSeat::class)->whereNull('assigned_to')->whereNull('deleted_at')->whereNull('asset_id'); } /** @@ -627,14 +626,12 @@ class License extends Depreciable */ public static function getExpiringLicenses($days = 60) { - - return License::whereNotNull('expiration_date') + return self::whereNotNull('expiration_date') ->whereNull('deleted_at') ->whereRaw(DB::raw('DATE_SUB(`expiration_date`,INTERVAL '.$days.' DAY) <= DATE(NOW()) ')) - ->where('expiration_date', '>', date("Y-m-d")) + ->where('expiration_date', '>', date('Y-m-d')) ->orderBy('expiration_date', 'ASC') ->get(); - } /** diff --git a/app/Models/LicenseSeat.php b/app/Models/LicenseSeat.php index 40a53adf86..2207edd02c 100755 --- a/app/Models/LicenseSeat.php +++ b/app/Models/LicenseSeat.php @@ -1,4 +1,5 @@ * @since [v4.0] - * @return boolean + * @return bool */ public function requireAcceptance() { return $this->license->category->require_acceptance; } - public function getEula() { + public function getEula() + { return $this->license->getEula(); } - + /** * Establishes the seat -> license relationship * @@ -62,7 +63,7 @@ class LicenseSeat extends SnipeModel implements ICompanyableChild */ public function license() { - return $this->belongsTo('\App\Models\License', 'license_id'); + return $this->belongsTo(\App\Models\License::class, 'license_id'); } /** @@ -74,7 +75,7 @@ class LicenseSeat extends SnipeModel implements ICompanyableChild */ public function user() { - return $this->belongsTo('\App\Models\User', 'assigned_to')->withTrashed(); + return $this->belongsTo(\App\Models\User::class, 'assigned_to')->withTrashed(); } /** @@ -86,7 +87,7 @@ class LicenseSeat extends SnipeModel implements ICompanyableChild */ public function asset() { - return $this->belongsTo('\App\Models\Asset', 'asset_id')->withTrashed(); + return $this->belongsTo(\App\Models\Asset::class, 'asset_id')->withTrashed(); } /** @@ -101,13 +102,11 @@ class LicenseSeat extends SnipeModel implements ICompanyableChild { if (($this->user) && ($this->user->location)) { return $this->user->location; - } elseif (($this->asset) && ($this->asset->location)) { return $this->asset->location; } return false; - } /** @@ -120,12 +119,8 @@ class LicenseSeat extends SnipeModel implements ICompanyableChild */ public function scopeOrderDepartments($query, $order) { - return $query->leftJoin('users as license_seat_users', 'license_seats.assigned_to', '=', 'license_seat_users.id') - ->leftJoin('departments as license_user_dept', 'license_user_dept.id', '=', 'license_seat_users.department_id') + return $query->leftJoin('users as license_seat_users', 'license_seats.assigned_to', '=', 'license_seat_users.id') + ->leftJoin('departments as license_user_dept', 'license_user_dept.id', '=', 'license_seat_users.department_id') ->orderBy('license_user_dept.name', $order); } - - - - } diff --git a/app/Models/Location.php b/app/Models/Location.php index 1f48f96e77..a85c8905e0 100755 --- a/app/Models/Location.php +++ b/app/Models/Location.php @@ -1,4 +1,5 @@ 'required|min:2|max:255|unique_undeleted', 'city' => 'min:2|max:255|nullable', 'country' => 'min:2|max:255|nullable', @@ -28,8 +32,8 @@ class Location extends SnipeModel 'address2' => 'max:80|nullable', 'zip' => 'min:3|max:10|nullable', 'manager_id' => 'exists:users,id|nullable', - 'parent_id' => 'non_circular:locations,id' - ); + 'parent_id' => 'non_circular:locations,id', + ]; protected $casts = [ 'parent_id' => 'integer', @@ -37,17 +41,16 @@ class Location extends SnipeModel ]; /** - * 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 boolean - */ + * 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; use ValidatingTrait; use UniqueUndeletedTrait; - /** * The attributes that are mass assignable. * @@ -70,41 +73,41 @@ class Location extends SnipeModel protected $hidden = ['user_id']; use Searchable; - + /** * The attributes that should be included when searching the model. - * + * * @var array */ protected $searchableAttributes = ['name', 'address', 'city', 'state', 'zip', 'created_at', 'ldap_ou']; /** * The relations and their attributes that should be included when searching the model. - * + * * @var array */ protected $searchableRelations = [ - 'parent' => ['name'] + 'parent' => ['name'], ]; public function isDeletable() { return Gate::allows('delete', $this) - && ($this->assignedAssets()->count()===0) - && ($this->assets()->count()===0) - && ($this->users()->count()===0); + && ($this->assignedAssets()->count() === 0) + && ($this->assets()->count() === 0) + && ($this->users()->count() === 0); } public function users() { - return $this->hasMany('\App\Models\User', 'location_id'); + return $this->hasMany(\App\Models\User::class, 'location_id'); } public function assets() { - return $this->hasMany('\App\Models\Asset', 'location_id') + return $this->hasMany(\App\Models\Asset::class, 'location_id') ->whereHas('assetstatus', function ($query) { - $query->where('status_labels.deployable', '=', 1) + $query->where('status_labels.deployable', '=', 1) ->orWhere('status_labels.pending', '=', 1) ->orWhere('status_labels.archived', '=', 0); }); @@ -117,35 +120,36 @@ class Location extends SnipeModel definitely was setting fire to the query-planner. So don't do that. It is arguable that we should have a '...->whereNull('assigned_to') - bit in there, but that isn't always correct either (in the case + bit in there, but that isn't always correct either (in the case where a user has no location, for example). In all likelyhood, we need to denorm an "effective_location" column into Assets to make this slightly less miserable. */ - return $this->hasMany('\App\Models\Asset', 'rtd_location_id'); + return $this->hasMany(\App\Models\Asset::class, 'rtd_location_id'); } public function parent() { - return $this->belongsTo('\App\Models\Location', 'parent_id','id') + return $this->belongsTo(self::class, 'parent_id', 'id') ->with('parent'); } public function manager() { - return $this->belongsTo('\App\Models\User', 'manager_id'); + return $this->belongsTo(\App\Models\User::class, 'manager_id'); } - public function children() { - return $this->hasMany('\App\Models\Location','parent_id') + public function children() + { + return $this->hasMany(self::class, 'parent_id') ->with('children'); } // I don't think we need this anymore since we de-normed location_id in assets? public function assignedAssets() { - return $this->morphMany('App\Models\Asset', 'assigned', 'assigned_type', 'assigned_to')->withTrashed(); + return $this->morphMany(\App\Models\Asset::class, 'assigned', 'assigned_type', 'assigned_to')->withTrashed(); } public function setLdapOuAttribute($ldap_ou) @@ -153,7 +157,6 @@ class Location extends SnipeModel return $this->attributes['ldap_ou'] = empty($ldap_ou) ? null : $ldap_ou; } - /** * Query builder scope to order on parent * @@ -162,42 +165,38 @@ class Location extends SnipeModel * * @return Illuminate\Database\Query\Builder Modified query builder */ + public static function indenter($locations_with_children, $parent_id = null, $prefix = '') + { + $results = []; - public static function indenter($locations_with_children, $parent_id = null, $prefix = '') { - $results = Array(); - - - if (!array_key_exists($parent_id, $locations_with_children)) { + if (! array_key_exists($parent_id, $locations_with_children)) { return []; } - foreach ($locations_with_children[$parent_id] as $location) { $location->use_text = $prefix.' '.$location->name; $location->use_image = ($location->image) ? url('/').'/uploads/locations/'.$location->image : null; $results[] = $location; //now append the children. (if we have any) if (array_key_exists($location->id, $locations_with_children)) { - $results = array_merge($results, Location::indenter($locations_with_children, $location->id,$prefix.'--')); + $results = array_merge($results, self::indenter($locations_with_children, $location->id, $prefix.'--')); } } + return $results; } - - - /** - * Query builder scope to order on parent - * - * @param Illuminate\Database\Query\Builder $query Query builder instance - * @param text $order Order - * - * @return Illuminate\Database\Query\Builder Modified query builder - */ + * Query builder scope to order on parent + * + * @param Illuminate\Database\Query\Builder $query Query builder instance + * @param text $order Order + * + * @return Illuminate\Database\Query\Builder Modified query builder + */ public function scopeOrderParent($query, $order) { - // Left join here, or it will only return results with parents + // Left join here, or it will only return results with parents return $query->leftJoin('locations as parent_loc', 'locations.parent_id', '=', 'parent_loc.id')->orderBy('parent_loc.name', $order); } diff --git a/app/Models/Loggable.php b/app/Models/Loggable.php index 501b5057ca..3c44009aab 100644 --- a/app/Models/Loggable.php +++ b/app/Models/Loggable.php @@ -2,19 +2,17 @@ namespace App\Models; +use App\Models\Setting; use App\Notifications\AuditNotification; use Illuminate\Support\Facades\Auth; -use App\Models\Setting; trait Loggable { - /** * @author Daniel Meltzer * @since [v3.4] * @return \App\Models\Actionlog */ - public function log() { return $this->morphMany(Actionlog::class, 'item'); @@ -33,20 +31,21 @@ trait Loggable $log->user_id = Auth::user()->id; } - if (!isset($target)) { + if (! isset($target)) { throw new \Exception('All checkout logs require a target.'); + return; } - if (!isset($target->id)) { + if (! isset($target->id)) { throw new \Exception('That target seems invalid (no target ID available).'); + return; } $log->target_type = get_class($target); $log->target_id = $target->id; - // Figure out what the target is if ($log->target_type == Location::class) { $log->location_id = $target->id; @@ -59,7 +58,7 @@ trait Loggable $log->note = $note; $log->action_date = $action_date; - if (!$log->action_date) { + if (! $log->action_date) { $log->action_date = date('Y-m-d H:i:s'); } @@ -69,8 +68,8 @@ trait Loggable } /** - * Helper method to determine the log item type - */ + * Helper method to determine the log item type + */ private function determineLogItemType($log) { // We need to special case licenses because of license_seat vs license. So much for clean polymorphism : @@ -84,6 +83,7 @@ trait Loggable return $log; } + /** * @author Daniel Meltzer * @since [v3.4] @@ -100,7 +100,6 @@ trait Loggable $log->item_type = License::class; $log->item_id = $this->license_id; } else { - $log->item_type = static::class; $log->item_id = $this->id; @@ -109,17 +108,15 @@ trait Loggable $asset->increment('checkin_counter', 1); } } - } - $log->location_id = null; $log->note = $note; if (Auth::user()) { $log->user_id = Auth::user()->id; } - + $log->logaction('checkin from'); // $params = [ @@ -158,7 +155,6 @@ trait Loggable return $log; } - /** * @author A. Gianotto * @since [v4.0] @@ -186,15 +182,13 @@ trait Loggable 'filename' => $log->filename, 'admin' => $log->user, 'location' => ($location) ? $location->name : '', - 'note' => $note + 'note' => $note, ]; Setting::getSettings()->notify(new AuditNotification($params)); return $log; } - - /** * @author Daniel Meltzer * @since [v3.5] @@ -219,6 +213,7 @@ trait Loggable $log->user_id = $user_id; $log->logaction('create'); $log->save(); + return $log; } @@ -239,9 +234,9 @@ trait Loggable } $log->user_id = Auth::user()->id; $log->note = $note; - $log->target_id = null; - $log->created_at = date("Y-m-d H:i:s"); - $log->filename = $filename; + $log->target_id = null; + $log->created_at = date('Y-m-d H:i:s'); + $log->filename = $filename; $log->logaction('uploaded'); return $log; diff --git a/app/Models/Manufacturer.php b/app/Models/Manufacturer.php index 085bed2d3f..5f01c3c273 100755 --- a/app/Models/Manufacturer.php +++ b/app/Models/Manufacturer.php @@ -1,37 +1,41 @@ 'required|min:2|max:255|unique:manufacturers,name,NULL,id,deleted_at,NULL', 'url' => 'url|nullable', 'support_url' => 'url|nullable', - 'support_email' => 'email|nullable' - ); + 'support_email' => 'email|nullable', + ]; protected $hidden = ['user_id']; /** - * 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 boolean - */ + * 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; use ValidatingTrait; @@ -65,38 +69,37 @@ class Manufacturer extends SnipeModel */ protected $searchableRelations = []; - public function isDeletable() { - return (Gate::allows('delete', $this) - && ($this->assets()->count() === 0) + return Gate::allows('delete', $this) + && ($this->assets()->count() === 0) && ($this->licenses()->count() === 0) && ($this->consumables()->count() === 0) - && ($this->accessories()->count() === 0)); + && ($this->accessories()->count() === 0); } public function assets() { - return $this->hasManyThrough('\App\Models\Asset', '\App\Models\AssetModel', 'manufacturer_id', 'model_id'); + return $this->hasManyThrough(\App\Models\Asset::class, \App\Models\AssetModel::class, 'manufacturer_id', 'model_id'); } public function models() { - return $this->hasMany('\App\Models\AssetModel', 'manufacturer_id'); + return $this->hasMany(\App\Models\AssetModel::class, 'manufacturer_id'); } public function licenses() { - return $this->hasMany('\App\Models\License', 'manufacturer_id'); + return $this->hasMany(\App\Models\License::class, 'manufacturer_id'); } public function accessories() { - return $this->hasMany('\App\Models\Accessory', 'manufacturer_id'); + return $this->hasMany(\App\Models\Accessory::class, 'manufacturer_id'); } public function consumables() { - return $this->hasMany('\App\Models\Consumable', 'manufacturer_id'); + return $this->hasMany(\App\Models\Consumable::class, 'manufacturer_id'); } } diff --git a/app/Models/PredefinedKit.php b/app/Models/PredefinedKit.php index 317cf3cd6a..1bf6cb098b 100644 --- a/app/Models/PredefinedKit.php +++ b/app/Models/PredefinedKit.php @@ -1,4 +1,5 @@ ] * @version v1.0 */ class PredefinedKit extends SnipeModel { - protected $presenter = 'App\Presenters\PredefinedKitPresenter'; + protected $presenter = \App\Presenters\PredefinedKitPresenter::class; use Presentable; protected $table = 'kits'; /** * Category validation rules */ - public $rules = array( - 'name' => 'required|min:1|max:255|unique' - ); + public $rules = [ + 'name' => 'required|min:1|max:255|unique', + ]; use ValidatingTrait; public $modelRules = [ 'model_id' => 'required|exists:models,id', 'quantity' => 'required|integer|min:1', - 'pivot_id' => 'integer|exists:kits_models,id' + 'pivot_id' => 'integer|exists:kits_models,id', ]; /** @@ -39,7 +40,7 @@ class PredefinedKit extends SnipeModel * @param int $model_id * @param bool $new = true if append a new element to kit */ - public function makeModelRules($model_id, $new=false) + public function makeModelRules($model_id, $new = false) { return $this->_makeRuleHelper('models', 'kits_models', 'model_id', $model_id, $new); } @@ -50,7 +51,7 @@ class PredefinedKit extends SnipeModel * @param int $license_id * @param bool $new = true if append a new element to kit */ - public function makeLicenseRules($license_id, $new=false) + public function makeLicenseRules($license_id, $new = false) { return $this->_makeRuleHelper('licenses', 'kits_licenses', 'license_id', $license_id, $new); } @@ -61,7 +62,7 @@ class PredefinedKit extends SnipeModel * @param int $accessoriy_id * @param bool $new = true if append a new element to kit */ - public function makeAccessoryRules($accessory_id, $new=false) + public function makeAccessoryRules($accessory_id, $new = false) { return $this->_makeRuleHelper('accessories', 'kits_accessories', 'accessory_id', $accessory_id, $new); } @@ -72,7 +73,7 @@ class PredefinedKit extends SnipeModel * @param int $consumable_id * @param bool $new = true if append a new element to kit */ - public function makeConsumableRules($consumable_id, $new=false) + public function makeConsumableRules($consumable_id, $new = false) { return $this->_makeRuleHelper('consumables', 'kits_consumables', 'consumable_id', $consumable_id, $new); } @@ -96,14 +97,14 @@ class PredefinedKit extends SnipeModel $pivot_elem_key => [ 'required', "exists:$table,id", - Rule::unique($pivot_table)->whereNot($pivot_elem_key, $element_id)->where('kit_id', $this->id) + Rule::unique($pivot_table)->whereNot($pivot_elem_key, $element_id)->where('kit_id', $this->id), ], - 'quantity' => 'required|integer|min:1' + 'quantity' => 'required|integer|min:1', ]; - if (!$new) { + if (! $new) { $rule['pivot_id'] = "integer|exists:$pivot_table,id"; - } + return $rule; } @@ -113,38 +114,37 @@ class PredefinedKit extends SnipeModel * @var array */ protected $fillable = [ - 'name' + 'name', ]; use Searchable; /** * The attributes that should be included when searching the kit. - * + * * @var array */ protected $searchableAttributes = ['name']; /** * The relations and their attributes that should be included when searching the kit. - * + * * @var array */ protected $searchableRelations = []; - /** * Establishes the kits -> models relationship * @return \Illuminate\Database\Eloquent\Relations\Relation */ public function models() { - return $this->belongsToMany('\App\Models\AssetModel', 'kits_models', 'kit_id', 'model_id')->withPivot('id', 'quantity'); + return $this->belongsToMany(\App\Models\AssetModel::class, 'kits_models', 'kit_id', 'model_id')->withPivot('id', 'quantity'); } public function assets() { - return $this->hasManyThrough('\App\Models\Asset', '\App\Models\AssetModel', 'country_id', 'user_id'); + return $this->hasManyThrough(\App\Models\Asset::class, \App\Models\AssetModel::class, 'country_id', 'user_id'); } /** @@ -153,7 +153,7 @@ class PredefinedKit extends SnipeModel */ public function licenses() { - return $this->belongsToMany('\App\Models\License', 'kits_licenses', 'kit_id', 'license_id')->withPivot('id', 'quantity'); + return $this->belongsToMany(\App\Models\License::class, 'kits_licenses', 'kit_id', 'license_id')->withPivot('id', 'quantity'); } /** @@ -162,7 +162,7 @@ class PredefinedKit extends SnipeModel */ public function consumables() { - return $this->belongsToMany('\App\Models\Consumable', 'kits_consumables', 'kit_id', 'consumable_id')->withPivot('id', 'quantity'); + return $this->belongsToMany(\App\Models\Consumable::class, 'kits_consumables', 'kit_id', 'consumable_id')->withPivot('id', 'quantity'); } /** @@ -171,7 +171,7 @@ class PredefinedKit extends SnipeModel */ public function accessories() { - return $this->belongsToMany('\App\Models\Accessory', 'kits_accessories', 'kit_id', 'accessory_id')->withPivot('id', 'quantity'); + return $this->belongsToMany(\App\Models\Accessory::class, 'kits_accessories', 'kit_id', 'accessory_id')->withPivot('id', 'quantity'); } /** @@ -179,5 +179,4 @@ class PredefinedKit extends SnipeModel * BEGIN QUERY SCOPES * ----------------------------------------------- **/ - } diff --git a/app/Models/Recipients/AdminRecipient.php b/app/Models/Recipients/AdminRecipient.php index a5311bbcda..0a15557caf 100644 --- a/app/Models/Recipients/AdminRecipient.php +++ b/app/Models/Recipients/AdminRecipient.php @@ -1,14 +1,14 @@ email = $settings->admin_cc_email; } - } diff --git a/app/Models/Requestable.php b/app/Models/Requestable.php index 5fc3f5450f..3983254e41 100644 --- a/app/Models/Requestable.php +++ b/app/Models/Requestable.php @@ -9,7 +9,6 @@ use Illuminate\Support\Facades\Auth; // $asset->whereRequestedBy($user) trait Requestable { - public function requests() { return $this->morphMany(CheckoutRequest::class, 'requestable'); @@ -17,7 +16,7 @@ trait Requestable public function isRequestedBy(User $user) { - return $this->requests->where('canceled_at', NULL)->where('user_id', $user->id)->first(); + return $this->requests->where('canceled_at', null)->where('user_id', $user->id)->first(); } public function scopeRequestedBy($query, User $user) diff --git a/app/Models/Setting.php b/app/Models/Setting.php index 13d7b38bc1..91e349f9fd 100755 --- a/app/Models/Setting.php +++ b/app/Models/Setting.php @@ -2,6 +2,7 @@ namespace App\Models; +use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Notifications\Notifiable; use Illuminate\Support\Collection; @@ -15,6 +16,7 @@ use Watson\Validating\ValidatingTrait; */ class Setting extends Model { + use HasFactory; use Notifiable, ValidatingTrait; /** @@ -96,7 +98,7 @@ class Setting extends Model * * @return \App\Models\Setting|null */ - public static function getSettings(): ?Setting + public static function getSettings(): ?self { return Cache::rememberForever(self::APP_SETTINGS_KEY, function () { // Need for setup as no tables exist @@ -106,7 +108,7 @@ class Setting extends Model return null; } }); - } + } /** * Check to see if setup process is complete. @@ -116,17 +118,16 @@ class Setting extends Model */ public static function setupCompleted(): bool { - try { - $usercount = User::withTrashed()->count(); - $settingsCount = self::count(); - return $usercount > 0 && $settingsCount > 0; - } catch (\Throwable $th) { - \Log::debug('User table and settings table DO NOT exist or DO NOT have records'); - // Catch the error if the tables dont exit - return false; - } - + try { + $usercount = User::withTrashed()->count(); + $settingsCount = self::count(); + return $usercount > 0 && $settingsCount > 0; + } catch (\Throwable $th) { + \Log::debug('User table and settings table DO NOT exist or DO NOT have records'); + // Catch the error if the tables dont exit + return false; + } } /** @@ -187,9 +188,9 @@ class Setting extends Model * Escapes the custom CSS, and then un-escapes the greater-than symbol * so it can work with direct descendant characters for bootstrap * menu overrides like:. - * + * * .skin-blue .sidebar-menu>li.active>a, .skin-blue .sidebar-menu>li:hover>a - * + * * Important: Do not remove the e() escaping here, as we output raw in the blade. * * @return string escaped CSS @@ -210,14 +211,14 @@ class Setting extends Model } /** - * Converts bytes into human readable file size. - * - * @param string $bytes + * Converts bytes into human readable file size. * - * @return string human readable file size (2,87 Мб) + * @param string $bytes * - * @author Mogilev Arseny - */ + * @return string human readable file size (2,87 Мб) + * + * @author Mogilev Arseny + */ public static function fileSizeConvert($bytes): string { $bytes = floatval($bytes); @@ -244,15 +245,15 @@ class Setting extends Model ], ]; - foreach ($arBytes as $arItem) { + foreach ($arBytes as $arItem) { if ($bytes >= $arItem['VALUE']) { $result = $bytes / $arItem['VALUE']; $result = round($result, 2).$arItem['UNIT']; - break; - } + break; } + } - return $result; + return $result; } /** @@ -307,8 +308,6 @@ class Setting extends Model return 'required|min:'.$settings->pwd_secure_min.$security_rules; } - - /** * Get the specific LDAP settings * diff --git a/app/Models/SnipeModel.php b/app/Models/SnipeModel.php index 2911be1c38..e5a039a4e1 100644 --- a/app/Models/SnipeModel.php +++ b/app/Models/SnipeModel.php @@ -14,7 +14,6 @@ class SnipeModel extends Model $value = null; } $this->attributes['purchase_date'] = $value; - return; } /** @@ -22,13 +21,12 @@ class SnipeModel extends Model */ public function setPurchaseCostAttribute($value) { - $value = Helper::ParseFloat($value); + $value = Helper::ParseFloat($value); if ($value == '0.0') { $value = null; } $this->attributes['purchase_cost'] = $value; - return; } public function setLocationIdAttribute($value) @@ -37,7 +35,6 @@ class SnipeModel extends Model $value = null; } $this->attributes['location_id'] = $value; - return; } public function setCategoryIdAttribute($value) @@ -47,7 +44,6 @@ class SnipeModel extends Model } $this->attributes['category_id'] = $value; // dd($this->attributes); - return; } public function setSupplierIdAttribute($value) @@ -56,7 +52,6 @@ class SnipeModel extends Model $value = null; } $this->attributes['supplier_id'] = $value; - return; } public function setDepreciationIdAttribute($value) @@ -65,7 +60,6 @@ class SnipeModel extends Model $value = null; } $this->attributes['depreciation_id'] = $value; - return; } public function setManufacturerIdAttribute($value) @@ -74,7 +68,6 @@ class SnipeModel extends Model $value = null; } $this->attributes['manufacturer_id'] = $value; - return; } public function setMinAmtAttribute($value) @@ -83,7 +76,6 @@ class SnipeModel extends Model $value = null; } $this->attributes['min_amt'] = $value; - return; } public function setParentIdAttribute($value) @@ -92,79 +84,70 @@ class SnipeModel extends Model $value = null; } $this->attributes['parent_id'] = $value; - return; } public function setFieldSetIdAttribute($value) { - if($value == '') { + if ($value == '') { $value = null; } $this->attributes['fieldset_id'] = $value; - return; } public function setCompanyIdAttribute($value) { - if($value == '') { + if ($value == '') { $value = null; } $this->attributes['company_id'] = $value; - return; } public function setWarrantyMonthsAttribute($value) { - if($value == '') { + if ($value == '') { $value = null; } $this->attributes['warranty_months'] = $value; - return; } public function setRtdLocationIdAttribute($value) { - if($value == '') { + if ($value == '') { $value = null; } $this->attributes['rtd_location_id'] = $value; - return; } public function setDepartmentIdAttribute($value) { - if($value == '') { + if ($value == '') { $value = null; } $this->attributes['department_id'] = $value; - return; } public function setManagerIdAttribute($value) { - if($value == '') { + if ($value == '') { $value = null; } $this->attributes['manager_id'] = $value; - return; } public function setModelIdAttribute($value) { - if($value == '') { + if ($value == '') { $value = null; } $this->attributes['model_id'] = $value; - return; } public function setStatusIdAttribute($value) { - if($value == '') { + if ($value == '') { $value = null; } $this->attributes['status_id'] = $value; - return; } // diff --git a/app/Models/Statuslabel.php b/app/Models/Statuslabel.php index fc252af714..da856b4b7f 100755 --- a/app/Models/Statuslabel.php +++ b/app/Models/Statuslabel.php @@ -1,30 +1,32 @@ 'required|string|unique_undeleted', 'notes' => 'string|nullable', 'deployable' => 'required', 'pending' => 'required', 'archived' => 'required', - ); + ]; protected $fillable = [ 'archived', @@ -35,22 +37,21 @@ class Statuslabel extends SnipeModel ]; use Searchable; - + /** * The attributes that should be included when searching the model. - * + * * @var array */ protected $searchableAttributes = ['name', 'notes']; /** * The relations and their attributes that should be included when searching the model. - * + * * @var array */ protected $searchableRelations = []; - /** * Establishes the status label -> assets relationship * @@ -60,7 +61,7 @@ class Statuslabel extends SnipeModel */ public function assets() { - return $this->hasMany('\App\Models\Asset', 'status_id'); + return $this->hasMany(\App\Models\Asset::class, 'status_id'); } /** @@ -72,17 +73,15 @@ class Statuslabel extends SnipeModel */ public function getStatuslabelType() { - - if (($this->pending == '1') && ($this->archived == '0') && ($this->deployable == '0')) { + if (($this->pending == '1') && ($this->archived == '0') && ($this->deployable == '0')) { return 'pending'; - } elseif (($this->pending == '0') && ($this->archived == '1') && ($this->deployable == '0')) { + } elseif (($this->pending == '0') && ($this->archived == '1') && ($this->deployable == '0')) { return 'archived'; - } elseif (($this->pending == '0') && ($this->archived == '0') && ($this->deployable == '0')) { + } elseif (($this->pending == '0') && ($this->archived == '0') && ($this->deployable == '0')) { return 'undeployable'; } return 'deployable'; - } /** @@ -130,7 +129,6 @@ class Statuslabel extends SnipeModel */ public static function getStatuslabelTypesForDB($type) { - $statustype['pending'] = 0; $statustype['deployable'] = 0; $statustype['archived'] = 0; @@ -139,12 +137,10 @@ class Statuslabel extends SnipeModel $statustype['pending'] = 1; $statustype['deployable'] = 0; $statustype['archived'] = 0; - } elseif ($type == 'deployable') { $statustype['pending'] = 0; $statustype['deployable'] = 1; $statustype['archived'] = 0; - } elseif ($type == 'archived') { $statustype['pending'] = 0; $statustype['deployable'] = 0; diff --git a/app/Models/Supplier.php b/app/Models/Supplier.php index 230a713cda..a96fdacdb6 100755 --- a/app/Models/Supplier.php +++ b/app/Models/Supplier.php @@ -1,18 +1,21 @@ 'required|min:1|max:255|unique_undeleted', 'address' => 'max:50|nullable', 'address2' => 'max:50|nullable', @@ -26,43 +29,40 @@ class Supplier extends SnipeModel 'email' => 'email|max:150|nullable', 'zip' => 'max:10|nullable', 'url' => 'sometimes|nullable|string|max:250', - ); + ]; /** - * 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 boolean - */ + * 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; use ValidatingTrait; use UniqueUndeletedTrait; - use Searchable; - + /** * The attributes that should be included when searching the model. - * + * * @var array */ protected $searchableAttributes = ['name']; /** * The relations and their attributes that should be included when searching the model. - * + * * @var array */ protected $searchableRelations = []; - /** * The attributes that are mass assignable. * * @var array */ - protected $fillable = ['name','address','address2','city','state','country','zip','phone','fax','email','contact','url','notes']; - + protected $fillable = ['name', 'address', 'address2', 'city', 'state', 'country', 'zip', 'phone', 'fax', 'email', 'contact', 'url', 'notes']; /** * Eager load counts @@ -106,7 +106,7 @@ class Supplier extends SnipeModel */ public function assets() { - return $this->hasMany('\App\Models\Asset', 'supplier_id'); + return $this->hasMany(\App\Models\Asset::class, 'supplier_id'); } /** @@ -118,7 +118,7 @@ class Supplier extends SnipeModel */ public function accessories() { - return $this->hasMany('\App\Models\Accessory', 'supplier_id'); + return $this->hasMany(\App\Models\Accessory::class, 'supplier_id'); } /** @@ -130,7 +130,7 @@ class Supplier extends SnipeModel */ public function asset_maintenances() { - return $this->hasMany('\App\Models\AssetMaintenance', 'supplier_id'); + return $this->hasMany(\App\Models\AssetMaintenance::class, 'supplier_id'); } /** @@ -158,7 +158,7 @@ class Supplier extends SnipeModel */ public function licenses() { - return $this->hasMany('\App\Models\License', 'supplier_id'); + return $this->hasMany(\App\Models\License::class, 'supplier_id'); } /** @@ -184,9 +184,10 @@ class Supplier extends SnipeModel */ public function addhttp($url) { - if (!preg_match("~^(?:f|ht)tps?://~i", $url)) { - $url = "http://" . $url; + if (! preg_match('~^(?:f|ht)tps?://~i', $url)) { + $url = 'http://'.$url; } + return $url; } } diff --git a/app/Models/Traits/Acceptable.php b/app/Models/Traits/Acceptable.php index 4da3575182..b0ddd665a6 100644 --- a/app/Models/Traits/Acceptable.php +++ b/app/Models/Traits/Acceptable.php @@ -9,20 +9,25 @@ use App\Models\User; * * @author Till Deeke */ -trait Acceptable { +trait Acceptable +{ /** * Run after the checkout acceptance was accepted by the user - * + * * @param User $acceptedBy * @param string $signature */ - public function acceptedCheckout(User $acceptedBy, $signature) {} + public function acceptedCheckout(User $acceptedBy, $signature) + { + } /** * Run after the checkout acceptance was declined by the user - * + * * @param User $acceptedBy * @param string $signature - */ - public function declinedCheckout(User $declinedBy, $signature) {} + */ + public function declinedCheckout(User $declinedBy, $signature) + { + } } diff --git a/app/Models/Traits/Searchable.php b/app/Models/Traits/Searchable.php index e43081e557..3661c66226 100644 --- a/app/Models/Traits/Searchable.php +++ b/app/Models/Traits/Searchable.php @@ -7,16 +7,16 @@ use App\Models\CustomField; use Illuminate\Database\Eloquent\Builder; /** - * This trait allows for cleaner searching of models, + * This trait allows for cleaner searching of models, * moving from complex queries to an easier declarative syntax. * * @author Till Deeke */ -trait Searchable { - +trait Searchable +{ /** * Performs a search on the model, using the provided search terms - * + * * @param \Illuminate\Database\Eloquent\Builder $query The query to start the search on * @param string $search * @return \Illuminate\Database\Eloquent\Builder A query with added "where" clauses @@ -27,13 +27,13 @@ trait Searchable { /** * Search the attributes of this model - */ + */ $query = $this->searchAttributes($query, $terms); /** * Search through the custom fields of the model */ - $query = $this->searchCustomFields($query, $terms); + $query = $this->searchCustomFields($query, $terms); /** * Search through the relations of the model @@ -53,32 +53,32 @@ trait Searchable { * @param string $search The search term * @return array An array of search terms */ - private function prepeareSearchTerms($search) { - return explode(' OR ', $search); - } + private function prepeareSearchTerms($search) + { + return explode(' OR ', $search); + } /** * Searches the models attributes for the search terms - * + * * @param Illuminate\Database\Eloquent\Builder $query * @param array $terms * @return Illuminate\Database\Eloquent\Builder */ - private function searchAttributes(Builder $query, array $terms) { - + private function searchAttributes(Builder $query, array $terms) + { $table = $this->getTable(); $firstConditionAdded = false; - foreach($this->getSearchableAttributes() as $column) { - - foreach($terms as $term) { + foreach ($this->getSearchableAttributes() as $column) { + foreach ($terms as $term) { /** * Making sure to only search in date columns if the search term consists of characters that can make up a MySQL timestamp! * * @see https://github.com/snipe/snipe-it/issues/4590 */ - if (!preg_match('/^[0-9 :-]++$/', $term) && in_array($column, $this->getDates())) { + if (! preg_match('/^[0-9 :-]++$/', $term) && in_array($column, $this->getDates())) { continue; } @@ -88,29 +88,30 @@ trait Searchable { * * @todo This does the job, but is inelegant and fragile */ - if (!$firstConditionAdded) { - $query = $query->where($table . '.' . $column, 'LIKE', '%'.$term.'%'); + if (! $firstConditionAdded) { + $query = $query->where($table.'.'.$column, 'LIKE', '%'.$term.'%'); $firstConditionAdded = true; continue; } - - $query = $query->orWhere($table . '.' . $column, 'LIKE', '%'.$term.'%'); + + $query = $query->orWhere($table.'.'.$column, 'LIKE', '%'.$term.'%'); } } - return $query; + return $query; } /** * Searches the models custom fields for the search terms - * - * @param Illuminate\Database\Eloquent\Builder $query + * + * @param Illuminate\Database\Eloquent\Builder $query * @param array $terms * @return Illuminate\Database\Eloquent\Builder */ - private function searchCustomFields(Builder $query, array $terms) { - + private function searchCustomFields(Builder $query, array $terms) + { + /** * If we are searching on something other that an asset, skip custom fields. */ @@ -121,29 +122,27 @@ trait Searchable { $customFields = CustomField::all(); foreach ($customFields as $field) { - foreach($terms as $term) { - $query->orWhere($this->getTable() . '.'. $field->db_column_name(), 'LIKE', '%'.$term.'%'); + foreach ($terms as $term) { + $query->orWhere($this->getTable().'.'.$field->db_column_name(), 'LIKE', '%'.$term.'%'); } } - return $query; - } + return $query; + } /** * Searches the models relations for the search terms - * + * * @param Illuminate\Database\Eloquent\Builder $query * @param array $terms * @return Illuminate\Database\Eloquent\Builder */ - private function searchRelations(Builder $query, array $terms) { - - foreach($this->getSearchableRelations() as $relation => $columns) { - - $query = $query->orWhereHas($relation, function($query) use ($relation, $columns, $terms) { - + private function searchRelations(Builder $query, array $terms) + { + foreach ($this->getSearchableRelations() as $relation => $columns) { + $query = $query->orWhereHas($relation, function ($query) use ($relation, $columns, $terms) { $table = $this->getRelationTable($relation); - + /** * We need to form the query properly, starting with a "where", * otherwise the generated nested select is wrong. @@ -152,72 +151,75 @@ trait Searchable { */ $firstConditionAdded = false; - foreach($columns as $column) { - foreach($terms as $term) { - if (!$firstConditionAdded) { - $query->where($table . '.' . $column, 'LIKE', '%'.$term.'%'); + foreach ($columns as $column) { + foreach ($terms as $term) { + if (! $firstConditionAdded) { + $query->where($table.'.'.$column, 'LIKE', '%'.$term.'%'); $firstConditionAdded = true; continue; } - $query->orWhere($table . '.' . $column, 'LIKE', '%'.$term.'%'); + $query->orWhere($table.'.'.$column, 'LIKE', '%'.$term.'%'); } } }); + } - } - - return $query; + return $query; } /** * Run additional, advanced searches that can't be done using the attributes or relations. * * This is a noop in this trait, but can be overridden in the implementing model, to allow more advanced searches - * + * * @param Illuminate\Database\Eloquent\Builder $query * @param array $terms The search terms * @return Illuminate\Database\Eloquent\Builder * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function advancedTextSearch(Builder $query, array $terms) { + public function advancedTextSearch(Builder $query, array $terms) + { return $query; - } + } /** * Get the searchable attributes, if defined. Otherwise it returns an empty array - * + * * @return array The attributes to search in */ - private function getSearchableAttributes() { + private function getSearchableAttributes() + { return isset($this->searchableAttributes) ? $this->searchableAttributes : []; } /** * Get the searchable relations, if defined. Otherwise it returns an empty array - * + * * @return array The relations to search in - */ - private function getSearchableRelations() { + */ + private function getSearchableRelations() + { return isset($this->searchableRelations) ? $this->searchableRelations : []; } /** * Get the table name of a relation. * - * This method loops over a relation name, + * This method loops over a relation name, * getting the table name of the last relation in the series. - * So "category" would get the table name for the Category model, + * So "category" would get the table name for the Category model, * "model.manufacturer" would get the tablename for the Manufacturer model. - * + * * @param string $relation * @return string The table name */ - private function getRelationTable($relation) { + private function getRelationTable($relation) + { $related = $this; - foreach(explode('.', $relation) as $relationName) { + foreach (explode('.', $relation) as $relationName) { $related = $related->{$relationName}()->getRelated(); } @@ -249,6 +251,6 @@ trait Searchable { return implode('_', $parts->toArray()); } - return $related->getTable(); + return $related->getTable(); } } diff --git a/app/Models/User.php b/app/Models/User.php index 9f7ad20af2..492dece3ff 100755 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -1,4 +1,5 @@ 'exists:locations,id|nullable', ]; - /** * The attributes that should be included when searching the model. * @@ -96,7 +98,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo 'notes', 'phone', 'jobtitle', - 'employee_num' + 'employee_num', ]; /** @@ -109,21 +111,19 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo 'department' => ['name'], 'groups' => ['name'], 'company' => ['name'], - 'manager' => ['first_name', 'last_name', 'username'] + 'manager' => ['first_name', 'last_name', 'username'], ]; - /** * Internally check the user permission for the given section * - * @return boolean + * @return bool */ protected function checkPermissionSection($section) { $user_groups = $this->groups; + if (($this->permissions == '') && (count($user_groups) == 0)) { - - if (($this->permissions=='') && (count($user_groups) == 0)) { return false; } @@ -131,18 +131,18 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo $is_user_section_permissions_set = ($user_permissions != '') && array_key_exists($section, $user_permissions); //If the user is explicitly granted, return true - if ($is_user_section_permissions_set && ($user_permissions[$section]=='1')) { + if ($is_user_section_permissions_set && ($user_permissions[$section] == '1')) { return true; } // If the user is explicitly denied, return false - if ($is_user_section_permissions_set && ($user_permissions[$section]=='-1')) { + if ($is_user_section_permissions_set && ($user_permissions[$section] == '-1')) { return false; } // Loop through the groups to see if any of them grant this permission foreach ($user_groups as $user_group) { $group_permissions = (array) json_decode($user_group->permissions, true); - if (((array_key_exists($section, $group_permissions)) && ($group_permissions[$section]=='1'))) { + if (((array_key_exists($section, $group_permissions)) && ($group_permissions[$section] == '1'))) { return true; } } @@ -158,13 +158,14 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo * * @author A. Gianotto * @since [v1.0] - * @return boolean + * @return bool */ public function hasAccess($section) { if ($this->isSuperUser()) { return true; } + return $this->checkPermissionSection($section); } @@ -173,7 +174,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo * * @author A. Gianotto * @since [v1.0] - * @return boolean + * @return bool */ public function isSuperUser() { @@ -190,7 +191,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo */ public function company() { - return $this->belongsTo('\App\Models\Company', 'company_id'); + return $this->belongsTo(\App\Models\Company::class, 'company_id'); } /** @@ -202,7 +203,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo */ public function department() { - return $this->belongsTo('\App\Models\Department', 'department_id'); + return $this->belongsTo(\App\Models\Department::class, 'department_id'); } /** @@ -210,11 +211,11 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo * * @author A. Gianotto * @since [v1.0] - * @return boolean + * @return bool */ public function isActivated() { - return $this->activated ==1; + return $this->activated == 1; } /** @@ -226,7 +227,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo */ public function getFullNameAttribute() { - return $this->first_name . " " . $this->last_name; + return $this->first_name.' '.$this->last_name; } /** @@ -240,7 +241,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo */ public function getCompleteNameAttribute() { - return $this->last_name . ", " . $this->first_name . " (" . $this->username . ")"; + return $this->last_name.', '.$this->first_name.' ('.$this->username.')'; } /** @@ -253,10 +254,10 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo // At this point the endpoint is the same for everything. // In the future this may want to be adapted for individual notifications. $this->endpoint = \App\Models\Setting::getSettings()->slack_endpoint; + return $this->endpoint; } - /** * Establishes the user -> assets relationship * @@ -266,7 +267,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo */ public function assets() { - return $this->morphMany('App\Models\Asset', 'assigned', 'assigned_type', 'assigned_to')->withTrashed(); + return $this->morphMany(\App\Models\Asset::class, 'assigned', 'assigned_type', 'assigned_to')->withTrashed(); } /** @@ -281,7 +282,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo */ public function assetmaintenances() { - return $this->hasMany('\App\Models\AssetMaintenance', 'user_id')->withTrashed(); + return $this->hasMany(\App\Models\AssetMaintenance::class, 'user_id')->withTrashed(); } /** @@ -293,7 +294,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo */ public function accessories() { - return $this->belongsToMany('\App\Models\Accessory', 'accessories_users', 'assigned_to', 'accessory_id') + return $this->belongsToMany(\App\Models\Accessory::class, 'accessories_users', 'assigned_to', 'accessory_id') ->withPivot('id', 'created_at', 'note')->withTrashed(); } @@ -306,7 +307,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo */ public function consumables() { - return $this->belongsToMany('\App\Models\Consumable', 'consumables_users', 'assigned_to', 'consumable_id')->withPivot('id')->withTrashed(); + return $this->belongsToMany(\App\Models\Consumable::class, 'consumables_users', 'assigned_to', 'consumable_id')->withPivot('id')->withTrashed(); } /** @@ -318,7 +319,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo */ public function licenses() { - return $this->belongsToMany('\App\Models\License', 'license_seats', 'assigned_to', 'license_id')->withPivot('id'); + return $this->belongsToMany(\App\Models\License::class, 'license_seats', 'assigned_to', 'license_id')->withPivot('id'); } /** @@ -330,10 +331,9 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo */ public function userlog() { - return $this->hasMany('\App\Models\Actionlog', 'target_id')->where('target_type', '=', 'App\Models\User')->orderBy('created_at', 'DESC')->withTrashed(); + return $this->hasMany(\App\Models\Actionlog::class, 'target_id')->where('target_type', '=', self::class)->orderBy('created_at', 'DESC')->withTrashed(); } - /** * Establishes the user -> location relationship * @@ -345,13 +345,11 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo * @since [v4.0] * @return \Illuminate\Database\Eloquent\Relations\Relation */ - public function userloc() { - return $this->belongsTo('\App\Models\Location', 'location_id')->withTrashed(); + return $this->belongsTo(\App\Models\Location::class, 'location_id')->withTrashed(); } - /** * Establishes the user -> location relationship * @@ -361,7 +359,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo */ public function location() { - return $this->belongsTo('\App\Models\Location', 'location_id')->withTrashed(); + return $this->belongsTo(\App\Models\Location::class, 'location_id')->withTrashed(); } /** @@ -373,7 +371,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo */ public function manager() { - return $this->belongsTo('\App\Models\User', 'manager_id')->withTrashed(); + return $this->belongsTo(self::class, 'manager_id')->withTrashed(); } /** @@ -385,7 +383,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo */ public function managedLocations() { - return $this->hasMany('\App\Models\Location', 'manager_id'); + return $this->hasMany(\App\Models\Location::class, 'manager_id'); } /** @@ -397,7 +395,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo */ public function groups() { - return $this->belongsToMany('\App\Models\Group', 'users_groups'); + return $this->belongsToMany(\App\Models\Group::class, 'users_groups'); } /** @@ -409,7 +407,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo */ public function assetlog() { - return $this->hasMany('\App\Models\Asset', 'id')->withTrashed(); + return $this->hasMany(\App\Models\Asset::class, 'id')->withTrashed(); } /** @@ -423,8 +421,8 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo */ public function uploads() { - return $this->hasMany('\App\Models\Actionlog', 'item_id') - ->where('item_type', User::class) + return $this->hasMany(\App\Models\Actionlog::class, 'item_id') + ->where('item_type', self::class) ->where('action_type', '=', 'uploaded') ->whereNotNull('filename') ->orderBy('created_at', 'desc'); @@ -485,7 +483,8 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo */ public static function generateEmailFromFullName($name) { - $username = User::generateFormattedNameFromFullName($name, Setting::getSettings()->email_format); + $username = self::generateFormattedNameFromFullName($name, Setting::getSettings()->email_format); + return $username['username'].'@'.Setting::getSettings()->email_domain; } @@ -496,40 +495,30 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo if (strpos($users_name, ' ') === false) { $first_name = $users_name; $last_name = ''; - $username = $users_name; - + $username = $users_name; } else { - - list($first_name, $last_name) = explode(" ", $users_name, 2); + list($first_name, $last_name) = explode(' ', $users_name, 2); // Assume filastname by default $username = str_slug(substr($first_name, 0, 1).$last_name); - if ($format=='firstname.lastname') { - $username = str_slug($first_name) . '.' . str_slug($last_name); - - } elseif ($format=='lastnamefirstinitial') { + if ($format == 'firstname.lastname') { + $username = str_slug($first_name).'.'.str_slug($last_name); + } elseif ($format == 'lastnamefirstinitial') { $username = str_slug($last_name.substr($first_name, 0, 1)); - - } elseif ($format=='firstintial.lastname') { + } elseif ($format == 'firstintial.lastname') { $username = substr($first_name, 0, 1).'.'.str_slug($last_name); - - } elseif ($format=='firstname_lastname') { + } elseif ($format == 'firstname_lastname') { $username = str_slug($first_name).'_'.str_slug($last_name); - - } elseif ($format=='firstname') { + } elseif ($format == 'firstname') { $username = str_slug($first_name); - } - elseif ($format=='firstinitial.lastname') { - $username = str_slug(substr($first_name, 0, 1). '.' . str_slug($last_name)); - } - elseif ($format=='lastname_firstinitial') { + } elseif ($format == 'firstinitial.lastname') { + $username = str_slug(substr($first_name, 0, 1).'.'.str_slug($last_name)); + } elseif ($format == 'lastname_firstinitial') { $username = str_slug($last_name).'_'.str_slug(substr($first_name, 0, 1)); - } - elseif ($format=='firstnamelastname') { - $username = str_slug($first_name) . str_slug($last_name); - } - elseif ($format=='firstnamelastinitial') { + } elseif ($format == 'firstnamelastname') { + $username = str_slug($first_name).str_slug($last_name); + } elseif ($format == 'firstnamelastinitial') { $username = str_slug(($first_name.substr($last_name, 0, 1))); } } @@ -537,9 +526,8 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo $user['first_name'] = $first_name; $user['last_name'] = $last_name; $user['username'] = strtolower($username); + return $user; - - } /** @@ -554,21 +542,19 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo * * @return bool */ - public function two_factor_active () { + public function two_factor_active() + { // If the 2FA is optional and the user has opted in - if ((Setting::getSettings()->two_factor_enabled =='1') && ($this->two_factor_optin =='1')) - { + if ((Setting::getSettings()->two_factor_enabled == '1') && ($this->two_factor_optin == '1')) { return true; } // If the 2FA is required for everyone so is implicitly active - elseif (Setting::getSettings()->two_factor_enabled =='2') - { + elseif (Setting::getSettings()->two_factor_enabled == '2') { return true; } return false; - } /** @@ -584,20 +570,19 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo * * @return bool */ - public function two_factor_active_and_enrolled () { + public function two_factor_active_and_enrolled() + { // If the 2FA is optional and the user has opted in and is enrolled - if ((Setting::getSettings()->two_factor_enabled =='1') && ($this->two_factor_optin =='1') && ($this->two_factor_enrolled =='1')) - { + if ((Setting::getSettings()->two_factor_enabled == '1') && ($this->two_factor_optin == '1') && ($this->two_factor_enrolled == '1')) { return true; } // If the 2FA is required for everyone and the user has enrolled - elseif ((Setting::getSettings()->two_factor_enabled =='2') && ($this->two_factor_enrolled)) - { + elseif ((Setting::getSettings()->two_factor_enabled == '2') && ($this->two_factor_enrolled)) { return true; } - return false; + return false; } @@ -615,16 +600,16 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo * @param array $terms The search terms * @return \Illuminate\Database\Query\Builder */ - public function scopeSimpleNameSearch($query, $search) { - + public function scopeSimpleNameSearch($query, $search) + { $query = $query->where('first_name', 'LIKE', '%'.$search.'%') ->orWhere('last_name', 'LIKE', '%'.$search.'%') ->orWhereRaw('CONCAT('.DB::getTablePrefix().'users.first_name," ",'.DB::getTablePrefix().'users.last_name) LIKE ?', ["%$search%"]); + return $query; } - /** * Run additional, advanced searches. * @@ -648,13 +633,13 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo * @param int $id * @return \Illuminate\Database\Query\Builder */ - public function scopeByGroup($query, $id) { + public function scopeByGroup($query, $id) + { return $query->whereHas('groups', function ($query) use ($id) { $query->where('permission_groups.id', '=', $id); }); } - /** * Query builder scope to order on manager * @@ -682,7 +667,6 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo return $query->leftJoin('locations as locations_users', 'users.location_id', '=', 'locations_users.id')->orderBy('locations_users.name', $order); } - /** * Query builder scope to order on department * @@ -709,9 +693,8 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo return $query->leftJoin('companies as companies_user', 'users.company_id', '=', 'companies_user.id')->orderBy('companies_user.name', $order); } - public function preferredLocale(){ + public function preferredLocale() + { return $this->locale; } - - } diff --git a/app/Notifications/AuditNotification.php b/app/Notifications/AuditNotification.php index 900650e975..84f1753767 100644 --- a/app/Notifications/AuditNotification.php +++ b/app/Notifications/AuditNotification.php @@ -43,15 +43,14 @@ class AuditNotification extends Notification public function toSlack() { - return (new SlackMessage) ->success() - ->content(class_basename(get_class($this->params['item'])) . " Audited") + ->content(class_basename(get_class($this->params['item'])).' Audited') ->attachment(function ($attachment) { $item = $this->params['item']; $admin_user = $this->params['admin']; $fields = [ - 'By' => '<'.$admin_user->present()->viewUrl().'|'.$admin_user->present()->fullName().'>' + 'By' => '<'.$admin_user->present()->viewUrl().'|'.$admin_user->present()->fullName().'>', ]; array_key_exists('note', $this->params) && $fields['Notes'] = $this->params['note']; array_key_exists('location', $this->params) && $fields['Location'] = $this->params['location']; diff --git a/app/Notifications/CheckinAccessoryNotification.php b/app/Notifications/CheckinAccessoryNotification.php index ba7c3b2011..f9abba59f9 100644 --- a/app/Notifications/CheckinAccessoryNotification.php +++ b/app/Notifications/CheckinAccessoryNotification.php @@ -21,10 +21,10 @@ class CheckinAccessoryNotification extends Notification */ public function __construct(Accessory $accessory, $checkedOutTo, User $checkedInby, $note) { - $this->item = $accessory; - $this->target = $checkedOutTo; - $this->admin = $checkedInby; - $this->note = $note; + $this->item = $accessory; + $this->target = $checkedOutTo; + $this->admin = $checkedInby; + $this->note = $note; $this->settings = Setting::getSettings(); \Log::debug('Constructor for notification fired'); } @@ -43,16 +43,14 @@ class CheckinAccessoryNotification extends Notification $notifyBy[] = 'slack'; } - if (Setting::getSettings()->slack_endpoint!='') { + if (Setting::getSettings()->slack_endpoint != '') { $notifyBy[] = 'slack'; } - /** * Only send notifications to users that have email addresses */ if ($this->target instanceof User && $this->target->email != '') { - \Log::debug('The target is a user'); /** @@ -63,16 +61,12 @@ class CheckinAccessoryNotification extends Notification $notifyBy[] = 'mail'; } - - - - /** * Send an email if the asset requires acceptance, * so the user can accept or decline the asset */ if ($this->item->requireAcceptance()) { - \Log::debug('This accessory requires acceptance'); + \Log::debug('This accessory requires acceptance'); } /** @@ -88,7 +82,6 @@ class CheckinAccessoryNotification extends Notification if ($this->item->checkin_email()) { \Log::debug('This accessory has a checkin_email()'); } - } \Log::debug('checkin_email on this category is '.$this->item->checkin_email()); @@ -98,12 +91,11 @@ class CheckinAccessoryNotification extends Notification public function toSlack() { - $target = $this->target; $admin = $this->admin; $item = $this->item; $note = $this->note; - $botname = ($this->settings->slack_botname) ? $this->settings->slack_botname : 'Snipe-Bot' ; + $botname = ($this->settings->slack_botname) ? $this->settings->slack_botname : 'Snipe-Bot'; $fields = [ 'To' => '<'.$target->present()->viewUrl().'|'.$target->present()->fullName().'>', @@ -119,6 +111,7 @@ class CheckinAccessoryNotification extends Notification ->content($note); }); } + /** * Get the mail representation of the notification. * @@ -128,6 +121,7 @@ class CheckinAccessoryNotification extends Notification public function toMail() { \Log::debug('to email called'); + return (new MailMessage)->markdown('notifications.markdown.checkin-accessory', [ 'item' => $this->item, @@ -136,6 +130,5 @@ class CheckinAccessoryNotification extends Notification 'target' => $this->target, ]) ->subject(trans('mail.Accessory_Checkin_Notification')); - } } diff --git a/app/Notifications/CheckinAssetNotification.php b/app/Notifications/CheckinAssetNotification.php index e0f1e66f3a..df2665beaa 100644 --- a/app/Notifications/CheckinAssetNotification.php +++ b/app/Notifications/CheckinAssetNotification.php @@ -14,7 +14,6 @@ class CheckinAssetNotification extends Notification { use Queueable; - /** * Create a new notification instance. * @@ -23,9 +22,9 @@ class CheckinAssetNotification extends Notification public function __construct(Asset $asset, $checkedOutTo, User $checkedInBy, $note) { $this->target = $checkedOutTo; - $this->item = $asset; - $this->admin = $checkedInBy; - $this->note = $note; + $this->item = $asset; + $this->admin = $checkedInBy; + $this->note = $note; $this->settings = Setting::getSettings(); $this->expected_checkin = ''; @@ -43,10 +42,9 @@ class CheckinAssetNotification extends Notification */ public function via() { - $notifyBy = []; - if (Setting::getSettings()->slack_endpoint!='') { + if (Setting::getSettings()->slack_endpoint != '') { \Log::debug('use slack'); $notifyBy[] = 'slack'; } @@ -55,8 +53,7 @@ class CheckinAssetNotification extends Notification * Only send checkin notifications to users if the category * has the corresponding checkbox checked. */ - if ($this->item->checkin_email() && $this->target instanceof User && $this->target->email != '') - { + if ($this->item->checkin_email() && $this->target instanceof User && $this->target->email != '') { \Log::debug('use email'); $notifyBy[] = 'mail'; } @@ -66,11 +63,10 @@ class CheckinAssetNotification extends Notification public function toSlack() { - $admin = $this->admin; $item = $this->item; $note = $this->note; - $botname = ($this->settings->slack_botname!='') ? $this->settings->slack_botname : 'Snipe-Bot' ; + $botname = ($this->settings->slack_botname != '') ? $this->settings->slack_botname : 'Snipe-Bot'; $fields = [ trans('general.administrator') => '<'.$admin->present()->viewUrl().'|'.$admin->present()->fullName().'>', @@ -86,8 +82,6 @@ class CheckinAssetNotification extends Notification ->fields($fields) ->content($note); }); - - } /** @@ -115,8 +109,6 @@ class CheckinAssetNotification extends Notification ]) ->subject(trans('mail.Asset_Checkin_Notification')); - return $message; } - } diff --git a/app/Notifications/CheckinLicenseSeatNotification.php b/app/Notifications/CheckinLicenseSeatNotification.php index a3bfb039e2..faeafecb1b 100644 --- a/app/Notifications/CheckinLicenseSeatNotification.php +++ b/app/Notifications/CheckinLicenseSeatNotification.php @@ -41,7 +41,7 @@ class CheckinLicenseSeatNotification extends Notification { $notifyBy = []; - if (Setting::getSettings()->slack_endpoint!='') { + if (Setting::getSettings()->slack_endpoint != '') { $notifyBy[] = 'slack'; } @@ -49,8 +49,7 @@ class CheckinLicenseSeatNotification extends Notification * Only send checkin notifications to users if the category * has the corresponding checkbox checked. */ - if ($this->item->checkin_email() && $this->target instanceof User && $this->target->email != '') - { + if ($this->item->checkin_email() && $this->target instanceof User && $this->target->email != '') { $notifyBy[] = 'mail'; } @@ -59,13 +58,11 @@ class CheckinLicenseSeatNotification extends Notification public function toSlack() { - $target = $this->target; $admin = $this->admin; $item = $this->item; $note = $this->note; - $botname = ($this->settings->slack_botname) ? $this->settings->slack_botname : 'Snipe-Bot' ; - + $botname = ($this->settings->slack_botname) ? $this->settings->slack_botname : 'Snipe-Bot'; if ($admin) { $fields = [ @@ -79,9 +76,6 @@ class CheckinLicenseSeatNotification extends Notification ]; } - - - return (new SlackMessage) ->content(':arrow_down: :floppy_disk: '.trans('mail.License_Checkin_Notification')) ->from($botname) @@ -91,6 +85,7 @@ class CheckinLicenseSeatNotification extends Notification ->content($note); }); } + /** * Get the mail representation of the notification. * @@ -107,7 +102,5 @@ class CheckinLicenseSeatNotification extends Notification 'target' => $this->target, ]) ->subject(trans('mail.License_Checkin_Notification')); - } - } diff --git a/app/Notifications/CheckoutAccessoryNotification.php b/app/Notifications/CheckoutAccessoryNotification.php index 2c2001253d..5882fdf275 100644 --- a/app/Notifications/CheckoutAccessoryNotification.php +++ b/app/Notifications/CheckoutAccessoryNotification.php @@ -19,7 +19,6 @@ class CheckoutAccessoryNotification extends Notification */ public function __construct(Accessory $accessory, $checkedOutTo, User $checkedOutBy, $acceptance, $note) { - $this->item = $accessory; $this->admin = $checkedOutBy; $this->note = $note; @@ -27,7 +26,6 @@ class CheckoutAccessoryNotification extends Notification $this->acceptance = $acceptance; $this->settings = Setting::getSettings(); - } /** @@ -37,14 +35,12 @@ class CheckoutAccessoryNotification extends Notification */ public function via() { - $notifyBy = []; - if (Setting::getSettings()->slack_endpoint!='') { + if (Setting::getSettings()->slack_endpoint != '') { $notifyBy[] = 'slack'; } - /** * Only send notifications to users that have email addresses */ @@ -71,7 +67,6 @@ class CheckoutAccessoryNotification extends Notification if ($this->item->checkin_email()) { $notifyBy[1] = 'mail'; } - } return $notifyBy; @@ -83,7 +78,7 @@ class CheckoutAccessoryNotification extends Notification $admin = $this->admin; $item = $this->item; $note = $this->note; - $botname = ($this->settings->slack_botname) ? $this->settings->slack_botname : 'Snipe-Bot' ; + $botname = ($this->settings->slack_botname) ? $this->settings->slack_botname : 'Snipe-Bot'; $fields = [ 'To' => '<'.$target->present()->viewUrl().'|'.$target->present()->fullName().'>', @@ -99,6 +94,7 @@ class CheckoutAccessoryNotification extends Notification ->content($note); }); } + /** * Get the mail representation of the notification. * @@ -107,7 +103,7 @@ class CheckoutAccessoryNotification extends Notification public function toMail() { \Log::debug($this->item->getImageUrl()); - $eula = $this->item->getEula(); + $eula = $this->item->getEula(); $req_accept = $this->item->requireAcceptance(); $accept_url = is_null($this->acceptance) ? null : route('account.accept.item', $this->acceptance); @@ -123,6 +119,5 @@ class CheckoutAccessoryNotification extends Notification 'accept_url' => $accept_url, ]) ->subject(trans('mail.Confirm_accessory_delivery')); - } } diff --git a/app/Notifications/CheckoutAssetNotification.php b/app/Notifications/CheckoutAssetNotification.php index ff759f68ef..791f0c1c32 100644 --- a/app/Notifications/CheckoutAssetNotification.php +++ b/app/Notifications/CheckoutAssetNotification.php @@ -21,7 +21,6 @@ class CheckoutAssetNotification extends Notification */ public function __construct(Asset $asset, $checkedOutTo, User $checkedOutBy, $acceptance, $note) { - $this->item = $asset; $this->admin = $checkedOutBy; $this->note = $note; @@ -42,8 +41,6 @@ class CheckoutAssetNotification extends Notification $this->expected_checkin = \App\Helpers\Helper::getFormattedDateObject($this->item->expected_checkin, 'date', false); } - - } /** @@ -53,10 +50,9 @@ class CheckoutAssetNotification extends Notification */ public function via() { - $notifyBy = []; - if (Setting::getSettings()->slack_endpoint!='') { + if (Setting::getSettings()->slack_endpoint != '') { \Log::debug('use slack'); $notifyBy[] = 'slack'; } @@ -87,7 +83,6 @@ class CheckoutAssetNotification extends Notification if ($this->item->checkin_email()) { $notifyBy[1] = 'mail'; } - } return $notifyBy; @@ -95,19 +90,18 @@ class CheckoutAssetNotification extends Notification public function toSlack() { - $target = $this->target; $admin = $this->admin; $item = $this->item; $note = $this->note; - $botname = ($this->settings->slack_botname) ? $this->settings->slack_botname : 'Snipe-Bot' ; + $botname = ($this->settings->slack_botname) ? $this->settings->slack_botname : 'Snipe-Bot'; $fields = [ 'To' => '<'.$target->present()->viewUrl().'|'.$target->present()->fullName().'>', 'By' => '<'.$admin->present()->viewUrl().'|'.$admin->present()->fullName().'>', ]; - if (($this->expected_checkin) && ($this->expected_checkin!='')) { + if (($this->expected_checkin) && ($this->expected_checkin != '')) { $fields['Expected Checkin'] = $this->expected_checkin; } @@ -120,6 +114,7 @@ class CheckoutAssetNotification extends Notification ->content($note); }); } + /** * Get the mail representation of the notification. * @@ -128,8 +123,7 @@ class CheckoutAssetNotification extends Notification */ public function toMail() { - - $eula = method_exists($this->item, 'getEula') ? $this->item->getEula() : ''; + $eula = method_exists($this->item, 'getEula') ? $this->item->getEula() : ''; $req_accept = method_exists($this->item, 'requireAcceptance') ? $this->item->requireAcceptance() : 0; $fields = []; @@ -156,9 +150,6 @@ class CheckoutAssetNotification extends Notification ]) ->subject(trans('mail.Confirm_asset_delivery')); - return $message; - } - } diff --git a/app/Notifications/CheckoutConsumableNotification.php b/app/Notifications/CheckoutConsumableNotification.php index edf970789d..bfebe2c7d5 100644 --- a/app/Notifications/CheckoutConsumableNotification.php +++ b/app/Notifications/CheckoutConsumableNotification.php @@ -25,7 +25,6 @@ class CheckoutConsumableNotification extends Notification */ public function __construct(Consumable $consumable, $checkedOutTo, User $checkedOutBy, $acceptance, $note) { - $this->item = $consumable; $this->admin = $checkedOutBy; $this->note = $note; @@ -33,7 +32,6 @@ class CheckoutConsumableNotification extends Notification $this->acceptance = $acceptance; $this->settings = Setting::getSettings(); - } /** @@ -45,7 +43,7 @@ class CheckoutConsumableNotification extends Notification { $notifyBy = []; - if (Setting::getSettings()->slack_endpoint!='') { + if (Setting::getSettings()->slack_endpoint != '') { $notifyBy[] = 'slack'; } @@ -72,12 +70,9 @@ class CheckoutConsumableNotification extends Notification /** * Send an email if an email should be sent at checkin/checkout */ - if ((method_exists($this->item, 'checkin_email')) && ($this->item->checkin_email())) { - $notifyBy[1] = 'mail'; } - } return $notifyBy; @@ -89,7 +84,7 @@ class CheckoutConsumableNotification extends Notification $admin = $this->admin; $item = $this->item; $note = $this->note; - $botname = ($this->settings->slack_botname) ? $this->settings->slack_botname : 'Snipe-Bot' ; + $botname = ($this->settings->slack_botname) ? $this->settings->slack_botname : 'Snipe-Bot'; $fields = [ 'To' => '<'.$target->present()->viewUrl().'|'.$target->present()->fullName().'>', @@ -105,6 +100,7 @@ class CheckoutConsumableNotification extends Notification ->content($note); }); } + /** * Get the mail representation of the notification. * @@ -112,9 +108,8 @@ class CheckoutConsumableNotification extends Notification */ public function toMail() { - \Log::debug($this->item->getImageUrl()); - $eula = $this->item->getEula(); + $eula = $this->item->getEula(); $req_accept = $this->item->requireAcceptance(); $accept_url = is_null($this->acceptance) ? null : route('account.accept.item', $this->acceptance); @@ -130,7 +125,5 @@ class CheckoutConsumableNotification extends Notification 'accept_url' => $accept_url, ]) ->subject(trans('mail.Confirm_consumable_delivery')); - } - } diff --git a/app/Notifications/CheckoutLicenseSeatNotification.php b/app/Notifications/CheckoutLicenseSeatNotification.php index 3ec2c1f9ae..50d8313c09 100644 --- a/app/Notifications/CheckoutLicenseSeatNotification.php +++ b/app/Notifications/CheckoutLicenseSeatNotification.php @@ -43,7 +43,7 @@ class CheckoutLicenseSeatNotification extends Notification { $notifyBy = []; - if (Setting::getSettings()->slack_endpoint!='') { + if (Setting::getSettings()->slack_endpoint != '') { $notifyBy[] = 'slack'; } @@ -73,7 +73,6 @@ class CheckoutLicenseSeatNotification extends Notification if ($this->item->checkin_email()) { $notifyBy[1] = 'mail'; } - } return $notifyBy; @@ -85,7 +84,7 @@ class CheckoutLicenseSeatNotification extends Notification $admin = $this->admin; $item = $this->item; $note = $this->note; - $botname = ($this->settings->slack_botname) ? $this->settings->slack_botname : 'Snipe-Bot' ; + $botname = ($this->settings->slack_botname) ? $this->settings->slack_botname : 'Snipe-Bot'; $fields = [ 'To' => '<'.$target->present()->viewUrl().'|'.$target->present()->fullName().'>', @@ -101,6 +100,7 @@ class CheckoutLicenseSeatNotification extends Notification ->content($note); }); } + /** * Get the mail representation of the notification. * @@ -108,8 +108,7 @@ class CheckoutLicenseSeatNotification extends Notification */ public function toMail() { - - $eula = method_exists($this->item, 'getEula') ? $this->item->getEula() : ''; + $eula = method_exists($this->item, 'getEula') ? $this->item->getEula() : ''; $req_accept = method_exists($this->item, 'requireAcceptance') ? $this->item->requireAcceptance() : 0; $accept_url = is_null($this->acceptance) ? null : route('account.accept.item', $this->acceptance); @@ -125,7 +124,5 @@ class CheckoutLicenseSeatNotification extends Notification 'accept_url' => $accept_url, ]) ->subject(trans('mail.Confirm_license_delivery')); - } - } diff --git a/app/Notifications/ExpectedCheckinAdminNotification.php b/app/Notifications/ExpectedCheckinAdminNotification.php index 7f29a915f5..67c709f98d 100644 --- a/app/Notifications/ExpectedCheckinAdminNotification.php +++ b/app/Notifications/ExpectedCheckinAdminNotification.php @@ -32,7 +32,8 @@ class ExpectedCheckinAdminNotification extends Notification public function via() { $notifyBy = []; - $notifyBy[]='mail'; + $notifyBy[] = 'mail'; + return $notifyBy; } @@ -43,7 +44,6 @@ class ExpectedCheckinAdminNotification extends Notification */ public function toMail() { - $message = (new MailMessage)->markdown('notifications.markdown.report-expected-checkins', [ 'assets' => $this->assets, @@ -51,8 +51,5 @@ class ExpectedCheckinAdminNotification extends Notification ->subject(trans('mail.Expected_Checkin_Report')); return $message; - - } - } diff --git a/app/Notifications/ExpectedCheckinNotification.php b/app/Notifications/ExpectedCheckinNotification.php index dadd920cf0..6248b72779 100644 --- a/app/Notifications/ExpectedCheckinNotification.php +++ b/app/Notifications/ExpectedCheckinNotification.php @@ -35,7 +35,8 @@ class ExpectedCheckinNotification extends Notification $notifyBy = []; $item = $this->params['item']; - $notifyBy[]='mail'; + $notifyBy[] = 'mail'; + return $notifyBy; } @@ -46,18 +47,15 @@ class ExpectedCheckinNotification extends Notification */ public function toMail() { - $message = (new MailMessage)->markdown('notifications.markdown.expected-checkin', [ 'date' => Helper::getFormattedDateObject($this->params->expected_checkin, 'date', false), 'asset' => $this->params->present()->name(), 'serial' => $this->params->serial, - 'asset_tag' => $this->params->asset_tag + 'asset_tag' => $this->params->asset_tag, ]) ->subject(trans('mail.Expected_Checkin_Notification', ['name' => $this->params->present()->name()])); return $message; - } - } diff --git a/app/Notifications/ExpiringAssetsNotification.php b/app/Notifications/ExpiringAssetsNotification.php index 47d5509259..076db149fb 100644 --- a/app/Notifications/ExpiringAssetsNotification.php +++ b/app/Notifications/ExpiringAssetsNotification.php @@ -33,7 +33,8 @@ class ExpiringAssetsNotification extends Notification public function via() { $notifyBy = []; - $notifyBy[]='mail'; + $notifyBy[] = 'mail'; + return $notifyBy; } @@ -45,7 +46,6 @@ class ExpiringAssetsNotification extends Notification */ public function toMail() { - $message = (new MailMessage)->markdown('notifications.markdown.report-expiring-assets', [ 'assets' => $this->assets, @@ -54,8 +54,5 @@ class ExpiringAssetsNotification extends Notification ->subject(trans('mail.Expiring_Assets_Report')); return $message; - - } - } diff --git a/app/Notifications/ExpiringLicenseNotification.php b/app/Notifications/ExpiringLicenseNotification.php index 5ca1e93cf6..4be549e452 100644 --- a/app/Notifications/ExpiringLicenseNotification.php +++ b/app/Notifications/ExpiringLicenseNotification.php @@ -34,7 +34,8 @@ class ExpiringLicenseNotification extends Notification public function via() { $notifyBy = []; - $notifyBy[]='mail'; + $notifyBy[] = 'mail'; + return $notifyBy; } @@ -46,7 +47,6 @@ class ExpiringLicenseNotification extends Notification */ public function toMail() { - $message = (new MailMessage)->markdown('notifications.markdown.report-expiring-licenses', [ 'licenses' => $this->licenses, @@ -55,8 +55,5 @@ class ExpiringLicenseNotification extends Notification ->subject(trans('mail.Expiring_Licenses_Report')); return $message; - - } - } diff --git a/app/Notifications/FirstAdminNotification.php b/app/Notifications/FirstAdminNotification.php index 153aff4aec..71637b5e80 100644 --- a/app/Notifications/FirstAdminNotification.php +++ b/app/Notifications/FirstAdminNotification.php @@ -10,7 +10,7 @@ class FirstAdminNotification extends Notification { use Queueable; - private $_data = array(); + private $_data = []; /** * Create a new notification instance. @@ -45,8 +45,7 @@ class FirstAdminNotification extends Notification public function toMail() { return (new MailMessage) - ->subject(trans('mail.welcome', ['name' => $this->_data['first_name'] . ' ' . $this->_data['last_name'] ])) + ->subject(trans('mail.welcome', ['name' => $this->_data['first_name'].' '.$this->_data['last_name']])) ->markdown('notifications.FirstAdmin', $this->_data); } - } diff --git a/app/Notifications/RequestAssetCancelation.php b/app/Notifications/RequestAssetCancelation.php index d50aea3529..ea76056af3 100644 --- a/app/Notifications/RequestAssetCancelation.php +++ b/app/Notifications/RequestAssetCancelation.php @@ -55,15 +55,13 @@ class RequestAssetCancelation extends Notification */ public function via() { - $notifyBy = []; - if (Setting::getSettings()->slack_endpoint!='') { + if (Setting::getSettings()->slack_endpoint != '') { \Log::debug('use slack'); $notifyBy[] = 'slack'; } - $notifyBy[] = 'mail'; return $notifyBy; @@ -75,19 +73,19 @@ class RequestAssetCancelation extends Notification $item = $this->item; $note = $this->note; $qty = $this->item_quantity; - $botname = ($this->settings->slack_botname) ? $this->settings->slack_botname : 'Snipe-Bot' ; + $botname = ($this->settings->slack_botname) ? $this->settings->slack_botname : 'Snipe-Bot'; $fields = [ 'QTY' => $qty, 'Canceled By' => '<'.$target->present()->viewUrl().'|'.$target->present()->fullName().'>', ]; - if (($this->expected_checkin) && ($this->expected_checkin!='')) { + if (($this->expected_checkin) && ($this->expected_checkin != '')) { $fields['Expected Checkin'] = $this->expected_checkin; } return (new SlackMessage) - ->content( trans('mail.a_user_canceled')) + ->content(trans('mail.a_user_canceled')) ->from($botname) ->attachment(function ($attachment) use ($item, $note, $fields) { $attachment->title(htmlspecialchars_decode($item->present()->name), $item->present()->viewUrl()) @@ -95,6 +93,7 @@ class RequestAssetCancelation extends Notification ->content($note); }); } + /** * Get the mail representation of the notification. * @@ -103,7 +102,6 @@ class RequestAssetCancelation extends Notification */ public function toMail() { - $fields = []; // Check if the item has custom fields associated with it @@ -125,8 +123,6 @@ class RequestAssetCancelation extends Notification ]) ->subject(trans('Item Request Canceled')); - return $message; } - } diff --git a/app/Notifications/RequestAssetNotification.php b/app/Notifications/RequestAssetNotification.php index b78f5eeb93..22a8f3d464 100644 --- a/app/Notifications/RequestAssetNotification.php +++ b/app/Notifications/RequestAssetNotification.php @@ -46,8 +46,6 @@ class RequestAssetNotification extends Notification $this->expected_checkin = Helper::getFormattedDateObject($this->item->expected_checkin, 'date', false); } - - } /** @@ -58,10 +56,9 @@ class RequestAssetNotification extends Notification */ public function via() { - $notifyBy = []; - if (Setting::getSettings()->slack_endpoint!='') { + if (Setting::getSettings()->slack_endpoint != '') { $notifyBy[] = 'slack'; } @@ -76,7 +73,7 @@ class RequestAssetNotification extends Notification $qty = $this->item_quantity; $item = $this->item; $note = $this->note; - $botname = ($this->settings->slack_botname) ? $this->settings->slack_botname : 'Snipe-Bot' ; + $botname = ($this->settings->slack_botname) ? $this->settings->slack_botname : 'Snipe-Bot'; $fields = [ 'QTY' => $qty, @@ -92,6 +89,7 @@ class RequestAssetNotification extends Notification ->content($note); }); } + /** * Get the mail representation of the notification. * @@ -99,7 +97,6 @@ class RequestAssetNotification extends Notification */ public function toMail() { - $fields = []; // Check if the item has custom fields associated with it @@ -121,8 +118,6 @@ class RequestAssetNotification extends Notification ]) ->subject(trans('mail.Item_Requested')); - return $message; } - } diff --git a/app/Notifications/SendUpcomingAuditNotification.php b/app/Notifications/SendUpcomingAuditNotification.php index a6863ea8e3..a883220f2f 100644 --- a/app/Notifications/SendUpcomingAuditNotification.php +++ b/app/Notifications/SendUpcomingAuditNotification.php @@ -4,9 +4,9 @@ namespace App\Notifications; use App\Models\Setting; use Illuminate\Bus\Queueable; -use Illuminate\Notifications\Notification; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; +use Illuminate\Notifications\Notification; class SendUpcomingAuditNotification extends Notification { diff --git a/app/Notifications/WelcomeNotification.php b/app/Notifications/WelcomeNotification.php index 9a98a97734..3d2657b944 100644 --- a/app/Notifications/WelcomeNotification.php +++ b/app/Notifications/WelcomeNotification.php @@ -10,7 +10,7 @@ class WelcomeNotification extends Notification { use Queueable; - private $_data = array(); + private $_data = []; /** * Create a new notification instance. @@ -45,7 +45,7 @@ class WelcomeNotification extends Notification public function toMail() { return (new MailMessage) - ->subject(trans('mail.welcome', ['name' => $this->_data['first_name'] . ' ' . $this->_data['last_name'] ])) + ->subject(trans('mail.welcome', ['name' => $this->_data['first_name'].' '.$this->_data['last_name']])) ->markdown('notifications.Welcome', $this->_data); } } diff --git a/app/Observers/AccessoryObserver.php b/app/Observers/AccessoryObserver.php index 1dd3e40437..f97d166b17 100644 --- a/app/Observers/AccessoryObserver.php +++ b/app/Observers/AccessoryObserver.php @@ -16,16 +16,14 @@ class AccessoryObserver */ public function updated(Accessory $accessory) { - $logAction = new Actionlog(); $logAction->item_type = Accessory::class; $logAction->item_id = $accessory->id; - $logAction->created_at = date("Y-m-d H:i:s"); + $logAction->created_at = date('Y-m-d H:i:s'); $logAction->user_id = Auth::id(); $logAction->logaction('update'); } - /** * Listen to the Accessory created event when * a new accessory is created. @@ -38,10 +36,9 @@ class AccessoryObserver $logAction = new Actionlog(); $logAction->item_type = Accessory::class; $logAction->item_id = $accessory->id; - $logAction->created_at = date("Y-m-d H:i:s"); + $logAction->created_at = date('Y-m-d H:i:s'); $logAction->user_id = Auth::id(); $logAction->logaction('create'); - } /** @@ -55,7 +52,7 @@ class AccessoryObserver $logAction = new Actionlog(); $logAction->item_type = Accessory::class; $logAction->item_id = $accessory->id; - $logAction->created_at = date("Y-m-d H:i:s"); + $logAction->created_at = date('Y-m-d H:i:s'); $logAction->user_id = Auth::id(); $logAction->logaction('delete'); } diff --git a/app/Observers/AssetObserver.php b/app/Observers/AssetObserver.php index 164792a3a9..85e33ee045 100644 --- a/app/Observers/AssetObserver.php +++ b/app/Observers/AssetObserver.php @@ -22,8 +22,7 @@ class AssetObserver // (Those other actions already create log entries.) if (($asset->getAttributes()['assigned_to'] == $asset->getOriginal()['assigned_to']) && ($asset->getAttributes()['next_audit_date'] == $asset->getOriginal()['next_audit_date']) - && ($asset->getAttributes()['last_checkout'] == $asset->getOriginal()['last_checkout'])) - { + && ($asset->getAttributes()['last_checkout'] == $asset->getOriginal()['last_checkout'])) { $changed = []; foreach ($asset->getOriginal() as $key => $value) { @@ -33,22 +32,18 @@ class AssetObserver } } - $logAction = new Actionlog(); $logAction->item_type = Asset::class; $logAction->item_id = $asset->id; - $logAction->created_at = date("Y-m-d H:i:s"); + $logAction->created_at = date('Y-m-d H:i:s'); $logAction->user_id = Auth::id(); $logAction->log_meta = json_encode($changed); $logAction->logaction('update'); - - } - + } } - /** - * Listen to the Asset created event, and increment + * Listen to the Asset created event, and increment * the next_auto_tag_base value in the settings table when i * a new asset is created. * @@ -65,10 +60,9 @@ class AssetObserver $logAction = new Actionlog(); $logAction->item_type = Asset::class; $logAction->item_id = $asset->id; - $logAction->created_at = date("Y-m-d H:i:s"); + $logAction->created_at = date('Y-m-d H:i:s'); $logAction->user_id = Auth::id(); $logAction->logaction('create'); - } /** @@ -82,7 +76,7 @@ class AssetObserver $logAction = new Actionlog(); $logAction->item_type = Asset::class; $logAction->item_id = $asset->id; - $logAction->created_at = date("Y-m-d H:i:s"); + $logAction->created_at = date('Y-m-d H:i:s'); $logAction->user_id = Auth::id(); $logAction->logaction('delete'); } diff --git a/app/Observers/ComponentObserver.php b/app/Observers/ComponentObserver.php index 3cb0aeda6c..57792022bb 100644 --- a/app/Observers/ComponentObserver.php +++ b/app/Observers/ComponentObserver.php @@ -16,16 +16,14 @@ class ComponentObserver */ public function updated(Component $component) { - $logAction = new Actionlog(); $logAction->item_type = Component::class; $logAction->item_id = $component->id; - $logAction->created_at = date("Y-m-d H:i:s"); + $logAction->created_at = date('Y-m-d H:i:s'); $logAction->user_id = Auth::id(); $logAction->logaction('update'); } - /** * Listen to the Component created event when * a new component is created. @@ -38,10 +36,9 @@ class ComponentObserver $logAction = new Actionlog(); $logAction->item_type = Component::class; $logAction->item_id = $component->id; - $logAction->created_at = date("Y-m-d H:i:s"); + $logAction->created_at = date('Y-m-d H:i:s'); $logAction->user_id = Auth::id(); $logAction->logaction('create'); - } /** @@ -55,7 +52,7 @@ class ComponentObserver $logAction = new Actionlog(); $logAction->item_type = Component::class; $logAction->item_id = $component->id; - $logAction->created_at = date("Y-m-d H:i:s"); + $logAction->created_at = date('Y-m-d H:i:s'); $logAction->user_id = Auth::id(); $logAction->logaction('delete'); } diff --git a/app/Observers/ConsumableObserver.php b/app/Observers/ConsumableObserver.php index 22c94f2688..b945196e20 100644 --- a/app/Observers/ConsumableObserver.php +++ b/app/Observers/ConsumableObserver.php @@ -16,16 +16,14 @@ class ConsumableObserver */ public function updated(Consumable $consumable) { - $logAction = new Actionlog(); $logAction->item_type = Consumable::class; $logAction->item_id = $consumable->id; - $logAction->created_at = date("Y-m-d H:i:s"); + $logAction->created_at = date('Y-m-d H:i:s'); $logAction->user_id = Auth::id(); $logAction->logaction('update'); } - /** * Listen to the Consumable created event when * a new consumable is created. @@ -35,14 +33,12 @@ class ConsumableObserver */ public function created(Consumable $consumable) { - $logAction = new Actionlog(); $logAction->item_type = Consumable::class; $logAction->item_id = $consumable->id; - $logAction->created_at = date("Y-m-d H:i:s"); + $logAction->created_at = date('Y-m-d H:i:s'); $logAction->user_id = Auth::id(); $logAction->logaction('create'); - } /** @@ -56,7 +52,7 @@ class ConsumableObserver $logAction = new Actionlog(); $logAction->item_type = Consumable::class; $logAction->item_id = $consumable->id; - $logAction->created_at = date("Y-m-d H:i:s"); + $logAction->created_at = date('Y-m-d H:i:s'); $logAction->user_id = Auth::id(); $logAction->logaction('delete'); } diff --git a/app/Observers/LicenseObserver.php b/app/Observers/LicenseObserver.php index 5f0132f208..1478aba113 100644 --- a/app/Observers/LicenseObserver.php +++ b/app/Observers/LicenseObserver.php @@ -16,16 +16,14 @@ class LicenseObserver */ public function updated(License $license) { - $logAction = new Actionlog(); $logAction->item_type = License::class; $logAction->item_id = $license->id; - $logAction->created_at = date("Y-m-d H:i:s"); + $logAction->created_at = date('Y-m-d H:i:s'); $logAction->user_id = Auth::id(); $logAction->logaction('update'); } - /** * Listen to the License created event when * a new license is created. @@ -35,14 +33,12 @@ class LicenseObserver */ public function created(License $license) { - $logAction = new Actionlog(); $logAction->item_type = License::class; $logAction->item_id = $license->id; - $logAction->created_at = date("Y-m-d H:i:s"); + $logAction->created_at = date('Y-m-d H:i:s'); $logAction->user_id = Auth::id(); $logAction->logaction('create'); - } /** @@ -56,7 +52,7 @@ class LicenseObserver $logAction = new Actionlog(); $logAction->item_type = License::class; $logAction->item_id = $license->id; - $logAction->created_at = date("Y-m-d H:i:s"); + $logAction->created_at = date('Y-m-d H:i:s'); $logAction->user_id = Auth::id(); $logAction->logaction('delete'); } diff --git a/app/Observers/SettingObserver.php b/app/Observers/SettingObserver.php index eea0240017..aeb682a03a 100644 --- a/app/Observers/SettingObserver.php +++ b/app/Observers/SettingObserver.php @@ -18,6 +18,5 @@ class SettingObserver { Cache::forget(Setting::APP_SETTINGS_KEY); Cache::forget(Setting::SETUP_CHECK_KEY); - } } diff --git a/app/Policies/CheckoutablePermissionsPolicy.php b/app/Policies/CheckoutablePermissionsPolicy.php index d1c39ae314..bcd0e0f39a 100644 --- a/app/Policies/CheckoutablePermissionsPolicy.php +++ b/app/Policies/CheckoutablePermissionsPolicy.php @@ -1,12 +1,12 @@ hasAccess($this->columnName().'.checkout'); } - /** + /** * Determine whether the user can checkin the accessory. * * @param \App\User $user @@ -28,7 +28,7 @@ abstract class CheckoutablePermissionsPolicy extends SnipePermissionsPolicy return $user->hasAccess($this->columnName().'.checkin'); } - /** + /** * Determine whether the user can manage the accessory. * * @param \App\User $user diff --git a/app/Policies/CustomFieldsetPolicy.php b/app/Policies/CustomFieldsetPolicy.php index 0d95cbafe5..a6c06a7007 100644 --- a/app/Policies/CustomFieldsetPolicy.php +++ b/app/Policies/CustomFieldsetPolicy.php @@ -8,11 +8,11 @@ class CustomFieldsetPolicy extends SnipePermissionsPolicy { /** * Proxy the authorization for custom fieldsets down to custom fields. - * This allows us to use the existing permissions in use and have more + * This allows us to use the existing permissions in use and have more * semantically correct authorization checks for custom fieldsets. * * See: https://github.com/snipe/snipe-it/pull/5795 */ return 'customfields'; - } + } } diff --git a/app/Policies/LicensePolicy.php b/app/Policies/LicensePolicy.php index 9d1ec815c6..7a92b5b7de 100644 --- a/app/Policies/LicensePolicy.php +++ b/app/Policies/LicensePolicy.php @@ -13,25 +13,26 @@ class LicensePolicy extends CheckoutablePermissionsPolicy } /** - * Determine whether the user can view license keys. - * This gets a little tricky, UX/logic-wise. If a user has the ability - * to create a license (which requires a product key), shouldn't they - * have the ability to see the product key as well? - * - * Example: I create the license, realize I need to change - * something (maybe I got the product key wrong), and now I can never - * see/edit that product key. - * - * @see https://github.com/snipe/snipe-it/issues/6956 - * @param \App\Models\User $user - * @param \App\Models\License $license - * @return mixed - */ + * Determine whether the user can view license keys. + * This gets a little tricky, UX/logic-wise. If a user has the ability + * to create a license (which requires a product key), shouldn't they + * have the ability to see the product key as well? + * + * Example: I create the license, realize I need to change + * something (maybe I got the product key wrong), and now I can never + * see/edit that product key. + * + * @see https://github.com/snipe/snipe-it/issues/6956 + * @param \App\Models\User $user + * @param \App\Models\License $license + * @return mixed + */ public function viewKeys(User $user, License $license = null) { if ($user->hasAccess('licenses.keys') || $user->hasAccess('licenses.create') || $user->hasAccess('licenses.edit')) { return true; } + return false; } diff --git a/app/Policies/SnipePermissionsPolicy.php b/app/Policies/SnipePermissionsPolicy.php index 435828fd14..f6f6e4db82 100644 --- a/app/Policies/SnipePermissionsPolicy.php +++ b/app/Policies/SnipePermissionsPolicy.php @@ -1,4 +1,5 @@ hasAccess($this->columnName().'.view'); } + /** * Determine whether the user can view the accessory. * @@ -93,12 +93,13 @@ abstract class SnipePermissionsPolicy { $itemConditional = true; if ($item) { - $itemConditional = empty($item->deleted_at); + $itemConditional = empty($item->deleted_at); } + return $itemConditional && $user->hasAccess($this->columnName().'.delete'); } - /** + /** * Determine whether the user can manage the accessory. * * @param \App\Models\User $user @@ -108,6 +109,4 @@ abstract class SnipePermissionsPolicy { return $user->hasAccess($this->columnName().'.edit'); } - - } diff --git a/app/Presenters/AccessoryPresenter.php b/app/Presenters/AccessoryPresenter.php index bf7074ad55..5eb58f4bc1 100644 --- a/app/Presenters/AccessoryPresenter.php +++ b/app/Presenters/AccessoryPresenter.php @@ -1,9 +1,9 @@ "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false - ],[ - "field" => "image", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/hardware/table.image'), - "visible" => true, - "formatter" => "imageFormatter" + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "company", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/companies/table.title'), - "visible" => false, - "formatter" => "companiesLinkObjFormatter" + 'field' => 'image', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/hardware/table.image'), + 'visible' => true, + 'formatter' => 'imageFormatter', ], [ - "field" => "name", - "searchable" => true, - "sortable" => true, - "title" => trans('general.name'), - "formatter" => "accessoriesLinkFormatter" + 'field' => 'company', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/companies/table.title'), + 'visible' => false, + 'formatter' => 'companiesLinkObjFormatter', ], [ - "field" => "category", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/accessories/general.accessory_category'), - "formatter" => "categoriesLinkObjFormatter" + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.name'), + 'formatter' => 'accessoriesLinkFormatter', ], [ - "field" => "model_number", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/models/table.modelnumber'), - "formatter" => "accessoriesLinkFormatter" + 'field' => 'category', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/accessories/general.accessory_category'), + 'formatter' => 'categoriesLinkObjFormatter', ], [ - "field" => "manufacturer", - "searchable" => true, - "sortable" => true, - "title" => trans('general.manufacturer'), - "formatter" => "manufacturersLinkObjFormatter", + 'field' => 'model_number', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/models/table.modelnumber'), + 'formatter' => 'accessoriesLinkFormatter', ], [ - "field" => "supplier", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.supplier'), - "visible" => false, - "formatter" => "suppliersLinkObjFormatter" + 'field' => 'manufacturer', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.manufacturer'), + 'formatter' => 'manufacturersLinkObjFormatter', ], [ - "field" => "location", - "searchable" => true, - "sortable" => true, - "title" => trans('general.location'), - "formatter" => "locationsLinkObjFormatter", + 'field' => 'supplier', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.supplier'), + 'visible' => false, + 'formatter' => 'suppliersLinkObjFormatter', ], [ - "field" => "qty", - "searchable" => false, - "sortable" => false, - "title" => trans('admin/accessories/general.total'), + 'field' => 'location', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.location'), + 'formatter' => 'locationsLinkObjFormatter', + ], [ + 'field' => 'qty', + 'searchable' => false, + 'sortable' => false, + 'title' => trans('admin/accessories/general.total'), ], [ - "field" => "min_qty", - "searchable" => false, - "sortable" => true, - "title" => trans('general.min_amt'), + 'field' => 'min_qty', + 'searchable' => false, + 'sortable' => true, + 'title' => trans('general.min_amt'), ], [ - "field" => "remaining_qty", - "searchable" => false, - "sortable" => false, - "title" => trans('admin/accessories/general.remaining'), + 'field' => 'remaining_qty', + 'searchable' => false, + 'sortable' => false, + 'title' => trans('admin/accessories/general.remaining'), ], [ - "field" => "purchase_date", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('general.purchase_date'), - "formatter" => "dateDisplayFormatter" + 'field' => 'purchase_date', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.purchase_date'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "purchase_cost", - "searchable" => true, - "sortable" => true, - "title" => trans('general.purchase_cost'), - "footerFormatter" => 'sumFormatter', + 'field' => 'purchase_cost', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.purchase_cost'), + 'footerFormatter' => 'sumFormatter', ], [ - "field" => "order_number", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('general.order_number'), - ],[ - "field" => "change", - "searchable" => false, - "sortable" => false, - "visible" => true, - "title" => trans('general.change'), - "formatter" => "accessoriesInOutFormatter", + 'field' => 'order_number', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.order_number'), ], [ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "formatter" => "accessoriesActionsFormatter", - ] + 'field' => 'change', + 'searchable' => false, + 'sortable' => false, + 'visible' => true, + 'title' => trans('general.change'), + 'formatter' => 'accessoriesInOutFormatter', + ], [ + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'formatter' => 'accessoriesActionsFormatter', + ], ]; return json_encode($layout); } - /** * Pregenerated link to this accessories view page. * @return string diff --git a/app/Presenters/ActionlogPresenter.php b/app/Presenters/ActionlogPresenter.php index 79ab28269e..ff62d16a69 100644 --- a/app/Presenters/ActionlogPresenter.php +++ b/app/Presenters/ActionlogPresenter.php @@ -4,26 +4,25 @@ namespace App\Presenters; /** * Class CompanyPresenter - * @package App\Presenters */ class ActionlogPresenter extends Presenter { - public function admin() { if ($user = $this->model->user) { - if(empty($user->deleted_at)) { + if (empty($user->deleted_at)) { return $user->present()->nameUrl(); } // The user was deleted - return ''.$user->getFullNameAttribute()." (deleted)"; + return ''.$user->getFullNameAttribute().' (deleted)'; } + return ''; } public function item() { - if($this->action_type=='uploaded') { + if ($this->action_type == 'uploaded') { return (string) link_to_route('show/userfile', $this->model->filename, [$this->model->item->id, $this->model->id]); } if ($item = $this->model->item) { @@ -33,63 +32,63 @@ class ActionlogPresenter extends Presenter // The item was deleted return ''.$item->name.' (deleted)'; } + return ''; } - public function icon() { - $itemicon = 'fa fa-paperclip'; + $itemicon = 'fa fa-paperclip'; - if ($this->itemType() == "asset") { + if ($this->itemType() == 'asset') { $itemicon = 'fa fa-barcode'; - } elseif ($this->itemType() == "accessory") { - $itemicon = 'fa fa-keyboard-o'; - } elseif ($this->itemType()=="consumable") { - $itemicon = 'fa fa-tint'; - } elseif ($this->itemType()=="license") { - $itemicon = 'fa fa-floppy-o'; - } elseif ($this->itemType()=="component") { - $itemicon = 'fa fa-hdd-o'; - } + } elseif ($this->itemType() == 'accessory') { + $itemicon = 'fa fa-keyboard-o'; + } elseif ($this->itemType() == 'consumable') { + $itemicon = 'fa fa-tint'; + } elseif ($this->itemType() == 'license') { + $itemicon = 'fa fa-floppy-o'; + } elseif ($this->itemType() == 'component') { + $itemicon = 'fa fa-hdd-o'; + } return $itemicon; } - - public function actionType() { + public function actionType() + { return mb_strtolower(trans('general.'.str_replace(' ', '_', $this->action_type))); } - - public function target() { $target = null; // Target is messy. // On an upload, the target is the item we are uploading to, stored as the "item" in the log. - if ($this->action_type=='uploaded') { + if ($this->action_type == 'uploaded') { $target = $this->model->item; - } elseif (($this->action_type=='accepted') || ($this->action_type=='declined')) { - // If we are logging an accept/reject, the target is not stored directly, - // so we access it through who the item is assigned to. - // FIXME: On a reject it's not assigned to anyone. + } elseif (($this->action_type == 'accepted') || ($this->action_type == 'declined')) { + // If we are logging an accept/reject, the target is not stored directly, + // so we access it through who the item is assigned to. + // FIXME: On a reject it's not assigned to anyone. $target = $this->model->item->assignedTo; - } elseif ($this->action_type=='requested') { + } elseif ($this->action_type == 'requested') { if ($this->model->user) { $target = $this->model->user; } } elseif ($this->model->target) { - // Otherwise, we'll just take the target of the log. + // Otherwise, we'll just take the target of the log. $target = $this->model->target; } - if($target) { + if ($target) { if (empty($target->deleted_at)) { return $target->present()->nameUrl(); } + return ''.$target->present()->name().''; } + return ''; } } diff --git a/app/Presenters/AssetAuditPresenter.php b/app/Presenters/AssetAuditPresenter.php index bfc917eea5..6af3952fca 100644 --- a/app/Presenters/AssetAuditPresenter.php +++ b/app/Presenters/AssetAuditPresenter.php @@ -1,4 +1,5 @@ "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "company", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.company'), - "visible" => false, - "formatter" => 'assetCompanyObjFilterFormatter' + 'field' => 'company', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.company'), + 'visible' => false, + 'formatter' => 'assetCompanyObjFilterFormatter', ], [ - "field" => "name", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/form.name'), - "visible" => true, - "formatter" => "hardwareLinkFormatter" + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/form.name'), + 'visible' => true, + 'formatter' => 'hardwareLinkFormatter', ], [ - "field" => "image", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/hardware/table.image'), - "visible" => false, - "formatter" => "imageFormatter" + 'field' => 'image', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/hardware/table.image'), + 'visible' => false, + 'formatter' => 'imageFormatter', ], [ - "field" => "asset_tag", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/table.asset_tag'), - "visible" => true, - "formatter" => "hardwareLinkFormatter" + 'field' => 'asset_tag', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/table.asset_tag'), + 'visible' => true, + 'formatter' => 'hardwareLinkFormatter', ], [ - "field" => "serial", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/form.serial'), - "visible" => true, - "formatter" => "hardwareLinkFormatter" + 'field' => 'serial', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/form.serial'), + 'visible' => true, + 'formatter' => 'hardwareLinkFormatter', ], [ - "field" => "model", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/form.model'), - "visible" => true, - "formatter" => "modelsLinkObjFormatter" + 'field' => 'model', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/form.model'), + 'visible' => true, + 'formatter' => 'modelsLinkObjFormatter', ], [ - "field" => "model_number", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/models/table.modelnumber'), - "visible" => false + 'field' => 'model_number', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/models/table.modelnumber'), + 'visible' => false, ], [ - "field" => "category", - "searchable" => true, - "sortable" => true, - "title" => trans('general.category'), - "visible" => false, - "formatter" => "categoriesLinkObjFormatter" + 'field' => 'category', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.category'), + 'visible' => false, + 'formatter' => 'categoriesLinkObjFormatter', ], [ - "field" => "status_label", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/table.status'), - "visible" => true, - "formatter" => "statuslabelsLinkObjFormatter" + 'field' => 'status_label', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/table.status'), + 'visible' => true, + 'formatter' => 'statuslabelsLinkObjFormatter', ], [ - "field" => "assigned_to", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/form.checkedout_to'), - "visible" => true, - "formatter" => "polymorphicItemFormatter" + 'field' => 'assigned_to', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/form.checkedout_to'), + 'visible' => true, + 'formatter' => 'polymorphicItemFormatter', ], [ - "field" => "location", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/table.location'), - "visible" => true, - "formatter" => "deployedLocationFormatter" + 'field' => 'location', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/table.location'), + 'visible' => true, + 'formatter' => 'deployedLocationFormatter', ], [ - "field" => "rtd_location", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/form.default_location'), - "visible" => false, - "formatter" => "deployedLocationFormatter" + 'field' => 'rtd_location', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/form.default_location'), + 'visible' => false, + 'formatter' => 'deployedLocationFormatter', ], [ - "field" => "manufacturer", - "searchable" => true, - "sortable" => true, - "title" => trans('general.manufacturer'), - "visible" => false, - "formatter" => "manufacturersLinkObjFormatter" + 'field' => 'manufacturer', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.manufacturer'), + 'visible' => false, + 'formatter' => 'manufacturersLinkObjFormatter', ], [ - "field" => "purchase_date", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('general.purchase_date'), - "formatter" => "dateDisplayFormatter" + 'field' => 'purchase_date', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.purchase_date'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "purchase_cost", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('general.purchase_cost'), - "footerFormatter" => 'sumFormatter', + 'field' => 'purchase_cost', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.purchase_cost'), + 'footerFormatter' => 'sumFormatter', ], [ - "field" => "order_number", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('general.order_number'), - 'formatter' => "orderNumberObjFilterFormatter" + 'field' => 'order_number', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.order_number'), + 'formatter' => 'orderNumberObjFilterFormatter', ], [ - "field" => "eol", - "searchable" => false, - "sortable" => false, - "visible" => false, - "title" => trans('general.eol'), - "formatter" => "dateDisplayFormatter" + 'field' => 'eol', + 'searchable' => false, + 'sortable' => false, + 'visible' => false, + 'title' => trans('general.eol'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "warranty_months", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('admin/hardware/form.warranty') - ],[ - "field" => "warranty_expires", - "searchable" => false, - "sortable" => false, - "visible" => false, - "title" => trans('admin/hardware/form.warranty_expires'), - "formatter" => "dateDisplayFormatter" - ],[ - "field" => "notes", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('general.notes'), + 'field' => 'warranty_months', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('admin/hardware/form.warranty'), + ], [ + 'field' => 'warranty_expires', + 'searchable' => false, + 'sortable' => false, + 'visible' => false, + 'title' => trans('admin/hardware/form.warranty_expires'), + 'formatter' => 'dateDisplayFormatter', + ], [ + 'field' => 'notes', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.notes'), ], [ - "field" => "checkout_counter", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('general.checkouts_count') - - ],[ - "field" => "checkin_counter", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('general.checkins_count') + 'field' => 'checkout_counter', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.checkouts_count'), ], [ - "field" => "requests_counter", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('general.user_requests_count') + 'field' => 'checkin_counter', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.checkins_count'), ], [ - "field" => "created_at", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('general.created_at'), - "formatter" => "dateDisplayFormatter" + 'field' => 'requests_counter', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.user_requests_count'), + ], [ - "field" => "updated_at", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('general.updated_at'), - "formatter" => "dateDisplayFormatter" + 'field' => 'created_at', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.created_at'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "last_checkout", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('admin/hardware/table.checkout_date'), - "formatter" => "dateDisplayFormatter" + 'field' => 'updated_at', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.updated_at'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "expected_checkin", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('admin/hardware/form.expected_checkin'), - "formatter" => "dateDisplayFormatter" + 'field' => 'last_checkout', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('admin/hardware/table.checkout_date'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "last_audit_date", - "searchable" => false, - "sortable" => true, - "visible" => true, - "title" => trans('general.last_audit'), - "formatter" => "dateDisplayFormatter" + 'field' => 'expected_checkin', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('admin/hardware/form.expected_checkin'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "next_audit_date", - "searchable" => false, - "sortable" => true, - "visible" => true, - "title" => trans('general.next_audit_date'), - "formatter" => "dateDisplayFormatter" + 'field' => 'last_audit_date', + 'searchable' => false, + 'sortable' => true, + 'visible' => true, + 'title' => trans('general.last_audit'), + 'formatter' => 'dateDisplayFormatter', + ], [ + 'field' => 'next_audit_date', + 'searchable' => false, + 'sortable' => true, + 'visible' => true, + 'title' => trans('general.next_audit_date'), + 'formatter' => 'dateDisplayFormatter', ], ]; @@ -238,36 +237,31 @@ class AssetAuditPresenter extends Presenter // models. We only pass the fieldsets that pertain to each asset (via their model) so that we // don't junk up the REST API with tons of custom fields that don't apply - $fields = CustomField::whereHas('fieldset', function ($query) { + $fields = CustomField::whereHas('fieldset', function ($query) { $query->whereHas('models'); })->get(); foreach ($fields as $field) { $layout[] = [ - "field" => 'custom_fields.'.$field->convertUnicodeDbSlug(), - "searchable" => true, - "sortable" => true, - "visible" => false, - "switchable" => true, - "title" => ($field->field_encrypted=='1') ?' '.e($field->name) : e($field->name), - "formatter" => "customFieldsFormatter" + 'field' => 'custom_fields.'.$field->convertUnicodeDbSlug(), + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'switchable' => true, + 'title' => ($field->field_encrypted == '1') ? ' '.e($field->name) : e($field->name), + 'formatter' => 'customFieldsFormatter', ]; - } - $layout[] = [ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "formatter" => "hardwareAuditFormatter", + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'formatter' => 'hardwareAuditFormatter', ]; return json_encode($layout); } - - - } diff --git a/app/Presenters/AssetMaintenancesPresenter.php b/app/Presenters/AssetMaintenancesPresenter.php index 3d69cd794f..f7a9ff0229 100644 --- a/app/Presenters/AssetMaintenancesPresenter.php +++ b/app/Presenters/AssetMaintenancesPresenter.php @@ -4,11 +4,9 @@ namespace App\Presenters; /** * Class AssetModelPresenter - * @package App\Presenters */ class AssetMaintenancesPresenter extends Presenter { - /** * Json Column Layout for bootstrap table * @return string @@ -17,106 +15,106 @@ class AssetMaintenancesPresenter extends Presenter { $layout = [ [ - "field" => "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false - ],[ - "field" => "company", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/companies/table.title'), - "visible" => false, - "formatter" => "companiesLinkObjFormatter" + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "asset_name", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/asset_maintenances/table.asset_name'), - "formatter" => "assetNameLinkFormatter" - ],[ - "field" => "asset_tag", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/table.asset_tag'), - "formatter" => "assetTagLinkFormatter" + 'field' => 'company', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/companies/table.title'), + 'visible' => false, + 'formatter' => 'companiesLinkObjFormatter', ], [ - "field" => "model", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/hardware/form.model'), - "visible" => false, - "formatter" => "modelsLinkObjFormatter" - ],[ - "field" => "supplier", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.supplier'), - "visible" => false, - "formatter" => "suppliersLinkObjFormatter" + 'field' => 'asset_name', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/asset_maintenances/table.asset_name'), + 'formatter' => 'assetNameLinkFormatter', ], [ - "field" => "location", - "searchable" => true, - "sortable" => true, - "title" => trans('general.location'), - "formatter" => "locationsLinkObjFormatter", + 'field' => 'asset_tag', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/table.asset_tag'), + 'formatter' => 'assetTagLinkFormatter', ], [ - "field" => "asset_maintenance_type", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/asset_maintenances/form.asset_maintenance_type'), + 'field' => 'model', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/hardware/form.model'), + 'visible' => false, + 'formatter' => 'modelsLinkObjFormatter', ], [ - "field" => "title", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/asset_maintenances/form.title'), + 'field' => 'supplier', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.supplier'), + 'visible' => false, + 'formatter' => 'suppliersLinkObjFormatter', ], [ - "field" => "start_date", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/asset_maintenances/form.start_date'), - "formatter" => "dateDisplayFormatter" + 'field' => 'location', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.location'), + 'formatter' => 'locationsLinkObjFormatter', ], [ - "field" => "completion_date", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/asset_maintenances/form.completion_date'), - "formatter" => "dateDisplayFormatter" + 'field' => 'asset_maintenance_type', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/asset_maintenances/form.asset_maintenance_type'), ], [ - "field" => "notes", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/asset_maintenances/form.notes') - ],[ - "field" => "is_warranty", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/asset_maintenances/table.is_warranty') + 'field' => 'title', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/asset_maintenances/form.title'), ], [ - "field" => "cost", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/asset_maintenances/form.cost') + 'field' => 'start_date', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/asset_maintenances/form.start_date'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "user_id", - "searchable" => true, - "sortable" => true, - "title" => trans('general.admin'), - "formatter" => "usersLinkObjFormatter" + 'field' => 'completion_date', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/asset_maintenances/form.completion_date'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "visible" => true, - "formatter" => "maintenancesActionsFormatter", - ] + 'field' => 'notes', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/asset_maintenances/form.notes'), + ], [ + 'field' => 'is_warranty', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/asset_maintenances/table.is_warranty'), + ], [ + 'field' => 'cost', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/asset_maintenances/form.cost'), + ], [ + 'field' => 'user_id', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.admin'), + 'formatter' => 'usersLinkObjFormatter', + ], [ + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'visible' => true, + 'formatter' => 'maintenancesActionsFormatter', + ], ]; return json_encode($layout); diff --git a/app/Presenters/AssetModelPresenter.php b/app/Presenters/AssetModelPresenter.php index 65836da9a8..08fec15200 100644 --- a/app/Presenters/AssetModelPresenter.php +++ b/app/Presenters/AssetModelPresenter.php @@ -4,150 +4,147 @@ namespace App\Presenters; /** * Class AssetModelPresenter - * @package App\Presenters */ class AssetModelPresenter extends Presenter { - public static function dataTableLayout() { - + public static function dataTableLayout() + { $layout = [ [ - "field" => "checkbox", - "checkbox" => true + 'field' => 'checkbox', + 'checkbox' => true, ], [ - "field" => "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "company", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/companies/table.title'), - "visible" => false, - "formatter" => "companiesLinkObjFormatter" + 'field' => 'company', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/companies/table.title'), + 'visible' => false, + 'formatter' => 'companiesLinkObjFormatter', ], [ - "field" => "name", - "searchable" => true, - "sortable" => true, - "visible" => true, - "title" => trans('general.name'), - "formatter" => "modelsLinkFormatter" + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'visible' => true, + 'title' => trans('general.name'), + 'formatter' => 'modelsLinkFormatter', ], [ - "field" => "image", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.image'), - "visible" => true, - "formatter" => 'imageFormatter', + 'field' => 'image', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.image'), + 'visible' => true, + 'formatter' => 'imageFormatter', ], [ - "field" => "manufacturer", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.manufacturer'), - "visible" => false, - "formatter" => 'manufacturersLinkObjFormatter', + 'field' => 'manufacturer', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.manufacturer'), + 'visible' => false, + 'formatter' => 'manufacturersLinkObjFormatter', ], [ - "field" => "model_number", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/models/table.modelnumber'), - "visible" => true, + 'field' => 'model_number', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/models/table.modelnumber'), + 'visible' => true, ], [ - "field" => "assets_count", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/models/table.numassets'), - "visible" => true, + 'field' => 'assets_count', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/models/table.numassets'), + 'visible' => true, ], [ - "field" => "depreciation", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.depreciation'), - "visible" => false, - "formatter" => "depreciationsLinkObjFormatter", + 'field' => 'depreciation', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.depreciation'), + 'visible' => false, + 'formatter' => 'depreciationsLinkObjFormatter', ], [ - "field" => "category", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.category'), - "visible" => false, - "formatter" => "categoriesLinkObjFormatter", + 'field' => 'category', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.category'), + 'visible' => false, + 'formatter' => 'categoriesLinkObjFormatter', ], [ - "field" => "eol", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.eol'), - "visible" => true, + 'field' => 'eol', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.eol'), + 'visible' => true, ], [ - "field" => "fieldset", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/models/general.fieldset'), - "visible" => true, - "formatter" => "fieldsetsLinkObjFormatter", + 'field' => 'fieldset', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/models/general.fieldset'), + 'visible' => true, + 'formatter' => 'fieldsetsLinkObjFormatter', ], [ - "field" => "notes", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.notes'), - "visible" => false, + 'field' => 'notes', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.notes'), + 'visible' => false, ], [ - "field" => "created_at", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('general.created_at'), - "formatter" => "dateDisplayFormatter" + 'field' => 'created_at', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.created_at'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "updated_at", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('general.updated_at'), - "formatter" => "dateDisplayFormatter" + 'field' => 'updated_at', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.updated_at'), + 'formatter' => 'dateDisplayFormatter', ], ]; - $layout[] = [ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "formatter" => "modelsActionsFormatter", + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'formatter' => 'modelsActionsFormatter', ]; - return json_encode($layout); - } + /** * Formatted note for this model * @return string @@ -159,7 +156,6 @@ class AssetModelPresenter extends Presenter if ($this->model->note) { return $Parsedown->text($this->model->note); } - } public function eolText() @@ -167,6 +163,7 @@ class AssetModelPresenter extends Presenter if ($this->eol) { return $this->eol.' '.trans('general.months'); } + return ''; } @@ -183,8 +180,9 @@ class AssetModelPresenter extends Presenter $name .= $this->name; if ($this->model_number) { - $name .=" (#".$this->model_number.')'; + $name .= ' (#'.$this->model_number.')'; } + return $name; } @@ -203,9 +201,10 @@ class AssetModelPresenter extends Presenter */ public function imageUrl() { - if (!empty($this->image)) { - return ''.$this->name.''; + if (! empty($this->image)) { + return ''.$this->name.''; } + return ''; } @@ -215,9 +214,10 @@ class AssetModelPresenter extends Presenter */ public function imageSrc() { - if (!empty($this->image)) { - return url('/') . '/uploads/models/' . $this->image; + if (! empty($this->image)) { + return url('/').'/uploads/models/'.$this->image; } + return ''; } diff --git a/app/Presenters/AssetPresenter.php b/app/Presenters/AssetPresenter.php index feb8aa8b8b..1a58a31ff6 100644 --- a/app/Presenters/AssetPresenter.php +++ b/app/Presenters/AssetPresenter.php @@ -1,4 +1,5 @@ "checkbox", - "checkbox" => true + 'field' => 'checkbox', + 'checkbox' => true, ], [ - "field" => "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "company", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.company'), - "visible" => false, - "formatter" => 'assetCompanyObjFilterFormatter' + 'field' => 'company', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.company'), + 'visible' => false, + 'formatter' => 'assetCompanyObjFilterFormatter', ], [ - "field" => "name", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/form.name'), - "visible" => true, - "formatter" => "hardwareLinkFormatter" + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/form.name'), + 'visible' => true, + 'formatter' => 'hardwareLinkFormatter', ], [ - "field" => "image", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/hardware/table.image'), - "visible" => true, - "formatter" => "imageFormatter" + 'field' => 'image', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/hardware/table.image'), + 'visible' => true, + 'formatter' => 'imageFormatter', ], [ - "field" => "asset_tag", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/table.asset_tag'), - "visible" => true, - "formatter" => "hardwareLinkFormatter" + 'field' => 'asset_tag', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/table.asset_tag'), + 'visible' => true, + 'formatter' => 'hardwareLinkFormatter', ], [ - "field" => "serial", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/form.serial'), - "visible" => true, - "formatter" => "hardwareLinkFormatter" + 'field' => 'serial', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/form.serial'), + 'visible' => true, + 'formatter' => 'hardwareLinkFormatter', ], [ - "field" => "model", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/form.model'), - "visible" => true, - "formatter" => "modelsLinkObjFormatter" + 'field' => 'model', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/form.model'), + 'visible' => true, + 'formatter' => 'modelsLinkObjFormatter', ], [ - "field" => "model_number", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/models/table.modelnumber'), - "visible" => false + 'field' => 'model_number', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/models/table.modelnumber'), + 'visible' => false, ], [ - "field" => "category", - "searchable" => true, - "sortable" => true, - "title" => trans('general.category'), - "visible" => true, - "formatter" => "categoriesLinkObjFormatter" + 'field' => 'category', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.category'), + 'visible' => true, + 'formatter' => 'categoriesLinkObjFormatter', ], [ - "field" => "status_label", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/table.status'), - "visible" => true, - "formatter" => "statuslabelsLinkObjFormatter" + 'field' => 'status_label', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/table.status'), + 'visible' => true, + 'formatter' => 'statuslabelsLinkObjFormatter', ], [ - "field" => "assigned_to", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/form.checkedout_to'), - "visible" => true, - "formatter" => "polymorphicItemFormatter" + 'field' => 'assigned_to', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/form.checkedout_to'), + 'visible' => true, + 'formatter' => 'polymorphicItemFormatter', ], [ - "field" => "employee_number", - "searchable" => false, - "sortable" => false, - "title" => trans('admin/users/table.employee_num'), - "visible" => false, - "formatter" => "employeeNumFormatter" - ],[ - "field" => "location", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/table.location'), - "visible" => true, - "formatter" => "deployedLocationFormatter" + 'field' => 'employee_number', + 'searchable' => false, + 'sortable' => false, + 'title' => trans('admin/users/table.employee_num'), + 'visible' => false, + 'formatter' => 'employeeNumFormatter', ], [ - "field" => "rtd_location", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/form.default_location'), - "visible" => false, - "formatter" => "deployedLocationFormatter" + 'field' => 'location', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/table.location'), + 'visible' => true, + 'formatter' => 'deployedLocationFormatter', ], [ - "field" => "manufacturer", - "searchable" => true, - "sortable" => true, - "title" => trans('general.manufacturer'), - "visible" => false, - "formatter" => "manufacturersLinkObjFormatter" - ],[ - "field" => "supplier", - "searchable" => true, - "sortable" => true, - "title" => trans('general.supplier'), - "visible" => false, - "formatter" => "suppliersLinkObjFormatter" + 'field' => 'rtd_location', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/form.default_location'), + 'visible' => false, + 'formatter' => 'deployedLocationFormatter', ], [ - "field" => "purchase_date", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('general.purchase_date'), - "formatter" => "dateDisplayFormatter" + 'field' => 'manufacturer', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.manufacturer'), + 'visible' => false, + 'formatter' => 'manufacturersLinkObjFormatter', ], [ - "field" => "purchase_cost", - "searchable" => true, - "sortable" => true, - "title" => trans('general.purchase_cost'), - "footerFormatter" => 'sumFormatter', + 'field' => 'supplier', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.supplier'), + 'visible' => false, + 'formatter' => 'suppliersLinkObjFormatter', ], [ - "field" => "order_number", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('general.order_number'), - 'formatter' => "orderNumberObjFilterFormatter" + 'field' => 'purchase_date', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.purchase_date'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "eol", - "searchable" => false, - "sortable" => false, - "visible" => false, - "title" => trans('general.eol'), - "formatter" => "dateDisplayFormatter" + 'field' => 'purchase_cost', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.purchase_cost'), + 'footerFormatter' => 'sumFormatter', ], [ - "field" => "warranty_months", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('admin/hardware/form.warranty') - ],[ - "field" => "warranty_expires", - "searchable" => false, - "sortable" => false, - "visible" => false, - "title" => trans('admin/hardware/form.warranty_expires'), - "formatter" => "dateDisplayFormatter" - ],[ - "field" => "notes", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('general.notes'), + 'field' => 'order_number', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.order_number'), + 'formatter' => 'orderNumberObjFilterFormatter', + ], [ + 'field' => 'eol', + 'searchable' => false, + 'sortable' => false, + 'visible' => false, + 'title' => trans('general.eol'), + 'formatter' => 'dateDisplayFormatter', + ], [ + 'field' => 'warranty_months', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('admin/hardware/form.warranty'), + ], [ + 'field' => 'warranty_expires', + 'searchable' => false, + 'sortable' => false, + 'visible' => false, + 'title' => trans('admin/hardware/form.warranty_expires'), + 'formatter' => 'dateDisplayFormatter', + ], [ + 'field' => 'notes', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.notes'), ], [ - "field" => "checkout_counter", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('general.checkouts_count') - - ],[ - "field" => "checkin_counter", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('general.checkins_count') + 'field' => 'checkout_counter', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.checkouts_count'), ], [ - "field" => "requests_counter", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('general.user_requests_count') + 'field' => 'checkin_counter', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.checkins_count'), ], [ - "field" => "created_at", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('general.created_at'), - "formatter" => "dateDisplayFormatter" + 'field' => 'requests_counter', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.user_requests_count'), + ], [ - "field" => "updated_at", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('general.updated_at'), - "formatter" => "dateDisplayFormatter" + 'field' => 'created_at', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.created_at'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "last_checkout", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('admin/hardware/table.checkout_date'), - "formatter" => "dateDisplayFormatter" + 'field' => 'updated_at', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.updated_at'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "expected_checkin", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('admin/hardware/form.expected_checkin'), - "formatter" => "dateDisplayFormatter" + 'field' => 'last_checkout', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('admin/hardware/table.checkout_date'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "last_audit_date", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('general.last_audit'), - "formatter" => "dateDisplayFormatter" + 'field' => 'expected_checkin', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('admin/hardware/form.expected_checkin'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "next_audit_date", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('general.next_audit_date'), - "formatter" => "dateDisplayFormatter" + 'field' => 'last_audit_date', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.last_audit'), + 'formatter' => 'dateDisplayFormatter', + ], [ + 'field' => 'next_audit_date', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.next_audit_date'), + 'formatter' => 'dateDisplayFormatter', ], ]; @@ -254,53 +253,49 @@ class AssetPresenter extends Presenter // models. We only pass the fieldsets that pertain to each asset (via their model) so that we // don't junk up the REST API with tons of custom fields that don't apply - $fields = CustomField::whereHas('fieldset', function ($query) { + $fields = CustomField::whereHas('fieldset', function ($query) { $query->whereHas('models'); })->get(); - // Note: We do not need to e() escape the field names here, as they are already escaped when // they are presented in the blade view. If we escape them here, custom fields with quotes in their // name can break the listings page. - snipe foreach ($fields as $field) { $layout[] = [ - "field" => 'custom_fields.'.$field->convertUnicodeDbSlug(), - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => $field->name, - "formatter"=> 'customFieldsFormatter', - "escape" => true, - "class" => ($field->field_encrypted=='1') ? 'css-padlock' : '', - "visible" => true, + 'field' => 'custom_fields.'.$field->convertUnicodeDbSlug(), + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => $field->name, + 'formatter'=> 'customFieldsFormatter', + 'escape' => true, + 'class' => ($field->field_encrypted == '1') ? 'css-padlock' : '', + 'visible' => true, ]; - } $layout[] = [ - "field" => "checkincheckout", - "searchable" => false, - "sortable" => false, - "switchable" => true, - "title" => trans('general.checkin').'/'.trans('general.checkout'), - "visible" => true, - "formatter" => "hardwareInOutFormatter", + 'field' => 'checkincheckout', + 'searchable' => false, + 'sortable' => false, + 'switchable' => true, + 'title' => trans('general.checkin').'/'.trans('general.checkout'), + 'visible' => true, + 'formatter' => 'hardwareInOutFormatter', ]; $layout[] = [ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "formatter" => "hardwareActionsFormatter", + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'formatter' => 'hardwareActionsFormatter', ]; return json_encode($layout); } - - /** * Generate html link to this items name. * @return string @@ -315,6 +310,7 @@ class AssetPresenter extends Presenter if ($this->model->model) { return $this->model->model->present()->nameUrl(); } + return ''; } @@ -325,17 +321,18 @@ class AssetPresenter extends Presenter public function imageUrl() { $imagePath = ''; - if ($this->image && !empty($this->image)) { + if ($this->image && ! empty($this->image)) { $imagePath = $this->image; $imageAlt = $this->name; - } elseif ($this->model && !empty($this->model->image)) { + } elseif ($this->model && ! empty($this->model->image)) { $imagePath = $this->model->image; $imageAlt = $this->model->name; } $url = config('app.url'); - if (!empty($imagePath)) { + if (! empty($imagePath)) { $imagePath = ''.$imageAlt.''; } + return $imagePath; } @@ -346,14 +343,15 @@ class AssetPresenter extends Presenter public function imageSrc() { $imagePath = ''; - if ($this->image && !empty($this->image)) { + if ($this->image && ! empty($this->image)) { $imagePath = $this->image; - } elseif ($this->model && !empty($this->model->image)) { + } elseif ($this->model && ! empty($this->model->image)) { $imagePath = $this->model->image; } - if (!empty($imagePath)) { + if (! empty($imagePath)) { return config('app.url').'/uploads/assets/'.$imagePath; } + return $imagePath; } @@ -391,21 +389,22 @@ class AssetPresenter extends Presenter if ($this->model->model) { $str .= ' - '.$this->model->model->name; } + return $str; } + /** * Returns the date this item hits EOL. * @return false|string */ public function eol_date() { - - if (( $this->purchase_date ) && ( $this->model->model ) && ($this->model->model->eol) ) { + if (($this->purchase_date) && ($this->model->model) && ($this->model->model->eol)) { $date = date_create($this->purchase_date); - date_add($date, date_interval_create_from_date_string($this->model->model->eol . ' months')); + date_add($date, date_interval_create_from_date_string($this->model->model->eol.' months')); + return date_format($date, 'Y-m-d'); } - } /** @@ -414,10 +413,9 @@ class AssetPresenter extends Presenter */ public function months_until_eol() { - - $today = date("Y-m-d"); - $d1 = new DateTime($today); - $d2 = new DateTime($this->eol_date()); + $today = date('Y-m-d'); + $d1 = new DateTime($today); + $d2 = new DateTime($this->eol_date()); if ($this->eol_date() > $today) { $interval = $d2->diff($d1); @@ -438,6 +436,7 @@ class AssetPresenter extends Presenter if ($this->model->assigned) { return 'deployed'; } + return $this->model->assetstatus->getStatuslabelType(); } @@ -451,6 +450,7 @@ class AssetPresenter extends Presenter if ($this->model->assigned) { return trans('general.deployed'); } + return $this->model->assetstatus->name; } @@ -468,7 +468,8 @@ class AssetPresenter extends Presenter * (if not deployed:) * Another Status Label */ - public function fullStatusText() { + public function fullStatusText() + { // Make sure the status is valid if ($this->assetstatus) { @@ -477,7 +478,7 @@ class AssetPresenter extends Presenter // If it's assigned and not set to the default "ready to deploy" status if ($this->assetstatus->name != trans('general.ready_to_deploy')) { - return trans('general.deployed'). ' (' . $this->model->assetstatus->name.')'; + return trans('general.deployed').' ('.$this->model->assetstatus->name.')'; } // If it's assigned to the default "ready to deploy" status, just @@ -503,7 +504,8 @@ class AssetPresenter extends Presenter { if (($this->purchase_date) && ($this->warranty_months)) { $date = date_create($this->purchase_date); - date_add($date, date_interval_create_from_date_string($this->warranty_months . ' months')); + date_add($date, date_interval_create_from_date_string($this->warranty_months.' months')); + return date_format($date, 'Y-m-d'); } diff --git a/app/Presenters/CategoryPresenter.php b/app/Presenters/CategoryPresenter.php index 0b87b13e02..5a93d12612 100644 --- a/app/Presenters/CategoryPresenter.php +++ b/app/Presenters/CategoryPresenter.php @@ -4,11 +4,9 @@ namespace App\Presenters; /** * Class CategoryPresenter - * @package App\Presenters */ class CategoryPresenter extends Presenter { - /** * Json Column Layout for bootstrap table * @return string @@ -17,51 +15,72 @@ class CategoryPresenter extends Presenter { $layout = [ [ - "field" => "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "name", - "searchable" => true, - "sortable" => true, - "title" => trans('general.name'), - "visible" => true, - "formatter" => 'categoriesLinkFormatter', - ],[ - "field" => "image", - "searchable" => false, - "sortable" => true, - "title" => trans('general.image'), - "visible" => true, - "formatter" => 'imageFormatter', - ],[ - "field" => "category_type", - "searchable" => true, - "sortable" => true, - "title" => trans('general.type'), - "visible" => true - ],[ - "field" => "item_count", - "searchable" => false, - "sortable" => true, - "title" => trans('general.qty'), - "visible" => true - ],[ - "field" => "has_eula", - "searchable" => false, - "sortable" => false, - "title" => trans('admin/categories/table.eula_text'), - "visible" => false, - "formatter" => 'trueFalseFormatter', + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.name'), + 'visible' => true, + 'formatter' => 'categoriesLinkFormatter', + ], [ + 'field' => 'image', + 'searchable' => false, + 'sortable' => true, + 'title' => trans('general.image'), + 'visible' => true, + 'formatter' => 'imageFormatter', + ], [ + 'field' => 'category_type', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.type'), + 'visible' => true, + ], [ + 'field' => 'item_count', + 'searchable' => false, + 'sortable' => true, + 'title' => trans('general.qty'), + 'visible' => true, + ], [ + 'field' => 'has_eula', + 'searchable' => false, + 'sortable' => false, + 'title' => trans('admin/categories/table.eula_text'), + 'visible' => false, + 'formatter' => 'trueFalseFormatter', + ], [ + 'field' => 'checkin_email', + 'searchable' => false, + 'sortable' => true, + 'class' => 'css-envelope', + 'title' => 'Send Email', + 'visible' => true, + 'formatter' => 'trueFalseFormatter', + ], [ + 'field' => 'require_acceptance', + 'searchable' => false, + 'sortable' => true, + 'title' => trans('admin/categories/table.require_acceptance'), + 'visible' => true, + 'formatter' => 'trueFalseFormatter', + ], [ + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), ],[ "field" => "use_default_eula", "searchable" => false, "sortable" => true, "title" => trans('admin/categories/general.use_default_eula_column'), - "visible" => false, + 'visible' => true, "formatter" => 'trueFalseFormatter', ],[ "field" => "checkin_email", @@ -75,40 +94,29 @@ class CategoryPresenter extends Presenter "field" => "require_acceptance", "searchable" => false, "sortable" => true, - "title" => trans('admin/categories/table.require_acceptance'), - "visible" => true, - "formatter" => 'trueFalseFormatter', - ],[ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "visible" => true, - "formatter" => "categoriesActionsFormatter", + 'formatter' => 'categoriesActionsFormatter', ], [ - "field" => "created_at", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('general.created_at'), - "formatter" => "dateDisplayFormatter" + 'field' => 'created_at', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.created_at'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "updated_at", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('general.updated_at'), - "formatter" => "dateDisplayFormatter" + 'field' => 'updated_at', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.updated_at'), + 'formatter' => 'dateDisplayFormatter', ], ]; return json_encode($layout); } - /** * Link to this categories name * @return string diff --git a/app/Presenters/CompanyPresenter.php b/app/Presenters/CompanyPresenter.php index 9f8e6fb376..5f829f1ccb 100644 --- a/app/Presenters/CompanyPresenter.php +++ b/app/Presenters/CompanyPresenter.php @@ -4,7 +4,6 @@ namespace App\Presenters; /** * Class CompanyPresenter - * @package App\Presenters */ class CompanyPresenter extends Presenter { @@ -16,95 +15,94 @@ class CompanyPresenter extends Presenter { $layout = [ [ - "field" => "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false - ],[ - "field" => "name", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/companies/table.name'), - "visible" => true, - "formatter" => 'companiesLinkFormatter', - ],[ - "field" => "image", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.image'), - "visible" => true, - "formatter" => 'imageFormatter', - ],[ - "field" => "users_count", - "searchable" => false, - "sortable" => true, - "title" => '', - "visible" => true, - - ],[ - "field" => "assets_count", - "searchable" => false, - "sortable" => true, - "title" => '', - "visible" => true, + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, + ], [ + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/companies/table.name'), + 'visible' => true, + 'formatter' => 'companiesLinkFormatter', + ], [ + 'field' => 'image', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.image'), + 'visible' => true, + 'formatter' => 'imageFormatter', + ], [ + 'field' => 'users_count', + 'searchable' => false, + 'sortable' => true, + 'title' => '', + 'visible' => true, - ],[ - "field" => "licenses_count", - "searchable" => false, - "sortable" => true, - "visible" => true, - "title" => ' ', - ],[ - "field" => "accessories_count", - "searchable" => false, - "sortable" => true, - "visible" => true, - "title" => ' ', - ],[ - "field" => "consumables_count", - "searchable" => false, - "sortable" => true, - "visible" => true, - "title" => ' ', - ],[ - "field" => "components_count", - "searchable" => false, - "sortable" => true, - "visible" => true, - "title" => ' ', - ],[ - "field" => "updated_at", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('general.updated_at'), - "formatter" => 'createdAtFormatter', - ],[ - "field" => "created_at", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('general.created_at'), - "formatter" => 'createdAtFormatter', - ],[ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "visible" => true, - "formatter" => "companiesActionsFormatter", - ] + ], [ + 'field' => 'assets_count', + 'searchable' => false, + 'sortable' => true, + 'title' => '', + 'visible' => true, + + ], [ + 'field' => 'licenses_count', + 'searchable' => false, + 'sortable' => true, + 'visible' => true, + 'title' => ' ', + ], [ + 'field' => 'accessories_count', + 'searchable' => false, + 'sortable' => true, + 'visible' => true, + 'title' => ' ', + ], [ + 'field' => 'consumables_count', + 'searchable' => false, + 'sortable' => true, + 'visible' => true, + 'title' => ' ', + ], [ + 'field' => 'components_count', + 'searchable' => false, + 'sortable' => true, + 'visible' => true, + 'title' => ' ', + ], [ + 'field' => 'updated_at', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.updated_at'), + 'formatter' => 'createdAtFormatter', + ], [ + 'field' => 'created_at', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.created_at'), + 'formatter' => 'createdAtFormatter', + ], [ + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'visible' => true, + 'formatter' => 'companiesActionsFormatter', + ], ]; return json_encode($layout); } - /** * Link to this companies name * @return string diff --git a/app/Presenters/ComponentPresenter.php b/app/Presenters/ComponentPresenter.php index 669b5c651f..7f3dab0aa2 100644 --- a/app/Presenters/ComponentPresenter.php +++ b/app/Presenters/ComponentPresenter.php @@ -4,11 +4,9 @@ namespace App\Presenters; /** * Class ComponentPresenter - * @package App\Presenters */ class ComponentPresenter extends Presenter { - /** * Json Column Layout for bootstrap table * @return string @@ -17,116 +15,115 @@ class ComponentPresenter extends Presenter { $layout = [ [ - "field" => "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "company", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.company'), - "visible" => false, - "formatter" => 'companiesLinkObjFormatter', + 'field' => 'company', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.company'), + 'visible' => false, + 'formatter' => 'companiesLinkObjFormatter', ], [ - "field" => "name", - "searchable" => true, - "sortable" => true, - "title" => trans('general.name'), - "visible" => true, - "formatter" => 'componentsLinkFormatter', + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.name'), + 'visible' => true, + 'formatter' => 'componentsLinkFormatter', ], [ - "field" => "image", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.image'), - "visible" => false, - "formatter" => 'imageFormatter', - ],[ - "field" => "serial", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/hardware/form.serial'), - "formatter" => "componentsLinkFormatter" + 'field' => 'image', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.image'), + 'visible' => false, + 'formatter' => 'imageFormatter', ], [ - "field" => "category", - "searchable" => true, - "sortable" => true, - "title" => trans('general.category'), - "formatter" => "categoriesLinkObjFormatter" + 'field' => 'serial', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/hardware/form.serial'), + 'formatter' => 'componentsLinkFormatter', ], [ - "field" => "qty", - "searchable" => false, - "sortable" => true, - "title" => trans('admin/components/general.total'), - "visible" => true, + 'field' => 'category', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.category'), + 'formatter' => 'categoriesLinkObjFormatter', ], [ - "field" => "remaining", - "searchable" => false, - "sortable" => false, - "title" => trans('admin/components/general.remaining'), - "visible" => true, + 'field' => 'qty', + 'searchable' => false, + 'sortable' => true, + 'title' => trans('admin/components/general.total'), + 'visible' => true, ], [ - "field" => "min_amt", - "searchable" => false, - "sortable" => false, - "title" => trans('general.min_amt'), - "visible" => true, + 'field' => 'remaining', + 'searchable' => false, + 'sortable' => false, + 'title' => trans('admin/components/general.remaining'), + 'visible' => true, ], [ - "field" => "location", - "searchable" => true, - "sortable" => true, - "title" => trans('general.location'), - "formatter" => "locationsLinkObjFormatter" + 'field' => 'min_amt', + 'searchable' => false, + 'sortable' => false, + 'title' => trans('general.min_amt'), + 'visible' => true, ], [ - "field" => "order_number", - "searchable" => true, - "sortable" => true, - "title" => trans('general.order_number'), - "visible" => true, - ],[ - "field" => "purchase_date", - "searchable" => true, - "sortable" => true, - "title" => trans('general.purchase_date'), - "visible" => true, - "formatter" => "dateDisplayFormatter", - ],[ - "field" => "purchase_cost", - "searchable" => true, - "sortable" => true, - "title" => trans('general.purchase_cost'), - "visible" => true, - "footerFormatter" => 'sumFormatter', + 'field' => 'location', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.location'), + 'formatter' => 'locationsLinkObjFormatter', + ], [ + 'field' => 'order_number', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.order_number'), + 'visible' => true, + ], [ + 'field' => 'purchase_date', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.purchase_date'), + 'visible' => true, + 'formatter' => 'dateDisplayFormatter', + ], [ + 'field' => 'purchase_cost', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.purchase_cost'), + 'visible' => true, + 'footerFormatter' => 'sumFormatter', ], ]; $layout[] = [ - "field" => "checkincheckout", - "searchable" => false, - "sortable" => false, - "switchable" => true, - "title" => trans('general.checkin').'/'.trans('general.checkout'), - "visible" => true, - "formatter" => "componentsInOutFormatter", + 'field' => 'checkincheckout', + 'searchable' => false, + 'sortable' => false, + 'switchable' => true, + 'title' => trans('general.checkin').'/'.trans('general.checkout'), + 'visible' => true, + 'formatter' => 'componentsInOutFormatter', ]; $layout[] = [ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "formatter" => "componentsActionsFormatter", + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'formatter' => 'componentsActionsFormatter', ]; - return json_encode($layout); } @@ -147,6 +144,4 @@ class ComponentPresenter extends Presenter { return route('accessories.show', $this->id); } - - } diff --git a/app/Presenters/ConsumablePresenter.php b/app/Presenters/ConsumablePresenter.php index 334398fabd..c80972955e 100644 --- a/app/Presenters/ConsumablePresenter.php +++ b/app/Presenters/ConsumablePresenter.php @@ -2,14 +2,11 @@ namespace App\Presenters; - /** * Class ComponentPresenter - * @package App\Presenters */ class ConsumablePresenter extends Presenter { - /** * Json Column Layout for bootstrap table * @return string @@ -18,121 +15,121 @@ class ConsumablePresenter extends Presenter { $layout = [ [ - "field" => "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "company", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.company'), - "visible" => false, - "formatter" => 'companiesLinkObjFormatter', + 'field' => 'company', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.company'), + 'visible' => false, + 'formatter' => 'companiesLinkObjFormatter', ], [ - "field" => "name", - "searchable" => true, - "sortable" => true, - "title" => trans('general.name'), - "visible" => true, - "formatter" => 'consumablesLinkFormatter', + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.name'), + 'visible' => true, + 'formatter' => 'consumablesLinkFormatter', ], [ - "field" => "image", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.image'), - "visible" => false, - "formatter" => 'imageFormatter', + 'field' => 'image', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.image'), + 'visible' => false, + 'formatter' => 'imageFormatter', ], [ - "field" => "category", - "searchable" => true, - "sortable" => true, - "title" => trans('general.category'), - "formatter" => "categoriesLinkObjFormatter" - ],[ - "field" => "model_number", - "searchable" => true, - "sortable" => true, - "title" => trans('general.model_no'), - ],[ - "field" => "item_no", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/consumables/general.item_no') + 'field' => 'category', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.category'), + 'formatter' => 'categoriesLinkObjFormatter', ], [ - "field" => "qty", - "searchable" => false, - "sortable" => false, - "title" => trans('admin/components/general.total'), - "visible" => true, + 'field' => 'model_number', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.model_no'), ], [ - "field" => "remaining", - "searchable" => false, - "sortable" => false, - "title" => trans('admin/components/general.remaining'), - "visible" => true, + 'field' => 'item_no', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/consumables/general.item_no'), ], [ - "field" => "min_amt", - "searchable" => false, - "sortable" => false, - "title" => trans('general.min_amt'), - "visible" => true, + 'field' => 'qty', + 'searchable' => false, + 'sortable' => false, + 'title' => trans('admin/components/general.total'), + 'visible' => true, + ], [ + 'field' => 'remaining', + 'searchable' => false, + 'sortable' => false, + 'title' => trans('admin/components/general.remaining'), + 'visible' => true, + ], [ + 'field' => 'min_amt', + 'searchable' => false, + 'sortable' => false, + 'title' => trans('general.min_amt'), + 'visible' => true, ], [ - "field" => "location", - "searchable" => true, - "sortable" => true, - "title" => trans('general.location'), - "formatter" => "locationsLinkObjFormatter" + 'field' => 'location', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.location'), + 'formatter' => 'locationsLinkObjFormatter', ], [ - "field" => "manufacturer", - "searchable" => true, - "sortable" => true, - "title" => trans('general.manufacturer'), - "visible" => false, - "formatter" => "manufacturersLinkObjFormatter" + 'field' => 'manufacturer', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.manufacturer'), + 'visible' => false, + 'formatter' => 'manufacturersLinkObjFormatter', ], [ - "field" => "order_number", - "searchable" => true, - "sortable" => true, - "title" => trans('general.order_number'), - "visible" => true, - ],[ - "field" => "purchase_date", - "searchable" => true, - "sortable" => true, - "title" => trans('general.purchase_date'), - "visible" => true, - "formatter" => "dateDisplayFormatter", - ],[ - "field" => "purchase_cost", - "searchable" => true, - "sortable" => true, - "title" => trans('general.purchase_cost'), - "visible" => true, - "footerFormatter" => 'sumFormatter', - ],[ - "field" => "change", - "searchable" => false, - "sortable" => false, - "visible" => true, - "title" => trans('general.change'), - "formatter" => "consumablesInOutFormatter", + 'field' => 'order_number', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.order_number'), + 'visible' => true, ], [ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "visible" => true, - "formatter" => "consumablesActionsFormatter", - ] + 'field' => 'purchase_date', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.purchase_date'), + 'visible' => true, + 'formatter' => 'dateDisplayFormatter', + ], [ + 'field' => 'purchase_cost', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.purchase_cost'), + 'visible' => true, + 'footerFormatter' => 'sumFormatter', + ], [ + 'field' => 'change', + 'searchable' => false, + 'sortable' => false, + 'visible' => true, + 'title' => trans('general.change'), + 'formatter' => 'consumablesInOutFormatter', + ], [ + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'visible' => true, + 'formatter' => 'consumablesActionsFormatter', + ], ]; return json_encode($layout); @@ -155,6 +152,4 @@ class ConsumablePresenter extends Presenter { return (string) link_to_route('consumables.show', e($this->name), $this->id); } - - } diff --git a/app/Presenters/DepreciationPresenter.php b/app/Presenters/DepreciationPresenter.php index d6e51ec81c..2a293a46ff 100644 --- a/app/Presenters/DepreciationPresenter.php +++ b/app/Presenters/DepreciationPresenter.php @@ -4,7 +4,6 @@ namespace App\Presenters; /** * Class DepreciationPresenter - * @package App\Presenters */ class DepreciationPresenter extends Presenter { @@ -16,41 +15,47 @@ class DepreciationPresenter extends Presenter { $layout = [ [ - "field" => "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "name", - "searchable" => true, - "sortable" => true, - "title" => trans('general.name'), - "visible" => true, - "formatter" => 'depreciationsLinkFormatter', + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.name'), + 'visible' => true, + 'formatter' => 'depreciationsLinkFormatter', ], [ - "field" => "months", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/depreciations/table.term'), - "visible" => true, + 'field' => 'months', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/depreciations/table.term'), + 'visible' => true, ], [ - "field" => "actions", + "field" => 'depreciation_min', "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), + "sortable" => true, + "title" => trans('admin/depreciations/table.depreciation_min'), "visible" => true, - "formatter" => "depreciationsActionsFormatter", - ] + ], + [ + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'visible' => true, + 'formatter' => 'depreciationsActionsFormatter', + ], ]; return json_encode($layout); } - } diff --git a/app/Presenters/LicensePresenter.php b/app/Presenters/LicensePresenter.php index be5a600c4f..d050a521d2 100644 --- a/app/Presenters/LicensePresenter.php +++ b/app/Presenters/LicensePresenter.php @@ -4,7 +4,6 @@ namespace App\Presenters; /** * Class LicensePresenter - * @package App\Presenters */ class LicensePresenter extends Presenter { @@ -16,174 +15,172 @@ class LicensePresenter extends Presenter { $layout = [ [ - "field" => "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "company", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/companies/table.title'), - "visible" => false, - "formatter" => "companiesLinkObjFormatter" + 'field' => 'company', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/companies/table.title'), + 'visible' => false, + 'formatter' => 'companiesLinkObjFormatter', ], [ - "field" => "name", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/licenses/table.title'), - "formatter" => "licensesLinkFormatter" + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/licenses/table.title'), + 'formatter' => 'licensesLinkFormatter', ], [ - "field" => "product_key", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/licenses/form.license_key'), - "formatter" => "licensesLinkFormatter" + 'field' => 'product_key', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/licenses/form.license_key'), + 'formatter' => 'licensesLinkFormatter', ], [ - "field" => "expiration_date", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/licenses/form.expiration'), - 'formatter' => 'dateDisplayFormatter' + 'field' => 'expiration_date', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/licenses/form.expiration'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "license_email", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/licenses/form.to_email') + 'field' => 'license_email', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/licenses/form.to_email'), ], [ - "field" => "license_name", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/licenses/form.to_name'), + 'field' => 'license_name', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/licenses/form.to_name'), ], [ - "field" => "category", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.category'), - "visible" => false, - "formatter" => "categoriesLinkObjFormatter" + 'field' => 'category', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.category'), + 'visible' => false, + 'formatter' => 'categoriesLinkObjFormatter', ], [ - "field" => "supplier", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.supplier'), - "visible" => false, - "formatter" => "suppliersLinkObjFormatter" + 'field' => 'supplier', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.supplier'), + 'visible' => false, + 'formatter' => 'suppliersLinkObjFormatter', ], [ - "field" => "manufacturer", - "searchable" => true, - "sortable" => true, - "title" => trans('general.manufacturer'), - "formatter" => "manufacturersLinkObjFormatter", + 'field' => 'manufacturer', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.manufacturer'), + 'formatter' => 'manufacturersLinkObjFormatter', ], [ - "field" => "seats", - "searchable" => false, - "sortable" => true, - "title" => trans('admin/accessories/general.total'), + 'field' => 'seats', + 'searchable' => false, + 'sortable' => true, + 'title' => trans('admin/accessories/general.total'), ], [ - "field" => "free_seats_count", - "searchable" => false, - "sortable" => true, - "title" => trans('admin/accessories/general.remaining'), + 'field' => 'free_seats_count', + 'searchable' => false, + 'sortable' => true, + 'title' => trans('admin/accessories/general.remaining'), ], [ - "field" => "purchase_date", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('general.purchase_date'), - 'formatter' => 'dateDisplayFormatter' + 'field' => 'purchase_date', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.purchase_date'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "termination_date", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('admin/licenses/form.termination_date'), - 'formatter' => 'dateDisplayFormatter' + 'field' => 'termination_date', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('admin/licenses/form.termination_date'), + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "depreciation", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/hardware/form.depreciation'), - "visible" => false, - "formatter" => "depreciationsLinkObjFormatter", + 'field' => 'depreciation', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/hardware/form.depreciation'), + 'visible' => false, + 'formatter' => 'depreciationsLinkObjFormatter', ], [ - "field" => "maintained", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('admin/licenses/form.maintained'), - "formatter" => "trueFalseFormatter" + 'field' => 'maintained', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('admin/licenses/form.maintained'), + 'formatter' => 'trueFalseFormatter', ], [ - "field" => "reassignable", - "searchable" => false, - "sortable" => true, - "visible" => false, - "title" => trans('admin/licenses/form.reassignable'), - "formatter" => "trueFalseFormatter" + 'field' => 'reassignable', + 'searchable' => false, + 'sortable' => true, + 'visible' => false, + 'title' => trans('admin/licenses/form.reassignable'), + 'formatter' => 'trueFalseFormatter', ], [ - "field" => "purchase_cost", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('general.purchase_cost'), - "footerFormatter" => 'sumFormatter', + 'field' => 'purchase_cost', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.purchase_cost'), + 'footerFormatter' => 'sumFormatter', ], [ - "field" => "purchase_order", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('admin/licenses/form.purchase_order'), + 'field' => 'purchase_order', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('admin/licenses/form.purchase_order'), ], [ - "field" => "order_number", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('general.order_number'), + 'field' => 'order_number', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.order_number'), ], [ - "field" => "notes", - "searchable" => true, - "sortable" => true, - "visible" => false, - "title" => trans('general.notes'), - "formatter" => "notesFormatter" - ] + 'field' => 'notes', + 'searchable' => true, + 'sortable' => true, + 'visible' => false, + 'title' => trans('general.notes'), + 'formatter' => 'notesFormatter', + ], ]; $layout[] = [ - "field" => "checkincheckout", - "searchable" => false, - "sortable" => false, - "switchable" => true, - "title" => trans('general.checkin').'/'.trans('general.checkout'), - "visible" => true, - "formatter" => "licensesInOutFormatter", + 'field' => 'checkincheckout', + 'searchable' => false, + 'sortable' => false, + 'switchable' => true, + 'title' => trans('general.checkin').'/'.trans('general.checkout'), + 'visible' => true, + 'formatter' => 'licensesInOutFormatter', ]; $layout[] = [ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "formatter" => "licensesActionsFormatter", + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'formatter' => 'licensesActionsFormatter', ]; - return json_encode($layout); } - /** * Json Column Layout for bootstrap table * @return string @@ -192,69 +189,68 @@ class LicensePresenter extends Presenter { $layout = [ [ - "field" => "name", - "searchable" => false, - "sortable" => false, - "sorter" => "numericOnly", - "switchable" => true, - "title" => trans('admin/licenses/general.seat'), - "visible" => true, + 'field' => 'name', + 'searchable' => false, + 'sortable' => false, + 'sorter' => 'numericOnly', + 'switchable' => true, + 'title' => trans('admin/licenses/general.seat'), + 'visible' => true, ], [ - "field" => "assigned_user", - "searchable" => false, - "sortable" => false, - "switchable" => true, - "title" => trans('admin/licenses/general.user'), - "visible" => true, - "formatter" => "usersLinkObjFormatter" + 'field' => 'assigned_user', + 'searchable' => false, + 'sortable' => false, + 'switchable' => true, + 'title' => trans('admin/licenses/general.user'), + 'visible' => true, + 'formatter' => 'usersLinkObjFormatter', ], [ - "field" => "department", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.department'), - "visible" => false, - "formatter" => "departmentNameLinkFormatter" + 'field' => 'department', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.department'), + 'visible' => false, + 'formatter' => 'departmentNameLinkFormatter', ], [ - "field" => "assigned_asset", - "searchable" => false, - "sortable" => false, - "switchable" => true, - "title" => trans('admin/licenses/form.asset'), - "visible" => true, - "formatter" => "hardwareLinkObjFormatter" + 'field' => 'assigned_asset', + 'searchable' => false, + 'sortable' => false, + 'switchable' => true, + 'title' => trans('admin/licenses/form.asset'), + 'visible' => true, + 'formatter' => 'hardwareLinkObjFormatter', ], [ - "field" => "location", - "searchable" => false, - "sortable" => false, - "switchable" => true, - "title" => trans('general.location'), - "visible" => true, - "formatter" => "locationsLinkObjFormatter" + 'field' => 'location', + 'searchable' => false, + 'sortable' => false, + 'switchable' => true, + 'title' => trans('general.location'), + 'visible' => true, + 'formatter' => 'locationsLinkObjFormatter', ], [ - "field" => "checkincheckout", - "searchable" => false, - "sortable" => false, - "switchable" => true, - "title" => trans('general.checkin').'/'.trans('general.checkout'), - "visible" => true, - "formatter" => "licenseSeatInOutFormatter" - ] + 'field' => 'checkincheckout', + 'searchable' => false, + 'sortable' => false, + 'switchable' => true, + 'title' => trans('general.checkin').'/'.trans('general.checkout'), + 'visible' => true, + 'formatter' => 'licenseSeatInOutFormatter', + ], ]; return json_encode($layout); } - /** * Link to this licenses Name * @return string */ public function nameUrl() { - return (string)link_to_route('licenses.show', $this->name, $this->id); + return (string) link_to_route('licenses.show', $this->name, $this->id); } /** @@ -266,14 +262,13 @@ class LicensePresenter extends Presenter return $this->name; } - /** * Link to this licenses serial * @return string */ public function serialUrl() { - return (string) link_to('/licenses/'.$this->id, mb_strimwidth($this->serial, 0, 50, "...")); + return (string) link_to('/licenses/'.$this->id, mb_strimwidth($this->serial, 0, 50, '...')); } /** diff --git a/app/Presenters/LicenseSeatPresenter.php b/app/Presenters/LicenseSeatPresenter.php index 03f02cbd72..ed706f95a7 100644 --- a/app/Presenters/LicenseSeatPresenter.php +++ b/app/Presenters/LicenseSeatPresenter.php @@ -4,7 +4,6 @@ namespace App\Presenters; /** * Class LicensePresenter - * @package App\Presenters */ class LicenseSeatPresenter extends Presenter { diff --git a/app/Presenters/LocationPresenter.php b/app/Presenters/LocationPresenter.php index 9a91e2af2a..b327cf07b3 100644 --- a/app/Presenters/LocationPresenter.php +++ b/app/Presenters/LocationPresenter.php @@ -4,11 +4,9 @@ namespace App\Presenters; /** * Class LocationPresenter - * @package App\Presenters */ class LocationPresenter extends Presenter { - /** * Json Column Layout for bootstrap table * @return string @@ -18,163 +16,161 @@ class LocationPresenter extends Presenter $layout = [ [ - "field" => "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "name", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/locations/table.name'), - "visible" => true, - "formatter" => "locationsLinkFormatter" + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/locations/table.name'), + 'visible' => true, + 'formatter' => 'locationsLinkFormatter', ], [ - "field" => "image", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.image'), - "visible" => true, - "formatter" => "imageFormatter" + 'field' => 'image', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.image'), + 'visible' => true, + 'formatter' => 'imageFormatter', ], [ - "field" => "parent", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/locations/table.parent'), - "visible" => true, - "formatter" => "locationsLinkObjFormatter" + 'field' => 'parent', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/locations/table.parent'), + 'visible' => true, + 'formatter' => 'locationsLinkObjFormatter', ], [ - "field" => "assets_count", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/locations/table.assets_rtd'), - "visible" => true, + 'field' => 'assets_count', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/locations/table.assets_rtd'), + 'visible' => true, ], [ - "field" => "assigned_assets_count", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/locations/table.assets_checkedout'), - "visible" => true, + 'field' => 'assigned_assets_count', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/locations/table.assets_checkedout'), + 'visible' => true, ], [ - "field" => "users_count", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.people'), - "visible" => true, + 'field' => 'users_count', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.people'), + 'visible' => true, ], [ - "field" => "currency", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.currency'), - "visible" => true, + 'field' => 'currency', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.currency'), + 'visible' => true, ], [ - "field" => "address", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/locations/table.address'), - "visible" => true, + 'field' => 'address', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/locations/table.address'), + 'visible' => true, ], [ - "field" => "city", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/locations/table.city'), - "visible" => true, + 'field' => 'city', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/locations/table.city'), + 'visible' => true, ], [ - "field" => "state", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/locations/table.state'), - "visible" => true, + 'field' => 'state', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/locations/table.state'), + 'visible' => true, ], [ - "field" => "zip", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/locations/table.zip'), - "visible" => false, + 'field' => 'zip', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/locations/table.zip'), + 'visible' => false, ], [ - "field" => "country", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/locations/table.country'), - "visible" => false, + 'field' => 'country', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/locations/table.country'), + 'visible' => false, ], [ - "field" => "ldap_ou", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/locations/table.ldap_ou'), - "visible" => false, + 'field' => 'ldap_ou', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/locations/table.ldap_ou'), + 'visible' => false, ], [ - "field" => "manager", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/users/table.manager'), - "visible" => false, - "formatter" => 'usersLinkObjFormatter' + 'field' => 'manager', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/users/table.manager'), + 'visible' => false, + 'formatter' => 'usersLinkObjFormatter', ], [ - "field" => "created_at", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.created_at'), - "visible" => false, - 'formatter' => 'dateDisplayFormatter' + 'field' => 'created_at', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.created_at'), + 'visible' => false, + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "visible" => true, - "formatter" => "locationsActionsFormatter", - ] + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'visible' => true, + 'formatter' => 'locationsActionsFormatter', + ], ]; return json_encode($layout); } - - /** * Link to this locations name * @return string */ public function nameUrl() { - return (string)link_to_route('locations.show', $this->name, $this->id); + return (string) link_to_route('locations.show', $this->name, $this->id); } /** @@ -199,8 +195,9 @@ class LocationPresenter extends Presenter { return ''; } - - public function fullName() { + + public function fullName() + { return $this->name; } } diff --git a/app/Presenters/ManufacturerPresenter.php b/app/Presenters/ManufacturerPresenter.php index c78da85f00..d2c3a93456 100644 --- a/app/Presenters/ManufacturerPresenter.php +++ b/app/Presenters/ManufacturerPresenter.php @@ -4,11 +4,9 @@ namespace App\Presenters; /** * Class ManufacturerPresenter - * @package App\Presenters */ class ManufacturerPresenter extends Presenter { - /** * Json Column Layout for bootstrap table * @return string @@ -18,131 +16,129 @@ class ManufacturerPresenter extends Presenter $layout = [ [ - "field" => "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "name", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/manufacturers/table.name'), - "visible" => true, - "formatter" => "manufacturersLinkFormatter" + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/manufacturers/table.name'), + 'visible' => true, + 'formatter' => 'manufacturersLinkFormatter', ], [ - "field" => "image", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.image'), - "visible" => true, - "formatter" => "imageFormatter" + 'field' => 'image', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.image'), + 'visible' => true, + 'formatter' => 'imageFormatter', ], [ - "field" => "url", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/manufacturers/table.url'), - "visible" => true, - "formatter" => "linkFormatter" + 'field' => 'url', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/manufacturers/table.url'), + 'visible' => true, + 'formatter' => 'linkFormatter', ], [ - "field" => "support_url", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/manufacturers/table.support_url'), - "visible" => true, - "formatter" => "linkFormatter" + 'field' => 'support_url', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/manufacturers/table.support_url'), + 'visible' => true, + 'formatter' => 'linkFormatter', ], [ - "field" => "support_phone", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/manufacturers/table.support_phone'), - "visible" => true, - "formatter" => "phoneFormatter" + 'field' => 'support_phone', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/manufacturers/table.support_phone'), + 'visible' => true, + 'formatter' => 'phoneFormatter', ], [ - "field" => "support_email", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/manufacturers/table.support_email'), - "visible" => true, - "formatter" => "emailFormatter" + 'field' => 'support_email', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/manufacturers/table.support_email'), + 'visible' => true, + 'formatter' => 'emailFormatter', ], [ - "field" => "assets_count", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => ' ' + 'field' => 'assets_count', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => ' ' .'', - "visible" => true, + 'visible' => true, ], [ - "field" => "licenses_count", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => ' ' + 'field' => 'licenses_count', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => ' ' .'', - "visible" => true, + 'visible' => true, ], [ - "field" => "consumables_count", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => ' ' + 'field' => 'consumables_count', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => ' ' .'', - "visible" => true, + 'visible' => true, ], [ - "field" => "accessories_count", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => ' ' + 'field' => 'accessories_count', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => ' ' .'', - "visible" => true, + 'visible' => true, ], [ - "field" => "created_at", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.created_at'), - "visible" => false, - 'formatter' => 'dateDisplayFormatter' + 'field' => 'created_at', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.created_at'), + 'visible' => false, + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "visible" => true, - "formatter" => "manufacturersActionsFormatter", - ] + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'visible' => true, + 'formatter' => 'manufacturersActionsFormatter', + ], ]; return json_encode($layout); } - - /** * Link to this manufacturers name * @return string diff --git a/app/Presenters/PredefinedKitPresenter.php b/app/Presenters/PredefinedKitPresenter.php index dddaff069f..b9fa5b5ae5 100644 --- a/app/Presenters/PredefinedKitPresenter.php +++ b/app/Presenters/PredefinedKitPresenter.php @@ -4,7 +4,6 @@ namespace App\Presenters; /** * Class LicensePresenter - * @package App\Presenters */ class PredefinedKitPresenter extends Presenter { @@ -16,45 +15,43 @@ class PredefinedKitPresenter extends Presenter { $layout = [ [ - "field" => "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "name", - "searchable" => true, - "sortable" => true, - "title" => 'Name', // TODO: trans - "formatter" => "kitsLinkFormatter" - ] + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'title' => 'Name', // TODO: trans + 'formatter' => 'kitsLinkFormatter', + ], ]; $layout[] = [ - "field" => "checkincheckout", - "searchable" => false, - "sortable" => false, - "switchable" => true, - "title" => trans('general.checkin').'/'.trans('general.checkout'), - "visible" => true, - "formatter" => "kitsInOutFormatter", + 'field' => 'checkincheckout', + 'searchable' => false, + 'sortable' => false, + 'switchable' => true, + 'title' => trans('general.checkin').'/'.trans('general.checkout'), + 'visible' => true, + 'formatter' => 'kitsInOutFormatter', ]; $layout[] = [ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "formatter" => "kitsActionsFormatter", + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'formatter' => 'kitsActionsFormatter', ]; - return json_encode($layout); } - /** * Json Column Layout for bootstrap table of kit models * @return string @@ -63,215 +60,213 @@ class PredefinedKitPresenter extends Presenter { $layout = [ [ - "field" => "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "pivot_id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'pivot_id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "owner_id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'owner_id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "name", - "searchable" => true, - "sortable" => true, - "title" => 'Name', // TODO: trans - "formatter" => "modelsLinkFormatter" + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'title' => 'Name', // TODO: trans + 'formatter' => 'modelsLinkFormatter', ], [ - "field" => "quantity", - "searchable" => false, - "sortable" => false, - "title" => 'Quantity', // TODO: trans + 'field' => 'quantity', + 'searchable' => false, + 'sortable' => false, + 'title' => 'Quantity', // TODO: trans ], [ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "formatter" => "kits_modelsActionsFormatter", - ] + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'formatter' => 'kits_modelsActionsFormatter', + ], ]; return json_encode($layout); } /** - * Json Column Layout for bootstrap table of kit licenses - * @return string - */ + * Json Column Layout for bootstrap table of kit licenses + * @return string + */ public static function dataTableLicenses() { $layout = [ [ - "field" => "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "pivot_id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'pivot_id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "owner_id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'owner_id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "name", - "searchable" => true, - "sortable" => true, - "title" => 'Name', // TODO: trans - "formatter" => "licensesLinkFormatter" + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'title' => 'Name', // TODO: trans + 'formatter' => 'licensesLinkFormatter', ], [ - "field" => "quantity", - "searchable" => false, - "sortable" => false, - "title" => 'Quantity', // TODO: trans + 'field' => 'quantity', + 'searchable' => false, + 'sortable' => false, + 'title' => 'Quantity', // TODO: trans ], [ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "formatter" => "kits_licensesActionsFormatter", - ] + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'formatter' => 'kits_licensesActionsFormatter', + ], ]; return json_encode($layout); } /** - * Json Column Layout for bootstrap table of kit accessories - * @return string - */ + * Json Column Layout for bootstrap table of kit accessories + * @return string + */ public static function dataTableAccessories() { $layout = [ [ - "field" => "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "pivot_id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'pivot_id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "owner_id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'owner_id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "name", - "searchable" => true, - "sortable" => true, - "title" => 'Name', // TODO: trans - "formatter" => "accessoriesLinkFormatter" + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'title' => 'Name', // TODO: trans + 'formatter' => 'accessoriesLinkFormatter', ], [ - "field" => "quantity", - "searchable" => false, - "sortable" => false, - "title" => 'Quantity', // TODO: trans + 'field' => 'quantity', + 'searchable' => false, + 'sortable' => false, + 'title' => 'Quantity', // TODO: trans ], [ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "formatter" => "kits_accessoriesActionsFormatter", - ] + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'formatter' => 'kits_accessoriesActionsFormatter', + ], ]; return json_encode($layout); } - /** - * Json Column Layout for bootstrap table of kit consumables - * @return string - */ + * Json Column Layout for bootstrap table of kit consumables + * @return string + */ public static function dataTableConsumables() { $layout = [ [ - "field" => "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "pivot_id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'pivot_id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "owner_id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'owner_id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "name", - "searchable" => true, - "sortable" => true, - "title" => 'Name', // TODO: trans - "formatter" => "consumablesLinkFormatter" + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'title' => 'Name', // TODO: trans + 'formatter' => 'consumablesLinkFormatter', ], [ - "field" => "quantity", - "searchable" => false, - "sortable" => false, - "title" => 'Quantity', // TODO: trans + 'field' => 'quantity', + 'searchable' => false, + 'sortable' => false, + 'title' => 'Quantity', // TODO: trans ], [ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "formatter" => "kits_consumablesActionsFormatter", - ] + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'formatter' => 'kits_consumablesActionsFormatter', + ], ]; return json_encode($layout); } - /** * Link to this kit Name * @return string */ public function nameUrl() { - return (string)link_to_route('kits.show', $this->name, $this->id); + return (string) link_to_route('kits.show', $this->name, $this->id); } /** diff --git a/app/Presenters/Presentable.php b/app/Presenters/Presentable.php index 19e9526599..15da2ba04f 100644 --- a/app/Presenters/Presentable.php +++ b/app/Presenters/Presentable.php @@ -4,21 +4,18 @@ namespace App\Presenters; trait Presentable { - protected $presenterInterface; public function present() { - - if (!$this->presenter || !class_exists($this->presenter)) { + if (! $this->presenter || ! class_exists($this->presenter)) { throw new \Exception('Presenter class does not exist'); } - if (!isset($this->presenterInterface)) { + if (! isset($this->presenterInterface)) { $this->presenterInterface = new $this->presenter($this); } return $this->presenterInterface; - } } diff --git a/app/Presenters/Presenter.php b/app/Presenters/Presenter.php index c47c2547d9..85fe2338ae 100644 --- a/app/Presenters/Presenter.php +++ b/app/Presenters/Presenter.php @@ -6,7 +6,6 @@ use App\Models\SnipeModel; abstract class Presenter { - /** * @var SnipeModel */ @@ -33,6 +32,7 @@ abstract class Presenter if ($model->category) { return $model->category->present()->nameUrl(); } + return ''; } @@ -41,6 +41,7 @@ abstract class Presenter if ($this->model->location) { return $this->model->location->present()->nameUrl(); } + return ''; } @@ -49,8 +50,10 @@ abstract class Presenter if ($this->model->company) { return $this->model->company->present()->nameUrl(); } + return ''; } + public function manufacturerUrl() { $model = $this->model; @@ -62,6 +65,7 @@ abstract class Presenter if ($model->manufacturer) { return $model->manufacturer->present()->nameUrl(); } + return ''; } diff --git a/app/Presenters/UserPresenter.php b/app/Presenters/UserPresenter.php index 77d24265fe..993dbbe42c 100644 --- a/app/Presenters/UserPresenter.php +++ b/app/Presenters/UserPresenter.php @@ -10,12 +10,9 @@ use Illuminate\Support\Facades\Storage; /** * Class UserPresenter - * @package App\Presenters */ class UserPresenter extends Presenter { - - /** * Json Column Layout for bootstrap table * @return string @@ -24,152 +21,170 @@ class UserPresenter extends Presenter { $layout = [ [ - "field" => "checkbox", - "checkbox" => true + 'field' => 'checkbox', + 'checkbox' => true, ], [ - "field" => "id", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.id'), - "visible" => false + 'field' => 'id', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.id'), + 'visible' => false, ], [ - "field" => "avatar", - "searchable" => false, - "sortable" => false, - "switchable" => true, - "title" => 'Avatar', - "visible" => false, - "formatter" => "imageFormatter" + 'field' => 'avatar', + 'searchable' => false, + 'sortable' => false, + 'switchable' => true, + 'title' => 'Avatar', + 'visible' => false, + 'formatter' => 'imageFormatter', ], [ - "field" => "company", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/companies/table.title'), - "visible" => false, - "formatter" => "companiesLinkObjFormatter" + 'field' => 'company', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/companies/table.title'), + 'visible' => false, + 'formatter' => 'companiesLinkObjFormatter', ], [ - "field" => "name", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/users/table.name'), - "visible" => true, - "formatter" => "usersLinkFormatter" + 'field' => 'name', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/users/table.name'), + 'visible' => true, + 'formatter' => 'usersLinkFormatter', + ], + + [ + 'field' => 'first_name', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.first_name'), + 'visible' => false, + 'formatter' => 'usersLinkFormatter', + ], + + [ + 'field' => 'last_name', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('general.last_name'), + 'visible' => false, + 'formatter' => 'usersLinkFormatter', ], [ - "field" => "jobtitle", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/users/table.title'), - "visible" => true, - "formatter" => "usersLinkFormatter" + 'field' => 'jobtitle', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/users/table.title'), + 'visible' => true, + 'formatter' => 'usersLinkFormatter', ], [ - "field" => "email", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/users/table.email'), - "visible" => true, - "formatter" => "emailFormatter" + 'field' => 'email', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/users/table.email'), + 'visible' => true, + 'formatter' => 'emailFormatter', ], [ - "field" => "phone", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/users/table.phone'), - "visible" => true, - "formatter" => "phoneFormatter", + 'field' => 'phone', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/users/table.phone'), + 'visible' => true, + 'formatter' => 'phoneFormatter', ], [ - "field" => "address", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.address'), - "visible" => false, + 'field' => 'address', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.address'), + 'visible' => false, ], [ - "field" => "city", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.city'), - "visible" => false, + 'field' => 'city', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.city'), + 'visible' => false, ], [ - "field" => "state", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.state'), - "visible" => false, + 'field' => 'state', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.state'), + 'visible' => false, ], [ - "field" => "country", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.country'), - "visible" => false, + 'field' => 'country', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.country'), + 'visible' => false, ], [ - "field" => "zip", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.zip'), - "visible" => false, + 'field' => 'zip', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.zip'), + 'visible' => false, ], [ - "field" => "username", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/users/table.username'), - "visible" => true, - "formatter" => "usersLinkFormatter" + 'field' => 'username', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/users/table.username'), + 'visible' => true, + 'formatter' => 'usersLinkFormatter', ], [ - "field" => "employee_num", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/users/table.employee_num'), - "visible" => false + 'field' => 'employee_num', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/users/table.employee_num'), + 'visible' => false, ], [ - "field" => "department", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.department'), - "visible" => true, - "formatter" => "departmentsLinkObjFormatter" + 'field' => 'department', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.department'), + 'visible' => true, + 'formatter' => 'departmentsLinkObjFormatter', ], [ - "field" => "location", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/users/table.location'), - "visible" => true, - "formatter" => "locationsLinkObjFormatter" + 'field' => 'location', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/users/table.location'), + 'visible' => true, + 'formatter' => 'locationsLinkObjFormatter', ], [ - "field" => "manager", - "searchable" => true, - "sortable" => true, - "title" => trans('admin/users/table.manager'), - "visible" => true, - "formatter" => "usersLinkObjFormatter" + 'field' => 'manager', + 'searchable' => true, + 'sortable' => true, + 'title' => trans('admin/users/table.manager'), + 'visible' => true, + 'formatter' => 'usersLinkObjFormatter', ], [ 'field' => 'assets_count', @@ -182,126 +197,127 @@ class UserPresenter extends Presenter 'visible' => true, ], [ - "field" => "licenses_count", - "searchable" => false, - "sortable" => true, - "switchable" => true, + 'field' => 'licenses_count', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, 'class' => 'css-license', - "title" => 'License', - "visible" => true, + 'title' => 'License', + 'visible' => true, ], [ - "field" => "consumables_count", - "searchable" => false, - "sortable" => true, - "switchable" => true, + 'field' => 'consumables_count', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, 'class' => 'css-consumable', - "title" => 'Consumables', - "visible" => true, + 'title' => 'Consumables', + 'visible' => true, ], [ - "field" => "accessories_count", - "searchable" => false, - "sortable" => true, - "switchable" => true, + 'field' => 'accessories_count', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, 'class' => 'css-accessory', - "title" => 'Accessories', - "visible" => true, + 'title' => 'Accessories', + 'visible' => true, ], [ - "field" => "notes", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.notes'), - "visible" => true, + 'field' => 'notes', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.notes'), + 'visible' => true, ], [ - "field" => "groups", - "searchable" => false, - "sortable" => false, - "switchable" => true, - "title" => trans('general.groups'), - "visible" => true, - 'formatter' => 'groupsFormatter' + 'field' => 'groups', + 'searchable' => false, + 'sortable' => false, + 'switchable' => true, + 'title' => trans('general.groups'), + 'visible' => true, + 'formatter' => 'groupsFormatter', ], [ - "field" => "ldap_import", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/settings/general.ldap_enabled'), - "visible" => false, - 'formatter' => 'trueFalseFormatter' + 'field' => 'ldap_import', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/settings/general.ldap_enabled'), + 'visible' => false, + 'formatter' => 'trueFalseFormatter', ], [ - "field" => "two_factor_enrolled", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('admin/users/general.two_factor_enrolled'), - "visible" => false, - 'formatter' => 'trueFalseFormatter' + 'field' => 'two_factor_enrolled', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('admin/users/general.two_factor_enrolled'), + 'visible' => false, + 'formatter' => 'trueFalseFormatter', ], [ - "field" => "two_factor_activated", - "searchable" => false, - "sortable" => false, - "switchable" => true, - "title" => trans('admin/users/general.two_factor_active'), - "visible" => false, - 'formatter' => 'trueFalseFormatter' + 'field' => 'two_factor_activated', + 'searchable' => false, + 'sortable' => false, + 'switchable' => true, + 'title' => trans('admin/users/general.two_factor_active'), + 'visible' => false, + 'formatter' => 'trueFalseFormatter', ], [ - "field" => "activated", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.login_enabled'), - "visible" => true, - 'formatter' => 'trueFalseFormatter' + 'field' => 'activated', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.login_enabled'), + 'visible' => true, + 'formatter' => 'trueFalseFormatter', ], [ - "field" => "created_at", - "searchable" => true, - "sortable" => true, - "switchable" => true, - "title" => trans('general.created_at'), - "visible" => false, - 'formatter' => 'dateDisplayFormatter' + 'field' => 'created_at', + 'searchable' => true, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.created_at'), + 'visible' => false, + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "last_login", - "searchable" => false, - "sortable" => true, - "switchable" => true, - "title" => trans('general.last_login'), - "visible" => false, - 'formatter' => 'dateDisplayFormatter' + 'field' => 'last_login', + 'searchable' => false, + 'sortable' => true, + 'switchable' => true, + 'title' => trans('general.last_login'), + 'visible' => false, + 'formatter' => 'dateDisplayFormatter', ], [ - "field" => "actions", - "searchable" => false, - "sortable" => false, - "switchable" => false, - "title" => trans('table.actions'), - "visible" => true, - "formatter" => "usersActionsFormatter", - ] + 'field' => 'actions', + 'searchable' => false, + 'sortable' => false, + 'switchable' => false, + 'title' => trans('table.actions'), + 'visible' => true, + 'formatter' => 'usersActionsFormatter', + ], ]; return json_encode($layout); } - public function emailLink() { if ($this->email) { return ''.$this->email.'' .''; } + return ''; } + /** * Returns the user full name, it simply concatenates * the user first and last name. @@ -322,6 +338,7 @@ class UserPresenter extends Presenter { return $this->fullName(); } + /** * Returns the user Gravatar image url. * @@ -329,25 +346,24 @@ class UserPresenter extends Presenter */ public function gravatar() { - - if ($this->avatar) { return Storage::disk('public')->url('avatars/'.e($this->avatar)); } - if (Setting::getSettings()->load_remote=='1') { - if ($this->model->gravatar!='') { + if (Setting::getSettings()->load_remote == '1') { + if ($this->model->gravatar != '') { $gravatar = md5(strtolower(trim($this->model->gravatar))); - return "//gravatar.com/avatar/".$gravatar; - } elseif ($this->email!='') { + + return '//gravatar.com/avatar/'.$gravatar; + } elseif ($this->email != '') { $gravatar = md5(strtolower(trim($this->email))); - return "//gravatar.com/avatar/".$gravatar; + + return '//gravatar.com/avatar/'.$gravatar; } } // Set a fun, gender-neutral default icon return url('/').'/img/default-sm.png'; - } /** diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index c2651c3aef..bb5643a920 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -1,6 +1,6 @@ app->environment('production')) && (config('logging.channels.rollbar.access_token'))) { + if (($this->app->environment('production')) && (config('logging.channels.rollbar.access_token'))) { $this->app->register(\Rollbar\Laravel\RollbarServiceProvider::class); } - } } diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index b24df173c3..31a328abfe 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -80,14 +80,12 @@ class AuthServiceProvider extends ServiceProvider */ public function boot() { - $this->commands([ \Laravel\Passport\Console\InstallCommand::class, \Laravel\Passport\Console\ClientCommand::class, \Laravel\Passport\Console\KeysCommand::class, ]); - $this->registerPolicies(); Passport::routes(); Passport::tokensExpireIn(Carbon::now()->addYears(config('passport.expiration_years'))); @@ -95,7 +93,6 @@ class AuthServiceProvider extends ServiceProvider Passport::personalAccessTokensExpireIn(Carbon::now()->addYears(config('passport.expiration_years'))); Passport::withCookieSerialization(); - // -------------------------------- // BEFORE ANYTHING ELSE // -------------------------------- @@ -117,42 +114,40 @@ class AuthServiceProvider extends ServiceProvider } }); - // Can the user import CSVs? Gate::define('import', function ($user) { - if ($user->hasAccess('import') ) { + if ($user->hasAccess('import')) { return true; } }); - - # ----------------------------------------- - # Reports - # ----------------------------------------- + // ----------------------------------------- + // Reports + // ----------------------------------------- Gate::define('reports.view', function ($user) { if ($user->hasAccess('reports.view')) { return true; } }); - # ----------------------------------------- - # Self - # ----------------------------------------- + // ----------------------------------------- + // Self + // ----------------------------------------- Gate::define('self.two_factor', function ($user) { if (($user->hasAccess('self.two_factor')) || ($user->hasAccess('admin'))) { return true; } }); - Gate::define('self.api', function($user) { + Gate::define('self.api', function ($user) { return $user->hasAccess('self.api'); }); - Gate::define('self.edit_location', function($user) { + Gate::define('self.edit_location', function ($user) { return $user->hasAccess('self.edit_location'); }); - Gate::define('self.checkout_assets', function($user) { + Gate::define('self.checkout_assets', function ($user) { return $user->hasAccess('self.checkout_assets'); }); @@ -167,7 +162,7 @@ class AuthServiceProvider extends ServiceProvider || $user->can('view', Company::class) || $user->can('view', Manufacturer::class) || $user->can('view', CustomField::class) - || $user->can('view', CustomFieldset::class) + || $user->can('view', CustomFieldset::class) || $user->can('view', Depreciation::class); }); } diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index a67715fc12..1f08b445c9 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -15,11 +15,11 @@ class EventServiceProvider extends ServiceProvider */ protected $listen = [ 'Illuminate\Auth\Events\Login' => [ - 'App\Listeners\LogSuccessfulLogin', + \App\Listeners\LogSuccessfulLogin::class, ], 'Illuminate\Auth\Events\Failed' => [ - 'App\Listeners\LogFailedLogin', + \App\Listeners\LogFailedLogin::class, ], ]; @@ -30,6 +30,6 @@ class EventServiceProvider extends ServiceProvider */ protected $subscribe = [ LogListener::class, - CheckoutableListener::class + CheckoutableListener::class, ]; } diff --git a/app/Providers/LdapServiceProvider.php b/app/Providers/LdapServiceProvider.php index 5b3e71761c..58f93096d3 100644 --- a/app/Providers/LdapServiceProvider.php +++ b/app/Providers/LdapServiceProvider.php @@ -1,12 +1,13 @@ -configureRateLimiting(); - parent::boot(); - } + $this->routes(function () { + $this->mapApiRoutes(); - /** - * Define the routes for the application. - * - * @return void - */ - public function map() - { - $this->mapApiRoutes(); + $this->mapWebRoutes(); - $this->mapWebRoutes(); - - // + // + }); } /** @@ -85,4 +71,16 @@ class RouteServiceProvider extends ServiceProvider require base_path('routes/api.php'); }); } + + /** + * Configure the rate limiters for the application. + * + * @return void + */ + protected function configureRateLimiting() + { + RateLimiter::for('api', function (Request $request) { + return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip()); + }); + } } diff --git a/app/Providers/SamlServiceProvider.php b/app/Providers/SamlServiceProvider.php index 0caf0e77dd..18b93cf56f 100644 --- a/app/Providers/SamlServiceProvider.php +++ b/app/Providers/SamlServiceProvider.php @@ -3,8 +3,8 @@ namespace App\Providers; use App\Services\Saml; -use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Route; +use Illuminate\Support\ServiceProvider; class SamlServiceProvider extends ServiceProvider { @@ -23,7 +23,7 @@ class SamlServiceProvider extends ServiceProvider 'metadata', [ 'as' => 'saml.metadata', - 'uses' => 'Auth\SamlController@metadata' ] + 'uses' => 'Auth\SamlController@metadata', ] ); Route::match( @@ -31,14 +31,14 @@ class SamlServiceProvider extends ServiceProvider 'acs', [ 'as' => 'saml.acs', - 'uses' => 'Auth\SamlController@acs' ] + 'uses' => 'Auth\SamlController@acs', ] ); Route::get( 'sls', [ 'as' => 'saml.sls', - 'uses' => 'Auth\SamlController@sls' ] + 'uses' => 'Auth\SamlController@sls', ] ); }); @@ -46,14 +46,12 @@ class SamlServiceProvider extends ServiceProvider 'login/saml', [ 'as' => 'saml.login', - 'uses' => 'Auth\SamlController@login' ] + 'uses' => 'Auth\SamlController@login', ] ); - Route::group(['prefix' => 'admin','middleware' => ['web','auth', 'authorize:superuser']], function () { - - Route::get('saml', ['as' => 'settings.saml.index','uses' => 'SettingsController@getSamlSettings' ]); - Route::post('saml', ['as' => 'settings.saml.save','uses' => 'SettingsController@postSamlSettings' ]); - + Route::group(['prefix' => 'admin', 'middleware' => ['web', 'auth', 'authorize:superuser']], function () { + Route::get('saml', ['as' => 'settings.saml.index', 'uses' => 'SettingsController@getSamlSettings']); + Route::post('saml', ['as' => 'settings.saml.save', 'uses' => 'SettingsController@postSamlSettings']); }); }); } diff --git a/app/Providers/SettingsServiceProvider.php b/app/Providers/SettingsServiceProvider.php index adf25b6435..be9928282c 100644 --- a/app/Providers/SettingsServiceProvider.php +++ b/app/Providers/SettingsServiceProvider.php @@ -1,8 +1,9 @@ composer('*', function ($view) { $view->with('snipeSettings', Setting::getSettings()); }); - /** * Set some common variables so that they're globally available. * The paths should always be public (versus private uploads) */ - - // Model paths and URLs - \App::singleton('assets_upload_path', function(){ + \App::singleton('assets_upload_path', function () { return 'assets/'; }); - \App::singleton('accessories_upload_path', function() { + \App::singleton('accessories_upload_path', function () { return 'public/uploads/accessories/'; }); - \App::singleton('models_upload_path', function(){ + \App::singleton('models_upload_path', function () { return 'models/'; }); - \App::singleton('models_upload_url', function(){ + \App::singleton('models_upload_url', function () { return 'models/'; }); // Categories - \App::singleton('categories_upload_path', function(){ + \App::singleton('categories_upload_path', function () { return 'categories/'; }); - \App::singleton('categories_upload_url', function(){ + \App::singleton('categories_upload_url', function () { return 'categories/'; }); // Locations - \App::singleton('locations_upload_path', function(){ + \App::singleton('locations_upload_path', function () { return 'locations/'; }); - \App::singleton('locations_upload_url', function(){ + \App::singleton('locations_upload_url', function () { return 'locations/'; }); // Users - \App::singleton('users_upload_path', function(){ + \App::singleton('users_upload_path', function () { return 'avatars/'; }); - \App::singleton('users_upload_url', function(){ + \App::singleton('users_upload_url', function () { return 'users/'; }); // Manufacturers - \App::singleton('manufacturers_upload_path', function(){ + \App::singleton('manufacturers_upload_path', function () { return 'manufacturers/'; }); - \App::singleton('manufacturers_upload_url', function(){ + \App::singleton('manufacturers_upload_url', function () { return 'manufacturers/'; }); // Suppliers - \App::singleton('suppliers_upload_path', function(){ + \App::singleton('suppliers_upload_path', function () { return 'suppliers/'; }); - \App::singleton('suppliers_upload_url', function(){ + \App::singleton('suppliers_upload_url', function () { return 'suppliers/'; }); // Departments - \App::singleton('departments_upload_path', function(){ + \App::singleton('departments_upload_path', function () { return 'departments/'; }); - \App::singleton('departments_upload_url', function(){ + \App::singleton('departments_upload_url', function () { return 'departments/'; }); // Company paths and URLs - \App::singleton('companies_upload_path', function(){ + \App::singleton('companies_upload_path', function () { return 'companies/'; }); - \App::singleton('companies_upload_url', function(){ + \App::singleton('companies_upload_url', function () { return 'companies/'; }); // Accessories paths and URLs - \App::singleton('accessories_upload_path', function(){ + \App::singleton('accessories_upload_path', function () { return 'accessories/'; }); - \App::singleton('accessories_upload_url', function(){ + \App::singleton('accessories_upload_url', function () { return 'accessories/'; }); // Consumables paths and URLs - \App::singleton('consumables_upload_path', function(){ + \App::singleton('consumables_upload_path', function () { return 'consumables/'; }); - \App::singleton('consumables_upload_url', function(){ + \App::singleton('consumables_upload_url', function () { return 'consumables/'; }); - // Components paths and URLs - \App::singleton('components_upload_path', function(){ + \App::singleton('components_upload_path', function () { return 'components/'; }); - \App::singleton('components_upload_url', function(){ + \App::singleton('components_upload_url', function () { return 'components/'; }); - - // Set the monetary locale to the configured locale to make helper::parseFloat work. setlocale(LC_MONETARY, config('app.locale')); setlocale(LC_NUMERIC, config('app.locale')); - } /** @@ -162,6 +154,5 @@ class SettingsServiceProvider extends ServiceProvider */ public function register() { - } } diff --git a/app/Providers/ValidationServiceProvider.php b/app/Providers/ValidationServiceProvider.php index ea9c322765..d68c79a268 100644 --- a/app/Providers/ValidationServiceProvider.php +++ b/app/Providers/ValidationServiceProvider.php @@ -1,4 +1,5 @@ 'email'); - $messages = array( - 'alert_email.*'=>trans('validation.email_array') - ); + $rules = ['alert_email.*'=>'email']; + $messages = [ + 'alert_email.*'=>trans('validation.email_array'), + ]; $validator = Validator::make($email_to_validate, $rules, $messages); return $validator->passes(); - }); - // Unique only if undeleted // This works around the use case where multiple deleted items have the same unique attribute. // (I think this is a bug in Laravel's validator?) Validator::extend('unique_undeleted', function ($attribute, $value, $parameters, $validator) { - if (count($parameters)) { $count = DB::table($parameters[0])->select('id')->where($attribute, '=', $value)->whereNull('deleted_at')->where('id', '!=', $parameters[1])->count(); + return $count < 1; } - }); - // Prevent circular references // // Example usage in Location model where parent_id references another Location: @@ -83,7 +79,7 @@ class ValidationServiceProvider extends ServiceProvider $data_pk = array_get($data, $pk); $value_pk = $value; - // If we’re editing an existing model and there is a parent value set… + // If we’re editing an existing model and there is a parent value set… while ($data_pk && $value_pk) { // It’s not valid for any parent id to be equal to the existing model’s id @@ -103,7 +99,6 @@ class ValidationServiceProvider extends ServiceProvider return true; }); - // Yo dawg. I heard you like validators. // This validates the custom validator regex in custom fields. // We're just checking that the regex won't throw an exception, not @@ -112,7 +107,7 @@ class ValidationServiceProvider extends ServiceProvider Validator::extend('valid_regex', function ($attribute, $value, $parameters, $validator) { // Make sure it's not just an ANY format - if ($value!='') { + if ($value != '') { // Check that the string starts with regex: if (strpos($value, 'regex:') === false) { @@ -122,55 +117,50 @@ class ValidationServiceProvider extends ServiceProvider $test_string = 'My hovercraft is full of eels'; // We have to stip out the regex: part here to check with preg_match - $test_pattern = str_replace('regex:','', $value); + $test_pattern = str_replace('regex:', '', $value); try { preg_match($test_pattern, $test_string); + return true; } catch (\Exception $e) { return false; } - } + return true; - }); - // This ONLY works for create/update user forms, since the Update Profile Password form doesn't // include any of these additional validator fields Validator::extend('disallow_same_pwd_as_user_fields', function ($attribute, $value, $parameters, $validator) { - $data = $validator->getData(); - if (array_key_exists("username", $data)) { + if (array_key_exists('username', $data)) { if ($data['username'] == $data['password']) { return false; } } - if (array_key_exists("email", $data)) { + if (array_key_exists('email', $data)) { if ($data['email'] == $data['password']) { return false; } } - if (array_key_exists("first_name", $data)) { + if (array_key_exists('first_name', $data)) { if ($data['first_name'] == $data['password']) { return false; } } - if (array_key_exists("last_name", $data)) { + if (array_key_exists('last_name', $data)) { if ($data['last_name'] == $data['password']) { return false; } } - - return true; - - + return true; }); Validator::extend('letters', function ($attribute, $value, $parameters) { @@ -196,7 +186,7 @@ class ValidationServiceProvider extends ServiceProvider // $validator gives us proper access to the rest of the actual data $data = $validator->getData(); - if(array_key_exists("id", $data)) { + if (array_key_exists('id', $data)) { if ($value && $value == $data['id']) { // if you definitely have an ID - you're saving an existing user - and your ID matches your manager's ID - fail. return false; @@ -209,8 +199,6 @@ class ValidationServiceProvider extends ServiceProvider return true; } }); - - } /** @@ -220,6 +208,5 @@ class ValidationServiceProvider extends ServiceProvider */ public function register() { - } } diff --git a/app/Services/LdapAd.php b/app/Services/LdapAd.php index 4bfef3d3ed..186a2c7a9d 100644 --- a/app/Services/LdapAd.php +++ b/app/Services/LdapAd.php @@ -47,9 +47,9 @@ class LdapAd extends LdapAdConfiguration '262688', // 0x40220 NORMAL_ACCOUNT, PASSWD_NOTREQD, SMARTCARD_REQUIRED '328192', // 0x50200 NORMAL_ACCOUNT, SMARTCARD_REQUIRED, DONT_EXPIRE_PASSWORD '328224', // 0x50220 NORMAL_ACCOUNT, PASSWD_NOT_REQD, SMARTCARD_REQUIRED, DONT_EXPIRE_PASSWORD - '4260352',// 0x410200 NORMAL_ACCOUNT, DONT_EXPIRE_PASSWORD, DONT_REQ_PREAUTH - '1049088',// 0x100200 NORMAL_ACCOUNT, NOT_DELEGATED - '1114624',// 0x110200 NORMAL_ACCOUNT, NOT_DELEGATED, DONT_EXPIRE_PASSWORD + '4260352', // 0x410200 NORMAL_ACCOUNT, DONT_EXPIRE_PASSWORD, DONT_REQ_PREAUTH + '1049088', // 0x100200 NORMAL_ACCOUNT, NOT_DELEGATED + '1114624', // 0x110200 NORMAL_ACCOUNT, NOT_DELEGATED, DONT_EXPIRE_PASSWORD ]; /** @@ -86,8 +86,8 @@ class LdapAd extends LdapAdConfiguration } parent::init(); - if($this->isLdapEnabled()) { - if($this->ldapSettings['is_ad'] == 0 ) { //only for NON-AD setups! + if ($this->isLdapEnabled()) { + if ($this->ldapSettings['is_ad'] == 0) { //only for NON-AD setups! $this->ldapConfig['account_prefix'] = $this->ldapSettings['ldap_auth_filter_query']; $this->ldapConfig['account_suffix'] = ','.$this->ldapConfig['base_dn']; } /* @@ -98,16 +98,19 @@ class LdapAd extends LdapAdConfiguration */ $this->ldap = new Adldap(); $this->ldap->addProvider($this->ldapConfig); + return true; } + return false; } - public function __construct() { + public function __construct() + { $this->init(); } - /** + /** * Create a user if they successfully login to the LDAP server. * * @author Wes Hulette @@ -124,7 +127,7 @@ class LdapAd extends LdapAdConfiguration public function ldapLogin(string $username, string $password): User { if ($this->ldapSettings['ad_append_domain']) { //if you're using 'userprincipalname', don't check the ad_append_domain checkbox - $login_username = $username . '@' . $this->ldapSettings['ad_domain']; // I feel like could can be solved with the 'suffix' feature? Then this would be easier. + $login_username = $username.'@'.$this->ldapSettings['ad_domain']; // I feel like could can be solved with the 'suffix' feature? Then this would be easier. } else { $login_username = $username; } @@ -137,18 +140,17 @@ class LdapAd extends LdapAdConfiguration if (($this->ldap) && ($this->ldap->auth()->attempt($login_username, $password, $bind_as_user) === false)) { throw new Exception('Unable to validate user credentials!'); - } + } // Should we sync the logged in user Log::debug('Attempting to find user in LDAP directory'); $record = $this->ldap->search()->findBy($this->ldapSettings['ldap_username_field'], $username); - if($record) { + if ($record) { if ($this->isLdapSync($record)) { $this->syncUserLdapLogin($record, $password); } - } - else { + } else { throw new Exception('Unable to find user in LDAP directory!'); } @@ -158,7 +160,7 @@ class LdapAd extends LdapAdConfiguration /* Above, I could've just done ->firstOrFail() which would've been cleaner, but it would've been miserable to troubleshoot if it ever came up (giving a really generic and untraceable error message) */ - if (!$user) { + if (! $user) { throw new Exception("User is either deleted, not activated (can't log in), not from LDAP, or can't be found in database"); } @@ -178,19 +180,19 @@ class LdapAd extends LdapAdConfiguration * * @return null|\App\Models\User */ - public function processUser(AdldapUser $user, ?Collection $defaultLocation=null, ?Collection $mappedLocations=null): ?User + public function processUser(AdldapUser $user, ?Collection $defaultLocation = null, ?Collection $mappedLocations = null): ?User { // Only sync active users <- I think this actually means 'existing', not 'activated/deactivated' - if(!$user) { + if (! $user) { return null; } $snipeUser = []; - $snipeUser['username'] = $user->{$this->ldapSettings['ldap_username_field']}[0] ?? ''; + $snipeUser['username'] = $user->{$this->ldapSettings['ldap_username_field']}[0] ?? ''; $snipeUser['employee_number'] = $user->{$this->ldapSettings['ldap_emp_num']}[0] ?? ''; - $snipeUser['lastname'] = $user->{$this->ldapSettings['ldap_lname_field']}[0] ?? ''; - $snipeUser['firstname'] = $user->{$this->ldapSettings['ldap_fname_field']}[0] ?? ''; - $snipeUser['email'] = $user->{$this->ldapSettings['ldap_email']}[0] ?? ''; - $snipeUser['title'] = $user->getTitle() ?? ''; + $snipeUser['lastname'] = $user->{$this->ldapSettings['ldap_lname_field']}[0] ?? ''; + $snipeUser['firstname'] = $user->{$this->ldapSettings['ldap_fname_field']}[0] ?? ''; + $snipeUser['email'] = $user->{$this->ldapSettings['ldap_email']}[0] ?? ''; + $snipeUser['title'] = $user->getTitle() ?? ''; $snipeUser['telephonenumber'] = $user->getTelephoneNumber() ?? ''; /* @@ -204,7 +206,7 @@ class LdapAd extends LdapAdConfiguration * and it *will* override the administrators previous choices. I think this is a fair compromise. */ $locationId = $this->getLocationId($user, $defaultLocation, $mappedLocations); - if ($locationId !== null ) { + if ($locationId !== null) { $snipeUser['location_id'] = $locationId; } @@ -233,29 +235,29 @@ class LdapAd extends LdapAdConfiguration $user = User::firstOrNew([ 'username' => $userInfo['username'], ]); - $user->username = $user->username ?? trim($userInfo['username']); - $user->password = $user->password ?? Helper::generateEncyrptedPassword(); - $user->first_name = trim($userInfo['firstname']); - $user->last_name = trim($userInfo['lastname']); - $user->email = trim($userInfo['email']); + $user->username = $user->username ?? trim($userInfo['username']); + $user->password = $user->password ?? Helper::generateEncyrptedPassword(); + $user->first_name = trim($userInfo['firstname']); + $user->last_name = trim($userInfo['lastname']); + $user->email = trim($userInfo['email']); $user->employee_num = trim($userInfo['employee_number']); - $user->jobtitle = trim($userInfo['title']); - $user->phone = trim($userInfo['telephonenumber']); - if (array_key_exists('activated',$userInfo)) { - $user->activated = $userInfo['activated']; - } else if ( !$user->exists ) { // no 'activated' flag was set or unset, *AND* this user is new - activate by default. + $user->jobtitle = trim($userInfo['title']); + $user->phone = trim($userInfo['telephonenumber']); + if (array_key_exists('activated', $userInfo)) { + $user->activated = $userInfo['activated']; + } elseif (! $user->exists) { // no 'activated' flag was set or unset, *AND* this user is new - activate by default. $user->activated = 1; } - if (array_key_exists('location_id',$userInfo)) { - $user->location_id = $userInfo['location_id']; + if (array_key_exists('location_id', $userInfo)) { + $user->location_id = $userInfo['location_id']; } // this is a new user - if (!isset($user->id)) { - $user->notes = 'Imported from LDAP'; + if (! isset($user->id)) { + $user->notes = 'Imported from LDAP'; } - $user->ldap_import = 1; + $user->ldap_import = 1; return $user; } @@ -285,7 +287,7 @@ class LdapAd extends LdapAdConfiguration $user->password = bcrypt($password); } - if (!$user->save()) { + if (! $user->save()) { Log::debug('Could not save user. '.$user->getErrors()); throw new Exception('Could not save user: '.$user->getErrors()); } @@ -304,13 +306,13 @@ class LdapAd extends LdapAdConfiguration */ private function isLdapSync(AdldapUser $user): bool { - if ( !$this->ldapSettings['ldap_active_flag']) { + if (! $this->ldapSettings['ldap_active_flag']) { return true; // always sync if you didn't define an 'active' flag } - - if ( $user->{$this->ldapSettings['ldap_active_flag']} && // if your LDAP user has the aforementioned flag as an attribute *AND* - count($user->{$this->ldapSettings['ldap_active_flag']}) == 1 && // if that attribute has exactly one value *AND* - strtolower($user->{$this->ldapSettings['ldap_active_flag']}[0]) == 'false') { // that value is the string 'false' (regardless of case), + + if ($user->{$this->ldapSettings['ldap_active_flag']} && // if your LDAP user has the aforementioned flag as an attribute *AND* + count($user->{$this->ldapSettings['ldap_active_flag']}) == 1 && // if that attribute has exactly one value *AND* + strtolower($user->{$this->ldapSettings['ldap_active_flag']}[0]) == 'false') { // that value is the string 'false' (regardless of case), return false; // then your user is *INACTIVE* - return false } // otherwise, return true @@ -338,8 +340,8 @@ class LdapAd extends LdapAdConfiguration * If the admin has set their own 'active flag' - respect that instead * (this may work to allow AD users to ignore the built-in UAC stuff that AD does) */ - if ($user->hasAttribute($user->getSchema()->userAccountControl()) && !$this->ldapSettings['ldap_active_flag']) { - \Log::debug('This is AD - userAccountControl is'. $user->getSchema()->userAccountControl()); + if ($user->hasAttribute($user->getSchema()->userAccountControl()) && ! $this->ldapSettings['ldap_active_flag']) { + \Log::debug('This is AD - userAccountControl is'.$user->getSchema()->userAccountControl()); $activeStatus = (in_array($user->getUserAccountControl(), self::AD_USER_ACCOUNT_CONTROL_FLAGS)) ? 1 : 0; } else { @@ -347,26 +349,27 @@ class LdapAd extends LdapAdConfiguration // If there is no activated flag, then we can't make any determination about activated/deactivated if (false == $this->ldapSettings['ldap_active_flag']) { \Log::debug('ldap_active_flag is false - no ldap_active_flag is set'); + return null; } // If there *is* an activated flag, then respect it *only* if it is actually present. If it's not there, ignore it. - if (!$user->hasAttribute($this->ldapSettings['ldap_active_flag'])) { + if (! $user->hasAttribute($this->ldapSettings['ldap_active_flag'])) { return null; // 'active' flag is defined, but does not exist on returned user record. So we don't know if they're active or not. } // if $user has the flag *AND* that flag has exactly one value - - if ( $user->{$this->ldapSettings['ldap_active_flag']} && count($user->{$this->ldapSettings['ldap_active_flag']}) == 1 ) { - + if ($user->{$this->ldapSettings['ldap_active_flag']} && count($user->{$this->ldapSettings['ldap_active_flag']}) == 1) { $active_flag_value = $user->{$this->ldapSettings['ldap_active_flag']}[0]; // if the value of that flag is case-insensitively the string 'false' or boolean false - if ( strcasecmp($active_flag_value, "false") == 0 || $active_flag_value === false ) { + if (strcasecmp($active_flag_value, 'false') == 0 || $active_flag_value === false) { return 0; // then make them INACTIVE } else { return 1; // otherwise active } } + return 1; // fail 'open' (active) if we have the attribute and it's multivalued or empty; that's weird } @@ -399,7 +402,7 @@ class LdapAd extends LdapAdConfiguration $location = $mappedLocations->filter(function ($value, $key) use ($user) { //if ($user->inOu($value)) { // <----- *THIS* seems not to be working, and it seems more 'intelligent' - but it's literally just a strpos() call, and it doesn't work quite right against plain strings $user_ou = substr($user->getDn(), -strlen($value)); // get the LAST chars of the user's DN, the count of those chars being the length of the thing we're checking against - if(strcasecmp($user_ou, $value) === 0) { // case *IN*sensitive comparision - some people say OU=blah, some say ou=blah. returns 0 when strings are identical (which is a little odd, yeah) + if (strcasecmp($user_ou, $value) === 0) { // case *IN*sensitive comparision - some people say OU=blah, some say ou=blah. returns 0 when strings are identical (which is a little odd, yeah) return $key; // WARNING: we are doing a 'filter' - not a regular for-loop. So the answer(s) get "return"ed into the $location array } }); @@ -423,7 +426,7 @@ class LdapAd extends LdapAdConfiguration */ private function getBaseDn(): string { - if (!is_null($this->baseDn)) { + if (! is_null($this->baseDn)) { return $this->baseDn; } @@ -442,7 +445,7 @@ class LdapAd extends LdapAdConfiguration private function getFilter(): ?string { $filter = $this->ldapSettings['ldap_filter']; - if (!$filter) { + if (! $filter) { return null; } // Add surrounding parentheses as needed @@ -468,6 +471,7 @@ class LdapAd extends LdapAdConfiguration { /** @var Schema $schema */ $schema = new $this->ldapConfig['schema']; + return array_values(array_filter([ $this->ldapSettings['ldap_username_field'], $this->ldapSettings['ldap_fname_field'], @@ -557,7 +561,7 @@ class LdapAd extends LdapAdConfiguration $search = $this->ldap->search()->users()->in($this->getBaseDn()); //this looks wrong; we should instead have a passable parameter that does this, and use this as a 'sane' default, yeah? $filter = $this->getFilter(); - if (!is_null($filter)) { + if (! is_null($filter)) { $search = $search->rawFilter($filter); } //I think it might be possible to potentially do our own paging here? diff --git a/app/Services/LdapAdConfiguration.php b/app/Services/LdapAdConfiguration.php index 7a30092b0e..25f0fba372 100644 --- a/app/Services/LdapAdConfiguration.php +++ b/app/Services/LdapAdConfiguration.php @@ -19,9 +19,9 @@ use Illuminate\Support\Collection; */ class LdapAdConfiguration { - const LDAP_PORT = 389; - const CONNECTION_TIMEOUT = 5; - const DEFAULT_LDAP_VERSION = 3; + const LDAP_PORT = 389; + const CONNECTION_TIMEOUT = 5; + const DEFAULT_LDAP_VERSION = 3; const LDAP_BOOLEAN_SETTINGS = [ 'ldap_enabled', 'ldap_server_cert_ignore', @@ -51,7 +51,8 @@ class LdapAdConfiguration * * @since 5.0.0 */ - public function init() { + public function init() + { // This try/catch is dumb, but is necessary to run initial migrations, since // this service provider is booted even during migrations. :( - snipe @@ -64,7 +65,6 @@ class LdapAdConfiguration \Log::debug($e); $this->ldapSettings = null; } - } /** @@ -92,7 +92,7 @@ class LdapAdConfiguration private function getSnipeItLdapSettings(): Collection { $ldapSettings = collect(); - if(Setting::first()) { // during early migration steps, there may be no settings table entry to start with + if (Setting::first()) { // during early migration steps, there may be no settings table entry to start with $ldapSettings = Setting::getLdapSettings() ->map(function ($item, $key) { // Trim the items @@ -105,7 +105,7 @@ class LdapAdConfiguration } // Decrypt the admin password - if ('ldap_pword' === $key && !empty($item)) { + if ('ldap_pword' === $key && ! empty($item)) { try { return decrypt($item); } catch (Exception $e) { @@ -120,6 +120,7 @@ class LdapAdConfiguration return $item; }); } + return $ldapSettings; } @@ -224,6 +225,7 @@ class LdapAdConfiguration if ($port && is_int($port)) { return $port; } + return self::LDAP_PORT; } @@ -242,6 +244,7 @@ class LdapAdConfiguration if ($scheme && 'ldaps' === strtolower($scheme)) { return true; } + return false; } @@ -261,11 +264,12 @@ class LdapAdConfiguration return trim($item); })->toArray(); } */ // <- this was the *original* intent of the PR for AdLdap2, but we've been moving away from having - // two separate fields - one for "ldap_host" and one for "ad_domain" - towards just using "ldap_host" - // ad_domain for us just means "append this domain to your usernames for login, if you click that checkbox" - // that's all, nothing more (I hope). + // two separate fields - one for "ldap_host" and one for "ad_domain" - towards just using "ldap_host" + // ad_domain for us just means "append this domain to your usernames for login, if you click that checkbox" + // that's all, nothing more (I hope). $url = $this->getLdapServerData('host'); + return $url ? [$url] : []; } diff --git a/app/Services/PredefinedKitCheckoutService.php b/app/Services/PredefinedKitCheckoutService.php index 8a1c624cbe..7ef28c9ee0 100644 --- a/app/Services/PredefinedKitCheckoutService.php +++ b/app/Services/PredefinedKitCheckoutService.php @@ -17,6 +17,7 @@ use Illuminate\Support\Facades\DB; class PredefinedKitCheckoutService { use AuthorizesRequests; + /** * @param Request $request, this function works with fields: checkout_at, expected_checkin, note * @param PredefinedKit $kit kit for checkout @@ -43,8 +44,8 @@ class PredefinedKitCheckoutService return ['errors' => $errors]; } - $checkout_at = date("Y-m-d H:i:s"); - if (($request->filled('checkout_at')) && ($request->get('checkout_at') != date("Y-m-d"))) { + $checkout_at = date('Y-m-d H:i:s'); + if (($request->filled('checkout_at')) && ($request->get('checkout_at') != date('Y-m-d'))) { $checkout_at = $request->get('checkout_at'); } @@ -59,7 +60,7 @@ class PredefinedKitCheckoutService $errors = $this->saveToDb($user, $admin, $checkout_at, $expected_checkin, $errors, $assets_to_add, $license_seats_to_add, $consumables_to_add, $accessories_to_add, $note); - return ['errors' => $errors, 'assets' => $assets_to_add, 'accessories' => $accessories_to_add, 'consumables' => $consumables_to_add ]; + return ['errors' => $errors, 'assets' => $assets_to_add, 'accessories' => $accessories_to_add, 'consumables' => $consumables_to_add]; } catch (ModelNotFoundException $e) { return ['errors' => [$e->getMessage()]]; } catch (CheckoutNotAllowed $e) { @@ -79,12 +80,10 @@ class PredefinedKitCheckoutService $assets = $model->assets; $quantity = $model->pivot->quantity; foreach ($assets as $asset) { - if ( $asset->availableForCheckout() - && !$asset->is($user) + && ! $asset->is($user) ) { - $this->authorize('checkout', $asset); $quantity -= 1; $assets_to_add[] = $asset; @@ -116,6 +115,7 @@ class PredefinedKitCheckoutService $seats_to_add[] = $license->freeSeats[$i]; } } + return $seats_to_add; } @@ -127,6 +127,7 @@ class PredefinedKitCheckoutService $errors[] = trans('admin/kits/general.none_consumables', ['consumable'=> $consumable->name, 'qty' => $consumable->pivot->quantity]); } } + return $consumables; } @@ -138,6 +139,7 @@ class PredefinedKitCheckoutService $errors[] = trans('admin/kits/general.none_accessory', ['accessory'=> $accessory->name, 'qty' => $accessory->pivot->quantity]); } } + return $accessories; } @@ -169,7 +171,7 @@ class PredefinedKitCheckoutService $consumable->users()->attach($consumable->id, [ 'consumable_id' => $consumable->id, 'user_id' => $admin->id, - 'assigned_to' => $user->id + 'assigned_to' => $user->id, ]); event(new CheckoutableCheckedOut($consumable, $user, $admin, $note)); } @@ -179,10 +181,11 @@ class PredefinedKitCheckoutService $accessory->users()->attach($accessory->id, [ 'accessory_id' => $accessory->id, 'user_id' => $admin->id, - 'assigned_to' => $user->id + 'assigned_to' => $user->id, ]); event(new CheckoutableCheckedOut($accessory, $user, $admin, $note)); } + return $errors; } ); diff --git a/app/Services/Saml.php b/app/Services/Saml.php index 9b0204bbce..9d73e05b49 100644 --- a/app/Services/Saml.php +++ b/app/Services/Saml.php @@ -2,15 +2,15 @@ namespace App\Services; -use OneLogin\Saml2\Auth as OneLogin_Saml2_Auth; -use OneLogin\Saml2\IdPMetadataParser as OneLogin_Saml2_IdPMetadataParser; -use OneLogin\Saml2\Settings as OneLogin_Saml2_Settings; -use OneLogin\Saml2\Utils as OneLogin_Saml2_Utils; use App\Models\Setting; use App\Models\User; use Exception; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Session; +use OneLogin\Saml2\Auth as OneLogin_Saml2_Auth; +use OneLogin\Saml2\IdPMetadataParser as OneLogin_Saml2_IdPMetadataParser; +use OneLogin\Saml2\Settings as OneLogin_Saml2_Settings; +use OneLogin\Saml2\Utils as OneLogin_Saml2_Utils; use Symfony\Component\HttpKernel\Exception\HttpException; /** @@ -112,15 +112,15 @@ class Saml /** * Initializes the SAML service and builds the OneLogin_Saml2_Auth instance. - * + * * @author Johnson Yi - * + * * @since 5.0.0 - * + * * @throws Exception * @throws Error */ - function __construct() + public function __construct() { $this->loadSettings(); @@ -139,10 +139,10 @@ class Saml /** * Builds settings from Snipe-IT for OneLogin_Saml2_Auth. - * + * * @author Johnson Yi * @author Michael Pietsch - * + * * @since 5.0.0 * * @return void @@ -163,19 +163,19 @@ class Saml data_set($settings, 'sp.singleLogoutService.url', route('saml.sls')); data_set($settings, 'sp.x509cert', $setting->saml_sp_x509cert); data_set($settings, 'sp.privateKey', $setting->saml_sp_privatekey); - if(!empty($setting->saml_sp_x509certNew)) { + if (! empty($setting->saml_sp_x509certNew)) { data_set($settings, 'sp.x509certNew', $setting->saml_sp_x509certNew); } else { - data_set($settings, 'sp.x509certNew', ""); + data_set($settings, 'sp.x509certNew', ''); } - if (!empty(data_get($settings, 'sp.privateKey'))) { + if (! empty(data_get($settings, 'sp.privateKey'))) { data_set($settings, 'security.logoutRequestSigned', true); data_set($settings, 'security.logoutResponseSigned', true); } $idpMetadata = $setting->saml_idp_metadata; - if (!empty($idpMetadata)) { + if (! empty($idpMetadata)) { $updatedAt = $setting->updated_at->timestamp; $metadataCache = Cache::get('saml_idp_metadata_cache'); try { @@ -203,16 +203,16 @@ class Saml } catch (Exception $e) { } } - + $custom_settings = preg_split('/\r\n|\r|\n/', $setting->saml_custom_settings); - if ($custom_settings){ - foreach($custom_settings as $custom_setting) { + if ($custom_settings) { + foreach ($custom_settings as $custom_setting) { $split = explode('=', $custom_setting, 2); if (count($split) == 2) { $boolValue = filter_var($split[1], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); - if (!is_null($boolValue)) { + if (! is_null($boolValue)) { $split[1] = $boolValue; } @@ -226,16 +226,17 @@ class Saml /** * Load SAML data from Session. - * + * * @author Johnson Yi - * + * * @since 5.0.0 - * + * * @return void */ - private function loadDataFromSession() { + private function loadDataFromSession() + { $samlData = collect(session(self::DATA_SESSION_KEY)); - $this->_authenticated = !$samlData->isEmpty(); + $this->_authenticated = ! $samlData->isEmpty(); $this->_nameid = $samlData->get('nameId'); $this->_nameidFormat = $samlData->get('nameIdFormat'); $this->_nameidNameQualifier = $samlData->get('nameIdNameQualifier'); @@ -248,9 +249,9 @@ class Saml /** * Save SAML data to Session. - * + * * @author Johnson Yi - * + * * @since 5.0.0 * * @param string $data @@ -264,9 +265,9 @@ class Saml /** * Check to see if SAML is enabled and has valid settings. - * + * * @author Johnson Yi - * + * * @since 5.0.0 * * @return bool @@ -278,9 +279,9 @@ class Saml /** * Clear SAML data from session. - * + * * @author Johnson Yi - * + * * @since 5.0.0 * * @return void @@ -293,36 +294,38 @@ class Saml /** * Find user from SAML data. - * + * * @author Johnson Yi - * + * * @since 5.0.0 * * @param string $data * * @return \App\Models\User */ - public function samlLogin($data) { + public function samlLogin($data) + { $setting = Setting::getSettings(); $this->saveDataToSession($data); $this->loadDataFromSession(); - + $username = $this->getUsername(); - + return User::where('username', '=', $username)->whereNull('deleted_at')->where('activated', '=', '1')->first(); } /** - * Returns the OneLogin_Saml2_Auth instance. - * + * Returns the OneLogin_Saml2_Auth instance. + * * @author Johnson Yi - * + * * @since 5.0.0 - * + * * @return OneLogin\Saml2\Auth */ - public function getAuth() { - if (!$this->isEnabled()) { + public function getAuth() + { + if (! $this->isEnabled()) { throw new HttpException(403, 'SAML not enabled.'); } @@ -331,15 +334,16 @@ class Saml /** * Get a setting. - * + * * @author Johnson Yi - * + * * @param string|array|int $key * @param mixed $default - * + * * @return void */ - public function getSetting($key, $default = null) { + public function getSetting($key, $default = null) + { return data_get($this->_settings, $key, $default); } @@ -359,27 +363,28 @@ class Saml public function getSPMetadata($alwaysPublishEncryptionCert = false, $validUntil = null, $cacheDuration = null) { try { - $settings = new OneLogin_Saml2_Settings($this->_settings , true); + $settings = new OneLogin_Saml2_Settings($this->_settings, true); $metadata = $settings->getSPMetadata($alwaysPublishEncryptionCert, $validUntil, $cacheDuration); - + return $metadata; } catch (Exception $e) { - return ""; + return ''; } } /** - * Extract data from SAML Response. - * + * Extract data from SAML Response. + * * @author Johnson Yi - * + * * @since 5.0.0 - * + * * @return array */ public function extractData() { $auth = $this->getAuth(); + return [ 'attributes' => $auth->getAttributes(), 'attributesWithFriendlyName' => $auth->getAttributesWithFriendlyName(), @@ -483,12 +488,12 @@ class Saml } /** - * Returns the correct username from SAML Response. - * + * Returns the correct username from SAML Response. + * * @author Johnson Yi - * + * * @since 5.0.0 - * + * * @return string */ public function getUsername() @@ -496,8 +501,7 @@ class Saml $setting = Setting::getSettings(); $username = $this->getNameId(); - if (!empty($setting->saml_attr_mapping_username)) - { + if (! empty($setting->saml_attr_mapping_username)) { $attributes = $this->getAttributes(); if (isset($attributes[$setting->saml_attr_mapping_username])) { diff --git a/composer.json b/composer.json index d700cbc8ab..e27a0cd1e9 100644 --- a/composer.json +++ b/composer.json @@ -11,54 +11,59 @@ "license": "AGPL-3.0-or-later", "type": "project", "require": { - "php": "^7.2.5", + "php": "^7.3", "ext-curl": "*", "ext-fileinfo": "*", "ext-json": "*", "ext-mbstring": "*", "ext-pdo": "*", "adldap2/adldap2": "^10.2", - "alek13/slack": "^1.12", + "alek13/slack": "^2.0", "bacon/bacon-qr-code": "^1.0", - "barryvdh/laravel-cors": "^0.11.3", - "barryvdh/laravel-debugbar": "^3.2", + "barryvdh/laravel-debugbar": "^3.6", "doctrine/cache": "^1.10", "doctrine/common": "^2.12", - "doctrine/dbal": "^2.10", + "doctrine/dbal": "^3.1", "doctrine/inflector": "^1.3", "doctrine/instantiator": "^1.3", "eduardokum/laravel-mail-auto-embed": "^1.0", "enshrined/svg-sanitize": "^0.13.3", "erusev/parsedown": "^1.7", + "facade/ignition": "^2.10", "fideloper/proxy": "^4.3", - "guzzlehttp/guzzle": "^6.5", + "fruitcake/laravel-cors": "^2.0", + "guzzlehttp/guzzle": "^7.0.1", "intervention/image": "^2.5", "javiereguiluz/easyslugger": "^1.0", - "laravel/framework": "^6.20", - "laravel/helpers": "^1.2", - "laravel/passport": "^9.3.2", - "laravel/slack-notification-channel": "^2.0", - "laravel/tinker": "^2.4", - "laravelcollective/html": "^6.0", - "league/csv": "^9.5", - "league/flysystem": "1.1.4", + "laravel/framework": "^8.46", + "laravel/helpers": "^1.4", + "laravel/passport": "^10.1", + "laravel/slack-notification-channel": "^2.3", + "laravel/tinker": "^2.6", + "laravel/ui": "^3.3", + "laravelcollective/html": "^6.2", + "lcobucci/clock": "1.2.0", + "lcobucci/jwt": "^3.4.5", + "league/csv": "^9.7", "league/flysystem-aws-s3-v3": "^1.0", - "league/flysystem-cached-adapter": "^1.0", + "league/flysystem-cached-adapter": "^1.1", + "livewire/livewire": "^2.4", + "mediconesystems/livewire-datatables": "^0.4.3", "neitanod/forceutf8": "^2.0", "nesbot/carbon": "^2.32", - "nunomaduro/collision": "^3.2", + "nunomaduro/collision": "^5.4", "onelogin/php-saml": "^3.4", "paragonie/constant_time_encoding": "^2.3", "patchwork/utf8": "^1.3", "phpdocumentor/reflection-docblock": "^5.1", "phpspec/prophecy": "^1.10", "pragmarx/google2fa-laravel": "^1.3", - "rollbar/rollbar-laravel": "^6.0", - "spatie/laravel-backup": "^6.9", + "rollbar/rollbar-laravel": "^7.0", + "spatie/laravel-backup": "^6.16", "tecnickcom/tc-lib-barcode": "^1.15", - "tightenco/ziggy": "^0.9.0", + "tightenco/ziggy": "v1.2.0", "unicodeveloper/laravel-password": "^1.0", - "watson/validating": "^4.0" + "watson/validating": "^6.1" }, "require-dev": { "codeception/codeception": "^4.1", @@ -67,7 +72,7 @@ "codeception/module-rest": "^1.2", "codeception/module-webdriver": "^1.0", "fzaninotto/faker": "^1.9", - "overtrue/phplint": "^2.2", + "overtrue/phplint": "^3.0", "phpunit/php-token-stream": "^3.1", "phpunit/phpunit": "^8.5", "squizlabs/php_codesniffer": "^3.5", @@ -89,7 +94,9 @@ "database" ], "psr-4": { - "App\\": "app/" + "App\\": "app/", + "Database\\Factories\\": "database/factories/", + "Database\\Seeders\\": "database/seeders/" } }, "autoload-dev": { @@ -111,9 +118,6 @@ "sort-packages": true, "optimize-autoloader": true, "discard-changes": true, - "process-timeout": 3000, - "platform": { - "php": "7.2.5" + "process-timeout": 3000 } - } -} +} \ No newline at end of file diff --git a/config/app.php b/config/app.php index 55184884dc..6c0cfd81f4 100755 --- a/config/app.php +++ b/config/app.php @@ -8,7 +8,6 @@ | be modified directly. */ - return [ /* @@ -164,8 +163,8 @@ return [ | Logging Detail |-------------------------------------------------------------------------- | - | By default, Laravel writes all log levels to storage. However, in your - | production environment, you may wish to configure the minimum severity that + | By default, Laravel writes all log levels to storage. However, in your + | production environment, you may wish to configure the minimum severity that | should be logged by editing your APP_LOG_LEVEL env config. | | Laravel will log all levels greater than or equal to the specified severity. @@ -176,9 +175,8 @@ return [ | "debug", "info", "notice", "warning", "error", "critical", "alert", "emergency" | */ - - 'log_level' => env('APP_LOG_LEVEL', 'error'), + 'log_level' => env('APP_LOG_LEVEL', 'error'), /* |-------------------------------------------------------------------------- @@ -195,7 +193,6 @@ return [ 'private_uploads' => storage_path().'/private_uploads', - /* |-------------------------------------------------------------------------- | ALLOW I-FRAMING @@ -209,7 +206,6 @@ return [ 'allow_iframing' => env('ALLOW_IFRAMING', false), - /* |-------------------------------------------------------------------------- | ENABLE HTTP Strict Transport Security (HSTS) @@ -254,9 +250,6 @@ return [ 'enable_csp' => env('ENABLE_CSP', false), - - - /* |-------------------------------------------------------------------------- | Demo Mode Lockdown @@ -269,7 +262,6 @@ return [ 'lock_passwords' => env('APP_LOCKED', false), - /* |-------------------------------------------------------------------------- | Minimum PHP version @@ -281,7 +273,6 @@ return [ 'min_php' => '7.2.5', - /* |-------------------------------------------------------------------------- | Autoloaded Service Providers @@ -346,7 +337,6 @@ return [ App\Providers\SettingsServiceProvider::class, App\Providers\ValidationServiceProvider::class, - /* * Custom service provider */ @@ -354,7 +344,6 @@ return [ App\Providers\LdapServiceProvider::class, App\Providers\SamlServiceProvider::class, - ], /* @@ -379,6 +368,7 @@ return [ 'Config' => Illuminate\Support\Facades\Config::class, 'Cookie' => Illuminate\Support\Facades\Cookie::class, 'Crypt' => Illuminate\Support\Facades\Crypt::class, + 'Date' => Illuminate\Support\Facades\Date::class, 'DB' => Illuminate\Support\Facades\DB::class, 'Eloquent' => Illuminate\Database\Eloquent\Model::class, 'Event' => Illuminate\Support\Facades\Event::class, @@ -408,7 +398,6 @@ return [ 'Image' => Intervention\Image\ImageServiceProvider::class, 'Carbon' => Carbon\Carbon::class, - ], ]; diff --git a/config/auth.php b/config/auth.php index 24ecf6d184..4fc626a964 100644 --- a/config/auth.php +++ b/config/auth.php @@ -1,14 +1,5 @@ App\Models\User::class, ], + // 'users' => [ + // 'driver' => 'database', + // 'table' => 'users', + // ], ], /* @@ -103,10 +98,11 @@ return [ 'email' => 'auth.emails.password', 'table' => 'password_resets', 'expire' => env('RESET_PASSWORD_LINK_EXPIRES', 900), - 'throttle' => [ + 'throttle' => 60, 'max_attempts' => env('LOGIN_MAX_ATTEMPTS', 5), - 'lockout_duration' => env('LOGIN_LOCKOUT_DURATION', 60) - ], + + 'lockout_duration' => env('LOGIN_LOCKOUT_DURATION', 60), + ], ], @@ -123,5 +119,4 @@ return [ 'password_timeout' => 10800, - ]; diff --git a/config/backup.php b/config/backup.php index f63516c077..479b1db6aa 100644 --- a/config/backup.php +++ b/config/backup.php @@ -8,7 +8,6 @@ | be modified directly. */ - // This is janky, but necessary to figure out whether to include the .env in the backup $included_dirs = [ base_path('public/uploads'), @@ -18,7 +17,7 @@ $included_dirs = [ ]; -if (env('BACKUP_ENV')=='true') { +if (env('BACKUP_ENV') == 'true') { $included_dirs[] = base_path('.env'); } @@ -212,4 +211,4 @@ return [ ], ], -]; \ No newline at end of file +]; diff --git a/config/broadcasting.php b/config/broadcasting.php index e3f0576864..2d529820cc 100644 --- a/config/broadcasting.php +++ b/config/broadcasting.php @@ -1,15 +1,5 @@ env('BROADCAST_DRIVER', 'pusher'), + 'default' => env('BROADCAST_DRIVER', 'null'), /* |-------------------------------------------------------------------------- @@ -40,14 +32,20 @@ return [ 'pusher' => [ 'driver' => 'pusher', - 'key' => env('PUSHER_KEY'), - 'secret' => env('PUSHER_SECRET'), + 'key' => env('PUSHER_APP_KEY'), + 'secret' => env('PUSHER_APP_SECRET'), 'app_id' => env('PUSHER_APP_ID'), 'options' => [ - // + 'cluster' => env('PUSHER_APP_CLUSTER'), + 'useTLS' => true, ], ], + 'ably' => [ + 'driver' => 'ably', + 'key' => env('ABLY_KEY'), + ], + 'redis' => [ 'driver' => 'redis', 'connection' => 'default', @@ -57,6 +55,10 @@ return [ 'driver' => 'log', ], + 'null' => [ + 'driver' => 'null', + ], + ], ]; diff --git a/config/cache.php b/config/cache.php index c1af7b98ce..de0e53401f 100644 --- a/config/cache.php +++ b/config/cache.php @@ -1,14 +1,6 @@ [ @@ -44,12 +39,14 @@ return [ 'array' => [ 'driver' => 'array', + 'serialize' => false, ], 'database' => [ 'driver' => 'database', - 'table' => 'cache', + 'table' => 'cache', 'connection' => null, + 'lock_connection' => null, ], 'file' => [ @@ -58,7 +55,15 @@ return [ ], 'memcached' => [ - 'driver' => 'memcached', + 'driver' => 'memcached', + 'persistent_id' => env('MEMCACHED_PERSISTENT_ID'), + 'sasl' => [ + env('MEMCACHED_USERNAME'), + env('MEMCACHED_PASSWORD'), + ], + 'options' => [ + // Memcached::OPT_CONNECT_TIMEOUT => 2000, + ], 'servers' => [ [ 'host' => env('MEMCACHED_HOST', '127.0.0.1'), @@ -71,6 +76,16 @@ return [ 'redis' => [ 'driver' => 'redis', 'connection' => 'default', + 'lock_connection' => 'default', + ], + + 'dynamodb' => [ + 'driver' => 'dynamodb', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'), + 'endpoint' => env('DYNAMODB_ENDPOINT'), ], ], @@ -86,6 +101,6 @@ return [ | */ - 'prefix' => env('CACHE_PREFIX', 'snipeit'), + 'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache'), ]; diff --git a/config/compile.php b/config/compile.php index f5fe56d0d5..086b36545a 100644 --- a/config/compile.php +++ b/config/compile.php @@ -8,8 +8,6 @@ | be modified directly. */ - - return [ /* diff --git a/config/cors.php b/config/cors.php index 0aa4b8cef4..f09ab4979f 100644 --- a/config/cors.php +++ b/config/cors.php @@ -1,48 +1,44 @@ false, - 'allowedOrigins' => $allowed_origins, - 'allowedOriginsPatterns' => [], + + 'allowedOrigins' => ['*'], + 'allowedHeaders' => ['*'], + 'allowedMethods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], - 'exposedHeaders' => [], + 'maxAge' => 0, + /* + |-------------------------------------------------------------------------- + | Cross-Origin Resource Sharing (CORS) Configuration + |-------------------------------------------------------------------------- + | + | Here you may configure your settings for cross-origin resource sharing + | or "CORS". This determines what cross-origin operations may execute + | in web browsers. You are free to adjust these settings as needed. + | + | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS + | + */ + + 'paths' => ['api/*', 'sanctum/csrf-cookie'], + + 'allowed_methods' => ['*'], + + 'allowed_origins' => ['*'], + + 'allowed_origins_patterns' => [], + + 'allowed_headers' => ['*'], + + 'exposed_headers' => [], + + 'max_age' => 0, + + 'supports_credentials' => false, + ]; diff --git a/config/database.php b/config/database.php index f32810326a..9d94454db2 100755 --- a/config/database.php +++ b/config/database.php @@ -8,7 +8,6 @@ | be modified directly. */ - return [ /* @@ -79,7 +78,7 @@ return [ 'prefix' => env('DB_PREFIX', null), 'strict' => false, 'engine' => 'InnoDB', - 'unix_socket' => env('DB_SOCKET',''), + 'unix_socket' => env('DB_SOCKET', ''), 'dump' => [ 'dump_binary_path' => env('DB_DUMP_PATH', '/usr/local/bin'), // only the path, so without 'mysqldump' 'use_single_transaction' => false, @@ -96,8 +95,8 @@ return [ PDO::MYSQL_ATTR_SSL_KEY => env('DB_SSL_KEY_PATH'), // /path/to/key.pem PDO::MYSQL_ATTR_SSL_CERT => env('DB_SSL_CERT_PATH'), // /path/to/cert.pem PDO::MYSQL_ATTR_SSL_CA => env('DB_SSL_CA_PATH'), // /path/to/ca.pem - PDO::MYSQL_ATTR_SSL_CIPHER => env('DB_SSL_CIPHER') - ]) : [] + PDO::MYSQL_ATTR_SSL_CIPHER => env('DB_SSL_CIPHER'), + ]) : [], ], 'pgsql' => [ diff --git a/config/debugbar.php b/config/debugbar.php index aeb5005615..ca7848678c 100644 --- a/config/debugbar.php +++ b/config/debugbar.php @@ -1,6 +1,6 @@ array( + 'storage' => [ 'enabled' => true, 'driver' => 'file', // redis, file, pdo - 'path' => storage_path() . '/debugbar', // For file driver + 'path' => storage_path().'/debugbar', // For file driver 'connection' => null, // Leave null for default connection (Redis/PDO) - ), + ], /* |-------------------------------------------------------------------------- @@ -81,7 +81,7 @@ return array( | */ - 'collectors' => array( + 'collectors' => [ 'phpinfo' => true, // Php version 'messages' => true, // Messages 'time' => true, // Time Datalogger @@ -102,7 +102,7 @@ return array( 'auth' => true, // Display Laravel authentication status 'gate' => true, // Display Laravel Gate checks 'session' => true, // Display session data - ), + ], /* |-------------------------------------------------------------------------- @@ -113,33 +113,33 @@ return array( | */ - 'options' => array( - 'auth' => array( + 'options' => [ + 'auth' => [ 'show_name' => false, // Also show the users name/email in the debugbar - ), - 'db' => array( + ], + 'db' => [ 'with_params' => true, // Render SQL with the parameters substituted 'timeline' => true, // Add the queries to the timeline 'backtrace' => true, // EXPERIMENTAL: Use a backtrace to find the origin of the query in your files. - 'explain' => array( // EXPERIMENTAL: Show EXPLAIN output on queries + 'explain' => [ // EXPERIMENTAL: Show EXPLAIN output on queries 'enabled' => false, - 'types' => array('SELECT'), // array('SELECT', 'INSERT', 'UPDATE', 'DELETE'); for MySQL 5.6.3+ - ), + 'types' => ['SELECT'], // array('SELECT', 'INSERT', 'UPDATE', 'DELETE'); for MySQL 5.6.3+ + ], 'hints' => true, // Show hints for common mistakes - ), - 'mail' => array( - 'full_log' => false - ), - 'views' => array( + ], + 'mail' => [ + 'full_log' => false, + ], + 'views' => [ 'data' => false, //Note: Can slow down the application, because the data can be quite large.. - ), - 'route' => array( - 'label' => true // show complete route on bar - ), - 'logs' => array( - 'file' => null - ), - ), + ], + 'route' => [ + 'label' => true, // show complete route on bar + ], + 'logs' => [ + 'file' => null, + ], + ], /* |-------------------------------------------------------------------------- @@ -166,4 +166,4 @@ return array( */ 'route_prefix' => '_debugbar', -); +]; diff --git a/config/filesystems.php b/config/filesystems.php index b4bf6303e4..50b2675589 100644 --- a/config/filesystems.php +++ b/config/filesystems.php @@ -105,4 +105,4 @@ $config = [ // (by default, the PUBLIC_FILESYSTEM DISK is 'local_public', in the public/uploads directory) $config['disks']['public'] = $config['disks'][env('PUBLIC_FILESYSTEM_DISK','local_public')]; -return $config; +return $config; \ No newline at end of file diff --git a/config/image.php b/config/image.php index 1b9dbaaf06..9458b9c1cc 100644 --- a/config/image.php +++ b/config/image.php @@ -8,8 +8,7 @@ | be modified directly. */ - -return array( +return [ /* |-------------------------------------------------------------------------- @@ -26,4 +25,4 @@ return array( 'driver' => env('IMAGE_LIB', 'gd'), -); +]; diff --git a/config/logging.php b/config/logging.php index 1f6538e1b8..1aa06aa30f 100644 --- a/config/logging.php +++ b/config/logging.php @@ -1,8 +1,10 @@ env('LOG_CHANNEL', 'stack'), /* @@ -35,68 +38,68 @@ $config = [ 'stack' => [ 'driver' => 'stack', 'channels' => ['single'], + 'ignore_exceptions' => false, ], 'single' => [ 'driver' => 'single', 'path' => storage_path('logs/laravel.log'), - 'level' => env('APP_LOG_LEVEL', 'error'), + 'level' => env('LOG_LEVEL', 'debug'), ], - 'daily' => [ 'driver' => 'daily', 'path' => storage_path('logs/laravel.log'), - 'level' => 'debug', - 'days' => env('APP_LOG_MAX_FILES', 5), + 'level' => env('LOG_LEVEL', 'debug'), + 'days' => 14, ], - 'rollbar' => [ - 'driver' => 'monolog', - 'handler' => \Rollbar\Laravel\MonologHandler::class, - 'access_token' => env('ROLLBAR_TOKEN'), - 'level' => env('APP_LOG_LEVEL', 'debug'), - ], - - 'slack' => [ 'driver' => 'slack', 'url' => env('LOG_SLACK_WEBHOOK_URL'), 'username' => 'Laravel Log', 'emoji' => ':boom:', - 'level' => 'critical', + 'level' => env('LOG_LEVEL', 'critical'), + ], + + 'papertrail' => [ + 'driver' => 'monolog', + 'level' => env('LOG_LEVEL', 'debug'), + 'handler' => SyslogUdpHandler::class, + 'handler_with' => [ + 'host' => env('PAPERTRAIL_URL'), + 'port' => env('PAPERTRAIL_PORT'), + ], ], 'stderr' => [ 'driver' => 'monolog', + 'level' => env('LOG_LEVEL', 'debug'), 'handler' => StreamHandler::class, + 'formatter' => env('LOG_STDERR_FORMATTER'), 'with' => [ 'stream' => 'php://stderr', ], ], - 'stdout' => [ - 'driver' => 'monolog', - 'handler' => StreamHandler::class, - 'with' => [ 'stream' => 'php://stdout', ], - ], - 'syslog' => [ 'driver' => 'syslog', - 'level' => env('APP_LOG_LEVEL', 'error'), + 'level' => env('LOG_LEVEL', 'debug'), ], 'errorlog' => [ 'driver' => 'errorlog', - 'level' => env('APP_LOG_LEVEL', 'error'), + 'level' => env('LOG_LEVEL', 'debug'), + ], + + 'null' => [ + 'driver' => 'monolog', + 'handler' => NullHandler::class, + ], + + 'emergency' => [ + 'path' => storage_path('logs/laravel.log'), ], ], ]; - -if ((env('APP_ENV')=='production') && env('ROLLBAR_TOKEN')) { - array_push($config['channels']['stack']['channels'], 'rollbar'); -} - - -return $config; diff --git a/config/mail.php b/config/mail.php index 9c2aac439f..d47d182ed3 100755 --- a/config/mail.php +++ b/config/mail.php @@ -8,7 +8,6 @@ | be modified directly. */ - return [ /* @@ -70,13 +69,11 @@ return [ | */ - 'from' => - [ + 'from' => [ 'address' => env('MAIL_FROM_ADDR', null), - 'name' => env('MAIL_FROM_NAME', null) + 'name' => env('MAIL_FROM_NAME', null), ], - /* |-------------------------------------------------------------------------- | Global "Reply-To" Address @@ -84,13 +81,13 @@ return [ | | You may wish for all e-mails sent by your application to have a different "Reply-to" | address than the "From" address. If this is left blank, the application will use - | your MAIL_FROM information. + | your MAIL_FROM information. | */ 'reply_to' => [ - 'address' => env('MAIL_REPLYTO_ADDR',null), - 'name' => env('MAIL_REPLYTO_NAME', null) + 'address' => env('MAIL_REPLYTO_ADDR', null), + 'name' => env('MAIL_REPLYTO_NAME', null), ], /* @@ -145,7 +142,6 @@ return [ 'sendmail' => '/usr/sbin/sendmail -bs', - 'markdown' => [ 'theme' => 'default', 'paths' => [ diff --git a/config/passport.php b/config/passport.php index b8342a6b59..d410cfe20e 100644 --- a/config/passport.php +++ b/config/passport.php @@ -1,4 +1,5 @@ env('PASSPORT_PRIVATE_KEY'), 'public_key' => env('PASSPORT_PUBLIC_KEY'), 'expiration_years' => env('API_TOKEN_EXPIRATION_YEARS', 20), -]; \ No newline at end of file +]; diff --git a/config/permissions.php b/config/permissions.php index 0176dc13ba..57aa4a3232 100644 --- a/config/permissions.php +++ b/config/permissions.php @@ -6,639 +6,625 @@ |-------------------------------------------------------------------------- */ +return [ -return array( - - 'Global' => array( - array( + 'Global' => [ + [ 'permission' => 'superuser', 'label' => 'Super User', 'note' => 'Determines whether the user has full access to all aspects of the admin. This setting overrides any more specific permissions throughout the system. ', 'display' => true, - ), - ), + ], + ], - 'Admin' => array( - array( + 'Admin' => [ + [ 'permission' => 'admin', 'label' => '', 'note' => 'Determines whether the user has access to most aspects of the admin. ', 'display' => true, - ) - ), + ], + ], - 'CSV Import' => array( - array( + 'CSV Import' => [ + [ 'permission' => 'import', 'label' => '', 'note' => 'This will allow users to import even if access to users, assets, etc is denied elsewhere.', 'display' => true, - ) - ), + ], + ], - 'Reports' => array( - array( + 'Reports' => [ + [ 'permission' => 'reports.view', 'label' => 'View', 'note' => 'Determines whether the user has the ability to view reports.', 'display' => true, - ), - ), + ], + ], - 'Assets' => array( - array( + 'Assets' => [ + [ 'permission' => 'assets.view', 'label' => 'View ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'assets.create', 'label' => 'Create ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'assets.edit', 'label' => 'Edit ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'assets.delete', 'label' => 'Delete ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'assets.checkout', 'label' => 'Checkout ', 'note' => '', 'display' => false, - ), + ], - array( + [ 'permission' => 'assets.checkin', 'label' => 'Checkin ', 'note' => '', 'display' => true, - ), + ], - array( + [ 'permission' => 'assets.checkout', 'label' => 'Checkout ', 'note' => '', 'display' => true, - ), + ], - array( + [ 'permission' => 'assets.audit', 'label' => 'Audit ', 'note' => 'Allows the user to mark an asset as physically inventoried.', 'display' => true, - ), + ], - - array( + [ 'permission' => 'assets.view.requestable', 'label' => 'View Requestable Assets', 'note' => '', 'display' => true, - ), + ], - ), + ], - 'Accessories' => array( - array( + 'Accessories' => [ + [ 'permission' => 'accessories.view', 'label' => 'View ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'accessories.create', 'label' => 'Create ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'accessories.edit', 'label' => 'Edit ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'accessories.delete', 'label' => 'Delete ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'accessories.checkout', 'label' => 'Checkout ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'accessories.checkin', 'label' => 'Checkin ', 'note' => '', 'display' => true, - ), - ), + ], + ], - 'Consumables' => array( - array( + 'Consumables' => [ + [ 'permission' => 'consumables.view', 'label' => 'View', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'consumables.create', 'label' => 'Create ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'consumables.edit', 'label' => 'Edit ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'consumables.delete', 'label' => 'Delete ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'consumables.checkout', 'label' => 'Checkout ', 'note' => '', 'display' => true, - ), - ), + ], + ], - - 'Licenses' => array( - array( + 'Licenses' => [ + [ 'permission' => 'licenses.view', 'label' => 'View', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'licenses.create', 'label' => 'Create ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'licenses.edit', 'label' => 'Edit ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'licenses.delete', 'label' => 'Delete ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'licenses.checkout', 'label' => 'Checkout ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'licenses.keys', 'label' => 'View License Keys', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'licenses.files', 'label' => 'View and Modify License Files', 'note' => '', 'display' => true, - ), - ), + ], + ], - - 'Components' => array( - array( + 'Components' => [ + [ 'permission' => 'components.view', 'label' => 'View', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'components.create', 'label' => 'Create ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'components.edit', 'label' => 'Edit ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'components.delete', 'label' => 'Delete ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'components.checkout', 'label' => 'Checkout ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'components.checkin', 'label' => 'Checkin ', 'note' => '', 'display' => true, - ), + ], - ), + ], - 'Kits' => array( - array( + 'Kits' => [ + [ 'permission' => 'kits.view', 'label' => 'View ', 'note' => 'These are predefined kits that can be used to quickly checkout assets, licenses, etc.', 'display' => true, - ), - array( + ], + [ 'permission' => 'kits.create', 'label' => 'Create ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'kits.edit', 'label' => 'Edit ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'kits.delete', 'label' => 'Delete ', 'note' => '', 'display' => true, - ), + ], - array( + [ 'permission' => 'kits.checkout', 'label' => 'Checkout ', 'note' => '', 'display' => true, - ), - ), + ], + ], - - 'Users' => array( - array( + 'Users' => [ + [ 'permission' => 'users.view', 'label' => 'View ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'users.create', 'label' => 'Create Users', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'users.edit', 'label' => 'Edit Users', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'users.delete', 'label' => 'Delete Users', 'note' => '', 'display' => true, - ), + ], - ), + ], - - 'Models' => array( - array( + 'Models' => [ + [ 'permission' => 'models.view', 'label' => 'View ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'models.create', 'label' => 'Create ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'models.edit', 'label' => 'Edit ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'models.delete', 'label' => 'Delete ', 'note' => '', 'display' => true, - ), + ], - ), + ], - 'Categories' => array( - array( + 'Categories' => [ + [ 'permission' => 'categories.view', 'label' => 'View ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'categories.create', 'label' => 'Create ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'categories.edit', 'label' => 'Edit ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'categories.delete', 'label' => 'Delete ', 'note' => '', 'display' => true, - ), - ), + ], + ], - 'Departments' => array( - array( + 'Departments' => [ + [ 'permission' => 'departments.view', 'label' => 'View ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'departments.create', 'label' => 'Create ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'departments.edit', 'label' => 'Edit ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'departments.delete', 'label' => 'Delete ', 'note' => '', 'display' => true, - ), - ), + ], + ], - 'Status Labels' => array( - array( + 'Status Labels' => [ + [ 'permission' => 'statuslabels.view', 'label' => 'View ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'statuslabels.create', 'label' => 'Create ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'statuslabels.edit', 'label' => 'Edit ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'statuslabels.delete', 'label' => 'Delete ', 'note' => '', 'display' => true, - ), - ), + ], + ], - 'Custom Fields' => array( - array( + 'Custom Fields' => [ + [ 'permission' => 'customfields.view', 'label' => 'View', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'customfields.create', 'label' => 'Create', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'customfields.edit', 'label' => 'Edit', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'customfields.delete', 'label' => 'Delete', 'note' => '', 'display' => true, - ), - ), + ], + ], - 'Suppliers' => array( - array( + 'Suppliers' => [ + [ 'permission' => 'suppliers.view', 'label' => 'View ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'suppliers.create', 'label' => 'Create ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'suppliers.edit', 'label' => 'Edit ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'suppliers.delete', 'label' => 'Delete ', 'note' => '', 'display' => true, - ), - ), + ], + ], - - 'Manufacturers' => array( - array( + 'Manufacturers' => [ + [ 'permission' => 'manufacturers.view', 'label' => 'View ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'manufacturers.create', 'label' => 'Create ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'manufacturers.edit', 'label' => 'Edit ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'manufacturers.delete', 'label' => 'Delete ', 'note' => '', 'display' => true, - ), - ), + ], + ], - 'Depreciations' => array( - array( + 'Depreciations' => [ + [ 'permission' => 'depreciations.view', 'label' => 'View ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'depreciations.create', 'label' => 'Create ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'depreciations.edit', 'label' => 'Edit ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'depreciations.delete', 'label' => 'Delete ', 'note' => '', 'display' => true, - ), - ), + ], + ], - 'Locations' => array( - array( + 'Locations' => [ + [ 'permission' => 'locations.view', 'label' => 'View ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'locations.create', 'label' => 'Create ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'locations.edit', 'label' => 'Edit ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'locations.delete', 'label' => 'Delete ', 'note' => '', 'display' => true, - ), - ), + ], + ], - 'Companies' => array( - array( + 'Companies' => [ + [ 'permission' => 'companies.view', 'label' => 'View ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'companies.create', 'label' => 'Create ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'companies.edit', 'label' => 'Edit ', 'note' => '', 'display' => true, - ), - array( + ], + [ 'permission' => 'companies.delete', 'label' => 'Delete ', 'note' => '', 'display' => true, - ), - ), + ], + ], - - - - 'Self' => array( - array( + 'Self' => [ + [ 'permission' => 'self.two_factor', 'label' => 'Two-Factor Authentication', 'note' => 'The user may disable/enable two-factor authentication themselves if two-factor is enabled and set to selective.', 'display' => true, - ), + ], - array( + [ 'permission' => 'self.api', 'label' => 'Create API Keys', 'note' => 'The user create personal API keys to utilize the REST API.', 'display' => true, - ), + ], - array( + [ 'permission' => 'self.edit_location', 'label' => 'Profile Edit Location', 'note' => 'The user may update their own location in their profile. Note that this is not affected by any additional Users permissions you grant to this user or group.', 'display' => true, - ), + ], - array( + [ 'permission' => 'self.checkout_assets', 'label' => 'Self-Checkout', 'note' => 'This user may check out assets that are marked for self-checkout.', 'display' => true, - ), + ], - ), + ], - - - - -); +]; diff --git a/config/queue.php b/config/queue.php index 6c2b7d2e17..25ea5a8193 100644 --- a/config/queue.php +++ b/config/queue.php @@ -4,19 +4,16 @@ return [ /* |-------------------------------------------------------------------------- - | Default Queue Driver + | Default Queue Connection Name |-------------------------------------------------------------------------- | - | The Laravel queue API supports a variety of back-ends via an unified + | Laravel's queue API supports an assortment of back-ends via a single | API, giving you convenient access to each back-end using the same - | syntax for each one. Here you may set the default queue driver. - | - | Supported: "null", "sync", "database", "beanstalkd", - | "sqs", "redis" + | syntax for every one. Here you may define a default connection. | */ - 'default' => env('QUEUE_DRIVER', 'sync'), + 'default' => env('QUEUE_CONNECTION', 'sync'), /* |-------------------------------------------------------------------------- @@ -27,6 +24,8 @@ return [ | is used by your application. A default configuration has been added | for each back-end shipped with Laravel. You are free to add more. | + | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null" + | */ 'connections' => [ @@ -37,32 +36,39 @@ return [ 'database' => [ 'driver' => 'database', - 'table' => 'jobs', - 'queue' => 'default', - 'expire' => 60, + 'table' => 'jobs', + 'queue' => 'default', + 'retry_after' => 90, + 'after_commit' => false, ], 'beanstalkd' => [ 'driver' => 'beanstalkd', - 'host' => 'localhost', - 'queue' => 'default', - 'ttr' => 60, + 'host' => 'localhost', + 'queue' => 'default', + 'retry_after' => 90, + 'block_for' => 0, + 'after_commit' => false, ], 'sqs' => [ 'driver' => 'sqs', - 'key' => 'your-public-key', - 'secret' => 'your-secret-key', - 'prefix' => 'https://sqs.us-east-1.amazonaws.com/your-account-id', - 'queue' => 'your-queue-name', - 'region' => 'us-east-1', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'), + 'queue' => env('SQS_QUEUE', 'default'), + 'suffix' => env('SQS_SUFFIX'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'after_commit' => false, ], 'redis' => [ - 'driver' => 'redis', + 'driver' => 'redis', 'connection' => 'default', - 'queue' => 'default', - 'expire' => 60, + 'queue' => env('REDIS_QUEUE', 'default'), + 'retry_after' => 90, + 'block_for' => null, + 'after_commit' => false, ], ], @@ -79,8 +85,9 @@ return [ */ 'failed' => [ + 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'), 'database' => env('DB_CONNECTION', 'mysql'), - 'table' => 'failed_jobs', + 'table' => 'failed_jobs', ], ]; diff --git a/config/services.php b/config/services.php index c5eb915b55..dd594e67cb 100644 --- a/config/services.php +++ b/config/services.php @@ -8,7 +8,6 @@ | be modified directly. */ - return [ /* @@ -49,10 +48,9 @@ return [ 'app_key' => env('STUNNING_APP_KEY'), 'stripe_id' => env('STUNNING_STRIPE_ID'), ], - + 'google' => [ - 'maps_api_key' => env('GOOGLE_MAPS_API') + 'maps_api_key' => env('GOOGLE_MAPS_API'), ], - ]; diff --git a/config/session.php b/config/session.php index d6710975a6..d867229956 100644 --- a/config/session.php +++ b/config/session.php @@ -8,8 +8,6 @@ | be modified directly. */ - - return [ /* @@ -67,7 +65,7 @@ return [ | */ - 'files' => (env('SESSION_PATH')!='' ? env('SESSION_PATH') : storage_path('framework/sessions')), + 'files' => (env('SESSION_PATH') != '' ? env('SESSION_PATH') : storage_path('framework/sessions')), /* |-------------------------------------------------------------------------- @@ -158,6 +156,6 @@ return [ | */ - 'secure' => env('SECURE_COOKIES', false) + 'secure' => env('SECURE_COOKIES', false), ]; diff --git a/config/trustedproxy.php b/config/trustedproxy.php index 04e90ac2d2..a3d80418ba 100644 --- a/config/trustedproxy.php +++ b/config/trustedproxy.php @@ -8,7 +8,6 @@ | be modified directly. */ - return [ /* @@ -40,13 +39,13 @@ return [ * To trust one or more specific proxies that connect * directly to your server, use an array of IP addresses: */ - # 'proxies' => ['192.168.1.1'], + // 'proxies' => ['192.168.1.1'], /* * Or, to trust all proxies that connect * directly to your server, use a "*" */ - # 'proxies' => '*', + // 'proxies' => '*', /* * Which headers to use to detect proxy related data (For, Host, Proto, Port) @@ -60,5 +59,4 @@ return [ */ 'headers' => Illuminate\Http\Request::HEADER_X_FORWARDED_ALL, - ]; diff --git a/config/version.php b/config/version.php index 068c95074f..008ac13252 100644 --- a/config/version.php +++ b/config/version.php @@ -1,10 +1,10 @@ 'v5.2.0', - 'full_app_version' => 'v5.2.0 - build 6339-g14a8baeca', - 'build_version' => '6339', + 'app_version' => 'v6-pre-alpha', + 'full_app_version' => 'v6-pre-alpha - build 6109-gace7abc1a', + 'build_version' => '6109', 'prerelease_version' => '', - 'hash_version' => 'g14a8baeca', - 'full_hash' => 'v5.2.0-188-g14a8baeca', - 'branch' => 'develop', + 'hash_version' => 'gace7abc1a', + 'full_hash' => 'v6-pre-alpha-71-gace7abc1a', + 'branch' => 'develop-v6-integration', ); \ No newline at end of file diff --git a/database/factories/AccessoryFactory.php b/database/factories/AccessoryFactory.php index 9e69004862..84edcb705c 100644 --- a/database/factories/AccessoryFactory.php +++ b/database/factories/AccessoryFactory.php @@ -1,5 +1,9 @@ define(App\Models\Accessory::class, function (Faker\Generator $faker) { - return [ - 'user_id' => 1, - 'model_number' => $faker->numberBetween(1000000, 50000000), - 'location_id' => rand(1,5), - ]; -}); +class AccessoryFactory extends Factory +{ + /** + * The name of the factory's corresponding model. + * + * @var string + */ + protected $model = \App\Models\Accessory::class; -$factory->state(App\Models\Accessory::class, 'apple-bt-keyboard', function ($faker) { + /** + * Define the model's default state. + * + * @return array + */ + public function definition() + { + return [ + 'user_id' => 1, + 'model_number' => $this->faker->numberBetween(1000000, 50000000), + 'location_id' => rand(1, 5), + ]; + } - return [ - 'name' => 'Bluetooth Keyboard', - 'image' => 'bluetooth.jpg', - 'category_id' => 8, - 'manufacturer_id' => 1, - 'qty' => 10, - 'min_amt' => 2, - 'supplier_id' => rand(1,5) - ]; + public function appleBtKeyboard() + { + return $this->state(function () { + return [ + 'name' => 'Bluetooth Keyboard', + 'image' => 'bluetooth.jpg', + 'category_id' => 8, + 'manufacturer_id' => 1, + 'qty' => 10, + 'min_amt' => 2, + 'supplier_id' => rand(1, 5), + ]; + }); + } -}); + public function appleUsbKeyboard() + { + return $this->state(function () { + return [ + 'name' => 'USB Keyboard', + 'image' => 'usb-keyboard.jpg', + 'category_id' => 8, + 'manufacturer_id' => 1, + 'qty' => 15, + 'min_amt' => 2, + 'supplier_id' => rand(1, 5), + ]; + }); + } -$factory->state(App\Models\Accessory::class, 'apple-usb-keyboard', function ($faker) { - - return [ - 'name' => 'USB Keyboard', - 'image' => 'usb-keyboard.jpg', - 'category_id' => 8, - 'manufacturer_id' => 1, - 'qty' => 15, - 'min_amt' => 2, - 'supplier_id' => rand(1,5) - ]; - -}); - -$factory->state(App\Models\Accessory::class, 'apple-mouse', function ($faker) { - - return [ - 'name' => 'Magic Mouse', - 'image' => 'magic-mouse.jpg', - 'category_id' => 9, - 'manufacturer_id' => 1, - 'qty' => 13, - 'min_amt' => 2, - 'supplier_id' => rand(1,5) - ]; - -}); - -$factory->state(App\Models\Accessory::class, 'microsoft-mouse', function ($faker) { - - return [ - 'name' => 'Sculpt Comfort Mouse', - 'image' => 'comfort-mouse.jpg', - 'category_id' => 9, - 'manufacturer_id' => 2, - 'qty' => 13, - 'min_amt' => 2 - ]; - -}); + public function appleMouse() + { + return $this->state(function () { + return [ + 'name' => 'Magic Mouse', + 'image' => 'magic-mouse.jpg', + 'category_id' => 9, + 'manufacturer_id' => 1, + 'qty' => 13, + 'min_amt' => 2, + 'supplier_id' => rand(1, 5), + ]; + }); + } + public function microsoftMouse() + { + return $this->state(function () { + return [ + 'name' => 'Sculpt Comfort Mouse', + 'image' => 'comfort-mouse.jpg', + 'category_id' => 9, + 'manufacturer_id' => 2, + 'qty' => 13, + 'min_amt' => 2, + ]; + }); + } +} diff --git a/database/factories/ActionLogFactory.php b/database/factories/ActionLogFactory.php deleted file mode 100644 index d1a8ece7dd..0000000000 --- a/database/factories/ActionLogFactory.php +++ /dev/null @@ -1,151 +0,0 @@ -define(Actionlog::class, function (Faker\Generator $faker) { - return [ - 'note' => 'Sample checkout from DB seeder!', - ]; -}); - - -$factory->defineAs(App\Models\Actionlog::class, 'asset-upload', function ($faker) { - $asset = factory(App\Models\Asset::class)->create(); - return [ - 'item_type' => get_class($asset), - 'item_id' => 1, - 'user_id' => 1, - 'filename' => $faker->word, - 'action_type' => 'uploaded' - ]; -}); - - -$factory->defineAs(Actionlog::class, 'asset-checkout-user', function (Faker\Generator $faker) { - $target = User::inRandomOrder()->first(); - $item = Asset::inRandomOrder()->RTD()->first(); - $user_id = rand(1,2); // keep it simple - make it one of the two superadmins - $asset = App\Models\Asset::where('id', $item->id) - ->update( - [ - 'assigned_to' => $target->id, - 'assigned_type' => App\Models\User::class, - 'assigned_to' => $target->location_id, - ] - ); - - return [ - 'created_at' => $faker->dateTimeBetween('-1 years','now', date_default_timezone_get()), - 'user_id' => $user_id, - 'action_type' => 'checkout', - 'item_id' => $item->id, - 'item_type' => App\Models\Asset::class, - 'target_id' => $target->id, - 'target_type' => get_class($target), - - - ]; -}); - -$factory->defineAs(Actionlog::class, 'asset-checkout-location', function (Faker\Generator $faker) { - $target = Location::inRandomOrder()->first(); - $item = Asset::inRandomOrder()->RTD()->first(); - $user_id = rand(1,2); // keep it simple - make it one of the two superadmins - $asset = App\Models\Asset::where('id', $item->id) - ->update( - [ - 'assigned_to' => $target->id, - 'assigned_type' => App\Models\Location::class, - 'assigned_to' => $target->id, - ] - ); - - return [ - 'created_at' => $faker->dateTimeBetween('-1 years','now', date_default_timezone_get()), - 'user_id' => $user_id, - 'action_type' => 'checkout', - 'item_id' => $item->id, - 'item_type' => App\Models\Asset::class, - 'target_id' => $target->id, - 'target_type' => get_class($target), - ]; -}); - -// This doesn't work - we need to assign a seat -$factory->defineAs(Actionlog::class, 'license-checkout-asset', function (Faker\Generator $faker) { - $target = Asset::inRandomOrder()->RTD()->first(); - $item = License::inRandomOrder()->first(); - $user_id = rand(1,2); // keep it simple - make it one of the two superadmins - - return [ - 'user_id' => $user_id, - 'action_type' => 'checkout', - 'item_id' => $item->id, - 'item_type' => get_class($item), - 'target_id' => $target->id, - 'target_type' => get_class($target), - 'created_at' => $faker->dateTime(), - 'note' => $faker->sentence - ]; -}); - - -$factory->defineAs(Actionlog::class, 'accessory-checkout', function (Faker\Generator $faker) { - $target = Asset::inRandomOrder()->RTD()->first(); - $item = Accessory::inRandomOrder()->first(); - $user_id = rand(1,2); // keep it simple - make it one of the two superadmins - - return [ - 'user_id' => $user_id, - 'action_type' => 'checkout', - 'item_id' => $item->id, - 'item_type' => get_class($item), - 'target_id' => $target->id, - 'target_type' => get_class($target), - 'created_at' => $faker->dateTime(), - 'note' => $faker->sentence - ]; -}); - -$factory->defineAs(Actionlog::class, 'consumable-checkout', function (Faker\Generator $faker) { - $company = factory(App\Models\Company::class)->create(); - $user = factory(App\Models\User::class)->create(['company_id' => $company->id]); - $target = factory(App\Models\User::class)->create(['company_id' => $company->id]); - $item = factory(App\Models\Consumable::class)->create(['company_id' => $company->id]); - - return [ - 'user_id' => $user->id, - 'action_type' => 'checkout', - 'item_id' => $item->id, - 'item_type' => get_class($item), - 'target_id' => $target->id, - 'target_type' => get_class($target), - 'created_at' => $faker->dateTime(), - 'note' => $faker->sentence, - 'company_id' => $company->id - ]; -}); - -$factory->defineAs(Actionlog::class, 'component-checkout', function (Faker\Generator $faker) { - $company = factory(App\Models\Company::class)->create(); - $user = factory(App\Models\User::class)->create(['company_id' => $company->id]); - $target = factory(App\Models\User::class)->create(['company_id' => $company->id]); - $item = factory(App\Models\Component::class)->create(['company_id' => $company->id]); - - return [ - 'user_id' => $user->id, - 'action_type' => 'checkout', - 'item_id' => $item->id, - 'item_type' => get_class($item), - 'target_id' => $target->id, - 'target_type' => get_class($target), - 'created_at' => $faker->dateTime(), - 'note' => $faker->sentence, - 'company_id' => $company->id - ]; -}); diff --git a/database/factories/ActionlogFactory.php b/database/factories/ActionlogFactory.php new file mode 100644 index 0000000000..005e975de4 --- /dev/null +++ b/database/factories/ActionlogFactory.php @@ -0,0 +1,105 @@ +create(); + return [ + 'item_type' => get_class($asset), + 'item_id' => 1, + 'user_id' => 1, + 'filename' => $this->faker->word, + 'action_type' => 'uploaded', + ]; + } + + + public function assetCheckoutToUser() + { + return $this->state(function () { + $target = \App\Models\User::inRandomOrder()->first(); + $item = \App\Models\Asset::inRandomOrder()->RTD()->first(); + $user_id = rand(1, 2); // keep it simple - make it one of the two superadmins + $asset = Asset::where('id', $item->id) + ->update( + [ + 'assigned_to' => $target->id, + 'assigned_type' => \App\Models\User::class, + 'assigned_to' => $target->location_id, + ] + ); + + return [ + 'created_at' => $this->faker->dateTimeBetween('-1 years', 'now', date_default_timezone_get()), + 'user_id' => $user_id, + 'action_type' => 'checkout', + 'item_id' => $item->id, + 'item_type' => \App\Models\Asset::class, + 'target_id' => $target->id, + 'target_type' => get_class($target), + + ]; + }); + } + + + public function assetCheckoutToLocation() + { + return $this->state(function () { + $target = \App\Models\Location::inRandomOrder()->first(); + $item = \App\Models\Asset::inRandomOrder()->RTD()->first(); + $user_id = rand(1, 2); // keep it simple - make it one of the two superadmins + $asset = \App\Models\Asset::where('id', $item->id) + ->update( + [ + 'assigned_to' => $target->id, + 'assigned_type' => \App\Models\Location::class, + 'assigned_to' => $target->id, + ] + ); + + return [ + 'created_at' => $this->faker->dateTimeBetween('-1 years', 'now', date_default_timezone_get()), + 'user_id' => $user_id, + 'action_type' => 'checkout', + 'item_id' => $item->id, + 'item_type' => \App\Models\Asset::class, + 'target_id' => $target->id, + 'target_type' => get_class($target), + ]; + }); + } + + +} diff --git a/database/factories/AssetFactory.php b/database/factories/AssetFactory.php index e028127c89..d52d25962b 100644 --- a/database/factories/AssetFactory.php +++ b/database/factories/AssetFactory.php @@ -1,8 +1,11 @@ define(Asset::class, function (Faker\Generator $faker) { - return [ - 'name' => null, - 'rtd_location_id' => rand(1,10), - 'serial' => $faker->uuid, - 'status_id' => 1, - 'user_id' => 1, - 'asset_tag' => $faker->unixTime('now'), - 'notes' => 'Created by DB seeder', - 'purchase_date' => $faker->dateTimeBetween('-1 years','now', date_default_timezone_get()), - 'purchase_cost' => $faker->randomFloat(2, '299.99', '2999.99'), - 'order_number' => $faker->numberBetween(1000000, 50000000), - 'supplier_id' => 1, - 'requestable' => $faker->boolean(), - 'assigned_to' => null, - 'assigned_type' => null, - 'next_audit_date' => null, - 'last_checkout' => null, - ]; -}); - - - - -$factory->state(Asset::class, 'laptop-mbp', function ($faker) { - return [ - 'model_id' => 1 - ]; -}); - -$factory->state(Asset::class, 'laptop-mbp-pending', function ($faker) { - return [ - 'model_id' => 1, - 'status_id' => 2, - ]; -}); - -$factory->state(Asset::class, 'laptop-mbp-archived', function ($faker) { - return [ - 'model_id' => 1, - 'status_id' => 3, - ]; -}); - -$factory->state(Asset::class, 'laptop-air', function ($faker) { - return [ - 'model_id' => 2 - ]; -}); - -$factory->state(Asset::class, 'laptop-surface', function ($faker) { - return [ - 'model_id' => 3 - ]; -}); - -$factory->state(Asset::class, 'laptop-xps', function ($faker) { - return [ - 'model_id' => 4 - ]; -}); - -$factory->state(Asset::class, 'laptop-spectre', function ($faker) { - return [ - 'model_id' => 5 - ]; -}); - -$factory->state(Asset::class, 'laptop-zenbook', function ($faker) { - return [ - 'model_id' => 6 - ]; -}); - -$factory->state(Asset::class, 'laptop-yoga', function ($faker) { - return [ - 'model_id' => 7 - ]; -}); - -$factory->state(Asset::class, 'desktop-macpro', function ($faker) { - return [ - 'model_id' => 8 - ]; -}); - -$factory->state(Asset::class, 'desktop-lenovo-i5', function ($faker) { - return [ - 'model_id' => 9 - ]; -}); - -$factory->state(Asset::class, 'desktop-optiplex', function ($faker) { - return [ - 'model_id' => 10 - ]; -}); - -$factory->state(Asset::class, 'conf-polycom', function ($faker) { - return [ - 'model_id' => 11 - ]; -}); - -$factory->state(Asset::class, 'conf-polycomcx', function ($faker) { - return [ - 'model_id' => 12 - ]; -}); - -$factory->state(Asset::class, 'tablet-ipad', function ($faker) { - return [ - 'model_id' => 13 - ]; -}); - -$factory->state(Asset::class, 'tablet-tab3', function ($faker) { - return [ - 'model_id' => 14 - ]; -}); - -$factory->state(Asset::class, 'phone-iphone6s', function ($faker) { - return [ - 'model_id' => 15 - ]; -}); - -$factory->state(Asset::class, 'phone-iphone7', function ($faker) { - return [ - 'model_id' => 16 - ]; -}); - -$factory->state(Asset::class, 'ultrafine', function ($faker) { - return [ - 'model_id' => 17 - ]; -}); - -$factory->state(Asset::class, 'ultrasharp', function ($faker) { - return [ - 'model_id' => 18 - ]; -}); - - // These are just for unit tests, not to generate data -$factory->state(Asset::class, 'assigned-to-user', function ($faker) { - return [ - 'model_id' => 1, - 'assigned_to' => factory(App\Models\User::class)->create()->id, - 'assigned_type' => App\Models\User::class, - ]; -}); -$factory->state(Asset::class, 'assigned-to-location', function ($faker) { - return [ - 'model_id' => 1, - 'assigned_to' => factory(App\Models\Location::class)->create()->id, - 'assigned_type' => App\Models\Location::class, - ]; -}); -$factory->state(Asset::class, 'assigned-to-asset', function ($faker) { - return [ - 'model_id' => 1, - 'assigned_to' => factory(App\Models\Asset::class)->create()->id, - 'assigned_type' => App\Models\Asset::class, - ]; -}); +class AssetFactory extends Factory +{ + /** + * The name of the factory's corresponding model. + * + * @var string + */ + protected $model = Asset::class; -$factory->state(Asset::class, 'requires-acceptance', function ($faker) { - return [ - 'model_id' => 1, - ]; -}); + /** + * Define the model's default state. + * + * @return array + */ + public function definition() + { + return [ + 'name' => null, + 'rtd_location_id' => rand(1, 10), + 'serial' => $this->faker->uuid, + 'status_id' => 1, + 'user_id' => 1, + 'asset_tag' => $this->faker->unixTime('now'), + 'notes' => 'Created by DB seeder', + 'purchase_date' => $this->faker->dateTimeBetween('-1 years', 'now', date_default_timezone_get()), + 'purchase_cost' => $this->faker->randomFloat(2, '299.99', '2999.99'), + 'order_number' => $this->faker->numberBetween(1000000, 50000000), + 'supplier_id' => 1, + 'requestable' => $this->faker->boolean(), + 'assigned_to' => null, + 'assigned_type' => null, + 'next_audit_date' => null, + 'last_checkout' => null, + ]; + } + public function laptopMbp() + { + return $this->state(function () { + return [ + 'model_id' => 1, + ]; + }); + } -$factory->state(Asset::class, 'deleted', function ($faker) { - return [ - 'model_id' => 1, - 'deleted_at' => $faker->dateTime() - ]; -}); + public function laptopMbpPending() + { + return $this->state(function () { + return [ + 'model_id' => 1, + 'status_id' => 2, + ]; + }); + } + public function laptopMbpArchived() + { + return $this->state(function () { + return [ + 'model_id' => 1, + 'status_id' => 3, + ]; + }); + } -$factory->define(App\Models\AssetMaintenance::class, function (Faker\Generator $faker) { - return [ - 'asset_id' => function () { - return factory(App\Models\Asset::class)->create()->id; - }, - 'supplier_id' => function () { - return factory(App\Models\Supplier::class)->create()->id; - }, - 'asset_maintenance_type' => $faker->randomElement(['maintenance', 'repair', 'upgrade']), - 'title' => $faker->sentence, - 'start_date' => $faker->date(), - 'is_warranty' => $faker->boolean(), - 'notes' => $faker->paragraph(), - ]; -}); + public function laptopAir() + { + return $this->state(function () { + return [ + 'model_id' => 2, + ]; + }); + } + + public function laptopSurface() + { + return $this->state(function () { + return [ + 'model_id' => 3, + ]; + }); + } + + public function laptopXps() + { + return $this->state(function () { + return [ + 'model_id' => 4, + ]; + }); + } + + public function laptopSpectre() + { + return $this->state(function () { + return [ + 'model_id' => 5, + ]; + }); + } + + public function laptopZenbook() + { + return $this->state(function () { + return [ + 'model_id' => 6, + ]; + }); + } + + public function laptopYoga() + { + return $this->state(function () { + return [ + 'model_id' => 7, + ]; + }); + } + + public function desktopMacpro() + { + return $this->state(function () { + return [ + 'model_id' => 8, + ]; + }); + } + + public function desktopLenovoI5() + { + return $this->state(function () { + return [ + 'model_id' => 9, + ]; + }); + } + + public function desktopOptiplex() + { + return $this->state(function () { + return [ + 'model_id' => 10, + ]; + }); + } + + public function confPolycom() + { + return $this->state(function () { + return [ + 'model_id' => 11, + ]; + }); + } + + public function confPolycomcx() + { + return $this->state(function () { + return [ + 'model_id' => 12, + ]; + }); + } + + public function tabletIpad() + { + return $this->state(function () { + return [ + 'model_id' => 13, + ]; + }); + } + + public function tabletTab3() + { + return $this->state(function () { + return [ + 'model_id' => 14, + ]; + }); + } + + public function phoneIphone11() + { + return $this->state(function () { + return [ + 'model_id' => 15, + ]; + }); + } + + public function phoneIphone12() + { + return $this->state(function () { + return [ + 'model_id' => 16, + ]; + }); + } + + public function ultrafine() + { + return $this->state(function () { + return [ + 'model_id' => 17, + ]; + }); + } + + public function ultrasharp() + { + return $this->state(function () { + return [ + 'model_id' => 18, + ]; + }); + } + + public function assignedToUser() + { + return $this->state(function () { + return [ + 'model_id' => 1, + 'assigned_to' => \App\Models\User::factory()->create()->id, + 'assigned_type' => \App\Models\User::class, + ]; + }); + } + + public function assignedToLocation() + { + return $this->state(function () { + return [ + 'model_id' => 1, + 'assigned_to' => \App\Models\Location::factory()->create()->id, + 'assigned_type' => \App\Models\Location::class, + ]; + }); + } + + public function assignedToAsset() + { + return $this->state(function () { + return [ + 'model_id' => 1, + 'assigned_to' => \App\Models\Asset::factory()->create()->id, + 'assigned_type' => \App\Models\Asset::class, + ]; + }); + } + + public function requiresAcceptance() + { + return $this->state(function () { + return [ + 'model_id' => 1, + ]; + }); + } + + public function deleted() + { + return $this->state(function () { + return [ + 'model_id' => 1, + 'deleted_at' => $this->faker->dateTime(), + ]; + }); + } +} diff --git a/database/factories/AssetMaintenanceFactory.php b/database/factories/AssetMaintenanceFactory.php new file mode 100644 index 0000000000..f9351f5188 --- /dev/null +++ b/database/factories/AssetMaintenanceFactory.php @@ -0,0 +1,49 @@ + function () { + return \App\Models\Asset::factory()->create()->id; + }, + 'supplier_id' => function () { + return \App\Models\Supplier::factory()->create()->id; + }, + 'asset_maintenance_type' => $this->faker->randomElement(['maintenance', 'repair', 'upgrade']), + 'title' => $this->faker->sentence, + 'start_date' => $this->faker->date(), + 'is_warranty' => $this->faker->boolean(), + 'notes' => $this->faker->paragraph(), + ]; + } +} diff --git a/database/factories/AssetModelFactory.php b/database/factories/AssetModelFactory.php index 025b2b9f99..63c659fbf8 100644 --- a/database/factories/AssetModelFactory.php +++ b/database/factories/AssetModelFactory.php @@ -1,5 +1,9 @@ define(App\Models\AssetModel::class, function (Faker\Generator $faker) { - return [ - 'user_id' => 1, - 'model_number' => $faker->creditCardNumber(), - 'notes' => 'Created by demo seeder', - - ]; -}); - // 1 -$factory->state(App\Models\AssetModel::class, 'mbp-13-model', function ($faker) { - return [ - 'name' => 'Macbook Pro 13"', - 'category_id' => 1, - 'manufacturer_id' => 1, - 'eol' => '36', - 'depreciation_id' => 1, - 'image' => 'mbp.jpg', - 'fieldset_id' => 2, - ]; -}); // 2 -$factory->state(App\Models\AssetModel::class, 'mbp-air-model', function ($faker) { - return [ - 'name' => 'Macbook Air', - 'category_id' => 1, - 'manufacturer_id' => 1, - 'eol' => '36', - 'depreciation_id' => 1, - 'image' => 'macbookair.jpg', - 'fieldset_id' => 2, - ]; -}); // 3 -$factory->state(App\Models\AssetModel::class, 'surface-model', function ($faker) { - return [ - 'name' => 'Surface', - 'category_id' => 1, - 'manufacturer_id' => 2, - 'eol' => '36', - 'depreciation_id' => 1, - 'image' => 'surface.jpg', - 'fieldset_id' => 2, - ]; -}); // 4 -$factory->state(App\Models\AssetModel::class, 'xps13-model', function ($faker) { - return [ - 'name' => 'XPS 13', - 'category_id' => 1, - 'manufacturer_id' => 3, - 'eol' => '36', - 'depreciation_id' => 1, - 'image' => 'xps.jpg', - 'fieldset_id' => 2, - ]; -}); // 5 -$factory->state(App\Models\AssetModel::class, 'zenbook-model', function ($faker) { - return [ - 'name' => 'ZenBook UX310', - 'category_id' => 1, - 'manufacturer_id' => 4, - 'eol' => '36', - 'depreciation_id' => 1, - 'image' => 'zenbook.jpg', - 'fieldset_id' => 2, - ]; -}); // 6 -$factory->state(App\Models\AssetModel::class, 'spectre-model', function ($faker) { - return [ - 'name' => 'Spectre', - 'category_id' => 1, - 'manufacturer_id' => 5, - 'eol' => '36', - 'depreciation_id' => 1, - 'image' => 'spectre.jpg', - 'fieldset_id' => 2, - ]; -}); // 7 -$factory->state(App\Models\AssetModel::class, 'yoga-model', function ($faker) { - return [ - 'name' => 'Yoga 910', - 'category_id' => 1, - 'manufacturer_id' => 6, - 'eol' => '36', - 'depreciation_id' => 1, - 'image' => 'yoga.png', - 'fieldset_id' => 2, - ]; -}); /* |-------------------------------------------------------------------------- @@ -121,165 +39,316 @@ $factory->state(App\Models\AssetModel::class, 'yoga-model', function ($faker) { |-------------------------------------------------------------------------- */ - -$factory->state(App\Models\AssetModel::class, 'macpro-model', function ($faker) { - return [ - 'name' => 'iMac Pro', - 'category_id' => 2, - 'manufacturer_id' => 1, - 'eol' => '24', - 'depreciation_id' => 1, - 'image' => 'imacpro.jpg', - 'fieldset_id' => 2, - ]; -}); - -$factory->state(App\Models\AssetModel::class, 'lenovo-i5-model', function ($faker) { - return [ - 'name' => 'Lenovo Intel Core i5', - 'category_id' => 2, - 'manufacturer_id' => 6, - 'eol' => '24', - 'depreciation_id' => 1, - 'image' => 'lenovoi5.png', - 'fieldset_id' => 2, - ]; -}); - -$factory->state(App\Models\AssetModel::class, 'optiplex-model', function ($faker) { - return [ - 'name' => 'OptiPlex', - 'category_id' => 2, - 'manufacturer_id' => 3, - 'model_number' => '5040 (MRR81)', - 'eol' => '24', - 'depreciation_id' => 1, - 'image' => 'optiplex.jpg', - 'fieldset_id' => 2, - ]; -}); - - /* |-------------------------------------------------------------------------- | Conference Phones |-------------------------------------------------------------------------- */ - -$factory->state(App\Models\AssetModel::class, 'polycom-model', function ($faker) { - return [ - 'name' => 'SoundStation 2', - 'category_id' => 6, - 'manufacturer_id' => 8, - 'eol' => '12', - 'depreciation_id' => 1, - 'image' => 'soundstation.jpg', - ]; -}); - -$factory->state(App\Models\AssetModel::class, 'polycomcx-model', function ($faker) { - return [ - 'name' => 'Polycom CX3000 IP Conference Phone', - 'category_id' => 6, - 'manufacturer_id' => 8, - 'eol' => '12', - 'depreciation_id' => 1, - 'image' => 'cx3000.png', - ]; -}); - - /* |-------------------------------------------------------------------------- | Tablets |-------------------------------------------------------------------------- */ -$factory->state(App\Models\AssetModel::class, 'ipad-model', function ($faker) { - return [ - 'name' => 'iPad Pro', - 'category_id' => 3, - 'manufacturer_id' => 1, - 'eol' => '12', - 'depreciation_id' => 1, - 'image' => 'ipad.jpg', - ]; -}); - - -$factory->state(App\Models\AssetModel::class, 'tab3-model', function ($faker) { - return [ - 'name' => 'Tab3', - 'category_id' => 3, - 'manufacturer_id' => 6, - 'eol' => '12', - 'depreciation_id' => 1, - 'image' => 'tab3.png', - ]; -}); - - /* |-------------------------------------------------------------------------- | Mobile Phones |-------------------------------------------------------------------------- */ -$factory->state(App\Models\AssetModel::class, 'iphone11-model', function ($faker) { - return [ - 'name' => 'iPhone 11', - 'category_id' => 4, - 'manufacturer_id' => 1, - 'eol' => '12', - 'depreciation_id' => 3, - 'image' => 'iphone11.jpeg', - 'fieldset_id' => 1, - ]; -}); - -$factory->state(App\Models\AssetModel::class, 'iphone12-model', function ($faker) { - return [ - 'name' => 'iPhone 12', - 'category_id' => 4, - 'manufacturer_id' => 1, - 'eol' => '12', - 'depreciation_id' => 1, - 'image' => 'iphone12.jpeg', - 'fieldset_id' => 1, - ]; -}); - /* |-------------------------------------------------------------------------- | Displays |-------------------------------------------------------------------------- */ -$factory->state(App\Models\AssetModel::class, 'ultrafine', function ($faker) { - return [ - 'name' => 'Ultrafine 4k', - 'category_id' => 5, - 'manufacturer_id' => 7, - 'eol' => '12', - 'depreciation_id' => 2, - 'image' => 'ultrafine.jpg', - ]; -}); +class AssetModelFactory extends Factory +{ + /** + * The name of the factory's corresponding model. + * + * @var string + */ + protected $model = \App\Models\AssetModel::class; -$factory->state(App\Models\AssetModel::class, 'ultrasharp', function ($faker) { - return [ - 'name' => 'Ultrasharp U2415', - 'category_id' => 5, - 'manufacturer_id' => 3, - 'eol' => '12', - 'depreciation_id' => 2, - 'image' => 'ultrasharp.jpg', - ]; -}); + /** + * Define the model's default state. + * + * @return array + */ + public function definition() + { + return [ + 'user_id' => 1, + 'model_number' => $this->faker->creditCardNumber(), + 'notes' => 'Created by demo seeder', + ]; + } + public function mbp13Model() + { + return $this->state(function () { + return [ + 'name' => 'Macbook Pro 13"', + 'category_id' => 1, + 'manufacturer_id' => 1, + 'eol' => '36', + 'depreciation_id' => 1, + 'image' => 'mbp.jpg', + 'fieldset_id' => 2, + ]; + }); + } + public function mbpAirModel() + { + return $this->state(function () { + return [ + 'name' => 'Macbook Air', + 'category_id' => 1, + 'manufacturer_id' => 1, + 'eol' => '36', + 'depreciation_id' => 1, + 'image' => 'macbookair.jpg', + 'fieldset_id' => 2, + ]; + }); + } + public function surfaceModel() + { + return $this->state(function () { + return [ + 'name' => 'Surface', + 'category_id' => 1, + 'manufacturer_id' => 2, + 'eol' => '36', + 'depreciation_id' => 1, + 'image' => 'surface.jpg', + 'fieldset_id' => 2, + ]; + }); + } + public function xps13Model() + { + return $this->state(function () { + return [ + 'name' => 'XPS 13', + 'category_id' => 1, + 'manufacturer_id' => 3, + 'eol' => '36', + 'depreciation_id' => 1, + 'image' => 'xps.jpg', + 'fieldset_id' => 2, + ]; + }); + } + public function zenbookModel() + { + return $this->state(function () { + return [ + 'name' => 'ZenBook UX310', + 'category_id' => 1, + 'manufacturer_id' => 4, + 'eol' => '36', + 'depreciation_id' => 1, + 'image' => 'zenbook.jpg', + 'fieldset_id' => 2, + ]; + }); + } + + public function spectreModel() + { + return $this->state(function () { + return [ + 'name' => 'Spectre', + 'category_id' => 1, + 'manufacturer_id' => 5, + 'eol' => '36', + 'depreciation_id' => 1, + 'image' => 'spectre.jpg', + 'fieldset_id' => 2, + ]; + }); + } + + public function yogaModel() + { + return $this->state(function () { + return [ + 'name' => 'Yoga 910', + 'category_id' => 1, + 'manufacturer_id' => 6, + 'eol' => '36', + 'depreciation_id' => 1, + 'image' => 'yoga.png', + 'fieldset_id' => 2, + ]; + }); + } + + public function macproModel() + { + return $this->state(function () { + return [ + 'name' => 'iMac Pro', + 'category_id' => 2, + 'manufacturer_id' => 1, + 'eol' => '24', + 'depreciation_id' => 1, + 'image' => 'imacpro.jpg', + 'fieldset_id' => 2, + ]; + }); + } + + public function lenovoI5Model() + { + return $this->state(function () { + return [ + 'name' => 'Lenovo Intel Core i5', + 'category_id' => 2, + 'manufacturer_id' => 6, + 'eol' => '24', + 'depreciation_id' => 1, + 'image' => 'lenovoi5.png', + 'fieldset_id' => 2, + ]; + }); + } + + public function optiplexModel() + { + return $this->state(function () { + return [ + 'name' => 'OptiPlex', + 'category_id' => 2, + 'manufacturer_id' => 3, + 'model_number' => '5040 (MRR81)', + 'eol' => '24', + 'depreciation_id' => 1, + 'image' => 'optiplex.jpg', + 'fieldset_id' => 2, + ]; + }); + } + + public function polycomModel() + { + return $this->state(function () { + return [ + 'name' => 'SoundStation 2', + 'category_id' => 6, + 'manufacturer_id' => 8, + 'eol' => '12', + 'depreciation_id' => 1, + 'image' => 'soundstation.jpg', + ]; + }); + } + + public function polycomcxModel() + { + return $this->state(function () { + return [ + 'name' => 'Polycom CX3000 IP Conference Phone', + 'category_id' => 6, + 'manufacturer_id' => 8, + 'eol' => '12', + 'depreciation_id' => 1, + 'image' => 'cx3000.png', + ]; + }); + } + + public function ipadModel() + { + return $this->state(function () { + return [ + 'name' => 'iPad Pro', + 'category_id' => 3, + 'manufacturer_id' => 1, + 'eol' => '12', + 'depreciation_id' => 1, + 'image' => 'ipad.jpg', + ]; + }); + } + + public function tab3Model() + { + return $this->state(function () { + return [ + 'name' => 'Tab3', + 'category_id' => 3, + 'manufacturer_id' => 6, + 'eol' => '12', + 'depreciation_id' => 1, + 'image' => 'tab3.png', + ]; + }); + } + + public function iphone11Model() + { + return $this->state(function () { + return [ + 'name' => 'iPhone 11', + 'category_id' => 4, + 'manufacturer_id' => 1, + 'eol' => '12', + 'depreciation_id' => 3, + 'image' => 'iphone11.jpeg', + 'fieldset_id' => 1, + ]; + }); + } + + public function iphone12Model() + { + return $this->state(function () { + return [ + 'name' => 'iPhone 12', + 'category_id' => 4, + 'manufacturer_id' => 1, + 'eol' => '12', + 'depreciation_id' => 1, + 'image' => 'iphone12.jpeg', + 'fieldset_id' => 1, + ]; + }); + } + + public function ultrafine() + { + return $this->state(function () { + return [ + 'name' => 'Ultrafine 4k', + 'category_id' => 5, + 'manufacturer_id' => 7, + 'eol' => '12', + 'depreciation_id' => 2, + 'image' => 'ultrafine.jpg', + ]; + }); + } + + public function ultrasharp() + { + return $this->state(function () { + return [ + 'name' => 'Ultrasharp U2415', + 'category_id' => 5, + 'manufacturer_id' => 3, + 'eol' => '12', + 'depreciation_id' => 2, + 'image' => 'ultrasharp.jpg', + ]; + }); + } +} diff --git a/database/factories/CategoryFactory.php b/database/factories/CategoryFactory.php index 26b59ffac2..3001c6001e 100644 --- a/database/factories/CategoryFactory.php +++ b/database/factories/CategoryFactory.php @@ -1,5 +1,9 @@ define(App\Models\Category::class, function (Faker\Generator $faker) { - return [ - 'checkin_email' => $faker->boolean(), - 'eula_text' => $faker->paragraph(), - 'require_acceptance' => false, - 'use_default_eula' => $faker->boolean(), - 'user_id' => 1, - ]; -}); + /** + * Define the model's default state. + * + * @return array + */ + public function definition() + { + return [ + 'checkin_email' => $this->faker->boolean(), + 'eula_text' => $this->faker->paragraph(), + 'require_acceptance' => false, + 'use_default_eula' => $this->faker->boolean(), + 'user_id' => 1, + ]; + } -$factory->state(App\Models\Category::class, 'asset-laptop-category', function ($faker) { - return [ - 'name' => 'Laptops', - 'category_type' => 'asset', - 'require_acceptance' => true, - ]; -}); + public function assetLaptopCategory() + { + return $this->state(function () { + return [ + 'name' => 'Laptops', + 'category_type' => 'asset', + 'require_acceptance' => true, + ]; + }); + } -$factory->state(App\Models\Category::class, 'asset-desktop-category', function ($faker) { - return [ - 'name' => 'Desktops', - 'category_type' => 'asset', - ]; -}); + public function assetDesktopCategory() + { + return $this->state(function () { + return [ + 'name' => 'Desktops', + 'category_type' => 'asset', + ]; + }); + } -$factory->state(App\Models\Category::class, 'asset-display-category', function ($faker) { - return [ - 'name' => 'Displays', - 'category_type' => 'asset', - ]; -}); + public function assetDisplayCategory() + { + return $this->state(function () { + return [ + 'name' => 'Displays', + 'category_type' => 'asset', + ]; + }); + } -$factory->state(App\Models\Category::class, 'asset-tablet-category', function ($faker) { - return [ - 'name' => 'Tablets', - 'category_type' => 'asset', - ]; -}); + public function assetTabletCategory() + { + return $this->state(function () { + return [ + 'name' => 'Tablets', + 'category_type' => 'asset', + ]; + }); + } -$factory->state(App\Models\Category::class, 'asset-mobile-category', function ($faker) { - return [ - 'name' => 'Mobile Phones', - 'category_type' => 'asset', - ]; -}); + public function assetMobileCategory() + { + return $this->state(function () { + return [ + 'name' => 'Mobile Phones', + 'category_type' => 'asset', + ]; + }); + } -$factory->state(App\Models\Category::class, 'asset-conference-category', function ($faker) { - return [ - 'name' => 'Conference Phones', - 'category_type' => 'asset', - ]; -}); + public function assetConferenceCategory() + { + return $this->state(function () { + return [ + 'name' => 'Conference Phones', + 'category_type' => 'asset', + ]; + }); + } -$factory->state(App\Models\Category::class, 'asset-voip-category', function ($faker) { - return [ - 'name' => 'VOIP Phones', - 'category_type' => 'asset', - ]; -}); + public function assetVoipCategory() + { + return $this->state(function () { + return [ + 'name' => 'VOIP Phones', + 'category_type' => 'asset', + ]; + }); + } + public function accessoryKeyboardCategory() + { + return $this->state(function () { + return [ + 'name' => 'Keyboards', + 'category_type' => 'accessory', + ]; + }); + } -$factory->state(App\Models\Category::class, 'accessory-keyboard-category', function ($faker) { - return [ - 'name' => 'Keyboards', - 'category_type' => 'accessory', - ]; -}); + public function accessoryMouseCategory() + { + return $this->state(function () { + return [ + 'name' => 'Mouse', + 'category_type' => 'accessory', + ]; + }); + } -$factory->state(App\Models\Category::class, 'accessory-mouse-category', function ($faker) { - return [ - 'name' => 'Mouse', - 'category_type' => 'accessory', - ]; -}); + public function componentHddCategory() + { + return $this->state(function () { + return [ + 'name' => 'HDD/SSD', + 'category_type' => 'component', + ]; + }); + } + public function componentRamCategory() + { + return $this->state(function () { + return [ + 'name' => 'RAM', + 'category_type' => 'component', + ]; + }); + } -$factory->state(App\Models\Category::class, 'component-hdd-category', function ($faker) { - return [ - 'name' => 'HDD/SSD', - 'category_type' => 'component', - ]; -}); + public function consumablePaperCategory() + { + return $this->state(function () { + return [ + 'name' => 'Printer Paper', + 'category_type' => 'consumable', + ]; + }); + } -$factory->state(App\Models\Category::class, 'component-ram-category', function ($faker) { - return [ - 'name' => 'RAM', - 'category_type' => 'component', - ]; -}); + public function consumableInkCategory() + { + return $this->state(function () { + return [ + 'name' => 'Printer Ink', + 'category_type' => 'consumable', + ]; + }); + } -$factory->state(App\Models\Category::class, 'consumable-paper-category', function ($faker) { - return [ - 'name' => 'Printer Paper', - 'category_type' => 'consumable', - ]; -}); + public function licenseGraphicsCategory() + { + return $this->state(function () { + return [ + 'name' => 'Graphics Software', + 'category_type' => 'license', + ]; + }); + } -$factory->state(App\Models\Category::class, 'consumable-ink-category', function ($faker) { - return [ - 'name' => 'Printer Ink', - 'category_type' => 'consumable', - ]; -}); - - -$factory->state(App\Models\Category::class, 'license-graphics-category', function ($faker) { - return [ - 'name' => 'Graphics Software', - 'category_type' => 'license', - ]; -}); - - -$factory->state(App\Models\Category::class, 'license-office-category', function ($faker) { - return [ - 'name' => 'Office Software', - 'category_type' => 'license', - ]; -}); + public function licenseOfficeCategory() + { + return $this->state(function () { + return [ + 'name' => 'Office Software', + 'category_type' => 'license', + ]; + }); + } +} diff --git a/database/factories/CompanyFactory.php b/database/factories/CompanyFactory.php new file mode 100644 index 0000000000..695a2dbdb5 --- /dev/null +++ b/database/factories/CompanyFactory.php @@ -0,0 +1,45 @@ + $this->faker->company, + ]; + } +} diff --git a/database/factories/ComponentFactory.php b/database/factories/ComponentFactory.php new file mode 100644 index 0000000000..bd971162ab --- /dev/null +++ b/database/factories/ComponentFactory.php @@ -0,0 +1,101 @@ + $this->faker->text(20), + 'category_id' => function () { + return \App\Models\Category::factory()->create()->id; + }, + 'location_id' => 1, + 'serial' => $this->faker->uuid, + 'qty' => $this->faker->numberBetween(3, 10), + 'order_number' => $this->faker->numberBetween(1000000, 50000000), + 'purchase_date' => $this->faker->dateTime(), + 'purchase_cost' => $this->faker->randomFloat(2), + 'min_amt' => $this->faker->numberBetween($min = 1, $max = 2), + 'company_id' => function () { + return \App\Models\Company::factory()->create()->id; + }, + ]; + } + + public function ramCrucial4() + { + return $this->state(function () { + return [ + 'name' => 'Crucial 4GB DDR3L-1600 SODIMM', + 'category_id' => 13, + 'qty' => 10, + 'min_amt' => 2, + 'location_id' => 3, + 'company_id' => 2, + ]; + }); + } + + public function ramCrucial8() + { + return $this->state(function () { + return [ + 'name' => 'Crucial 8GB DDR3L-1600 SODIMM Memory for Mac', + 'category_id' => 13, + 'qty' => 10, + 'min_amt' => 2, + ]; + }); + } + + public function ssdCrucial120() + { + return $this->state(function () { + return [ + 'name' => 'Crucial BX300 120GB SATA Internal SSD', + 'category_id' => 12, + 'qty' => 10, + 'min_amt' => 2, + ]; + }); + } + + public function ssdCrucial240() + { + return $this->state(function () { + return [ + 'name' => 'Crucial BX300 240GB SATA Internal SSD', + 'category_id' => 12, + 'qty' => 10, + 'min_amt' => 2, + ]; + }); + } + + +} diff --git a/database/factories/ComponentsFactory.php b/database/factories/ComponentsFactory.php deleted file mode 100644 index c550493c2b..0000000000 --- a/database/factories/ComponentsFactory.php +++ /dev/null @@ -1,66 +0,0 @@ -define(App\Models\Component::class, function (Faker\Generator $faker) { - return [ - 'user_id' => 1, - 'order_number' => $faker->numberBetween(1000000, 50000000), - 'purchase_date' => $faker->dateTimeBetween('-1 years','now', date_default_timezone_get()), - 'purchase_cost' => $faker->randomFloat(2, 1, 50), - 'qty' => $faker->numberBetween(5, 10), - 'min_amt' => $faker->numberBetween($min = 1, $max = 2), - ]; -}); - -$factory->state(App\Models\Component::class, 'ram-crucial4', function ($faker) { - - return [ - 'name' => 'Crucial 4GB DDR3L-1600 SODIMM', - 'category_id' => 13, - 'qty' => 10, - 'min_amt' => 2, - 'location_id' => 3, - 'company_id' => 2 - ]; -}); - -$factory->state(App\Models\Component::class, 'ram-crucial8', function ($faker) { - - return [ - 'name' => 'Crucial 8GB DDR3L-1600 SODIMM Memory for Mac', - 'category_id' => 13, - 'qty' => 10, - 'min_amt' => 2 - ]; -}); - -$factory->state(App\Models\Component::class, 'ssd-crucial120', function ($faker) { - - return [ - 'name' => 'Crucial BX300 120GB SATA Internal SSD', - 'category_id' => 12, - 'qty' => 10, - 'min_amt' => 2 - ]; -}); - -$factory->state(App\Models\Component::class, 'ssd-crucial240', function ($faker) { - - return [ - 'name' => 'Crucial BX300 240GB SATA Internal SSD', - 'category_id' => 12, - 'qty' => 10, - 'min_amt' => 2 - ]; -}); - - - diff --git a/database/factories/ConsumableFactory.php b/database/factories/ConsumableFactory.php index 41ddcf42a8..50a9db0ba2 100644 --- a/database/factories/ConsumableFactory.php +++ b/database/factories/ConsumableFactory.php @@ -1,5 +1,9 @@ define(App\Models\Consumable::class, function (Faker\Generator $faker) { - return [ - 'user_id' => 1, - 'item_no' => $faker->numberBetween(1000000, 50000000), - 'order_number' => $faker->numberBetween(1000000, 50000000), - 'purchase_date' => $faker->dateTimeBetween('-1 years','now', date_default_timezone_get()), - 'purchase_cost' => $faker->randomFloat(2, 1, 50), - 'qty' => $faker->numberBetween(5, 10), - 'min_amt' => $faker->numberBetween($min = 1, $max = 2), - ]; -}); +class ConsumableFactory extends Factory +{ + /** + * The name of the factory's corresponding model. + * + * @var string + */ + protected $model = \App\Models\Consumable::class; -$factory->state(App\Models\Consumable::class, 'cardstock', function ($faker) { - - return [ - 'name' => 'Cardstock (White)', - 'category_id' => 10, - 'manufacturer_id' => 10, - 'qty' => 10, - 'min_amt' => 2, - 'company_id' => 3 - ]; -}); - -$factory->state(App\Models\Consumable::class, 'paper', function ($faker) { - - return [ - 'name' => 'Laserjet Paper (Ream)', - 'category_id' => 10, - 'manufacturer_id' => 10, - 'qty' => 20, - 'min_amt' => 2 - ]; -}); - -$factory->state(App\Models\Consumable::class, 'ink', function ($faker) { - - return [ - 'name' => 'Laserjet Toner (black)', - 'category_id' => 11, - 'manufacturer_id' => 5, - 'qty' => 20, - 'min_amt' => 2 - ]; -}); + /** + * Define the model's default state. + * + * @return array + */ + public function definition() + { + return [ + 'user_id' => 1, + 'item_no' => $this->faker->numberBetween(1000000, 50000000), + 'order_number' => $this->faker->numberBetween(1000000, 50000000), + 'purchase_date' => $this->faker->dateTimeBetween('-1 years', 'now', date_default_timezone_get()), + 'purchase_cost' => $this->faker->randomFloat(2, 1, 50), + 'qty' => $this->faker->numberBetween(5, 10), + 'min_amt' => $this->faker->numberBetween($min = 1, $max = 2), + ]; + } + public function cardstock() + { + return $this->state(function () { + return [ + 'name' => 'Cardstock (White)', + 'category_id' => 10, + 'manufacturer_id' => 10, + 'qty' => 10, + 'min_amt' => 2, + 'company_id' => 3, + ]; + }); + } + public function paper() + { + return $this->state(function () { + return [ + 'name' => 'Laserjet Paper (Ream)', + 'category_id' => 10, + 'manufacturer_id' => 10, + 'qty' => 20, + 'min_amt' => 2, + ]; + }); + } + public function ink() + { + return $this->state(function () { + return [ + 'name' => 'Laserjet Toner (black)', + 'category_id' => 11, + 'manufacturer_id' => 5, + 'qty' => 20, + 'min_amt' => 2, + ]; + }); + } +} diff --git a/database/factories/CustomFieldFactory.php b/database/factories/CustomFieldFactory.php new file mode 100644 index 0000000000..c964ea44d1 --- /dev/null +++ b/database/factories/CustomFieldFactory.php @@ -0,0 +1,80 @@ + $this->faker->catchPhrase, + 'format' => '', + 'element' => 'text', + ]; + } + + public function imei() + { + return $this->state(function () { + return [ + 'name' => 'IMEI', + 'help_text' => 'The IMEI number for this device.', + 'format' => 'regex:/^[0-9]{15}$/', + ]; + }); + } + + public function phone() + { + return $this->state(function () { + return [ + 'name' => 'Phone Number', + 'help_text' => 'Enter the phone number for this device.', + ]; + }); + } + + public function ram() + { + return $this->state(function () { + return [ + 'name' => 'RAM', + 'help_text' => 'The amount of RAM this device has.', + ]; + }); + } + + public function cpu() + { + return $this->state(function () { + return [ + 'name' => 'CPU', + 'help_text' => 'The speed of the processor on this device.', + ]; + }); + } + + public function macAddress() + { + return $this->state(function () { + return [ + 'name' => 'MAC Address', + 'format' => 'regex:/^([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}$/', + ]; + }); + } +} diff --git a/database/factories/CustomFieldsFactory.php b/database/factories/CustomFieldsFactory.php deleted file mode 100644 index 7840014fd0..0000000000 --- a/database/factories/CustomFieldsFactory.php +++ /dev/null @@ -1,48 +0,0 @@ -define(App\Models\CustomField::class, function (Faker\Generator $faker) { - return [ - 'name' => $faker->catchPhrase, - 'format' => '', - 'element' => 'text', - ]; -}); - -$factory->state(App\Models\CustomField::class, 'imei', function ($faker) { - return [ - 'name' => 'IMEI', - 'help_text' => 'The IMEI number for this device.', - 'format' => 'regex:/^[0-9]{15}$/', - ]; -}); - -$factory->state(App\Models\CustomField::class, 'phone', function ($faker) { - return [ - 'name' => 'Phone Number', - 'help_text' => 'Enter the phone number for this device.', - ]; -}); - -$factory->state(App\Models\CustomField::class, 'ram', function ($faker) { - return [ - 'name' => 'RAM', - 'help_text' => 'The amount of RAM this device has.', - ]; -}); - -$factory->state(App\Models\CustomField::class, 'cpu', function ($faker) { - return [ - 'name' => 'CPU', - 'help_text' => 'The speed of the processor on this device.', - ]; -}); - - -$factory->state(App\Models\CustomField::class, 'mac-address', function ($faker) { - return [ - 'name' => 'MAC Address', - 'format' => 'regex:/^([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}$/', - ]; -}); - diff --git a/database/factories/CustomFieldsetFactory.php b/database/factories/CustomFieldsetFactory.php index bab8cbe58f..1dd834d052 100644 --- a/database/factories/CustomFieldsetFactory.php +++ b/database/factories/CustomFieldsetFactory.php @@ -1,23 +1,45 @@ define(App\Models\CustomFieldset::class, function (Faker\Generator $faker) { - return [ - 'name' => $faker->catchPhrase, - ]; -}); +use Illuminate\Database\Eloquent\Factories\Factory; -$factory->state(App\Models\CustomFieldset::class, 'mobile', function ($faker) { - return [ - 'name' => 'Mobile Devices', - ]; -}); - -$factory->state(App\Models\CustomFieldset::class, 'computer', function ($faker) { - return [ - 'name' => 'Laptops and Desktops', - ]; -}); +class CustomFieldsetFactory extends Factory +{ + /** + * The name of the factory's corresponding model. + * + * @var string + */ + protected $model = \App\Models\CustomFieldset::class; + /** + * Define the model's default state. + * + * @return array + */ + public function definition() + { + return [ + 'name' => $this->faker->catchPhrase, + ]; + } + public function mobile() + { + return $this->state(function () { + return [ + 'name' => 'Mobile Devices', + ]; + }); + } + public function computer() + { + return $this->state(function () { + return [ + 'name' => 'Laptops and Desktops', + ]; + }); + } +} diff --git a/database/factories/DepartmentFactory.php b/database/factories/DepartmentFactory.php new file mode 100644 index 0000000000..ad80d32841 --- /dev/null +++ b/database/factories/DepartmentFactory.php @@ -0,0 +1,100 @@ + 1, + 'location_id' => rand(1, 5), + ]; + } + + public function hr() + { + return $this->state(function () { + return [ + 'name' => 'Human Resources', + ]; + }); + } + + public function engineering() + { + return $this->state(function () { + return [ + 'name' => 'Engineering', + ]; + }); + } + + public function marketing() + { + return $this->state(function () { + return [ + 'name' => 'Marketing', + ]; + }); + } + + public function client() + { + return $this->state(function () { + return [ + 'name' => 'Client Services', + ]; + }); + } + + public function design() + { + return $this->state(function () { + return [ + 'name' => 'Graphic Design', + ]; + }); + } + + public function product() + { + return $this->state(function () { + return [ + 'name' => 'Product Management', + ]; + }); + } + + public function silly() + { + return $this->state(function () { + return [ + 'name' => 'Dept of Silly Walks', + ]; + }); + } +} diff --git a/database/factories/DepartmentsFactory.php b/database/factories/DepartmentsFactory.php deleted file mode 100644 index 8b4d0f357a..0000000000 --- a/database/factories/DepartmentsFactory.php +++ /dev/null @@ -1,62 +0,0 @@ -define(App\Models\Department::class, function (Faker\Generator $faker) { - return [ - 'user_id' => 1, - 'location_id' => rand(1,5), - ]; -}); - -$factory->state(App\Models\Department::class, 'hr', function ($faker) { - return [ - 'name' => 'Human Resources', - ]; -}); - -$factory->state(App\Models\Department::class, 'engineering', function ($faker) { - return [ - 'name' => 'Engineering', - ]; -}); - -$factory->state(App\Models\Department::class, 'marketing', function ($faker) { - return [ - 'name' => 'Marketing', - ]; -}); - -$factory->state(App\Models\Department::class, 'client', function ($faker) { - return [ - 'name' => 'Client Services', - ]; -}); - -$factory->state(App\Models\Department::class, 'design', function ($faker) { - return [ - 'name' => 'Graphic Design', - ]; -}); - -$factory->state(App\Models\Department::class, 'product', function ($faker) { - return [ - 'name' => 'Product Management', - ]; -}); - -$factory->state(App\Models\Department::class, 'silly', function ($faker) { - return [ - 'name' => 'Dept of Silly Walks', - ]; -}); - - - diff --git a/database/factories/DepreciationFactory.php b/database/factories/DepreciationFactory.php index e1df63dab2..2a1bfe4cd2 100644 --- a/database/factories/DepreciationFactory.php +++ b/database/factories/DepreciationFactory.php @@ -1,5 +1,9 @@ define(App\Models\Depreciation::class, function (Faker\Generator $faker) { - return [ - 'user_id' => 1, - ]; -}); - -$factory->state(App\Models\Depreciation::class, 'computer', function ($faker) { - return [ - 'name' => 'Computer Depreciation', - 'months' => 36, - ]; -}); - -$factory->state(App\Models\Depreciation::class, 'display', function ($faker) { - return [ - 'name' => 'Display Depreciation', - 'months' => 12, - ]; -}); - -$factory->state(App\Models\Depreciation::class, 'mobile-phones', function ($faker) { - return [ - 'name' => 'Mobile Phone Depreciation', - 'months' => 24, - ]; -}); +class DepreciationFactory extends Factory +{ + /** + * The name of the factory's corresponding model. + * + * @var string + */ + protected $model = \App\Models\Depreciation::class; + /** + * Define the model's default state. + * + * @return array + */ + public function definition() + { + return [ + 'user_id' => 1, + ]; + } + public function computer() + { + return $this->state(function () { + return [ + 'name' => 'Computer Depreciation', + 'months' => 36, + ]; + }); + } + public function display() + { + return $this->state(function () { + return [ + 'name' => 'Display Depreciation', + 'months' => 12, + ]; + }); + } + public function mobilePhones() + { + return $this->state(function () { + return [ + 'name' => 'Mobile Phone Depreciation', + 'months' => 24, + ]; + }); + } +} diff --git a/database/factories/GroupFactory.php b/database/factories/GroupFactory.php new file mode 100644 index 0000000000..17f3493c2b --- /dev/null +++ b/database/factories/GroupFactory.php @@ -0,0 +1,45 @@ + $this->faker->name, + ]; + } +} diff --git a/database/factories/LicenseFactory.php b/database/factories/LicenseFactory.php index b4b440f45c..7b4c1bc787 100644 --- a/database/factories/LicenseFactory.php +++ b/database/factories/LicenseFactory.php @@ -1,5 +1,9 @@ define(App\Models\License::class, function (Faker\Generator $faker) { - - return [ - 'user_id' => 1, - 'license_name' => $faker->name, - 'license_email' => $faker->safeEmail, - 'serial' => $faker->uuid, - 'notes' => 'Created by DB seeder', - 'purchase_date' => $faker->dateTimeBetween('-1 years','now', date_default_timezone_get()), - 'order_number' => $faker->numberBetween(1000000, 50000000), - 'expiration_date' => $faker->dateTimeBetween('now', '+3 years', date_default_timezone_get())->format('Y-m-d H:i:s'), - 'reassignable' => $faker->boolean(), - 'termination_date' => $faker->dateTimeBetween('-1 years','now', date_default_timezone_get())->format('Y-m-d H:i:s'), - 'supplier_id' => $faker->numberBetween(1,5), - ]; -}); - // 1 -$factory->state(App\Models\License::class, 'photoshop', function ($faker) { - $data = [ - 'name' => 'Photoshop', - 'manufacturer_id' => 9, - 'purchase_cost' => '299.99', - 'seats' => 10, - 'purchase_order' => '13503Q', - 'maintained' => true, - 'category_id' => 14, - ]; - - return $data; - -}); // 2 -$factory->state(App\Models\License::class, 'acrobat', function ($faker) { - - $data = [ - 'name' => 'Acrobat', - 'manufacturer_id' => 9, - 'purchase_cost' => '29.99', - 'seats' => 10, - 'category_id' => 14, - ]; - - - return $data; -}); // 3 -$factory->state(App\Models\License::class, 'indesign', function ($faker) { - $data = [ - 'name' => 'InDesign', - 'manufacturer_id' => 9, - 'purchase_cost' => '199.99', - 'seats' => 10, - 'category_id' => 14, - ]; - - - return $data; -}); - // 4 -$factory->state(App\Models\License::class, 'office', function ($faker) { - $data = [ - 'name' => 'Office', - 'manufacturer_id' => 2, - 'purchase_cost' => '49.99', - 'seats' => 20, - 'category_id' => 15, - ]; +class LicenseFactory extends Factory +{ + /** + * The name of the factory's corresponding model. + * + * @var string + */ + protected $model = \App\Models\License::class; - return $data; -}); + /** + * Define the model's default state. + * + * @return array + */ + public function definition() + { + return [ + 'user_id' => 1, + 'license_name' => $this->faker->name, + 'license_email' => $this->faker->safeEmail, + 'serial' => $this->faker->uuid, + 'notes' => 'Created by DB seeder', + 'purchase_date' => $this->faker->dateTimeBetween('-1 years', 'now', date_default_timezone_get()), + 'order_number' => $this->faker->numberBetween(1000000, 50000000), + 'expiration_date' => $this->faker->dateTimeBetween('now', '+3 years', date_default_timezone_get())->format('Y-m-d H:i:s'), + 'reassignable' => $this->faker->boolean(), + 'termination_date' => $this->faker->dateTimeBetween('-1 years', 'now', date_default_timezone_get())->format('Y-m-d H:i:s'), + 'supplier_id' => $this->faker->numberBetween(1, 5), + ]; + } + public function photoshop() + { + return $this->state(function () { + $data = [ + 'name' => 'Photoshop', + 'manufacturer_id' => 9, + 'purchase_cost' => '299.99', + 'seats' => 10, + 'purchase_order' => '13503Q', + 'maintained' => true, + 'category_id' => 14, + ]; + return $data; + }); + } + + public function acrobat() + { + return $this->state(function () { + $data = [ + 'name' => 'Acrobat', + 'manufacturer_id' => 9, + 'purchase_cost' => '29.99', + 'seats' => 10, + 'category_id' => 14, + ]; + + return $data; + }); + } + + public function indesign() + { + return $this->state(function () { + $data = [ + 'name' => 'InDesign', + 'manufacturer_id' => 9, + 'purchase_cost' => '199.99', + 'seats' => 10, + 'category_id' => 14, + ]; + + return $data; + }); + } + + public function office() + { + return $this->state(function () { + $data = [ + 'name' => 'Office', + 'manufacturer_id' => 2, + 'purchase_cost' => '49.99', + 'seats' => 20, + 'category_id' => 15, + ]; + + return $data; + }); + } +} diff --git a/database/factories/LocationFactory.php b/database/factories/LocationFactory.php new file mode 100644 index 0000000000..ef90f006a9 --- /dev/null +++ b/database/factories/LocationFactory.php @@ -0,0 +1,53 @@ + $this->faker->city, + 'address' => $this->faker->streetAddress, + 'address2' => $this->faker->secondaryAddress, + 'city' => $this->faker->city, + 'state' => $this->faker->stateAbbr, + 'country' => $this->faker->countryCode, + 'currency' => $this->faker->currencyCode, + 'zip' => $this->faker->postcode, + 'image' => rand(1, 9).'.jpg', + ]; + } +} diff --git a/database/factories/ManufacturerFactory.php b/database/factories/ManufacturerFactory.php index ff1ab4645f..427cd0b6db 100644 --- a/database/factories/ManufacturerFactory.php +++ b/database/factories/ManufacturerFactory.php @@ -1,5 +1,9 @@ define(App\Models\Manufacturer::class, function (Faker\Generator $faker) { - return [ - 'user_id' => 1, - 'support_phone' => $faker->phoneNumber(), - 'url' => $faker->url(), - 'support_email' => $faker->safeEmail(), - ]; -}); - - // 1 -$factory->state(App\Models\Manufacturer::class, 'apple', function ($faker) { - return [ - 'name' => 'Apple', - 'url' => 'https://apple.com', - 'support_url' => 'https://support.apple.com', - 'image' => 'apple.jpg', - ]; -}); // 2 -$factory->state(App\Models\Manufacturer::class, 'microsoft', function ($faker) { - return [ - 'name' => 'Microsoft', - 'url' => 'https://microsoft.com', - 'support_url' => 'https://support.microsoft.com', - 'image' => 'microsoft.png', - ]; -}); // 3 -$factory->state(App\Models\Manufacturer::class, 'dell', function ($faker) { - return [ - 'name' => 'Dell', - 'url' => 'https://dell.com', - 'support_url' => 'https://support.dell.com', - 'image' => 'dell.png', - ]; -}); // 4 -$factory->state(App\Models\Manufacturer::class, 'asus', function ($faker) { - return [ - 'name' => 'Asus', - 'url' => 'https://asus.com', - 'support_url' => 'https://support.asus.com', - 'image' => 'asus.png', - ]; -}); // 5 -$factory->state(App\Models\Manufacturer::class, 'hp', function ($faker) { - return [ - 'name' => 'HP', - 'url' => 'https://hp.com', - 'support_url' => 'https://support.hp.com', - 'image' => 'hp.png', - ]; -}); // 6 -$factory->state(App\Models\Manufacturer::class, 'lenovo', function ($faker) { - return [ - 'name' => 'Lenovo', - 'url' => 'https://lenovo.com', - 'support_url' => 'https://support.lenovo.com', - 'image' => 'lenovo.jpg', - ]; -}); // 7 -$factory->state(App\Models\Manufacturer::class, 'lg', function ($faker) { - return [ - 'name' => 'LG', - 'url' => 'https://lg.com', - 'support_url' => 'https://support.lg.com', - 'image' => 'lg.jpg', - ]; -}); // 8 -$factory->state(App\Models\Manufacturer::class, 'polycom', function ($faker) { - return [ - 'name' => 'Polycom', - 'url' => 'https://polycom.com', - 'support_url' => 'https://support.polycom.com', - 'image' => 'polycom.png', - ]; -}); // 9 -$factory->state(App\Models\Manufacturer::class, 'adobe', function ($faker) { - return [ - 'name' => 'Adobe', - 'url' => 'https://adobe.com', - 'support_url' => 'https://support.adobe.com', - 'image' => 'adobe.jpg', - ]; -}); - // 10 -$factory->state(App\Models\Manufacturer::class, 'avery', function ($faker) { - return [ - 'name' => 'Avery', - 'url' => 'https://avery.com', - 'support_url' => 'https://support.avery.com', - 'image' => 'avery.png', - ]; -}); // 11 -$factory->state(App\Models\Manufacturer::class, 'crucial', function ($faker) { - return [ - 'name' => 'Crucial', - 'url' => 'https://crucial.com', - 'support_url' => 'https://support.crucial.com', - 'image' => 'crucial.jpg', - ]; -}); +class ManufacturerFactory extends Factory +{ + /** + * The name of the factory's corresponding model. + * + * @var string + */ + protected $model = \App\Models\Manufacturer::class; + /** + * Define the model's default state. + * + * @return array + */ + public function definition() + { + return [ + 'user_id' => 1, + 'support_phone' => $this->faker->phoneNumber(), + 'url' => $this->faker->url(), + 'support_email' => $this->faker->safeEmail(), + ]; + } + public function apple() + { + return $this->state(function () { + return [ + 'name' => 'Apple', + 'url' => 'https://apple.com', + 'support_url' => 'https://support.apple.com', + 'image' => 'apple.jpg', + ]; + }); + } + + public function microsoft() + { + return $this->state(function () { + return [ + 'name' => 'Microsoft', + 'url' => 'https://microsoft.com', + 'support_url' => 'https://support.microsoft.com', + 'image' => 'microsoft.png', + ]; + }); + } + + public function dell() + { + return $this->state(function () { + return [ + 'name' => 'Dell', + 'url' => 'https://dell.com', + 'support_url' => 'https://support.dell.com', + 'image' => 'dell.png', + ]; + }); + } + + public function asus() + { + return $this->state(function () { + return [ + 'name' => 'Asus', + 'url' => 'https://asus.com', + 'support_url' => 'https://support.asus.com', + 'image' => 'asus.png', + ]; + }); + } + + public function hp() + { + return $this->state(function () { + return [ + 'name' => 'HP', + 'url' => 'https://hp.com', + 'support_url' => 'https://support.hp.com', + 'image' => 'hp.png', + ]; + }); + } + + public function lenovo() + { + return $this->state(function () { + return [ + 'name' => 'Lenovo', + 'url' => 'https://lenovo.com', + 'support_url' => 'https://support.lenovo.com', + 'image' => 'lenovo.jpg', + ]; + }); + } + + public function lg() + { + return $this->state(function () { + return [ + 'name' => 'LG', + 'url' => 'https://lg.com', + 'support_url' => 'https://support.lg.com', + 'image' => 'lg.jpg', + ]; + }); + } + + public function polycom() + { + return $this->state(function () { + return [ + 'name' => 'Polycom', + 'url' => 'https://polycom.com', + 'support_url' => 'https://support.polycom.com', + 'image' => 'polycom.png', + ]; + }); + } + + public function adobe() + { + return $this->state(function () { + return [ + 'name' => 'Adobe', + 'url' => 'https://adobe.com', + 'support_url' => 'https://support.adobe.com', + 'image' => 'adobe.jpg', + ]; + }); + } + + public function avery() + { + return $this->state(function () { + return [ + 'name' => 'Avery', + 'url' => 'https://avery.com', + 'support_url' => 'https://support.avery.com', + 'image' => 'avery.png', + ]; + }); + } + + public function crucial() + { + return $this->state(function () { + return [ + 'name' => 'Crucial', + 'url' => 'https://crucial.com', + 'support_url' => 'https://support.crucial.com', + 'image' => 'crucial.jpg', + ]; + }); + } +} diff --git a/database/factories/ModelFactory.php b/database/factories/ModelFactory.php deleted file mode 100644 index ad903e33ba..0000000000 --- a/database/factories/ModelFactory.php +++ /dev/null @@ -1,101 +0,0 @@ -define(App\Models\Company::class, function (Faker\Generator $faker) { - return [ - 'name' => $faker->company, - ]; -}); - -$factory->define(App\Models\Component::class, function (Faker\Generator $faker) { - return [ - 'name' => $faker->text(20), - 'category_id' => function () { - return factory(App\Models\Category::class)->create()->id; - }, - 'location_id' => 1, - 'serial' => $faker->uuid, - 'qty' => $faker->numberBetween(3, 10), - 'order_number' => $faker->numberBetween(1000000, 50000000), - 'purchase_date' => $faker->dateTime(), - 'purchase_cost' => $faker->randomFloat(2), - 'min_amt' => $faker->numberBetween($min = 1, $max = 2), - 'company_id' => function () { - return factory(App\Models\Company::class)->create()->id; - }, - ]; -}); - -$factory->define(App\Models\Group::class, function (Faker\Generator $faker) { - return [ - 'name' => $faker->name, - ]; -}); - -$factory->define(App\Models\Location::class, function (Faker\Generator $faker) { - return [ - 'name' => $faker->city, - 'address' => $faker->streetAddress, - 'address2' => $faker->secondaryAddress, - 'city' => $faker->city, - 'state' => $faker->stateAbbr, - 'country' => $faker->countryCode, - 'currency' => $faker->currencyCode, - 'zip' => $faker->postcode, - 'image' => rand(1,9).'.jpg', - ]; -}); - - -$factory->define(App\Models\Supplier::class, function (Faker\Generator $faker) { - return [ - 'name' => $faker->company, - 'address' => $faker->streetAddress, - 'address2' => $faker->secondaryAddress, - 'city' => $faker->city, - 'state' => $faker->stateAbbr, - 'zip' => $faker->postCode, - 'country' => $faker->countryCode, - 'contact' => $faker->name, - 'phone' => $faker->phoneNumber, - 'fax' => $faker->phoneNumber, - 'email' => $faker->safeEmail, - 'url' => $faker->url, - 'notes' => $faker->text(191) // Supplier notes can be a max of 255 characters. - ]; -}); - -$factory->define(App\Models\Setting::class, function ($faker) { - return [ - 'user_id' => 1, - 'per_page' => 20, - 'site_name' => $faker->sentence, - 'auto_increment_assets' => false, - 'alert_email' => $faker->safeEmail(), - 'alerts_enabled' => true, - 'brand' => 1, - 'default_currency' => $faker->currencyCode, - 'locale' => $faker->locale, - 'pwd_secure_min' => 10, // Match web setup - 'email_domain' => 'test.com', - ]; -}); diff --git a/database/factories/SettingFactory.php b/database/factories/SettingFactory.php new file mode 100644 index 0000000000..d5858e1931 --- /dev/null +++ b/database/factories/SettingFactory.php @@ -0,0 +1,55 @@ + 1, + 'per_page' => 20, + 'site_name' => $this->faker->sentence, + 'auto_increment_assets' => false, + 'alert_email' => $this->faker->safeEmail(), + 'alerts_enabled' => true, + 'brand' => 1, + 'default_currency' => $this->faker->currencyCode, + 'locale' => $this->faker->locale, + 'pwd_secure_min' => 10, // Match web setup + 'email_domain' => 'test.com', + ]; + } +} diff --git a/database/factories/StatusLabelFactory.php b/database/factories/StatusLabelFactory.php deleted file mode 100644 index ac4d07d6e0..0000000000 --- a/database/factories/StatusLabelFactory.php +++ /dev/null @@ -1,67 +0,0 @@ -define(Statuslabel::class, function (Faker\Generator $faker) { - return [ - 'name' => $faker->sentence, - 'created_at' => $faker->dateTime(), - 'updated_at' => $faker->dateTime(), - 'user_id' => 1, - 'deleted_at' => null, - 'deployable' => 0, - 'pending' => 0, - 'archived' => 0, - 'notes' => '' - ]; -}); -$factory->state(Statuslabel::class, 'rtd', function (Faker\Generator $faker) { - return [ - 'notes' => $faker->sentence, - 'deployable' => 1, - 'default_label' => 1, - ]; -}); -$factory->state(Statuslabel::class, 'pending', function (Faker\Generator $faker) { - return [ - 'notes' => $faker->sentence, - 'pending' => 1, - 'default_label' => 1, - ]; -}); - -$factory->state(Statuslabel::class, 'archived', function (Faker\Generator $faker) { - return [ - 'notes' => 'These assets are permanently undeployable', - 'archived' => 1, - 'default_label' => 0, - ]; -}); - -$factory->state(Statuslabel::class, 'out_for_diagnostics', function (Faker\Generator $faker) { - return [ - 'name' => 'Out for Diagnostics', - 'default_label' => 0, - ]; -}); - -$factory->state(Statuslabel::class, 'out_for_repair', function (Faker\Generator $faker) { - return [ - 'name' => 'Out for Repair', - 'default_label' => 0, - ]; -}); - -$factory->state(Statuslabel::class, 'broken', function (Faker\Generator $faker) { - return [ - 'name' => 'Broken - Not Fixable', - 'default_label' => 0, - ]; -}); - -$factory->state(Statuslabel::class, 'lost', function (Faker\Generator $faker) { - return [ - 'name' => 'Lost/Stolen', - 'default_label' => 0, - ]; -}); diff --git a/database/factories/StatuslabelFactory.php b/database/factories/StatuslabelFactory.php new file mode 100644 index 0000000000..051e8131ee --- /dev/null +++ b/database/factories/StatuslabelFactory.php @@ -0,0 +1,109 @@ + $this->faker->sentence, + 'created_at' => $this->faker->dateTime(), + 'updated_at' => $this->faker->dateTime(), + 'user_id' => 1, + 'deleted_at' => null, + 'deployable' => 0, + 'pending' => 0, + 'archived' => 0, + 'notes' => '', + ]; + } + + public function rtd() + { + return $this->state(function () { + return [ + 'notes' => $this->faker->sentence, + 'deployable' => 1, + 'default_label' => 1, + ]; + }); + } + + public function pending() + { + return $this->state(function () { + return [ + 'notes' => $this->faker->sentence, + 'pending' => 1, + 'default_label' => 1, + ]; + }); + } + + public function archived() + { + return $this->state(function () { + return [ + 'notes' => 'These assets are permanently undeployable', + 'archived' => 1, + 'default_label' => 0, + ]; + }); + } + + public function outForDiagnostics() + { + return $this->state(function () { + return [ + 'name' => 'Out for Diagnostics', + 'default_label' => 0, + ]; + }); + } + + public function outForRepair() + { + return $this->state(function () { + return [ + 'name' => 'Out for Repair', + 'default_label' => 0, + ]; + }); + } + + public function broken() + { + return $this->state(function () { + return [ + 'name' => 'Broken - Not Fixable', + 'default_label' => 0, + ]; + }); + } + + public function lost() + { + return $this->state(function () { + return [ + 'name' => 'Lost/Stolen', + 'default_label' => 0, + ]; + }); + } +} diff --git a/database/factories/SupplierFactory.php b/database/factories/SupplierFactory.php new file mode 100644 index 0000000000..344dfe7d5b --- /dev/null +++ b/database/factories/SupplierFactory.php @@ -0,0 +1,57 @@ + $this->faker->company, + 'address' => $this->faker->streetAddress, + 'address2' => $this->faker->secondaryAddress, + 'city' => $this->faker->city, + 'state' => $this->faker->stateAbbr, + 'zip' => $this->faker->postCode, + 'country' => $this->faker->countryCode, + 'contact' => $this->faker->name, + 'phone' => $this->faker->phoneNumber, + 'fax' => $this->faker->phoneNumber, + 'email' => $this->faker->safeEmail, + 'url' => $this->faker->url, + 'notes' => $this->faker->text(191), // Supplier notes can be a max of 255 characters. + ]; + } +} diff --git a/database/factories/UserFactory.php b/database/factories/UserFactory.php index a26897817c..86681f2598 100644 --- a/database/factories/UserFactory.php +++ b/database/factories/UserFactory.php @@ -1,280 +1,408 @@ define(App\Models\User::class, function (Faker\Generator $faker) use ($password) { - return [ - 'activated' => 1, - 'address' => $faker->address, - 'city' => $faker->city, - 'company_id' => rand(1,4), - 'country' => $faker->country, - 'department_id' => rand(1,6), - 'email' => $faker->safeEmail, - 'employee_num' => $faker->numberBetween(3500, 35050), - 'first_name' => $faker->firstName, - 'jobtitle' => $faker->jobTitle, - 'last_name' => $faker->lastName, - 'locale' => $faker->locale, - 'location_id' => rand(1,5), - 'notes' => 'Created by DB seeder', - 'password' => $password, - 'permissions' => '{"user":"0"}', - 'phone' => $faker->phoneNumber, - 'state' => $faker->stateAbbr, - 'username' => $faker->username, - 'zip' => $faker->postcode - ]; -}); +use Illuminate\Database\Eloquent\Factories\Factory; -$factory->state(App\Models\User::class, 'first-admin', function ($faker) { - return [ - 'first_name' => 'Admin', - 'last_name' => 'User', - 'username' => 'admin', - 'permissions' => '{"superuser":"1"}', - ]; -}); +class UserFactory extends Factory +{ + /** + * The name of the factory's corresponding model. + * + * @var string + */ + protected $model = \App\Models\User::class; -$factory->state(App\Models\User::class, 'snipe-admin', function ($faker) { - return [ - 'first_name' => 'Snipe E.', - 'last_name' => 'Head', - 'username' => 'snipe', - 'email' => 'snipe@snipe.net', - 'permissions' => '{"superuser":"1"}', - ]; -}); + /** + * Define the model's default state. + * + * @return array + */ + public function definition() + { + $password = bcrypt('password'); + return [ + 'activated' => 1, + 'address' => $this->faker->address, + 'city' => $this->faker->city, + 'company_id' => rand(1, 4), + 'country' => $this->faker->country, + 'department_id' => rand(1, 6), + 'email' => $this->faker->safeEmail, + 'employee_num' => $this->faker->numberBetween(3500, 35050), + 'first_name' => $this->faker->firstName, + 'jobtitle' => $this->faker->jobTitle, + 'last_name' => $this->faker->lastName, + 'locale' => $this->faker->locale, + 'location_id' => rand(1, 5), + 'notes' => 'Created by DB seeder', + 'password' => $password, + 'permissions' => '{"user":"0"}', + 'phone' => $this->faker->phoneNumber, + 'state' => $this->faker->stateAbbr, + 'username' => $this->faker->username, + 'zip' => $this->faker->postcode, + ]; + } + public function firstAdmin() + { + return $this->state(function () { + return [ + 'first_name' => 'Admin', + 'last_name' => 'User', + 'username' => 'admin', + 'permissions' => '{"superuser":"1"}', + ]; + }); + } -// USER GLOBAL PERMISSION STATES -$factory->state(App\Models\User::class, 'superuser', function ($faker) { - return [ - 'permissions' => '{"superuser":"1"}', - ]; -}); + public function snipeAdmin() + { + return $this->state(function () { + return [ + 'first_name' => 'Snipe E.', + 'last_name' => 'Head', + 'username' => 'snipe', + 'email' => 'snipe@snipe.net', + 'permissions' => '{"superuser":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'admin', function ($faker) { - return [ - 'permissions' => '{"admin":"1"}', - 'manager_id' => rand(1,2), - ]; -}); -// USER ASSET PERMISSION STATES -$factory->state(App\Models\User::class, 'view-assets', function ($faker) { - return [ - 'permissions' => '{"assets.view":"1"}', - ]; -}); + public function superuser() + { + return $this->state(function () { + return [ + 'permissions' => '{"superuser":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'create-assets', function ($faker) { - return [ - 'permissions' => '{"assets.create":"1"}', - ]; -}); + public function admin() + { + return $this->state(function () { + return [ + 'permissions' => '{"admin":"1"}', + 'manager_id' => rand(1, 2), + ]; + }); + } -$factory->state(App\Models\User::class, 'edit-assets', function ($faker) { - return [ - 'permissions' => '{"assets.edit":"1"}', - ]; -}); + public function viewAssets() + { + return $this->state(function () { + return [ + 'permissions' => '{"assets.view":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'delete-assets', function ($faker) { - return [ - 'permissions' => '{"assets.delete":"1"}', - ]; -}); + public function createAssets() + { + return $this->state(function () { + return [ + 'permissions' => '{"assets.create":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'checkin-assets', function ($faker) { - return [ - 'permissions' => '{"assets.checkin":"1"}', - ]; -}); + public function editAssets() + { + return $this->state(function () { + return [ + 'permissions' => '{"assets.edit":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'checkout-assets', function ($faker) { - return [ - 'permissions' => '{"assets.checkout":"1"}', - ]; -}); + public function deleteAssets() + { + return $this->state(function () { + return [ + 'permissions' => '{"assets.delete":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'view-requestable-assets', function ($faker) { - return [ - 'permissions' => '{"assets.view.requestable":"1"}', - ]; -}); + public function checkinAssets() + { + return $this->state(function () { + return [ + 'permissions' => '{"assets.checkin":"1"}', + ]; + }); + } -// USER ACCESSORY PERMISSION STATES -$factory->state(App\Models\User::class, 'view-accessories', function ($faker) { - return [ - 'permissions' => '{"accessories.view":"1"}', - ]; -}); + public function checkoutAssets() + { + return $this->state(function () { + return [ + 'permissions' => '{"assets.checkout":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'create-accessories', function ($faker) { - return [ - 'permissions' => '{"accessories.create":"1"}', - ]; -}); + public function viewRequestableAssets() + { + return $this->state(function () { + return [ + 'permissions' => '{"assets.view.requestable":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'edit-accessories', function ($faker) { - return [ - 'permissions' => '{"accessories.edit":"1"}', - ]; -}); + public function viewAccessories() + { + return $this->state(function () { + return [ + 'permissions' => '{"accessories.view":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'delete-accessories', function ($faker) { - return [ - 'permissions' => '{"accessories.delete":"1"}', - ]; -}); + public function createAccessories() + { + return $this->state(function () { + return [ + 'permissions' => '{"accessories.create":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'checkin-accessories', function ($faker) { - return [ - 'permissions' => '{"accessories.checkin":"1"}', - ]; -}); + public function editAccessories() + { + return $this->state(function () { + return [ + 'permissions' => '{"accessories.edit":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'checkout-accessories', function ($faker) { - return [ - 'permissions' => '{"accessories.checkout":"1"}', - ]; -}); + public function deleteAccessories() + { + return $this->state(function () { + return [ + 'permissions' => '{"accessories.delete":"1"}', + ]; + }); + } -// USER CONSUMABLE PERMISSION STATES -$factory->state(App\Models\User::class, 'view-consumables', function ($faker) { - return [ - 'permissions' => '{"consumables.view":"1"}', - ]; -}); + public function checkinAccessories() + { + return $this->state(function () { + return [ + 'permissions' => '{"accessories.checkin":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'create-consumables', function ($faker) { - return [ - 'permissions' => '{"consumables.create":"1"}', - ]; -}); + public function checkoutAccessories() + { + return $this->state(function () { + return [ + 'permissions' => '{"accessories.checkout":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'edit-consumables', function ($faker) { - return [ - 'permissions' => '{"consumables.edit":"1"}', - ]; -}); + public function viewConsumables() + { + return $this->state(function () { + return [ + 'permissions' => '{"consumables.view":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'delete-consumables', function ($faker) { - return [ - 'permissions' => '{"consumables.delete":"1"}', - ]; -}); + public function createConsumables() + { + return $this->state(function () { + return [ + 'permissions' => '{"consumables.create":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'checkin-consumables', function ($faker) { - return [ - 'permissions' => '{"consumables.checkin":"1"}', - ]; -}); + public function editConsumables() + { + return $this->state(function () { + return [ + 'permissions' => '{"consumables.edit":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'checkout-consumables', function ($faker) { - return [ - 'permissions' => '{"consumables.checkout":"1"}', - ]; -}); + public function deleteConsumables() + { + return $this->state(function () { + return [ + 'permissions' => '{"consumables.delete":"1"}', + ]; + }); + } -// USER LICENSE PERMISSION STATES -$factory->state(App\Models\User::class, 'view-licenses', function ($faker) { - return [ - 'permissions' => '{"licenses.view":"1"}', - ]; -}); + public function checkinConsumables() + { + return $this->state(function () { + return [ + 'permissions' => '{"consumables.checkin":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'create-licenses', function ($faker) { - return [ - 'permissions' => '{"licenses.create":"1"}', - ]; -}); + public function checkoutConsumables() + { + return $this->state(function () { + return [ + 'permissions' => '{"consumables.checkout":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'edit-licenses', function ($faker) { - return [ - 'permissions' => '{"licenses.edit":"1"}', - ]; -}); + public function viewLicenses() + { + return $this->state(function () { + return [ + 'permissions' => '{"licenses.view":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'delete-licenses', function ($faker) { - return [ - 'permissions' => '{"licenses.delete":"1"}', - ]; -}); + public function createLicenses() + { + return $this->state(function () { + return [ + 'permissions' => '{"licenses.create":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'checkout-licenses', function ($faker) { - return [ - 'permissions' => '{"licenses.checkout":"1"}', - ]; -}); + public function editLicenses() + { + return $this->state(function () { + return [ + 'permissions' => '{"licenses.edit":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'view-keys-licenses', function ($faker) { - return [ - 'permissions' => '{"licenses.keys":"1"}', - ]; -}); + public function deleteLicenses() + { + return $this->state(function () { + return [ + 'permissions' => '{"licenses.delete":"1"}', + ]; + }); + } -// USER COMPONENTS PERMISSION STATES -$factory->state(App\Models\User::class, 'view-components', function ($faker) { - return [ - 'permissions' => '{"components.view":"1"}', - ]; -}); + public function checkoutLicenses() + { + return $this->state(function () { + return [ + 'permissions' => '{"licenses.checkout":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'create-components', function ($faker) { - return [ - 'permissions' => '{"components.create":"1"}', - ]; -}); + public function viewKeysLicenses() + { + return $this->state(function () { + return [ + 'permissions' => '{"licenses.keys":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'edit-components', function ($faker) { - return [ - 'permissions' => '{"components.edit":"1"}', - ]; -}); + public function viewComponents() + { + return $this->state(function () { + return [ + 'permissions' => '{"components.view":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'delete-components', function ($faker) { - return [ - 'permissions' => '{"components.delete":"1"}', - ]; -}); + public function createComponents() + { + return $this->state(function () { + return [ + 'permissions' => '{"components.create":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'checkin-components', function ($faker) { - return [ - 'permissions' => '{"components.checkin":"1"}', - ]; -}); + public function editComponents() + { + return $this->state(function () { + return [ + 'permissions' => '{"components.edit":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'checkout-components', function ($faker) { - return [ - 'permissions' => '{"components.checkout":"1"}', - ]; -}); + public function deleteComponents() + { + return $this->state(function () { + return [ + 'permissions' => '{"components.delete":"1"}', + ]; + }); + } -// USER USER PERMISSION STATES -$factory->state(App\Models\User::class, 'view-users', function ($faker) { - return [ - 'permissions' => '{"users.view":"1"}', - ]; -}); + public function checkinComponents() + { + return $this->state(function () { + return [ + 'permissions' => '{"components.checkin":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'create-users', function ($faker) { - return [ - 'permissions' => '{"users.create":"1"}', - ]; -}); + public function checkoutComponents() + { + return $this->state(function () { + return [ + 'permissions' => '{"components.checkout":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'edit-users', function ($faker) { - return [ - 'permissions' => '{"users.edit":"1"}', - ]; -}); + public function viewUsers() + { + return $this->state(function () { + return [ + 'permissions' => '{"users.view":"1"}', + ]; + }); + } -$factory->state(App\Models\User::class, 'delete-users', function ($faker) { - return [ - 'permissions' => '{"users.delete":"1"}', - ]; -}); + public function createUsers() + { + return $this->state(function () { + return [ + 'permissions' => '{"users.create":"1"}', + ]; + }); + } + + public function editUsers() + { + return $this->state(function () { + return [ + 'permissions' => '{"users.edit":"1"}', + ]; + }); + } + + public function deleteUsers() + { + return $this->state(function () { + return [ + 'permissions' => '{"users.delete":"1"}', + ]; + }); + } +} diff --git a/database/migrations/2012_12_06_225921_migration_cartalyst_sentry_install_users.php b/database/migrations/2012_12_06_225921_migration_cartalyst_sentry_install_users.php index bee5d9370c..c4518f7926 100644 --- a/database/migrations/2012_12_06_225921_migration_cartalyst_sentry_install_users.php +++ b/database/migrations/2012_12_06_225921_migration_cartalyst_sentry_install_users.php @@ -10,7 +10,6 @@ * bundled with this package in the LICENSE file. It is also available at * the following URL: http://www.opensource.org/licenses/BSD-3-Clause * - * @package Sentry * @version 2.0.0 * @author Cartalyst LLC * @license BSD License (3-clause) @@ -20,48 +19,46 @@ use Illuminate\Database\Migrations\Migration; -class MigrationCartalystSentryInstallUsers extends Migration { +class MigrationCartalystSentryInstallUsers extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('users', function ($table) { + $table->increments('id'); + $table->string('email'); + $table->string('password'); + $table->text('permissions')->nullable(); + $table->boolean('activated')->default(0); + $table->string('activation_code')->nullable(); + $table->timestamp('activated_at')->nullable(); + $table->timestamp('last_login')->nullable(); + $table->string('persist_code')->nullable(); + $table->string('reset_password_code')->nullable(); + $table->string('first_name')->nullable(); + $table->string('last_name')->nullable(); + $table->timestamps(); - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('users', function($table) - { - $table->increments('id'); - $table->string('email'); - $table->string('password'); - $table->text('permissions')->nullable(); - $table->boolean('activated')->default(0); - $table->string('activation_code')->nullable(); - $table->timestamp('activated_at')->nullable(); - $table->timestamp('last_login')->nullable(); - $table->string('persist_code')->nullable(); - $table->string('reset_password_code')->nullable(); - $table->string('first_name')->nullable(); - $table->string('last_name')->nullable(); - $table->timestamps(); - - // We'll need to ensure that MySQL uses the InnoDB engine to - // support the indexes, other engines aren't affected. - $table->engine = 'InnoDB'; - $table->unique('email'); - $table->index('activation_code'); - $table->index('reset_password_code'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::drop('users'); - } + // We'll need to ensure that MySQL uses the InnoDB engine to + // support the indexes, other engines aren't affected. + $table->engine = 'InnoDB'; + $table->unique('email'); + $table->index('activation_code'); + $table->index('reset_password_code'); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('users'); + } } diff --git a/database/migrations/2012_12_06_225929_migration_cartalyst_sentry_install_groups.php b/database/migrations/2012_12_06_225929_migration_cartalyst_sentry_install_groups.php index d929a62707..cd45847bc7 100644 --- a/database/migrations/2012_12_06_225929_migration_cartalyst_sentry_install_groups.php +++ b/database/migrations/2012_12_06_225929_migration_cartalyst_sentry_install_groups.php @@ -10,7 +10,6 @@ * bundled with this package in the LICENSE file. It is also available at * the following URL: http://www.opensource.org/licenses/BSD-3-Clause * - * @package Sentry * @version 2.0.0 * @author Cartalyst LLC * @license BSD License (3-clause) @@ -20,33 +19,31 @@ use Illuminate\Database\Migrations\Migration; -class MigrationCartalystSentryInstallGroups extends Migration { - - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('permission_groups', function($table) - { - $table->increments('id'); - $table->string('name'); - $table->text('permissions')->nullable(); - $table->timestamps(); - $table->engine = 'InnoDB'; - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::drop('permission_groups'); - } +class MigrationCartalystSentryInstallGroups extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('permission_groups', function ($table) { + $table->increments('id'); + $table->string('name'); + $table->text('permissions')->nullable(); + $table->timestamps(); + $table->engine = 'InnoDB'; + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('permission_groups'); + } } diff --git a/database/migrations/2012_12_06_225945_migration_cartalyst_sentry_install_users_groups_pivot.php b/database/migrations/2012_12_06_225945_migration_cartalyst_sentry_install_users_groups_pivot.php index 012873c6c0..d5ecbe35dd 100644 --- a/database/migrations/2012_12_06_225945_migration_cartalyst_sentry_install_users_groups_pivot.php +++ b/database/migrations/2012_12_06_225945_migration_cartalyst_sentry_install_users_groups_pivot.php @@ -10,7 +10,6 @@ * bundled with this package in the LICENSE file. It is also available at * the following URL: http://www.opensource.org/licenses/BSD-3-Clause * - * @package Sentry * @version 2.0.0 * @author Cartalyst LLC * @license BSD License (3-clause) @@ -20,35 +19,33 @@ use Illuminate\Database\Migrations\Migration; -class MigrationCartalystSentryInstallUsersGroupsPivot extends Migration { +class MigrationCartalystSentryInstallUsersGroupsPivot extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('users_groups', function ($table) { + $table->integer('user_id')->unsigned(); + $table->integer('group_id')->unsigned(); - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('users_groups', function($table) - { - $table->integer('user_id')->unsigned(); - $table->integer('group_id')->unsigned(); - - // We'll need to ensure that MySQL uses the InnoDB engine to - // support the indexes, other engines aren't affected. - $table->engine = 'InnoDB'; - $table->primary(array('user_id', 'group_id')); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::drop('users_groups'); - } + // We'll need to ensure that MySQL uses the InnoDB engine to + // support the indexes, other engines aren't affected. + $table->engine = 'InnoDB'; + $table->primary(['user_id', 'group_id']); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('users_groups'); + } } diff --git a/database/migrations/2012_12_06_225988_migration_cartalyst_sentry_install_throttle.php b/database/migrations/2012_12_06_225988_migration_cartalyst_sentry_install_throttle.php index 07c1d27a68..641e3187b5 100644 --- a/database/migrations/2012_12_06_225988_migration_cartalyst_sentry_install_throttle.php +++ b/database/migrations/2012_12_06_225988_migration_cartalyst_sentry_install_throttle.php @@ -10,7 +10,6 @@ * bundled with this package in the LICENSE file. It is also available at * the following URL: http://www.opensource.org/licenses/BSD-3-Clause * - * @package Sentry * @version 2.0.0 * @author Cartalyst LLC * @license BSD License (3-clause) @@ -20,42 +19,40 @@ use Illuminate\Database\Migrations\Migration; -class MigrationCartalystSentryInstallThrottle extends Migration { +class MigrationCartalystSentryInstallThrottle extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('throttle', function ($table) { + $table->increments('id'); + $table->integer('user_id')->unsigned()->nullable(); + $table->string('ip_address')->nullable(); + $table->integer('attempts')->default(0); + $table->boolean('suspended')->default(0); + $table->boolean('banned')->default(0); + $table->timestamp('last_attempt_at')->nullable(); + $table->timestamp('suspended_at')->nullable(); + $table->timestamp('banned_at')->nullable(); - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('throttle', function($table) - { - $table->increments('id'); - $table->integer('user_id')->unsigned()->nullable(); - $table->string('ip_address')->nullable(); - $table->integer('attempts')->default(0); - $table->boolean('suspended')->default(0); - $table->boolean('banned')->default(0); - $table->timestamp('last_attempt_at')->nullable(); - $table->timestamp('suspended_at')->nullable(); - $table->timestamp('banned_at')->nullable(); - - // We'll need to ensure that MySQL uses the InnoDB engine to - // support the indexes, other engines aren't affected. - $table->engine = 'InnoDB'; - $table->index('user_id'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::drop('throttle'); - } + // We'll need to ensure that MySQL uses the InnoDB engine to + // support the indexes, other engines aren't affected. + $table->engine = 'InnoDB'; + $table->index('user_id'); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('throttle'); + } } diff --git a/database/migrations/2013_03_23_193214_update_users_table.php b/database/migrations/2013_03_23_193214_update_users_table.php index eed98d12ee..9c95a0c858 100755 --- a/database/migrations/2013_03_23_193214_update_users_table.php +++ b/database/migrations/2013_03_23_193214_update_users_table.php @@ -32,5 +32,4 @@ class UpdateUsersTable extends Migration $table->dropColumn('deleted_at', 'website', 'country', 'gravatar'); }); } - } diff --git a/database/migrations/2013_11_13_075318_create_models_table.php b/database/migrations/2013_11_13_075318_create_models_table.php index 393cbcf9a1..cd2d9dfc70 100755 --- a/database/migrations/2013_11_13_075318_create_models_table.php +++ b/database/migrations/2013_11_13_075318_create_models_table.php @@ -11,7 +11,7 @@ class CreateModelsTable extends Migration */ public function up() { - Schema::create('models', function ($table) { + Schema::create('models', function ($table) { $table->increments('id'); $table->string('name'); $table->string('modelno')->nullable(); @@ -31,5 +31,4 @@ class CreateModelsTable extends Migration { Schema::drop('models'); } - } diff --git a/database/migrations/2013_11_13_075335_create_categories_table.php b/database/migrations/2013_11_13_075335_create_categories_table.php index bb64d87cb0..280c2f48a8 100755 --- a/database/migrations/2013_11_13_075335_create_categories_table.php +++ b/database/migrations/2013_11_13_075335_create_categories_table.php @@ -4,7 +4,7 @@ use Illuminate\Database\Migrations\Migration; class CreateCategoriesTable extends Migration { -/** + /** * Run the migrations. * * @return void @@ -29,5 +29,4 @@ class CreateCategoriesTable extends Migration { Schema::drop('categories'); } - } diff --git a/database/migrations/2013_11_13_075347_create_manufacturers_table.php b/database/migrations/2013_11_13_075347_create_manufacturers_table.php index 3f2426ea6d..827ee7da7c 100755 --- a/database/migrations/2013_11_13_075347_create_manufacturers_table.php +++ b/database/migrations/2013_11_13_075347_create_manufacturers_table.php @@ -28,5 +28,4 @@ class CreateManufacturersTable extends Migration { Schema::drop('manufacturers'); } - } diff --git a/database/migrations/2013_11_15_015858_add_user_id_to_categories.php b/database/migrations/2013_11_15_015858_add_user_id_to_categories.php index a4744877ba..935362ab52 100755 --- a/database/migrations/2013_11_15_015858_add_user_id_to_categories.php +++ b/database/migrations/2013_11_15_015858_add_user_id_to_categories.php @@ -25,5 +25,4 @@ class AddUserIdToCategories extends Migration { // } - } diff --git a/database/migrations/2013_11_15_112701_add_user_id_to_manufacturers.php b/database/migrations/2013_11_15_112701_add_user_id_to_manufacturers.php index a21ad59277..fee43b0ba8 100755 --- a/database/migrations/2013_11_15_112701_add_user_id_to_manufacturers.php +++ b/database/migrations/2013_11_15_112701_add_user_id_to_manufacturers.php @@ -25,5 +25,4 @@ class AddUserIdToManufacturers extends Migration { // } - } diff --git a/database/migrations/2013_11_15_190327_create_assets_table.php b/database/migrations/2013_11_15_190327_create_assets_table.php index 12f906fa27..a66a933025 100755 --- a/database/migrations/2013_11_15_190327_create_assets_table.php +++ b/database/migrations/2013_11_15_190327_create_assets_table.php @@ -38,5 +38,4 @@ class CreateAssetsTable extends Migration { Schema::drop('assets'); } - } diff --git a/database/migrations/2013_11_15_190357_create_licenses_table.php b/database/migrations/2013_11_15_190357_create_licenses_table.php index d6e01cac39..848315ef39 100755 --- a/database/migrations/2013_11_15_190357_create_licenses_table.php +++ b/database/migrations/2013_11_15_190357_create_licenses_table.php @@ -12,20 +12,20 @@ class CreateLicensesTable extends Migration public function up() { Schema::create('licenses', function ($table) { - $table->increments('id'); - $table->string('name'); - $table->integer('model_id'); - $table->text('serial'); - $table->string('license_email'); - $table->string('license_name'); - $table->date('purchase_date')->nullable(); - $table->decimal('purchase_cost', 8, 2)->nullable(); - $table->string('order_number'); - $table->integer('assigned_to'); - $table->text('notes'); - $table->integer('user_id')->nullable(); - $table->timestamps(); - $table->engine = 'InnoDB'; + $table->increments('id'); + $table->string('name'); + $table->integer('model_id'); + $table->text('serial'); + $table->string('license_email'); + $table->string('license_name'); + $table->date('purchase_date')->nullable(); + $table->decimal('purchase_cost', 8, 2)->nullable(); + $table->string('order_number'); + $table->integer('assigned_to'); + $table->text('notes'); + $table->integer('user_id')->nullable(); + $table->timestamps(); + $table->engine = 'InnoDB'; }); } @@ -38,5 +38,4 @@ class CreateLicensesTable extends Migration { Schema::dropIfExists('licenses'); } - } diff --git a/database/migrations/2013_11_15_201848_add_license_name_to_licenses.php b/database/migrations/2013_11_15_201848_add_license_name_to_licenses.php index 50b0a1ff05..f9094c4f02 100755 --- a/database/migrations/2013_11_15_201848_add_license_name_to_licenses.php +++ b/database/migrations/2013_11_15_201848_add_license_name_to_licenses.php @@ -11,7 +11,6 @@ class AddLicenseNameToLicenses extends Migration */ public function up() { - } /** @@ -23,5 +22,4 @@ class AddLicenseNameToLicenses extends Migration { // } - } diff --git a/database/migrations/2013_11_16_040323_create_depreciations_table.php b/database/migrations/2013_11_16_040323_create_depreciations_table.php index 620b5299a4..b35a04fee3 100755 --- a/database/migrations/2013_11_16_040323_create_depreciations_table.php +++ b/database/migrations/2013_11_16_040323_create_depreciations_table.php @@ -31,5 +31,4 @@ class CreateDepreciationsTable extends Migration { Schema::drop('depreciations'); } - } diff --git a/database/migrations/2013_11_16_042851_add_depreciation_id_to_models.php b/database/migrations/2013_11_16_042851_add_depreciation_id_to_models.php index a9e9dbd496..0e5e0db18a 100755 --- a/database/migrations/2013_11_16_042851_add_depreciation_id_to_models.php +++ b/database/migrations/2013_11_16_042851_add_depreciation_id_to_models.php @@ -25,5 +25,4 @@ class AddDepreciationIdToModels extends Migration { // } - } diff --git a/database/migrations/2013_11_16_084923_add_user_id_to_models.php b/database/migrations/2013_11_16_084923_add_user_id_to_models.php index b14f40be2e..070a5feb9f 100755 --- a/database/migrations/2013_11_16_084923_add_user_id_to_models.php +++ b/database/migrations/2013_11_16_084923_add_user_id_to_models.php @@ -25,5 +25,4 @@ class AddUserIdToModels extends Migration { // } - } diff --git a/database/migrations/2013_11_16_103258_create_locations_table.php b/database/migrations/2013_11_16_103258_create_locations_table.php index d87a273e35..2bbc1cce4f 100755 --- a/database/migrations/2013_11_16_103258_create_locations_table.php +++ b/database/migrations/2013_11_16_103258_create_locations_table.php @@ -15,8 +15,8 @@ class CreateLocationsTable extends Migration $table->increments('id'); $table->string('name')->nullable(); $table->string('city')->nullable(); - $table->string('state',2)->nullable(); - $table->string('country',2)->nullable(); + $table->string('state', 2)->nullable(); + $table->string('country', 2)->nullable(); $table->timestamps(); $table->integer('user_id')->nullable(); $table->engine = 'InnoDB'; @@ -32,5 +32,4 @@ class CreateLocationsTable extends Migration { Schema::drop('locations'); } - } diff --git a/database/migrations/2013_11_16_103336_add_location_id_to_assets.php b/database/migrations/2013_11_16_103336_add_location_id_to_assets.php index fbaee98b3e..11c462ec92 100755 --- a/database/migrations/2013_11_16_103336_add_location_id_to_assets.php +++ b/database/migrations/2013_11_16_103336_add_location_id_to_assets.php @@ -25,5 +25,4 @@ class AddLocationIdToAssets extends Migration { // } - } diff --git a/database/migrations/2013_11_16_103407_add_checkedout_to_to_assets.php b/database/migrations/2013_11_16_103407_add_checkedout_to_to_assets.php index 8fdb112f03..9e3594b746 100755 --- a/database/migrations/2013_11_16_103407_add_checkedout_to_to_assets.php +++ b/database/migrations/2013_11_16_103407_add_checkedout_to_to_assets.php @@ -25,5 +25,4 @@ class AddCheckedoutToToAssets extends Migration { // } - } diff --git a/database/migrations/2013_11_16_103425_create_history_table.php b/database/migrations/2013_11_16_103425_create_history_table.php index 3e5d6ba84d..d3d84f3843 100755 --- a/database/migrations/2013_11_16_103425_create_history_table.php +++ b/database/migrations/2013_11_16_103425_create_history_table.php @@ -30,5 +30,4 @@ class CreateHistoryTable extends Migration { //Schema::drop('history'); } - } diff --git a/database/migrations/2013_11_17_054359_drop_licenses_table.php b/database/migrations/2013_11_17_054359_drop_licenses_table.php index 353dcc6944..6fbc11703b 100755 --- a/database/migrations/2013_11_17_054359_drop_licenses_table.php +++ b/database/migrations/2013_11_17_054359_drop_licenses_table.php @@ -23,5 +23,4 @@ class DropLicensesTable extends Migration { // } - } diff --git a/database/migrations/2013_11_17_054526_add_physical_to_assets.php b/database/migrations/2013_11_17_054526_add_physical_to_assets.php index 725d1e900b..2ccc7c43dc 100755 --- a/database/migrations/2013_11_17_054526_add_physical_to_assets.php +++ b/database/migrations/2013_11_17_054526_add_physical_to_assets.php @@ -1,6 +1,7 @@ dropColumn('physical'); } - } diff --git a/database/migrations/2013_11_17_055126_create_settings_table.php b/database/migrations/2013_11_17_055126_create_settings_table.php index 0bedd659bf..5e36add8c0 100755 --- a/database/migrations/2013_11_17_055126_create_settings_table.php +++ b/database/migrations/2013_11_17_055126_create_settings_table.php @@ -31,5 +31,4 @@ class CreateSettingsTable extends Migration { Schema::drop('settings'); } - } diff --git a/database/migrations/2013_11_17_062634_add_license_to_assets.php b/database/migrations/2013_11_17_062634_add_license_to_assets.php index 7766b34f2c..fbc81fae1e 100755 --- a/database/migrations/2013_11_17_062634_add_license_to_assets.php +++ b/database/migrations/2013_11_17_062634_add_license_to_assets.php @@ -26,5 +26,4 @@ class AddLicenseToAssets extends Migration { // } - } diff --git a/database/migrations/2013_11_18_134332_add_contacts_to_users.php b/database/migrations/2013_11_18_134332_add_contacts_to_users.php index bf6d482d37..acff0b75a5 100755 --- a/database/migrations/2013_11_18_134332_add_contacts_to_users.php +++ b/database/migrations/2013_11_18_134332_add_contacts_to_users.php @@ -15,7 +15,6 @@ class AddContactsToUsers extends Migration $table->integer('location_id')->nullable(); $table->string('phone')->nullable(); $table->string('jobtitle')->nullable(); - }); } @@ -30,9 +29,6 @@ class AddContactsToUsers extends Migration $table->dropColumn('location_id'); $table->dropColumn('phone'); $table->dropColumn('jobtitle'); - }); - } - } diff --git a/database/migrations/2013_11_18_142847_add_info_to_locations.php b/database/migrations/2013_11_18_142847_add_info_to_locations.php index 07f85b6116..9cd240a0bf 100755 --- a/database/migrations/2013_11_18_142847_add_info_to_locations.php +++ b/database/migrations/2013_11_18_142847_add_info_to_locations.php @@ -12,11 +12,9 @@ class AddInfoToLocations extends Migration public function up() { Schema::table('locations', function ($table) { - $table->string('address', 80)->nullable(); $table->string('address2', 80)->nullable(); $table->string('zip', 10)->nullable(); - }); } @@ -28,12 +26,9 @@ class AddInfoToLocations extends Migration public function down() { Schema::table('locations', function ($table) { - $table->dropColumn('address'); $table->dropColumn('address2'); $table->dropColumn('zip'); - }); } - } diff --git a/database/migrations/2013_11_18_152942_remove_location_id_from_asset.php b/database/migrations/2013_11_18_152942_remove_location_id_from_asset.php index 07ef525fe4..f7450cdb59 100755 --- a/database/migrations/2013_11_18_152942_remove_location_id_from_asset.php +++ b/database/migrations/2013_11_18_152942_remove_location_id_from_asset.php @@ -27,5 +27,4 @@ class RemoveLocationIdFromAsset extends Migration $table->integer('location_id')->nullable(); }); } - } diff --git a/database/migrations/2013_11_18_164423_set_nullvalues_for_user.php b/database/migrations/2013_11_18_164423_set_nullvalues_for_user.php index 6665934587..6f52b47ee4 100755 --- a/database/migrations/2013_11_18_164423_set_nullvalues_for_user.php +++ b/database/migrations/2013_11_18_164423_set_nullvalues_for_user.php @@ -9,14 +9,12 @@ class SetNullvaluesForUser extends Migration * * @return void */ - public function up() { // - // $prefix = DB::getTablePrefix(); + // $prefix = DB::getTablePrefix(); // DB::statement('ALTER TABLE '.$prefix.'users MODIFY phone varchar(20) null'); // DB::statement('ALTER TABLE '.$prefix.'users MODIFY jobtitle varchar(50) null'); - } /** @@ -28,5 +26,4 @@ class SetNullvaluesForUser extends Migration { // } - } diff --git a/database/migrations/2013_11_19_013337_create_asset_logs_table.php b/database/migrations/2013_11_19_013337_create_asset_logs_table.php index 3bdf3f9bae..51aebacbd4 100755 --- a/database/migrations/2013_11_19_013337_create_asset_logs_table.php +++ b/database/migrations/2013_11_19_013337_create_asset_logs_table.php @@ -32,5 +32,4 @@ class CreateAssetLogsTable extends Migration { Schema::drop('asset_logs'); } - } diff --git a/database/migrations/2013_11_19_061409_edit_added_on_asset_logs_table.php b/database/migrations/2013_11_19_061409_edit_added_on_asset_logs_table.php index b1c8a848b3..57ce195e93 100755 --- a/database/migrations/2013_11_19_061409_edit_added_on_asset_logs_table.php +++ b/database/migrations/2013_11_19_061409_edit_added_on_asset_logs_table.php @@ -12,7 +12,6 @@ class EditAddedOnAssetLogsTable extends Migration public function up() { // DB::statement('ALTER TABLE ' . DB::getTablePrefix() . 'asset_logs MODIFY added_on timestamp null'); - } /** @@ -24,5 +23,4 @@ class EditAddedOnAssetLogsTable extends Migration { // } - } diff --git a/database/migrations/2013_11_19_062250_edit_location_id_asset_logs_table.php b/database/migrations/2013_11_19_062250_edit_location_id_asset_logs_table.php index 02d1118eea..9ea493b34e 100755 --- a/database/migrations/2013_11_19_062250_edit_location_id_asset_logs_table.php +++ b/database/migrations/2013_11_19_062250_edit_location_id_asset_logs_table.php @@ -16,8 +16,6 @@ class EditLocationIdAssetLogsTable extends Migration // $table->string('location_id')->nullable()->change(); // $table->dateTime('added_on',11)->nullable()->default(DB::raw('CURRENT_TIMESTAMP(0)'))->change(); // }); - - } /** @@ -29,5 +27,4 @@ class EditLocationIdAssetLogsTable extends Migration { // } - } diff --git a/database/migrations/2013_11_20_055822_add_soft_delete_on_assets.php b/database/migrations/2013_11_20_055822_add_soft_delete_on_assets.php index c729376383..2405878d5f 100755 --- a/database/migrations/2013_11_20_055822_add_soft_delete_on_assets.php +++ b/database/migrations/2013_11_20_055822_add_soft_delete_on_assets.php @@ -25,5 +25,4 @@ class AddSoftDeleteOnAssets extends Migration { // } - } diff --git a/database/migrations/2013_11_20_121404_add_soft_delete_on_locations.php b/database/migrations/2013_11_20_121404_add_soft_delete_on_locations.php index afdc9e2aa2..33a3577a9f 100755 --- a/database/migrations/2013_11_20_121404_add_soft_delete_on_locations.php +++ b/database/migrations/2013_11_20_121404_add_soft_delete_on_locations.php @@ -25,5 +25,4 @@ class AddSoftDeleteOnLocations extends Migration { // } - } diff --git a/database/migrations/2013_11_20_123137_add_soft_delete_on_manufacturers.php b/database/migrations/2013_11_20_123137_add_soft_delete_on_manufacturers.php index 04cb01d15d..0ba42701fa 100755 --- a/database/migrations/2013_11_20_123137_add_soft_delete_on_manufacturers.php +++ b/database/migrations/2013_11_20_123137_add_soft_delete_on_manufacturers.php @@ -25,5 +25,4 @@ class AddSoftDeleteOnManufacturers extends Migration { // } - } diff --git a/database/migrations/2013_11_20_123725_add_soft_delete_on_categories.php b/database/migrations/2013_11_20_123725_add_soft_delete_on_categories.php index a17045bf79..8da8d8dccb 100755 --- a/database/migrations/2013_11_20_123725_add_soft_delete_on_categories.php +++ b/database/migrations/2013_11_20_123725_add_soft_delete_on_categories.php @@ -25,5 +25,4 @@ class AddSoftDeleteOnCategories extends Migration { // } - } diff --git a/database/migrations/2013_11_20_130248_create_status_labels.php b/database/migrations/2013_11_20_130248_create_status_labels.php index 7bdfb8a6f6..5b7634682f 100755 --- a/database/migrations/2013_11_20_130248_create_status_labels.php +++ b/database/migrations/2013_11_20_130248_create_status_labels.php @@ -13,7 +13,7 @@ class CreateStatusLabels extends Migration { Schema::create('status_labels', function ($table) { $table->increments('id'); - $table->string('name',100)->nullable(); + $table->string('name', 100)->nullable(); $table->integer('user_id')->nullable(); $table->timestamps(); $table->softDeletes(); @@ -30,5 +30,4 @@ class CreateStatusLabels extends Migration { Schema::drop('status_labels'); } - } diff --git a/database/migrations/2013_11_20_130830_add_status_id_on_assets_table.php b/database/migrations/2013_11_20_130830_add_status_id_on_assets_table.php index 01b24c5a04..ac561efa71 100755 --- a/database/migrations/2013_11_20_130830_add_status_id_on_assets_table.php +++ b/database/migrations/2013_11_20_130830_add_status_id_on_assets_table.php @@ -27,5 +27,4 @@ class AddStatusIdOnAssetsTable extends Migration $table->dropColumn('status_id'); }); } - } diff --git a/database/migrations/2013_11_20_131544_add_status_type_on_status_labels.php b/database/migrations/2013_11_20_131544_add_status_type_on_status_labels.php index 2a8cfcd229..70ad31f9c4 100755 --- a/database/migrations/2013_11_20_131544_add_status_type_on_status_labels.php +++ b/database/migrations/2013_11_20_131544_add_status_type_on_status_labels.php @@ -27,5 +27,4 @@ class AddStatusTypeOnStatusLabels extends Migration $table->dropColumn('deployable'); }); } - } diff --git a/database/migrations/2013_11_20_134103_add_archived_to_assets.php b/database/migrations/2013_11_20_134103_add_archived_to_assets.php index 4623f67d7e..dd00382ac9 100755 --- a/database/migrations/2013_11_20_134103_add_archived_to_assets.php +++ b/database/migrations/2013_11_20_134103_add_archived_to_assets.php @@ -27,5 +27,4 @@ class AddArchivedToAssets extends Migration $table->dropColumn('archived'); }); } - } diff --git a/database/migrations/2013_11_21_002321_add_uploads_table.php b/database/migrations/2013_11_21_002321_add_uploads_table.php index d54d5e5d76..233416e2bc 100755 --- a/database/migrations/2013_11_21_002321_add_uploads_table.php +++ b/database/migrations/2013_11_21_002321_add_uploads_table.php @@ -32,5 +32,4 @@ class AddUploadsTable extends Migration { Schema::drop('asset_uploads'); } - } diff --git a/database/migrations/2013_11_21_024531_remove_deployable_boolean_from_status_labels.php b/database/migrations/2013_11_21_024531_remove_deployable_boolean_from_status_labels.php index 574c7bd8ec..3db9e2f1d3 100755 --- a/database/migrations/2013_11_21_024531_remove_deployable_boolean_from_status_labels.php +++ b/database/migrations/2013_11_21_024531_remove_deployable_boolean_from_status_labels.php @@ -27,5 +27,4 @@ class RemoveDeployableBooleanFromStatusLabels extends Migration $table->boolean('deployable'); }); } - } diff --git a/database/migrations/2013_11_22_075308_add_option_label_to_settings_table.php b/database/migrations/2013_11_22_075308_add_option_label_to_settings_table.php index 9e007850d0..803edfe1ee 100755 --- a/database/migrations/2013_11_22_075308_add_option_label_to_settings_table.php +++ b/database/migrations/2013_11_22_075308_add_option_label_to_settings_table.php @@ -27,5 +27,4 @@ class AddOptionLabelToSettingsTable extends Migration // $table->dropColumn('option_label'); // }); } - } diff --git a/database/migrations/2013_11_22_213400_edits_to_settings_table.php b/database/migrations/2013_11_22_213400_edits_to_settings_table.php index e689e5cd0a..942c82d3df 100755 --- a/database/migrations/2013_11_22_213400_edits_to_settings_table.php +++ b/database/migrations/2013_11_22_213400_edits_to_settings_table.php @@ -16,10 +16,8 @@ class EditsToSettingsTable extends Migration //$table->dropColumn('option_name'); // $table->dropColumn('option_value'); $table->integer('per_page')->default(20); - $table->string('site_name','100')->default("Snipe IT Asset Management"); + $table->string('site_name', '100')->default('Snipe IT Asset Management'); }); - - } /** @@ -31,5 +29,4 @@ class EditsToSettingsTable extends Migration { // } - } diff --git a/database/migrations/2013_11_25_013244_create_licenses_table.php b/database/migrations/2013_11_25_013244_create_licenses_table.php index 38c2f6f68e..404a37228b 100755 --- a/database/migrations/2013_11_25_013244_create_licenses_table.php +++ b/database/migrations/2013_11_25_013244_create_licenses_table.php @@ -39,5 +39,4 @@ class ReCreateLicensesTable extends Migration // Schema::drop('licenses'); } - } diff --git a/database/migrations/2013_11_25_031458_create_license_seats_table.php b/database/migrations/2013_11_25_031458_create_license_seats_table.php index acd101e3f8..466ef00870 100755 --- a/database/migrations/2013_11_25_031458_create_license_seats_table.php +++ b/database/migrations/2013_11_25_031458_create_license_seats_table.php @@ -33,5 +33,4 @@ class CreateLicenseSeatsTable extends Migration { // } - } diff --git a/database/migrations/2013_11_25_032022_add_type_to_actionlog_table.php b/database/migrations/2013_11_25_032022_add_type_to_actionlog_table.php index 4edfc94091..73fd422355 100755 --- a/database/migrations/2013_11_25_032022_add_type_to_actionlog_table.php +++ b/database/migrations/2013_11_25_032022_add_type_to_actionlog_table.php @@ -29,5 +29,4 @@ class AddTypeToActionlogTable extends Migration $table->dropColumn('asset_type'); }); } - } diff --git a/database/migrations/2013_11_25_033008_delete_bad_licenses_table.php b/database/migrations/2013_11_25_033008_delete_bad_licenses_table.php index 755b647228..91179fb7be 100755 --- a/database/migrations/2013_11_25_033008_delete_bad_licenses_table.php +++ b/database/migrations/2013_11_25_033008_delete_bad_licenses_table.php @@ -23,5 +23,4 @@ class DeleteBadLicensesTable extends Migration { // } - } diff --git a/database/migrations/2013_11_25_033131_create_new_licenses_table.php b/database/migrations/2013_11_25_033131_create_new_licenses_table.php index c852e0dc00..c56d0da77d 100755 --- a/database/migrations/2013_11_25_033131_create_new_licenses_table.php +++ b/database/migrations/2013_11_25_033131_create_new_licenses_table.php @@ -39,5 +39,4 @@ class CreateNewLicensesTable extends Migration // Schema::drop('licenses'); } - } diff --git a/database/migrations/2013_11_25_033534_add_licensed_to_licenses_table.php b/database/migrations/2013_11_25_033534_add_licensed_to_licenses_table.php index d51d88bceb..74297099ca 100755 --- a/database/migrations/2013_11_25_033534_add_licensed_to_licenses_table.php +++ b/database/migrations/2013_11_25_033534_add_licensed_to_licenses_table.php @@ -31,5 +31,4 @@ class AddLicensedToLicensesTable extends Migration $table->dropColumn('license_email'); }); } - } diff --git a/database/migrations/2013_11_25_101308_add_warrantee_to_assets_table.php b/database/migrations/2013_11_25_101308_add_warrantee_to_assets_table.php index e912aacf86..bbce108de2 100755 --- a/database/migrations/2013_11_25_101308_add_warrantee_to_assets_table.php +++ b/database/migrations/2013_11_25_101308_add_warrantee_to_assets_table.php @@ -29,5 +29,4 @@ class AddWarranteeToAssetsTable extends Migration $table->dropColumn('warrantee_months'); }); } - } diff --git a/database/migrations/2013_11_25_104343_alter_warranty_column_on_assets.php b/database/migrations/2013_11_25_104343_alter_warranty_column_on_assets.php index e0d994f5e5..be62374dce 100755 --- a/database/migrations/2013_11_25_104343_alter_warranty_column_on_assets.php +++ b/database/migrations/2013_11_25_104343_alter_warranty_column_on_assets.php @@ -12,7 +12,7 @@ class AlterWarrantyColumnOnAssets extends Migration public function up() { Schema::table('assets', function ($table) { - $table->renameColumn('warrantee_months', 'warranty_months'); + $table->renameColumn('warrantee_months', 'warranty_months'); }); } @@ -25,5 +25,4 @@ class AlterWarrantyColumnOnAssets extends Migration { // } - } diff --git a/database/migrations/2013_11_25_150450_drop_parent_from_categories.php b/database/migrations/2013_11_25_150450_drop_parent_from_categories.php index ba1949941a..665bc781f9 100755 --- a/database/migrations/2013_11_25_150450_drop_parent_from_categories.php +++ b/database/migrations/2013_11_25_150450_drop_parent_from_categories.php @@ -25,5 +25,4 @@ class DropParentFromCategories extends Migration { // } - } diff --git a/database/migrations/2013_11_25_151920_add_depreciate_to_assets.php b/database/migrations/2013_11_25_151920_add_depreciate_to_assets.php index 13e009bfd4..233392fe6e 100755 --- a/database/migrations/2013_11_25_151920_add_depreciate_to_assets.php +++ b/database/migrations/2013_11_25_151920_add_depreciate_to_assets.php @@ -14,7 +14,6 @@ class AddDepreciateToAssets extends Migration // Schema::table('assets', function ($table) { $table->boolean('depreciate')->nullable(); - }); } @@ -28,9 +27,5 @@ class AddDepreciateToAssets extends Migration Schema::table('assets', function ($table) { $table->dropColumn('depreciate'); }); - - - } - } diff --git a/database/migrations/2013_11_25_152903_add_depreciate_to_licenses_table.php b/database/migrations/2013_11_25_152903_add_depreciate_to_licenses_table.php index 1a2fbc05a0..bbe23a482f 100755 --- a/database/migrations/2013_11_25_152903_add_depreciate_to_licenses_table.php +++ b/database/migrations/2013_11_25_152903_add_depreciate_to_licenses_table.php @@ -27,9 +27,5 @@ class AddDepreciateToLicensesTable extends Migration Schema::table('licenses', function ($table) { $table->dropColumn('depreciate'); }); - - - } - } diff --git a/database/migrations/2013_11_26_211820_drop_license_from_assets_table.php b/database/migrations/2013_11_26_211820_drop_license_from_assets_table.php index 611cf4b123..5640c24261 100755 --- a/database/migrations/2013_11_26_211820_drop_license_from_assets_table.php +++ b/database/migrations/2013_11_26_211820_drop_license_from_assets_table.php @@ -26,5 +26,4 @@ class DropLicenseFromAssetsTable extends Migration { // } - } diff --git a/database/migrations/2013_11_27_062510_add_note_to_asset_logs_table.php b/database/migrations/2013_11_27_062510_add_note_to_asset_logs_table.php index de0d70a00f..90fa457183 100755 --- a/database/migrations/2013_11_27_062510_add_note_to_asset_logs_table.php +++ b/database/migrations/2013_11_27_062510_add_note_to_asset_logs_table.php @@ -14,7 +14,6 @@ class AddNoteToAssetLogsTable extends Migration // Schema::table('asset_logs', function ($table) { $table->text('note')->nullable(); - }); } @@ -30,5 +29,4 @@ class AddNoteToAssetLogsTable extends Migration $table->dropColumn('note'); }); } - } diff --git a/database/migrations/2013_12_01_113426_add_filename_to_asset_log.php b/database/migrations/2013_12_01_113426_add_filename_to_asset_log.php index 01b9e3130a..8a174dcb14 100755 --- a/database/migrations/2013_12_01_113426_add_filename_to_asset_log.php +++ b/database/migrations/2013_12_01_113426_add_filename_to_asset_log.php @@ -14,7 +14,6 @@ class AddFilenameToAssetLog extends Migration // Schema::table('asset_logs', function ($table) { $table->text('filename')->nullable(); - }); } @@ -30,5 +29,4 @@ class AddFilenameToAssetLog extends Migration $table->dropColumn('filename'); }); } - } diff --git a/database/migrations/2013_12_06_094618_add_nullable_to_licenses_table.php b/database/migrations/2013_12_06_094618_add_nullable_to_licenses_table.php index fed1b8e9de..24a7cfa674 100755 --- a/database/migrations/2013_12_06_094618_add_nullable_to_licenses_table.php +++ b/database/migrations/2013_12_06_094618_add_nullable_to_licenses_table.php @@ -11,13 +11,11 @@ class AddNullableToLicensesTable extends Migration */ public function up() { - Schema::table('licenses', function ($table) { - $table->string('order_number',50)->nullable()->change(); - $table->string('notes',255)->nullable()->change(); - $table->string('license_name',120)->nullable()->change(); - }); - - + Schema::table('licenses', function ($table) { + $table->string('order_number', 50)->nullable()->change(); + $table->string('notes', 255)->nullable()->change(); + $table->string('license_name', 120)->nullable()->change(); + }); } /** @@ -29,5 +27,4 @@ class AddNullableToLicensesTable extends Migration { // } - } diff --git a/database/migrations/2013_12_10_084038_add_eol_on_models_table.php b/database/migrations/2013_12_10_084038_add_eol_on_models_table.php index 5e873bebb1..d8d222deec 100755 --- a/database/migrations/2013_12_10_084038_add_eol_on_models_table.php +++ b/database/migrations/2013_12_10_084038_add_eol_on_models_table.php @@ -12,8 +12,7 @@ class AddEolOnModelsTable extends Migration public function up() { Schema::table('models', function ($table) { - $table->integer('eol')->nullable()->default(NULL); - + $table->integer('eol')->nullable()->default(null); }); } @@ -28,5 +27,4 @@ class AddEolOnModelsTable extends Migration $table->dropColumn('old'); }); } - } diff --git a/database/migrations/2013_12_12_055218_add_manager_to_users_table.php b/database/migrations/2013_12_12_055218_add_manager_to_users_table.php index 3d399c39b4..5ffbfd633f 100755 --- a/database/migrations/2013_12_12_055218_add_manager_to_users_table.php +++ b/database/migrations/2013_12_12_055218_add_manager_to_users_table.php @@ -12,8 +12,7 @@ class AddManagerToUsersTable extends Migration public function up() { Schema::table('users', function ($table) { - $table->integer('manager_id')->nullable()->default(NULL); - + $table->integer('manager_id')->nullable()->default(null); }); } @@ -28,5 +27,4 @@ class AddManagerToUsersTable extends Migration $table->dropColumn('manager_id'); }); } - } diff --git a/database/migrations/2014_01_28_031200_add_qr_code_to_settings_table.php b/database/migrations/2014_01_28_031200_add_qr_code_to_settings_table.php index 671f127eaf..37d0b48c12 100755 --- a/database/migrations/2014_01_28_031200_add_qr_code_to_settings_table.php +++ b/database/migrations/2014_01_28_031200_add_qr_code_to_settings_table.php @@ -12,8 +12,7 @@ class AddQrCodeToSettingsTable extends Migration public function up() { Schema::table('settings', function ($table) { - $table->integer('qr_code')->nullable()->default(NULL); - + $table->integer('qr_code')->nullable()->default(null); }); } @@ -28,5 +27,4 @@ class AddQrCodeToSettingsTable extends Migration $table->dropColumn('qr_code'); }); } - } diff --git a/database/migrations/2014_02_13_183016_add_qr_text_to_settings_table.php b/database/migrations/2014_02_13_183016_add_qr_text_to_settings_table.php index 48d17aed2b..b55b01ab04 100755 --- a/database/migrations/2014_02_13_183016_add_qr_text_to_settings_table.php +++ b/database/migrations/2014_02_13_183016_add_qr_text_to_settings_table.php @@ -1,7 +1,7 @@ string('qr_text', 32)->nullable()->default(NULL); + $table->string('qr_text', 32)->nullable()->default(null); }); } @@ -28,5 +28,4 @@ class AddQrTextToSettingsTable extends Migration $table->dropColumn('qr_text'); }); } - } diff --git a/database/migrations/2014_05_24_093839_alter_default_license_depreciation_id.php b/database/migrations/2014_05_24_093839_alter_default_license_depreciation_id.php index bec8ae64b3..d14195ff84 100755 --- a/database/migrations/2014_05_24_093839_alter_default_license_depreciation_id.php +++ b/database/migrations/2014_05_24_093839_alter_default_license_depreciation_id.php @@ -1,7 +1,7 @@ integer('display_asset_name')->nullable()->default(NULL); - + $table->integer('display_asset_name')->nullable()->default(null); }); } @@ -29,5 +28,4 @@ class AddAssetNameToSettings extends Migration $table->dropColumn('display_asset_name'); }); } - } diff --git a/database/migrations/2014_06_20_004847_make_asset_log_checkedout_to_nullable.php b/database/migrations/2014_06_20_004847_make_asset_log_checkedout_to_nullable.php index 75eb893998..a430c41a8c 100755 --- a/database/migrations/2014_06_20_004847_make_asset_log_checkedout_to_nullable.php +++ b/database/migrations/2014_06_20_004847_make_asset_log_checkedout_to_nullable.php @@ -1,7 +1,7 @@ increments('id'); $table->string('name'); - $table->string('address',50)->nullable()->default(NULL); - $table->string('address2',50)->nullable()->default(NULL); - $table->string('city')->nullable()->default(NULL); - $table->string('state',2)->nullable()->default(NULL); - $table->string('country',2)->nullable()->default(NULL); - $table->string('phone',20)->nullable()->default(NULL); - $table->string('fax',20)->nullable()->default(NULL); - $table->string('email',150)->nullable()->default(NULL); - $table->string('contact',100)->nullable()->default(NULL); - $table->string('notes')->nullable()->default(NULL); + $table->string('address', 50)->nullable()->default(null); + $table->string('address2', 50)->nullable()->default(null); + $table->string('city')->nullable()->default(null); + $table->string('state', 2)->nullable()->default(null); + $table->string('country', 2)->nullable()->default(null); + $table->string('phone', 20)->nullable()->default(null); + $table->string('fax', 20)->nullable()->default(null); + $table->string('email', 150)->nullable()->default(null); + $table->string('contact', 100)->nullable()->default(null); + $table->string('notes')->nullable()->default(null); $table->timestamps(); $table->integer('user_id')->nullable(); $table->softDeletes(); @@ -42,5 +42,4 @@ class AddSuppliers extends Migration // Schema::drop('suppliers'); } - } diff --git a/database/migrations/2014_06_24_010742_add_supplier_id_to_asset.php b/database/migrations/2014_06_24_010742_add_supplier_id_to_asset.php index 75c9c97e86..331e1739f2 100755 --- a/database/migrations/2014_06_24_010742_add_supplier_id_to_asset.php +++ b/database/migrations/2014_06_24_010742_add_supplier_id_to_asset.php @@ -1,7 +1,7 @@ integer('supplier_id')->nullable()->default(NULL); + $table->integer('supplier_id')->nullable()->default(null); }); } @@ -28,5 +28,4 @@ class AddSupplierIdToAsset extends Migration $table->dropColumn('supplier_id'); }); } - } diff --git a/database/migrations/2014_06_24_012839_add_zip_to_supplier.php b/database/migrations/2014_06_24_012839_add_zip_to_supplier.php index 49eff46409..5eb356257e 100755 --- a/database/migrations/2014_06_24_012839_add_zip_to_supplier.php +++ b/database/migrations/2014_06_24_012839_add_zip_to_supplier.php @@ -1,7 +1,7 @@ string('zip',10)->nullable()->default(NULL); - + $table->string('zip', 10)->nullable()->default(null); }); } @@ -29,6 +28,4 @@ class AddZipToSupplier extends Migration $table->dropColumn('zip'); }); } - - } diff --git a/database/migrations/2014_06_24_033908_add_url_to_supplier.php b/database/migrations/2014_06_24_033908_add_url_to_supplier.php index 806a775e0c..9cb1bb198b 100755 --- a/database/migrations/2014_06_24_033908_add_url_to_supplier.php +++ b/database/migrations/2014_06_24_033908_add_url_to_supplier.php @@ -1,7 +1,7 @@ string('url',250)->nullable()->default(NULL); - + $table->string('url', 250)->nullable()->default(null); }); } @@ -29,5 +28,4 @@ class AddUrlToSupplier extends Migration $table->dropColumn('url'); }); } - } diff --git a/database/migrations/2014_07_08_054116_add_employee_id_to_users.php b/database/migrations/2014_07_08_054116_add_employee_id_to_users.php index dc64a9f601..fcf4336b54 100755 --- a/database/migrations/2014_07_08_054116_add_employee_id_to_users.php +++ b/database/migrations/2014_07_08_054116_add_employee_id_to_users.php @@ -1,35 +1,33 @@ text('employee_num','50')->nullable()->default(NULL); +class AddEmployeeIdToUsers extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + // + Schema::table('users', function ($table) { + $table->text('employee_num', '50')->nullable()->default(null); }); - } + } - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::table('users', function ($table) { + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::table('users', function ($table) { $table->dropColumn('employee_num'); }); - - } - + } } diff --git a/database/migrations/2014_07_09_134316_add_requestable_to_assets.php b/database/migrations/2014_07_09_134316_add_requestable_to_assets.php index 69e4838b26..a37939baaa 100755 --- a/database/migrations/2014_07_09_134316_add_requestable_to_assets.php +++ b/database/migrations/2014_07_09_134316_add_requestable_to_assets.php @@ -1,37 +1,33 @@ tinyInteger('requestable')->default(0); }); + } - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::table('assets', function ($table) { + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::table('assets', function ($table) { $table->dropColumn('requestable'); }); - - } - + } } - diff --git a/database/migrations/2014_07_17_085822_add_asset_to_software.php b/database/migrations/2014_07_17_085822_add_asset_to_software.php index ecca3f4387..e5e83cf882 100755 --- a/database/migrations/2014_07_17_085822_add_asset_to_software.php +++ b/database/migrations/2014_07_17_085822_add_asset_to_software.php @@ -1,34 +1,33 @@ integer('asset_id')->nullable()->default(NULL); +class AddAssetToSoftware extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + // + Schema::table('license_seats', function ($table) { + $table->integer('asset_id')->nullable()->default(null); }); - } + } - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::table('license_seats', function ($table) { + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::table('license_seats', function ($table) { $table->dropColumn('asset_id'); }); - } - + } } diff --git a/database/migrations/2014_07_17_161625_make_asset_id_in_logs_nullable.php b/database/migrations/2014_07_17_161625_make_asset_id_in_logs_nullable.php index 1c8f5c1cad..337f98e417 100755 --- a/database/migrations/2014_07_17_161625_make_asset_id_in_logs_nullable.php +++ b/database/migrations/2014_07_17_161625_make_asset_id_in_logs_nullable.php @@ -1,29 +1,28 @@ integer('rtd_location_id')->nullable()->default(NULL); +class AddRtdLocationToAssets extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + // + Schema::table('assets', function ($table) { + $table->integer('rtd_location_id')->nullable()->default(null); }); - } + } - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::table('assets', function ($table) { + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::table('assets', function ($table) { $table->dropColumn('rtd_location_id'); }); - } - + } } diff --git a/database/migrations/2014_10_24_000417_alter_supplier_state_to_32.php b/database/migrations/2014_10_24_000417_alter_supplier_state_to_32.php index 5195c5c714..da1fdaa518 100644 --- a/database/migrations/2014_10_24_000417_alter_supplier_state_to_32.php +++ b/database/migrations/2014_10_24_000417_alter_supplier_state_to_32.php @@ -1,28 +1,27 @@ integer('display_checkout_date')->nullable()->default(NULL); - + $table->integer('display_checkout_date')->nullable()->default(null); }); } @@ -29,5 +28,4 @@ class AddDisplayCheckoutDate extends Migration { $table->dropColumn('display_checkout_date'); }); } - } diff --git a/database/migrations/2014_10_28_222654_add_avatar_field_to_users_table.php b/database/migrations/2014_10_28_222654_add_avatar_field_to_users_table.php index 27eb94684c..16c95eae67 100644 --- a/database/migrations/2014_10_28_222654_add_avatar_field_to_users_table.php +++ b/database/migrations/2014_10_28_222654_add_avatar_field_to_users_table.php @@ -3,35 +3,29 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; -class AddAvatarFieldToUsersTable extends Migration { - - /** - * Make changes to the table. - * - * @return void - */ - public function up() - { - Schema::table('users', function(Blueprint $table) { - - $table->string('avatar')->nullable(); - - }); - - } - - /** - * Revert the changes to the table. - * - * @return void - */ - public function down() - { - Schema::table('users', function(Blueprint $table) { - - $table->dropColumn('avatar'); - - }); - } +class AddAvatarFieldToUsersTable extends Migration +{ + /** + * Make changes to the table. + * + * @return void + */ + public function up() + { + Schema::table('users', function (Blueprint $table) { + $table->string('avatar')->nullable(); + }); + } + /** + * Revert the changes to the table. + * + * @return void + */ + public function down() + { + Schema::table('users', function (Blueprint $table) { + $table->dropColumn('avatar'); + }); + } } diff --git a/database/migrations/2014_10_29_045924_add_image_field_to_models_table.php b/database/migrations/2014_10_29_045924_add_image_field_to_models_table.php index 27ec34cb03..986c1d29fa 100644 --- a/database/migrations/2014_10_29_045924_add_image_field_to_models_table.php +++ b/database/migrations/2014_10_29_045924_add_image_field_to_models_table.php @@ -1,37 +1,31 @@ string('image')->nullable(); - - }); - - } - - /** - * Revert the changes to the table. - * - * @return void - */ - public function down() - { - Schema::table('models', function(Blueprint $table) { - - $table->dropColumn('image'); - - }); - } +class AddImageFieldToModelsTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('models', function (Blueprint $table) { + $table->string('image')->nullable(); + }); + } + /** + * Revert the changes to the table. + * + * @return void + */ + public function down() + { + Schema::table('models', function (Blueprint $table) { + $table->dropColumn('image'); + }); + } } diff --git a/database/migrations/2014_11_01_214955_add_eol_display_to_settings.php b/database/migrations/2014_11_01_214955_add_eol_display_to_settings.php index 9c7e8061fe..82d69e12ba 100644 --- a/database/migrations/2014_11_01_214955_add_eol_display_to_settings.php +++ b/database/migrations/2014_11_01_214955_add_eol_display_to_settings.php @@ -1,20 +1,19 @@ integer('display_eol')->nullable()->default(NULL); - + $table->integer('display_eol')->nullable()->default(null); }); } @@ -29,5 +28,4 @@ class AddEolDisplayToSettings extends Migration { $table->dropColumn('display_eol'); }); } - } diff --git a/database/migrations/2014_11_04_231416_update_group_field_for_reporting.php b/database/migrations/2014_11_04_231416_update_group_field_for_reporting.php index 248e26dde2..c5c42b1f0e 100644 --- a/database/migrations/2014_11_04_231416_update_group_field_for_reporting.php +++ b/database/migrations/2014_11_04_231416_update_group_field_for_reporting.php @@ -1,11 +1,11 @@ update(['permissions' => '{"users-poop":1,"reports":1}']); Group::where('id', 2)->update(['permissions' => '{"users-pop":1,"reports":1}']); - } elseif (Schema::hasTable('groups')) { DB::update('update '.DB::getTablePrefix().'groups set permissions = ? where id = ?', ['{"admin-farts":1,"users":1,"reports":1}', 1]); DB::update('update '.DB::getTablePrefix().'groups set permissions = ? where id = ?', ['{"users-farts":1,"reports":1}', 2]); } - } /** @@ -41,5 +38,4 @@ class UpdateGroupFieldForReporting extends Migration { { // } - } diff --git a/database/migrations/2014_11_05_212408_add_fields_to_licenses.php b/database/migrations/2014_11_05_212408_add_fields_to_licenses.php index e5bbad46d5..f8909764e0 100644 --- a/database/migrations/2014_11_05_212408_add_fields_to_licenses.php +++ b/database/migrations/2014_11_05_212408_add_fields_to_licenses.php @@ -1,36 +1,35 @@ integer('supplier_id')->nullable()->default(NULL); - $table->date('expiration_date')->nullable(); - $table->string('purchase_order')->nullable(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('licenses', function ($table) { - $table->dropColumn('supplier_id'); - $table->dropColumn('expiration_date'); - $table->dropColumn('purchase_order'); - }); - } +class AddFieldsToLicenses extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('licenses', function ($table) { + $table->integer('supplier_id')->nullable()->default(null); + $table->date('expiration_date')->nullable(); + $table->string('purchase_order')->nullable(); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('licenses', function ($table) { + $table->dropColumn('supplier_id'); + $table->dropColumn('expiration_date'); + $table->dropColumn('purchase_order'); + }); + } } diff --git a/database/migrations/2014_11_07_021042_add_image_to_supplier.php b/database/migrations/2014_11_07_021042_add_image_to_supplier.php index 0efb41eb09..a1c71d90a2 100644 --- a/database/migrations/2014_11_07_021042_add_image_to_supplier.php +++ b/database/migrations/2014_11_07_021042_add_image_to_supplier.php @@ -1,37 +1,31 @@ string('image')->nullable(); + }); + } - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::table('suppliers', function(Blueprint $table) { - - $table->string('image')->nullable(); - - }); - - } - - /** - * Revert the changes to the table. - * - * @return void - */ - public function down() - { - Schema::table('suppliers', function(Blueprint $table) { - - $table->dropColumn('image'); - - }); - } - -} \ No newline at end of file + /** + * Revert the changes to the table. + * + * @return void + */ + public function down() + { + Schema::table('suppliers', function (Blueprint $table) { + $table->dropColumn('image'); + }); + } +} diff --git a/database/migrations/2014_11_20_203007_add_username_to_user.php b/database/migrations/2014_11_20_203007_add_username_to_user.php index 5dfecac39a..0861145f21 100644 --- a/database/migrations/2014_11_20_203007_add_username_to_user.php +++ b/database/migrations/2014_11_20_203007_add_username_to_user.php @@ -1,39 +1,33 @@ string('username')->nullable()->default(NULL); - - }); - - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::table('users', function(Blueprint $table) { - - $table->dropColumn('username'); - - }); - } +class AddUsernameToUser extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + // + Schema::table('users', function (Blueprint $table) { + $table->string('username')->nullable()->default(null); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::table('users', function (Blueprint $table) { + $table->dropColumn('username'); + }); + } } diff --git a/database/migrations/2014_11_20_223947_add_auto_to_settings.php b/database/migrations/2014_11_20_223947_add_auto_to_settings.php index 3d3a4765f7..529e00d907 100644 --- a/database/migrations/2014_11_20_223947_add_auto_to_settings.php +++ b/database/migrations/2014_11_20_223947_add_auto_to_settings.php @@ -1,38 +1,33 @@ integer('auto_increment_assets')->default(0); - - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::table('settings', function(Blueprint $table) { - - $table->dropColumn('auto_increment_assets'); - - }); - } +class AddAutoToSettings extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + // + Schema::table('settings', function (Blueprint $table) { + $table->integer('auto_increment_assets')->default(0); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::table('settings', function (Blueprint $table) { + $table->dropColumn('auto_increment_assets'); + }); + } } diff --git a/database/migrations/2014_11_20_224421_add_prefix_to_settings.php b/database/migrations/2014_11_20_224421_add_prefix_to_settings.php index e325b3c55e..06162125dc 100644 --- a/database/migrations/2014_11_20_224421_add_prefix_to_settings.php +++ b/database/migrations/2014_11_20_224421_add_prefix_to_settings.php @@ -1,38 +1,33 @@ string('auto_increment_prefix')->nullable()->default(NULL); - - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::table('settings', function(Blueprint $table) { - - $table->dropColumn('auto_increment_prefix'); - - }); - } +class AddPrefixToSettings extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + // + Schema::table('settings', function (Blueprint $table) { + $table->string('auto_increment_prefix')->nullable()->default(null); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::table('settings', function (Blueprint $table) { + $table->dropColumn('auto_increment_prefix'); + }); + } } diff --git a/database/migrations/2014_11_21_104401_change_licence_type.php b/database/migrations/2014_11_21_104401_change_licence_type.php index 1028cca3e5..97701d0b0f 100644 --- a/database/migrations/2014_11_21_104401_change_licence_type.php +++ b/database/migrations/2014_11_21_104401_change_licence_type.php @@ -1,32 +1,31 @@ date('termination_date')->nullable(); - $table->boolean('maintained')->nullable(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('licenses', function ($table) { - $table->dropColumn('termination_date'); - $table->dropColumn('maintained'); - }); - } +class AddFieldsMaintainedTermToLicenses extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('licenses', function ($table) { + $table->date('termination_date')->nullable(); + $table->boolean('maintained')->nullable(); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('licenses', function ($table) { + $table->dropColumn('termination_date'); + $table->dropColumn('maintained'); + }); + } } diff --git a/database/migrations/2015_02_04_155757_increase_user_field_lengths.php b/database/migrations/2015_02_04_155757_increase_user_field_lengths.php index e71eedd007..493e07ee41 100644 --- a/database/migrations/2015_02_04_155757_increase_user_field_lengths.php +++ b/database/migrations/2015_02_04_155757_increase_user_field_lengths.php @@ -1,30 +1,29 @@ getDoctrineSchemaManager()->getDatabasePlatform(); $platform->registerDoctrineTypeMapping('enum', 'string'); Schema::table('asset_logs', function ($table) { - $table->string('asset_type',100)->nullable()->change(); + $table->string('asset_type', 100)->nullable()->change(); }); - // DB::statement('ALTER TABLE ' . DB::getTablePrefix() . 'asset_logs MODIFY column asset_type varchar(100) null'); - // DB::statement('ALTER TABLE ' . DB::getTablePrefix() . 'asset_logs MODIFY column added_on timestamp default "0000-00-00 00:00:00"'); - // Schema::table('asset_logs', function ($table) { - // $table->renameColumn('added_on', 'created_at'); - // $table->timestamp('updated_at'); + // DB::statement('ALTER TABLE ' . DB::getTablePrefix() . 'asset_logs MODIFY column asset_type varchar(100) null'); + // DB::statement('ALTER TABLE ' . DB::getTablePrefix() . 'asset_logs MODIFY column added_on timestamp default "0000-00-00 00:00:00"'); + // Schema::table('asset_logs', function ($table) { + // $table->renameColumn('added_on', 'created_at'); + // $table->timestamp('updated_at'); // $table->softDeletes(); - // }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // Schema::table('asset_logs', function ($table) { - // $table->renameColumn('created_at', 'added_on'); - // $table->dropColumn('updated_at'); - // $table->dropSoftDeletes(); - // }); - } + // }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // Schema::table('asset_logs', function ($table) { + // $table->renameColumn('created_at', 'added_on'); + // $table->dropColumn('updated_at'); + // $table->dropSoftDeletes(); + // }); + } } diff --git a/database/migrations/2015_02_10_040958_fix_bad_assigned_to_ids.php b/database/migrations/2015_02_10_040958_fix_bad_assigned_to_ids.php index 7be7dc63a1..36ba8f8caa 100644 --- a/database/migrations/2015_02_10_040958_fix_bad_assigned_to_ids.php +++ b/database/migrations/2015_02_10_040958_fix_bad_assigned_to_ids.php @@ -1,50 +1,47 @@ boolean('deployable')->default(0); - $table->boolean('pending')->default(0); - $table->boolean('archived')->default(0); - $table->text('notes')->nullable(); - }); + Schema::table('status_labels', function ($table) { + $table->boolean('deployable')->default(0); + $table->boolean('pending')->default(0); + $table->boolean('archived')->default(0); + $table->text('notes')->nullable(); + }); DB::table('status_labels')->insert([ ['user_id' => 1, 'name' => 'Pending', 'deployable' => 0, 'pending' => 1, 'archived' => 0, 'notes' => 'These assets are not yet ready to be deployed, usually because of configuration or waiting on parts.'], ['user_id' => 1, 'name' => 'Ready to Deploy', 'deployable' => 1, 'pending' => 0, 'archived' => 0, 'notes' => 'These assets are ready to deploy.'], ['user_id' => 1, 'name' => 'Archived', 'deployable' => 0, 'pending' => 0, 'archived' => 1, 'notes' => 'These assets are no longer in circulation or viable.'], ]); + } - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::table('status_labels', function ($table) { - $table->dropColumn('deployable'); - $table->dropColumn('pending'); - $table->dropColumn('archived'); - $table->dropColumn('notes'); - - }); - } - + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::table('status_labels', function ($table) { + $table->dropColumn('deployable'); + $table->dropColumn('pending'); + $table->dropColumn('archived'); + $table->dropColumn('notes'); + }); + } } diff --git a/database/migrations/2015_02_10_053310_migrate_data_to_new_statuses.php b/database/migrations/2015_02_10_053310_migrate_data_to_new_statuses.php index 8b9c33632c..50dacc1f7a 100644 --- a/database/migrations/2015_02_10_053310_migrate_data_to_new_statuses.php +++ b/database/migrations/2015_02_10_053310_migrate_data_to_new_statuses.php @@ -1,60 +1,51 @@ where('name', 'Pending')->orWhere('name', 'Ready to Deploy')->get(); - foreach ($statuses as $status) { - if ($status->name =="Pending") { - $pending_id = array($status->id); - } elseif ($status->name =="Ready to Deploy") { - $rtd_id = array($status->id); - } - } + foreach ($statuses as $status) { + if ($status->name == 'Pending') { + $pending_id = [$status->id]; + } elseif ($status->name == 'Ready to Deploy') { + $rtd_id = [$status->id]; + } + } - // Pending + // Pending $pendings = DB::table('assets')->where('status_id', null)->where('physical', '1')->get(); + foreach ($pendings as $pending) { + DB::update('update '.DB::getTablePrefix().'assets set status_id = ? where status_id IS NULL AND physical=1', $pending_id); + } - foreach ($pendings as $pending) { - DB::update('update ' . DB::getTablePrefix() . 'assets set status_id = ? where status_id IS NULL AND physical=1',$pending_id); - - } - - - // Ready to Deploy + // Ready to Deploy $rtds = DB::table('assets')->where('status_id', 0)->where('physical', '1')->get(); - foreach ($rtds as $rtd) { - //DB::update('update users set votes = 100 where name = ?', array('John')); - DB::update('update ' . DB::getTablePrefix() . 'assets set status_id = ? where status_id = 0 AND physical=1',$rtd_id); - - } - - - - - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - } + foreach ($rtds as $rtd) { + //DB::update('update users set votes = 100 where name = ?', array('John')); + DB::update('update '.DB::getTablePrefix().'assets set status_id = ? where status_id = 0 AND physical=1', $rtd_id); + } + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + } } diff --git a/database/migrations/2015_02_11_044104_migrate_make_license_assigned_null.php b/database/migrations/2015_02_11_044104_migrate_make_license_assigned_null.php index 75f2e46301..e3586b7763 100644 --- a/database/migrations/2015_02_11_044104_migrate_make_license_assigned_null.php +++ b/database/migrations/2015_02_11_044104_migrate_make_license_assigned_null.php @@ -1,29 +1,28 @@ increments('id'); $table->integer('asset_id'); $table->integer('user_id')->nullable(); @@ -21,17 +21,16 @@ class MigrateCreateRequestsTable extends Migration { $table->timestamps(); $table->softDeletes(); }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::drop('requests'); - } + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::drop('requests'); + } } diff --git a/database/migrations/2015_02_12_001312_add_mac_address_to_asset.php b/database/migrations/2015_02_12_001312_add_mac_address_to_asset.php index eb658a53ae..8f0bf1385a 100644 --- a/database/migrations/2015_02_12_001312_add_mac_address_to_asset.php +++ b/database/migrations/2015_02_12_001312_add_mac_address_to_asset.php @@ -1,43 +1,41 @@ string('mac_address')->nullable()->default(null); + }); - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - // - Schema::table('assets', function ($table) { - $table->string('mac_address')->nullable()->default(NULL); - }); + Schema::table('models', function ($table) { + $table->boolean('show_mac_address')->default(0); + }); + } - Schema::table('models', function ($table) { - $table->boolean('show_mac_address')->default(0); - }); - - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::table('assets', function ($table) { - $table->dropColumn('mac_address'); - }); - - Schema::table('models', function ($table) { - $table->dropColumn('show_mac_address'); - }); - } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::table('assets', function ($table) { + $table->dropColumn('mac_address'); + }); + Schema::table('models', function ($table) { + $table->dropColumn('show_mac_address'); + }); + } } diff --git a/database/migrations/2015_02_12_024100_change_license_notes_type.php b/database/migrations/2015_02_12_024100_change_license_notes_type.php index a9a3029a8b..ba2f4b3188 100644 --- a/database/migrations/2015_02_12_024100_change_license_notes_type.php +++ b/database/migrations/2015_02_12_024100_change_license_notes_type.php @@ -1,27 +1,29 @@ text('notes')->change(); - }); +use Illuminate\Database\Schema\Blueprint; - } - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { +class ChangeLicenseNotesType extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + // + Schema::table('licenses', function ($table) { + $table->text('notes')->change(); + }); + } - } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + } } diff --git a/database/migrations/2015_02_17_231020_add_localonly_to_settings.php b/database/migrations/2015_02_17_231020_add_localonly_to_settings.php index 6ac91ba23d..5c5b0eeb95 100644 --- a/database/migrations/2015_02_17_231020_add_localonly_to_settings.php +++ b/database/migrations/2015_02_17_231020_add_localonly_to_settings.php @@ -1,35 +1,33 @@ boolean('load_remote')->default(1); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::table('settings', function ($table) { - $table->dropColumn('load_remote'); - }); - - } +class AddLocalonlyToSettings extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + // + Schema::table('settings', function ($table) { + $table->boolean('load_remote')->default(1); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::table('settings', function ($table) { + $table->dropColumn('load_remote'); + }); + } } diff --git a/database/migrations/2015_02_19_222322_add_logo_and_colors_to_settings.php b/database/migrations/2015_02_19_222322_add_logo_and_colors_to_settings.php index f047a7080f..cb2d7ac983 100644 --- a/database/migrations/2015_02_19_222322_add_logo_and_colors_to_settings.php +++ b/database/migrations/2015_02_19_222322_add_logo_and_colors_to_settings.php @@ -1,37 +1,35 @@ string('logo')->nullable()->default(NULL); - $table->string('header_color')->nullable()->default(NULL); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::table('settings', function ($table) { - $table->dropColumn('logo'); - $table->dropColumn('header_color'); - }); - - } +class AddLogoAndColorsToSettings extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + // + Schema::table('settings', function ($table) { + $table->string('logo')->nullable()->default(null); + $table->string('header_color')->nullable()->default(null); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::table('settings', function ($table) { + $table->dropColumn('logo'); + $table->dropColumn('header_color'); + }); + } } diff --git a/database/migrations/2015_02_24_072043_add_alerts_to_settings.php b/database/migrations/2015_02_24_072043_add_alerts_to_settings.php index 8a208457ea..d7119ab4cd 100644 --- a/database/migrations/2015_02_24_072043_add_alerts_to_settings.php +++ b/database/migrations/2015_02_24_072043_add_alerts_to_settings.php @@ -1,36 +1,35 @@ string('alert_email')->nullable()->default(NULL); - $table->boolean('alerts_enabled')->default(1); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::table('settings', function ($table) { - $table->dropColumn('alert_email'); - $table->dropColumn('alerts_enabled'); - }); - } +class AddAlertsToSettings extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + // + Schema::table('settings', function ($table) { + $table->string('alert_email')->nullable()->default(null); + $table->boolean('alerts_enabled')->default(1); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::table('settings', function ($table) { + $table->dropColumn('alert_email'); + $table->dropColumn('alerts_enabled'); + }); + } } diff --git a/database/migrations/2015_02_25_022931_add_eula_fields.php b/database/migrations/2015_02_25_022931_add_eula_fields.php index a4eff87120..90c249dd49 100644 --- a/database/migrations/2015_02_25_022931_add_eula_fields.php +++ b/database/migrations/2015_02_25_022931_add_eula_fields.php @@ -1,69 +1,67 @@ longText('default_eula_text')->nullable()->default(null); + }); - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - // - Schema::table('settings', function ($table) { - $table->longText('default_eula_text')->nullable()->default(NULL); - }); + Schema::table('categories', function ($table) { + $table->longText('eula_text')->nullable()->default(null); + $table->boolean('use_default_eula')->default(0); + $table->boolean('require_acceptance')->default(0); + }); - Schema::table('categories', function ($table) { - $table->longText('eula_text')->nullable()->default(NULL); - $table->boolean('use_default_eula')->default(0); - $table->boolean('require_acceptance')->default(0); - }); + Schema::table('asset_logs', function ($table) { + $table->dateTime('requested_at')->nullable()->default(null); + $table->dateTime('accepted_at')->nullable()->default(null); + }); - Schema::table('asset_logs', function ($table) { - $table->dateTime('requested_at')->nullable()->default(NULL); - $table->dateTime('accepted_at')->nullable()->default(NULL); - }); + Schema::create('requested_assets', function ($table) { + $table->increments('id'); + $table->integer('asset_id')->default(null); + $table->integer('user_id')->default(null); + $table->dateTime('accepted_at')->nullable()->default(null); + $table->dateTime('denied_at')->nullable()->default(null); + $table->string('notes')->default(null); + $table->timestamps(); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::table('settings', function ($table) { + $table->dropColumn('default_eula_text'); + }); - Schema::create('requested_assets', function ($table) { - $table->increments('id'); - $table->integer('asset_id')->default(NULL); - $table->integer('user_id')->default(NULL); - $table->dateTime('accepted_at')->nullable()->default(NULL); - $table->dateTime('denied_at')->nullable()->default(NULL); - $table->string('notes')->default(NULL); - $table->timestamps(); - }); - } + Schema::table('categories', function ($table) { + $table->dropColumn('eula_text'); + $table->dropColumn('use_default_eula'); + $table->dropColumn('require_acceptance'); + }); - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::table('settings', function ($table) { - $table->dropColumn('default_eula_text'); - }); - - Schema::table('categories', function ($table) { - $table->dropColumn('eula_text'); - $table->dropColumn('use_default_eula'); - $table->dropColumn('require_acceptance'); - }); - - Schema::table('asset_logs', function ($table) { - $table->dropColumn('requested_at'); - $table->dropColumn('accepted_at'); - }); - - Schema::drop('requested_assets'); - } + Schema::table('asset_logs', function ($table) { + $table->dropColumn('requested_at'); + $table->dropColumn('accepted_at'); + }); + Schema::drop('requested_assets'); + } } diff --git a/database/migrations/2015_02_25_204513_add_accessories_table.php b/database/migrations/2015_02_25_204513_add_accessories_table.php index 037351f861..49d95d721f 100644 --- a/database/migrations/2015_02_25_204513_add_accessories_table.php +++ b/database/migrations/2015_02_25_204513_add_accessories_table.php @@ -1,23 +1,23 @@ increments('id'); - $table->string('name')->nullable()->default(NULL); - $table->integer('category_id')->nullable()->default(NULL); - $table->integer('user_id')->nullable()->default(NULL); + $table->string('name')->nullable()->default(null); + $table->integer('category_id')->nullable()->default(null); + $table->integer('user_id')->nullable()->default(null); $table->integer('qty')->default(0); $table->boolean('requestable')->default(0); $table->timestamps(); @@ -26,24 +26,22 @@ class AddAccessoriesTable extends Migration { }); Schema::table('asset_logs', function ($table) { - $table->integer('accessory_id')->nullable()->default(NULL); - }); + $table->integer('accessory_id')->nullable()->default(null); + }); + } - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::drop('accessories'); - - Schema::table('asset_logs', function ($table) { - $table->dropColumn('accessory_id'); - }); - } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::drop('accessories'); + Schema::table('asset_logs', function ($table) { + $table->dropColumn('accessory_id'); + }); + } } diff --git a/database/migrations/2015_02_26_091228_add_accessories_user_table.php b/database/migrations/2015_02_26_091228_add_accessories_user_table.php index e8a01d5508..38e1ac5b52 100644 --- a/database/migrations/2015_02_26_091228_add_accessories_user_table.php +++ b/database/migrations/2015_02_26_091228_add_accessories_user_table.php @@ -1,46 +1,43 @@ increments('id'); - $table->integer('user_id')->nullable()->default(NULL); - $table->integer('accessory_id')->nullable()->default(NULL); - $table->integer('assigned_to')->nullable()->default(NULL); + $table->integer('user_id')->nullable()->default(null); + $table->integer('accessory_id')->nullable()->default(null); + $table->integer('assigned_to')->nullable()->default(null); $table->timestamps(); }); - + Schema::table('accessories', function ($table) { - $table->integer('location_id')->nullable()->default(NULL); - }); + $table->integer('location_id')->nullable()->default(null); + }); + } - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::drop('accessories_users'); - - Schema::table('accessories', function ($table) { - $table->dropColumn('location_id'); - }); - - } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::drop('accessories_users'); + Schema::table('accessories', function ($table) { + $table->dropColumn('location_id'); + }); + } } diff --git a/database/migrations/2015_02_26_115128_add_deleted_at_models.php b/database/migrations/2015_02_26_115128_add_deleted_at_models.php index 044647d43d..28f42d2366 100644 --- a/database/migrations/2015_02_26_115128_add_deleted_at_models.php +++ b/database/migrations/2015_02_26_115128_add_deleted_at_models.php @@ -1,32 +1,31 @@ softDeletes(); }); - } + } - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('models', function ($table){ + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('models', function ($table) { $table->dropColumn('deleted_at'); }); - } - + } } diff --git a/database/migrations/2015_02_26_233005_add_category_type.php b/database/migrations/2015_02_26_233005_add_category_type.php index 7fe85587f1..8f41f6fda9 100644 --- a/database/migrations/2015_02_26_233005_add_category_type.php +++ b/database/migrations/2015_02_26_233005_add_category_type.php @@ -1,34 +1,33 @@ string('category_type')->nullable()->default('asset'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::table('categories', function ($table) { - $table->dropColumn('category_type'); - }); - } +class AddCategoryType extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + // + Schema::table('categories', function ($table) { + $table->string('category_type')->nullable()->default('asset'); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::table('categories', function ($table) { + $table->dropColumn('category_type'); + }); + } } diff --git a/database/migrations/2015_03_01_231912_update_accepted_at_to_acceptance_id.php b/database/migrations/2015_03_01_231912_update_accepted_at_to_acceptance_id.php index 6d913e03a5..9cae90a791 100644 --- a/database/migrations/2015_03_01_231912_update_accepted_at_to_acceptance_id.php +++ b/database/migrations/2015_03_01_231912_update_accepted_at_to_acceptance_id.php @@ -1,47 +1,44 @@ integer('accepted_id')->nullable()->default(null); + }); - Schema::table('asset_logs', function ($table) { - $table->integer('accepted_id')->nullable()->default(NULL); - }); - - $results = DB::table('asset_logs as invitation')->join('asset_logs as acceptance', function($join) { + $results = DB::table('asset_logs as invitation')->join('asset_logs as acceptance', function ($join) { $join->on('invitation.checkedout_to', '=', 'acceptance.checkedout_to'); $join->on('invitation.asset_id', '=', 'acceptance.asset_id'); })->select('invitation.id as invitation_id', 'acceptance.id as acceptance_id') ->where('invitation.action_type', 'checkout')->where('acceptance.action_type', 'accepted')->get(); - foreach ($results as $result) { - $update = DB::update('update '.DB::getTablePrefix().'asset_logs set accepted_id=? where id=?', [$result->acceptance_id, $result->invitation_id]); - } - - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::table('asset_logs', function ($table) { - $table->dropColumn('accepted_id'); - }); - - } + foreach ($results as $result) { + $update = DB::update('update '.DB::getTablePrefix().'asset_logs set accepted_id=? where id=?', [$result->acceptance_id, $result->invitation_id]); + } + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::table('asset_logs', function ($table) { + $table->dropColumn('accepted_id'); + }); + } } diff --git a/database/migrations/2015_03_05_011929_add_qr_type_to_settings.php b/database/migrations/2015_03_05_011929_add_qr_type_to_settings.php index cc171bbfef..e85d79bd97 100644 --- a/database/migrations/2015_03_05_011929_add_qr_type_to_settings.php +++ b/database/migrations/2015_03_05_011929_add_qr_type_to_settings.php @@ -1,34 +1,33 @@ string('barcode_type')->nullable()->default('QRCODE'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::table('settings', function ($table) { - $table->dropColumn('barcode_type'); - }); - } +class AddQrTypeToSettings extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + // + Schema::table('settings', function ($table) { + $table->string('barcode_type')->nullable()->default('QRCODE'); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::table('settings', function ($table) { + $table->dropColumn('barcode_type'); + }); + } } diff --git a/database/migrations/2015_03_18_055327_add_note_to_user.php b/database/migrations/2015_03_18_055327_add_note_to_user.php index 631f4574c0..191d34c572 100644 --- a/database/migrations/2015_03_18_055327_add_note_to_user.php +++ b/database/migrations/2015_03_18_055327_add_note_to_user.php @@ -1,32 +1,31 @@ text('notes')->nullable(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('users', function ($table) { - $table->dropColumn('notes'); - }); - } +class AddNoteToUser extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('users', function ($table) { + $table->text('notes')->nullable(); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('users', function ($table) { + $table->dropColumn('notes'); + }); + } } diff --git a/database/migrations/2015_04_29_234704_add_slack_to_settings.php b/database/migrations/2015_04_29_234704_add_slack_to_settings.php index 8dca9e0b06..c7970ef1dd 100644 --- a/database/migrations/2015_04_29_234704_add_slack_to_settings.php +++ b/database/migrations/2015_04_29_234704_add_slack_to_settings.php @@ -1,39 +1,36 @@ string('slack_endpoint')->nullable()->default(NULL); - $table->string('slack_channel')->nullable()->default(NULL); - $table->string('slack_botname')->nullable()->default(NULL); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('settings', function(Blueprint $table) - { - // - $table->dropColumn('slack_endpoint'); - $table->dropColumn('slack_channel'); - $table->dropColumn('slack_botname'); - }); - } +class AddSlackToSettings extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('settings', function (Blueprint $table) { + $table->string('slack_endpoint')->nullable()->default(null); + $table->string('slack_channel')->nullable()->default(null); + $table->string('slack_botname')->nullable()->default(null); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('settings', function (Blueprint $table) { + // + $table->dropColumn('slack_endpoint'); + $table->dropColumn('slack_channel'); + $table->dropColumn('slack_botname'); + }); + } } diff --git a/database/migrations/2015_05_04_085151_add_parent_id_to_locations_table.php b/database/migrations/2015_05_04_085151_add_parent_id_to_locations_table.php index 6c0ed7f831..5b9dc26ea1 100644 --- a/database/migrations/2015_05_04_085151_add_parent_id_to_locations_table.php +++ b/database/migrations/2015_05_04_085151_add_parent_id_to_locations_table.php @@ -1,36 +1,33 @@ integer('parent_id')->nullable()->default(NULL); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('locations', function(Blueprint $table) - { - // - $table->dropColumn('parent_id'); - }); - } +class AddParentIdToLocationsTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('locations', function (Blueprint $table) { + // + $table->integer('parent_id')->nullable()->default(null); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('locations', function (Blueprint $table) { + // + $table->dropColumn('parent_id'); + }); + } } diff --git a/database/migrations/2015_05_22_124421_add_reassignable_to_licenses.php b/database/migrations/2015_05_22_124421_add_reassignable_to_licenses.php index b0e94a92f8..fc029e2619 100644 --- a/database/migrations/2015_05_22_124421_add_reassignable_to_licenses.php +++ b/database/migrations/2015_05_22_124421_add_reassignable_to_licenses.php @@ -1,35 +1,32 @@ boolean('reassignable')->default(true); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('licenses', function(Blueprint $table) - { - // - $table->dropColumn('reassignable'); - }); - } +class AddReassignableToLicenses extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('licenses', function (Blueprint $table) { + $table->boolean('reassignable')->default(true); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('licenses', function (Blueprint $table) { + // + $table->dropColumn('reassignable'); + }); + } } diff --git a/database/migrations/2015_06_10_003314_fix_default_for_user_notes.php b/database/migrations/2015_06_10_003314_fix_default_for_user_notes.php index 12255c4c23..6fb202c443 100644 --- a/database/migrations/2015_06_10_003314_fix_default_for_user_notes.php +++ b/database/migrations/2015_06_10_003314_fix_default_for_user_notes.php @@ -1,29 +1,28 @@ increments('id'); - $table->string('name')->nullable()->default(NULL); - $table->integer('category_id')->nullable()->default(NULL); - $table->integer('location_id')->nullable()->default(NULL); - $table->integer('user_id')->nullable()->default(NULL); + $table->string('name')->nullable()->default(null); + $table->integer('category_id')->nullable()->default(null); + $table->integer('location_id')->nullable()->default(null); + $table->integer('user_id')->nullable()->default(null); $table->integer('qty')->default(0); $table->boolean('requestable')->default(0); $table->timestamps(); @@ -27,38 +27,32 @@ class CreateConsumables extends Migration { }); Schema::table('asset_logs', function ($table) { - $table->integer('consumable_id')->nullable()->default(NULL); - }); - - Schema::create('consumables_users', function ($table) { - $table->increments('id'); - $table->integer('user_id')->nullable()->default(NULL); - $table->integer('consumable_id')->nullable()->default(NULL); - $table->integer('assigned_to')->nullable()->default(NULL); - $table->timestamps(); + $table->integer('consumable_id')->nullable()->default(null); }); + Schema::create('consumables_users', function ($table) { + $table->increments('id'); + $table->integer('user_id')->nullable()->default(null); + $table->integer('consumable_id')->nullable()->default(null); + $table->integer('assigned_to')->nullable()->default(null); + $table->timestamps(); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::drop('consumables'); - } - - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::drop('consumables'); - - Schema::table('asset_logs', function ($table) { - $table->dropColumn('consumable_id'); - }); - - Schema::drop('consumables_users'); - - } + Schema::table('asset_logs', function ($table) { + $table->dropColumn('consumable_id'); + }); + Schema::drop('consumables_users'); + } } diff --git a/database/migrations/2015_06_15_183253_move_email_to_username.php b/database/migrations/2015_06_15_183253_move_email_to_username.php index 66c07acb77..8506bd4d16 100644 --- a/database/migrations/2015_06_15_183253_move_email_to_username.php +++ b/database/migrations/2015_06_15_183253_move_email_to_username.php @@ -1,30 +1,29 @@ string('email')->nullable()->change(); - }); - - - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - - } +class MakeEmailNullable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('users', function (Blueprint $table) { + $table->string('email')->nullable()->change(); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + } } diff --git a/database/migrations/2015_06_26_213716_create_asset_maintenances_table.php b/database/migrations/2015_06_26_213716_create_asset_maintenances_table.php index 4c465528dc..f328bb61f8 100644 --- a/database/migrations/2015_06_26_213716_create_asset_maintenances_table.php +++ b/database/migrations/2015_06_26_213716_create_asset_maintenances_table.php @@ -6,7 +6,6 @@ class CreateAssetMaintenancesTable extends Migration { - /** * Run the migrations. * @@ -14,39 +13,36 @@ */ public function up() { - - Schema::create( 'asset_maintenances', function ( Blueprint $table ) { - - $table->increments( 'id' ); - $table->integer( 'asset_id' ) + Schema::create('asset_maintenances', function (Blueprint $table) { + $table->increments('id'); + $table->integer('asset_id') ->unsigned(); - $table->integer( 'supplier_id' ) + $table->integer('supplier_id') ->unsigned(); - $table->string( 'asset_maintenance_type'); - $table->string( 'title', 100 ); - $table->boolean( 'is_warranty' ); - $table->date( 'start_date' ); - $table->date( 'completion_date' ) + $table->string('asset_maintenance_type'); + $table->string('title', 100); + $table->boolean('is_warranty'); + $table->date('start_date'); + $table->date('completion_date') ->nullable(); - $table->integer( 'asset_maintenance_time' ) + $table->integer('asset_maintenance_time') ->nullable(); - $table->longText( 'notes' ) + $table->longText('notes') ->nullable(); - $table->decimal( 'cost', 10, 2 ) + $table->decimal('cost', 10, 2) ->nullable(); - $table->dateTime( 'deleted_at' ) + $table->dateTime('deleted_at') ->nullable(); $table->timestamps(); - } ); + }); } protected function getEnumFields() { - return [ - trans( 'admin/asset_maintenances/general.maintenance' ), - trans( 'admin/asset_maintenances/general.repair' ), - trans( 'admin/asset_maintenances/general.upgrade' ) + trans('admin/asset_maintenances/general.maintenance'), + trans('admin/asset_maintenances/general.repair'), + trans('admin/asset_maintenances/general.upgrade'), ]; } @@ -57,9 +53,6 @@ */ public function down() { - - Schema::dropIfExists( 'asset_maintenances' ); - + Schema::dropIfExists('asset_maintenances'); } - -} + } diff --git a/database/migrations/2015_07_04_212443_create_custom_fields_table.php b/database/migrations/2015_07_04_212443_create_custom_fields_table.php index b2dbbebb8c..3e3319c635 100644 --- a/database/migrations/2015_07_04_212443_create_custom_fields_table.php +++ b/database/migrations/2015_07_04_212443_create_custom_fields_table.php @@ -5,32 +5,30 @@ use Illuminate\Database\Migrations\Migration; class CreateCustomFieldsTable extends Migration { + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('custom_fields', function ($table) { + $table->increments('id'); + $table->string('name'); + $table->string('format'); + $table->string('element'); + $table->timestamps(); + }); + } - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('custom_fields', function ($table) { - $table->increments('id'); - $table->string('name'); - $table->string('format'); - $table->string('element'); - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::drop('custom_fields'); - } - + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::drop('custom_fields'); + } } diff --git a/database/migrations/2015_07_09_014359_add_currency_to_settings_and_locations.php b/database/migrations/2015_07_09_014359_add_currency_to_settings_and_locations.php index 254a3c018b..37e0edb743 100644 --- a/database/migrations/2015_07_09_014359_add_currency_to_settings_and_locations.php +++ b/database/migrations/2015_07_09_014359_add_currency_to_settings_and_locations.php @@ -1,56 +1,46 @@ string('default_currency',10)->nullable()->default(NULL); - }); +class AddCurrencyToSettingsAndLocations extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('settings', function (Blueprint $table) { + $table->string('default_currency', 10)->nullable()->default(null); + }); DB::table('settings')->update(['default_currency' => trans('general.currency')]); - Schema::table('locations', function(Blueprint $table) - { - $table->string('currency',10)->nullable()->default(NULL); - }); + Schema::table('locations', function (Blueprint $table) { + $table->string('currency', 10)->nullable()->default(null); + }); DB::table('locations')->update(['currency' => trans('general.currency')]); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::table('settings', function (Blueprint $table) { + // + $table->dropColumn('default_currency'); + }); - - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::table('settings', function(Blueprint $table) - { - // - $table->dropColumn('default_currency'); - }); - - Schema::table('locations', function(Blueprint $table) - { - // - $table->dropColumn('currency'); - }); - - } - + Schema::table('locations', function (Blueprint $table) { + // + $table->dropColumn('currency'); + }); + } } diff --git a/database/migrations/2015_07_21_122022_add_expected_checkin_date_to_asset_logs.php b/database/migrations/2015_07_21_122022_add_expected_checkin_date_to_asset_logs.php index 40826af579..cb8f6b3aaf 100644 --- a/database/migrations/2015_07_21_122022_add_expected_checkin_date_to_asset_logs.php +++ b/database/migrations/2015_07_21_122022_add_expected_checkin_date_to_asset_logs.php @@ -1,37 +1,31 @@ date('expected_checkin')->nullable()->default(NULL); +class AddExpectedCheckinDateToAssetLogs extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('asset_logs', function ($table) { + $table->date('expected_checkin')->nullable()->default(null); }); + } - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - - Schema::table('asset_logs', function(Blueprint $table) - { - $table->dropColumn('expected_checkin'); - }); - - } - + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('asset_logs', function (Blueprint $table) { + $table->dropColumn('expected_checkin'); + }); + } } diff --git a/database/migrations/2015_07_24_093845_add_checkin_email_to_category_table.php b/database/migrations/2015_07_24_093845_add_checkin_email_to_category_table.php index a2009e4dea..00e6aaa3d1 100644 --- a/database/migrations/2015_07_24_093845_add_checkin_email_to_category_table.php +++ b/database/migrations/2015_07_24_093845_add_checkin_email_to_category_table.php @@ -1,32 +1,31 @@ boolean('checkin_email')->default(0); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('categories', function ($table) { - $table->dropColumn('checkin_email'); - }); - } +class AddCheckinEmailToCategoryTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('categories', function ($table) { + $table->boolean('checkin_email')->default(0); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('categories', function ($table) { + $table->dropColumn('checkin_email'); + }); + } } diff --git a/database/migrations/2015_07_25_055415_remove_email_unique_constraint.php b/database/migrations/2015_07_25_055415_remove_email_unique_constraint.php index 06c84a9df3..48f01645ed 100644 --- a/database/migrations/2015_07_25_055415_remove_email_unique_constraint.php +++ b/database/migrations/2015_07_25_055415_remove_email_unique_constraint.php @@ -1,31 +1,29 @@ dropUnique('users_email_unique'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - } +class RemoveEmailUniqueConstraint extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('users', function (Blueprint $table) { + $table->dropUnique('users_email_unique'); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + } } diff --git a/database/migrations/2015_07_29_230054_add_thread_id_to_asset_logs_table.php b/database/migrations/2015_07_29_230054_add_thread_id_to_asset_logs_table.php index 4a0e45bbef..eefc283e3f 100644 --- a/database/migrations/2015_07_29_230054_add_thread_id_to_asset_logs_table.php +++ b/database/migrations/2015_07_29_230054_add_thread_id_to_asset_logs_table.php @@ -1,12 +1,11 @@ dropIndex( 'thread_id' ); - $table->dropColumn( 'thread_id' ); - } ); + Schema::table('asset_logs', function (Blueprint $table) { + $table->dropIndex('thread_id'); + $table->dropColumn('thread_id'); + }); } /** @@ -125,9 +120,8 @@ * @author Vincent Sposato * @version v1.0 */ - protected function hasAssetChanged( $assetLog ) + protected function hasAssetChanged($assetLog) { - return $assetLog->asset_id !== $this->currentAssetId; } @@ -139,11 +133,10 @@ * @author Vincent Sposato * @version v1.0 */ - protected function resetCurrentAssetInformation( $assetLog ) + protected function resetCurrentAssetInformation($assetLog) { - - $this->currentAssetId = $assetLog->asset_id; - $this->currentAssetLogId = $assetLog->id; + $this->currentAssetId = $assetLog->asset_id; + $this->currentAssetLogId = $assetLog->id; $this->startOfCurrentThread = true; } @@ -156,10 +149,9 @@ * @author Vincent Sposato * @version v1.0 */ - protected function hasReachedEndOfChain( $assetLog ) + protected function hasReachedEndOfChain($assetLog) { - - return in_array( $assetLog->action_type, $this->threadFinalActionTypes ) + return in_array($assetLog->action_type, $this->threadFinalActionTypes) && $this->startOfCurrentThread == false; } @@ -170,10 +162,9 @@ */ protected function clearCurrentAssetInformation() { - $this->startOfCurrentThread = true; - $this->currentAssetLogId = null; - $this->currentAssetId = null; + $this->currentAssetLogId = null; + $this->currentAssetId = null; } /** @@ -184,16 +175,15 @@ * @author Vincent Sposato * @version v1.0 */ - protected function updateAssetLogWithThreadInformation( $assetLog ) + protected function updateAssetLogWithThreadInformation($assetLog) { - - $loadedAssetLog = Actionlog::find( $assetLog->id ); + $loadedAssetLog = Actionlog::find($assetLog->id); $loadedAssetLog->thread_id = $this->currentAssetLogId; $loadedAssetLog->update(); - unset( $loadedAssetLog ); + unset($loadedAssetLog); } /** @@ -205,11 +195,9 @@ * @author Vincent Sposato * @version v1.0 */ - protected function hasBegunNewChain( $assetLog ) + protected function hasBegunNewChain($assetLog) { - - return in_array( $assetLog->action_type, $this->threadStartingActionTypes ) + return in_array($assetLog->action_type, $this->threadStartingActionTypes) && $this->startOfCurrentThread == true; } - } diff --git a/database/migrations/2015_07_31_015430_add_accepted_to_assets.php b/database/migrations/2015_07_31_015430_add_accepted_to_assets.php index 8f07b0951c..db964b5456 100644 --- a/database/migrations/2015_07_31_015430_add_accepted_to_assets.php +++ b/database/migrations/2015_07_31_015430_add_accepted_to_assets.php @@ -1,34 +1,31 @@ string('accepted')->nullable(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('assets', function(Blueprint $table) - { - $table->dropColumn('accepted'); - }); - } +class AddAcceptedToAssets extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('assets', function (Blueprint $table) { + $table->string('accepted')->nullable(); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('assets', function (Blueprint $table) { + $table->dropColumn('accepted'); + }); + } } diff --git a/database/migrations/2015_09_09_195301_add_custom_css_to_settings.php b/database/migrations/2015_09_09_195301_add_custom_css_to_settings.php index 0baa89bb08..8acb55757b 100644 --- a/database/migrations/2015_09_09_195301_add_custom_css_to_settings.php +++ b/database/migrations/2015_09_09_195301_add_custom_css_to_settings.php @@ -1,34 +1,31 @@ text('custom_css')->nullable()->default(NULL); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('settings', function(Blueprint $table) - { - $table->dropColumn('custom_css'); - }); - } +class AddCustomCssToSettings extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('settings', function (Blueprint $table) { + $table->text('custom_css')->nullable()->default(null); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('settings', function (Blueprint $table) { + $table->dropColumn('custom_css'); + }); + } } diff --git a/database/migrations/2015_09_21_235926_create_custom_field_custom_fieldset.php b/database/migrations/2015_09_21_235926_create_custom_field_custom_fieldset.php index acf920ce73..6e56769d5c 100644 --- a/database/migrations/2015_09_21_235926_create_custom_field_custom_fieldset.php +++ b/database/migrations/2015_09_21_235926_create_custom_field_custom_fieldset.php @@ -1,36 +1,34 @@ integer('custom_field_id'); + $table->integer('custom_fieldset_id'); - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('custom_field_custom_fieldset', function(Blueprint $table) - { - $table->integer('custom_field_id'); - $table->integer('custom_fieldset_id'); - - $table->integer('order'); - $table->boolean('required'); - $table->engine = 'InnoDB'; - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::drop('custom_field_custom_fieldset'); - } + $table->integer('order'); + $table->boolean('required'); + $table->engine = 'InnoDB'; + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('custom_field_custom_fieldset'); + } } diff --git a/database/migrations/2015_09_22_000104_create_custom_fieldsets.php b/database/migrations/2015_09_22_000104_create_custom_fieldsets.php index 436a579692..5265404d15 100644 --- a/database/migrations/2015_09_22_000104_create_custom_fieldsets.php +++ b/database/migrations/2015_09_22_000104_create_custom_fieldsets.php @@ -1,34 +1,32 @@ increments('id'); - $table->string('name'); - $table->engine = 'InnoDB'; - // - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::drop('custom_fieldsets'); - } +class CreateCustomFieldsets extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('custom_fieldsets', function (Blueprint $table) { + $table->increments('id'); + $table->string('name'); + $table->engine = 'InnoDB'; + // + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('custom_fieldsets'); + } } diff --git a/database/migrations/2015_09_22_003321_add_fieldset_id_to_assets.php b/database/migrations/2015_09_22_003321_add_fieldset_id_to_assets.php index 7771b30e0e..721271250c 100644 --- a/database/migrations/2015_09_22_003321_add_fieldset_id_to_assets.php +++ b/database/migrations/2015_09_22_003321_add_fieldset_id_to_assets.php @@ -1,33 +1,31 @@ integer('fieldset_id')->nullable(); - }); - - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('models',function (Blueprint $table) { - $table->dropColumn('fieldset_id'); - }); - } +class AddFieldsetIdToAssets extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('models', function (Blueprint $table) { + $table->integer('fieldset_id')->nullable(); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('models', function (Blueprint $table) { + $table->dropColumn('fieldset_id'); + }); + } } diff --git a/database/migrations/2015_09_22_003413_migrate_mac_address.php b/database/migrations/2015_09_22_003413_migrate_mac_address.php index 6345773ca1..516b5c2ec7 100644 --- a/database/migrations/2015_09_22_003413_migrate_mac_address.php +++ b/database/migrations/2015_09_22_003413_migrate_mac_address.php @@ -1,61 +1,60 @@ getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string'); - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - DB::getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string'); + $f2 = new \App\Models\CustomFieldset(['name' => 'Asset with MAC Address']); + $f2->timestamps = false; //when this model was first created, it had no timestamps. But later on it gets them. + if (! $f2->save()) { + throw new Exception("couldn't save customfieldset"); + } + $macid = DB::table('custom_fields')->insertGetId([ + 'name' => 'MAC Address', + 'format' => \App\Models\CustomField::PREDEFINED_FORMATS['MAC'], + 'element'=>'text', ]); + if (! $macid) { + throw new Exception("Can't save MAC Custom field: $macid"); + } - $f2=new \App\Models\CustomFieldset(['name' => "Asset with MAC Address"]); - $f2->timestamps=false; //when this model was first created, it had no timestamps. But later on it gets them. - if(!$f2->save()) { - throw new Exception("couldn't save customfieldset"); - } - $macid=DB::table('custom_fields')->insertGetId([ - 'name' => "MAC Address", - 'format' => \App\Models\CustomField::PREDEFINED_FORMATS['MAC'], - 'element'=>'text']); - if(!$macid) { - throw new Exception("Can't save MAC Custom field: $macid"); - } + $f2->fields()->attach($macid, ['required' => false, 'order' => 1]); + \App\Models\AssetModel::where(['show_mac_address' => true])->update(['fieldset_id'=>$f2->id]); - $f2->fields()->attach($macid,['required' => false, 'order' => 1]); - \App\Models\AssetModel::where(["show_mac_address" => true])->update(["fieldset_id"=>$f2->id]); + Schema::table('assets', function (Blueprint $table) { + $table->renameColumn('mac_address', '_snipeit_mac_address'); + }); - Schema::table('assets', function (Blueprint $table) { - $table->renameColumn('mac_address', '_snipeit_mac_address'); - }); + // DB::statement("ALTER TABLE assets CHANGE mac_address _snipeit_mac_address varchar(255)"); - // DB::statement("ALTER TABLE assets CHANGE mac_address _snipeit_mac_address varchar(255)"); - - $ans=Schema::table("models",function (Blueprint $table) { - $table->renameColumn('show_mac_address','deprecated_mac_address'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - $f=\App\Models\CustomFieldset::where(["name" => "Asset with MAC Address"])->first(); - $f->fields()->delete(); - $f->delete(); - Schema::table("models",function(Blueprint $table) { - $table->renameColumn("deprecated_mac_address","show_mac_address"); - }); - DB::statement("ALTER TABLE assets CHANGE _snipeit_mac_address mac_address varchar(255)"); - } + $ans = Schema::table('models', function (Blueprint $table) { + $table->renameColumn('show_mac_address', 'deprecated_mac_address'); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + $f = \App\Models\CustomFieldset::where(['name' => 'Asset with MAC Address'])->first(); + $f->fields()->delete(); + $f->delete(); + Schema::table('models', function (Blueprint $table) { + $table->renameColumn('deprecated_mac_address', 'show_mac_address'); + }); + DB::statement('ALTER TABLE assets CHANGE _snipeit_mac_address mac_address varchar(255)'); + } } diff --git a/database/migrations/2015_09_28_003314_fix_default_purchase_order.php b/database/migrations/2015_09_28_003314_fix_default_purchase_order.php index 5e9f14c1a6..749df3c821 100644 --- a/database/migrations/2015_09_28_003314_fix_default_purchase_order.php +++ b/database/migrations/2015_09_28_003314_fix_default_purchase_order.php @@ -1,33 +1,32 @@ string('purchase_order')->nullable()->change(); + }); - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::table('licenses', function (Blueprint $table) { - $table->string('purchase_order')->nullable()->change(); - }); - - // DB::statement('ALTER TABLE `'.DB::getTablePrefix().'licenses` MODIFY `purchase_order` varchar(255) DEFAULT NULL;'); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - // DB::statement('ALTER TABLE `'.DB::getTablePrefix().'licenses` MODIFY `purchase_order` varchar(255);'); - } + // DB::statement('ALTER TABLE `'.DB::getTablePrefix().'licenses` MODIFY `purchase_order` varchar(255) DEFAULT NULL;'); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + // DB::statement('ALTER TABLE `'.DB::getTablePrefix().'licenses` MODIFY `purchase_order` varchar(255);'); + } } diff --git a/database/migrations/2015_10_01_024551_add_accessory_consumable_price_info.php b/database/migrations/2015_10_01_024551_add_accessory_consumable_price_info.php index 7e3535c71a..e9192fd56e 100644 --- a/database/migrations/2015_10_01_024551_add_accessory_consumable_price_info.php +++ b/database/migrations/2015_10_01_024551_add_accessory_consumable_price_info.php @@ -1,48 +1,47 @@ date('purchase_date')->nullable(); +class AddAccessoryConsumablePriceInfo extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('accessories', function ($table) { + $table->date('purchase_date')->nullable(); $table->decimal('purchase_cost', 13, 4)->nullable(); $table->string('order_number')->nullable(); - }); + }); - Schema::table('consumables', function ($table) { - $table->date('purchase_date')->nullable(); + Schema::table('consumables', function ($table) { + $table->date('purchase_date')->nullable(); $table->decimal('purchase_cost', 13, 4)->nullable(); $table->string('order_number')->nullable(); - }); - } + }); + } - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('accessories', function ($table) { - $table->dropColumn('purchase_date'); + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('accessories', function ($table) { + $table->dropColumn('purchase_date'); $table->dropColumn('purchase_cost'); $table->dropColumn('order_number'); - }); + }); - Schema::table('consumables', function ($table) { - $table->dropColumn('purchase_date'); + Schema::table('consumables', function ($table) { + $table->dropColumn('purchase_date'); $table->dropColumn('purchase_cost'); $table->dropColumn('order_number'); - }); - } - + }); + } } diff --git a/database/migrations/2015_10_12_192706_add_brand_to_settings.php b/database/migrations/2015_10_12_192706_add_brand_to_settings.php index eae3acd849..109a982a5a 100644 --- a/database/migrations/2015_10_12_192706_add_brand_to_settings.php +++ b/database/migrations/2015_10_12_192706_add_brand_to_settings.php @@ -1,34 +1,31 @@ tinyInteger('brand')->default(1); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('settings', function(Blueprint $table) - { - $table->dropColumn('brand'); - }); - } +class AddBrandToSettings extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('settings', function (Blueprint $table) { + $table->tinyInteger('brand')->default(1); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('settings', function (Blueprint $table) { + $table->dropColumn('brand'); + }); + } } diff --git a/database/migrations/2015_10_22_003314_fix_defaults_accessories.php b/database/migrations/2015_10_22_003314_fix_defaults_accessories.php index 9ac9e824d1..da7dcfbabe 100644 --- a/database/migrations/2015_10_22_003314_fix_defaults_accessories.php +++ b/database/migrations/2015_10_22_003314_fix_defaults_accessories.php @@ -1,41 +1,40 @@ string('order_number')->nullable()->change(); + }); - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::table('accessories', function (Blueprint $table) { - $table->string('order_number')->nullable()->change(); - }); - - Schema::table('consumables', function (Blueprint $table) { - $table->string('order_number')->nullable()->change(); - }); + Schema::table('consumables', function (Blueprint $table) { + $table->string('order_number')->nullable()->change(); + }); + // + // DB::statement('ALTER TABLE `'.DB::getTablePrefix().'accessories` MODIFY `order_number` varchar(255) DEFAULT NULL;'); // - // DB::statement('ALTER TABLE `'.DB::getTablePrefix().'accessories` MODIFY `order_number` varchar(255) DEFAULT NULL;'); - // - // DB::statement('ALTER TABLE `'.DB::getTablePrefix().'consumables` MODIFY `order_number` varchar(255) DEFAULT NULL;'); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - DB::statement('ALTER TABLE `'.DB::getTablePrefix().'accessories` MODIFY `order_number` varchar(255);'); - DB::statement('ALTER TABLE `'.DB::getTablePrefix().'consumables` MODIFY `order_number` varchar(255);'); - } + // DB::statement('ALTER TABLE `'.DB::getTablePrefix().'consumables` MODIFY `order_number` varchar(255) DEFAULT NULL;'); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + DB::statement('ALTER TABLE `'.DB::getTablePrefix().'accessories` MODIFY `order_number` varchar(255);'); + DB::statement('ALTER TABLE `'.DB::getTablePrefix().'consumables` MODIFY `order_number` varchar(255);'); + } } diff --git a/database/migrations/2015_10_23_182625_add_checkout_time_and_expected_checkout_date_to_assets.php b/database/migrations/2015_10_23_182625_add_checkout_time_and_expected_checkout_date_to_assets.php index ac220f5984..87ecf062d8 100644 --- a/database/migrations/2015_10_23_182625_add_checkout_time_and_expected_checkout_date_to_assets.php +++ b/database/migrations/2015_10_23_182625_add_checkout_time_and_expected_checkout_date_to_assets.php @@ -1,40 +1,37 @@ dateTime('last_checkout')->nullable(); - $table->date('expected_checkin')->nullable(); - }); - DB::statement("UPDATE ".DB::getTablePrefix()."assets SET last_checkout=(SELECT MAX(created_at) FROM ".DB::getTablePrefix()."asset_logs WHERE ".DB::getTablePrefix()."asset_logs.id=".DB::getTablePrefix()."assets.id AND action_type='checkout') WHERE assigned_to IS NOT NULL"); - DB::statement("UPDATE ".DB::getTablePrefix()."assets SET expected_checkin=(SELECT expected_checkin FROM ".DB::getTablePrefix()."asset_logs WHERE ".DB::getTablePrefix()."asset_logs.id=".DB::getTablePrefix()."assets.id AND action_type='checkout' ORDER BY id DESC limit 1) WHERE assigned_to IS NOT NULL"); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('assets', function(Blueprint $table) - { - // - $table->dropColumn('last_checkout'); - $table->dropColumn('expected_checkin'); - }); - } +class AddCheckoutTimeAndExpectedCheckoutDateToAssets extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('assets', function (Blueprint $table) { + // + $answer = $table->dateTime('last_checkout')->nullable(); + $table->date('expected_checkin')->nullable(); + }); + DB::statement('UPDATE '.DB::getTablePrefix().'assets SET last_checkout=(SELECT MAX(created_at) FROM '.DB::getTablePrefix().'asset_logs WHERE '.DB::getTablePrefix().'asset_logs.id='.DB::getTablePrefix()."assets.id AND action_type='checkout') WHERE assigned_to IS NOT NULL"); + DB::statement('UPDATE '.DB::getTablePrefix().'assets SET expected_checkin=(SELECT expected_checkin FROM '.DB::getTablePrefix().'asset_logs WHERE '.DB::getTablePrefix().'asset_logs.id='.DB::getTablePrefix()."assets.id AND action_type='checkout' ORDER BY id DESC limit 1) WHERE assigned_to IS NOT NULL"); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('assets', function (Blueprint $table) { + // + $table->dropColumn('last_checkout'); + $table->dropColumn('expected_checkin'); + }); + } } diff --git a/database/migrations/2015_11_05_061015_create_companies_table.php b/database/migrations/2015_11_05_061015_create_companies_table.php index d0bc86cbe6..4c7c736f5e 100644 --- a/database/migrations/2015_11_05_061015_create_companies_table.php +++ b/database/migrations/2015_11_05_061015_create_companies_table.php @@ -1,10 +1,10 @@ increments('id'); $table->string('name')->unique(); $table->timestamps(); diff --git a/database/migrations/2015_11_05_061115_add_company_id_to_consumables_table.php b/database/migrations/2015_11_05_061115_add_company_id_to_consumables_table.php index 930b47e3c9..afcb9e1c0f 100644 --- a/database/migrations/2015_11_05_061115_add_company_id_to_consumables_table.php +++ b/database/migrations/2015_11_05_061115_add_company_id_to_consumables_table.php @@ -1,10 +1,10 @@ integer('company_id')->unsigned()->nullable(); //$table->foreign('company_id')->references('id')->on('companies'); }); @@ -26,8 +25,7 @@ class AddCompanyIdToConsumablesTable extends Migration { */ public function down() { - Schema::table('consumables', function(Blueprint $table) - { + Schema::table('consumables', function (Blueprint $table) { //$table->dropForeign('consumables_company_id_foreign'); $table->dropColumn('company_id'); }); diff --git a/database/migrations/2015_11_05_183749_image.php b/database/migrations/2015_11_05_183749_image.php index 8d5749a43a..0582b852aa 100644 --- a/database/migrations/2015_11_05_183749_image.php +++ b/database/migrations/2015_11_05_183749_image.php @@ -1,34 +1,32 @@ text('image')->after('notes')->nullable()->default(NULL); - // - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('assets', function ($table) { - $table->dropColumn('image'); - }); - } +class Image extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('assets', function (Blueprint $table) { + $table->text('image')->after('notes')->nullable()->default(null); + // + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('assets', function ($table) { + $table->dropColumn('image'); + }); + } } diff --git a/database/migrations/2015_11_06_092038_add_company_id_to_accessories_table.php b/database/migrations/2015_11_06_092038_add_company_id_to_accessories_table.php index cee633bc3d..e51cb797ef 100644 --- a/database/migrations/2015_11_06_092038_add_company_id_to_accessories_table.php +++ b/database/migrations/2015_11_06_092038_add_company_id_to_accessories_table.php @@ -1,10 +1,10 @@ integer('company_id')->unsigned()->nullable(); //$table->foreign('company_id')->references('id')->on('companies'); }); @@ -26,8 +25,7 @@ class AddCompanyIdToAccessoriesTable extends Migration { */ public function down() { - Schema::table('accessories', function(Blueprint $table) - { + Schema::table('accessories', function (Blueprint $table) { //$table->dropForeign('accessories_company_id_foreign'); $table->dropColumn('company_id'); }); diff --git a/database/migrations/2015_11_06_100045_add_company_id_to_users_table.php b/database/migrations/2015_11_06_100045_add_company_id_to_users_table.php index aef83fe265..37e8ce12ee 100644 --- a/database/migrations/2015_11_06_100045_add_company_id_to_users_table.php +++ b/database/migrations/2015_11_06_100045_add_company_id_to_users_table.php @@ -1,10 +1,10 @@ integer('company_id')->unsigned()->nullable(); //$table->foreign('company_id')->references('id')->on('companies'); }); @@ -26,8 +25,7 @@ class AddCompanyIdToUsersTable extends Migration { */ public function down() { - Schema::table('users', function(Blueprint $table) - { + Schema::table('users', function (Blueprint $table) { //$table->dropForeign('users_company_id_foreign'); $table->dropColumn('company_id'); }); diff --git a/database/migrations/2015_11_06_134742_add_company_id_to_licenses_table.php b/database/migrations/2015_11_06_134742_add_company_id_to_licenses_table.php index 4f0756cf2c..2d4a5ba9df 100644 --- a/database/migrations/2015_11_06_134742_add_company_id_to_licenses_table.php +++ b/database/migrations/2015_11_06_134742_add_company_id_to_licenses_table.php @@ -1,10 +1,10 @@ integer('company_id')->unsigned()->nullable(); //$table->foreign('company_id')->references('id')->on('companies'); }); @@ -26,8 +25,7 @@ class AddCompanyIdToLicensesTable extends Migration { */ public function down() { - Schema::table('licenses', function(Blueprint $table) - { + Schema::table('licenses', function (Blueprint $table) { //$table->dropForeign('licenses_company_id_foreign'); $table->dropColumn('company_id'); }); diff --git a/database/migrations/2015_11_08_035832_add_company_id_to_assets_table.php b/database/migrations/2015_11_08_035832_add_company_id_to_assets_table.php index 010ec528e7..9aec3920eb 100644 --- a/database/migrations/2015_11_08_035832_add_company_id_to_assets_table.php +++ b/database/migrations/2015_11_08_035832_add_company_id_to_assets_table.php @@ -1,10 +1,10 @@ integer('company_id')->unsigned()->nullable(); //$table->foreign('company_id')->references('id')->on('companies'); }); @@ -26,8 +25,7 @@ class AddCompanyIdToAssetsTable extends Migration { */ public function down() { - Schema::table('assets', function(Blueprint $table) - { + Schema::table('assets', function (Blueprint $table) { // $table->dropForeign('assets_company_id_foreign'); $table->dropColumn('company_id'); }); diff --git a/database/migrations/2015_11_08_222305_add_ldap_fields_to_settings.php b/database/migrations/2015_11_08_222305_add_ldap_fields_to_settings.php index a293b43525..d52191f3d0 100644 --- a/database/migrations/2015_11_08_222305_add_ldap_fields_to_settings.php +++ b/database/migrations/2015_11_08_222305_add_ldap_fields_to_settings.php @@ -1,60 +1,57 @@ string('ldap_enabled')->nullable()->default(NULL); - $table->string('ldap_server')->nullable()->default(NULL); - $table->string('ldap_uname')->nullable()->default(NULL); - $table->longText('ldap_pword')->nullable()->default(NULL); - $table->string('ldap_basedn')->nullable()->default(NULL); - $table->string('ldap_filter')->nullable()->default('cn=*'); - $table->string('ldap_username_field')->nullable()->default('samaccountname'); - $table->string('ldap_lname_field')->nullable()->default('sn'); - $table->string('ldap_fname_field')->nullable()->default('givenname'); - $table->string('ldap_auth_filter_query')->nullable()->default('uid=samaccountname'); - $table->integer('ldap_version')->nullable()->default(3); - $table->string('ldap_active_flag')->nullable()->default(NULL); - $table->string('ldap_emp_num')->nullable()->default(NULL); - $table->string('ldap_email')->nullable()->default(NULL); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('settings', function(Blueprint $table) - { - $table->dropColumn('ldap_enabled'); - $table->dropColumn('ldap_server'); - $table->dropColumn('ldap_uname'); - $table->dropColumn('ldap_pword'); - $table->dropColumn('ldap_basedn'); - $table->dropColumn('ldap_filter'); - $table->dropColumn('ldap_username_field'); - $table->dropColumn('ldap_lname_field'); - $table->dropColumn('ldap_fname_field'); - $table->dropColumn('ldap_auth_filter_query'); - $table->dropColumn('ldap_version'); - $table->dropColumn('ldap_active_flag'); - $table->dropColumn('ldap_emp_num'); - $table->dropColumn('ldap_email'); - }); - } +class AddLdapFieldsToSettings extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('settings', function (Blueprint $table) { + $table->string('ldap_enabled')->nullable()->default(null); + $table->string('ldap_server')->nullable()->default(null); + $table->string('ldap_uname')->nullable()->default(null); + $table->longText('ldap_pword')->nullable()->default(null); + $table->string('ldap_basedn')->nullable()->default(null); + $table->string('ldap_filter')->nullable()->default('cn=*'); + $table->string('ldap_username_field')->nullable()->default('samaccountname'); + $table->string('ldap_lname_field')->nullable()->default('sn'); + $table->string('ldap_fname_field')->nullable()->default('givenname'); + $table->string('ldap_auth_filter_query')->nullable()->default('uid=samaccountname'); + $table->integer('ldap_version')->nullable()->default(3); + $table->string('ldap_active_flag')->nullable()->default(null); + $table->string('ldap_emp_num')->nullable()->default(null); + $table->string('ldap_email')->nullable()->default(null); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('settings', function (Blueprint $table) { + $table->dropColumn('ldap_enabled'); + $table->dropColumn('ldap_server'); + $table->dropColumn('ldap_uname'); + $table->dropColumn('ldap_pword'); + $table->dropColumn('ldap_basedn'); + $table->dropColumn('ldap_filter'); + $table->dropColumn('ldap_username_field'); + $table->dropColumn('ldap_lname_field'); + $table->dropColumn('ldap_fname_field'); + $table->dropColumn('ldap_auth_filter_query'); + $table->dropColumn('ldap_version'); + $table->dropColumn('ldap_active_flag'); + $table->dropColumn('ldap_emp_num'); + $table->dropColumn('ldap_email'); + }); + } } diff --git a/database/migrations/2015_11_15_151803_add_full_multiple_companies_support_to_settings_table.php b/database/migrations/2015_11_15_151803_add_full_multiple_companies_support_to_settings_table.php index 9cf8b163b0..b15db47da5 100644 --- a/database/migrations/2015_11_15_151803_add_full_multiple_companies_support_to_settings_table.php +++ b/database/migrations/2015_11_15_151803_add_full_multiple_companies_support_to_settings_table.php @@ -1,10 +1,10 @@ boolean('full_multiple_companies_support')->default(FALSE); + Schema::table('settings', function (Blueprint $table) { + $table->boolean('full_multiple_companies_support')->default(false); }); } @@ -25,10 +24,8 @@ class AddFullMultipleCompaniesSupportToSettingsTable extends Migration { */ public function down() { - Schema::table('settings', function(Blueprint $table) - { + Schema::table('settings', function (Blueprint $table) { $table->dropColumn('full_multiple_companies_support'); }); } - } diff --git a/database/migrations/2015_11_26_195528_import_ldap_settings.php b/database/migrations/2015_11_26_195528_import_ldap_settings.php index 3cd3826901..eb66bf6f68 100644 --- a/database/migrations/2015_11_26_195528_import_ldap_settings.php +++ b/database/migrations/2015_11_26_195528_import_ldap_settings.php @@ -1,77 +1,68 @@ ldap_server)) { + $settings->ldap_enabled = 1; + $settings->ldap_server = config('ldap.url'); + $settings->ldap_uname = config('ldap.username'); + $settings->ldap_pword = Crypt::encrypt(config('ldap.password')); + $settings->ldap_basedn = config('ldap.basedn'); + $settings->ldap_filter = config('ldap.filter'); + $settings->ldap_username_field = config('ldap.result.username'); + $settings->ldap_lname_field = config('ldap.result.last.name'); + $settings->ldap_fname_field = config('ldap.result.first.name'); + $settings->ldap_auth_filter_query = config('ldap.authentication.filter.query'); + $settings->ldap_version = config('ldap.version'); + $settings->ldap_active_flag = config('ldap.result.active.flag'); + $settings->ldap_emp_num = config('ldap.result.emp.num'); + $settings->ldap_email = config('ldap.result.email'); - // Only update the settings record if there IS an LDAP Config - // AND the Settings table doesn't already have LDAP settings in it + // Save the imported settings + if ($settings->save()) { + echo 'LDAP settings imported into database'."\n"; - if ((config('ldap.url')) && ($settings) && ($settings->ldap_server)) { - - $settings->ldap_enabled = 1; - $settings->ldap_server = config('ldap.url'); - $settings->ldap_uname = config('ldap.username'); - $settings->ldap_pword = Crypt::encrypt(config('ldap.password')); - $settings->ldap_basedn = config('ldap.basedn'); - $settings->ldap_filter = config('ldap.filter'); - $settings->ldap_username_field = config('ldap.result.username'); - $settings->ldap_lname_field = config('ldap.result.last.name'); - $settings->ldap_fname_field = config('ldap.result.first.name'); - $settings->ldap_auth_filter_query = config('ldap.authentication.filter.query'); - $settings->ldap_version = config('ldap.version'); - $settings->ldap_active_flag = config('ldap.result.active.flag'); - $settings->ldap_emp_num = config('ldap.result.emp.num'); - $settings->ldap_email = config('ldap.result.email'); - - // Save the imported settings - if ($settings->save()) { - echo 'LDAP settings imported into database'."\n"; - - // Copy the old LDAP config file to prevent any future confusion - if (@copy(app_path().'/config/'.app()->environment().'/ldap.php', app_path().'/config/'.app()->environment().'/deprecated.ldap.php')) { - - if (@unlink(app_path().'/config/'.app()->environment().'/ldap.php')) { - echo 'Original LDAP file archived to '.app_path().'/config/'.app()->environment().'/deprecated.ldap.php'."\n"; - } else { - echo 'Could not archive LDAP config file'."\n"; + // Copy the old LDAP config file to prevent any future confusion + if (@copy(app_path().'/config/'.app()->environment().'/ldap.php', app_path().'/config/'.app()->environment().'/deprecated.ldap.php')) { + if (@unlink(app_path().'/config/'.app()->environment().'/ldap.php')) { + echo 'Original LDAP file archived to '.app_path().'/config/'.app()->environment().'/deprecated.ldap.php'."\n"; + } else { + echo 'Could not archive LDAP config file'."\n"; + } + } else { + echo 'Could not archive LDAP config file'."\n"; + } } - - } else { - echo 'Could not archive LDAP config file'."\n"; } - - } - } - } - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - - if (@copy(app_path().'/config/'.app()->environment().'/deprecated.ldap.php', app_path().'/config/'.app()->environment().'/ldap.php')) { - echo 'Un-archived LDAP config file'."\n"; - @unlink(app_path().'/config/'.app()->environment().'/deprecated.ldap.php'); - - } else { - echo 'Could not un-archive LDAP config file. Manually rename it instead.'."\n"; + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + if (@copy(app_path().'/config/'.app()->environment().'/deprecated.ldap.php', app_path().'/config/'.app()->environment().'/ldap.php')) { + echo 'Un-archived LDAP config file'."\n"; + @unlink(app_path().'/config/'.app()->environment().'/deprecated.ldap.php'); + } else { + echo 'Could not un-archive LDAP config file. Manually rename it instead.'."\n"; + } } - } - } diff --git a/database/migrations/2015_11_30_191504_remove_fk_company_id.php b/database/migrations/2015_11_30_191504_remove_fk_company_id.php index bd0a9bda06..37ec4a1833 100644 --- a/database/migrations/2015_11_30_191504_remove_fk_company_id.php +++ b/database/migrations/2015_11_30_191504_remove_fk_company_id.php @@ -1,18 +1,18 @@ dropForeign('users_company_id_foreign'); @@ -37,18 +37,15 @@ class RemoveFkCompanyId extends Migration { // { // $table->dropForeign('licenses_company_id_foreign'); // }); + } - - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - } - + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + } } diff --git a/database/migrations/2015_12_21_193006_add_ldap_server_cert_ignore_to_settings_table.php b/database/migrations/2015_12_21_193006_add_ldap_server_cert_ignore_to_settings_table.php index 0e22c78683..ce0fad9e7a 100644 --- a/database/migrations/2015_12_21_193006_add_ldap_server_cert_ignore_to_settings_table.php +++ b/database/migrations/2015_12_21_193006_add_ldap_server_cert_ignore_to_settings_table.php @@ -1,34 +1,31 @@ boolean('ldap_server_cert_ignore')->default(FALSE); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('settings', function(Blueprint $table) - { - $table->dropColumn('ldap_server_cert_ignore'); - }); - } +class AddLdapServerCertIgnoreToSettingsTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('settings', function (Blueprint $table) { + $table->boolean('ldap_server_cert_ignore')->default(false); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('settings', function (Blueprint $table) { + $table->dropColumn('ldap_server_cert_ignore'); + }); + } } diff --git a/database/migrations/2015_12_30_233509_add_timestamp_and_userId_to_custom_fields.php b/database/migrations/2015_12_30_233509_add_timestamp_and_userId_to_custom_fields.php index 9b7854615a..52586b46a4 100644 --- a/database/migrations/2015_12_30_233509_add_timestamp_and_userId_to_custom_fields.php +++ b/database/migrations/2015_12_30_233509_add_timestamp_and_userId_to_custom_fields.php @@ -1,34 +1,31 @@ integer("user_id")->nullable(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('custom_fields', function(Blueprint $table) - { - $table->dropColumn("user_id"); - }); - } +class AddTimestampAndUserIdToCustomFields extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('custom_fields', function (Blueprint $table) { + $table->integer('user_id')->nullable(); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('custom_fields', function (Blueprint $table) { + $table->dropColumn('user_id'); + }); + } } diff --git a/database/migrations/2015_12_30_233658_add_timestamp_and_userId_to_custom_fieldsets.php b/database/migrations/2015_12_30_233658_add_timestamp_and_userId_to_custom_fieldsets.php index 1d2ba523ee..a0c475fac5 100644 --- a/database/migrations/2015_12_30_233658_add_timestamp_and_userId_to_custom_fieldsets.php +++ b/database/migrations/2015_12_30_233658_add_timestamp_and_userId_to_custom_fieldsets.php @@ -1,38 +1,34 @@ timestamps(); - $table->integer("user_id")->nullable(); - }); - - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('custom_fieldsets', function(Blueprint $table) - { - $table->dropTimestamps(); - $table->dropColumn("user_id"); - }); - } +class AddTimestampAndUserIdToCustomFieldsets extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + // + Schema::table('custom_fieldsets', function (Blueprint $table) { + $table->timestamps(); + $table->integer('user_id')->nullable(); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('custom_fieldsets', function (Blueprint $table) { + $table->dropTimestamps(); + $table->dropColumn('user_id'); + }); + } } diff --git a/database/migrations/2016_01_28_041048_add_notes_to_models.php b/database/migrations/2016_01_28_041048_add_notes_to_models.php index de922da180..abbc42dae1 100644 --- a/database/migrations/2016_01_28_041048_add_notes_to_models.php +++ b/database/migrations/2016_01_28_041048_add_notes_to_models.php @@ -1,32 +1,31 @@ text('note')->nullable()->default(NULL); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('models', function ($table) { - $table->dropColumn('note'); - }); - } +class AddNotesToModels extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('models', function ($table) { + $table->text('note')->nullable()->default(null); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('models', function ($table) { + $table->dropColumn('note'); + }); + } } diff --git a/database/migrations/2016_02_19_070119_add_remember_token_to_users_table.php b/database/migrations/2016_02_19_070119_add_remember_token_to_users_table.php index 6270018e53..06531a9584 100644 --- a/database/migrations/2016_02_19_070119_add_remember_token_to_users_table.php +++ b/database/migrations/2016_02_19_070119_add_remember_token_to_users_table.php @@ -1,7 +1,7 @@ text('remember_token')->nullable()->default(null); }); diff --git a/database/migrations/2016_02_19_073625_create_password_resets_table.php b/database/migrations/2016_02_19_073625_create_password_resets_table.php index 113175711b..2a5c366cb4 100644 --- a/database/migrations/2016_02_19_073625_create_password_resets_table.php +++ b/database/migrations/2016_02_19_073625_create_password_resets_table.php @@ -1,7 +1,7 @@ engine = 'InnoDB'; - $table->string('email')->index(); - $table->string('token')->index(); - $table->timestamp('created_at'); - }); + Schema::create('password_resets', function (Blueprint $table) { + $table->engine = 'InnoDB'; + $table->string('email')->index(); + $table->string('token')->index(); + $table->timestamp('created_at'); + }); } /** diff --git a/database/migrations/2016_03_02_193043_add_ldap_flag_to_users.php b/database/migrations/2016_03_02_193043_add_ldap_flag_to_users.php index c7e6f2b9a7..7c51eaf4c5 100644 --- a/database/migrations/2016_03_02_193043_add_ldap_flag_to_users.php +++ b/database/migrations/2016_03_02_193043_add_ldap_flag_to_users.php @@ -1,7 +1,7 @@ boolean('ldap_import')->default(0); - }); - - DB::table('users')->where('notes','LIKE','%LDAP%')->update(['ldap_import' => 1]); + Schema::table('users', function (Blueprint $table) { + $table->boolean('ldap_import')->default(0); + }); + DB::table('users')->where('notes', 'LIKE', '%LDAP%')->update(['ldap_import' => 1]); } /** @@ -27,8 +26,8 @@ class AddLdapFlagToUsers extends Migration */ public function down() { - Schema::table('users', function ($table) { - $table->dropColumn('ldap_import'); - }); + Schema::table('users', function ($table) { + $table->dropColumn('ldap_import'); + }); } } diff --git a/database/migrations/2016_03_02_220517_update_ldap_filter_to_longer_field.php b/database/migrations/2016_03_02_220517_update_ldap_filter_to_longer_field.php index 57a1786dba..a17830f114 100644 --- a/database/migrations/2016_03_02_220517_update_ldap_filter_to_longer_field.php +++ b/database/migrations/2016_03_02_220517_update_ldap_filter_to_longer_field.php @@ -1,7 +1,7 @@ text('ldap_filter')->default(NULL)->change(); - }); + Schema::table('settings', function (Blueprint $table) { + $table->text('ldap_filter')->default(null)->change(); + }); } /** diff --git a/database/migrations/2016_03_08_225351_create_components_table.php b/database/migrations/2016_03_08_225351_create_components_table.php index 446285b014..8a3dfb7c5a 100644 --- a/database/migrations/2016_03_08_225351_create_components_table.php +++ b/database/migrations/2016_03_08_225351_create_components_table.php @@ -1,68 +1,61 @@ increments('id'); - $table->string('name')->nullable()->default(NULL); - $table->integer('category_id')->nullable()->default(NULL); - $table->integer('location_id')->nullable()->default(NULL); - $table->integer('company_id')->nullable()->default(NULL); - $table->integer('user_id')->nullable()->default(NULL); - $table->integer('total_qty')->default(1); - $table->integer('order_number')->nullable()->default(NULL); - $table->date('purchase_date')->nullable()->default(NULL); - $table->decimal('purchase_cost', 13,4)->nullable()->default(NULL); - $table->timestamps(); - $table->softDeletes(); - $table->engine = 'InnoDB'; - }); + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + // + Schema::create('components', function ($table) { + $table->increments('id'); + $table->string('name')->nullable()->default(null); + $table->integer('category_id')->nullable()->default(null); + $table->integer('location_id')->nullable()->default(null); + $table->integer('company_id')->nullable()->default(null); + $table->integer('user_id')->nullable()->default(null); + $table->integer('total_qty')->default(1); + $table->integer('order_number')->nullable()->default(null); + $table->date('purchase_date')->nullable()->default(null); + $table->decimal('purchase_cost', 13, 4)->nullable()->default(null); + $table->timestamps(); + $table->softDeletes(); + $table->engine = 'InnoDB'; + }); Schema::table('asset_logs', function ($table) { - $table->integer('component_id')->nullable()->default(NULL); - }); + $table->integer('component_id')->nullable()->default(null); + }); - Schema::create('components_assets', function ($table) { - $table->increments('id'); - $table->integer('user_id')->nullable()->default(NULL); - $table->integer('assigned_qty')->nullable()->default(1); - $table->integer('component_id')->nullable()->default(NULL); - $table->integer('asset_id')->nullable()->default(NULL); - $table->timestamps(); - }); + Schema::create('components_assets', function ($table) { + $table->increments('id'); + $table->integer('user_id')->nullable()->default(null); + $table->integer('assigned_qty')->nullable()->default(1); + $table->integer('component_id')->nullable()->default(null); + $table->integer('asset_id')->nullable()->default(null); + $table->timestamps(); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::dropIfExists('components'); + Schema::dropIfExists('components_assets'); - - } - - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::dropIfExists('components'); - Schema::dropIfExists('components_assets'); - - Schema::table('asset_logs', function ($table) { - $table->dropColumn('component_id'); - }); - - - } - + Schema::table('asset_logs', function ($table) { + $table->dropColumn('component_id'); + }); + } } diff --git a/database/migrations/2016_03_09_024038_add_min_stock_to_tables.php b/database/migrations/2016_03_09_024038_add_min_stock_to_tables.php index 5fd8cc6e2e..6d00779f74 100644 --- a/database/migrations/2016_03_09_024038_add_min_stock_to_tables.php +++ b/database/migrations/2016_03_09_024038_add_min_stock_to_tables.php @@ -1,7 +1,7 @@ integer('min_amt')->nullable()->default(NULL); - }); - Schema::table('consumables', function (Blueprint $table) { - $table->integer('min_amt')->nullable()->default(NULL); - }); - Schema::table('components', function (Blueprint $table) { - $table->integer('min_amt')->nullable()->default(NULL); - }); + Schema::table('accessories', function (Blueprint $table) { + $table->integer('min_amt')->nullable()->default(null); + }); + Schema::table('consumables', function (Blueprint $table) { + $table->integer('min_amt')->nullable()->default(null); + }); + Schema::table('components', function (Blueprint $table) { + $table->integer('min_amt')->nullable()->default(null); + }); } /** @@ -30,14 +30,14 @@ class AddMinStockToTables extends Migration */ public function down() { - Schema::table('accessories', function ($table) { - $table->dropColumn('min_amt'); - }); - Schema::table('components', function ($table) { - $table->dropColumn('min_amt'); - }); - Schema::table('consumables', function ($table) { - $table->dropColumn('min_amt'); - }); + Schema::table('accessories', function ($table) { + $table->dropColumn('min_amt'); + }); + Schema::table('components', function ($table) { + $table->dropColumn('min_amt'); + }); + Schema::table('consumables', function ($table) { + $table->dropColumn('min_amt'); + }); } } diff --git a/database/migrations/2016_03_10_133849_add_locale_to_users.php b/database/migrations/2016_03_10_133849_add_locale_to_users.php index cf2d484dee..9a903f5391 100644 --- a/database/migrations/2016_03_10_133849_add_locale_to_users.php +++ b/database/migrations/2016_03_10_133849_add_locale_to_users.php @@ -1,7 +1,7 @@ string('locale',5)->nullable()->default(config('app.locale')); - }); + Schema::table('users', function (Blueprint $table) { + $table->string('locale', 5)->nullable()->default(config('app.locale')); + }); } /** @@ -24,8 +24,8 @@ class AddLocaleToUsers extends Migration */ public function down() { - Schema::table('users', function ($table) { - $table->dropColumn('locale'); - }); + Schema::table('users', function ($table) { + $table->dropColumn('locale'); + }); } } diff --git a/database/migrations/2016_03_10_135519_add_locale_to_settings.php b/database/migrations/2016_03_10_135519_add_locale_to_settings.php index 58ade4724f..e9ee81aaf4 100644 --- a/database/migrations/2016_03_10_135519_add_locale_to_settings.php +++ b/database/migrations/2016_03_10_135519_add_locale_to_settings.php @@ -1,7 +1,7 @@ string('locale',5)->nullable()->default(config('app.locale')); - }); + Schema::table('settings', function (Blueprint $table) { + $table->string('locale', 5)->nullable()->default(config('app.locale')); + }); } /** @@ -24,8 +24,8 @@ class AddLocaleToSettings extends Migration */ public function down() { - Schema::table('settings', function ($table) { - $table->dropColumn('locale'); - }); + Schema::table('settings', function ($table) { + $table->dropColumn('locale'); + }); } } diff --git a/database/migrations/2016_03_11_185621_add_label_settings_to_settings.php b/database/migrations/2016_03_11_185621_add_label_settings_to_settings.php index ab85695cbd..679bf51994 100644 --- a/database/migrations/2016_03_11_185621_add_label_settings_to_settings.php +++ b/database/migrations/2016_03_11_185621_add_label_settings_to_settings.php @@ -1,7 +1,7 @@ tinyInteger('labels_per_page')->default(30); - $table->decimal('labels_width', 6, 5)->default(2.625); - $table->decimal('labels_height', 6, 5)->default(1); - $table->decimal('labels_pmargin_left', 6, 5)->default(0.21975); - $table->decimal('labels_pmargin_right', 6, 5)->default(0.21975); - $table->decimal('labels_pmargin_top', 6, 5)->default(0.5); - $table->decimal('labels_pmargin_bottom', 6, 5)->default(0.5); - $table->decimal('labels_display_bgutter', 6, 5)->default(0.07); - $table->decimal('labels_display_sgutter', 6, 5)->default(0.05); - $table->tinyInteger('labels_fontsize')->default(9); - $table->decimal('labels_pagewidth', 7, 5)->default(8.5); - $table->decimal('labels_pageheight', 7, 5)->default(11); - $table->tinyInteger('labels_display_name')->default(0); - $table->tinyInteger('labels_display_serial')->default(1); - $table->tinyInteger('labels_display_tag')->default(1); - }); + Schema::table('settings', function (Blueprint $table) { + $table->tinyInteger('labels_per_page')->default(30); + $table->decimal('labels_width', 6, 5)->default(2.625); + $table->decimal('labels_height', 6, 5)->default(1); + $table->decimal('labels_pmargin_left', 6, 5)->default(0.21975); + $table->decimal('labels_pmargin_right', 6, 5)->default(0.21975); + $table->decimal('labels_pmargin_top', 6, 5)->default(0.5); + $table->decimal('labels_pmargin_bottom', 6, 5)->default(0.5); + $table->decimal('labels_display_bgutter', 6, 5)->default(0.07); + $table->decimal('labels_display_sgutter', 6, 5)->default(0.05); + $table->tinyInteger('labels_fontsize')->default(9); + $table->decimal('labels_pagewidth', 7, 5)->default(8.5); + $table->decimal('labels_pageheight', 7, 5)->default(11); + $table->tinyInteger('labels_display_name')->default(0); + $table->tinyInteger('labels_display_serial')->default(1); + $table->tinyInteger('labels_display_tag')->default(1); + }); } /** @@ -38,8 +38,8 @@ class AddLabelSettingsToSettings extends Migration */ public function down() { - Schema::table('settings', function ($table) { - $table->dropColumn( + Schema::table('settings', function ($table) { + $table->dropColumn( 'labels_per_page', 'labels_width', 'labels_height', @@ -56,6 +56,6 @@ class AddLabelSettingsToSettings extends Migration 'labels_display_serial', 'labels_display_tag' ); - }); + }); } } diff --git a/database/migrations/2016_03_22_125911_fix_custom_fields_regexes.php b/database/migrations/2016_03_22_125911_fix_custom_fields_regexes.php index e731a1b05e..8634ede9af 100644 --- a/database/migrations/2016_03_22_125911_fix_custom_fields_regexes.php +++ b/database/migrations/2016_03_22_125911_fix_custom_fields_regexes.php @@ -1,7 +1,7 @@ format) { + foreach (\App\Models\CustomField::all() as $custom_field) { + switch ($custom_field->format) { case '[a-zA-Z]*': - $custom_field->format='ALPHA'; + $custom_field->format = 'ALPHA'; break; case '[0-9]*': - $custom_field->format='NUMERIC'; + $custom_field->format = 'NUMERIC'; break; case '([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])': - $custom_field->format='IP'; + $custom_field->format = 'IP'; break; //ANYTHING ELSE. default: - $custom_field->format='regex:/^'.$custom_field->format."$/"; + $custom_field->format = 'regex:/^'.$custom_field->format.'$/'; } $custom_field->save(); } - } /** diff --git a/database/migrations/2016_04_28_141554_add_show_to_users.php b/database/migrations/2016_04_28_141554_add_show_to_users.php index 52b80d6fd9..8b6fd47122 100644 --- a/database/migrations/2016_04_28_141554_add_show_to_users.php +++ b/database/migrations/2016_04_28_141554_add_show_to_users.php @@ -1,7 +1,7 @@ boolean('show_in_list')->default(1); + $table->boolean('show_in_list')->default(1); }); } diff --git a/database/migrations/2016_05_16_164733_add_model_mfg_to_consumable.php b/database/migrations/2016_05_16_164733_add_model_mfg_to_consumable.php index 182eedae49..180ef43279 100644 --- a/database/migrations/2016_05_16_164733_add_model_mfg_to_consumable.php +++ b/database/migrations/2016_05_16_164733_add_model_mfg_to_consumable.php @@ -1,7 +1,7 @@ integer('model_no')->nullable()->default(NULL); - $table->integer('manufacturer_id')->nullable()->default(NULL); - $table->string('item_no')->nullable()->default(NULL); + $table->integer('model_no')->nullable()->default(null); + $table->integer('manufacturer_id')->nullable()->default(null); + $table->string('item_no')->nullable()->default(null); }); } diff --git a/database/migrations/2016_05_19_180351_add_alt_barcode_settings.php b/database/migrations/2016_05_19_180351_add_alt_barcode_settings.php index bbd849a24e..68320ae9ed 100644 --- a/database/migrations/2016_05_19_180351_add_alt_barcode_settings.php +++ b/database/migrations/2016_05_19_180351_add_alt_barcode_settings.php @@ -1,7 +1,7 @@ dropColumn('option_name'); + } }); } diff --git a/database/migrations/2016_05_20_143758_remove_option_value_from_settings_table.php b/database/migrations/2016_05_20_143758_remove_option_value_from_settings_table.php index 2836aaefb6..dccbbe5e60 100644 --- a/database/migrations/2016_05_20_143758_remove_option_value_from_settings_table.php +++ b/database/migrations/2016_05_20_143758_remove_option_value_from_settings_table.php @@ -1,7 +1,7 @@ dropColumn('option_value'); + } }); } diff --git a/database/migrations/2016_06_01_000001_create_oauth_auth_codes_table.php b/database/migrations/2016_06_01_000001_create_oauth_auth_codes_table.php index a7261b4278..86ebc1d6ca 100644 --- a/database/migrations/2016_06_01_000001_create_oauth_auth_codes_table.php +++ b/database/migrations/2016_06_01_000001_create_oauth_auth_codes_table.php @@ -13,7 +13,7 @@ class CreateOauthAuthCodesTable extends Migration */ public function up() { - if (!Schema::hasTable('oauth_auth_codes')) { + if (! Schema::hasTable('oauth_auth_codes')) { Schema::create('oauth_auth_codes', function (Blueprint $table) { $table->string('id', 100)->primary(); $table->unsignedBigInteger('user_id')->index(); @@ -32,6 +32,6 @@ class CreateOauthAuthCodesTable extends Migration */ public function down() { - Schema::dropIfExists('oauth_auth_codes'); + Schema::dropIfExists('oauth_auth_codes'); } } diff --git a/database/migrations/2016_06_01_000002_create_oauth_access_tokens_table.php b/database/migrations/2016_06_01_000002_create_oauth_access_tokens_table.php index ca15e62454..a12ea153bb 100644 --- a/database/migrations/2016_06_01_000002_create_oauth_access_tokens_table.php +++ b/database/migrations/2016_06_01_000002_create_oauth_access_tokens_table.php @@ -13,8 +13,7 @@ class CreateOauthAccessTokensTable extends Migration */ public function up() { - if (!Schema::hasTable('oauth_access_tokens')) { - + if (! Schema::hasTable('oauth_access_tokens')) { Schema::create('oauth_access_tokens', function (Blueprint $table) { $table->string('id', 100)->primary(); $table->unsignedBigInteger('user_id')->nullable()->index(); @@ -35,6 +34,6 @@ class CreateOauthAccessTokensTable extends Migration */ public function down() { - Schema::dropIfExists('oauth_access_tokens'); + Schema::dropIfExists('oauth_access_tokens'); } } diff --git a/database/migrations/2016_06_01_000003_create_oauth_refresh_tokens_table.php b/database/migrations/2016_06_01_000003_create_oauth_refresh_tokens_table.php index 9d7327d69c..30c4e27546 100644 --- a/database/migrations/2016_06_01_000003_create_oauth_refresh_tokens_table.php +++ b/database/migrations/2016_06_01_000003_create_oauth_refresh_tokens_table.php @@ -13,7 +13,7 @@ class CreateOauthRefreshTokensTable extends Migration */ public function up() { - if (!Schema::hasTable('oauth_refresh_tokens')) { + if (! Schema::hasTable('oauth_refresh_tokens')) { Schema::create('oauth_refresh_tokens', function (Blueprint $table) { $table->string('id', 100)->primary(); $table->string('access_token_id', 100); @@ -30,6 +30,6 @@ class CreateOauthRefreshTokensTable extends Migration */ public function down() { - Schema::dropIfExists('oauth_refresh_tokens'); + Schema::dropIfExists('oauth_refresh_tokens'); } } diff --git a/database/migrations/2016_06_01_000004_create_oauth_clients_table.php b/database/migrations/2016_06_01_000004_create_oauth_clients_table.php index 65937a72af..0046eb6e79 100644 --- a/database/migrations/2016_06_01_000004_create_oauth_clients_table.php +++ b/database/migrations/2016_06_01_000004_create_oauth_clients_table.php @@ -13,7 +13,7 @@ class CreateOauthClientsTable extends Migration */ public function up() { - if (!Schema::hasTable('oauth_clients')) { + if (! Schema::hasTable('oauth_clients')) { Schema::create('oauth_clients', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('user_id')->nullable()->index(); @@ -35,6 +35,6 @@ class CreateOauthClientsTable extends Migration */ public function down() { - Schema::dropIfExists('oauth_clients'); + Schema::dropIfExists('oauth_clients'); } } diff --git a/database/migrations/2016_06_01_000005_create_oauth_personal_access_clients_table.php b/database/migrations/2016_06_01_000005_create_oauth_personal_access_clients_table.php index b469b42364..0a50768ed8 100644 --- a/database/migrations/2016_06_01_000005_create_oauth_personal_access_clients_table.php +++ b/database/migrations/2016_06_01_000005_create_oauth_personal_access_clients_table.php @@ -13,14 +13,13 @@ class CreateOauthPersonalAccessClientsTable extends Migration */ public function up() { - if (!Schema::hasTable('oauth_personal_access_clients')) { + if (! Schema::hasTable('oauth_personal_access_clients')) { Schema::create('oauth_personal_access_clients', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('client_id'); $table->timestamps(); }); } - } /** @@ -30,6 +29,6 @@ class CreateOauthPersonalAccessClientsTable extends Migration */ public function down() { - Schema::dropIfExists('oauth_personal_access_clients'); + Schema::dropIfExists('oauth_personal_access_clients'); } } diff --git a/database/migrations/2016_06_01_140218_add_email_domain_and_format_to_settings.php b/database/migrations/2016_06_01_140218_add_email_domain_and_format_to_settings.php index a2b29e9b60..02789e8a99 100644 --- a/database/migrations/2016_06_01_140218_add_email_domain_and_format_to_settings.php +++ b/database/migrations/2016_06_01_140218_add_email_domain_and_format_to_settings.php @@ -1,7 +1,7 @@ string('email_domain')->nullable()->default(NULL); + $table->string('email_domain')->nullable()->default(null); $table->string('email_format')->nullable()->default('filastname'); $table->string('username_format')->nullable()->default('filastname'); }); diff --git a/database/migrations/2016_06_22_160725_add_user_id_to_maintenances.php b/database/migrations/2016_06_22_160725_add_user_id_to_maintenances.php index cdbd128759..284a63ca9b 100644 --- a/database/migrations/2016_06_22_160725_add_user_id_to_maintenances.php +++ b/database/migrations/2016_06_22_160725_add_user_id_to_maintenances.php @@ -1,7 +1,7 @@ integer('user_id')->nullable()->default(NULL); + $table->integer('user_id')->nullable()->default(null); }); } diff --git a/database/migrations/2016_07_13_150015_add_is_ad_to_settings.php b/database/migrations/2016_07_13_150015_add_is_ad_to_settings.php index ad6bc1beec..35543c90fe 100644 --- a/database/migrations/2016_07_13_150015_add_is_ad_to_settings.php +++ b/database/migrations/2016_07_13_150015_add_is_ad_to_settings.php @@ -1,7 +1,7 @@ string('ad_domain')->nullable()->default(NULL); + $table->string('ad_domain')->nullable()->default(null); }); } diff --git a/database/migrations/2016_07_22_003348_fix_custom_fields_regex_stuff.php b/database/migrations/2016_07_22_003348_fix_custom_fields_regex_stuff.php index f487910823..da81cb1e50 100644 --- a/database/migrations/2016_07_22_003348_fix_custom_fields_regex_stuff.php +++ b/database/migrations/2016_07_22_003348_fix_custom_fields_regex_stuff.php @@ -1,7 +1,7 @@ format, 'ALPHA') !== false) { - $custom_field->format='alpha'; + $custom_field->format = 'alpha'; // Numeric } elseif (stripos($custom_field->format, 'NUMERIC') !== false) { - $custom_field->format='numeric'; + $custom_field->format = 'numeric'; // IP } elseif (stripos($custom_field->format, 'IP') !== false) { - $custom_field->format='ip'; + $custom_field->format = 'ip'; // Email } elseif (stripos($custom_field->format, 'EMAIL') !== false) { - $custom_field->format='email'; + $custom_field->format = 'email'; // MAC } elseif (stripos($custom_field->format, 'regex:/^[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}$/') !== false) { - $custom_field->format='regex:/^[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}$/'; + $custom_field->format = 'regex:/^[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}$/'; // Date } elseif (stripos($custom_field->format, 'DATE') !== false) { - $custom_field->format='date'; - + $custom_field->format = 'date'; // URL } elseif (stripos($custom_field->format, 'URL') !== false) { - $custom_field->format='url'; + $custom_field->format = 'url'; // ANY } elseif (stripos($custom_field->format, 'ANY') !== false) { - $custom_field->format=''; + $custom_field->format = ''; // Fix any custom regexes } else { diff --git a/database/migrations/2016_07_22_054850_one_more_mac_addr_fix.php b/database/migrations/2016_07_22_054850_one_more_mac_addr_fix.php index cc45976d54..ac64e278fe 100644 --- a/database/migrations/2016_07_22_054850_one_more_mac_addr_fix.php +++ b/database/migrations/2016_07_22_054850_one_more_mac_addr_fix.php @@ -1,7 +1,7 @@ format=='regex:/^MAC$/') { + foreach (\App\Models\CustomField::all() as $custom_field) { + if ($custom_field->format == 'regex:/^MAC$/') { $custom_field->format = 'regex:/^[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}$/'; } $custom_field->save(); - } } diff --git a/database/migrations/2016_07_22_143045_add_port_to_ldap_settings.php b/database/migrations/2016_07_22_143045_add_port_to_ldap_settings.php index b0dd1a601c..1eda0698a5 100644 --- a/database/migrations/2016_07_22_143045_add_port_to_ldap_settings.php +++ b/database/migrations/2016_07_22_143045_add_port_to_ldap_settings.php @@ -1,7 +1,7 @@ string('color', 10)->nullable()->default(NULL); + $table->string('color', 10)->nullable()->default(null); }); } diff --git a/database/migrations/2016_08_04_134500_add_disallow_ldap_pw_sync_to_settings.php b/database/migrations/2016_08_04_134500_add_disallow_ldap_pw_sync_to_settings.php index c46203fdad..d141af056c 100644 --- a/database/migrations/2016_08_04_134500_add_disallow_ldap_pw_sync_to_settings.php +++ b/database/migrations/2016_08_04_134500_add_disallow_ldap_pw_sync_to_settings.php @@ -1,7 +1,7 @@ getDoctrineSchemaManager()->getDatabasePlatform(); $platform->registerDoctrineTypeMapping('enum', 'string'); Schema::table('assets', function ($table) { - $table->decimal('purchase_cost',8,2)->nullable()->default(null)->change(); + $table->decimal('purchase_cost', 8, 2)->nullable()->default(null)->change(); }); } diff --git a/database/migrations/2016_09_01_141051_add_requestable_to_asset_model.php b/database/migrations/2016_09_01_141051_add_requestable_to_asset_model.php index 6fc16b9cdf..89b5dfc556 100644 --- a/database/migrations/2016_09_01_141051_add_requestable_to_asset_model.php +++ b/database/migrations/2016_09_01_141051_add_requestable_to_asset_model.php @@ -1,7 +1,7 @@ increments('id'); $table->integer('user_id')->nullable(); diff --git a/database/migrations/2016_09_04_182149_migrate_asset_log_to_action_log.php b/database/migrations/2016_09_04_182149_migrate_asset_log_to_action_log.php index 4d0de747ae..874f7a6070 100644 --- a/database/migrations/2016_09_04_182149_migrate_asset_log_to_action_log.php +++ b/database/migrations/2016_09_04_182149_migrate_asset_log_to_action_log.php @@ -23,45 +23,44 @@ class MigrateAssetLogToActionLog extends Migration // var_dump($log); $a->user_id = $log->user_id; - if (!is_null($log->asset_id)) { + if (! is_null($log->asset_id)) { $a->item_id = $log->asset_id; - if ($log->asset_type == "hardware") { - $a->item_type = 'App\\Models\\Asset'; + if ($log->asset_type == 'hardware') { + $a->item_type = \App\Models\Asset::class; } else { - $a->item_type = 'App\\Models\\License'; + $a->item_type = \App\Models\License::class; } } - if (!is_null($log->accessory_id)) { + if (! is_null($log->accessory_id)) { $a->item_id = $log->accessory_id; - $a->item_type = 'App\\Models\\Accessory'; - } else if (!is_null($log->consumable_id)) { + $a->item_type = \App\Models\Accessory::class; + } elseif (! is_null($log->consumable_id)) { $a->item_id = $log->consumable_id; - $a->item_type = 'App\\Models\\Consumable'; - } else if (!is_null($log->component_id)) { + $a->item_type = \App\Models\Consumable::class; + } elseif (! is_null($log->component_id)) { $a->item_id = $log->component_id; - $a->item_type = 'App\\Models\\Component'; + $a->item_type = \App\Models\Component::class; } $a->action_type = $log->action_type; // $a->checkout_to = $log->checkout_to; - if(!is_null($log->checkedout_to)) { + if (! is_null($log->checkedout_to)) { $a->target_id = $log->checkedout_to; $a->target_type = User::class; } - if(!is_null($log->accepted_id)) { + if (! is_null($log->accepted_id)) { $a->target_id = $log->accepted_id; $a->target_type = User::class; } - $a->location_id = $log->location_id; - $a->created_at = $log->created_at; - $a->updated_at = $log->updated_at; - $a->deleted_at = $log->deleted_at; - $a->note = $log->note; - $a->expected_checkin = $log->expected_checkin; - $a->accepted_id = $log->accepted_id; - $a->filename = $log->filename; + $a->location_id = $log->location_id; + $a->created_at = $log->created_at; + $a->updated_at = $log->updated_at; + $a->deleted_at = $log->deleted_at; + $a->note = $log->note; + $a->expected_checkin = $log->expected_checkin; + $a->accepted_id = $log->accepted_id; + $a->filename = $log->filename; $a->save(); - } // dd($logs); } diff --git a/database/migrations/2016_09_19_235935_fix_fieldtype_for_target_type.php b/database/migrations/2016_09_19_235935_fix_fieldtype_for_target_type.php index db10820f60..0d74936ef6 100644 --- a/database/migrations/2016_09_19_235935_fix_fieldtype_for_target_type.php +++ b/database/migrations/2016_09_19_235935_fix_fieldtype_for_target_type.php @@ -1,7 +1,7 @@ get(); foreach ($logs as $log) { - if($log->item) { + if ($log->item) { $log->company_id = $log->item->company_id; $log->save(); } else { diff --git a/database/migrations/2016_10_14_130709_fix_order_number_to_varchar.php b/database/migrations/2016_10_14_130709_fix_order_number_to_varchar.php index 96f801987f..280984e33e 100644 --- a/database/migrations/2016_10_14_130709_fix_order_number_to_varchar.php +++ b/database/migrations/2016_10_14_130709_fix_order_number_to_varchar.php @@ -1,7 +1,7 @@ renameColumn('model_number', 'modelno'); - }); } } diff --git a/database/migrations/2016_10_16_015211_rename_consumable_modelno_to_model_number.php b/database/migrations/2016_10_16_015211_rename_consumable_modelno_to_model_number.php index daf93c3ac5..86718230d0 100644 --- a/database/migrations/2016_10_16_015211_rename_consumable_modelno_to_model_number.php +++ b/database/migrations/2016_10_16_015211_rename_consumable_modelno_to_model_number.php @@ -1,7 +1,7 @@ renameColumn('notes', 'note'); }); } diff --git a/database/migrations/2016_10_16_165052_rename_component_total_qty_to_qty.php b/database/migrations/2016_10_16_165052_rename_component_total_qty_to_qty.php index 1aba51ce99..e9fa829c7c 100644 --- a/database/migrations/2016_10_16_165052_rename_component_total_qty_to_qty.php +++ b/database/migrations/2016_10_16_165052_rename_component_total_qty_to_qty.php @@ -1,7 +1,7 @@ string('serial_number')->nullable()->default(null); }); - } /** @@ -28,6 +27,5 @@ class AddSerialToComponents extends Migration Schema::table('components', function ($table) { $table->dropColumn('serial_number'); }); - } } diff --git a/database/migrations/2016_10_27_213251_increase_serial_field_capacity.php b/database/migrations/2016_10_27_213251_increase_serial_field_capacity.php index f81c9373ef..71302ff3ac 100644 --- a/database/migrations/2016_10_27_213251_increase_serial_field_capacity.php +++ b/database/migrations/2016_10_27_213251_increase_serial_field_capacity.php @@ -1,7 +1,7 @@ where('filename', '!=', null)->get(); // - foreach($logs as $log) { + foreach ($logs as $log) { $matching_action_log = Actionlog::where('item_id', $log->asset_id) ->where('created_at', $log->created_at) ->where('note', $log->note) @@ -24,21 +24,19 @@ class FixForgottenFilenameInActionLogs extends Migration ->withTrashed() ->get()->first(); - if($matching_action_log) { + if ($matching_action_log) { $matching_action_log->filename = $log->filename; $matching_action_log->save(); - }else{ - echo("Couldn't find matching Action log row when trying to migrate". + } else { + echo "Couldn't find matching Action log row when trying to migrate". " filename from asset log:\n". "LogDate{$log->created_at} LogForAsset:{$log->asset_id}". - "LogNote:{$log->note} \n"); + "LogNote:{$log->note} \n"; } } - }); } - /** * Reverse the migrations. * diff --git a/database/migrations/2016_11_13_020954_rename_component_serial_number_to_serial.php b/database/migrations/2016_11_13_020954_rename_component_serial_number_to_serial.php index b1cde650e9..d6be3bb199 100644 --- a/database/migrations/2016_11_13_020954_rename_component_serial_number_to_serial.php +++ b/database/migrations/2016_11_13_020954_rename_component_serial_number_to_serial.php @@ -1,7 +1,7 @@ getDoctrineSchemaManager()->getDatabasePlatform(); $platform->registerDoctrineTypeMapping('enum', 'string'); - Schema::table('assets', function ($table) { - $table->decimal('purchase_cost', 20, 2)->nullable()->default(null)->change(); + $table->decimal('purchase_cost', 20, 2)->nullable()->default(null)->change(); }); Schema::table('accessories', function ($table) { - $table->decimal('purchase_cost', 20, 2)->nullable()->default(null)->change(); + $table->decimal('purchase_cost', 20, 2)->nullable()->default(null)->change(); }); Schema::table('asset_maintenances', function ($table) { - $table->decimal('cost', 20, 2)->nullable()->default(null)->change(); + $table->decimal('cost', 20, 2)->nullable()->default(null)->change(); }); Schema::table('components', function ($table) { - $table->decimal('purchase_cost', 20, 2)->nullable()->default(null)->change(); + $table->decimal('purchase_cost', 20, 2)->nullable()->default(null)->change(); }); Schema::table('consumables', function ($table) { - $table->decimal('purchase_cost', 20, 2)->nullable()->default(null)->change(); + $table->decimal('purchase_cost', 20, 2)->nullable()->default(null)->change(); }); Schema::table('licenses', function ($table) { - $table->decimal('purchase_cost', 20, 2)->nullable()->default(null)->change(); + $table->decimal('purchase_cost', 20, 2)->nullable()->default(null)->change(); }); - } /** @@ -53,27 +51,27 @@ class IncreasePurchaseCostSize extends Migration $platform->registerDoctrineTypeMapping('enum', 'string'); Schema::table('assets', function ($table) { - $table->decimal('purchase_cost', 8, 2)->nullable()->default(null)->change(); + $table->decimal('purchase_cost', 8, 2)->nullable()->default(null)->change(); }); Schema::table('accessories', function ($table) { - $table->decimal('purchase_cost', 13, 4)->nullable()->default(null)->change(); + $table->decimal('purchase_cost', 13, 4)->nullable()->default(null)->change(); }); Schema::table('asset_maintenances', function ($table) { - $table->decimal('cost', 10, 2)->nullable()->default(null)->change(); + $table->decimal('cost', 10, 2)->nullable()->default(null)->change(); }); Schema::table('components', function ($table) { - $table->decimal('purchase_cost', 13, 4)->nullable()->default(null)->change(); + $table->decimal('purchase_cost', 13, 4)->nullable()->default(null)->change(); }); Schema::table('consumables', function ($table) { - $table->decimal('purchase_cost', 13, 4)->nullable()->default(null)->change(); + $table->decimal('purchase_cost', 13, 4)->nullable()->default(null)->change(); }); Schema::table('licenses', function ($table) { - $table->decimal('purchase_cost', 8, 2)->nullable()->default(null)->change(); + $table->decimal('purchase_cost', 8, 2)->nullable()->default(null)->change(); }); } } diff --git a/database/migrations/2016_11_17_161317_longer_state_field_in_location.php b/database/migrations/2016_11_17_161317_longer_state_field_in_location.php index b60466597b..3c77db6743 100644 --- a/database/migrations/2016_11_17_161317_longer_state_field_in_location.php +++ b/database/migrations/2016_11_17_161317_longer_state_field_in_location.php @@ -1,7 +1,7 @@ where('target_type', null)->where(function($query) { + DB::table('action_logs')->where('target_type', null)->where(function ($query) { $query->where('action_type', 'accepted') ->orWhere('action_type', 'declined'); - })->update(['target_type'=> 'App\Models\User']); + })->update(['target_type'=> \App\Models\User::class]); } /** diff --git a/database/migrations/2016_12_07_173720_increase_size_of_state_in_suppliers.php b/database/migrations/2016_12_07_173720_increase_size_of_state_in_suppliers.php index 1c1468d23a..70539c1198 100644 --- a/database/migrations/2016_12_07_173720_increase_size_of_state_in_suppliers.php +++ b/database/migrations/2016_12_07_173720_increase_size_of_state_in_suppliers.php @@ -1,7 +1,7 @@ string('phone',35)->nullable()->default(NULL)->change(); - $table->string('fax',35)->nullable()->default(NULL)->change(); + $table->string('phone', 35)->nullable()->default(null)->change(); + $table->string('fax', 35)->nullable()->default(null)->change(); }); } @@ -29,9 +29,8 @@ class ExtendPhoneLengthsInSupplierAndElsewhere extends Migration { Schema::table('suppliers', function (Blueprint $table) { // - $table->string('phone',20)->nullable()->default(NULL)->change(); - $table->string('fax',20)->nullable()->default(NULL)->change(); - + $table->string('phone', 20)->nullable()->default(null)->change(); + $table->string('fax', 20)->nullable()->default(null)->change(); }); } } diff --git a/database/migrations/2016_12_27_212631_make_asset_assigned_to_polymorphic.php b/database/migrations/2016_12_27_212631_make_asset_assigned_to_polymorphic.php index 772bd170a5..c4534ddcc8 100644 --- a/database/migrations/2016_12_27_212631_make_asset_assigned_to_polymorphic.php +++ b/database/migrations/2016_12_27_212631_make_asset_assigned_to_polymorphic.php @@ -1,10 +1,10 @@ string('assigned_type')->nullable(); - }); - if(config('database.default') == 'mysql') { + Schema::table('assets', function (Blueprint $table) { + $table->string('assigned_type')->nullable(); + }); + if (config('database.default') == 'mysql') { Asset::whereNotNull('assigned_to')->orWhere('assigned_to', '!=', '')->update(['assigned_type' => User::class]); } } diff --git a/database/migrations/2017_01_09_040429_create_locations_ldap_query_field.php b/database/migrations/2017_01_09_040429_create_locations_ldap_query_field.php index f67f85c2aa..f0556e2833 100644 --- a/database/migrations/2017_01_09_040429_create_locations_ldap_query_field.php +++ b/database/migrations/2017_01_09_040429_create_locations_ldap_query_field.php @@ -1,7 +1,7 @@ ] * @since [v4.0] - * @return Array + * @return array */ - -function updateLegacyColumnName($customfield) { - +function updateLegacyColumnName($customfield) +{ $name_to_db_name = CustomField::name_to_db_name($customfield->name); //\Log::debug('Trying to rename '.$name_to_db_name." to ".$customfield->convertUnicodeDbSlug()."...\n"); if (Schema::hasColumn(CustomField::$table_name, $name_to_db_name)) { - return Schema::table(CustomField::$table_name, - function ($table) use ($name_to_db_name, $customfield) { + function ($table) use ($name_to_db_name, $customfield) { $table->renameColumn($name_to_db_name, $customfield->convertUnicodeDbSlug()); } ); - } else { //\Log::debug('Legacy DB column '.$name_to_db_name.' was not found on the assets table.'); } - } - - - class FixUtf8CustomFieldColumnNames extends Migration { /** @@ -52,15 +45,14 @@ class FixUtf8CustomFieldColumnNames extends Migration $platform = Schema::getConnection()->getDoctrineSchemaManager()->getDatabasePlatform(); $platform->registerDoctrineTypeMapping('enum', 'string'); - if (!Schema::hasColumn('custom_fields', 'db_column')) { + if (! Schema::hasColumn('custom_fields', 'db_column')) { Schema::table('custom_fields', function ($table) { $table->string('db_column')->nullable(); $table->text('help_text')->nullable(); }); } - foreach(CustomField::all() as $field) { - + foreach (CustomField::all() as $field) { $db_column = $field->convertUnicodeDbSlug(); DB::table('custom_fields') @@ -69,11 +61,7 @@ class FixUtf8CustomFieldColumnNames extends Migration // change the name of the column updateLegacyColumnName($field); - - } - - } /** @@ -88,5 +76,4 @@ class FixUtf8CustomFieldColumnNames extends Migration $table->dropColumn('help_text'); }); } - } diff --git a/database/migrations/2017_03_03_154632_add_time_date_display_to_settings.php b/database/migrations/2017_03_03_154632_add_time_date_display_to_settings.php index b3f40ab98d..c704696893 100644 --- a/database/migrations/2017_03_03_154632_add_time_date_display_to_settings.php +++ b/database/migrations/2017_03_03_154632_add_time_date_display_to_settings.php @@ -1,8 +1,8 @@ text('field_values')->nullable()->default(null)->change(); }); - } /** diff --git a/database/migrations/2017_05_22_204422_create_departments.php b/database/migrations/2017_05_22_204422_create_departments.php index cf2e1eaf7c..a1c235af69 100644 --- a/database/migrations/2017_05_22_204422_create_departments.php +++ b/database/migrations/2017_05_22_204422_create_departments.php @@ -1,8 +1,8 @@ whereNull('deleted_at')->get(); - if (!$next = Asset::nextAutoIncrement($assets)) { + if (! $next = Asset::nextAutoIncrement($assets)) { $next = 1; } @@ -31,7 +29,6 @@ class AddNextAutoincrementToSettings extends Migration $settings->next_auto_tag_base = $next; $settings->save(); } - } /** diff --git a/database/migrations/2017_06_18_151753_add_header_and_first_row_to_importer_table.php b/database/migrations/2017_06_18_151753_add_header_and_first_row_to_importer_table.php index 6947c421a1..8f82243a70 100644 --- a/database/migrations/2017_06_18_151753_add_header_and_first_row_to_importer_table.php +++ b/database/migrations/2017_06_18_151753_add_header_and_first_row_to_importer_table.php @@ -1,8 +1,8 @@ boolean('pwd_secure_uncommon')->default('0'); - $table->string('pwd_secure_complexity')->nullable()->default(NULL); + $table->string('pwd_secure_complexity')->nullable()->default(null); $table->integer('pwd_secure_min')->default('8'); }); } diff --git a/database/migrations/2017_08_25_074822_add_auditing_tables.php b/database/migrations/2017_08_25_074822_add_auditing_tables.php index e8a6f5209a..ef064ffc26 100644 --- a/database/migrations/2017_08_25_074822_add_auditing_tables.php +++ b/database/migrations/2017_08_25_074822_add_auditing_tables.php @@ -1,8 +1,8 @@ date('next_audit_date')->nullable()->default(NULL); + $table->date('next_audit_date')->nullable()->default(null); }); } diff --git a/database/migrations/2017_08_25_101435_add_auditing_to_settings.php b/database/migrations/2017_08_25_101435_add_auditing_to_settings.php index 7ef4ed306f..14522da79f 100644 --- a/database/migrations/2017_08_25_101435_add_auditing_to_settings.php +++ b/database/migrations/2017_08_25_101435_add_auditing_to_settings.php @@ -1,8 +1,8 @@ integer('audit_interval')->nullable()->default(NULL); - $table->integer('audit_warning_days')->nullable()->default(NULL); + $table->integer('audit_interval')->nullable()->default(null); + $table->integer('audit_warning_days')->nullable()->default(null); }); } diff --git a/database/migrations/2017_09_18_225619_fix_assigned_type_not_being_nulled.php b/database/migrations/2017_09_18_225619_fix_assigned_type_not_being_nulled.php index b9d2239981..ef7c3cd4c0 100644 --- a/database/migrations/2017_09_18_225619_fix_assigned_type_not_being_nulled.php +++ b/database/migrations/2017_09_18_225619_fix_assigned_type_not_being_nulled.php @@ -21,7 +21,7 @@ class FixAssignedTypeNotBeingNulled extends Migration // Additionally, the importer did not set assigned_type when importing. // In the case where we have an assigned_to but not an assigned_type, set the assigned_type to User. - Asset::whereNotNull('assigned_to')->whereNull('assigned_type')->update(['assigned_type' => 'App\Models\User']); + Asset::whereNotNull('assigned_to')->whereNull('assigned_type')->update(['assigned_type' => \App\Models\User::class]); } /** diff --git a/database/migrations/2017_10_03_015503_drop_foreign_keys.php b/database/migrations/2017_10_03_015503_drop_foreign_keys.php index 37ef6ae684..9f42fc068e 100644 --- a/database/migrations/2017_10_03_015503_drop_foreign_keys.php +++ b/database/migrations/2017_10_03_015503_drop_foreign_keys.php @@ -1,8 +1,8 @@ dropForeign(['company_id']); }); @@ -21,7 +21,7 @@ class DropForeignKeys extends Migration //echo $e; } - try { + try { Schema::table('users', function (Blueprint $table) { $table->dropForeign(['company_id']); }); @@ -29,7 +29,7 @@ class DropForeignKeys extends Migration //echo $e; } - try { + try { Schema::table('assets', function (Blueprint $table) { $table->dropForeign(['company_id']); }); @@ -37,7 +37,7 @@ class DropForeignKeys extends Migration //echo $e; } - try { + try { Schema::table('components', function (Blueprint $table) { $table->dropForeign(['company_id']); }); @@ -45,7 +45,7 @@ class DropForeignKeys extends Migration //echo $e; } - try { + try { Schema::table('consumables', function (Blueprint $table) { $table->dropForeign(['company_id']); }); @@ -53,16 +53,13 @@ class DropForeignKeys extends Migration //echo $e; } - try { + try { Schema::table('licenses', function (Blueprint $table) { $table->dropForeign(['company_id']); }); } catch (\Exception $e) { //echo $e; } - - - } /** diff --git a/database/migrations/2017_10_10_123504_allow_nullable_depreciation_id_in_models.php b/database/migrations/2017_10_10_123504_allow_nullable_depreciation_id_in_models.php index fd252bd59c..c1e296095c 100644 --- a/database/migrations/2017_10_10_123504_allow_nullable_depreciation_id_in_models.php +++ b/database/migrations/2017_10_10_123504_allow_nullable_depreciation_id_in_models.php @@ -1,8 +1,8 @@ integer('depreciation_id')->nullable()->default(null)->change(); }); - } /** diff --git a/database/migrations/2017_10_17_133709_add_display_url_to_settings.php b/database/migrations/2017_10_17_133709_add_display_url_to_settings.php index 9b90df9571..8f8237b7d2 100644 --- a/database/migrations/2017_10_17_133709_add_display_url_to_settings.php +++ b/database/migrations/2017_10_17_133709_add_display_url_to_settings.php @@ -1,8 +1,8 @@ index('rtd_location_id'); - $table->index(['assigned_type','assigned_to']); + $table->index(['assigned_type', 'assigned_to']); }); } @@ -29,7 +29,7 @@ class AddLocationIndicesToAssets extends Migration Schema::table('assets', function (Blueprint $table) { // $table->dropIndex(['rtd_location_id']); - $table->dropIndex(['assigned_type','assigned_to']); + $table->dropIndex(['assigned_type', 'assigned_to']); }); } } diff --git a/database/migrations/2017_10_25_202930_add_images_uploads_to_locations_manufacturers_etc.php b/database/migrations/2017_10_25_202930_add_images_uploads_to_locations_manufacturers_etc.php index f6775a564a..7fb7cedd24 100644 --- a/database/migrations/2017_10_25_202930_add_images_uploads_to_locations_manufacturers_etc.php +++ b/database/migrations/2017_10_25_202930_add_images_uploads_to_locations_manufacturers_etc.php @@ -1,8 +1,8 @@ string('image')->nullable()->default(null); }); - } /** @@ -65,7 +64,5 @@ class AddImagesUploadsToLocationsManufacturersEtc extends Migration Schema::table('manufacturers', function (Blueprint $table) { $table->dropColumn('image'); }); - - } } diff --git a/database/migrations/2017_10_27_180947_denorm_asset_locations.php b/database/migrations/2017_10_27_180947_denorm_asset_locations.php index b6ec3df8e4..7d26fd36c3 100644 --- a/database/migrations/2017_10_27_180947_denorm_asset_locations.php +++ b/database/migrations/2017_10_27_180947_denorm_asset_locations.php @@ -1,9 +1,8 @@ integer('location_id')->nullable()->default(null); }); - } /** diff --git a/database/migrations/2017_10_27_192423_migrate_denormed_asset_locations.php b/database/migrations/2017_10_27_192423_migrate_denormed_asset_locations.php index 2da67eb667..e0e10e1a88 100644 --- a/database/migrations/2017_10_27_192423_migrate_denormed_asset_locations.php +++ b/database/migrations/2017_10_27_192423_migrate_denormed_asset_locations.php @@ -1,6 +1,6 @@ dropColumn('city'); $table->dropColumn('state'); $table->dropColumn('zip'); - }); } } diff --git a/database/migrations/2017_11_08_025918_add_alert_menu_setting.php b/database/migrations/2017_11_08_025918_add_alert_menu_setting.php index 5833f157c3..a2c5f3af81 100644 --- a/database/migrations/2017_11_08_025918_add_alert_menu_setting.php +++ b/database/migrations/2017_11_08_025918_add_alert_menu_setting.php @@ -1,8 +1,8 @@ datetime('last_audit_date')->after('assigned_type')->nullable()->default(null); }); } - - - } /** diff --git a/database/migrations/2017_12_12_033618_add_actionlog_meta.php b/database/migrations/2017_12_12_033618_add_actionlog_meta.php index a9a662fa1a..1189f828c8 100644 --- a/database/migrations/2017_12_12_033618_add_actionlog_meta.php +++ b/database/migrations/2017_12_12_033618_add_actionlog_meta.php @@ -1,8 +1,8 @@ unsetEventDispatcher(); $asset->save(); } - } } } diff --git a/database/migrations/2018_01_17_184354_add_archived_in_list_setting.php b/database/migrations/2018_01_17_184354_add_archived_in_list_setting.php index 970e218cdc..128ab58d39 100644 --- a/database/migrations/2018_01_17_184354_add_archived_in_list_setting.php +++ b/database/migrations/2018_01_17_184354_add_archived_in_list_setting.php @@ -1,8 +1,8 @@ boolean('login_remote_user_enabled')->default(0); $table->boolean('login_common_disabled')->default(0); - $table->string('login_remote_user_custom_logout_url')->default(""); + $table->string('login_remote_user_custom_logout_url')->default(''); }); } diff --git a/database/migrations/2018_03_03_011032_add_theme_to_settings.php b/database/migrations/2018_03_03_011032_add_theme_to_settings.php index 876b618d8b..2c44a4af35 100644 --- a/database/migrations/2018_03_03_011032_add_theme_to_settings.php +++ b/database/migrations/2018_03_03_011032_add_theme_to_settings.php @@ -1,8 +1,8 @@ index(['user_id','requestable_id','requestable_type'], 'checkout_requests_user_id_requestable_id_requestable_type_unique')->unique(); + $table->index(['user_id', 'requestable_id', 'requestable_type'], 'checkout_requests_user_id_requestable_id_requestable_type_unique')->unique(); }); } } diff --git a/database/migrations/2018_03_29_070511_add_new_index_requestable.php b/database/migrations/2018_03_29_070511_add_new_index_requestable.php index 09c06566e8..394dbaac45 100644 --- a/database/migrations/2018_03_29_070511_add_new_index_requestable.php +++ b/database/migrations/2018_03_29_070511_add_new_index_requestable.php @@ -1,8 +1,8 @@ index(['user_id','requestable_id','requestable_type'], 'checkout_requests_user_id_requestable_id_requestable_type'); + $table->index(['user_id', 'requestable_id', 'requestable_type'], 'checkout_requests_user_id_requestable_id_requestable_type'); }); } diff --git a/database/migrations/2018_04_02_150700_labels_display_model_name.php b/database/migrations/2018_04_02_150700_labels_display_model_name.php index 60200cdbe2..93e44bb0ba 100644 --- a/database/migrations/2018_04_02_150700_labels_display_model_name.php +++ b/database/migrations/2018_04_02_150700_labels_display_model_name.php @@ -1,8 +1,8 @@ boolean('labels_display_model')->default(0); + $table->boolean('labels_display_model')->default(0); }); } diff --git a/database/migrations/2018_04_16_133902_create_custom_field_default_values_table.php b/database/migrations/2018_04_16_133902_create_custom_field_default_values_table.php index aea8509b8b..072ed2ca19 100644 --- a/database/migrations/2018_04_16_133902_create_custom_field_default_values_table.php +++ b/database/migrations/2018_04_16_133902_create_custom_field_default_values_table.php @@ -1,8 +1,8 @@ integer('category_id')->nullable()->default(null); }); - } /** diff --git a/database/migrations/2018_05_04_075235_add_update_license_category.php b/database/migrations/2018_05_04_075235_add_update_license_category.php index 4997b0a1cf..964ca103fc 100644 --- a/database/migrations/2018_05_04_075235_add_update_license_category.php +++ b/database/migrations/2018_05_04_075235_add_update_license_category.php @@ -1,10 +1,10 @@ withTrashed() ->update(['category_id' => $category->id]); } - } /** @@ -35,7 +34,6 @@ class AddUpdateLicenseCategory extends Migration */ public function down() { - App\Models\Category::where('name', 'Misc Software')->forceDelete(); License::whereNotNull('category_id') diff --git a/database/migrations/2018_05_08_031515_add_gdpr_privacy_footer.php b/database/migrations/2018_05_08_031515_add_gdpr_privacy_footer.php index bc5de9f2c1..0207548f2a 100644 --- a/database/migrations/2018_05_08_031515_add_gdpr_privacy_footer.php +++ b/database/migrations/2018_05_08_031515_add_gdpr_privacy_footer.php @@ -1,8 +1,8 @@ index(['item_type', 'item_id', 'action_type']); $table->index(['target_type', 'target_id', 'action_type']); }); - } /** diff --git a/database/migrations/2018_05_14_223646_add_indexes_to_assets.php b/database/migrations/2018_05_14_223646_add_indexes_to_assets.php index a7161bdb53..ceff4891a2 100644 --- a/database/migrations/2018_05_14_223646_add_indexes_to_assets.php +++ b/database/migrations/2018_05_14_223646_add_indexes_to_assets.php @@ -1,8 +1,8 @@ char('version_footer', 5)->nullable()->default('on'); }); } + /** * Reverse the migrations. * diff --git a/database/migrations/2018_07_05_215440_add_unique_serial_option_to_settings.php b/database/migrations/2018_07_05_215440_add_unique_serial_option_to_settings.php index eeaeb79279..42e3c9f149 100644 --- a/database/migrations/2018_07_05_215440_add_unique_serial_option_to_settings.php +++ b/database/migrations/2018_07_05_215440_add_unique_serial_option_to_settings.php @@ -1,8 +1,8 @@ boolean('logo_print_assets')->default('0'); }); - - } /** diff --git a/database/migrations/2018_07_28_023826_create_checkout_acceptances_table.php b/database/migrations/2018_07_28_023826_create_checkout_acceptances_table.php index 8a8d32fcfa..adc9477b37 100644 --- a/database/migrations/2018_07_28_023826_create_checkout_acceptances_table.php +++ b/database/migrations/2018_07_28_023826_create_checkout_acceptances_table.php @@ -1,8 +1,8 @@ where('assigned_type', 'App\Models\User')->where('accepted', 'pending')->get(); + $assets = DB::table('assets')->where('assigned_type', \App\Models\User::class)->where('accepted', 'pending')->get(); $acceptances = []; - foreach($assets as $asset) { + foreach ($assets as $asset) { $acceptances[] = [ - 'checkoutable_type' => 'App\Models\Asset', + 'checkoutable_type' => \App\Models\Asset::class, 'checkoutable_id' => $asset->id, 'assigned_to_id' => $asset->assigned_to, ]; } - DB::table('checkout_acceptances')->insert($acceptances); + DB::table('checkout_acceptances')->insert($acceptances); } /** diff --git a/database/migrations/2018_10_18_191228_add_kits_licenses_table.php b/database/migrations/2018_10_18_191228_add_kits_licenses_table.php index 44ca2c0a24..4942942121 100644 --- a/database/migrations/2018_10_18_191228_add_kits_licenses_table.php +++ b/database/migrations/2018_10_18_191228_add_kits_licenses_table.php @@ -1,36 +1,35 @@ increments('id'); - $table->integer('kit_id')->nullable()->default(NULL); - $table->integer('license_id')->nullable()->default(NULL); + $table->integer('kit_id')->nullable()->default(null); + $table->integer('license_id')->nullable()->default(null); $table->integer('quantity')->default(1); $table->timestamps(); }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::drop('kits_licenses'); - } + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::drop('kits_licenses'); + } } diff --git a/database/migrations/2018_10_19_153910_add_kits_table.php b/database/migrations/2018_10_19_153910_add_kits_table.php index 949c150146..04e9290aba 100644 --- a/database/migrations/2018_10_19_153910_add_kits_table.php +++ b/database/migrations/2018_10_19_153910_add_kits_table.php @@ -1,37 +1,34 @@ increments('id'); - $table->string('name')->nullable()->default(NULL); + $table->string('name')->nullable()->default(null); $table->timestamps(); $table->engine = 'InnoDB'; }); + } - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::drop('kits'); - - } - + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::drop('kits'); + } } diff --git a/database/migrations/2018_10_19_154013_add_kits_models_table.php b/database/migrations/2018_10_19_154013_add_kits_models_table.php index a0abeeef7b..0f62dd45ef 100644 --- a/database/migrations/2018_10_19_154013_add_kits_models_table.php +++ b/database/migrations/2018_10_19_154013_add_kits_models_table.php @@ -1,36 +1,35 @@ increments('id'); - $table->integer('kit_id')->nullable()->default(NULL); - $table->integer('model_id')->nullable()->default(NULL); + $table->integer('kit_id')->nullable()->default(null); + $table->integer('model_id')->nullable()->default(null); $table->integer('quantity')->default(1); $table->timestamps(); }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - // - Schema::drop('kits_models'); - } + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // + Schema::drop('kits_models'); + } } diff --git a/database/migrations/2018_12_05_211936_add_favicon_to_settings.php b/database/migrations/2018_12_05_211936_add_favicon_to_settings.php index 570eb53926..067ef30b91 100644 --- a/database/migrations/2018_12_05_211936_add_favicon_to_settings.php +++ b/database/migrations/2018_12_05_211936_add_favicon_to_settings.php @@ -1,8 +1,8 @@ increments('id'); - $table->integer('kit_id')->nullable()->default(NULL); - $table->integer('consumable_id')->nullable()->default(NULL); + $table->integer('kit_id')->nullable()->default(null); + $table->integer('consumable_id')->nullable()->default(null); $table->integer('quantity')->default(1); $table->timestamps(); }); @@ -31,6 +31,6 @@ class AddKitsConsumablesTable extends Migration public function down() { // - Schema::drop('kits_consumables'); + Schema::drop('kits_consumables'); } } diff --git a/database/migrations/2019_02_07_190030_add_kits_accessories_table.php b/database/migrations/2019_02_07_190030_add_kits_accessories_table.php index f0e80249db..12e20beba2 100644 --- a/database/migrations/2019_02_07_190030_add_kits_accessories_table.php +++ b/database/migrations/2019_02_07_190030_add_kits_accessories_table.php @@ -1,8 +1,8 @@ increments('id'); - $table->integer('kit_id')->nullable()->default(NULL); - $table->integer('accessory_id')->nullable()->default(NULL); + $table->integer('kit_id')->nullable()->default(null); + $table->integer('accessory_id')->nullable()->default(null); $table->integer('quantity')->default(1); $table->timestamps(); }); @@ -31,6 +31,6 @@ class AddKitsAccessoriesTable extends Migration public function down() { // - Schema::drop('kits_accessories'); + Schema::drop('kits_accessories'); } } diff --git a/database/migrations/2019_02_12_182750_add_actiondate_to_actionlog.php b/database/migrations/2019_02_12_182750_add_actiondate_to_actionlog.php index 053b793b9a..1bbff083ae 100644 --- a/database/migrations/2019_02_12_182750_add_actiondate_to_actionlog.php +++ b/database/migrations/2019_02_12_182750_add_actiondate_to_actionlog.php @@ -1,8 +1,8 @@ select('created_at', 'id')->where('action_type', 'checkout')->orWhere('action_type', 'checkin from')->get(); - foreach($results as $result){ + foreach ($results as $result) { $update = DB::update('update '.DB::getTablePrefix().'action_logs set action_date=? where id=?', [$result->created_at, $result->id]); } } diff --git a/database/migrations/2019_02_14_154310_change_auto_increment_prefix_to_nullable.php b/database/migrations/2019_02_14_154310_change_auto_increment_prefix_to_nullable.php index faf24747d1..4808209d21 100644 --- a/database/migrations/2019_02_14_154310_change_auto_increment_prefix_to_nullable.php +++ b/database/migrations/2019_02_14_154310_change_auto_increment_prefix_to_nullable.php @@ -1,8 +1,8 @@ string('city')->nullable()->default(null)->change(); $table->string('state')->nullable()->default(null)->change(); diff --git a/database/migrations/2019_04_06_060145_add_user_skin_setting.php b/database/migrations/2019_04_06_060145_add_user_skin_setting.php index efe1f94c48..475f0c6aec 100644 --- a/database/migrations/2019_04_06_060145_add_user_skin_setting.php +++ b/database/migrations/2019_04_06_060145_add_user_skin_setting.php @@ -1,8 +1,8 @@ dropColumn('allow_user_skin'); }); } -} \ No newline at end of file +} diff --git a/database/migrations/2019_06_12_184327_rename_groups_table.php b/database/migrations/2019_06_12_184327_rename_groups_table.php index 3c50971614..58dafbc8f6 100644 --- a/database/migrations/2019_06_12_184327_rename_groups_table.php +++ b/database/migrations/2019_06_12_184327_rename_groups_table.php @@ -1,8 +1,8 @@ string('login_remote_user_header_name')->default(""); + $table->string('login_remote_user_header_name')->default(''); }); } diff --git a/database/migrations/2020_02_04_172100_add_ad_append_domain_settings.php b/database/migrations/2020_02_04_172100_add_ad_append_domain_settings.php index aced0bf111..e5b62c8ce6 100644 --- a/database/migrations/2020_02_04_172100_add_ad_append_domain_settings.php +++ b/database/migrations/2020_02_04_172100_add_ad_append_domain_settings.php @@ -1,9 +1,9 @@ ad_append_domain = 1; $s->save(); } -} + } /** * Reverse the migrations. diff --git a/database/migrations/2020_04_29_222305_add_saml_fields_to_settings.php b/database/migrations/2020_04_29_222305_add_saml_fields_to_settings.php index 90c656ce24..dd23aed1b6 100644 --- a/database/migrations/2020_04_29_222305_add_saml_fields_to_settings.php +++ b/database/migrations/2020_04_29_222305_add_saml_fields_to_settings.php @@ -1,48 +1,45 @@ boolean('saml_enabled')->default(0); - $table->text('saml_idp_metadata')->nullable()->default(NULL); - $table->string('saml_attr_mapping_username')->nullable()->default(NULL); +class AddSamlFieldsToSettings extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::table('settings', function (Blueprint $table) { + $table->boolean('saml_enabled')->default(0); + $table->text('saml_idp_metadata')->nullable()->default(null); + $table->string('saml_attr_mapping_username')->nullable()->default(null); $table->boolean('saml_forcelogin')->default(0); - $table->boolean('saml_slo')->default(0); - $table->text('saml_sp_x509cert')->nullable()->default(NULL); - $table->text('saml_sp_privatekey')->nullable()->default(NULL); - $table->text('saml_custom_settings')->nullable()->default(NULL); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('settings', function(Blueprint $table) - { - $table->dropColumn('saml_enabled'); - $table->dropColumn('saml_idp_metadata'); - $table->dropColumn('saml_attr_mapping_username'); - $table->dropColumn('saml_forcelogin'); - $table->dropColumn('saml_slo'); - $table->dropColumn('saml_sp_x509cert'); - $table->dropColumn('saml_sp_privatekey'); - $table->dropColumn('saml_custom_settings'); - }); - } + $table->boolean('saml_slo')->default(0); + $table->text('saml_sp_x509cert')->nullable()->default(null); + $table->text('saml_sp_privatekey')->nullable()->default(null); + $table->text('saml_custom_settings')->nullable()->default(null); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('settings', function (Blueprint $table) { + $table->dropColumn('saml_enabled'); + $table->dropColumn('saml_idp_metadata'); + $table->dropColumn('saml_attr_mapping_username'); + $table->dropColumn('saml_forcelogin'); + $table->dropColumn('saml_slo'); + $table->dropColumn('saml_sp_x509cert'); + $table->dropColumn('saml_sp_privatekey'); + $table->dropColumn('saml_custom_settings'); + }); + } } diff --git a/database/migrations/2020_08_11_200712_add_saml_key_rollover.php b/database/migrations/2020_08_11_200712_add_saml_key_rollover.php index 42a3e24dcd..7b81f2b1ca 100644 --- a/database/migrations/2020_08_11_200712_add_saml_key_rollover.php +++ b/database/migrations/2020_08_11_200712_add_saml_key_rollover.php @@ -13,8 +13,8 @@ class AddSamlKeyRollover extends Migration */ public function up() { - Schema::table('settings', function(Blueprint $table) { - $table->text('saml_sp_x509certNew')->nullable()->default(NULL); + Schema::table('settings', function (Blueprint $table) { + $table->text('saml_sp_x509certNew')->nullable()->default(null); }); } @@ -25,7 +25,7 @@ class AddSamlKeyRollover extends Migration */ public function down() { - Schema::table('settings', function(Blueprint $table) { + Schema::table('settings', function (Blueprint $table) { $table->dropColumn('saml_sp_x509certNew'); }); } diff --git a/database/migrations/2020_10_22_233743_move_accessory_checkout_note_to_join_table.php b/database/migrations/2020_10_22_233743_move_accessory_checkout_note_to_join_table.php index 7ff0b0af8b..e6398909d3 100644 --- a/database/migrations/2020_10_22_233743_move_accessory_checkout_note_to_join_table.php +++ b/database/migrations/2020_10_22_233743_move_accessory_checkout_note_to_join_table.php @@ -1,10 +1,10 @@ count()); - + \Log::debug('Accessory Count: '.$accessories->count()); // Loop through all of the accessories foreach ($accessories as $accessory) { @@ -44,24 +43,23 @@ class MoveAccessoryCheckoutNoteToJoinTable extends Migration // Loop through the accessories_users records foreach ($join_logs as $join_log) { \Log::debug($join_logs->count().' join log records'); - \Log::debug('Looking for accessories_users that match '. $join_log->created_at); + \Log::debug('Looking for accessories_users that match '.$join_log->created_at); // Get the records from action_logs so we can copy the notes over to the new notes field // on the accessories_users table - $action_log_entries = Actionlog::where('created_at', '=',$join_log->created_at) - ->where('target_id', '=',$join_log->assigned_to) - ->where('item_id', '=',$accessory->id) + $action_log_entries = Actionlog::where('created_at', '=', $join_log->created_at) + ->where('target_id', '=', $join_log->assigned_to) + ->where('item_id', '=', $accessory->id) + ->where('target_type', '=', \App\Models\User::class) ->where('item_type', '=','App\\Models\\Accessory') - ->where('target_type', '=','App\\Models\\User') ->where('action_type', '=', 'checkout') ->where('note', '!=', '') ->orderBy('created_at', 'DESC')->get(); \Log::debug($action_log_entries->count().' matching entries in the action_logs table'); - \Log::debug('Looking for action_logs that match '. $join_log->created_at); + \Log::debug('Looking for action_logs that match '.$join_log->created_at); foreach ($action_log_entries as $action_log_entry) { - \Log::debug('Checkout date in asset log: '.$action_log_entry->created_at.' against accessories_users: '.$join_log->created_at); \Log::debug('Action log: '.$action_log_entry->created_at); \Log::debug('Join log: '.$join_log->created_at); @@ -74,14 +72,8 @@ class MoveAccessoryCheckoutNoteToJoinTable extends Migration \Log::debug('No match'); } } - } - - - } - - } /** diff --git a/database/migrations/2020_10_23_161736_fix_zero_values_for_locations.php b/database/migrations/2020_10_23_161736_fix_zero_values_for_locations.php index 66685c8e41..110a6c3e91 100644 --- a/database/migrations/2020_10_23_161736_fix_zero_values_for_locations.php +++ b/database/migrations/2020_10_23_161736_fix_zero_values_for_locations.php @@ -1,10 +1,10 @@ update(['location_id' => null]); - } /** diff --git a/database/migrations/2020_12_14_233815_add_digit_separator_to_settings.php b/database/migrations/2020_12_14_233815_add_digit_separator_to_settings.php index 70fc292cf9..e6b93bf964 100644 --- a/database/migrations/2020_12_14_233815_add_digit_separator_to_settings.php +++ b/database/migrations/2020_12_14_233815_add_digit_separator_to_settings.php @@ -1,8 +1,8 @@ where("ldap_server","not like","ldaps://%"); - foreach($settings->get() AS $setting) { // we don't formally support having multiple settings records, but just in case they come up... - $setting->ldap_server = "ldap://".$setting->ldap_server; + $settings = App\Models\Setting::where('ldap_server', 'not like', 'ldap://%')->where('ldap_server', 'not like', 'ldaps://%'); + foreach ($settings->get() as $setting) { // we don't formally support having multiple settings records, but just in case they come up... + $setting->ldap_server = 'ldap://'.$setting->ldap_server; $setting->save(); } } diff --git a/database/migrations/2021_02_05_172502_add_provider_to_oauth_table.php b/database/migrations/2021_02_05_172502_add_provider_to_oauth_table.php index b2dff776e7..0f9164c08d 100644 --- a/database/migrations/2021_02_05_172502_add_provider_to_oauth_table.php +++ b/database/migrations/2021_02_05_172502_add_provider_to_oauth_table.php @@ -15,7 +15,7 @@ class AddProviderToOauthTable extends Migration public function up() { // Add a 'provider' column if not existing or else modify it - if (!Schema::hasColumn('oauth_clients', 'provider')) { + if (! Schema::hasColumn('oauth_clients', 'provider')) { Schema::table('oauth_clients', function (Blueprint $table) { $table->string('provider')->after('secret')->nullable(); }); diff --git a/database/migrations/2021_04_07_001811_add_ldap_dept.php b/database/migrations/2021_04_07_001811_add_ldap_dept.php index 5557a6747f..7ce62e8709 100644 --- a/database/migrations/2021_04_07_001811_add_ldap_dept.php +++ b/database/migrations/2021_04_07_001811_add_ldap_dept.php @@ -27,7 +27,6 @@ class AddLdapDept extends Migration { Schema::table('settings', function (Blueprint $table) { $table->dropColumn('ldap_dept'); - }); } } diff --git a/database/migrations/2021_04_14_180125_add_ids_to_tables.php b/database/migrations/2021_04_14_180125_add_ids_to_tables.php index 22cf03ebf9..07172164fe 100644 --- a/database/migrations/2021_04_14_180125_add_ids_to_tables.php +++ b/database/migrations/2021_04_14_180125_add_ids_to_tables.php @@ -13,23 +13,19 @@ class AddIdsToTables extends Migration */ public function up() { - Schema::table('migrations', function (Blueprint $table) { // Add the id column to the migrations table if it doesn't yet have one - if (!Schema::hasColumn('migrations', 'id')) { + if (! Schema::hasColumn('migrations', 'id')) { $table->increments('id'); } }); Schema::table('password_resets', function (Blueprint $table) { // Add the id column to the password_resets table if it doesn't yet have one - if (!Schema::hasColumn('password_resets', 'id')) { + if (! Schema::hasColumn('password_resets', 'id')) { $table->increments('id'); } }); - - - } /** diff --git a/database/migrations/2021_08_17_005043_add_depreciation_minimum_value.php b/database/migrations/2021_08_17_005043_add_depreciation_minimum_value.php new file mode 100644 index 0000000000..007fb77c0f --- /dev/null +++ b/database/migrations/2021_08_17_005043_add_depreciation_minimum_value.php @@ -0,0 +1,32 @@ +decimal('depreciation_min', 8,2)->after('months')->nullable(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('depreciations', function (Blueprint $table) { + $table->dropColumn('depreciation_min'); + }); + } +} \ No newline at end of file diff --git a/database/seeds/.gitkeep b/database/seeders/.gitkeep similarity index 100% rename from database/seeds/.gitkeep rename to database/seeders/.gitkeep diff --git a/database/seeders/AccessorySeeder.php b/database/seeders/AccessorySeeder.php new file mode 100644 index 0000000000..6c4123c08b --- /dev/null +++ b/database/seeders/AccessorySeeder.php @@ -0,0 +1,47 @@ +truncate(); + Accessory::factory()->count(1)->appleUsbKeyboard()->create(); + Accessory::factory()->count(1)->appleBtKeyboard()->create(); + Accessory::factory()->count(1)->appleMouse()->create(); + Accessory::factory()->count(1)->microsoftMouse()->create(); + + $src = public_path('/img/demo/accessories/'); + $dst = 'accessories'.'/'; + $del_files = Storage::files($dst); + + foreach ($del_files as $del_file) { // iterate files + $file_to_delete = str_replace($src, '', $del_file); + Log::debug('Deleting: '.$file_to_delete); + try { + Storage::disk('public')->delete($dst.$del_file); + } catch (\Exception $e) { + Log::debug($e); + } + } + + $add_files = glob($src.'/*.*'); + foreach ($add_files as $add_file) { + $file_to_copy = str_replace($src, '', $add_file); + Log::debug('Copying: '.$file_to_copy); + try { + Storage::disk('public')->put($dst.$file_to_copy, file_get_contents($src.$file_to_copy)); + } catch (\Exception $e) { + Log::debug($e); + } + } + } +} diff --git a/database/seeders/ActionlogSeeder.php b/database/seeders/ActionlogSeeder.php new file mode 100644 index 0000000000..06eb27bdeb --- /dev/null +++ b/database/seeders/ActionlogSeeder.php @@ -0,0 +1,18 @@ +count(300)->assetCheckoutToUser()->create(); + Actionlog::factory()->count(100)->assetCheckoutToLocation()->create(); + + + } +} diff --git a/database/seeders/AssetModelSeeder.php b/database/seeders/AssetModelSeeder.php new file mode 100755 index 0000000000..e8816cc509 --- /dev/null +++ b/database/seeders/AssetModelSeeder.php @@ -0,0 +1,71 @@ +count(1)->mbp13Model()->create(); // 1 + AssetModel::factory()->count(1)->mbpAirModel()->create(); // 2 + AssetModel::factory()->count(1)->surfaceModel()->create(); // 3 + AssetModel::factory()->count(1)->xps13Model()->create(); // 4 + AssetModel::factory()->count(1)->spectreModel()->create(); // 5 + AssetModel::factory()->count(1)->zenbookModel()->create(); // 6 + AssetModel::factory()->count(1)->yogaModel()->create(); // 7 + + // Desktops + AssetModel::factory()->count(1)->macproModel()->create(); // 8 + AssetModel::factory()->count(1)->lenovoI5Model()->create(); // 9 + AssetModel::factory()->count(1)->optiplexModel()->create(); // 10 + + // Conference Phones + AssetModel::factory()->count(1)->polycomModel()->create(); // 11 + AssetModel::factory()->count(1)->polycomcxModel()->create(); // 12 + + // Tablets + AssetModel::factory()->count(1)->ipadModel()->create(); // 13 + AssetModel::factory()->count(1)->tab3Model()->create(); // 14 + + // Phones + AssetModel::factory()->count(1)->iphone6sModel()->create(); // 15 + AssetModel::factory()->count(1)->iphone7Model()->create(); // 16 + + // Displays + AssetModel::factory()->count(1)->ultrafine()->create(); // 17 + AssetModel::factory()->count(1)->ultrasharp()->create(); // 18 + + $src = public_path('/img/demo/models/'); + $dst = 'models'.'/'; + $del_files = Storage::files($dst); + + foreach ($del_files as $del_file) { // iterate files + $file_to_delete = str_replace($src, '', $del_file); + Log::debug('Deleting: '.$file_to_delete); + try { + Storage::disk('public')->delete($dst.$del_file); + } catch (\Exception $e) { + Log::debug($e); + } + } + + $add_files = glob($src.'/*.*'); + foreach ($add_files as $add_file) { + $file_to_copy = str_replace($src, '', $add_file); + Log::debug('Copying: '.$file_to_copy); + try { + Storage::disk('public')->put($dst.$file_to_copy, file_get_contents($src.$file_to_copy)); + } catch (\Exception $e) { + Log::debug($e); + } + } + } +} diff --git a/database/seeders/AssetSeeder.php b/database/seeders/AssetSeeder.php new file mode 100644 index 0000000000..c5ea479a34 --- /dev/null +++ b/database/seeders/AssetSeeder.php @@ -0,0 +1,54 @@ +count(1000)->laptopMbp()->create(); + Asset::factory()->count(50)->laptopMbpPending()->create(); + Asset::factory()->count(50)->laptopMbpArchived()->create(); + Asset::factory()->count(50)->laptopAir()->create(); + Asset::factory()->count(5)->laptopSurface()->create(); + Asset::factory()->count(5)->laptopXps()->create(); + Asset::factory()->count(5)->laptopSpectre()->create(); + Asset::factory()->count(5)->laptopZenbook()->create(); + Asset::factory()->count(3)->laptopYoga()->create(); + + Asset::factory()->count(30)->desktopMacpro()->create(); + Asset::factory()->count(30)->desktopLenovoI5()->create(); + Asset::factory()->count(30)->desktopOptiplex()->create(); + + Asset::factory()->count(5)->confPolycom()->create(); + Asset::factory()->count(2)->confPolycomcx()->create(); + + Asset::factory()->count(12)->tabletIpad()->create(); + Asset::factory()->count(4)->tabletTab3()->create(); + + Asset::factory()->count(27)->phoneIphone11()->create(); + Asset::factory()->count(40)->phoneIphone12()->create(); + + Asset::factory()->count(10)->ultrafine()->create(); + Asset::factory()->count(10)->ultrasharp()->create(); + + $del_files = Storage::files('assets'); + foreach ($del_files as $del_file) { // iterate files + Log::debug('Deleting: '.$del_files); + try { + Storage::disk('public')->delete('assets'.'/'.$del_files); + } catch (\Exception $e) { + Log::debug($e); + } + } + + DB::table('checkout_requests')->truncate(); + } +} diff --git a/database/seeders/CategorySeeder.php b/database/seeders/CategorySeeder.php new file mode 100755 index 0000000000..6a554fc825 --- /dev/null +++ b/database/seeders/CategorySeeder.php @@ -0,0 +1,30 @@ +count(1)->assetLaptopCategory()->create(); // 1 + Category::factory()->count(1)->assetDesktopCategory()->create(); // 2 + Category::factory()->count(1)->assetTabletCategory()->create(); // 3 + Category::factory()->count(1)->assetMobileCategory()->create(); // 4 + Category::factory()->count(1)->assetDisplayCategory()->create(); // 5 + Category::factory()->count(1)->assetVoipCategory()->create(); // 6 + Category::factory()->count(1)->assetConferenceCategory()->create(); // 7 + Category::factory()->count(1)->accessoryKeyboardCategory()->create(); // 8 + Category::factory()->count(1)->accessoryMouseCategory()->create(); // 9 + Category::factory()->count(1)->consumablePaperCategory()->create(); // 10 + Category::factory()->count(1)->consumableInkCategory()->create(); // 11 + Category::factory()->count(1)->componentHddCategory()->create(); // 12 + Category::factory()->count(1)->componentRamCategory()->create(); // 13 + Category::factory()->count(1)->licenseGraphicsCategory()->create(); // 14 + Category::factory()->count(1)->licenseOfficeCategory()->create(); // 15 + } +} diff --git a/database/seeds/CompanySeeder.php b/database/seeders/CompanySeeder.php similarity index 50% rename from database/seeds/CompanySeeder.php rename to database/seeders/CompanySeeder.php index eeae5492b7..04f9190f7c 100644 --- a/database/seeds/CompanySeeder.php +++ b/database/seeders/CompanySeeder.php @@ -1,7 +1,11 @@ create(); - + Company::factory()->count(4)->create(); $src = public_path('/img/demo/companies/'); $dst = 'companies'.'/'; $del_files = Storage::files('companies/'.$dst); - foreach($del_files as $del_file){ // iterate files - $file_to_delete = str_replace($src,'',$del_file); - \Log::debug('Deleting: '.$file_to_delete); - try { + foreach ($del_files as $del_file) { // iterate files + $file_to_delete = str_replace($src, '', $del_file); + Log::debug('Deleting: '.$file_to_delete); + try { Storage::disk('public')->delete($dst.$del_file); } catch (\Exception $e) { - \Log::debug($e); + Log::debug($e); } } - - $add_files = glob($src."/*.*"); - foreach($add_files as $add_file){ - $file_to_copy = str_replace($src,'',$add_file); - \Log::debug('Copying: '.$file_to_copy); - try { + $add_files = glob($src.'/*.*'); + foreach ($add_files as $add_file) { + $file_to_copy = str_replace($src, '', $add_file); + Log::debug('Copying: '.$file_to_copy); + try { Storage::disk('public')->put($dst.$file_to_copy, file_get_contents($src.$file_to_copy)); } catch (\Exception $e) { - \Log::debug($e); + Log::debug($e); } } - - } } diff --git a/database/seeders/ComponentSeeder.php b/database/seeders/ComponentSeeder.php new file mode 100644 index 0000000000..46380e1682 --- /dev/null +++ b/database/seeders/ComponentSeeder.php @@ -0,0 +1,20 @@ +truncate(); + Component::factory()->count(1)->ramCrucial4()->create(); // 1 + Component::factory()->count(1)->ramCrucial8()->create(); // 1 + Component::factory()->count(1)->ssdCrucial120()->create(); // 1 + Component::factory()->count(1)->ssdCrucial240()->create(); // 1 + } +} diff --git a/database/seeders/ConsumableSeeder.php b/database/seeders/ConsumableSeeder.php new file mode 100644 index 0000000000..240741fe6d --- /dev/null +++ b/database/seeders/ConsumableSeeder.php @@ -0,0 +1,19 @@ +truncate(); + Consumable::factory()->count(1)->cardstock()->create(); // 1 + Consumable::factory()->count(1)->paper()->create(); // 2 + Consumable::factory()->count(1)->ink()->create(); // 3 + } +} diff --git a/database/seeders/CustomFieldSeeder.php b/database/seeders/CustomFieldSeeder.php new file mode 100644 index 0000000000..8776872644 --- /dev/null +++ b/database/seeders/CustomFieldSeeder.php @@ -0,0 +1,61 @@ +getColumnListing('assets'); + + foreach ($columns as $column) { + if (strpos($column, '_snipeit_') !== false) { + Schema::table('assets', function (Blueprint $table) use ($column) { + $table->dropColumn($column); + }); + } + } + CustomField::truncate(); + CustomFieldset::truncate(); + DB::table('custom_field_custom_fieldset')->truncate(); + + CustomFieldset::factory()->count(1)->mobile()->create(); + CustomFieldset::factory()->count(1)->computer()->create(); + CustomField::factory()->count(1)->imei()->create(); + CustomField::factory()->count(1)->phone()->create(); + CustomField::factory()->count(1)->ram()->create(); + CustomField::factory()->count(1)->cpu()->create(); + CustomField::factory()->count(1)->macAddress()->create(); + + DB::table('custom_field_custom_fieldset')->insert([ + [ + 'custom_field_id' => '1', + 'custom_fieldset_id' => '1', + ], + [ + 'custom_field_id' => '2', + 'custom_fieldset_id' => '1', + ], + [ + 'custom_field_id' => '3', + 'custom_fieldset_id' => '2', + ], + [ + 'custom_field_id' => '4', + 'custom_fieldset_id' => '2', + ], + [ + 'custom_field_id' => '5', + 'custom_fieldset_id' => '2', + ], + + ]); + } +} diff --git a/database/seeds/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php similarity index 71% rename from database/seeds/DatabaseSeeder.php rename to database/seeders/DatabaseSeeder.php index f90326c058..54fb1e088b 100644 --- a/database/seeds/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -1,8 +1,22 @@ create(); + if (! Setting::first()) { + // factory(Setting::class)->create(); $this->call(SettingsSeeder::class); } @@ -40,17 +54,14 @@ class DatabaseSeeder extends Seeder $this->call(ActionlogSeeder::class); $this->call(CustomFieldSeeder::class); - Artisan::call('snipeit:sync-asset-locations', ['--output' => 'all']); $output = Artisan::output(); - \Log::info($output); + Log::info($output); Model::reguard(); DB::table('imports')->truncate(); DB::table('asset_maintenances')->truncate(); DB::table('requested_assets')->truncate(); - - } } diff --git a/database/seeders/DepartmentSeeder.php b/database/seeders/DepartmentSeeder.php new file mode 100644 index 0000000000..f82e355edd --- /dev/null +++ b/database/seeders/DepartmentSeeder.php @@ -0,0 +1,20 @@ +count(1)->hr()->create(); // 1 + Department::factory()->count(1)->engineering()->create(); // 2 + Department::factory()->count(1)->marketing()->create(); // 3 + Department::factory()->count(1)->client()->create(); // 4 + Department::factory()->count(1)->product()->create(); // 5 + Department::factory()->count(1)->silly()->create(); // 6 + } +} diff --git a/database/seeders/DepreciationSeeder.php b/database/seeders/DepreciationSeeder.php new file mode 100644 index 0000000000..1dfebd3062 --- /dev/null +++ b/database/seeders/DepreciationSeeder.php @@ -0,0 +1,17 @@ +count(1)->computer()->create(); // 1 + Depreciation::factory()->count(1)->display()->create(); // 2 + Depreciation::factory()->count(1)->mobilePhones()->create(); // 3 + } +} diff --git a/database/seeders/LicenseSeeder.php b/database/seeders/LicenseSeeder.php new file mode 100644 index 0000000000..843eeb42f1 --- /dev/null +++ b/database/seeders/LicenseSeeder.php @@ -0,0 +1,20 @@ +count(1)->photoshop()->create(); + License::factory()->count(1)->acrobat()->create(); + License::factory()->count(1)->indesign()->create(); + License::factory()->count(1)->office()->create(); + } +} diff --git a/database/seeds/LocationSeeder.php b/database/seeders/LocationSeeder.php similarity index 51% rename from database/seeds/LocationSeeder.php rename to database/seeders/LocationSeeder.php index f7d857f34d..4a98ecb9e8 100644 --- a/database/seeds/LocationSeeder.php +++ b/database/seeders/LocationSeeder.php @@ -1,6 +1,10 @@ create(); + Location::factory()->count(10)->create(); $src = public_path('/img/demo/locations/'); $dst = 'locations'.'/'; $del_files = Storage::files($dst); - foreach($del_files as $del_file){ // iterate files - $file_to_delete = str_replace($src,'',$del_file); - \Log::debug('Deleting: '.$file_to_delete); - try { + foreach ($del_files as $del_file) { // iterate files + $file_to_delete = str_replace($src, '', $del_file); + Log::debug('Deleting: '.$file_to_delete); + try { Storage::disk('public')->delete($dst.$del_file); } catch (\Exception $e) { - \Log::debug($e); + Log::debug($e); } } - - $add_files = glob($src."/*.*"); - foreach($add_files as $add_file){ - $file_to_copy = str_replace($src,'',$add_file); - \Log::debug('Copying: '.$file_to_copy); - try { + $add_files = glob($src.'/*.*'); + foreach ($add_files as $add_file) { + $file_to_copy = str_replace($src, '', $add_file); + Log::debug('Copying: '.$file_to_copy); + try { Storage::disk('public')->put($dst.$file_to_copy, file_get_contents($src.$file_to_copy)); } catch (\Exception $e) { - \Log::debug($e); + Log::debug($e); } } - } } diff --git a/database/seeders/ManufacturerSeeder.php b/database/seeders/ManufacturerSeeder.php new file mode 100644 index 0000000000..fc6a3c34e9 --- /dev/null +++ b/database/seeders/ManufacturerSeeder.php @@ -0,0 +1,52 @@ +count(1)->apple()->create(); // 1 + Manufacturer::factory()->count(1)->microsoft()->create(); // 2 + Manufacturer::factory()->count(1)->dell()->create(); // 3 + Manufacturer::factory()->count(1)->asus()->create(); // 4 + Manufacturer::factory()->count(1)->hp()->create(); // 5 + Manufacturer::factory()->count(1)->lenovo()->create(); // 6 + Manufacturer::factory()->count(1)->lg()->create(); // 7 + Manufacturer::factory()->count(1)->polycom()->create(); // 8 + Manufacturer::factory()->count(1)->adobe()->create(); // 9 + Manufacturer::factory()->count(1)->avery()->create(); // 10 + Manufacturer::factory()->count(1)->crucial()->create(); // 10 + + $src = public_path('/img/demo/manufacturers/'); + $dst = 'manufacturers'.'/'; + $del_files = Storage::files($dst); + + foreach ($del_files as $del_file) { // iterate files + $file_to_delete = str_replace($src, '', $del_file); + Log::debug('Deleting: '.$file_to_delete); + try { + Storage::disk('public')->delete($dst.$del_file); + } catch (\Exception $e) { + Log::debug($e); + } + } + + $add_files = glob($src.'/*.*'); + foreach ($add_files as $add_file) { + $file_to_copy = str_replace($src, '', $add_file); + Log::debug('Copying: '.$file_to_copy); + try { + Storage::disk('public')->put($dst.$file_to_copy, file_get_contents($src.$file_to_copy)); + } catch (\Exception $e) { + Log::debug($e); + } + } + } +} diff --git a/database/seeds/SettingsSeeder.php b/database/seeders/SettingsSeeder.php similarity index 96% rename from database/seeds/SettingsSeeder.php rename to database/seeders/SettingsSeeder.php index 3ad8b8d856..9cbdf79f94 100644 --- a/database/seeds/SettingsSeeder.php +++ b/database/seeders/SettingsSeeder.php @@ -1,8 +1,11 @@ save(); } - // Copy the logos from the img/demo directory Storage::disk('local_public')->put('snipe-logo.png', file_get_contents(public_path('img/demo/snipe-logo.png'))); Storage::disk('local_public')->put('snipe-logo-lg.png', file_get_contents(public_path('img/demo/snipe-logo-lg.png'))); - } } diff --git a/database/seeders/StatuslabelSeeder.php b/database/seeders/StatuslabelSeeder.php new file mode 100755 index 0000000000..94cd2140ae --- /dev/null +++ b/database/seeders/StatuslabelSeeder.php @@ -0,0 +1,21 @@ +rtd()->create(['name' => 'Ready to Deploy']); + Statuslabel::factory()->pending()->create(['name' => 'Pending']); + Statuslabel::factory()->archived()->create(['name' => 'Archived']); + Statuslabel::factory()->outForDiagnostics()->create(); + Statuslabel::factory()->outForRepair()->create(); + Statuslabel::factory()->broken()->create(); + Statuslabel::factory()->lost()->create(); + } +} diff --git a/database/seeds/SupplierSeeder.php b/database/seeders/SupplierSeeder.php similarity index 68% rename from database/seeds/SupplierSeeder.php rename to database/seeders/SupplierSeeder.php index 8dbeac9964..dc012e9b7f 100644 --- a/database/seeds/SupplierSeeder.php +++ b/database/seeders/SupplierSeeder.php @@ -1,13 +1,15 @@ create(); - + Supplier::factory()->count(5)->create(); } } diff --git a/database/seeders/UserSeeder.php b/database/seeders/UserSeeder.php new file mode 100644 index 0000000000..c66f23265e --- /dev/null +++ b/database/seeders/UserSeeder.php @@ -0,0 +1,24 @@ +count(1)->firstAdmin()->create(); + User::factory()->count(1)->snipeAdmin()->create(); + User::factory()->count(3)->superuser()->create(); + User::factory()->count(3)->admin()->create(); + User::factory()->count(50)->viewAssets()->create(); + } +} diff --git a/database/seeds/AccessorySeeder.php b/database/seeds/AccessorySeeder.php deleted file mode 100644 index a9041b782c..0000000000 --- a/database/seeds/AccessorySeeder.php +++ /dev/null @@ -1,43 +0,0 @@ -truncate(); - factory(Accessory::class, 1)->states('apple-usb-keyboard')->create(); - factory(Accessory::class, 1)->states('apple-bt-keyboard')->create(); - factory(Accessory::class, 1)->states('apple-mouse')->create(); - factory(Accessory::class, 1)->states('microsoft-mouse')->create(); - - $src = public_path('/img/demo/accessories/'); - $dst = 'accessories'.'/'; - $del_files = Storage::files($dst); - - foreach($del_files as $del_file){ // iterate files - $file_to_delete = str_replace($src,'',$del_file); - \Log::debug('Deleting: '.$file_to_delete); - try { - Storage::disk('public')->delete($dst.$del_file); - } catch (\Exception $e) { - \Log::debug($e); - } - } - - - $add_files = glob($src."/*.*"); - foreach($add_files as $add_file){ - $file_to_copy = str_replace($src,'',$add_file); - \Log::debug('Copying: '.$file_to_copy); - try { - Storage::disk('public')->put($dst.$file_to_copy, file_get_contents($src.$file_to_copy)); - } catch (\Exception $e) { - \Log::debug($e); - } - } - } -} diff --git a/database/seeds/ActionlogSeeder.php b/database/seeds/ActionlogSeeder.php deleted file mode 100644 index e186bf6ab4..0000000000 --- a/database/seeds/ActionlogSeeder.php +++ /dev/null @@ -1,13 +0,0 @@ -create(); - factory(Actionlog::class, 'asset-checkout-location',100)->create(); - } -} diff --git a/database/seeds/AssetSeeder.php b/database/seeds/AssetSeeder.php deleted file mode 100644 index 9bb9fd75db..0000000000 --- a/database/seeds/AssetSeeder.php +++ /dev/null @@ -1,51 +0,0 @@ -states('laptop-mbp')->create(); - factory(Asset::class, 50)->states('laptop-mbp-pending')->create(); - factory(Asset::class, 50)->states('laptop-mbp-archived')->create(); - factory(Asset::class, 50)->states('laptop-air')->create(); - factory(Asset::class, 5)->states('laptop-surface')->create(); - factory(Asset::class, 5)->states('laptop-xps')->create(); - factory(Asset::class, 5)->states('laptop-spectre')->create(); - factory(Asset::class, 5)->states('laptop-zenbook')->create(); - factory(Asset::class, 3)->states('laptop-yoga')->create(); - - factory(Asset::class, 30)->states('desktop-macpro')->create(); - factory(Asset::class, 30)->states('desktop-lenovo-i5')->create(); - factory(Asset::class, 30)->states('desktop-optiplex')->create(); - - factory(Asset::class, 5)->states('conf-polycom')->create(); - factory(Asset::class, 2)->states('conf-polycomcx')->create(); - - factory(Asset::class, 12)->states('tablet-ipad')->create(); - factory(Asset::class, 4)->states('tablet-tab3')->create(); - - factory(Asset::class, 27)->states('phone-iphone6s')->create(); - factory(Asset::class, 40)->states('phone-iphone7')->create(); - - factory(Asset::class, 10)->states('ultrafine')->create(); - factory(Asset::class, 10)->states('ultrasharp')->create(); - - - $del_files = Storage::files('assets'); - foreach($del_files as $del_file){ // iterate files - \Log::debug('Deleting: '.$del_files); - try { - Storage::disk('public')->delete('assets'.'/'.$del_files); - } catch (\Exception $e) { - \Log::debug($e); - } - } - - DB::table('checkout_requests')->truncate(); - - } -} diff --git a/database/seeds/CategorySeeder.php b/database/seeds/CategorySeeder.php deleted file mode 100755 index dbf4dfca1e..0000000000 --- a/database/seeds/CategorySeeder.php +++ /dev/null @@ -1,28 +0,0 @@ -states('asset-laptop-category')->create(); // 1 - factory(Category::class, 1)->states('asset-desktop-category')->create(); // 2 - factory(Category::class, 1)->states('asset-tablet-category')->create(); // 3 - factory(Category::class, 1)->states('asset-mobile-category')->create(); // 4 - factory(Category::class, 1)->states('asset-display-category')->create(); // 5 - factory(Category::class, 1)->states('asset-voip-category')->create(); // 6 - factory(Category::class, 1)->states('asset-conference-category')->create(); // 7 - factory(Category::class, 1)->states('accessory-keyboard-category')->create(); // 8 - factory(Category::class, 1)->states('accessory-mouse-category')->create(); // 9 - factory(Category::class, 1)->states('consumable-paper-category')->create(); // 10 - factory(Category::class, 1)->states('consumable-ink-category')->create(); // 11 - factory(Category::class, 1)->states('component-hdd-category')->create(); // 12 - factory(Category::class, 1)->states('component-ram-category')->create(); // 13 - factory(Category::class, 1)->states('license-graphics-category')->create(); // 14 - factory(Category::class, 1)->states('license-office-category')->create(); // 15 - } - -} diff --git a/database/seeds/ComponentSeeder.php b/database/seeds/ComponentSeeder.php deleted file mode 100644 index bf22c394fe..0000000000 --- a/database/seeds/ComponentSeeder.php +++ /dev/null @@ -1,16 +0,0 @@ -truncate(); - factory(Component::class, 1)->states('ram-crucial4')->create(); // 1 - factory(Component::class, 1)->states('ram-crucial8')->create(); // 1 - factory(Component::class, 1)->states('ssd-crucial120')->create(); // 1 - factory(Component::class, 1)->states('ssd-crucial240')->create(); // 1 - } -} diff --git a/database/seeds/ConsumableSeeder.php b/database/seeds/ConsumableSeeder.php deleted file mode 100644 index 0e5577cdb9..0000000000 --- a/database/seeds/ConsumableSeeder.php +++ /dev/null @@ -1,15 +0,0 @@ -truncate(); - factory(Consumable::class, 1)->states('cardstock')->create(); // 1 - factory(Consumable::class, 1)->states('paper')->create(); // 2 - factory(Consumable::class, 1)->states('ink')->create(); // 3 - } -} diff --git a/database/seeds/CustomFieldSeeder.php b/database/seeds/CustomFieldSeeder.php deleted file mode 100644 index c743b3fc58..0000000000 --- a/database/seeds/CustomFieldSeeder.php +++ /dev/null @@ -1,64 +0,0 @@ -getColumnListing('assets'); - - - foreach ($columns as $column) { - if(strpos($column, '_snipeit_') !== FALSE) { - - Schema::table('assets', function (Blueprint $table) use ($column) { - $table->dropColumn($column); - }); - } - } - CustomField::truncate(); - CustomFieldset::truncate(); - DB::table('custom_field_custom_fieldset')->truncate(); - - factory(CustomFieldset::class, 1)->states('mobile')->create(); - factory(CustomFieldset::class, 1)->states('computer')->create(); - factory(CustomField::class, 1)->states('imei')->create(); - factory(CustomField::class, 1)->states('phone')->create(); - factory(CustomField::class, 1)->states('ram')->create(); - factory(CustomField::class, 1)->states('cpu')->create(); - factory(CustomField::class, 1)->states('mac-address')->create(); - - DB::table('custom_field_custom_fieldset')->insert([ - [ - 'custom_field_id' => '1', - 'custom_fieldset_id' => '1' - ], - [ - 'custom_field_id' => '2', - 'custom_fieldset_id' => '1' - ], - [ - 'custom_field_id' => '3', - 'custom_fieldset_id' => '2' - ], - [ - 'custom_field_id' => '4', - 'custom_fieldset_id' => '2' - ], - [ - 'custom_field_id' => '5', - 'custom_fieldset_id' => '2' - ], - - ]); - - - - - } -} diff --git a/database/seeds/DepartmentSeeder.php b/database/seeds/DepartmentSeeder.php deleted file mode 100644 index b92455a1fc..0000000000 --- a/database/seeds/DepartmentSeeder.php +++ /dev/null @@ -1,17 +0,0 @@ -states('hr')->create(); // 1 - factory(Department::class, 1)->states('engineering')->create(); // 2 - factory(Department::class, 1)->states('marketing')->create(); // 3 - factory(Department::class, 1)->states('client')->create(); // 4 - factory(Department::class, 1)->states('product')->create(); // 5 - factory(Department::class, 1)->states('silly')->create(); // 6 - } -} diff --git a/database/seeds/DepreciationSeeder.php b/database/seeds/DepreciationSeeder.php deleted file mode 100644 index 4cf6055e6f..0000000000 --- a/database/seeds/DepreciationSeeder.php +++ /dev/null @@ -1,14 +0,0 @@ -states('computer')->create(); // 1 - factory(Depreciation::class, 1)->states('display')->create(); // 2 - factory(Depreciation::class, 1)->states('mobile-phones')->create(); // 3 - } -} diff --git a/database/seeds/LicenseSeeder.php b/database/seeds/LicenseSeeder.php deleted file mode 100644 index 75ab8d3b6e..0000000000 --- a/database/seeds/LicenseSeeder.php +++ /dev/null @@ -1,17 +0,0 @@ -states('photoshop')->create(); - factory(License::class, 1)->states('acrobat')->create(); - factory(License::class, 1)->states('indesign')->create(); - factory(License::class, 1)->states('office')->create(); - } -} diff --git a/database/seeds/ManufacturerSeeder.php b/database/seeds/ManufacturerSeeder.php deleted file mode 100644 index a65d12a2e4..0000000000 --- a/database/seeds/ManufacturerSeeder.php +++ /dev/null @@ -1,53 +0,0 @@ -states('apple')->create(); // 1 - factory(Manufacturer::class, 1)->states('microsoft')->create(); // 2 - factory(Manufacturer::class, 1)->states('dell')->create(); // 3 - factory(Manufacturer::class, 1)->states('asus')->create(); // 4 - factory(Manufacturer::class, 1)->states('hp')->create(); // 5 - factory(Manufacturer::class, 1)->states('lenovo')->create(); // 6 - factory(Manufacturer::class, 1)->states('lg')->create(); // 7 - factory(Manufacturer::class, 1)->states('polycom')->create(); // 8 - factory(Manufacturer::class, 1)->states('adobe')->create(); // 9 - factory(Manufacturer::class, 1)->states('avery')->create(); // 10 - factory(Manufacturer::class, 1)->states('crucial')->create(); // 10 - - $src = public_path('/img/demo/manufacturers/'); - $dst = 'manufacturers'.'/'; - $del_files = Storage::files($dst); - - foreach($del_files as $del_file){ // iterate files - $file_to_delete = str_replace($src,'',$del_file); - \Log::debug('Deleting: '.$file_to_delete); - try { - Storage::disk('public')->delete($dst.$del_file); - } catch (\Exception $e) { - \Log::debug($e); - } - } - - - $add_files = glob($src."/*.*"); - foreach($add_files as $add_file){ - $file_to_copy = str_replace($src,'',$add_file); - \Log::debug('Copying: '.$file_to_copy); - try { - Storage::disk('public')->put($dst.$file_to_copy, file_get_contents($src.$file_to_copy)); - } catch (\Exception $e) { - \Log::debug($e); - } - } - - - } - - -} diff --git a/database/seeds/StatuslabelSeeder.php b/database/seeds/StatuslabelSeeder.php deleted file mode 100755 index 1c58d76a0b..0000000000 --- a/database/seeds/StatuslabelSeeder.php +++ /dev/null @@ -1,19 +0,0 @@ -states('rtd')->create(['name' => "Ready to Deploy"]); - factory(Statuslabel::class)->states('pending')->create(['name' => "Pending"]); - factory(Statuslabel::class)->states('archived')->create(['name' => "Archived"]); - factory(Statuslabel::class)->states('out_for_diagnostics')->create(); - factory(Statuslabel::class)->states('out_for_repair')->create(); - factory(Statuslabel::class)->states('broken')->create(); - factory(Statuslabel::class)->states('lost')->create(); - } -} diff --git a/database/seeds/UserSeeder.php b/database/seeds/UserSeeder.php deleted file mode 100644 index 348a26a6b4..0000000000 --- a/database/seeds/UserSeeder.php +++ /dev/null @@ -1,23 +0,0 @@ -states('first-admin')->create(); - factory(User::class, 1)->states('snipe-admin')->create(); - factory(User::class, 3)->states('superuser')->create(); - factory(User::class, 3)->states('admin')->create(); - factory(User::class, 50)->states('view-assets')->create(); - - } -} diff --git a/package.json b/package.json index 064898bb74..22bb200e02 100644 --- a/package.json +++ b/package.json @@ -1,58 +1,57 @@ { - "private": true, - "scripts": { - "dev": "npm run development", - "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --config=node_modules/laravel-mix/setup/webpack.config.js", - "watch": "npm run development -- --watch", - "watch-poll": "npm run watch -- --watch-poll", - "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --disable-host-check --config=node_modules/laravel-mix/setup/webpack.config.js", - "prod": "npm run production", - "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --config=node_modules/laravel-mix/setup/webpack.config.js" - }, - "engines": { - "node": ">=0.12" - }, - "devDependencies": { - "axios": "^0.20.0", - "babel-preset-latest": "^6.24.1", - "cross-env": "^7.0", - "jquery": "^3.5.1", - "laravel-mix": "^5.0.1", - "lodash": "^4.17.20", - "vue": "2.4.4", - "vue-loader": "^15.9.6", - "vue-template-compiler": "2.4.4" - }, - "dependencies": { - "@fortawesome/fontawesome-free": "^5.15.1", - "admin-lte": "^2.4.18", - "ajv": "^6.12.6", - "blueimp-file-upload": "^9.34.0", - "bootstrap": "^3.4.1", - "bootstrap-colorpicker": "^2.5.3", - "bootstrap-datepicker": "^1.9.0", - "bootstrap-less": "^3.3.8", - "bootstrap-table": "^1.18.0", - "chart.js": "^2.9.4", - "css-loader": "^3.6.0", - "ekko-lightbox": "^5.1.1", - "font-awesome": "^4.7.0", - "icheck": "^1.0.2", - "imagemin": "^5.3.1", - "jquery-form-validator": "^2.3.79", - "jquery-slimscroll": "^1.3.8", - "jquery-ui": "^1.12.1", - "jquery-ui-bundle": "^1.12.1", - "jquery.iframe-transport": "^1.0.0", - "less": "^3.13.1", - "less-loader": "^4.1.0", - "list.js": "^1.5.0", - "papaparse": "^4.3.3", - "phantomjs": "^2.1.7", - "select2": "4.0.13", - "sheetjs": "^2.0.0", - "tableexport.jquery.plugin": "^1.10.20", - "tether": "^1.4.0", - "vue-resource": "^1.3.3" - } + "private": true, + "scripts": { + "dev": "npm run development", + "development": "mix", + "watch": "mix watch", + "watch-poll": "mix watch -- --watch-options-poll=1000", + "hot": "mix watch --hot", + "prod": "npm run production", + "production": "mix --production" + }, + "engines": { + "node": ">=0.12" + }, + "devDependencies": { + "axios": "^0.20.0", + "babel-preset-latest": "^6.24.1", + "jquery": "^3.6.0", + "laravel-mix": "^6.0.12", + "lodash": "^4.17.20", + "postcss": "^8.2.8", + "vue": "2.4.4", + "vue-loader": "^15.9.7", + "vue-template-compiler": "2.4.4" + }, + "dependencies": { + "@fortawesome/fontawesome-free": "^5.15.3", + "admin-lte": "^2.4.18", + "ajv": "^6.12.6", + "blueimp-file-upload": "^9.34.0", + "bootstrap": "^3.4.1", + "bootstrap-colorpicker": "^2.5.3", + "bootstrap-datepicker": "^1.9.0", + "bootstrap-less": "^3.3.8", + "bootstrap-table": "^1.18.3", + "chart.js": "^2.9.4", + "css-loader": "^3.6.0", + "ekko-lightbox": "^5.1.1", + "font-awesome": "^4.7.0", + "icheck": "^1.0.2", + "imagemin": "^5.3.1", + "jquery-form-validator": "^2.3.79", + "jquery-slimscroll": "^1.3.8", + "jquery-ui": "^1.12.1", + "jquery-ui-bundle": "^1.12.1", + "jquery.iframe-transport": "^1.0.0", + "less": "^4.1.1", + "less-loader": "^5.0.0", + "list.js": "^1.5.0", + "papaparse": "^4.3.3", + "select2": "4.0.13", + "sheetjs": "^2.0.0", + "tableexport.jquery.plugin": "^1.10.26", + "tether": "^1.4.0", + "vue-resource": "^1.5.2" + } } diff --git a/public/css/dist/signature-pad.min.css b/public/css/dist/signature-pad.min.css index 7065929572..218b9c2365 100644 --- a/public/css/dist/signature-pad.min.css +++ b/public/css/dist/signature-pad.min.css @@ -1 +1,135 @@ -#signature-pad{padding-top:250px;margin:auto}.m-signature-pad{position:relative;font-size:10px;width:100%;height:300px;border:1px solid #e8e8e8;background-color:#fff;box-shadow:0 1px 4px rgba(0,0,0,.27),0 0 40px rgba(0,0,0,.08) inset;border-radius:4px}.m-signature-pad:after,.m-signature-pad:before{position:absolute;z-index:-1;content:"";width:40%;height:10px;left:20px;bottom:10px;background:0 0;-webkit-transform:skew(-3deg) rotate(-3deg);-moz-transform:skew(-3deg) rotate(-3deg);-ms-transform:skew(-3deg) rotate(-3deg);-o-transform:skew(-3deg) rotate(-3deg);transform:skew(-3deg) rotate(-3deg);box-shadow:0 8px 12px rgba(0,0,0,.4)}.m-signature-pad:after{left:auto;right:20px;-webkit-transform:skew(3deg) rotate(3deg);-moz-transform:skew(3deg) rotate(3deg);-ms-transform:skew(3deg) rotate(3deg);-o-transform:skew(3deg) rotate(3deg);transform:skew(3deg) rotate(3deg)}.m-signature-pad--body{position:absolute;top:20px;bottom:60px;border:1px solid #f4f4f4;background-color:#fff}.m-signature-pad--body canvas{position:absolute;left:0;top:0;width:100%;height:100%;border-radius:4px;box-shadow:0 0 5px rgba(0,0,0,.02) inset}.m-signature-pad--footer{position:absolute;left:20px;right:20px;bottom:20px;height:40px}.m-signature-pad--footer .description{color:#c3c3c3;text-align:center;font-size:1.2em;margin-top:1.8em}.m-signature-pad--footer .button{position:absolute;bottom:0}.m-signature-pad--footer .button.clear{left:0}.m-signature-pad--footer .button.save{right:0}@media screen and (max-width:1024px){.m-signature-pad{top:0;left:0;right:0;bottom:0;width:auto;height:auto;min-width:250px;min-height:140px;margin:5%}}@media screen and (min-device-width:768px) and (max-device-width:1024px){.m-signature-pad{margin:10%}}@media screen and (max-height:320px){.m-signature-pad--body{left:0;right:0;top:0;bottom:32px}.m-signature-pad--footer{left:20px;right:20px;bottom:4px;height:28px}.m-signature-pad--footer .description{font-size:1em;margin-top:1em}} + +#signature-pad { + padding-top: 250px; + margin: auto; +} +.m-signature-pad { + + position: relative; + font-size: 10px; + width: 100%; + height: 300px; + border: 1px solid #e8e8e8; + background-color: #fff; + box-shadow: 0 1px 4px rgba(0, 0, 0, 0.27), 0 0 40px rgba(0, 0, 0, 0.08) inset; + border-radius: 4px; +} + +.m-signature-pad:before, .m-signature-pad:after { + position: absolute; + z-index: -1; + content: ""; + width: 40%; + height: 10px; + left: 20px; + bottom: 10px; + background: transparent; + -webkit-transform: skew(-3deg) rotate(-3deg); + -moz-transform: skew(-3deg) rotate(-3deg); + -ms-transform: skew(-3deg) rotate(-3deg); + -o-transform: skew(-3deg) rotate(-3deg); + transform: skew(-3deg) rotate(-3deg); + box-shadow: 0 8px 12px rgba(0, 0, 0, 0.4); +} + +.m-signature-pad:after { + left: auto; + right: 20px; + -webkit-transform: skew(3deg) rotate(3deg); + -moz-transform: skew(3deg) rotate(3deg); + -ms-transform: skew(3deg) rotate(3deg); + -o-transform: skew(3deg) rotate(3deg); + transform: skew(3deg) rotate(3deg); +} + +.m-signature-pad--body { + position: absolute; + top: 20px; + bottom: 60px; + border: 1px solid #f4f4f4; + background-color: white; +} + +.m-signature-pad--body + canvas { + position: absolute; + left: 0; + top: 0; + width: 100%; + height: 100%; + border-radius: 4px; + box-shadow: 0 0 5px rgba(0, 0, 0, 0.02) inset; + } + +.m-signature-pad--footer { + position: absolute; + left: 20px; + right: 20px; + bottom: 20px; + height: 40px; +} + +.m-signature-pad--footer + .description { + color: #C3C3C3; + text-align: center; + font-size: 1.2em; + margin-top: 1.8em; + } + +.m-signature-pad--footer + .button { + position: absolute; + bottom: 0; + } + +.m-signature-pad--footer + .button.clear { + left: 0; + } + +.m-signature-pad--footer + .button.save { + right: 0; + } + +@media screen and (max-width: 1024px) { + .m-signature-pad { + top: 0; + left: 0; + right: 0; + bottom: 0; + width: auto; + height: auto; + min-width: 250px; + min-height: 140px; + margin: 5%; + } + +} + +@media screen and (min-device-width: 768px) and (max-device-width: 1024px) { + .m-signature-pad { + margin: 10%; + } +} + +@media screen and (max-height: 320px) { + .m-signature-pad--body { + left: 0; + right: 0; + top: 0; + bottom: 32px; + } + .m-signature-pad--footer { + left: 20px; + right: 20px; + bottom: 4px; + height: 28px; + } + .m-signature-pad--footer + .description { + font-size: 1em; + margin-top: 1em; + } +} diff --git a/public/index.php b/public/index.php index 348b3d9785..66ea93cd05 100644 --- a/public/index.php +++ b/public/index.php @@ -1,11 +1,24 @@ - */ +use Illuminate\Contracts\Http\Kernel; +use Illuminate\Http\Request; + +define('LARAVEL_START', microtime(true)); + +/* +|-------------------------------------------------------------------------- +| Check If The Application Is Under Maintenance +|-------------------------------------------------------------------------- +| +| If the application is in maintenance / demo mode via the "down" command +| we will load this file so that any pre-rendered content can be shown +| instead of starting the framework, which could cause an exception. +| +*/ + +if (file_exists(__DIR__.'/../storage/framework/maintenance.php')) { + require __DIR__.'/../storage/framework/maintenance.php'; +} /* |-------------------------------------------------------------------------- @@ -13,51 +26,30 @@ |-------------------------------------------------------------------------- | | Composer provides a convenient, automatically generated class loader for -| our application. We just need to utilize it! We'll simply require it -| into the script here so that we don't have to worry about manual -| loading any of our classes later on. It feels nice to relax. +| this application. We just need to utilize it! We'll simply require it +| into the script here so we don't need to manually load our classes. | */ -require __DIR__.'/../bootstrap/autoload.php'; - -/* -|-------------------------------------------------------------------------- -| Turn On The Lights -|-------------------------------------------------------------------------- -| -| We need to illuminate PHP development, so let us turn on the lights. -| This bootstraps the framework and gets it ready for use, then it -| will load up this application so that we can run it and send -| the responses back to the browser and delight our users. -| -*/ - -$app = require_once __DIR__.'/../bootstrap/app.php'; - -// set the public path to this directory -$app->bind('path.public', function() { - return __DIR__; -}); +require __DIR__.'/../vendor/autoload.php'; /* |-------------------------------------------------------------------------- | Run The Application |-------------------------------------------------------------------------- | -| Once we have the application, we can handle the incoming request -| through the kernel, and send the associated response back to -| the client's browser allowing them to enjoy the creative -| and wonderful application we have prepared for them. +| Once we have the application, we can handle the incoming request using +| the application's HTTP kernel. Then, we will send the response back +| to this client's browser, allowing them to enjoy our application. | */ -$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class); +$app = require_once __DIR__.'/../bootstrap/app.php'; -$response = $kernel->handle( - $request = Illuminate\Http\Request::capture() -); +$kernel = $app->make(Kernel::class); -$response->send(); +$response = tap($kernel->handle( + $request = Request::capture() +))->send(); $kernel->terminate($request, $response); diff --git a/public/vendor/livewire/livewire.js b/public/vendor/livewire/livewire.js new file mode 100644 index 0000000000..fa1179a52b --- /dev/null +++ b/public/vendor/livewire/livewire.js @@ -0,0 +1,14 @@ +!function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?module.exports=factory():"function"==typeof define&&define.amd?define(factory):(global="undefined"!=typeof globalThis?globalThis:global||self).Livewire=factory()}(this,(function(){"use strict";function ownKeys$1(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))),keys.push.apply(keys,symbols)}return keys}function _objectSpread2(target){for(var i=1;iarr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i0&&void 0!==arguments[0]?arguments[0]:"right";return this.modifiers.includes("up")?"up":this.modifiers.includes("down")?"down":this.modifiers.includes("left")?"left":this.modifiers.includes("right")?"right":fallback}}]),Directive}();function walk(root,callback){if(!1!==callback(root))for(var node=root.firstElementChild;node;)walk(node,callback),node=node.nextElementSibling}function dispatch(eventName){var event=document.createEvent("Events");return event.initEvent(eventName,!0,!0),document.dispatchEvent(event),event}function getCsrfToken(){var _window$livewire_toke,tokenTag=document.head.querySelector('meta[name="csrf-token"]');return tokenTag?tokenTag.content:null!==(_window$livewire_toke=window.livewire_token)&&void 0!==_window$livewire_toke?_window$livewire_toke:void 0}function kebabCase(subject){return subject.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[_\s]/,"-").toLowerCase()} +/*! + * isobject + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */var isobject=function(val){return null!=val&&"object"==typeof val&&!1===Array.isArray(val)},getValue=function(target,path,options){if(isobject(options)||(options={default:options}),!isValidObject(target))return void 0!==options.default?options.default:target;"number"==typeof path&&(path=String(path));const isArray=Array.isArray(path),isString="string"==typeof path,splitChar=options.separator||".",joinChar=options.joinChar||("string"==typeof splitChar?splitChar:".");if(!isString&&!isArray)return target;if(isString&&path in target)return isValid(path,target,options)?target[path]:options.default;let segs=isArray?path:split$1(path,splitChar,options),len=segs.length,idx=0;do{let prop=segs[idx];for("number"==typeof prop&&(prop=String(prop));prop&&"\\"===prop.slice(-1);)prop=join([prop.slice(0,-1),segs[++idx]||""],joinChar,options);if(prop in target){if(!isValid(prop,target,options))return options.default;target=target[prop]}else{let hasProp=!1,n=idx+1;for(;n + * + * Copyright (c) 2014-2018, Jon Schlinkert. + * Released under the MIT License. + */function join(segs,joinChar,options){return"function"==typeof options.join?options.join(segs):segs[0]+joinChar+segs[1]}function split$1(path,splitChar,options){return"function"==typeof options.split?options.split(path):path.split(splitChar)}function isValid(key,target,options){return"function"!=typeof options.isValid||options.isValid(key,target)}function isValidObject(val){return isobject(val)||Array.isArray(val)||"function"==typeof val}var _default$6=function(){function _default(el){var skipWatcher=arguments.length>1&&void 0!==arguments[1]&&arguments[1];_classCallCheck(this,_default),this.el=el,this.skipWatcher=skipWatcher,this.resolveCallback=function(){},this.rejectCallback=function(){}}return _createClass(_default,[{key:"toId",value:function(){return btoa(encodeURIComponent(this.el.outerHTML))}},{key:"onResolve",value:function(callback){this.resolveCallback=callback}},{key:"onReject",value:function(callback){this.rejectCallback=callback}},{key:"resolve",value:function(thing){this.resolveCallback(thing)}},{key:"reject",value:function(thing){this.rejectCallback(thing)}}]),_default}(),_default$5=function(_Action){_inherits(_default,_Action);var _super=_createSuper(_default);function _default(event,params,el){var _this;return _classCallCheck(this,_default),(_this=_super.call(this,el)).type="fireEvent",_this.payload={event:event,params:params},_this}return _createClass(_default,[{key:"toId",value:function(){return btoa(encodeURIComponent(this.type,this.payload.event,JSON.stringify(this.payload.params)))}}]),_default}(_default$6),MessageBus=function(){function MessageBus(){_classCallCheck(this,MessageBus),this.listeners={}}return _createClass(MessageBus,[{key:"register",value:function(name,callback){this.listeners[name]||(this.listeners[name]=[]),this.listeners[name].push(callback)}},{key:"call",value:function(name){for(var _len=arguments.length,params=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)params[_key-1]=arguments[_key];(this.listeners[name]||[]).forEach((function(callback){callback.apply(void 0,params)}))}},{key:"has",value:function(name){return Object.keys(this.listeners).includes(name)}}]),MessageBus}(),HookManager={availableHooks:["component.initialized","element.initialized","element.updating","element.updated","element.removed","message.sent","message.failed","message.received","message.processed","interceptWireModelSetValue","interceptWireModelAttachListener","beforeReplaceState","beforePushState"],bus:new MessageBus,register:function(name,callback){if(!this.availableHooks.includes(name))throw"Livewire: Referencing unknown hook: [".concat(name,"]");this.bus.register(name,callback)},call:function(name){for(var _this$bus,_len=arguments.length,params=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)params[_key-1]=arguments[_key];(_this$bus=this.bus).call.apply(_this$bus,[name].concat(params))}},DirectiveManager={directives:new MessageBus,register:function(name,callback){if(this.has(name))throw"Livewire: Directive already registered: [".concat(name,"]");this.directives.register(name,callback)},call:function(name,el,directive,component){this.directives.call(name,el,directive,component)},has:function(name){return this.directives.has(name)}},store$2={componentsById:{},listeners:new MessageBus,initialRenderIsFinished:!1,livewireIsInBackground:!1,livewireIsOffline:!1,sessionHasExpired:!1,directives:DirectiveManager,hooks:HookManager,onErrorCallback:function(){},components:function(){var _this=this;return Object.keys(this.componentsById).map((function(key){return _this.componentsById[key]}))},addComponent:function(component){return this.componentsById[component.id]=component},findComponent:function(id){return this.componentsById[id]},getComponentsByName:function(name){return this.components().filter((function(component){return component.name===name}))},hasComponent:function(id){return!!this.componentsById[id]},tearDownComponents:function(){var _this2=this;this.components().forEach((function(component){_this2.removeComponent(component)}))},on:function(event,callback){this.listeners.register(event,callback)},emit:function(event){for(var _this$listeners,_len=arguments.length,params=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)params[_key-1]=arguments[_key];(_this$listeners=this.listeners).call.apply(_this$listeners,[event].concat(params)),this.componentsListeningForEvent(event).forEach((function(component){return component.addAction(new _default$5(event,params))}))},emitUp:function(el,event){for(var _len2=arguments.length,params=new Array(_len2>2?_len2-2:0),_key2=2;_key2<_len2;_key2++)params[_key2-2]=arguments[_key2];this.componentsListeningForEventThatAreTreeAncestors(el,event).forEach((function(component){return component.addAction(new _default$5(event,params))}))},emitSelf:function(componentId,event){var component=this.findComponent(componentId);if(component.listeners.includes(event)){for(var _len3=arguments.length,params=new Array(_len3>2?_len3-2:0),_key3=2;_key3<_len3;_key3++)params[_key3-2]=arguments[_key3];component.addAction(new _default$5(event,params))}},emitTo:function(componentName,event){for(var _len4=arguments.length,params=new Array(_len4>2?_len4-2:0),_key4=2;_key4<_len4;_key4++)params[_key4-2]=arguments[_key4];var components=this.getComponentsByName(componentName);components.forEach((function(component){component.listeners.includes(event)&&component.addAction(new _default$5(event,params))}))},componentsListeningForEventThatAreTreeAncestors:function(el,event){for(var parentIds=[],parent=el.parentElement.closest("[wire\\:id]");parent;)parentIds.push(parent.getAttribute("wire:id")),parent=parent.parentElement.closest("[wire\\:id]");return this.components().filter((function(component){return component.listeners.includes(event)&&parentIds.includes(component.id)}))},componentsListeningForEvent:function(event){return this.components().filter((function(component){return component.listeners.includes(event)}))},registerDirective:function(name,callback){this.directives.register(name,callback)},registerHook:function(name,callback){this.hooks.register(name,callback)},callHook:function(name){for(var _this$hooks,_len5=arguments.length,params=new Array(_len5>1?_len5-1:0),_key5=1;_key5<_len5;_key5++)params[_key5-1]=arguments[_key5];(_this$hooks=this.hooks).call.apply(_this$hooks,[name].concat(params))},changeComponentId:function(component,newId){var oldId=component.id;component.id=newId,component.fingerprint.id=newId,this.componentsById[newId]=component,delete this.componentsById[oldId],this.components().forEach((function(component){var children=component.serverMemo.children||{};Object.entries(children).forEach((function(_ref){var _ref2=_slicedToArray(_ref,2),key=_ref2[0],_ref2$=_ref2[1],id=_ref2$.id;_ref2$.tagName,id===oldId&&(children[key].id=newId)}))}))},removeComponent:function(component){component.tearDown(),delete this.componentsById[component.id]},onError:function(callback){this.onErrorCallback=callback},getClosestParentId:function(childId,subsetOfParentIds){var _this3=this,distancesByParentId={};subsetOfParentIds.forEach((function(parentId){var distance=_this3.getDistanceToChild(parentId,childId);distance&&(distancesByParentId[parentId]=distance)}));var closestParentId,smallestDistance=Math.min.apply(Math,_toConsumableArray(Object.values(distancesByParentId)));return Object.entries(distancesByParentId).forEach((function(_ref3){var _ref4=_slicedToArray(_ref3,2),parentId=_ref4[0];_ref4[1]===smallestDistance&&(closestParentId=parentId)})),closestParentId},getDistanceToChild:function(parentId,childId){var distanceMemo=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,parentComponent=this.findComponent(parentId);if(parentComponent){var childIds=parentComponent.childIds;if(childIds.includes(childId))return distanceMemo;for(var i=0;i0&&void 0!==arguments[0]?arguments[0]:null;null===node&&(node=document);var allEls=Array.from(node.querySelectorAll("[wire\\:initial-data]")),onlyChildEls=Array.from(node.querySelectorAll("[wire\\:initial-data] [wire\\:initial-data]"));return allEls.filter((function(el){return!onlyChildEls.includes(el)}))},allModelElementsInside:function(root){return Array.from(root.querySelectorAll("[wire\\:model]"))},getByAttributeAndValue:function(attribute,value){return document.querySelector("[wire\\:".concat(attribute,'="').concat(value,'"]'))},nextFrame:function(fn){var _this=this;requestAnimationFrame((function(){requestAnimationFrame(fn.bind(_this))}))},closestRoot:function(el){return this.closestByAttribute(el,"id")},closestByAttribute:function(el,attribute){var closestEl=el.closest("[wire\\:".concat(attribute,"]"));if(!closestEl)throw"\nLivewire Error:\n\nCannot find parent element in DOM tree containing attribute: [wire:".concat(attribute,"].\n\nUsually this is caused by Livewire's DOM-differ not being able to properly track changes.\n\nReference the following guide for common causes: https://laravel-livewire.com/docs/troubleshooting \n\nReferenced element:\n\n").concat(el.outerHTML,"\n");return closestEl},isComponentRootEl:function(el){return this.hasAttribute(el,"id")},hasAttribute:function(el,attribute){return el.hasAttribute("wire:".concat(attribute))},getAttribute:function(el,attribute){return el.getAttribute("wire:".concat(attribute))},removeAttribute:function(el,attribute){return el.removeAttribute("wire:".concat(attribute))},setAttribute:function(el,attribute,value){return el.setAttribute("wire:".concat(attribute),value)},hasFocus:function(el){return el===document.activeElement},isInput:function(el){return["INPUT","TEXTAREA","SELECT"].includes(el.tagName.toUpperCase())},isTextInput:function(el){return["INPUT","TEXTAREA"].includes(el.tagName.toUpperCase())&&!["checkbox","radio"].includes(el.type)},valueFromInput:function(el,component){if("checkbox"===el.type){var modelName=wireDirectives(el).get("model").value,modelValue=component.deferredActions[modelName]?component.deferredActions[modelName].payload.value:getValue(component.data,modelName);return Array.isArray(modelValue)?this.mergeCheckboxValueIntoArray(el,modelValue):!!el.checked&&(el.getAttribute("value")||!0)}return"SELECT"===el.tagName&&el.multiple?this.getSelectValues(el):el.value},mergeCheckboxValueIntoArray:function(el,arrayValue){return el.checked?arrayValue.includes(el.value)?arrayValue:arrayValue.concat(el.value):arrayValue.filter((function(item){return item!==el.value}))},setInputValueFromModel:function(el,component){var modelString=wireDirectives(el).get("model").value,modelValue=getValue(component.data,modelString);"input"===el.tagName.toLowerCase()&&"file"===el.type||this.setInputValue(el,modelValue)},setInputValue:function(el,value){if(store$2.callHook("interceptWireModelSetValue",value,el),"radio"===el.type)el.checked=el.value==value;else if("checkbox"===el.type)if(Array.isArray(value)){var valueFound=!1;value.forEach((function(val){val==el.value&&(valueFound=!0)})),el.checked=valueFound}else el.checked=!!value;else"SELECT"===el.tagName?this.updateSelect(el,value):(value=void 0===value?"":value,el.value=value)},getSelectValues:function(el){return Array.from(el.options).filter((function(option){return option.selected})).map((function(option){return option.value||option.text}))},updateSelect:function(el,value){var arrayWrappedValue=[].concat(value).map((function(value){return value+""}));Array.from(el.options).forEach((function(option){option.selected=arrayWrappedValue.includes(option.value)}))}},ceil=Math.ceil,floor=Math.floor,toInteger=function(argument){return isNaN(argument=+argument)?0:(argument>0?floor:ceil)(argument)},requireObjectCoercible=function(it){if(null==it)throw TypeError("Can't call method on "+it);return it},createMethod$3=function(CONVERT_TO_STRING){return function($this,pos){var first,second,S=String(requireObjectCoercible($this)),position=toInteger(pos),size=S.length;return position<0||position>=size?CONVERT_TO_STRING?"":void 0:(first=S.charCodeAt(position))<55296||first>56319||position+1===size||(second=S.charCodeAt(position+1))<56320||second>57343?CONVERT_TO_STRING?S.charAt(position):first:CONVERT_TO_STRING?S.slice(position,position+2):second-56320+(first-55296<<10)+65536}},stringMultibyte={codeAt:createMethod$3(!1),charAt:createMethod$3(!0)},commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(fn,basedir,module){return fn(module={path:basedir,exports:{},require:function(path,base){return commonjsRequire(path,null==base?module.path:base)}},module.exports),module.exports}function commonjsRequire(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}var check=function(it){return it&&it.Math==Math&&it},global_1=check("object"==typeof globalThis&&globalThis)||check("object"==typeof window&&window)||check("object"==typeof self&&self)||check("object"==typeof commonjsGlobal&&commonjsGlobal)||function(){return this}()||Function("return this")(),fails=function(exec){try{return!!exec()}catch(error){return!0}},descriptors=!fails((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),isObject=function(it){return"object"==typeof it?null!==it:"function"==typeof it},document$3=global_1.document,EXISTS=isObject(document$3)&&isObject(document$3.createElement),documentCreateElement=function(it){return EXISTS?document$3.createElement(it):{}},ie8DomDefine=!descriptors&&!fails((function(){return 7!=Object.defineProperty(documentCreateElement("div"),"a",{get:function(){return 7}}).a})),anObject=function(it){if(!isObject(it))throw TypeError(String(it)+" is not an object");return it},toPrimitive=function(input,PREFERRED_STRING){if(!isObject(input))return input;var fn,val;if(PREFERRED_STRING&&"function"==typeof(fn=input.toString)&&!isObject(val=fn.call(input)))return val;if("function"==typeof(fn=input.valueOf)&&!isObject(val=fn.call(input)))return val;if(!PREFERRED_STRING&&"function"==typeof(fn=input.toString)&&!isObject(val=fn.call(input)))return val;throw TypeError("Can't convert object to primitive value")},$defineProperty=Object.defineProperty,f$5=descriptors?$defineProperty:function(O,P,Attributes){if(anObject(O),P=toPrimitive(P,!0),anObject(Attributes),ie8DomDefine)try{return $defineProperty(O,P,Attributes)}catch(error){}if("get"in Attributes||"set"in Attributes)throw TypeError("Accessors not supported");return"value"in Attributes&&(O[P]=Attributes.value),O},objectDefineProperty={f:f$5},createPropertyDescriptor=function(bitmap,value){return{enumerable:!(1&bitmap),configurable:!(2&bitmap),writable:!(4&bitmap),value:value}},createNonEnumerableProperty=descriptors?function(object,key,value){return objectDefineProperty.f(object,key,createPropertyDescriptor(1,value))}:function(object,key,value){return object[key]=value,object},setGlobal=function(key,value){try{createNonEnumerableProperty(global_1,key,value)}catch(error){global_1[key]=value}return value},SHARED="__core-js_shared__",store$1=global_1[SHARED]||setGlobal(SHARED,{}),sharedStore=store$1,functionToString=Function.toString;"function"!=typeof sharedStore.inspectSource&&(sharedStore.inspectSource=function(it){return functionToString.call(it)});var inspectSource=sharedStore.inspectSource,WeakMap$1=global_1.WeakMap,nativeWeakMap="function"==typeof WeakMap$1&&/native code/.test(inspectSource(WeakMap$1)),toObject=function(argument){return Object(requireObjectCoercible(argument))},hasOwnProperty={}.hasOwnProperty,has$1=Object.hasOwn||function(it,key){return hasOwnProperty.call(toObject(it),key)},shared=createCommonjsModule((function(module){(module.exports=function(key,value){return sharedStore[key]||(sharedStore[key]=void 0!==value?value:{})})("versions",[]).push({version:"3.15.2",mode:"global",copyright:"© 2021 Denis Pushkarev (zloirock.ru)"})})),id=0,postfix=Math.random(),uid=function(key){return"Symbol("+String(void 0===key?"":key)+")_"+(++id+postfix).toString(36)},keys=shared("keys"),sharedKey=function(key){return keys[key]||(keys[key]=uid(key))},hiddenKeys$1={},OBJECT_ALREADY_INITIALIZED="Object already initialized",WeakMap=global_1.WeakMap,set$1,get,has,enforce=function(it){return has(it)?get(it):set$1(it,{})},getterFor=function(TYPE){return function(it){var state;if(!isObject(it)||(state=get(it)).type!==TYPE)throw TypeError("Incompatible receiver, "+TYPE+" required");return state}};if(nativeWeakMap||sharedStore.state){var store=sharedStore.state||(sharedStore.state=new WeakMap),wmget=store.get,wmhas=store.has,wmset=store.set;set$1=function(it,metadata){if(wmhas.call(store,it))throw new TypeError(OBJECT_ALREADY_INITIALIZED);return metadata.facade=it,wmset.call(store,it,metadata),metadata},get=function(it){return wmget.call(store,it)||{}},has=function(it){return wmhas.call(store,it)}}else{var STATE=sharedKey("state");hiddenKeys$1[STATE]=!0,set$1=function(it,metadata){if(has$1(it,STATE))throw new TypeError(OBJECT_ALREADY_INITIALIZED);return metadata.facade=it,createNonEnumerableProperty(it,STATE,metadata),metadata},get=function(it){return has$1(it,STATE)?it[STATE]:{}},has=function(it){return has$1(it,STATE)}}var internalState={set:set$1,get:get,has:has,enforce:enforce,getterFor:getterFor},$propertyIsEnumerable={}.propertyIsEnumerable,getOwnPropertyDescriptor$3=Object.getOwnPropertyDescriptor,NASHORN_BUG=getOwnPropertyDescriptor$3&&!$propertyIsEnumerable.call({1:2},1),f$4=NASHORN_BUG?function(V){var descriptor=getOwnPropertyDescriptor$3(this,V);return!!descriptor&&descriptor.enumerable}:$propertyIsEnumerable,objectPropertyIsEnumerable={f:f$4},toString={}.toString,classofRaw=function(it){return toString.call(it).slice(8,-1)},split="".split,indexedObject=fails((function(){return!Object("z").propertyIsEnumerable(0)}))?function(it){return"String"==classofRaw(it)?split.call(it,""):Object(it)}:Object,toIndexedObject=function(it){return indexedObject(requireObjectCoercible(it))},$getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor,f$3=descriptors?$getOwnPropertyDescriptor:function(O,P){if(O=toIndexedObject(O),P=toPrimitive(P,!0),ie8DomDefine)try{return $getOwnPropertyDescriptor(O,P)}catch(error){}if(has$1(O,P))return createPropertyDescriptor(!objectPropertyIsEnumerable.f.call(O,P),O[P])},objectGetOwnPropertyDescriptor={f:f$3},redefine=createCommonjsModule((function(module){var getInternalState=internalState.get,enforceInternalState=internalState.enforce,TEMPLATE=String(String).split("String");(module.exports=function(O,key,value,options){var state,unsafe=!!options&&!!options.unsafe,simple=!!options&&!!options.enumerable,noTargetGet=!!options&&!!options.noTargetGet;"function"==typeof value&&("string"!=typeof key||has$1(value,"name")||createNonEnumerableProperty(value,"name",key),(state=enforceInternalState(value)).source||(state.source=TEMPLATE.join("string"==typeof key?key:""))),O!==global_1?(unsafe?!noTargetGet&&O[key]&&(simple=!0):delete O[key],simple?O[key]=value:createNonEnumerableProperty(O,key,value)):simple?O[key]=value:setGlobal(key,value)})(Function.prototype,"toString",(function(){return"function"==typeof this&&getInternalState(this).source||inspectSource(this)}))})),path=global_1,aFunction$1=function(variable){return"function"==typeof variable?variable:void 0},getBuiltIn=function(namespace,method){return arguments.length<2?aFunction$1(path[namespace])||aFunction$1(global_1[namespace]):path[namespace]&&path[namespace][method]||global_1[namespace]&&global_1[namespace][method]},min$2=Math.min,toLength=function(argument){return argument>0?min$2(toInteger(argument),9007199254740991):0},max=Math.max,min$1=Math.min,toAbsoluteIndex=function(index,length){var integer=toInteger(index);return integer<0?max(integer+length,0):min$1(integer,length)},createMethod$2=function(IS_INCLUDES){return function($this,el,fromIndex){var value,O=toIndexedObject($this),length=toLength(O.length),index=toAbsoluteIndex(fromIndex,length);if(IS_INCLUDES&&el!=el){for(;length>index;)if((value=O[index++])!=value)return!0}else for(;length>index;index++)if((IS_INCLUDES||index in O)&&O[index]===el)return IS_INCLUDES||index||0;return!IS_INCLUDES&&-1}},arrayIncludes={includes:createMethod$2(!0),indexOf:createMethod$2(!1)},indexOf=arrayIncludes.indexOf,objectKeysInternal=function(object,names){var key,O=toIndexedObject(object),i=0,result=[];for(key in O)!has$1(hiddenKeys$1,key)&&has$1(O,key)&&result.push(key);for(;names.length>i;)has$1(O,key=names[i++])&&(~indexOf(result,key)||result.push(key));return result},enumBugKeys=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],hiddenKeys=enumBugKeys.concat("length","prototype"),f$2=Object.getOwnPropertyNames||function(O){return objectKeysInternal(O,hiddenKeys)},objectGetOwnPropertyNames={f:f$2},f$1=Object.getOwnPropertySymbols,objectGetOwnPropertySymbols={f:f$1},ownKeys=getBuiltIn("Reflect","ownKeys")||function(it){var keys=objectGetOwnPropertyNames.f(anObject(it)),getOwnPropertySymbols=objectGetOwnPropertySymbols.f;return getOwnPropertySymbols?keys.concat(getOwnPropertySymbols(it)):keys},copyConstructorProperties=function(target,source){for(var keys=ownKeys(source),defineProperty=objectDefineProperty.f,getOwnPropertyDescriptor=objectGetOwnPropertyDescriptor.f,i=0;i=74)&&(match=engineUserAgent.match(/Chrome\/(\d+)/),match&&(version=match[1])));var engineV8Version=version&&+version,nativeSymbol=!!Object.getOwnPropertySymbols&&!fails((function(){var symbol=Symbol();return!String(symbol)||!(Object(symbol)instanceof Symbol)||!Symbol.sham&&engineV8Version&&engineV8Version<41})),useSymbolAsUid=nativeSymbol&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,WellKnownSymbolsStore=shared("wks"),Symbol$1=global_1.Symbol,createWellKnownSymbol=useSymbolAsUid?Symbol$1:Symbol$1&&Symbol$1.withoutSetter||uid,wellKnownSymbol=function(name){return has$1(WellKnownSymbolsStore,name)&&(nativeSymbol||"string"==typeof WellKnownSymbolsStore[name])||(nativeSymbol&&has$1(Symbol$1,name)?WellKnownSymbolsStore[name]=Symbol$1[name]:WellKnownSymbolsStore[name]=createWellKnownSymbol("Symbol."+name)),WellKnownSymbolsStore[name]},ITERATOR$5=wellKnownSymbol("iterator"),BUGGY_SAFARI_ITERATORS$1=!1,returnThis$2=function(){return this},IteratorPrototype$2,PrototypeOfArrayIteratorPrototype,arrayIterator;[].keys&&(arrayIterator=[].keys(),"next"in arrayIterator?(PrototypeOfArrayIteratorPrototype=objectGetPrototypeOf(objectGetPrototypeOf(arrayIterator)),PrototypeOfArrayIteratorPrototype!==Object.prototype&&(IteratorPrototype$2=PrototypeOfArrayIteratorPrototype)):BUGGY_SAFARI_ITERATORS$1=!0);var NEW_ITERATOR_PROTOTYPE=null==IteratorPrototype$2||fails((function(){var test={};return IteratorPrototype$2[ITERATOR$5].call(test)!==test}));NEW_ITERATOR_PROTOTYPE&&(IteratorPrototype$2={}),has$1(IteratorPrototype$2,ITERATOR$5)||createNonEnumerableProperty(IteratorPrototype$2,ITERATOR$5,returnThis$2);var iteratorsCore={IteratorPrototype:IteratorPrototype$2,BUGGY_SAFARI_ITERATORS:BUGGY_SAFARI_ITERATORS$1},objectKeys=Object.keys||function(O){return objectKeysInternal(O,enumBugKeys)},objectDefineProperties=descriptors?Object.defineProperties:function(O,Properties){anObject(O);for(var key,keys=objectKeys(Properties),length=keys.length,index=0;length>index;)objectDefineProperty.f(O,key=keys[index++],Properties[key]);return O},html=getBuiltIn("document","documentElement"),GT=">",LT="<",PROTOTYPE="prototype",SCRIPT="script",IE_PROTO=sharedKey("IE_PROTO"),EmptyConstructor=function(){},scriptTag=function(content){return LT+SCRIPT+GT+content+LT+"/"+SCRIPT+GT},NullProtoObjectViaActiveX=function(activeXDocument){activeXDocument.write(scriptTag("")),activeXDocument.close();var temp=activeXDocument.parentWindow.Object;return activeXDocument=null,temp},NullProtoObjectViaIFrame=function(){var iframeDocument,iframe=documentCreateElement("iframe"),JS="java"+SCRIPT+":";return iframe.style.display="none",html.appendChild(iframe),iframe.src=String(JS),(iframeDocument=iframe.contentWindow.document).open(),iframeDocument.write(scriptTag("document.F=Object")),iframeDocument.close(),iframeDocument.F},activeXDocument,NullProtoObject=function(){try{activeXDocument=document.domain&&new ActiveXObject("htmlfile")}catch(error){}NullProtoObject=activeXDocument?NullProtoObjectViaActiveX(activeXDocument):NullProtoObjectViaIFrame();for(var length=enumBugKeys.length;length--;)delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];return NullProtoObject()};hiddenKeys$1[IE_PROTO]=!0;var objectCreate=Object.create||function(O,Properties){var result;return null!==O?(EmptyConstructor[PROTOTYPE]=anObject(O),result=new EmptyConstructor,EmptyConstructor[PROTOTYPE]=null,result[IE_PROTO]=O):result=NullProtoObject(),void 0===Properties?result:objectDefineProperties(result,Properties)},defineProperty$1=objectDefineProperty.f,TO_STRING_TAG$3=wellKnownSymbol("toStringTag"),setToStringTag=function(it,TAG,STATIC){it&&!has$1(it=STATIC?it:it.prototype,TO_STRING_TAG$3)&&defineProperty$1(it,TO_STRING_TAG$3,{configurable:!0,value:TAG})},iterators={},IteratorPrototype$1=iteratorsCore.IteratorPrototype,returnThis$1=function(){return this},createIteratorConstructor=function(IteratorConstructor,NAME,next){var TO_STRING_TAG=NAME+" Iterator";return IteratorConstructor.prototype=objectCreate(IteratorPrototype$1,{next:createPropertyDescriptor(1,next)}),setToStringTag(IteratorConstructor,TO_STRING_TAG,!1),iterators[TO_STRING_TAG]=returnThis$1,IteratorConstructor},aPossiblePrototype=function(it){if(!isObject(it)&&null!==it)throw TypeError("Can't set "+String(it)+" as a prototype");return it},objectSetPrototypeOf=Object.setPrototypeOf||("__proto__"in{}?function(){var setter,CORRECT_SETTER=!1,test={};try{(setter=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(test,[]),CORRECT_SETTER=test instanceof Array}catch(error){}return function(O,proto){return anObject(O),aPossiblePrototype(proto),CORRECT_SETTER?setter.call(O,proto):O.__proto__=proto,O}}():void 0),IteratorPrototype=iteratorsCore.IteratorPrototype,BUGGY_SAFARI_ITERATORS=iteratorsCore.BUGGY_SAFARI_ITERATORS,ITERATOR$4=wellKnownSymbol("iterator"),KEYS="keys",VALUES="values",ENTRIES="entries",returnThis=function(){return this},defineIterator=function(Iterable,NAME,IteratorConstructor,next,DEFAULT,IS_SET,FORCED){createIteratorConstructor(IteratorConstructor,NAME,next);var CurrentIteratorPrototype,methods,KEY,getIterationMethod=function(KIND){if(KIND===DEFAULT&&defaultIterator)return defaultIterator;if(!BUGGY_SAFARI_ITERATORS&&KIND in IterablePrototype)return IterablePrototype[KIND];switch(KIND){case KEYS:case VALUES:case ENTRIES:return function(){return new IteratorConstructor(this,KIND)}}return function(){return new IteratorConstructor(this)}},TO_STRING_TAG=NAME+" Iterator",INCORRECT_VALUES_NAME=!1,IterablePrototype=Iterable.prototype,nativeIterator=IterablePrototype[ITERATOR$4]||IterablePrototype["@@iterator"]||DEFAULT&&IterablePrototype[DEFAULT],defaultIterator=!BUGGY_SAFARI_ITERATORS&&nativeIterator||getIterationMethod(DEFAULT),anyNativeIterator="Array"==NAME&&IterablePrototype.entries||nativeIterator;if(anyNativeIterator&&(CurrentIteratorPrototype=objectGetPrototypeOf(anyNativeIterator.call(new Iterable)),IteratorPrototype!==Object.prototype&&CurrentIteratorPrototype.next&&(objectGetPrototypeOf(CurrentIteratorPrototype)!==IteratorPrototype&&(objectSetPrototypeOf?objectSetPrototypeOf(CurrentIteratorPrototype,IteratorPrototype):"function"!=typeof CurrentIteratorPrototype[ITERATOR$4]&&createNonEnumerableProperty(CurrentIteratorPrototype,ITERATOR$4,returnThis)),setToStringTag(CurrentIteratorPrototype,TO_STRING_TAG,!0))),DEFAULT==VALUES&&nativeIterator&&nativeIterator.name!==VALUES&&(INCORRECT_VALUES_NAME=!0,defaultIterator=function(){return nativeIterator.call(this)}),IterablePrototype[ITERATOR$4]!==defaultIterator&&createNonEnumerableProperty(IterablePrototype,ITERATOR$4,defaultIterator),iterators[NAME]=defaultIterator,DEFAULT)if(methods={values:getIterationMethod(VALUES),keys:IS_SET?defaultIterator:getIterationMethod(KEYS),entries:getIterationMethod(ENTRIES)},FORCED)for(KEY in methods)(BUGGY_SAFARI_ITERATORS||INCORRECT_VALUES_NAME||!(KEY in IterablePrototype))&&redefine(IterablePrototype,KEY,methods[KEY]);else _export({target:NAME,proto:!0,forced:BUGGY_SAFARI_ITERATORS||INCORRECT_VALUES_NAME},methods);return methods},charAt=stringMultibyte.charAt,STRING_ITERATOR="String Iterator",setInternalState$2=internalState.set,getInternalState$2=internalState.getterFor(STRING_ITERATOR);defineIterator(String,"String",(function(iterated){setInternalState$2(this,{type:STRING_ITERATOR,string:String(iterated),index:0})}),(function(){var point,state=getInternalState$2(this),string=state.string,index=state.index;return index>=string.length?{value:void 0,done:!0}:(point=charAt(string,index),state.index+=point.length,{value:point,done:!1})}));var aFunction=function(it){if("function"!=typeof it)throw TypeError(String(it)+" is not a function");return it},functionBindContext=function(fn,that,length){if(aFunction(fn),void 0===that)return fn;switch(length){case 0:return function(){return fn.call(that)};case 1:return function(a){return fn.call(that,a)};case 2:return function(a,b){return fn.call(that,a,b)};case 3:return function(a,b,c){return fn.call(that,a,b,c)}}return function(){return fn.apply(that,arguments)}},iteratorClose=function(iterator){var returnMethod=iterator.return;if(void 0!==returnMethod)return anObject(returnMethod.call(iterator)).value},callWithSafeIterationClosing=function(iterator,fn,value,ENTRIES){try{return ENTRIES?fn(anObject(value)[0],value[1]):fn(value)}catch(error){throw iteratorClose(iterator),error}},ITERATOR$3=wellKnownSymbol("iterator"),ArrayPrototype$1=Array.prototype,isArrayIteratorMethod=function(it){return void 0!==it&&(iterators.Array===it||ArrayPrototype$1[ITERATOR$3]===it)},createProperty=function(object,key,value){var propertyKey=toPrimitive(key);propertyKey in object?objectDefineProperty.f(object,propertyKey,createPropertyDescriptor(0,value)):object[propertyKey]=value},TO_STRING_TAG$2=wellKnownSymbol("toStringTag"),test={};test[TO_STRING_TAG$2]="z";var toStringTagSupport="[object z]"===String(test),TO_STRING_TAG$1=wellKnownSymbol("toStringTag"),CORRECT_ARGUMENTS="Arguments"==classofRaw(function(){return arguments}()),tryGet=function(it,key){try{return it[key]}catch(error){}},classof=toStringTagSupport?classofRaw:function(it){var O,tag,result;return void 0===it?"Undefined":null===it?"Null":"string"==typeof(tag=tryGet(O=Object(it),TO_STRING_TAG$1))?tag:CORRECT_ARGUMENTS?classofRaw(O):"Object"==(result=classofRaw(O))&&"function"==typeof O.callee?"Arguments":result},ITERATOR$2=wellKnownSymbol("iterator"),getIteratorMethod=function(it){if(null!=it)return it[ITERATOR$2]||it["@@iterator"]||iterators[classof(it)]},arrayFrom=function(arrayLike){var length,result,step,iterator,next,value,O=toObject(arrayLike),C="function"==typeof this?this:Array,argumentsLength=arguments.length,mapfn=argumentsLength>1?arguments[1]:void 0,mapping=void 0!==mapfn,iteratorMethod=getIteratorMethod(O),index=0;if(mapping&&(mapfn=functionBindContext(mapfn,argumentsLength>2?arguments[2]:void 0,2)),null==iteratorMethod||C==Array&&isArrayIteratorMethod(iteratorMethod))for(result=new C(length=toLength(O.length));length>index;index++)value=mapping?mapfn(O[index],index):O[index],createProperty(result,index,value);else for(next=(iterator=iteratorMethod.call(O)).next,result=new C;!(step=next.call(iterator)).done;index++)value=mapping?callWithSafeIterationClosing(iterator,mapfn,[step.value,index],!0):step.value,createProperty(result,index,value);return result.length=index,result},ITERATOR$1=wellKnownSymbol("iterator"),SAFE_CLOSING=!1;try{var called=0,iteratorWithReturn={next:function(){return{done:!!called++}},return:function(){SAFE_CLOSING=!0}};iteratorWithReturn[ITERATOR$1]=function(){return this},Array.from(iteratorWithReturn,(function(){throw 2}))}catch(error){}var checkCorrectnessOfIteration=function(exec,SKIP_CLOSING){if(!SKIP_CLOSING&&!SAFE_CLOSING)return!1;var ITERATION_SUPPORT=!1;try{var object={};object[ITERATOR$1]=function(){return{next:function(){return{done:ITERATION_SUPPORT=!0}}}},exec(object)}catch(error){}return ITERATION_SUPPORT},INCORRECT_ITERATION$1=!checkCorrectnessOfIteration((function(iterable){Array.from(iterable)}));_export({target:"Array",stat:!0,forced:INCORRECT_ITERATION$1},{from:arrayFrom}),path.Array.from;var UNSCOPABLES=wellKnownSymbol("unscopables"),ArrayPrototype=Array.prototype;null==ArrayPrototype[UNSCOPABLES]&&objectDefineProperty.f(ArrayPrototype,UNSCOPABLES,{configurable:!0,value:objectCreate(null)});var addToUnscopables=function(key){ArrayPrototype[UNSCOPABLES][key]=!0},$includes=arrayIncludes.includes;_export({target:"Array",proto:!0},{includes:function(el){return $includes(this,el,arguments.length>1?arguments[1]:void 0)}}),addToUnscopables("includes");var call=Function.call,entryUnbind=function(CONSTRUCTOR,METHOD,length){return functionBindContext(call,global_1[CONSTRUCTOR].prototype[METHOD],length)};entryUnbind("Array","includes");var isArray=Array.isArray||function(arg){return"Array"==classofRaw(arg)},flattenIntoArray=function(target,original,source,sourceLen,start,depth,mapper,thisArg){for(var element,targetIndex=start,sourceIndex=0,mapFn=!!mapper&&functionBindContext(mapper,thisArg,3);sourceIndex0&&isArray(element))targetIndex=flattenIntoArray(target,original,element,toLength(element.length),targetIndex,depth-1)-1;else{if(targetIndex>=9007199254740991)throw TypeError("Exceed the acceptable array length");target[targetIndex]=element}targetIndex++}sourceIndex++}return targetIndex},flattenIntoArray_1=flattenIntoArray,SPECIES$3=wellKnownSymbol("species"),arraySpeciesCreate=function(originalArray,length){var C;return isArray(originalArray)&&("function"!=typeof(C=originalArray.constructor)||C!==Array&&!isArray(C.prototype)?isObject(C)&&null===(C=C[SPECIES$3])&&(C=void 0):C=void 0),new(void 0===C?Array:C)(0===length?0:length)};_export({target:"Array",proto:!0},{flat:function(){var depthArg=arguments.length?arguments[0]:void 0,O=toObject(this),sourceLen=toLength(O.length),A=arraySpeciesCreate(O,0);return A.length=flattenIntoArray_1(A,O,O,sourceLen,0,void 0===depthArg?1:toInteger(depthArg)),A}}),addToUnscopables("flat"),entryUnbind("Array","flat");var push=[].push,createMethod$1=function(TYPE){var IS_MAP=1==TYPE,IS_FILTER=2==TYPE,IS_SOME=3==TYPE,IS_EVERY=4==TYPE,IS_FIND_INDEX=6==TYPE,IS_FILTER_OUT=7==TYPE,NO_HOLES=5==TYPE||IS_FIND_INDEX;return function($this,callbackfn,that,specificCreate){for(var value,result,O=toObject($this),self=indexedObject(O),boundFunction=functionBindContext(callbackfn,that,3),length=toLength(self.length),index=0,create=specificCreate||arraySpeciesCreate,target=IS_MAP?create($this,length):IS_FILTER||IS_FILTER_OUT?create($this,0):void 0;length>index;index++)if((NO_HOLES||index in self)&&(result=boundFunction(value=self[index],index,O),TYPE))if(IS_MAP)target[index]=result;else if(result)switch(TYPE){case 3:return!0;case 5:return value;case 6:return index;case 2:push.call(target,value)}else switch(TYPE){case 4:return!1;case 7:push.call(target,value)}return IS_FIND_INDEX?-1:IS_SOME||IS_EVERY?IS_EVERY:target}},arrayIteration={forEach:createMethod$1(0),map:createMethod$1(1),filter:createMethod$1(2),some:createMethod$1(3),every:createMethod$1(4),find:createMethod$1(5),findIndex:createMethod$1(6),filterOut:createMethod$1(7)},$find=arrayIteration.find,FIND="find",SKIPS_HOLES=!0;FIND in[]&&Array(1)[FIND]((function(){SKIPS_HOLES=!1})),_export({target:"Array",proto:!0,forced:SKIPS_HOLES},{find:function(callbackfn){return $find(this,callbackfn,arguments.length>1?arguments[1]:void 0)}}),addToUnscopables(FIND),entryUnbind("Array","find");var $assign=Object.assign,defineProperty=Object.defineProperty,objectAssign=!$assign||fails((function(){if(descriptors&&1!==$assign({b:1},$assign(defineProperty({},"a",{enumerable:!0,get:function(){defineProperty(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var A={},B={},symbol=Symbol();return A[symbol]=7,"abcdefghijklmnopqrst".split("").forEach((function(chr){B[chr]=chr})),7!=$assign({},A)[symbol]||"abcdefghijklmnopqrst"!=objectKeys($assign({},B)).join("")}))?function(target,source){for(var T=toObject(target),argumentsLength=arguments.length,index=1,getOwnPropertySymbols=objectGetOwnPropertySymbols.f,propertyIsEnumerable=objectPropertyIsEnumerable.f;argumentsLength>index;)for(var key,S=indexedObject(arguments[index++]),keys=getOwnPropertySymbols?objectKeys(S).concat(getOwnPropertySymbols(S)):objectKeys(S),length=keys.length,j=0;length>j;)key=keys[j++],descriptors&&!propertyIsEnumerable.call(S,key)||(T[key]=S[key]);return T}:$assign;_export({target:"Object",stat:!0,forced:Object.assign!==objectAssign},{assign:objectAssign}),path.Object.assign;var propertyIsEnumerable=objectPropertyIsEnumerable.f,createMethod=function(TO_ENTRIES){return function(it){for(var key,O=toIndexedObject(it),keys=objectKeys(O),length=keys.length,i=0,result=[];length>i;)key=keys[i++],descriptors&&!propertyIsEnumerable.call(O,key)||result.push(TO_ENTRIES?[key,O[key]]:O[key]);return result}},objectToArray={entries:createMethod(!0),values:createMethod(!1)},$entries=objectToArray.entries;_export({target:"Object",stat:!0},{entries:function(O){return $entries(O)}}),path.Object.entries;var $values=objectToArray.values;_export({target:"Object",stat:!0},{values:function(O){return $values(O)}}),path.Object.values;var Result=function(stopped,result){this.stopped=stopped,this.result=result},iterate=function(iterable,unboundFunction,options){var iterator,iterFn,index,length,result,next,step,that=options&&options.that,AS_ENTRIES=!(!options||!options.AS_ENTRIES),IS_ITERATOR=!(!options||!options.IS_ITERATOR),INTERRUPTED=!(!options||!options.INTERRUPTED),fn=functionBindContext(unboundFunction,that,1+AS_ENTRIES+INTERRUPTED),stop=function(condition){return iterator&&iteratorClose(iterator),new Result(!0,condition)},callFn=function(value){return AS_ENTRIES?(anObject(value),INTERRUPTED?fn(value[0],value[1],stop):fn(value[0],value[1])):INTERRUPTED?fn(value,stop):fn(value)};if(IS_ITERATOR)iterator=iterable;else{if("function"!=typeof(iterFn=getIteratorMethod(iterable)))throw TypeError("Target is not iterable");if(isArrayIteratorMethod(iterFn)){for(index=0,length=toLength(iterable.length);length>index;index++)if((result=callFn(iterable[index]))&&result instanceof Result)return result;return new Result(!1)}iterator=iterFn.call(iterable)}for(next=iterator.next;!(step=next.call(iterator)).done;){try{result=callFn(step.value)}catch(error){throw iteratorClose(iterator),error}if("object"==typeof result&&result&&result instanceof Result)return result}return new Result(!1)},$AggregateError=function(errors,message){var that=this;if(!(that instanceof $AggregateError))return new $AggregateError(errors,message);objectSetPrototypeOf&&(that=objectSetPrototypeOf(new Error(void 0),objectGetPrototypeOf(that))),void 0!==message&&createNonEnumerableProperty(that,"message",String(message));var errorsArray=[];return iterate(errors,errorsArray.push,{that:errorsArray}),createNonEnumerableProperty(that,"errors",errorsArray),that};$AggregateError.prototype=objectCreate(Error.prototype,{constructor:createPropertyDescriptor(5,$AggregateError),message:createPropertyDescriptor(5,""),name:createPropertyDescriptor(5,"AggregateError")}),_export({global:!0},{AggregateError:$AggregateError});var objectToString=toStringTagSupport?{}.toString:function(){return"[object "+classof(this)+"]"};toStringTagSupport||redefine(Object.prototype,"toString",objectToString,{unsafe:!0});var nativePromiseConstructor=global_1.Promise,redefineAll=function(target,src,options){for(var key in src)redefine(target,key,src[key],options);return target},SPECIES$2=wellKnownSymbol("species"),setSpecies=function(CONSTRUCTOR_NAME){var Constructor=getBuiltIn(CONSTRUCTOR_NAME),defineProperty=objectDefineProperty.f;descriptors&&Constructor&&!Constructor[SPECIES$2]&&defineProperty(Constructor,SPECIES$2,{configurable:!0,get:function(){return this}})},anInstance=function(it,Constructor,name){if(!(it instanceof Constructor))throw TypeError("Incorrect "+(name?name+" ":"")+"invocation");return it},SPECIES$1=wellKnownSymbol("species"),speciesConstructor=function(O,defaultConstructor){var S,C=anObject(O).constructor;return void 0===C||null==(S=anObject(C)[SPECIES$1])?defaultConstructor:aFunction(S)},engineIsIos=/(?:iphone|ipod|ipad).*applewebkit/i.test(engineUserAgent),engineIsNode="process"==classofRaw(global_1.process),location=global_1.location,set=global_1.setImmediate,clear=global_1.clearImmediate,process$2=global_1.process,MessageChannel=global_1.MessageChannel,Dispatch=global_1.Dispatch,counter=0,queue={},ONREADYSTATECHANGE="onreadystatechange",defer,channel,port,run=function(id){if(queue.hasOwnProperty(id)){var fn=queue[id];delete queue[id],fn()}},runner=function(id){return function(){run(id)}},listener=function(event){run(event.data)},post=function(id){global_1.postMessage(id+"",location.protocol+"//"+location.host)};set&&clear||(set=function(fn){for(var args=[],i=1;arguments.length>i;)args.push(arguments[i++]);return queue[++counter]=function(){("function"==typeof fn?fn:Function(fn)).apply(void 0,args)},defer(counter),counter},clear=function(id){delete queue[id]},engineIsNode?defer=function(id){process$2.nextTick(runner(id))}:Dispatch&&Dispatch.now?defer=function(id){Dispatch.now(runner(id))}:MessageChannel&&!engineIsIos?(channel=new MessageChannel,port=channel.port2,channel.port1.onmessage=listener,defer=functionBindContext(port.postMessage,port,1)):global_1.addEventListener&&"function"==typeof postMessage&&!global_1.importScripts&&location&&"file:"!==location.protocol&&!fails(post)?(defer=post,global_1.addEventListener("message",listener,!1)):defer=ONREADYSTATECHANGE in documentCreateElement("script")?function(id){html.appendChild(documentCreateElement("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this),run(id)}}:function(id){setTimeout(runner(id),0)});var task$1={set:set,clear:clear},engineIsWebosWebkit=/web0s(?!.*chrome)/i.test(engineUserAgent),getOwnPropertyDescriptor$1=objectGetOwnPropertyDescriptor.f,macrotask=task$1.set,MutationObserver=global_1.MutationObserver||global_1.WebKitMutationObserver,document$2=global_1.document,process$1=global_1.process,Promise$1=global_1.Promise,queueMicrotaskDescriptor=getOwnPropertyDescriptor$1(global_1,"queueMicrotask"),queueMicrotask=queueMicrotaskDescriptor&&queueMicrotaskDescriptor.value,flush,head,last,notify$1,toggle,node,promise,then;queueMicrotask||(flush=function(){var parent,fn;for(engineIsNode&&(parent=process$1.domain)&&parent.exit();head;){fn=head.fn,head=head.next;try{fn()}catch(error){throw head?notify$1():last=void 0,error}}last=void 0,parent&&parent.enter()},engineIsIos||engineIsNode||engineIsWebosWebkit||!MutationObserver||!document$2?Promise$1&&Promise$1.resolve?(promise=Promise$1.resolve(void 0),promise.constructor=Promise$1,then=promise.then,notify$1=function(){then.call(promise,flush)}):notify$1=engineIsNode?function(){process$1.nextTick(flush)}:function(){macrotask.call(global_1,flush)}:(toggle=!0,node=document$2.createTextNode(""),new MutationObserver(flush).observe(node,{characterData:!0}),notify$1=function(){node.data=toggle=!toggle}));var microtask=queueMicrotask||function(fn){var task={fn:fn,next:void 0};last&&(last.next=task),head||(head=task,notify$1()),last=task},PromiseCapability=function(C){var resolve,reject;this.promise=new C((function($$resolve,$$reject){if(void 0!==resolve||void 0!==reject)throw TypeError("Bad Promise constructor");resolve=$$resolve,reject=$$reject})),this.resolve=aFunction(resolve),this.reject=aFunction(reject)},f=function(C){return new PromiseCapability(C)},newPromiseCapability$1={f:f},promiseResolve=function(C,x){if(anObject(C),isObject(x)&&x.constructor===C)return x;var promiseCapability=newPromiseCapability$1.f(C);return(0,promiseCapability.resolve)(x),promiseCapability.promise},hostReportErrors=function(a,b){var console=global_1.console;console&&console.error&&(1===arguments.length?console.error(a):console.error(a,b))},perform=function(exec){try{return{error:!1,value:exec()}}catch(error){return{error:!0,value:error}}},engineIsBrowser="object"==typeof window,task=task$1.set,SPECIES=wellKnownSymbol("species"),PROMISE="Promise",getInternalState$1=internalState.get,setInternalState$1=internalState.set,getInternalPromiseState=internalState.getterFor(PROMISE),NativePromisePrototype=nativePromiseConstructor&&nativePromiseConstructor.prototype,PromiseConstructor=nativePromiseConstructor,PromiseConstructorPrototype=NativePromisePrototype,TypeError$1=global_1.TypeError,document$1=global_1.document,process=global_1.process,newPromiseCapability=newPromiseCapability$1.f,newGenericPromiseCapability=newPromiseCapability,DISPATCH_EVENT=!!(document$1&&document$1.createEvent&&global_1.dispatchEvent),NATIVE_REJECTION_EVENT="function"==typeof PromiseRejectionEvent,UNHANDLED_REJECTION="unhandledrejection",REJECTION_HANDLED="rejectionhandled",PENDING=0,FULFILLED=1,REJECTED=2,HANDLED=1,UNHANDLED=2,SUBCLASSING=!1,Internal,OwnPromiseCapability,PromiseWrapper,nativeThen,FORCED=isForced_1(PROMISE,(function(){var PROMISE_CONSTRUCTOR_SOURCE=inspectSource(PromiseConstructor),GLOBAL_CORE_JS_PROMISE=PROMISE_CONSTRUCTOR_SOURCE!==String(PromiseConstructor);if(!GLOBAL_CORE_JS_PROMISE&&66===engineV8Version)return!0;if(engineV8Version>=51&&/native code/.test(PROMISE_CONSTRUCTOR_SOURCE))return!1;var promise=new PromiseConstructor((function(resolve){resolve(1)})),FakePromise=function(exec){exec((function(){}),(function(){}))};return(promise.constructor={})[SPECIES]=FakePromise,!(SUBCLASSING=promise.then((function(){}))instanceof FakePromise)||!GLOBAL_CORE_JS_PROMISE&&engineIsBrowser&&!NATIVE_REJECTION_EVENT})),INCORRECT_ITERATION=FORCED||!checkCorrectnessOfIteration((function(iterable){PromiseConstructor.all(iterable).catch((function(){}))})),isThenable=function(it){var then;return!(!isObject(it)||"function"!=typeof(then=it.then))&&then},notify=function(state,isReject){if(!state.notified){state.notified=!0;var chain=state.reactions;microtask((function(){for(var value=state.value,ok=state.state==FULFILLED,index=0;chain.length>index;){var result,then,exited,reaction=chain[index++],handler=ok?reaction.ok:reaction.fail,resolve=reaction.resolve,reject=reaction.reject,domain=reaction.domain;try{handler?(ok||(state.rejection===UNHANDLED&&onHandleUnhandled(state),state.rejection=HANDLED),!0===handler?result=value:(domain&&domain.enter(),result=handler(value),domain&&(domain.exit(),exited=!0)),result===reaction.promise?reject(TypeError$1("Promise-chain cycle")):(then=isThenable(result))?then.call(result,resolve,reject):resolve(result)):reject(value)}catch(error){domain&&!exited&&domain.exit(),reject(error)}}state.reactions=[],state.notified=!1,isReject&&!state.rejection&&onUnhandled(state)}))}},dispatchEvent=function(name,promise,reason){var event,handler;DISPATCH_EVENT?((event=document$1.createEvent("Event")).promise=promise,event.reason=reason,event.initEvent(name,!1,!0),global_1.dispatchEvent(event)):event={promise:promise,reason:reason},!NATIVE_REJECTION_EVENT&&(handler=global_1["on"+name])?handler(event):name===UNHANDLED_REJECTION&&hostReportErrors("Unhandled promise rejection",reason)},onUnhandled=function(state){task.call(global_1,(function(){var result,promise=state.facade,value=state.value;if(isUnhandled(state)&&(result=perform((function(){engineIsNode?process.emit("unhandledRejection",value,promise):dispatchEvent(UNHANDLED_REJECTION,promise,value)})),state.rejection=engineIsNode||isUnhandled(state)?UNHANDLED:HANDLED,result.error))throw result.value}))},isUnhandled=function(state){return state.rejection!==HANDLED&&!state.parent},onHandleUnhandled=function(state){task.call(global_1,(function(){var promise=state.facade;engineIsNode?process.emit("rejectionHandled",promise):dispatchEvent(REJECTION_HANDLED,promise,state.value)}))},bind=function(fn,state,unwrap){return function(value){fn(state,value,unwrap)}},internalReject=function(state,value,unwrap){state.done||(state.done=!0,unwrap&&(state=unwrap),state.value=value,state.state=REJECTED,notify(state,!0))},internalResolve=function(state,value,unwrap){if(!state.done){state.done=!0,unwrap&&(state=unwrap);try{if(state.facade===value)throw TypeError$1("Promise can't be resolved itself");var then=isThenable(value);then?microtask((function(){var wrapper={done:!1};try{then.call(value,bind(internalResolve,wrapper,state),bind(internalReject,wrapper,state))}catch(error){internalReject(wrapper,error,state)}})):(state.value=value,state.state=FULFILLED,notify(state,!1))}catch(error){internalReject({done:!1},error,state)}}};if(FORCED&&(PromiseConstructor=function(executor){anInstance(this,PromiseConstructor,PROMISE),aFunction(executor),Internal.call(this);var state=getInternalState$1(this);try{executor(bind(internalResolve,state),bind(internalReject,state))}catch(error){internalReject(state,error)}},PromiseConstructorPrototype=PromiseConstructor.prototype,Internal=function(executor){setInternalState$1(this,{type:PROMISE,done:!1,notified:!1,parent:!1,reactions:[],rejection:!1,state:PENDING,value:void 0})},Internal.prototype=redefineAll(PromiseConstructorPrototype,{then:function(onFulfilled,onRejected){var state=getInternalPromiseState(this),reaction=newPromiseCapability(speciesConstructor(this,PromiseConstructor));return reaction.ok="function"!=typeof onFulfilled||onFulfilled,reaction.fail="function"==typeof onRejected&&onRejected,reaction.domain=engineIsNode?process.domain:void 0,state.parent=!0,state.reactions.push(reaction),state.state!=PENDING&¬ify(state,!1),reaction.promise},catch:function(onRejected){return this.then(void 0,onRejected)}}),OwnPromiseCapability=function(){var promise=new Internal,state=getInternalState$1(promise);this.promise=promise,this.resolve=bind(internalResolve,state),this.reject=bind(internalReject,state)},newPromiseCapability$1.f=newPromiseCapability=function(C){return C===PromiseConstructor||C===PromiseWrapper?new OwnPromiseCapability(C):newGenericPromiseCapability(C)},"function"==typeof nativePromiseConstructor&&NativePromisePrototype!==Object.prototype)){nativeThen=NativePromisePrototype.then,SUBCLASSING||(redefine(NativePromisePrototype,"then",(function(onFulfilled,onRejected){var that=this;return new PromiseConstructor((function(resolve,reject){nativeThen.call(that,resolve,reject)})).then(onFulfilled,onRejected)}),{unsafe:!0}),redefine(NativePromisePrototype,"catch",PromiseConstructorPrototype.catch,{unsafe:!0}));try{delete NativePromisePrototype.constructor}catch(error){}objectSetPrototypeOf&&objectSetPrototypeOf(NativePromisePrototype,PromiseConstructorPrototype)}_export({global:!0,wrap:!0,forced:FORCED},{Promise:PromiseConstructor}),setToStringTag(PromiseConstructor,PROMISE,!1),setSpecies(PROMISE),PromiseWrapper=getBuiltIn(PROMISE),_export({target:PROMISE,stat:!0,forced:FORCED},{reject:function(r){var capability=newPromiseCapability(this);return capability.reject.call(void 0,r),capability.promise}}),_export({target:PROMISE,stat:!0,forced:FORCED},{resolve:function(x){return promiseResolve(this,x)}}),_export({target:PROMISE,stat:!0,forced:INCORRECT_ITERATION},{all:function(iterable){var C=this,capability=newPromiseCapability(C),resolve=capability.resolve,reject=capability.reject,result=perform((function(){var $promiseResolve=aFunction(C.resolve),values=[],counter=0,remaining=1;iterate(iterable,(function(promise){var index=counter++,alreadyCalled=!1;values.push(void 0),remaining++,$promiseResolve.call(C,promise).then((function(value){alreadyCalled||(alreadyCalled=!0,values[index]=value,--remaining||resolve(values))}),reject)})),--remaining||resolve(values)}));return result.error&&reject(result.value),capability.promise},race:function(iterable){var C=this,capability=newPromiseCapability(C),reject=capability.reject,result=perform((function(){var $promiseResolve=aFunction(C.resolve);iterate(iterable,(function(promise){$promiseResolve.call(C,promise).then(capability.resolve,reject)}))}));return result.error&&reject(result.value),capability.promise}}),_export({target:"Promise",stat:!0},{allSettled:function(iterable){var C=this,capability=newPromiseCapability$1.f(C),resolve=capability.resolve,reject=capability.reject,result=perform((function(){var promiseResolve=aFunction(C.resolve),values=[],counter=0,remaining=1;iterate(iterable,(function(promise){var index=counter++,alreadyCalled=!1;values.push(void 0),remaining++,promiseResolve.call(C,promise).then((function(value){alreadyCalled||(alreadyCalled=!0,values[index]={status:"fulfilled",value:value},--remaining||resolve(values))}),(function(error){alreadyCalled||(alreadyCalled=!0,values[index]={status:"rejected",reason:error},--remaining||resolve(values))}))})),--remaining||resolve(values)}));return result.error&&reject(result.value),capability.promise}});var PROMISE_ANY_ERROR="No one promise resolved";_export({target:"Promise",stat:!0},{any:function(iterable){var C=this,capability=newPromiseCapability$1.f(C),resolve=capability.resolve,reject=capability.reject,result=perform((function(){var promiseResolve=aFunction(C.resolve),errors=[],counter=0,remaining=1,alreadyResolved=!1;iterate(iterable,(function(promise){var index=counter++,alreadyRejected=!1;errors.push(void 0),remaining++,promiseResolve.call(C,promise).then((function(value){alreadyRejected||alreadyResolved||(alreadyResolved=!0,resolve(value))}),(function(error){alreadyRejected||alreadyResolved||(alreadyRejected=!0,errors[index]=error,--remaining||reject(new(getBuiltIn("AggregateError"))(errors,PROMISE_ANY_ERROR)))}))})),--remaining||reject(new(getBuiltIn("AggregateError"))(errors,PROMISE_ANY_ERROR))}));return result.error&&reject(result.value),capability.promise}});var NON_GENERIC=!!nativePromiseConstructor&&fails((function(){nativePromiseConstructor.prototype.finally.call({then:function(){}},(function(){}))}));if(_export({target:"Promise",proto:!0,real:!0,forced:NON_GENERIC},{finally:function(onFinally){var C=speciesConstructor(this,getBuiltIn("Promise")),isFunction="function"==typeof onFinally;return this.then(isFunction?function(x){return promiseResolve(C,onFinally()).then((function(){return x}))}:onFinally,isFunction?function(e){return promiseResolve(C,onFinally()).then((function(){throw e}))}:onFinally)}}),"function"==typeof nativePromiseConstructor){var method=getBuiltIn("Promise").prototype.finally;nativePromiseConstructor.prototype.finally!==method&&redefine(nativePromiseConstructor.prototype,"finally",method,{unsafe:!0})}var domIterables={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},ARRAY_ITERATOR="Array Iterator",setInternalState=internalState.set,getInternalState=internalState.getterFor(ARRAY_ITERATOR),es_array_iterator=defineIterator(Array,"Array",(function(iterated,kind){setInternalState(this,{type:ARRAY_ITERATOR,target:toIndexedObject(iterated),index:0,kind:kind})}),(function(){var state=getInternalState(this),target=state.target,kind=state.kind,index=state.index++;return!target||index>=target.length?(state.target=void 0,{value:void 0,done:!0}):"keys"==kind?{value:index,done:!1}:"values"==kind?{value:target[index],done:!1}:{value:[index,target[index]],done:!1}}),"values");iterators.Arguments=iterators.Array,addToUnscopables("keys"),addToUnscopables("values"),addToUnscopables("entries");var ITERATOR=wellKnownSymbol("iterator"),TO_STRING_TAG=wellKnownSymbol("toStringTag"),ArrayValues=es_array_iterator.values;for(var COLLECTION_NAME in domIterables){var Collection=global_1[COLLECTION_NAME],CollectionPrototype=Collection&&Collection.prototype;if(CollectionPrototype){if(CollectionPrototype[ITERATOR]!==ArrayValues)try{createNonEnumerableProperty(CollectionPrototype,ITERATOR,ArrayValues)}catch(error){CollectionPrototype[ITERATOR]=ArrayValues}if(CollectionPrototype[TO_STRING_TAG]||createNonEnumerableProperty(CollectionPrototype,TO_STRING_TAG,COLLECTION_NAME),domIterables[COLLECTION_NAME])for(var METHOD_NAME in es_array_iterator)if(CollectionPrototype[METHOD_NAME]!==es_array_iterator[METHOD_NAME])try{createNonEnumerableProperty(CollectionPrototype,METHOD_NAME,es_array_iterator[METHOD_NAME])}catch(error){CollectionPrototype[METHOD_NAME]=es_array_iterator[METHOD_NAME]}}}path.Promise,_export({target:"Promise",stat:!0},{try:function(callbackfn){var promiseCapability=newPromiseCapability$1.f(this),result=perform(callbackfn);return(result.error?promiseCapability.reject:promiseCapability.resolve)(result.value),promiseCapability.promise}});var MATCH$1=wellKnownSymbol("match"),isRegexp=function(it){var isRegExp;return isObject(it)&&(void 0!==(isRegExp=it[MATCH$1])?!!isRegExp:"RegExp"==classofRaw(it))},notARegexp=function(it){if(isRegexp(it))throw TypeError("The method doesn't accept regular expressions");return it},MATCH=wellKnownSymbol("match"),correctIsRegexpLogic=function(METHOD_NAME){var regexp=/./;try{"/./"[METHOD_NAME](regexp)}catch(error1){try{return regexp[MATCH]=!1,"/./"[METHOD_NAME](regexp)}catch(error2){}}return!1},getOwnPropertyDescriptor=objectGetOwnPropertyDescriptor.f,$startsWith="".startsWith,min=Math.min,CORRECT_IS_REGEXP_LOGIC=correctIsRegexpLogic("startsWith"),MDN_POLYFILL_BUG=!(CORRECT_IS_REGEXP_LOGIC||(descriptor=getOwnPropertyDescriptor(String.prototype,"startsWith"),!descriptor||descriptor.writable)),descriptor;_export({target:"String",proto:!0,forced:!MDN_POLYFILL_BUG&&!CORRECT_IS_REGEXP_LOGIC},{startsWith:function(searchString){var that=String(requireObjectCoercible(this));notARegexp(searchString);var index=toLength(min(arguments.length>1?arguments[1]:void 0,that.length)),search=String(searchString);return $startsWith?$startsWith.call(that,search,index):that.slice(index,index+search.length)===search}}),entryUnbind("String","startsWith");var global$1="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||void 0!==global$1&&global$1,support={searchParams:"URLSearchParams"in global$1,iterable:"Symbol"in global$1&&"iterator"in Symbol,blob:"FileReader"in global$1&&"Blob"in global$1&&function(){try{return new Blob,!0}catch(e){return!1}}(),formData:"FormData"in global$1,arrayBuffer:"ArrayBuffer"in global$1};function isDataView(obj){return obj&&DataView.prototype.isPrototypeOf(obj)}if(support.arrayBuffer)var viewClasses=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],isArrayBufferView=ArrayBuffer.isView||function(obj){return obj&&viewClasses.indexOf(Object.prototype.toString.call(obj))>-1};function normalizeName(name){if("string"!=typeof name&&(name=String(name)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name)||""===name)throw new TypeError('Invalid character in header field name: "'+name+'"');return name.toLowerCase()}function normalizeValue(value){return"string"!=typeof value&&(value=String(value)),value}function iteratorFor(items){var iterator={next:function(){var value=items.shift();return{done:void 0===value,value:value}}};return support.iterable&&(iterator[Symbol.iterator]=function(){return iterator}),iterator}function Headers(headers){this.map={},headers instanceof Headers?headers.forEach((function(value,name){this.append(name,value)}),this):Array.isArray(headers)?headers.forEach((function(header){this.append(header[0],header[1])}),this):headers&&Object.getOwnPropertyNames(headers).forEach((function(name){this.append(name,headers[name])}),this)}function consumed(body){if(body.bodyUsed)return Promise.reject(new TypeError("Already read"));body.bodyUsed=!0}function fileReaderReady(reader){return new Promise((function(resolve,reject){reader.onload=function(){resolve(reader.result)},reader.onerror=function(){reject(reader.error)}}))}function readBlobAsArrayBuffer(blob){var reader=new FileReader,promise=fileReaderReady(reader);return reader.readAsArrayBuffer(blob),promise}function readBlobAsText(blob){var reader=new FileReader,promise=fileReaderReady(reader);return reader.readAsText(blob),promise}function readArrayBufferAsText(buf){for(var view=new Uint8Array(buf),chars=new Array(view.length),i=0;i-1?upcased:method}function Request(input,options){if(!(this instanceof Request))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');var body=(options=options||{}).body;if(input instanceof Request){if(input.bodyUsed)throw new TypeError("Already read");this.url=input.url,this.credentials=input.credentials,options.headers||(this.headers=new Headers(input.headers)),this.method=input.method,this.mode=input.mode,this.signal=input.signal,body||null==input._bodyInit||(body=input._bodyInit,input.bodyUsed=!0)}else this.url=String(input);if(this.credentials=options.credentials||this.credentials||"same-origin",!options.headers&&this.headers||(this.headers=new Headers(options.headers)),this.method=normalizeMethod(options.method||this.method||"GET"),this.mode=options.mode||this.mode||null,this.signal=options.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&body)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(body),!("GET"!==this.method&&"HEAD"!==this.method||"no-store"!==options.cache&&"no-cache"!==options.cache)){var reParamSearch=/([?&])_=[^&]*/;if(reParamSearch.test(this.url))this.url=this.url.replace(reParamSearch,"$1_="+(new Date).getTime());else{this.url+=(/\?/.test(this.url)?"&":"?")+"_="+(new Date).getTime()}}}function decode(body){var form=new FormData;return body.trim().split("&").forEach((function(bytes){if(bytes){var split=bytes.split("="),name=split.shift().replace(/\+/g," "),value=split.join("=").replace(/\+/g," ");form.append(decodeURIComponent(name),decodeURIComponent(value))}})),form}function parseHeaders(rawHeaders){var headers=new Headers;return rawHeaders.replace(/\r?\n[\t ]+/g," ").split("\r").map((function(header){return 0===header.indexOf("\n")?header.substr(1,header.length):header})).forEach((function(line){var parts=line.split(":"),key=parts.shift().trim();if(key){var value=parts.join(":").trim();headers.append(key,value)}})),headers}function Response(bodyInit,options){if(!(this instanceof Response))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');options||(options={}),this.type="default",this.status=void 0===options.status?200:options.status,this.ok=this.status>=200&&this.status<300,this.statusText=void 0===options.statusText?"":""+options.statusText,this.headers=new Headers(options.headers),this.url=options.url||"",this._initBody(bodyInit)}Request.prototype.clone=function(){return new Request(this,{body:this._bodyInit})},Body.call(Request.prototype),Body.call(Response.prototype),Response.prototype.clone=function(){return new Response(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new Headers(this.headers),url:this.url})},Response.error=function(){var response=new Response(null,{status:0,statusText:""});return response.type="error",response};var redirectStatuses=[301,302,303,307,308];Response.redirect=function(url,status){if(-1===redirectStatuses.indexOf(status))throw new RangeError("Invalid status code");return new Response(null,{status:status,headers:{location:url}})};var DOMException=global$1.DOMException;try{new DOMException}catch(err){DOMException=function(message,name){this.message=message,this.name=name;var error=Error(message);this.stack=error.stack},DOMException.prototype=Object.create(Error.prototype),DOMException.prototype.constructor=DOMException}function fetch$1(input,init){return new Promise((function(resolve,reject){var request=new Request(input,init);if(request.signal&&request.signal.aborted)return reject(new DOMException("Aborted","AbortError"));var xhr=new XMLHttpRequest;function abortXhr(){xhr.abort()}xhr.onload=function(){var options={status:xhr.status,statusText:xhr.statusText,headers:parseHeaders(xhr.getAllResponseHeaders()||"")};options.url="responseURL"in xhr?xhr.responseURL:options.headers.get("X-Request-URL");var body="response"in xhr?xhr.response:xhr.responseText;setTimeout((function(){resolve(new Response(body,options))}),0)},xhr.onerror=function(){setTimeout((function(){reject(new TypeError("Network request failed"))}),0)},xhr.ontimeout=function(){setTimeout((function(){reject(new TypeError("Network request failed"))}),0)},xhr.onabort=function(){setTimeout((function(){reject(new DOMException("Aborted","AbortError"))}),0)},xhr.open(request.method,function(url){try{return""===url&&global$1.location.href?global$1.location.href:url}catch(e){return url}}(request.url),!0),"include"===request.credentials?xhr.withCredentials=!0:"omit"===request.credentials&&(xhr.withCredentials=!1),"responseType"in xhr&&(support.blob?xhr.responseType="blob":support.arrayBuffer&&request.headers.get("Content-Type")&&-1!==request.headers.get("Content-Type").indexOf("application/octet-stream")&&(xhr.responseType="arraybuffer")),!init||"object"!=typeof init.headers||init.headers instanceof Headers?request.headers.forEach((function(value,name){xhr.setRequestHeader(name,value)})):Object.getOwnPropertyNames(init.headers).forEach((function(name){xhr.setRequestHeader(name,normalizeValue(init.headers[name]))})),request.signal&&(request.signal.addEventListener("abort",abortXhr),xhr.onreadystatechange=function(){4===xhr.readyState&&request.signal.removeEventListener("abort",abortXhr)}),xhr.send(void 0===request._bodyInit?null:request._bodyInit)}))}fetch$1.polyfill=!0,global$1.fetch||(global$1.fetch=fetch$1,global$1.Headers=Headers,global$1.Request=Request,global$1.Response=Response),null==Element.prototype.getAttributeNames&&(Element.prototype.getAttributeNames=function(){for(var attributes=this.attributes,length=attributes.length,result=new Array(length),i=0;i=0&&matches.item(i)!==this;);return i>-1}),Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(s){var el=this;do{if(el.matches(s))return el;el=el.parentElement||el.parentNode}while(null!==el&&1===el.nodeType);return null});var Connection=function(){function Connection(){_classCallCheck(this,Connection)}return _createClass(Connection,[{key:"onMessage",value:function(message,payload){message.component.receiveMessage(message,payload)}},{key:"onError",value:function(message,status){return message.component.messageSendFailed(),store$2.onErrorCallback(status)}},{key:"showExpiredMessage",value:function(){confirm("This page has expired due to inactivity.\nWould you like to refresh the page?")&&window.location.reload()}},{key:"sendMessage",value:function(message){var _this=this,payload=message.payload(),csrfToken=getCsrfToken(),socketId=this.getSocketId();if(window.__testing_request_interceptor)return window.__testing_request_interceptor(payload,this);fetch("".concat(window.livewire_app_url,"/livewire/message/").concat(payload.fingerprint.name),{method:"POST",body:JSON.stringify(payload),credentials:"same-origin",headers:_objectSpread2(_objectSpread2({"Content-Type":"application/json",Accept:"text/html, application/xhtml+xml","X-Livewire":!0,Referer:window.location.href},csrfToken&&{"X-CSRF-TOKEN":csrfToken}),socketId&&{"X-Socket-ID":socketId})}).then((function(response){if(response.ok)response.text().then((function(response){_this.isOutputFromDump(response)?(_this.onError(message),_this.showHtmlModal(response)):_this.onMessage(message,JSON.parse(response))}));else{if(!1===_this.onError(message,response.status))return;if(419===response.status){if(store$2.sessionHasExpired)return;store$2.sessionHasExpired=!0,_this.showExpiredMessage()}else response.text().then((function(response){_this.showHtmlModal(response)}))}})).catch((function(){_this.onError(message)}))}},{key:"isOutputFromDump",value:function(output){return!!output.match(/ diff --git a/resources/views/depreciations/edit.blade.php b/resources/views/depreciations/edit.blade.php index 3a011cfb16..c523b21010 100755 --- a/resources/views/depreciations/edit.blade.php +++ b/resources/views/depreciations/edit.blade.php @@ -15,12 +15,21 @@ -
-
- +
+ + {!! $errors->first('months', '') !!}
+
+ + +
+ +
+
- {!! $errors->first('months', '') !!} + {!! $errors->first('depreciation_min', '') !!}
diff --git a/resources/views/hardware/view.blade.php b/resources/views/hardware/view.blade.php index c5feb06c57..cd8b743f2e 100755 --- a/resources/views/hardware/view.blade.php +++ b/resources/views/hardware/view.blade.php @@ -463,7 +463,28 @@
@endif + @if (($asset->model) && ($asset->depreciation)) +
+
+ + {{ trans('admin/hardware/table.current_value') }} + +
+
+
+ @if (($asset->id) && ($asset->location)) + {{ $asset->location->currency }} + @elseif (($asset->id) && ($asset->location)) + {{ $asset->location->currency }} + @else + {{ $snipeSettings->default_currency }} + @endif + {{ \App\Helpers\Helper::formatCurrencyOutput($asset->getDepreciatedValue() )}} +
+
+
+ @endif @if ($asset->order_number)
diff --git a/resources/views/layouts/basic.blade.php b/resources/views/layouts/basic.blade.php index 2c781264b3..7efedf73b2 100644 --- a/resources/views/layouts/basic.blade.php +++ b/resources/views/layouts/basic.blade.php @@ -20,6 +20,7 @@ } }; + @livewireStyles @if (($snipeSettings) && ($snipeSettings->header_color)) @@ -74,6 +75,7 @@ @stack('js') + @livewireScripts diff --git a/resources/views/layouts/default.blade.php b/resources/views/layouts/default.blade.php index 57b9b16859..4fc9cae265 100644 --- a/resources/views/layouts/default.blade.php +++ b/resources/views/layouts/default.blade.php @@ -80,6 +80,7 @@ + @livewireStyles @@ -926,6 +927,6 @@ @endif - + @livewireScripts diff --git a/resources/views/livewire/custom-field-set-default-values-for-model.blade.php b/resources/views/livewire/custom-field-set-default-values-for-model.blade.php new file mode 100644 index 0000000000..b1c56047b9 --- /dev/null +++ b/resources/views/livewire/custom-field-set-default-values-for-model.blade.php @@ -0,0 +1,22 @@ +
+
+ +
+ {{ Form::select('custom_fieldset', \App\Helpers\Helper::customFieldsetList(),old('custom_fieldset', 0000 /*$item->fieldset_id*/), array('class'=>'select2 js-fieldset-field', 'style'=>'width:350px', 'aria-label'=>'custom_fieldset', 'wire:model' => 'fieldset_id')) }} + {!! $errors->first('custom_fieldset', '') !!} + +
+
+ @if($this->add_default_values) {{-- 'if the checkbox is enabled *AND* there are more than 0 fields in the fieldsset' --}} +
+
+ @livewire('custom-fields-for-fieldset',['fieldset_id' => $fieldset_id]) +
+
+ @endif +
diff --git a/resources/views/livewire/custom-fields-for-fieldset.blade.php b/resources/views/livewire/custom-fields-for-fieldset.blade.php new file mode 100644 index 0000000000..773aa82767 --- /dev/null +++ b/resources/views/livewire/custom-fields-for-fieldset.blade.php @@ -0,0 +1,43 @@ + + + @empty($fields) {{-- There was an error? --}} + +
+
+ There was a problem retrieving the fields for this fieldset. +
+
+ + @else + {{-- NOTE: This stuff could work well also for the 'view this asset and do its custom fields' thing --}} + {{-- I don't know if we break *here* or if we break per field element? --}} + @foreach ($fields as $field) +
+ + + +
+ + @if ($field->element == "text") + + @elseif($field->element == "textarea") +
+ @elseif($field->element == "listbox") + + + @else + + Unknown field element: {{ $field->element }} + + @endif +
+
+ + @endforeach + @endif + diff --git a/resources/views/livewire/login-form.blade.php b/resources/views/livewire/login-form.blade.php new file mode 100644 index 0000000000..5d5b3cd907 --- /dev/null +++ b/resources/views/livewire/login-form.blade.php @@ -0,0 +1,105 @@ +
+
+ + + + + + +
+
+ +
+ + + +
+ +
+
+
+ +
\ No newline at end of file diff --git a/resources/views/models/edit.blade.php b/resources/views/models/edit.blade.php index 37dd138987..c3df06f09e 100755 --- a/resources/views/models/edit.blade.php +++ b/resources/views/models/edit.blade.php @@ -34,24 +34,28 @@
-
-
+
+ {{--
{{ Form::select('custom_fieldset', \App\Helpers\Helper::customFieldsetList(),old('custom_fieldset', $item->fieldset_id), array('class'=>'select2 js-fieldset-field', 'style'=>'width:350px', 'aria-label'=>'custom_fieldset')) }} {!! $errors->first('custom_fieldset', '') !!}
-
+
--}} - - + --}} + @livewire('custom-field-set-default-values-for-model',["model_id" => $item->id]) +
@include ('partials.forms.edit.notes') @@ -78,10 +82,10 @@ @stop -@section('moar_scripts') +{{-- @section('moar_scripts') -@endsection +@endsection --}} diff --git a/resources/views/users/edit.blade.php b/resources/views/users/edit.blade.php index e9a50c795b..a86741971a 100755 --- a/resources/views/users/edit.blade.php +++ b/resources/views/users/edit.blade.php @@ -77,7 +77,7 @@ -
+
@if (!Auth::user()->isSuperUser())

Only superadmins may grant a user superadmin access.

diff --git a/routes/api.php b/routes/api.php index 398af78bce..2d3731b7ca 100644 --- a/routes/api.php +++ b/routes/api.php @@ -1,6 +1,9 @@ 'v1', 'middleware' => 'api'], function () { -Route::group(['prefix' => 'v1','namespace' => 'Api', 'middleware' => 'auth:api'], function () { - - - Route::get('/', function() { - + Route::get('/', function () { return response()->json( [ 'status' => 'error', @@ -28,1036 +28,1063 @@ Route::group(['prefix' => 'v1','namespace' => 'Api', 'middleware' => 'auth:api'] }); - - + /** + * Account routes + */ Route::group(['prefix' => 'account'], function () { - Route::get('requestable/hardware', - [ - 'as' => 'api.assets.requestable', - 'uses' => 'AssetsController@requestable' - ] - ); - Route::get('requests', [ - 'as' => 'api.assets.requested', - 'uses' => 'ProfileController@requestedAssets' + Api\ProfileController::class, + 'requestedAssets' ] - ); + )->name('api.assets.requested'); - }); + Route::get('requestable/hardware', + [ + Api\AssetsController::class, + 'requestable' + ] + )->name('api.assets.requestable'); - /*--- Accessories API ---*/ + + + }); // end account group + + + /** + * Accessories routes + */ Route::group(['prefix' => 'accessories'], function () { Route::get('{accessory}/checkedout', [ - 'as' => 'api.accessories.checkedout', - 'uses' => 'AccessoriesController@checkedout' + Api\AccessoriesController::class, + 'checkedout' ] - ); + )->name('api.accessories.checkedout'); + + Route::get('{accessory}/checkout', + [ + Api\AccessoriesController::class, + 'checkout' + ] + )->name('api.accessories.checkout'); + + + Route::get('{accessory}/checkin', + [ + Api\AccessoriesController::class, + 'checkin' + ] + )->name('api.accessories.checkin'); Route::get('selectlist', [ - 'as' => 'api.accessories.selectlist', - 'uses'=> 'AccessoriesController@selectlist' + Api\AccessoriesController::class, + 'selectlist' ] - ); - }); + )->name('api.accessories.selectlist'); - // Accessories group - Route::resource('accessories', 'AccessoriesController', - ['names' => - [ - 'index' => 'api.accessories.index', - 'show' => 'api.accessories.show', - 'update' => 'api.accessories.update', - 'store' => 'api.accessories.store', - 'destroy' => 'api.accessories.destroy' - ], + Route::resource('accessories', + Api\AccessoriesController::class, + ['names' => + [ + 'index' => 'api.accessories.index', + 'show' => 'api.accessories.show', + 'update' => 'api.accessories.update', + 'store' => 'api.accessories.store', + 'destroy' => 'api.accessories.destroy', + ], 'except' => ['create', 'edit'], - 'parameters' => ['accessory' => 'accessory_id'] - ] - ); - - // Accessories resource - - Route::group(['prefix' => 'accessories'], function () { - - Route::get('{accessory}/checkedout', - [ - 'as' => 'api.accessories.checkedout', - 'uses' => 'AccessoriesController@checkedout' + 'parameters' => ['accessory' => 'accessory_id'], ] ); - Route::post('{accessory}/checkout', - [ - 'as' => 'api.accessories.checkout', - 'uses' => 'AccessoriesController@checkout' - ] - ); - - Route::post('{accessory}/checkin', - [ - 'as' => 'api.accessories.checkin', - 'uses' => 'AccessoriesController@checkin' - ] - ); - - }); // Accessories group - - - /*--- Categories API ---*/ - - Route::group(['prefix' => 'categories'], function () { + }); // end accessories group + + /** + * Categpries API routes + */ + Route::group(['prefix' => 'categories'], function () { + Route::get('{item_type}/selectlist', [ - 'as' => 'api.categories.selectlist', - 'uses' => 'CategoriesController@selectlist' + Api\CategoriesController::class, + 'selectlist' ] - ); + )->name('api.categories.selectlist'); - }); + }); - // Categories group - Route::resource('categories', 'CategoriesController', - [ - 'names' => - [ - 'index' => 'api.categories.index', - 'show' => 'api.categories.show', - 'store' => 'api.categories.store', - 'update' => 'api.categories.update', - 'destroy' => 'api.categories.destroy' - ], - 'except' => ['edit', 'create'], - 'parameters' => ['category' => 'category_id'] + Route::resource('categories', + Api\CategoriesController::class, + ['names' => + [ + 'index' => 'api.categories.index', + 'show' => 'api.categories.show', + 'update' => 'api.categories.update', + 'store' => 'api.categories.store', + 'destroy' => 'api.categories.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['category' => 'category_id'], ] - ); // Categories resource - - - /*--- Companies API ---*/ - - Route::get( 'companies/selectlist', [ - 'as' => 'companies.selectlist', - 'uses' => 'CompaniesController@selectlist' - ]); - - - // Companies resource - Route::resource('companies', 'CompaniesController', - [ - 'names' => - [ - 'index' => 'api.companies.index', - 'show' => 'api.companies.show', - 'store' => 'api.companies.store', - 'update' => 'api.companies.update', - 'destroy' => 'api.companies.destroy' - ], - 'except' => ['create', 'edit'], - 'parameters' => ['company' => 'company_id'] - ] - ); // Companies resource - - - /*--- Departments API ---*/ - - Route::group(['prefix' => 'departments'], function () { - + ); // end category API routes + /** + * Companies API routes + */ + Route::group(['prefix' => 'companies'], function () { + Route::get('selectlist', [ - 'as' => 'api.departments.selectlist', - 'uses' => 'DepartmentsController@selectlist' + Api\CompaniesController::class, + 'selectlist' ] - ); - }); // Departments group + )->name('api.companies.selectlist'); + }); - - Route::resource('departments', 'DepartmentsController', - [ - 'names' => - [ - 'index' => 'api.departments.index', - 'show' => 'api.departments.show', - 'store' => 'api.departments.store', - 'update' => 'api.departments.update', - 'destroy' => 'api.departments.destroy' - ], - 'except' => ['create', 'edit'], - 'parameters' => ['department' => 'department_id'] + Route::resource('companies', + Api\CompaniesController::class, + ['names' => + [ + 'index' => 'api.companies.index', + 'show' => 'api.companies.show', + 'update' => 'api.companies.update', + 'store' => 'api.companies.store', + 'destroy' => 'api.companies.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['company' => 'company_id'], ] - ); // Departments resource + ); // end companies API routes - /*--- Components API ---*/ + /** + * Departments API routes + */ + Route::group(['prefix' => 'departments'], function () { + + Route::get('selectlist', + [ + Api\DepartmentsController::class, + 'selectlist' + ] + )->name('api.departments.selectlist'); - Route::group(['prefix' => 'components'], function () { + }); + + Route::resource('departments', + Api\DepartmentsController::class, + ['names' => + [ + 'index' => 'api.departments.index', + 'show' => 'api.departments.show', + 'update' => 'api.departments.update', + 'store' => 'api.departments.store', + 'destroy' => 'api.departments.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['department' => 'department_id'], + ] + ); // end departments API routes + + + /** + * Components API routes + */ + Route::group(['prefix' => 'components'], function () { + + Route::get('selectlist', + [ + Api\ComponentsController::class, + 'selectlist' + ] + )->name('api.components.selectlist'); Route::get('{component}/assets', + [ + Api\ComponentsController::class, + 'getAssets' + ] + )->name('api.components.assets'); + + }); + + + Route::resource('components', + Api\ComponentsController::class, + ['names' => [ - 'as' =>'api.components.assets', - 'uses' => 'ComponentsController@getAssets', - ] - ); + 'index' => 'api.components.index', + 'show' => 'api.components.show', + 'update' => 'api.components.update', + 'store' => 'api.components.store', + 'destroy' => 'api.components.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['component' => 'component_id'], + ] + ); // end components API routes - Route::post('{component}/checkout', + + /** + * Consumables API routes + */ + Route::group(['prefix' => 'consumables'], function () { + + Route::get('selectlist', [ - 'as' =>'api.components.checkout', - 'uses' => 'ComponentsController@checkout', + Api\ConsumablesController::class, + 'selectlist' ] - ); + )->name('api.consumables.selectlist'); - Route::post('{component}/checkin', - [ - 'as' =>'api.components.checkin', - 'uses' => 'ComponentsController@checkin', - ] - ); - - }); // Components group - - - Route::resource('components', 'ComponentsController', - [ - 'names' => - [ - 'index' => 'api.components.index', - 'show' => 'api.components.show', - 'store' => 'api.components.store', - 'update' => 'api.components.update', - 'destroy' => 'api.components.destroy' - ], - 'except' => ['create', 'edit'], - 'parameters' => ['component' => 'component_id'] - ] - ); // Components resource - - - - - /*--- Consumables API ---*/ - Route::get('consumables/selectlist', - [ - 'as' => 'api.consumables.selectlist', - 'uses'=> 'ConsumablesController@selectlist' - ] - ); - - Route::resource('consumables', 'ConsumablesController', - [ - 'names' => - [ - 'index' => 'api.consumables.index', - 'show' => 'api.consumables.show', - 'store' => 'api.consumables.store', - 'update' => 'api.consumables.update', - 'destroy' => 'api.consumables.destroy' - ], - 'except' => ['create', 'edit'], - 'parameters' => ['consumable' => 'consumable_id'] - ] - ); // Consumables resource - - Route::group(['prefix' => 'consumables'], function () { Route::get('view/{id}/users', [ - 'as' => 'api.consumables.showUsers', - 'uses' => 'ConsumablesController@getDataView' + Api\ConsumablesController::class, + 'getDataView' ] - ); + )->name('api.consumables.showUsers'); - Route::post('{consumable}/checkout', + Route::get('{consumable}/checkout', [ - 'as' => 'api.consumables.checkout', - 'uses' => 'ConsumablesController@checkout' + Api\ConsumablesController::class, + 'checkout' ] - ); - }); + )->name('api.consumables.checkout'); - /*--- Depreciations API ---*/ + }); - Route::resource('depreciations', 'DepreciationsController', - [ - 'names' => + + Route::resource('consumables', + Api\ConsumablesController::class, + ['names' => + [ + 'index' => 'api.consumables.index', + 'show' => 'api.consumables.show', + 'update' => 'api.consumables.update', + 'store' => 'api.consumables.store', + 'destroy' => 'api.consumables.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['consumable' => 'consumable_id'], + ] + ); // end consumables API routes + + + + /** + * Depreciations API routes + */ + Route::resource('depreciations', + Api\DepreciationsController::class, + ['names' => + [ + 'index' => 'api.depreciations.index', + 'show' => 'api.depreciations.show', + 'update' => 'api.depreciations.update', + 'store' => 'api.depreciations.store', + 'destroy' => 'api.depreciations.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['depreciations' => 'depreciation_id'], + ] + ); // end depreciations API routes + + + /** + * Fields API routes + */ + Route::group(['prefix' => 'fields'], function () { + + Route::post('fieldsets/{id}/order', [ - 'index' => 'api.depreciations.index', - 'show' => 'api.depreciations.show', - 'store' => 'api.depreciations.store', - 'update' => 'api.depreciations.update', - 'destroy' => 'api.depreciations.destroy' + Api\CustomFieldsController::class, + 'postReorder' + ] + )->name('api.customfields.order'); + + Route::post('{field}/associate', + [ + Api\CustomFieldsController::class, + 'associate' + ] + )->name('api.customfields.associate'); + + Route::post('{field}/disassociate', + [ + Api\CustomFieldsController::class, + 'disassociate' + ] + )->name('api.customfields.disassociate'); + }); + + Route::resource('fields', + Api\CustomFieldsController::class, + ['names' => + [ + 'index' => 'api.customfields.index', + 'show' => 'api.customfields.show', + 'update' => 'api.customfields.update', + 'store' => 'api.customfields.store', + 'destroy' => 'api.customfields.destroy', ], 'except' => ['create', 'edit'], - 'parameters' => ['depreciation' => 'depreciation_id'] - ] - ); // Depreciations resource - - - /*--- Fields API ---*/ - - Route::resource('fields', 'CustomFieldsController', [ - 'names' => [ - 'index' => 'api.customfields.index', - 'show' => 'api.customfields.show', - 'store' => 'api.customfields.store', - 'update' => 'api.customfields.update', - 'destroy' => 'api.customfields.destroy' - ], - 'except' => [ 'create', 'edit' ], - 'parameters' => [ 'field' => 'field_id' ] - ]); - - Route::group(['prefix' => 'fields'], function () { - Route::post('fieldsets/{id}/order', - [ - 'as' => 'api.customfields.order', - 'uses' => 'CustomFieldsController@postReorder' + 'parameters' => ['field' => 'field_id'], ] - ); - Route::post('{field}/associate', - [ - 'as' => 'api.customfields.associate', - 'uses' => 'CustomFieldsController@associate' - ] - ); - Route::post('{field}/disassociate', - [ - 'as' => 'api.customfields.disassociate', - 'uses' => 'CustomFieldsController@disassociate' - ] - ); - }); // Fields group + ); // end custom fields API routes - - /*--- Fieldsets API ---*/ - - Route::group(['prefix' => 'fieldsets'], function () { - Route::get('{fieldset}/fields', - [ - 'as' => 'api.fieldsets.fields', - 'uses' => 'CustomFieldsetsController@fields' - ] - ); - Route::get('/{fieldset}/fields/{model}', - [ - 'as' => 'api.fieldsets.fields-with-default-value', - 'uses' => 'CustomFieldsetsController@fieldsWithDefaultValues' - ] - ); - }); - - Route::resource('fieldsets', 'CustomFieldsetsController', - [ - 'names' => + /** + * Fieldsets API routes + */ + Route::group(['prefix' => 'fieldsets'], function () { + + Route::post('{fieldset}/fields', [ - 'index' => 'api.fieldsets.index', - 'show' => 'api.fieldsets.show', - 'store' => 'api.fieldsets.store', - 'update' => 'api.fieldsets.update', - 'destroy' => 'api.fieldsets.destroy' + Api\CustomFieldsetsController::class, + 'fields' + ] + )->name('api.fieldsets.fields'); + + Route::post('{fieldset}/fields/{model}', + [ + Api\CustomFieldsetsController::class, + 'fieldsWithDefaultValues' + ] + )->name('api.fieldsets.fields-with-default-value'); + + }); + + Route::resource('fields', + Api\CustomFieldsetsController::class, + ['names' => + [ + 'index' => 'api.customfields.index', + 'show' => 'api.customfields.show', + 'update' => 'api.customfields.update', + 'store' => 'api.customfields.store', + 'destroy' => 'api.customfields.destroy', ], 'except' => ['create', 'edit'], - 'parameters' => ['fieldset' => 'fieldset_id'] - ] - ); // Custom fieldset resource + 'parameters' => ['field' => 'field_id'], + ] + ); // end custom fieldsets API routes - /*--- Groups API ---*/ - Route::resource('groups', 'GroupsController', - [ - 'names' => + /** + * Groups API routes + */ + Route::resource('groups', + Api\CustomFieldsetsController::class, + ['names' => [ 'index' => 'api.groups.index', 'show' => 'api.groups.show', - 'store' => 'api.groups.store', 'update' => 'api.groups.update', - 'destroy' => 'api.groups.destroy' + 'store' => 'api.groups.store', + 'destroy' => 'api.groups.destroy', ], 'except' => ['create', 'edit'], - 'parameters' => ['group' => 'group_id'] - ] - ); // Groups resource - - - /*--- Hardware API ---*/ - - Route::group(['prefix' => 'hardware'], function () { - - Route::get('{asset_id}/licenses', [ - 'as' => 'api.assets.licenselist', - 'uses' => 'AssetsController@licenses' - ]); + 'parameters' => ['group' => 'group_id'], + ] + ); // end groups API routes - Route::get( 'bytag/{tag}', [ - 'as' => 'assets.show.bytag', - 'uses' => 'AssetsController@showByTag' - ]); + + /** + * Assets API routes + */ + Route::group(['prefix' => 'hardware'], function () { + + Route::get('selectlist', + [ + Api\AssetsController::class, + 'selectlist' + ] + )->name('assets.selectlist'); + + Route::get('{asset_id}/licenses', + [ + Api\AssetsController::class, + 'licenses' + ] + )->name('api.assets.licenselist'); + + Route::get('bytag/{tag}', + [ + Api\AssetsController::class, + 'showByTag' + ] + )->name('assets.show.bytag'); Route::get('bytag/{any}', [ - 'as' => 'api.assets.show.bytag', - 'uses' => 'AssetsController@showByTag' + Api\AssetsController::class, + 'showByTag' ] - )->where('any', '.*'); - + )->name('api.assets.show.bytag') + ->where('any', '.*'); Route::get('byserial/{any}', [ - 'as' => 'api.assets.show.byserial', - 'uses' => 'AssetsController@showBySerial' + Api\AssetsController::class, + 'showBySerial' ] - )->where('any', '.*'); + )->name('api.assets.show.byserial') + ->where('any', '.*'); + + Route::get('audit/{audit}', + [ + Api\AssetsController::class, + 'index' + ] + )->name('api.asset.to-audit'); + + Route::post('audit', + [ + Api\AssetsController::class, + 'audit' + ] + )->name('api.asset.audit'); + + Route::post('checkin', + [ + Api\AssetsController::class, + 'checkin' + ] + )->name('api.asset.checkin'); + + Route::post('checkout', + [ + Api\AssetsController::class, + 'checkout' + ] + )->name('api.asset.checkout'); + }); + + + Route::resource('hardware', + Api\AssetsController::class, + ['names' => + [ + 'index' => 'api.assets.index', + 'show' => 'api.assets.show', + 'update' => 'api.assets.update', + 'store' => 'api.assets.store', + 'destroy' => 'api.assets.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['asset' => 'asset_id'], + ] + ); // end assets API routes + + /** + * Asset maintenances API routes + */ + Route::resource('maintenances', + Api\AssetMaintenancesController::class, + ['names' => + [ + 'index' => 'api.maintenances.index', + 'show' => 'api.maintenances.show', + 'update' => 'api.maintenances.update', + 'store' => 'api.maintenances.store', + 'destroy' => 'api.maintenances.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['maintenance' => 'maintenance_id'], + ] + ); // end assets API routes + + + /** + * Imports API routes + */ + Route::group(['prefix' => 'imports'], function () { - - Route::get( 'selectlist', [ - 'as' => 'assets.selectlist', - 'uses' => 'AssetsController@selectlist' - ]); - - Route::get('audit/{audit}', [ - 'as' => 'api.asset.to-audit', - 'uses' => 'AssetsController@index' - ]); - - - Route::post('audit', [ - 'as' => 'api.asset.audit', - 'uses' => 'AssetsController@audit' - ]); - - Route::post('{asset_id}/checkout', - [ - 'as' => 'api.assets.checkout', - 'uses' => 'AssetsController@checkout' - ] - ); - - Route::post('{asset_id}/checkin', - [ - 'as' => 'api.assets.checkin', - 'uses' => 'AssetsController@checkin' - ] - ); - - Route::post('{asset_id}/restore', - [ - 'as' => 'api.assets.restore', - 'uses' => 'AssetsController@restore' - ] - ); - - Route::post('{asset_id}/destroy', - [ - 'as' => 'api.assets.destroy', - 'uses' => 'AssetsController@destroy' - ] - ); - - }); - - /*--- Asset Maintenances API ---*/ - Route::resource('maintenances', 'AssetMaintenancesController', - [ - 'names' => - [ - 'index' => 'api.maintenances.index', - 'show' => 'api.maintenances.show', - 'store' => 'api.maintenances.store', - 'update' => 'api.maintenances.update', - 'destroy' => 'api.maintenances.destroy' - ], - 'except' => ['create', 'edit'], - 'parameters' => ['maintenance' => 'maintenance_id'] - ] - ); // Consumables resource - - - Route::resource('hardware', 'AssetsController', - [ - 'names' => - [ - 'index' => 'api.assets.index', - 'show' => 'api.assets.show', - 'store' => 'api.assets.store', - 'update' => 'api.assets.update', - 'destroy' => 'api.assets.destroy' - ], - 'except' => ['create', 'edit'], - 'parameters' => ['asset' => 'asset_id'] - ] - ); // Hardware resource - - - /*--- Imports API ---*/ - - Route::resource('imports', 'ImportController', - [ - 'names' => - [ - 'index' => 'api.imports.index', - 'show' => 'api.imports.show', - 'store' => 'api.imports.store', - 'update' => 'api.imports.update', - 'destroy' => 'api.imports.destroy' - ], - 'except' => ['create', 'edit'], - 'parameters' => ['import' => 'import_id'] - ] - ); // Imports resource - - Route::group(['prefix' => 'imports'], function () { - Route::post('process/{import}', [ - 'as' => 'api.imports.importFile', - 'uses'=> 'ImportController@process' + Api\ImportController::class, + 'process' ] - ); - }); // Imports group + )->name('api.imports.importFile'); + }); - - - /*--- Licenses API ---*/ - - Route::group(['prefix' => 'licenses'], function () { - Route::get('selectlist', + Route::resource('imports', + Api\ImportController::class, + ['names' => [ - 'as' => 'api.licenses.selectlist', - 'uses'=> 'LicensesController@selectlist' - ] - ); - - }); // Licenses group - - Route::resource('licenses', 'LicensesController', - [ - 'names' => - [ - 'index' => 'api.licenses.index', - 'show' => 'api.licenses.show', - 'store' => 'api.licenses.store', - 'update' => 'api.licenses.update', - 'destroy' => 'api.licenses.destroy' - ], - 'except' => ['create', 'edit'], - 'parameters' => ['license' => 'license_id'] + 'index' => 'api.imports.index', + 'show' => 'api.imports.show', + 'update' => 'api.imports.update', + 'store' => 'api.imports.store', + 'destroy' => 'api.imports.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['import' => 'import_id'], ] - ); // Licenses resource - - Route::resource('licenses.seats', 'LicenseSeatsController', - [ - 'names' => - [ - 'index' => 'api.licenses.seats.index', - 'show' => 'api.licenses.seats.show', - 'update' => 'api.licenses.seats.update' - ], - 'except' => ['create', 'edit', 'destroy', 'store'], - 'parameters' => ['licenseseat' => 'licenseseat_id'] - ] - ); // Licenseseats resource - - /*--- Locations API ---*/ - - Route::group(['prefix' => 'locations'], function () { - - Route::get('{location}/users', - [ - 'as'=>'api.locations.viewusers', - 'uses'=>'LocationsController@getDataViewUsers' - ] - ); - - Route::get('{location}/assets', - [ - 'as'=>'api.locations.viewassets', - 'uses'=>'LocationsController@getDataViewAssets' - ] - ); - - // Do we actually still need this, now that we have an API? - Route::get('{location}/check', - [ - 'as' => 'api.locations.check', - 'uses' => 'LocationsController@show' - ] - ); - - Route::get( 'selectlist', [ - 'as' => 'locations.selectlist', - 'uses' => 'LocationsController@selectlist' - ]); - }); // Locations group + ); // end imports API routes - Route::resource('locations', 'LocationsController', - [ - 'names' => - [ - 'index' => 'api.locations.index', - 'show' => 'api.locations.show', - 'store' => 'api.locations.store', - 'update' => 'api.locations.update', - 'destroy' => 'api.locations.destroy' - ], - 'except' => ['create', 'edit'], - 'parameters' => ['location' => 'location_id'] - ] - ); // Locations resource - - - - - /*--- Manufacturers API ---*/ - - Route::group(['prefix' => 'manufacturers'], function () { - - Route::get( 'selectlist', [ - 'as' => 'manufacturers.selectlist', - 'uses' => 'ManufacturersController@selectlist' - ]); - }); // Locations group - - - Route::resource('manufacturers', 'ManufacturersController', - [ - 'names' => - [ - 'index' => 'api.manufacturers.index', - 'show' => 'api.manufacturers.show', - 'store' => 'api.manufacturers.store', - 'update' => 'api.manufacturers.update', - 'destroy' => 'api.manufacturers.destroy' - ], - 'except' => ['create', 'edit'], - 'parameters' => ['manufacturer' => 'manufacturer_id'] - ] - ); // Manufacturers resource - - - /*--- Models API ---*/ - - Route::group(['prefix' => 'models'], function () { - - Route::get('assets', - [ - 'as' => 'api.models.assets', - 'uses'=> 'AssetModelsController@assets' - ] - ); - Route::get('selectlist', - [ - 'as' => 'api.models.selectlist', - 'uses'=> 'AssetModelsController@selectlist' - ] - ); - }); // Models group - - - Route::resource('models', 'AssetModelsController', - [ - 'names' => - [ - 'index' => 'api.models.index', - 'show' => 'api.models.show', - 'store' => 'api.models.store', - 'update' => 'api.models.update', - 'destroy' => 'api.models.destroy' - ], - 'except' => ['create', 'edit'], - 'parameters' => ['model' => 'model_id'] - ] - ); // Models resource - - - - - /*--- Settings API ---*/ - Route::get('settings/ldaptest', [ - 'as' => 'api.settings.ldaptest', - 'uses' => 'SettingsController@ldapAdSettingsTest' - ]); - - Route::post('settings/purge_barcodes', [ - 'as' => 'api.settings.purgebarcodes', - 'uses' => 'SettingsController@purgeBarcodes' - ]); - - Route::get('settings/login-attempts', [ - 'middleware' => ['auth', 'authorize:superuser'], - 'as' => 'api.settings.login_attempts', - 'uses' => 'SettingsController@showLoginAttempts' - ]); - - - Route::post('settings/ldaptestlogin', [ - 'as' => 'api.settings.ldaptestlogin', - 'uses' => 'SettingsController@ldaptestlogin' - ]); - - Route::post('settings/slacktest', [ - 'as' => 'api.settings.slacktest', - 'uses' => 'SettingsController@slacktest' - ]); - - Route::post( - 'settings/mailtest', - [ - 'as' => 'api.settings.mailtest', - 'uses' => 'SettingsController@ajaxTestEmail' - ]); - - - Route::resource('settings', 'SettingsController', - [ - 'names' => - [ - 'index' => 'api.settings.index', - 'store' => 'api.settings.store', - 'show' => 'api.settings.show', - 'update' => 'api.settings.update' - ], - 'except' => ['create', 'edit', 'destroy'], - 'parameters' => ['setting' => 'setting_id'] - ] - ); // Settings resource - - - - - /*--- Status Labels API ---*/ - - - Route::group(['prefix' => 'statuslabels'], function () { - - // Pie chart for dashboard - Route::get('assets', - [ - 'as' => 'api.statuslabels.assets.bytype', - 'uses' => 'StatuslabelsController@getAssetCountByStatuslabel' - ] - ); - - Route::get('{statuslabel}/assetlist', - [ - 'as' => 'api.statuslabels.assets', - 'uses' => 'StatuslabelsController@assets' - ] - ); - - Route::get('{statuslabel}/deployable', - [ - 'as' => 'api.statuslabels.deployable', - 'uses' => 'StatuslabelsController@checkIfDeployable' - ] - ); - - - }); - - Route::resource('statuslabels', 'StatuslabelsController', - [ - 'names' => - [ - 'index' => 'api.statuslabels.index', - 'store' => 'api.statuslabels.store', - 'show' => 'api.statuslabels.show', - 'update' => 'api.statuslabels.update', - 'destroy' => 'api.statuslabels.destroy' - ], - 'except' => ['create', 'edit'], - 'parameters' => ['statuslabel' => 'statuslabel_id'] - ] - ); - - // Status labels group - - - /*--- Suppliers API ---*/ - Route::group(['prefix' => 'suppliers'], function () { - - Route::get('list', - [ - 'as'=>'api.suppliers.list', - 'uses'=>'SuppliersController@getDatatable' - ] - ); + /** + * Licenses API routes + */ + Route::group(['prefix' => 'licenses'], function () { Route::get('selectlist', [ - 'as' => 'api.suppliers.selectlist', - 'uses' => 'SuppliersController@selectlist' + Api\LicensesController::class, + 'selectlist' ] - ); - }); // Suppliers group + )->name('api.licenses.selectlist'); + + }); + + Route::resource('licenses', + Api\LicensesController::class, + ['names' => + [ + 'index' => 'api.licenses.index', + 'show' => 'api.licenses.show', + 'update' => 'api.licenses.update', + 'store' => 'api.licenses.store', + 'destroy' => 'api.licenses.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['licenses' => 'license_id'], + ] + ); - Route::resource('suppliers', 'SuppliersController', - [ - 'names' => + Route::resource('licenses.seats', + Api\LicenseSeatsController::class, + ['names' => + [ + 'index' => 'api.licenses.seats.index', + 'show' => 'api.licenses.seats.show', + 'update' => 'api.licenses.seats.update', + ], + 'except' => ['create', 'edit', 'destroy', 'store'], + 'parameters' => ['licenseseat' => 'licenseseat_id'], + ] + ); // end license API routes + + + /** + * Locations API routes + */ + Route::group(['prefix' => 'locations'], function () { + + Route::get('selectlist', [ - 'index' => 'api.suppliers.index', - 'show' => 'api.suppliers.show', - 'store' => 'api.suppliers.store', - 'update' => 'api.suppliers.update', - 'destroy' => 'api.suppliers.destroy' - ], - 'except' => ['create', 'edit'], - 'parameters' => ['supplier' => 'supplier_id'] - ] - ); // Suppliers resource + Api\LocationsController::class, + 'selectlist' + ] + )->name('api.locations.selectlist'); - - - - /*--- Users API ---*/ - - - Route::group([ 'prefix' => 'users' ], function () { - - Route::post('two_factor_reset', - [ - 'as' => 'api.users.two_factor_reset', - 'uses' => 'UsersController@postTwoFactorReset' - ] - ); - - Route::get('me', - [ - 'as' => 'api.users.me', - 'uses' => 'UsersController@getCurrentUserInfo' - ] - ); - - Route::get('list/{status?}', - [ - 'as' => 'api.users.list', - 'uses' => 'UsersController@getDatatable' - ] - ); - - Route::get('selectlist', - [ - 'as' => 'api.users.selectlist', - 'uses' => 'UsersController@selectList' - ] - ); - - Route::get('{user}/assets', - [ - 'as' => 'api.users.assetlist', - 'uses' => 'UsersController@assets' - ] - ); - - - Route::get('{user}/accessories', - [ - 'as' => 'api.users.accessorieslist', - 'uses' => 'UsersController@accessories' - ] - ); - - - Route::get('{user}/licenses', - [ - 'as' => 'api.users.licenselist', - 'uses' => 'UsersController@licenses' - ] - ); - - Route::post('{user}/upload', - [ - 'as' => 'api.users.uploads', - 'uses' => 'UsersController@postUpload' - ] - ); - }); // Users group - - Route::resource('users', 'UsersController', - [ - 'names' => + Route::get('{location}/users', [ - 'index' => 'api.users.index', - 'show' => 'api.users.show', - 'store' => 'api.users.store', - 'update' => 'api.users.update', - 'destroy' => 'api.users.destroy' - ], - 'except' => ['create', 'edit'], - 'parameters' => ['user' => 'user_id'] + Api\LocationsController::class, + 'getDataViewUsers' + ] + )->name('api.locations.viewusers'); + + Route::get('{location}/assets', + [ + Api\LocationsController::class, + 'getDataViewAssets' + ] + )->name('api.locations.viewassets'); + + }); + + Route::resource('locations', + Api\LocationsController::class, + ['names' => + [ + 'index' => 'api.locations.index', + 'show' => 'api.locations.show', + 'update' => 'api.locations.update', + 'store' => 'api.locations.store', + 'destroy' => 'api.locations.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['location' => 'location_id'], ] - ); // Users resource + ); // end locations API routes - Route::get( - 'reports/activity', - [ 'as' => 'api.activity.index', 'uses' => 'ReportsController@index' ] - ); + /** + * Manufacturers API routes + */ + Route::group(['prefix' => 'manufacturers'], function () { - Route::get( - 'reports/depreciation', - [ - 'as' => 'api.depreciation-report.index', - 'uses' => 'AssetsController@index' - ] - ); - - /*--- Kits API ---*/ - - Route::resource('kits', 'PredefinedKitsController', - [ - 'names' => + Route::get('selectlist', [ - 'index' => 'api.kits.index', - 'show' => 'api.kits.show', - 'store' => 'api.kits.store', - 'update' => 'api.kits.update', - 'destroy' => 'api.kits.destroy', - ], - 'except' => ['create', 'edit'], - 'parameters' => ['kit' => 'kit_id'] + Api\ManufacturersController::class, + 'selectlist' + ] + )->name('api.manufacturers.selectlist'); + + }); + + Route::resource('manufacturers', + Api\ManufacturersController::class, + ['names' => + [ + 'index' => 'api.manufacturers.index', + 'show' => 'api.manufacturers.show', + 'update' => 'api.manufacturers.update', + 'store' => 'api.manufacturers.store', + 'destroy' => 'api.manufacturers.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['manufacturer' => 'manufacturer_id'], ] - ); + ); // end manufacturers API routes - Route::group([ 'prefix' => 'kits/{kit_id}' ], function () { + /** + * Asset models API routes + */ + Route::group(['prefix' => 'models'], function () { - // kit licenses - Route::get('licenses', + Route::get('selectlist', + [ + Api\AssetModelsController::class, + 'selectlist' + ] + )->name('api.models.selectlist'); + + Route::get('assets', + [ + Api\AssetModelsController::class, + 'assets' + ] + )->name('api.models.assets'); + + }); + + Route::resource('models', + Api\AssetModelsController::class, + ['names' => [ - 'as' => 'api.kits.licenses.index', - 'uses' => 'PredefinedKitsController@indexLicenses', + 'index' => 'api.models.index', + 'show' => 'api.models.show', + 'update' => 'api.models.update', + 'store' => 'api.models.store', + 'destroy' => 'api.models.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['model' => 'model_id'], + ] + ); // end asset models API routes + + + + /** + * Settings API routes + */ + Route::group(['middleware'=> ['auth', 'authorize:superuser'], 'prefix' => 'settings'], function () { + + Route::post('ldaptest', + [ + Api\SettingsController::class, + 'ldapAdSettingsTest' + ] + )->name('api.settings.ldaptest'); + + Route::post('purge_barcodes', + [ + Api\SettingsController::class, + 'purgeBarcodes' + ] + )->name('api.settings.purgebarcodes'); + + Route::get('login-attempts', + [ + Api\SettingsController::class, + 'showLoginAttempts' + ] + )->name('api.settings.login_attempts'); + + Route::post('ldaptestlogin', + [ + Api\SettingsController::class, + 'ldaptestlogin' + ] + )->name('api.settings.ldaptestlogin'); + + Route::post('slacktest', + [ + Api\SettingsController::class, + 'slacktest' ] - ); + )->name('api.settings.slacktest'); + + Route::post('mailtest', + [ + Api\SettingsController::class, + 'ajaxTestEmail' + ] + )->name('api.settings.mailtest'); + + }); - Route::post('licenses', + Route::resource('settings', + Api\SettingsController::class, + ['names' => [ - 'as' => 'api.kits.licenses.store', - 'uses' => 'PredefinedKitsController@storeLicense', + 'index' => 'api.settings.index', + 'show' => 'api.settings.show', + 'update' => 'api.settings.update', + 'store' => 'api.settings.store', + 'destroy' => 'api.settings.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['setting' => 'setting_id'], + ] + ); // end settings API + + + /** + * Status labels API routes + */ + Route::group(['prefix' => 'statuslabels'], function () { + + Route::get('selectlist', + [ + Api\StatuslabelsController::class, + 'selectlist' + ] + )->name('api.statuslabels.selectlist'); + + Route::get('assets', + [ + Api\StatuslabelsController::class, + 'getAssetCountByStatuslabel' + ] + )->name('api.statuslabels.assets.bytype'); + + Route::get('assetlist', + [ + Api\StatuslabelsController::class, + 'assets' + ] + )->name('api.statuslabels.assets'); + + Route::get('{statuslabel}/deployable', + [ + Api\StatuslabelsController::class, + 'checkIfDeployable' + ] + )->name('api.statuslabels.deployable'); + + }); + + Route::resource('statuslabels', + Api\StatuslabelsController::class, + ['names' => + [ + 'index' => 'api.statuslabels.index', + 'show' => 'api.statuslabels.show', + 'update' => 'api.statuslabels.update', + 'store' => 'api.statuslabels.store', + 'destroy' => 'api.statuslabels.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['statuslabel' => 'statuslabel_id'], + ] + ); // end status labels API routes + + + /** + * Suppliers API routes + */ + Route::group(['prefix' => 'suppliers'], function () { + + Route::get('selectlist', + [ + Api\SuppliersController::class, + 'selectlist' + ] + )->name('api.suppliers.selectlist'); + + }); + + Route::resource('suppliers', + Api\SuppliersController::class, + ['names' => + [ + 'index' => 'api.suppliers.index', + 'show' => 'api.suppliers.show', + 'update' => 'api.suppliers.update', + 'store' => 'api.suppliers.store', + 'destroy' => 'api.suppliers.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['supplier' => 'supplier_id'], + ] + ); // end suppliers API routes + + + + /** + * Users API routes + */ + Route::group(['prefix' => 'users'], function () { + + Route::get('selectlist', + [ + Api\UsersController::class, + 'selectlist' + ] + )->name('api.users.selectlist'); + + Route::post('two_factor_reset', + [ + Api\UsersController::class, + 'postTwoFactorReset' + ] + )->name('api.users.two_factor_reset'); + + Route::get('me', + [ + Api\UsersController::class, + 'getCurrentUserInfo' + ] + )->name('api.users.me'); + + Route::get('list/{status?}', + [ + Api\UsersController::class, + 'getDatatable' ] - ); + )->name('api.users.list'); + + Route::get('{user}/assets', + [ + Api\UsersController::class, + 'assets' + ] + )->name('api.users.assetlist'); + + Route::get('{user}/accessories', + [ + Api\UsersController::class, + 'accessories' + ] + )->name('api.users.accessorieslist'); + + Route::get('{user}/licenses', + [ + Api\UsersController::class, + 'licenses' + ] + )->name('api.users.licenselist'); + + Route::post('{user}/upload', + [ + Api\UsersController::class, + 'postUpload' + ] + )->name('api.users.uploads'); + + Route::post('{user}/restore', + [ + Api\UsersController::class, + 'restore' + ] + )->name('api.users.restore'); + + }); + + Route::resource('users', + Api\UsersController::class, + ['names' => + [ + 'index' => 'api.users.index', + 'show' => 'api.users.show', + 'update' => 'api.users.update', + 'store' => 'api.users.store', + 'destroy' => 'api.users.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['user' => 'user_id'], + ] + ); // end users API routes + + + /** + * Kits API routes + */ + Route::resource('kits', + Api\PredefinedKitsController::class, + ['names' => + [ + 'index' => 'api.kits.index', + 'show' => 'api.kits.show', + 'update' => 'api.kits.update', + 'store' => 'api.kits.store', + 'destroy' => 'api.kits.destroy', + ], + 'except' => ['create', 'edit'], + 'parameters' => ['kit' => 'kit_id'], + ] + ); // end kits API routes + + + Route::group(['prefix' => 'kits/{kit_id}'], function () { + + // kit licenses + Route::get('licenses', + [ + Api\PredefinedKitsController::class, + 'indexLicenses' + ] + )->name('api.kits.licenses.index'); + + Route::post('licenses', + [ + Api\PredefinedKitsController::class, + 'storeLicense' + ] + )->name('api.kits.licenses.store'); + + Route::put('licenses/{license_id}', + [ + Api\PredefinedKitsController::class, + 'updateLicense' + ] + )->name('api.kits.licenses.update'); + + Route::delete('licenses/{license_id}', + [ + Api\PredefinedKitsController::class, + 'detachLicense' + ] + )->name('api.kits.licenses.destroy'); + + + // kit models + Route::get('models', + [ + Api\PredefinedKitsController::class, + 'indexModels' + ] + )->name('api.kits.models.index'); + + Route::post('models', + [ + Api\PredefinedKitsController::class, + 'storeModels' + ] + )->name('api.kits.models.store'); + + Route::put('models/{model_id}', + [ + Api\PredefinedKitsController::class, + 'updateModels' + ] + )->name('api.kits.models.update'); + + Route::delete('models/{model_id}', + [ + Api\PredefinedKitsController::class, + 'detachModels' + ] + )->name('api.kits.models.destroy'); + + // kit accessories + Route::get('accessories', + [ + Api\PredefinedKitsController::class, + 'indexAccessories' + ] + )->name('api.kits.accessories.index'); + + Route::post('accessories', + [ + Api\PredefinedKitsController::class, + 'storeAccessory' + ] + )->name('api.kits.accessories.store'); + + Route::put('accessories/{accessory_id}', + [ + Api\PredefinedKitsController::class, + 'updateAccessory' + ] + )->name('api.kits.accessories.update'); + + Route::delete('accessories/{accessory_id}', + [ + Api\PredefinedKitsController::class, + 'detachAccessory' + ] + )->name('api.kits.accessories.destroy'); + + // kit consumables + Route::get('consumables', + [ + Api\PredefinedKitsController::class, + 'indexConsumables' + ] + )->name('api.kits.consumables.index'); + + Route::post('consumables', + [ + Api\PredefinedKitsController::class, + 'storeConsumable' + ] + )->name('api.kits.consumables.store'); + + Route::put('consumables/{consumable_id}', + [ + Api\PredefinedKitsController::class, + 'updateConsumable' + ] + )->name('api.kits.consumables.update'); + + Route::delete('consumables/{consumable_id}', + [ + Api\PredefinedKitsController::class, + 'detachConsumable' + ] + )->name('api.kits.consumables.destroy'); + + }); // end consumable routes + - Route::put('licenses/{license_id}', - [ - 'as' => 'api.kits.licenses.update', - 'uses' => 'PredefinedKitsController@updateLicense', - ] - ); - - Route::delete('licenses/{license_id}', - [ - 'as' => 'api.kits.licenses.destroy', - 'uses' => 'PredefinedKitsController@detachLicense', - ] - ); + /** + * Reports API routes + */ - // kit models - Route::get('models', - [ - 'as' => 'api.kits.models.index', - 'uses' => 'PredefinedKitsController@indexModels', - ] - ); - - Route::post('models', - [ - 'as' => 'api.kits.models.store', - 'uses' => 'PredefinedKitsController@storeModel', - ] - ); - - Route::put('models/{model_id}', - [ - 'as' => 'api.kits.models.update', - 'uses' => 'PredefinedKitsController@updateModel', - ] - ); + Route::group(['prefix' => 'reports'], function () { - Route::delete('models/{model_id}', + Route::get('activity', [ - 'as' => 'api.kits.models.destroy', - 'uses' => 'PredefinedKitsController@detachModel', + Api\ReportsController::class, + 'index' ] - ); - - // kit accessories - Route::get('accessories', - [ - 'as' => 'api.kits.accessories.index', - 'uses' => 'PredefinedKitsController@indexAccessories', - ] - ); - - Route::post('accessories', - [ - 'as' => 'api.kits.accessories.store', - 'uses' => 'PredefinedKitsController@storeAccessory', - ] - ); - - Route::put('accessories/{accessory_id}', - [ - 'as' => 'api.kits.accessories.update', - 'uses' => 'PredefinedKitsController@updateAccessory', - ] - ); - - Route::delete('accessories/{accessory_id}', - [ - 'as' => 'api.kits.accessories.destroy', - 'uses' => 'PredefinedKitsController@detachAccessory', - ] - ); - - // kit consumables - Route::get('consumables', - [ - 'as' => 'api.kits.consumables.index', - 'uses' => 'PredefinedKitsController@indexConsumables', - ] - ); - - Route::post('consumables', - [ - 'as' => 'api.kits.consumables.store', - 'uses' => 'PredefinedKitsController@storeConsumable', - ] - ); - - Route::put('consumables/{consumable_id}', - [ - 'as' => 'api.kits.consumables.update', - 'uses' => 'PredefinedKitsController@updateConsumable', - ] - ); - - Route::delete('consumables/{consumable_id}', - [ - 'as' => 'api.kits.consumables.destroy', - 'uses' => 'PredefinedKitsController@detachConsumable', - ] - ); - - }); // kits group - - Route::fallback(function(){ - return response()->json( - [ - 'status' => 'error', - 'message' => '404 endpoint not found. Please check the API reference at https://snipe-it.readme.io/reference to find a valid API endpoint.', - 'payload' => null, - ], 404); - }); - -}); + )->name('api.activity.index'); + }); // end reports api routes + Route::fallback(function () { + return response()->json( + [ + 'status' => 'error', + 'message' => '404 endpoint not found. Please check the API reference at https://snipe-it.readme.io/reference to find a valid API endpoint.', + 'payload' => null, + ], 404); + }); // end fallback routes + + +}); // end API routes \ No newline at end of file diff --git a/routes/console.php b/routes/console.php index 785b9387e4..a4c876ae04 100644 --- a/routes/console.php +++ b/routes/console.php @@ -16,10 +16,10 @@ use Illuminate\Foundation\Inspiring; Artisan::command('inspire', function () { $this->comment(Inspiring::quote()); -})->describe('Display an inspiring quote'); +})->purpose('Display an inspiring quote'); Artisan::command('snipeit:travisci-install', function () { - if(!Setting::setupCompleted()) { + if (! Setting::setupCompleted()) { $settings = new Setting; $settings->site_name = 'test-ci'; $settings->alert_email = 'test@example.com'; @@ -34,4 +34,4 @@ Artisan::command('snipeit:travisci-install', function () { } else { $this->comment('Setup already ran'); } -})->describe('Travis-cli install script for unit tests'); +})->purpose('Travis-cli install script for unit tests'); diff --git a/routes/web.php b/routes/web.php index 21600d9f11..7a6c25bdcb 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,84 +1,101 @@ 'auth'], function () { /* * Companies */ - Route::resource('companies', 'CompaniesController', [ - 'parameters' => ['company' => 'company_id'] + Route::resource('companies', CompaniesController::class, [ + 'parameters' => ['company' => 'company_id'], ]); /* * Categories */ - Route::resource('categories', 'CategoriesController', [ - 'parameters' => ['category' => 'category_id'] + Route::resource('categories', CategoriesController::class, [ + 'parameters' => ['category' => 'category_id'], ]); /* * Locations */ - Route::resource('locations', 'LocationsController', [ - 'parameters' => ['location' => 'location_id'] + Route::resource('locations', LocationsController::class, [ + 'parameters' => ['location' => 'location_id'], ]); - + Route::get( 'locations/{locationId}/printassigned', - [ 'as' => 'locations.print_assigned', 'uses' => 'LocationsController@print_assigned' ] - ); - + [LocationsController::class, 'print_assigned'] + )->name('locations.print_assigned'); + Route::get( 'locations/{locationId}/printallassigned', - [ 'as' => 'locations.print_all_assigned', 'uses' => 'LocationsController@print_all_assigned' ] - ); + [LocationsController::class, 'print_all_assigned'] + )->name('locations.print_all_assigned'); /* * Manufacturers */ - Route::group([ 'prefix' => 'manufacturers', 'middleware' => ['auth'] ], function () { - - Route::get('{manufacturers_id}/restore', [ 'as' => 'restore/manufacturer', 'uses' => 'ManufacturersController@restore']); + Route::group(['prefix' => 'manufacturers', 'middleware' => ['auth']], function () { + Route::get('{manufacturers_id}/restore', [ManufacturersController::class, 'restore'] )->name('restore/manufacturer'); }); - Route::resource('manufacturers', 'ManufacturersController', [ - 'parameters' => ['manufacturer' => 'manufacturers_id'] + Route::resource('manufacturers', ManufacturersController::class, [ + 'parameters' => ['manufacturer' => 'manufacturers_id'], ]); /* * Suppliers */ - Route::resource('suppliers', 'SuppliersController', [ - 'parameters' => ['supplier' => 'supplier_id'] + Route::resource('suppliers', SuppliersController::class, [ + 'parameters' => ['supplier' => 'supplier_id'], ]); /* * Depreciations */ - Route::resource('depreciations', 'DepreciationsController', [ - 'parameters' => ['depreciation' => 'depreciation_id'] + Route::resource('depreciations', DepreciationsController::class, [ + 'parameters' => ['depreciation' => 'depreciation_id'], ]); - /* - * Status Labels - */ - Route::resource('statuslabels', 'StatuslabelsController', [ - 'parameters' => ['statuslabel' => 'statuslabel_id'] + /* + * Status Labels + */ + Route::resource('statuslabels', StatuslabelsController::class, [ + 'parameters' => ['statuslabel' => 'statuslabel_id'], ]); - /* * Departments */ - Route::resource('departments', 'DepartmentsController', [ - 'parameters' => ['department' => 'department_id'] + Route::resource('departments', DepartmentsController::class, [ + 'parameters' => ['department' => 'department_id'], ]); - - }); - /* | |-------------------------------------------------------------------------- @@ -86,11 +103,11 @@ Route::group(['middleware' => 'auth'], function () { |-------------------------------------------------------------------------- | | Routes for various modal dialogs to interstitially create various things -| +| */ -Route::group(['middleware' => 'auth','prefix' => 'modals'], function () { - Route::get('{type}/{itemId?}',['as' => 'modal.show', 'uses' => 'ModalController@show']); +Route::group(['middleware' => 'auth', 'prefix' => 'modals'], function () { + Route::get('{type}/{itemId?}', [ModalController::class, 'show'] )->name('modal.show'); }); /* @@ -103,19 +120,12 @@ Route::group(['middleware' => 'auth','prefix' => 'modals'], function () { */ Route::group(['middleware' => 'auth'], function () { - Route::get( 'display-sig/{filename}', - [ - 'as' => 'log.signature.view', - 'uses' => 'ActionlogController@displaySig' ] - ); - - + [ActionlogController::class, 'displaySig'] + )->name('log.signature.view'); }); - - /* |-------------------------------------------------------------------------- | Admin Routes @@ -125,89 +135,71 @@ Route::group(['middleware' => 'auth'], function () { | */ +Route::group(['prefix' => 'admin', 'middleware' => ['auth', 'authorize:superuser']], function () { + Route::get('settings', [SettingsController::class, 'getSettings'])->name('settings.general.index'); + Route::post('settings', [SettingsController::class, 'postSettings'])->name('settings.general.save'); + Route::get('branding', [SettingsController::class, 'getBranding'])->name('settings.branding.index'); + Route::post('branding', [SettingsController::class, 'postBranding'])->name('settings.branding.save'); -Route::group([ 'prefix' => 'admin','middleware' => ['auth', 'authorize:superuser']], function () { + Route::get('security', [SettingsController::class, 'getSecurity'])->name('settings.security.index'); + Route::post('security', [SettingsController::class, 'postSecurity'])->name('settings.security.save'); - Route::get('settings', ['as' => 'settings.general.index','uses' => 'SettingsController@getSettings' ]); - Route::post('settings', ['as' => 'settings.general.save','uses' => 'SettingsController@postSettings' ]); + Route::get('groups', [GroupsController::class, 'index'])->name('settings.groups.index'); + Route::get('localization', [SettingsController::class, 'getLocalization'])->name('settings.localization.index'); + Route::post('localization', [SettingsController::class, 'postLocalization'])->name('settings.localization.save'); - Route::get('branding', ['as' => 'settings.branding.index','uses' => 'SettingsController@getBranding' ]); - Route::post('branding', ['as' => 'settings.branding.save','uses' => 'SettingsController@postBranding' ]); + Route::get('notifications', [SettingsController::class, 'getAlerts'])->name('settings.alerts.index'); + Route::post('notifications', [SettingsController::class, 'postAlerts'])->name('settings.alerts.save'); - Route::get('security', ['as' => 'settings.security.index','uses' => 'SettingsController@getSecurity' ]); - Route::post('security', ['as' => 'settings.security.save','uses' => 'SettingsController@postSecurity' ]); + Route::get('slack', [SettingsController::class, 'getSlack'])->name('settings.slack.index'); + Route::post('slack', [SettingsController::class, 'postSlack'])->name('settings.slack.save'); - Route::get('groups', ['as' => 'settings.groups.index','uses' => 'GroupsController@index' ]); + Route::get('asset_tags', [SettingsController::class, 'getAssetTags'])->name('settings.asset_tags.index'); + Route::post('asset_tags', [SettingsController::class, 'postAssetTags'])->name('settings.asset_tags.save'); - Route::get('localization', ['as' => 'settings.localization.index','uses' => 'SettingsController@getLocalization' ]); - Route::post('localization', ['as' => 'settings.localization.save','uses' => 'SettingsController@postLocalization' ]); + Route::get('barcodes', [SettingsController::class, 'getBarcodes'])->name('settings.barcodes.index'); + Route::post('barcodes', [SettingsController::class, 'postBarcodes'])->name('settings.barcodes.save'); - Route::get('notifications', ['as' => 'settings.alerts.index','uses' => 'SettingsController@getAlerts' ]); - Route::post('notifications', ['as' => 'settings.alerts.save','uses' => 'SettingsController@postAlerts' ]); + Route::get('labels', [SettingsController::class, 'getLabels'])->name('settings.labels.index'); + Route::post('labels', [SettingsController::class, 'postLabels'])->name('settings.labels.save'); - Route::get('slack', ['as' => 'settings.slack.index','uses' => 'SettingsController@getSlack' ]); - Route::post('slack', ['as' => 'settings.slack.save','uses' => 'SettingsController@postSlack' ]); + Route::get('ldap', [SettingsController::class, 'getLdapSettings'])->name('settings.ldap.index'); + Route::post('ldap', [SettingsController::class, 'postLdapSettings'])->name('settings.ldap.save'); - Route::get('asset_tags', ['as' => 'settings.asset_tags.index','uses' => 'SettingsController@getAssetTags' ]); - Route::post('asset_tags', ['as' => 'settings.asset_tags.save','uses' => 'SettingsController@postAssetTags' ]); + Route::get('phpinfo', [SettingsController::class, 'getPhpInfo'])->name('settings.phpinfo.index'); - Route::get('barcodes', ['as' => 'settings.barcodes.index','uses' => 'SettingsController@getBarcodes' ]); - Route::post('barcodes', ['as' => 'settings.barcodes.save','uses' => 'SettingsController@postBarcodes' ]); + Route::get('oauth', [SettingsController::class, 'api'])->name('settings.oauth.index'); - Route::get('labels', ['as' => 'settings.labels.index','uses' => 'SettingsController@getLabels' ]); - Route::post('labels', ['as' => 'settings.labels.save','uses' => 'SettingsController@postLabels' ]); + Route::get('purge', [SettingsController::class, 'getPurge'])->name('settings.purge.index'); + Route::post('purge', [SettingsController::class, 'postPurge'])->name('settings.purge.save'); - Route::get('ldap', ['as' => 'settings.ldap.index','uses' => 'SettingsController@getLdapSettings' ]); - Route::post('ldap', ['as' => 'settings.ldap.save','uses' => 'SettingsController@postLdapSettings' ]); + Route::get('login-attempts', [SettingsController::class, 'getLoginAttempts'])->name('settings.logins.index'); - Route::get('phpinfo', ['as' => 'settings.phpinfo.index','uses' => 'SettingsController@getPhpInfo' ]); + // Backups + Route::group(['prefix' => 'backups', 'middleware' => 'auth'], function () { + Route::get('download/{filename}', + [SettingsController::class, 'downloadFile'])->name('settings.backups.download'); + Route::delete('delete/{filename}', + [SettingsController::class, 'deleteFile'])->name('settings.backups.destroy'); - Route::get('oauth', [ 'as' => 'settings.oauth.index', 'uses' => 'SettingsController@api' ]); - - Route::get('purge', ['as' => 'settings.purge.index', 'uses' => 'SettingsController@getPurge']); - Route::post('purge', ['as' => 'settings.purge.save', 'uses' => 'SettingsController@postPurge']); - - Route::get('login-attempts', ['as' => 'settings.logins.index','uses' => 'SettingsController@getLoginAttempts' ]); - - # Backups - Route::group([ 'prefix' => 'backups', 'middleware' => 'auth' ], function () { - - - Route::get('download/{filename}', [ - 'as' => 'settings.backups.download', - 'uses' => 'SettingsController@downloadFile' ]); - - Route::delete('delete/{filename}', [ - 'as' => 'settings.backups.destroy', - 'uses' => 'SettingsController@deleteFile' ]); - - Route::post('/', [ - 'as' => 'settings.backups.create', - 'uses' => 'SettingsController@postBackups' - ]); - - Route::get('/', [ 'as' => 'settings.backups.index', 'uses' => 'SettingsController@getBackups' ]); + Route::post('/', + [SettingsController::class, 'postBackups'] + )->name('settings.backups.create'); + Route::get('/', [SettingsController::class, 'getBackups'])->name('settings.backups.index'); }); - - - Route::resource('groups', 'GroupsController', [ + Route::resource('groups', GroupsController::class, [ 'middleware' => ['auth'], - 'parameters' => ['group' => 'group_id'] + 'parameters' => ['group' => 'group_id'], ]); - Route::get('/', ['as' => 'settings.index', 'uses' => 'SettingsController@index' ]); - - + Route::get('/', [SettingsController::class, 'index'])->name('settings.index'); }); - - - /* |-------------------------------------------------------------------------- | Importer Routes @@ -216,14 +208,12 @@ Route::group([ 'prefix' => 'admin','middleware' => ['auth', 'authorize:superuser | | */ -Route::group([ 'prefix' => 'import', 'middleware' => ['auth']], function () { - Route::get('/', [ - 'as' => 'imports.index', - 'uses' => 'ImportsController@index' - ]); +Route::group(['prefix' => 'import', 'middleware' => ['auth']], function () { + Route::get('/', + [ImportsController::class, 'index'] + )->name('imports.index'); }); - /* |-------------------------------------------------------------------------- | Account Routes @@ -232,130 +222,117 @@ Route::group([ 'prefix' => 'import', 'middleware' => ['auth']], function () { | | */ -Route::group([ 'prefix' => 'account', 'middleware' => ['auth']], function () { +Route::group(['prefix' => 'account', 'middleware' => ['auth']], function () { - # Profile - Route::get('profile', [ 'as' => 'profile', 'uses' => 'ProfileController@getIndex' ]); - Route::post('profile', 'ProfileController@postIndex'); + // Profile + Route::get('profile', [ProfileController::class, 'getIndex'])->name('profile'); + Route::post('profile', [ProfileController::class, 'postIndex']); - Route::get('menu', [ 'as' => 'account.menuprefs', 'uses' => 'ProfileController@getMenuState' ]); + Route::get('menu', [ProfileController::class, 'getMenuState'])->name('account.menuprefs'); - Route::get('password', [ 'as' => 'account.password.index', 'uses' => 'ProfileController@password' ]); - Route::post('password', [ 'uses' => 'ProfileController@passwordSave' ]); + Route::get('password', [ProfileController::class, 'password'])->name('account.password.index'); + Route::post('password', [ProfileController::class, 'passwordSave']); - Route::get('api', [ 'as' => 'user.api', 'uses' => 'ProfileController@api' ]); + Route::get('api', [ProfileController::class, 'api'])->name('user.api'); - # View Assets - Route::get('view-assets', [ 'as' => 'view-assets', 'uses' => 'ViewAssetsController@getIndex' ]); + // View Assets + Route::get('view-assets', [ViewAssetsController::class, 'getIndex'])->name('view-assets'); - Route::get('requested', [ 'as' => 'account.requested', 'uses' => 'ViewAssetsController@getRequestedAssets' ]); + Route::get('requested', [ViewAssetsController::class, 'getRequestedAssets'])->name('account.requested'); - # Accept Asset + // Accept Asset Route::get( 'accept-asset/{logID}', - [ 'as' => 'account/accept-assets', 'uses' => 'ViewAssetsController@getAcceptAsset' ] - ); + [ViewAssetsController::class, 'getAcceptAsset'] + )->name('account/accept-assets'); - # Profile + // Profile Route::get( 'requestable-assets', - [ 'as' => 'requestable-assets', 'uses' => 'ViewAssetsController@getRequestableIndex' ] - ); + [ViewAssetsController::class, 'getRequestableIndex'] + )->name('requestable-assets'); Route::get( 'request-asset/{assetId}', - [ 'as' => 'account/request-asset', 'uses' => 'ViewAssetsController@getRequestAsset' ] - ); + [ViewAssetsController::class, 'getRequestAsset'] + )->name('account/request-asset'); Route::post( 'request/{itemType}/{itemId}', - [ 'as' => 'account/request-item', 'uses' => 'ViewAssetsController@getRequestItem'] - ); + [ViewAssetsController::class, 'getRequestItem'] + )->name('account/request-item'); - # Account Dashboard - Route::get('/', [ 'as' => 'account', 'uses' => 'ViewAssetsController@getIndex' ]); + // Account Dashboard + Route::get('/', [ViewAssetsController::class, 'getIndex'])->name('account'); - - Route::get('accept', 'Account\AcceptanceController@index') + Route::get('accept', [Account\AcceptanceController::class, 'index']) ->name('account.accept'); - - Route::get('accept/{id}', 'Account\AcceptanceController@create') + + Route::get('accept/{id}', [Account\AcceptanceController::class, 'create']) ->name('account.accept.item'); - Route::post('accept/{id}', 'Account\AcceptanceController@store'); - + Route::post('accept/{id}', [Account\AcceptanceController::class, 'store']); }); - Route::group(['middleware' => ['auth']], function () { - - Route::get('reports/audit', [ - 'as' => 'reports.audit', - 'uses' => 'ReportsController@audit' - ]); + Route::get('reports/audit', + [ReportsController::class, 'audit'] + )->name('reports.audit'); Route::get( 'reports/depreciation', - [ 'as' => 'reports/depreciation', 'uses' => 'ReportsController@getDeprecationReport' ] - ); + [ReportsController::class, 'getDeprecationReport'] + )->name('reports/depreciation'); Route::get( 'reports/export/depreciation', - [ 'as' => 'reports/export/depreciation', 'uses' => 'ReportsController@exportDeprecationReport' ] - ); + [ReportsController::class, 'exportDeprecationReport'] + )->name('reports/export/depreciation'); Route::get( 'reports/asset_maintenances', - [ 'as' => 'reports/asset_maintenances', 'uses' => 'ReportsController@getAssetMaintenancesReport' ] - ); + [ReportsController::class, 'getAssetMaintenancesReport'] + )->name('reports/asset_maintenances'); Route::get( 'reports/export/asset_maintenances', - [ - 'as' => 'reports/export/asset_maintenances', - 'uses' => 'ReportsController@exportAssetMaintenancesReport' - ] - ); + [ReportsController::class, 'exportAssetMaintenancesReport'] + )->name('reports/export/asset_maintenances'); Route::get( 'reports/licenses', - [ 'as' => 'reports/licenses', 'uses' => 'ReportsController@getLicenseReport' ] - ); + [ReportsController::class, 'getLicenseReport'] + )->name('reports/licenses'); Route::get( 'reports/export/licenses', - [ 'as' => 'reports/export/licenses', 'uses' => 'ReportsController@exportLicenseReport' ] - ); + [ReportsController::class, 'exportLicenseReport'] + )->name('reports/export/licenses'); - Route::get('reports/accessories', [ 'as' => 'reports/accessories', 'uses' => 'ReportsController@getAccessoryReport' ]); + Route::get('reports/accessories', [ReportsController::class, 'getAccessoryReport'])->name('reports/accessories'); Route::get( 'reports/export/accessories', - [ 'as' => 'reports/export/accessories', 'uses' => 'ReportsController@exportAccessoryReport' ] - ); - Route::get('reports/custom', [ 'as' => 'reports/custom', 'uses' => 'ReportsController@getCustomReport' ]); - Route::post('reports/custom', 'ReportsController@postCustom'); + [ReportsController::class, 'exportAccessoryReport'] + )->name('reports/export/accessories'); + Route::get('reports/custom', [ReportsController::class, 'getCustomReport'])->name('reports/custom'); + Route::post('reports/custom', [ReportsController::class, 'postCustom']); Route::get( 'reports/activity', - [ 'as' => 'reports.activity', 'uses' => 'ReportsController@getActivityReport' ] - ); - - Route::post('reports/activity', 'ReportsController@postActivityReport'); - + [ReportsController::class, 'getActivityReport'] + )->name('reports.activity'); + Route::post('reports/activity', [ReportsController::class, 'postActivityReport']); Route::get( 'reports/unaccepted_assets', - [ 'as' => 'reports/unaccepted_assets', 'uses' => 'ReportsController@getAssetAcceptanceReport' ] - ); + [ReportsController::class, 'getAssetAcceptanceReport'] + )->name('reports/unaccepted_assets'); Route::get( 'reports/export/unaccepted_assets', - [ 'as' => 'reports/export/unaccepted_assets', 'uses' => 'ReportsController@exportAssetAcceptanceReport' ] - ); + [ReportsController::class, 'exportAssetAcceptanceReport'] + )->name('reports/export/unaccepted_assets'); }); Route::get( 'auth/signin', - ['uses' => 'Auth\LoginController@legacyAuthRedirect' ] + [LoginController::class, 'legacyAuthRedirect'] ); - - - /* |-------------------------------------------------------------------------- | Setup Routes @@ -364,114 +341,82 @@ Route::get( | | */ -Route::group([ 'prefix' => 'setup', 'middleware' => 'web'], function () { +Route::group(['prefix' => 'setup', 'middleware' => 'web'], function () { Route::get( 'user', - [ - 'as' => 'setup.user', - 'uses' => 'SettingsController@getSetupUser' ] - ); + [SettingsController::class, 'getSetupUser'] + )->name('setup.user'); Route::post( 'user', - [ - 'as' => 'setup.user.save', - 'uses' => 'SettingsController@postSaveFirstAdmin' ] - ); - + [SettingsController::class, 'postSaveFirstAdmin'] + )->name('setup.user.save'); Route::get( 'migrate', - [ - 'as' => 'setup.migrate', - 'uses' => 'SettingsController@getSetupMigrate' ] - ); + [SettingsController::class, 'getSetupMigrate'] + )->name('setup.migrate'); Route::get( 'done', - [ - 'as' => 'setup.done', - 'uses' => 'SettingsController@getSetupDone' ] - ); + [SettingsController::class, 'getSetupDone'] + )->name('setup.done'); Route::get( 'mailtest', - [ - 'as' => 'setup.mailtest', - 'uses' => 'SettingsController@ajaxTestEmail' ] - ); - + [SettingsController::class, 'ajaxTestEmail'] + )->name('setup.mailtest'); Route::get( '/', - [ - 'as' => 'setup', - 'uses' => 'SettingsController@getSetupIndex' ] - ); - + [SettingsController::class, 'getSetupIndex'] + )->name('setup'); }); -Route::get( - 'two-factor-enroll', - [ - 'as' => 'two-factor-enroll', - 'middleware' => ['web'], - 'uses' => 'Auth\LoginController@getTwoFactorEnroll' ] -); - -Route::get( - 'two-factor', - [ - 'as' => 'two-factor', - 'middleware' => ['web'], - 'uses' => 'Auth\LoginController@getTwoFactorAuth' ] -); - -Route::post( - 'two-factor', - [ - 'as' => 'two-factor', - 'middleware' => ['web'], - 'uses' => 'Auth\LoginController@postTwoFactorAuth' ] -); - -Route::get( - '/', - [ - 'as' => 'home', - 'middleware' => ['auth'], - 'uses' => 'DashboardController@getIndex' ] -); +Route::middleware(['web'], function () { + Route::get( + 'two-factor-enroll', + [LoginController::class, 'getTwoFactorEnroll'] + )->name('two-factor-enroll'); + + Route::get( + 'two-factor', + [LoginController::class, 'getTwoFactorAuth'] + )->name('two-factor'); + + Route::post( + 'two-factor', + [LoginController::class, 'postTwoFactorAuth'] + ); +}); Route::group(['middleware' => 'web'], function () { - //Route::auth(); Route::get( 'login', - [ - 'as' => 'login', - 'middleware' => ['web'], - 'uses' => 'Auth\LoginController@showLoginForm' ] - ); + [LoginController::class, 'showLoginForm'] + )->name("login"); Route::post( 'login', - [ - 'as' => 'login', - 'middleware' => ['web'], - 'uses' => 'Auth\LoginController@login' ] + [LoginController::class, 'login'] ); Route::get( 'logout', - [ - 'as' => 'logout', - 'uses' => 'Auth\LoginController@logout' ] - ); - + [LoginController::class, 'logout'] + )->name('logout'); }); Auth::routes(); -Route::get('/health', [ 'as' => 'health', 'uses' => 'HealthController@get']); \ No newline at end of file +Route::get( + '/health', + [HealthController::class, 'get'] +)->name('health'); + +Route::middleware(['auth'])->get( + '/', + [DashboardController::class, 'index'] +)->name('home'); diff --git a/routes/web/accessories.php b/routes/web/accessories.php index 1f1a70fa6f..c6e9b5a8e2 100644 --- a/routes/web/accessories.php +++ b/routes/web/accessories.php @@ -1,31 +1,35 @@ 'accessories', 'middleware' => ['auth']], function () { - +Route::group(['prefix' => 'accessories', 'middleware' => ['auth']], function () { Route::get( '{accessoryID}/checkout', - [ 'as' => 'checkout/accessory', 'uses' => 'Accessories\AccessoryCheckoutController@create' ] - ); + [Accessories\AccessoryCheckoutController::class, 'create'] + )->name('checkout/accessory'); + Route::post( '{accessoryID}/checkout', - [ 'as' => 'checkout/accessory', 'uses' => 'Accessories\AccessoryCheckoutController@store' ] - ); + [Accessories\AccessoryCheckoutController::class, 'store'] + )->name('checkout/accessory'); Route::get( '{accessoryID}/checkin/{backto?}', - [ 'as' => 'checkin/accessory', 'uses' => 'Accessories\AccessoryCheckinController@create' ] - ); + [Accessories\AccessoryCheckinController::class, 'create'] + )->name('checkout/accessory'); + Route::post( '{accessoryID}/checkin/{backto?}', - [ 'as' => 'checkin/accessory', 'uses' => 'Accessories\AccessoryCheckinController@store' ] - ); + [Accessories\AccessoryCheckinController::class, 'store'] + )->name('checkout/accessory'); }); -Route::resource('accessories', 'Accessories\AccessoriesController', [ +Route::resource('accessories', Accessories\AccessoriesController::class, [ 'middleware' => ['auth'], - 'parameters' => ['accessory' => 'accessory_id'] + 'parameters' => ['accessory' => 'accessory_id'], ]); diff --git a/routes/web/components.php b/routes/web/components.php index b467c090b5..08c8533f5f 100644 --- a/routes/web/components.php +++ b/routes/web/components.php @@ -1,28 +1,33 @@ 'components','middleware' => ['auth'] ], function () { +use App\Http\Controllers\Components; +use Illuminate\Support\Facades\Route; + +// Components +Route::group(['prefix' => 'components', 'middleware' => ['auth']], function () { + Route::get( + '{componentID}/checkout', + [Components\ComponentCheckoutController::class, 'create'] + )->name('checkout/accessory'); + + Route::post( + '{componentID}/checkout', + [Components\ComponentCheckoutController::class, 'store'] + )->name('checkout/accessory'); Route::get( - '{componentID}/checkout', - [ 'as' => 'checkout/component', 'uses' => 'Components\ComponentCheckoutController@create' ] - ); + '{componentID}/checkin/{backto?}', + [Components\ComponentCheckinController::class, 'create'] + )->name('checkout/accessory'); + Route::post( - '{componentID}/checkout', - [ 'as' => 'checkout/component', 'uses' => 'Components\ComponentCheckoutController@store' ] - ); - Route::get( - '{componentID}/checkin', - [ 'as' => 'checkin/component', 'uses' => 'Components\ComponentCheckinController@create' ] - ); - Route::post( - '{componentID}/checkin', - [ 'as' => 'component.checkin.save', 'uses' => 'Components\ComponentCheckinController@store' ] - ); + '{componentID}/checkin/{backto?}', + [Components\ComponentCheckinController::class, 'store'] + )->name('checkout/accessory'); }); -Route::resource('components', 'Components\ComponentsController', [ +Route::resource('components', Components\ComponentsController::class, [ 'middleware' => ['auth'], - 'parameters' => ['component' => 'component_id'] + 'parameters' => ['component' => 'component_id'], ]); diff --git a/routes/web/consumables.php b/routes/web/consumables.php index 8fbdded4bd..b4359be2ed 100644 --- a/routes/web/consumables.php +++ b/routes/web/consumables.php @@ -1,19 +1,25 @@ 'consumables', 'middleware' => ['auth']], function () { - Route::get( - '{consumableID}/checkout', - [ 'as' => 'checkout/consumable','uses' => 'Consumables\ConsumableCheckoutController@create' ] - ); - Route::post( - '{consumableID}/checkout', - [ 'as' => 'checkout/consumable', 'uses' => 'Consumables\ConsumableCheckoutController@store' ] - ); - }); - Route::resource('consumables', 'Consumables\ConsumablesController', [ - 'middleware' => ['auth'], - 'parameters' => ['consumable' => 'consumable_id'] - ]); + +Route::group(['prefix' => 'consumables', 'middleware' => ['auth']], function () { + Route::get( + '{consumablesID}/checkout', + [Consumables\ConsumableCheckoutController::class, 'create'] + )->name('checkout/accessory'); + + Route::post( + '{consumablesID}/checkout', + [Consumables\ConsumableCheckoutController::class, 'store'] + )->name('checkout/accessory'); + + +}); + +Route::resource('consumables', Consumables\ConsumablesController::class, [ + 'middleware' => ['auth'], + 'parameters' => ['consumable' => 'consumable_id'], +]); diff --git a/routes/web/fields.php b/routes/web/fields.php index a2fedcfd93..faf3b7fe26 100644 --- a/routes/web/fields.php +++ b/routes/web/fields.php @@ -1,40 +1,58 @@ 'fields', 'middleware' => ['auth']], function () { + Route::get( + 'required/{fieldset_id}/{field_id}', + [ + CustomFieldsetsController::class, + 'makeFieldRequired' + ] + )->name('fields.required'); -Route::group([ 'prefix' => 'fields','middleware' => ['auth'] ], function () { + Route::get( + 'optional/{fieldset_id}/{field_id}', + [ + CustomFieldsetsController::class, + 'makeFieldOptional' + ] + )->name('fields.optional'); - Route::get('required/{fieldset_id}/{field_id}', - ['uses' => 'CustomFieldsetsController@makeFieldRequired', - 'as' => 'fields.required'] - ); + Route::get( + '{field_id}/fieldset/{fieldset_id}/disassociate', + [ + CustomFieldsetsController::class, + 'deleteFieldFromFieldset' + ] + )->name('fields.disassociate'); - Route::get('optional/{fieldset_id}/{field_id}', - ['uses' => 'CustomFieldsetsController@makeFieldOptional', - 'as' => 'fields.optional'] - ); + Route::get( + 'fieldsets/{id}/associate', + [ + CustomFieldsetsController::class, + 'associate' + ] + )->name('fields.associate'); - Route::get('{field_id}/fieldset/{fieldset_id}/disassociate', - ['uses' => 'CustomFieldsController@deleteFieldFromFieldset', - 'as' => 'fields.disassociate'] - ); - - Route::post('fieldsets/{id}/associate', - ['uses' => 'CustomFieldsetsController@associate', - 'as' => 'fieldsets.associate'] - ); - - Route::resource('fieldsets', 'CustomFieldsetsController', [ - 'parameters' => ['fieldset' => 'field_id', 'field' => 'field_id'] - ]); + Route::resource('fieldsets', CustomFieldsetsController::class, [ + 'parameters' => ['fieldset' => 'field_id', 'field' => 'field_id'], + ]); }); + -Route::resource('fields', 'CustomFieldsController', [ - 'middleware' => ['auth'], - 'parameters' => ['field' => 'field_id', 'fieldset' => 'fieldset_id'] +Route::resource('fields', CustomFieldsController::class, [ + 'parameters' => ['field' => 'field_id'], ]); + + + diff --git a/routes/web/hardware.php b/routes/web/hardware.php index a5d6258b3b..363f6fcd00 100644 --- a/routes/web/hardware.php +++ b/routes/web/hardware.php @@ -1,4 +1,9 @@ 'hardware', - 'middleware' => ['auth']], + 'middleware' => ['auth'], ], function () { + Route::get('bulkaudit', + [Assets\AssetsController::class, 'quickScan'] + )->name('assets.bulkaudit'); - Route::get( 'bulkaudit', [ - 'as' => 'assets.bulkaudit', - 'uses' => 'Assets\AssetsController@quickScan' + // Asset Maintenances + Route::resource('maintenances', AssetMaintenancesController::class, [ + 'parameters' => ['maintenance' => 'maintenance_id', 'asset' => 'asset_id'], ]); - # Asset Maintenances - Route::resource('maintenances', 'AssetMaintenancesController', [ - 'parameters' => ['maintenance' => 'maintenance_id', 'asset' => 'asset_id'] - ]); + Route::get('requested', [Assets\AssetsController::class, 'getRequestedIndex'])->name('assets.requested'); - Route::get('requested', [ 'as' => 'assets.requested', 'uses' => 'Assets\AssetsController@getRequestedIndex']); + Route::get('scan', + [Assets\AssetsController::class, 'scan'] + )->name('asset.scan'); - Route::get('scan', [ - 'as' => 'asset.scan', - 'uses' => 'Assets\AssetsController@scan' - ]); + Route::get('audit/due', + [Assets\AssetsController::class, 'dueForAudit'] + )->name('assets.audit.due'); - Route::get('audit/due', [ - 'as' => 'assets.audit.due', - 'uses' => 'Assets\AssetsController@dueForAudit' - ]); + Route::get('audit/overdue', + [Assets\AssetsController::class, 'overdueForAudit'] + )->name('assets.audit.overdue'); - Route::get('audit/overdue', [ - 'as' => 'assets.audit.overdue', - 'uses' => 'Assets\AssetsController@overdueForAudit' - ]); + Route::get('audit/due', + [Assets\AssetsController::class, 'dueForAudit'] + )->name('assets.audit.due'); - Route::get('audit/due', [ - 'as' => 'assets.audit.due', - 'uses' => 'Assets\AssetsController@dueForAudit' - ]); + Route::get('audit/overdue', + [Assets\AssetsController::class, 'overdueForAudit'] + )->name('assets.audit.overdue'); - Route::get('audit/overdue', [ - 'as' => 'assets.audit.overdue', - 'uses' => 'Assets\AssetsController@overdueForAudit' - ]); + Route::get('audit/due', + [Assets\AssetsController::class, 'dueForAudit'] + )->name('assets.audit.due'); - Route::get('audit/due', [ - 'as' => 'assets.audit.due', - 'uses' => 'Assets\AssetsController@dueForAudit' - ]); + Route::get('audit/overdue', + [Assets\AssetsController::class, 'overdueForAudit'] + )->name('assets.audit.overdue'); - Route::get('audit/overdue', [ - 'as' => 'assets.audit.overdue', - 'uses' => 'Assets\AssetsController@overdueForAudit' - ]); + Route::get('audit/{id}', + [Assets\AssetsController::class, 'audit'] + )->name('asset.audit.create'); - Route::get('audit/{id}', [ - 'as' => 'asset.audit.create', - 'uses' => 'Assets\AssetsController@audit' - ]); + Route::post('audit/{id}', + [Assets\AssetsController::class, 'auditStore'] + )->name('asset.audit.store'); - Route::post('audit/{id}', [ - 'as' => 'asset.audit.store', - 'uses' => 'Assets\AssetsController@auditStore' - ]); + Route::get('history', + [Assets\AssetsController::class, 'getImportHistory'] + )->name('asset.import-history'); - - Route::get('history', [ - 'as' => 'asset.import-history', - 'uses' => 'Assets\AssetsController@getImportHistory' - ]); - - Route::post('history', [ - 'as' => 'asset.process-import-history', - 'uses' => 'Assets\AssetsController@postImportHistory' - ]); + Route::post('history', + [Assets\AssetsController::class, 'postImportHistory'] + )->name('asset.process-import-history'); Route::get('bytag/{any?}', - [ - 'as' => 'findbytag/hardware', - 'uses' => 'Assets\AssetsController@getAssetByTag' - ] - )->where('any', '.*'); + [Assets\AssetsController::class, 'getAssetByTag'] + )->where('any', '.*')->name('findbytag/hardware'); Route::get('byserial/{any?}', - [ - 'as' => 'findbyserial/hardware', - 'uses' => 'Assets\AssetsController@getAssetBySerial' - ] - )->where('any', '.*'); + [Assets\AssetsController::class, 'getAssetBySerial'] + )->where('any', '.*')->name('findbyserial/hardware'); + Route::get('{assetId}/clone', + [Assets\AssetsController::class, 'getClone'] + )->name('clone/hardware'); + Route::get('{assetId}/label', + [Assets\AssetsController::class, 'getLabel'] + )->name('label/hardware'); - Route::get('{assetId}/clone', [ - 'as' => 'clone/hardware', - 'uses' => 'Assets\AssetsController@getClone' - ]); + Route::post('{assetId}/clone', [Assets\AssetsController::class, 'postCreate']); - Route::get('{assetId}/label', [ - 'as' => 'label/hardware', - 'uses' => 'Assets\AssetsController@getLabel' - ]); + Route::get('{assetId}/checkout', + [Assets\AssetCheckoutController::class, 'create'] + )->name('checkout/hardware'); + Route::post('{assetId}/checkout', + [Assets\AssetCheckoutController::class, 'store'] + )->name('checkout/hardware'); + Route::get('{assetId}/checkin/{backto?}', + [Assets\AssetCheckinController::class, 'create'] + )->name('checkin/hardware'); - Route::post('{assetId}/clone', 'Assets\AssetsController@postCreate'); + Route::post('{assetId}/checkin/{backto?}', + [Assets\AssetCheckinController::class, 'store'] + )->name('checkin/hardware'); + Route::get('{assetId}/view', + [Assets\AssetsController::class, 'show'] + )->name('hardware.view'); + Route::get('{assetId}/qr_code', [Assets\AssetsController::class, 'getQrCode'])->name('qr_code/hardware'); + Route::get('{assetId}/barcode', [Assets\AssetsController::class, 'getBarCode'])->name('barcode/hardware'); + Route::get('{assetId}/restore', + [Assets\AssetsController::class, 'getRestore'] + )->name('restore/hardware'); + Route::post('{assetId}/upload', + [Assets\AssetFilesController::class, 'store'] + )->name('upload/asset'); - Route::get('{assetId}/checkout', [ - 'as' => 'checkout/hardware', - 'uses' => 'Assets\AssetCheckoutController@create' - ]); - Route::post('{assetId}/checkout', [ - 'as' => 'checkout/hardware', - 'uses' => 'Assets\AssetCheckoutController@store' - ]); - Route::get('{assetId}/checkin/{backto?}', [ - 'as' => 'checkin/hardware', - 'uses' => 'Assets\AssetCheckinController@create' - ]); - - Route::post('{assetId}/checkin/{backto?}', [ - 'as' => 'checkin/hardware', - 'uses' => 'Assets\AssetCheckinController@store' - ]); - Route::get('{assetId}/view', [ - 'as' => 'hardware.view', - 'uses' => 'Assets\AssetsController@show' - ]); - Route::get('{assetId}/qr_code', [ 'as' => 'qr_code/hardware', 'uses' => 'Assets\AssetsController@getQrCode' ]); - Route::get('{assetId}/barcode', [ 'as' => 'barcode/hardware', 'uses' => 'Assets\AssetsController@getBarCode' ]); - Route::get('{assetId}/restore', [ - 'as' => 'restore/hardware', - 'uses' => 'Assets\AssetsController@getRestore' - ]); - Route::post('{assetId}/upload', [ - 'as' => 'upload/asset', - 'uses' => 'Assets\AssetFilesController@store' - ]); - - Route::get('{assetId}/showfile/{fileId}/{download?}', [ - 'as' => 'show/assetfile', - 'uses' => 'Assets\AssetFilesController@show' - ]); - - Route::delete('{assetId}/showfile/{fileId}/delete', [ - 'as' => 'delete/assetfile', - 'uses' => 'Assets\AssetFilesController@destroy' - ]); + Route::get('{assetId}/showfile/{fileId}/{download?}', + [Assets\AssetFilesController::class, 'show'] + )->name('show/assetfile'); + Route::delete('{assetId}/showfile/{fileId}/delete', + [Assets\AssetFilesController::class, 'destroy'] + )->name('delete/assetfile'); Route::post( 'bulkedit', - [ - 'as' => 'hardware/bulkedit', - 'uses' => 'Assets\BulkAssetsController@edit' - ] - ); + [Assets\BulkAssetsController::class, 'edit'] + )->name('hardware/bulkedit'); Route::post( 'bulkdelete', - [ - 'as' => 'hardware/bulkdelete', - 'uses' => 'Assets\BulkAssetsController@destroy' - ] - ); + [Assets\BulkAssetsController::class, 'destroy'] + )->name('hardware/bulkdelete'); Route::post( 'bulksave', - [ - 'as' => 'hardware/bulksave', - 'uses' => 'Assets\BulkAssetsController@update' - ] - ); + [Assets\BulkAssetsController::class, 'update'] + )->name('hardware/bulksave'); - # Bulk checkout / checkin - Route::get( 'bulkcheckout', [ - 'as' => 'hardware/bulkcheckout', - 'uses' => 'Assets\BulkAssetsController@showCheckout' - ]); - Route::post( 'bulkcheckout', [ - 'as' => 'hardware/bulkcheckout', - 'uses' => 'Assets\BulkAssetsController@storeCheckout' - ]); + // Bulk checkout / checkin + Route::get('bulkcheckout', + [Assets\BulkAssetsController::class, 'showCheckout'] + )->name('hardware/bulkcheckout'); + Route::post('bulkcheckout', + [Assets\BulkAssetsController::class, 'storeCheckout'] + )->name('hardware/bulkcheckout'); + }); - - - -}); - - -Route::resource('hardware', 'Assets\AssetsController', [ +Route::resource('hardware', Assets\AssetsController::class, [ 'middleware' => ['auth'], - 'parameters' => ['asset' => 'asset_id'] + 'parameters' => ['asset' => 'asset_id'], ]); diff --git a/routes/web/kits.php b/routes/web/kits.php index 50712aba43..6b687f0bff 100644 --- a/routes/web/kits.php +++ b/routes/web/kits.php @@ -1,137 +1,80 @@ ['auth'], - 'parameters' => ['kit' => 'kit_id'] + 'parameters' => ['kit' => 'kit_id'], ]); +Route::group(['prefix' => 'kits/{kit_id}', 'middleware' => ['auth']], function () { + // Route::get('licenses', + // [Kits\PredefinedKitsController::class, 'indexLicenses'] + // )->name('kits.licenses.index'); -Route::group([ 'prefix' => 'kits/{kit_id}', 'middleware' => ['auth'] ], function () { + Route::post('licenses', + [Kits\PredefinedKitsController::class, 'storeLicense'] + )->name('kits.licenses.store'); - // Route::get('licenses', - // [ - // 'as' => 'kits.licenses.index', - // 'uses' => 'Kits\PredefinedKitsController@indexLicenses', - // ] - // ); - - Route::post('licenses', - [ - 'as' => 'kits.licenses.store', - 'uses' => 'Kits\PredefinedKitsController@storeLicense', - ] - ); - - Route::put('licenses/{license_id}', - [ - 'as' => 'kits.licenses.update', - 'uses' => 'Kits\PredefinedKitsController@updateLicense', - ] - ); - - Route::get('licenses/{license_id}/edit', - [ - 'as' => 'kits.licenses.edit', - 'uses' => 'Kits\PredefinedKitsController@editLicense', - - ] - ); + Route::put('licenses/{license_id}', + [Kits\PredefinedKitsController::class, 'updateLicense'] + )->name('kits.licenses.update'); - Route::delete('licenses/{license_id}', - [ - 'as' => 'kits.licenses.detach', - 'uses' => 'Kits\PredefinedKitsController@detachLicense', - ] - ); + Route::get('licenses/{license_id}/edit', + [Kits\PredefinedKitsController::class, 'editLicense'] + )->name('kits.licenses.edit'); + + Route::delete('licenses/{license_id}', + [Kits\PredefinedKitsController::class, 'detachLicense'] + )->name('kits.licenses.detach'); - // Models - - Route::put('models/{model_id}', - [ - 'as' => 'kits.models.update', - 'uses' => 'Kits\PredefinedKitsController@updateModel', - 'parameters' => [2 => 'kit_id', 1 => 'model_id'] - ] - ); - - Route::get('models/{model_id}/edit', - [ - 'as' => 'kits.models.edit', - 'uses' => 'Kits\PredefinedKitsController@editModel', - - ] - ); - Route::delete('models/{model_id}', - [ - 'as' => 'kits.models.detach', - 'uses' => 'Kits\PredefinedKitsController@detachModel', - ] - ); + Route::put('models/{model_id}', + [Kits\PredefinedKitsController::class, 'updateModel'] + )/* ->parameters([2 => 'kit_id', 1 => 'model_id'])*/->name('kits.models.update'); + Route::get('models/{model_id}/edit', + [Kits\PredefinedKitsController::class, 'editModel'] + )->name('kits.models.edit'); + + Route::delete('models/{model_id}', + [Kits\PredefinedKitsController::class, 'detachModel'] + )->name('kits.models.detach'); // Consumables - Route::put('consumables/{consumable_id}', - [ - 'as' => 'kits.consumables.update', - 'uses' => 'Kits\PredefinedKitsController@updateConsumable', - 'parameters' => [2 => 'kit_id', 1 => 'consumable_id'] - ] - ); - - Route::get('consumables/{consumable_id}/edit', - [ - 'as' => 'kits.consumables.edit', - 'uses' => 'Kits\PredefinedKitsController@editConsumable', - - ] - ); + Route::put('consumables/{consumable_id}', + [Kits\PredefinedKitsController::class, 'updateConsumable'] + )/*->parameters([2 => 'kit_id', 1 => 'consumable_id'])*/->name('kits.consumables.update'); - Route::delete('consumables/{consumable_id}', - [ - 'as' => 'kits.consumables.detach', - 'uses' => 'Kits\PredefinedKitsController@detachConsumable', - ] - ); + Route::get('consumables/{consumable_id}/edit', + [Kits\PredefinedKitsController::class, 'editConsumable'] + )->name('kits.consumables.edit'); + Route::delete('consumables/{consumable_id}', + [Kits\PredefinedKitsController::class, 'detachConsumable'] + )->name('kits.consumables.detach'); // Accessories - Route::put('accessories/{accessory_id}', - [ - 'as' => 'kits.accessories.update', - 'uses' => 'Kits\PredefinedKitsController@updateAccessory', - 'parameters' => [2 => 'kit_id', 1 => 'accessory_id'] - ] - ); + Route::put('accessories/{accessory_id}', + [Kits\PredefinedKitsController::class, 'updateAccessory'] + )/*->parameters([2 => 'kit_id', 1 => 'accessory_id'])*/->name('kits.accessories.update'); - Route::get('accessories/{accessory_id}/edit', - [ - 'as' => 'kits.accessories.edit', - 'uses' => 'Kits\PredefinedKitsController@editAccessory', - - ] - ); + Route::get('accessories/{accessory_id}/edit', + [Kits\PredefinedKitsController::class, 'editAccessory'] + )->name('kits.accessories.edit'); - Route::delete('accessories/{accessory_id}', - [ - 'as' => 'kits.accessories.detach', - 'uses' => 'Kits\PredefinedKitsController@detachAccessory', - ] - ); + Route::delete('accessories/{accessory_id}', + [Kits\PredefinedKitsController::class, 'detachAccessory'] + )->name('kits.accessories.detach'); Route::get('checkout', - [ - 'as' => 'kits.checkout.show', - 'uses' => 'Kits\CheckoutKitController@showCheckout', - ] - ); + [Kits\CheckoutKitController::class, 'showCheckout'] + )->name('kits.checkout.show'); Route::post('checkout', - [ - 'as' => 'kits.checkout.store', - 'uses' => 'Kits\CheckoutKitController@store', - ] - ); -}); // kits \ No newline at end of file + [Kits\CheckoutKitController::class, 'store'] + )->name('kits.checkout.store'); +}); // kits diff --git a/routes/web/licenses.php b/routes/web/licenses.php index ce046c3a3c..ebcb5a2b2b 100644 --- a/routes/web/licenses.php +++ b/routes/web/licenses.php @@ -1,48 +1,45 @@ 'licenses', 'middleware' => ['auth'] ], function () { +// Licenses +Route::group(['prefix' => 'licenses', 'middleware' => ['auth']], function () { + Route::get('{licenseId}/clone', [Licenses\LicensesController::class, 'getClone'])->name('clone/license'); - Route::get('{licenseId}/clone', [ 'as' => 'clone/license', 'uses' => 'Licenses\LicensesController@getClone' ]); - - Route::get('{licenseId}/freecheckout', [ - 'as' => 'licenses.freecheckout', - 'uses' => 'Licenses\LicensesController@getFreeLicense' - ]); - Route::get('{licenseId}/checkout/{seatId?}', [ - 'as' => 'licenses.checkout', - 'uses' => 'Licenses\LicenseCheckoutController@create' - ]); + Route::get('{licenseId}/freecheckout', + [Licenses\LicensesController::class, 'getFreeLicense'] + )->name('licenses.freecheckout'); + Route::get('{licenseId}/checkout/{seatId?}', + [Licenses\LicenseCheckoutController::class, 'create'] + )->name('licenses.checkout'); Route::post( '{licenseId}/checkout/{seatId?}', - [ 'as' => 'licenses.checkout', 'uses' => 'Licenses\LicenseCheckoutController@store' ] - ); - Route::get('{licenseSeatId}/checkin/{backto?}', [ - 'as' => 'licenses.checkin', - 'uses' => 'Licenses\LicenseCheckinController@create' - ]); + [Licenses\LicenseCheckoutController::class, 'store'] + ); //name() would duplicate here, so we skip it. + Route::get('{licenseSeatId}/checkin/{backto?}', + [Licenses\LicenseCheckinController::class, 'create'] + )->name('licenses.checkin'); - Route::post('{licenseId}/checkin/{backto?}', [ - 'as' => 'licenses.checkin.save', - 'uses' => 'Licenses\LicenseCheckinController@store' - ]); + Route::post('{licenseId}/checkin/{backto?}', + [Licenses\LicenseCheckinController::class, 'store'] + )->name('licenses.checkin.save'); Route::post( '{licenseId}/upload', - [ 'as' => 'upload/license', 'uses' => 'Licenses\LicenseFilesController@store' ] - ); + [Licenses\LicenseFilesController::class, 'store'] + )->name('upload/license'); Route::delete( '{licenseId}/deletefile/{fileId}', - [ 'as' => 'delete/licensefile', 'uses' => 'Licenses\LicenseFilesController@destroy' ] - ); + [Licenses\LicenseFilesController::class, 'destroy'] + )->name('delete/licensefile'); Route::get( '{licenseId}/showfile/{fileId}/{download?}', - [ 'as' => 'show.licensefile', 'uses' => 'Licenses\LicenseFilesController@show' ] - ); + [Licenses\LicenseFilesController::class, 'show'] + )->name('show.licensefile'); }); -Route::resource('licenses', 'Licenses\LicensesController', [ +Route::resource('licenses', Licenses\LicensesController::class, [ 'middleware' => ['auth'], - 'parameters' => ['license' => 'license_id'] + 'parameters' => ['license' => 'license_id'], ]); diff --git a/routes/web/models.php b/routes/web/models.php index a491c395da..e1acd9bad3 100644 --- a/routes/web/models.php +++ b/routes/web/models.php @@ -1,19 +1,82 @@ 'models', 'middleware' => ['auth'] ], function () { +use App\Http\Controllers\AssetModelsController; +use App\Http\Controllers\BulkAssetModelsController; +use Illuminate\Support\Facades\Route; + +// Asset Model Management + + +Route::group(['prefix' => 'models', 'middleware' => ['auth']], function () { + + Route::get( + '{modelId}/clone', + [ + AssetModelsController::class, + 'getClone' + ] + )->name('clone/model'); + + Route::post( + '{modelId}/clone', + [ + AssetModelsController::class, + 'postCreate' + ] + )->name('clone/model'); + + Route::get( + '{modelId}/view', + [ + AssetModelsController::class, + 'getView' + ] + )->name('view/model'); + + Route::get( + '{modelID}/restore', + [ + AssetModelsController::class, + 'getRestore' + ] + )->name('restore/model'); + + Route::get( + '{modelId}/custom_fields', + [ + AssetModelsController::class, + 'getCustomFields' + ] + )->name('custom_fields/model'); + + Route::post( + 'bulkedit', + [ + BulkAssetModelsController::class, + 'edit' + ] + )->name('models.bulkedit.index'); + + Route::post( + 'bulksave', + [ + BulkAssetModelsController::class, + 'update' + ] + )->name('models.bulkedit.store'); + + Route::post( + 'bulkdelete', + [ + BulkAssetModelsController::class, + 'destroy' + ] + )->name('models.bulkdelete.store'); + - Route::get('{modelId}/clone', [ 'as' => 'clone/model', 'uses' => 'AssetModelsController@getClone' ]); - Route::post('{modelId}/clone', 'AssetModelsController@postCreate'); - Route::get('{modelId}/view', [ 'as' => 'view/model', 'uses' => 'AssetModelsController@getView' ]); - Route::get('{modelID}/restore', [ 'as' => 'restore/model', 'uses' => 'AssetModelsController@getRestore', 'middleware' => ['authorize:superuser'] ]); - Route::get('{modelId}/custom_fields', ['as' => 'custom_fields/model','uses' => 'AssetModelsController@getCustomFields']); - Route::post('bulkedit', ['as' => 'models.bulkedit.index','uses' => 'BulkAssetModelsController@edit']); - Route::post('bulksave', ['as' => 'models.bulkedit.store','uses' => 'BulkAssetModelsController@update']); - Route::post('bulkdelete', ['as' => 'models.bulkdelete.store','uses' => 'BulkAssetModelsController@destroy']); }); -Route::resource('models', 'AssetModelsController', [ +Route::resource('models', AssetModelsController::class, [ 'middleware' => ['auth'], - 'parameters' => ['model' => 'model_id'] + 'parameters' => ['model' => 'model_id'], ]); diff --git a/routes/web/users.php b/routes/web/users.php index fd0ef77158..af856d725a 100644 --- a/routes/web/users.php +++ b/routes/web/users.php @@ -1,68 +1,137 @@ 'users', 'middleware' => ['auth']], function () { +use App\Http\Controllers\Users; +use Illuminate\Support\Facades\Route; - Route::get('ldap', ['as' => 'ldap/user', 'uses' => 'Users\LDAPImportController@create' ]); - Route::post('ldap', 'Users\LDAPImportController@store'); - Route::get('export', [ 'as' => 'users.export', 'uses' => 'Users\UsersController@getExportUserCsv' ]); - Route::get('{userId}/clone', [ 'as' => 'clone/user', 'uses' => 'Users\UsersController@getClone' ]); - Route::post('{userId}/clone', [ 'uses' => 'Users\UsersController@postCreate' ]); - Route::get('{userId}/restore', [ 'as' => 'restore/user', 'uses' => 'Users\UsersController@getRestore' ]); - Route::get('{userId}/unsuspend', [ 'as' => 'unsuspend/user', 'uses' => 'Users\UsersController@getUnsuspend' ]); - Route::post('{userId}/upload', [ 'as' => 'upload/user', 'uses' => 'Users\UserFilesController@store' ]); - Route::delete( - '{userId}/deletefile/{fileId}', - [ 'as' => 'userfile.destroy', 'uses' => 'Users\UserFilesController@destroy' ] +// User Management + +Route::group(['prefix' => 'users', 'middleware' => ['auth']], function () { + + Route::get( + 'ldap', + [ + Users\LDAPImportController::class, + 'create' + ] + )->name('ldap/user'); + + Route::post( + 'ldap', + [ + Users\LDAPImportController::class, + 'store' + ] ); + Route::get( + 'export', + [ + Users\UsersController::class, + 'getExportUserCsv' + ] + )->name('users.export'); + + Route::get( + '{userId}/clone', + [ + Users\UsersController::class, + 'getClone' + ] + )->name('clone/user'); + + Route::post( + '{userId}/clone', + [ + Users\UsersController::class, + 'postCreate' + ] + )->name('clone/user'); + + Route::get( + '{userId}/restore', + [ + Users\UsersController::class, + 'getRestore' + ] + )->name('restore/user'); + + Route::get( + '{userId}/unsuspend', + [ + Users\UsersController::class, + 'getUnsuspend' + ] + )->name('unsuspend/user'); + + Route::post( + '{userId}/upload', + [ + Users\UserFilesController::class, + 'store' + ] + )->name('upload/user'); + + Route::delete( + '{userId}/deletefile/{fileId}', + [ + Users\UserFilesController::class, + 'destroy' + ] + )->name('userfile.destroy'); + + Route::get( + '{userId}/showfile/{fileId}', + [ + Users\UserFilesController::class, + 'show' + ] + )->name('show/userfile'); Route::post( '{userId}/password', [ - 'as' => 'users.password', - 'uses' => 'Users\UsersController@sendPasswordReset', + Users\UsersController::class, + 'sendPasswordReset' ] - ); - + )->name('users.password'); Route::get( '{userId}/print', - [ 'as' => 'users.print', 'uses' => 'Users\UsersController@printInventory' ] - ); - - - Route::get( - '{userId}/showfile/{fileId}', - [ 'as' => 'show/userfile', 'uses' => 'Users\UserFilesController@show' ] - ); + [ + Users\UsersController::class, + 'printInventory' + ] + )->name('users.print'); Route::post( 'bulkedit', [ - 'as' => 'users/bulkedit', - 'uses' => 'Users\BulkUsersController@edit', + Users\BulkUsersController::class, + 'edit' ] - ); + )->name('users/bulkedit'); + + Route::post( 'bulksave', [ - 'as' => 'users/bulksave', - 'uses' => 'Users\BulkUsersController@destroy', + Users\BulkUsersController::class, + 'destroy' ] - ); + )->name('users/bulksave'); + Route::post( 'bulkeditsave', [ - 'as' => 'users/bulkeditsave', - 'uses' => 'Users\BulkUsersController@update', + Users\BulkUsersController::class, + 'update' ] - ); + )->name('users/bulkeditsave'); }); -Route::resource('users', 'Users\UsersController', [ +Route::resource('users', Users\UsersController::class, [ 'middleware' => ['auth'], - 'parameters' => ['user' => 'user_id'] + 'parameters' => ['user' => 'user_id'], ]); diff --git a/storage/framework/.gitignore b/storage/framework/.gitignore index 953edb7a99..05c4471f2b 100755 --- a/storage/framework/.gitignore +++ b/storage/framework/.gitignore @@ -1,7 +1,9 @@ -config.php -routes.php compiled.php -services.json -events.scanned.php -routes.scanned.php +config.php down +events.scanned.php +maintenance.php +routes.php +routes.scanned.php +schedule-* +services.json diff --git a/tests/TestCase.php b/tests/TestCase.php index 7b3c65c174..c0e60bde33 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -18,16 +18,16 @@ class TestCase extends Illuminate\Foundation\Testing\TestCase { $app = require __DIR__.'/../bootstrap/app.php'; $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap(); + return $app; } - - public function setUp() + protected function setUp(): void { parent::setUp(); } - public function tearDown() + protected function tearDown(): void { //Artisan::call('migrate:reset'); parent::tearDown(); diff --git a/tests/_bootstrap.php b/tests/_bootstrap.php index 243f9c85bc..074505f279 100644 --- a/tests/_bootstrap.php +++ b/tests/_bootstrap.php @@ -1,2 +1,3 @@ loadSessionSnapshot('login')) return; + // if snapshot exists - skipping login + //if ($I->loadSessionSnapshot('login')) return; - // logging in - $I->amOnPage('/login'); - $I->fillField('username', 'snipe'); - $I->fillField('password', 'password'); - $I->click('Login'); - //$I->saveSessionSnapshot('login'); + // logging in + $I->amOnPage('/login'); + $I->fillField('username', 'snipe'); + $I->fillField('password', 'password'); + $I->click('Login'); + //$I->saveSessionSnapshot('login'); } } diff --git a/tests/_support/ApiTester.php b/tests/_support/ApiTester.php index 1d6f6f18ff..f76364bc19 100644 --- a/tests/_support/ApiTester.php +++ b/tests/_support/ApiTester.php @@ -1,6 +1,5 @@ createPersonalAccessClient($user->id, 'Codeception API Test Client', @@ -54,6 +52,7 @@ class ApiTester extends \Codeception\Actor { unset($array['created_at']); unset($array['updated_at']); + return $array; } } diff --git a/tests/_support/FunctionalTester.php b/tests/_support/FunctionalTester.php index 937ce41d8c..7eabf4cf4b 100644 --- a/tests/_support/FunctionalTester.php +++ b/tests/_support/FunctionalTester.php @@ -14,8 +14,7 @@ use App\Models\Manufacturer; use App\Models\Supplier; use App\Models\User; - - /** +/** * Inherited Methods * @method void wantToTest($text) * @method void wantTo($text) @@ -29,33 +28,32 @@ use App\Models\Manufacturer; * @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL) * * @SuppressWarnings(PHPMD) -*/ + */ class FunctionalTester extends \Codeception\Actor { use _generated\FunctionalTesterActions; - /** - * Define custom actions here - */ - + /** + * Define custom actions here + */ public function getCompanyId() { - return Company::inRandomOrder()->first()->id; + return Company::inRandomOrder()->first()->id; } public function getCategoryId() { - return Category::inRandomOrder()->first()->id; + return Category::inRandomOrder()->first()->id; } public function getManufacturerId() { - return Manufacturer::inRandomOrder()->first()->id; + return Manufacturer::inRandomOrder()->first()->id; } public function getLocationId() { - return Location::inRandomOrder()->first()->id; + return Location::inRandomOrder()->first()->id; } /** @@ -63,7 +61,7 @@ class FunctionalTester extends \Codeception\Actor */ public function getAccessoryId() { - return Accessory::inRandomOrder()->first()->id; + return Accessory::inRandomOrder()->first()->id; } /** diff --git a/tests/_support/Helper/Acceptance.php b/tests/_support/Helper/Acceptance.php index 65b94215e3..2dd1562b13 100644 --- a/tests/_support/Helper/Acceptance.php +++ b/tests/_support/Helper/Acceptance.php @@ -1,4 +1,5 @@ */ - namespace Helper; use Codeception\TestCase; @@ -61,25 +60,25 @@ class HTMLValidator extends \Codeception\Module private function validateByVNU($html) { $javaPath = $this->_getConfig('javaPath'); - if (!$javaPath) { + if (! $javaPath) { $javaPath = 'java'; } $vnuPath = $this->_getConfig('vnuPath'); - if (!$vnuPath) { + if (! $vnuPath) { $vnuPath = '/usr/local/bin/vnu.jar'; } - $filename = DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . uniqid('html-validate') . '.html'; + $filename = DIRECTORY_SEPARATOR.'tmp'.DIRECTORY_SEPARATOR.uniqid('html-validate').'.html'; file_put_contents($filename, $html); - exec($javaPath . " -Xss1024k -jar " . $vnuPath . " --format json " . $filename . " 2>&1", $return); + exec($javaPath.' -Xss1024k -jar '.$vnuPath.' --format json '.$filename.' 2>&1', $return); $data = json_decode($return[0], true); - if (!$data || !isset($data['messages']) || !is_array($data['messages'])) { - throw new \Exception('Invalid data returned from validation service: ' . $return); + if (! $data || ! isset($data['messages']) || ! is_array($data['messages'])) { + throw new \Exception('Invalid data returned from validation service: '.$return); } + return $data['messages']; } - /** * @return string * @throws \Codeception\Exception\ModuleException @@ -87,12 +86,13 @@ class HTMLValidator extends \Codeception\Module */ private function getPageSource() { - if (!$this->hasModule('WebDriver')) { + if (! $this->hasModule('WebDriver')) { throw new \Exception('This validator needs WebDriver to work'); } /** @var \Codeception\Module\WebDriver $webdriver */ $webdriver = $this->getModule('WebDriver'); + return $webdriver->webDriver->getPageSource(); } @@ -106,27 +106,28 @@ class HTMLValidator extends \Codeception\Module $messages = $this->validateByVNU($source); } catch (\Exception $e) { $this->fail($e->getMessage()); + return; } $failMessages = []; - $lines = explode("\n", $source); + $lines = explode("\n", $source); foreach ($messages as $message) { if ($message['type'] == 'error') { - $formattedMsg = '- Line ' . $message['lastLine'] . ', column ' . $message['lastColumn'] . ': ' . - $message['message'] . "\n > " . $lines[$message['lastLine'] - 1]; - $ignoring = false; + $formattedMsg = '- Line '.$message['lastLine'].', column '.$message['lastColumn'].': '. + $message['message']."\n > ".$lines[$message['lastLine'] - 1]; + $ignoring = false; foreach ($ignoreMessages as $ignoreMessage) { if (mb_stripos($formattedMsg, $ignoreMessage) !== false) { $ignoring = true; } } - if (!$ignoring) { + if (! $ignoring) { $failMessages[] = $formattedMsg; } } } if (count($failMessages) > 0) { - \PHPUnit_Framework_Assert::fail('Invalid HTML: ' . "\n" . implode("\n", $failMessages)); + \PHPUnit_Framework_Assert::fail('Invalid HTML: '."\n".implode("\n", $failMessages)); } } } diff --git a/tests/_support/Helper/Unit.php b/tests/_support/Helper/Unit.php index 6064d37327..4d27aa3599 100644 --- a/tests/_support/Helper/Unit.php +++ b/tests/_support/Helper/Unit.php @@ -1,4 +1,5 @@ wantTo('ensure that the accessories listing page loads without errors'); $I->lookForwardTo('seeing it load without errors'); $I->amOnPage('/accessories'); $I->waitForElement('.table', 5); // secs -$I->seeNumberOfElements('table[name="accessories"] tr', [5,30]); +$I->seeNumberOfElements('table[name="accessories"] tr', [5, 30]); $I->seeInTitle('Accessories'); $I->see('Accessories'); $I->seeInPageSource('accessories/create'); diff --git a/tests/acceptance/AssetsCept.php b/tests/acceptance/AssetsCept.php index a4b4c81efb..6cc39e028c 100644 --- a/tests/acceptance/AssetsCept.php +++ b/tests/acceptance/AssetsCept.php @@ -1,4 +1,5 @@ am('logged in user'); @@ -7,14 +8,13 @@ $I->amGoingTo('go to the assets listing page'); $I->lookForwardTo('seeing it load without errors'); $I->amOnPage('/hardware'); $I->waitForElement('.table', 5); // secs -$I->seeNumberOfElements('table[name="assets"] tr', [5,50]); +$I->seeNumberOfElements('table[name="assets"] tr', [5, 50]); $I->seeInTitle('Assets'); $I->see('Assets'); $I->seeInPageSource('hardware/create'); $I->dontSee('Assets', '.page-header'); $I->see('Assets', 'h1.pull-left'); - /* Create Form */ $I->wantTo('ensure that the create assets form loads without errors'); $I->lookForwardTo('seeing it load without errors'); diff --git a/tests/acceptance/AssetsCest.php b/tests/acceptance/AssetsCest.php index 6939f007da..51011ce830 100644 --- a/tests/acceptance/AssetsCest.php +++ b/tests/acceptance/AssetsCest.php @@ -1,4 +1,4 @@ -am('logged in user'); @@ -16,7 +15,7 @@ class AssetsCest $I->lookForwardTo('seeing it load without errors'); $I->amOnPage('/hardware'); $I->waitForElement('.table', 20); // secs - $I->seeNumberOfElements('table[name="assets"] tr', [5,50]); + $I->seeNumberOfElements('table[name="assets"] tr', [5, 50]); $I->seeInTitle(trans('general.assets')); $I->see(trans('general.assets')); $I->seeInPageSource('hardware/create'); diff --git a/tests/acceptance/CategoriesCept.php b/tests/acceptance/CategoriesCept.php index 06d9074105..75a6d2be11 100644 --- a/tests/acceptance/CategoriesCept.php +++ b/tests/acceptance/CategoriesCept.php @@ -1,4 +1,5 @@ am('logged in user'); @@ -6,7 +7,7 @@ $I->wantTo('ensure that the categories listing page loads without errors'); $I->lookForwardTo('seeing it load without errors'); $I->amOnPage('/categories'); $I->waitForElement('.table', 5); // secs -$I->seeNumberOfElements('table[name="categories"] tr', [5,30]); +$I->seeNumberOfElements('table[name="categories"] tr', [5, 30]); $I->seeInTitle('Categories'); $I->see('Categories'); $I->seeInPageSource('/categories/create'); diff --git a/tests/acceptance/CompaniesCept.php b/tests/acceptance/CompaniesCept.php index 139e960185..98a06a6bfb 100644 --- a/tests/acceptance/CompaniesCept.php +++ b/tests/acceptance/CompaniesCept.php @@ -1,4 +1,5 @@ wantTo('ensure that the company listing page loads without errors'); $I->lookForwardTo('seeing it load without errors'); $I->amOnPage('/companies'); $I->waitForElement('.table', 5); // secs -$I->seeNumberOfElements('table[name="companies"] tr', [5,30]); +$I->seeNumberOfElements('table[name="companies"] tr', [5, 30]); $I->seeInTitle('Companies'); $I->see('Companies'); $I->seeInPageSource('companies/create'); diff --git a/tests/acceptance/ConsumablesCept.php b/tests/acceptance/ConsumablesCept.php index 42d6d58293..9461c232c3 100644 --- a/tests/acceptance/ConsumablesCept.php +++ b/tests/acceptance/ConsumablesCept.php @@ -1,4 +1,5 @@ am('logged in user'); @@ -6,7 +7,7 @@ $I->wantTo('ensure that the consumables listing page loads without errors'); $I->lookForwardTo('seeing it load without errors'); $I->amOnPage('/consumables'); $I->waitForElement('.table', 5); // secs -$I->seeNumberOfElements('table[name="consumables"] tr', [5,30]); +$I->seeNumberOfElements('table[name="consumables"] tr', [5, 30]); $I->seeInTitle('Consumables'); $I->see('Consumables'); $I->seeInPageSource('/consumables/create'); diff --git a/tests/acceptance/CustomfieldsCept.php b/tests/acceptance/CustomfieldsCept.php index c17ef60c3a..9526316999 100644 --- a/tests/acceptance/CustomfieldsCept.php +++ b/tests/acceptance/CustomfieldsCept.php @@ -1,4 +1,5 @@ am('logged in user'); diff --git a/tests/acceptance/DepartmentsCept.php b/tests/acceptance/DepartmentsCept.php index 6549eac7ce..e9f6fd6b9c 100644 --- a/tests/acceptance/DepartmentsCept.php +++ b/tests/acceptance/DepartmentsCept.php @@ -1,4 +1,5 @@ wantTo('ensure that the department listing page loads without errors'); $I->lookForwardTo('seeing it load without errors'); $I->amOnPage('/departments'); $I->waitForElement('.table', 5); // secs -$I->seeNumberOfElements('table[name="departments"] tr', [5,30]); +$I->seeNumberOfElements('table[name="departments"] tr', [5, 30]); $I->seeInTitle('Departments'); $I->see('Departments'); $I->seeInPageSource('departments/create'); diff --git a/tests/acceptance/DepreciationsCept.php b/tests/acceptance/DepreciationsCept.php index 710e36ac32..d0f43ad4e5 100644 --- a/tests/acceptance/DepreciationsCept.php +++ b/tests/acceptance/DepreciationsCept.php @@ -1,4 +1,5 @@ am('logged in user'); @@ -8,7 +9,7 @@ $I->lookForwardTo('seeing it load without errors'); $I->amOnPage('/depreciations'); $I->seeInTitle('Depreciations'); $I->waitForElement('.table', 5); // secs -$I->seeNumberOfElements('table[name="depreciations"] tbody tr', [1,5]); +$I->seeNumberOfElements('table[name="depreciations"] tbody tr', [1, 5]); $I->seeInPageSource('/depreciations/create'); $I->dontSee('Depreciations', '.page-header'); $I->see('Depreciations', 'h1.pull-left'); diff --git a/tests/acceptance/LocationsCept.php b/tests/acceptance/LocationsCept.php index 31c33a4c21..600b5c2822 100644 --- a/tests/acceptance/LocationsCept.php +++ b/tests/acceptance/LocationsCept.php @@ -1,4 +1,5 @@ am('logged in user'); @@ -6,14 +7,13 @@ $I->wantTo('ensure that the locations listing page loads without errors'); $I->lookForwardTo('seeing it load without errors'); $I->amOnPage('/locations'); $I->waitForElement('.table', 5); // secs -$I->seeNumberOfElements('tr', [5,30]); +$I->seeNumberOfElements('tr', [5, 30]); $I->seeInTitle('Locations'); $I->see('Locations'); $I->seeInPageSource('/locations/create'); $I->dontSee('Locations', '.page-header'); $I->see('Locations', 'h1.pull-left'); - /* Create Form */ $I->wantTo('ensure that the create location form loads without errors'); $I->lookForwardTo('seeing it load without errors'); diff --git a/tests/acceptance/ManufacturersCept.php b/tests/acceptance/ManufacturersCept.php index 3aed82c1da..69d0c0e6da 100644 --- a/tests/acceptance/ManufacturersCept.php +++ b/tests/acceptance/ManufacturersCept.php @@ -1,18 +1,18 @@ am('logged in user'); $I->wantTo('ensure that the manufacturers listing page loads without errors'); $I->lookForwardTo('seeing it load without errors'); $I->amOnPage('/manufacturers'); -$I->seeNumberOfElements('table[name="manufacturers"] tr', [5,30]); +$I->seeNumberOfElements('table[name="manufacturers"] tr', [5, 30]); $I->see('Manufacturers'); $I->seeInTitle('Manufacturers'); $I->seeInPageSource('manufacturers/create'); $I->dontSee('Manufacturers', '.page-header'); $I->see('Manufacturers', 'h1.pull-left'); - /* Create Form */ $I->wantTo('ensure that the create manufacturer form loads without errors'); $I->lookForwardTo('seeing it load without errors'); diff --git a/tests/acceptance/StatuslabelsCept.php b/tests/acceptance/StatuslabelsCept.php index 70b97c26b2..224a713250 100644 --- a/tests/acceptance/StatuslabelsCept.php +++ b/tests/acceptance/StatuslabelsCept.php @@ -1,4 +1,5 @@ am('logged in user'); @@ -6,7 +7,7 @@ $I->wantTo('ensure the status labels listing page loads without errors'); $I->lookForwardTo('seeing it load without errors'); $I->amOnPage('/statuslabels'); $I->waitForElement('.table', 5); // secs -$I->seeNumberOfElements('tr', [1,30]); +$I->seeNumberOfElements('tr', [1, 30]); $I->seeInTitle('Status Labels'); $I->see('Status Labels'); $I->seeInPageSource('statuslabels/create'); diff --git a/tests/acceptance/SuppliersCept.php b/tests/acceptance/SuppliersCept.php index 0aed96cf9f..59840dfd9d 100644 --- a/tests/acceptance/SuppliersCept.php +++ b/tests/acceptance/SuppliersCept.php @@ -1,4 +1,5 @@ am('logged in user'); @@ -6,7 +7,7 @@ $I->wantTo('ensure that the suppliers listing page loads without errors'); $I->lookForwardTo('seeing it load without errors'); $I->amOnPage('/suppliers'); $I->waitForElement('.table', 5); // secs -$I->seeNumberOfElements('table[name="suppliers"] tr', [5,25]); +$I->seeNumberOfElements('table[name="suppliers"] tr', [5, 25]); $I->seeInTitle('Suppliers'); $I->see('Suppliers'); $I->seeInPageSource('suppliers/create'); diff --git a/tests/acceptance/UsersCept.php b/tests/acceptance/UsersCept.php index 85d695b3eb..0c25a263d6 100644 --- a/tests/acceptance/UsersCept.php +++ b/tests/acceptance/UsersCept.php @@ -1,4 +1,5 @@ am('logged in user'); @@ -15,7 +16,6 @@ $I->dontSee('Users', '.page-header'); $I->see('Users', 'h1.pull-left'); $I->seeLink('Create New'); // matches Logout - /* Create form */ $I->am('logged in admin'); $I->wantTo('ensure that you get errors when you submit an incomplete form'); @@ -33,7 +33,6 @@ $I->submitForm('#userForm', [ $I->seeElement('.alert-danger'); $I->dontSeeInSource('<br><'); - /* Submit form and expect errors */ $I->click(['name' => 'email']); $I->click(['name' => 'username']); @@ -47,8 +46,6 @@ $I->submitForm('#userForm', [ $I->seeElement('.alert-danger'); $I->dontSeeInSource('<br><'); - - /* Submit form and expect success */ $I->wantTo('submit the form successfully'); $I->click(['name' => 'email']); diff --git a/tests/acceptance/_bootstrap.php b/tests/acceptance/_bootstrap.php index 8a88555806..62817a53c4 100644 --- a/tests/acceptance/_bootstrap.php +++ b/tests/acceptance/_bootstrap.php @@ -1,2 +1,3 @@ wantTo('Get a list of accessories'); // call @@ -40,9 +39,9 @@ class ApiAccessoriesCest { $I->wantTo('Create a new accessory'); - $temp_accessory = factory(\App\Models\Accessory::class)->states('apple-bt-keyboard')->make([ - 'name' => "Test Accessory Name", - 'company_id' => 2 + $temp_accessory = \App\Models\Accessory::factory()->appleBtKeyboard()->make([ + 'name' => 'Test Accessory Name', + 'company_id' => 2, ]); // setup @@ -68,22 +67,23 @@ class ApiAccessoriesCest // Put is routed to the same method in the controller // DO we actually need to test both? + /** @test */ public function updateAccessoryWithPatch(ApiTester $I, $scenario) { $I->wantTo('Update an accessory with PATCH'); // create - $accessory = factory(\App\Models\Accessory::class)->states('apple-bt-keyboard')->create([ + $accessory = \App\Models\Accessory::factory()->appleBtKeyboard()->create([ 'name' => 'Original Accessory Name', 'company_id' => 2, - 'location_id' => 3 + 'location_id' => 3, ]); $I->assertInstanceOf(\App\Models\Accessory::class, $accessory); - $temp_accessory = factory(\App\Models\Accessory::class)->states('microsoft-mouse')->make([ + $temp_accessory = \App\Models\Accessory::factory()->microsoftMouse()->make([ 'company_id' => 3, - 'name' => "updated accessory name", + 'name' => 'updated accessory name', 'location_id' => 1, ]); @@ -105,7 +105,7 @@ class ApiAccessoriesCest $I->assertNotEquals($accessory->name, $data['name']); // update - $I->sendPATCH('/accessories/' . $accessory->id, $data); + $I->sendPATCH('/accessories/'.$accessory->id, $data); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -121,7 +121,7 @@ class ApiAccessoriesCest $temp_accessory->updated_at = Carbon::parse($response->payload->updated_at); $temp_accessory->id = $accessory->id; // verify - $I->sendGET('/accessories/' . $accessory->id); + $I->sendGET('/accessories/'.$accessory->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); $I->seeResponseContainsJson((new AccessoriesTransformer)->transformAccessory($temp_accessory)); @@ -133,13 +133,13 @@ class ApiAccessoriesCest $I->wantTo('Delete an accessory'); // create - $accessory = factory(\App\Models\Accessory::class)->states('apple-bt-keyboard')->create([ - 'name' => "Soon to be deleted" + $accessory = \App\Models\Accessory::factory()->appleBtKeyboard()->create([ + 'name' => 'Soon to be deleted', ]); $I->assertInstanceOf(\App\Models\Accessory::class, $accessory); // delete - $I->sendDELETE('/accessories/' . $accessory->id); + $I->sendDELETE('/accessories/'.$accessory->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -148,7 +148,7 @@ class ApiAccessoriesCest $I->assertEquals(trans('admin/accessories/message.delete.success'), $response->messages); // verify, expect a 200 - $I->sendGET('/accessories/' . $accessory->id); + $I->sendGET('/accessories/'.$accessory->id); $I->seeResponseCodeIs(200); $I->seeResponseIsJson(); } diff --git a/tests/api/ApiAssetsCest.php b/tests/api/ApiAssetsCest.php index cfa5a9645b..554d4c4230 100644 --- a/tests/api/ApiAssetsCest.php +++ b/tests/api/ApiAssetsCest.php @@ -16,14 +16,13 @@ class ApiAssetsCest { $this->faker = \Faker\Factory::create(); $this->user = \App\Models\User::find(1); - Setting::getSettings()->time_display_format = "H:i"; + Setting::getSettings()->time_display_format = 'H:i'; $I->amBearerAuthenticated($I->getToken($this->user)); } /** @test */ public function indexAssets(ApiTester $I) { - $I->wantTo('Get a list of assets'); // call @@ -47,9 +46,9 @@ class ApiAssetsCest { $I->wantTo('Create a new asset'); - $temp_asset = factory(\App\Models\Asset::class)->states('laptop-mbp')->make([ - 'asset_tag' => "Test Asset Tag", - 'company_id' => 2 + $temp_asset = \App\Models\Asset::factory()->laptopMbp()->make([ + 'asset_tag' => 'Test Asset Tag', + 'company_id' => 2, ]); // setup @@ -82,15 +81,15 @@ class ApiAssetsCest $I->wantTo('Update an asset with PATCH'); // create - $asset = factory(\App\Models\Asset::class)->states('laptop-mbp')->create([ + $asset = \App\Models\Asset::factory()->laptopMbp()->create([ 'company_id' => 2, - 'rtd_location_id' => 3 + 'rtd_location_id' => 3, ]); $I->assertInstanceOf(\App\Models\Asset::class, $asset); - $temp_asset = factory(\App\Models\Asset::class)->states('laptop-air')->make([ + $temp_asset = \App\Models\Asset::factory()->laptopAir()->make([ 'company_id' => 3, - 'name' => "updated asset name", + 'name' => 'updated asset name', 'rtd_location_id' => 1, ]); @@ -115,7 +114,7 @@ class ApiAssetsCest $I->assertNotEquals($asset->name, $data['name']); // update - $I->sendPATCH('/hardware/' . $asset->id, $data); + $I->sendPATCH('/hardware/'.$asset->id, $data); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -133,7 +132,7 @@ class ApiAssetsCest $temp_asset->location_id = $response->payload->rtd_location_id; // verify - $I->sendGET('/hardware/' . $asset->id); + $I->sendGET('/hardware/'.$asset->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); $I->seeResponseContainsJson((new AssetsTransformer)->transformAsset($temp_asset)); @@ -145,11 +144,11 @@ class ApiAssetsCest $I->wantTo('Delete an asset'); // create - $asset = factory(\App\Models\Asset::class)->states('laptop-mbp')->create(); + $asset = \App\Models\Asset::factory()->laptopMbp()->create(); $I->assertInstanceOf(\App\Models\Asset::class, $asset); // delete - $I->sendDELETE('/hardware/' . $asset->id); + $I->sendDELETE('/hardware/'.$asset->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -158,7 +157,7 @@ class ApiAssetsCest $I->assertEquals(trans('admin/hardware/message.delete.success'), $response->messages); // verify, expect a 200 - $I->sendGET('/hardware/' . $asset->id); + $I->sendGET('/hardware/'.$asset->id); $I->seeResponseCodeIs(200); $I->seeResponseIsJson(); diff --git a/tests/api/ApiCategoriesCest.php b/tests/api/ApiCategoriesCest.php index d844f45e99..7605872a17 100644 --- a/tests/api/ApiCategoriesCest.php +++ b/tests/api/ApiCategoriesCest.php @@ -21,7 +21,6 @@ class ApiCategoriesCest /** @test */ public function indexCategorys(ApiTester $I) { - $I->wantTo('Get a list of categories'); // call @@ -31,7 +30,7 @@ class ApiCategoriesCest $response = json_decode($I->grabResponse(), true); // sample verify - $category = App\Models\Category::withCount('assets as assets_count','accessories as accessories_count','consumables as consumables_count','components as components_count','licenses as licenses_count') + $category = App\Models\Category::withCount('assets as assets_count', 'accessories as accessories_count', 'consumables as consumables_count', 'components as components_count', 'licenses as licenses_count') ->orderByDesc('created_at')->take(10)->get()->shuffle()->first(); $I->seeResponseContainsJson($I->removeTimestamps((new CategoriesTransformer)->transformCategory($category))); } @@ -41,8 +40,8 @@ class ApiCategoriesCest { $I->wantTo('Create a new category'); - $temp_category = factory(\App\Models\Category::class)->states('asset-laptop-category')->make([ - 'name' => "Test Category Tag", + $temp_category = \App\Models\Category::factory()->assetLaptopCategory()->make([ + 'name' => 'Test Category Tag', ]); // setup @@ -63,21 +62,21 @@ class ApiCategoriesCest // Put is routed to the same method in the controller // DO we actually need to test both? + /** @test */ public function updateCategoryWithPatch(ApiTester $I, $scenario) { $I->wantTo('Update an category with PATCH'); // create - $category = factory(\App\Models\Category::class)->states('asset-laptop-category') + $category = \App\Models\Category::factory()->assetLaptopCategory() ->create([ 'name' => 'Original Category Name', ]); $I->assertInstanceOf(\App\Models\Category::class, $category); - $temp_category = factory(\App\Models\Category::class) - ->states('accessory-mouse-category')->make([ - 'name' => "updated category name", + $temp_category = \App\Models\Category::factory()->accessoryMouseCategory()->make([ + 'name' => 'updated category name', ]); $data = [ @@ -92,7 +91,7 @@ class ApiCategoriesCest $I->assertNotEquals($category->name, $data['name']); // update - $I->sendPATCH('/categories/' . $category->id, $data); + $I->sendPATCH('/categories/'.$category->id, $data); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -108,11 +107,10 @@ class ApiCategoriesCest $temp_category->id = $category->id; // verify - $I->sendGET('/categories/' . $category->id); + $I->sendGET('/categories/'.$category->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); $I->seeResponseContainsJson((new CategoriesTransformer)->transformCategory($temp_category)); - } /** @test */ @@ -121,13 +119,13 @@ class ApiCategoriesCest $I->wantTo('Delete an category'); // create - $category = factory(\App\Models\Category::class)->states('asset-laptop-category')->create([ - 'name' => "Soon to be deleted" + $category = \App\Models\Category::factory()->assetLaptopCategory()->create([ + 'name' => 'Soon to be deleted', ]); $I->assertInstanceOf(\App\Models\Category::class, $category); // delete - $I->sendDELETE('/categories/' . $category->id); + $I->sendDELETE('/categories/'.$category->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -136,7 +134,7 @@ class ApiCategoriesCest $I->assertEquals(trans('admin/categories/message.delete.success'), $response->messages); // verify, expect a 200 - $I->sendGET('/categories/' . $category->id); + $I->sendGET('/categories/'.$category->id); $I->seeResponseCodeIs(200); $I->seeResponseIsJson(); } diff --git a/tests/api/ApiCheckoutAssetsCest.php b/tests/api/ApiCheckoutAssetsCest.php index e9588b38f8..48b4bd2335 100644 --- a/tests/api/ApiCheckoutAssetsCest.php +++ b/tests/api/ApiCheckoutAssetsCest.php @@ -20,17 +20,18 @@ class ApiCheckoutAssetsCest } /** @test */ - public function checkoutAssetToUser(ApiTester $I) { + public function checkoutAssetToUser(ApiTester $I) + { $I->wantTo('Check out an asset to a user'); //Grab an asset from the database that isn't checked out. $asset = Asset::whereNull('assigned_to')->first(); - $targetUser = factory('App\Models\User')->create(); + $targetUser = \App\Models\User::factory()->create(); $data = [ 'assigned_user' => $targetUser->id, - 'note' => "This is a test checkout note", - 'expected_checkin' => "2018-05-24", - 'name' => "Updated Asset Name", - 'checkout_to_type' => 'user' + 'note' => 'This is a test checkout note', + 'expected_checkin' => '2018-05-24', + 'name' => 'Updated Asset Name', + 'checkout_to_type' => 'user', ]; $I->sendPOST("/hardware/{$asset->id}/checkout", $data); $I->seeResponseIsJson(); @@ -45,28 +46,28 @@ class ApiCheckoutAssetsCest $I->seeResponseContainsJson([ 'assigned_to' => [ 'id' => $targetUser->id, - 'type' => 'user' + 'type' => 'user', ], - 'name' => "Updated Asset Name", - 'expected_checkin' => Helper::getFormattedDateObject('2018-05-24', 'date') + 'name' => 'Updated Asset Name', + 'expected_checkin' => Helper::getFormattedDateObject('2018-05-24', 'date'), ]); - } - /** @test */ - public function checkoutAssetToAsset(ApiTester $I) { + /** @test */ + public function checkoutAssetToAsset(ApiTester $I) + { $I->wantTo('Check out an asset to an asset'); //Grab an asset from the database that isn't checked out. $asset = Asset::whereNull('assigned_to') - ->where('model_id',8) + ->where('model_id', 8) ->where('status_id', Statuslabel::deployable()->first()->id) ->first(); // We need to make sure that this is an asset/model that doesn't require acceptance - $targetAsset = factory('App\Models\Asset')->states('desktop-macpro')->create([ - 'name' => "Test Asset For Checkout to" + $targetAsset = \App\Models\Asset::factory()->desktopMacpro()->create([ + 'name' => 'Test Asset For Checkout to', ]); $data = [ 'assigned_asset' => $targetAsset->id, - 'checkout_to_type' => 'asset' + 'checkout_to_type' => 'asset', ]; $I->sendPOST("/hardware/{$asset->id}/checkout", $data); $I->seeResponseIsJson(); @@ -81,26 +82,26 @@ class ApiCheckoutAssetsCest $I->seeResponseContainsJson([ 'assigned_to' => [ 'id' => $targetAsset->id, - 'type' => 'asset' - ] + 'type' => 'asset', + ], ]); - } - /** @test */ - public function checkoutAssetToLocation(ApiTester $I) { + /** @test */ + public function checkoutAssetToLocation(ApiTester $I) + { $I->wantTo('Check out an asset to an asset'); //Grab an asset from the database that isn't checked out. $asset = Asset::whereNull('assigned_to') - ->where('model_id',8) + ->where('model_id', 8) ->where('status_id', Statuslabel::deployable()->first()->id) ->first(); // We need to make sure that this is an asset/model that doesn't require acceptance - $targetLocation = factory('App\Models\Location')->create([ - 'name' => "Test Location for Checkout" + $targetLocation = \App\Models\Location::factory()->create([ + 'name' => 'Test Location for Checkout', ]); $data = [ 'assigned_location' => $targetLocation->id, - 'checkout_to_type' => 'location' + 'checkout_to_type' => 'location', ]; $I->sendPOST("/hardware/{$asset->id}/checkout", $data); $I->seeResponseIsJson(); @@ -115,20 +116,20 @@ class ApiCheckoutAssetsCest $I->seeResponseContainsJson([ 'assigned_to' => [ 'id' => $targetLocation->id, - 'type' => 'location' - ] + 'type' => 'location', + ], ]); - } /** @test */ - public function checkinAsset(ApiTester $I) { + public function checkinAsset(ApiTester $I) + { $I->wantTo('Checkin an asset that is currently checked out'); $asset = Asset::whereNotNull('assigned_to')->first(); $I->sendPOST("/hardware/{$asset->id}/checkin", [ - "note" => "Checkin Note" + 'note' => 'Checkin Note', ]); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -140,7 +141,7 @@ class ApiCheckoutAssetsCest // Verify $I->sendGET("/hardware/{$asset->id}"); $I->seeResponseContainsJson([ - 'assigned_to' => null + 'assigned_to' => null, ]); } } diff --git a/tests/api/ApiCompaniesCest.php b/tests/api/ApiCompaniesCest.php index a6ad1345e7..55fa5bc218 100644 --- a/tests/api/ApiCompaniesCest.php +++ b/tests/api/ApiCompaniesCest.php @@ -21,7 +21,6 @@ class ApiCompaniesCest /** @test */ public function indexCompanys(ApiTester $I) { - $I->wantTo('Get a list of companies'); // call @@ -32,7 +31,7 @@ class ApiCompaniesCest $response = json_decode($I->grabResponse(), true); // dd($response); // sample verify - $company = App\Models\Company::withCount('assets as assets_count','licenses as licenses_count','accessories as accessories_count','consumables as consumables_count','components as components_count','users as users_count') + $company = App\Models\Company::withCount('assets as assets_count', 'licenses as licenses_count', 'accessories as accessories_count', 'consumables as consumables_count', 'components as components_count', 'users as users_count') ->orderByDesc('created_at')->take(10)->get()->shuffle()->first(); $I->seeResponseContainsJson($I->removeTimestamps((new CompaniesTransformer)->transformCompany($company))); @@ -43,8 +42,8 @@ class ApiCompaniesCest { $I->wantTo('Create a new company'); - $temp_company = factory(\App\Models\Company::class)->make([ - 'name' => "Test Company Tag", + $temp_company = \App\Models\Company::factory()->make([ + 'name' => 'Test Company Tag', ]); // setup @@ -60,19 +59,20 @@ class ApiCompaniesCest // Put is routed to the same method in the controller // DO we actually need to test both? + /** @test */ public function updateCompanyWithPatch(ApiTester $I, $scenario) { $I->wantTo('Update an company with PATCH'); // create - $company = factory(\App\Models\Company::class)->create([ + $company = \App\Models\Company::factory()->create([ 'name' => 'Original Company Name', ]); $I->assertInstanceOf(\App\Models\Company::class, $company); - $temp_company = factory(\App\Models\Company::class)->make([ - 'name' => "updated company name", + $temp_company = \App\Models\Company::factory()->make([ + 'name' => 'updated company name', ]); $data = [ @@ -82,7 +82,7 @@ class ApiCompaniesCest $I->assertNotEquals($company->name, $data['name']); // update - $I->sendPATCH('/companies/' . $company->id, $data); + $I->sendPATCH('/companies/'.$company->id, $data); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -98,11 +98,10 @@ class ApiCompaniesCest $temp_company->id = $company->id; // verify - $I->sendGET('/companies/' . $company->id); + $I->sendGET('/companies/'.$company->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); $I->seeResponseContainsJson((new CompaniesTransformer)->transformCompany($temp_company)); - } /** @test */ @@ -111,13 +110,13 @@ class ApiCompaniesCest $I->wantTo('Delete an company'); // create - $company = factory(\App\Models\Company::class)->create([ - 'name' => "Soon to be deleted" + $company = \App\Models\Company::factory()->create([ + 'name' => 'Soon to be deleted', ]); $I->assertInstanceOf(\App\Models\Company::class, $company); // delete - $I->sendDELETE('/companies/' . $company->id); + $I->sendDELETE('/companies/'.$company->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -126,7 +125,7 @@ class ApiCompaniesCest $I->assertEquals(trans('admin/companies/message.delete.success'), $response->messages); // verify, expect a 200 - $I->sendGET('/companies/' . $company->id); + $I->sendGET('/companies/'.$company->id); $I->seeResponseCodeIs(200); $I->seeResponseIsJson(); } diff --git a/tests/api/ApiComponentsCest.php b/tests/api/ApiComponentsCest.php index 006b19e876..dea9ece186 100644 --- a/tests/api/ApiComponentsCest.php +++ b/tests/api/ApiComponentsCest.php @@ -40,9 +40,9 @@ class ApiComponentsCest { $I->wantTo('Create a new component'); - $temp_component = factory(\App\Models\Component::class)->states('ram-crucial4')->make([ - 'name' => "Test Component Name", - 'company_id' => 2 + $temp_component = \App\Models\Component::factory()->ramCrucial4()->make([ + 'name' => 'Test Component Name', + 'company_id' => 2, ]); // setup @@ -57,7 +57,7 @@ class ApiComponentsCest 'purchase_cost' => $temp_component->purchase_cost, 'purchase_date' => $temp_component->purchase_date, 'qty' => $temp_component->qty, - 'serial' => $temp_component->serial + 'serial' => $temp_component->serial, ]; // create @@ -68,22 +68,23 @@ class ApiComponentsCest // Put is routed to the same method in the controller // DO we actually need to test both? + /** @test */ public function updateComponentWithPatch(ApiTester $I, $scenario) { $I->wantTo('Update an component with PATCH'); // create - $component = factory(\App\Models\Component::class)->states('ram-crucial4')->create([ + $component = \App\Models\Component::factory()->ramCrucial4()->create([ 'name' => 'Original Component Name', 'company_id' => 2, - 'location_id' => 3 + 'location_id' => 3, ]); $I->assertInstanceOf(\App\Models\Component::class, $component); - $temp_component = factory(\App\Models\Component::class)->states('ssd-crucial240')->make([ + $temp_component = \App\Models\Component::factory()->ssdCrucial240()->make([ 'company_id' => 3, - 'name' => "updated component name", + 'name' => 'updated component name', 'location_id' => 1, ]); @@ -103,7 +104,7 @@ class ApiComponentsCest $I->assertNotEquals($component->name, $data['name']); // update - $I->sendPATCH('/components/' . $component->id, $data); + $I->sendPATCH('/components/'.$component->id, $data); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -119,7 +120,7 @@ class ApiComponentsCest $temp_component->updated_at = Carbon::parse($response->payload->updated_at); $temp_component->id = $component->id; // verify - $I->sendGET('/components/' . $component->id); + $I->sendGET('/components/'.$component->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); $I->seeResponseContainsJson((new ComponentsTransformer)->transformComponent($temp_component)); @@ -131,13 +132,13 @@ class ApiComponentsCest $I->wantTo('Delete an component'); // create - $component = factory(\App\Models\Component::class)->states('ram-crucial4')->create([ - 'name' => "Soon to be deleted" + $component = \App\Models\Component::factory()->ramCrucial4()->create([ + 'name' => 'Soon to be deleted', ]); $I->assertInstanceOf(\App\Models\Component::class, $component); // delete - $I->sendDELETE('/components/' . $component->id); + $I->sendDELETE('/components/'.$component->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -147,7 +148,7 @@ class ApiComponentsCest $I->assertEquals(trans('admin/components/message.delete.success'), $response->messages); // verify, expect a 200 - $I->sendGET('/components/' . $component->id); + $I->sendGET('/components/'.$component->id); $I->seeResponseCodeIs(200); $I->seeResponseIsJson(); diff --git a/tests/api/ApiConsumablesCest.php b/tests/api/ApiConsumablesCest.php index 73b431102c..8490c3a56e 100644 --- a/tests/api/ApiConsumablesCest.php +++ b/tests/api/ApiConsumablesCest.php @@ -40,9 +40,9 @@ class ApiConsumablesCest { $I->wantTo('Create a new consumable'); - $temp_consumable = factory(\App\Models\Consumable::class)->states('ink')->make([ - 'name' => "Test Consumable Name", - 'company_id' => 2 + $temp_consumable = \App\Models\Consumable::factory()->ink()->make([ + 'name' => 'Test Consumable Name', + 'company_id' => 2, ]); // setup @@ -67,22 +67,23 @@ class ApiConsumablesCest // Put is routed to the same method in the controller // DO we actually need to test both? + /** @test */ public function updateConsumableWithPatch(ApiTester $I, $scenario) { $I->wantTo('Update an consumable with PATCH'); // create - $consumable = factory(\App\Models\Consumable::class)->states('ink')->create([ + $consumable = \App\Models\Consumable::factory()->ink()->create([ 'name' => 'Original Consumable Name', 'company_id' => 2, - 'location_id' => 3 + 'location_id' => 3, ]); $I->assertInstanceOf(\App\Models\Consumable::class, $consumable); - $temp_consumable = factory(\App\Models\Consumable::class)->states('cardstock')->make([ + $temp_consumable = \App\Models\Consumable::factory()->cardstock()->make([ 'company_id' => 3, - 'name' => "updated consumable name", + 'name' => 'updated consumable name', 'location_id' => 1, ]); @@ -104,7 +105,7 @@ class ApiConsumablesCest $I->assertNotEquals($consumable->name, $data['name']); // update - $I->sendPATCH('/consumables/' . $consumable->id, $data); + $I->sendPATCH('/consumables/'.$consumable->id, $data); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -120,7 +121,7 @@ class ApiConsumablesCest $temp_consumable->updated_at = Carbon::parse($response->payload->updated_at); $temp_consumable->id = $consumable->id; // verify - $I->sendGET('/consumables/' . $consumable->id); + $I->sendGET('/consumables/'.$consumable->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); $I->seeResponseContainsJson((new ConsumablesTransformer)->transformConsumable($temp_consumable)); @@ -132,13 +133,13 @@ class ApiConsumablesCest $I->wantTo('Delete an consumable'); // create - $consumable = factory(\App\Models\Consumable::class)->states('ink')->create([ - 'name' => "Soon to be deleted" + $consumable = \App\Models\Consumable::factory()->ink()->create([ + 'name' => 'Soon to be deleted', ]); $I->assertInstanceOf(\App\Models\Consumable::class, $consumable); // delete - $I->sendDELETE('/consumables/' . $consumable->id); + $I->sendDELETE('/consumables/'.$consumable->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -147,7 +148,7 @@ class ApiConsumablesCest $I->assertEquals(trans('admin/consumables/message.delete.success'), $response->messages); // verify, expect a 200 - $I->sendGET('/consumables/' . $consumable->id); + $I->sendGET('/consumables/'.$consumable->id); $I->seeResponseCodeIs(200); $I->seeResponseIsJson(); } diff --git a/tests/api/ApiLicenseSeatsCest.php b/tests/api/ApiLicenseSeatsCest.php index 30c9ccaa92..664915bb4c 100644 --- a/tests/api/ApiLicenseSeatsCest.php +++ b/tests/api/ApiLicenseSeatsCest.php @@ -30,14 +30,14 @@ class ApiLicenseSeatsCest // sample verify $licenseSeats = App\Models\LicenseSeat::where('license_id', 1) - ->orderBy('id','desc')->take(10)->get(); + ->orderBy('id', 'desc')->take(10)->get(); // pick a random seat $licenseSeat = $licenseSeats->random(); // need the index in the original list so that the "name" field is determined correctly $licenseSeatNumber = 0; - foreach($licenseSeats as $index=>$seat) { + foreach ($licenseSeats as $index=>$seat) { if ($licenseSeat === $seat) { - $licenseSeatNumber = $index+1; + $licenseSeatNumber = $index + 1; } } $I->seeResponseContainsJson($I->removeTimestamps((new LicenseSeatsTransformer)->transformLicenseSeat($licenseSeat, $licenseSeatNumber))); @@ -69,7 +69,7 @@ class ApiLicenseSeatsCest $data = [ 'assigned_to' => $user->id, - 'note' => 'Test Checkout to User via API' + 'note' => 'Test Checkout to User via API', ]; // update @@ -95,7 +95,7 @@ class ApiLicenseSeatsCest $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); $I->seeResponseContainsJson([ - "action_type" => "checkout" + 'action_type' => 'checkout', ]); } @@ -110,7 +110,7 @@ class ApiLicenseSeatsCest $data = [ 'asset_id' => $asset->id, - 'note' => 'Test Checkout to Asset via API' + 'note' => 'Test Checkout to Asset via API', ]; // update @@ -136,7 +136,7 @@ class ApiLicenseSeatsCest $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); $I->seeResponseContainsJson([ - "action_type" => "checkout" + 'action_type' => 'checkout', ]); } @@ -153,7 +153,7 @@ class ApiLicenseSeatsCest $data = [ 'asset_id' => $asset->id, 'assigned_to' => $user->id, - 'note' => 'Test Checkout to User and Asset via API' + 'note' => 'Test Checkout to User and Asset via API', ]; // update @@ -179,7 +179,7 @@ class ApiLicenseSeatsCest $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); $I->seeResponseContainsJson([ - "action_type" => "checkout" + 'action_type' => 'checkout', ]); } } diff --git a/tests/api/ApiLicensesCest.php b/tests/api/ApiLicensesCest.php index db386d062c..0668e87628 100644 --- a/tests/api/ApiLicensesCest.php +++ b/tests/api/ApiLicensesCest.php @@ -41,10 +41,10 @@ class ApiLicensesCest { $I->wantTo('Create a new license'); - $temp_license = factory(\App\Models\License::class)->states('acrobat')->make([ - 'name' => "Test License Name", + $temp_license = \App\Models\License::factory()->acrobat()->make([ + 'name' => 'Test License Name', 'depreciation_id' => 3, - 'company_id' => 2 + 'company_id' => 2, ]); // setup @@ -77,22 +77,23 @@ class ApiLicensesCest // Put is routed to the same method in the controller // DO we actually need to test both? + /** @test */ public function updateLicenseWithPatch(ApiTester $I, $scenario) { $I->wantTo('Update a license with PATCH'); // create - $license = factory(\App\Models\License::class)->states('acrobat')->create([ + $license = \App\Models\License::factory()->acrobat()->create([ 'name' => 'Original License Name', 'depreciation_id' => 3, - 'company_id' => 2 + 'company_id' => 2, ]); $I->assertInstanceOf(\App\Models\License::class, $license); - $temp_license = factory(\App\Models\License::class)->states('office')->make([ + $temp_license = \App\Models\License::factory()->office()->make([ 'company_id' => 3, - 'depreciation_id' => 2 + 'depreciation_id' => 2, ]); $data = [ @@ -121,7 +122,7 @@ class ApiLicensesCest $I->assertNotEquals($license->name, $data['name']); // update - $I->sendPATCH('/licenses/' . $license->id, $data); + $I->sendPATCH('/licenses/'.$license->id, $data); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -134,7 +135,7 @@ class ApiLicensesCest $temp_license->updated_at = Carbon::parse($response->payload->updated_at); $temp_license->id = $license->id; // verify - $I->sendGET('/licenses/' . $license->id); + $I->sendGET('/licenses/'.$license->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); $I->seeResponseContainsJson((new LicensesTransformer)->transformLicense($temp_license)); @@ -146,8 +147,8 @@ class ApiLicensesCest $I->wantTo('Ensure a license with seats checked out cannot be deleted'); // create - $license = factory(\App\Models\License::class)->states('acrobat')->create([ - 'name' => "Soon to be deleted" + $license = \App\Models\License::factory()->acrobat()->create([ + 'name' => 'Soon to be deleted', ]); $licenseSeat = $license->freeSeat(); $licenseSeat->assigned_to = $this->user->id; @@ -155,7 +156,7 @@ class ApiLicensesCest $I->assertInstanceOf(\App\Models\License::class, $license); // delete - $I->sendDELETE('/licenses/' . $license->id); + $I->sendDELETE('/licenses/'.$license->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -170,13 +171,13 @@ class ApiLicensesCest $I->wantTo('Delete an license'); // create - $license = factory(\App\Models\License::class)->states('acrobat')->create([ - 'name' => "Soon to be deleted" + $license = \App\Models\License::factory()->acrobat()->create([ + 'name' => 'Soon to be deleted', ]); $I->assertInstanceOf(\App\Models\License::class, $license); // delete - $I->sendDELETE('/licenses/' . $license->id); + $I->sendDELETE('/licenses/'.$license->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -185,7 +186,7 @@ class ApiLicensesCest $I->assertEquals(trans('admin/licenses/message.delete.success'), $response->messages); // verify, expect a 200 - $I->sendGET('/licenses/' . $license->id); + $I->sendGET('/licenses/'.$license->id); $I->seeResponseCodeIs(200); $I->seeResponseIsJson(); diff --git a/tests/api/ApiLocationsCest.php b/tests/api/ApiLocationsCest.php index 76573a35b7..536830f00d 100644 --- a/tests/api/ApiLocationsCest.php +++ b/tests/api/ApiLocationsCest.php @@ -21,7 +21,6 @@ class ApiLocationsCest /** @test */ public function indexLocations(ApiTester $I) { - $I->wantTo('Get a list of locations'); // call @@ -32,7 +31,7 @@ class ApiLocationsCest $response = json_decode($I->grabResponse(), true); // sample verify $location = App\Models\Location::orderByDesc('created_at') - ->withCount('assignedAssets as assigned_assets_count', 'assets as assets_count', 'users as users_count') + ->withCount('assignedAssets as assigned_assets_count', 'assets as assets_count', 'users as users_count') ->take(10)->get()->shuffle()->first(); $I->seeResponseContainsJson($I->removeTimestamps((new LocationsTransformer)->transformLocation($location))); } @@ -42,8 +41,8 @@ class ApiLocationsCest { $I->wantTo('Create a new location'); - $temp_location = factory(\App\Models\Location::class)->make([ - 'name' => "Test Location Tag", + $temp_location = \App\Models\Location::factory()->make([ + 'name' => 'Test Location Tag', ]); // setup @@ -59,7 +58,7 @@ class ApiLocationsCest 'parent_id' => $temp_location->parent_id, 'parent_id' => $temp_location->parent_id, 'manager_id' => $temp_location->manager_id, - 'currency' => $temp_location->currency + 'currency' => $temp_location->currency, ]; // create @@ -70,19 +69,20 @@ class ApiLocationsCest // Put is routed to the same method in the controller // DO we actually need to test both? + /** @test */ public function updateLocationWithPatch(ApiTester $I, $scenario) { $I->wantTo('Update an location with PATCH'); // create - $location = factory(\App\Models\Location::class)->create([ + $location = \App\Models\Location::factory()->create([ 'name' => 'Original Location Name', ]); $I->assertInstanceOf(\App\Models\Location::class, $location); - $temp_location = factory(\App\Models\Location::class)->make([ - 'name' => "updated location name", + $temp_location = \App\Models\Location::factory()->make([ + 'name' => 'updated location name', ]); $data = [ @@ -97,13 +97,13 @@ class ApiLocationsCest 'parent_id' => $temp_location->parent_id, 'parent_id' => $temp_location->parent_id, 'manager_id' => $temp_location->manager_id, - 'currency' => $temp_location->currency + 'currency' => $temp_location->currency, ]; $I->assertNotEquals($location->name, $data['name']); // update - $I->sendPATCH('/locations/' . $location->id, $data); + $I->sendPATCH('/locations/'.$location->id, $data); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -120,7 +120,7 @@ class ApiLocationsCest $temp_location->id = $location->id; // verify - $I->sendGET('/locations/' . $location->id); + $I->sendGET('/locations/'.$location->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); $I->seeResponseContainsJson((new LocationsTransformer)->transformLocation($temp_location)); @@ -132,13 +132,13 @@ class ApiLocationsCest $I->wantTo('Delete an location'); // create - $location = factory(\App\Models\Location::class)->create([ - 'name' => "Soon to be deleted" + $location = \App\Models\Location::factory()->create([ + 'name' => 'Soon to be deleted', ]); $I->assertInstanceOf(\App\Models\Location::class, $location); // delete - $I->sendDELETE('/locations/' . $location->id); + $I->sendDELETE('/locations/'.$location->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -147,7 +147,7 @@ class ApiLocationsCest $I->assertEquals(trans('admin/locations/message.delete.success'), $response->messages); // verify, expect a 200 - $I->sendGET('/locations/' . $location->id); + $I->sendGET('/locations/'.$location->id); $I->seeResponseCodeIs(200); $I->seeResponseIsJson(); } diff --git a/tests/api/ApiManufacturersCest.php b/tests/api/ApiManufacturersCest.php index a9a8d3da51..be2f4cc483 100644 --- a/tests/api/ApiManufacturersCest.php +++ b/tests/api/ApiManufacturersCest.php @@ -21,7 +21,6 @@ class ApiManufacturersCest /** @test */ public function indexManufacturers(ApiTester $I) { - $I->wantTo('Get a list of manufacturers'); // call @@ -31,7 +30,7 @@ class ApiManufacturersCest $response = json_decode($I->grabResponse(), true); // sample verify - $manufacturer = App\Models\Manufacturer::withCount('assets as assets_count','accessories as accessories_count','consumables as consumables_count','licenses as licenses_count') + $manufacturer = App\Models\Manufacturer::withCount('assets as assets_count', 'accessories as accessories_count', 'consumables as consumables_count', 'licenses as licenses_count') ->orderByDesc('created_at')->take(10)->get()->shuffle()->first(); $I->seeResponseContainsJson($I->removeTimestamps((new ManufacturersTransformer)->transformManufacturer($manufacturer))); @@ -42,8 +41,8 @@ class ApiManufacturersCest { $I->wantTo('Create a new manufacturer'); - $temp_manufacturer = factory(\App\Models\Manufacturer::class)->states('apple')->make([ - 'name' => "Test Manufacturer Tag", + $temp_manufacturer = \App\Models\Manufacturer::factory()->apple()->make([ + 'name' => 'Test Manufacturer Tag', ]); // setup @@ -64,20 +63,21 @@ class ApiManufacturersCest // Put is routed to the same method in the controller // DO we actually need to test both? + /** @test */ public function updateManufacturerWithPatch(ApiTester $I, $scenario) { $I->wantTo('Update an manufacturer with PATCH'); // create - $manufacturer = factory(\App\Models\Manufacturer::class)->states('apple') + $manufacturer = \App\Models\Manufacturer::factory()->apple() ->create([ 'name' => 'Original Manufacturer Name', ]); $I->assertInstanceOf(\App\Models\Manufacturer::class, $manufacturer); - $temp_manufacturer = factory(\App\Models\Manufacturer::class)->states('dell')->make([ - 'name' => "updated manufacturer name", + $temp_manufacturer = \App\Models\Manufacturer::factory()->dell()->make([ + 'name' => 'updated manufacturer name', ]); $data = [ @@ -92,7 +92,7 @@ class ApiManufacturersCest $I->assertNotEquals($manufacturer->name, $data['name']); // update - $I->sendPATCH('/manufacturers/' . $manufacturer->id, $data); + $I->sendPATCH('/manufacturers/'.$manufacturer->id, $data); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -108,11 +108,10 @@ class ApiManufacturersCest $temp_manufacturer->id = $manufacturer->id; // verify - $I->sendGET('/manufacturers/' . $manufacturer->id); + $I->sendGET('/manufacturers/'.$manufacturer->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); $I->seeResponseContainsJson((new ManufacturersTransformer)->transformManufacturer($temp_manufacturer)); - } /** @test */ @@ -121,13 +120,13 @@ class ApiManufacturersCest $I->wantTo('Delete an manufacturer'); // create - $manufacturer = factory(\App\Models\Manufacturer::class)->states('apple')->create([ - 'name' => "Soon to be deleted" + $manufacturer = \App\Models\Manufacturer::factory()->apple()->create([ + 'name' => 'Soon to be deleted', ]); $I->assertInstanceOf(\App\Models\Manufacturer::class, $manufacturer); // delete - $I->sendDELETE('/manufacturers/' . $manufacturer->id); + $I->sendDELETE('/manufacturers/'.$manufacturer->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -136,7 +135,7 @@ class ApiManufacturersCest $I->assertEquals(trans('admin/manufacturers/message.delete.success'), $response->messages); // verify, expect a 200 - $I->sendGET('/manufacturers/' . $manufacturer->id); + $I->sendGET('/manufacturers/'.$manufacturer->id); $I->seeResponseCodeIs(200); $I->seeResponseIsJson(); } diff --git a/tests/api/ApiModelsCest.php b/tests/api/ApiModelsCest.php index 003dc995e9..1d3d6fc788 100644 --- a/tests/api/ApiModelsCest.php +++ b/tests/api/ApiModelsCest.php @@ -6,7 +6,7 @@ use App\Models\AssetModel; use App\Models\Setting; use Illuminate\Support\Facades\Auth; -class ApiAssetModelsCest +class ApiModelsCest { protected $user; protected $timeFormat; @@ -21,7 +21,6 @@ class ApiAssetModelsCest /** @test */ public function indexAssetModels(ApiTester $I) { - $I->wantTo('Get a list of assetmodels'); // call @@ -40,8 +39,8 @@ class ApiAssetModelsCest { $I->wantTo('Create a new assetmodel'); - $temp_assetmodel = factory(\App\Models\AssetModel::class)->states('mbp-13-model')->make([ - 'name' => "Test AssetModel Tag", + $temp_assetmodel = \App\Models\AssetModel::factory()->mbp13Model()->make([ + 'name' => 'Test AssetModel Tag', ]); // setup @@ -64,19 +63,20 @@ class ApiAssetModelsCest // Put is routed to the same method in the controller // DO we actually need to test both? + /** @test */ public function updateAssetModelWithPatch(ApiTester $I, $scenario) { $I->wantTo('Update an assetmodel with PATCH'); // create - $assetmodel = factory(\App\Models\AssetModel::class)->states('mbp-13-model')->create([ + $assetmodel = \App\Models\AssetModel::factory()->mbp13Model()->create([ 'name' => 'Original AssetModel Name', ]); $I->assertInstanceOf(\App\Models\AssetModel::class, $assetmodel); - $temp_assetmodel = factory(\App\Models\AssetModel::class)->states('polycomcx-model')->make([ - 'name' => "updated AssetModel name", + $temp_assetmodel = \App\Models\AssetModel::factory()->polycomcxModel()->make([ + 'name' => 'updated AssetModel name', 'fieldset_id' => 2, ]); @@ -95,7 +95,7 @@ class ApiAssetModelsCest $I->assertNotEquals($assetmodel->name, $data['name']); // update - $I->sendPATCH('/models/' . $assetmodel->id, $data); + $I->sendPATCH('/models/'.$assetmodel->id, $data); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -111,7 +111,7 @@ class ApiAssetModelsCest $temp_assetmodel->updated_at = Carbon::parse($response->payload->updated_at); $temp_assetmodel->id = $assetmodel->id; // verify - $I->sendGET('/models/' . $assetmodel->id); + $I->sendGET('/models/'.$assetmodel->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); $I->seeResponseContainsJson((new AssetModelsTransformer)->transformAssetModel($temp_assetmodel)); @@ -123,13 +123,13 @@ class ApiAssetModelsCest $I->wantTo('Delete an assetmodel'); // create - $assetmodel = factory(\App\Models\AssetModel::class)->states('mbp-13-model')->create([ - 'name' => "Soon to be deleted" + $assetmodel = \App\Models\AssetModel::factory()->mbp13Model()->create([ + 'name' => 'Soon to be deleted', ]); $I->assertInstanceOf(\App\Models\AssetModel::class, $assetmodel); // delete - $I->sendDELETE('/models/' . $assetmodel->id); + $I->sendDELETE('/models/'.$assetmodel->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -138,7 +138,7 @@ class ApiAssetModelsCest $I->assertEquals(trans('admin/models/message.delete.success'), $response->messages); // verify, expect a 200 - $I->sendGET('/models/' . $assetmodel->id); + $I->sendGET('/models/'.$assetmodel->id); $I->seeResponseCodeIs(200); $I->seeResponseIsJson(); } diff --git a/tests/api/ApiStatusLabelsCest.php b/tests/api/ApiStatusLabelsCest.php index 2a3c7c26ce..fabb71d51f 100644 --- a/tests/api/ApiStatusLabelsCest.php +++ b/tests/api/ApiStatusLabelsCest.php @@ -2,11 +2,11 @@ use App\Helpers\Helper; use App\Http\Transformers\StatuslabelsTransformer; -use App\Models\Statuslabel; use App\Models\Setting; +use App\Models\Statuslabel; use Illuminate\Support\Facades\Auth; -class ApiStatuslabelsCest +class ApiStatusLabelsCest { protected $user; protected $timeFormat; @@ -21,7 +21,6 @@ class ApiStatuslabelsCest /** @test */ public function indexStatuslabels(ApiTester $I) { - $I->wantTo('Get a list of statuslabels'); // call @@ -42,8 +41,8 @@ class ApiStatuslabelsCest { $I->wantTo('Create a new statuslabel'); - $temp_statuslabel = factory(\App\Models\Statuslabel::class)->make([ - 'name' => "Test Statuslabel Tag", + $temp_statuslabel = \App\Models\Statuslabel::factory()->make([ + 'name' => 'Test Statuslabel Tag', ]); // setup @@ -53,7 +52,7 @@ class ApiStatuslabelsCest 'deployable' => $temp_statuslabel->deployable, 'notes' => $temp_statuslabel->notes, 'pending' => $temp_statuslabel->pending, - 'type' => 'deployable' + 'type' => 'deployable', ]; // create @@ -64,20 +63,21 @@ class ApiStatuslabelsCest // Put is routed to the same method in the controller // DO we actually need to test both? + /** @test */ public function updateStatuslabelWithPatch(ApiTester $I, $scenario) { $I->wantTo('Update an statuslabel with PATCH'); // create - $statuslabel = factory(\App\Models\Statuslabel::class)->states('rtd')->create([ + $statuslabel = \App\Models\Statuslabel::factory()->rtd()->create([ 'name' => 'Original Statuslabel Name', ]); $I->assertInstanceOf(\App\Models\Statuslabel::class, $statuslabel); - $temp_statuslabel = factory(\App\Models\Statuslabel::class)->states('pending')->make([ - 'name' => "updated statuslabel name", - 'type' => 'pending' + $temp_statuslabel = \App\Models\Statuslabel::factory()->pending()->make([ + 'name' => 'updated statuslabel name', + 'type' => 'pending', ]); $data = [ @@ -86,18 +86,18 @@ class ApiStatuslabelsCest 'deployable' => $temp_statuslabel->deployable, 'notes' => $temp_statuslabel->notes, 'pending' => $temp_statuslabel->pending, - 'type' => $temp_statuslabel->type + 'type' => $temp_statuslabel->type, ]; $I->assertNotEquals($statuslabel->name, $data['name']); // update - $I->sendPATCH('/statuslabels/' . $statuslabel->id, $data); + $I->sendPATCH('/statuslabels/'.$statuslabel->id, $data); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); $response = json_decode($I->grabResponse()); -// dd($response); + // dd($response); $I->assertEquals('success', $response->status); $I->assertEquals(trans('admin/statuslabels/message.update.success'), $response->messages); $I->assertEquals($statuslabel->id, $response->payload->id); // statuslabel id does not change @@ -108,11 +108,10 @@ class ApiStatuslabelsCest $temp_statuslabel->id = $statuslabel->id; // verify - $I->sendGET('/statuslabels/' . $statuslabel->id); + $I->sendGET('/statuslabels/'.$statuslabel->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); $I->seeResponseContainsJson((new StatuslabelsTransformer)->transformStatuslabel($temp_statuslabel)); - } /** @test */ @@ -121,13 +120,13 @@ class ApiStatuslabelsCest $I->wantTo('Delete an statuslabel'); // create - $statuslabel = factory(\App\Models\Statuslabel::class)->create([ - 'name' => "Soon to be deleted" + $statuslabel = \App\Models\Statuslabel::factory()->create([ + 'name' => 'Soon to be deleted', ]); $I->assertInstanceOf(\App\Models\Statuslabel::class, $statuslabel); // delete - $I->sendDELETE('/statuslabels/' . $statuslabel->id); + $I->sendDELETE('/statuslabels/'.$statuslabel->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -136,7 +135,7 @@ class ApiStatuslabelsCest $I->assertEquals(trans('admin/statuslabels/message.delete.success'), $response->messages); // verify, expect a 200 - $I->sendGET('/statuslabels/' . $statuslabel->id); + $I->sendGET('/statuslabels/'.$statuslabel->id); $I->seeResponseCodeIs(200); $I->seeResponseIsJson(); } diff --git a/tests/api/ApiUsersCest.php b/tests/api/ApiUsersCest.php index 1306e81b0f..912653be2d 100644 --- a/tests/api/ApiUsersCest.php +++ b/tests/api/ApiUsersCest.php @@ -42,10 +42,10 @@ class ApiUsersCest { $I->wantTo('Create a new user'); - $temp_user = factory(\App\Models\User::class)->make([ - 'name' => "Test User Name", + $temp_user = \App\Models\User::factory()->make([ + 'name' => 'Test User Name', ]); - factory(Group::class, 2)->create(); + Group::factory()->count(2)->create(); $groups = Group::pluck('id'); // setup $data = [ @@ -70,7 +70,7 @@ class ApiUsersCest 'state' => $temp_user->state, 'username' => $temp_user->username, 'zip' => $temp_user->zip, - 'groups' => $groups + 'groups' => $groups, ]; // create @@ -83,26 +83,27 @@ class ApiUsersCest // Put is routed to the same method in the controller // DO we actually need to test both? + /** @test */ public function updateUserWithPatch(ApiTester $I, $scenario) { $I->wantTo('Update an user with PATCH'); // create - $user = factory(\App\Models\User::class)->create([ + $user = \App\Models\User::factory()->create([ 'first_name' => 'Original User Name', 'company_id' => 2, - 'location_id' => 3 + 'location_id' => 3, ]); $I->assertInstanceOf(\App\Models\User::class, $user); - $temp_user = factory(\App\Models\User::class)->make([ + $temp_user = \App\Models\User::factory()->make([ 'company_id' => 3, - 'first_name' => "updated user name", + 'first_name' => 'updated user name', 'location_id' => 1, ]); - factory(Group::class, 2)->create(); + Group::factory()->count(2)->create(); $groups = Group::pluck('id'); $data = [ @@ -132,7 +133,7 @@ class ApiUsersCest $I->assertNotEquals($user->first_name, $data['first_name']); // update - $I->sendPATCH('/users/' . $user->id, $data); + $I->sendPATCH('/users/'.$user->id, $data); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -150,7 +151,7 @@ class ApiUsersCest $temp_user->updated_at = Carbon::parse($response->payload->updated_at->datetime); $temp_user->id = $user->id; // verify - $I->sendGET('/users/' . $user->id); + $I->sendGET('/users/'.$user->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); $I->seeResponseContainsJson((new UsersTransformer)->transformUser($temp_user)); @@ -162,13 +163,13 @@ class ApiUsersCest $I->wantTo('Delete an user'); // create - $user = factory(\App\Models\User::class)->create([ - 'first_name' => "Soon to be deleted" + $user = \App\Models\User::factory()->create([ + 'first_name' => 'Soon to be deleted', ]); $I->assertInstanceOf(\App\Models\User::class, $user); // delete - $I->sendDELETE('/users/' . $user->id); + $I->sendDELETE('/users/'.$user->id); $I->seeResponseIsJson(); $I->seeResponseCodeIs(200); @@ -178,15 +179,16 @@ class ApiUsersCest $I->assertEquals(trans('admin/users/message.success.delete'), $response->messages); // verify, expect a 200 - $I->sendGET('/users/' . $user->id); + $I->sendGET('/users/'.$user->id); $I->seeResponseCodeIs(200); $I->seeResponseIsJson(); } /** @test */ - public function fetchUserAssetsTest(ApiTester $I, $scenario) { - $I->wantTo("Fetch assets for a user"); + public function fetchUserAssetsTest(ApiTester $I, $scenario) + { + $I->wantTo('Fetch assets for a user'); $user = User::has('assets')->first(); $asset = $user->assets->shuffle()->first(); diff --git a/tests/api/_bootstrap.php b/tests/api/_bootstrap.php index 8a88555806..62817a53c4 100644 --- a/tests/api/_bootstrap.php +++ b/tests/api/_bootstrap.php @@ -1,2 +1,3 @@ amOnPage('/login'); - $I->fillField('username', 'admin'); - $I->fillField('password', 'password'); - $I->click('Login'); - $I->seeAuthentication(); + $I->amOnPage('/login'); + $I->fillField('username', 'admin'); + $I->fillField('password', 'password'); + $I->click('Login'); + $I->seeAuthentication(); } // tests @@ -25,7 +24,7 @@ class AccessoriesCest public function failsEmptyValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with blank elements"); + $I->wantTo('Test Validation Fails with blank elements'); $I->amOnPage('/accessories/create'); $I->seeResponseCodeIs(200); $I->click('Save'); @@ -37,7 +36,7 @@ class AccessoriesCest public function failsShortValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with short name"); + $I->wantTo('Test Validation Fails with short name'); $I->amOnPage('/accessories/create'); $I->seeResponseCodeIs(200); $I->fillField('name', 't2'); @@ -53,7 +52,7 @@ class AccessoriesCest public function passesCorrectValidation(FunctionalTester $I) { - $accessory = factory(App\Models\Accessory::class)->states('apple-bt-keyboard')->make(); + $accessory = \App\Models\Accessory::factory()->appleBtKeyboard()->make(); $values = [ 'category_id' => $accessory->category_id, 'location_id' => $accessory->location_id, @@ -65,7 +64,7 @@ class AccessoriesCest 'qty' => $accessory->qty, ]; - $I->wantTo("Test Validation Succeeds"); + $I->wantTo('Test Validation Succeeds'); $I->amOnPage('/accessories/create'); $I->seeResponseCodeIs(200); @@ -79,7 +78,7 @@ class AccessoriesCest public function allowsDelete(FunctionalTester $I) { $I->wantTo('Ensure I can delete an accessory'); - $I->sendDelete( route('accessories.destroy', $I->getAccessoryId() ), ['_token' => csrf_token()] ); + $I->sendDelete(route('accessories.destroy', $I->getAccessoryId()), ['_token' => csrf_token()]); $I->seeResponseCodeIs(200); } } diff --git a/tests/functional/AssetModelsCest.php b/tests/functional/AssetModelsCest.php index d16a2996b5..fbf43a5c57 100644 --- a/tests/functional/AssetModelsCest.php +++ b/tests/functional/AssetModelsCest.php @@ -1,6 +1,5 @@ fillField('password', 'password'); $I->click('Login'); } + // tests public function tryToTest(FunctionalTester $I) { @@ -22,7 +22,7 @@ class AssetModelsCest public function failsEmptyValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with blank elements"); + $I->wantTo('Test Validation Fails with blank elements'); $I->amOnPage(route('models.create')); $I->click('Save'); $I->seeElement('.alert-danger'); @@ -33,7 +33,7 @@ class AssetModelsCest public function passesCorrectValidation(FunctionalTester $I) { - $model = factory(App\Models\AssetModel::class)->states('mbp-13-model')->make(['name'=>'Test Model']); + $model = \App\Models\AssetModel::factory()->mbp13Model()->make(['name'=>'Test Model']); $values = [ 'category_id' => $model->category_id, 'depreciation_id' => $model->depreciation_id, @@ -44,7 +44,7 @@ class AssetModelsCest 'notes' => $model->notes, ]; - $I->wantTo("Test Validation Succeeds"); + $I->wantTo('Test Validation Succeeds'); $I->amOnPage(route('models.create')); $I->submitForm('form#create-form', $values); @@ -56,9 +56,8 @@ class AssetModelsCest public function allowsDelete(FunctionalTester $I) { $I->wantTo('Ensure I can delete an asset model'); - $model = factory(App\Models\AssetModel::class)->states('mbp-13-model')->create(['name' => "Test Model"]); + $model = \App\Models\AssetModel::factory()->mbp13Model()->create(['name' => 'Test Model']); $I->sendDelete(route('models.destroy', $model->id), ['_token' => csrf_token()]); $I->seeResponseCodeIs(200); } - } diff --git a/tests/functional/AssetsCest.php b/tests/functional/AssetsCest.php index 078a39aa92..3c7ffc1282 100644 --- a/tests/functional/AssetsCest.php +++ b/tests/functional/AssetsCest.php @@ -1,6 +1,5 @@ fillField('password', 'password'); $I->click('Login'); } + // tests public function tryToTest(FunctionalTester $I) { @@ -22,7 +22,7 @@ class AssetsCest public function failsEmptyValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with blank elements"); + $I->wantTo('Test Validation Fails with blank elements'); $I->amOnPage(route('hardware.create')); // Settings factory can enable auto prefixes, which generate a random asset id. Lets clear it out for the sake of this test. $I->fillField('#asset_tag', ''); @@ -34,11 +34,11 @@ class AssetsCest public function passesCreateAndCheckout(FunctionalTester $I) { - $asset = factory(App\Models\Asset::class)->states('laptop-mbp')->make([ + $asset = \App\Models\Asset::factory()->laptopMbp()->make([ 'asset_tag'=>'test tag', - 'name'=> "test asset", + 'name'=> 'test asset', 'company_id'=>1, - 'warranty_months'=>15 + 'warranty_months'=>15, ]); $userId = $I->getUserId(); $values = [ @@ -62,7 +62,7 @@ class AssetsCest $seenValues = [ 'asset_tag' => $asset->asset_tag, 'assigned_to' => $userId, - 'assigned_type' => 'App\\Models\\User', + 'assigned_type' => \App\Models\User::class, 'company_id' => $asset->company_id, 'model_id' => $asset->model_id, 'name' => $asset->name, @@ -78,7 +78,7 @@ class AssetsCest 'warranty_months' => $asset->warranty_months, ]; - $I->wantTo("Test Validation Succeeds"); + $I->wantTo('Test Validation Succeeds'); $I->amOnPage(route('hardware.create')); $I->submitForm('form#create-form', $values); $I->seeRecord('assets', $seenValues); diff --git a/tests/functional/CategoriesCest.php b/tests/functional/CategoriesCest.php index 6f054b5dd9..ff89fcc152 100644 --- a/tests/functional/CategoriesCest.php +++ b/tests/functional/CategoriesCest.php @@ -1,14 +1,13 @@ amOnPage('/login'); - $I->fillField('username', 'admin'); - $I->fillField('password', 'password'); - $I->click('Login'); + $I->amOnPage('/login'); + $I->fillField('username', 'admin'); + $I->fillField('password', 'password'); + $I->click('Login'); } public function _after(FunctionalTester $I) @@ -27,7 +26,7 @@ class CategoriesCest public function failsEmptyValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with blank elements"); + $I->wantTo('Test Validation Fails with blank elements'); $I->amOnPage(route('categories.create')); $I->click('Save'); $I->seeElement('.alert-danger'); @@ -37,8 +36,8 @@ class CategoriesCest public function passesCorrectValidation(FunctionalTester $I) { - $category = factory(App\Models\Category::class)->states('asset-laptop-category')->make([ - 'name' => "Test Category" + $category = \App\Models\Category::factory()->assetLaptopCategory()->make([ + 'name' => 'Test Category', ]); $values = [ 'category_type' => $category->category_type, @@ -47,18 +46,19 @@ class CategoriesCest 'name' => $category->name, 'require_acceptance' => $category->require_acceptance, ]; - $I->wantTo("Test Validation Succeeds"); + $I->wantTo('Test Validation Succeeds'); $I->amOnPage(route('categories.create')); $I->submitForm('form#create-form', $values); $I->seeRecord('categories', $values); $I->dontSee('<span class="'); $I->seeElement('.alert-success'); } + public function allowsDelete(FunctionalTester $I) { $I->wantTo('Ensure I can delete a category'); - $category = factory(App\Models\Category::class)->states('asset-laptop-category')->create([ - 'name'=>"Deletable Test Category" + $category = \App\Models\Category::factory()->assetLaptopCategory()->create([ + 'name'=>'Deletable Test Category', ]); $I->sendDelete(route('categories.destroy', $category->id), ['_token' => csrf_token()]); $I->seeResponseCodeIs(200); diff --git a/tests/functional/CompaniesCest.php b/tests/functional/CompaniesCest.php index 8ede140a21..75724aa206 100644 --- a/tests/functional/CompaniesCest.php +++ b/tests/functional/CompaniesCest.php @@ -1,14 +1,13 @@ amOnPage('/login'); - $I->fillField('username', 'admin'); - $I->fillField('password', 'password'); - $I->click('Login'); + $I->amOnPage('/login'); + $I->fillField('username', 'admin'); + $I->fillField('password', 'password'); + $I->click('Login'); } // tests @@ -23,7 +22,7 @@ class CompaniesCest public function failsEmptyValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with blank elements"); + $I->wantTo('Test Validation Fails with blank elements'); $I->amOnPage(route('companies.create')); $I->click('Save'); $I->seeElement('.alert-danger'); @@ -32,11 +31,11 @@ class CompaniesCest public function passesCorrectValidation(FunctionalTester $I) { - $company = factory(App\Models\Company::class)->make(); + $company = \App\Models\Company::factory()->make(); $values = [ - 'name' => $company->name + 'name' => $company->name, ]; - $I->wantTo("Test Validation Succeeds"); + $I->wantTo('Test Validation Succeeds'); $I->amOnPage(route('companies.create')); $I->fillField('name', 'TestCompany'); $I->submitForm('form#create-form', $values); diff --git a/tests/functional/ComponentsCest.php b/tests/functional/ComponentsCest.php index c23aaa5547..6e2a7f136b 100644 --- a/tests/functional/ComponentsCest.php +++ b/tests/functional/ComponentsCest.php @@ -1,14 +1,13 @@ amOnPage('/login'); - $I->fillField('username', 'admin'); - $I->fillField('password', 'password'); - $I->click('Login'); + $I->amOnPage('/login'); + $I->fillField('username', 'admin'); + $I->fillField('password', 'password'); + $I->click('Login'); } // tests @@ -23,7 +22,7 @@ class ComponentsCest public function failsEmptyValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with blank elements"); + $I->wantTo('Test Validation Fails with blank elements'); $I->amOnPage(route('components.create')); $I->click('Save'); $I->seeElement('.alert-danger'); @@ -34,7 +33,7 @@ class ComponentsCest public function failsShortValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with short name"); + $I->wantTo('Test Validation Fails with short name'); $I->amOnPage(route('components.create')); $I->fillField('name', 't2'); $I->fillField('qty', '-15'); @@ -47,9 +46,9 @@ class ComponentsCest public function passesCorrectValidation(FunctionalTester $I) { - $component = factory(App\Models\Component::class)->states('ram-crucial4')->make([ + $component = \App\Models\Component::factory()->ramCrucial4()->make([ 'name' => 'Test Component', - 'serial' => '3523-235325-1350235' + 'serial' => '3523-235325-1350235', ]); $values = [ 'category_id' => $component->category_id, @@ -63,13 +62,14 @@ class ComponentsCest 'qty' => $component->qty, 'serial' => $component->serial, ]; - $I->wantTo("Test Validation Succeeds"); + $I->wantTo('Test Validation Succeeds'); $I->amOnPage(route('components.create')); $I->submitForm('form#create-form', $values); $I->seeRecord('components', $values); $I->dontSee('<span class="'); $I->seeElement('.alert-success'); } + public function allowsDelete(FunctionalTester $I) { $I->wantTo('Ensure I can delete a component'); diff --git a/tests/functional/ConsumablesCest.php b/tests/functional/ConsumablesCest.php index c6f8285ec2..c47eb23c0f 100644 --- a/tests/functional/ConsumablesCest.php +++ b/tests/functional/ConsumablesCest.php @@ -1,14 +1,13 @@ amOnPage('/login'); - $I->fillField('username', 'admin'); - $I->fillField('password', 'password'); - $I->click('Login'); + $I->amOnPage('/login'); + $I->fillField('username', 'admin'); + $I->fillField('password', 'password'); + $I->click('Login'); } // tests @@ -23,7 +22,7 @@ class ConsumablesCest public function failsEmptyValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with blank elements"); + $I->wantTo('Test Validation Fails with blank elements'); $I->amOnPage(route('consumables.create')); $I->click('Save'); $I->seeElement('.alert-danger'); @@ -34,7 +33,7 @@ class ConsumablesCest public function failsShortValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with short name"); + $I->wantTo('Test Validation Fails with short name'); $I->amOnPage(route('consumables.create')); $I->fillField('name', 't2'); $I->fillField('qty', '-15'); @@ -48,9 +47,9 @@ class ConsumablesCest public function passesCorrectValidation(FunctionalTester $I) { - $consumable = factory(App\Models\Consumable::class)->states('cardstock')->make([ + $consumable = \App\Models\Consumable::factory()->cardstock()->make([ 'name' => 'Test Consumable', - 'model_number' => 23520 + 'model_number' => 23520, ]); // dd($consumable); $values = [ @@ -66,7 +65,7 @@ class ConsumablesCest 'purchase_date' => '2016-01-01', 'qty' => $consumable->qty, ]; - $I->wantTo("Test Validation Succeeds"); + $I->wantTo('Test Validation Succeeds'); $I->amOnPage(route('consumables.create')); $I->submitForm('form#create-form', $values); $I->seeRecord('consumables', $values); diff --git a/tests/functional/DepreciationsCest.php b/tests/functional/DepreciationsCest.php index 8e39a64f72..25dcfaef1f 100644 --- a/tests/functional/DepreciationsCest.php +++ b/tests/functional/DepreciationsCest.php @@ -1,14 +1,13 @@ amOnPage('/login'); - $I->fillField('username', 'admin'); - $I->fillField('password', 'password'); - $I->click('Login'); + $I->amOnPage('/login'); + $I->fillField('username', 'admin'); + $I->fillField('password', 'password'); + $I->click('Login'); } // tests @@ -24,7 +23,7 @@ class DepreciationCest public function failsEmptyValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with blank elements"); + $I->wantTo('Test Validation Fails with blank elements'); $I->amOnPage(route('depreciations.create')); $I->click('Save'); $I->seeElement('.alert-danger'); @@ -34,7 +33,7 @@ class DepreciationCest public function failsShortValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with short name"); + $I->wantTo('Test Validation Fails with short name'); $I->amOnPage(route('depreciations.create')); $I->fillField('name', 't2'); $I->click('Save'); @@ -44,14 +43,14 @@ class DepreciationCest public function passesCorrectValidation(FunctionalTester $I) { - $depreciation = factory(App\Models\Depreciation::class)->states('computer')->make([ - 'name'=>'Test Depreciation' + $depreciation = \App\Models\Depreciation::factory()->computer()->make([ + 'name'=>'Test Depreciation', ]); $values = [ 'name' => $depreciation->name, - 'months' => $depreciation->months + 'months' => $depreciation->months, ]; - $I->wantTo("Test Validation Succeeds"); + $I->wantTo('Test Validation Succeeds'); $I->amOnPage(route('depreciations.create')); $I->submitForm('form#create-form', $values); $I->seeRecord('depreciations', $values); diff --git a/tests/functional/GroupsCest.php b/tests/functional/GroupsCest.php index dd976d8c00..aa9ba9872a 100644 --- a/tests/functional/GroupsCest.php +++ b/tests/functional/GroupsCest.php @@ -1,16 +1,15 @@ amOnPage('/login'); - $I->fillField('username', 'admin'); - $I->fillField('password', 'password'); - $I->click('Login'); + $I->amOnPage('/login'); + $I->fillField('username', 'admin'); + $I->fillField('password', 'password'); + $I->click('Login'); } // tests @@ -26,7 +25,7 @@ class GroupsCest public function failsEmptyValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with blank elements"); + $I->wantTo('Test Validation Fails with blank elements'); $I->amOnPage(route('groups.create')); $I->seeResponseCodeIs(200); $I->click('Save'); @@ -36,7 +35,7 @@ class GroupsCest public function failsShortValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with short name"); + $I->wantTo('Test Validation Fails with short name'); $I->amOnPage(route('groups.create')); $I->seeResponseCodeIs(200); $I->fillField('name', 't'); @@ -47,7 +46,7 @@ class GroupsCest public function passesCorrectValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Succeeds"); + $I->wantTo('Test Validation Succeeds'); $I->amOnPage(route('groups.create')); $I->seeResponseCodeIs(200); $I->fillField('name', 'TestGroup'); diff --git a/tests/functional/LicensesCest.php b/tests/functional/LicensesCest.php index 85c90232c1..5add67f51d 100644 --- a/tests/functional/LicensesCest.php +++ b/tests/functional/LicensesCest.php @@ -1,16 +1,15 @@ amOnPage('/login'); - $I->fillField('username', 'admin'); - $I->fillField('password', 'password'); - $I->click('Login'); + $I->amOnPage('/login'); + $I->fillField('username', 'admin'); + $I->fillField('password', 'password'); + $I->click('Login'); } // tests @@ -25,7 +24,7 @@ class LicensesCest public function failsEmptyValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with blank elements"); + $I->wantTo('Test Validation Fails with blank elements'); $I->amOnPage(route('licenses.create')); $I->click('Save'); $I->seeElement('.alert-danger'); @@ -36,7 +35,7 @@ class LicensesCest public function failsShortValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with short name"); + $I->wantTo('Test Validation Fails with short name'); $I->amOnPage(route('licenses.create')); $I->fillField('name', 't2'); $I->fillField('seats', '-15'); @@ -48,7 +47,7 @@ class LicensesCest public function passesCorrectValidation(FunctionalTester $I) { - $license = factory(App\Models\License::class)->states('photoshop')->make([ + $license = \App\Models\License::factory()->photoshop()->make([ 'name' => 'Test License', 'company_id' => 3, ]); @@ -72,7 +71,7 @@ class LicensesCest 'termination_date' => '2020-01-01', ]; - $I->wantTo("Test Validation Succeeds"); + $I->wantTo('Test Validation Succeeds'); $I->amOnPage(route('licenses.create')); $I->submitForm('form#create-form', $values); $I->seeRecord('licenses', $values); @@ -86,5 +85,4 @@ class LicensesCest $I->sendDelete(route('licenses.destroy', License::doesntHave('assignedUsers')->first()->id), ['_token' => csrf_token()]); $I->seeResponseCodeIs(200); } - } diff --git a/tests/functional/LocationsCest.php b/tests/functional/LocationsCest.php index 4977c15c0a..9177c6ae4b 100644 --- a/tests/functional/LocationsCest.php +++ b/tests/functional/LocationsCest.php @@ -1,17 +1,16 @@ amOnPage('/login'); - $I->fillField('username', 'admin'); - $I->fillField('password', 'password'); - $I->click('Login'); + // logging in + $I->amOnPage('/login'); + $I->fillField('username', 'admin'); + $I->fillField('password', 'password'); + $I->click('Login'); } // tests @@ -27,7 +26,7 @@ class LocationsCest public function failsEmptyValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with blank elements"); + $I->wantTo('Test Validation Fails with blank elements'); $I->amOnPage(route('locations.create')); $I->click('Save'); $I->seeElement('.alert-danger'); @@ -36,16 +35,17 @@ class LocationsCest public function failsShortValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with short values"); + $I->wantTo('Test Validation Fails with short values'); $I->amOnPage(route('locations.create')); $I->fillField('name', 't'); $I->click('Save'); $I->seeElement('.alert-danger'); $I->see('The name must be at least 2 characters', '.alert-msg'); } + public function passesCorrectValidation(FunctionalTester $I) { - $location = factory(App\Models\Location::class)->make(); + $location = \App\Models\Location::factory()->make(); $values = [ 'name' => $location->name, 'parent_id' => $I->getLocationId(), @@ -57,7 +57,7 @@ class LocationsCest 'country' => $location->country, 'zip' => $location->zip, ]; - $I->wantTo("Test Validation Succeeds"); + $I->wantTo('Test Validation Succeeds'); $I->amOnPage(route('locations.create')); $I->submitForm('form#create-form', $values); $I->seeRecord('locations', $values); @@ -67,7 +67,7 @@ class LocationsCest public function allowsDelete(FunctionalTester $I) { $I->wantTo('Ensure I can delete a location'); - $location = factory(App\Models\Location::class)->create(); + $location = \App\Models\Location::factory()->create(); $I->sendDelete(route('locations.destroy', $location->id), ['_token' => csrf_token()]); $I->seeResponseCodeIs(200); } diff --git a/tests/functional/ManufacturersCest.php b/tests/functional/ManufacturersCest.php index 8c34badd1a..65c8b1d190 100644 --- a/tests/functional/ManufacturersCest.php +++ b/tests/functional/ManufacturersCest.php @@ -1,16 +1,15 @@ amOnPage('/login'); - $I->fillField('username', 'admin'); - $I->fillField('password', 'password'); - $I->click('Login'); + $I->amOnPage('/login'); + $I->fillField('username', 'admin'); + $I->fillField('password', 'password'); + $I->click('Login'); } // tests @@ -25,7 +24,7 @@ class ManufacturersCest public function failsEmptyValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with blank elements"); + $I->wantTo('Test Validation Fails with blank elements'); $I->amOnPage(route('manufacturers.create')); $I->click('Save'); $I->seeElement('.alert-danger'); @@ -34,22 +33,23 @@ class ManufacturersCest public function failsShortValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with short name"); + $I->wantTo('Test Validation Fails with short name'); $I->amOnPage(route('manufacturers.create')); $I->fillField('name', 't'); $I->click('Save'); $I->seeElement('.alert-danger'); $I->see('The name must be at least 2 characters', '.alert-msg'); } + public function passesCorrectValidation(FunctionalTester $I) { - $manufacturer = factory(App\Models\Manufacturer::class)->states('microsoft')->make([ - 'name' => 'Test Manufacturer' + $manufacturer = \App\Models\Manufacturer::factory()->microsoft()->make([ + 'name' => 'Test Manufacturer', ]); $values = [ - 'name' => $manufacturer->name + 'name' => $manufacturer->name, ]; - $I->wantTo("Test Validation Succeeds"); + $I->wantTo('Test Validation Succeeds'); $I->amOnPage(route('manufacturers.create')); $I->submitForm('form#create-form', $values); $I->seeRecord('manufacturers', $values); @@ -59,7 +59,7 @@ class ManufacturersCest public function allowsDelete(FunctionalTester $I) { $I->wantTo('Ensure I can delete a manufacturer'); - $manufacturerId = factory(App\Models\Manufacturer::class)->states('microsoft')->create(['name' => "Deletable Test Manufacturer"])->id; + $manufacturerId = \App\Models\Manufacturer::factory()->microsoft()->create(['name' => 'Deletable Test Manufacturer'])->id; $I->sendDelete(route('manufacturers.destroy', $manufacturerId), ['_token' => csrf_token()]); $I->seeResponseCodeIs(200); } diff --git a/tests/functional/StatusLabelsCest.php b/tests/functional/StatusLabelsCest.php index aba061842b..ff1ec90961 100644 --- a/tests/functional/StatusLabelsCest.php +++ b/tests/functional/StatusLabelsCest.php @@ -1,16 +1,15 @@ amOnPage('/login'); - $I->fillField('username', 'admin'); - $I->fillField('password', 'password'); - $I->click('Login'); + $I->amOnPage('/login'); + $I->fillField('username', 'admin'); + $I->fillField('password', 'password'); + $I->click('Login'); } // tests @@ -25,7 +24,7 @@ class StatusLabelsCest public function failsEmptyValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with blank elements"); + $I->wantTo('Test Validation Fails with blank elements'); $I->amOnPage(route('statuslabels.create')); $I->click('Save'); $I->seeElement('.alert-danger'); @@ -34,7 +33,7 @@ class StatusLabelsCest public function passesCorrectValidation(FunctionalTester $I) { - $status = factory(App\Models\Statuslabel::class)->states('pending')->make(); + $status = \App\Models\Statuslabel::factory()->pending()->make(); $submitValues = [ 'name' => 'Testing Status', 'statuslabel_types' => 'pending', @@ -52,7 +51,7 @@ class StatusLabelsCest 'notes' => $status->notes, 'show_in_nav' => true, ]; - $I->wantTo("Test Validation Succeeds"); + $I->wantTo('Test Validation Succeeds'); $I->amOnPage(route('statuslabels.create')); $I->submitForm('form#create-form', $submitValues); $I->seeRecord('status_labels', $recordValues); diff --git a/tests/functional/SuppliersCest.php b/tests/functional/SuppliersCest.php index e555023c04..69746f86a5 100644 --- a/tests/functional/SuppliersCest.php +++ b/tests/functional/SuppliersCest.php @@ -4,10 +4,10 @@ class SuppliersCest { public function _before(FunctionalTester $I) { - $I->amOnPage('/login'); - $I->fillField('username', 'admin'); - $I->fillField('password', 'password'); - $I->click('Login'); + $I->amOnPage('/login'); + $I->fillField('username', 'admin'); + $I->fillField('password', 'password'); + $I->click('Login'); } // tests @@ -22,7 +22,7 @@ class SuppliersCest public function failsEmptyValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with blank elements"); + $I->wantTo('Test Validation Fails with blank elements'); $I->amOnPage(route('suppliers.create')); $I->click('Save'); $I->seeElement('.alert-danger'); @@ -31,7 +31,7 @@ class SuppliersCest public function passesCorrectValidation(FunctionalTester $I) { - $supplier = factory(App\Models\Supplier::class)->make(); + $supplier = \App\Models\Supplier::factory()->make(); $values = [ 'name' => $supplier->name, @@ -46,9 +46,9 @@ class SuppliersCest 'fax' => $supplier->fax, 'email' => $supplier->email, 'url' => $supplier->url, - 'notes' => $supplier->notes + 'notes' => $supplier->notes, ]; - $I->wantTo("Test Validation Succeeds"); + $I->wantTo('Test Validation Succeeds'); $I->amOnPage(route('suppliers.create')); $I->submitForm('form#create-form', $values); $I->seeRecord('suppliers', $values); @@ -58,7 +58,7 @@ class SuppliersCest public function allowsDelete(FunctionalTester $I) { $I->wantTo('Ensure I can delete a supplier'); - $supplier = factory(App\Models\Supplier::class)->create(); + $supplier = \App\Models\Supplier::factory()->create(); $I->sendDelete(route('suppliers.destroy', $supplier->id), ['_token' => csrf_token()]); $I->seeResponseCodeIs(200); } diff --git a/tests/functional/UsersCest.php b/tests/functional/UsersCest.php index 42ca897342..e861694918 100644 --- a/tests/functional/UsersCest.php +++ b/tests/functional/UsersCest.php @@ -4,15 +4,16 @@ use App\Models\User; class UsersCest { - public function _before(\FunctionalTester $I) + public function _before(FunctionalTester $I) { - $I->amOnPage('/login'); - $I->fillField('username', 'admin'); - $I->fillField('password', 'password'); - $I->click('Login'); + $I->amOnPage('/login'); + $I->fillField('username', 'admin'); + $I->fillField('password', 'password'); + $I->click('Login'); } + // tests - public function tryToTest(\FunctionalTester $I) + public function tryToTest(FunctionalTester $I) { $I->wantTo('ensure that the create users form loads without errors'); $I->lookForwardTo('seeing it load without errors'); @@ -23,7 +24,7 @@ class UsersCest public function failsEmptyValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with blank elements"); + $I->wantTo('Test Validation Fails with blank elements'); $I->amOnPage(route('users.create')); $I->click('Save'); $I->seeElement('.alert-danger'); @@ -34,7 +35,7 @@ class UsersCest public function failsShortValidation(FunctionalTester $I) { - $I->wantTo("Test Validation Fails with short name"); + $I->wantTo('Test Validation Fails with short name'); $I->amOnPage(route('users.create')); $I->fillField('first_name', 't2'); $I->fillField('last_name', 't2'); @@ -43,11 +44,11 @@ class UsersCest $I->click('Save'); $I->seeElement('.alert-danger'); $I->see('The password must be at least 8 characters', '.alert-msg'); - } + public function passesCorrectValidation(FunctionalTester $I) { - $user = factory(App\Models\User::class)->make(); + $user = \App\Models\User::factory()->make(); $submitValues = [ 'first_name' => $user->first_name, 'last_name' => $user->last_name, @@ -63,7 +64,7 @@ class UsersCest 'location_id' => $user->location_id, 'phone' => $user->phone, 'activated' => true, - 'notes' => $user->notes + 'notes' => $user->notes, ]; $storedValues = [ 'first_name' => $user->first_name, @@ -78,10 +79,10 @@ class UsersCest 'location_id' => $user->location_id, 'phone' => $user->phone, 'activated' => true, - 'notes' => $user->notes + 'notes' => $user->notes, ]; $I->amOnPage(route('users.create')); - $I->wantTo("Test Validation Succeeds"); + $I->wantTo('Test Validation Succeeds'); $I->submitForm('form#userForm', $submitValues); $I->seeRecord('users', $storedValues); $I->seeElement('.alert-success'); @@ -89,7 +90,7 @@ class UsersCest public function allowsDelete(FunctionalTester $I) { - $user = factory(App\Models\User::class)->create(); + $user = \App\Models\User::factory()->create(); $I->wantTo('Ensure I can delete a user'); $I->sendDelete(route('users.destroy', $user->id), ['_token' => csrf_token()]); $I->seeResponseCodeIs(200); diff --git a/tests/functional/_bootstrap.php b/tests/functional/_bootstrap.php index 8a88555806..62817a53c4 100644 --- a/tests/functional/_bootstrap.php +++ b/tests/functional/_bootstrap.php @@ -1,2 +1,3 @@ 'name', 'qty' => 'qty', - 'category_id' => 'category id' + 'category_id' => 'category id', ]; $errors = $a->getErrors(); foreach ($fields as $field => $fieldTitle) { @@ -34,15 +35,15 @@ class AccessoryTest extends BaseTest // An Accessory name has a min length of 3 // An Accessory has a min qty of 1 // An Accessory has a min amount of 0 - $a = factory(Accessory::class)->make([ + $a = Accessory::factory()->make([ 'name' => 'a', 'qty' => 0, - 'min_amt' => -1 + 'min_amt' => -1, ]); $fields = [ 'name' => 'name', 'qty' => 'qty', - 'min_amt' => 'min amt' + 'min_amt' => 'min amt', ]; $this->assertFalse($a->isValid()); $errors = $a->getErrors(); @@ -54,37 +55,37 @@ class AccessoryTest extends BaseTest public function testCategoryIdMustExist() { $category = $this->createValidCategory('accessory-keyboard-category', ['category_type' => 'accessory']); - $accessory = factory(Accessory::class)->states('apple-bt-keyboard')->make(['category_id' => $category->id]); + $accessory = Accessory::factory()->appleBtKeyboard()->make(['category_id' => $category->id]); $this->createValidManufacturer('apple'); $accessory->save(); $this->assertTrue($accessory->isValid()); $newId = $category->id + 1; - $accessory = factory(Accessory::class)->states('apple-bt-keyboard')->make(['category_id' => $newId]); + $accessory = Accessory::factory()->appleBtKeyboard()->make(['category_id' => $newId]); $accessory->save(); $this->assertFalse($accessory->isValid()); - $this->assertStringContainsString("The selected category id is invalid.", $accessory->getErrors()->get('category_id')[0]); + $this->assertStringContainsString('The selected category id is invalid.', $accessory->getErrors()->get('category_id')[0]); } public function testAnAccessoryBelongsToACompany() { - $accessory = factory(Accessory::class) - ->create(['company_id' => factory(App\Models\Company::class)->create()->id]); + $accessory = Accessory::factory() + ->create(['company_id' => \App\Models\Company::factory()->create()->id]); $this->assertInstanceOf(App\Models\Company::class, $accessory->company); } public function testAnAccessoryHasALocation() { - $accessory = factory(Accessory::class) - ->create(['location_id' => factory(App\Models\Location::class)->create()->id]); + $accessory = Accessory::factory() + ->create(['location_id' => \App\Models\Location::factory()->create()->id]); $this->assertInstanceOf(App\Models\Location::class, $accessory->location); } public function testAnAccessoryBelongsToACategory() { - $accessory = factory(Accessory::class)->states('apple-bt-keyboard') - ->create(['category_id' => factory(Category::class)->states('accessory-keyboard-category')->create(['category_type' => 'accessory'])->id]); + $accessory = Accessory::factory()->appleBtKeyboard() + ->create(['category_id' => Category::factory()->accessoryKeyboardCategory()->create(['category_type' => 'accessory'])->id]); $this->assertInstanceOf(App\Models\Category::class, $accessory->category); $this->assertEquals('accessory', $accessory->category->category_type); } @@ -93,7 +94,7 @@ class AccessoryTest extends BaseTest { $this->createValidManufacturer('apple'); $this->createValidCategory('accessory-keyboard-category'); - $accessory = factory(Accessory::class)->states('apple-bt-keyboard')->create(['category_id' => 1]); + $accessory = Accessory::factory()->appleBtKeyboard()->create(['category_id' => 1]); $this->assertInstanceOf(App\Models\Manufacturer::class, $accessory->manufacturer); } } diff --git a/tests/unit/AssetMaintenanceTest.php b/tests/unit/AssetMaintenanceTest.php index 0d56f07d06..1ea522b7b1 100644 --- a/tests/unit/AssetMaintenanceTest.php +++ b/tests/unit/AssetMaintenanceTest.php @@ -1,6 +1,5 @@ is_warranty = ''; $this->assertTrue($c->is_warranty === 0); $c->is_warranty = '4'; - $this->assertTrue($c->is_warranty==4); + $this->assertTrue($c->is_warranty == 4); } /** @@ -31,9 +30,9 @@ class AssetMaintenanceTest extends BaseTest $c->cost = '0.00'; $this->assertTrue($c->cost === null); $c->cost = '9.54'; - $this->assertTrue($c->cost===9.54); + $this->assertTrue($c->cost === 9.54); $c->cost = '9.50'; - $this->assertTrue($c->cost===9.5); + $this->assertTrue($c->cost === 9.5); } /** @@ -45,7 +44,7 @@ class AssetMaintenanceTest extends BaseTest $c->notes = ''; $this->assertTrue($c->notes === null); $c->notes = 'This is a long note'; - $this->assertTrue($c->notes==='This is a long note'); + $this->assertTrue($c->notes === 'This is a long note'); } /** @@ -57,9 +56,8 @@ class AssetMaintenanceTest extends BaseTest $c->completion_date = ''; $this->assertTrue($c->completion_date === null); $c->completion_date = '0000-00-00'; - $this->assertTrue($c->completion_date===null); + $this->assertTrue($c->completion_date === null); $c->completion_date = '2017-05-12'; - $this->assertTrue($c->completion_date==Carbon::parse('2017-05-12')); - + $this->assertTrue($c->completion_date == Carbon::parse('2017-05-12')); } } diff --git a/tests/unit/AssetModelTest.php b/tests/unit/AssetModelTest.php index a65832b7c6..8a5501dce1 100644 --- a/tests/unit/AssetModelTest.php +++ b/tests/unit/AssetModelTest.php @@ -1,4 +1,5 @@ assertFalse($a->isValid()); - $fields = [ + public function testAnAssetModelRequiresAttributes() + { + // An Asset Model requires a name, a category_id, and a manufacturer_id. + $a = AssetModel::create(); + $this->assertFalse($a->isValid()); + $fields = [ 'name' => 'name', 'manufacturer_id' => 'manufacturer id', - 'category_id' => 'category id' + 'category_id' => 'category id', ]; - $errors = $a->getErrors(); - foreach ($fields as $field => $fieldTitle) { - $this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required."); - } - } + $errors = $a->getErrors(); + foreach ($fields as $field => $fieldTitle) { + $this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required."); + } + } - public function testAnAssetModelZerosOutBlankEols() - { - $am = new AssetModel; - $am->eol = ''; - $this->assertTrue($am->eol === 0); - $am->eol = '4'; - $this->assertTrue($am->eol==4); - } + public function testAnAssetModelZerosOutBlankEols() + { + $am = new AssetModel; + $am->eol = ''; + $this->assertTrue($am->eol === 0); + $am->eol = '4'; + $this->assertTrue($am->eol == 4); + } - public function testAnAssetModelContainsAssets() - { - $assetModel = $this->createValidAssetModel(); - $this->createValidAsset([ + public function testAnAssetModelContainsAssets() + { + $assetModel = $this->createValidAssetModel(); + $this->createValidAsset([ 'model_id' => $assetModel->id, ]); - $this->assertEquals(1, $assetModel->assets()->count()); - } + $this->assertEquals(1, $assetModel->assets()->count()); + } - public function testAnAssetModelHasACategory() - { - $assetmodel = $this->createValidAssetModel(); - $this->assertInstanceOf(App\Models\Category::class, $assetmodel->category); - } + public function testAnAssetModelHasACategory() + { + $assetmodel = $this->createValidAssetModel(); + $this->assertInstanceOf(App\Models\Category::class, $assetmodel->category); + } - public function testAnAssetModelHasADepreciation() - { - - $assetmodel = $this->createValidAssetModel(); - $this->assertInstanceOf(App\Models\Depreciation::class, $assetmodel->depreciation); - } - - public function testAnAssetModelHasAManufacturer() - { - $assetmodel = $this->createValidAssetModel(); - $this->assertInstanceOf(App\Models\Manufacturer::class, $assetmodel->manufacturer); - } + public function testAnAssetModelHasADepreciation() + { + $assetmodel = $this->createValidAssetModel(); + $this->assertInstanceOf(App\Models\Depreciation::class, $assetmodel->depreciation); + } + public function testAnAssetModelHasAManufacturer() + { + $assetmodel = $this->createValidAssetModel(); + $this->assertInstanceOf(App\Models\Manufacturer::class, $assetmodel->manufacturer); + } } diff --git a/tests/unit/AssetTest.php b/tests/unit/AssetTest.php index d1b5638859..84b83f1f27 100644 --- a/tests/unit/AssetTest.php +++ b/tests/unit/AssetTest.php @@ -1,4 +1,5 @@ assertFalse($a->isValid()); + $a = Asset::create(); + $this->assertFalse($a->isValid()); - $fields = [ + $fields = [ 'model_id' => 'model id', 'status_id' => 'status id', - 'asset_tag' => 'asset tag' + 'asset_tag' => 'asset tag', ]; - $errors = $a->getErrors(); - foreach ($fields as $field => $fieldTitle) { - $this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required."); - } - } - + $errors = $a->getErrors(); + foreach ($fields as $field => $fieldTitle) { + $this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required."); + } + } public function testAutoIncrementMixed() { @@ -46,7 +45,7 @@ class AssetTest extends BaseTest ['asset_tag' => 'WTF-745'], ['asset_tag' => '0012346'], ['asset_tag' => '00123410'], - ['asset_tag' => 'U8T7597h77'] + ['asset_tag' => 'U8T7597h77'], ]) ); @@ -64,263 +63,261 @@ class AssetTest extends BaseTest ['asset_tag' => 'WTF-745'], ['asset_tag' => '0012346'], ['asset_tag' => '00123410'], - ['asset_tag' => 'U8T7597h77'] + ['asset_tag' => 'U8T7597h77'], ] ); $this->assertEquals($expected, $next); } - - /** * @test */ - public function testWarrantyExpiresAttribute() - { - $asset = factory(Asset::class)->states('laptop-mbp')->create([ + public function testWarrantyExpiresAttribute() + { + $asset = Asset::factory()->laptopMbp()->create([ 'model_id' => $this->createValidAssetModel()->id, 'supplier_id' => $this->createvalidSupplier()->id, - 'rtd_location_id' => $this->createValidLocation()->id + 'rtd_location_id' => $this->createValidLocation()->id, ]); - $asset->purchase_date = Carbon::createFromDate(2017, 1, 1)->hour(0)->minute(0)->second(0); - $asset->warranty_months = 24; - $asset->save(); + $asset->purchase_date = Carbon::createFromDate(2017, 1, 1)->hour(0)->minute(0)->second(0); + $asset->warranty_months = 24; + $asset->save(); - $saved_asset = Asset::find($asset->id); + $saved_asset = Asset::find($asset->id); - $this->tester->assertInstanceOf(\DateTime::class, $saved_asset->purchase_date); - $this->tester->assertEquals( + $this->tester->assertInstanceOf(\DateTime::class, $saved_asset->purchase_date); + $this->tester->assertEquals( Carbon::createFromDate(2017, 1, 1)->format('Y-m-d'), $saved_asset->purchase_date->format('Y-m-d') ); - $this->tester->assertEquals( + $this->tester->assertEquals( Carbon::createFromDate(2017, 1, 1)->setTime(0, 0, 0), $saved_asset->purchase_date ); - $this->tester->assertEquals(24, $saved_asset->warranty_months); - $this->tester->assertInstanceOf(\DateTime::class, $saved_asset->warranty_expires); - $this->tester->assertEquals( + $this->tester->assertEquals(24, $saved_asset->warranty_months); + $this->tester->assertInstanceOf(\DateTime::class, $saved_asset->warranty_expires); + $this->tester->assertEquals( Carbon::createFromDate(2019, 1, 1)->format('Y-m-d'), $saved_asset->warranty_expires->format('Y-m-d') ); - $this->tester->assertEquals( + $this->tester->assertEquals( Carbon::createFromDate(2019, 1, 1)->setTime(0, 0, 0), $saved_asset->warranty_expires ); - } + } - public function testModelIdMustExist() - { - $model = $this->createValidAssetModel(); - $asset = factory(Asset::class)->make([ + public function testModelIdMustExist() + { + $model = $this->createValidAssetModel(); + $asset = Asset::factory()->make([ 'model_id' => $model->id, 'supplier_id' => $this->createValidSupplier()->id, - 'rtd_location_id' => $this->createValidLocation()->id + 'rtd_location_id' => $this->createValidLocation()->id, ]); - $asset->save(); - $this->assertTrue($asset->isValid()); - $newId = $model->id + 1; - $asset = factory(Asset::class)->make(['model_id' => $newId]); - $asset->save(); + $asset->save(); + $this->assertTrue($asset->isValid()); + $newId = $model->id + 1; + $asset = Asset::factory()->make(['model_id' => $newId]); + $asset->save(); - $this->assertFalse($asset->isValid()); - } + $this->assertFalse($asset->isValid()); + } - public function testAnAssetHasRelationships() - { - $asset = factory(Asset::class)->states('laptop-mbp') + public function testAnAssetHasRelationships() + { + $asset = Asset::factory()->laptopMbp() ->create([ 'model_id' => $this->createValidAssetModel()->id, 'company_id' => $this->createValidCompany()->id, 'supplier_id' => $this->createValidSupplier()->id, ]); - $this->assertInstanceOf(AssetModel::class, $asset->model); - $this->assertInstanceOf(Company::class, $asset->company); - $this->assertInstanceOf(App\Models\Depreciation::class, $asset->depreciation); - $this->assertInstanceOf(App\Models\Statuslabel::class, $asset->assetstatus); - $this->assertInstanceOf(App\Models\Supplier::class, $asset->supplier); - } + $this->assertInstanceOf(AssetModel::class, $asset->model); + $this->assertInstanceOf(Company::class, $asset->company); + $this->assertInstanceOf(App\Models\Depreciation::class, $asset->depreciation); + $this->assertInstanceOf(App\Models\Statuslabel::class, $asset->assetstatus); + $this->assertInstanceOf(App\Models\Supplier::class, $asset->supplier); + } - public function testAnAssetCanBeAvailableForCheckout() - { - // Logic: If the asset is not assigned to anyone, - // and the statuslabel type is "deployable" - // and the asset is not deleted - // Then it is available for checkout + public function testAnAssetCanBeAvailableForCheckout() + { + // Logic: If the asset is not assigned to anyone, + // and the statuslabel type is "deployable" + // and the asset is not deleted + // Then it is available for checkout - // An asset assigned to someone should not be available for checkout. - $assetAssigned = factory(Asset::class) - ->states('laptop-mbp', 'assigned-to-user') + // An asset assigned to someone should not be available for checkout. + $assetAssigned = Asset::factory()->laptopMbp()->assignedToUser() ->create(['model_id' => $this->createValidAssetModel()]); - $this->assertFalse($assetAssigned->availableForCheckout()); + $this->assertFalse($assetAssigned->availableForCheckout()); - // An asset with a non deployable statuslabel should not be available for checkout. - $assetUndeployable = factory(Asset::class)->create([ + // An asset with a non deployable statuslabel should not be available for checkout. + $assetUndeployable = Asset::factory()->create([ 'status_id' => $this->createValidStatuslabel('archived')->id, - 'model_id' => $this->createValidAssetModel() + 'model_id' => $this->createValidAssetModel(), ]); - $this->assertFalse($assetUndeployable->availableForCheckout()); + $this->assertFalse($assetUndeployable->availableForCheckout()); - // An asset that has been deleted is not avaiable for checkout. - $assetDeleted = factory(Asset::class)->states('deleted')->create([ - 'model_id' => $this->createValidAssetModel() + // An asset that has been deleted is not avaiable for checkout. + $assetDeleted = Asset::factory()->deleted()->create([ + 'model_id' => $this->createValidAssetModel(), ]); - $this->assertFalse($assetDeleted->availableForCheckout()); + $this->assertFalse($assetDeleted->availableForCheckout()); - // A ready to deploy asset that isn't assigned to anyone is available for checkout - $asset = factory(Asset::class)->create([ + // A ready to deploy asset that isn't assigned to anyone is available for checkout + $asset = Asset::factory()->create([ 'status_id' => $this->createValidStatuslabel('rtd')->id, - 'model_id' => $this->createValidAssetModel() + 'model_id' => $this->createValidAssetModel(), ]); - $this->assertTrue($asset->availableForCheckout()); - } + $this->assertTrue($asset->availableForCheckout()); + } - public function testAnAssetCanHaveComponents() - { - $asset = $this->createValidAsset(); + public function testAnAssetCanHaveComponents() + { + $asset = $this->createValidAsset(); - $components = factory(App\Models\Component::class, 5)->states('ram-crucial4')->create([ - 'category_id' => $this->createValidCategory('component-hdd-category')->id + $components = \App\Models\Component::factory()->count(5)->ramCrucial4()->create([ + 'category_id' => $this->createValidCategory('component-hdd-category')->id, ]); - $components->each(function($component) use ($asset) { - $component->assets()->attach($component, [ - 'asset_id'=>$asset->id + $components->each(function ($component) use ($asset) { + $component->assets()->attach($component, [ + 'asset_id'=>$asset->id, ]); - }); - $this->assertInstanceOf(App\Models\Component::class, $asset->components()->first()); - $this->assertCount(5, $asset->components); - } + }); + $this->assertInstanceOf(App\Models\Component::class, $asset->components()->first()); + $this->assertCount(5, $asset->components); + } - public function testAnAssetCanHaveUploads() - { - $asset = $this->createValidAsset([ - 'supplier_id' => $this->createValidSupplier()->id + public function testAnAssetCanHaveUploads() + { + $asset = $this->createValidAsset([ + 'supplier_id' => $this->createValidSupplier()->id, ]); - $this->assertCount(0, $asset->uploads); - factory(App\Models\Actionlog::class, 'asset-upload')->create(['item_id' => $asset->id]); - $this->assertCount(1, $asset->fresh()->uploads); - } + $this->assertCount(0, $asset->uploads); + \App\Models\Actionlog::factory()->count('asset-upload')->create(['item_id' => $asset->id]); + $this->assertCount(1, $asset->fresh()->uploads); + } // Helper Method for checking in assets.... We should extract this to the model or a trait. - private function checkin($asset, $target) { - $asset->expected_checkin = null; - $asset->last_checkout = null; - $asset->assigned_to = null; - $asset->assigned_type = null; - $asset->location_id = $asset->rtd_location_id; - $asset->assignedTo()->disassociate($asset); - $asset->accepted = null; - $asset->save(); - $asset->logCheckin($target, 'Test Checkin'); - } + private function checkin($asset, $target) + { + $asset->expected_checkin = null; + $asset->last_checkout = null; + $asset->assigned_to = null; + $asset->assigned_type = null; + $asset->location_id = $asset->rtd_location_id; + $asset->assignedTo()->disassociate($asset); + $asset->accepted = null; + $asset->save(); + $asset->logCheckin($target, 'Test Checkin'); + } - public function testAnAssetCanBeCheckedOut() - { - // This tests Asset::checkOut(), Asset::assignedTo(), Asset::assignedAssets(), Asset::assetLoc(), Asset::assignedType(), defaultLoc() - $asset = $this->createValidAsset(); - $adminUser = $this->signIn(); + public function testAnAssetCanBeCheckedOut() + { + // This tests Asset::checkOut(), Asset::assignedTo(), Asset::assignedAssets(), Asset::assetLoc(), Asset::assignedType(), defaultLoc() + $asset = $this->createValidAsset(); + $adminUser = $this->signIn(); - $target = factory(App\Models\User::class)->create([ - 'location_id' => factory(App\Models\Location::class)->create() + $target = \App\Models\User::factory()->create([ + 'location_id' => \App\Models\Location::factory()->create(), ]); - // An Asset Can be checked out to a user, and this should be logged. - $asset->checkOut($target, $adminUser); - $asset->save(); - $this->assertInstanceOf(App\Models\User::class, $asset->assignedTo); + // An Asset Can be checked out to a user, and this should be logged. + $asset->checkOut($target, $adminUser); + $asset->save(); + $this->assertInstanceOf(App\Models\User::class, $asset->assignedTo); - $this->assertEquals($asset->location->id, $target->userLoc->id); - $this->assertEquals('user', $asset->assignedType()); - $this->assertEquals($asset->defaultLoc->id, $asset->rtd_location_id); - $this->tester->seeRecord('action_logs', [ + $this->assertEquals($asset->location->id, $target->userLoc->id); + $this->assertEquals('user', $asset->assignedType()); + $this->assertEquals($asset->defaultLoc->id, $asset->rtd_location_id); + $this->tester->seeRecord('action_logs', [ 'action_type' => 'checkout', 'target_type' => get_class($target), - 'target_id' => $target->id + 'target_id' => $target->id, ]); - $this->tester->seeRecord('assets', [ + $this->tester->seeRecord('assets', [ 'id' => $asset->id, 'assigned_to' => $target->id, - 'assigned_type' => User::class + 'assigned_type' => User::class, ]); - $this->checkin($asset, $target); - $this->assertNull($asset->fresh()->assignedTo); + $this->checkin($asset, $target); + $this->assertNull($asset->fresh()->assignedTo); - $this->tester->seeRecord('action_logs', [ + $this->tester->seeRecord('action_logs', [ 'action_type' => 'checkin from', 'target_type' => get_class($target), - 'target_id' => $target->id + 'target_id' => $target->id, ]); - $this->tester->seeRecord('assets', [ + $this->tester->seeRecord('assets', [ 'id' => $asset->id, 'assigned_to' => null, - 'assigned_type' => null + 'assigned_type' => null, ]); - // An Asset Can be checked out to a asset, and this should be logged. - $target = $this->createValidAsset(); + // An Asset Can be checked out to a asset, and this should be logged. + $target = $this->createValidAsset(); - $asset->checkOut($target, $adminUser); - $asset->save(); - $this->assertInstanceOf(App\Models\Asset::class, $asset->fresh()->assignedTo); - $this->assertEquals($asset->fresh()->location->id, $target->fresh()->location->id); - $this->assertEquals('asset', $asset->assignedType()); - $this->assertEquals($asset->defaultLoc->id, $asset->rtd_location_id); - $this->tester->seeRecord('action_logs', [ + $asset->checkOut($target, $adminUser); + $asset->save(); + $this->assertInstanceOf(App\Models\Asset::class, $asset->fresh()->assignedTo); + $this->assertEquals($asset->fresh()->location->id, $target->fresh()->location->id); + $this->assertEquals('asset', $asset->assignedType()); + $this->assertEquals($asset->defaultLoc->id, $asset->rtd_location_id); + $this->tester->seeRecord('action_logs', [ 'action_type' => 'checkout', 'target_type' => get_class($target), - 'target_id' => $target->id + 'target_id' => $target->id, ]); - $this->assertCount(1, $target->assignedAssets); - $this->checkin($asset, $target); - $this->assertNull($asset->fresh()->assignedTo); + $this->assertCount(1, $target->assignedAssets); + $this->checkin($asset, $target); + $this->assertNull($asset->fresh()->assignedTo); - $this->tester->seeRecord('action_logs', [ + $this->tester->seeRecord('action_logs', [ 'action_type' => 'checkin from', 'target_type' => get_class($target), - 'target_id' => $target->id + 'target_id' => $target->id, ]); - // An Asset cannot be checked out to itself. - $target = $this->createValidAsset(); - $this->expectException(CheckoutNotAllowed::class); - $target->checkOut($target, $adminUser); + // An Asset cannot be checked out to itself. + $target = $this->createValidAsset(); + $this->expectException(CheckoutNotAllowed::class); + $target->checkOut($target, $adminUser); - // An Asset Can be checked out to a location, and this should be logged. - $target = $this->createValidLocation(); + // An Asset Can be checked out to a location, and this should be logged. + $target = $this->createValidLocation(); - $asset->checkOut($target, $adminUser); - $asset->save(); - $this->assertInstanceOf(App\Models\Location::class, $asset->fresh()->assignedTo); + $asset->checkOut($target, $adminUser); + $asset->save(); + $this->assertInstanceOf(App\Models\Location::class, $asset->fresh()->assignedTo); - $this->assertEquals($asset->fresh()->location->id, $target->fresh()->id); - $this->assertEquals('location', $asset->assignedType()); - $this->assertEquals($asset->defaultLoc->id, $asset->rtd_location_id); - $this->tester->seeRecord('action_logs', [ + $this->assertEquals($asset->fresh()->location->id, $target->fresh()->id); + $this->assertEquals('location', $asset->assignedType()); + $this->assertEquals($asset->defaultLoc->id, $asset->rtd_location_id); + $this->tester->seeRecord('action_logs', [ 'action_type' => 'checkout', 'target_type' => get_class($target), - 'target_id' => $target->id + 'target_id' => $target->id, ]); - $this->checkin($asset, $target); - $this->assertNull($asset->fresh()->assignedTo); + $this->checkin($asset, $target); + $this->assertNull($asset->fresh()->assignedTo); - $this->tester->seeRecord('action_logs', [ + $this->tester->seeRecord('action_logs', [ 'action_type' => 'checkin from', 'target_type' => get_class($target), - 'target_id' => $target->id + 'target_id' => $target->id, ]); - } + } - public function testAnAssetHasMaintenances() - { - $asset = $this->createValidAsset(); - factory(App\Models\AssetMaintenance::class)->create(['asset_id' => $asset->id]); - $this->assertCount(1, $asset->assetmaintenances); - } + public function testAnAssetHasMaintenances() + { + $asset = $this->createValidAsset(); + \App\Models\AssetMaintenance::factory()->create(['asset_id' => $asset->id]); + $this->assertCount(1, $asset->assetmaintenances); + } } diff --git a/tests/unit/BaseTest.php b/tests/unit/BaseTest.php index 16b171193a..a2e81599b1 100644 --- a/tests/unit/BaseTest.php +++ b/tests/unit/BaseTest.php @@ -1,4 +1,5 @@ create(); + \App\Models\Setting::factory()->create(); } protected function signIn($user = null) { - if (!$user) { - $user = factory(User::class)->states('superuser')->create([ - 'location_id' => $this->createValidLocation()->id + if (! $user) { + $user = User::factory()->superuser()->create([ + 'location_id' => $this->createValidLocation()->id, ]); } Auth::login($user); @@ -25,64 +27,62 @@ class BaseTest extends \Codeception\TestCase\Test return $user; } - protected function createValidAssetModel($state = 'mbp-13-model', $overrides = []) { - return factory(\App\Models\AssetModel::class)->states($state)->create(array_merge([ + return \App\Models\AssetModel::factory()->state()->create(array_merge([ 'category_id' => $this->createValidCategory(), 'manufacturer_id' => $this->createValidManufacturer(), 'depreciation_id' => $this->createValidDepreciation(), - ],$overrides)); + ], $overrides)); } protected function createValidCategory($state = 'asset-laptop-category', $overrides = []) { - return factory(App\Models\Category::class)->states($state)->create($overrides); + return \App\Models\Category::factory()->state()->create($overrides); } protected function createValidCompany($overrides = []) { - return factory(App\Models\Company::class)->create($overrides); + return \App\Models\Company::factory()->create($overrides); } - protected function createValidDepartment($state = 'engineering', $overrides = []) { - return factory(App\Models\Department::class)->states($state)->create(array_merge([ - 'location_id' => $this->createValidLocation()->id + return \App\Models\Department::factory()->state()->create(array_merge([ + 'location_id' => $this->createValidLocation()->id, ], $overrides)); } protected function createValidDepreciation($state = 'computer', $overrides = []) { - return factory(App\Models\Depreciation::class)->states($state)->create($overrides); + return \App\Models\Depreciation::factory()->state()->create($overrides); } protected function createValidLocation($overrides = []) { - return factory(App\Models\Location::class)->create($overrides); + return \App\Models\Location::factory()->create($overrides); } protected function createValidManufacturer($state = 'apple', $overrides = []) { - return factory(App\Models\Manufacturer::class)->states($state)->create($overrides); + return \App\Models\Manufacturer::factory()->state()->create($overrides); } protected function createValidSupplier($overrides = []) { - return factory(App\Models\Supplier::class)->create($overrides); + return \App\Models\Supplier::factory()->create($overrides); } - protected function createValidStatuslabel($state = 'rtd', $overrides= []) + protected function createValidStatuslabel($state = 'rtd', $overrides = []) { - return factory(App\Models\Statuslabel::class)->states($state)->create($overrides); + return \App\Models\Statuslabel::factory()->state()->create($overrides); } - protected function createValidUser($overrides= []) + protected function createValidUser($overrides = []) { - return factory(App\Models\User::class)->create( - array_merge([ - 'location_id'=>$this->createValidLocation()->id + return \App\Models\User::factory()->create( + array_merge([ + 'location_id'=>$this->createValidLocation()->id, ], $overrides) ); } @@ -91,14 +91,13 @@ class BaseTest extends \Codeception\TestCase\Test { $locId = $this->createValidLocation()->id; $this->createValidAssetModel(); - return factory(\App\Models\Asset::class)->states('laptop-mbp')->create( + + return \App\Models\Asset::factory()->laptopMbp()->create( array_merge([ 'rtd_location_id' => $locId, 'location_id' => $locId, - 'supplier_id' => $this->createValidSupplier()->id + 'supplier_id' => $this->createValidSupplier()->id, ], $overrides) ); } - - } diff --git a/tests/unit/CategoryTest.php b/tests/unit/CategoryTest.php index 69fc841ac9..88ca9c3d28 100644 --- a/tests/unit/CategoryTest.php +++ b/tests/unit/CategoryTest.php @@ -1,9 +1,10 @@ assertFalse($a->isValid()); + $a = Category::create(); + $this->assertFalse($a->isValid()); - $fields = [ + $fields = [ 'name' => 'name', - 'category_type' => 'category type' + 'category_type' => 'category type', ]; - $errors = $a->getErrors(); - foreach ($fields as $field => $fieldTitle) { - $this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required."); - } - } + $errors = $a->getErrors(); + foreach ($fields as $field => $fieldTitle) { + $this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required."); + } + } - public function testACategoryCanHaveAssets() - { - $this->createValidAssetModel(); //This will seed various things to make the following work better. - $category = $this->createValidCategory('asset-desktop-category'); - $models = factory(App\Models\AssetModel::class, 5)->states('mbp-13-model')->create(['category_id' => $category->id]); + public function testACategoryCanHaveAssets() + { + $this->createValidAssetModel(); //This will seed various things to make the following work better. + $category = $this->createValidCategory('asset-desktop-category'); + $models = \App\Models\AssetModel::factory()->count(5)->mbp13Model()->create(['category_id' => $category->id]); - $this->assertEquals(5, $category->models->count()); - $this->assertCount(5, $category->models); + $this->assertEquals(5, $category->models->count()); + $this->assertCount(5, $category->models); - $models->each(function($model) { + $models->each(function ($model) { // This is intentionally run twice to generate the ten imagined assets, done this way to keep it in sync with createValidAsset rather than using the factory directly. - $this->createValidAsset(['model_id' => $model->id]); - $this->createValidAsset(['model_id' => $model->id]); - }); - $this->assertEquals(10, $category->itemCount()); - } + $this->createValidAsset(['model_id' => $model->id]); + $this->createValidAsset(['model_id' => $model->id]); + }); + $this->assertEquals(10, $category->itemCount()); + } - public function testACategoryCanHaveAccessories() - { - $category = $this->createValidCategory('accessory-keyboard-category'); - factory(App\Models\Accessory::class, 5)->states('apple-bt-keyboard')->create(['category_id' => $category->id]); + public function testACategoryCanHaveAccessories() + { + $category = $this->createValidCategory('accessory-keyboard-category'); + \App\Models\Accessory::factory()->count(5)->appleBtKeyboard()->create(['category_id' => $category->id]); - $this->assertCount(5, $category->accessories); - $this->assertEquals(5, $category->itemCount()); - } + $this->assertCount(5, $category->accessories); + $this->assertEquals(5, $category->itemCount()); + } - public function testACategoryCanHaveConsumables() - { - $category = $this->createValidCategory('consumable-paper-category'); - factory(App\Models\Consumable::class, 5)->states('cardstock')->create(['category_id' => $category->id]); - $this->assertCount(5, $category->consumables); - $this->assertEquals(5, $category->itemCount()); - } + public function testACategoryCanHaveConsumables() + { + $category = $this->createValidCategory('consumable-paper-category'); + \App\Models\Consumable::factory()->count(5)->cardstock()->create(['category_id' => $category->id]); + $this->assertCount(5, $category->consumables); + $this->assertEquals(5, $category->itemCount()); + } - public function testACategoryCanHaveComponents() - { - $category = $this->createValidCategory('component-ram-category'); - factory(App\Models\Component::class, 5)->states('ram-crucial4')->create(['category_id' => $category->id]); - $this->assertCount(5, $category->components); - $this->assertEquals(5, $category->itemCount()); - } + public function testACategoryCanHaveComponents() + { + $category = $this->createValidCategory('component-ram-category'); + \App\Models\Component::factory()->count(5)->ramCrucial4()->create(['category_id' => $category->id]); + $this->assertCount(5, $category->components); + $this->assertEquals(5, $category->itemCount()); + } } diff --git a/tests/unit/CompanyTest.php b/tests/unit/CompanyTest.php index 22ac12bd87..7fe40ddb25 100644 --- a/tests/unit/CompanyTest.php +++ b/tests/unit/CompanyTest.php @@ -1,9 +1,10 @@ assertFalse($a->isValid()); + $a = Company::create(); + $this->assertFalse($a->isValid()); - $fields = [ + $fields = [ 'name' => 'name', ]; - $errors = $a->getErrors(); - foreach ($fields as $field => $fieldTitle) { - $this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required."); - } - } + $errors = $a->getErrors(); + foreach ($fields as $field => $fieldTitle) { + $this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required."); + } + } - public function testACompanyCanHaveUsers() - { - $company = $this->createValidCompany(); - $user = $this->createValidUser(['company_id'=>$company->id]); - $this->assertCount(1, $company->users); - } + public function testACompanyCanHaveUsers() + { + $company = $this->createValidCompany(); + $user = $this->createValidUser(['company_id'=>$company->id]); + $this->assertCount(1, $company->users); + } - public function testACompanyCanHaveAssets() - { - $company = $this->createValidCompany(); - $this->createValidAsset(['company_id' => $company->id]); - $this->assertCount(1, $company->assets); - } + public function testACompanyCanHaveAssets() + { + $company = $this->createValidCompany(); + $this->createValidAsset(['company_id' => $company->id]); + $this->assertCount(1, $company->assets); + } - public function testACompanyCanHaveLicenses() - { - $company = $this->createValidCompany(); - factory(App\Models\License::class, 1)->states('acrobat')->create([ + public function testACompanyCanHaveLicenses() + { + $company = $this->createValidCompany(); + \App\Models\License::factory()->count(1)->acrobat()->create([ 'company_id'=>$company->id, - 'manufacturer_id' => factory(App\Models\Manufacturer::class)->states('adobe')->create()->id, - 'category_id' => factory(App\Models\Category::class)->states('license-office-category')->create()->id + 'manufacturer_id' => \App\Models\Manufacturer::factory()->adobe()->create()->id, + 'category_id' => \App\Models\Category::factory()->licenseOfficeCategory()->create()->id, ]); - $this->assertCount(1, $company->licenses); - } + $this->assertCount(1, $company->licenses); + } - public function testACompanyCanHaveAccessories() - { - $company = $this->createValidCompany(); - $a = factory(App\Models\Accessory::class)->states('apple-bt-keyboard')->create([ - 'category_id' => factory(App\Models\Category::class)->states('accessory-keyboard-category')->create()->id, - 'company_id' => $company->id - ]); - - $this->assertCount(1, $company->accessories); - } - - public function testACompanyCanHaveConsumables() - { - $company = $this->createValidCompany(); - factory(App\Models\Consumable::class, 1)->states('cardstock')->create([ + public function testACompanyCanHaveAccessories() + { + $company = $this->createValidCompany(); + $a = \App\Models\Accessory::factory()->appleBtKeyboard()->create([ + 'category_id' => \App\Models\Category::factory()->accessoryKeyboardCategory()->create()->id, 'company_id' => $company->id, - 'category_id' => factory(App\Models\Category::class)->states('consumable-paper-category')->create()->id ]); - $this->assertCount(1, $company->consumables); - } - public function testACompanyCanHaveComponents() - { - $company = $this->createValidCompany(); - factory(App\Models\Component::class, 1)->states('ram-crucial4')->create([ - 'company_id'=>$company->id, - 'category_id' => factory(App\Models\Category::class)->states('component-ram-category')->create()->id + $this->assertCount(1, $company->accessories); + } + + public function testACompanyCanHaveConsumables() + { + $company = $this->createValidCompany(); + \App\Models\Consumable::factory()->count(1)->cardstock()->create([ + 'company_id' => $company->id, + 'category_id' => \App\Models\Category::factory()->consumablePaperCategory()->create()->id, ]); - $this->assertCount(1, $company->components); - } + $this->assertCount(1, $company->consumables); + } + + public function testACompanyCanHaveComponents() + { + $company = $this->createValidCompany(); + \App\Models\Component::factory()->count(1)->ramCrucial4()->create([ + 'company_id'=>$company->id, + 'category_id' => \App\Models\Category::factory()->componentRamCategory()->create()->id, + ]); + $this->assertCount(1, $company->components); + } } diff --git a/tests/unit/ComponentTest.php b/tests/unit/ComponentTest.php index 1e167955a6..985c2c8f7a 100644 --- a/tests/unit/ComponentTest.php +++ b/tests/unit/ComponentTest.php @@ -1,4 +1,5 @@ 'name', 'qty' => 'qty', - 'category_id' => 'category id' + 'category_id' => 'category id', ]; $errors = $a->getErrors(); foreach ($fields as $field => $fieldTitle) { @@ -36,15 +37,15 @@ class ComponentTest extends BaseTest // An Component name has a min length of 3 // An Component has a min qty of 1 // An Component has a min amount of 0 - $a = factory(Component::class)->make([ + $a = Component::factory()->make([ 'name' => 'a', 'qty' => 0, - 'min_amt' => -1 + 'min_amt' => -1, ]); $fields = [ 'name' => 'name', 'qty' => 'qty', - 'min_amt' => 'min amt' + 'min_amt' => 'min amt', ]; $this->assertFalse($a->isValid()); $errors = $a->getErrors(); @@ -55,44 +56,42 @@ class ComponentTest extends BaseTest public function testCategoryIdMustExist() { - $category = $this->createValidCategory('component-hdd-category', + $category = $this->createValidCategory('component-hdd-category', ['category_type' => 'component']); - $component = factory(Component::class) - ->states('ssd-crucial240') + $component = Component::factory()->ssdCrucial240() ->make(['category_id' => $category->id]); $this->createValidManufacturer('apple'); $component->save(); $this->assertTrue($component->isValid()); $newId = $category->id + 1; - $component = factory(Component::class)->states('ssd-crucial240')->make(['category_id' => $newId]); + $component = Component::factory()->ssdCrucial240()->make(['category_id' => $newId]); $component->save(); $this->assertFalse($component->isValid()); - $this->assertStringContainsString("The selected category id is invalid.", $component->getErrors()->get('category_id')[0]); + $this->assertStringContainsString('The selected category id is invalid.', $component->getErrors()->get('category_id')[0]); } public function testAnComponentBelongsToACompany() { - $component = factory(Component::class) - ->create(['company_id' => factory(Company::class)->create()->id]); + $component = Component::factory() + ->create(['company_id' => Company::factory()->create()->id]); $this->assertInstanceOf(Company::class, $component->company); } public function testAnComponentHasALocation() { - $component = factory(Component::class) - ->create(['location_id' => factory(Location::class)->create()->id]); + $component = Component::factory() + ->create(['location_id' => Location::factory()->create()->id]); $this->assertInstanceOf(Location::class, $component->location); } public function testAnComponentBelongsToACategory() { - $component = factory(Component::class)->states('ssd-crucial240') + $component = Component::factory()->ssdCrucial240() ->create([ - 'category_id' => factory(Category::class) - ->states('component-hdd-category') - ->create(['category_type' => 'component'])->id + 'category_id' => Category::factory()->componentHddCategory() + ->create(['category_type' => 'component'])->id, ]); $this->assertInstanceOf(Category::class, $component->category); $this->assertEquals('component', $component->category->category_type); diff --git a/tests/unit/ConsumableTest.php b/tests/unit/ConsumableTest.php index 1126594a19..276699e6f2 100644 --- a/tests/unit/ConsumableTest.php +++ b/tests/unit/ConsumableTest.php @@ -1,9 +1,10 @@ assertFalse($a->isValid()); + $a = Consumable::create(); + $this->assertFalse($a->isValid()); - $fields = [ + $fields = [ 'name' => 'name', 'qty' => 'qty', - 'category_id' => 'category id' + 'category_id' => 'category id', ]; - $errors = $a->getErrors(); - foreach ($fields as $field => $fieldTitle) { - $this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required."); - } - } + $errors = $a->getErrors(); + foreach ($fields as $field => $fieldTitle) { + $this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required."); + } + } - public function testAConsumableHasRelationships() - { - $consumable = factory(Consumable::class)->states('cardstock')->create([ + public function testAConsumableHasRelationships() + { + $consumable = Consumable::factory()->cardstock()->create([ 'category_id' => $this->createValidCategory('consumable-paper-category')->id, 'manufacturer_id' => $this->createValidManufacturer('apple')->id, 'company_id' => $this->createValidCompany()->id, 'location_id' => $this->createValidLocation()->id, - 'user_id' => $this->signIn()->id + 'user_id' => $this->signIn()->id, ]); - - $this->assertInstanceOf(App\Models\User::class, $consumable->admin); - $this->assertInstanceOf(App\Models\Company::class, $consumable->company); - $this->assertInstanceOf(App\Models\Manufacturer::class, $consumable->manufacturer); - $this->assertInstanceOf(App\Models\Location::class, $consumable->location); - $this->assertInstanceOf(App\Models\Category::class, $consumable->category); - } + $this->assertInstanceOf(App\Models\User::class, $consumable->admin); + $this->assertInstanceOf(App\Models\Company::class, $consumable->company); + $this->assertInstanceOf(App\Models\Manufacturer::class, $consumable->manufacturer); + $this->assertInstanceOf(App\Models\Location::class, $consumable->location); + $this->assertInstanceOf(App\Models\Category::class, $consumable->category); + } } diff --git a/tests/unit/CustomFieldTest.php b/tests/unit/CustomFieldTest.php index 973bc2bb90..33fbae5db7 100644 --- a/tests/unit/CustomFieldTest.php +++ b/tests/unit/CustomFieldTest.php @@ -1,9 +1,10 @@ make(['format' => 'IP']); + $customfield = CustomField::factory()->make(['format' => 'IP']); $values = [ 'name' => $customfield->name, 'format' => $customfield->format, @@ -28,75 +29,73 @@ class CustomFieldTest extends BaseTest ]; $this->assertEquals($customfield->getAttributes()['format'], CustomField::PREDEFINED_FORMATS['IP']); //this seems undocumented... - $this->assertEquals($customfield->format, "IP"); + $this->assertEquals($customfield->format, 'IP'); } public function testDbNameAscii() { $customfield = new CustomField(); - $customfield->name = "My hovercraft is full of eels"; + $customfield->name = 'My hovercraft is full of eels'; $customfield->id = 1337; - $this->assertEquals($customfield->convertUnicodeDbSlug(), "_snipeit_my_hovercraft_is_full_of_eels_1337"); + $this->assertEquals($customfield->convertUnicodeDbSlug(), '_snipeit_my_hovercraft_is_full_of_eels_1337'); } // Western Europe public function testDbNameLatin() { - $customfield=new CustomField(); - $customfield->name="My hovercraft is full of eels"; + $customfield = new CustomField(); + $customfield->name = 'My hovercraft is full of eels'; $customfield->id = 1337; - $this->assertEquals($customfield->convertUnicodeDbSlug(), "_snipeit_my_hovercraft_is_full_of_eels_1337"); + $this->assertEquals($customfield->convertUnicodeDbSlug(), '_snipeit_my_hovercraft_is_full_of_eels_1337'); } - // Asian public function testDbNameChinese() { - $customfield=new CustomField(); - $customfield->name="我的氣墊船裝滿了鱔魚"; + $customfield = new CustomField(); + $customfield->name = '我的氣墊船裝滿了鱔魚'; $customfield->id = 1337; if (function_exists('transliterator_transliterate')) { - $this->assertEquals($customfield->convertUnicodeDbSlug(), "_snipeit_wo_de_qi_dian_chuan_zhuang_man_le_shan_yu_1337"); + $this->assertEquals($customfield->convertUnicodeDbSlug(), '_snipeit_wo_de_qi_dian_chuan_zhuang_man_le_shan_yu_1337'); } else { - $this->assertEquals($customfield->convertUnicodeDbSlug(), "_snipeit_aecsae0ase1eaeaeoees_1337"); + $this->assertEquals($customfield->convertUnicodeDbSlug(), '_snipeit_aecsae0ase1eaeaeoees_1337'); } } public function testDbNameJapanese() { - $customfield=new CustomField(); - $customfield->name="私のホバークラフトは鰻でいっぱいです"; + $customfield = new CustomField(); + $customfield->name = '私のホバークラフトは鰻でいっぱいです'; $customfield->id = 1337; if (function_exists('transliterator_transliterate')) { - $this->assertEquals($customfield->convertUnicodeDbSlug(), "_snipeit_sinohohakurafutoha_manteihhaitesu_1337"); + $this->assertEquals($customfield->convertUnicodeDbSlug(), '_snipeit_sinohohakurafutoha_manteihhaitesu_1337'); } else { - $this->assertEquals($customfield->convertUnicodeDbSlug(), "_snipeit_caafafafaafcafafae0aaaaaaa_1337"); + $this->assertEquals($customfield->convertUnicodeDbSlug(), '_snipeit_caafafafaafcafafae0aaaaaaa_1337'); } } public function testDbNameKorean() { $customfield = new CustomField(); - $customfield->name = "내 호버크라프트는 장어로 가득 차 있어요"; + $customfield->name = '내 호버크라프트는 장어로 가득 차 있어요'; $customfield->id = 1337; if (function_exists('transliterator_transliterate')) { - $this->assertEquals($customfield->convertUnicodeDbSlug(), "_snipeit_nae_hobeokeulapeuteuneun_jang_eolo_gadeug_1337"); + $this->assertEquals($customfield->convertUnicodeDbSlug(), '_snipeit_nae_hobeokeulapeuteuneun_jang_eolo_gadeug_1337'); } else { - $this->assertEquals($customfield->convertUnicodeDbSlug(), "_snipeit_e_ie2ieiises_izieoe_e0e_i0_iziis_1337"); + $this->assertEquals($customfield->convertUnicodeDbSlug(), '_snipeit_e_ie2ieiises_izieoe_e0e_i0_iziis_1337'); } - } // Nordic languages public function testDbNameNonLatinEuro() { $customfield = new CustomField(); - $customfield->name = "Mój poduszkowiec jest pełen węgorzy"; + $customfield->name = 'Mój poduszkowiec jest pełen węgorzy'; $customfield->id = 1337; if (function_exists('transliterator_transliterate')) { - $this->assertEquals($customfield->convertUnicodeDbSlug(), "_snipeit_moj_poduszkowiec_jest_pelen_wegorzy_1337"); + $this->assertEquals($customfield->convertUnicodeDbSlug(), '_snipeit_moj_poduszkowiec_jest_pelen_wegorzy_1337'); } else { - $this->assertEquals($customfield->convertUnicodeDbSlug(), "_snipeit_ma3j_poduszkowiec_jest_peaen_waegorzy_1337"); + $this->assertEquals($customfield->convertUnicodeDbSlug(), '_snipeit_ma3j_poduszkowiec_jest_peaen_waegorzy_1337'); } } @@ -104,24 +103,24 @@ class CustomFieldTest extends BaseTest public function testDbNameTurkish() { $customfield = new CustomField(); - $customfield->name = "Hoverkraftım yılan balığı dolu"; + $customfield->name = 'Hoverkraftım yılan balığı dolu'; $customfield->id = 1337; if (function_exists('transliterator_transliterate')) { - $this->assertEquals($customfield->convertUnicodeDbSlug(), "_snipeit_hoverkraftim_yilan_baligi_dolu_1337"); + $this->assertEquals($customfield->convertUnicodeDbSlug(), '_snipeit_hoverkraftim_yilan_baligi_dolu_1337'); } else { - $this->assertEquals($customfield->convertUnicodeDbSlug(), "_snipeit_hoverkraftaem_yaelan_balaeaeyae_dolu_1337"); + $this->assertEquals($customfield->convertUnicodeDbSlug(), '_snipeit_hoverkraftaem_yaelan_balaeaeyae_dolu_1337'); } } public function testDbNameArabic() { - $customfield=new CustomField(); - $customfield->name="حَوّامتي مُمْتِلئة بِأَنْقَلَيْسون"; + $customfield = new CustomField(); + $customfield->name = 'حَوّامتي مُمْتِلئة بِأَنْقَلَيْسون'; $customfield->id = 1337; if (function_exists('transliterator_transliterate')) { - $this->assertEquals($customfield->convertUnicodeDbSlug(), "_snipeit_hwamty_mmtlyt_banqlyswn_1337"); + $this->assertEquals($customfield->convertUnicodeDbSlug(), '_snipeit_hwamty_mmtlyt_banqlyswn_1337'); } else { - $this->assertEquals($customfield->convertUnicodeDbSlug(), "_snipeit_ouzuuouoaus_uuuuoauuooc_ououzuuuuzuuzusuo_1337"); + $this->assertEquals($customfield->convertUnicodeDbSlug(), '_snipeit_ouzuuouoaus_uuuuoauuooc_ououzuuuuzuuzusuo_1337'); } } } diff --git a/tests/unit/DepartmentTest.php b/tests/unit/DepartmentTest.php index 92e77e3afb..ad20285dba 100644 --- a/tests/unit/DepartmentTest.php +++ b/tests/unit/DepartmentTest.php @@ -1,4 +1,5 @@ tester->seeRecord('departments', $values); // } - } diff --git a/tests/unit/DepreciationTest.php b/tests/unit/DepreciationTest.php index 9e442b1d4a..69dccb5ce9 100644 --- a/tests/unit/DepreciationTest.php +++ b/tests/unit/DepreciationTest.php @@ -1,8 +1,9 @@ assertFalse($a->isValid()); + $a = Depreciation::create(); + $this->assertFalse($a->isValid()); - $fields = [ + $fields = [ 'name' => 'name', 'months' => 'months', ]; - $errors = $a->getErrors(); - foreach ($fields as $field => $fieldTitle) { - $this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required."); - } - } + $errors = $a->getErrors(); + foreach ($fields as $field => $fieldTitle) { + $this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required."); + } + } - public function testADepreciationHasModels() - { - $this->createValidAssetModel(); - $depreciation = $this->createValidDepreciation('computer', ['name' => 'New Depreciation']); - $models = factory(App\Models\AssetModel::class, 5)->states('mbp-13-model')->create(['depreciation_id'=>$depreciation->id]); - $this->assertEquals(5,$depreciation->models->count()); - } + public function testADepreciationHasModels() + { + $this->createValidAssetModel(); + $depreciation = $this->createValidDepreciation('computer', ['name' => 'New Depreciation']); + $models = \App\Models\AssetModel::factory()->count(5)->mbp13Model()->create(['depreciation_id'=>$depreciation->id]); + $this->assertEquals(5, $depreciation->models->count()); + } - public function testADepreciationHasLicenses() - { - $category = $this->createValidCategory('license-graphics-category'); - $depreciation = $this->createValidDepreciation('computer', ['name' => 'New Depreciation']); - $licenses = factory(App\Models\License::class, 5)->states('photoshop')->create([ + public function testADepreciationHasLicenses() + { + $category = $this->createValidCategory('license-graphics-category'); + $depreciation = $this->createValidDepreciation('computer', ['name' => 'New Depreciation']); + $licenses = \App\Models\License::factory()->count(5)->photoshop()->create([ 'depreciation_id'=>$depreciation->id, - 'category_id' => $category->id + 'category_id' => $category->id, ]); - $this->assertEquals(5,$depreciation->licenses()->count()); - } + $this->assertEquals(5, $depreciation->licenses()->count()); + } } diff --git a/tests/unit/ImporterTest.php b/tests/unit/ImporterTest.php index db2aef4d5c..b0cb05f6ee 100644 --- a/tests/unit/ImporterTest.php +++ b/tests/unit/ImporterTest.php @@ -1,4 +1,5 @@ 'bnelson0@cdbaby.com', ]); $this->tester->seeRecord('categories', [ - 'name' => 'quam' + 'name' => 'quam', ]); $this->tester->seeRecord('models', [ 'name' => 'massa id', - 'model_number' => 6377018600094472 + 'model_number' => 6377018600094472, ]); $this->tester->seeRecord('manufacturers', [ - 'name' => 'Linkbridge' + 'name' => 'Linkbridge', ]); $this->tester->seeRecord('locations', [ - 'name' => 'Daping' + 'name' => 'Daping', ]); $this->tester->seeRecord('companies', [ - 'name' => 'Alpha' + 'name' => 'Alpha', ]); $this->tester->seeRecord('status_labels', [ - 'name' => 'Undeployable' + 'name' => 'Undeployable', ]); $this->tester->seeRecord('suppliers', [ - 'name' => 'Blogspan' + 'name' => 'Blogspan', ]); $this->tester->seeRecord('assets', [ 'name' => 'eget nunc donec quis', 'serial' => '27aa8378-b0f4-4289-84a4-405da95c6147', 'asset_tag' => '970882174-8', - 'notes' => "Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.", + 'notes' => 'Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.', 'purchase_date' => '2016-04-05 00:00:01', - 'purchase_cost' => 133289.59 -, 'warranty_months' => 14, - '_snipeit_weight_2' => 35 + 'purchase_cost' => 133289.59, 'warranty_months' => 14, + '_snipeit_weight_2' => 35, ]); } @@ -105,30 +105,29 @@ EOT; $this->tester->seeRecord('assets', [ 'asset_tag' => '970882174-8', 'assigned_type' => User::class, - 'assigned_to' => $user->id + 'assigned_to' => $user->id, ]); $user = User::where('username', 'mgibson2')->firstOrFail(); $this->tester->seeRecord('assets', [ 'asset_tag' => '710141467-2', 'assigned_type' => User::class, - 'assigned_to' => $user->id + 'assigned_to' => $user->id, ]); $location = Location::where('name', 'Planet Earth')->firstOrFail(); $this->tester->seeRecord('assets', [ 'asset_tag' => '998233705-X', 'assigned_type' => Location::class, - 'assigned_to' => $location->id + 'assigned_to' => $location->id, ]); $location = Location::where('name', 'Daping')->firstOrFail(); $this->tester->seeRecord('assets', [ 'asset_tag' => '927820758-6', 'assigned_type' => Location::class, - 'assigned_to' => $location->id + 'assigned_to' => $location->id, ]); - } public function testUpdateAssetIncludingCustomFields() @@ -153,47 +152,47 @@ EOT; ->import(); $this->tester->seeRecord('categories', [ - 'name' => 'some other category' + 'name' => 'some other category', ]); $this->tester->seeRecord('models', [ 'name' => 'Another Model', - 'model_number' => 356 + 'model_number' => 356, ]); $this->tester->seeRecord('manufacturers', [ - 'name' => 'Linkbridge 32' + 'name' => 'Linkbridge 32', ]); $this->tester->seeRecord('locations', [ - 'name' => 'New Location' + 'name' => 'New Location', ]); $this->tester->seeRecord('companies', [ - 'name' => 'Another Company' + 'name' => 'Another Company', ]); $this->tester->seeRecord('status_labels', [ - 'name' => 'Ready To Go' + 'name' => 'Ready To Go', ]); $this->tester->seeRecord('suppliers', [ - 'name' => 'Not Creative' + 'name' => 'Not Creative', ]); $this->tester->seeRecord('assets', [ 'name' => 'A new name', 'serial' => '67433477', 'asset_tag' => '970882174-8', - 'notes' => "I have no notes", + 'notes' => 'I have no notes', 'purchase_date' => '2018-04-05 00:00:01', 'purchase_cost' => 25.59, 'warranty_months' => 18, - '_snipeit_weight_2' => 95 + '_snipeit_weight_2' => 95, ]); } - public function testAssetModelNumber4359() + public function testAssetModelNumber4359() { // As per bug #4359 // 1) Create model with blank model # and custom field. @@ -206,27 +205,26 @@ Bonnie Nelson,bnelson0@cdbaby.com,bnelson0,eget nunc donec quis,quam,massa id,Li EOT; // Need to do this manually... - $customField = factory(App\Models\CustomField::class)->create(['name' => 'Weight']); - $customFieldSet = factory(App\Models\CustomFieldset::class)->create(['name' => 'Default']); - $customFieldSet->fields()->attach($customField, [ + $customField = \App\Models\CustomField::factory()->create(['name' => 'Weight']); + $customFieldSet = \App\Models\CustomFieldset::factory()->create(['name' => 'Default']); + $customFieldSet->fields()->attach($customField, [ 'required' => false, - 'order' => 'asc']); + 'order' => 'asc', ]); - factory(App\Models\Category::class)->states('asset-laptop-category')->create([ - 'name' => 'quam' + \App\Models\Category::factory()->assetLaptopCategory()->create([ + 'name' => 'quam', ]); - factory(App\Models\Manufacturer::class)->states('apple')->create([ - 'name' => 'Linkbridge' + \App\Models\Manufacturer::factory()->apple()->create([ + 'name' => 'Linkbridge', ]); - - $am = factory(App\Models\AssetModel::class)->create([ + $am = \App\Models\AssetModel::factory()->create([ 'name' => 'massa id', 'fieldset_id' => $customFieldSet->id, 'category_id' => 1, 'manufacturer_id' => 1, - 'model_number' => null + 'model_number' => null, ]); $this->import(new AssetImporter($csv)); @@ -242,21 +240,21 @@ EOT; $this->tester->seeRecord('assets', [ 'asset_tag' => '970882174-8', - '_snipeit_weight_2' => 115 + '_snipeit_weight_2' => 115, ]); } public function initializeCustomFields() { - $customField = factory(App\Models\CustomField::class)->create(['name' => 'Weight']); - $customFieldSet = factory(App\Models\CustomFieldset::class)->create(['name' => 'Default']); - $customFieldSet->fields()->attach($customField, [ + $customField = \App\Models\CustomField::factory()->create(['name' => 'Weight']); + $customFieldSet = \App\Models\CustomFieldset::factory()->create(['name' => 'Default']); + $customFieldSet->fields()->attach($customField, [ 'required' => false, - 'order' => 'asc']); + 'order' => 'asc', ]); - $am = factory(App\Models\AssetModel::class)->create([ + $am = \App\Models\AssetModel::factory()->create([ 'name' => 'massa id', - 'fieldset_id' => $customFieldSet->id + 'fieldset_id' => $customFieldSet->id, ]); } @@ -276,7 +274,7 @@ EOT; 'expiration_date' => 'expiration date', 'location' => 'loc', 'notes' => 'Some Notes', - 'asset_model' => "model name", + 'asset_model' => 'model name', ]; $this->import(new AssetImporter($csv), $customFieldMap); @@ -294,44 +292,44 @@ EOT; ]); $this->tester->seeRecord('categories', [ - 'name' => 'quam' + 'name' => 'quam', ]); $this->tester->seeRecord('models', [ 'name' => 'massa id', - 'model_number' => 6377018600094472 + 'model_number' => 6377018600094472, ]); $this->tester->seeRecord('manufacturers', [ - 'name' => 'Linkbridge' + 'name' => 'Linkbridge', ]); $this->tester->seeRecord('locations', [ - 'name' => 'Daping' + 'name' => 'Daping', ]); $this->tester->seeRecord('companies', [ - 'name' => 'Alpha' + 'name' => 'Alpha', ]); $this->tester->seeRecord('status_labels', [ - 'name' => 'Undeployable' + 'name' => 'Undeployable', ]); $this->tester->seeRecord('suppliers', [ - 'name' => 'Blogspan' + 'name' => 'Blogspan', ]); $this->tester->seeRecord('assets', [ 'name' => 'eget nunc donec quis', 'serial' => '27aa8378-b0f4-4289-84a4-405da95c6147', 'asset_tag' => '970882174-8', - 'notes' => "Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.", + 'notes' => 'Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.', 'purchase_date' => '2016-04-05 00:00:01', 'purchase_cost' => 133289.59, 'warranty_months' => 14, 'assigned_to' => $createdUser['id'], - 'assigned_type' => User::class + 'assigned_type' => User::class, ]); } @@ -347,19 +345,19 @@ EOT; 'purchase_date' => '2006-09-01 00:00:01', 'order_number' => 'J935H60W', 'requestable' => 0, - 'qty' => 278 + 'qty' => 278, ]); $this->tester->seeRecord('locations', [ - 'name' => 'metus. Vivamus' + 'name' => 'metus. Vivamus', ]); $this->tester->seeRecord('companies', [ - 'name' => 'Macromedia' + 'name' => 'Macromedia', ]); $this->tester->seeRecord('categories', [ - 'name' => 'Customers' + 'name' => 'Customers', ]); } @@ -372,7 +370,6 @@ EOT; $this->import(new AccessoryImporter($csv)); $this->tester->seeNumRecords(1, 'accessories'); - $updatedCSV = <<<'EOT' Item Name,Purchase Date,Purchase Cost,Location,Company,Order Number,Category,Requestable,Quantity Walter Carter,09/01/2015,350,metus. Vivamus,Macromedia,35GGH,Customers,True,12 @@ -389,7 +386,7 @@ EOT; 'purchase_date' => '2015-09-01 00:00:01', 'order_number' => '35GGH', 'requestable' => 1, - 'qty' => 12 + 'qty' => 12, ]); } @@ -406,10 +403,10 @@ EOT; 'item_name' => 'Name', 'location' => 'Loc', 'purchase_date' => 'Pur Date', - 'purchase_cost' => "Cost", + 'purchase_cost' => 'Cost', 'order_number' => 'Order Num', 'requestable' => 'Request', - 'quantity' => 'Quan' + 'quantity' => 'Quan', ]; $this->import(new AccessoryImporter($csv), $customFieldMap); // dd($this->tester->grabRecord('accessories')); @@ -418,19 +415,19 @@ EOT; 'purchase_date' => '2006-09-01 00:00:01', 'order_number' => 'J935H60W', 'requestable' => 0, - 'qty' => 278 + 'qty' => 278, ]); $this->tester->seeRecord('locations', [ - 'name' => 'metus. Vivamus' + 'name' => 'metus. Vivamus', ]); $this->tester->seeRecord('companies', [ - 'name' => 'Macromedia' + 'name' => 'Macromedia', ]); $this->tester->seeRecord('categories', [ - 'name' => 'Customers' + 'name' => 'Customers', ]); } @@ -449,19 +446,19 @@ EOT; 'requestable' => 0, 'qty' => 322, 'item_no' => 3305, - 'model_number' => 30123 + 'model_number' => 30123, ]); $this->tester->seeRecord('locations', [ - 'name' => 'mauris blandit mattis.' + 'name' => 'mauris blandit mattis.', ]); $this->tester->seeRecord('companies', [ - 'name' => 'Lycos' + 'name' => 'Lycos', ]); $this->tester->seeRecord('categories', [ - 'name' => 'Triamterene/Hydrochlorothiazide' + 'name' => 'Triamterene/Hydrochlorothiazide', ]); } @@ -474,7 +471,6 @@ EOT; $this->import(new ConsumableImporter($csv)); $this->tester->seeNumRecords(1, 'consumables'); - $updatedCSV = <<<'EOT' Item Name,Purchase Date,Purchase Cost,Location,Company,Order Number,Category,Requestable,Quantity eget,12/05/2016,35.45,mauris blandit mattis.,Lycos,3666FF,New Cat,Yes,15 @@ -492,7 +488,7 @@ EOT; 'purchase_cost' => 35.45, 'order_number' => '3666FF', 'requestable' => 1, - 'qty' => 15 + 'qty' => 15, ]); } @@ -509,10 +505,10 @@ EOT; 'item_name' => 'Name', 'location' => 'Loc', 'purchase_date' => 'Pur date', - 'purchase_cost' => "Pur Cost", + 'purchase_cost' => 'Pur Cost', 'order_number' => 'Order Num', 'requestable' => 'Request', - 'quantity' => 'Quan' + 'quantity' => 'Quan', ]; $this->import(new ConsumableImporter($csv), $customFieldMap); $this->tester->seeRecord('consumables', [ @@ -521,19 +517,19 @@ EOT; 'purchase_cost' => 85.91, 'order_number' => 'T295T06V', 'requestable' => 0, - 'qty' => 322 + 'qty' => 322, ]); $this->tester->seeRecord('locations', [ - 'name' => 'mauris blandit mattis.' + 'name' => 'mauris blandit mattis.', ]); $this->tester->seeRecord('companies', [ - 'name' => 'Lycos' + 'name' => 'Lycos', ]); $this->tester->seeRecord('categories', [ - 'name' => 'Triamterene/Hydrochlorothiazide' + 'name' => 'Triamterene/Hydrochlorothiazide', ]); } @@ -573,31 +569,31 @@ EOT; 'maintained' => 0, 'notes' => 'Sed ante. Vivamus tortor. Duis mattis egestas metus.', 'purchase_cost' => 79.66, - 'purchase_order' => "53008", + 'purchase_order' => '53008', 'reassignable' => 0, 'serial' => '1aa5b0eb-79c5-40b2-8943-5472a6893c3c', ]); $this->tester->seeRecord('manufacturers', [ - 'name' => 'Beer, Leannon and Lubowitz' + 'name' => 'Beer, Leannon and Lubowitz', ]); $this->tester->seeRecord('suppliers', [ - 'name' => "Hegmann, Mohr and Cremin", + 'name' => 'Hegmann, Mohr and Cremin', ]); $this->tester->seeRecord('companies', [ - 'name' => 'Haag, Schmidt and Farrell' + 'name' => 'Haag, Schmidt and Farrell', ]); $this->tester->seeRecord('categories', [ - 'name' => 'Graphics Software' + 'name' => 'Graphics Software', ]); $this->tester->seeNumRecords(80, 'license_seats'); $this->tester->seeRecord('license_seats', [ 'assigned_to' => $createdUser['id'], - 'license_id' => \App\Models\License::where('serial','1aa5b0eb-79c5-40b2-8943-5472a6893c3c')->first()->id, - 'asset_id' => $testAsset->id + 'license_id' => \App\Models\License::where('serial', '1aa5b0eb-79c5-40b2-8943-5472a6893c3c')->first()->id, + 'asset_id' => $testAsset->id, ]); } @@ -610,7 +606,6 @@ EOT; $this->import(new LicenseImporter($csv)); $this->tester->seeNumRecords(1, 'licenses'); - $updatedCSV = <<<'EOT' Item name,serial,manufacturer,purchase date,purchase cost,purchase order,order number,Licensed To Name,Licensed to Email,expiration date,maintained,reassignable,seats,company,supplier,category,notes Argentum Malachite Athletes Foot Relief,1aa5b0eb-79c5-40b2-8943-5472a6893c3c,"Beer, Leannon and Lubowitz",05/15/2019,$1865.34,63 ar,18334,A Legend,Legendary@gov.uk,04/27/2016,yes,true,64,"Haag, Schmidt and Farrell","Hegmann, Mohr and Cremin",Graphics Software,Sed ante. Vivamus tortor. Duis mattis egestas metus. @@ -635,7 +630,7 @@ EOT; 'maintained' => 1, 'notes' => 'Sed ante. Vivamus tortor. Duis mattis egestas metus.', 'purchase_cost' => 1865.34, - 'purchase_order' => "63 ar", + 'purchase_order' => '63 ar', 'reassignable' => 1, 'serial' => '1aa5b0eb-79c5-40b2-8943-5472a6893c3c', ]); @@ -660,9 +655,9 @@ EOT; 'manufacturer' => 'manuf', 'notes' => 'note', 'order_number' => 'Order Num', - 'purchase_cost' => "Pur Cost", + 'purchase_cost' => 'Pur Cost', 'purchase_date' => 'Pur date', - 'purchase_order' => "Purc Order", + 'purchase_order' => 'Purc Order', 'quantity' => 'Quan', 'reassignable' => 'reass', 'requestable' => 'Request', @@ -682,27 +677,26 @@ EOT; 'maintained' => 0, 'notes' => 'Sed ante. Vivamus tortor. Duis mattis egestas metus.', 'purchase_cost' => 79.66, - 'purchase_order' => "53008", + 'purchase_order' => '53008', 'reassignable' => 0, 'serial' => '1aa5b0eb-79c5-40b2-8943-5472a6893c3c', ]); $this->tester->seeRecord('manufacturers', [ - 'name' => 'Beer, Leannon and Lubowitz' + 'name' => 'Beer, Leannon and Lubowitz', ]); $this->tester->seeRecord('suppliers', [ - 'name' => "Hegmann, Mohr and Cremin", + 'name' => 'Hegmann, Mohr and Cremin', ]); $this->tester->seeRecord('companies', [ - 'name' => 'Haag, Schmidt and Farrell' + 'name' => 'Haag, Schmidt and Farrell', ]); $this->tester->seeNumRecords(80, 'license_seats'); } - public function testDefaultUserImport() { Notification::fake(); @@ -724,20 +718,21 @@ EOT; 'username' => 'bocollopy0', 'phone' => '63-(199)661-2186', 'jobtitle' => 'Clinical Specialist', - 'employee_num' => '7080919053' + 'employee_num' => '7080919053', ]); $this->tester->seeRecord('companies', [ - 'name' => 'Morar-Ward' + 'name' => 'Morar-Ward', ]); $this->tester->seeRecord('departments', [ - 'name' => 'Management' + 'name' => 'Management', ]); Notification::assertSentTo(User::find(2), \App\Notifications\WelcomeNotification::class); Notification::assertNotSentTo(User::find(3), \App\Notifications\WelcomeNotification::class); } + private function import($importer, $mappings = null) { if ($mappings) { diff --git a/tests/unit/LocationTest.php b/tests/unit/LocationTest.php index 82f0a14ef1..2bb330cb49 100644 --- a/tests/unit/LocationTest.php +++ b/tests/unit/LocationTest.php @@ -1,42 +1,40 @@ createValidLocation(['id' => 10]); - $a = factory(Location::class)->make([ + $a = Location::factory()->make([ 'name' => 'Test Location', 'id' => 1, 'parent_id' => 10, ]); $this->assertTrue($a->isValid()); - } - public function testFailsIfSelfParent() { - - $a = factory(Location::class)->make([ + public function testFailsIfSelfParent() + { + $a = Location::factory()->make([ 'name' => 'Test Location', 'id' => 1, 'parent_id' => 1, ]); $this->assertFalse($a->isValid()); - $this->assertStringContainsString("The parent id and id must be different", $a->getErrors()); - - + $this->assertStringContainsString('The parent id and id must be different', $a->getErrors()); } - } diff --git a/tests/unit/ManufacturerTest.php b/tests/unit/ManufacturerTest.php index a5e3d5d051..15f62e4080 100644 --- a/tests/unit/ManufacturerTest.php +++ b/tests/unit/ManufacturerTest.php @@ -1,9 +1,10 @@ tester->seeRecord('manufacturers', $values); // } - } diff --git a/tests/unit/NotificationTest.php b/tests/unit/NotificationTest.php index 4f1441b0e1..72d815b498 100644 --- a/tests/unit/NotificationTest.php +++ b/tests/unit/NotificationTest.php @@ -1,4 +1,5 @@ states('superuser')->create(); + public function testAUserIsEmailedIfTheyCheckoutAnAssetWithEULA() + { + $admin = User::factory()->superuser()->create(); Auth::login($admin); $cat = $this->createValidCategory('asset-laptop-category', ['require_acceptance' => true]); $model = $this->createValidAssetModel('mbp-13-model', ['category_id' => $cat->id]); @@ -31,5 +32,5 @@ class NotificationTest extends BaseTest Notification::fake(); $asset->checkOut($user, 1); Notification::assertSentTo($user, CheckoutAssetNotification::class); - } + } } diff --git a/tests/unit/PermissionsTest.php b/tests/unit/PermissionsTest.php index ea648293bc..8c7d3a101f 100644 --- a/tests/unit/PermissionsTest.php +++ b/tests/unit/PermissionsTest.php @@ -12,7 +12,6 @@ use Illuminate\Foundation\Testing\WithoutMiddleware; class PermissionsTest extends BaseTest { - public function _before() { parent::_before(); @@ -57,7 +56,6 @@ class PermissionsTest extends BaseTest 'users.edit' => false, 'users.delete' => false, ]; - } private $noHardware; @@ -68,12 +66,13 @@ class PermissionsTest extends BaseTest private $noUsers; // tests + /** * @test */ public function a_user_with_no_permissions_sees_nothing() { - $u = factory(App\Models\User::class)->create(); + $u = \App\Models\User::factory()->create(); $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers; // $permissions = $this->noHardware; $this->hitRoutes($permissions, $u); @@ -84,7 +83,7 @@ class PermissionsTest extends BaseTest */ public function a_user_with_view_asset_permissions_can_view_assets() { - $u = factory(App\Models\User::class)->states('view-assets')->create(); + $u = \App\Models\User::factory()->viewAssets()->create(); $permissions = $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers; $permissions = array_merge($permissions, [ @@ -101,7 +100,7 @@ class PermissionsTest extends BaseTest */ public function a_user_with_create_asset_permissions_can_create_assets() { - $u = factory(App\Models\User::class)->states('create-assets')->create(); + $u = \App\Models\User::factory()->createAssets()->create(); $permissions = $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers; $permissions = array_merge($permissions, [ @@ -118,7 +117,7 @@ class PermissionsTest extends BaseTest */ public function a_user_with_edit_assets_permissions_can_edit_assets() { - $u = factory(App\Models\User::class)->states('edit-assets')->create(); + $u = \App\Models\User::factory()->editAssets()->create(); $permissions = $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers; @@ -136,7 +135,7 @@ class PermissionsTest extends BaseTest */ public function a_user_with_delete_assets_permissions_can_delete_assets() { - $u = factory(App\Models\User::class)->states('delete-assets')->create(); + $u = \App\Models\User::factory()->deleteAssets()->create(); $permissions = $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers; $permissions = array_merge($permissions, [ 'assets.view' => false, @@ -152,7 +151,7 @@ class PermissionsTest extends BaseTest */ public function a_user_with_view_licenses_permissions_can_view_licenses() { - $u = factory(App\Models\User::class)->states('view-licenses')->create(); + $u = \App\Models\User::factory()->viewLicenses()->create(); $permissions = $this->noHardware + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers; $permissions = array_merge($permissions, [ @@ -169,7 +168,7 @@ class PermissionsTest extends BaseTest */ public function a_user_with_create_licenses_permissions_can_create_licenses() { - $u = factory(App\Models\User::class)->states('create-licenses')->create(); + $u = \App\Models\User::factory()->createLicenses()->create(); $permissions = $this->noHardware + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers; $permissions = array_merge($permissions, [ @@ -186,7 +185,7 @@ class PermissionsTest extends BaseTest */ public function a_user_with_edit_licenses_permissions_can_edit_licenses() { - $u = factory(App\Models\User::class)->states('edit-licenses')->create(); + $u = \App\Models\User::factory()->editLicenses()->create(); $permissions = $this->noHardware + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers; $permissions = array_merge($permissions, [ @@ -203,7 +202,7 @@ class PermissionsTest extends BaseTest */ public function a_user_with_delete_licenses_permissions_can_delete_licenses() { - $u = factory(App\Models\User::class)->states('delete-licenses')->create(); + $u = \App\Models\User::factory()->deleteLicenses()->create(); $permissions = $this->noHardware + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers; $permissions = array_merge($permissions, [ @@ -217,10 +216,10 @@ class PermissionsTest extends BaseTest /** * @test - */ + */ public function a_user_with_view_accessories_permissions_can_view_accessories() { - $u = factory(App\Models\User::class)->states('view-accessories')->create(); + $u = \App\Models\User::factory()->viewAccessories()->create(); $permissions = $this->noHardware + $this->noLicenses + $this->noConsumables + $this->noComponents + $this->noUsers; @@ -238,7 +237,7 @@ class PermissionsTest extends BaseTest */ public function a_user_with_create_accessories_permissions_can_create_accessories() { - $u = factory(App\Models\User::class)->states('create-accessories')->create(); + $u = \App\Models\User::factory()->createAccessories()->create(); $permissions = $this->noHardware + $this->noLicenses + $this->noConsumables + $this->noComponents + $this->noUsers; @@ -256,7 +255,7 @@ class PermissionsTest extends BaseTest */ public function a_user_with_edit_accessories_permissions_can_edit_accessories() { - $u = factory(App\Models\User::class)->states('edit-accessories')->create(); + $u = \App\Models\User::factory()->editAccessories()->create(); $permissions = $this->noHardware + $this->noLicenses + $this->noConsumables + $this->noComponents + $this->noUsers; @@ -274,7 +273,7 @@ class PermissionsTest extends BaseTest */ public function a_user_with_delete_accessories_permissions_can_delete_accessories() { - $u = factory(App\Models\User::class)->states('delete-accessories')->create(); + $u = \App\Models\User::factory()->deleteAccessories()->create(); $permissions = $this->noHardware + $this->noLicenses + $this->noConsumables + $this->noComponents + $this->noUsers; @@ -292,7 +291,7 @@ class PermissionsTest extends BaseTest */ public function a_user_with_view_consumables_permissions_can_view_consumables() { - $u = factory(App\Models\User::class)->states('view-consumables')->create(); + $u = \App\Models\User::factory()->viewConsumables()->create(); $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noComponents + $this->noUsers; @@ -310,7 +309,7 @@ class PermissionsTest extends BaseTest */ public function a_user_with_create_consumables_permissions_can_create_consumables() { - $u = factory(App\Models\User::class)->states('create-consumables')->create(); + $u = \App\Models\User::factory()->createConsumables()->create(); $permissions = $this->noHardware + $this->noLicenses + $this->noConsumables + $this->noComponents + $this->noUsers; @@ -328,7 +327,7 @@ class PermissionsTest extends BaseTest */ public function a_user_with_edit_consumables_permissions_can_edit_consumables() { - $u = factory(App\Models\User::class)->states('edit-consumables')->create(); + $u = \App\Models\User::factory()->editConsumables()->create(); $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noComponents + $this->noUsers; @@ -346,7 +345,7 @@ class PermissionsTest extends BaseTest */ public function a_user_with_delete_consumables_permissions_can_delete_consumables() { - $u = factory(App\Models\User::class)->states('delete-consumables')->create(); + $u = \App\Models\User::factory()->deleteConsumables()->create(); $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noComponents + $this->noUsers; @@ -364,9 +363,9 @@ class PermissionsTest extends BaseTest */ public function a_user_with_view_users_permissions_can_view_users() { - $u = factory(App\Models\User::class)->states('view-users')->create(); + $u = \App\Models\User::factory()->viewUsers()->create(); - $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories +$this->noConsumables + $this->noComponents; + $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents; $permissions = array_merge($permissions, [ 'users.view' => true, @@ -382,9 +381,9 @@ class PermissionsTest extends BaseTest */ public function a_user_with_create_users_permissions_can_create_users() { - $u = factory(App\Models\User::class)->states('create-users')->create(); + $u = \App\Models\User::factory()->createUsers()->create(); - $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories +$this->noConsumables + $this->noComponents; + $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents; $permissions = array_merge($permissions, [ 'users.view' => false, @@ -400,9 +399,9 @@ class PermissionsTest extends BaseTest */ public function a_user_with_edit_users_permissions_can_edit_users() { - $u = factory(App\Models\User::class)->states('edit-users')->create(); + $u = \App\Models\User::factory()->editUsers()->create(); - $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories +$this->noConsumables + $this->noComponents; + $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents; $permissions = array_merge($permissions, [ 'users.view' => false, @@ -418,9 +417,9 @@ class PermissionsTest extends BaseTest */ public function a_user_with_delete_users_permissions_can_delete_users() { - $u = factory(App\Models\User::class)->states('delete-users')->create(); + $u = \App\Models\User::factory()->deleteUsers()->create(); - $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories +$this->noConsumables + $this->noComponents; + $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents; $permissions = array_merge($permissions, [ 'users.view' => false, @@ -436,9 +435,9 @@ class PermissionsTest extends BaseTest */ public function a_user_with_view_components_permissions_can_view_components() { - $u = factory(App\Models\User::class)->states('view-components')->create(); + $u = \App\Models\User::factory()->viewComponents()->create(); - $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories +$this->noConsumables + $this->noUsers; + $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noUsers; $permissions = array_merge($permissions, [ 'components.view' => true, @@ -454,8 +453,8 @@ class PermissionsTest extends BaseTest */ public function a_user_with_create_components_permissions_can_create_components() { - $u = factory(App\Models\User::class)->states('create-components')->create(); - $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories +$this->noConsumables + $this->noUsers; + $u = \App\Models\User::factory()->createComponents()->create(); + $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noUsers; $permissions = array_merge($permissions, [ 'components.view' => false, @@ -471,9 +470,9 @@ class PermissionsTest extends BaseTest */ public function a_user_with_edit_components_permissions_can_edit_components() { - $u = factory(App\Models\User::class)->states('edit-components')->create(); + $u = \App\Models\User::factory()->editComponents()->create(); - $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories +$this->noConsumables + $this->noUsers; + $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noUsers; $permissions = array_merge($permissions, [ 'components.view' => false, @@ -489,9 +488,9 @@ class PermissionsTest extends BaseTest */ public function a_user_with_delete_components_permissions_can_delete_components() { - $u = factory(App\Models\User::class)->states('delete-components')->create(); + $u = \App\Models\User::factory()->deleteComponents()->create(); - $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories +$this->noConsumables + $this->noUsers; + $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noUsers; $permissions = array_merge($permissions, [ 'components.view' => false, diff --git a/tests/unit/SnipeModelTest.php b/tests/unit/SnipeModelTest.php index c7771cb9b5..0cf013e682 100644 --- a/tests/unit/SnipeModelTest.php +++ b/tests/unit/SnipeModelTest.php @@ -1,6 +1,5 @@ purchase_date = ''; $this->assertTrue($c->purchase_date === null); $c->purchase_date = '2016-03-25 12:35:50'; - $this->assertTrue($c->purchase_date==='2016-03-25 12:35:50'); + $this->assertTrue($c->purchase_date === '2016-03-25 12:35:50'); } /** @@ -32,9 +32,9 @@ class SnipeModelTest extends BaseTest $c->purchase_cost = '0.00'; $this->assertTrue($c->purchase_cost === null); $c->purchase_cost = '9.54'; - $this->assertTrue($c->purchase_cost===9.54); + $this->assertTrue($c->purchase_cost === 9.54); $c->purchase_cost = '9.50'; - $this->assertTrue($c->purchase_cost===9.5); + $this->assertTrue($c->purchase_cost === 9.5); } /** @@ -46,8 +46,9 @@ class SnipeModelTest extends BaseTest $c->location_id = ''; $this->assertTrue($c->location_id === null); $c->location_id = '5'; - $this->assertTrue($c->location_id==5); + $this->assertTrue($c->location_id == 5); } + /** * @test */ @@ -57,7 +58,7 @@ class SnipeModelTest extends BaseTest $c->category_id = ''; $this->assertTrue($c->category_id === null); $c->category_id = '1'; - $this->assertTrue($c->category_id==1); + $this->assertTrue($c->category_id == 1); } /** @@ -69,7 +70,7 @@ class SnipeModelTest extends BaseTest $c->supplier_id = ''; $this->assertTrue($c->supplier_id === null); $c->supplier_id = '4'; - $this->assertTrue($c->supplier_id==4); + $this->assertTrue($c->supplier_id == 4); } /** @@ -81,7 +82,7 @@ class SnipeModelTest extends BaseTest $c->depreciation_id = ''; $this->assertTrue($c->depreciation_id === null); $c->depreciation_id = '4'; - $this->assertTrue($c->depreciation_id==4); + $this->assertTrue($c->depreciation_id == 4); } /** @@ -93,6 +94,6 @@ class SnipeModelTest extends BaseTest $c->manufacturer_id = ''; $this->assertTrue($c->manufacturer_id === null); $c->manufacturer_id = '4'; - $this->assertTrue($c->manufacturer_id==4); + $this->assertTrue($c->manufacturer_id == 4); } -} \ No newline at end of file +} diff --git a/tests/unit/StatuslabelTest.php b/tests/unit/StatuslabelTest.php index 8884537cc0..6cbc582235 100644 --- a/tests/unit/StatuslabelTest.php +++ b/tests/unit/StatuslabelTest.php @@ -1,21 +1,22 @@ states('rtd')->make(); - $values = [ + public function testRTDStatuslabelAdd() + { + $statuslabel = Statuslabel::factory()->rtd()->make(); + $values = [ 'name' => $statuslabel->name, 'deployable' => $statuslabel->deployable, 'pending' => $statuslabel->pending, @@ -23,91 +24,91 @@ class StatuslabelTest extends BaseTest ]; - Statuslabel::create($values); - $this->tester->seeRecord('status_labels', $values); - } + Statuslabel::create($values); + $this->tester->seeRecord('status_labels', $values); + } - public function testPendingStatuslabelAdd() - { - $statuslabel = factory(Statuslabel::class)->states('pending')->make(); - $values = [ + public function testPendingStatuslabelAdd() + { + $statuslabel = Statuslabel::factory()->pending()->make(); + $values = [ 'name' => $statuslabel->name, 'deployable' => $statuslabel->deployable, 'pending' => $statuslabel->pending, 'archived' => $statuslabel->archived, ]; - Statuslabel::create($values); - $this->tester->seeRecord('status_labels', $values); - } + Statuslabel::create($values); + $this->tester->seeRecord('status_labels', $values); + } - public function testArchivedStatuslabelAdd() - { - $statuslabel = factory(Statuslabel::class)->states('archived')->make(); - $values = [ + public function testArchivedStatuslabelAdd() + { + $statuslabel = Statuslabel::factory()->archived()->make(); + $values = [ 'name' => $statuslabel->name, 'deployable' => $statuslabel->deployable, 'pending' => $statuslabel->pending, 'archived' => $statuslabel->archived, ]; - Statuslabel::create($values); - $this->tester->seeRecord('status_labels', $values); - } + Statuslabel::create($values); + $this->tester->seeRecord('status_labels', $values); + } - public function testOutForRepairStatuslabelAdd() - { - $statuslabel = factory(Statuslabel::class)->states('out_for_repair')->make(); - $values = [ + public function testOutForRepairStatuslabelAdd() + { + $statuslabel = Statuslabel::factory()->outForRepair()->make(); + $values = [ 'name' => $statuslabel->name, 'deployable' => $statuslabel->deployable, 'pending' => $statuslabel->pending, 'archived' => $statuslabel->archived, ]; - Statuslabel::create($values); - $this->tester->seeRecord('status_labels', $values); - } + Statuslabel::create($values); + $this->tester->seeRecord('status_labels', $values); + } - public function testOutForDiagnosticsStatuslabelAdd() - { - $statuslabel = factory(Statuslabel::class)->states('out_for_diagnostics')->make(); - $values = [ + public function testOutForDiagnosticsStatuslabelAdd() + { + $statuslabel = Statuslabel::factory()->outForDiagnostics()->make(); + $values = [ 'name' => $statuslabel->name, 'deployable' => $statuslabel->deployable, 'pending' => $statuslabel->pending, 'archived' => $statuslabel->archived, ]; - Statuslabel::create($values); - $this->tester->seeRecord('status_labels', $values); - } + Statuslabel::create($values); + $this->tester->seeRecord('status_labels', $values); + } - public function testBrokenStatuslabelAdd() - { - $statuslabel = factory(Statuslabel::class)->states('broken')->make(); - $values = [ + public function testBrokenStatuslabelAdd() + { + $statuslabel = Statuslabel::factory()->broken()->make(); + $values = [ 'name' => $statuslabel->name, 'deployable' => $statuslabel->deployable, 'pending' => $statuslabel->pending, 'archived' => $statuslabel->archived, ]; - Statuslabel::create($values); - $this->tester->seeRecord('status_labels', $values); - } + Statuslabel::create($values); + $this->tester->seeRecord('status_labels', $values); + } - public function testLostStatuslabelAdd() - { - $statuslabel = factory(Statuslabel::class)->states('lost')->make(); - $values = [ + public function testLostStatuslabelAdd() + { + $statuslabel = Statuslabel::factory()->lost()->make(); + $values = [ 'name' => $statuslabel->name, 'deployable' => $statuslabel->deployable, 'pending' => $statuslabel->pending, 'archived' => $statuslabel->archived, ]; - Statuslabel::create($values); - $this->tester->seeRecord('status_labels', $values); - } + Statuslabel::create($values); + $this->tester->seeRecord('status_labels', $values); + } } diff --git a/tests/unit/SupplierTest.php b/tests/unit/SupplierTest.php index bd8c172edc..856f53c389 100644 --- a/tests/unit/SupplierTest.php +++ b/tests/unit/SupplierTest.php @@ -1,9 +1,10 @@ tester->seeRecord('suppliers', $values); // } - } diff --git a/tests/unit/UserTest.php b/tests/unit/UserTest.php index bbd4048156..010bd9c787 100644 --- a/tests/unit/UserTest.php +++ b/tests/unit/UserTest.php @@ -1,9 +1,10 @@ tester->seeRecord('users', $values); // } - public function testFirstNameSplit() { $fullname = "Natalia Allanovna Romanova-O'Shostakova"; @@ -62,7 +62,6 @@ class UserTest extends BaseTest $this->assertEquals($expected_username, $user['username']); } - public function testFirstInitialLastName() { $fullname = "Natalia Allanovna Romanova-O'Shostakova"; @@ -81,11 +80,12 @@ class UserTest extends BaseTest public function testSingleName() { - $fullname = "Natalia"; + $fullname = 'Natalia'; $expected_username = 'natalia'; $user = User::generateFormattedNameFromFullName('firstname_lastname', $fullname); $this->assertEquals($expected_username, $user['username']); } + public function firstInitialDotLastname() { $fullname = "Natalia Allanovna Romanova-O'Shostakova"; @@ -93,6 +93,7 @@ class UserTest extends BaseTest $user = User::generateFormattedNameFromFullName($fullname, 'firstinitial.lastname'); $this->assertEquals($expected_username, $user['username']); } + public function lastNameUnderscoreFirstInitial() { $fullname = "Natalia Allanovna Romanova-O'Shostakova"; @@ -100,6 +101,7 @@ class UserTest extends BaseTest $user = User::generateFormattedNameFromFullName($fullname, 'lastname_firstinitial'); $this->assertEquals($expected_username, $user['username']); } + public function firstNameLastName() { $fullname = "Natalia Allanovna Romanova-O'Shostakova"; @@ -107,6 +109,7 @@ class UserTest extends BaseTest $user = User::generateFormattedNameFromFullName($fullname, 'firstnamelastname'); $this->assertEquals($expected_username, $user['username']); } + public function firstNameLastInitial() { $fullname = "Natalia Allanovna Romanova-O'Shostakova"; @@ -114,5 +117,4 @@ class UserTest extends BaseTest $user = User::generateFormattedNameFromFullName($fullname, 'firstnamelastinitial'); $this->assertEquals($expected_username, $user['username']); } - } diff --git a/tests/unit/_bootstrap.php b/tests/unit/_bootstrap.php index 8a88555806..62817a53c4 100644 --- a/tests/unit/_bootstrap.php +++ b/tests/unit/_bootstrap.php @@ -1,2 +1,3 @@