Updating code to PSR-2 guidelines

This commit is contained in:
Hillel Coren 2015-01-11 14:30:08 +02:00
parent 0948b46ea2
commit 310bd2bdbc
64 changed files with 3745 additions and 4219 deletions

View File

@ -1,22 +1,21 @@
<?php <?php
class ActivityController extends \BaseController { class ActivityController extends \BaseController
{
public function getDatatable($clientPublicId) public function getDatatable($clientPublicId)
{ {
$query = DB::table('activities') $query = DB::table('activities')
->join('clients', 'clients.id', '=', 'activities.client_id') ->join('clients', 'clients.id', '=', 'activities.client_id')
->where('clients.public_id', '=', $clientPublicId) ->where('clients.public_id', '=', $clientPublicId)
->where('activities.account_id', '=', Auth::user()->account_id) ->where('activities.account_id', '=', Auth::user()->account_id)
->select('activities.id', 'activities.message', 'activities.created_at', 'clients.currency_id', 'activities.balance', 'activities.adjustment'); ->select('activities.id', 'activities.message', 'activities.created_at', 'clients.currency_id', 'activities.balance', 'activities.adjustment');
return Datatable::query($query) return Datatable::query($query)
//->addColumn('blank', function($model) { return ''; }) //->addColumn('blank', function($model) { return ''; })
->addColumn('id', function($model) { return Utils::timestampToDateTimeString(strtotime($model->created_at)); }) ->addColumn('id', function ($model) { return Utils::timestampToDateTimeString(strtotime($model->created_at)); })
->addColumn('message', function($model) { return Utils::decodeActivity($model->message); }) ->addColumn('message', function ($model) { return Utils::decodeActivity($model->message); })
->addColumn('balance', function($model) { return Utils::formatMoney($model->balance, $model->currency_id); }) ->addColumn('balance', function ($model) { return Utils::formatMoney($model->balance, $model->currency_id); })
->addColumn('adjustment', function($model) { return $model->adjustment != 0 ? Utils::formatMoney($model->adjustment, $model->currency_id) : ''; }) ->addColumn('adjustment', function ($model) { return $model->adjustment != 0 ? Utils::formatMoney($model->adjustment, $model->currency_id) : ''; })
->make(); ->make();
} }
}
}

View File

