Refactored API index methods

This commit is contained in:
Hillel Coren 2016-05-01 23:55:13 +03:00
parent e7296cf513
commit 4db5a19885
13 changed files with 186 additions and 228 deletions

View File

@ -2,6 +2,8 @@
use Session; use Session;
use Utils; use Utils;
use Auth;
use Input;
use Response; use Response;
use Request; use Request;
use League\Fractal; use League\Fractal;
@ -9,8 +11,10 @@ use League\Fractal\Manager;
use League\Fractal\Resource\Item; use League\Fractal\Resource\Item;
use League\Fractal\Resource\Collection; use League\Fractal\Resource\Collection;
use League\Fractal\Pagination\IlluminatePaginatorAdapter; use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use App\Models\EntityModel;
use App\Ninja\Serializers\ArraySerializer; use App\Ninja\Serializers\ArraySerializer;
use League\Fractal\Serializer\JsonApiSerializer; use League\Fractal\Serializer\JsonApiSerializer;
use Illuminate\Pagination\LengthAwarePaginator;
/** /**
* @SWG\Swagger( * @SWG\Swagger(
@ -64,6 +68,23 @@ class BaseAPIController extends Controller
} }
} }
protected function returnList($query)
{
if ($clientPublicId = Input::get('client_id')) {
$filter = function($query) use ($clientPublicId) {
$query->where('public_id', '=', $clientPublicId);
};
$query->whereHas('client', $filter);
}
$transformerClass = EntityModel::getTransformerName($this->entityType);
$transformer = new $transformerClass(Auth::user()->account, Input::get('serializer'));
$data = $this->createCollection($query, $transformer, $this->entityType);
return $this->response($data);
}
protected function createItem($data, $transformer, $entityType) protected function createItem($data, $transformer, $entityType)
{ {
if ($this->serializer && $this->serializer != API_SERIALIZER_JSON) { if ($this->serializer && $this->serializer != API_SERIALIZER_JSON) {
@ -74,18 +95,19 @@ class BaseAPIController extends Controller
return $this->manager->createData($resource)->toArray(); return $this->manager->createData($resource)->toArray();
} }
protected function createCollection($data, $transformer, $entityType, $paginator = false) protected function createCollection($query, $transformer, $entityType)
{ {
if ($this->serializer && $this->serializer != API_SERIALIZER_JSON) { if ($this->serializer && $this->serializer != API_SERIALIZER_JSON) {
$entityType = null; $entityType = null;
} }
$resource = new Collection($data, $transformer, $entityType); if ($query instanceof LengthAwarePaginator) {
$resource = new Collection($query, $transformer, $entityType);
if ($paginator) { } else {
$resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); $resource = new Collection($query->get(), $transformer, $entityType);
$resource->setPaginator(new IlluminatePaginatorAdapter($query->paginate()));
} }
return $this->manager->createData($resource)->toArray(); return $this->manager->createData($resource)->toArray();
} }

View File

@ -18,6 +18,8 @@ class ClientApiController extends BaseAPIController
protected $clientRepo; protected $clientRepo;
protected $clientService; protected $clientService;
protected $entityType = ENTITY_CLIENT;
public function __construct(ClientRepository $clientRepo, ClientService $clientService) public function __construct(ClientRepository $clientRepo, ClientService $clientService)
{ {
parent::__construct(); parent::__construct();
@ -53,26 +55,18 @@ class ClientApiController extends BaseAPIController
{ {
$clients = Client::scope() $clients = Client::scope()
->with($this->getIncluded()) ->with($this->getIncluded())
->orderBy('created_at', 'desc')->withTrashed(); ->orderBy('created_at', 'desc')
->withTrashed();
// Filter by email // Filter by email
if (Input::has('email')) { if (Input::has('email')) {
$email = Input::get('email'); $email = Input::get('email');
$clients = $clients->whereHas('contacts', function ($query) use ($email) { $clients = $clients->whereHas('contacts', function ($query) use ($email) {
$query->where('email', $email); $query->where('email', $email);
}); });
} }
$clients = $clients->paginate(); return $this->returnList($clients);
$transformer = new ClientTransformer(Auth::user()->account, Input::get('serializer'));
$paginator = Client::scope()->withTrashed()->paginate();
$data = $this->createCollection($clients, $transformer, ENTITY_CLIENT, $paginator);
return $this->response($data);
} }
/** /**

View File

@ -1,5 +1,5 @@
<?php namespace App\Http\Controllers; <?php namespace App\Http\Controllers;
// vendor
use App\Models\Expense; use App\Models\Expense;
use app\Ninja\Repositories\ExpenseRepository; use app\Ninja\Repositories\ExpenseRepository;
use App\Ninja\Transformers\ExpenseTransformer; use App\Ninja\Transformers\ExpenseTransformer;
@ -16,6 +16,8 @@ class ExpenseApiController extends BaseAPIController
protected $expenseRepo; protected $expenseRepo;
protected $expenseService; protected $expenseService;
protected $entityType = ENTITY_EXPENSE;
public function __construct(ExpenseRepository $expenseRepo, ExpenseService $expenseService) public function __construct(ExpenseRepository $expenseRepo, ExpenseService $expenseService)
{ {
parent::__construct(); parent::__construct();
@ -26,20 +28,11 @@ class ExpenseApiController extends BaseAPIController
public function index() public function index()
{ {
$expenses = Expense::scope() $expenses = Expense::scope()
->withTrashed() ->withTrashed()
->orderBy('created_at','desc'); ->orderBy('created_at','desc');
$expenses = $expenses->paginate(); return $this->returnList($expenses);
$transformer = new ExpenseTransformer(Auth::user()->account, Input::get('serializer'));
$paginator = Expense::scope()->withTrashed()->paginate();
$data = $this->createCollection($expenses, $transformer, ENTITY_EXPENSE, $paginator);
return $this->response($data);
} }
public function update() public function update()

View File

@ -26,6 +26,8 @@ class InvoiceApiController extends BaseAPIController
{ {
protected $invoiceRepo; protected $invoiceRepo;
protected $entityType = ENTITY_INVOICE;
public function __construct(InvoiceService $invoiceService, InvoiceRepository $invoiceRepo, ClientRepository $clientRepo, PaymentRepository $paymentRepo, Mailer $mailer) public function __construct(InvoiceService $invoiceService, InvoiceRepository $invoiceRepo, ClientRepository $clientRepo, PaymentRepository $paymentRepo, Mailer $mailer)
{ {
parent::__construct(); parent::__construct();
@ -55,36 +57,12 @@ class InvoiceApiController extends BaseAPIController
*/ */
public function index() public function index()
{ {
$paginator = Invoice::scope()->withTrashed(); $invoices = Invoice::scope()
$invoices = Invoice::scope()->withTrashed() ->withTrashed()
->with(array_merge(['invoice_items'], $this->getIncluded())); ->with(array_merge(['invoice_items'], $this->getIncluded()))
->orderBy('created_at', 'desc');
if ($clientPublicId = Input::get('client_id')) { return $this->returnList($invoices);
$filter = function($query) use ($clientPublicId) {
$query->where('public_id', '=', $clientPublicId);
};
$invoices->whereHas('client', $filter);
$paginator->whereHas('client', $filter);
}
$invoices = $invoices->orderBy('created_at', 'desc')->paginate();
/*
// Add the first invitation link to the data
foreach ($invoices as $key => $invoice) {
foreach ($invoice->invitations as $subKey => $invitation) {
$invoices[$key]['link'] = $invitation->getLink();
}
unset($invoice['invitations']);
}
*/
$transformer = new InvoiceTransformer(Auth::user()->account, Input::get('serializer'));
$paginator = $paginator->paginate();
$data = $this->createCollection($invoices, $transformer, 'invoices', $paginator);
return $this->response($data);
} }
/** /**
@ -106,7 +84,6 @@ class InvoiceApiController extends BaseAPIController
public function show($publicId) public function show($publicId)
{ {
$invoice = Invoice::scope($publicId)->withTrashed()->first(); $invoice = Invoice::scope($publicId)->withTrashed()->first();
if(!$invoice) if(!$invoice)

View File

@ -546,13 +546,13 @@ class InvoiceController extends BaseController
} }
} }
public function convertQuote(InvoiceRequest $request, $publicId) public function convertQuote(InvoiceRequest $request)
{ {
$invoice = Invoice::with('invoice_items')->scope($publicId)->firstOrFail(); $clone = $this->invoiceService->convertQuote($request->entity());
$clone = $this->invoiceService->convertQuote($invoice);
Session::flash('message', trans('texts.converted_to_invoice')); Session::flash('message', trans('texts.converted_to_invoice'));
return Redirect::to('invoices/'.$clone->public_id);
return Redirect::to('invoices/' . $clone->public_id);
} }
public function cloneInvoice(InvoiceRequest $request, $publicId) public function cloneInvoice(InvoiceRequest $request, $publicId)

View File

@ -17,13 +17,14 @@ class PaymentApiController extends BaseAPIController
{ {
protected $paymentRepo; protected $paymentRepo;
protected $entityType = ENTITY_PAYMENT;
public function __construct(PaymentRepository $paymentRepo, ContactMailer $contactMailer) public function __construct(PaymentRepository $paymentRepo, ContactMailer $contactMailer)
{ {
parent::__construct(); parent::__construct();
$this->paymentRepo = $paymentRepo; $this->paymentRepo = $paymentRepo;
$this->contactMailer = $contactMailer; $this->contactMailer = $contactMailer;
} }
/** /**
@ -44,85 +45,71 @@ class PaymentApiController extends BaseAPIController
*/ */
public function index() public function index()
{ {
$paginator = Payment::scope();
$payments = Payment::scope() $payments = Payment::scope()
->with('client.contacts', 'invitation', 'user', 'invoice')->withTrashed(); ->withTrashed()
->with(array_merge(['client.contacts', 'invitation', 'user', 'invoice'], $this->getIncluded()))
->orderBy('created_at', 'desc');
if ($clientPublicId = Input::get('client_id')) { return $this->returnList($payments);
$filter = function($query) use ($clientPublicId) {
$query->where('public_id', '=', $clientPublicId);
};
$payments->whereHas('client', $filter);
$paginator->whereHas('client', $filter);
}
$payments = $payments->orderBy('created_at', 'desc')->paginate();
$paginator = $paginator->paginate();
$transformer = new PaymentTransformer(Auth::user()->account, Input::get('serializer'));
$data = $this->createCollection($payments, $transformer, 'payments', $paginator);
return $this->response($data);
} }
/**
* @SWG\Put(
* path="/payments/{payment_id",
* summary="Update a payment",
* tags={"payment"},
* @SWG\Parameter(
* in="body",
* name="body",
* @SWG\Schema(ref="#/definitions/Payment")
* ),
* @SWG\Response(
* response=200,
* description="Update payment",
* @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Payment"))
* ),
* @SWG\Response(
* response="default",
* description="an ""unexpected"" error"
* )
* )
*/
/** public function update(Request $request, $publicId)
* @SWG\Put( {
* path="/payments/{payment_id", $data = Input::all();
* summary="Update a payment", $data['public_id'] = $publicId;
* tags={"payment"}, $error = false;
* @SWG\Parameter(
* in="body",
* name="body",
* @SWG\Schema(ref="#/definitions/Payment")
* ),
* @SWG\Response(
* response=200,
* description="Update payment",
* @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Payment"))
* ),
* @SWG\Response(
* response="default",
* description="an ""unexpected"" error"
* )
* )
*/
public function update(Request $request, $publicId) if ($request->action == ACTION_ARCHIVE) {
{ $payment = Payment::scope($publicId)->withTrashed()->firstOrFail();
$data = Input::all(); $this->paymentRepo->archive($payment);
$data['public_id'] = $publicId;
$error = false;
if ($request->action == ACTION_ARCHIVE) {
$payment = Payment::scope($publicId)->withTrashed()->firstOrFail();
$this->paymentRepo->archive($payment);
$transformer = new PaymentTransformer(\Auth::user()->account, Input::get('serializer'));
$data = $this->createItem($payment, $transformer, 'invoice');
return $this->response($data);
}
$payment = $this->paymentRepo->save($data);
if ($error) {
return $error;
}
/*
$invoice = Invoice::scope($data['invoice_id'])->with('client', 'invoice_items', 'invitations')->with(['payments' => function($query) {
$query->withTrashed();
}])->withTrashed()->first();
*/
$transformer = new PaymentTransformer(\Auth::user()->account, Input::get('serializer')); $transformer = new PaymentTransformer(\Auth::user()->account, Input::get('serializer'));
$data = $this->createItem($payment, $transformer, 'invoice'); $data = $this->createItem($payment, $transformer, 'invoice');
return $this->response($data); return $this->response($data);
} }
$payment = $this->paymentRepo->save($data);
if ($error) {
return $error;
}
/*
$invoice = Invoice::scope($data['invoice_id'])->with('client', 'invoice_items', 'invitations')->with(['payments' => function($query) {
$query->withTrashed();
}])->withTrashed()->first();
*/
$transformer = new PaymentTransformer(\Auth::user()->account, Input::get('serializer'));
$data = $this->createItem($payment, $transformer, 'invoice');
return $this->response($data);
}
/** /**
* @SWG\Post( * @SWG\Post(
@ -190,44 +177,44 @@ class PaymentApiController extends BaseAPIController
} }
/** /**
* @SWG\Delete( * @SWG\Delete(
* path="/payments/{payment_id}", * path="/payments/{payment_id}",
* summary="Delete a payment", * summary="Delete a payment",
* tags={"payment"}, * tags={"payment"},
* @SWG\Parameter( * @SWG\Parameter(
* in="body", * in="body",
* name="body", * name="body",
* @SWG\Schema(ref="#/definitions/Payment") * @SWG\Schema(ref="#/definitions/Payment")
* ), * ),
* @SWG\Response( * @SWG\Response(
* response=200, * response=200,
* description="Delete payment", * description="Delete payment",
* @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Payment")) * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Payment"))
* ), * ),
* @SWG\Response( * @SWG\Response(
* response="default", * response="default",
* description="an ""unexpected"" error" * description="an ""unexpected"" error"
* ) * )
* ) * )
*/ */
public function destroy($publicId) public function destroy($publicId)
{ {
$payment = Payment::scope($publicId)->withTrashed()->first(); $payment = Payment::scope($publicId)->withTrashed()->first();
$invoiceId = $payment->invoice->public_id; $invoiceId = $payment->invoice->public_id;
$this->paymentRepo->delete($payment); $this->paymentRepo->delete($payment);
/* /*
$invoice = Invoice::scope($invoiceId)->with('client', 'invoice_items', 'invitations')->with(['payments' => function($query) { $invoice = Invoice::scope($invoiceId)->with('client', 'invoice_items', 'invitations')->with(['payments' => function($query) {
$query->withTrashed(); $query->withTrashed();
}])->first(); }])->first();
*/ */
$transformer = new PaymentTransformer(\Auth::user()->account, Input::get('serializer')); $transformer = new PaymentTransformer(\Auth::user()->account, Input::get('serializer'));
$data = $this->createItem($payment, $transformer, 'invoice'); $data = $this->createItem($payment, $transformer, 'invoice');
return $this->response($data); return $this->response($data);
} }
} }

