snipe-it/app/Http/Controllers/ConsumablesController.php
Daniel Meltzer 323c3807fa Cleanup controller escaping (#3084)
* Make delete routes work.  We put a little form in the modal that spoofs the delete field.

* Fix route on creating a user.

* Fix redundant id parameter.

* Port acceptance tests to new urls.

* Initial work on migrating to model based policies instead of global gates.  Will allow for much more detailed permissions bits in the future.

* This needs to stay for the dashboard checks.

* Add user states for permissions to build tests.

* Build up unit tests for gates/permissions.  Move accessories/consumables/assets to policies instead of in authserviceprovider

* Migrate various locations to new syntax.  Update test to be more specific

* Fix functional tests.

Add an artisan command for installing a settings setup on travis-ci

* Try a different id... Need to come up with a better way of passing the id for tests that need an existing one.

* Try to fix travis

* Update urls to use routes and not hardcode old paths.  Also fix some migration errors found along the way.:

* Add a environment for travis functional tests.

* Adjust config file to make travis use it.

* Use redirect()->route instead of redirect()-to

* Dump all failures in the output directory if travis fails.

* Cleanups and minor fixes.

* Adjust the supplier modelfactory to comply with new validation restrictions.

* Some test fixes.

* Locales can be longer than 5 characters according to faker... fex gez_ET.  Increase lenght in mysql and add a validation

* Update test database dump to latest migrations.

* Extend Supplier phone/fax length.

This catches issues found in testing with a phone number with a five digit extension.  fex (356) 654-3024 x36632

Also move away from escaping all values put into eloquent.  Eloquent
already uses PDO parameter binding, and this was leading to names like
Mr Ryan O'Malley turning into an html escaped version of that name when
stored.  All values should be escaped when using {{}}, we'll just have
to be more cautious when we use {!!, but I think we already are?

* Remove additional escaping here, like we did in suppliers controller.

* No need to eager load all of these relationships when we can call the count on the querybuilder directly

* Work on controller cleanup

* Always start from scrach, catches more issues this way.

* Update sql dump.  Remove old code from permissions test.

* Generate a deletable item on demand in the test, rather than relying on one existing.  I think we should probably move to mock all the database stuff at some point..

* More travis related fixes

* Break script into multiple functional lines

* Update all controllers to use the new helper, also cleanup syntax and docblocks along the way.
2016-12-19 22:00:50 -08:00

493 lines
19 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Helpers\Helper;
use App\Models\Actionlog;
use App\Models\Company;
use App\Models\Consumable;
use App\Models\Setting;
use App\Models\User;
use Auth;
use Config;
use DB;
use Input;
use Lang;
use Mail;
use Redirect;
use Slack;
use Str;
use View;
use Gate;
/**
* This controller handles all actions related to Consumables for
* the Snipe-IT Asset Management application.
*
* @version v1.0
*/
class ConsumablesController extends Controller
{
/**
* Return a view to display component information.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @see ConsumablesController::getDatatable() method that generates the JSON response
* @since [v1.0]
* @return \Illuminate\Contracts\View\View
*/
public function index()
{
$this->authorize('index', Consumable::class);
return View::make('consumables/index');
}
/**
* Return a view to display the form view to create a new consumable
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @see ConsumablesController::postCreate() method that stores the form data
* @since [v1.0]
* @return \Illuminate\Contracts\View\View
*/
public function create()
{
$this->authorize('create', Consumable::class);
// Show the page
return View::make('consumables/edit')
->with('item', new Consumable)
->with('category_list', Helper::categoryList('consumable'))
->with('company_list', Helper::companyList())
->with('location_list', Helper::locationsList())
->with('manufacturer_list', Helper::manufacturerList());
}
/**
* Validate and store new consumable data.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @see ConsumablesController::getCreate() method that returns the form view
* @since [v1.0]
* @return \Illuminate\Http\RedirectResponse
*/
public function store()
{
$this->authorize('create', Consumable::class);
$consumable = new Consumable();
$consumable->name = Input::get('name');
$consumable->category_id = Input::get('category_id');
$consumable->location_id = Input::get('location_id');
$consumable->company_id = Company::getIdForCurrentUser(Input::get('company_id'));
$consumable->order_number = Input::get('order_number');
$consumable->min_amt = Input::get('min_amt');
$consumable->manufacturer_id = Input::get('manufacturer_id');
$consumable->model_number = Input::get('model_number');
$consumable->item_no = Input::get('item_no');
if (Input::get('purchase_date') == '') {
$consumable->purchase_date = null;
} else {
$consumable->purchase_date = Input::get('purchase_date');
}
if (Input::get('purchase_cost') == '0.00') {
$consumable->purchase_cost = null;
} else {
$consumable->purchase_cost = Helper::ParseFloat(Input::get('purchase_cost'));
}
$consumable->qty = Input::get('qty');
$consumable->user_id = Auth::id();
// Was the consumable created?
if ($consumable->save()) {
$consumable->logCreate();
// Redirect to the new consumable page
return redirect()->route('consumables.index')->with('success', trans('admin/consumables/message.create.success'));
}
return redirect()->back()->withInput()->withErrors($consumable->getErrors());
}
/**
* Returns a form view to edit a consumable.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $consumableId
* @see ConsumablesController::postEdit() method that stores the form data.
* @since [v1.0]
* @return \Illuminate\Contracts\View\View
*/
public function edit($consumableId = null)
{
// Check if the consumable exists
if (is_null($item = Consumable::find($consumableId))) {
// Redirect to the blogs management page
return redirect()->route('consumables.index')->with('error', trans('admin/consumables/message.does_not_exist'));
}
$this->authorize($item);
return View::make('consumables/edit', compact('item'))
->with('category_list', Helper::categoryList('consumable'))
->with('company_list', Helper::companyList())
->with('location_list', Helper::locationsList())
->with('manufacturer_list', Helper::manufacturerList());
}
/**
* Returns a form view to edit a consumable.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $consumableId
* @see ConsumablesController::getEdit() method that stores the form data.
* @since [v1.0]
* @return \Illuminate\Http\RedirectResponse
*/
public function update($consumableId = null)
{
if (is_null($consumable = Consumable::find($consumableId))) {
return redirect()->route('consumables.index')->with('error', trans('admin/consumables/message.does_not_exist'));
}
$this->authorize($consumable);
$consumable->name = Input::get('name');
$consumable->category_id = Input::get('category_id');
$consumable->location_id = Input::get('location_id');
$consumable->company_id = Company::getIdForCurrentUser(Input::get('company_id'));
$consumable->order_number = Input::get('order_number');
$consumable->min_amt = Input::get('min_amt');
$consumable->manufacturer_id = Input::get('manufacturer_id');
$consumable->model_number = Input::get('model_number');
$consumable->item_no = Input::get('item_no');
if (Input::get('purchase_date') == '') {
$consumable->purchase_date = null;
} else {
$consumable->purchase_date = Input::get('purchase_date');
}
if (Input::get('purchase_cost') == '0.00') {
$consumable->purchase_cost = null;
} else {
$consumable->purchase_cost = Helper::ParseFloat(Input::get('purchase_cost'));
}
$consumable->qty = Helper::ParseFloat(Input::get('qty'));
if ($consumable->save()) {
return redirect()->route('consumables.index')->with('success', trans('admin/consumables/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($consumable->getErrors());
}
/**
* Delete a consumable.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $consumableId
* @since [v1.0]
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy($consumableId)
{
// Check if the blog post exists
if (is_null($consumable = Consumable::find($consumableId))) {
// Redirect to the blogs management page
return redirect()->route('consumables.index')->with('error', trans('admin/consumables/message.not_found'));
}
$this->authorize($consumable);
$consumable->delete();
// Redirect to the locations management page
return redirect()->route('consumables.index')->with('success', trans('admin/consumables/message.delete.success'));
}
/**
* Return a view to display component information.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @see ConsumablesController::getDataView() method that generates the JSON response
* @since [v1.0]
* @param int $consumableId
* @return \Illuminate\Contracts\View\View
*/
public function show($consumableId = null)
{
$consumable = Consumable::find($consumableId);
$this->authorize($consumable);
if (isset($consumable->id)) {
return View::make('consumables/view', compact('consumable'));
}
// Prepare the error message
$error = trans('admin/consumables/message.does_not_exist', compact('id'));
// Redirect to the user management page
return redirect()->route('consumables')->with('error', $error);
}
/**
* Return a view to checkout a consumable to a user.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @see ConsumablesController::postCheckout() method that stores the data.
* @since [v1.0]
* @param int $consumableId
* @return \Illuminate\Contracts\View\View
*/
public function getCheckout($consumableId)
{
// Check if the consumable exists
if (is_null($consumable = Consumable::find($consumableId))) {
// Redirect to the consumable management page with error
return redirect()->route('consumables.index')->with('error', trans('admin/consumables/message.not_found'));
}
$this->authorize('checkout', $consumable);
// Get the dropdown of users and then pass it to the checkout view
return View::make('consumables/checkout', compact('consumable'))->with('users_list', Helper::usersList());
}
/**
* Saves the checkout information
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @see ConsumablesController::getCheckout() method that returns the form.
* @since [v1.0]
* @param int $consumableId
* @return \Illuminate\Http\RedirectResponse
*/
public function postCheckout($consumableId)
{
// Check if the consumable exists
if (is_null($consumable = Consumable::find($consumableId))) {
// Redirect to the consumable management page with error
return redirect()->route('consumables.index')->with('error', trans('admin/consumables/message.not_found'));
}
$this->authorize('checkout', $consumable);
$admin_user = Auth::user();
$assigned_to = e(Input::get('assigned_to'));
// Check if the user exists
if (is_null($user = User::find($assigned_to))) {
// Redirect to the consumable management page with error
return redirect()->route('consumables.index')->with('error', trans('admin/consumables/message.user_does_not_exist'));
}
// Update the consumable data
$consumable->assigned_to = e(Input::get('assigned_to'));
$consumable->users()->attach($consumable->id, [
'consumable_id' => $consumable->id,
'user_id' => $admin_user->id,
'assigned_to' => e(Input::get('assigned_to'))
]);
$logaction = $consumable->logCheckout(e(Input::get('note')));
$settings = Setting::getSettings();
if ($settings->slack_endpoint) {
$slack_settings = [
'username' => $settings->botname,
'channel' => $settings->slack_channel,
'link_names' => true
];
$client = new \Maknz\Slack\Client($settings->slack_endpoint, $slack_settings);
try {
$client->attach([
'color' => 'good',
'fields' => [
[
'title' => 'Checked Out:',
'value' => 'Consumable <'.route('consumables.show', $consumable->id).'|'.$consumable->name
.'> checked out to <'.route('users.show', $user->id).'|'.$user->fullName()
.'> by <'.route('users.show', $admin_user->id).'|'.$admin_user->fullName().'>.'
],
[
'title' => 'Note:',
'value' => e($logaction->note)
],
]
])->send('Consumable Checked Out');
} catch (Exception $e) {
}
}
$consumable_user = DB::table('consumables_users')->where('assigned_to', '=', $consumable->assigned_to)->where('consumable_id', '=', $consumable->id)->first();
$data['log_id'] = $logaction->id;
$data['eula'] = $consumable->getEula();
$data['first_name'] = $user->first_name;
$data['item_name'] = $consumable->name;
$data['checkout_date'] = $logaction->created_at;
$data['note'] = $logaction->note;
$data['require_acceptance'] = $consumable->requireAcceptance();
if (($consumable->requireAcceptance()=='1') || ($consumable->getEula())) {
Mail::send('emails.accept-asset', $data, function ($m) use ($user) {
$m->to($user->email, $user->first_name . ' ' . $user->last_name);
$m->replyTo(config('mail.reply_to.address'), config('mail.reply_to.name'));
$m->subject(trans('mail.Confirm_consumable_delivery'));
});
}
// Redirect to the new consumable page
return redirect()->route('consumables.index')->with('success', trans('admin/consumables/message.checkout.success'));
}
/**
* Returns the JSON response containing the the consumables data.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @see ConsumablesController::getIndex() method that returns the view that consumes the JSON.
* @since [v1.0]
* @return array
*/
public function getDatatable()
{
$this->authorize('index', Consumable::class);
$consumables = Company::scopeCompanyables(
Consumable::select('consumables.*')
->whereNull('consumables.deleted_at')
->with('company', 'location', 'category', 'users', 'manufacturer')
);
if (Input::has('search')) {
$consumables = $consumables->TextSearch(e(Input::get('search')));
}
$offset = request('offset', 0);
$limit = request('limit', 50);
$allowed_columns = ['id','name','order_number','min_amt','purchase_date','purchase_cost','companyName','category','model_number', 'item_no', 'manufacturer'];
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'created_at';
switch ($sort) {
case 'category':
$consumables = $consumables->OrderCategory($order);
break;
case 'location':
$consumables = $consumables->OrderLocation($order);
break;
case 'manufacturer':
$consumables = $consumables->OrderManufacturer($order);
break;
case 'companyName':
$consumables = $consumables->OrderCompany($order);
break;
default:
$consumables = $consumables->orderBy($sort, $order);
break;
}
$consumCount = $consumables->count();
$consumables = $consumables->skip($offset)->take($limit)->get();
$rows = array();
foreach ($consumables as $consumable) {
$actions = '<nobr>';
if (Gate::allows('checkout', $consumable)) {
$actions .= Helper::generateDatatableButton('checkout', route('checkout/consumable', $consumable->id), $consumable->numRemaining() > 0);
}
if (Gate::allows('update', $consumable)) {
$actions .= Helper::generateDatatableButton('edit', route('consumables.edit', $consumable->id));
}
if (Gate::allows('delete', $consumable)) {
$actions .= Helper::generateDatatableButton(
'delete',
route('consumables.destroy', $consumable->id),
true, /* enabled */
trans('admin/consumables/message.delete.confirm'),
$consumable->name
);
}
$actions .='</nobr>';
$company = $consumable->company;
$rows[] = array(
'id' => $consumable->id,
'name' => (string)link_to_route('consumables.show', e($consumable->name), ['consumable' => $consumable->id]),
'location' => ($consumable->location) ? e($consumable->location->name) : '',
'min_amt' => e($consumable->min_amt),
'qty' => e($consumable->qty),
'manufacturer' => ($consumable->manufacturer) ? (string) link_to_route('manufacturers.show', $consumable->manufacturer->name, ['manufacturer' => $consumable->manufacturer_id]): '',
'model_number' => e($consumable->model_number),
'item_no' => e($consumable->item_no),
'category' => ($consumable->category) ? (string) link_to_route('categories.show', $consumable->category->name, ['category' => $consumable->category_id]) : 'Missing category',
'order_number' => e($consumable->order_number),
'purchase_date' => e($consumable->purchase_date),
'purchase_cost' => Helper::formatCurrencyOutput($consumable->purchase_cost),
'numRemaining' => $consumable->numRemaining(),
'actions' => $actions,
'companyName' => is_null($company) ? '' : e($company->name),
);
}
$data = array('total' => $consumCount, 'rows' => $rows);
return $data;
}
/**
* Returns a JSON response containing details on the users associated with this consumable.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @see ConsumablesController::getView() method that returns the form.
* @since [v1.0]
* @param int $consumableId
* @return array
*/
public function getDataView($consumableId)
{
//$consumable = Consumable::find($consumableID);
$consumable = Consumable::with(array('consumableAssigments'=>
function ($query) {
$query->orderBy('created_at', 'DESC');
},
'consumableAssigments.admin'=> function ($query) {
},
'consumableAssigments.user'=> function ($query) {
},
))->find($consumableId);
// $consumable->load('consumableAssigments.admin','consumableAssigments.user');
if (!Company::isCurrentUserHasAccess($consumable)) {
return ['total' => 0, 'rows' => []];
}
$this->authorize('view', Component::class);
$rows = array();
foreach ($consumable->consumableAssigments as $consumable_assignment) {
$rows[] = array(
'name' => (string)link_to_route('users.show', e($consumable_assignment->user->fullName()), ['user' => $consumable_assignment->user->id]),
'created_at' => ($consumable_assignment->created_at->format('Y-m-d H:i:s')=='-0001-11-30 00:00:00') ? '' : $consumable_assignment->created_at->format('Y-m-d H:i:s'),
'admin' => ($consumable_assignment->admin) ? e($consumable_assignment->admin->fullName()) : '',
);
}
$consumableCount = $consumable->users->count();
$data = array('total' => $consumableCount, 'rows' => $rows);
return $data;
}
}