@ -43,7 +43,7 @@ class AppController extends BaseController {
$database = Input::get('database'); $database = Input::get('database');
$dbType = $database['default']; $dbType = $database['default'];
$database[$dbType] = $database['type']; $database[$dbType] = $database['type'];
//unset($database['type']); unset($database['type']);
$mail = Input::get('mail'); $mail = Input::get('mail');
$email = $mail['username']; $email = $mail['username'];
@ -58,7 +58,7 @@ class AppController extends BaseController {
if ($test == 'db') if ($test == 'db')
{ {
return $valid ? 'Success' : 'Failed'; return $valid === true ? 'Success' : $valid;
} }
else if (!$valid) else if (!$valid)
{ {
@ -115,7 +115,7 @@ class AppController extends BaseController {
{ {
Config::set("database.connections.{$dbType}.{$key}", $val); Config::set("database.connections.{$dbType}.{$key}", $val);
} }
try try
{ {
$valid = DB::connection()->getDatabaseName() ? true : false; $valid = DB::connection()->getDatabaseName() ? true : false;

View File

@ -1,22 +1,21 @@
<?php <?php
class BaseController extends Controller { class BaseController extends Controller
{
/**
* Setup the layout used by the controller.
*
* @return void
*/
protected function setupLayout()
{
if (! is_null($this->layout)) {
$this->layout = View::make($this->layout);
}
}
/** public function __construct()
* Setup the layout used by the controller. {
* $this->beforeFilter('csrf', array('on' => array('post', 'delete', 'put')));
* @return void }
*/ }
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$this->layout = View::make($this->layout);
}
}
public function __construct()
{
$this->beforeFilter('csrf', array('on' => array('post', 'delete', 'put')));
}
}

View File

@ -2,56 +2,56 @@
use ninja\repositories\ClientRepository; use ninja\repositories\ClientRepository;
class ClientApiController extends Controller { class ClientApiController extends Controller
{
protected $clientRepo;
protected $clientRepo; public function __construct(ClientRepository $clientRepo)
public function __construct(ClientRepository $clientRepo)
{
$this->clientRepo = $clientRepo;
}
public function ping()
{
$headers = Utils::getApiHeaders();
return Response::make('', 200, $headers);
}
public function index()
{
if (!Utils::isPro()) {
return Redirect::to('/');
}
$clients = Client::scope()->with('contacts')->orderBy('created_at', 'desc')->get();
$clients = Utils::remapPublicIds($clients->toArray());
$response = json_encode($clients, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders(count($clients));
return Response::make($response, 200, $headers);
}
public function store()
{
if (!Utils::isPro()) {
return Redirect::to('/');
}
$data = Input::all();
$error = $this->clientRepo->getErrors($data);
if ($error)
{ {
$headers = Utils::getApiHeaders(); $this->clientRepo = $clientRepo;
return Response::make($error, 500, $headers);
}
else
{
$client = $this->clientRepo->save(false, $data, false);
$response = json_encode($client, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders();
return Response::make($response, 200, $headers);
} }
} public function ping()
{
$headers = Utils::getApiHeaders();
return Response::make('', 200, $headers);
}
public function index()
{
if (!Utils::isPro()) {
return Redirect::to('/');
}
$clients = Client::scope()->with('contacts')->orderBy('created_at', 'desc')->get();
$clients = Utils::remapPublicIds($clients->toArray());
$response = json_encode($clients, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders(count($clients));
return Response::make($response, 200, $headers);
}
public function store()
{
if (!Utils::isPro()) {
return Redirect::to('/');
}
$data = Input::all();
$error = $this->clientRepo->getErrors($data);
if ($error) {
$headers = Utils::getApiHeaders();
return Response::make($error, 500, $headers);
} else {
$client = $this->clientRepo->save(false, $data, false);
$response = json_encode($client, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders();
return Response::make($response, 200, $headers);
}
}
} }

View File

@ -2,300 +2,276 @@
use ninja\repositories\ClientRepository; use ninja\repositories\ClientRepository;
class ClientController extends \BaseController { class ClientController extends \BaseController
{
protected $clientRepo;
protected $clientRepo; public function __construct(ClientRepository $clientRepo)
{
parent::__construct();
public function __construct(ClientRepository $clientRepo) $this->clientRepo = $clientRepo;
{ }
parent::__construct();
$this->clientRepo = $clientRepo; /**
} * Display a listing of the resource.
*
* @return Response
*/
public function index()
{
return View::make('list', array(
'entityType' => ENTITY_CLIENT,
'title' => trans('texts.clients'),
'columns' => Utils::trans(['checkbox', 'client', 'contact', 'email', 'date_created', 'last_login', 'balance', 'action']),
));
}
/** public function getDatatable()
* Display a listing of the resource. {
* $clients = $this->clientRepo->find(Input::get('sSearch'));
* @return Response
*/
public function index()
{
return View::make('list', array(
'entityType'=>ENTITY_CLIENT,
'title' => trans('texts.clients'),
'columns'=>Utils::trans(['checkbox', 'client', 'contact', 'email', 'date_created', 'last_login', 'balance', 'action'])
));
}
public function getDatatable()
{
$clients = $this->clientRepo->find(Input::get('sSearch'));
return Datatable::query($clients) return Datatable::query($clients)
->addColumn('checkbox', function($model) { return '<input type="checkbox" name="ids[]" value="' . $model->public_id . '" ' . Utils::getEntityRowClass($model) . '>'; }) ->addColumn('checkbox', function ($model) { return '<input type="checkbox" name="ids[]" value="'.$model->public_id.'" '.Utils::getEntityRowClass($model).'>'; })
->addColumn('name', function($model) { return link_to('clients/' . $model->public_id, $model->name); }) ->addColumn('name', function ($model) { return link_to('clients/'.$model->public_id, $model->name); })
->addColumn('first_name', function($model) { return link_to('clients/' . $model->public_id, $model->first_name . ' ' . $model->last_name); }) ->addColumn('first_name', function ($model) { return link_to('clients/'.$model->public_id, $model->first_name.' '.$model->last_name); })
->addColumn('email', function($model) { return link_to('clients/' . $model->public_id, $model->email); }) ->addColumn('email', function ($model) { return link_to('clients/'.$model->public_id, $model->email); })
->addColumn('created_at', function($model) { return Utils::timestampToDateString(strtotime($model->created_at)); }) ->addColumn('created_at', function ($model) { return Utils::timestampToDateString(strtotime($model->created_at)); })
->addColumn('last_login', function($model) { return Utils::timestampToDateString(strtotime($model->last_login)); }) ->addColumn('last_login', function ($model) { return Utils::timestampToDateString(strtotime($model->last_login)); })
->addColumn('balance', function($model) { return Utils::formatMoney($model->balance, $model->currency_id); }) ->addColumn('balance', function ($model) { return Utils::formatMoney($model->balance, $model->currency_id); })
->addColumn('dropdown', function($model) ->addColumn('dropdown', function ($model) {
{ if ($model->is_deleted) {
if ($model->is_deleted) return '<div style="height:38px"/>';
{
return '<div style="height:38px"/>';
} }
$str = '<div class="btn-group tr-action" style="visibility:hidden;"> $str = '<div class="btn-group tr-action" style="visibility:hidden;">
<button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown"> <button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown">
'.trans('texts.select').' <span class="caret"></span> '.trans('texts.select').' <span class="caret"></span>
</button> </button>
<ul class="dropdown-menu" role="menu">'; <ul class="dropdown-menu" role="menu">';
if (!$model->deleted_at || $model->deleted_at == '0000-00-00') if (!$model->deleted_at || $model->deleted_at == '0000-00-00') {
{ $str .= '<li><a href="'.URL::to('clients/'.$model->public_id.'/edit').'">'.trans('texts.edit_client').'</a></li>
$str .= '<li><a href="' . URL::to('clients/'.$model->public_id.'/edit') . '">'.trans('texts.edit_client').'</a></li>
<li class="divider"></li> <li class="divider"></li>
<li><a href="' . URL::to('invoices/create/'.$model->public_id) . '">'.trans('texts.new_invoice').'</a></li> <li><a href="'.URL::to('invoices/create/'.$model->public_id).'">'.trans('texts.new_invoice').'</a></li>
<li><a href="' . URL::to('payments/create/'.$model->public_id) . '">'.trans('texts.new_payment').'</a></li> <li><a href="'.URL::to('payments/create/'.$model->public_id).'">'.trans('texts.new_payment').'</a></li>
<li><a href="' . URL::to('credits/create/'.$model->public_id) . '">'.trans('texts.new_credit').'</a></li> <li><a href="'.URL::to('credits/create/'.$model->public_id).'">'.trans('texts.new_credit').'</a></li>
<li class="divider"></li> <li class="divider"></li>
<li><a href="javascript:archiveEntity(' . $model->public_id. ')">'.trans('texts.archive_client').'</a></li>'; <li><a href="javascript:archiveEntity('.$model->public_id.')">'.trans('texts.archive_client').'</a></li>';
} } else {
else $str .= '<li><a href="javascript:restoreEntity('.$model->public_id.')">'.trans('texts.restore_client').'</a></li>';
{ }
$str .= '<li><a href="javascript:restoreEntity(' . $model->public_id. ')">'.trans('texts.restore_client').'</a></li>';
} return $str.'<li><a href="javascript:deleteEntity('.$model->public_id.')">'.trans('texts.delete_client').'</a></li></ul>
return $str . '<li><a href="javascript:deleteEntity(' . $model->public_id. ')">'.trans('texts.delete_client').'</a></li></ul>
</div>'; </div>';
}) })
->make(); ->make();
} }
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
return $this->save();
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($publicId)
{
$client = Client::withTrashed()->scope($publicId)->with('contacts', 'size', 'industry')->firstOrFail();
Utils::trackViewed($client->getDisplayName(), ENTITY_CLIENT);
/** $actionLinks = [
* Store a newly created resource in storage. [trans('texts.create_invoice'), URL::to('invoices/create/'.$client->public_id)],
* [trans('texts.enter_payment'), URL::to('payments/create/'.$client->public_id)],
* @return Response [trans('texts.enter_credit'), URL::to('credits/create/'.$client->public_id)],
*/
public function store()
{
return $this->save();
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($publicId)
{
$client = Client::withTrashed()->scope($publicId)->with('contacts', 'size', 'industry')->firstOrFail();
Utils::trackViewed($client->getDisplayName(), ENTITY_CLIENT);
$actionLinks = [
[trans('texts.create_invoice'), URL::to('invoices/create/' . $client->public_id )],
[trans('texts.enter_payment'), URL::to('payments/create/' . $client->public_id )],
[trans('texts.enter_credit'), URL::to('credits/create/' . $client->public_id )]
]; ];
if (Utils::isPro()) if (Utils::isPro()) {
{ array_unshift($actionLinks, [trans('texts.create_quote'), URL::to('quotes/create/'.$client->public_id)]);
array_unshift($actionLinks, [trans('texts.create_quote'), URL::to('quotes/create/' . $client->public_id )]); }
$data = array(
'actionLinks' => $actionLinks,
'showBreadcrumbs' => false,
'client' => $client,
'credit' => $client->getTotalCredit(),
'title' => trans('texts.view_client'),
'hasRecurringInvoices' => Invoice::scope()->where('is_recurring', '=', true)->whereClientId($client->id)->count() > 0,
);
return View::make('clients.show', $data);
} }
$data = array( /**
'actionLinks' => $actionLinks, * Show the form for creating a new resource.
'showBreadcrumbs' => false, *
'client' => $client, * @return Response
'credit' => $client->getTotalCredit(), */
'title' => trans('texts.view_client'), public function create()
'hasRecurringInvoices' => Invoice::scope()->where('is_recurring', '=', true)->whereClientId($client->id)->count() > 0 {
); if (Client::scope()->count() > Auth::user()->getMaxNumClients()) {
return View::make('error', ['hideHeader' => true, 'error' => "Sorry, you've exceeded the limit of ".Auth::user()->getMaxNumClients()." clients"]);
}
return View::make('clients.show', $data); $data = [
} 'client' => null,
'method' => 'POST',
'url' => 'clients',
'title' => trans('texts.new_client'),
];
/** $data = array_merge($data, self::getViewModel());
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
if (Client::scope()->count() > Auth::user()->getMaxNumClients())
{
return View::make('error', ['hideHeader' => true, 'error' => "Sorry, you've exceeded the limit of " . Auth::user()->getMaxNumClients() . " clients"]);
}
$data = [ return View::make('clients.edit', $data);
'client' => null, }
'method' => 'POST',
'url' => 'clients',
'title' => trans('texts.new_client')
];
$data = array_merge($data, self::getViewModel()); /**
return View::make('clients.edit', $data); * Show the form for editing the specified resource.
} *
* @param int $id
* @return Response
*/
public function edit($publicId)
{
$client = Client::scope($publicId)->with('contacts')->firstOrFail();
$data = [
'client' => $client,
'method' => 'PUT',
'url' => 'clients/'.$publicId,
'title' => trans('texts.edit_client'),
];
/** $data = array_merge($data, self::getViewModel());
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($publicId)
{
$client = Client::scope($publicId)->with('contacts')->firstOrFail();
$data = [
'client' => $client,
'method' => 'PUT',
'url' => 'clients/' . $publicId,
'title' => trans('texts.edit_client')
];
$data = array_merge($data, self::getViewModel()); return View::make('clients.edit', $data);
return View::make('clients.edit', $data); }
}
private static function getViewModel() private static function getViewModel()
{ {
return [ return [
'sizes' => Size::remember(DEFAULT_QUERY_CACHE)->orderBy('id')->get(), 'sizes' => Size::remember(DEFAULT_QUERY_CACHE)->orderBy('id')->get(),
'paymentTerms' => PaymentTerm::remember(DEFAULT_QUERY_CACHE)->orderBy('num_days')->get(['name', 'num_days']), 'paymentTerms' => PaymentTerm::remember(DEFAULT_QUERY_CACHE)->orderBy('num_days')->get(['name', 'num_days']),
'industries' => Industry::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(), 'industries' => Industry::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(),
'currencies' => Currency::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(), 'currencies' => Currency::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(),
'countries' => Country::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(), 'countries' => Country::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(),
'customLabel1' => Auth::user()->account->custom_client_label1, 'customLabel1' => Auth::user()->account->custom_client_label1,
'customLabel2' => Auth::user()->account->custom_client_label2, 'customLabel2' => Auth::user()->account->custom_client_label2,
]; ];
} }
/** /**
* Update the specified resource in storage. * Update the specified resource in storage.
* *
* @param int $id * @param int $id
* @return Response * @return Response
*/ */
public function update($publicId) public function update($publicId)
{ {
return $this->save($publicId); return $this->save($publicId);
} }
private function save($publicId = null) private function save($publicId = null)
{ {
$rules = array( $rules = array(
'email' => 'required' 'email' => 'required',
); );
$validator = Validator::make(Input::all(), $rules); $validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) if ($validator->fails()) {
{ $url = $publicId ? 'clients/'.$publicId.'/edit' : 'clients/create';
$url = $publicId ? 'clients/' . $publicId . '/edit' : 'clients/create';
return Redirect::to($url)
->withErrors($validator)
->withInput(Input::except('password'));
}
else
{
if ($publicId)
{
$client = Client::scope($publicId)->firstOrFail();
}
else
{
$client = Client::createNew();
}
$client->name = trim(Input::get('name')); return Redirect::to($url)
$client->id_number = trim(Input::get('id_number')); ->withErrors($validator)
$client->vat_number = trim(Input::get('vat_number')); ->withInput(Input::except('password'));
$client->work_phone = trim(Input::get('work_phone')); } else {
$client->custom_value1 = trim(Input::get('custom_value1')); if ($publicId) {
$client->custom_value2 = trim(Input::get('custom_value2')); $client = Client::scope($publicId)->firstOrFail();
$client->address1 = trim(Input::get('address1')); } else {
$client->address2 = trim(Input::get('address2')); $client = Client::createNew();
$client->city = trim(Input::get('city')); }
$client->state = trim(Input::get('state'));
$client->postal_code = trim(Input::get('postal_code'));
$client->country_id = Input::get('country_id') ? : null;
$client->private_notes = trim(Input::get('private_notes'));
$client->size_id = Input::get('size_id') ? : null;
$client->industry_id = Input::get('industry_id') ? : null;
$client->currency_id = Input::get('currency_id') ? : null;
$client->payment_terms = Input::get('payment_terms') ? : 0;
$client->website = trim(Input::get('website'));
$client->save(); $client->name = trim(Input::get('name'));
$client->id_number = trim(Input::get('id_number'));
$client->vat_number = trim(Input::get('vat_number'));
$client->work_phone = trim(Input::get('work_phone'));
$client->custom_value1 = trim(Input::get('custom_value1'));
$client->custom_value2 = trim(Input::get('custom_value2'));
$client->address1 = trim(Input::get('address1'));
$client->address2 = trim(Input::get('address2'));
$client->city = trim(Input::get('city'));
$client->state = trim(Input::get('state'));
$client->postal_code = trim(Input::get('postal_code'));
$client->country_id = Input::get('country_id') ?: null;
$client->private_notes = trim(Input::get('private_notes'));
$client->size_id = Input::get('size_id') ?: null;
$client->industry_id = Input::get('industry_id') ?: null;
$client->currency_id = Input::get('currency_id') ?: null;
$client->payment_terms = Input::get('payment_terms') ?: 0;
$client->website = trim(Input::get('website'));
$data = json_decode(Input::get('data')); $client->save();
$contactIds = [];
$isPrimary = true;
foreach ($data->contacts as $contact)
{
if (isset($contact->public_id) && $contact->public_id)
{
$record = Contact::scope($contact->public_id)->firstOrFail();
}
else
{
$record = Contact::createNew();
}
$record->email = trim(strtolower($contact->email)); $data = json_decode(Input::get('data'));
$record->first_name = trim($contact->first_name); $contactIds = [];
$record->last_name = trim($contact->last_name); $isPrimary = true;
$record->phone = trim($contact->phone);
$record->is_primary = $isPrimary;
$isPrimary = false;
$client->contacts()->save($record); foreach ($data->contacts as $contact) {
$contactIds[] = $record->public_id; if (isset($contact->public_id) && $contact->public_id) {
} $record = Contact::scope($contact->public_id)->firstOrFail();
} else {
$record = Contact::createNew();
}
foreach ($client->contacts as $contact) $record->email = trim(strtolower($contact->email));
{ $record->first_name = trim($contact->first_name);
if (!in_array($contact->public_id, $contactIds)) $record->last_name = trim($contact->last_name);
{ $record->phone = trim($contact->phone);
$contact->delete(); $record->is_primary = $isPrimary;
} $isPrimary = false;
}
if ($publicId)
{
Session::flash('message', trans('texts.updated_client'));
}
else
{
Activity::createClient($client);
Session::flash('message', trans('texts.created_client'));
}
return Redirect::to('clients/' . $client->public_id); $client->contacts()->save($record);
} $contactIds[] = $record->public_id;
} }
public function bulk() foreach ($client->contacts as $contact) {
{ if (!in_array($contact->public_id, $contactIds)) {
$action = Input::get('action'); $contact->delete();
$ids = Input::get('id') ? Input::get('id') : Input::get('ids'); }
$count = $this->clientRepo->bulk($ids, $action); }
$message = Utils::pluralize($action.'d_client', $count); if ($publicId) {
Session::flash('message', $message); Session::flash('message', trans('texts.updated_client'));
} else {
Activity::createClient($client);
Session::flash('message', trans('texts.created_client'));
}
if ($action == 'restore' && $count == 1) return Redirect::to('clients/'.$client->public_id);
{ }
return Redirect::to('clients/' . $ids[0]); }
}
else public function bulk()
{ {
return Redirect::to('clients'); $action = Input::get('action');
} $ids = Input::get('id') ? Input::get('id') : Input::get('ids');
} $count = $this->clientRepo->bulk($ids, $action);
}
$message = Utils::pluralize($action.'d_client', $count);
Session::flash('message', $message);
if ($action == 'restore' && $count == 1) {
return Redirect::to('clients/'.$ids[0]);
} else {
return Redirect::to('clients');
}
}
}

View File

@ -1,9 +1,9 @@
<?php <?php
use ninja\repositories\CreditRepository; use ninja\repositories\CreditRepository;
class CreditController extends \BaseController { class CreditController extends \BaseController
{
protected $creditRepo; protected $creditRepo;
public function __construct(CreditRepository $creditRepo) public function __construct(CreditRepository $creditRepo)
@ -11,7 +11,7 @@ class CreditController extends \BaseController {
parent::__construct(); parent::__construct();
$this->creditRepo = $creditRepo; $this->creditRepo = $creditRepo;
} }
/** /**
* Display a listing of the resource. * Display a listing of the resource.
@ -21,9 +21,9 @@ class CreditController extends \BaseController {
public function index() public function index()
{ {
return View::make('list', array( return View::make('list', array(
'entityType'=>ENTITY_CREDIT, 'entityType' => ENTITY_CREDIT,
'title' => trans('texts.credits'), 'title' => trans('texts.credits'),
'columns'=>Utils::trans(['checkbox', 'client', 'credit_amount', 'credit_balance', 'credit_date', 'private_notes', 'action']) 'columns' => Utils::trans(['checkbox', 'client', 'credit_amount', 'credit_balance', 'credit_date', 'private_notes', 'action']),
)); ));
} }
@ -31,22 +31,19 @@ class CreditController extends \BaseController {
{ {
$credits = $this->creditRepo->find($clientPublicId, Input::get('sSearch')); $credits = $this->creditRepo->find($clientPublicId, Input::get('sSearch'));
$table = Datatable::query($credits); $table = Datatable::query($credits);
if (!$clientPublicId) if (!$clientPublicId) {
{ $table->addColumn('checkbox', function ($model) { return '<input type="checkbox" name="ids[]" value="'.$model->public_id.'" '.Utils::getEntityRowClass($model).'>'; })
$table->addColumn('checkbox', function($model) { return '<input type="checkbox" name="ids[]" value="' . $model->public_id . '" ' . Utils::getEntityRowClass($model) . '>'; }) ->addColumn('client_name', function ($model) { return link_to('clients/'.$model->client_public_id, Utils::getClientDisplayName($model)); });
->addColumn('client_name', function($model) { return link_to('clients/' . $model->client_public_id, Utils::getClientDisplayName($model)); });
} }
return $table->addColumn('amount', function($model){ return Utils::formatMoney($model->amount, $model->currency_id) . '<span ' . Utils::getEntityRowClass($model) . '/>'; }) return $table->addColumn('amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id).'<span '.Utils::getEntityRowClass($model).'/>'; })
->addColumn('balance', function($model){ return Utils::formatMoney($model->balance, $model->currency_id); }) ->addColumn('balance', function ($model) { return Utils::formatMoney($model->balance, $model->currency_id); })
->addColumn('credit_date', function($model) { return Utils::fromSqlDate($model->credit_date); }) ->addColumn('credit_date', function ($model) { return Utils::fromSqlDate($model->credit_date); })
->addColumn('private_notes', function($model) { return $model->private_notes; }) ->addColumn('private_notes', function ($model) { return $model->private_notes; })
->addColumn('dropdown', function($model) ->addColumn('dropdown', function ($model) {
{ if ($model->is_deleted) {
if ($model->is_deleted)
{
return '<div style="height:38px"/>'; return '<div style="height:38px"/>';
} }
@ -56,34 +53,30 @@ class CreditController extends \BaseController {
</button> </button>
<ul class="dropdown-menu" role="menu">'; <ul class="dropdown-menu" role="menu">';
if (!$model->deleted_at || $model->deleted_at == '0000-00-00') if (!$model->deleted_at || $model->deleted_at == '0000-00-00') {
{ $str .= '<li><a href="javascript:archiveEntity('.$model->public_id.')">'.trans('texts.archive_credit').'</a></li>';
$str .= '<li><a href="javascript:archiveEntity(' . $model->public_id. ')">'.trans('texts.archive_credit').'</a></li>'; } else {
$str .= '<li><a href="javascript:restoreEntity('.$model->public_id.')">'.trans('texts.restore_credit').'</a></li>';
} }
else
{ return $str.'<li><a href="javascript:deleteEntity('.$model->public_id.')">'.trans('texts.delete_credit').'</a></li></ul>
$str .= '<li><a href="javascript:restoreEntity(' . $model->public_id. ')">'.trans('texts.restore_credit').'</a></li>';
}
return $str . '<li><a href="javascript:deleteEntity(' . $model->public_id. ')">'.trans('texts.delete_credit').'</a></li></ul>
</div>'; </div>';
}) })
->make(); ->make();
} }
public function create($clientPublicId = 0) public function create($clientPublicId = 0)
{ {
$data = array( $data = array(
'clientPublicId' => Input::old('client') ? Input::old('client') : $clientPublicId, 'clientPublicId' => Input::old('client') ? Input::old('client') : $clientPublicId,
//'invoicePublicId' => Input::old('invoice') ? Input::old('invoice') : $invoicePublicId, //'invoicePublicId' => Input::old('invoice') ? Input::old('invoice') : $invoicePublicId,
'credit' => null, 'credit' => null,
'method' => 'POST', 'method' => 'POST',
'url' => 'credits', 'url' => 'credits',
'title' => trans('texts.new_credit'), 'title' => trans('texts.new_credit'),
//'currencies' => Currency::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(), //'currencies' => Currency::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(),
//'invoices' => Invoice::scope()->with('client', 'invoice_status')->orderBy('invoice_number')->get(), //'invoices' => Invoice::scope()->with('client', 'invoice_status')->orderBy('invoice_number')->get(),
'clients' => Client::scope()->with('contacts')->orderBy('name')->get()); 'clients' => Client::scope()->with('contacts')->orderBy('name')->get(), );
return View::make('credits.edit', $data); return View::make('credits.edit', $data);
} }
@ -95,12 +88,13 @@ class CreditController extends \BaseController {
$data = array( $data = array(
'client' => null, 'client' => null,
'credit' => $credit, 'credit' => $credit,
'method' => 'PUT', 'method' => 'PUT',
'url' => 'credits/' . $publicId, 'url' => 'credits/'.$publicId,
'title' => 'Edit Credit', 'title' => 'Edit Credit',
//'currencies' => Currency::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(), //'currencies' => Currency::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(),
'clients' => Client::scope()->with('contacts')->orderBy('name')->get()); 'clients' => Client::scope()->with('contacts')->orderBy('name')->get(), );
return View::make('credit.edit', $data); return View::make('credit.edit', $data);
} }
@ -123,35 +117,33 @@ class CreditController extends \BaseController {
$validator = Validator::make(Input::all(), $rules); $validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) if ($validator->fails()) {
{ $url = $publicId ? 'credits/'.$publicId.'/edit' : 'credits/create';
$url = $publicId ? 'credits/' . $publicId . '/edit' : 'credits/create';
return Redirect::to($url) return Redirect::to($url)
->withErrors($validator) ->withErrors($validator)
->withInput(); ->withInput();
} } else {
else
{
$this->creditRepo->save($publicId, Input::all()); $this->creditRepo->save($publicId, Input::all());
$message = trans('texts.created_credit'); $message = trans('texts.created_credit');
Session::flash('message', $message); Session::flash('message', $message);
return Redirect::to('clients/' . Input::get('client'));
return Redirect::to('clients/'.Input::get('client'));
} }
} }
public function bulk() public function bulk()
{ {
$action = Input::get('action'); $action = Input::get('action');
$ids = Input::get('id') ? Input::get('id') : Input::get('ids'); $ids = Input::get('id') ? Input::get('id') : Input::get('ids');
$count = $this->creditRepo->bulk($ids, $action); $count = $this->creditRepo->bulk($ids, $action);
if ($count > 0) if ($count > 0) {
{ $message = Utils::pluralize($action.'d_credit', $count);
$message = Utils::pluralize($action.'d_credit', $count);
Session::flash('message', $message); Session::flash('message', $message);
} }
return Redirect::to('credits'); return Redirect::to('credits');
} }
} }

View File

@ -1,16 +1,16 @@
<?php <?php
class DashboardController extends \BaseController { class DashboardController extends \BaseController
{
public function index() public function index()
{ {
// total_income, billed_clients, invoice_sent and active_clients // total_income, billed_clients, invoice_sent and active_clients
$select = DB::raw('COUNT(DISTINCT CASE WHEN invoices.id IS NOT NULL THEN clients.id ELSE null END) billed_clients, $select = DB::raw('COUNT(DISTINCT CASE WHEN invoices.id IS NOT NULL THEN clients.id ELSE null END) billed_clients,
SUM(CASE WHEN invoices.invoice_status_id >= '.INVOICE_STATUS_SENT.' THEN 1 ELSE 0 END) invoices_sent, SUM(CASE WHEN invoices.invoice_status_id >= '.INVOICE_STATUS_SENT.' THEN 1 ELSE 0 END) invoices_sent,
COUNT(DISTINCT clients.id) active_clients, COUNT(DISTINCT clients.id) active_clients,
AVG(invoices.amount) as invoice_avg'); AVG(invoices.amount) as invoice_avg');
$metrics = DB::table('accounts') $metrics = DB::table('accounts')
->select($select) ->select($select)
->leftJoin('clients', 'accounts.id', '=', 'clients.account_id') ->leftJoin('clients', 'accounts.id', '=', 'clients.account_id')
->leftJoin('invoices', 'clients.id', '=', 'invoices.client_id') ->leftJoin('invoices', 'clients.id', '=', 'invoices.client_id')
@ -18,10 +18,10 @@ class DashboardController extends \BaseController {
->where('clients.is_deleted', '=', false) ->where('clients.is_deleted', '=', false)
->groupBy('accounts.id') ->groupBy('accounts.id')
->first(); ->first();
$select = DB::raw('SUM(clients.paid_to_date) as value');
$totalIncome = DB::table('accounts') $select = DB::raw('SUM(clients.paid_to_date) as value');
$totalIncome = DB::table('accounts')
->select($select) ->select($select)
->leftJoin('clients', 'accounts.id', '=', 'clients.account_id') ->leftJoin('clients', 'accounts.id', '=', 'clients.account_id')
->where('accounts.id', '=', Auth::user()->account_id) ->where('accounts.id', '=', Auth::user()->account_id)
@ -29,18 +29,18 @@ class DashboardController extends \BaseController {
->groupBy('accounts.id') ->groupBy('accounts.id')
->first(); ->first();
$activities = Activity::where('activities.account_id', '=', Auth::user()->account_id) $activities = Activity::where('activities.account_id', '=', Auth::user()->account_id)
->orderBy('created_at', 'desc')->take(6)->get(); ->orderBy('created_at', 'desc')->take(6)->get();
$pastDue = Invoice::scope() $pastDue = Invoice::scope()
->where('due_date', '<', date('Y-m-d')) ->where('due_date', '<', date('Y-m-d'))
->where('balance', '>', 0) ->where('balance', '>', 0)
->where('is_recurring', '=', false) ->where('is_recurring', '=', false)
->where('is_quote', '=', false) ->where('is_quote', '=', false)
->where('is_deleted', '=', false) ->where('is_deleted', '=', false)
->orderBy('due_date', 'asc')->take(6)->get(); ->orderBy('due_date', 'asc')->take(6)->get();
$upcoming = Invoice::scope() $upcoming = Invoice::scope()
->where('due_date', '>=', date('Y-m-d')) ->where('due_date', '>=', date('Y-m-d'))
->where('balance', '>', 0) ->where('balance', '>', 0)
->where('is_recurring', '=', false) ->where('is_recurring', '=', false)
@ -48,7 +48,7 @@ class DashboardController extends \BaseController {
->where('is_deleted', '=', false) ->where('is_deleted', '=', false)
->orderBy('due_date', 'asc')->take(6)->get(); ->orderBy('due_date', 'asc')->take(6)->get();
$data = [ $data = [
'totalIncome' => Utils::formatMoney($totalIncome ? $totalIncome->value : 0, Session::get(SESSION_CURRENCY)), 'totalIncome' => Utils::formatMoney($totalIncome ? $totalIncome->value : 0, Session::get(SESSION_CURRENCY)),
'billedClients' => $metrics ? $metrics->billed_clients : 0, 'billedClients' => $metrics ? $metrics->billed_clients : 0,
'invoicesSent' => $metrics ? $metrics->invoices_sent : 0, 'invoicesSent' => $metrics ? $metrics->invoices_sent : 0,
@ -56,10 +56,9 @@ class DashboardController extends \BaseController {
'invoiceAvg' => Utils::formatMoney(($metrics ? $metrics->invoice_avg : 0), Session::get(SESSION_CURRENCY)), 'invoiceAvg' => Utils::formatMoney(($metrics ? $metrics->invoice_avg : 0), Session::get(SESSION_CURRENCY)),
'activities' => $activities, 'activities' => $activities,
'pastDue' => $pastDue, 'pastDue' => $pastDue,
'upcoming' => $upcoming 'upcoming' => $upcoming,
]; ];
return View::make('dashboard', $data); return View::make('dashboard', $data);
} }
} }

View File

@ -2,160 +2,148 @@
use ninja\mailers\Mailer; use ninja\mailers\Mailer;
class HomeController extends BaseController { class HomeController extends BaseController
{
protected $mailer;
protected $mailer; public function __construct(Mailer $mailer)
{
parent::__construct();
public function __construct(Mailer $mailer) $this->mailer = $mailer;
{ }
parent::__construct();
$this->mailer = $mailer; public function showIndex()
} {
if (Utils::isNinja()) {
return View::make('public.splash');
} else {
if (!Utils::isDatabaseSetup()) {
return Redirect::to('/setup');
} elseif (Account::count() == 0) {
return Redirect::to('/invoice_now');
} else {
return Redirect::to('/login');
}
}
}
public function showIndex() public function showAboutUs()
{ {
if (Utils::isNinja()) $data = [
{ 'title' => 'About Us',
return View::make('public.splash'); 'description' => 'Invoice Ninja is an an open-source solution where you can create, customize, and generate invoices online for free using our templates!',
} ];
else
{
if (!Utils::isDatabaseSetup())
{
return Redirect::to('/setup');
}
else if (Account::count() == 0)
{
return Redirect::to('/invoice_now');
}
else
{
return Redirect::to('/login');
}
}
}
public function showAboutUs() return View::make('public.about_us', $data);
{ }
$data = [
'title' => 'About Us',
'description' => 'Invoice Ninja is an an open-source solution where you can create, customize, and generate invoices online for free using our templates!'
];
return View::make('public.about_us', $data); public function showContactUs()
} {
$data = [
'title' => 'Contact Us',
'description' => 'Contact us today and try out our free or premium hassle-free plans. Start your online invoicing today with Invoice Ninja!',
];
public function showContactUs() return View::make('public.contact_us', $data);
{ }
$data = [
'title' => 'Contact Us',
'description' => 'Contact us today and try out our free or premium hassle-free plans. Start your online invoicing today with Invoice Ninja!'
];
return View::make('public.contact_us', $data); public function showTerms()
} {
return View::make('public.terms');
}
public function showTerms() public function showFaq()
{ {
return View::make('public.terms'); return View::make('public.faq');
} }
public function showFaq() public function showFeatures()
{ {
return View::make('public.faq'); return View::make('public.features');
} }
public function showFeatures() public function showPlans()
{ {
return View::make('public.features'); $data = [
} 'title' => 'Professional Invoicing Software & Templates',
'description' => 'Invoice Ninja allows you to create and generate your own custom invoices. Choose from our professional invoice templates or customize your own with our pro plan.',
];
public function showPlans() return View::make('public.plans', $data);
{ }
$data = [
'title' => 'Professional Invoicing Software & Templates',
'description' => 'Invoice Ninja allows you to create and generate your own custom invoices. Choose from our professional invoice templates or customize your own with our pro plan.'
];
return View::make('public.plans', $data);
}
public function showTestimonials() public function showTestimonials()
{ {
return View::make('public.testimonials'); return View::make('public.testimonials');
} }
public function doContactUs()
{
$email = Input::get('email');
$name = Input::get('name');
$message = Input::get('message');
public function doContactUs() $data = [
{ 'text' => $message,
$email = Input::get('email'); ];
$name = Input::get('name');
$message = Input::get('message');
$data = [ $this->mailer->sendTo(CONTACT_EMAIL, $email, $name, 'Invoice Ninja Feedback', 'contact', $data);
'text' => $message
];
$this->mailer->sendTo(CONTACT_EMAIL, $email, $name, 'Invoice Ninja Feedback', 'contact', $data); $message = trans('texts.sent_message');
Session::flash('message', $message);
$message = trans('texts.sent_message'); return View::make('public.contact_us');
Session::flash('message', $message); }
return View::make('public.contact_us'); public function showComingSoon()
} {
return View::make('coming_soon');
}
public function showComingSoon() public function showSecurePayment()
{ {
return View::make('coming_soon'); return View::make('secure_payment');
} }
public function showSecurePayment() public function showCompare()
{ {
return View::make('secure_payment'); return View::make('public.compare');
} }
public function showCompare() public function invoiceNow()
{ {
return View::make('public.compare'); if (Auth::check()) {
} return Redirect::to('invoices/create');
} else {
return View::make('public.header', ['invoiceNow' => true]);
}
}
public function invoiceNow() public function newsFeed($userType, $version)
{ {
if (Auth::check()) $response = Utils::getNewsFeedResponse($userType);
{
return Redirect::to('invoices/create');
}
else
{
return View::make('public.header', ['invoiceNow' => true]);
}
}
public function newsFeed($userType, $version) return Response::json($response);
{ }
$response = Utils::getNewsFeedResponse($userType);
return Response::json($response); public function hideMessage()
} {
if (Auth::check() && Session::has('news_feed_id')) {
$newsFeedId = Session::get('news_feed_id');
if ($newsFeedId != NEW_VERSION_AVAILABLE && $newsFeedId > Auth::user()->news_feed_id) {
$user = Auth::user();
$user->news_feed_id = $newsFeedId;
$user->save();
}
public function hideMessage() Session::forget('news_feed_message');
{ }
if (Auth::check() && Session::has('news_feed_id')) {
$newsFeedId = Session::get('news_feed_id');
if ($newsFeedId != NEW_VERSION_AVAILABLE && $newsFeedId > Auth::user()->news_feed_id) {
$user = Auth::user();
$user->news_feed_id = $newsFeedId;
$user->save();
}
Session::forget('news_feed_message'); return 'success';
} }
return 'success'; public function logError()
} {
return Utils::logError(Input::get('error'), 'JavaScript');
public function logError() }
{ }
return Utils::logError(Input::get('error'), 'JavaScript');
}
}

View File

@ -1,29 +1,26 @@
<?php <?php
class IntegrationController extends Controller { class IntegrationController extends Controller
{
public function subscribe() public function subscribe()
{
$eventId = Utils::lookupEventId(trim(Input::get('event')));
if (!$eventId)
{ {
return Response::json('', 500); $eventId = Utils::lookupEventId(trim(Input::get('event')));
if (!$eventId) {
return Response::json('', 500);
}
$subscription = Subscription::where('account_id', '=', Auth::user()->account_id)->where('event_id', '=', $eventId)->first();
if (!$subscription) {
$subscription = new Subscription();
$subscription->account_id = Auth::user()->account_id;
$subscription->event_id = $eventId;
}
$subscription->target_url = trim(Input::get('target_url'));
$subscription->save();
return Response::json('{"id":'.$subscription->id.'}', 201);
} }
}
$subscription = Subscription::where('account_id', '=', Auth::user()->account_id)->where('event_id', '=', $eventId)->first();
if (!$subscription)
{
$subscription = new Subscription;
$subscription->account_id = Auth::user()->account_id;
$subscription->event_id = $eventId;
}
$subscription->target_url = trim(Input::get('target_url'));
$subscription->save();
return Response::json('{"id":'.$subscription->id.'}', 201);
}
}

View File

@ -2,30 +2,31 @@
use ninja\repositories\InvoiceRepository; use ninja\repositories\InvoiceRepository;
class InvoiceApiController extends Controller { class InvoiceApiController extends Controller
{
protected $invoiceRepo;
protected $invoiceRepo; public function __construct(InvoiceRepository $invoiceRepo)
{
public function __construct(InvoiceRepository $invoiceRepo) $this->invoiceRepo = $invoiceRepo;
{
$this->invoiceRepo = $invoiceRepo;
}
public function index()
{
if (!Utils::isPro()) {
return Redirect::to('/');
} }
$invoices = Invoice::scope()->where('invoices.is_quote', '=', false)->orderBy('created_at', 'desc')->get();
$invoices = Utils::remapPublicIds($invoices->toArray());
$response = json_encode($invoices, JSON_PRETTY_PRINT); public function index()
$headers = Utils::getApiHeaders(count($invoices)); {
return Response::make($response, 200, $headers); if (!Utils::isPro()) {
} return Redirect::to('/');
}
/* $invoices = Invoice::scope()->where('invoices.is_quote', '=', false)->orderBy('created_at', 'desc')->get();
$invoices = Utils::remapPublicIds($invoices->toArray());
$response = json_encode($invoices, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders(count($invoices));
return Response::make($response, 200, $headers);
}
/*
public function store() public function store()
{ {
$data = Input::all(); $data = Input::all();

View File

@ -5,544 +5,493 @@ use ninja\repositories\InvoiceRepository;
use ninja\repositories\ClientRepository; use ninja\repositories\ClientRepository;
use ninja\repositories\TaxRateRepository; use ninja\repositories\TaxRateRepository;
class InvoiceController extends \BaseController { class InvoiceController extends \BaseController
{
protected $mailer;
protected $invoiceRepo;
protected $clientRepo;
protected $taxRateRepo;
protected $mailer; public function __construct(Mailer $mailer, InvoiceRepository $invoiceRepo, ClientRepository $clientRepo, TaxRateRepository $taxRateRepo)
protected $invoiceRepo;
protected $clientRepo;
protected $taxRateRepo;
public function __construct(Mailer $mailer, InvoiceRepository $invoiceRepo, ClientRepository $clientRepo, TaxRateRepository $taxRateRepo)
{
parent::__construct();
$this->mailer = $mailer;
$this->invoiceRepo = $invoiceRepo;
$this->clientRepo = $clientRepo;
$this->taxRateRepo = $taxRateRepo;
}
public function index()
{
$data = [
'title' => trans('texts.invoices'),
'entityType'=>ENTITY_INVOICE,
'columns'=>Utils::trans(['checkbox', 'invoice_number', 'client', 'invoice_date', 'invoice_total', 'balance_due', 'due_date', 'status', 'action'])
];
$recurringInvoices = Invoice::scope()->where('is_recurring', '=', true);
if (Session::get('show_trash:invoice'))
{ {
$recurringInvoices->withTrashed(); parent::__construct();
$this->mailer = $mailer;
$this->invoiceRepo = $invoiceRepo;
$this->clientRepo = $clientRepo;
$this->taxRateRepo = $taxRateRepo;
} }
if ($recurringInvoices->count() > 0) public function index()
{
$data['secEntityType'] = ENTITY_RECURRING_INVOICE;
$data['secColumns'] = Utils::trans(['checkbox', 'frequency', 'client', 'start_date', 'end_date', 'invoice_total', 'action']);
}
return View::make('list', $data);
}
public function clientIndex()
{
$data = [
'showClientHeader' => true,
'hideLogo' => Session::get('white_label'),
'title' => trans('texts.invoices'),
'entityType'=>ENTITY_INVOICE,
'columns'=>Utils::trans(['invoice_number', 'invoice_date', 'invoice_total', 'balance_due', 'due_date'])
];
return View::make('public_list', $data);
}
public function getDatatable($clientPublicId = null)
{
$accountId = Auth::user()->account_id;
$search = Input::get('sSearch');
return $this->invoiceRepo->getDatatable($accountId, $clientPublicId, ENTITY_INVOICE, $search);
}
public function getClientDatatable()
{
//$accountId = Auth::user()->account_id;
$search = Input::get('sSearch');
$invitationKey = Session::get('invitation_key');
$invitation = Invitation::where('invitation_key', '=', $invitationKey)->first();
if (!$invitation || $invitation->is_deleted)
{
return [];
}
$invoice = $invitation->invoice;
if (!$invoice || $invoice->is_deleted)
{
return [];
}
return $this->invoiceRepo->getClientDatatable($invitation->contact_id, ENTITY_INVOICE, $search);
}
public function getRecurringDatatable($clientPublicId = null)
{ {
$query = $this->invoiceRepo->getRecurringInvoices(Auth::user()->account_id, $clientPublicId, Input::get('sSearch')); $data = [
$table = Datatable::query($query); 'title' => trans('texts.invoices'),
'entityType' => ENTITY_INVOICE,
'columns' => Utils::trans(['checkbox', 'invoice_number', 'client', 'invoice_date', 'invoice_total', 'balance_due', 'due_date', 'status', 'action']),
];
if (!$clientPublicId) { $recurringInvoices = Invoice::scope()->where('is_recurring', '=', true);
$table->addColumn('checkbox', function($model) { return '<input type="checkbox" name="ids[]" value="' . $model->public_id . '" '. Utils::getEntityRowClass($model) . '>'; });
}
$table->addColumn('frequency', function($model) { return link_to('invoices/' . $model->public_id, $model->frequency); });
if (!$clientPublicId) { if (Session::get('show_trash:invoice')) {
$table->addColumn('client_name', function($model) { return link_to('clients/' . $model->client_public_id, Utils::getClientDisplayName($model)); }); $recurringInvoices->withTrashed();
} }
return $table->addColumn('start_date', function($model) { return Utils::fromSqlDate($model->start_date); }) if ($recurringInvoices->count() > 0) {
->addColumn('end_date', function($model) { return Utils::fromSqlDate($model->end_date); }) $data['secEntityType'] = ENTITY_RECURRING_INVOICE;
->addColumn('amount', function($model) { return Utils::formatMoney($model->amount, $model->currency_id); }) $data['secColumns'] = Utils::trans(['checkbox', 'frequency', 'client', 'start_date', 'end_date', 'invoice_total', 'action']);
->addColumn('dropdown', function($model) }
{
if ($model->is_deleted) return View::make('list', $data);
{ }
public function clientIndex()
{
$data = [
'showClientHeader' => true,
'hideLogo' => Session::get('white_label'),
'title' => trans('texts.invoices'),
'entityType' => ENTITY_INVOICE,
'columns' => Utils::trans(['invoice_number', 'invoice_date', 'invoice_total', 'balance_due', 'due_date']),
];
return View::make('public_list', $data);
}
public function getDatatable($clientPublicId = null)
{
$accountId = Auth::user()->account_id;
$search = Input::get('sSearch');
return $this->invoiceRepo->getDatatable($accountId, $clientPublicId, ENTITY_INVOICE, $search);
}
public function getClientDatatable()
{
//$accountId = Auth::user()->account_id;
$search = Input::get('sSearch');
$invitationKey = Session::get('invitation_key');
$invitation = Invitation::where('invitation_key', '=', $invitationKey)->first();
if (!$invitation || $invitation->is_deleted) {
return [];
}
$invoice = $invitation->invoice;
if (!$invoice || $invoice->is_deleted) {
return [];
}
return $this->invoiceRepo->getClientDatatable($invitation->contact_id, ENTITY_INVOICE, $search);
}
public function getRecurringDatatable($clientPublicId = null)
{
$query = $this->invoiceRepo->getRecurringInvoices(Auth::user()->account_id, $clientPublicId, Input::get('sSearch'));
$table = Datatable::query($query);
if (!$clientPublicId) {
$table->addColumn('checkbox', function ($model) { return '<input type="checkbox" name="ids[]" value="'.$model->public_id.'" '.Utils::getEntityRowClass($model).'>'; });
}
$table->addColumn('frequency', function ($model) { return link_to('invoices/'.$model->public_id, $model->frequency); });
if (!$clientPublicId) {
$table->addColumn('client_name', function ($model) { return link_to('clients/'.$model->client_public_id, Utils::getClientDisplayName($model)); });
}
return $table->addColumn('start_date', function ($model) { return Utils::fromSqlDate($model->start_date); })
->addColumn('end_date', function ($model) { return Utils::fromSqlDate($model->end_date); })
->addColumn('amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id); })
->addColumn('dropdown', function ($model) {
if ($model->is_deleted) {
return '<div style="height:38px"/>'; return '<div style="height:38px"/>';
} }
$str = '<div class="btn-group tr-action" style="visibility:hidden;"> $str = '<div class="btn-group tr-action" style="visibility:hidden;">
<button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown"> <button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown">
'.trans('texts.select').' <span class="caret"></span> '.trans('texts.select').' <span class="caret"></span>
</button> </button>
<ul class="dropdown-menu" role="menu">'; <ul class="dropdown-menu" role="menu">';
if (!$model->deleted_at || $model->deleted_at == '0000-00-00') if (!$model->deleted_at || $model->deleted_at == '0000-00-00') {
{ $str .= '<li><a href="'.URL::to('invoices/'.$model->public_id.'/edit').'">'.trans('texts.edit_invoice').'</a></li>
$str .= '<li><a href="' . URL::to('invoices/'.$model->public_id.'/edit') . '">'.trans('texts.edit_invoice').'</a></li>
<li class="divider"></li> <li class="divider"></li>
<li><a href="javascript:archiveEntity(' . $model->public_id . ')">'.trans('texts.archive_invoice').'</a></li> <li><a href="javascript:archiveEntity('.$model->public_id.')">'.trans('texts.archive_invoice').'</a></li>
<li><a href="javascript:deleteEntity(' . $model->public_id . ')">'.trans('texts.delete_invoice').'</a></li>'; <li><a href="javascript:deleteEntity('.$model->public_id.')">'.trans('texts.delete_invoice').'</a></li>';
} else {
$str .= '<li><a href="javascript:restoreEntity('.$model->public_id.')">'.trans('texts.restore_invoice').'</a></li>';
} }
else
{ return $str.'</ul>
$str .= '<li><a href="javascript:restoreEntity(' . $model->public_id. ')">'.trans('texts.restore_invoice').'</a></li>';
}
return $str . '</ul>
</div>'; </div>';
})
->make();
})
->make();
} }
public function view($invitationKey)
{
$invitation = Invitation::where('invitation_key', '=', $invitationKey)->firstOrFail();
public function view($invitationKey) $invoice = $invitation->invoice;
{
$invitation = Invitation::where('invitation_key', '=', $invitationKey)->firstOrFail();
$invoice = $invitation->invoice; if (!$invoice || $invoice->is_deleted) {
return View::make('invoices.deleted');
if (!$invoice || $invoice->is_deleted) }
{
return View::make('invoices.deleted');
}
if ($invoice->is_quote && $invoice->quote_invoice_id) if ($invoice->is_quote && $invoice->quote_invoice_id) {
{ $invoice = Invoice::scope($invoice->quote_invoice_id, $invoice->account_id)->firstOrFail();
$invoice = Invoice::scope($invoice->quote_invoice_id, $invoice->account_id)->firstOrFail();
if (!$invoice || $invoice->is_deleted) if (!$invoice || $invoice->is_deleted) {
{ return View::make('invoices.deleted');
return View::make('invoices.deleted'); }
} }
}
$invoice->load('user', 'invoice_items', 'invoice_design', 'account.country', 'client.contacts', 'client.country'); $invoice->load('user', 'invoice_items', 'invoice_design', 'account.country', 'client.contacts', 'client.country');
$client = $invoice->client; $client = $invoice->client;
if (!$client || $client->is_deleted)
{
return View::make('invoices.deleted');
}
if (!Session::has($invitationKey) && (!Auth::check() || Auth::user()->account_id != $invoice->account_id)) if (!$client || $client->is_deleted) {
{ return View::make('invoices.deleted');
Activity::viewInvoice($invitation); }
Event::fire('invoice.viewed', $invoice);
}
Session::set($invitationKey, true); if (!Session::has($invitationKey) && (!Auth::check() || Auth::user()->account_id != $invoice->account_id)) {
Session::set('invitation_key', $invitationKey); Activity::viewInvoice($invitation);
Session::set('white_label', $client->account->isWhiteLabel()); Event::fire('invoice.viewed', $invoice);
}
$client->account->loadLocalizationSettings(); Session::set($invitationKey, true);
Session::set('invitation_key', $invitationKey);
Session::set('white_label', $client->account->isWhiteLabel());
$invoice->invoice_date = Utils::fromSqlDate($invoice->invoice_date); $client->account->loadLocalizationSettings();
$invoice->due_date = Utils::fromSqlDate($invoice->due_date);
$invoice->is_pro = $client->account->isPro();
$contact = $invitation->contact; $invoice->invoice_date = Utils::fromSqlDate($invoice->invoice_date);
$contact->setVisible([ $invoice->due_date = Utils::fromSqlDate($invoice->due_date);
'first_name', $invoice->is_pro = $client->account->isPro();
'last_name',
'email',
'phone']);
$data = array( $contact = $invitation->contact;
'showClientHeader' => true, $contact->setVisible([
'showBreadcrumbs' => false, 'first_name',
'hideLogo' => $client->account->isWhiteLabel(), 'last_name',
'invoice' => $invoice->hidePrivateFields(), 'email',
'invitation' => $invitation, 'phone', ]);
'invoiceLabels' => $client->account->getInvoiceLabels(),
'contact' => $contact
);
return View::make('invoices.view', $data); $data = array(
} 'showClientHeader' => true,
'showBreadcrumbs' => false,
'hideLogo' => $client->account->isWhiteLabel(),
'invoice' => $invoice->hidePrivateFields(),
'invitation' => $invitation,
'invoiceLabels' => $client->account->getInvoiceLabels(),
'contact' => $contact,
);
public function edit($publicId, $clone = false) return View::make('invoices.view', $data);
{
$invoice = Invoice::scope($publicId)->withTrashed()->with('invitations', 'account.country', 'client.contacts', 'client.country', 'invoice_items')->firstOrFail();
$entityType = $invoice->getEntityType();
$contactIds = DB::table('invitations')
->join('contacts', 'contacts.id', '=','invitations.contact_id')
->where('invitations.invoice_id', '=', $invoice->id)
->where('invitations.account_id', '=', Auth::user()->account_id)
->where('invitations.deleted_at', '=', null)
->select('contacts.public_id')->lists('public_id');
if ($clone)
{
$invoice->id = null;
$invoice->invoice_number = Auth::user()->account->getNextInvoiceNumber($invoice->is_quote);
$invoice->balance = $invoice->amount;
$invoice->invoice_status_id = 0;
$invoice->invoice_date = date_create()->format('Y-m-d');
$method = 'POST';
$url = "{$entityType}s";
}
else
{
Utils::trackViewed($invoice->invoice_number . ' - ' . $invoice->client->getDisplayName(), $invoice->getEntityType());
$method = 'PUT';
$url = "{$entityType}s/{$publicId}";
}
$invoice->invoice_date = Utils::fromSqlDate($invoice->invoice_date);
$invoice->due_date = Utils::fromSqlDate($invoice->due_date);
$invoice->start_date = Utils::fromSqlDate($invoice->start_date);
$invoice->end_date = Utils::fromSqlDate($invoice->end_date);
$invoice->is_pro = Auth::user()->isPro();
$data = array(
'entityType' => $entityType,
'showBreadcrumbs' => $clone,
'account' => $invoice->account,
'invoice' => $invoice,
'data' => false,
'method' => $method,
'invitationContactIds' => $contactIds,
'url' => $url,
'title' => trans("texts.edit_{$entityType}"),
'client' => $invoice->client);
$data = array_merge($data, self::getViewModel());
// Set the invitation link on the client's contacts
if (!$clone)
{
$clients = $data['clients'];
foreach ($clients as $client)
{
if ($client->id == $invoice->client->id)
{
foreach ($invoice->invitations as $invitation)
{
foreach ($client->contacts as $contact)
{
if ($invitation->contact_id == $contact->id)
{
$contact->invitation_link = $invitation->getLink();
}
}
}
break;
}
}
}
return View::make('invoices.edit', $data);
}
public function create($clientPublicId = 0)
{
$client = null;
$invoiceNumber = Auth::user()->account->getNextInvoiceNumber();
$account = Account::with('country')->findOrFail(Auth::user()->account_id);
if ($clientPublicId)
{
$client = Client::scope($clientPublicId)->firstOrFail();
} }
$data = array( public function edit($publicId, $clone = false)
'entityType' => ENTITY_INVOICE, {
'account' => $account, $invoice = Invoice::scope($publicId)->withTrashed()->with('invitations', 'account.country', 'client.contacts', 'client.country', 'invoice_items')->firstOrFail();
'invoice' => null, $entityType = $invoice->getEntityType();
'data' => Input::old('data'),
'invoiceNumber' => $invoiceNumber,
'method' => 'POST',
'url' => 'invoices',
'title' => trans('texts.new_invoice'),
'client' => $client);
$data = array_merge($data, self::getViewModel());
return View::make('invoices.edit', $data); $contactIds = DB::table('invitations')
} ->join('contacts', 'contacts.id', '=', 'invitations.contact_id')
->where('invitations.invoice_id', '=', $invoice->id)
->where('invitations.account_id', '=', Auth::user()->account_id)
->where('invitations.deleted_at', '=', null)
->select('contacts.public_id')->lists('public_id');
private static function getViewModel() if ($clone) {
{ $invoice->id = null;
$recurringHelp = ''; $invoice->invoice_number = Auth::user()->account->getNextInvoiceNumber($invoice->is_quote);
foreach(preg_split("/((\r?\n)|(\r\n?))/", trans('texts.recurring_help')) as $line){ $invoice->balance = $invoice->amount;
$parts = explode("=>", $line); $invoice->invoice_status_id = 0;
if (count($parts) > 1) { $invoice->invoice_date = date_create()->format('Y-m-d');
$line = $parts[0] . ' => ' . Utils::processVariables($parts[0]); $method = 'POST';
$recurringHelp .= '<li>' . strip_tags($line) . '</li>'; $url = "{$entityType}s";
} else { } else {
$recurringHelp .= $line; Utils::trackViewed($invoice->invoice_number.' - '.$invoice->client->getDisplayName(), $invoice->getEntityType());
} $method = 'PUT';
} $url = "{$entityType}s/{$publicId}";
}
return [ $invoice->invoice_date = Utils::fromSqlDate($invoice->invoice_date);
'account' => Auth::user()->account, $invoice->due_date = Utils::fromSqlDate($invoice->due_date);
'products' => Product::scope()->orderBy('id')->get(array('product_key','notes','cost','qty')), $invoice->start_date = Utils::fromSqlDate($invoice->start_date);
'countries' => Country::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(), $invoice->end_date = Utils::fromSqlDate($invoice->end_date);
'clients' => Client::scope()->with('contacts', 'country')->orderBy('name')->get(), $invoice->is_pro = Auth::user()->isPro();
'taxRates' => TaxRate::scope()->orderBy('name')->get(),
'currencies' => Currency::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(), $data = array(
'sizes' => Size::remember(DEFAULT_QUERY_CACHE)->orderBy('id')->get(), 'entityType' => $entityType,
'paymentTerms' => PaymentTerm::remember(DEFAULT_QUERY_CACHE)->orderBy('num_days')->get(['name', 'num_days']), 'showBreadcrumbs' => $clone,
'industries' => Industry::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(), 'account' => $invoice->account,
'invoice' => $invoice,
'data' => false,
'method' => $method,
'invitationContactIds' => $contactIds,
'url' => $url,
'title' => trans("texts.edit_{$entityType}"),
'client' => $invoice->client, );
$data = array_merge($data, self::getViewModel());
// Set the invitation link on the client's contacts
if (!$clone) {
$clients = $data['clients'];
foreach ($clients as $client) {
if ($client->id == $invoice->client->id) {
foreach ($invoice->invitations as $invitation) {
foreach ($client->contacts as $contact) {
if ($invitation->contact_id == $contact->id) {
$contact->invitation_link = $invitation->getLink();
}
}
}
break;
}
}
}
return View::make('invoices.edit', $data);
}
public function create($clientPublicId = 0)
{
$client = null;
$invoiceNumber = Auth::user()->account->getNextInvoiceNumber();
$account = Account::with('country')->findOrFail(Auth::user()->account_id);
if ($clientPublicId) {
$client = Client::scope($clientPublicId)->firstOrFail();
}
$data = array(
'entityType' => ENTITY_INVOICE,
'account' => $account,
'invoice' => null,
'data' => Input::old('data'),
'invoiceNumber' => $invoiceNumber,
'method' => 'POST',
'url' => 'invoices',
'title' => trans('texts.new_invoice'),
'client' => $client, );
$data = array_merge($data, self::getViewModel());
return View::make('invoices.edit', $data);
}
private static function getViewModel()
{
$recurringHelp = '';
foreach (preg_split("/((\r?\n)|(\r\n?))/", trans('texts.recurring_help')) as $line) {
$parts = explode("=>", $line);
if (count($parts) > 1) {
$line = $parts[0].' => '.Utils::processVariables($parts[0]);
$recurringHelp .= '<li>'.strip_tags($line).'</li>';
} else {
$recurringHelp .= $line;
}
}
return [
'account' => Auth::user()->account,
'products' => Product::scope()->orderBy('id')->get(array('product_key', 'notes', 'cost', 'qty')),
'countries' => Country::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(),
'clients' => Client::scope()->with('contacts', 'country')->orderBy('name')->get(),
'taxRates' => TaxRate::scope()->orderBy('name')->get(),
'currencies' => Currency::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(),
'sizes' => Size::remember(DEFAULT_QUERY_CACHE)->orderBy('id')->get(),
'paymentTerms' => PaymentTerm::remember(DEFAULT_QUERY_CACHE)->orderBy('num_days')->get(['name', 'num_days']),
'industries' => Industry::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(),
'invoiceDesigns' => InvoiceDesign::remember(DEFAULT_QUERY_CACHE, 'invoice_designs_cache_'.Auth::user()->maxInvoiceDesignId()) 'invoiceDesigns' => InvoiceDesign::remember(DEFAULT_QUERY_CACHE, 'invoice_designs_cache_'.Auth::user()->maxInvoiceDesignId())
->where('id', '<=', Auth::user()->maxInvoiceDesignId())->orderBy('id')->get(), ->where('id', '<=', Auth::user()->maxInvoiceDesignId())->orderBy('id')->get(),
'frequencies' => array( 'frequencies' => array(
1 => 'Weekly', 1 => 'Weekly',
2 => 'Two weeks', 2 => 'Two weeks',
3 => 'Four weeks', 3 => 'Four weeks',
4 => 'Monthly', 4 => 'Monthly',
5 => 'Three months', 5 => 'Three months',
6 => 'Six months', 6 => 'Six months',
7 => 'Annually' 7 => 'Annually',
), ),
'recurringHelp' => $recurringHelp 'recurringHelp' => $recurringHelp
]; ];
} }
/** /**
* Store a newly created resource in storage. * Store a newly created resource in storage.
* *
* @return Response * @return Response
*/ */
public function store() public function store()
{ {
return InvoiceController::save(); return InvoiceController::save();
} }
private function save($publicId = null) private function save($publicId = null)
{ {
$action = Input::get('action'); $action = Input::get('action');
$entityType = Input::get('entityType'); $entityType = Input::get('entityType');
if (in_array($action, ['archive', 'delete', 'mark', 'restore'])) if (in_array($action, ['archive', 'delete', 'mark', 'restore'])) {
{ return InvoiceController::bulk($entityType);
return InvoiceController::bulk($entityType); }
}
$input = json_decode(Input::get('data')); $input = json_decode(Input::get('data'));
$invoice = $input->invoice; $invoice = $input->invoice;
if ($errors = $this->invoiceRepo->getErrors($invoice)) if ($errors = $this->invoiceRepo->getErrors($invoice)) {
{ Session::flash('error', trans('texts.invoice_error'));
Session::flash('error', trans('texts.invoice_error'));
return Redirect::to("{$entityType}s/create") return Redirect::to("{$entityType}s/create")
->withInput()->withErrors($errors); ->withInput()->withErrors($errors);
} } else {
else $this->taxRateRepo->save($input->tax_rates);
{
$this->taxRateRepo->save($input->tax_rates);
$clientData = (array) $invoice->client;
$client = $this->clientRepo->save($invoice->client->public_id, $clientData);
$invoiceData = (array) $invoice;
$invoiceData['client_id'] = $client->id;
$invoice = $this->invoiceRepo->save($publicId, $invoiceData, $entityType);
$account = Auth::user()->account;
if ($account->invoice_taxes != $input->invoice_taxes
|| $account->invoice_item_taxes != $input->invoice_item_taxes
|| $account->invoice_design_id != $input->invoice->invoice_design_id)
{
$account->invoice_taxes = $input->invoice_taxes;
$account->invoice_item_taxes = $input->invoice_item_taxes;
$account->invoice_design_id = $input->invoice->invoice_design_id;
$account->save();
}
$client->load('contacts'); $clientData = (array) $invoice->client;
$sendInvoiceIds = []; $client = $this->clientRepo->save($invoice->client->public_id, $clientData);
foreach ($client->contacts as $contact) $invoiceData = (array) $invoice;
{ $invoiceData['client_id'] = $client->id;
if ($contact->send_invoice || count($client->contacts) == 1) $invoice = $this->invoiceRepo->save($publicId, $invoiceData, $entityType);
{
$sendInvoiceIds[] = $contact->id;
}
}
foreach ($client->contacts as $contact)
{
$invitation = Invitation::scope()->whereContactId($contact->id)->whereInvoiceId($invoice->id)->first();
if (in_array($contact->id, $sendInvoiceIds) && !$invitation)
{
$invitation = Invitation::createNew();
$invitation->invoice_id = $invoice->id;
$invitation->contact_id = $contact->id;
$invitation->invitation_key = str_random(RANDOM_KEY_LENGTH);
$invitation->save();
}
else if (!in_array($contact->id, $sendInvoiceIds) && $invitation)
{
$invitation->delete();
}
}
$message = trans($publicId ? "texts.updated_{$entityType}" : "texts.created_{$entityType}"); $account = Auth::user()->account;
if ($input->invoice->client->public_id == '-1') if ($account->invoice_taxes != $input->invoice_taxes
{ || $account->invoice_item_taxes != $input->invoice_item_taxes
$message = $message . ' ' . trans('texts.and_created_client'); || $account->invoice_design_id != $input->invoice->invoice_design_id) {
$account->invoice_taxes = $input->invoice_taxes;
$account->invoice_item_taxes = $input->invoice_item_taxes;
$account->invoice_design_id = $input->invoice->invoice_design_id;
$account->save();
}
$url = URL::to('clients/' . $client->public_id); $client->load('contacts');
Utils::trackViewed($client->getDisplayName(), ENTITY_CLIENT, $url); $sendInvoiceIds = [];
}
if ($action == 'clone')
{
return $this->cloneInvoice($publicId);
}
else if ($action == 'convert')
{
return $this->convertQuote($publicId);
}
else if ($action == 'email')
{
if (Auth::user()->confirmed && !Auth::user()->isDemo())
{
$message = trans("texts.emailed_{$entityType}");
$this->mailer->sendInvoice($invoice);
Session::flash('message', $message);
}
else
{
$errorMessage = trans(Auth::user()->registered ? 'texts.confirmation_required' : 'texts.registration_required');
Session::flash('error', $errorMessage);
Session::flash('message', $message);
}
}
else
{
Session::flash('message', $message);
}
$url = "{$entityType}s/" . $invoice->public_id . '/edit'; foreach ($client->contacts as $contact) {
return Redirect::to($url); if ($contact->send_invoice || count($client->contacts) == 1) {
} $sendInvoiceIds[] = $contact->id;
} }
}
/** foreach ($client->contacts as $contact) {
* Display the specified resource. $invitation = Invitation::scope()->whereContactId($contact->id)->whereInvoiceId($invoice->id)->first();
*
* @param int $id
* @return Response
*/
public function show($publicId)
{
Session::reflash();
return Redirect::to('invoices/'.$publicId.'/edit');
}
/** if (in_array($contact->id, $sendInvoiceIds) && !$invitation) {
* Update the specified resource in storage. $invitation = Invitation::createNew();
* $invitation->invoice_id = $invoice->id;
* @param int $id $invitation->contact_id = $contact->id;
* @return Response $invitation->invitation_key = str_random(RANDOM_KEY_LENGTH);
*/ $invitation->save();
public function update($publicId) } elseif (!in_array($contact->id, $sendInvoiceIds) && $invitation) {
{ $invitation->delete();
return InvoiceController::save($publicId); }
} }
/** $message = trans($publicId ? "texts.updated_{$entityType}" : "texts.created_{$entityType}");
* Remove the specified resource from storage. if ($input->invoice->client->public_id == '-1') {
* $message = $message.' '.trans('texts.and_created_client');
* @param int $id
* @return Response
*/
public function bulk($entityType = ENTITY_INVOICE)
{
$action = Input::get('action');
$statusId = Input::get('statusId', INVOICE_STATUS_SENT);
$ids = Input::get('id') ? Input::get('id') : Input::get('ids');
$count = $this->invoiceRepo->bulk($ids, $action, $statusId);
if ($count > 0) $url = URL::to('clients/'.$client->public_id);
{ Utils::trackViewed($client->getDisplayName(), ENTITY_CLIENT, $url);
$key = $action == 'mark' ? "updated_{$entityType}" : "{$action}d_{$entityType}"; }
$message = Utils::pluralize($key, $count);
Session::flash('message', $message);
}
if ($action == 'restore' && $count == 1) if ($action == 'clone') {
{ return $this->cloneInvoice($publicId);
return Redirect::to("{$entityType}s/" . $ids[0]); } elseif ($action == 'convert') {
} return $this->convertQuote($publicId);
else } elseif ($action == 'email') {
{ if (Auth::user()->confirmed && !Auth::user()->isDemo()) {
return Redirect::to("{$entityType}s"); $message = trans("texts.emailed_{$entityType}");
} $this->mailer->sendInvoice($invoice);
} Session::flash('message', $message);
} else {
$errorMessage = trans(Auth::user()->registered ? 'texts.confirmation_required' : 'texts.registration_required');
Session::flash('error', $errorMessage);
Session::flash('message', $message);
}
} else {
Session::flash('message', $message);
}
public function convertQuote($publicId) $url = "{$entityType}s/".$invoice->public_id.'/edit';
{
$invoice = Invoice::with('invoice_items')->scope($publicId)->firstOrFail();
$clone = $this->invoiceRepo->cloneInvoice($invoice, $invoice->id);
Session::flash('message', trans('texts.converted_to_invoice')); return Redirect::to($url);
return Redirect::to('invoices/' . $clone->public_id); }
} }
public function cloneInvoice($publicId) /**
{ * Display the specified resource.
/* *
$invoice = Invoice::with('invoice_items')->scope($publicId)->firstOrFail(); * @param int $id
$clone = $this->invoiceRepo->cloneInvoice($invoice); * @return Response
$entityType = $invoice->getEntityType(); */
public function show($publicId)
{
Session::reflash();
Session::flash('message', trans('texts.cloned_invoice')); return Redirect::to('invoices/'.$publicId.'/edit');
return Redirect::to("{$entityType}s/" . $clone->public_id); }
*/
return self::edit($publicId, true); /**
} * Update the specified resource in storage.
} *
* @param int $id
* @return Response
*/
public function update($publicId)
{
return InvoiceController::save($publicId);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function bulk($entityType = ENTITY_INVOICE)
{
$action = Input::get('action');
$statusId = Input::get('statusId', INVOICE_STATUS_SENT);
$ids = Input::get('id') ? Input::get('id') : Input::get('ids');
$count = $this->invoiceRepo->bulk($ids, $action, $statusId);
if ($count > 0) {
$key = $action == 'mark' ? "updated_{$entityType}" : "{$action}d_{$entityType}";
$message = Utils::pluralize($key, $count);
Session::flash('message', $message);
}
if ($action == 'restore' && $count == 1) {
return Redirect::to("{$entityType}s/".$ids[0]);
} else {
return Redirect::to("{$entityType}s");
}
}
public function convertQuote($publicId)
{
$invoice = Invoice::with('invoice_items')->scope($publicId)->firstOrFail();
$clone = $this->invoiceRepo->cloneInvoice($invoice, $invoice->id);
Session::flash('message', trans('texts.converted_to_invoice'));
return Redirect::to('invoices/'.$clone->public_id);
}
public function cloneInvoice($publicId)
{
/*
$invoice = Invoice::with('invoice_items')->scope($publicId)->firstOrFail();
$clone = $this->invoiceRepo->cloneInvoice($invoice);
$entityType = $invoice->getEntityType();
Session::flash('message', trans('texts.cloned_invoice'));
return Redirect::to("{$entityType}s/" . $clone->public_id);
*/
return self::edit($publicId, true);
}
}

View File

@ -2,30 +2,31 @@
use ninja\repositories\PaymentRepository; use ninja\repositories\PaymentRepository;
class PaymentApiController extends Controller { class PaymentApiController extends Controller
{
protected $paymentRepo;
protected $paymentRepo; public function __construct(PaymentRepository $paymentRepo)
{
public function __construct(PaymentRepository $paymentRepo) $this->paymentRepo = $paymentRepo;
{
$this->paymentRepo = $paymentRepo;
}
public function index()
{
if (!Utils::isPro()) {
return Redirect::to('/');
} }
$payments = Payment::scope()->orderBy('created_at', 'desc')->get();
$payments = Utils::remapPublicIds($payments->toArray());
$response = json_encode($payments, JSON_PRETTY_PRINT); public function index()
$headers = Utils::getApiHeaders(count($payments)); {
return Response::make($response, 200, $headers); if (!Utils::isPro()) {
} return Redirect::to('/');
}
/* $payments = Payment::scope()->orderBy('created_at', 'desc')->get();
$payments = Utils::remapPublicIds($payments->toArray());
$response = json_encode($payments, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders(count($payments));
return Response::make($response, 200, $headers);
}
/*
public function store() public function store()
{ {
$data = Input::all(); $data = Input::all();

View File

@ -5,7 +5,7 @@ use ninja\repositories\InvoiceRepository;
use ninja\repositories\AccountRepository; use ninja\repositories\AccountRepository;
use ninja\mailers\ContactMailer; use ninja\mailers\ContactMailer;
class PaymentController extends \BaseController class PaymentController extends \BaseController
{ {
protected $creditRepo; protected $creditRepo;
@ -17,14 +17,14 @@ class PaymentController extends \BaseController
$this->invoiceRepo = $invoiceRepo; $this->invoiceRepo = $invoiceRepo;
$this->accountRepo = $accountRepo; $this->accountRepo = $accountRepo;
$this->contactMailer = $contactMailer; $this->contactMailer = $contactMailer;
} }
public function index() public function index()
{ {
return View::make('list', array( return View::make('list', array(
'entityType'=>ENTITY_PAYMENT, 'entityType' => ENTITY_PAYMENT,
'title' => trans('texts.payments'), 'title' => trans('texts.payments'),
'columns'=>Utils::trans(['checkbox', 'invoice', 'client', 'transaction_reference', 'method', 'payment_amount', 'payment_date', 'action']) 'columns' => Utils::trans(['checkbox', 'invoice', 'client', 'transaction_reference', 'method', 'payment_amount', 'payment_date', 'action']),
)); ));
} }
@ -33,57 +33,52 @@ class PaymentController extends \BaseController
return View::make('public_list', array( return View::make('public_list', array(
'showClientHeader' => true, 'showClientHeader' => true,
'hideLogo' => Session::get('white_label'), 'hideLogo' => Session::get('white_label'),
'entityType'=>ENTITY_PAYMENT, 'entityType' => ENTITY_PAYMENT,
'title' => trans('texts.payments'), 'title' => trans('texts.payments'),
'columns'=>Utils::trans(['invoice', 'transaction_reference', 'method', 'payment_amount', 'payment_date']) 'columns' => Utils::trans(['invoice', 'transaction_reference', 'method', 'payment_amount', 'payment_date']),
)); ));
} }
public function getDatatable($clientPublicId = null) public function getDatatable($clientPublicId = null)
{ {
$payments = $this->paymentRepo->find($clientPublicId, Input::get('sSearch')); $payments = $this->paymentRepo->find($clientPublicId, Input::get('sSearch'));
$table = Datatable::query($payments); $table = Datatable::query($payments);
if (!$clientPublicId) { if (!$clientPublicId) {
$table->addColumn('checkbox', function($model) { return '<input type="checkbox" name="ids[]" value="' . $model->public_id . '" ' . Utils::getEntityRowClass($model) . '>'; }); $table->addColumn('checkbox', function ($model) { return '<input type="checkbox" name="ids[]" value="'.$model->public_id.'" '.Utils::getEntityRowClass($model).'>'; });
} }
$table->addColumn('invoice_number', function($model) { return $model->invoice_public_id ? link_to('invoices/' . $model->invoice_public_id . '/edit', $model->invoice_number, ['class' => Utils::getEntityRowClass($model)]) : ''; }); $table->addColumn('invoice_number', function ($model) { return $model->invoice_public_id ? link_to('invoices/'.$model->invoice_public_id.'/edit', $model->invoice_number, ['class' => Utils::getEntityRowClass($model)]) : ''; });
if (!$clientPublicId) { if (!$clientPublicId) {
$table->addColumn('client_name', function($model) { return link_to('clients/' . $model->client_public_id, Utils::getClientDisplayName($model)); }); $table->addColumn('client_name', function ($model) { return link_to('clients/'.$model->client_public_id, Utils::getClientDisplayName($model)); });
} }
$table->addColumn('transaction_reference', function($model) { return $model->transaction_reference ? $model->transaction_reference : '<i>Manual entry</i>'; }) $table->addColumn('transaction_reference', function ($model) { return $model->transaction_reference ? $model->transaction_reference : '<i>Manual entry</i>'; })
->addColumn('payment_type', function($model) { return $model->payment_type ? $model->payment_type : ($model->account_gateway_id ? '<i>Online payment</i>' : ''); }); ->addColumn('payment_type', function ($model) { return $model->payment_type ? $model->payment_type : ($model->account_gateway_id ? '<i>Online payment</i>' : ''); });
return $table->addColumn('amount', function($model) { return Utils::formatMoney($model->amount, $model->currency_id); }) return $table->addColumn('amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id); })
->addColumn('payment_date', function($model) { return Utils::dateToString($model->payment_date); }) ->addColumn('payment_date', function ($model) { return Utils::dateToString($model->payment_date); })
->addColumn('dropdown', function($model) ->addColumn('dropdown', function ($model) {
{ if ($model->is_deleted) {
if ($model->is_deleted)
{
return '<div style="height:38px"/>'; return '<div style="height:38px"/>';
} }
$str = '<div class="btn-group tr-action" style="visibility:hidden;"> $str = '<div class="btn-group tr-action" style="visibility:hidden;">
<button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown"> <button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown">
'.trans('texts.select').' <span class="caret"></span> '.trans('texts.select').' <span class="caret"></span>
</button> </button>
<ul class="dropdown-menu" role="menu">'; <ul class="dropdown-menu" role="menu">';
if (!$model->deleted_at || $model->deleted_at == '0000-00-00') if (!$model->deleted_at || $model->deleted_at == '0000-00-00') {
{ $str .= '<li><a href="javascript:archiveEntity('.$model->public_id.')">'.trans('texts.archive_payment').'</a></li>';
$str .= '<li><a href="javascript:archiveEntity(' . $model->public_id. ')">'.trans('texts.archive_payment').'</a></li>'; } else {
$str .= '<li><a href="javascript:restoreEntity('.$model->public_id.')">'.trans('texts.restore_payment').'</a></li>';
} }
else
{ return $str.'<li><a href="javascript:deleteEntity('.$model->public_id.')">'.trans('texts.delete_payment').'</a></li></ul>
$str .= '<li><a href="javascript:restoreEntity(' . $model->public_id. ')">'.trans('texts.restore_payment').'</a></li>';
}
return $str . '<li><a href="javascript:deleteEntity(' . $model->public_id. ')">'.trans('texts.delete_payment').'</a></li></ul>
</div>'; </div>';
}) })
->make(); ->make();
} }
@ -93,52 +88,49 @@ class PaymentController extends \BaseController
$invitationKey = Session::get('invitation_key'); $invitationKey = Session::get('invitation_key');
$invitation = Invitation::where('invitation_key', '=', $invitationKey)->with('contact.client')->first(); $invitation = Invitation::where('invitation_key', '=', $invitationKey)->with('contact.client')->first();
if (!$invitation) if (!$invitation) {
{ return [];
return [];
} }
$invoice = $invitation->invoice; $invoice = $invitation->invoice;
if (!$invoice || $invoice->is_deleted) if (!$invoice || $invoice->is_deleted) {
{ return [];
return [];
} }
$payments = $this->paymentRepo->findForContact($invitation->contact->id, Input::get('sSearch')); $payments = $this->paymentRepo->findForContact($invitation->contact->id, Input::get('sSearch'));
return Datatable::query($payments) return Datatable::query($payments)
->addColumn('invoice_number', function($model) { return $model->invitation_key ? link_to('/view/' . $model->invitation_key, $model->invoice_number) : $model->invoice_number; }) ->addColumn('invoice_number', function ($model) { return $model->invitation_key ? link_to('/view/'.$model->invitation_key, $model->invoice_number) : $model->invoice_number; })
->addColumn('transaction_reference', function($model) { return $model->transaction_reference ? $model->transaction_reference : '<i>Manual entry</i>'; }) ->addColumn('transaction_reference', function ($model) { return $model->transaction_reference ? $model->transaction_reference : '<i>Manual entry</i>'; })
->addColumn('payment_type', function($model) { return $model->payment_type ? $model->payment_type : ($model->account_gateway_id ? '<i>Online payment</i>' : ''); }) ->addColumn('payment_type', function ($model) { return $model->payment_type ? $model->payment_type : ($model->account_gateway_id ? '<i>Online payment</i>' : ''); })
->addColumn('amount', function($model) { return Utils::formatMoney($model->amount, $model->currency_id); }) ->addColumn('amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id); })
->addColumn('payment_date', function($model) { return Utils::dateToString($model->payment_date); }) ->addColumn('payment_date', function ($model) { return Utils::dateToString($model->payment_date); })
->make(); ->make();
} }
public function create($clientPublicId = 0, $invoicePublicId = 0) public function create($clientPublicId = 0, $invoicePublicId = 0)
{ {
$data = array( $data = array(
'clientPublicId' => Input::old('client') ? Input::old('client') : $clientPublicId, 'clientPublicId' => Input::old('client') ? Input::old('client') : $clientPublicId,
'invoicePublicId' => Input::old('invoice') ? Input::old('invoice') : $invoicePublicId, 'invoicePublicId' => Input::old('invoice') ? Input::old('invoice') : $invoicePublicId,
'invoice' => null, 'invoice' => null,
'invoices' => Invoice::scope()->where('is_recurring', '=', false)->where('is_quote', '=', false) 'invoices' => Invoice::scope()->where('is_recurring', '=', false)->where('is_quote', '=', false)
->with('client', 'invoice_status')->orderBy('invoice_number')->get(), ->with('client', 'invoice_status')->orderBy('invoice_number')->get(),
'payment' => null, 'payment' => null,
'method' => 'POST', 'method' => 'POST',
'url' => "payments", 'url' => "payments",
'title' => trans('texts.new_payment'), 'title' => trans('texts.new_payment'),
//'currencies' => Currency::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(), //'currencies' => Currency::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(),
'paymentTypes' => PaymentType::remember(DEFAULT_QUERY_CACHE)->orderBy('id')->get(), 'paymentTypes' => PaymentType::remember(DEFAULT_QUERY_CACHE)->orderBy('id')->get(),
'clients' => Client::scope()->with('contacts')->orderBy('name')->get()); 'clients' => Client::scope()->with('contacts')->orderBy('name')->get(), );
return View::make('payments.edit', $data); return View::make('payments.edit', $data);
} }
public function edit($publicId) public function edit($publicId)
{ {
$payment = Payment::scope($publicId)->firstOrFail(); $payment = Payment::scope($publicId)->firstOrFail();
$payment->payment_date = Utils::fromSqlDate($payment->payment_date); $payment->payment_date = Utils::fromSqlDate($payment->payment_date);
$data = array( $data = array(
@ -146,50 +138,48 @@ class PaymentController extends \BaseController
'invoice' => null, 'invoice' => null,
'invoices' => Invoice::scope()->where('is_recurring', '=', false)->where('is_quote', '=', false) 'invoices' => Invoice::scope()->where('is_recurring', '=', false)->where('is_quote', '=', false)
->with('client', 'invoice_status')->orderBy('invoice_number')->get(), ->with('client', 'invoice_status')->orderBy('invoice_number')->get(),
'payment' => $payment, 'payment' => $payment,
'method' => 'PUT', 'method' => 'PUT',
'url' => 'payments/' . $publicId, 'url' => 'payments/'.$publicId,
'title' => 'Edit Payment', 'title' => 'Edit Payment',
//'currencies' => Currency::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(), //'currencies' => Currency::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(),
'paymentTypes' => PaymentType::remember(DEFAULT_QUERY_CACHE)->orderBy('id')->get(), 'paymentTypes' => PaymentType::remember(DEFAULT_QUERY_CACHE)->orderBy('id')->get(),
'clients' => Client::scope()->with('contacts')->orderBy('name')->get()); 'clients' => Client::scope()->with('contacts')->orderBy('name')->get(), );
return View::make('payments.edit', $data); return View::make('payments.edit', $data);
} }
private function createGateway($accountGateway) private function createGateway($accountGateway)
{ {
$gateway = Omnipay::create($accountGateway->gateway->provider); $gateway = Omnipay::create($accountGateway->gateway->provider);
$config = json_decode($accountGateway->config); $config = json_decode($accountGateway->config);
/* /*
$gateway->setSolutionType("Sole"); $gateway->setSolutionType("Sole");
$gateway->setLandingPage("Billing"); $gateway->setLandingPage("Billing");
*/ */
foreach ($config as $key => $val) foreach ($config as $key => $val) {
{ if (!$val) {
if (!$val)
{
continue; continue;
} }
$function = "set" . ucfirst($key); $function = "set".ucfirst($key);
$gateway->$function($val); $gateway->$function($val);
} }
if (Utils::isNinjaDev()) if (Utils::isNinjaDev()) {
{ $gateway->setTestMode(true);
$gateway->setTestMode(true); }
}
return $gateway; return $gateway;
} }
private function getLicensePaymentDetails($input, $affiliate) private function getLicensePaymentDetails($input, $affiliate)
{ {
$data = self::convertInputForOmnipay($input); $data = self::convertInputForOmnipay($input);
$card = new CreditCard($data); $card = new CreditCard($data);
return [ return [
'amount' => $affiliate->price, 'amount' => $affiliate->price,
'card' => $card, 'card' => $card,
@ -197,7 +187,6 @@ class PaymentController extends \BaseController
'returnUrl' => URL::to('license_complete'), 'returnUrl' => URL::to('license_complete'),
'cancelUrl' => URL::to('/') 'cancelUrl' => URL::to('/')
]; ];
} }
private function convertInputForOmnipay($input) private function convertInputForOmnipay($input)
@ -224,19 +213,16 @@ class PaymentController extends \BaseController
private function getPaymentDetails($invoice, $input = null) private function getPaymentDetails($invoice, $input = null)
{ {
$key = $invoice->invoice_number . '_details'; $key = $invoice->invoice_number.'_details';
$gateway = $invoice->client->account->account_gateways[0]->gateway; $gateway = $invoice->client->account->account_gateways[0]->gateway;
$paymentLibrary = $gateway->paymentlibrary; $paymentLibrary = $gateway->paymentlibrary;
$currencyCode = $invoice->client->currency ? $invoice->client->currency->code : ($invoice->account->currency ? $invoice->account->currency->code : 'USD'); $currencyCode = $invoice->client->currency ? $invoice->client->currency->code : ($invoice->account->currency ? $invoice->account->currency->code : 'USD');
if ($input && $paymentLibrary->id == PAYMENT_LIBRARY_OMNIPAY) if ($input && $paymentLibrary->id == PAYMENT_LIBRARY_OMNIPAY) {
{
$data = self::convertInputForOmnipay($input); $data = self::convertInputForOmnipay($input);
Session::put($key, $data); Session::put($key, $data);
} } elseif ($input && $paymentLibrary->id == PAYMENT_LIBRARY_PHP_PAYMENTS) {
else if ($input && $paymentLibrary->id == PAYMENT_LIBRARY_PHP_PAYMENTS)
{
$input = Input::all(); $input = Input::all();
$data = [ $data = [
'first_name' => $input['first_name'], 'first_name' => $input['first_name'],
@ -256,9 +242,8 @@ class PaymentController extends \BaseController
'ship_to_postal_code' => $input['postal_code'], 'ship_to_postal_code' => $input['postal_code'],
'currency_code' => $currencyCode, 'currency_code' => $currencyCode,
]; ];
switch($gateway->id) switch ($gateway->id) {
{
case GATEWAY_BEANSTREAM: case GATEWAY_BEANSTREAM:
$data['phone'] = $input['phone']; $data['phone'] = $input['phone'];
$data['email'] = $input['email']; $data['email'] = $input['email'];
@ -269,28 +254,23 @@ class PaymentController extends \BaseController
$data['ship_to_state'] = 'Ohio'; //$input['state']; $data['ship_to_state'] = 'Ohio'; //$input['state'];
break; break;
} }
if(strlen($data['cc_exp']) == 5) if (strlen($data['cc_exp']) == 5) {
{
$data['cc_exp'] = '0'.$data['cc_exp']; $data['cc_exp'] = '0'.$data['cc_exp'];
} }
Session::put($key, $data); Session::put($key, $data);
return $data; return $data;
} } elseif (Session::get($key)) {
else if (Session::get($key))
{
$data = Session::get($key); $data = Session::get($key);
} } else {
else
{
$data = []; $data = [];
} }
if($paymentLibrary->id == PAYMENT_LIBRARY_OMNIPAY) if ($paymentLibrary->id == PAYMENT_LIBRARY_OMNIPAY) {
{
$card = new CreditCard($data); $card = new CreditCard($data);
return [ return [
'amount' => $invoice->amount, 'amount' => $invoice->amount,
'card' => $card, 'card' => $card,
@ -298,36 +278,31 @@ class PaymentController extends \BaseController
'returnUrl' => URL::to('complete'), 'returnUrl' => URL::to('complete'),
'cancelUrl' => URL::to('/') 'cancelUrl' => URL::to('/')
]; ];
} } else {
else
{
return $data; return $data;
} }
} }
public function show_payment($invitationKey) public function show_payment($invitationKey)
{ {
// For PayPal Express we redirect straight to their site // For PayPal Express we redirect straight to their site
$invitation = Invitation::with('invoice.client.account', 'invoice.client.account.account_gateways.gateway')->where('invitation_key', '=', $invitationKey)->firstOrFail(); $invitation = Invitation::with('invoice.client.account', 'invoice.client.account.account_gateways.gateway')->where('invitation_key', '=', $invitationKey)->firstOrFail();
$account = $invitation->invoice->client->account; $account = $invitation->invoice->client->account;
if ($account->isGatewayConfigured(GATEWAY_PAYPAL_EXPRESS)) if ($account->isGatewayConfigured(GATEWAY_PAYPAL_EXPRESS)) {
{ if (Session::has('error')) {
if (Session::has('error'))
{
Session::reflash(); Session::reflash();
return Redirect::to('view/' . $invitationKey);
} return Redirect::to('view/'.$invitationKey);
else } else {
{
return self::do_payment($invitationKey, false); return self::do_payment($invitationKey, false);
} }
} }
$invitation = Invitation::with('invoice.invoice_items', 'invoice.client.currency', 'invoice.client.account.account_gateways.gateway')->where('invitation_key', '=', $invitationKey)->firstOrFail(); $invitation = Invitation::with('invoice.invoice_items', 'invoice.client.currency', 'invoice.client.account.account_gateways.gateway')->where('invitation_key', '=', $invitationKey)->firstOrFail();
$invoice = $invitation->invoice; $invoice = $invitation->invoice;
$client = $invoice->client; $client = $invoice->client;
$accountGateway = $invoice->client->account->account_gateways[0]; $accountGateway = $invoice->client->account->account_gateways[0];
$gateway = $invoice->client->account->account_gateways[0]->gateway; $gateway = $invoice->client->account->account_gateways[0]->gateway;
$paymentLibrary = $gateway->paymentlibrary; $paymentLibrary = $gateway->paymentlibrary;
$acceptedCreditCardTypes = $accountGateway->getCreditcardTypes(); $acceptedCreditCardTypes = $accountGateway->getCreditcardTypes();
@ -335,51 +310,45 @@ class PaymentController extends \BaseController
$data = [ $data = [
'showBreadcrumbs' => false, 'showBreadcrumbs' => false,
'hideHeader' => true, 'hideHeader' => true,
'url' => 'payment/' . $invitationKey, 'url' => 'payment/'.$invitationKey,
'amount' => $invoice->amount, 'amount' => $invoice->amount,
'client' => $client, 'client' => $client,
'contact' => $invitation->contact, 'contact' => $invitation->contact,
'paymentLibrary' => $paymentLibrary, 'paymentLibrary' => $paymentLibrary,
'gateway' => $gateway, 'gateway' => $gateway,
'acceptedCreditCardTypes' => $acceptedCreditCardTypes, 'acceptedCreditCardTypes' => $acceptedCreditCardTypes,
'countries' => Country::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(), 'countries' => Country::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(),
'currencyId' => $client->currency_id 'currencyId' => $client->currency_id,
]; ];
return View::make('payments.payment', $data); return View::make('payments.payment', $data);
} }
public function show_license_payment() public function show_license_payment()
{ {
if (Input::has('return_url')) if (Input::has('return_url')) {
{
Session::set('return_url', Input::get('return_url')); Session::set('return_url', Input::get('return_url'));
} }
if (Input::has('affiliate_key')) if (Input::has('affiliate_key')) {
{ if ($affiliate = Affiliate::where('affiliate_key', '=', Input::get('affiliate_key'))->first()) {
if ($affiliate = Affiliate::where('affiliate_key', '=', Input::get('affiliate_key'))->first()) Session::set('affiliate_id', $affiliate->id);
{
Session::set('affiliate_id', $affiliate->id);
} }
} }
Session::set('product_id', Input::get('product_id', PRODUCT_ONE_CLICK_INSTALL)); Session::set('product_id', Input::get('product_id', PRODUCT_ONE_CLICK_INSTALL));
if (!Session::get('affiliate_id')) if (!Session::get('affiliate_id')) {
{ return Utils::fatalError();
return Utils::fatalError();
} }
if (Utils::isNinjaDev() && Input::has('test_mode')) if (Utils::isNinjaDev() && Input::has('test_mode')) {
{
Session::set('test_mode', Input::get('test_mode')); Session::set('test_mode', Input::get('test_mode'));
} }
$account = $this->accountRepo->getNinjaAccount();
$account = $this->accountRepo->getNinjaAccount();
$account->load('account_gateways.gateway'); $account->load('account_gateways.gateway');
$accountGateway = $account->account_gateways[0]; $accountGateway = $account->account_gateways[0];
$gateway = $accountGateway->gateway; $gateway = $accountGateway->gateway;
$paymentLibrary = $gateway->paymentlibrary; $paymentLibrary = $gateway->paymentlibrary;
$acceptedCreditCardTypes = $accountGateway->getCreditcardTypes(); $acceptedCreditCardTypes = $accountGateway->getCreditcardTypes();
@ -395,17 +364,17 @@ class PaymentController extends \BaseController
'contact' => false, 'contact' => false,
'paymentLibrary' => $paymentLibrary, 'paymentLibrary' => $paymentLibrary,
'gateway' => $gateway, 'gateway' => $gateway,
'acceptedCreditCardTypes' => $acceptedCreditCardTypes, 'acceptedCreditCardTypes' => $acceptedCreditCardTypes,
'countries' => Country::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(), 'countries' => Country::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(),
'currencyId' => 1, 'currencyId' => 1,
'paymentTitle' => $affiliate->payment_title, 'paymentTitle' => $affiliate->payment_title,
'paymentSubtitle' => $affiliate->payment_subtitle 'paymentSubtitle' => $affiliate->payment_subtitle,
]; ];
return View::make('payments.payment', $data); return View::make('payments.payment', $data);
} }
public function do_license_payment() public function do_license_payment()
{ {
$testMode = Session::get('test_mode') === 'true'; $testMode = Session::get('test_mode') === 'true';
@ -424,49 +393,43 @@ class PaymentController extends \BaseController
$validator = Validator::make(Input::all(), $rules); $validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) if ($validator->fails()) {
{
return Redirect::to('license') return Redirect::to('license')
->withErrors($validator); ->withErrors($validator);
} }
$account = $this->accountRepo->getNinjaAccount(); $account = $this->accountRepo->getNinjaAccount();
$account->load('account_gateways.gateway'); $account->load('account_gateways.gateway');
$accountGateway = $account->account_gateways[0]; $accountGateway = $account->account_gateways[0];
try try {
{
$affiliate = Affiliate::find(Session::get('affiliate_id')); $affiliate = Affiliate::find(Session::get('affiliate_id'));
if ($testMode) if ($testMode) {
{
$ref = 'TEST_MODE'; $ref = 'TEST_MODE';
} } else {
else
{
$gateway = self::createGateway($accountGateway); $gateway = self::createGateway($accountGateway);
$details = self::getLicensePaymentDetails(Input::all(), $affiliate); $details = self::getLicensePaymentDetails(Input::all(), $affiliate);
$response = $gateway->purchase($details)->send(); $response = $gateway->purchase($details)->send();
$ref = $response->getTransactionReference(); $ref = $response->getTransactionReference();
if (!$ref) if (!$ref) {
{ Session::flash('error', $response->getMessage());
Session::flash('error', $response->getMessage());
return Redirect::to('license')->withInput(); return Redirect::to('license')->withInput();
} }
if (!$response->isSuccessful()) if (!$response->isSuccessful()) {
{ Session::flash('error', $response->getMessage());
Session::flash('error', $response->getMessage());
Utils::logError($response->getMessage()); Utils::logError($response->getMessage());
return Redirect::to('license')->withInput();
}
return Redirect::to('license')->withInput();
}
} }
$licenseKey = Utils::generateLicense(); $licenseKey = Utils::generateLicense();
$license = new License; $license = new License();
$license->first_name = Input::get('first_name'); $license->first_name = Input::get('first_name');
$license->last_name = Input::get('last_name'); $license->last_name = Input::get('last_name');
$license->email = Input::get('email'); $license->email = Input::get('email');
@ -474,33 +437,29 @@ class PaymentController extends \BaseController
$license->license_key = $licenseKey; $license->license_key = $licenseKey;
$license->affiliate_id = Session::get('affiliate_id'); $license->affiliate_id = Session::get('affiliate_id');
$license->product_id = Session::get('product_id'); $license->product_id = Session::get('product_id');
$license->save(); $license->save();
$data = [ $data = [
'message' => $affiliate->payment_subtitle, 'message' => $affiliate->payment_subtitle,
'license' => $licenseKey, 'license' => $licenseKey,
'hideHeader' => true 'hideHeader' => true,
]; ];
$name = "{$license->first_name} {$license->last_name}"; $name = "{$license->first_name} {$license->last_name}";
$this->contactMailer->sendLicensePaymentConfirmation($name, $license->email, $affiliate->price, $license->license_key, $license->product_id); $this->contactMailer->sendLicensePaymentConfirmation($name, $license->email, $affiliate->price, $license->license_key, $license->product_id);
if (Session::has('return_url')) if (Session::has('return_url')) {
{ return Redirect::away(Session::get('return_url')."?license_key={$license->license_key}&product_id=".Session::get('product_id'));
return Redirect::away(Session::get('return_url') . "?license_key={$license->license_key}&product_id=" . Session::get('product_id')); } else {
}
else
{
return View::make('public.license', $data); return View::make('public.license', $data);
} }
} } catch (\Exception $e) {
catch (\Exception $e)
{
$errorMessage = trans('texts.payment_error'); $errorMessage = trans('texts.payment_error');
Session::flash('error', $errorMessage); Session::flash('error', $errorMessage);
Utils::logError(Utils::getErrorString($e)); Utils::logError(Utils::getErrorString($e));
return Redirect::to('license')->withInput(); return Redirect::to('license')->withInput();
} }
} }
public function claim_license() public function claim_license()
@ -513,18 +472,14 @@ class PaymentController extends \BaseController
->where('product_id', '=', $productId) ->where('product_id', '=', $productId)
->first(); ->first();
if ($license) if ($license) {
{ if ($license->transaction_reference != 'TEST_MODE') {
if ($license->transaction_reference != 'TEST_MODE')
{
$license->is_claimed = true; $license->is_claimed = true;
$license->save(); $license->save();
} }
return $productId == PRODUCT_INVOICE_DESIGNS ? $_ENV['INVOICE_DESIGNS'] : 'valid'; return $productId == PRODUCT_INVOICE_DESIGNS ? $_ENV['INVOICE_DESIGNS'] : 'valid';
} } else {
else
{
return 'invalid'; return 'invalid';
} }
} }
@ -544,24 +499,21 @@ class PaymentController extends \BaseController
'postal_code' => 'required', 'postal_code' => 'required',
); );
if ($onSite) if ($onSite) {
{
$validator = Validator::make(Input::all(), $rules); $validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) if ($validator->fails()) {
{ return Redirect::to('payment/'.$invitationKey)
return Redirect::to('payment/' . $invitationKey)
->withErrors($validator); ->withErrors($validator);
} }
} }
$invitation = Invitation::with('invoice.invoice_items', 'invoice.client.currency', 'invoice.client.account.account_gateways.gateway')->where('invitation_key', '=', $invitationKey)->firstOrFail(); $invitation = Invitation::with('invoice.invoice_items', 'invoice.client.currency', 'invoice.client.account.account_gateways.gateway')->where('invitation_key', '=', $invitationKey)->firstOrFail();
$invoice = $invitation->invoice; $invoice = $invitation->invoice;
$accountGateway = $invoice->client->account->account_gateways[0]; $accountGateway = $invoice->client->account->account_gateways[0];
$paymentLibrary = $accountGateway->gateway->paymentlibrary; $paymentLibrary = $accountGateway->gateway->paymentlibrary;
if ($onSite) if ($onSite) {
{
$client = $invoice->client; $client = $invoice->client;
$client->address1 = trim(Input::get('address1')); $client->address1 = trim(Input::get('address1'));
$client->address2 = trim(Input::get('address2')); $client->address2 = trim(Input::get('address2'));
@ -570,56 +522,48 @@ class PaymentController extends \BaseController
$client->postal_code = trim(Input::get('postal_code')); $client->postal_code = trim(Input::get('postal_code'));
$client->save(); $client->save();
} }
try try {
{ if ($paymentLibrary->id == PAYMENT_LIBRARY_OMNIPAY) {
if($paymentLibrary->id == PAYMENT_LIBRARY_OMNIPAY)
{
$gateway = self::createGateway($accountGateway); $gateway = self::createGateway($accountGateway);
$details = self::getPaymentDetails($invoice, Input::all()); $details = self::getPaymentDetails($invoice, Input::all());
$response = $gateway->purchase($details)->send(); $response = $gateway->purchase($details)->send();
$ref = $response->getTransactionReference(); $ref = $response->getTransactionReference();
if (!$ref) if (!$ref) {
{ Session::flash('error', $response->getMessage());
Session::flash('error', $response->getMessage());
return Redirect::to('payment/' . $invitationKey) return Redirect::to('payment/'.$invitationKey)
->withInput(); ->withInput();
} }
if ($response->isSuccessful()) if ($response->isSuccessful()) {
{
$payment = self::createPayment($invitation, $ref); $payment = self::createPayment($invitation, $ref);
Session::flash('message', trans('texts.applied_payment')); Session::flash('message', trans('texts.applied_payment'));
return Redirect::to('view/' . $payment->invitation->invitation_key);
} return Redirect::to('view/'.$payment->invitation->invitation_key);
else if ($response->isRedirect()) } elseif ($response->isRedirect()) {
{
$invitation->transaction_reference = $ref; $invitation->transaction_reference = $ref;
$invitation->save(); $invitation->save();
$response->redirect(); $response->redirect();
} } else {
else Session::flash('error', $response->getMessage());
{
Session::flash('error', $response->getMessage());
return Utils::fatalError('Sorry, there was an error processing your payment. Please try again later.<p>', $response->getMessage()); return Utils::fatalError('Sorry, there was an error processing your payment. Please try again later.<p>', $response->getMessage());
} }
} } elseif ($paymentLibrary->id == PAYMENT_LIBRARY_PHP_PAYMENTS) {
else if ($paymentLibrary->id == PAYMENT_LIBRARY_PHP_PAYMENTS)
{
$gateway = $accountGateway->gateway; $gateway = $accountGateway->gateway;
$provider = $gateway->provider; $provider = $gateway->provider;
$p = new PHP_Payments(array('mode' => 'test')); $p = new PHP_Payments(array('mode' => 'test'));
$config = Payment_Utility::load('config', 'drivers/'.$provider); $config = Payment_Utility::load('config', 'drivers/'.$provider);
switch($gateway->id) switch ($gateway->id) {
{
case GATEWAY_BEANSTREAM: case GATEWAY_BEANSTREAM:
$config['delay_charge'] = FALSE; $config['delay_charge'] = false;
$config['bill_outstanding'] = TRUE; $config['bill_outstanding'] = true;
break; break;
case GATEWAY_AMAZON: case GATEWAY_AMAZON:
$config['return_url'] = URL::to('complete'); $config['return_url'] = URL::to('complete');
@ -630,31 +574,29 @@ class PaymentController extends \BaseController
$config['collect_shipping_address'] = false; $config['collect_shipping_address'] = false;
break; break;
} }
$details = self::getPaymentDetails($invoice, Input::all()); $details = self::getPaymentDetails($invoice, Input::all());
$response = $p->oneoff_payment($provider, $details, $config); $response = $p->oneoff_payment($provider, $details, $config);
if (strtolower($response->status) == 'success') if (strtolower($response->status) == 'success') {
{
$payment = self::createPayment($invitation, $response->response_message); $payment = self::createPayment($invitation, $response->response_message);
Session::flash('message', trans('texts.applied_payment')); Session::flash('message', trans('texts.applied_payment'));
return Redirect::to('view/' . $payment->invitation->invitation_key);
} return Redirect::to('view/'.$payment->invitation->invitation_key);
else } else {
{ Session::flash('error', $response->response_message);
Session::flash('error', $response->response_message);
return Utils::fatalError('Sorry, there was an error processing your payment. Please try again later.<p>', $response->response_message); return Utils::fatalError('Sorry, there was an error processing your payment. Please try again later.<p>', $response->response_message);
} }
} }
} } catch (\Exception $e) {
catch (\Exception $e)
{
$errorMessage = trans('texts.payment_error'); $errorMessage = trans('texts.payment_error');
Session::flash('error', $errorMessage); Session::flash('error', $errorMessage);
Utils::logError(Utils::getErrorString($e)); Utils::logError(Utils::getErrorString($e));
return Redirect::to('payment/' . $invitationKey)
return Redirect::to('payment/'.$invitationKey)
->withInput(); ->withInput();
} }
} }
@ -664,44 +606,41 @@ class PaymentController extends \BaseController
$invoice = $invitation->invoice; $invoice = $invitation->invoice;
$accountGateway = $invoice->client->account->account_gateways[0]; $accountGateway = $invoice->client->account->account_gateways[0];
if ($invoice->account->account_key == NINJA_ACCOUNT_KEY) if ($invoice->account->account_key == NINJA_ACCOUNT_KEY) {
{
$account = Account::find($invoice->client->public_id); $account = Account::find($invoice->client->public_id);
$account->pro_plan_paid = date_create()->format('Y-m-d'); $account->pro_plan_paid = date_create()->format('Y-m-d');
$account->save(); $account->save();
} }
if ($invoice->is_quote) if ($invoice->is_quote) {
{
$invoice = $this->invoiceRepo->cloneInvoice($invoice, $invoice->id); $invoice = $this->invoiceRepo->cloneInvoice($invoice, $invoice->id);
} }
$payment = Payment::createNew($invitation); $payment = Payment::createNew($invitation);
$payment->invitation_id = $invitation->id; $payment->invitation_id = $invitation->id;
$payment->account_gateway_id = $accountGateway->id; $payment->account_gateway_id = $accountGateway->id;
$payment->invoice_id = $invoice->id; $payment->invoice_id = $invoice->id;
$payment->amount = $invoice->amount; $payment->amount = $invoice->amount;
$payment->client_id = $invoice->client_id; $payment->client_id = $invoice->client_id;
$payment->contact_id = $invitation->contact_id; $payment->contact_id = $invitation->contact_id;
$payment->transaction_reference = $ref; $payment->transaction_reference = $ref;
$payment->payment_date = date_create()->format('Y-m-d'); $payment->payment_date = date_create()->format('Y-m-d');
if ($payerId) if ($payerId) {
{ $payment->payer_id = $payerId;
$payment->payer_id = $payerId;
} }
$payment->save(); $payment->save();
Event::fire('invoice.paid', $payment); Event::fire('invoice.paid', $payment);
return $payment; return $payment;
} }
public function offsite_payment() public function offsite_payment()
{ {
$payerId = Request::query('PayerID'); $payerId = Request::query('PayerID');
$token = Request::query('token'); $token = Request::query('token');
$invitation = Invitation::with('invoice.client.currency', 'invoice.client.account.account_gateways.gateway')->where('transaction_reference', '=', $token)->firstOrFail(); $invitation = Invitation::with('invoice.client.currency', 'invoice.client.account.account_gateways.gateway')->where('transaction_reference', '=', $token)->firstOrFail();
$invoice = $invitation->invoice; $invoice = $invitation->invoice;
@ -709,37 +648,33 @@ class PaymentController extends \BaseController
$accountGateway = $invoice->client->account->account_gateways[0]; $accountGateway = $invoice->client->account->account_gateways[0];
$gateway = self::createGateway($accountGateway); $gateway = self::createGateway($accountGateway);
try try {
{
$details = self::getPaymentDetails($invoice); $details = self::getPaymentDetails($invoice);
$response = $gateway->completePurchase($details)->send(); $response = $gateway->completePurchase($details)->send();
$ref = $response->getTransactionReference(); $ref = $response->getTransactionReference();
if ($response->isSuccessful()) if ($response->isSuccessful()) {
{ $payment = self::createPayment($invitation, $ref, $payerId);
$payment = self::createPayment($invitation, $ref, $payerId);
Session::flash('message', trans('texts.applied_payment')); Session::flash('message', trans('texts.applied_payment'));
return Redirect::to('view/' . $invitation->invitation_key);
} return Redirect::to('view/'.$invitation->invitation_key);
else } else {
{ $errorMessage = trans('texts.payment_error')."\n\n".$response->getMessage();
$errorMessage = trans('texts.payment_error') . "\n\n" . $response->getMessage(); Session::flash('error', $errorMessage);
Session::flash('error', $errorMessage);
Utils::logError($errorMessage); Utils::logError($errorMessage);
return Redirect::to('view/' . $invitation->invitation_key);
return Redirect::to('view/'.$invitation->invitation_key);
} }
} } catch (\Exception $e) {
catch (\Exception $e)
{
$errorMessage = trans('texts.payment_error'); $errorMessage = trans('texts.payment_error');
Session::flash('error', $errorMessage); Session::flash('error', $errorMessage);
Utils::logError($errorMessage . "\n\n" . $e->getMessage()); Utils::logError($errorMessage."\n\n".$e->getMessage());
return Redirect::to('view/' . $invitation->invitation_key);
return Redirect::to('view/'.$invitation->invitation_key);
} }
} }
public function store() public function store()
{ {
return $this->save(); return $this->save();
@ -752,19 +687,18 @@ class PaymentController extends \BaseController
private function save($publicId = null) private function save($publicId = null)
{ {
if ($errors = $this->paymentRepo->getErrors(Input::all())) if ($errors = $this->paymentRepo->getErrors(Input::all())) {
{ $url = $publicId ? 'payments/'.$publicId.'/edit' : 'payments/create';
$url = $publicId ? 'payments/' . $publicId . '/edit' : 'payments/create';
return Redirect::to($url) return Redirect::to($url)
->withErrors($errors) ->withErrors($errors)
->withInput(); ->withInput();
} } else {
else
{
$this->paymentRepo->save($publicId, Input::all()); $this->paymentRepo->save($publicId, Input::all());
Session::flash('message', trans('texts.created_payment')); Session::flash('message', trans('texts.created_payment'));
return Redirect::to('clients/' . Input::get('client'));
return Redirect::to('clients/'.Input::get('client'));
} }
} }
@ -774,12 +708,11 @@ class PaymentController extends \BaseController
$ids = Input::get('id') ? Input::get('id') : Input::get('ids'); $ids = Input::get('id') ? Input::get('id') : Input::get('ids');
$count = $this->paymentRepo->bulk($ids, $action); $count = $this->paymentRepo->bulk($ids, $action);
if ($count > 0) if ($count > 0) {
{ $message = Utils::pluralize($action.'d_payment', $count);
$message = Utils::pluralize($action.'d_payment', $count);
Session::flash('message', $message); Session::flash('message', $message);
} }
return Redirect::to('payments'); return Redirect::to('payments');
} }
} }