View File

@ -20,8 +20,9 @@ use App\Services\ProductService;
class ProductApiController extends BaseAPIController class ProductApiController extends BaseAPIController
{ {
protected $productService; protected $productService;
protected $productRepo;
protected $productRepo;
protected $entityType = ENTITY_PRODUCT;
public function __construct(ProductService $productService, ProductRepository $productRepo) public function __construct(ProductService $productService, ProductRepository $productRepo)
{ {
@ -33,17 +34,11 @@ class ProductApiController extends BaseAPIController
public function index() public function index()
{ {
$products = Product::scope()
->withTrashed()
->orderBy('created_at', 'desc');
$products = Product::scope()->withTrashed(); return $this->returnList($products);
$products = $products->paginate();
$paginator = Product::scope()->withTrashed()->paginate();
$transformer = new ProductTransformer(\Auth::user()->account, $this->serializer);
$data = $this->createCollection($products, $transformer, 'products', $paginator);
return $this->response($data);
} }
public function getDatatable() public function getDatatable()

View File

@ -13,6 +13,8 @@ class TaskApiController extends BaseAPIController
{ {
protected $taskRepo; protected $taskRepo;
protected $entityType = ENTITY_TASK;
public function __construct(TaskRepository $taskRepo) public function __construct(TaskRepository $taskRepo)
{ {
parent::__construct(); parent::__construct();
@ -38,25 +40,12 @@ class TaskApiController extends BaseAPIController
*/ */
public function index() public function index()
{ {
$paginator = Task::scope(); $payments = Task::scope()
$tasks = Task::scope() ->withTrashed()
->with($this->getIncluded()); ->with($this->getIncluded())
->orderBy('created_at', 'desc');
if ($clientPublicId = Input::get('client_id')) { return $this->returnList($payments);
$filter = function($query) use ($clientPublicId) {
$query->where('public_id', '=', $clientPublicId);
};
$tasks->whereHas('client', $filter);
$paginator->whereHas('client', $filter);
}
$tasks = $tasks->orderBy('created_at', 'desc')->paginate();
$paginator = $paginator->paginate();
$transformer = new TaskTransformer(\Auth::user()->account, Input::get('serializer'));
$data = $this->createCollection($tasks, $transformer, 'tasks', $paginator);
return $this->response($data);
} }
/** /**

View File

@ -14,6 +14,8 @@ class TaxRateApiController extends BaseAPIController
protected $taxRateService; protected $taxRateService;
protected $taxRateRepo; protected $taxRateRepo;
protected $entityType = ENTITY_TAX_RATE;
public function __construct(TaxRateService $taxRateService, TaxRateRepository $taxRateRepo) public function __construct(TaxRateService $taxRateService, TaxRateRepository $taxRateRepo)
{ {
parent::__construct(); parent::__construct();
@ -24,15 +26,11 @@ class TaxRateApiController extends BaseAPIController
public function index() public function index()
{ {
$taxRates = TaxRate::scope()->withTrashed(); $taxRates = TaxRate::scope()
$taxRates = $taxRates->paginate(); ->withTrashed()
->orderBy('created_at', 'desc');
$paginator = TaxRate::scope()->withTrashed()->paginate();
return $this->returnList($taxRates);
$transformer = new TaxRateTransformer(Auth::user()->account, $this->serializer);
$data = $this->createCollection($taxRates, $transformer, 'tax_rates', $paginator);
return $this->response($data);
} }
public function store(CreateTaxRateRequest $request) public function store(CreateTaxRateRequest $request)

View File

@ -14,6 +14,8 @@ class UserApiController extends BaseAPIController
protected $userService; protected $userService;
protected $userRepo; protected $userRepo;
protected $entityType = ENTITY_USER;
public function __construct(UserService $userService, UserRepository $userRepo) public function __construct(UserService $userService, UserRepository $userRepo)
{ {
parent::__construct(); parent::__construct();
@ -24,16 +26,11 @@ class UserApiController extends BaseAPIController
public function index() public function index()
{ {
$user = Auth::user(); $users = User::whereAccountId(Auth::user()->account_id)
$users = User::whereAccountId($user->account_id)->withTrashed(); ->withTrashed()
$users = $users->paginate(); ->orderBy('created_at', 'desc');
$paginator = User::whereAccountId($user->account_id)->withTrashed()->paginate(); return $this->returnList($users);
$transformer = new UserTransformer(Auth::user()->account, $this->serializer);
$data = $this->createCollection($users, $transformer, 'users', $paginator);
return $this->response($data);
} }
/* /*

View File

@ -14,6 +14,8 @@ class VendorApiController extends BaseAPIController
{ {
protected $vendorRepo; protected $vendorRepo;
protected $entityType = ENTITY_VENDOR;
public function __construct(VendorRepository $vendorRepo) public function __construct(VendorRepository $vendorRepo)
{ {
parent::__construct(); parent::__construct();
@ -46,17 +48,12 @@ class VendorApiController extends BaseAPIController
*/ */
public function index() public function index()
{ {
$vendors = Vendor::scope() $vendors = Vendor::scope()
->with($this->getIncluded()) ->with($this->getIncluded())
->withTrashed() ->withTrashed()
->orderBy('created_at', 'desc') ->orderBy('created_at', 'desc');
->paginate();
$transformer = new VendorTransformer(Auth::user()->account, Input::get('serializer')); return $this->returnList($vendors);
$paginator = Vendor::scope()->paginate();
$data = $this->createCollection($vendors, $transformer, ENTITY_VENDOR, $paginator);
return $this->response($data);
} }
/** /**

View File

@ -4,17 +4,16 @@ class InvoiceRequest extends EntityRequest {
protected $entityType = ENTITY_INVOICE; protected $entityType = ENTITY_INVOICE;
/*
public function entity() public function entity()
{ {
$expense = parent::entity(); $invoice = parent::entity();
// eager load the contacts // eager load the contacts
if ($expense && ! count($expense->documents)) { if ($invoice && ! count($invoice->invoice_items)) {
$expense->load('documents'); $invoice->load('invoice_items');
} }
return $expense; return $invoice;
} }
*/
} }

View File

@ -101,6 +101,16 @@ class EntityModel extends Eloquent
return $this->getName(); return $this->getName();
} }
public static function getClassName($entityType)
{
return 'App\\Models\\' . ucwords(Utils::toCamelCase($entityType));
}
public static function getTransformerName($entityType)
{
return 'App\\Ninja\\Transformers\\' . ucwords(Utils::toCamelCase($entityType)) . 'Transformer';
}
public function setNullValues() public function setNullValues()
{ {
foreach ($this->fillable as $field) { foreach ($this->fillable as $field) {