Additional API routes and controllers for models, suppliers, users, locations and status labels

This commit is contained in:
snipe 2017-01-13 04:50:20 -08:00
parent bc5fcf8736
commit c7e1b426e7
14 changed files with 264 additions and 219 deletions

View file

@ -0,0 +1,110 @@
<?php
namespace App\Http\Controllers\Api;
use App\Models\AssetModel;
use App\Http\Controllers\Controller;
use App\Helpers\Helper;
use Illuminate\Http\Request;
use App\Http\Transformers\DatatablesTransformer;
/**
* This class controls all actions related to asset models for
* the Snipe-IT Asset Management application.
*
* @version v4.0
* @author [A. Gianotto] [<snipe@snipe.net>]
*/
class AssetModelsController extends Controller
{
/**
* Display a listing of the resource.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @return \Illuminate\Http\Response
*/
public function index()
{
$this->authorize('view', AssetModel::class);
$assetmodels = AssetModel::all();
return (new DatatablesTransformer)->transformDatatables($assetmodels, count($assetmodels));
}
/**
* Store a newly created resource in storage.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->authorize('create', AssetModel::class);
$assetmodel = new AssetModel;
$assetmodel->fill($request->all());
if ($assetmodel->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $assetmodel, trans('admin/assetmodels/message.create.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $assetmodel->getErrors()));
}
/**
* Display the specified resource.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$this->authorize('view', AssetModel::class);
$assetmodel = AssetModel::findOrFail($id);
return $assetmodel;
}
/**
* Update the specified resource in storage.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->authorize('edit', AssetModel::class);
$assetmodel = AssetModel::findOrFail($id);
$assetmodel->fill($request->all());
if ($assetmodel->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $assetmodel, trans('admin/assetmodels/message.update.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $assetmodel->getErrors()));
}
/**
* Remove the specified resource from storage.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$this->authorize('delete', AssetModel::class);
$assetmodel = AssetModel::findOrFail($id);
$this->authorize('delete', $assetmodel);
$assetmodel->delete();
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/assetmodels/message.delete.success')));
}
}

View file

@ -21,7 +21,7 @@ class LocationsController extends Controller
{ {
$this->authorize('view', Location::class); $this->authorize('view', Location::class);
$locations = Location::all(); $locations = Location::all();
return (new DatatablesTransformer)->transformDatatables($locations); return (new DatatablesTransformer)->transformDatatables($locations, count($locations));
} }

View file

@ -7,6 +7,7 @@ use App\Http\Controllers\Controller;
use App\Helpers\Helper; use App\Helpers\Helper;
use App\Models\Statuslabel; use App\Models\Statuslabel;
use App\Models\Asset; use App\Models\Asset;
use App\Http\Transformers\StatuslabelsTransformer;
class StatuslabelsController extends Controller class StatuslabelsController extends Controller
{ {
@ -21,7 +22,7 @@ class StatuslabelsController extends Controller
{ {
$this->authorize('view', Statuslabel::class); $this->authorize('view', Statuslabel::class);
$statuslabels = Statuslabel::all(); $statuslabels = Statuslabel::all();
return $statuslabels; return (new StatuslabelsTransformer)->transformStatuslabels($statuslabels);
} }

View file

@ -6,6 +6,7 @@ use Illuminate\Http\Request;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Helpers\Helper; use App\Helpers\Helper;
use App\Models\Supplier; use App\Models\Supplier;
use App\Http\Transformers\DatatablesTransformer;
class SuppliersController extends Controller class SuppliersController extends Controller
{ {
@ -16,10 +17,31 @@ class SuppliersController extends Controller
* @since [v4.0] * @since [v4.0]
* @return \Illuminate\Http\Response * @return \Illuminate\Http\Response
*/ */
public function index() public function index(Request $request)
{ {
$this->authorize('view', Supplier::class); $this->authorize('view', Supplier::class);
$suppliers = Supplier::all(); $allowed_columns = ['id','name','address','phone','contact','fax','email'];
// Not sure how to access the withCount value?
$suppliers = Supplier::select(
array('id','name','address','address2','city','state','country','fax', 'phone','email','contact')
)->withCount('assets')->withCount('licenses')->whereNull('deleted_at');
if ($request->has('search')) {
$suppliers = $suppliers->TextSearch($request->input('search'));
}
$offset = request('offset', 0);
$limit = $request->input('limit', 50);
$order = $request->input('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array($request->input('sort'), $allowed_columns) ? $request->input('sort') : 'created_at';
$suppliers->orderBy($sort, $order);
$total = $suppliers->count();
$suppliers = $suppliers->skip($offset)->take($limit)->get();
return (new DatatablesTransformer)->transformDatatables($suppliers, $total);
return $suppliers; return $suppliers;
} }

View file

@ -5,7 +5,7 @@ namespace App\Http\Controllers\Api;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Http\Transformers\UsersTransformer; use App\Http\Transformers\UsersTransformer;
use App\Http\Transformers\DatatablesTransformer; use App\Models\Company;
use App\Models\User; use App\Models\User;
class UsersController extends Controller class UsersController extends Controller
@ -18,11 +18,60 @@ class UsersController extends Controller
* *
* @return \Illuminate\Http\Response * @return \Illuminate\Http\Response
*/ */
public function index() public function index(Request $request)
{ {
$this->authorize('view', User::class); $this->authorize('view', User::class);
$users = User::all();
return (new UsersTransformer)->transformUsers($users); $users = User::select([
'users.id',
'users.employee_num',
'users.two_factor_enrolled',
'users.jobtitle',
'users.email',
'users.username',
'users.location_id',
'users.manager_id',
'users.first_name',
'users.last_name',
'users.created_at',
'users.notes',
'users.company_id',
'users.deleted_at',
'users.activated'
])->with('manager', 'groups', 'userloc', 'company', 'throttle');
$users = Company::scopeCompanyables($users);
if ($request->has('search')) {
$users = $users->TextSearch($request->input('search'));
}
$order = $request->input('order') === 'asc' ? 'asc' : 'desc';
$offset = request('offset', 0);
$limit = request('limit', 50);
switch ($request->input('sort')) {
case 'manager':
$users = $users->OrderManager($order);
break;
case 'location':
$users = $users->OrderLocation($order);
break;
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'
];
$sort = in_array($request->get('sort'), $allowed_columns) ? $request->get('sort') : 'first_name';
$users = $users->orderBy($sort, $order);
break;
}
$userCount = $users->count();
$users = $users->skip($offset)->take($limit)->get();
return (new UsersTransformer)->transformUsers($users, $userCount);
} }

View file

@ -353,54 +353,6 @@ class AssetModelsController extends Controller
/**
* Get the JSON response to populate the data tables on the
* Asset Model listing page.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v2.0]
* @param string $status
* @return String JSON
*/
public function getDatatable(Request $request, $status = null)
{
$models = AssetModel::with('category', 'assets', 'depreciation', 'manufacturer');
switch ($status) {
case 'Deleted':
$models->withTrashed()->Deleted();
break;
}
if (Input::has('search')) {
$models = $models->TextSearch($request->input('search'));
}
$offset = request('offset', 0);
$limit = request('limit', 50);
$allowed_columns = ['id','name','model_number'];
$order = $request->input('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array($request->input('sort'), $allowed_columns) ? e($request->input('sort')) : 'created_at';
$models = $models->orderBy($sort, $order);
$modelCount = $models->count();
$models = $models->skip($offset)->take($limit)->get();
$rows = array();
foreach ($models as $model) {
$rows[] = $model->present()->forDataTable();
}
$data = array('total' => $modelCount, 'rows' => $rows);
return $data;
}
/** /**
* Get the asset information to present to the model view detail page * Get the asset information to present to the model view detail page
* *

View file

@ -231,56 +231,4 @@ class SuppliersController extends Controller
return redirect()->route('suppliers')->with('error', $error); return redirect()->route('suppliers')->with('error', $error);
} }
public function getDatatable()
{
$suppliers = Supplier::with('assets', 'licenses')->select(array('id','name','address','address2','city','state','country','fax', 'phone','email','contact'))
->whereNull('deleted_at');
if (Input::has('search')) {
$suppliers = $suppliers->TextSearch(e(Input::get('search')));
}
$offset = request('offset', 0);
$limit = request('limit', 50);
$allowed_columns = ['id','name','address','phone','contact','fax','email'];
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'created_at';
$suppliers->orderBy($sort, $order);
$suppliersCount = $suppliers->count();
$suppliers = $suppliers->skip($offset)->take($limit)->get();
$rows = array();
foreach ($suppliers as $supplier) {
$actions = '<nobr>';
$actions .= Helper::generateDatatableButton('edit', route('suppliers.edit', $supplier->id));
$actions .= Helper::generateDatatableButton(
'delete',
route('suppliers.destroy', $supplier->id),
true, /*enabled*/
trans('admin/suppliers/message.delete.confirm'),
$supplier->name
);
$actions .= '</nobr>';
$rows[] = array(
'id' => $supplier->id,
'name' => (string)link_to_route('suppliers.show', e($supplier->name), ['supplier' => $supplier->id ]),
'contact' => e($supplier->contact),
'address' => e($supplier->address).' '.e($supplier->address2).' '.e($supplier->city).' '.e($supplier->state).' '.e($supplier->country),
'phone' => e($supplier->phone),
'fax' => e($supplier->fax),
'email' => ($supplier->email!='') ? '<a href="mailto:'.e($supplier->email).'">'.e($supplier->email).'</a>' : '',
'assets' => $supplier->assets->count(),
'licenses' => $supplier->licenses->count(),
'actions' => $actions
);
}
$data = array('total' => $suppliersCount, 'rows' => $rows);
return $data;
}
} }