View File

@ -1,101 +1,96 @@
<?php <?php
class ProductController extends \BaseController { class ProductController extends \BaseController
{
public function getDatatable() public function getDatatable()
{ {
$query = DB::table('products') $query = DB::table('products')
->where('products.account_id', '=', Auth::user()->account_id) ->where('products.account_id', '=', Auth::user()->account_id)
->where('products.deleted_at', '=', null) ->where('products.deleted_at', '=', null)
->select('products.public_id', 'products.product_key', 'products.notes', 'products.cost'); ->select('products.public_id', 'products.product_key', 'products.notes', 'products.cost');
return Datatable::query($query)
return Datatable::query($query) ->addColumn('product_key', function ($model) { return link_to('products/'.$model->public_id.'/edit', $model->product_key); })
->addColumn('product_key', function($model) { return link_to('products/' . $model->public_id . '/edit', $model->product_key); }) ->addColumn('notes', function ($model) { return nl2br(Str::limit($model->notes, 100)); })
->addColumn('notes', function($model) { return nl2br(Str::limit($model->notes, 100)); }) ->addColumn('cost', function ($model) { return Utils::formatMoney($model->cost); })
->addColumn('cost', function($model) { return Utils::formatMoney($model->cost); }) ->addColumn('dropdown', function ($model) {
->addColumn('dropdown', function($model)
{
return '<div class="btn-group tr-action" style="visibility:hidden;"> return '<div class="btn-group tr-action" style="visibility:hidden;">
<button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown"> <button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown">
'.trans('texts.select').' <span class="caret"></span> '.trans('texts.select').' <span class="caret"></span>
</button> </button>
<ul class="dropdown-menu" role="menu"> <ul class="dropdown-menu" role="menu">
<li><a href="' . URL::to('products/'.$model->public_id) . '/edit">'.uctrans('texts.edit_product').'</a></li> <li><a href="'.URL::to('products/'.$model->public_id).'/edit">'.uctrans('texts.edit_product').'</a></li>
<li class="divider"></li> <li class="divider"></li>
<li><a href="' . URL::to('products/'.$model->public_id) . '/archive">'.uctrans('texts.archive_product').'</a></li> <li><a href="'.URL::to('products/'.$model->public_id).'/archive">'.uctrans('texts.archive_product').'</a></li>
</ul> </ul>
</div>'; </div>';
}) })
->orderColumns(['cost', 'product_key', 'cost']) ->orderColumns(['cost', 'product_key', 'cost'])
->make(); ->make();
} }
public function edit($publicId) public function edit($publicId)
{ {
$data = [ $data = [
'showBreadcrumbs' => false, 'showBreadcrumbs' => false,
'product' => Product::scope($publicId)->firstOrFail(), 'product' => Product::scope($publicId)->firstOrFail(),
'method' => 'PUT', 'method' => 'PUT',
'url' => 'products/' . $publicId, 'url' => 'products/'.$publicId,
'title' => trans('texts.edit_product') 'title' => trans('texts.edit_product'),
]; ];
return View::make('accounts.product', $data); return View::make('accounts.product', $data);
} }
public function create() public function create()
{ {
$data = [ $data = [
'showBreadcrumbs' => false, 'showBreadcrumbs' => false,
'product' => null, 'product' => null,
'method' => 'POST', 'method' => 'POST',
'url' => 'products', 'url' => 'products',
'title' => trans('texts.create_product') 'title' => trans('texts.create_product'),
]; ];
return View::make('accounts.product', $data); return View::make('accounts.product', $data);
}
public function store()
{
return $this->save();
}
public function update($publicId)
{
return $this->save($publicId);
}
private function save($productPublicId = false)
{
if ($productPublicId)
{
$product = Product::scope($productPublicId)->firstOrFail();
}
else
{
$product = Product::createNew();
} }
$product->product_key = trim(Input::get('product_key')); public function store()
$product->notes = trim(Input::get('notes')); {
$product->cost = trim(Input::get('cost')); return $this->save();
$product->save(); }
$message = $productPublicId ? trans('texts.updated_product') : trans('texts.created_product'); public function update($publicId)
Session::flash('message', $message); {
return $this->save($publicId);
}
return Redirect::to('company/products'); private function save($productPublicId = false)
} {
if ($productPublicId) {
$product = Product::scope($productPublicId)->firstOrFail();
} else {
$product = Product::createNew();
}
public function archive($publicId) $product->product_key = trim(Input::get('product_key'));
{ $product->notes = trim(Input::get('notes'));
$product = Product::scope($publicId)->firstOrFail(); $product->cost = trim(Input::get('cost'));
$product->delete(); $product->save();
Session::flash('message', trans('texts.archived_product')); $message = $productPublicId ? trans('texts.updated_product') : trans('texts.created_product');
return Redirect::to('company/products'); Session::flash('message', $message);
}
} return Redirect::to('company/products');
}
public function archive($publicId)
{
$product = Product::scope($publicId)->firstOrFail();
$product->delete();
Session::flash('message', trans('texts.archived_product'));
return Redirect::to('company/products');
}
}

