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,7 +1,7 @@
<?php
class ActivityController extends \BaseController {
class ActivityController extends \BaseController
{
public function getDatatable($clientPublicId)
{
$query = DB::table('activities')
@ -18,5 +18,4 @@ class ActivityController extends \BaseController {
->addColumn('adjustment', function ($model) { return $model->adjustment != 0 ? Utils::formatMoney($model->adjustment, $model->currency_id) : ''; })
->make();
}
}

View File

@ -43,7 +43,7 @@ class AppController extends BaseController {
$database = Input::get('database');
$dbType = $database['default'];
$database[$dbType] = $database['type'];
//unset($database['type']);
unset($database['type']);
$mail = Input::get('mail');
$email = $mail['username'];
@ -58,7 +58,7 @@ class AppController extends BaseController {
if ($test == 'db')
{
return $valid ? 'Success' : 'Failed';
return $valid === true ? 'Success' : $valid;
}
else if (!$valid)
{

View File

@ -1,7 +1,7 @@
<?php
class BaseController extends Controller {
class BaseController extends Controller
{
/**
* Setup the layout used by the controller.
*
@ -9,8 +9,7 @@ class BaseController extends Controller {
*/
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
if (! is_null($this->layout)) {
$this->layout = View::make($this->layout);
}
}

View File

@ -2,8 +2,8 @@
use ninja\repositories\ClientRepository;
class ClientApiController extends Controller {
class ClientApiController extends Controller
{
protected $clientRepo;
public function __construct(ClientRepository $clientRepo)
@ -14,6 +14,7 @@ class ClientApiController extends Controller {
public function ping()
{
$headers = Utils::getApiHeaders();
return Response::make('', 200, $headers);
}
@ -28,6 +29,7 @@ class ClientApiController extends Controller {
$response = json_encode($clients, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders(count($clients));
return Response::make($response, 200, $headers);
}
@ -40,18 +42,16 @@ class ClientApiController extends Controller {
$data = Input::all();
$error = $this->clientRepo->getErrors($data);
if ($error)
{
if ($error) {
$headers = Utils::getApiHeaders();
return Response::make($error, 500, $headers);
}
else
{
} 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,8 +2,8 @@
use ninja\repositories\ClientRepository;
class ClientController extends \BaseController {
class ClientController extends \BaseController
{
protected $clientRepo;
public function __construct(ClientRepository $clientRepo)
@ -23,7 +23,7 @@ class ClientController extends \BaseController {
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'])
'columns' => Utils::trans(['checkbox', 'client', 'contact', 'email', 'date_created', 'last_login', 'balance', 'action']),
));
}
@ -39,10 +39,8 @@ class ClientController extends \BaseController {
->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('balance', function ($model) { return Utils::formatMoney($model->balance, $model->currency_id); })
->addColumn('dropdown', function($model)
{
if ($model->is_deleted)
{
->addColumn('dropdown', function ($model) {
if ($model->is_deleted) {
return '<div style="height:38px"/>';
}
@ -52,8 +50,7 @@ class ClientController extends \BaseController {
</button>
<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>
<li class="divider"></li>
<li><a href="'.URL::to('invoices/create/'.$model->public_id).'">'.trans('texts.new_invoice').'</a></li>
@ -61,9 +58,7 @@ class ClientController extends \BaseController {
<li><a href="'.URL::to('credits/create/'.$model->public_id).'">'.trans('texts.new_credit').'</a></li>
<li class="divider"></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>';
}
@ -73,8 +68,6 @@ class ClientController extends \BaseController {
->make();
}
/**
* Store a newly created resource in storage.
*
@ -99,11 +92,10 @@ class ClientController extends \BaseController {
$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 )]
[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)]);
}
@ -113,7 +105,7 @@ class ClientController extends \BaseController {
'client' => $client,
'credit' => $client->getTotalCredit(),
'title' => trans('texts.view_client'),
'hasRecurringInvoices' => Invoice::scope()->where('is_recurring', '=', true)->whereClientId($client->id)->count() > 0
'hasRecurringInvoices' => Invoice::scope()->where('is_recurring', '=', true)->whereClientId($client->id)->count() > 0,
);
return View::make('clients.show', $data);
@ -126,8 +118,7 @@ class ClientController extends \BaseController {
*/
public function create()
{
if (Client::scope()->count() > Auth::user()->getMaxNumClients())
{
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"]);
}
@ -135,10 +126,11 @@ class ClientController extends \BaseController {
'client' => null,
'method' => 'POST',
'url' => 'clients',
'title' => trans('texts.new_client')
'title' => trans('texts.new_client'),
];
$data = array_merge($data, self::getViewModel());
return View::make('clients.edit', $data);
}
@ -155,10 +147,11 @@ class ClientController extends \BaseController {
'client' => $client,
'method' => 'PUT',
'url' => 'clients/'.$publicId,
'title' => trans('texts.edit_client')
'title' => trans('texts.edit_client'),
];
$data = array_merge($data, self::getViewModel());
return View::make('clients.edit', $data);
}
@ -189,25 +182,20 @@ class ClientController extends \BaseController {
private function save($publicId = null)
{
$rules = array(
'email' => 'required'
'email' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
if ($validator->fails()) {
$url = $publicId ? 'clients/'.$publicId.'/edit' : 'clients/create';
return Redirect::to($url)
->withErrors($validator)
->withInput(Input::except('password'));
}
else
{
if ($publicId)
{
} else {
if ($publicId) {
$client = Client::scope($publicId)->firstOrFail();
}
else
{
} else {
$client = Client::createNew();
}
@ -236,14 +224,10 @@ class ClientController extends \BaseController {
$contactIds = [];
$isPrimary = true;
foreach ($data->contacts as $contact)
{
if (isset($contact->public_id) && $contact->public_id)
{
foreach ($data->contacts as $contact) {
if (isset($contact->public_id) && $contact->public_id) {
$record = Contact::scope($contact->public_id)->firstOrFail();
}
else
{
} else {
$record = Contact::createNew();
}
@ -258,20 +242,15 @@ class ClientController extends \BaseController {
$contactIds[] = $record->public_id;
}
foreach ($client->contacts as $contact)
{
if (!in_array($contact->public_id, $contactIds))
{
foreach ($client->contacts as $contact) {
if (!in_array($contact->public_id, $contactIds)) {
$contact->delete();
}
}
if ($publicId)
{
if ($publicId) {
Session::flash('message', trans('texts.updated_client'));
}
else
{
} else {
Activity::createClient($client);
Session::flash('message', trans('texts.created_client'));
}
@ -289,12 +268,9 @@ class ClientController extends \BaseController {
$message = Utils::pluralize($action.'d_client', $count);
Session::flash('message', $message);
if ($action == 'restore' && $count == 1)
{
if ($action == 'restore' && $count == 1) {
return Redirect::to('clients/'.$ids[0]);
}
else
{
} else {
return Redirect::to('clients');
}
}

View File

@ -2,8 +2,8 @@
use ninja\repositories\CreditRepository;
class CreditController extends \BaseController {
class CreditController extends \BaseController
{
protected $creditRepo;
public function __construct(CreditRepository $creditRepo)
@ -23,7 +23,7 @@ class CreditController extends \BaseController {
return View::make('list', array(
'entityType' => ENTITY_CREDIT,
'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']),
));
}
@ -33,8 +33,7 @@ class CreditController extends \BaseController {
$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).'>'; })
->addColumn('client_name', function ($model) { return link_to('clients/'.$model->client_public_id, Utils::getClientDisplayName($model)); });
}
@ -43,10 +42,8 @@ class CreditController extends \BaseController {
->addColumn('balance', function ($model) { return Utils::formatMoney($model->balance, $model->currency_id); })
->addColumn('credit_date', function ($model) { return Utils::fromSqlDate($model->credit_date); })
->addColumn('private_notes', function ($model) { return $model->private_notes; })
->addColumn('dropdown', function($model)
{
if ($model->is_deleted)
{
->addColumn('dropdown', function ($model) {
if ($model->is_deleted) {
return '<div style="height:38px"/>';
}
@ -56,12 +53,9 @@ class CreditController extends \BaseController {
</button>
<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>';
}
else
{
} else {
$str .= '<li><a href="javascript:restoreEntity('.$model->public_id.')">'.trans('texts.restore_credit').'</a></li>';
}
@ -71,7 +65,6 @@ class CreditController extends \BaseController {
->make();
}
public function create($clientPublicId = 0)
{
$data = array(
@ -83,7 +76,7 @@ class CreditController extends \BaseController {
'title' => trans('texts.new_credit'),
//'currencies' => Currency::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->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);
}
@ -100,7 +93,8 @@ class CreditController extends \BaseController {
'url' => 'credits/'.$publicId,
'title' => 'Edit Credit',
//'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);
}
@ -123,19 +117,18 @@ class CreditController extends \BaseController {
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
if ($validator->fails()) {
$url = $publicId ? 'credits/'.$publicId.'/edit' : 'credits/create';
return Redirect::to($url)
->withErrors($validator)
->withInput();
}
else
{
} else {
$this->creditRepo->save($publicId, Input::all());
$message = trans('texts.created_credit');
Session::flash('message', $message);
return Redirect::to('clients/'.Input::get('client'));
}
}
@ -146,8 +139,7 @@ class CreditController extends \BaseController {
$ids = Input::get('id') ? Input::get('id') : Input::get('ids');
$count = $this->creditRepo->bulk($ids, $action);
if ($count > 0)
{
if ($count > 0) {
$message = Utils::pluralize($action.'d_credit', $count);
Session::flash('message', $message);
}

View File

@ -1,7 +1,7 @@
<?php
class DashboardController extends \BaseController {
class DashboardController extends \BaseController
{
public function index()
{
// total_income, billed_clients, invoice_sent and active_clients
@ -56,10 +56,9 @@ class DashboardController extends \BaseController {
'invoiceAvg' => Utils::formatMoney(($metrics ? $metrics->invoice_avg : 0), Session::get(SESSION_CURRENCY)),
'activities' => $activities,
'pastDue' => $pastDue,
'upcoming' => $upcoming
'upcoming' => $upcoming,
];
return View::make('dashboard', $data);
}
}

View File

@ -2,8 +2,8 @@
use ninja\mailers\Mailer;
class HomeController extends BaseController {
class HomeController extends BaseController
{
protected $mailer;
public function __construct(Mailer $mailer)
@ -15,22 +15,14 @@ class HomeController extends BaseController {
public function showIndex()
{
if (Utils::isNinja())
{
if (Utils::isNinja()) {
return View::make('public.splash');
}
else
{
if (!Utils::isDatabaseSetup())
{
} else {
if (!Utils::isDatabaseSetup()) {
return Redirect::to('/setup');
}
else if (Account::count() == 0)
{
} elseif (Account::count() == 0) {
return Redirect::to('/invoice_now');
}
else
{
} else {
return Redirect::to('/login');
}
}
@ -40,7 +32,7 @@ class HomeController extends BaseController {
{
$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!'
'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);
@ -50,7 +42,7 @@ class HomeController extends BaseController {
{
$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!'
'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);
@ -75,7 +67,7 @@ class HomeController extends BaseController {
{
$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.'
'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);
@ -85,7 +77,6 @@ class HomeController extends BaseController {
return View::make('public.testimonials');
}
public function doContactUs()
{
$email = Input::get('email');
@ -93,7 +84,7 @@ class HomeController extends BaseController {
$message = Input::get('message');
$data = [
'text' => $message
'text' => $message,
];
$this->mailer->sendTo(CONTACT_EMAIL, $email, $name, 'Invoice Ninja Feedback', 'contact', $data);
@ -121,12 +112,9 @@ class HomeController extends BaseController {
public function invoiceNow()
{
if (Auth::check())
{
if (Auth::check()) {
return Redirect::to('invoices/create');
}
else
{
} else {
return View::make('public.header', ['invoiceNow' => true]);
}
}

View File

@ -1,21 +1,19 @@
<?php
class IntegrationController extends Controller {
class IntegrationController extends Controller
{
public function subscribe()
{
$eventId = Utils::lookupEventId(trim(Input::get('event')));
if (!$eventId)
{
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;
if (!$subscription) {
$subscription = new Subscription();
$subscription->account_id = Auth::user()->account_id;
$subscription->event_id = $eventId;
}
@ -25,5 +23,4 @@ class IntegrationController extends Controller {
return Response::json('{"id":'.$subscription->id.'}', 201);
}
}

View File

@ -2,8 +2,8 @@
use ninja\repositories\InvoiceRepository;
class InvoiceApiController extends Controller {
class InvoiceApiController extends Controller
{
protected $invoiceRepo;
public function __construct(InvoiceRepository $invoiceRepo)
@ -22,6 +22,7 @@ class InvoiceApiController extends Controller {
$response = json_encode($invoices, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders(count($invoices));
return Response::make($response, 200, $headers);
}

View File

@ -5,8 +5,8 @@ use ninja\repositories\InvoiceRepository;
use ninja\repositories\ClientRepository;
use ninja\repositories\TaxRateRepository;
class InvoiceController extends \BaseController {
class InvoiceController extends \BaseController
{
protected $mailer;
protected $invoiceRepo;
protected $clientRepo;
@ -27,18 +27,16 @@ class InvoiceController extends \BaseController {
$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'])
'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'))
{
if (Session::get('show_trash:invoice')) {
$recurringInvoices->withTrashed();
}
if ($recurringInvoices->count() > 0)
{
if ($recurringInvoices->count() > 0) {
$data['secEntityType'] = ENTITY_RECURRING_INVOICE;
$data['secColumns'] = Utils::trans(['checkbox', 'frequency', 'client', 'start_date', 'end_date', 'invoice_total', 'action']);
}
@ -53,7 +51,7 @@ class InvoiceController extends \BaseController {
'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'])
'columns' => Utils::trans(['invoice_number', 'invoice_date', 'invoice_total', 'balance_due', 'due_date']),
];
return View::make('public_list', $data);
@ -74,15 +72,13 @@ class InvoiceController extends \BaseController {
$invitationKey = Session::get('invitation_key');
$invitation = Invitation::where('invitation_key', '=', $invitationKey)->first();
if (!$invitation || $invitation->is_deleted)
{
if (!$invitation || $invitation->is_deleted) {
return [];
}
$invoice = $invitation->invoice;
if (!$invoice || $invoice->is_deleted)
{
if (!$invoice || $invoice->is_deleted) {
return [];
}
@ -107,10 +103,8 @@ class InvoiceController extends \BaseController {
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)
{
->addColumn('dropdown', function ($model) {
if ($model->is_deleted) {
return '<div style="height:38px"/>';
}
@ -120,45 +114,36 @@ class InvoiceController extends \BaseController {
</button>
<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>
<li class="divider"></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>';
}
else
{
} else {
$str .= '<li><a href="javascript:restoreEntity('.$model->public_id.')">'.trans('texts.restore_invoice').'</a></li>';
}
return $str.'</ul>
</div>';
})
->make();
}
public function view($invitationKey)
{
$invitation = Invitation::where('invitation_key', '=', $invitationKey)->firstOrFail();
$invoice = $invitation->invoice;
if (!$invoice || $invoice->is_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();
if (!$invoice || $invoice->is_deleted)
{
if (!$invoice || $invoice->is_deleted) {
return View::make('invoices.deleted');
}
}
@ -167,13 +152,11 @@ class InvoiceController extends \BaseController {
$client = $invoice->client;
if (!$client || $client->is_deleted)
{
if (!$client || $client->is_deleted) {
return View::make('invoices.deleted');
}
if (!Session::has($invitationKey) && (!Auth::check() || Auth::user()->account_id != $invoice->account_id))
{
if (!Session::has($invitationKey) && (!Auth::check() || Auth::user()->account_id != $invoice->account_id)) {
Activity::viewInvoice($invitation);
Event::fire('invoice.viewed', $invoice);
}
@ -193,7 +176,7 @@ class InvoiceController extends \BaseController {
'first_name',
'last_name',
'email',
'phone']);
'phone', ]);
$data = array(
'showClientHeader' => true,
@ -202,7 +185,7 @@ class InvoiceController extends \BaseController {
'invoice' => $invoice->hidePrivateFields(),
'invitation' => $invitation,
'invoiceLabels' => $client->account->getInvoiceLabels(),
'contact' => $contact
'contact' => $contact,
);
return View::make('invoices.view', $data);
@ -220,8 +203,7 @@ class InvoiceController extends \BaseController {
->where('invitations.deleted_at', '=', null)
->select('contacts.public_id')->lists('public_id');
if ($clone)
{
if ($clone) {
$invoice->id = null;
$invoice->invoice_number = Auth::user()->account->getNextInvoiceNumber($invoice->is_quote);
$invoice->balance = $invoice->amount;
@ -229,9 +211,7 @@ class InvoiceController extends \BaseController {
$invoice->invoice_date = date_create()->format('Y-m-d');
$method = 'POST';
$url = "{$entityType}s";
}
else
{
} else {
Utils::trackViewed($invoice->invoice_number.' - '.$invoice->client->getDisplayName(), $invoice->getEntityType());
$method = 'PUT';
$url = "{$entityType}s/{$publicId}";
@ -253,23 +233,17 @@ class InvoiceController extends \BaseController {
'invitationContactIds' => $contactIds,
'url' => $url,
'title' => trans("texts.edit_{$entityType}"),
'client' => $invoice->client);
'client' => $invoice->client, );
$data = array_merge($data, self::getViewModel());
// Set the invitation link on the client's contacts
if (!$clone)
{
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)
{
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();
}
}
@ -288,8 +262,7 @@ class InvoiceController extends \BaseController {
$invoiceNumber = Auth::user()->account->getNextInvoiceNumber();
$account = Account::with('country')->findOrFail(Auth::user()->account_id);
if ($clientPublicId)
{
if ($clientPublicId) {
$client = Client::scope($clientPublicId)->firstOrFail();
}
@ -302,7 +275,7 @@ class InvoiceController extends \BaseController {
'method' => 'POST',
'url' => 'invoices',
'title' => trans('texts.new_invoice'),
'client' => $client);
'client' => $client, );
$data = array_merge($data, self::getViewModel());
return View::make('invoices.edit', $data);
@ -340,7 +313,7 @@ class InvoiceController extends \BaseController {
4 => 'Monthly',
5 => 'Three months',
6 => 'Six months',
7 => 'Annually'
7 => 'Annually',
),
'recurringHelp' => $recurringHelp
];
@ -361,23 +334,19 @@ class InvoiceController extends \BaseController {
$action = Input::get('action');
$entityType = Input::get('entityType');
if (in_array($action, ['archive', 'delete', 'mark', 'restore']))
{
if (in_array($action, ['archive', 'delete', 'mark', 'restore'])) {
return InvoiceController::bulk($entityType);
}
$input = json_decode(Input::get('data'));
$invoice = $input->invoice;
if ($errors = $this->invoiceRepo->getErrors($invoice))
{
if ($errors = $this->invoiceRepo->getErrors($invoice)) {
Session::flash('error', trans('texts.invoice_error'));
return Redirect::to("{$entityType}s/create")
->withInput()->withErrors($errors);
}
else
{
} else {
$this->taxRateRepo->save($input->tax_rates);
$clientData = (array) $invoice->client;
@ -390,8 +359,7 @@ class InvoiceController extends \BaseController {
$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_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;
@ -401,70 +369,54 @@ class InvoiceController extends \BaseController {
$client->load('contacts');
$sendInvoiceIds = [];
foreach ($client->contacts as $contact)
{
if ($contact->send_invoice || count($client->contacts) == 1)
{
foreach ($client->contacts as $contact) {
if ($contact->send_invoice || count($client->contacts) == 1) {
$sendInvoiceIds[] = $contact->id;
}
}
foreach ($client->contacts as $contact)
{
foreach ($client->contacts as $contact) {
$invitation = Invitation::scope()->whereContactId($contact->id)->whereInvoiceId($invoice->id)->first();
if (in_array($contact->id, $sendInvoiceIds) && !$invitation)
{
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)
{
} elseif (!in_array($contact->id, $sendInvoiceIds) && $invitation) {
$invitation->delete();
}
}
$message = trans($publicId ? "texts.updated_{$entityType}" : "texts.created_{$entityType}");
if ($input->invoice->client->public_id == '-1')
{
if ($input->invoice->client->public_id == '-1') {
$message = $message.' '.trans('texts.and_created_client');
$url = URL::to('clients/'.$client->public_id);
Utils::trackViewed($client->getDisplayName(), ENTITY_CLIENT, $url);
}
if ($action == 'clone')
{
if ($action == 'clone') {
return $this->cloneInvoice($publicId);
}
else if ($action == 'convert')
{
} elseif ($action == 'convert') {
return $this->convertQuote($publicId);
}
else if ($action == 'email')
{
if (Auth::user()->confirmed && !Auth::user()->isDemo())
{
} elseif ($action == 'email') {
if (Auth::user()->confirmed && !Auth::user()->isDemo()) {
$message = trans("texts.emailed_{$entityType}");
$this->mailer->sendInvoice($invoice);
Session::flash('message', $message);
}
else
{
} else {
$errorMessage = trans(Auth::user()->registered ? 'texts.confirmation_required' : 'texts.registration_required');
Session::flash('error', $errorMessage);
Session::flash('message', $message);
}
}
else
{
} else {
Session::flash('message', $message);
}
$url = "{$entityType}s/".$invoice->public_id.'/edit';
return Redirect::to($url);
}
}
@ -506,19 +458,15 @@ class InvoiceController extends \BaseController {
$ids = Input::get('id') ? Input::get('id') : Input::get('ids');
$count = $this->invoiceRepo->bulk($ids, $action, $statusId);
if ($count > 0)
{
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)
{
if ($action == 'restore' && $count == 1) {
return Redirect::to("{$entityType}s/".$ids[0]);
}
else
{
} else {
return Redirect::to("{$entityType}s");
}
}
@ -529,6 +477,7 @@ class InvoiceController extends \BaseController {
$clone = $this->invoiceRepo->cloneInvoice($invoice, $invoice->id);
Session::flash('message', trans('texts.converted_to_invoice'));
return Redirect::to('invoices/'.$clone->public_id);
}

View File

@ -2,8 +2,8 @@
use ninja\repositories\PaymentRepository;
class PaymentApiController extends Controller {
class PaymentApiController extends Controller
{
protected $paymentRepo;
public function __construct(PaymentRepository $paymentRepo)
@ -22,6 +22,7 @@ class PaymentApiController extends Controller {
$response = json_encode($payments, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders(count($payments));
return Response::make($response, 200, $headers);
}

View File

@ -24,7 +24,7 @@ class PaymentController extends \BaseController
return View::make('list', array(
'entityType' => ENTITY_PAYMENT,
'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']),
));
}
@ -35,7 +35,7 @@ class PaymentController extends \BaseController
'hideLogo' => Session::get('white_label'),
'entityType' => ENTITY_PAYMENT,
'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']),
));
}
@ -59,10 +59,8 @@ class PaymentController extends \BaseController
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('dropdown', function($model)
{
if ($model->is_deleted)
{
->addColumn('dropdown', function ($model) {
if ($model->is_deleted) {
return '<div style="height:38px"/>';
}
@ -72,12 +70,9 @@ class PaymentController extends \BaseController
</button>
<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>';
}
else
{
} else {
$str .= '<li><a href="javascript:restoreEntity('.$model->public_id.')">'.trans('texts.restore_payment').'</a></li>';
}
@ -93,15 +88,13 @@ class PaymentController extends \BaseController
$invitationKey = Session::get('invitation_key');
$invitation = Invitation::where('invitation_key', '=', $invitationKey)->with('contact.client')->first();
if (!$invitation)
{
if (!$invitation) {
return [];
}
$invoice = $invitation->invoice;
if (!$invoice || $invoice->is_deleted)
{
if (!$invoice || $invoice->is_deleted) {
return [];
}
@ -116,7 +109,6 @@ class PaymentController extends \BaseController
->make();
}
public function create($clientPublicId = 0, $invoicePublicId = 0)
{
$data = array(
@ -131,7 +123,7 @@ class PaymentController extends \BaseController
'title' => trans('texts.new_payment'),
//'currencies' => Currency::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->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);
}
@ -152,7 +144,8 @@ class PaymentController extends \BaseController
'title' => 'Edit Payment',
//'currencies' => Currency::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->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);
}
@ -166,10 +159,8 @@ class PaymentController extends \BaseController
$gateway->setLandingPage("Billing");
*/
foreach ($config as $key => $val)
{
if (!$val)
{
foreach ($config as $key => $val) {
if (!$val) {
continue;
}
@ -177,8 +168,7 @@ class PaymentController extends \BaseController
$gateway->$function($val);
}
if (Utils::isNinjaDev())
{
if (Utils::isNinjaDev()) {
$gateway->setTestMode(true);
}
@ -197,7 +187,6 @@ class PaymentController extends \BaseController
'returnUrl' => URL::to('license_complete'),
'cancelUrl' => URL::to('/')
];
}
private function convertInputForOmnipay($input)
@ -229,14 +218,11 @@ class PaymentController extends \BaseController
$paymentLibrary = $gateway->paymentlibrary;
$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);
Session::put($key, $data);
}
else if ($input && $paymentLibrary->id == PAYMENT_LIBRARY_PHP_PAYMENTS)
{
} elseif ($input && $paymentLibrary->id == PAYMENT_LIBRARY_PHP_PAYMENTS) {
$input = Input::all();
$data = [
'first_name' => $input['first_name'],
@ -257,8 +243,7 @@ class PaymentController extends \BaseController
'currency_code' => $currencyCode,
];
switch($gateway->id)
{
switch ($gateway->id) {
case GATEWAY_BEANSTREAM:
$data['phone'] = $input['phone'];
$data['email'] = $input['email'];
@ -270,25 +255,20 @@ class PaymentController extends \BaseController
break;
}
if(strlen($data['cc_exp']) == 5)
{
if (strlen($data['cc_exp']) == 5) {
$data['cc_exp'] = '0'.$data['cc_exp'];
}
Session::put($key, $data);
return $data;
}
else if (Session::get($key))
{
} elseif (Session::get($key)) {
$data = Session::get($key);
}
else
{
} else {
$data = [];
}
if($paymentLibrary->id == PAYMENT_LIBRARY_OMNIPAY)
{
if ($paymentLibrary->id == PAYMENT_LIBRARY_OMNIPAY) {
$card = new CreditCard($data);
return [
@ -298,9 +278,7 @@ class PaymentController extends \BaseController
'returnUrl' => URL::to('complete'),
'cancelUrl' => URL::to('/')
];
}
else
{
} else {
return $data;
}
}
@ -311,15 +289,12 @@ class PaymentController extends \BaseController
$invitation = Invitation::with('invoice.client.account', 'invoice.client.account.account_gateways.gateway')->where('invitation_key', '=', $invitationKey)->firstOrFail();
$account = $invitation->invoice->client->account;
if ($account->isGatewayConfigured(GATEWAY_PAYPAL_EXPRESS))
{
if (Session::has('error'))
{
if ($account->isGatewayConfigured(GATEWAY_PAYPAL_EXPRESS)) {
if (Session::has('error')) {
Session::reflash();
return Redirect::to('view/'.$invitationKey);
}
else
{
} else {
return self::do_payment($invitationKey, false);
}
}
@ -343,7 +318,7 @@ class PaymentController extends \BaseController
'gateway' => $gateway,
'acceptedCreditCardTypes' => $acceptedCreditCardTypes,
'countries' => Country::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(),
'currencyId' => $client->currency_id
'currencyId' => $client->currency_id,
];
return View::make('payments.payment', $data);
@ -351,32 +326,26 @@ class PaymentController extends \BaseController
public function show_license_payment()
{
if (Input::has('return_url'))
{
if (Input::has('return_url')) {
Session::set('return_url', Input::get('return_url'));
}
if (Input::has('affiliate_key'))
{
if ($affiliate = Affiliate::where('affiliate_key', '=', Input::get('affiliate_key'))->first())
{
if (Input::has('affiliate_key')) {
if ($affiliate = Affiliate::where('affiliate_key', '=', Input::get('affiliate_key'))->first()) {
Session::set('affiliate_id', $affiliate->id);
}
}
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();
}
if (Utils::isNinjaDev() && Input::has('test_mode'))
{
if (Utils::isNinjaDev() && Input::has('test_mode')) {
Session::set('test_mode', Input::get('test_mode'));
}
$account = $this->accountRepo->getNinjaAccount();
$account->load('account_gateways.gateway');
$accountGateway = $account->account_gateways[0];
@ -399,7 +368,7 @@ class PaymentController extends \BaseController
'countries' => Country::remember(DEFAULT_QUERY_CACHE)->orderBy('name')->get(),
'currencyId' => 1,
'paymentTitle' => $affiliate->payment_title,
'paymentSubtitle' => $affiliate->payment_subtitle
'paymentSubtitle' => $affiliate->payment_subtitle,
];
return View::make('payments.payment', $data);
@ -424,8 +393,7 @@ class PaymentController extends \BaseController
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
if ($validator->fails()) {
return Redirect::to('license')
->withErrors($validator);
}
@ -434,39 +402,34 @@ class PaymentController extends \BaseController
$account->load('account_gateways.gateway');
$accountGateway = $account->account_gateways[0];
try
{
try {
$affiliate = Affiliate::find(Session::get('affiliate_id'));
if ($testMode)
{
if ($testMode) {
$ref = 'TEST_MODE';
}
else
{
} else {
$gateway = self::createGateway($accountGateway);
$details = self::getLicensePaymentDetails(Input::all(), $affiliate);
$response = $gateway->purchase($details)->send();
$ref = $response->getTransactionReference();
if (!$ref)
{
if (!$ref) {
Session::flash('error', $response->getMessage());
return Redirect::to('license')->withInput();
}
if (!$response->isSuccessful())
{
if (!$response->isSuccessful()) {
Session::flash('error', $response->getMessage());
Utils::logError($response->getMessage());
return Redirect::to('license')->withInput();
}
}
$licenseKey = Utils::generateLicense();
$license = new License;
$license = new License();
$license->first_name = Input::get('first_name');
$license->last_name = Input::get('last_name');
$license->email = Input::get('email');
@ -479,26 +442,22 @@ class PaymentController extends \BaseController
$data = [
'message' => $affiliate->payment_subtitle,
'license' => $licenseKey,
'hideHeader' => true
'hideHeader' => true,
];
$name = "{$license->first_name} {$license->last_name}";
$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'));
}
else
{
} else {
return View::make('public.license', $data);
}
}
catch (\Exception $e)
{
} catch (\Exception $e) {
$errorMessage = trans('texts.payment_error');
Session::flash('error', $errorMessage);
Utils::logError(Utils::getErrorString($e));
return Redirect::to('license')->withInput();
}
}
@ -513,18 +472,14 @@ class PaymentController extends \BaseController
->where('product_id', '=', $productId)
->first();
if ($license)
{
if ($license->transaction_reference != 'TEST_MODE')
{
if ($license) {
if ($license->transaction_reference != 'TEST_MODE') {
$license->is_claimed = true;
$license->save();
}
return $productId == PRODUCT_INVOICE_DESIGNS ? $_ENV['INVOICE_DESIGNS'] : 'valid';
}
else
{
} else {
return 'invalid';
}
}
@ -544,12 +499,10 @@ class PaymentController extends \BaseController
'postal_code' => 'required',
);
if ($onSite)
{
if ($onSite) {
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
if ($validator->fails()) {
return Redirect::to('payment/'.$invitationKey)
->withErrors($validator);
}
@ -560,8 +513,7 @@ class PaymentController extends \BaseController
$accountGateway = $invoice->client->account->account_gateways[0];
$paymentLibrary = $accountGateway->gateway->paymentlibrary;
if ($onSite)
{
if ($onSite) {
$client = $invoice->client;
$client->address1 = trim(Input::get('address1'));
$client->address2 = trim(Input::get('address2'));
@ -571,55 +523,47 @@ class PaymentController extends \BaseController
$client->save();
}
try
{
if($paymentLibrary->id == PAYMENT_LIBRARY_OMNIPAY)
{
try {
if ($paymentLibrary->id == PAYMENT_LIBRARY_OMNIPAY) {
$gateway = self::createGateway($accountGateway);
$details = self::getPaymentDetails($invoice, Input::all());
$response = $gateway->purchase($details)->send();
$ref = $response->getTransactionReference();
if (!$ref)
{
if (!$ref) {
Session::flash('error', $response->getMessage());
return Redirect::to('payment/'.$invitationKey)
->withInput();
}
if ($response->isSuccessful())
{
if ($response->isSuccessful()) {
$payment = self::createPayment($invitation, $ref);
Session::flash('message', trans('texts.applied_payment'));
return Redirect::to('view/'.$payment->invitation->invitation_key);
}
else if ($response->isRedirect())
{
} elseif ($response->isRedirect()) {
$invitation->transaction_reference = $ref;
$invitation->save();
$response->redirect();
}
else
{
} else {
Session::flash('error', $response->getMessage());
return Utils::fatalError('Sorry, there was an error processing your payment. Please try again later.<p>', $response->getMessage());
}
}
else if ($paymentLibrary->id == PAYMENT_LIBRARY_PHP_PAYMENTS)
{
} elseif ($paymentLibrary->id == PAYMENT_LIBRARY_PHP_PAYMENTS) {
$gateway = $accountGateway->gateway;
$provider = $gateway->provider;
$p = new PHP_Payments(array('mode' => 'test'));
$config = Payment_Utility::load('config', 'drivers/'.$provider);
switch($gateway->id)
{
switch ($gateway->id) {
case GATEWAY_BEANSTREAM:
$config['delay_charge'] = FALSE;
$config['bill_outstanding'] = TRUE;
$config['delay_charge'] = false;
$config['bill_outstanding'] = true;
break;
case GATEWAY_AMAZON:
$config['return_url'] = URL::to('complete');
@ -635,25 +579,23 @@ class PaymentController extends \BaseController
$response = $p->oneoff_payment($provider, $details, $config);
if (strtolower($response->status) == 'success')
{
if (strtolower($response->status) == 'success') {
$payment = self::createPayment($invitation, $response->response_message);
Session::flash('message', trans('texts.applied_payment'));
return Redirect::to('view/'.$payment->invitation->invitation_key);
}
else
{
} else {
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);
}
}
}
catch (\Exception $e)
{
} catch (\Exception $e) {
$errorMessage = trans('texts.payment_error');
Session::flash('error', $errorMessage);
Utils::logError(Utils::getErrorString($e));
return Redirect::to('payment/'.$invitationKey)
->withInput();
}
@ -664,15 +606,13 @@ class PaymentController extends \BaseController
$invoice = $invitation->invoice;
$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->pro_plan_paid = date_create()->format('Y-m-d');
$account->save();
}
if ($invoice->is_quote)
{
if ($invoice->is_quote) {
$invoice = $this->invoiceRepo->cloneInvoice($invoice, $invoice->id);
}
@ -686,8 +626,7 @@ class PaymentController extends \BaseController
$payment->transaction_reference = $ref;
$payment->payment_date = date_create()->format('Y-m-d');
if ($payerId)
{
if ($payerId) {
$payment->payer_id = $payerId;
}
@ -709,37 +648,33 @@ class PaymentController extends \BaseController
$accountGateway = $invoice->client->account->account_gateways[0];
$gateway = self::createGateway($accountGateway);
try
{
try {
$details = self::getPaymentDetails($invoice);
$response = $gateway->completePurchase($details)->send();
$ref = $response->getTransactionReference();
if ($response->isSuccessful())
{
if ($response->isSuccessful()) {
$payment = self::createPayment($invitation, $ref, $payerId);
Session::flash('message', trans('texts.applied_payment'));
return Redirect::to('view/'.$invitation->invitation_key);
}
else
{
} else {
$errorMessage = trans('texts.payment_error')."\n\n".$response->getMessage();
Session::flash('error', $errorMessage);
Utils::logError($errorMessage);
return Redirect::to('view/'.$invitation->invitation_key);
}
}
catch (\Exception $e)
{
} catch (\Exception $e) {
$errorMessage = trans('texts.payment_error');
Session::flash('error', $errorMessage);
Utils::logError($errorMessage."\n\n".$e->getMessage());
return Redirect::to('view/'.$invitation->invitation_key);
}
}
public function store()
{
return $this->save();
@ -752,18 +687,17 @@ class PaymentController extends \BaseController
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';
return Redirect::to($url)
->withErrors($errors)
->withInput();
}
else
{
} else {
$this->paymentRepo->save($publicId, Input::all());
Session::flash('message', trans('texts.created_payment'));
return Redirect::to('clients/'.Input::get('client'));
}
}
@ -774,8 +708,7 @@ class PaymentController extends \BaseController
$ids = Input::get('id') ? Input::get('id') : Input::get('ids');
$count = $this->paymentRepo->bulk($ids, $action);
if ($count > 0)
{
if ($count > 0) {
$message = Utils::pluralize($action.'d_payment', $count);
Session::flash('message', $message);
}

View File

@ -1,7 +1,7 @@
<?php
class ProductController extends \BaseController {
class ProductController extends \BaseController
{
public function getDatatable()
{
$query = DB::table('products')
@ -9,13 +9,11 @@ class ProductController extends \BaseController {
->where('products.deleted_at', '=', null)
->select('products.public_id', 'products.product_key', 'products.notes', 'products.cost');
return Datatable::query($query)
->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('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;">
<button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown">
'.trans('texts.select').' <span class="caret"></span>
@ -38,7 +36,7 @@ class ProductController extends \BaseController {
'product' => Product::scope($publicId)->firstOrFail(),
'method' => 'PUT',
'url' => 'products/'.$publicId,
'title' => trans('texts.edit_product')
'title' => trans('texts.edit_product'),
];
return View::make('accounts.product', $data);
@ -51,7 +49,7 @@ class ProductController extends \BaseController {
'product' => null,
'method' => 'POST',
'url' => 'products',
'title' => trans('texts.create_product')
'title' => trans('texts.create_product'),
];
return View::make('accounts.product', $data);
@ -69,12 +67,9 @@ class ProductController extends \BaseController {
private function save($productPublicId = false)
{
if ($productPublicId)
{
if ($productPublicId) {
$product = Product::scope($productPublicId)->firstOrFail();
}
else
{
} else {
$product = Product::createNew();
}
@ -95,7 +90,7 @@ class ProductController extends \BaseController {
$product->delete();
Session::flash('message', trans('texts.archived_product'));
return Redirect::to('company/products');
}
}

View File

@ -2,8 +2,8 @@
use ninja\repositories\InvoiceRepository;
class QuoteApiController extends Controller {
class QuoteApiController extends Controller
{
protected $invoiceRepo;
public function __construct(InvoiceRepository $invoiceRepo)
@ -22,6 +22,7 @@ class QuoteApiController extends Controller {
$response = json_encode($invoices, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders(count($invoices));
return Response::make($response, 200, $headers);
}

View File

@ -5,8 +5,8 @@ use ninja\repositories\InvoiceRepository;
use ninja\repositories\ClientRepository;
use ninja\repositories\TaxRateRepository;
class QuoteController extends \BaseController {
class QuoteController extends \BaseController
{
protected $mailer;
protected $invoiceRepo;
protected $clientRepo;
@ -24,15 +24,14 @@ class QuoteController extends \BaseController {
public function index()
{
if (!Utils::isPro())
{
if (!Utils::isPro()) {
return Redirect::to('/invoices/create');
}
$data = [
'title' => trans('texts.quotes'),
'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']),
];
/*
@ -46,7 +45,6 @@ class QuoteController extends \BaseController {
return View::make('list', $data);
}
public function clientIndex()
{
$data = [
@ -54,13 +52,12 @@ class QuoteController extends \BaseController {
'hideLogo' => Session::get('white_label'),
'title' => trans('texts.quotes'),
'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);
}
public function getDatatable($clientPublicId = null)
{
$accountId = Auth::user()->account_id;
@ -75,15 +72,13 @@ class QuoteController extends \BaseController {
$invitationKey = Session::get('invitation_key');
$invitation = Invitation::where('invitation_key', '=', $invitationKey)->first();
if (!$invitation || $invitation->is_deleted)
{
if (!$invitation || $invitation->is_deleted) {
return [];
}
$invoice = $invitation->invoice;
if (!$invoice || $invoice->is_deleted)
{
if (!$invoice || $invoice->is_deleted) {
return [];
}
@ -92,8 +87,7 @@ class QuoteController extends \BaseController {
public function create($clientPublicId = 0)
{
if (!Utils::isPro())
{
if (!Utils::isPro()) {
return Redirect::to('/invoices/create');
}
@ -101,8 +95,7 @@ class QuoteController extends \BaseController {
$invoiceNumber = Auth::user()->account->getNextInvoiceNumber(true);
$account = Account::with('country')->findOrFail(Auth::user()->account_id);
if ($clientPublicId)
{
if ($clientPublicId) {
$client = Client::scope($clientPublicId)->firstOrFail();
}
@ -114,7 +107,7 @@ class QuoteController extends \BaseController {
'method' => 'POST',
'url' => 'invoices',
'title' => trans('texts.new_quote'),
'client' => $client);
'client' => $client, );
$data = array_merge($data, self::getViewModel());
return View::make('invoices.edit', $data);
@ -146,8 +139,7 @@ class QuoteController extends \BaseController {
$ids = Input::get('id') ? Input::get('id') : Input::get('ids');
$count = $this->invoiceRepo->bulk($ids, $action, $statusId);
if ($count > 0)
{
if ($count > 0) {
$key = $action == 'mark' ? "updated_quote" : "{$action}d_quote";
$message = Utils::pluralize($key, $count);
Session::flash('message', $message);

View File

@ -1,7 +1,7 @@
<?php
class ReportController extends \BaseController {
class ReportController extends \BaseController
{
public function d3()
{
$message = '';
@ -20,7 +20,7 @@ class ReportController extends \BaseController {
$data = [
'feature' => ACCOUNT_DATA_VISUALIZATIONS,
'clients' => $clients,
'message' => $message
'message' => $message,
];
return View::make('reports.d3', $data);
@ -28,15 +28,12 @@ class ReportController extends \BaseController {
public function report()
{
if (Input::all())
{
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
{
} else {
$groupBy = 'MONTH';
$chartType = 'Bar';
$startDate = Utils::today(false)->modify('-3 month');
@ -50,10 +47,8 @@ class ReportController extends \BaseController {
$maxTotals = 0;
$width = 10;
if (Auth::user()->account->isPro())
{
foreach ([ENTITY_INVOICE, ENTITY_PAYMENT, ENTITY_CREDIT] as $entityType)
{
if (Auth::user()->account->isPro()) {
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)
@ -62,8 +57,7 @@ class ReportController extends \BaseController {
->where($entityType.'s.'.$entityType.'_date', '<=', $endDate->format('Y-m-d'))
->groupBy($groupBy);
if ($entityType == ENTITY_INVOICE)
{
if ($entityType == ENTITY_INVOICE) {
$records->where('is_quote', '=', false)
->where('is_recurring', '=', false);
}
@ -77,14 +71,12 @@ class ReportController extends \BaseController {
$totals = [];
foreach ($period as $d)
{
foreach ($period as $d) {
$dateFormat = $groupBy == 'DAYOFYEAR' ? 'z' : ($groupBy == 'WEEK' ? 'W' : 'n');
$date = $d->format($dateFormat);
$totals[] = isset($data[$date]) ? $data[$date] : 0;
if ($entityType == ENTITY_INVOICE)
{
if ($entityType == ENTITY_INVOICE) {
$labelFormat = $groupBy == 'DAYOFYEAR' ? 'j' : ($groupBy == 'WEEK' ? 'W' : 'F');
$label = $d->format($labelFormat);
$labels[] = $label;
@ -93,11 +85,10 @@ class ReportController extends \BaseController {
$max = max($totals);
if ($max > 0)
{
if ($max > 0) {
$datasets[] = [
'totals' => $totals,
'colors' => $entityType == ENTITY_INVOICE ? '78,205,196' : ($entityType == ENTITY_CREDIT ? '199,244,100' : '255,107,107')
'colors' => $entityType == ENTITY_INVOICE ? '78,205,196' : ($entityType == ENTITY_CREDIT ? '199,244,100' : '255,107,107'),
];
$maxTotals = max($max, $maxTotals);
}
@ -110,12 +101,12 @@ class ReportController extends \BaseController {
$dateTypes = [
'DAYOFYEAR' => 'Daily',
'WEEK' => 'Weekly',
'MONTH' => 'Monthly'
'MONTH' => 'Monthly',
];
$chartTypes = [
'Bar' => 'Bar',
'Line' => 'Line'
'Line' => 'Line',
];
$params = [

View File

@ -13,8 +13,8 @@ use ninja\repositories\AccountRepository;
use ninja\mailers\ContactMailer;
use ninja\mailers\UserMailer;
class UserController extends BaseController {
class UserController extends BaseController
{
protected $accountRepo;
protected $contactMailer;
protected $userMailer;
@ -36,13 +36,11 @@ class UserController extends BaseController {
->where('users.public_id', '>', 0)
->select('users.public_id', 'users.first_name', 'users.last_name', 'users.email', 'users.confirmed', 'users.public_id');
return Datatable::query($query)
->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('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;">
<button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown">
'.trans('texts.select').' <span class="caret"></span>
@ -88,7 +86,7 @@ class UserController extends BaseController {
'user' => $user,
'method' => 'PUT',
'url' => 'users/'.$publicId,
'title' => trans('texts.edit_user')
'title' => trans('texts.edit_user'),
];
return View::make('users.edit', $data);
@ -110,18 +108,17 @@ class UserController extends BaseController {
*/
public function create()
{
if (!Auth::user()->confirmed)
{
if (!Auth::user()->confirmed) {
Session::flash('error', trans('texts.register_to_add_user'));
return Redirect::to('company/advanced_settings/user_management');
}
if (Utils::isNinja())
{
if (Utils::isNinja()) {
$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'));
return Redirect::to('company/advanced_settings/user_management');
}
}
@ -131,7 +128,7 @@ class UserController extends BaseController {
'user' => null,
'method' => 'POST',
'url' => 'users',
'title' => trans('texts.add_user')
'title' => trans('texts.add_user'),
];
return View::make('users.edit', $data);
@ -146,6 +143,7 @@ class UserController extends BaseController {
$user->delete();
Session::flash('message', trans('texts.deleted_user'));
return Redirect::to('company/advanced_settings/user_management');
}
@ -160,38 +158,31 @@ class UserController extends BaseController {
'last_name' => 'required',
];
if ($userPublicId)
{
if ($userPublicId) {
$user = User::where('account_id', '=', Auth::user()->account_id)
->where('public_id', '=', $userPublicId)->firstOrFail();
$rules['email'] = 'required|email|unique:users,email,'.$user->id.',id';
}
else
{
} else {
$rules['email'] = 'required|email|unique:users';
}
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
if ($validator->fails()) {
return Redirect::to($userPublicId ? 'users/edit' : 'users/create')->withInput()->withErrors($validator);
}
if ($userPublicId)
{
if ($userPublicId) {
$user->first_name = trim(Input::get('first_name'));
$user->last_name = trim(Input::get('last_name'));
$user->username = trim(Input::get('email'));
$user->email = trim(Input::get('email'));
}
else
{
} else {
$lastUser = User::withTrashed()->where('account_id', '=', Auth::user()->account_id)
->orderBy('public_id', 'DESC')->first();
$user = new User;
$user = new User();
$user->account_id = Auth::user()->account_id;
$user->first_name = trim(Input::get('first_name'));
$user->last_name = trim(Input::get('last_name'));
@ -205,13 +196,10 @@ class UserController extends BaseController {
$user->save();
if (!$user->confirmed)
{
if (!$user->confirmed) {
$this->userMailer->sendConfirmation($user, Auth::user());
$message = trans('texts.sent_invite');
}
else
{
} else {
$message = trans('texts.updated_user');
}
@ -226,8 +214,7 @@ class UserController extends BaseController {
*/
public function login()
{
if( Confide::user() )
{
if (Confide::user()) {
Event::fire('user.login');
Session::reflash();
@ -245,9 +232,7 @@ class UserController extends BaseController {
return Redirect::to('/dashboard');
}
*/
}
else
{
} else {
return View::make(Config::get('confide::login_form'));
}
}
@ -269,22 +254,18 @@ class UserController extends BaseController {
// with the second parameter as true.
// logAttempt will check if the 'email' perhaps is the username.
// 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');
// Redirect the user to the URL they were trying to access before
// caught by the authentication filter IE Redirect::guest('user/login').
// Otherwise fallback to '/'
// Fix pull #145
return Redirect::intended('/dashboard'); // change it to '/admin', '/dashboard' or something
}
else
{
} else {
//$user = new User;
// Check if there was too many login attempts
if( Confide::isThrottled( $input ) )
{
if (Confide::isThrottled($input)) {
$err_msg = trans('texts.confide.too_many_attempts');
}
/*
@ -293,8 +274,7 @@ class UserController extends BaseController {
$err_msg = Lang::get('confide::confide.alerts.not_confirmed');
}
*/
else
{
else {
$err_msg = trans('texts.confide.wrong_credentials');
}
@ -311,37 +291,30 @@ class UserController extends BaseController {
*/
public function confirm($code)
{
if ( Confide::confirm( $code ) )
{
if (Confide::confirm($code)) {
$notice_msg = trans('texts.confide.confirmation');
$user = User::where('confirmation_code', '=', $code)->get()->first();
$user->confirmation_code = '';
$user->save();
if ($user->public_id)
{
if ($user->public_id) {
Auth::login($user);
return Redirect::to('user/reset');
}
else
{
if (Session::has(REQUESTED_PRO_PLAN))
{
} else {
if (Session::has(REQUESTED_PRO_PLAN)) {
Session::forget(REQUESTED_PRO_PLAN);
$invitation = $this->accountRepo->enableProPlan();
return Redirect::to($invitation->getLink());
}
else
{
} else {
return Redirect::action('UserController@login')->with('message', $notice_msg);
}
}
}
else
{
} else {
$error_msg = trans('texts.confide.wrong_confirmation');
return Redirect::action('UserController@login')->with('error', $error_msg);
}
}
@ -364,10 +337,10 @@ class UserController extends BaseController {
Confide::forgotPassword(Input::get('email'));
$notice_msg = trans('texts.confide.password_forgot');
return Redirect::action('UserController@login')
->with('notice', $notice_msg);
/*
if( Confide::forgotPassword( Input::get( 'email' ) ) )
{
@ -401,16 +374,14 @@ class UserController extends BaseController {
*/
public function do_reset_password()
{
if (Auth::check())
{
if (Auth::check()) {
$rules = [
'password' => 'required|between:4,11|confirmed',
'password_confirmation' => 'between:4,11',
];
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
if ($validator->fails()) {
return Redirect::to('user/reset')->withInput()->withErrors($validator);
}
@ -419,10 +390,9 @@ class UserController extends BaseController {
$user->save();
Session::flash('message', trans('texts.confide.password_reset'));
return Redirect::to('/dashboard');
}
else
{
} else {
$input = array(
'token' => Input::get('token'),
'password' => Input::get('password'),
@ -430,15 +400,14 @@ class UserController extends BaseController {
);
// 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');
return Redirect::action('UserController@login')
->with('notice', $notice_msg);
}
else
{
} else {
$error_msg = trans('texts.confide.wrong_password_reset');
return Redirect::action('UserController@reset_password', array('token' => $input['token']))
->withInput()
->with('error', $error_msg);
@ -452,10 +421,8 @@ class UserController extends BaseController {
*/
public function logout()
{
if (Auth::check())
{
if (!Auth::user()->registered)
{
if (Auth::check()) {
if (!Auth::user()->registered) {
$account = Auth::user()->account;
$account->forceDelete();
}

View File

@ -68,20 +68,16 @@ class Account extends Eloquent
{
$this->load('account_gateways');
if ($gatewayId)
{
if ($gatewayId) {
return $this->getGatewayConfig($gatewayId) != false;
}
else
{
} else {
return count($this->account_gateways) > 0;
}
}
public function getDisplayName()
{
if ($this->name)
{
if ($this->name) {
return $this->name;
}
@ -93,22 +89,17 @@ class Account extends Eloquent
public function getTimezone()
{
if ($this->timezone)
{
if ($this->timezone) {
return $this->timezone->name;
}
else
{
} else {
return 'US/Eastern';
}
}
public function getGatewayConfig($gatewayId)
{
foreach ($this->account_gateways as $gateway)
{
if ($gateway->gateway_id == $gatewayId)
{
foreach ($this->account_gateways as $gateway) {
if ($gateway->gateway_id == $gatewayId) {
return $gateway;
}
}
@ -128,6 +119,7 @@ class Account extends Eloquent
return 0;
}
list($width, $height) = getimagesize($path);
return $width;
}
@ -138,6 +130,7 @@ class Account extends Eloquent
return 0;
}
list($width, $height) = getimagesize($path);
return $height;
}
@ -174,6 +167,7 @@ class Account extends Eloquent
public function getLocale()
{
$language = Language::remember(DEFAULT_QUERY_CACHE)->where('id', '=', $this->account->language_id)->first();
return $language->locale;
}
@ -219,8 +213,7 @@ class Account extends Eloquent
'invoice_issued_to',
];
foreach ($fields as $field)
{
foreach ($fields as $field) {
$data[$field] = trans("texts.$field");
}
@ -229,24 +222,19 @@ class Account extends Eloquent
public function isPro()
{
if (!Utils::isNinjaProd())
{
if (!Utils::isNinjaProd()) {
return true;
}
if ($this->account_key == NINJA_ACCOUNT_KEY)
{
if ($this->account_key == NINJA_ACCOUNT_KEY) {
return true;
}
$datePaid = $this->pro_plan_paid;
if (!$datePaid || $datePaid == '0000-00-00')
{
if (!$datePaid || $datePaid == '0000-00-00') {
return false;
}
else if ($datePaid == NINJA_DATE)
{
} elseif ($datePaid == NINJA_DATE) {
return true;
}
@ -259,8 +247,7 @@ class Account extends Eloquent
public function isWhiteLabel()
{
if (Utils::isNinjaProd())
{
if (Utils::isNinjaProd()) {
return false;
}
@ -274,8 +261,7 @@ class Account extends Eloquent
public function hideFieldsForViz()
{
foreach ($this->clients as $client)
{
foreach ($this->clients as $client) {
$client->setVisible([
'public_id',
'name',
@ -285,8 +271,7 @@ class Account extends Eloquent
'contacts',
]);
foreach ($client->invoices as $invoice)
{
foreach ($client->invoices as $invoice) {
$invoice->setVisible([
'public_id',
'invoice_number',
@ -297,8 +282,7 @@ class Account extends Eloquent
'created_at',
]);
foreach ($invoice->invoice_items as $invoiceItem)
{
foreach ($invoice->invoice_items as $invoiceItem) {
$invoiceItem->setVisible([
'product_key',
'cost',
@ -307,17 +291,15 @@ class Account extends Eloquent
}
}
foreach ($client->contacts as $contact)
{
foreach ($client->contacts as $contact) {
$contact->setVisible([
'public_id',
'first_name',
'last_name',
'email']);
'email', ]);
}
}
return $this;
}
}

View File

@ -12,11 +12,11 @@ class AccountGateway extends EntityModel
$flags = unserialize(CREDIT_CARDS);
$arrayOfImages = [];
foreach ($flags as $card => $name)
{
if (($this->accepted_credit_cards & $card) == $card)
foreach ($flags as $card => $name) {
if (($this->accepted_credit_cards & $card) == $card) {
$arrayOfImages[] = ['source' => asset($name['card']), 'alt' => $name['text']];
}
}
return $arrayOfImages;
}

View File

@ -35,7 +35,6 @@ define("ACTIVITY_TYPE_RESTORE_CLIENT", 26);
define("ACTIVITY_TYPE_RESTORE_PAYMENT", 27);
define("ACTIVITY_TYPE_RESTORE_CREDIT", 28);
class Activity extends Eloquent
{
public $timestamps = true;
@ -53,20 +52,15 @@ class Activity extends Eloquent
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->account_id = $entity->account_id;
}
else if (Auth::check())
{
} elseif (Auth::check()) {
$activity->user_id = Auth::user()->id;
$activity->account_id = Auth::user()->account_id;
}
else
{
} else {
Utils::fatalError();
}
@ -81,16 +75,14 @@ class Activity extends Eloquent
$activity->message = Utils::encodeActivity(Auth::user(), 'created', $client);
$activity->save();
if ($notify)
{
if ($notify) {
Activity::checkSubscriptions(EVENT_CREATE_CLIENT, $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->client_id = $client->id;
$activity->activity_type_id = ACTIVITY_TYPE_DELETE_CLIENT;
@ -101,8 +93,7 @@ class Activity extends Eloquent
public static function archiveClient($client)
{
if (!$client->is_deleted)
{
if (!$client->is_deleted) {
$activity = Activity::getBlank();
$activity->client_id = $client->id;
$activity->activity_type_id = ACTIVITY_TYPE_ARCHIVE_CLIENT;
@ -124,19 +115,15 @@ class Activity extends Eloquent
public static function createInvoice($invoice)
{
if (Auth::check())
{
if (Auth::check()) {
$message = Utils::encodeActivity(Auth::user(), 'created', $invoice);
}
else
{
} else {
$message = Utils::encodeActivity(null, 'created', $invoice);
}
$adjustment = 0;
$client = $invoice->client;
if (!$invoice->is_quote && !$invoice->is_recurring)
{
if (!$invoice->is_quote && !$invoice->is_recurring) {
$adjustment = $invoice->amount;
$client->balance = $client->balance + $adjustment;
$client->save();
@ -156,8 +143,7 @@ class Activity extends Eloquent
public static function archiveInvoice($invoice)
{
if (!$invoice->is_deleted)
{
if (!$invoice->is_deleted) {
$activity = Activity::getBlank();
$activity->invoice_id = $invoice->id;
$activity->client_id = $invoice->client_id;
@ -200,10 +186,8 @@ class Activity extends Eloquent
{
$client = $invoice->client;
if ($invoice->is_deleted && !$invoice->getOriginal('is_deleted'))
{
if (!$invoice->is_quote && !$invoice->is_recurring)
{
if ($invoice->is_deleted && !$invoice->getOriginal('is_deleted')) {
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->save();
@ -217,20 +201,16 @@ class Activity extends Eloquent
$activity->balance = $invoice->client->balance;
$activity->adjustment = $invoice->is_quote ? 0 : $invoice->balance * -1;
$activity->save();
}
else
{
} else {
$diff = floatval($invoice->amount) - floatval($invoice->getOriginal('amount'));
if ($diff == 0)
{
if ($diff == 0) {
return;
}
$backupInvoice = Invoice::with('invoice_items', 'client.account', 'client.contacts')->find($invoice->id);
if (!$invoice->is_quote && !$invoice->is_recurring)
{
if (!$invoice->is_quote && !$invoice->is_recurring) {
$client->balance = $client->balance + $diff;
$client->save();
}
@ -249,16 +229,14 @@ class Activity extends Eloquent
public static function viewInvoice($invitation)
{
if (Session::get($invitation->invitation_key))
{
if (Session::get($invitation->invitation_key)) {
return;
}
Session::put($invitation->invitation_key, true);
$invoice = $invitation->invoice;
if (!$invoice->isViewed())
{
if (!$invoice->isViewed()) {
$invoice->invoice_status_id = INVOICE_STATUS_VIEWED;
$invoice->save();
}
@ -283,8 +261,6 @@ class Activity extends Eloquent
$activity->save();
}
public static function createPayment($payment)
{
$client = $payment->client;
@ -292,14 +268,11 @@ class Activity extends Eloquent
$client->paid_to_date = $client->paid_to_date + $payment->amount;
$client->save();
if ($payment->contact_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
{
} 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);
@ -307,8 +280,7 @@ class Activity extends Eloquent
$activity->payment_id = $payment->id;
if ($payment->invoice_id)
{
if ($payment->invoice_id) {
$activity->invoice_id = $payment->invoice_id;
$invoice = $payment->invoice;
@ -329,8 +301,7 @@ class Activity extends Eloquent
public static function updatePayment($payment)
{
if ($payment->is_deleted && !$payment->getOriginal('is_deleted'))
{
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;
@ -349,9 +320,7 @@ class Activity extends Eloquent
$activity->balance = $client->balance;
$activity->adjustment = $payment->amount;
$activity->save();
}
else
{
} else {
/*
$diff = floatval($invoice->amount) - floatval($invoice->getOriginal('amount'));
@ -379,8 +348,7 @@ class Activity extends Eloquent
public static function archivePayment($payment)
{
if ($payment->is_deleted)
{
if ($payment->is_deleted) {
return;
}
@ -427,8 +395,7 @@ class Activity extends Eloquent
public static function updateCredit($credit)
{
if ($credit->is_deleted && !$credit->getOriginal('is_deleted'))
{
if ($credit->is_deleted && !$credit->getOriginal('is_deleted')) {
$activity = Activity::getBlank();
$activity->credit_id = $credit->id;
$activity->client_id = $credit->client_id;
@ -436,9 +403,7 @@ class Activity extends Eloquent
$activity->message = Utils::encodeActivity(Auth::user(), 'deleted '.Utils::formatMoney($credit->balance, $credit->client->currency_id).' credit');
$activity->balance = $credit->client->balance;
$activity->save();
}
else
{
} else {
/*
$diff = floatval($invoice->amount) - floatval($invoice->getOriginal('amount'));
@ -466,8 +431,7 @@ class Activity extends Eloquent
public static function archiveCredit($credit)
{
if ($credit->is_deleted)
{
if ($credit->is_deleted) {
return;
}
@ -499,8 +463,7 @@ class Activity extends Eloquent
$subscription = Auth::user()->account->getSubscription($event);
if ($subscription)
{
if ($subscription) {
Utils::notifyZapier($subscription, $data);
}
}

View File

@ -72,8 +72,7 @@ class Client extends EntityModel
public function getDisplayName()
{
if ($this->name)
{
if ($this->name) {
return $this->name;
}
@ -111,8 +110,7 @@ class Client extends EntityModel
$str .= '<br/>'.$this->country->name;
}
if ($str)
{
if ($str) {
$str = '<p>'.$str.'</p>';
}
@ -123,8 +121,7 @@ class Client extends EntityModel
{
$str = '';
if ($this->work_phone)
{
if ($this->work_phone) {
$str .= '<i class="fa fa-phone" style="width: 20px"></i>'.Utils::formatPhoneNumber($this->work_phone);
}
@ -135,8 +132,7 @@ class Client extends EntityModel
{
$str = '';
if ($this->id_number)
{
if ($this->id_number) {
$str .= '<i class="fa fa-vat-number" style="width: 20px"></i>'.$this->vat_number;
}
@ -147,21 +143,18 @@ class Client extends EntityModel
{
$str = '';
if ($this->vat_number)
{
if ($this->vat_number) {
$str .= '<i class="fa fa-vat-number" style="width: 20px"></i>'.$this->vat_number;
}
return $str;
}
public function getNotes()
{
$str = '';
if ($this->private_notes)
{
if ($this->private_notes) {
$str .= '<i>'.$this->private_notes.'</i>';
}
@ -172,13 +165,11 @@ class Client extends EntityModel
{
$str = '';
if ($this->client_industry)
{
if ($this->client_industry) {
$str .= $this->client_industry->name.' ';
}
if ($this->client_size)
{
if ($this->client_size) {
$str .= $this->client_size->name;
}
@ -190,13 +181,11 @@ class Client extends EntityModel
$str = '';
$account = $this->account;
if ($account->custom_client_label1 && $this->custom_value1)
{
if ($account->custom_client_label1 && $this->custom_value1) {
$str .= "{$account->custom_client_label1}: {$this->custom_value1}<br/>";
}
if ($account->custom_client_label2 && $this->custom_value2)
{
if ($account->custom_client_label2 && $this->custom_value2) {
$str .= "{$account->custom_client_label2}: {$this->custom_value2}<br/>";
}
@ -205,8 +194,7 @@ class Client extends EntityModel
public function getWebsite()
{
if (!$this->website)
{
if (!$this->website) {
return '';
}
@ -225,16 +213,12 @@ class Client extends EntityModel
public function getDateCreated()
{
if ($this->created_at == '0000-00-00 00:00:00')
{
if ($this->created_at == '0000-00-00 00:00:00') {
return '---';
}
else
{
} else {
return $this->created_at->format('m/d/y h:i a');
}
}
}
/*
@ -244,17 +228,14 @@ Client::created(function($client)
});
*/
Client::updating(function($client)
{
Client::updating(function ($client) {
Activity::updateClient($client);
});
Client::deleting(function($client)
{
Client::deleting(function ($client) {
Activity::archiveClient($client);
});
Client::restoring(function($client)
{
Client::restoring(function ($client) {
Activity::restoreClient($client);
});

View File

@ -33,25 +33,18 @@ class Contact extends EntityModel
public function getDisplayName()
{
if ($this->getFullName())
{
if ($this->getFullName()) {
return $this->getFullName();
}
else
{
} else {
return $this->email;
}
}
public function getFullName()
{
if ($this->first_name || $this->last_name)
{
if ($this->first_name || $this->last_name) {
return $this->first_name.' '.$this->last_name;
}
else
{
} else {
return '';
}
}
@ -60,23 +53,19 @@ class Contact extends EntityModel
{
$str = '';
if ($this->first_name || $this->last_name)
{
if ($this->first_name || $this->last_name) {
$str .= '<b>'.$this->first_name.' '.$this->last_name.'</b><br/>';
}
if ($this->email)
{
if ($this->email) {
$str .= '<i class="fa fa-envelope" style="width: 20px"></i>'.HTML::mailto($this->email, $this->email).'<br/>';
}
if ($this->phone)
{
if ($this->phone) {
$str .= '<i class="fa fa-phone" style="width: 20px"></i>'.Utils::formatPhoneNumber($this->phone);
}
if ($str)
{
if ($str) {
$str = '<p>'.$str.'</p>';
}

View File

@ -24,13 +24,10 @@ class Credit extends EntityModel
public function apply($amount)
{
if ($amount > $this->balance)
{
if ($amount > $this->balance) {
$applied = $this->balance;
$this->balance = 0;
}
else
{
} else {
$applied = $amount;
$this->balance = $this->balance - $amount;
}
@ -41,22 +38,18 @@ class Credit extends EntityModel
}
}
Credit::created(function($credit)
{
Credit::created(function ($credit) {
Activity::createCredit($credit);
});
Credit::updating(function($credit)
{
Credit::updating(function ($credit) {
Activity::updateCredit($credit);
});
Credit::deleting(function($credit)
{
Credit::deleting(function ($credit) {
Activity::archiveCredit($credit);
});
Credit::restoring(function($credit)
{
Credit::restoring(function ($credit) {
Activity::restoreCredit($credit);
});

View File

@ -12,29 +12,21 @@ class EntityModel extends Eloquent
$className = get_called_class();
$entity = new $className();
if ($parent)
{
if ($parent) {
$entity->user_id = $parent instanceof User ? $parent->id : $parent->user_id;
$entity->account_id = $parent->account_id;
}
else if (Auth::check())
{
} elseif (Auth::check()) {
$entity->user_id = Auth::user()->id;
$entity->account_id = Auth::user()->account_id;
}
else
{
} else {
Utils::fatalError();
}
$lastEntity = $className::withTrashed()->scope(false, $entity->account_id)->orderBy('public_id', 'DESC')->first();
if ($lastEntity)
{
if ($lastEntity) {
$entity->public_id = $lastEntity->public_id + 1;
}
else
{
} else {
$entity->public_id = 1;
}
@ -44,6 +36,7 @@ class EntityModel extends Eloquent
public static function getPrivateId($publicId)
{
$className = get_called_class();
return $className::scope($publicId)->pluck('id');
}
@ -66,21 +59,16 @@ class EntityModel extends Eloquent
public function scopeScope($query, $publicId = false, $accountId = false)
{
if (!$accountId)
{
if (!$accountId) {
$accountId = Auth::user()->account_id;
}
$query->whereAccountId($accountId);
if ($publicId)
{
if (is_array($publicId))
{
if ($publicId) {
if (is_array($publicId)) {
$query->whereIn('public_id', $publicId);
}
else
{
} else {
$query->wherePublicId($publicId);
}
}

View File

@ -29,6 +29,7 @@ class Gateway extends Eloquent
$key = 'texts.gateway_help_'.$this->id;
$str = trans($key, ['link' => "<a href='$link' target='_blank'>Click here</a>"]);
return $key != $str ? $str : '';
}
@ -36,21 +37,16 @@ class Gateway extends Eloquent
{
$paymentLibrary = $this->paymentlibrary;
if ($paymentLibrary->id == PAYMENT_LIBRARY_OMNIPAY)
{
if ($paymentLibrary->id == PAYMENT_LIBRARY_OMNIPAY) {
$fields = Omnipay::create($this->provider)->getDefaultParameters();
}
else
{
} else {
$fields = Payment_Utility::load('config', 'drivers/'.strtolower($this->provider));
}
if ($fields == null)
{
if ($fields == null) {
$fields = array();
}
return $fields;
}
}

View File

@ -4,5 +4,4 @@ class Industry extends Eloquent
{
public $timestamps = false;
protected $softDelete = false;
}

View File

@ -92,7 +92,7 @@ class Invoice extends EntityModel
'custom_value1',
'custom_value2',
'custom_taxes1',
'custom_taxes2']);
'custom_taxes2', ]);
$this->client->setVisible([
'name',
@ -109,7 +109,7 @@ class Invoice extends EntityModel
'country',
'currency_id',
'custom_value1',
'custom_value2']);
'custom_value2', ]);
$this->account->setVisible([
'name',
@ -135,26 +135,24 @@ class Invoice extends EntityModel
'hide_quantity',
'hide_paid_to_date',
'custom_invoice_label1',
'custom_invoice_label2']);
'custom_invoice_label2', ]);
foreach ($this->invoice_items as $invoiceItem)
{
foreach ($this->invoice_items as $invoiceItem) {
$invoiceItem->setVisible([
'product_key',
'notes',
'cost',
'qty',
'tax_name',
'tax_rate']);
'tax_rate', ]);
}
foreach ($this->client->contacts as $contact)
{
foreach ($this->client->contacts as $contact) {
$contact->setVisible([
'first_name',
'last_name',
'email',
'phone']);
'phone', ]);
}
return $this;
@ -162,13 +160,11 @@ class Invoice extends EntityModel
public function shouldSendToday()
{
if (!$this->start_date || strtotime($this->start_date) > strtotime('now'))
{
if (!$this->start_date || strtotime($this->start_date) > strtotime('now')) {
return false;
}
if ($this->end_date && strtotime($this->end_date) < strtotime('now'))
{
if ($this->end_date && strtotime($this->end_date) < strtotime('now')) {
return false;
}
@ -178,26 +174,21 @@ class Invoice extends EntityModel
$dayOfMonthToday = date('j');
$dayOfMonthStart = date('j', strtotime($this->start_date));
if (!$this->last_sent_date)
{
if (!$this->last_sent_date) {
return true;
}
else
{
} 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)
{
if ($daysSinceLastSent == 0) {
return false;
}
}
switch ($this->frequency_id)
{
switch ($this->frequency_id) {
case FREQUENCY_WEEKLY:
return $daysSinceLastSent >= 7;
case FREQUENCY_TWO_WEEKS:
@ -220,23 +211,19 @@ class Invoice extends EntityModel
}
}
Invoice::created(function($invoice)
{
Invoice::created(function ($invoice) {
$invoice->account->incrementCounter($invoice->invoice_number, $invoice->is_quote, $invoice->recurring_invoice_id);
Activity::createInvoice($invoice);
});
Invoice::updating(function($invoice)
{
Invoice::updating(function ($invoice) {
Activity::updateInvoice($invoice);
});
Invoice::deleting(function($invoice)
{
Invoice::deleting(function ($invoice) {
Activity::archiveInvoice($invoice);
});
Invoice::restoring(function($invoice)
{
Invoice::restoring(function ($invoice) {
Activity::restoreInvoice($invoice);
});

View File

@ -4,7 +4,7 @@ class Payment extends EntityModel
{
public function invoice()
{
return $this->belongsTo('Invoice')->withTrashed();;
return $this->belongsTo('Invoice')->withTrashed();
}
public function invitation()
@ -14,7 +14,7 @@ class Payment extends EntityModel
public function client()
{
return $this->belongsTo('Client')->withTrashed();;
return $this->belongsTo('Client')->withTrashed();
}
public function account()
@ -41,25 +41,20 @@ class Payment extends EntityModel
{
return ENTITY_PAYMENT;
}
}
Payment::created(function($payment)
{
Payment::created(function ($payment) {
Activity::createPayment($payment);
});
Payment::updating(function($payment)
{
Payment::updating(function ($payment) {
Activity::updatePayment($payment);
});
Payment::deleting(function($payment)
{
Payment::deleting(function ($payment) {
Activity::archivePayment($payment);
});
Payment::restoring(function($payment)
{
Payment::restoring(function ($payment) {
Activity::restorePayment($payment);
});

View File

@ -30,22 +30,16 @@ class Project extends Eloquent
$className = get_called_class();
$entity = new $className();
if ($parent)
{
if ($parent) {
$entity->user_id = $parent instanceof User ? $parent->id : $parent->user_id;
$entity->account_id = $parent->account_id;
}
else if (Auth::check())
{
} elseif (Auth::check()) {
$entity->user_id = Auth::user()->id;
$entity->account_id = Auth::user()->account_id;
}
else
{
} else {
Utils::fatalError();
}
return $entity;
}
}

View File

@ -30,18 +30,13 @@ class ProjectCode extends Eloquent
$className = get_called_class();
$entity = new $className();
if ($parent)
{
if ($parent) {
$entity->user_id = $parent instanceof User ? $parent->id : $parent->user_id;
$entity->account_id = $parent->account_id;
}
else if (Auth::check())
{
} elseif (Auth::check()) {
$entity->user_id = Auth::user()->id;
$entity->account_id = Auth::user()->account_id;
}
else
{
} else {
Utils::fatalError();
}

View File

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

View File

@ -55,18 +55,13 @@ class TimesheetEvent extends Eloquent
$className = get_called_class();
$entity = new $className();
if ($parent)
{
if ($parent) {
$entity->user_id = $parent instanceof User ? $parent->id : $parent->user_id;
$entity->account_id = $parent->account_id;
}
else if (Auth::check())
{
} elseif (Auth::check()) {
$entity->user_id = Auth::user()->id;
$entity->account_id = Auth::user()->account_id;
}
else
{
} else {
Utils::fatalError();
}
@ -106,7 +101,6 @@ class TimesheetEvent extends Eloquent
} elseif ($value != $attributes_new[$key]) {
$result[$key] = $attributes_new[$key];
}
} else {
$result[$key] = null;
}
@ -125,5 +119,4 @@ class TimesheetEvent extends Eloquent
return $result;
}
}

View File

@ -25,22 +25,16 @@ class TimesheetEventSource extends Eloquent
$className = get_called_class();
$entity = new $className();
if ($parent)
{
if ($parent) {
$entity->user_id = $parent instanceof User ? $parent->id : $parent->user_id;
$entity->account_id = $parent->account_id;
}
else if (Auth::check())
{
} elseif (Auth::check()) {
$entity->user_id = Auth::user()->id;
$entity->account_id = Auth::user()->account_id;
}
else
{
} else {
Utils::fatalError();
}
return $entity;
}
}

View File

@ -92,29 +92,20 @@ class User extends ConfideUser implements UserInterface, RemindableInterface
public function getDisplayName()
{
if ($this->getFullName())
{
if ($this->getFullName()) {
return $this->getFullName();
}
else if ($this->email)
{
} elseif ($this->email) {
return $this->email;
}
else
{
} else {
return 'Guest';
}
}
public function getFullName()
{
if ($this->first_name || $this->last_name)
{
if ($this->first_name || $this->last_name) {
return $this->first_name.' '.$this->last_name;
}
else
{
} else {
return '';
}
}
@ -131,21 +122,16 @@ class User extends ConfideUser implements UserInterface, RemindableInterface
public function getPopOverText()
{
if (!Utils::isNinja() || !Auth::check() || Session::has('error'))
{
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) {
if (!Utils::isRegistered()) {
return trans('texts.sign_up_to_save');
}
else if (!Auth::user()->account->name)
{
} elseif (!Auth::user()->account->name) {
return trans('texts.set_name');
}
}
@ -155,12 +141,9 @@ class User extends ConfideUser implements UserInterface, RemindableInterface
public function afterSave($success = true, $forced = false)
{
if ($this->email)
{
if ($this->email) {
return parent::afterSave($success = true, $forced = false);
}
else
{
} else {
return true;
}
}

View File

@ -3,22 +3,20 @@
use Mail;
use Utils;
class Mailer {
class Mailer
{
public function sendTo($toEmail, $fromEmail, $fromName, $subject, $view, $data = [])
{
$views = [
'emails.'.$view.'_html',
'emails.'.$view.'_text'
'emails.'.$view.'_text',
];
Mail::send($views, $data, function($message) use ($toEmail, $fromEmail, $fromName, $subject)
{
Mail::send($views, $data, function ($message) use ($toEmail, $fromEmail, $fromName, $subject) {
$replyEmail = $fromEmail;
// 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;
}

View File

@ -2,16 +2,14 @@
use Invoice;
use Payment;
use Contact;
use User;
use Utils;
class UserMailer extends Mailer {
class UserMailer extends Mailer
{
public function sendConfirmation(User $user, User $invitor = null)
{
if (!$user->email)
{
if (!$user->email) {
return;
}
@ -20,16 +18,13 @@ class UserMailer extends Mailer {
$data = [
'user' => $user,
'invitationMessage' => $invitor ? trans('texts.invitation_message', ['invitor' => $invitor->getDisplayName()]) : ''
'invitationMessage' => $invitor ? trans('texts.invitation_message', ['invitor' => $invitor->getDisplayName()]) : '',
];
if ($invitor)
{
if ($invitor) {
$fromEmail = $invitor->email;
$fromName = $invitor->getDisplayName();
}
else
{
} else {
$fromEmail = CONTACT_EMAIL;
$fromName = CONTACT_NAME;
}
@ -39,8 +34,7 @@ class UserMailer extends Mailer {
public function sendNotification(User $user, Invoice $invoice, $notificationType, Payment $payment = null)
{
if (!$user->email)
{
if (!$user->email) {
return;
}
@ -54,11 +48,10 @@ class UserMailer extends Mailer {
'userName' => $user->getDisplayName(),
'invoiceAmount' => Utils::formatMoney($invoice->amount, $invoice->client->currency_id),
'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);
}

View File

@ -18,15 +18,13 @@ class AccountRepository
{
public function create()
{
$account = new Account;
$account = new Account();
$account->ip = Request::getClientIp();
$account->account_key = str_random(RANDOM_KEY_LENGTH);
if (Session::has(SESSION_LOCALE))
{
if (Session::has(SESSION_LOCALE)) {
$locale = Session::get(SESSION_LOCALE);
if ($language = Language::whereLocale($locale)->first())
{
if ($language = Language::whereLocale($locale)->first()) {
$account->language_id = $language->id;
}
}
@ -35,7 +33,7 @@ class AccountRepository
$random = str_random(RANDOM_KEY_LENGTH);
$user = new User;
$user = new User();
$user->password = $random;
$user->password_confirmation = $random;
$user->username = $random;
@ -69,38 +67,33 @@ class AccountRepository
$data = [];
foreach ($clients->union($contacts)->union($invoices)->get() as $row)
{
foreach ($clients->union($contacts)->union($invoices)->get() as $row) {
$type = $row->type;
if (!isset($data[$type]))
{
if (!isset($data[$type])) {
$data[$type] = [];
}
$tokens = explode(' ', $row->name);
$tokens[] = $type;
if ($type == 'Invoices')
{
if ($type == 'Invoices') {
$tokens[] = intVal($row->token).'';
}
$data[$type][] = [
'value' => $row->name,
'public_id' => $row->public_id,
'tokens' => $tokens
'tokens' => $tokens,
];
}
return $data;
}
public function enableProPlan()
{
if (Auth::user()->isPro())
{
if (Auth::user()->isPro()) {
return false;
}
@ -153,12 +146,9 @@ class AccountRepository
{
$account = Account::whereAccountKey(NINJA_ACCOUNT_KEY)->first();
if ($account)
{
if ($account) {
return $account;
}
else
{
} else {
$account = new Account();
$account->name = 'Invoice Ninja';
$account->work_email = 'contact@invoiceninja.com';
@ -195,25 +185,22 @@ class AccountRepository
{
$client = Client::whereAccountId($ninjaAccount->id)->wherePublicId(Auth::user()->account_id)->first();
if (!$client)
{
$client = new 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)
{
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;
$contact = new Contact();
$contact->user_id = $ninjaAccount->users()->first()->id;
$contact->account_id = $ninjaAccount->id;
$contact->public_id = Auth::user()->account_id;
$contact->is_primary = true;
foreach (['first_name', 'last_name', 'email', 'phone'] as $field)
{
foreach (['first_name', 'last_name', 'email', 'phone'] as $field) {
$contact->$field = Auth::user()->$field;
}
$client->contacts()->save($contact);
@ -229,10 +216,12 @@ class AccountRepository
$fields = [
'first_name' => urlencode($user->first_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) {
$data .= $key.'='.$value.'&';
}
rtrim($data, '&');
$ch = curl_init();
@ -242,5 +231,4 @@ class AccountRepository
curl_exec($ch);
curl_close($ch);
}
}

View File

@ -14,15 +14,12 @@ class ClientRepository
->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');
if (!\Session::get('show_trash:client'))
{
if (!\Session::get('show_trash:client')) {
$query->where('clients.deleted_at', '=', null);
}
if ($filter)
{
$query->where(function($query) use ($filter)
{
if ($filter) {
$query->where(function ($query) use ($filter) {
$query->where('clients.name', 'like', '%'.$filter.'%')
->orWhere('contacts.first_name', 'like', '%'.$filter.'%')
->orWhere('contacts.last_name', 'like', '%'.$filter.'%')
@ -46,16 +43,13 @@ class ClientRepository
public function save($publicId, $data, $notify = true)
{
if (!$publicId || $publicId == "-1")
{
if (!$publicId || $publicId == "-1") {
$client = Client::createNew();
$client->currency_id = 1;
$contact = Contact::createNew();
$contact->is_primary = true;
$contact->send_invoice = true;
}
else
{
} else {
$client = Client::scope($publicId)->with('contacts')->firstOrFail();
$contact = $client->contacts()->where('is_primary', '=', true)->firstOrFail();
}
@ -120,8 +114,7 @@ class ClientRepository
$isPrimary = true;
$contactIds = [];
if (isset($data['contact']))
{
if (isset($data['contact'])) {
$info = $data['contact'];
if (isset($info['email'])) {
$contact->email = trim(strtolower($info['email']));
@ -138,19 +131,13 @@ class ClientRepository
$contact->is_primary = true;
$contact->send_invoice = true;
$client->contacts()->save($contact);
}
else
{
foreach ($data['contacts'] as $record)
{
} else {
foreach ($data['contacts'] as $record) {
$record = (array) $record;
if ($publicId != "-1" && isset($record['public_id']) && $record['public_id'])
{
if ($publicId != "-1" && isset($record['public_id']) && $record['public_id']) {
$contact = Contact::scope($record['public_id'])->firstOrFail();
}
else
{
} else {
$contact = Contact::createNew();
}
@ -174,10 +161,8 @@ class ClientRepository
$contactIds[] = $contact->public_id;
}
foreach ($client->contacts as $contact)
{
if (!in_array($contact->public_id, $contactIds))
{
foreach ($client->contacts as $contact) {
if (!in_array($contact->public_id, $contactIds)) {
$contact->delete();
}
}
@ -185,8 +170,7 @@ class ClientRepository
$client->save();
if (!$publicId || $publicId == "-1")
{
if (!$publicId || $publicId == "-1") {
\Activity::createClient($client, $notify);
}
@ -197,19 +181,14 @@ class ClientRepository
{
$clients = Client::withTrashed()->scope($ids)->get();
foreach ($clients as $client)
{
if ($action == 'restore')
{
foreach ($clients as $client) {
if ($action == 'restore') {
$client->restore();
$client->is_deleted = false;
$client->save();
}
else
{
if ($action == 'delete')
{
} else {
if ($action == 'delete') {
$client->is_deleted = true;
$client->save();
}

View File

@ -2,7 +2,6 @@
use Credit;
use Client;
use Invoice;
use Utils;
class CreditRepository
@ -17,20 +16,16 @@ class CreditRepository
->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');
if ($clientPublicId)
{
if ($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);
}
if ($filter)
{
$query->where(function($query) use ($filter)
{
if ($filter) {
$query->where(function ($query) use ($filter) {
$query->where('clients.name', 'like', '%'.$filter.'%');
});
}
@ -40,12 +35,9 @@ class CreditRepository
public function save($publicId = null, $input)
{
if ($publicId)
{
if ($publicId) {
$credit = Credit::scope($publicId)->firstOrFail();
}
else
{
} else {
$credit = Credit::createNew();
}
@ -61,23 +53,17 @@ class CreditRepository
public function bulk($ids, $action)
{
if (!$ids)
{
if (!$ids) {
return 0;
}
$credits = Credit::withTrashed()->scope($ids)->get();
foreach ($credits as $credit)
{
if ($action == 'restore')
{
foreach ($credits as $credit) {
if ($action == 'restore') {
$credit->restore();
}
else
{
if ($action == 'delete')
{
} else {
if ($action == 'delete') {
$credit->is_deleted = true;
$credit->save();
}

View File

@ -20,20 +20,16 @@ class PaymentRepository
->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');
if (!\Session::get('show_trash:payment'))
{
if (!\Session::get('show_trash:payment')) {
$query->where('payments.deleted_at', '=', null);
}
if ($clientPublicId)
{
if ($clientPublicId) {
$query->where('clients.public_id', '=', $clientPublicId);
}
if ($filter)
{
$query->where(function($query) use ($filter)
{
if ($filter) {
$query->where(function ($query) use ($filter) {
$query->where('clients.name', 'like', '%'.$filter.'%');
});
}
@ -47,8 +43,7 @@ class PaymentRepository
->join('clients', 'clients.id', '=', 'payments.client_id')
->join('invoices', 'invoices.id', '=', 'payments.invoice_id')
->join('contacts', 'contacts.client_id', '=', 'clients.id')
->leftJoin('invitations', function($join)
{
->leftJoin('invitations', function ($join) {
$join->on('invitations.invoice_id', '=', 'invoices.id')
->on('invitations.contact_id', '=', 'contacts.id');
})
@ -59,10 +54,8 @@ class PaymentRepository
->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');
if ($filter)
{
$query->where(function($query) use ($filter)
{
if ($filter) {
$query->where(function ($query) use ($filter) {
$query->where('clients.name', 'like', '%'.$filter.'%');
});
}
@ -75,18 +68,16 @@ class PaymentRepository
$rules = array(
'client' => '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'];
}
$validator = \Validator::make($input, $rules);
if ($validator->fails())
{
if ($validator->fails()) {
return $validator;
}
@ -95,12 +86,9 @@ class PaymentRepository
public function save($publicId = null, $input)
{
if ($publicId)
{
if ($publicId) {
$payment = Payment::scope($publicId)->firstOrFail();
}
else
{
} else {
$payment = Payment::createNew();
}
@ -108,18 +96,15 @@ class PaymentRepository
$clientId = Client::getPrivateId($input['client']);
$amount = Utils::parseFloat($input['amount']);
if ($paymentTypeId == PAYMENT_TYPE_CREDIT)
{
if ($paymentTypeId == PAYMENT_TYPE_CREDIT) {
$credits = Credit::scope()->where('client_id', '=', $clientId)
->where('balance', '>', 0)->orderBy('created_at')->get();
$applied = 0;
foreach ($credits as $credit)
{
foreach ($credits as $credit) {
$applied += $credit->apply($amount);
if ($applied >= $amount)
{
if ($applied >= $amount) {
break;
}
}
@ -138,23 +123,17 @@ class PaymentRepository
public function bulk($ids, $action)
{
if (!$ids)
{
if (!$ids) {
return 0;
}
$payments = Payment::withTrashed()->scope($ids)->get();
foreach ($payments as $payment)
{
if ($action == 'restore')
{
foreach ($payments as $payment) {
if ($action == 'restore') {
$payment->restore();
}
else
{
if ($action == 'delete')
{
} else {
if ($action == 'delete') {
$payment->is_deleted = true;
$payment->save();
}

View File

@ -9,24 +9,18 @@ class TaxRateRepository
{
$taxRateIds = [];
foreach ($taxRates as $record)
{
if (!isset($record->rate) || (isset($record->is_deleted) && $record->is_deleted))
{
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))
{
if (!isset($record->name) || !Utils::parseFloat($record->rate) || !trim($record->name)) {
continue;
}
if ($record->public_id)
{
if ($record->public_id) {
$taxRate = TaxRate::scope($record->public_id)->firstOrFail();
}
else
{
} else {
$taxRate = TaxRate::createNew();
}
@ -39,10 +33,8 @@ class TaxRateRepository
$taxRates = TaxRate::scope()->get();
foreach($taxRates as $taxRate)
{
if (!in_array($taxRate->public_id, $taxRateIds))
{
foreach ($taxRates as $taxRate) {
if (!in_array($taxRate->public_id, $taxRateIds)) {
$taxRate->delete();
}
}