View file

@ -780,89 +780,6 @@ class UsersController extends Controller
return redirect()->route('users.index')->with('duplicates', $duplicates)->with('success', 'Success'); return redirect()->route('users.index')->with('duplicates', $duplicates)->with('success', 'Success');
} }
/**
* Return JSON response with a list of user details for the getIndex() view.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.6]
* @see UsersController::getIndex() method that consumed this JSON response
* @return string JSON
*/
public function getDatatable(Request $request, $status = null)
{
$this->authorize('view', User::class);
$offset = request('offset', 0);
$limit = request('limit', 50);
if (Input::get('sort')=='name') {
$sort = 'first_name';
} else {
$sort = e(Input::get('sort'));
}
$users = User::select([
'users.id',
'users.employee_num',
'users.two_factor_enrolled',
'users.jobtitle',
'users.email',
'users.username',
'users.location_id',
'users.manager_id',
'users.first_name',
'users.last_name',
'users.created_at',
'users.notes',
'users.company_id',
'users.deleted_at',
'users.activated'
])->with('manager', 'groups', 'userloc', 'company', 'throttle');
$users = Company::scopeCompanyables($users);
switch ($status) {
case 'deleted':
$users = $users->withTrashed()->Deleted();
break;
}
if (Input::has('search')) {
$users = $users->TextSearch(Input::get('search'));
}
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
switch (Input::get('sort')) {
case 'manager':
$users = $users->OrderManager($order);
break;
case 'location':
$users = $users->OrderLocation($order);
break;
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'
];
$sort = in_array($sort, $allowed_columns) ? $sort : 'first_name';
$users = $users->orderBy($sort, $order);
break;
}
$userCount = $users->count();
$users = $users->skip($offset)->take($limit)->get();
$rows = array();
foreach ($users as $user) {
$rows[] = $user->present()->forDataTable();
}
$data = array('total'=>$userCount, 'rows'=>$rows);
return $data;
}
/** /**
* Return JSON response with a list of user details for the getIndex() view. * Return JSON response with a list of user details for the getIndex() view.

View file

@ -7,10 +7,10 @@ use App\Models\Location;
class DatatablesTransformer class DatatablesTransformer
{ {
public function transformDatatables($objects) public function transformDatatables($objects, $total = null)
{ {
(isset($total)) ? $objects_array['total'] = $total : $objects_array['total'] = count($objects);
$objects_array['rows'] = $objects; $objects_array['rows'] = $objects;
$objects_array['total'] = count($objects);
return $objects_array; return $objects_array;
} }
} }

View file

@ -0,0 +1,40 @@
<?php
namespace App\Http\Transformers;
use App\Models\Statuslabel;
use Illuminate\Database\Eloquent\Collection;
class StatuslabelsTransformer
{
public function transformStatuslabels (Collection $statuslabels)
{
$array = array();
foreach ($statuslabels as $statuslabel) {
$array[] = self::transformStatuslabel($statuslabel);
}
return (new DatatablesTransformer)->transformDatatables($array);
}
public function transformStatuslabel (Statuslabel $statuslabel)
{
$array = [
'id' => e($statuslabel->id),
'name' => e($statuslabel->name),
'type' => $statuslabel->getStatuslabelType(),
'color' => e($statuslabel->color),
'show_in_nav' => ($statuslabel->show_in_nav=='1') ? true : false,
'created_at' => $statuslabel->created_at,
'updated_at' => $statuslabel->updated_at,
];
return $array;
}
public function transformStatuslabelsDatatable($users) {
return (new DatatablesTransformer)->transformDatatables($users);
}
}

View file

@ -3,36 +3,41 @@ namespace App\Http\Transformers;
use App\Models\User; use App\Models\User;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
use phpDocumentor\Reflection\Types\Integer;
class UsersTransformer class UsersTransformer
{ {
public function transformUsers( Collection $users) public function transformUsers (Collection $users, $total)
{ {
$users_array = array(); $array = array();
foreach ($users as $user) { foreach ($users as $user) {
$users_array[] = self::transformUser($user); $array[] = self::transformUser($user);
} }
return (new DatatablesTransformer)->transformDatatables($users_array); return (new DatatablesTransformer)->transformDatatables($array, $total);
} }
public function transformUser(User $user) public function transformUser (User $user)
{ {
$user_array[] = [ $array = [
'id' => e($user->id), 'id' => e($user->id),
'name' => e($user->first_name).' '.($user->last_name), 'name' => e($user->first_name).' '.($user->last_name),
'firstname' => e($user->first_name), 'firstname' => e($user->first_name),
'lastname' => e($user->last_name), 'lastname' => e($user->last_name),
'username' => e($user->username), 'username' => e($user->username),
'employee_num' => e($user->employee_num),
'manager' => ($user->manager) ? $user->manager->name : false,
'jobtitle' => e($user->jobtitle), 'jobtitle' => e($user->jobtitle),
'email' => e($user->email), 'email' => e($user->email),
'location' => (new LocationsTransformer)->transformLocation($user->userloc), 'location' => (new LocationsTransformer)->transformLocation($user->userloc),
'permissions' => $user->decodePermissions(), 'permissions' => $user->decodePermissions(),
'activated' => ($user->activated =='1') ? true : false,
'two_factor_activated' => ($user->activated =='1') ? true : false,
'created_at' => $user->created_at, 'created_at' => $user->created_at,
'updated_at' => $user->updated_at, 'updated_at' => $user->updated_at,
]; ];
return $user_array; return $array;
} }
public function transformUsersDatatable($users) { public function transformUsersDatatable($users) {

View file

@ -23,7 +23,7 @@
name="statuslabels" name="statuslabels"
id="table" id="table"
class="snipe-table" class="snipe-table"
data-url="{{ route('api.statuslabels.list') }}" data-url="{{ route('api.statuslabels.index') }}"
data-cookie="true" data-cookie="true"
data-click-to-select="true" data-click-to-select="true"
data-cookie-id-table="statuslabelsTable-{{ config('version.hash_version') }}"> data-cookie-id-table="statuslabelsTable-{{ config('version.hash_version') }}">

View file

@ -23,7 +23,7 @@
name="suppliers" name="suppliers"
id="table" id="table"
class="table table-striped snipe-table" class="table table-striped snipe-table"
data-url="{{ route('api.suppliers.list') }}" data-url="{{ route('api.suppliers.index') }}"
data-cookie="true" data-cookie="true"
data-click-to-select="true" data-click-to-select="true"
data-cookie-id-table="suppliersTable-{{ config('version.hash_version') }}"> data-cookie-id-table="suppliersTable-{{ config('version.hash_version') }}">

View file

@ -33,6 +33,24 @@ Route::group(['prefix' => 'v1','namespace' => 'Api'], function () {
] ]
); );
Route::resource('models', 'AssetModelsController',
['names' =>
[
'index' => 'api.models.index',
'show' => 'api.models.show',
'update' => 'api.models.update',
'store' => 'api.models.store',
'destroy' => 'api.models.destroy'
],
'except' => ['edit', 'create'],
'parameters' => ['model' => 'model_id']
]
);
Route::resource('companies', 'CompaniesController', Route::resource('companies', 'CompaniesController',
['names' => ['names' =>
[ [
@ -275,23 +293,6 @@ Route::group(['prefix' => 'v1','namespace' => 'Api'], function () {
}); });
/*-- Suppliers API (mostly for creating new ones in-line while creating an asset) --*/
Route::group([ 'prefix' => 'suppliers' ], function () {
Route::resource('/', 'SuppliersController');
});
});
Route::get('test', function(){
return 'returned string from test route';
}); });