View File

@ -2,30 +2,31 @@
use ninja\repositories\InvoiceRepository; use ninja\repositories\InvoiceRepository;
class QuoteApiController extends Controller { class QuoteApiController extends Controller
{
protected $invoiceRepo;
protected $invoiceRepo; public function __construct(InvoiceRepository $invoiceRepo)
{
public function __construct(InvoiceRepository $invoiceRepo) $this->invoiceRepo = $invoiceRepo;
{
$this->invoiceRepo = $invoiceRepo;
}
public function index()
{
if (!Utils::isPro()) {
return Redirect::to('/');
} }
$invoices = Invoice::scope()->where('invoices.is_quote', '=', true)->orderBy('created_at', 'desc')->get(); public function index()
$invoices = Utils::remapPublicIds($invoices->toArray()); {
if (!Utils::isPro()) {
return Redirect::to('/');
}
$response = json_encode($invoices, JSON_PRETTY_PRINT); $invoices = Invoice::scope()->where('invoices.is_quote', '=', true)->orderBy('created_at', 'desc')->get();
$headers = Utils::getApiHeaders(count($invoices)); $invoices = Utils::remapPublicIds($invoices->toArray());
return Response::make($response, 200, $headers);
}
/* $response = json_encode($invoices, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders(count($invoices));
return Response::make($response, 200, $headers);
}
/*
public function store() public function store()
{ {
$data = Input::all(); $data = Input::all();

View File

@ -5,34 +5,33 @@ use ninja\repositories\InvoiceRepository;
use ninja\repositories\ClientRepository; use ninja\repositories\ClientRepository;
use ninja\repositories\TaxRateRepository; use ninja\repositories\TaxRateRepository;
class QuoteController extends \BaseController { class QuoteController extends \BaseController
{
protected $mailer;
protected $invoiceRepo;
protected $clientRepo;
protected $taxRateRepo;
protected $mailer; public function __construct(Mailer $mailer, InvoiceRepository $invoiceRepo, ClientRepository $clientRepo, TaxRateRepository $taxRateRepo)
protected $invoiceRepo;
protected $clientRepo;
protected $taxRateRepo;
public function __construct(Mailer $mailer, InvoiceRepository $invoiceRepo, ClientRepository $clientRepo, TaxRateRepository $taxRateRepo)
{
parent::__construct();
$this->mailer = $mailer;
$this->invoiceRepo = $invoiceRepo;
$this->clientRepo = $clientRepo;
$this->taxRateRepo = $taxRateRepo;
}
public function index()
{
if (!Utils::isPro())
{ {
return Redirect::to('/invoices/create'); parent::__construct();
$this->mailer = $mailer;
$this->invoiceRepo = $invoiceRepo;
$this->clientRepo = $clientRepo;
$this->taxRateRepo = $taxRateRepo;
} }
$data = [ public function index()
{
if (!Utils::isPro()) {
return Redirect::to('/invoices/create');
}
$data = [
'title' => trans('texts.quotes'), 'title' => trans('texts.quotes'),
'entityType'=>ENTITY_QUOTE, 'entityType' => ENTITY_QUOTE,
'columns'=>Utils::trans(['checkbox', 'quote_number', 'client', 'quote_date', 'quote_total', 'due_date', 'status', 'action']) 'columns' => Utils::trans(['checkbox', 'quote_number', 'client', 'quote_date', 'quote_total', 'due_date', 'status', 'action']),
]; ];
/* /*
@ -44,115 +43,108 @@ class QuoteController extends \BaseController {
*/ */
return View::make('list', $data); return View::make('list', $data);
} }
public function clientIndex()
public function clientIndex() {
{ $data = [
$data = [
'showClientHeader' => true, 'showClientHeader' => true,
'hideLogo' => Session::get('white_label'), 'hideLogo' => Session::get('white_label'),
'title' => trans('texts.quotes'), 'title' => trans('texts.quotes'),
'entityType'=>ENTITY_QUOTE, 'entityType' => ENTITY_QUOTE,
'columns'=>Utils::trans(['quote_number', 'quote_date', 'quote_total', 'due_date']) 'columns' => Utils::trans(['quote_number', 'quote_date', 'quote_total', 'due_date']),
]; ];
return View::make('public_list', $data); return View::make('public_list', $data);
}
public function getDatatable($clientPublicId = null)
{
$accountId = Auth::user()->account_id;
$search = Input::get('sSearch');
return $this->invoiceRepo->getDatatable($accountId, $clientPublicId, ENTITY_QUOTE, $search);
}
public function getClientDatatable()
{
$search = Input::get('sSearch');
$invitationKey = Session::get('invitation_key');
$invitation = Invitation::where('invitation_key', '=', $invitationKey)->first();
if (!$invitation || $invitation->is_deleted)
{
return [];
} }
$invoice = $invitation->invoice; public function getDatatable($clientPublicId = null)
if (!$invoice || $invoice->is_deleted)
{ {
return []; $accountId = Auth::user()->account_id;
$search = Input::get('sSearch');
return $this->invoiceRepo->getDatatable($accountId, $clientPublicId, ENTITY_QUOTE, $search);
} }
return $this->invoiceRepo->getClientDatatable($invitation->contact_id, ENTITY_QUOTE, $search); public function getClientDatatable()
}
public function create($clientPublicId = 0)
{
if (!Utils::isPro())
{ {
return Redirect::to('/invoices/create'); $search = Input::get('sSearch');
$invitationKey = Session::get('invitation_key');
$invitation = Invitation::where('invitation_key', '=', $invitationKey)->first();
if (!$invitation || $invitation->is_deleted) {
return [];
}
$invoice = $invitation->invoice;
if (!$invoice || $invoice->is_deleted) {
return [];
}
return $this->invoiceRepo->getClientDatatable($invitation->contact_id, ENTITY_QUOTE, $search);
} }
$client = null; public function create($clientPublicId = 0)
$invoiceNumber = Auth::user()->account->getNextInvoiceNumber(true);
$account = Account::with('country')->findOrFail(Auth::user()->account_id);
if ($clientPublicId)
{ {
$client = Client::scope($clientPublicId)->firstOrFail(); if (!Utils::isPro()) {
} return Redirect::to('/invoices/create');
}
$data = array( $client = null;
$invoiceNumber = Auth::user()->account->getNextInvoiceNumber(true);
$account = Account::with('country')->findOrFail(Auth::user()->account_id);
if ($clientPublicId) {
$client = Client::scope($clientPublicId)->firstOrFail();
}
$data = array(
'account' => $account, 'account' => $account,
'invoice' => null, 'invoice' => null,
'data' => Input::old('data'), 'data' => Input::old('data'),
'invoiceNumber' => $invoiceNumber, 'invoiceNumber' => $invoiceNumber,
'method' => 'POST', 'method' => 'POST',
'url' => 'invoices', 'url' => 'invoices',
'title' => trans('texts.new_quote'), 'title' => trans('texts.new_quote'),
'client' => $client); 'client' => $client, );
$data = array_merge($data, self::getViewModel()); $data = array_merge($data, self::getViewModel());
return View::make('invoices.edit', $data); return View::make('invoices.edit', $data);
} }
private static function getViewModel() private static function getViewModel()
{ {
return [ return [
'entityType' => ENTITY_QUOTE, 'entityType' => ENTITY_QUOTE,
'account' => Auth::user()->account, 'account' => Auth::user()->account,
'products' => Product::scope()->orderBy('id')->get(array('product_key','notes','cost','qty')), 'products' => Product::scope()->orderBy('id')->get(array('product_key', 'notes', 'cost', 'qty')),
'countries' => Country::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(), 'countries' => Country::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(),
'clients' => Client::scope()->with('contacts', 'country')->orderBy('name')->get(), 'clients' => Client::scope()->with('contacts', 'country')->orderBy('name')->get(),
'taxRates' => TaxRate::scope()->orderBy('name')->get(), 'taxRates' => TaxRate::scope()->orderBy('name')->get(),
'currencies' => Currency::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(), 'currencies' => Currency::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(),
'sizes' => Size::remember(DEFAULT_QUERY_CACHE)->orderBy('id')->get(), 'sizes' => Size::remember(DEFAULT_QUERY_CACHE)->orderBy('id')->get(),
'paymentTerms' => PaymentTerm::remember(DEFAULT_QUERY_CACHE)->orderBy('num_days')->get(['name', 'num_days']), 'paymentTerms' => PaymentTerm::remember(DEFAULT_QUERY_CACHE)->orderBy('num_days')->get(['name', 'num_days']),
'industries' => Industry::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(), 'industries' => Industry::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(),
'invoiceDesigns' => InvoiceDesign::remember(DEFAULT_QUERY_CACHE, 'invoice_designs_cache_'.Auth::user()->maxInvoiceDesignId()) 'invoiceDesigns' => InvoiceDesign::remember(DEFAULT_QUERY_CACHE, 'invoice_designs_cache_'.Auth::user()->maxInvoiceDesignId())
->where('id', '<=', Auth::user()->maxInvoiceDesignId())->orderBy('id')->get(), ->where('id', '<=', Auth::user()->maxInvoiceDesignId())->orderBy('id')->get(),
'invoiceLabels' => Auth::user()->account->getInvoiceLabels() 'invoiceLabels' => Auth::user()->account->getInvoiceLabels()
]; ];
}
public function bulk()
{
$action = Input::get('action');
$statusId = Input::get('statusId');
$ids = Input::get('id') ? Input::get('id') : Input::get('ids');
$count = $this->invoiceRepo->bulk($ids, $action, $statusId);
if ($count > 0)
{
$key = $action == 'mark' ? "updated_quote" : "{$action}d_quote";
$message = Utils::pluralize($key, $count);
Session::flash('message', $message);
} }
return Redirect::to('quotes'); public function bulk()
} {
} $action = Input::get('action');
$statusId = Input::get('statusId');
$ids = Input::get('id') ? Input::get('id') : Input::get('ids');
$count = $this->invoiceRepo->bulk($ids, $action, $statusId);
if ($count > 0) {
$key = $action == 'mark' ? "updated_quote" : "{$action}d_quote";
$message = Utils::pluralize($key, $count);
Session::flash('message', $message);
}
return Redirect::to('quotes');
}
}

View File

@ -1,136 +1,127 @@
<?php <?php
class ReportController extends \BaseController { class ReportController extends \BaseController
{
public function d3()
{
$message = '';
public function d3() if (Auth::user()->account->isPro()) {
{ $account = Account::where('id', '=', Auth::user()->account->id)->with(['clients.invoices.invoice_items', 'clients.contacts'])->first();
$message = ''; $account = $account->hideFieldsForViz();
$clients = $account->clients->toJson();
} elseif (isset($_ENV['DATA_VIZ_SAMPLE'])) {
$clients = $_ENV['DATA_VIZ_SAMPLE'];
$message = trans('texts.sample_data');
} else {
$clients = '[]';
}
if (Auth::user()->account->isPro()) { $data = [
$account = Account::where('id', '=', Auth::user()->account->id)->with(['clients.invoices.invoice_items', 'clients.contacts'])->first(); 'feature' => ACCOUNT_DATA_VISUALIZATIONS,
$account = $account->hideFieldsForViz(); 'clients' => $clients,
$clients = $account->clients->toJson(); 'message' => $message,
} else if (isset($_ENV['DATA_VIZ_SAMPLE'])) { ];
$clients = $_ENV['DATA_VIZ_SAMPLE'];
$message = trans('texts.sample_data');
} else {
$clients = '[]';
}
$data = [ return View::make('reports.d3', $data);
'feature' => ACCOUNT_DATA_VISUALIZATIONS, }
'clients' => $clients,
'message' => $message
];
return View::make('reports.d3', $data); public function report()
} {
if (Input::all()) {
$groupBy = Input::get('group_by');
$chartType = Input::get('chart_type');
$startDate = Utils::toSqlDate(Input::get('start_date'), false);
$endDate = Utils::toSqlDate(Input::get('end_date'), false);
} else {
$groupBy = 'MONTH';
$chartType = 'Bar';
$startDate = Utils::today(false)->modify('-3 month');
$endDate = Utils::today(false);
}
public function report() $padding = $groupBy == 'DAYOFYEAR' ? 'day' : ($groupBy == 'WEEK' ? 'week' : 'month');
{ $endDate->modify('+1 '.$padding);
if (Input::all()) $datasets = [];
{ $labels = [];
$groupBy = Input::get('group_by'); $maxTotals = 0;
$chartType = Input::get('chart_type'); $width = 10;
$startDate = Utils::toSqlDate(Input::get('start_date'), false);
$endDate = Utils::toSqlDate(Input::get('end_date'), false);
}
else
{
$groupBy = 'MONTH';
$chartType = 'Bar';
$startDate = Utils::today(false)->modify('-3 month');
$endDate = Utils::today(false);
}
$padding = $groupBy == 'DAYOFYEAR' ? 'day' : ($groupBy == 'WEEK' ? 'week' : 'month'); if (Auth::user()->account->isPro()) {
$endDate->modify('+1 '.$padding); foreach ([ENTITY_INVOICE, ENTITY_PAYMENT, ENTITY_CREDIT] as $entityType) {
$datasets = []; $records = DB::table($entityType.'s')
$labels = []; ->select(DB::raw('sum(amount) as total, '.$groupBy.'('.$entityType.'_date) as '.$groupBy))
$maxTotals = 0; ->where('account_id', '=', Auth::user()->account_id)
$width = 10; ->where($entityType.'s.deleted_at', '=', null)
->where($entityType.'s.'.$entityType.'_date', '>=', $startDate->format('Y-m-d'))
if (Auth::user()->account->isPro()) ->where($entityType.'s.'.$entityType.'_date', '<=', $endDate->format('Y-m-d'))
{ ->groupBy($groupBy);
foreach ([ENTITY_INVOICE, ENTITY_PAYMENT, ENTITY_CREDIT] as $entityType)
{
$records = DB::table($entityType.'s')
->select(DB::raw('sum(amount) as total, '.$groupBy.'('.$entityType.'_date) as '.$groupBy))
->where('account_id', '=', Auth::user()->account_id)
->where($entityType.'s.deleted_at', '=', null)
->where($entityType.'s.'.$entityType.'_date', '>=', $startDate->format('Y-m-d'))
->where($entityType.'s.'.$entityType.'_date', '<=', $endDate->format('Y-m-d'))
->groupBy($groupBy);
if ($entityType == ENTITY_INVOICE)
{
$records->where('is_quote', '=', false)
->where('is_recurring', '=', false);
}
$totals = $records->lists('total'); if ($entityType == ENTITY_INVOICE) {
$dates = $records->lists($groupBy); $records->where('is_quote', '=', false)
$data = array_combine($dates, $totals); ->where('is_recurring', '=', false);
}
$interval = new DateInterval('P1'.substr($groupBy, 0, 1));
$period = new DatePeriod($startDate, $interval, $endDate);
$totals = []; $totals = $records->lists('total');
$dates = $records->lists($groupBy);
$data = array_combine($dates, $totals);
foreach ($period as $d) $interval = new DateInterval('P1'.substr($groupBy, 0, 1));
{ $period = new DatePeriod($startDate, $interval, $endDate);
$dateFormat = $groupBy == 'DAYOFYEAR' ? 'z' : ($groupBy == 'WEEK' ? 'W' : 'n');
$date = $d->format($dateFormat);
$totals[] = isset($data[$date]) ? $data[$date] : 0;
if ($entityType == ENTITY_INVOICE) $totals = [];
{
$labelFormat = $groupBy == 'DAYOFYEAR' ? 'j' : ($groupBy == 'WEEK' ? 'W' : 'F');
$label = $d->format($labelFormat);
$labels[] = $label;
}
}
$max = max($totals); foreach ($period as $d) {
$dateFormat = $groupBy == 'DAYOFYEAR' ? 'z' : ($groupBy == 'WEEK' ? 'W' : 'n');
$date = $d->format($dateFormat);
$totals[] = isset($data[$date]) ? $data[$date] : 0;
if ($max > 0) if ($entityType == ENTITY_INVOICE) {
{ $labelFormat = $groupBy == 'DAYOFYEAR' ? 'j' : ($groupBy == 'WEEK' ? 'W' : 'F');
$datasets[] = [ $label = $d->format($labelFormat);
'totals' => $totals, $labels[] = $label;
'colors' => $entityType == ENTITY_INVOICE ? '78,205,196' : ($entityType == ENTITY_CREDIT ? '199,244,100' : '255,107,107') }
]; }
$maxTotals = max($max, $maxTotals);
}
}
$width = (ceil( $maxTotals / 100 ) * 100) / 10; $max = max($totals);
$width = max($width, 10);
}
$dateTypes = [ if ($max > 0) {
'DAYOFYEAR' => 'Daily', $datasets[] = [
'WEEK' => 'Weekly', 'totals' => $totals,
'MONTH' => 'Monthly' 'colors' => $entityType == ENTITY_INVOICE ? '78,205,196' : ($entityType == ENTITY_CREDIT ? '199,244,100' : '255,107,107'),
]; ];
$maxTotals = max($max, $maxTotals);
}
}
$chartTypes = [ $width = (ceil($maxTotals / 100) * 100) / 10;
'Bar' => 'Bar', $width = max($width, 10);
'Line' => 'Line' }
];
$params = [ $dateTypes = [
'labels' => $labels, 'DAYOFYEAR' => 'Daily',
'datasets' => $datasets, 'WEEK' => 'Weekly',
'scaleStepWidth' => $width, 'MONTH' => 'Monthly',
'dateTypes' => $dateTypes, ];
'chartTypes' => $chartTypes,
'chartType' => $chartType, $chartTypes = [
'startDate' => $startDate->format(Session::get(SESSION_DATE_FORMAT)), 'Bar' => 'Bar',
'endDate' => $endDate->modify('-1'.$padding)->format(Session::get(SESSION_DATE_FORMAT)), 'Line' => 'Line',
'groupBy' => $groupBy, ];
'feature' => ACCOUNT_CHART_BUILDER,
]; $params = [
'labels' => $labels,
return View::make('reports.report_builder', $params); 'datasets' => $datasets,
} 'scaleStepWidth' => $width,
} 'dateTypes' => $dateTypes,
'chartTypes' => $chartTypes,
'chartType' => $chartType,
'startDate' => $startDate->format(Session::get(SESSION_DATE_FORMAT)),
'endDate' => $endDate->modify('-1'.$padding)->format(Session::get(SESSION_DATE_FORMAT)),
'groupBy' => $groupBy,
'feature' => ACCOUNT_CHART_BUILDER,
];
return View::make('reports.report_builder', $params);
}
}

View File

@ -13,8 +13,8 @@ use ninja\repositories\AccountRepository;
use ninja\mailers\ContactMailer; use ninja\mailers\ContactMailer;
use ninja\mailers\UserMailer; use ninja\mailers\UserMailer;
class UserController extends BaseController { class UserController extends BaseController
{
protected $accountRepo; protected $accountRepo;
protected $contactMailer; protected $contactMailer;
protected $userMailer; protected $userMailer;
@ -26,36 +26,34 @@ class UserController extends BaseController {
$this->accountRepo = $accountRepo; $this->accountRepo = $accountRepo;
$this->contactMailer = $contactMailer; $this->contactMailer = $contactMailer;
$this->userMailer = $userMailer; $this->userMailer = $userMailer;
} }
public function getDatatable() public function getDatatable()
{ {
$query = DB::table('users') $query = DB::table('users')
->where('users.account_id', '=', Auth::user()->account_id) ->where('users.account_id', '=', Auth::user()->account_id)
->where('users.deleted_at', '=', null) ->where('users.deleted_at', '=', null)
->where('users.public_id', '>', 0) ->where('users.public_id', '>', 0)
->select('users.public_id', 'users.first_name', 'users.last_name', 'users.email', 'users.confirmed', 'users.public_id'); ->select('users.public_id', 'users.first_name', 'users.last_name', 'users.email', 'users.confirmed', 'users.public_id');
return Datatable::query($query)
return Datatable::query($query) ->addColumn('first_name', function ($model) { return link_to('users/'.$model->public_id.'/edit', $model->first_name.' '.$model->last_name); })
->addColumn('first_name', function($model) { return link_to('users/' . $model->public_id . '/edit', $model->first_name . ' ' . $model->last_name); }) ->addColumn('email', function ($model) { return $model->email; })
->addColumn('email', function($model) { return $model->email; }) ->addColumn('confirmed', function ($model) { return $model->confirmed ? trans('texts.active') : trans('texts.pending'); })
->addColumn('confirmed', function($model) { return $model->confirmed ? trans('texts.active') : trans('texts.pending'); }) ->addColumn('dropdown', function ($model) {
->addColumn('dropdown', function($model)
{
return '<div class="btn-group tr-action" style="visibility:hidden;"> return '<div class="btn-group tr-action" style="visibility:hidden;">
<button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown"> <button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown">
'.trans('texts.select').' <span class="caret"></span> '.trans('texts.select').' <span class="caret"></span>
</button> </button>
<ul class="dropdown-menu" role="menu"> <ul class="dropdown-menu" role="menu">
<li><a href="' . URL::to('users/'.$model->public_id) . '/edit">'.uctrans('texts.edit_user').'</a></li> <li><a href="'.URL::to('users/'.$model->public_id).'/edit">'.uctrans('texts.edit_user').'</a></li>
<li class="divider"></li> <li class="divider"></li>
<li><a href="javascript:deleteUser(' . $model->public_id. ')">'.uctrans('texts.delete_user').'</a></li> <li><a href="javascript:deleteUser('.$model->public_id.')">'.uctrans('texts.delete_user').'</a></li>
</ul> </ul>
</div>'; </div>';
}) })
->orderColumns(['first_name', 'email', 'confirmed']) ->orderColumns(['first_name', 'email', 'confirmed'])
->make(); ->make();
} }
public function setTheme() public function setTheme()
@ -63,7 +61,7 @@ class UserController extends BaseController {
$user = User::find(Auth::user()->id); $user = User::find(Auth::user()->id);
$user->theme_id = Input::get('theme_id'); $user->theme_id = Input::get('theme_id');
$user->save(); $user->save();
return Redirect::to(Input::get('path')); return Redirect::to(Input::get('path'));
} }
@ -75,7 +73,7 @@ class UserController extends BaseController {
Session::flash('message', trans('texts.confide.updated_settings')); Session::flash('message', trans('texts.confide.updated_settings'));
return Redirect::to('/dashboard'); return Redirect::to('/dashboard');
} }
public function edit($publicId) public function edit($publicId)
@ -86,12 +84,12 @@ class UserController extends BaseController {
$data = [ $data = [
'showBreadcrumbs' => false, 'showBreadcrumbs' => false,
'user' => $user, 'user' => $user,
'method' => 'PUT', 'method' => 'PUT',
'url' => 'users/' . $publicId, 'url' => 'users/'.$publicId,
'title' => trans('texts.edit_user') 'title' => trans('texts.edit_user'),
]; ];
return View::make('users.edit', $data); return View::make('users.edit', $data);
} }
public function update($publicId) public function update($publicId)
@ -110,30 +108,29 @@ class UserController extends BaseController {
*/ */
public function create() public function create()
{ {
if (!Auth::user()->confirmed) if (!Auth::user()->confirmed) {
{ Session::flash('error', trans('texts.register_to_add_user'));
Session::flash('error', trans('texts.register_to_add_user'));
return Redirect::to('company/advanced_settings/user_management'); return Redirect::to('company/advanced_settings/user_management');
} }
if (Utils::isNinja()) if (Utils::isNinja()) {
{
$count = User::where('account_id', '=', Auth::user()->account_id)->count(); $count = User::where('account_id', '=', Auth::user()->account_id)->count();
if ($count >= MAX_NUM_USERS) if ($count >= MAX_NUM_USERS) {
{
Session::flash('error', trans('texts.limit_users')); Session::flash('error', trans('texts.limit_users'));
return Redirect::to('company/advanced_settings/user_management');
} return Redirect::to('company/advanced_settings/user_management');
}
} }
$data = [ $data = [
'showBreadcrumbs' => false, 'showBreadcrumbs' => false,
'user' => null, 'user' => null,
'method' => 'POST', 'method' => 'POST',
'url' => 'users', 'url' => 'users',
'title' => trans('texts.add_user') 'title' => trans('texts.add_user'),
]; ];
return View::make('users.edit', $data); return View::make('users.edit', $data);
} }
@ -146,7 +143,8 @@ class UserController extends BaseController {
$user->delete(); $user->delete();
Session::flash('message', trans('texts.deleted_user')); Session::flash('message', trans('texts.deleted_user'));
return Redirect::to('company/advanced_settings/user_management');
return Redirect::to('company/advanced_settings/user_management');
} }
/** /**
@ -160,38 +158,31 @@ class UserController extends BaseController {
'last_name' => 'required', 'last_name' => 'required',
]; ];
if ($userPublicId) if ($userPublicId) {
{
$user = User::where('account_id', '=', Auth::user()->account_id) $user = User::where('account_id', '=', Auth::user()->account_id)
->where('public_id', '=', $userPublicId)->firstOrFail(); ->where('public_id', '=', $userPublicId)->firstOrFail();
$rules['email'] = 'required|email|unique:users,email,' . $user->id . ',id'; $rules['email'] = 'required|email|unique:users,email,'.$user->id.',id';
} } else {
else
{
$rules['email'] = 'required|email|unique:users'; $rules['email'] = 'required|email|unique:users';
} }
$validator = Validator::make(Input::all(), $rules); $validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) if ($validator->fails()) {
{
return Redirect::to($userPublicId ? 'users/edit' : 'users/create')->withInput()->withErrors($validator); return Redirect::to($userPublicId ? 'users/edit' : 'users/create')->withInput()->withErrors($validator);
} }
if ($userPublicId) if ($userPublicId) {
{
$user->first_name = trim(Input::get('first_name')); $user->first_name = trim(Input::get('first_name'));
$user->last_name = trim(Input::get('last_name')); $user->last_name = trim(Input::get('last_name'));
$user->username = trim(Input::get('email')); $user->username = trim(Input::get('email'));
$user->email = trim(Input::get('email')); $user->email = trim(Input::get('email'));
} } else {
else
{
$lastUser = User::withTrashed()->where('account_id', '=', Auth::user()->account_id) $lastUser = User::withTrashed()->where('account_id', '=', Auth::user()->account_id)
->orderBy('public_id', 'DESC')->first(); ->orderBy('public_id', 'DESC')->first();
$user = new User; $user = new User();
$user->account_id = Auth::user()->account_id; $user->account_id = Auth::user()->account_id;
$user->first_name = trim(Input::get('first_name')); $user->first_name = trim(Input::get('first_name'));
$user->last_name = trim(Input::get('last_name')); $user->last_name = trim(Input::get('last_name'));
@ -200,18 +191,15 @@ class UserController extends BaseController {
$user->registered = true; $user->registered = true;
$user->password = str_random(RANDOM_KEY_LENGTH); $user->password = str_random(RANDOM_KEY_LENGTH);
$user->password_confirmation = $user->password; $user->password_confirmation = $user->password;
$user->public_id = $lastUser->public_id + 1; $user->public_id = $lastUser->public_id + 1;
} }
$user->save(); $user->save();
if (!$user->confirmed) if (!$user->confirmed) {
{ $this->userMailer->sendConfirmation($user, Auth::user());
$this->userMailer->sendConfirmation($user, Auth::user());
$message = trans('texts.sent_invite'); $message = trans('texts.sent_invite');
} } else {
else
{
$message = trans('texts.updated_user'); $message = trans('texts.updated_user');
} }
@ -226,16 +214,15 @@ class UserController extends BaseController {
*/ */
public function login() public function login()
{ {
if( Confide::user() ) if (Confide::user()) {
{ Event::fire('user.login');
Event::fire('user.login');
Session::reflash(); Session::reflash();
return Redirect::to('/dashboard'); return Redirect::to('/dashboard');
/* /*
$invoice = Invoice::scope()->orderBy('id', 'desc')->first(); $invoice = Invoice::scope()->orderBy('id', 'desc')->first();
if ($invoice) if ($invoice)
{ {
return Redirect::to('/invoices/' . $invoice->public_id); return Redirect::to('/invoices/' . $invoice->public_id);
@ -245,9 +232,7 @@ class UserController extends BaseController {
return Redirect::to('/dashboard'); return Redirect::to('/dashboard');
} }
*/ */
} } else {
else
{
return View::make(Config::get('confide::login_form')); return View::make(Config::get('confide::login_form'));
} }
} }
@ -259,9 +244,9 @@ class UserController extends BaseController {
public function do_login() public function do_login()
{ {
$input = array( $input = array(
'email' => Input::get( 'login_email' ), // May be the username too 'email' => Input::get('login_email'), // May be the username too
'username' => Input::get( 'login_email' ), // so we have to pass both 'username' => Input::get('login_email'), // so we have to pass both
'password' => Input::get( 'login_password' ), 'password' => Input::get('login_password'),
'remember' => true, 'remember' => true,
); );
@ -269,22 +254,18 @@ class UserController extends BaseController {
// with the second parameter as true. // with the second parameter as true.
// logAttempt will check if the 'email' perhaps is the username. // logAttempt will check if the 'email' perhaps is the username.
// Get the value from the config file instead of changing the controller // Get the value from the config file instead of changing the controller
if ( Input::get( 'login_email' ) && Confide::logAttempt( $input, false ) ) if (Input::get('login_email') && Confide::logAttempt($input, false)) {
{
Event::fire('user.login'); Event::fire('user.login');
// Redirect the user to the URL they were trying to access before // Redirect the user to the URL they were trying to access before
// caught by the authentication filter IE Redirect::guest('user/login'). // caught by the authentication filter IE Redirect::guest('user/login').
// Otherwise fallback to '/' // Otherwise fallback to '/'
// Fix pull #145 // Fix pull #145
return Redirect::intended('/dashboard'); // change it to '/admin', '/dashboard' or something return Redirect::intended('/dashboard'); // change it to '/admin', '/dashboard' or something
} } else {
else
{
//$user = new User; //$user = new User;
// Check if there was too many login attempts // Check if there was too many login attempts
if( Confide::isThrottled( $input ) ) if (Confide::isThrottled($input)) {
{
$err_msg = trans('texts.confide.too_many_attempts'); $err_msg = trans('texts.confide.too_many_attempts');
} }
/* /*
@ -293,56 +274,48 @@ class UserController extends BaseController {
$err_msg = Lang::get('confide::confide.alerts.not_confirmed'); $err_msg = Lang::get('confide::confide.alerts.not_confirmed');
} }
*/ */
else else {
{
$err_msg = trans('texts.confide.wrong_credentials'); $err_msg = trans('texts.confide.wrong_credentials');
} }
return Redirect::action('UserController@login') return Redirect::action('UserController@login')
->withInput(Input::except('login_password')) ->withInput(Input::except('login_password'))
->with( 'error', $err_msg ); ->with('error', $err_msg);
} }
} }
/** /**
* Attempt to confirm account with code * Attempt to confirm account with code
* *
* @param string $code * @param string $code
*/ */
public function confirm( $code ) public function confirm($code)
{ {
if ( Confide::confirm( $code ) ) if (Confide::confirm($code)) {
{
$notice_msg = trans('texts.confide.confirmation'); $notice_msg = trans('texts.confide.confirmation');
$user = User::where('confirmation_code', '=', $code)->get()->first(); $user = User::where('confirmation_code', '=', $code)->get()->first();
$user->confirmation_code = ''; $user->confirmation_code = '';
$user->save(); $user->save();
if ($user->public_id) if ($user->public_id) {
{
Auth::login($user); Auth::login($user);
return Redirect::to('user/reset'); return Redirect::to('user/reset');
} } else {
else if (Session::has(REQUESTED_PRO_PLAN)) {
{ Session::forget(REQUESTED_PRO_PLAN);
if (Session::has(REQUESTED_PRO_PLAN))
{
Session::forget(REQUESTED_PRO_PLAN);
$invitation = $this->accountRepo->enableProPlan(); $invitation = $this->accountRepo->enableProPlan();
return Redirect::to($invitation->getLink()); return Redirect::to($invitation->getLink());
} } else {
else return Redirect::action('UserController@login')->with('message', $notice_msg);
{
return Redirect::action('UserController@login')->with( 'message', $notice_msg );
} }
} }
} } else {
else
{
$error_msg = trans('texts.confide.wrong_confirmation'); $error_msg = trans('texts.confide.wrong_confirmation');
return Redirect::action('UserController@login')->with( 'error', $error_msg );
return Redirect::action('UserController@login')->with('error', $error_msg);
} }
} }
@ -361,12 +334,12 @@ class UserController extends BaseController {
*/ */
public function do_forgot_password() public function do_forgot_password()
{ {
Confide::forgotPassword( Input::get( 'email' ) ); Confide::forgotPassword(Input::get('email'));
$notice_msg = trans('texts.confide.password_forgot'); $notice_msg = trans('texts.confide.password_forgot');
return Redirect::action('UserController@login')
->with( 'notice', $notice_msg );
return Redirect::action('UserController@login')
->with('notice', $notice_msg);
/* /*
if( Confide::forgotPassword( Input::get( 'email' ) ) ) if( Confide::forgotPassword( Input::get( 'email' ) ) )
@ -389,7 +362,7 @@ class UserController extends BaseController {
* Shows the change password form with the given token * Shows the change password form with the given token
* *
*/ */
public function reset_password( $token = false ) public function reset_password($token = false)
{ {
return View::make(Config::get('confide::reset_password_form')) return View::make(Config::get('confide::reset_password_form'))
->with('token', $token); ->with('token', $token);
@ -400,49 +373,45 @@ class UserController extends BaseController {
* *
*/ */
public function do_reset_password() public function do_reset_password()
{ {
if (Auth::check()) if (Auth::check()) {
{
$rules = [ $rules = [
'password' => 'required|between:4,11|confirmed', 'password' => 'required|between:4,11|confirmed',
'password_confirmation' => 'between:4,11', 'password_confirmation' => 'between:4,11',
]; ];
$validator = Validator::make(Input::all(), $rules); $validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) if ($validator->fails()) {
{
return Redirect::to('user/reset')->withInput()->withErrors($validator); return Redirect::to('user/reset')->withInput()->withErrors($validator);
} }
$user = Auth::user(); $user = Auth::user();
$user->password = Input::get('password'); $user->password = Input::get('password');
$user->save(); $user->save();
Session::flash('message', trans('texts.confide.password_reset')); Session::flash('message', trans('texts.confide.password_reset'));
return Redirect::to('/dashboard'); return Redirect::to('/dashboard');
} } else {
else
{
$input = array( $input = array(
'token'=>Input::get( 'token' ), 'token' => Input::get('token'),
'password'=>Input::get( 'password' ), 'password' => Input::get('password'),
'password_confirmation'=>Input::get( 'password_confirmation' ), 'password_confirmation' => Input::get('password_confirmation'),
); );
// By passing an array with the token, password and confirmation // By passing an array with the token, password and confirmation
if( Confide::resetPassword( $input ) ) if (Confide::resetPassword($input)) {
{
$notice_msg = trans('texts.confide.password_reset'); $notice_msg = trans('texts.confide.password_reset');
return Redirect::action('UserController@login') return Redirect::action('UserController@login')
->with( 'notice', $notice_msg ); ->with('notice', $notice_msg);
} } else {
else
{
$error_msg = trans('texts.confide.wrong_password_reset'); $error_msg = trans('texts.confide.wrong_password_reset');
return Redirect::action('UserController@reset_password', array('token'=>$input['token']))
return Redirect::action('UserController@reset_password', array('token' => $input['token']))
->withInput() ->withInput()
->with( 'error', $error_msg ); ->with('error', $error_msg);
} }
} }
} }
@ -452,10 +421,8 @@ class UserController extends BaseController {
*/ */
public function logout() public function logout()
{ {
if (Auth::check()) if (Auth::check()) {
{ if (!Auth::user()->registered) {
if (!Auth::user()->registered)
{
$account = Auth::user()->account; $account = Auth::user()->account;
$account->forceDelete(); $account->forceDelete();
} }

View File

@ -2,155 +2,148 @@
class Account extends Eloquent class Account extends Eloquent
{ {
protected $softDelete = true; protected $softDelete = true;
public function users() public function users()
{ {
return $this->hasMany('User'); return $this->hasMany('User');
} }
public function clients() public function clients()
{ {
return $this->hasMany('Client'); return $this->hasMany('Client');
} }
public function invoices() public function invoices()
{ {
return $this->hasMany('Invoice'); return $this->hasMany('Invoice');
} }
public function account_gateways() public function account_gateways()
{ {
return $this->hasMany('AccountGateway'); return $this->hasMany('AccountGateway');
} }
public function tax_rates() public function tax_rates()
{ {
return $this->hasMany('TaxRate'); return $this->hasMany('TaxRate');
} }
public function country() public function country()
{ {
return $this->belongsTo('Country'); return $this->belongsTo('Country');
} }
public function timezone() public function timezone()
{ {
return $this->belongsTo('Timezone'); return $this->belongsTo('Timezone');
} }
public function language() public function language()
{ {
return $this->belongsTo('Language'); return $this->belongsTo('Language');
} }
public function date_format() public function date_format()
{ {
return $this->belongsTo('DateFormat'); return $this->belongsTo('DateFormat');
} }
public function datetime_format() public function datetime_format()
{ {
return $this->belongsTo('DatetimeFormat'); return $this->belongsTo('DatetimeFormat');
} }
public function size() public function size()
{ {
return $this->belongsTo('Size'); return $this->belongsTo('Size');
} }
public function industry() public function industry()
{ {
return $this->belongsTo('Industry'); return $this->belongsTo('Industry');
} }
public function isGatewayConfigured($gatewayId = 0) public function isGatewayConfigured($gatewayId = 0)
{ {
$this->load('account_gateways'); $this->load('account_gateways');
if ($gatewayId) if ($gatewayId) {
{ return $this->getGatewayConfig($gatewayId) != false;
return $this->getGatewayConfig($gatewayId) != false; } else {
} return count($this->account_gateways) > 0;
else }
{ }
return count($this->account_gateways) > 0;
}
}
public function getDisplayName() public function getDisplayName()
{ {
if ($this->name) if ($this->name) {
{ return $this->name;
return $this->name; }
}
$this->load('users'); $this->load('users');
$user = $this->users()->first(); $user = $this->users()->first();
return $user->getDisplayName();
}
public function getTimezone() return $user->getDisplayName();
{ }
if ($this->timezone)
{
return $this->timezone->name;
}
else
{
return 'US/Eastern';
}
}
public function getGatewayConfig($gatewayId) public function getTimezone()
{ {
foreach ($this->account_gateways as $gateway) if ($this->timezone) {
{ return $this->timezone->name;
if ($gateway->gateway_id == $gatewayId) } else {
{ return 'US/Eastern';
return $gateway; }
} }
}
return false; public function getGatewayConfig($gatewayId)
} {
foreach ($this->account_gateways as $gateway) {
if ($gateway->gateway_id == $gatewayId) {
return $gateway;
}
}
public function getLogoPath() return false;
{ }
return 'logo/' . $this->account_key . '.jpg';
}
public function getLogoWidth() public function getLogoPath()
{ {
$path = $this->getLogoPath(); return 'logo/'.$this->account_key.'.jpg';
if (!file_exists($path)) { }
return 0;
}
list($width, $height) = getimagesize($path);
return $width;
}
public function getLogoHeight() public function getLogoWidth()
{ {
$path = $this->getLogoPath(); $path = $this->getLogoPath();
if (!file_exists($path)) { if (!file_exists($path)) {
return 0; return 0;
} }
list($width, $height) = getimagesize($path); list($width, $height) = getimagesize($path);
return $height;
}
public function getNextInvoiceNumber($isQuote = false) return $width;
{ }
$counter = $isQuote && !$this->share_counter ? $this->quote_number_counter : $this->invoice_number_counter;
$prefix = $isQuote ? $this->quote_number_prefix : $this->invoice_number_prefix;
return $prefix . str_pad($counter, 4, "0", STR_PAD_LEFT); public function getLogoHeight()
} {
$path = $this->getLogoPath();
if (!file_exists($path)) {
return 0;
}
list($width, $height) = getimagesize($path);
public function incrementCounter($invoiceNumber, $isQuote = false, $isRecurring) return $height;
{ }
public function getNextInvoiceNumber($isQuote = false)
{
$counter = $isQuote && !$this->share_counter ? $this->quote_number_counter : $this->invoice_number_counter;
$prefix = $isQuote ? $this->quote_number_prefix : $this->invoice_number_prefix;
return $prefix.str_pad($counter, 4, "0", STR_PAD_LEFT);
}
public function incrementCounter($invoiceNumber, $isQuote = false, $isRecurring)
{
// check if the user modified the invoice number // check if the user modified the invoice number
if (!$isRecurring && $invoiceNumber != $this->getNextInvoiceNumber($isQuote)) { if (!$isRecurring && $invoiceNumber != $this->getNextInvoiceNumber($isQuote)) {
$number = intval(preg_replace('/[^0-9]/', '', $invoiceNumber)); $number = intval(preg_replace('/[^0-9]/', '', $invoiceNumber));
@ -169,155 +162,144 @@ class Account extends Eloquent
} }
$this->save(); $this->save();
} }
public function getLocale()
{
$language = Language::remember(DEFAULT_QUERY_CACHE)->where('id', '=', $this->account->language_id)->first();
return $language->locale;
}
public function loadLocalizationSettings() public function getLocale()
{ {
$this->load('timezone', 'date_format', 'datetime_format', 'language'); $language = Language::remember(DEFAULT_QUERY_CACHE)->where('id', '=', $this->account->language_id)->first();
Session::put(SESSION_TIMEZONE, $this->timezone ? $this->timezone->name : DEFAULT_TIMEZONE); return $language->locale;
Session::put(SESSION_DATE_FORMAT, $this->date_format ? $this->date_format->format : DEFAULT_DATE_FORMAT); }
Session::put(SESSION_DATE_PICKER_FORMAT, $this->date_format ? $this->date_format->picker_format : DEFAULT_DATE_PICKER_FORMAT);
Session::put(SESSION_DATETIME_FORMAT, $this->datetime_format ? $this->datetime_format->format : DEFAULT_DATETIME_FORMAT);
Session::put(SESSION_CURRENCY, $this->currency_id ? $this->currency_id : DEFAULT_CURRENCY);
Session::put(SESSION_LOCALE, $this->language_id ? $this->language->locale : DEFAULT_LOCALE);
}
public function getInvoiceLabels() public function loadLocalizationSettings()
{ {
$data = []; $this->load('timezone', 'date_format', 'datetime_format', 'language');
$fields = [
'invoice',
'invoice_date',
'due_date',
'invoice_number',
'po_number',
'discount',
'taxes',
'tax',
'item',
'description',
'unit_cost',
'quantity',
'line_total',
'subtotal',
'paid_to_date',
'balance_due',
'terms',
'your_invoice',
'quote',
'your_quote',
'quote_date',
'quote_number',
'total',
'invoice_issued_to',
];
foreach ($fields as $field) Session::put(SESSION_TIMEZONE, $this->timezone ? $this->timezone->name : DEFAULT_TIMEZONE);
{ Session::put(SESSION_DATE_FORMAT, $this->date_format ? $this->date_format->format : DEFAULT_DATE_FORMAT);
$data[$field] = trans("texts.$field"); Session::put(SESSION_DATE_PICKER_FORMAT, $this->date_format ? $this->date_format->picker_format : DEFAULT_DATE_PICKER_FORMAT);
} Session::put(SESSION_DATETIME_FORMAT, $this->datetime_format ? $this->datetime_format->format : DEFAULT_DATETIME_FORMAT);
Session::put(SESSION_CURRENCY, $this->currency_id ? $this->currency_id : DEFAULT_CURRENCY);
Session::put(SESSION_LOCALE, $this->language_id ? $this->language->locale : DEFAULT_LOCALE);
}
return $data; public function getInvoiceLabels()
} {
$data = [];
$fields = [
'invoice',
'invoice_date',
'due_date',
'invoice_number',
'po_number',
'discount',
'taxes',
'tax',
'item',
'description',
'unit_cost',
'quantity',
'line_total',
'subtotal',
'paid_to_date',
'balance_due',
'terms',
'your_invoice',
'quote',
'your_quote',
'quote_date',
'quote_number',
'total',
'invoice_issued_to',
];
public function isPro() foreach ($fields as $field) {
{ $data[$field] = trans("texts.$field");
if (!Utils::isNinjaProd()) }
{
return true;
}
if ($this->account_key == NINJA_ACCOUNT_KEY) return $data;
{ }
return true;
}
$datePaid = $this->pro_plan_paid; public function isPro()
{
if (!Utils::isNinjaProd()) {
return true;
}
if (!$datePaid || $datePaid == '0000-00-00') if ($this->account_key == NINJA_ACCOUNT_KEY) {
{ return true;
return false; }
}
else if ($datePaid == NINJA_DATE)
{
return true;
}
$today = new DateTime('now'); $datePaid = $this->pro_plan_paid;
$datePaid = DateTime::createFromFormat('Y-m-d', $datePaid);
$interval = $today->diff($datePaid);
return $interval->y == 0;
}
public function isWhiteLabel() if (!$datePaid || $datePaid == '0000-00-00') {
{ return false;
if (Utils::isNinjaProd()) } elseif ($datePaid == NINJA_DATE) {
{ return true;
return false; }
}
return $this->pro_plan_paid == NINJA_DATE; $today = new DateTime('now');
} $datePaid = DateTime::createFromFormat('Y-m-d', $datePaid);
$interval = $today->diff($datePaid);
public function getSubscription($eventId) return $interval->y == 0;
{ }
return Subscription::where('account_id', '=', $this->id)->where('event_id', '=', $eventId)->first();
}
public function hideFieldsForViz() public function isWhiteLabel()
{ {
foreach ($this->clients as $client) if (Utils::isNinjaProd()) {
{ return false;
$client->setVisible([ }
'public_id',
'name',
'balance',
'paid_to_date',
'invoices',
'contacts',
]);
foreach ($client->invoices as $invoice)
{
$invoice->setVisible([
'public_id',
'invoice_number',
'amount',
'balance',
'invoice_status_id',
'invoice_items',
'created_at',
]);
foreach ($invoice->invoice_items as $invoiceItem) return $this->pro_plan_paid == NINJA_DATE;
{ }
$invoiceItem->setVisible([
'product_key',
'cost',
'qty',
]);
}
}
foreach ($client->contacts as $contact) public function getSubscription($eventId)
{ {
$contact->setVisible([ return Subscription::where('account_id', '=', $this->id)->where('event_id', '=', $eventId)->first();
'public_id', }
'first_name',
'last_name',
'email']);
}
}
return $this; public function hideFieldsForViz()
} {
foreach ($this->clients as $client) {
$client->setVisible([
'public_id',
'name',
'balance',
'paid_to_date',
'invoices',
'contacts',
]);
} foreach ($client->invoices as $invoice) {
$invoice->setVisible([
'public_id',
'invoice_number',
'amount',
'balance',
'invoice_status_id',
'invoice_items',
'created_at',
]);
foreach ($invoice->invoice_items as $invoiceItem) {
$invoiceItem->setVisible([
'product_key',
'cost',
'qty',
]);
}
}
foreach ($client->contacts as $contact) {
$contact->setVisible([
'public_id',
'first_name',
'last_name',
'email', ]);
}
}
return $this;
}
}

View File

@ -2,22 +2,22 @@
class AccountGateway extends EntityModel class AccountGateway extends EntityModel
{ {
public function gateway() public function gateway()
{ {
return $this->belongsTo('Gateway'); return $this->belongsTo('Gateway');
} }
public function getCreditcardTypes() public function getCreditcardTypes()
{ {
$flags = unserialize(CREDIT_CARDS); $flags = unserialize(CREDIT_CARDS);
$arrayOfImages = []; $arrayOfImages = [];
foreach ($flags as $card => $name) foreach ($flags as $card => $name) {
{ if (($this->accepted_credit_cards & $card) == $card) {
if (($this->accepted_credit_cards & $card) == $card)
$arrayOfImages[] = ['source' => asset($name['card']), 'alt' => $name['text']]; $arrayOfImages[] = ['source' => asset($name['card']), 'alt' => $name['text']];
} }
}
return $arrayOfImages; return $arrayOfImages;
} }
} }

View File

@ -35,473 +35,436 @@ define("ACTIVITY_TYPE_RESTORE_CLIENT", 26);
define("ACTIVITY_TYPE_RESTORE_PAYMENT", 27); define("ACTIVITY_TYPE_RESTORE_PAYMENT", 27);
define("ACTIVITY_TYPE_RESTORE_CREDIT", 28); define("ACTIVITY_TYPE_RESTORE_CREDIT", 28);
class Activity extends Eloquent class Activity extends Eloquent
{ {
public $timestamps = true; public $timestamps = true;
protected $softDelete = false; protected $softDelete = false;
public function scopeScope($query) public function scopeScope($query)
{ {
return $query->whereAccountId(Auth::user()->account_id); return $query->whereAccountId(Auth::user()->account_id);
} }
public function account() public function account()
{ {
return $this->belongsTo('Account'); return $this->belongsTo('Account');
} }
private static function getBlank($entity = false) private static function getBlank($entity = false)
{ {
$activity = new Activity; $activity = new Activity();
if ($entity) if ($entity) {
{ $activity->user_id = $entity instanceof User ? $entity->id : $entity->user_id;
$activity->user_id = $entity instanceof User ? $entity->id : $entity->user_id; $activity->account_id = $entity->account_id;
$activity->account_id = $entity->account_id; } elseif (Auth::check()) {
} $activity->user_id = Auth::user()->id;
else if (Auth::check()) $activity->account_id = Auth::user()->account_id;
{ } else {
$activity->user_id = Auth::user()->id; Utils::fatalError();
$activity->account_id = Auth::user()->account_id; }
}
else
{
Utils::fatalError();
}
return $activity; return $activity;
} }
public static function createClient($client, $notify = true) public static function createClient($client, $notify = true)
{ {
$activity = Activity::getBlank(); $activity = Activity::getBlank();
$activity->client_id = $client->id; $activity->client_id = $client->id;
$activity->activity_type_id = ACTIVITY_TYPE_CREATE_CLIENT; $activity->activity_type_id = ACTIVITY_TYPE_CREATE_CLIENT;
$activity->message = Utils::encodeActivity(Auth::user(), 'created', $client); $activity->message = Utils::encodeActivity(Auth::user(), 'created', $client);
$activity->save(); $activity->save();
if ($notify) if ($notify) {
{ Activity::checkSubscriptions(EVENT_CREATE_CLIENT, $client);
Activity::checkSubscriptions(EVENT_CREATE_CLIENT, $client); }
} }
}
public static function updateClient($client) public static function updateClient($client)
{ {
if ($client->is_deleted && !$client->getOriginal('is_deleted')) if ($client->is_deleted && !$client->getOriginal('is_deleted')) {
{ $activity = Activity::getBlank();
$activity = Activity::getBlank(); $activity->client_id = $client->id;
$activity->client_id = $client->id; $activity->activity_type_id = ACTIVITY_TYPE_DELETE_CLIENT;
$activity->activity_type_id = ACTIVITY_TYPE_DELETE_CLIENT; $activity->message = Utils::encodeActivity(Auth::user(), 'deleted', $client);
$activity->message = Utils::encodeActivity(Auth::user(), 'deleted', $client); $activity->save();
$activity->save(); }
} }
}
public static function archiveClient($client) public static function archiveClient($client)
{ {
if (!$client->is_deleted) if (!$client->is_deleted) {
{ $activity = Activity::getBlank();
$activity = Activity::getBlank(); $activity->client_id = $client->id;
$activity->client_id = $client->id; $activity->activity_type_id = ACTIVITY_TYPE_ARCHIVE_CLIENT;
$activity->activity_type_id = ACTIVITY_TYPE_ARCHIVE_CLIENT; $activity->message = Utils::encodeActivity(Auth::user(), 'archived', $client);
$activity->message = Utils::encodeActivity(Auth::user(), 'archived', $client); $activity->balance = $client->balance;
$activity->balance = $client->balance; $activity->save();
$activity->save(); }
} }
}
public static function restoreClient($client) public static function restoreClient($client)
{ {
$activity = Activity::getBlank(); $activity = Activity::getBlank();
$activity->client_id = $client->id; $activity->client_id = $client->id;
$activity->activity_type_id = ACTIVITY_TYPE_RESTORE_CLIENT; $activity->activity_type_id = ACTIVITY_TYPE_RESTORE_CLIENT;
$activity->message = Utils::encodeActivity(Auth::user(), 'restored', $client); $activity->message = Utils::encodeActivity(Auth::user(), 'restored', $client);
$activity->balance = $client->balance; $activity->balance = $client->balance;
$activity->save(); $activity->save();
} }
public static function createInvoice($invoice) public static function createInvoice($invoice)
{ {
if (Auth::check()) if (Auth::check()) {
{ $message = Utils::encodeActivity(Auth::user(), 'created', $invoice);
$message = Utils::encodeActivity(Auth::user(), 'created', $invoice); } else {
} $message = Utils::encodeActivity(null, 'created', $invoice);
else }
{
$message = Utils::encodeActivity(null, 'created', $invoice);
}
$adjustment = 0; $adjustment = 0;
$client = $invoice->client; $client = $invoice->client;
if (!$invoice->is_quote && !$invoice->is_recurring) if (!$invoice->is_quote && !$invoice->is_recurring) {
{ $adjustment = $invoice->amount;
$adjustment = $invoice->amount; $client->balance = $client->balance + $adjustment;
$client->balance = $client->balance + $adjustment; $client->save();
$client->save(); }
}
$activity = Activity::getBlank($invoice); $activity = Activity::getBlank($invoice);
$activity->invoice_id = $invoice->id; $activity->invoice_id = $invoice->id;
$activity->client_id = $invoice->client_id; $activity->client_id = $invoice->client_id;
$activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_CREATE_QUOTE : ACTIVITY_TYPE_CREATE_INVOICE; $activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_CREATE_QUOTE : ACTIVITY_TYPE_CREATE_INVOICE;
$activity->message = $message; $activity->message = $message;
$activity->balance = $client->balance; $activity->balance = $client->balance;
$activity->adjustment = $adjustment; $activity->adjustment = $adjustment;
$activity->save(); $activity->save();
Activity::checkSubscriptions($invoice->is_quote ? EVENT_CREATE_QUOTE : EVENT_CREATE_INVOICE, $invoice); Activity::checkSubscriptions($invoice->is_quote ? EVENT_CREATE_QUOTE : EVENT_CREATE_INVOICE, $invoice);
} }
public static function archiveInvoice($invoice) public static function archiveInvoice($invoice)
{ {
if (!$invoice->is_deleted) if (!$invoice->is_deleted) {
{ $activity = Activity::getBlank();
$activity = Activity::getBlank(); $activity->invoice_id = $invoice->id;
$activity->invoice_id = $invoice->id; $activity->client_id = $invoice->client_id;
$activity->client_id = $invoice->client_id; $activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_ARCHIVE_QUOTE : ACTIVITY_TYPE_ARCHIVE_INVOICE;
$activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_ARCHIVE_QUOTE : ACTIVITY_TYPE_ARCHIVE_INVOICE; $activity->message = Utils::encodeActivity(Auth::user(), 'archived', $invoice);
$activity->message = Utils::encodeActivity(Auth::user(), 'archived', $invoice); $activity->balance = $invoice->client->balance;
$activity->balance = $invoice->client->balance;
$activity->save(); $activity->save();
} }
} }
public static function restoreInvoice($invoice) public static function restoreInvoice($invoice)
{ {
$activity = Activity::getBlank(); $activity = Activity::getBlank();
$activity->invoice_id = $invoice->id; $activity->invoice_id = $invoice->id;
$activity->client_id = $invoice->client_id; $activity->client_id = $invoice->client_id;
$activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_RESTORE_QUOTE : ACTIVITY_TYPE_RESTORE_INVOICE; $activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_RESTORE_QUOTE : ACTIVITY_TYPE_RESTORE_INVOICE;
$activity->message = Utils::encodeActivity(Auth::user(), 'restored', $invoice); $activity->message = Utils::encodeActivity(Auth::user(), 'restored', $invoice);
$activity->balance = $invoice->client->balance; $activity->balance = $invoice->client->balance;
$activity->save(); $activity->save();
} }
public static function emailInvoice($invitation) public static function emailInvoice($invitation)
{ {
$adjustment = 0; $adjustment = 0;
$client = $invitation->invoice->client; $client = $invitation->invoice->client;
$activity = Activity::getBlank($invitation); $activity = Activity::getBlank($invitation);
$activity->client_id = $invitation->invoice->client_id; $activity->client_id = $invitation->invoice->client_id;
$activity->invoice_id = $invitation->invoice_id; $activity->invoice_id = $invitation->invoice_id;
$activity->contact_id = $invitation->contact_id; $activity->contact_id = $invitation->contact_id;
$activity->activity_type_id = $invitation->invoice ? ACTIVITY_TYPE_EMAIL_QUOTE : ACTIVITY_TYPE_EMAIL_INVOICE; $activity->activity_type_id = $invitation->invoice ? ACTIVITY_TYPE_EMAIL_QUOTE : ACTIVITY_TYPE_EMAIL_INVOICE;
$activity->message = Utils::encodeActivity(Auth::check() ? Auth::user() : null, 'emailed', $invitation->invoice, $invitation->contact); $activity->message = Utils::encodeActivity(Auth::check() ? Auth::user() : null, 'emailed', $invitation->invoice, $invitation->contact);
$activity->balance = $client->balance; $activity->balance = $client->balance;
$activity->save(); $activity->save();
} }
public static function updateInvoice($invoice) public static function updateInvoice($invoice)
{ {
$client = $invoice->client; $client = $invoice->client;
if ($invoice->is_deleted && !$invoice->getOriginal('is_deleted')) if ($invoice->is_deleted && !$invoice->getOriginal('is_deleted')) {
{ if (!$invoice->is_quote && !$invoice->is_recurring) {
if (!$invoice->is_quote && !$invoice->is_recurring) $client->balance = $client->balance - $invoice->balance;
{ $client->paid_to_date = $client->paid_to_date - ($invoice->amount - $invoice->balance);
$client->balance = $client->balance - $invoice->balance; $client->save();
$client->paid_to_date = $client->paid_to_date - ($invoice->amount - $invoice->balance); }
$client->save();
}
$activity = Activity::getBlank(); $activity = Activity::getBlank();
$activity->client_id = $invoice->client_id; $activity->client_id = $invoice->client_id;
$activity->invoice_id = $invoice->id; $activity->invoice_id = $invoice->id;
$activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_DELETE_QUOTE : ACTIVITY_TYPE_DELETE_INVOICE; $activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_DELETE_QUOTE : ACTIVITY_TYPE_DELETE_INVOICE;
$activity->message = Utils::encodeActivity(Auth::user(), 'deleted', $invoice); $activity->message = Utils::encodeActivity(Auth::user(), 'deleted', $invoice);
$activity->balance = $invoice->client->balance; $activity->balance = $invoice->client->balance;
$activity->adjustment = $invoice->is_quote ? 0 : $invoice->balance * -1; $activity->adjustment = $invoice->is_quote ? 0 : $invoice->balance * -1;
$activity->save(); $activity->save();
} } else {
else $diff = floatval($invoice->amount) - floatval($invoice->getOriginal('amount'));
{
$diff = floatval($invoice->amount) - floatval($invoice->getOriginal('amount'));
if ($diff == 0)
{
return;
}
$backupInvoice = Invoice::with('invoice_items', 'client.account', 'client.contacts')->find($invoice->id); if ($diff == 0) {
return;
}
if (!$invoice->is_quote && !$invoice->is_recurring) $backupInvoice = Invoice::with('invoice_items', 'client.account', 'client.contacts')->find($invoice->id);
{
$client->balance = $client->balance + $diff;
$client->save();
}
$activity = Activity::getBlank($invoice); if (!$invoice->is_quote && !$invoice->is_recurring) {
$activity->client_id = $invoice->client_id; $client->balance = $client->balance + $diff;
$activity->invoice_id = $invoice->id; $client->save();
$activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_UPDATE_QUOTE : ACTIVITY_TYPE_UPDATE_INVOICE; }
$activity->message = Utils::encodeActivity(Auth::user(), 'updated', $invoice);
$activity->balance = $client->balance;
$activity->adjustment = $invoice->is_quote || $invoice->is_recurring ? 0 : $diff;
$activity->json_backup = $backupInvoice->hidePrivateFields()->toJSON();
$activity->save();
}
}
public static function viewInvoice($invitation) $activity = Activity::getBlank($invoice);
{ $activity->client_id = $invoice->client_id;
if (Session::get($invitation->invitation_key)) $activity->invoice_id = $invoice->id;
{ $activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_UPDATE_QUOTE : ACTIVITY_TYPE_UPDATE_INVOICE;
return; $activity->message = Utils::encodeActivity(Auth::user(), 'updated', $invoice);
} $activity->balance = $client->balance;
$activity->adjustment = $invoice->is_quote || $invoice->is_recurring ? 0 : $diff;
$activity->json_backup = $backupInvoice->hidePrivateFields()->toJSON();
$activity->save();
}
}
Session::put($invitation->invitation_key, true); public static function viewInvoice($invitation)
$invoice = $invitation->invoice; {
if (Session::get($invitation->invitation_key)) {
if (!$invoice->isViewed()) return;
{ }
$invoice->invoice_status_id = INVOICE_STATUS_VIEWED;
$invoice->save();
}
$now = Carbon::now()->toDateTimeString();
$invitation->viewed_date = $now; Session::put($invitation->invitation_key, true);
$invitation->save(); $invoice = $invitation->invoice;
$client = $invoice->client; if (!$invoice->isViewed()) {
$client->last_login = $now; $invoice->invoice_status_id = INVOICE_STATUS_VIEWED;
$client->save(); $invoice->save();
}
$activity = Activity::getBlank($invitation); $now = Carbon::now()->toDateTimeString();
$activity->client_id = $invitation->invoice->client_id;
$activity->invitation_id = $invitation->id;
$activity->contact_id = $invitation->contact_id;
$activity->invoice_id = $invitation->invoice_id;
$activity->activity_type_id = $invitation->invoice->is_quote ? ACTIVITY_TYPE_VIEW_QUOTE : ACTIVITY_TYPE_VIEW_INVOICE;
$activity->message = Utils::encodeActivity($invitation->contact, 'viewed', $invitation->invoice);
$activity->balance = $invitation->invoice->client->balance;
$activity->save();
}
$invitation->viewed_date = $now;
$invitation->save();
$client = $invoice->client;
$client->last_login = $now;
$client->save();
public static function createPayment($payment) $activity = Activity::getBlank($invitation);
{ $activity->client_id = $invitation->invoice->client_id;
$client = $payment->client; $activity->invitation_id = $invitation->id;
$client->balance = $client->balance - $payment->amount; $activity->contact_id = $invitation->contact_id;
$client->paid_to_date = $client->paid_to_date + $payment->amount; $activity->invoice_id = $invitation->invoice_id;
$client->save(); $activity->activity_type_id = $invitation->invoice->is_quote ? ACTIVITY_TYPE_VIEW_QUOTE : ACTIVITY_TYPE_VIEW_INVOICE;
$activity->message = Utils::encodeActivity($invitation->contact, 'viewed', $invitation->invoice);
$activity->balance = $invitation->invoice->client->balance;
$activity->save();
}
if ($payment->contact_id) public static function createPayment($payment)
{ {
$activity = Activity::getBlank($client); $client = $payment->client;
$activity->contact_id = $payment->contact_id; $client->balance = $client->balance - $payment->amount;
$activity->message = Utils::encodeActivity($payment->invitation->contact, 'entered ' . $payment->getName() . ' for ', $payment->invoice); $client->paid_to_date = $client->paid_to_date + $payment->amount;
} $client->save();
else
{
$activity = Activity::getBlank($client);
$message = $payment->payment_type_id == PAYMENT_TYPE_CREDIT ? 'applied credit for ' : 'entered ' . $payment->getName() . ' for ';
$activity->message = Utils::encodeActivity(Auth::user(), $message, $payment->invoice);
}
$activity->payment_id = $payment->id; if ($payment->contact_id) {
$activity = Activity::getBlank($client);
$activity->contact_id = $payment->contact_id;
$activity->message = Utils::encodeActivity($payment->invitation->contact, 'entered '.$payment->getName().' for ', $payment->invoice);
} else {
$activity = Activity::getBlank($client);
$message = $payment->payment_type_id == PAYMENT_TYPE_CREDIT ? 'applied credit for ' : 'entered '.$payment->getName().' for ';
$activity->message = Utils::encodeActivity(Auth::user(), $message, $payment->invoice);
}
if ($payment->invoice_id) $activity->payment_id = $payment->id;
{
$activity->invoice_id = $payment->invoice_id;
$invoice = $payment->invoice; if ($payment->invoice_id) {
$invoice->balance = $invoice->balance - $payment->amount; $activity->invoice_id = $payment->invoice_id;
$invoice->invoice_status_id = ($invoice->balance > 0) ? INVOICE_STATUS_PARTIAL : INVOICE_STATUS_PAID;
$invoice->save();
}
$activity->payment_id = $payment->id; $invoice = $payment->invoice;
$activity->client_id = $payment->client_id; $invoice->balance = $invoice->balance - $payment->amount;
$activity->activity_type_id = ACTIVITY_TYPE_CREATE_PAYMENT; $invoice->invoice_status_id = ($invoice->balance > 0) ? INVOICE_STATUS_PARTIAL : INVOICE_STATUS_PAID;
$activity->balance = $client->balance; $invoice->save();
$activity->adjustment = $payment->amount * -1; }
$activity->save();
Activity::checkSubscriptions(EVENT_CREATE_PAYMENT, $payment); $activity->payment_id = $payment->id;
} $activity->client_id = $payment->client_id;
$activity->activity_type_id = ACTIVITY_TYPE_CREATE_PAYMENT;
$activity->balance = $client->balance;
$activity->adjustment = $payment->amount * -1;
$activity->save();
public static function updatePayment($payment) Activity::checkSubscriptions(EVENT_CREATE_PAYMENT, $payment);
{ }
if ($payment->is_deleted && !$payment->getOriginal('is_deleted'))
{
$client = $payment->client;
$client->balance = $client->balance + $payment->amount;
$client->paid_to_date = $client->paid_to_date - $payment->amount;
$client->save();
$invoice = $payment->invoice; public static function updatePayment($payment)
$invoice->balance = $invoice->balance + $payment->amount; {
$invoice->save(); if ($payment->is_deleted && !$payment->getOriginal('is_deleted')) {
$client = $payment->client;
$client->balance = $client->balance + $payment->amount;
$client->paid_to_date = $client->paid_to_date - $payment->amount;
$client->save();
$activity = Activity::getBlank(); $invoice = $payment->invoice;
$activity->payment_id = $payment->id; $invoice->balance = $invoice->balance + $payment->amount;
$activity->client_id = $invoice->client_id; $invoice->save();
$activity->invoice_id = $invoice->id;
$activity->activity_type_id = ACTIVITY_TYPE_DELETE_PAYMENT;
$activity->message = Utils::encodeActivity(Auth::user(), 'deleted ' . $payment->getName());
$activity->balance = $client->balance;
$activity->adjustment = $payment->amount;
$activity->save();
}
else
{
/*
$diff = floatval($invoice->amount) - floatval($invoice->getOriginal('amount'));
if ($diff == 0)
{
return;
}
$client = $invoice->client; $activity = Activity::getBlank();
$client->balance = $client->balance + $diff; $activity->payment_id = $payment->id;
$client->save(); $activity->client_id = $invoice->client_id;
$activity->invoice_id = $invoice->id;
$activity->activity_type_id = ACTIVITY_TYPE_DELETE_PAYMENT;
$activity->message = Utils::encodeActivity(Auth::user(), 'deleted '.$payment->getName());
$activity->balance = $client->balance;
$activity->adjustment = $payment->amount;
$activity->save();
} else {
/*
$diff = floatval($invoice->amount) - floatval($invoice->getOriginal('amount'));
$activity = Activity::getBlank($invoice); if ($diff == 0)
$activity->client_id = $invoice->client_id; {
$activity->invoice_id = $invoice->id; return;
$activity->activity_type_id = ACTIVITY_TYPE_UPDATE_INVOICE; }
$activity->message = Utils::encodeActivity(Auth::user(), 'updated', $invoice);
$activity->balance = $client->balance;
$activity->adjustment = $diff;
$activity->json_backup = $backupInvoice->hidePrivateFields()->toJSON();
$activity->save();
*/
}
}
public static function archivePayment($payment) $client = $invoice->client;
{ $client->balance = $client->balance + $diff;
if ($payment->is_deleted) $client->save();
{
return;
}
$client = $payment->client; $activity = Activity::getBlank($invoice);
$invoice = $payment->invoice; $activity->client_id = $invoice->client_id;
$activity->invoice_id = $invoice->id;
$activity->activity_type_id = ACTIVITY_TYPE_UPDATE_INVOICE;
$activity->message = Utils::encodeActivity(Auth::user(), 'updated', $invoice);
$activity->balance = $client->balance;
$activity->adjustment = $diff;
$activity->json_backup = $backupInvoice->hidePrivateFields()->toJSON();
$activity->save();
*/
}
}
$activity = Activity::getBlank(); public static function archivePayment($payment)
$activity->payment_id = $payment->id; {
$activity->invoice_id = $invoice->id; if ($payment->is_deleted) {
$activity->client_id = $client->id; return;
$activity->activity_type_id = ACTIVITY_TYPE_ARCHIVE_PAYMENT; }
$activity->message = Utils::encodeActivity(Auth::user(), 'archived ' . $payment->getName());
$activity->balance = $client->balance;
$activity->adjustment = 0;
$activity->save();
}
public static function restorePayment($payment) $client = $payment->client;
{ $invoice = $payment->invoice;
$client = $payment->client;
$invoice = $payment->invoice;
$activity = Activity::getBlank(); $activity = Activity::getBlank();
$activity->payment_id = $payment->id; $activity->payment_id = $payment->id;
$activity->invoice_id = $invoice->id; $activity->invoice_id = $invoice->id;
$activity->client_id = $client->id; $activity->client_id = $client->id;
$activity->activity_type_id = ACTIVITY_TYPE_RESTORE_PAYMENT; $activity->activity_type_id = ACTIVITY_TYPE_ARCHIVE_PAYMENT;
$activity->message = Utils::encodeActivity(Auth::user(), 'restored ' . $payment->getName()); $activity->message = Utils::encodeActivity(Auth::user(), 'archived '.$payment->getName());
$activity->balance = $client->balance; $activity->balance = $client->balance;
$activity->adjustment = 0; $activity->adjustment = 0;
$activity->save(); $activity->save();
} }
public static function createCredit($credit) public static function restorePayment($payment)
{ {
$activity = Activity::getBlank(); $client = $payment->client;
$activity->message = Utils::encodeActivity(Auth::user(), 'entered ' . Utils::formatMoney($credit->amount, $credit->client->currency_id) . ' credit'); $invoice = $payment->invoice;
$activity->credit_id = $credit->id;
$activity->client_id = $credit->client_id;
$activity->activity_type_id = ACTIVITY_TYPE_CREATE_CREDIT;
$activity->balance = $credit->client->balance;
$activity->save();
}
public static function updateCredit($credit) $activity = Activity::getBlank();
{ $activity->payment_id = $payment->id;
if ($credit->is_deleted && !$credit->getOriginal('is_deleted')) $activity->invoice_id = $invoice->id;
{ $activity->client_id = $client->id;
$activity = Activity::getBlank(); $activity->activity_type_id = ACTIVITY_TYPE_RESTORE_PAYMENT;
$activity->credit_id = $credit->id; $activity->message = Utils::encodeActivity(Auth::user(), 'restored '.$payment->getName());
$activity->client_id = $credit->client_id; $activity->balance = $client->balance;
$activity->activity_type_id = ACTIVITY_TYPE_DELETE_CREDIT; $activity->adjustment = 0;
$activity->message = Utils::encodeActivity(Auth::user(), 'deleted ' . Utils::formatMoney($credit->balance, $credit->client->currency_id) . ' credit'); $activity->save();
$activity->balance = $credit->client->balance; }
$activity->save();
}
else
{
/*
$diff = floatval($invoice->amount) - floatval($invoice->getOriginal('amount'));
if ($diff == 0)
{
return;
}
$client = $invoice->client; public static function createCredit($credit)
$client->balance = $client->balance + $diff; {
$client->save(); $activity = Activity::getBlank();
$activity->message = Utils::encodeActivity(Auth::user(), 'entered '.Utils::formatMoney($credit->amount, $credit->client->currency_id).' credit');
$activity->credit_id = $credit->id;
$activity->client_id = $credit->client_id;
$activity->activity_type_id = ACTIVITY_TYPE_CREATE_CREDIT;
$activity->balance = $credit->client->balance;
$activity->save();
}
$activity = Activity::getBlank($invoice); public static function updateCredit($credit)
$activity->client_id = $invoice->client_id; {
$activity->invoice_id = $invoice->id; if ($credit->is_deleted && !$credit->getOriginal('is_deleted')) {
$activity->activity_type_id = ACTIVITY_TYPE_UPDATE_INVOICE; $activity = Activity::getBlank();
$activity->message = Utils::encodeActivity(Auth::user(), 'updated', $invoice); $activity->credit_id = $credit->id;
$activity->balance = $client->balance; $activity->client_id = $credit->client_id;
$activity->adjustment = $diff; $activity->activity_type_id = ACTIVITY_TYPE_DELETE_CREDIT;
$activity->json_backup = $backupInvoice->hidePrivateFields()->toJSON(); $activity->message = Utils::encodeActivity(Auth::user(), 'deleted '.Utils::formatMoney($credit->balance, $credit->client->currency_id).' credit');
$activity->save(); $activity->balance = $credit->client->balance;
*/ $activity->save();
} } else {
} /*
$diff = floatval($invoice->amount) - floatval($invoice->getOriginal('amount'));
public static function archiveCredit($credit) if ($diff == 0)
{ {
if ($credit->is_deleted) return;
{ }
return;
}
$activity = Activity::getBlank();
$activity->client_id = $credit->client_id;
$activity->credit_id = $credit->id;
$activity->activity_type_id = ACTIVITY_TYPE_ARCHIVE_CREDIT;
$activity->message = Utils::encodeActivity(Auth::user(), 'archived ' . Utils::formatMoney($credit->balance, $credit->client->currency_id) . ' credit');
$activity->balance = $credit->client->balance;
$activity->save();
}
public static function restoreCredit($credit) $client = $invoice->client;
{ $client->balance = $client->balance + $diff;
$activity = Activity::getBlank(); $client->save();
$activity->client_id = $credit->client_id;
$activity->credit_id = $credit->id;
$activity->activity_type_id = ACTIVITY_TYPE_RESTORE_CREDIT;
$activity->message = Utils::encodeActivity(Auth::user(), 'restored ' . Utils::formatMoney($credit->balance, $credit->client->currency_id) . ' credit');
$activity->balance = $credit->client->balance;
$activity->save();
}
private static function checkSubscriptions($event, $data) $activity = Activity::getBlank($invoice);
{ $activity->client_id = $invoice->client_id;
if (!Auth::check()) { $activity->invoice_id = $invoice->id;
return; $activity->activity_type_id = ACTIVITY_TYPE_UPDATE_INVOICE;
} $activity->message = Utils::encodeActivity(Auth::user(), 'updated', $invoice);
$activity->balance = $client->balance;
$subscription = Auth::user()->account->getSubscription($event); $activity->adjustment = $diff;
$activity->json_backup = $backupInvoice->hidePrivateFields()->toJSON();
if ($subscription) $activity->save();
{ */
Utils::notifyZapier($subscription, $data); }
} }
}
} public static function archiveCredit($credit)
{
if ($credit->is_deleted) {
return;
}
$activity = Activity::getBlank();
$activity->client_id = $credit->client_id;
$activity->credit_id = $credit->id;
$activity->activity_type_id = ACTIVITY_TYPE_ARCHIVE_CREDIT;
$activity->message = Utils::encodeActivity(Auth::user(), 'archived '.Utils::formatMoney($credit->balance, $credit->client->currency_id).' credit');
$activity->balance = $credit->client->balance;
$activity->save();
}
public static function restoreCredit($credit)
{
$activity = Activity::getBlank();
$activity->client_id = $credit->client_id;
$activity->credit_id = $credit->id;
$activity->activity_type_id = ACTIVITY_TYPE_RESTORE_CREDIT;
$activity->message = Utils::encodeActivity(Auth::user(), 'restored '.Utils::formatMoney($credit->balance, $credit->client->currency_id).' credit');
$activity->balance = $credit->client->balance;
$activity->save();
}
private static function checkSubscriptions($event, $data)
{
if (!Auth::check()) {
return;
}
$subscription = Auth::user()->account->getSubscription($event);
if ($subscription) {
Utils::notifyZapier($subscription, $data);
}
}
}

View File

@ -2,6 +2,6 @@
class Affiliate extends Eloquent class Affiliate extends Eloquent
{ {
public $timestamps = true; public $timestamps = true;
protected $softDelete = true; protected $softDelete = true;
} }

View File

@ -2,259 +2,240 @@
class Client extends EntityModel class Client extends EntityModel
{ {
public static $fieldName = 'Client - Name'; public static $fieldName = 'Client - Name';
public static $fieldPhone = 'Client - Phone'; public static $fieldPhone = 'Client - Phone';
public static $fieldAddress1 = 'Client - Street'; public static $fieldAddress1 = 'Client - Street';
public static $fieldAddress2 = 'Client - Apt/Floor'; public static $fieldAddress2 = 'Client - Apt/Floor';
public static $fieldCity = 'Client - City'; public static $fieldCity = 'Client - City';
public static $fieldState = 'Client - State'; public static $fieldState = 'Client - State';
public static $fieldPostalCode = 'Client - Postal Code'; public static $fieldPostalCode = 'Client - Postal Code';
public static $fieldNotes = 'Client - Notes'; public static $fieldNotes = 'Client - Notes';
public static $fieldCountry = 'Client - Country'; public static $fieldCountry = 'Client - Country';
public function account() public function account()
{ {
return $this->belongsTo('Account'); return $this->belongsTo('Account');
} }
public function invoices() public function invoices()
{ {
return $this->hasMany('Invoice'); return $this->hasMany('Invoice');
} }
public function payments() public function payments()
{ {
return $this->hasMany('Payment'); return $this->hasMany('Payment');
} }
public function contacts() public function contacts()
{ {
return $this->hasMany('Contact'); return $this->hasMany('Contact');
} }
public function projects()
{
return $this->hasMany('Project');
}
public function country() public function projects()
{ {
return $this->belongsTo('Country'); return $this->hasMany('Project');
} }
public function currency() public function country()
{ {
return $this->belongsTo('Currency'); return $this->belongsTo('Country');
} }
public function size() public function currency()
{ {
return $this->belongsTo('Size'); return $this->belongsTo('Currency');
} }
public function industry() public function size()
{ {
return $this->belongsTo('Industry'); return $this->belongsTo('Size');
} }
public function getTotalCredit() public function industry()
{ {
return DB::table('credits') return $this->belongsTo('Industry');
->where('client_id','=',$this->id) }
->whereNull('deleted_at')
->sum('balance');
}
public function getName() public function getTotalCredit()
{ {
return $this->getDisplayName(); return DB::table('credits')
} ->where('client_id', '=', $this->id)
->whereNull('deleted_at')
->sum('balance');
}
public function getDisplayName() public function getName()
{ {
if ($this->name) return $this->getDisplayName();
{ }
return $this->name;
}
$this->load('contacts'); public function getDisplayName()
$contact = $this->contacts()->first(); {
if ($this->name) {
return $contact->getDisplayName(); return $this->name;
} }
public function getEntityType() $this->load('contacts');
{ $contact = $this->contacts()->first();
return ENTITY_CLIENT;
}
public function getAddress() return $contact->getDisplayName();
{ }
$str = '';
if ($this->address1) { public function getEntityType()
$str .= $this->address1 . '<br/>'; {
} return ENTITY_CLIENT;
if ($this->address2) { }
$str .= $this->address2 . '<br/>';
}
if ($this->city) {
$str .= $this->city . ', ';
}
if ($this->state) {
$str .= $this->state . ' ';
}
if ($this->postal_code) {
$str .= $this->postal_code;
}
if ($this->country) {
$str .= '<br/>' . $this->country->name;
}
if ($str) public function getAddress()
{ {
$str = '<p>' . $str . '</p>'; $str = '';
}
return $str; if ($this->address1) {
} $str .= $this->address1.'<br/>';
}
if ($this->address2) {
$str .= $this->address2.'<br/>';
}
if ($this->city) {
$str .= $this->city.', ';
}
if ($this->state) {
$str .= $this->state.' ';
}
if ($this->postal_code) {
$str .= $this->postal_code;
}
if ($this->country) {
$str .= '<br/>'.$this->country->name;
}
public function getPhone() if ($str) {
{ $str = '<p>'.$str.'</p>';
$str = ''; }
if ($this->work_phone) return $str;
{ }
$str .= '<i class="fa fa-phone" style="width: 20px"></i>' . Utils::formatPhoneNumber($this->work_phone);
}
return $str; public function getPhone()
} {
$str = '';
public function getIdNumber()
{
$str = '';
if ($this->id_number) if ($this->work_phone) {
{ $str .= '<i class="fa fa-phone" style="width: 20px"></i>'.Utils::formatPhoneNumber($this->work_phone);
$str .= '<i class="fa fa-vat-number" style="width: 20px"></i>' . $this->vat_number; }
}
return $str; return $str;
} }
public function getVatNumber()
{
$str = '';
if ($this->vat_number) public function getIdNumber()
{ {
$str .= '<i class="fa fa-vat-number" style="width: 20px"></i>' . $this->vat_number; $str = '';
}
return $str; if ($this->id_number) {
} $str .= '<i class="fa fa-vat-number" style="width: 20px"></i>'.$this->vat_number;
}
public function getNotes() return $str;
{ }
$str = '';
if ($this->private_notes) public function getVatNumber()
{ {
$str .= '<i>' . $this->private_notes . '</i>'; $str = '';
}
return $str; if ($this->vat_number) {
} $str .= '<i class="fa fa-vat-number" style="width: 20px"></i>'.$this->vat_number;
}
public function getIndustry() return $str;
{ }
$str = '';
if ($this->client_industry) public function getNotes()
{ {
$str .= $this->client_industry->name . ' '; $str = '';
}
if ($this->client_size) if ($this->private_notes) {
{ $str .= '<i>'.$this->private_notes.'</i>';
$str .= $this->client_size->name; }
}
return $str; return $str;
} }
public function getCustomFields() public function getIndustry()
{ {
$str = ''; $str = '';
$account = $this->account;
if ($account->custom_client_label1 && $this->custom_value1) if ($this->client_industry) {
{ $str .= $this->client_industry->name.' ';
$str .= "{$account->custom_client_label1}: {$this->custom_value1}<br/>"; }
}
if ($account->custom_client_label2 && $this->custom_value2) if ($this->client_size) {
{ $str .= $this->client_size->name;
$str .= "{$account->custom_client_label2}: {$this->custom_value2}<br/>"; }
}
return $str; return $str;
} }
public function getWebsite() public function getCustomFields()
{ {
if (!$this->website) $str = '';
{ $account = $this->account;
return '';
}
$link = $this->website; if ($account->custom_client_label1 && $this->custom_value1) {
$title = $this->website; $str .= "{$account->custom_client_label1}: {$this->custom_value1}<br/>";
$prefix = 'http://'; }
if (strlen($link) > 7 && substr($link, 0, 7) === $prefix) { if ($account->custom_client_label2 && $this->custom_value2) {
$title = substr($title, 7); $str .= "{$account->custom_client_label2}: {$this->custom_value2}<br/>";
} else { }
$link = $prefix . $link;
}
return link_to($link, $title, array('target'=>'_blank')); return $str;
} }
public function getDateCreated() public function getWebsite()
{ {
if ($this->created_at == '0000-00-00 00:00:00') if (!$this->website) {
{ return '';
return '---'; }
}
else
{
return $this->created_at->format('m/d/y h:i a');
}
}
$link = $this->website;
$title = $this->website;
$prefix = 'http://';
if (strlen($link) > 7 && substr($link, 0, 7) === $prefix) {
$title = substr($title, 7);
} else {
$link = $prefix.$link;
}
return link_to($link, $title, array('target' => '_blank'));
}
public function getDateCreated()
{
if ($this->created_at == '0000-00-00 00:00:00') {
return '---';
} else {
return $this->created_at->format('m/d/y h:i a');
}
}
} }
/* /*
Client::created(function($client) Client::created(function($client)
{ {
Activity::createClient($client); Activity::createClient($client);
}); });
*/ */
Client::updating(function($client) Client::updating(function ($client) {
{ Activity::updateClient($client);
Activity::updateClient($client);
}); });
Client::deleting(function($client) Client::deleting(function ($client) {
{ Activity::archiveClient($client);
Activity::archiveClient($client);
}); });
Client::restoring(function($client) Client::restoring(function ($client) {
{ Activity::restoreClient($client);
Activity::restoreClient($client); });
});

View File

@ -2,84 +2,73 @@
class Contact extends EntityModel class Contact extends EntityModel
{ {
public static $fieldFirstName = 'Contact - First Name'; public static $fieldFirstName = 'Contact - First Name';
public static $fieldLastName = 'Contact - Last Name'; public static $fieldLastName = 'Contact - Last Name';
public static $fieldEmail = 'Contact - Email'; public static $fieldEmail = 'Contact - Email';
public static $fieldPhone = 'Contact - Phone'; public static $fieldPhone = 'Contact - Phone';
public function client() public function client()
{ {
return $this->belongsTo('Client'); return $this->belongsTo('Client');
} }
public function getPersonType() public function getPersonType()
{ {
return PERSON_CONTACT; return PERSON_CONTACT;
} }
/* /*
public function getLastLogin() public function getLastLogin()
{ {
if ($this->last_login == '0000-00-00 00:00:00') if ($this->last_login == '0000-00-00 00:00:00')
{ {
return '---'; return '---';
} }
else else
{ {
return $this->last_login->format('m/d/y h:i a'); return $this->last_login->format('m/d/y h:i a');
} }
} }
*/ */
public function getDisplayName()
{
if ($this->getFullName())
{
return $this->getFullName();
}
else
{
return $this->email;
}
} public function getDisplayName()
{
if ($this->getFullName()) {
return $this->getFullName();
} else {
return $this->email;
}
}
public function getFullName() public function getFullName()
{ {
if ($this->first_name || $this->last_name) if ($this->first_name || $this->last_name) {
{ return $this->first_name.' '.$this->last_name;
return $this->first_name . ' ' . $this->last_name; } else {
} return '';
else }
{ }
return '';
}
}
public function getDetails() public function getDetails()
{ {
$str = ''; $str = '';
if ($this->first_name || $this->last_name)
{
$str .= '<b>' . $this->first_name . ' ' . $this->last_name . '</b><br/>';
}
if ($this->email) if ($this->first_name || $this->last_name) {
{ $str .= '<b>'.$this->first_name.' '.$this->last_name.'</b><br/>';
$str .= '<i class="fa fa-envelope" style="width: 20px"></i>' . HTML::mailto($this->email, $this->email) . '<br/>'; }
}
if ($this->phone) if ($this->email) {
{ $str .= '<i class="fa fa-envelope" style="width: 20px"></i>'.HTML::mailto($this->email, $this->email).'<br/>';
$str .= '<i class="fa fa-phone" style="width: 20px"></i>' . Utils::formatPhoneNumber($this->phone); }
}
if ($str) if ($this->phone) {
{ $str .= '<i class="fa fa-phone" style="width: 20px"></i>'.Utils::formatPhoneNumber($this->phone);
$str = '<p>' . $str . '</p>'; }
}
return $str; if ($str) {
} $str = '<p>'.$str.'</p>';
} }
return $str;
}
}

View File

@ -2,8 +2,8 @@
class Country extends Eloquent class Country extends Eloquent
{ {
public $timestamps = false; public $timestamps = false;
protected $softDelete = false; protected $softDelete = false;
protected $visible = ['id', 'name']; protected $visible = ['id', 'name'];
} }

View File

@ -1,62 +1,55 @@
<?php <?php
class Credit extends EntityModel class Credit extends EntityModel
{ {
public function invoice() public function invoice()
{ {
return $this->belongsTo('Invoice')->withTrashed(); return $this->belongsTo('Invoice')->withTrashed();
} }
public function client() public function client()
{ {
return $this->belongsTo('Client')->withTrashed(); return $this->belongsTo('Client')->withTrashed();
} }
public function getName() public function getName()
{ {
return ''; return '';
} }
public function getEntityType() public function getEntityType()
{ {
return ENTITY_CREDIT; return ENTITY_CREDIT;
} }
public function apply($amount) public function apply($amount)
{ {
if ($amount > $this->balance) if ($amount > $this->balance) {
{ $applied = $this->balance;
$applied = $this->balance; $this->balance = 0;
$this->balance = 0; } else {
} $applied = $amount;
else $this->balance = $this->balance - $amount;
{ }
$applied = $amount;
$this->balance = $this->balance - $amount;
}
$this->save(); $this->save();
return $applied; return $applied;
} }
} }
Credit::created(function($credit) Credit::created(function ($credit) {
{ Activity::createCredit($credit);
Activity::createCredit($credit);
}); });
Credit::updating(function($credit) Credit::updating(function ($credit) {
{ Activity::updateCredit($credit);
Activity::updateCredit($credit);
}); });
Credit::deleting(function($credit) Credit::deleting(function ($credit) {
{ Activity::archiveCredit($credit);
Activity::archiveCredit($credit);
}); });
Credit::restoring(function($credit) Credit::restoring(function ($credit) {
{ Activity::restoreCredit($credit);
Activity::restoreCredit($credit); });
});

View File

@ -2,6 +2,6 @@
class Currency extends Eloquent class Currency extends Eloquent
{ {
public $timestamps = false; public $timestamps = false;
protected $softDelete = false; protected $softDelete = false;
} }

View File

@ -2,6 +2,6 @@
class DateFormat extends Eloquent class DateFormat extends Eloquent
{ {
public $timestamps = false; public $timestamps = false;
protected $softDelete = false; protected $softDelete = false;
} }

View File

@ -2,6 +2,6 @@
class DatetimeFormat extends Eloquent class DatetimeFormat extends Eloquent
{ {
public $timestamps = false; public $timestamps = false;
protected $softDelete = false; protected $softDelete = false;
} }

View File

@ -2,89 +2,77 @@
class EntityModel extends Eloquent class EntityModel extends Eloquent
{ {
protected $softDelete = true; protected $softDelete = true;
public $timestamps = true; public $timestamps = true;
protected $hidden = ['id'];
public static function createNew($parent = false) protected $hidden = ['id'];
{
$className = get_called_class();
$entity = new $className();
if ($parent)
{
$entity->user_id = $parent instanceof User ? $parent->id : $parent->user_id;
$entity->account_id = $parent->account_id;
}
else if (Auth::check())
{
$entity->user_id = Auth::user()->id;
$entity->account_id = Auth::user()->account_id;
}
else
{
Utils::fatalError();
}
$lastEntity = $className::withTrashed()->scope(false, $entity->account_id)->orderBy('public_id', 'DESC')->first(); public static function createNew($parent = false)
{
$className = get_called_class();
$entity = new $className();
if ($lastEntity) if ($parent) {
{ $entity->user_id = $parent instanceof User ? $parent->id : $parent->user_id;
$entity->public_id = $lastEntity->public_id + 1; $entity->account_id = $parent->account_id;
} } elseif (Auth::check()) {
else $entity->user_id = Auth::user()->id;
{ $entity->account_id = Auth::user()->account_id;
$entity->public_id = 1; } else {
} Utils::fatalError();
}
return $entity;
}
public static function getPrivateId($publicId) $lastEntity = $className::withTrashed()->scope(false, $entity->account_id)->orderBy('public_id', 'DESC')->first();
{
$className = get_called_class();
return $className::scope($publicId)->pluck('id');
}
public function getActivityKey() if ($lastEntity) {
{ $entity->public_id = $lastEntity->public_id + 1;
return $this->getEntityType() . ':' . $this->public_id . ':' . $this->getName(); } else {
} $entity->public_id = 1;
}
/* return $entity;
public function getEntityType() }
{
return '';
}
public function getNmae() public static function getPrivateId($publicId)
{ {
return ''; $className = get_called_class();
}
*/
public function scopeScope($query, $publicId = false, $accountId = false) return $className::scope($publicId)->pluck('id');
{ }
if (!$accountId)
{
$accountId = Auth::user()->account_id;
}
$query->whereAccountId($accountId);
if ($publicId) public function getActivityKey()
{ {
if (is_array($publicId)) return $this->getEntityType().':'.$this->public_id.':'.$this->getName();
{ }
$query->whereIn('public_id', $publicId);
} /*
else public function getEntityType()
{ {
$query->wherePublicId($publicId); return '';
} }
}
public function getNmae()
return $query; {
} return '';
} }
*/
public function scopeScope($query, $publicId = false, $accountId = false)
{
if (!$accountId) {
$accountId = Auth::user()->account_id;
}
$query->whereAccountId($accountId);
if ($publicId) {
if (is_array($publicId)) {
$query->whereIn('public_id', $publicId);
} else {
$query->wherePublicId($publicId);
}
}
return $query;
}
}

View File

@ -2,6 +2,6 @@
class Frequency extends Eloquent class Frequency extends Eloquent
{ {
public $timestamps = false; public $timestamps = false;
protected $softDelete = false; protected $softDelete = false;
} }

View File

@ -2,55 +2,51 @@
class Gateway extends Eloquent class Gateway extends Eloquent
{ {
public $timestamps = true; public $timestamps = true;
protected $softDelete = false; protected $softDelete = false;
public function paymentlibrary() public function paymentlibrary()
{ {
return $this->belongsTo('PaymentLibrary', 'payment_library_id'); return $this->belongsTo('PaymentLibrary', 'payment_library_id');
} }
public function getLogoUrl()
{
return '/images/gateways/logo_'.$this->provider.'.png';
}
public function getHelp() public function getLogoUrl()
{ {
$link = ''; return '/images/gateways/logo_'.$this->provider.'.png';
}
if ($this->id == GATEWAY_AUTHORIZE_NET || $this->id == GATEWAY_AUTHORIZE_NET_SIM) { public function getHelp()
$link = 'http://reseller.authorize.net/application/?id=5560364'; {
} else if ($this->id == GATEWAY_PAYPAL_EXPRESS) { $link = '';
$link = 'https://www.paypal.com/us/cgi-bin/webscr?cmd=_login-api-run';
} else if ($this->id == GATEWAY_TWO_CHECKOUT) {
$link = 'https://www.2checkout.com/referral?r=2c37ac2298';
}
$key = 'texts.gateway_help_' . $this->id; if ($this->id == GATEWAY_AUTHORIZE_NET || $this->id == GATEWAY_AUTHORIZE_NET_SIM) {
$str = trans($key, ['link' => "<a href='$link' target='_blank'>Click here</a>"]); $link = 'http://reseller.authorize.net/application/?id=5560364';
return $key != $str ? $str : ''; } elseif ($this->id == GATEWAY_PAYPAL_EXPRESS) {
} $link = 'https://www.paypal.com/us/cgi-bin/webscr?cmd=_login-api-run';
} elseif ($this->id == GATEWAY_TWO_CHECKOUT) {
public function getFields() $link = 'https://www.2checkout.com/referral?r=2c37ac2298';
{ }
$paymentLibrary = $this->paymentlibrary;
if ($paymentLibrary->id == PAYMENT_LIBRARY_OMNIPAY)
{
$fields = Omnipay::create($this->provider)->getDefaultParameters();
}
else
{
$fields = Payment_Utility::load('config', 'drivers/'.strtolower($this->provider));
}
if ($fields == null) $key = 'texts.gateway_help_'.$this->id;
{ $str = trans($key, ['link' => "<a href='$link' target='_blank'>Click here</a>"]);
$fields = array();
} return $key != $str ? $str : '';
}
return $fields;
} public function getFields()
{
$paymentLibrary = $this->paymentlibrary;
if ($paymentLibrary->id == PAYMENT_LIBRARY_OMNIPAY) {
$fields = Omnipay::create($this->provider)->getDefaultParameters();
} else {
$fields = Payment_Utility::load('config', 'drivers/'.strtolower($this->provider));
}
if ($fields == null) {
$fields = array();
}
return $fields;
}
} }

View File

@ -2,7 +2,6 @@
class Industry extends Eloquent class Industry extends Eloquent
{ {
public $timestamps = false; public $timestamps = false;
protected $softDelete = false; protected $softDelete = false;
} }

View File

@ -2,241 +2,228 @@
class Invoice extends EntityModel class Invoice extends EntityModel
{ {
public function account() public function account()
{ {
return $this->belongsTo('Account'); return $this->belongsTo('Account');
} }
public function user() public function user()
{ {
return $this->belongsTo('User'); return $this->belongsTo('User');
} }
public function client() public function client()
{ {
return $this->belongsTo('Client')->withTrashed(); return $this->belongsTo('Client')->withTrashed();
} }
public function invoice_items() public function invoice_items()
{ {
return $this->hasMany('InvoiceItem'); return $this->hasMany('InvoiceItem');
} }
public function invoice_status() public function invoice_status()
{ {
return $this->belongsTo('InvoiceStatus'); return $this->belongsTo('InvoiceStatus');
} }
public function invoice_design() public function invoice_design()
{ {
return $this->belongsTo('InvoiceDesign'); return $this->belongsTo('InvoiceDesign');
} }
public function invitations() public function invitations()
{ {
return $this->hasMany('Invitation')->orderBy('invitations.contact_id'); return $this->hasMany('Invitation')->orderBy('invitations.contact_id');
} }
public function getName() public function getName()
{ {
return $this->invoice_number; return $this->invoice_number;
} }
public function getLink() public function getLink()
{ {
return link_to('invoices/' . $this->public_id, $this->invoice_number); return link_to('invoices/'.$this->public_id, $this->invoice_number);
} }
public function getEntityType() public function getEntityType()
{ {
return $this->is_quote ? ENTITY_QUOTE : ENTITY_INVOICE; return $this->is_quote ? ENTITY_QUOTE : ENTITY_INVOICE;
} }
public function isSent()
{
return $this->invoice_status_id >= INVOICE_STATUS_SENT;
}
public function isViewed() public function isSent()
{ {
return $this->invoice_status_id >= INVOICE_STATUS_VIEWED; return $this->invoice_status_id >= INVOICE_STATUS_SENT;
} }
public function isPaid() public function isViewed()
{ {
return $this->invoice_status_id >= INVOICE_STATUS_PAID; return $this->invoice_status_id >= INVOICE_STATUS_VIEWED;
} }
public function hidePrivateFields() public function isPaid()
{ {
$this->setVisible([ return $this->invoice_status_id >= INVOICE_STATUS_PAID;
'invoice_number', }
'discount',
'is_amount_discount',
'po_number',
'invoice_date',
'due_date',
'terms',
'public_notes',
'amount',
'balance',
'invoice_items',
'client',
'tax_name',
'tax_rate',
'account',
'invoice_design',
'invoice_design_id',
'is_pro',
'is_quote',
'custom_value1',
'custom_value2',
'custom_taxes1',
'custom_taxes2']);
$this->client->setVisible([
'name',
'id_number',
'vat_number',
'address1',
'address2',
'city',
'state',
'postal_code',
'work_phone',
'payment_terms',
'contacts',
'country',
'currency_id',
'custom_value1',
'custom_value2']);
$this->account->setVisible([ public function hidePrivateFields()
'name', {
'id_number', $this->setVisible([
'vat_number', 'invoice_number',
'address1', 'discount',
'address2', 'is_amount_discount',
'city', 'po_number',
'state', 'invoice_date',
'postal_code', 'due_date',
'work_phone', 'terms',
'work_email', 'public_notes',
'country', 'amount',
'currency_id', 'balance',
'custom_label1', 'invoice_items',
'custom_value1', 'client',
'custom_label2', 'tax_name',
'custom_value2', 'tax_rate',
'custom_client_label1', 'account',
'custom_client_label2', 'invoice_design',
'primary_color', 'invoice_design_id',
'secondary_color', 'is_pro',
'hide_quantity', 'is_quote',
'hide_paid_to_date', 'custom_value1',
'custom_invoice_label1', 'custom_value2',
'custom_invoice_label2']); 'custom_taxes1',
'custom_taxes2', ]);
foreach ($this->invoice_items as $invoiceItem) $this->client->setVisible([
{ 'name',
$invoiceItem->setVisible([ 'id_number',
'product_key', 'vat_number',
'notes', 'address1',
'cost', 'address2',
'qty', 'city',
'tax_name', 'state',
'tax_rate']); 'postal_code',
} 'work_phone',
'payment_terms',
'contacts',
'country',
'currency_id',
'custom_value1',
'custom_value2', ]);
foreach ($this->client->contacts as $contact) $this->account->setVisible([
{ 'name',
$contact->setVisible([ 'id_number',
'first_name', 'vat_number',
'last_name', 'address1',
'email', 'address2',
'phone']); 'city',
} 'state',
'postal_code',
'work_phone',
'work_email',
'country',
'currency_id',
'custom_label1',
'custom_value1',
'custom_label2',
'custom_value2',
'custom_client_label1',
'custom_client_label2',
'primary_color',
'secondary_color',
'hide_quantity',
'hide_paid_to_date',
'custom_invoice_label1',
'custom_invoice_label2', ]);
return $this; foreach ($this->invoice_items as $invoiceItem) {
} $invoiceItem->setVisible([
'product_key',
'notes',
'cost',
'qty',
'tax_name',
'tax_rate', ]);
}
public function shouldSendToday() foreach ($this->client->contacts as $contact) {
{ $contact->setVisible([
if (!$this->start_date || strtotime($this->start_date) > strtotime('now')) 'first_name',
{ 'last_name',
return false; 'email',
} 'phone', ]);
}
if ($this->end_date && strtotime($this->end_date) < strtotime('now')) return $this;
{ }
return false;
}
$dayOfWeekToday = date('w'); public function shouldSendToday()
$dayOfWeekStart = date('w', strtotime($this->start_date)); {
if (!$this->start_date || strtotime($this->start_date) > strtotime('now')) {
return false;
}
$dayOfMonthToday = date('j'); if ($this->end_date && strtotime($this->end_date) < strtotime('now')) {
$dayOfMonthStart = date('j', strtotime($this->start_date)); return false;
}
if (!$this->last_sent_date)
{
return true;
}
else
{
$date1 = new DateTime($this->last_sent_date);
$date2 = new DateTime();
$diff = $date2->diff($date1);
$daysSinceLastSent = $diff->format("%a");
$monthsSinceLastSent = ($diff->format('%y') * 12) + $diff->format('%m');
if ($daysSinceLastSent == 0) $dayOfWeekToday = date('w');
{ $dayOfWeekStart = date('w', strtotime($this->start_date));
return false;
}
}
switch ($this->frequency_id) $dayOfMonthToday = date('j');
{ $dayOfMonthStart = date('j', strtotime($this->start_date));
case FREQUENCY_WEEKLY:
return $daysSinceLastSent >= 7;
case FREQUENCY_TWO_WEEKS:
return $daysSinceLastSent >= 14;
case FREQUENCY_FOUR_WEEKS:
return $daysSinceLastSent >= 28;
case FREQUENCY_MONTHLY:
return $monthsSinceLastSent >= 1;
case FREQUENCY_THREE_MONTHS:
return $monthsSinceLastSent >= 3;
case FREQUENCY_SIX_MONTHS:
return $monthsSinceLastSent >= 6;
case FREQUENCY_ANNUALLY:
return $monthsSinceLastSent >= 12;
default:
return false;
}
return false; if (!$this->last_sent_date) {
} return true;
} else {
$date1 = new DateTime($this->last_sent_date);
$date2 = new DateTime();
$diff = $date2->diff($date1);
$daysSinceLastSent = $diff->format("%a");
$monthsSinceLastSent = ($diff->format('%y') * 12) + $diff->format('%m');
if ($daysSinceLastSent == 0) {
return false;
}
}
switch ($this->frequency_id) {
case FREQUENCY_WEEKLY:
return $daysSinceLastSent >= 7;
case FREQUENCY_TWO_WEEKS:
return $daysSinceLastSent >= 14;
case FREQUENCY_FOUR_WEEKS:
return $daysSinceLastSent >= 28;
case FREQUENCY_MONTHLY:
return $monthsSinceLastSent >= 1;
case FREQUENCY_THREE_MONTHS:
return $monthsSinceLastSent >= 3;
case FREQUENCY_SIX_MONTHS:
return $monthsSinceLastSent >= 6;
case FREQUENCY_ANNUALLY:
return $monthsSinceLastSent >= 12;
default:
return false;
}
return false;
}
} }
Invoice::created(function($invoice) Invoice::created(function ($invoice) {
{ $invoice->account->incrementCounter($invoice->invoice_number, $invoice->is_quote, $invoice->recurring_invoice_id);
$invoice->account->incrementCounter($invoice->invoice_number, $invoice->is_quote, $invoice->recurring_invoice_id); Activity::createInvoice($invoice);
Activity::createInvoice($invoice);
}); });
Invoice::updating(function($invoice) Invoice::updating(function ($invoice) {
{ Activity::updateInvoice($invoice);
Activity::updateInvoice($invoice);
}); });
Invoice::deleting(function($invoice) Invoice::deleting(function ($invoice) {
{ Activity::archiveInvoice($invoice);
Activity::archiveInvoice($invoice);
}); });
Invoice::restoring(function($invoice) Invoice::restoring(function ($invoice) {
{ Activity::restoreInvoice($invoice);
Activity::restoreInvoice($invoice); });
});

View File

@ -2,6 +2,6 @@
class InvoiceDesign extends Eloquent class InvoiceDesign extends Eloquent
{ {
public $timestamps = false; public $timestamps = false;
protected $softDelete = false; protected $softDelete = false;
} }

View File

@ -2,13 +2,13 @@
class InvoiceItem extends EntityModel class InvoiceItem extends EntityModel
{ {
public function invoice() public function invoice()
{ {
return $this->belongsTo('Invoice'); return $this->belongsTo('Invoice');
} }
public function product() public function product()
{ {
return $this->belongsTo('Product'); return $this->belongsTo('Product');
} }
} }

View File

@ -2,6 +2,6 @@
class InvoiceStatus extends Eloquent class InvoiceStatus extends Eloquent
{ {
public $timestamps = false; public $timestamps = false;
protected $softDelete = false; protected $softDelete = false;
} }

View File

@ -2,6 +2,6 @@
class Language extends Eloquent class Language extends Eloquent
{ {
public $timestamps = false; public $timestamps = false;
protected $softDelete = false; protected $softDelete = false;
} }

View File

@ -2,6 +2,6 @@
class License extends Eloquent class License extends Eloquent
{ {
public $timestamps = true; public $timestamps = true;
protected $softDelete = true; protected $softDelete = true;
} }

View File

@ -2,64 +2,59 @@
class Payment extends EntityModel class Payment extends EntityModel
{ {
public function invoice() public function invoice()
{ {
return $this->belongsTo('Invoice')->withTrashed();; return $this->belongsTo('Invoice')->withTrashed();
} }
public function invitation() public function invitation()
{ {
return $this->belongsTo('Invitation'); return $this->belongsTo('Invitation');
} }
public function client() public function client()
{ {
return $this->belongsTo('Client')->withTrashed();; return $this->belongsTo('Client')->withTrashed();
} }
public function account() public function account()
{ {
return $this->belongsTo('Account'); return $this->belongsTo('Account');
} }
public function contact() public function contact()
{ {
return $this->belongsTo('Contact'); return $this->belongsTo('Contact');
} }
public function getAmount() public function getAmount()
{ {
return Utils::formatMoney($this->amount, $this->client->currency_id); return Utils::formatMoney($this->amount, $this->client->currency_id);
} }
public function getName() public function getName()
{ {
return trim("payment {$this->transaction_reference}"); return trim("payment {$this->transaction_reference}");
} }
public function getEntityType()
{
return ENTITY_PAYMENT;
}
public function getEntityType()
{
return ENTITY_PAYMENT;
}
} }
Payment::created(function($payment) Payment::created(function ($payment) {
{ Activity::createPayment($payment);
Activity::createPayment($payment);
}); });
Payment::updating(function($payment) Payment::updating(function ($payment) {
{ Activity::updatePayment($payment);
Activity::updatePayment($payment);
}); });
Payment::deleting(function($payment) Payment::deleting(function ($payment) {
{ Activity::archivePayment($payment);
Activity::archivePayment($payment);
}); });
Payment::restoring(function($payment) Payment::restoring(function ($payment) {
{ Activity::restorePayment($payment);
Activity::restorePayment($payment); });
});

View File

@ -2,11 +2,11 @@
class PaymentLibrary extends Eloquent class PaymentLibrary extends Eloquent
{ {
protected $table = 'payment_libraries'; protected $table = 'payment_libraries';
public $timestamps = true; public $timestamps = true;
public function gateways() public function gateways()
{ {
return $this->hasMany('Gateway', 'payment_library_id'); return $this->hasMany('Gateway', 'payment_library_id');
} }
} }

View File

@ -2,6 +2,6 @@
class PaymentTerm extends Eloquent class PaymentTerm extends Eloquent
{ {
public $timestamps = false; public $timestamps = false;
protected $softDelete = false; protected $softDelete = false;
} }

View File

@ -2,6 +2,6 @@
class PaymentType extends Eloquent class PaymentType extends Eloquent
{ {
public $timestamps = false; public $timestamps = false;
protected $softDelete = false; protected $softDelete = false;
} }

View File

@ -1,9 +1,9 @@
<?php <?php
class Product extends EntityModel class Product extends EntityModel
{ {
public static function findProductByKey($key) public static function findProductByKey($key)
{ {
return Product::scope()->where('product_key','=',$key)->first(); return Product::scope()->where('product_key', '=', $key)->first();
} }
} }

View File

@ -2,50 +2,44 @@
class Project extends Eloquent class Project extends Eloquent
{ {
public $timestamps = true; public $timestamps = true;
protected $softDelete = true; protected $softDelete = true;
public function account() public function account()
{ {
return $this->belongsTo('Account'); return $this->belongsTo('Account');
} }
public function user()
{
return $this->belongsTo('User');
}
public function user()
{
return $this->belongsTo('User');
}
public function client() public function client()
{ {
return $this->belongsTo('Client'); return $this->belongsTo('Client');
} }
public function codes()
{
return $this->hasMany('ProjectCode');
}
public static function createNew($parent = false)
{
$className = get_called_class();
$entity = new $className();
if ($parent)
{
$entity->user_id = $parent instanceof User ? $parent->id : $parent->user_id;
$entity->account_id = $parent->account_id;
}
else if (Auth::check())
{
$entity->user_id = Auth::user()->id;
$entity->account_id = Auth::user()->account_id;
}
else
{
Utils::fatalError();
}
return $entity;
}
}
public function codes()
{
return $this->hasMany('ProjectCode');
}
public static function createNew($parent = false)
{
$className = get_called_class();
$entity = new $className();
if ($parent) {
$entity->user_id = $parent instanceof User ? $parent->id : $parent->user_id;
$entity->account_id = $parent->account_id;
} elseif (Auth::check()) {
$entity->user_id = Auth::user()->id;
$entity->account_id = Auth::user()->account_id;
} else {
Utils::fatalError();
}
return $entity;
}
}

View File

@ -2,49 +2,44 @@
class ProjectCode extends Eloquent class ProjectCode extends Eloquent
{ {
public $timestamps = true; public $timestamps = true;
protected $softDelete = true; protected $softDelete = true;
public function account() public function account()
{ {
return $this->belongsTo('Account'); return $this->belongsTo('Account');
} }
public function user()
{
return $this->belongsTo('User');
}
public function user()
{
return $this->belongsTo('User');
}
public function project() public function project()
{ {
return $this->belongsTo('Project'); return $this->belongsTo('Project');
} }
public function events() public function events()
{ {
return $this->hasMany('TimesheetEvent'); return $this->hasMany('TimesheetEvent');
} }
public static function createNew($parent = false) public static function createNew($parent = false)
{ {
$className = get_called_class(); $className = get_called_class();
$entity = new $className(); $entity = new $className();
if ($parent) if ($parent) {
{ $entity->user_id = $parent instanceof User ? $parent->id : $parent->user_id;
$entity->user_id = $parent instanceof User ? $parent->id : $parent->user_id; $entity->account_id = $parent->account_id;
$entity->account_id = $parent->account_id; } elseif (Auth::check()) {
} $entity->user_id = Auth::user()->id;
else if (Auth::check()) $entity->account_id = Auth::user()->account_id;
{ } else {
$entity->user_id = Auth::user()->id; Utils::fatalError();
$entity->account_id = Auth::user()->account_id; }
}
else return $entity;
{ }
Utils::fatalError(); }
}
return $entity;
}
}

View File

@ -2,6 +2,6 @@
class Size extends Eloquent class Size extends Eloquent
{ {
public $timestamps = false; public $timestamps = false;
protected $softDelete = false; protected $softDelete = false;
} }

View File

@ -2,6 +2,6 @@
class Subscription extends Eloquent class Subscription extends Eloquent
{ {
public $timestamps = true; public $timestamps = true;
protected $softDelete = true; protected $softDelete = true;
} }

View File

@ -2,5 +2,4 @@
class TaxRate extends EntityModel class TaxRate extends EntityModel
{ {
}
}

View File

@ -2,6 +2,6 @@
class Theme extends Eloquent class Theme extends Eloquent
{ {
public $timestamps = false; public $timestamps = false;
protected $softDelete = false; protected $softDelete = false;
} }

View File

@ -2,21 +2,21 @@
class Timesheet extends Eloquent class Timesheet extends Eloquent
{ {
public $timestamps = true; public $timestamps = true;
protected $softDelete = true; protected $softDelete = true;
public function account() public function account()
{ {
return $this->belongsTo('Account'); return $this->belongsTo('Account');
} }
public function user()
{
return $this->belongsTo('User');
}
public function user()
{
return $this->belongsTo('User');
}
public function timesheet_events() public function timesheet_events()
{ {
return $this->hasMany('TimeSheetEvent'); return $this->hasMany('TimeSheetEvent');
} }
} }

View File

@ -2,11 +2,11 @@
class TimesheetEvent extends Eloquent class TimesheetEvent extends Eloquent
{ {
public $timestamps = true; public $timestamps = true;
protected $softDelete = true; protected $softDelete = true;
/* protected $dates = array('org_updated_at'); /* protected $dates = array('org_updated_at');
public function getDates() { public function getDates() {
return array('created_at', 'updated_at', 'deleted_at'); return array('created_at', 'updated_at', 'deleted_at');
} */ } */
@ -16,63 +16,58 @@ class TimesheetEvent extends Eloquent
var_dump($value); var_dump($value);
$this->attributes['org_updated_at'] = $value->getTimestamp(); $this->attributes['org_updated_at'] = $value->getTimestamp();
}*/ }*/
public function account() public function account()
{ {
return $this->belongsTo('Account'); return $this->belongsTo('Account');
} }
public function user()
{
return $this->belongsTo('User');
}
public function user()
{
return $this->belongsTo('User');
}
public function source() public function source()
{ {
return $this->belongsTo('TimesheetEventSource'); return $this->belongsTo('TimesheetEventSource');
} }
public function timesheet() public function timesheet()
{ {
return $this->belongsTo('Timesheet'); return $this->belongsTo('Timesheet');
} }
public function project()
{
return $this->belongsTo('Project');
}
public function project()
{
return $this->belongsTo('Project');
}
public function project_code() public function project_code()
{ {
return $this->belongsTo('ProjectCode'); return $this->belongsTo('ProjectCode');
} }
/** /**
* @return TimesheetEvent * @return TimesheetEvent
*/ */
public static function createNew($parent = false) public static function createNew($parent = false)
{ {
$className = get_called_class(); $className = get_called_class();
$entity = new $className(); $entity = new $className();
if ($parent) if ($parent) {
{ $entity->user_id = $parent instanceof User ? $parent->id : $parent->user_id;
$entity->user_id = $parent instanceof User ? $parent->id : $parent->user_id; $entity->account_id = $parent->account_id;
$entity->account_id = $parent->account_id; } elseif (Auth::check()) {
} $entity->user_id = Auth::user()->id;
else if (Auth::check()) $entity->account_id = Auth::user()->account_id;
{ } else {
$entity->user_id = Auth::user()->id; Utils::fatalError();
$entity->account_id = Auth::user()->account_id; }
}
else return $entity;
{ }
Utils::fatalError();
}
return $entity;
}
public function toChangesArray(TimesheetEvent $other) public function toChangesArray(TimesheetEvent $other)
{ {
$attributes_old = parent::toArray(); $attributes_old = parent::toArray();
@ -80,50 +75,48 @@ class TimesheetEvent extends Eloquent
$skip_keys = ['id' => 1, 'created_at' => 1, 'updated_at' => 1, 'deleted_at' => 1, 'org_data' => 1, 'update_data' => 1]; $skip_keys = ['id' => 1, 'created_at' => 1, 'updated_at' => 1, 'deleted_at' => 1, 'org_data' => 1, 'update_data' => 1];
$zeroisempty_keys = ['discount' => 1]; $zeroisempty_keys = ['discount' => 1];
$result = []; $result = [];
// Find all the values that where changed or deleted // Find all the values that where changed or deleted
foreach ($attributes_old as $key => $value) { foreach ($attributes_old as $key => $value) {
// Skip null values, keys we don't care about and 0 value keys that means they are not used // Skip null values, keys we don't care about and 0 value keys that means they are not used
if(empty($value) || isset($skip_keys[$key])|| (isset($zeroisempty_keys[$key]) && $value) ) { if (empty($value) || isset($skip_keys[$key]) || (isset($zeroisempty_keys[$key]) && $value)) {
continue; continue;
} }
// Compare values if it exists in the new array // Compare values if it exists in the new array
if(isset($attributes_new[$key]) || array_key_exists($key, $attributes_new)) { if (isset($attributes_new[$key]) || array_key_exists($key, $attributes_new)) {
if($value instanceof \DateTime && $attributes_new[$key] instanceof \DateTime) { if ($value instanceof \DateTime && $attributes_new[$key] instanceof \DateTime) {
if($value != $attributes_new[$key]) { if ($value != $attributes_new[$key]) {
$result[$key] = $attributes_new[$key]->format("Y-m-d H:i:s"); $result[$key] = $attributes_new[$key]->format("Y-m-d H:i:s");
} }
} elseif($value instanceof \DateTime && is_string($attributes_new[$key])) { } elseif ($value instanceof \DateTime && is_string($attributes_new[$key])) {
if($value->format("Y-m-d H:i:s") != $attributes_new[$key]) { if ($value->format("Y-m-d H:i:s") != $attributes_new[$key]) {
$result[$key] = $attributes_new[$key]; $result[$key] = $attributes_new[$key];
} }
} elseif(is_string($value) && $attributes_new[$key] instanceof \DateTime) { } elseif (is_string($value) && $attributes_new[$key] instanceof \DateTime) {
if($attributes_new[$key]->format("Y-m-d H:i:s") != $value) { if ($attributes_new[$key]->format("Y-m-d H:i:s") != $value) {
$result[$key] = $attributes_new[$key]->format("Y-m-d H:i:s"); $result[$key] = $attributes_new[$key]->format("Y-m-d H:i:s");
} }
} elseif($value != $attributes_new[$key]) { } elseif ($value != $attributes_new[$key]) {
$result[$key] = $attributes_new[$key]; $result[$key] = $attributes_new[$key];
} }
} else { } else {
$result[$key] = null; $result[$key] = null;
} }
} }
// Find all the values that where deleted // Find all the values that where deleted
foreach ($attributes_new as $key => $value) { foreach ($attributes_new as $key => $value) {
if(isset($skip_keys[$key])) { if (isset($skip_keys[$key])) {
continue; continue;
} }
if(!isset($attributes_old[$key])) { if (!isset($attributes_old[$key])) {
$result[$key] = $value; $result[$key] = $value;
} }
} }
return $result; return $result;
} }
} }

View File

@ -2,45 +2,39 @@
class TimesheetEventSource extends Eloquent class TimesheetEventSource extends Eloquent
{ {
public $timestamps = true; public $timestamps = true;
protected $softDelete = true; protected $softDelete = true;
public function account() public function account()
{ {
return $this->belongsTo('Account'); return $this->belongsTo('Account');
} }
public function user()
{
return $this->belongsTo('User');
}
public function user()
{
return $this->belongsTo('User');
}
public function events() public function events()
{ {
return $this->hasMany('TimesheetEvent'); return $this->hasMany('TimesheetEvent');
} }
public static function createNew($parent = false) public static function createNew($parent = false)
{ {
$className = get_called_class(); $className = get_called_class();
$entity = new $className(); $entity = new $className();
if ($parent) if ($parent) {
{ $entity->user_id = $parent instanceof User ? $parent->id : $parent->user_id;
$entity->user_id = $parent instanceof User ? $parent->id : $parent->user_id; $entity->account_id = $parent->account_id;
$entity->account_id = $parent->account_id; } elseif (Auth::check()) {
} $entity->user_id = Auth::user()->id;
else if (Auth::check()) $entity->account_id = Auth::user()->account_id;
{ } else {
$entity->user_id = Auth::user()->id; Utils::fatalError();
$entity->account_id = Auth::user()->account_id; }
}
else return $entity;
{ }
Utils::fatalError(); }
}
return $entity;
}
}

View File

@ -1,7 +1,7 @@
<?php <?php
class Timezone extends Eloquent class Timezone extends Eloquent
{ {
public $timestamps = false; public $timestamps = false;
protected $softDelete = false; protected $softDelete = false;
} }

View File

@ -6,182 +6,165 @@ use Zizaco\Confide\ConfideUser;
class User extends ConfideUser implements UserInterface, RemindableInterface class User extends ConfideUser implements UserInterface, RemindableInterface
{ {
protected $softDelete = true; protected $softDelete = true;
public static $rules = array( public static $rules = array(
/* /*
'username' => 'required|unique:users', 'username' => 'required|unique:users',
'password' => 'required|between:6,32|confirmed', 'password' => 'required|between:6,32|confirmed',
'password_confirmation' => 'between:6,32', 'password_confirmation' => 'between:6,32',
*/ */
); );
protected $updateRules = array( protected $updateRules = array(
/* /*
'email' => 'required|unique:users', 'email' => 'required|unique:users',
'username' => 'required|unique:users', 'username' => 'required|unique:users',
*/ */
); );
/** /**
* The database table used by the model. * The database table used by the model.
* *
* @var string * @var string
*/ */
protected $table = 'users'; protected $table = 'users';
public function account() public function account()
{ {
return $this->belongsTo('Account'); return $this->belongsTo('Account');
} }
public function theme() public function theme()
{ {
return $this->belongsTo('Theme'); return $this->belongsTo('Theme');
} }
public function getPersonType() public function getPersonType()
{ {
return PERSON_USER; return PERSON_USER;
} }
/** /**
* Get the unique identifier for the user. * Get the unique identifier for the user.
* *
* @return mixed * @return mixed
*/ */
public function getAuthIdentifier() public function getAuthIdentifier()
{ {
return $this->getKey(); return $this->getKey();
} }
/** /**
* Get the password for the user. * Get the password for the user.
* *
* @return string * @return string
*/ */
public function getAuthPassword() public function getAuthPassword()
{ {
return $this->password; return $this->password;
} }
/** /**
* Get the e-mail address where password reminders are sent. * Get the e-mail address where password reminders are sent.
* *
* @return string * @return string
*/ */
public function getReminderEmail() public function getReminderEmail()
{ {
return $this->email; return $this->email;
} }
public function isPro() public function isPro()
{ {
return $this->account->isPro(); return $this->account->isPro();
} }
public function isDemo() public function isDemo()
{ {
return $this->account->id == Utils::getDemoAccountId(); return $this->account->id == Utils::getDemoAccountId();
} }
public function maxInvoiceDesignId() public function maxInvoiceDesignId()
{ {
return $this->isPro() ? 10 : COUNT_FREE_DESIGNS; return $this->isPro() ? 10 : COUNT_FREE_DESIGNS;
} }
public function getDisplayName() public function getDisplayName()
{ {
if ($this->getFullName()) if ($this->getFullName()) {
{ return $this->getFullName();
return $this->getFullName(); } elseif ($this->email) {
} return $this->email;
else if ($this->email) } else {
{ return 'Guest';
return $this->email; }
} }
else
{
return 'Guest';
}
}
public function getFullName()
{
if ($this->first_name || $this->last_name) {
return $this->first_name.' '.$this->last_name;
} else {
return '';
}
}
public function getFullName() public function showGreyBackground()
{ {
if ($this->first_name || $this->last_name) return !$this->theme_id || in_array($this->theme_id, [2, 3, 5, 6, 7, 8, 10, 11, 12]);
{ }
return $this->first_name . ' ' . $this->last_name;
}
else
{
return '';
}
}
public function showGreyBackground() public function getRequestsCount()
{ {
return !$this->theme_id || in_array($this->theme_id, [2, 3, 5, 6, 7, 8, 10, 11, 12]); return Session::get(SESSION_COUNTER, 0);
} }
public function getRequestsCount() public function getPopOverText()
{ {
return Session::get(SESSION_COUNTER, 0); if (!Utils::isNinja() || !Auth::check() || Session::has('error')) {
} return false;
}
public function getPopOverText() $count = self::getRequestsCount();
{
if (!Utils::isNinja() || !Auth::check() || Session::has('error'))
{
return false;
}
$count = self::getRequestsCount(); if ($count == 1 || $count % 5 == 0) {
if (!Utils::isRegistered()) {
if ($count == 1 || $count % 5 == 0) return trans('texts.sign_up_to_save');
{ } elseif (!Auth::user()->account->name) {
if (!Utils::isRegistered()) return trans('texts.set_name');
{ }
return trans('texts.sign_up_to_save'); }
}
else if (!Auth::user()->account->name)
{
return trans('texts.set_name');
}
}
return false; return false;
} }
public function afterSave($success=true, $forced = false) public function afterSave($success = true, $forced = false)
{ {
if ($this->email) if ($this->email) {
{ return parent::afterSave($success = true, $forced = false);
return parent::afterSave($success=true, $forced = false); } else {
} return true;
else }
{ }
return true;
}
}
public function getMaxNumClients() public function getMaxNumClients()
{ {
return $this->isPro() ? MAX_NUM_CLIENTS_PRO : MAX_NUM_CLIENTS; return $this->isPro() ? MAX_NUM_CLIENTS_PRO : MAX_NUM_CLIENTS;
} }
public function getRememberToken() public function getRememberToken()
{ {
return $this->remember_token; return $this->remember_token;
} }
public function setRememberToken($value) public function setRememberToken($value)
{ {
$this->remember_token = $value; $this->remember_token = $value;
} }
public function getRememberTokenName() public function getRememberTokenName()
{ {
return 'remember_token'; return 'remember_token';
} }
} }

View File

@ -25,7 +25,7 @@ class ContactMailer extends Mailer
if (!$invitation->contact || $invitation->contact->email) { if (!$invitation->contact || $invitation->contact->email) {
return false; return false;
} }
$invitation->sent_date = \Carbon::now()->toDateTimeString(); $invitation->sent_date = \Carbon::now()->toDateTimeString();
$invitation->save(); $invitation->save();

View File

@ -3,26 +3,24 @@
use Mail; use Mail;
use Utils; use Utils;
class Mailer { class Mailer
{
public function sendTo($toEmail, $fromEmail, $fromName, $subject, $view, $data = [])
{
$views = [
'emails.'.$view.'_html',
'emails.'.$view.'_text',
];
public function sendTo($toEmail, $fromEmail, $fromName, $subject, $view, $data = []) Mail::send($views, $data, function ($message) use ($toEmail, $fromEmail, $fromName, $subject) {
{ $replyEmail = $fromEmail;
$views = [
'emails.'.$view.'_html',
'emails.'.$view.'_text'
];
Mail::send($views, $data, function($message) use ($toEmail, $fromEmail, $fromName, $subject)
{
$replyEmail = $fromEmail;
// http://stackoverflow.com/questions/2421234/gmail-appearing-to-ignore-reply-to // http://stackoverflow.com/questions/2421234/gmail-appearing-to-ignore-reply-to
if (Utils::isNinja() && $toEmail != CONTACT_EMAIL) if (Utils::isNinja() && $toEmail != CONTACT_EMAIL) {
{ $fromEmail = NINJA_FROM_EMAIL;
$fromEmail = NINJA_FROM_EMAIL; }
}
$message->to($toEmail)->from($fromEmail, $fromName)->replyTo($replyEmail, $fromName)->subject($subject); $message->to($toEmail)->from($fromEmail, $fromName)->replyTo($replyEmail, $fromName)->subject($subject);
}); });
} }
} }

View File

@ -2,68 +2,61 @@
use Invoice; use Invoice;
use Payment; use Payment;
use Contact;
use User; use User;
use Utils; use Utils;
class UserMailer extends Mailer { class UserMailer extends Mailer
{
public function sendConfirmation(User $user, User $invitor = null)
{
if (!$user->email) {
return;
}
public function sendConfirmation(User $user, User $invitor = null) $view = 'confirm';
{ $subject = trans('texts.confirmation_subject');
if (!$user->email)
{
return;
}
$view = 'confirm'; $data = [
$subject = trans('texts.confirmation_subject'); 'user' => $user,
'invitationMessage' => $invitor ? trans('texts.invitation_message', ['invitor' => $invitor->getDisplayName()]) : '',
];
$data = [ if ($invitor) {
'user' => $user, $fromEmail = $invitor->email;
'invitationMessage' => $invitor ? trans('texts.invitation_message', ['invitor' => $invitor->getDisplayName()]) : '' $fromName = $invitor->getDisplayName();
]; } else {
$fromEmail = CONTACT_EMAIL;
if ($invitor) $fromName = CONTACT_NAME;
{ }
$fromEmail = $invitor->email;
$fromName = $invitor->getDisplayName();
}
else
{
$fromEmail = CONTACT_EMAIL;
$fromName = CONTACT_NAME;
}
$this->sendTo($user->email, $fromEmail, $fromName, $subject, $view, $data); $this->sendTo($user->email, $fromEmail, $fromName, $subject, $view, $data);
} }
public function sendNotification(User $user, Invoice $invoice, $notificationType, Payment $payment = null) public function sendNotification(User $user, Invoice $invoice, $notificationType, Payment $payment = null)
{ {
if (!$user->email) if (!$user->email) {
{ return;
return; }
}
$view = 'invoice_' . $notificationType; $view = 'invoice_'.$notificationType;
$entityType = $invoice->getEntityType(); $entityType = $invoice->getEntityType();
$data = [ $data = [
'entityType' => $entityType, 'entityType' => $entityType,
'clientName' => $invoice->client->getDisplayName(), 'clientName' => $invoice->client->getDisplayName(),
'accountName' => $invoice->account->getDisplayName(), 'accountName' => $invoice->account->getDisplayName(),
'userName' => $user->getDisplayName(), 'userName' => $user->getDisplayName(),
'invoiceAmount' => Utils::formatMoney($invoice->amount, $invoice->client->currency_id), 'invoiceAmount' => Utils::formatMoney($invoice->amount, $invoice->client->currency_id),
'invoiceNumber' => $invoice->invoice_number, 'invoiceNumber' => $invoice->invoice_number,
'invoiceLink' => SITE_URL . "/{$entityType}s/{$invoice->public_id}" 'invoiceLink' => SITE_URL."/{$entityType}s/{$invoice->public_id}",
]; ];
if ($payment) if ($payment) {
{ $data['paymentAmount'] = Utils::formatMoney($payment->amount, $invoice->client->currency_id);
$data['paymentAmount'] = Utils::formatMoney($payment->amount, $invoice->client->currency_id); }
}
$subject = trans("texts.notification_{$entityType}_{$notificationType}_subject", ['invoice'=>$invoice->invoice_number, 'client'=>$invoice->client->getDisplayName()]); $subject = trans("texts.notification_{$entityType}_{$notificationType}_subject", ['invoice' => $invoice->invoice_number, 'client' => $invoice->client->getDisplayName()]);
$this->sendTo($user->email, CONTACT_EMAIL, CONTACT_NAME, $subject, $view, $data); $this->sendTo($user->email, CONTACT_EMAIL, CONTACT_NAME, $subject, $view, $data);
} }
} }

View File

@ -16,231 +16,219 @@ use Utils;
class AccountRepository class AccountRepository
{ {
public function create() public function create()
{ {
$account = new Account; $account = new Account();
$account->ip = Request::getClientIp(); $account->ip = Request::getClientIp();
$account->account_key = str_random(RANDOM_KEY_LENGTH); $account->account_key = str_random(RANDOM_KEY_LENGTH);
if (Session::has(SESSION_LOCALE)) if (Session::has(SESSION_LOCALE)) {
{ $locale = Session::get(SESSION_LOCALE);
$locale = Session::get(SESSION_LOCALE); if ($language = Language::whereLocale($locale)->first()) {
if ($language = Language::whereLocale($locale)->first()) $account->language_id = $language->id;
{ }
$account->language_id = $language->id; }
}
}
$account->save(); $account->save();
$random = str_random(RANDOM_KEY_LENGTH);
$user = new User; $random = str_random(RANDOM_KEY_LENGTH);
$user->password = $random;
$user->password_confirmation = $random;
$user->username = $random;
$user->confirmed = !Utils::isNinja();
$account->users()->save($user, []);
return $account;
}
public function getSearchData() $user = new User();
{ $user->password = $random;
$clients = \DB::table('clients') $user->password_confirmation = $random;
->where('clients.deleted_at', '=', null) $user->username = $random;
->where('clients.account_id', '=', \Auth::user()->account_id) $user->confirmed = !Utils::isNinja();
->whereRaw("clients.name <> ''") $account->users()->save($user, []);
->select(\DB::raw("'Clients' as type, clients.public_id, clients.name, '' as token"));
$contacts = \DB::table('clients') return $account;
->join('contacts', 'contacts.client_id', '=', 'clients.id') }
->where('clients.deleted_at', '=', null)
->where('clients.account_id', '=', \Auth::user()->account_id)
->whereRaw("CONCAT(contacts.first_name, contacts.last_name, contacts.email) <> ''")
->select(\DB::raw("'Contacts' as type, clients.public_id, CONCAT(contacts.first_name, ' ', contacts.last_name, ' ', contacts.email) as name, '' as token"));
$invoices = \DB::table('clients') public function getSearchData()
->join('invoices', 'invoices.client_id', '=', 'clients.id') {
->where('clients.account_id', '=', \Auth::user()->account_id) $clients = \DB::table('clients')
->where('clients.deleted_at', '=', null) ->where('clients.deleted_at', '=', null)
->where('invoices.deleted_at', '=', null) ->where('clients.account_id', '=', \Auth::user()->account_id)
->select(\DB::raw("'Invoices' as type, invoices.public_id, CONCAT(invoices.invoice_number, ': ', clients.name) as name, invoices.invoice_number as token")); ->whereRaw("clients.name <> ''")
->select(\DB::raw("'Clients' as type, clients.public_id, clients.name, '' as token"));
$data = []; $contacts = \DB::table('clients')
->join('contacts', 'contacts.client_id', '=', 'clients.id')
->where('clients.deleted_at', '=', null)
->where('clients.account_id', '=', \Auth::user()->account_id)
->whereRaw("CONCAT(contacts.first_name, contacts.last_name, contacts.email) <> ''")
->select(\DB::raw("'Contacts' as type, clients.public_id, CONCAT(contacts.first_name, ' ', contacts.last_name, ' ', contacts.email) as name, '' as token"));
foreach ($clients->union($contacts)->union($invoices)->get() as $row) $invoices = \DB::table('clients')
{ ->join('invoices', 'invoices.client_id', '=', 'clients.id')
$type = $row->type; ->where('clients.account_id', '=', \Auth::user()->account_id)
->where('clients.deleted_at', '=', null)
->where('invoices.deleted_at', '=', null)
->select(\DB::raw("'Invoices' as type, invoices.public_id, CONCAT(invoices.invoice_number, ': ', clients.name) as name, invoices.invoice_number as token"));
if (!isset($data[$type])) $data = [];
{
$data[$type] = [];
}
$tokens = explode(' ', $row->name); foreach ($clients->union($contacts)->union($invoices)->get() as $row) {
$tokens[] = $type; $type = $row->type;
if ($type == 'Invoices') if (!isset($data[$type])) {
{ $data[$type] = [];
$tokens[] = intVal($row->token) . ''; }
}
$data[$type][] = [ $tokens = explode(' ', $row->name);
'value' => $row->name, $tokens[] = $type;
'public_id' => $row->public_id,
'tokens' => $tokens
];
}
return $data;
}
if ($type == 'Invoices') {
$tokens[] = intVal($row->token).'';
}
public function enableProPlan() $data[$type][] = [
{ 'value' => $row->name,
if (Auth::user()->isPro()) 'public_id' => $row->public_id,
{ 'tokens' => $tokens,
return false; ];
} }
$ninjaAccount = $this->getNinjaAccount(); return $data;
$lastInvoice = Invoice::withTrashed()->whereAccountId($ninjaAccount->id)->orderBy('public_id', 'DESC')->first(); }
$publicId = $lastInvoice ? ($lastInvoice->public_id + 1) : 1;
$ninjaClient = $this->getNinjaClient($ninjaAccount); public function enableProPlan()
$invitation = $this->createNinjaInvoice($publicId, $ninjaAccount, $ninjaClient); {
if (Auth::user()->isPro()) {
return false;
}
return $invitation; $ninjaAccount = $this->getNinjaAccount();
} $lastInvoice = Invoice::withTrashed()->whereAccountId($ninjaAccount->id)->orderBy('public_id', 'DESC')->first();
$publicId = $lastInvoice ? ($lastInvoice->public_id + 1) : 1;
private function createNinjaInvoice($publicId, $account, $client) $ninjaClient = $this->getNinjaClient($ninjaAccount);
{ $invitation = $this->createNinjaInvoice($publicId, $ninjaAccount, $ninjaClient);
$invoice = new Invoice();
$invoice->account_id = $account->id;
$invoice->user_id = $account->users()->first()->id;
$invoice->public_id = $publicId;
$invoice->client_id = $client->id;
$invoice->invoice_number = $account->getNextInvoiceNumber();
$invoice->invoice_date = date_create()->format('Y-m-d');
$invoice->amount = PRO_PLAN_PRICE;
$invoice->balance = PRO_PLAN_PRICE;
$invoice->save();
$item = new InvoiceItem(); return $invitation;
$item->account_id = $account->id; }
$item->user_id = $account->users()->first()->id;
$item->public_id = $publicId;
$item->qty = 1;
$item->cost = PRO_PLAN_PRICE;
$item->notes = trans('texts.pro_plan_description');
$item->product_key = trans('texts.pro_plan_product');
$invoice->invoice_items()->save($item);
$invitation = new Invitation(); private function createNinjaInvoice($publicId, $account, $client)
$invitation->account_id = $account->id; {
$invitation->user_id = $account->users()->first()->id; $invoice = new Invoice();
$invitation->public_id = $publicId; $invoice->account_id = $account->id;
$invitation->invoice_id = $invoice->id; $invoice->user_id = $account->users()->first()->id;
$invitation->contact_id = $client->contacts()->first()->id; $invoice->public_id = $publicId;
$invitation->invitation_key = str_random(RANDOM_KEY_LENGTH); $invoice->client_id = $client->id;
$invitation->save(); $invoice->invoice_number = $account->getNextInvoiceNumber();
$invoice->invoice_date = date_create()->format('Y-m-d');
$invoice->amount = PRO_PLAN_PRICE;
$invoice->balance = PRO_PLAN_PRICE;
$invoice->save();
return $invitation; $item = new InvoiceItem();
} $item->account_id = $account->id;
$item->user_id = $account->users()->first()->id;
$item->public_id = $publicId;
$item->qty = 1;
$item->cost = PRO_PLAN_PRICE;
$item->notes = trans('texts.pro_plan_description');
$item->product_key = trans('texts.pro_plan_product');
$invoice->invoice_items()->save($item);
public function getNinjaAccount() $invitation = new Invitation();
{ $invitation->account_id = $account->id;
$account = Account::whereAccountKey(NINJA_ACCOUNT_KEY)->first(); $invitation->user_id = $account->users()->first()->id;
$invitation->public_id = $publicId;
$invitation->invoice_id = $invoice->id;
$invitation->contact_id = $client->contacts()->first()->id;
$invitation->invitation_key = str_random(RANDOM_KEY_LENGTH);
$invitation->save();
if ($account) return $invitation;
{ }
return $account;
}
else
{
$account = new Account();
$account->name = 'Invoice Ninja';
$account->work_email = 'contact@invoiceninja.com';
$account->work_phone = '(800) 763-1948';
$account->account_key = NINJA_ACCOUNT_KEY;
$account->save();
$random = str_random(RANDOM_KEY_LENGTH); public function getNinjaAccount()
$user = new User(); {
$user->registered = true; $account = Account::whereAccountKey(NINJA_ACCOUNT_KEY)->first();
$user->confirmed = true;
$user->email = 'contact@invoiceninja.com';
$user->password = $random;
$user->password_confirmation = $random;
$user->username = $random;
$user->first_name = 'Invoice';
$user->last_name = 'Ninja';
$user->notify_sent = true;
$user->notify_paid = true;
$account->users()->save($user);
$accountGateway = new AccountGateway(); if ($account) {
$accountGateway->user_id = $user->id; return $account;
$accountGateway->gateway_id = NINJA_GATEWAY_ID; } else {
$accountGateway->public_id = 1; $account = new Account();
$accountGateway->config = NINJA_GATEWAY_CONFIG; $account->name = 'Invoice Ninja';
$account->account_gateways()->save($accountGateway); $account->work_email = 'contact@invoiceninja.com';
} $account->work_phone = '(800) 763-1948';
$account->account_key = NINJA_ACCOUNT_KEY;
$account->save();
return $account; $random = str_random(RANDOM_KEY_LENGTH);
} $user = new User();
$user->registered = true;
$user->confirmed = true;
$user->email = 'contact@invoiceninja.com';
$user->password = $random;
$user->password_confirmation = $random;
$user->username = $random;
$user->first_name = 'Invoice';
$user->last_name = 'Ninja';
$user->notify_sent = true;
$user->notify_paid = true;
$account->users()->save($user);
private function getNinjaClient($ninjaAccount) $accountGateway = new AccountGateway();
{ $accountGateway->user_id = $user->id;
$client = Client::whereAccountId($ninjaAccount->id)->wherePublicId(Auth::user()->account_id)->first(); $accountGateway->gateway_id = NINJA_GATEWAY_ID;
$accountGateway->public_id = 1;
$accountGateway->config = NINJA_GATEWAY_CONFIG;
$account->account_gateways()->save($accountGateway);
}
if (!$client) return $account;
{ }
$client = new Client;
$client->public_id = Auth::user()->account_id;
$client->user_id = $ninjaAccount->users()->first()->id;
$client->currency_id = 1;
foreach (['name', 'address1', 'address2', 'city', 'state', 'postal_code', 'country_id', 'work_phone'] as $field)
{
$client->$field = Auth::user()->account->$field;
}
$ninjaAccount->clients()->save($client);
$contact = new Contact; private function getNinjaClient($ninjaAccount)
$contact->user_id = $ninjaAccount->users()->first()->id; {
$contact->account_id = $ninjaAccount->id; $client = Client::whereAccountId($ninjaAccount->id)->wherePublicId(Auth::user()->account_id)->first();
$contact->public_id = Auth::user()->account_id;
$contact->is_primary = true;
foreach (['first_name', 'last_name', 'email', 'phone'] as $field)
{
$contact->$field = Auth::user()->$field;
}
$client->contacts()->save($contact);
}
return $client; if (!$client) {
} $client = new Client();
$client->public_id = Auth::user()->account_id;
$client->user_id = $ninjaAccount->users()->first()->id;
$client->currency_id = 1;
foreach (['name', 'address1', 'address2', 'city', 'state', 'postal_code', 'country_id', 'work_phone'] as $field) {
$client->$field = Auth::user()->account->$field;
}
$ninjaAccount->clients()->save($client);
public function registerUser($user) $contact = new Contact();
{ $contact->user_id = $ninjaAccount->users()->first()->id;
$url = NINJA_APP_URL . '/signup/register'; $contact->account_id = $ninjaAccount->id;
$data = ''; $contact->public_id = Auth::user()->account_id;
$fields = [ $contact->is_primary = true;
foreach (['first_name', 'last_name', 'email', 'phone'] as $field) {
$contact->$field = Auth::user()->$field;
}
$client->contacts()->save($contact);
}
return $client;
}
public function registerUser($user)
{
$url = NINJA_APP_URL.'/signup/register';
$data = '';
$fields = [
'first_name' => urlencode($user->first_name), 'first_name' => urlencode($user->first_name),
'last_name' => urlencode($user->last_name), 'last_name' => urlencode($user->last_name),
'email' => urlencode($user->email) 'email' => urlencode($user->email),
]; ];
foreach($fields as $key=>$value) { $data .= $key.'='.$value.'&'; } foreach ($fields as $key => $value) {
rtrim($data, '&'); $data .= $key.'='.$value.'&';
}
rtrim($data, '&');
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields)); curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch); curl_exec($ch);
curl_close($ch); curl_close($ch);
} }
}
}

View File

@ -5,219 +5,198 @@ use Contact;
class ClientRepository class ClientRepository
{ {
public function find($filter = null) public function find($filter = null)
{ {
$query = \DB::table('clients') $query = \DB::table('clients')
->join('contacts', 'contacts.client_id', '=', 'clients.id') ->join('contacts', 'contacts.client_id', '=', 'clients.id')
->where('clients.account_id', '=', \Auth::user()->account_id) ->where('clients.account_id', '=', \Auth::user()->account_id)
->where('contacts.is_primary', '=', true) ->where('contacts.is_primary', '=', true)
->where('contacts.deleted_at', '=', null) ->where('contacts.deleted_at', '=', null)
->select('clients.public_id','clients.name','contacts.first_name','contacts.last_name','clients.balance','clients.last_login','clients.created_at','clients.work_phone','contacts.email','clients.currency_id', 'clients.deleted_at', 'clients.is_deleted'); ->select('clients.public_id', 'clients.name', 'contacts.first_name', 'contacts.last_name', 'clients.balance', 'clients.last_login', 'clients.created_at', 'clients.work_phone', 'contacts.email', 'clients.currency_id', 'clients.deleted_at', 'clients.is_deleted');
if (!\Session::get('show_trash:client')) if (!\Session::get('show_trash:client')) {
{ $query->where('clients.deleted_at', '=', null);
$query->where('clients.deleted_at', '=', null); }
}
if ($filter) if ($filter) {
{ $query->where(function ($query) use ($filter) {
$query->where(function($query) use ($filter) $query->where('clients.name', 'like', '%'.$filter.'%')
{ ->orWhere('contacts.first_name', 'like', '%'.$filter.'%')
$query->where('clients.name', 'like', '%'.$filter.'%') ->orWhere('contacts.last_name', 'like', '%'.$filter.'%')
->orWhere('contacts.first_name', 'like', '%'.$filter.'%') ->orWhere('contacts.email', 'like', '%'.$filter.'%');
->orWhere('contacts.last_name', 'like', '%'.$filter.'%')
->orWhere('contacts.email', 'like', '%'.$filter.'%');
}); });
} }
return $query; return $query;
} }
public function getErrors($data) public function getErrors($data)
{ {
$contact = isset($data['contacts']) ? (array)$data['contacts'][0] : (isset($data['contact']) ? $data['contact'] : []); $contact = isset($data['contacts']) ? (array) $data['contacts'][0] : (isset($data['contact']) ? $data['contact'] : []);
$validator = \Validator::make($contact, ['email' => 'required|email']); $validator = \Validator::make($contact, ['email' => 'required|email']);
if ($validator->fails()) { if ($validator->fails()) {
return $validator->messages(); return $validator->messages();
} }
return false;
}
public function save($publicId, $data, $notify = true) return false;
{ }
if (!$publicId || $publicId == "-1")
{
$client = Client::createNew();
$client->currency_id = 1;
$contact = Contact::createNew();
$contact->is_primary = true;
$contact->send_invoice = true;
}
else
{
$client = Client::scope($publicId)->with('contacts')->firstOrFail();
$contact = $client->contacts()->where('is_primary', '=', true)->firstOrFail();
}
if (isset($data['name'])) {
$client->name = trim($data['name']);
}
if (isset($data['id_number'])) {
$client->id_number = trim($data['id_number']);
}
if (isset($data['vat_number'])) {
$client->vat_number = trim($data['vat_number']);
}
if (isset($data['work_phone'])) {
$client->work_phone = trim($data['work_phone']);
}
if (isset($data['custom_value1'])) {
$client->custom_value1 = trim($data['custom_value1']);
}
if (isset($data['custom_value2'])) {
$client->custom_value2 = trim($data['custom_value2']);
}
if (isset($data['address1'])) {
$client->address1 = trim($data['address1']);
}
if (isset($data['address2'])) {
$client->address2 = trim($data['address2']);
}
if (isset($data['city'])) {
$client->city = trim($data['city']);
}
if (isset($data['state'])) {
$client->state = trim($data['state']);
}
if (isset($data['postal_code'])) {
$client->postal_code = trim($data['postal_code']);
}
if (isset($data['country_id'])) {
$client->country_id = $data['country_id'] ? $data['country_id'] : null;
}
if (isset($data['private_notes'])) {
$client->private_notes = trim($data['private_notes']);
}
if (isset($data['size_id'])) {
$client->size_id = $data['size_id'] ? $data['size_id'] : null;
}
if (isset($data['industry_id'])) {
$client->industry_id = $data['industry_id'] ? $data['industry_id'] : null;
}
if (isset($data['currency_id'])) {
$client->currency_id = $data['currency_id'] ? $data['currency_id'] : null;
}
if (isset($data['payment_terms'])) {
$client->payment_terms = $data['payment_terms'];
}
if (isset($data['website'])) {
$client->website = trim($data['website']);
}
$client->save(); public function save($publicId, $data, $notify = true)
{
$isPrimary = true; if (!$publicId || $publicId == "-1") {
$contactIds = []; $client = Client::createNew();
$client->currency_id = 1;
$contact = Contact::createNew();
$contact->is_primary = true;
$contact->send_invoice = true;
} else {
$client = Client::scope($publicId)->with('contacts')->firstOrFail();
$contact = $client->contacts()->where('is_primary', '=', true)->firstOrFail();
}
if (isset($data['contact'])) if (isset($data['name'])) {
{ $client->name = trim($data['name']);
$info = $data['contact']; }
if (isset($info['email'])) { if (isset($data['id_number'])) {
$contact->email = trim(strtolower($info['email'])); $client->id_number = trim($data['id_number']);
} }
if (isset($info['first_name'])) { if (isset($data['vat_number'])) {
$contact->first_name = trim($info['first_name']); $client->vat_number = trim($data['vat_number']);
} }
if (isset($info['last_name'])) { if (isset($data['work_phone'])) {
$contact->last_name = trim($info['last_name']); $client->work_phone = trim($data['work_phone']);
} }
if (isset($info['phone'])) { if (isset($data['custom_value1'])) {
$contact->phone = trim($info['phone']); $client->custom_value1 = trim($data['custom_value1']);
} }
$contact->is_primary = true; if (isset($data['custom_value2'])) {
$contact->send_invoice = true; $client->custom_value2 = trim($data['custom_value2']);
$client->contacts()->save($contact); }
} if (isset($data['address1'])) {
else $client->address1 = trim($data['address1']);
{ }
foreach ($data['contacts'] as $record) if (isset($data['address2'])) {
{ $client->address2 = trim($data['address2']);
$record = (array) $record; }
if (isset($data['city'])) {
$client->city = trim($data['city']);
}
if (isset($data['state'])) {
$client->state = trim($data['state']);
}
if (isset($data['postal_code'])) {
$client->postal_code = trim($data['postal_code']);
}
if (isset($data['country_id'])) {
$client->country_id = $data['country_id'] ? $data['country_id'] : null;
}
if (isset($data['private_notes'])) {
$client->private_notes = trim($data['private_notes']);
}
if (isset($data['size_id'])) {
$client->size_id = $data['size_id'] ? $data['size_id'] : null;
}
if (isset($data['industry_id'])) {
$client->industry_id = $data['industry_id'] ? $data['industry_id'] : null;
}
if (isset($data['currency_id'])) {
$client->currency_id = $data['currency_id'] ? $data['currency_id'] : null;
}
if (isset($data['payment_terms'])) {
$client->payment_terms = $data['payment_terms'];
}
if (isset($data['website'])) {
$client->website = trim($data['website']);
}
if ($publicId != "-1" && isset($record['public_id']) && $record['public_id']) $client->save();
{
$contact = Contact::scope($record['public_id'])->firstOrFail();
}
else
{
$contact = Contact::createNew();
}
if (isset($record['email'])) { $isPrimary = true;
$contact->email = trim(strtolower($record['email'])); $contactIds = [];
}
if (isset($record['first_name'])) {
$contact->first_name = trim($record['first_name']);
}
if (isset($record['last_name'])) {
$contact->last_name = trim($record['last_name']);
}
if (isset($record['phone'])) {
$contact->phone = trim($record['phone']);
}
$contact->is_primary = $isPrimary;
$contact->send_invoice = isset($record['send_invoice']) ? $record['send_invoice'] : true;
$isPrimary = false;
$client->contacts()->save($contact); if (isset($data['contact'])) {
$contactIds[] = $contact->public_id; $info = $data['contact'];
} if (isset($info['email'])) {
$contact->email = trim(strtolower($info['email']));
foreach ($client->contacts as $contact) }
{ if (isset($info['first_name'])) {
if (!in_array($contact->public_id, $contactIds)) $contact->first_name = trim($info['first_name']);
{ }
$contact->delete(); if (isset($info['last_name'])) {
} $contact->last_name = trim($info['last_name']);
} }
} if (isset($info['phone'])) {
$contact->phone = trim($info['phone']);
}
$contact->is_primary = true;
$contact->send_invoice = true;
$client->contacts()->save($contact);
} else {
foreach ($data['contacts'] as $record) {
$record = (array) $record;
$client->save(); if ($publicId != "-1" && isset($record['public_id']) && $record['public_id']) {
$contact = Contact::scope($record['public_id'])->firstOrFail();
if (!$publicId || $publicId == "-1") } else {
{ $contact = Contact::createNew();
\Activity::createClient($client, $notify); }
}
return $client; if (isset($record['email'])) {
} $contact->email = trim(strtolower($record['email']));
}
if (isset($record['first_name'])) {
$contact->first_name = trim($record['first_name']);
}
if (isset($record['last_name'])) {
$contact->last_name = trim($record['last_name']);
}
if (isset($record['phone'])) {
$contact->phone = trim($record['phone']);
}
$contact->is_primary = $isPrimary;
$contact->send_invoice = isset($record['send_invoice']) ? $record['send_invoice'] : true;
$isPrimary = false;
public function bulk($ids, $action) $client->contacts()->save($contact);
{ $contactIds[] = $contact->public_id;
$clients = Client::withTrashed()->scope($ids)->get(); }
foreach ($clients as $client) foreach ($client->contacts as $contact) {
{ if (!in_array($contact->public_id, $contactIds)) {
if ($action == 'restore') $contact->delete();
{ }
$client->restore(); }
}
$client->save();
if (!$publicId || $publicId == "-1") {
\Activity::createClient($client, $notify);
}
return $client;
}
public function bulk($ids, $action)
{
$clients = Client::withTrashed()->scope($ids)->get();
foreach ($clients as $client) {
if ($action == 'restore') {
$client->restore();
$client->is_deleted = false; $client->is_deleted = false;
$client->save(); $client->save();
} } else {
else if ($action == 'delete') {
{ $client->is_deleted = true;
if ($action == 'delete') $client->save();
{ }
$client->is_deleted = true;
$client->save();
}
$client->delete();
}
}
return count($clients); $client->delete();
} }
} }
return count($clients);
}
}

View File

@ -2,53 +2,45 @@
use Credit; use Credit;
use Client; use Client;
use Invoice;
use Utils; use Utils;
class CreditRepository class CreditRepository
{ {
public function find($clientPublicId = null, $filter = null) public function find($clientPublicId = null, $filter = null)
{ {
$query = \DB::table('credits') $query = \DB::table('credits')
->join('clients', 'clients.id', '=','credits.client_id') ->join('clients', 'clients.id', '=', 'credits.client_id')
->join('contacts', 'contacts.client_id', '=', 'clients.id') ->join('contacts', 'contacts.client_id', '=', 'clients.id')
->where('clients.account_id', '=', \Auth::user()->account_id) ->where('clients.account_id', '=', \Auth::user()->account_id)
->where('clients.deleted_at', '=', null) ->where('clients.deleted_at', '=', null)
->where('contacts.is_primary', '=', true) ->where('contacts.is_primary', '=', true)
->select('credits.public_id', 'clients.name as client_name', 'clients.public_id as client_public_id', 'credits.amount', 'credits.balance', 'credits.credit_date', 'clients.currency_id', 'contacts.first_name', 'contacts.last_name', 'contacts.email', 'credits.private_notes', 'credits.deleted_at', 'credits.is_deleted'); ->select('credits.public_id', 'clients.name as client_name', 'clients.public_id as client_public_id', 'credits.amount', 'credits.balance', 'credits.credit_date', 'clients.currency_id', 'contacts.first_name', 'contacts.last_name', 'contacts.email', 'credits.private_notes', 'credits.deleted_at', 'credits.is_deleted');
if ($clientPublicId) if ($clientPublicId) {
{ $query->where('clients.public_id', '=', $clientPublicId);
$query->where('clients.public_id', '=', $clientPublicId); }
}
if (!\Session::get('show_trash:credit')) if (!\Session::get('show_trash:credit')) {
{
$query->where('credits.deleted_at', '=', null); $query->where('credits.deleted_at', '=', null);
} }
if ($filter) if ($filter) {
{ $query->where(function ($query) use ($filter) {
$query->where(function($query) use ($filter) $query->where('clients.name', 'like', '%'.$filter.'%');
{ });
$query->where('clients.name', 'like', '%'.$filter.'%'); }
});
}
return $query; return $query;
} }
public function save($publicId = null, $input) public function save($publicId = null, $input)
{ {
if ($publicId) if ($publicId) {
{
$credit = Credit::scope($publicId)->firstOrFail(); $credit = Credit::scope($publicId)->firstOrFail();
} } else {
else
{
$credit = Credit::createNew(); $credit = Credit::createNew();
} }
$credit->client_id = Client::getPrivateId($input['client']); $credit->client_id = Client::getPrivateId($input['client']);
$credit->credit_date = Utils::toSqlDate($input['credit_date']); $credit->credit_date = Utils::toSqlDate($input['credit_date']);
$credit->amount = Utils::parseFloat($input['amount']); $credit->amount = Utils::parseFloat($input['amount']);
@ -57,35 +49,29 @@ class CreditRepository
$credit->save(); $credit->save();
return $credit; return $credit;
} }
public function bulk($ids, $action) public function bulk($ids, $action)
{ {
if (!$ids) if (!$ids) {
{
return 0; return 0;
} }
$credits = Credit::withTrashed()->scope($ids)->get(); $credits = Credit::withTrashed()->scope($ids)->get();
foreach ($credits as $credit) foreach ($credits as $credit) {
{ if ($action == 'restore') {
if ($action == 'restore')
{
$credit->restore(); $credit->restore();
} } else {
else if ($action == 'delete') {
{
if ($action == 'delete')
{
$credit->is_deleted = true; $credit->is_deleted = true;
$credit->save(); $credit->save();
} }
$credit->delete(); $credit->delete();
} }
} }
return count($credits); return count($credits);
} }
} }

View File

@ -152,11 +152,11 @@ class InvoiceRepository
if ($entityType == ENTITY_INVOICE) { if ($entityType == ENTITY_INVOICE) {
if ($model->invoice_status_id < INVOICE_STATUS_PAID) { if ($model->invoice_status_id < INVOICE_STATUS_PAID) {
$str .= '<li><a href="'.\URL::to('payments/create/'.$model->client_public_id.'/'.$model->public_id).'">'.trans('texts.enter_payment').'</a></li>'; $str .= '<li><a href="'.\URL::to('payments/create/'.$model->client_public_id.'/'.$model->public_id).'">'.trans('texts.enter_payment').'</a></li>';
} }
if ($model->quote_id) { if ($model->quote_id) {
$str .= '<li><a href="'.\URL::to("quotes/{$model->quote_id}/edit").'">'.trans("texts.view_quote").'</a></li>'; $str .= '<li><a href="'.\URL::to("quotes/{$model->quote_id}/edit").'">'.trans("texts.view_quote").'</a></li>';
} }
} elseif ($entityType == ENTITY_QUOTE) { } elseif ($entityType == ENTITY_QUOTE) {
if ($model->quote_invoice_id) { if ($model->quote_invoice_id) {
@ -168,7 +168,7 @@ class InvoiceRepository
<li><a href="javascript:archiveEntity('.$model->public_id.')">'.trans("texts.archive_{$entityType}").'</a></li> <li><a href="javascript:archiveEntity('.$model->public_id.')">'.trans("texts.archive_{$entityType}").'</a></li>
<li><a href="javascript:deleteEntity('.$model->public_id.')">'.trans("texts.delete_{$entityType}").'</a></li>'; <li><a href="javascript:deleteEntity('.$model->public_id.')">'.trans("texts.delete_{$entityType}").'</a></li>';
} else { } else {
$str .= '<li><a href="javascript:restoreEntity('.$model->public_id.')">'.trans("texts.restore_{$entityType}").'</a></li> $str .= '<li><a href="javascript:restoreEntity('.$model->public_id.')">'.trans("texts.restore_{$entityType}").'</a></li>
<li><a href="javascript:deleteEntity('.$model->public_id.')">'.trans("texts.delete_{$entityType}").'</a></li>'; <li><a href="javascript:deleteEntity('.$model->public_id.')">'.trans("texts.delete_{$entityType}").'</a></li>';
} }

View File

@ -11,29 +11,25 @@ class PaymentRepository
public function find($clientPublicId = null, $filter = null) public function find($clientPublicId = null, $filter = null)
{ {
$query = \DB::table('payments') $query = \DB::table('payments')
->join('clients', 'clients.id', '=','payments.client_id') ->join('clients', 'clients.id', '=', 'payments.client_id')
->join('invoices', 'invoices.id', '=','payments.invoice_id') ->join('invoices', 'invoices.id', '=', 'payments.invoice_id')
->join('contacts', 'contacts.client_id', '=', 'clients.id') ->join('contacts', 'contacts.client_id', '=', 'clients.id')
->leftJoin('payment_types', 'payment_types.id', '=', 'payments.payment_type_id') ->leftJoin('payment_types', 'payment_types.id', '=', 'payments.payment_type_id')
->where('payments.account_id', '=', \Auth::user()->account_id) ->where('payments.account_id', '=', \Auth::user()->account_id)
->where('clients.deleted_at', '=', null) ->where('clients.deleted_at', '=', null)
->where('contacts.is_primary', '=', true) ->where('contacts.is_primary', '=', true)
->select('payments.public_id', 'payments.transaction_reference', 'clients.name as client_name', 'clients.public_id as client_public_id', 'payments.amount', 'payments.payment_date', 'invoices.public_id as invoice_public_id', 'invoices.invoice_number', 'clients.currency_id', 'contacts.first_name', 'contacts.last_name', 'contacts.email', 'payment_types.name as payment_type', 'payments.account_gateway_id', 'payments.deleted_at', 'payments.is_deleted'); ->select('payments.public_id', 'payments.transaction_reference', 'clients.name as client_name', 'clients.public_id as client_public_id', 'payments.amount', 'payments.payment_date', 'invoices.public_id as invoice_public_id', 'invoices.invoice_number', 'clients.currency_id', 'contacts.first_name', 'contacts.last_name', 'contacts.email', 'payment_types.name as payment_type', 'payments.account_gateway_id', 'payments.deleted_at', 'payments.is_deleted');
if (!\Session::get('show_trash:payment')) if (!\Session::get('show_trash:payment')) {
{
$query->where('payments.deleted_at', '=', null); $query->where('payments.deleted_at', '=', null);
} }
if ($clientPublicId) if ($clientPublicId) {
{
$query->where('clients.public_id', '=', $clientPublicId); $query->where('clients.public_id', '=', $clientPublicId);
} }
if ($filter) if ($filter) {
{ $query->where(function ($query) use ($filter) {
$query->where(function($query) use ($filter)
{
$query->where('clients.name', 'like', '%'.$filter.'%'); $query->where('clients.name', 'like', '%'.$filter.'%');
}); });
} }
@ -44,25 +40,22 @@ class PaymentRepository
public function findForContact($contactId = null, $filter = null) public function findForContact($contactId = null, $filter = null)
{ {
$query = \DB::table('payments') $query = \DB::table('payments')
->join('clients', 'clients.id', '=','payments.client_id') ->join('clients', 'clients.id', '=', 'payments.client_id')
->join('invoices', 'invoices.id', '=','payments.invoice_id') ->join('invoices', 'invoices.id', '=', 'payments.invoice_id')
->join('contacts', 'contacts.client_id', '=', 'clients.id') ->join('contacts', 'contacts.client_id', '=', 'clients.id')
->leftJoin('invitations', function($join) ->leftJoin('invitations', function ($join) {
{
$join->on('invitations.invoice_id', '=', 'invoices.id') $join->on('invitations.invoice_id', '=', 'invoices.id')
->on('invitations.contact_id', '=', 'contacts.id'); ->on('invitations.contact_id', '=', 'contacts.id');
}) })
->leftJoin('payment_types', 'payment_types.id', '=', 'payments.payment_type_id') ->leftJoin('payment_types', 'payment_types.id', '=', 'payments.payment_type_id')
->where('clients.is_deleted', '=', false) ->where('clients.is_deleted', '=', false)
->where('payments.is_deleted', '=', false) ->where('payments.is_deleted', '=', false)
->where('invitations.deleted_at', '=', null) ->where('invitations.deleted_at', '=', null)
->where('invitations.contact_id', '=', $contactId) ->where('invitations.contact_id', '=', $contactId)
->select('invitations.invitation_key', 'payments.public_id', 'payments.transaction_reference', 'clients.name as client_name', 'clients.public_id as client_public_id', 'payments.amount', 'payments.payment_date', 'invoices.public_id as invoice_public_id', 'invoices.invoice_number', 'clients.currency_id', 'contacts.first_name', 'contacts.last_name', 'contacts.email', 'payment_types.name as payment_type', 'payments.account_gateway_id'); ->select('invitations.invitation_key', 'payments.public_id', 'payments.transaction_reference', 'clients.name as client_name', 'clients.public_id as client_public_id', 'payments.amount', 'payments.payment_date', 'invoices.public_id as invoice_public_id', 'invoices.invoice_number', 'clients.currency_id', 'contacts.first_name', 'contacts.last_name', 'contacts.email', 'payment_types.name as payment_type', 'payments.account_gateway_id');
if ($filter) if ($filter) {
{ $query->where(function ($query) use ($filter) {
$query->where(function($query) use ($filter)
{
$query->where('clients.name', 'like', '%'.$filter.'%'); $query->where('clients.name', 'like', '%'.$filter.'%');
}); });
} }
@ -74,33 +67,28 @@ class PaymentRepository
{ {
$rules = array( $rules = array(
'client' => 'required', 'client' => 'required',
'invoice' => 'required', 'invoice' => 'required',
'amount' => 'required|positive' 'amount' => 'required|positive',
); );
if ($input['payment_type_id'] == PAYMENT_TYPE_CREDIT) if ($input['payment_type_id'] == PAYMENT_TYPE_CREDIT) {
{ $rules['payment_type_id'] = 'has_credit:'.$input['client'].','.$input['amount'];
$rules['payment_type_id'] = 'has_credit:' . $input['client'] . ',' . $input['amount'];
} }
$validator = \Validator::make($input, $rules); $validator = \Validator::make($input, $rules);
if ($validator->fails()) if ($validator->fails()) {
{
return $validator; return $validator;
} }
return false; return false;
} }
public function save($publicId = null, $input) public function save($publicId = null, $input)
{ {
if ($publicId) if ($publicId) {
{
$payment = Payment::scope($publicId)->firstOrFail(); $payment = Payment::scope($publicId)->firstOrFail();
} } else {
else
{
$payment = Payment::createNew(); $payment = Payment::createNew();
} }
@ -108,18 +96,15 @@ class PaymentRepository
$clientId = Client::getPrivateId($input['client']); $clientId = Client::getPrivateId($input['client']);
$amount = Utils::parseFloat($input['amount']); $amount = Utils::parseFloat($input['amount']);
if ($paymentTypeId == PAYMENT_TYPE_CREDIT) if ($paymentTypeId == PAYMENT_TYPE_CREDIT) {
{
$credits = Credit::scope()->where('client_id', '=', $clientId) $credits = Credit::scope()->where('client_id', '=', $clientId)
->where('balance', '>', 0)->orderBy('created_at')->get(); ->where('balance', '>', 0)->orderBy('created_at')->get();
$applied = 0; $applied = 0;
foreach ($credits as $credit) foreach ($credits as $credit) {
{
$applied += $credit->apply($amount); $applied += $credit->apply($amount);
if ($applied >= $amount) if ($applied >= $amount) {
{
break; break;
} }
} }
@ -132,37 +117,31 @@ class PaymentRepository
$payment->amount = $amount; $payment->amount = $amount;
$payment->transaction_reference = trim($input['transaction_reference']); $payment->transaction_reference = trim($input['transaction_reference']);
$payment->save(); $payment->save();
return $payment;
}
public function bulk($ids, $action) return $payment;
{ }
if (!$ids)
{ public function bulk($ids, $action)
{
if (!$ids) {
return 0; return 0;
} }
$payments = Payment::withTrashed()->scope($ids)->get(); $payments = Payment::withTrashed()->scope($ids)->get();
foreach ($payments as $payment) foreach ($payments as $payment) {
{ if ($action == 'restore') {
if ($action == 'restore')
{
$payment->restore(); $payment->restore();
} } else {
else if ($action == 'delete') {
{
if ($action == 'delete')
{
$payment->is_deleted = true; $payment->is_deleted = true;
$payment->save(); $payment->save();
} }
$payment->delete(); $payment->delete();
} }
} }
return count($payments); return count($payments);
} }
} }

View File

@ -5,46 +5,38 @@ use Utils;
class TaxRateRepository class TaxRateRepository
{ {
public function save($taxRates) public function save($taxRates)
{ {
$taxRateIds = []; $taxRateIds = [];
foreach ($taxRates as $record)
{
if (!isset($record->rate) || (isset($record->is_deleted) && $record->is_deleted))
{
continue;
}
if (!isset($record->name) || !Utils::parseFloat($record->rate) || !trim($record->name)) foreach ($taxRates as $record) {
{ if (!isset($record->rate) || (isset($record->is_deleted) && $record->is_deleted)) {
continue; continue;
} }
if ($record->public_id) if (!isset($record->name) || !Utils::parseFloat($record->rate) || !trim($record->name)) {
{ continue;
$taxRate = TaxRate::scope($record->public_id)->firstOrFail(); }
}
else
{
$taxRate = TaxRate::createNew();
}
$taxRate->rate = Utils::parseFloat($record->rate); if ($record->public_id) {
$taxRate->name = trim($record->name); $taxRate = TaxRate::scope($record->public_id)->firstOrFail();
$taxRate->save(); } else {
$taxRate = TaxRate::createNew();
}
$taxRateIds[] = $taxRate->public_id; $taxRate->rate = Utils::parseFloat($record->rate);
} $taxRate->name = trim($record->name);
$taxRate->save();
$taxRates = TaxRate::scope()->get();
foreach($taxRates as $taxRate) $taxRateIds[] = $taxRate->public_id;
{ }
if (!in_array($taxRate->public_id, $taxRateIds))
{ $taxRates = TaxRate::scope()->get();
$taxRate->delete();
} foreach ($taxRates as $taxRate) {
} if (!in_array($taxRate->public_id, $taxRateIds)) {
} $taxRate->delete();
} }
}
}
}