diff --git a/.env.example b/.env.example
index 18053683d7ba..1ed1ec049cbb 100644
--- a/.env.example
+++ b/.env.example
@@ -54,6 +54,12 @@ FCM_API_TOKEN=
GOOGLE_MAPS_ENABLED=true
#GOOGLE_MAPS_API_KEY=
+# Create a cookie to stay logged in
+#REMEMBER_ME_ENABLED=true
+
+# The app automatically logs the user out after this number of seconds
+#AUTO_LOGOUT_SECONDS=28800
+
#S3_KEY=
#S3_SECRET=
#S3_REGION=
@@ -88,5 +94,6 @@ WEPAY_APP_FEE_MULTIPLIER=0.002
WEPAY_APP_FEE_FIXED=0
WEPAY_THEME='{"name":"Invoice Ninja","primary_color":"0b4d78","secondary_color":"0b4d78","background_color":"f8f8f8","button_color":"33b753"}' # See https://www.wepay.com/developer/reference/structures#theme
+
BLUEVINE_PARTNER_UNIQUE_ID=
BLUEVINE_PARTNER_TOKEN=
diff --git a/.php_cs.dist b/.php_cs.dist
new file mode 100644
index 000000000000..568722c566f7
--- /dev/null
+++ b/.php_cs.dist
@@ -0,0 +1,98 @@
+notPath('bootstrap/cache')
+ ->notPath('storage')
+ ->notPath('vendor')
+ ->in(__DIR__)
+ ->name('*.php')
+ ->notName('*.blade.php')
+ ->ignoreDotFiles(true)
+ ->ignoreVCS(true);
+
+return PhpCsFixer\Config::create()
+ ->setRules([
+ '@PSR2' => true,
+ 'binary_operator_spaces' => true,
+ 'blank_line_after_namespace' => true,
+ 'blank_line_after_opening_tag' => true,
+ 'blank_line_before_return' => true,
+ 'braces' => true,
+ 'cast_spaces' => true,
+ 'class_definition' => true,
+ 'elseif' => true,
+ 'encoding' => true,
+ 'full_opening_tag' => true,
+ 'function_declaration' => true,
+ 'function_typehint_space' => true,
+ 'hash_to_slash_comment' => true,
+ 'heredoc_to_nowdoc' => true,
+ 'include' => true,
+ 'linebreak_after_opening_tag' => true,
+ 'lowercase_cast' => true,
+ 'lowercase_constants' => true,
+ 'lowercase_keywords' => true,
+ 'method_argument_space' => true,
+ 'method_separation' => true,
+ 'native_function_casing' => true,
+ 'new_with_braces' => true,
+ 'no_alias_functions' => true,
+ 'no_blank_lines_after_class_opening' => true,
+ 'no_blank_lines_after_phpdoc' => true,
+ 'no_closing_tag' => true,
+ 'no_empty_phpdoc' => true,
+ 'no_extra_consecutive_blank_lines' => true,
+ 'no_leading_import_slash' => true,
+ 'no_leading_namespace_whitespace' => true,
+ 'no_multiline_whitespace_around_double_arrow' => true,
+ 'no_multiline_whitespace_before_semicolons' => true,
+ 'no_short_bool_cast' => true,
+ 'no_singleline_whitespace_before_semicolons' => true,
+ 'no_spaces_after_function_name' => true,
+ 'no_spaces_inside_parenthesis' => true,
+ 'no_trailing_comma_in_list_call' => true,
+ 'no_trailing_comma_in_singleline_array' => true,
+ 'no_trailing_whitespace' => true,
+ 'no_trailing_whitespace_in_comment' => true,
+ 'no_unneeded_control_parentheses' => true,
+ 'no_unreachable_default_argument_value' => true,
+ 'no_unused_imports' => true,
+ 'no_useless_return' => true,
+ 'no_whitespace_before_comma_in_array' => true,
+ 'not_operator_with_successor_space' => true,
+ 'object_operator_without_whitespace' => true,
+ 'ordered_imports' => true,
+ 'phpdoc_add_missing_param_annotation' => true,
+ 'phpdoc_align' => true,
+ 'phpdoc_indent' => true,
+ 'phpdoc_inline_tag' => true,
+ 'phpdoc_no_access' => true,
+ 'phpdoc_no_package' => true,
+ 'phpdoc_order' => true,
+ 'phpdoc_scalar' => true,
+ 'phpdoc_separation' => true,
+ 'phpdoc_summary' => true,
+ 'phpdoc_to_comment' => true,
+ 'phpdoc_trim' => true,
+ 'phpdoc_types' => true,
+ 'phpdoc_var_without_name' => true,
+ 'self_accessor' => true,
+ 'short_scalar_cast' => true,
+ 'single_blank_line_at_eof' => true,
+ 'single_blank_line_before_namespace' => true,
+ 'single_import_per_statement' => true,
+ 'single_line_after_imports' => true,
+ 'single_quote' => true,
+ 'space_after_semicolon' => true,
+ 'standardize_not_equals' => true,
+ 'switch_case_semicolon_to_colon' => true,
+ 'switch_case_space' => true,
+ 'ternary_operator_spaces' => true,
+ 'trailing_comma_in_multiline_array' => true,
+ 'trim_array_spaces' => true,
+ 'unary_operator_spaces' => true,
+ 'visibility_required' => true,
+ 'whitespace_after_comma_in_array' => true,
+ 'array_syntax' => array('syntax' => 'short'),
+ ])
+ ->setFinder($finder);
diff --git a/.travis.yml b/.travis.yml
index 5eaa04417349..92bf4064b384 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -49,6 +49,7 @@ before_script:
- php artisan key:generate --no-interaction
- sed -i 's/APP_ENV=production/APP_ENV=development/g' .env
- sed -i 's/APP_DEBUG=false/APP_DEBUG=true/g' .env
+ - sed -i 's/MAIL_DRIVER=smtp/MAIL_DRIVER=log/g' .env
- sed -i '$a NINJA_DEV=true' .env
- sed -i '$a TRAVIS=true' .env
# create the database and user
diff --git a/LICENSE b/LICENSE
index a3f780707e33..3170777e2dcf 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2016 by Hillel Coren
+Copyright (c) 2017 by Hillel Coren
Invoice Ninja * https://www.invoiceninja.com
"CREATE. SEND. GET PAID"
diff --git a/README.md b/README.md
index 558472ba6bf6..53188aa1fc6b 100644
--- a/README.md
+++ b/README.md
@@ -61,9 +61,9 @@ The [self-host zip](https://www.invoiceninja.com/self-host/) includes all third
* [Feature Roadmap](https://trello.com/b/63BbiVVe/)
## Development
-* [Custom Module](http://docs.invoiceninja.com/en/latest/custom_modules.html) | [Watch Video](https://www.youtube.com/watch?v=8jJ-PYuq85k)
-* [PHP SDK](https://github.com/invoiceninja/sdk-php)
* [API Documentation](https://www.invoiceninja.com/api-documentation/)
+* [PHP SDK](https://github.com/invoiceninja/sdk-php)
+* [Custom Module](http://docs.invoiceninja.com/en/latest/custom_modules.html) | [Watch Video](https://www.youtube.com/watch?v=8jJ-PYuq85k)
## Contributing
All contributors are welcome!
diff --git a/app/Commands/Command.php b/app/Commands/Command.php
index d6a8d61150ae..3b33ca89d1b8 100644
--- a/app/Commands/Command.php
+++ b/app/Commands/Command.php
@@ -1,6 +1,7 @@
-client->public_id);
- if ( ! $account) {
+ if (! $account) {
continue;
}
$company = $account->company;
- if ( ! $company->plan || $company->plan == PLAN_FREE) {
+ if (! $company->plan || $company->plan == PLAN_FREE) {
continue;
}
$this->info("Charging invoice {$invoice->invoice_number}");
- if ( ! $this->paymentService->autoBillInvoice($invoice)) {
+ if (! $this->paymentService->autoBillInvoice($invoice)) {
$this->info('Failed to auto-bill, emailing invoice');
$this->mailer->sendInvoice($invoice);
}
diff --git a/app/Console/Commands/CheckData.php b/app/Console/Commands/CheckData.php
index c5f2d8e2aed3..dca1327f40ac 100644
--- a/app/Console/Commands/CheckData.php
+++ b/app/Console/Commands/CheckData.php
@@ -1,11 +1,13 @@
-logMessage(date('Y-m-d') . ' Running CheckData...');
- if (!$this->option('client_id')) {
+ if (! $this->option('client_id')) {
$this->checkPaidToDate();
$this->checkBlankInvoiceHistory();
}
$this->checkBalances();
- if (!$this->option('client_id')) {
+ if (! $this->option('client_id')) {
+ $this->checkFailedJobs();
$this->checkAccountData();
}
@@ -79,7 +81,7 @@ class CheckData extends Command {
Mail::raw($this->log, function ($message) use ($errorEmail) {
$message->to($errorEmail)
->from(CONTACT_EMAIL)
- ->subject('Check-Data');
+ ->subject('Check-Data: ' . strtoupper($this->isValid ? RESULT_SUCCESS : RESULT_FAILURE));
});
}
}
@@ -89,6 +91,17 @@ class CheckData extends Command {
$this->log .= $str . "\n";
}
+ private function checkFailedJobs()
+ {
+ $count = DB::table('failed_jobs')->count();
+
+ if ($count > 0) {
+ $this->isValid = false;
+ }
+
+ $this->logMessage($count . ' failed jobs');
+ }
+
private function checkBlankInvoiceHistory()
{
$count = DB::table('activities')
@@ -113,33 +126,33 @@ class CheckData extends Command {
ENTITY_CONTACT,
ENTITY_PAYMENT,
ENTITY_INVITATION,
- ENTITY_USER
+ ENTITY_USER,
],
'invoices' => [
ENTITY_CLIENT,
- ENTITY_USER
+ ENTITY_USER,
],
'payments' => [
ENTITY_INVOICE,
ENTITY_CLIENT,
ENTITY_USER,
ENTITY_INVITATION,
- ENTITY_CONTACT
+ ENTITY_CONTACT,
],
'tasks' => [
ENTITY_INVOICE,
ENTITY_CLIENT,
- ENTITY_USER
+ ENTITY_USER,
],
'credits' => [
ENTITY_CLIENT,
- ENTITY_USER
+ ENTITY_USER,
],
'expenses' => [
ENTITY_CLIENT,
ENTITY_VENDOR,
ENTITY_INVOICE,
- ENTITY_USER
+ ENTITY_USER,
],
'products' => [
ENTITY_USER,
@@ -150,7 +163,7 @@ class CheckData extends Command {
'projects' => [
ENTITY_USER,
ENTITY_CLIENT,
- ]
+ ],
];
foreach ($tables as $table => $entityTypes) {
@@ -249,7 +262,6 @@ class CheckData extends Command {
//$this->logMessage(var_dump($activities));
foreach ($activities as $activity) {
-
$activityFix = false;
if ($activity->invoice_id) {
@@ -258,7 +270,7 @@ class CheckData extends Command {
->first(['invoices.amount', 'invoices.is_recurring', 'invoices.invoice_type_id', 'invoices.deleted_at', 'invoices.id', 'invoices.is_deleted']);
// Check if this invoice was once set as recurring invoice
- if ($invoice && !$invoice->is_recurring && DB::table('invoices')
+ if ($invoice && ! $invoice->is_recurring && DB::table('invoices')
->where('recurring_invoice_id', '=', $activity->invoice_id)
->first(['invoices.id'])) {
$invoice->is_recurring = 1;
@@ -272,7 +284,6 @@ class CheckData extends Command {
}
}
-
if ($activity->activity_type_id == ACTIVITY_TYPE_CREATE_INVOICE
|| $activity->activity_type_id == ACTIVITY_TYPE_CREATE_QUOTE) {
@@ -293,12 +304,12 @@ class CheckData extends Command {
// **Fix for ninja invoices which didn't have the invoice_type_id value set
if ($noAdjustment && $client->account_id == 20432) {
- $this->logMessage("No adjustment for ninja invoice");
+ $this->logMessage('No adjustment for ninja invoice');
$foundProblem = true;
$clientFix += $invoice->amount;
$activityFix = $invoice->amount;
// **Fix for allowing converting a recurring invoice to a normal one without updating the balance**
- } elseif ($noAdjustment && $invoice->invoice_type_id == INVOICE_TYPE_STANDARD && !$invoice->is_recurring) {
+ } elseif ($noAdjustment && $invoice->invoice_type_id == INVOICE_TYPE_STANDARD && ! $invoice->is_recurring) {
$this->logMessage("No adjustment for new invoice:{$activity->invoice_id} amount:{$invoice->amount} invoiceTypeId:{$invoice->invoice_type_id} isRecurring:{$invoice->is_recurring}");
$foundProblem = true;
$clientFix += $invoice->amount;
@@ -322,7 +333,7 @@ class CheckData extends Command {
}
} elseif ($activity->activity_type_id == ACTIVITY_TYPE_ARCHIVE_INVOICE) {
// **Fix for updating balance when archiving an invoice**
- if ($activity->adjustment != 0 && !$invoice->is_recurring) {
+ if ($activity->adjustment != 0 && ! $invoice->is_recurring) {
$this->logMessage("Incorrect adjustment for archiving invoice adjustment:{$activity->adjustment}");
$foundProblem = true;
$activityFix = 0;
@@ -335,7 +346,7 @@ class CheckData extends Command {
$foundProblem = true;
$clientFix -= $activity->adjustment;
$activityFix = 0;
- } else if ((strtotime($activity->created_at) - strtotime($lastCreatedAt) <= 1) && $activity->adjustment > 0 && $activity->adjustment == $lastAdjustment) {
+ } elseif ((strtotime($activity->created_at) - strtotime($lastCreatedAt) <= 1) && $activity->adjustment > 0 && $activity->adjustment == $lastAdjustment) {
$this->logMessage("Duplicate adjustment for updated invoice adjustment:{$activity->adjustment}");
$foundProblem = true;
$clientFix -= $activity->adjustment;
@@ -349,7 +360,7 @@ class CheckData extends Command {
$clientFix += $lastBalance - $activity->balance;
$activityFix = 0;
}
- } else if ($activity->activity_type_id == ACTIVITY_TYPE_DELETE_PAYMENT) {
+ } elseif ($activity->activity_type_id == ACTIVITY_TYPE_DELETE_PAYMENT) {
// **Fix for deleting payment after deleting invoice**
if ($activity->adjustment != 0 && $invoice->is_deleted && $activity->created_at > $invoice->deleted_at) {
$this->logMessage("Incorrect adjustment for deleted payment adjustment:{$activity->adjustment}");
@@ -361,7 +372,7 @@ class CheckData extends Command {
if ($activityFix !== false || $clientFix !== false) {
$data = [
- 'balance' => $activity->balance + $clientFix
+ 'balance' => $activity->balance + $clientFix,
];
if ($activityFix !== false) {
@@ -384,8 +395,8 @@ class CheckData extends Command {
$this->logMessage("** Creating 'recovered update' activity **");
if ($this->option('fix') == 'true') {
DB::table('activities')->insert([
- 'created_at' => new Carbon,
- 'updated_at' => new Carbon,
+ 'created_at' => new Carbon(),
+ 'updated_at' => new Carbon(),
'account_id' => $client->account_id,
'client_id' => $client->id,
'adjustment' => $client->actual_balance - $activity->balance,
@@ -422,5 +433,4 @@ class CheckData extends Command {
['client_id', null, InputOption::VALUE_OPTIONAL, 'Client id', null],
];
}
-
}
diff --git a/app/Console/Commands/CreateTestData.php b/app/Console/Commands/CreateTestData.php
index 244f0b93fbd7..7e339643e182 100644
--- a/app/Console/Commands/CreateTestData.php
+++ b/app/Console/Commands/CreateTestData.php
@@ -1,17 +1,19 @@
-count; $i++) {
+ for ($i = 0; $i < $this->count; $i++) {
$data = [
'name' => $this->faker->name,
'address1' => $this->faker->streetAddress,
@@ -91,7 +94,7 @@ class CreateTestData extends Command
'last_name' => $this->faker->lastName,
'email' => $this->faker->safeEmail,
'phone' => $this->faker->phoneNumber,
- ]]
+ ]],
];
$client = $this->clientRepo->save($data);
@@ -106,7 +109,7 @@ class CreateTestData extends Command
*/
private function createInvoices($client)
{
- for ($i=0; $i<$this->count; $i++) {
+ for ($i = 0; $i < $this->count; $i++) {
$data = [
'client_id' => $client->id,
'invoice_date_sql' => date_create()->modify(rand(-100, 100) . ' days')->format('Y-m-d'),
@@ -115,8 +118,8 @@ class CreateTestData extends Command
'product_key' => $this->faker->word,
'qty' => $this->faker->randomDigit + 1,
'cost' => $this->faker->randomFloat(2, 1, 10),
- 'notes' => $this->faker->text($this->faker->numberBetween(50, 300))
- ]]
+ 'notes' => $this->faker->text($this->faker->numberBetween(50, 300)),
+ ]],
];
$invoice = $this->invoiceRepo->save($data);
@@ -146,7 +149,7 @@ class CreateTestData extends Command
private function createVendors()
{
- for ($i=0; $i<$this->count; $i++) {
+ for ($i = 0; $i < $this->count; $i++) {
$data = [
'name' => $this->faker->name,
'address1' => $this->faker->streetAddress,
@@ -159,7 +162,7 @@ class CreateTestData extends Command
'last_name' => $this->faker->lastName,
'email' => $this->faker->safeEmail,
'phone' => $this->faker->phoneNumber,
- ]]
+ ]],
];
$vendor = $this->vendorRepo->save($data);
@@ -174,7 +177,7 @@ class CreateTestData extends Command
*/
private function createExpense($vendor)
{
- for ($i=0; $i<$this->count; $i++) {
+ for ($i = 0; $i < $this->count; $i++) {
$data = [
'vendor_id' => $vendor->id,
'amount' => $this->faker->randomFloat(2, 1, 10),
diff --git a/app/Console/Commands/GenerateResources.php b/app/Console/Commands/GenerateResources.php
index 9826f3c70b07..17e139188caf 100644
--- a/app/Console/Commands/GenerateResources.php
+++ b/app/Console/Commands/GenerateResources.php
@@ -1,10 +1,12 @@
-comment(PHP_EOL.Inspiring::quote().PHP_EOL);
- }
+ /**
+ * The console command description.
+ *
+ * @var string
+ */
+ protected $description = 'Display an inspiring quote';
+ /**
+ * Execute the console command.
+ *
+ * @return mixed
+ */
+ public function handle()
+ {
+ $this->comment(PHP_EOL.Inspiring::quote().PHP_EOL);
+ }
}
diff --git a/app/Console/Commands/MakeClass.php b/app/Console/Commands/MakeClass.php
index 83b99fa62b30..8f1a5c7699a6 100644
--- a/app/Console/Commands/MakeClass.php
+++ b/app/Console/Commands/MakeClass.php
@@ -2,14 +2,14 @@
namespace App\Console\Commands;
-use Illuminate\Support\Str;
use Illuminate\Console\Command;
-use Symfony\Component\Console\Input\InputArgument;
-use Symfony\Component\Console\Input\InputOption;
-
+use Illuminate\Support\Str;
use Nwidart\Modules\Commands\GeneratorCommand;
use Nwidart\Modules\Support\Stub;
+
use Nwidart\Modules\Traits\ModuleCommandTrait;
+use Symfony\Component\Console\Input\InputArgument;
+use Symfony\Component\Console\Input\InputOption;
class MakeClass extends GeneratorCommand
{
@@ -48,20 +48,19 @@ class MakeClass extends GeneratorCommand
*/
protected function getOptions()
{
- return array(
- array('fields', null, InputOption::VALUE_OPTIONAL, 'The model attributes.', null),
- array('filename', null, InputOption::VALUE_OPTIONAL, 'The class filename.', null),
- );
+ return [
+ ['fields', null, InputOption::VALUE_OPTIONAL, 'The model attributes.', null],
+ ['filename', null, InputOption::VALUE_OPTIONAL, 'The class filename.', null],
+ ];
}
-
public function getTemplateContents()
{
$module = $this->laravel['modules']->findOrFail($this->getModuleName());
$path = str_replace('/', '\\', config('modules.paths.generator.' . $this->argument('class')));
return (new Stub('/' . $this->argument('prefix') . $this->argument('class') . '.stub', [
- 'NAMESPACE' => $this->getClassNamespace($module) . "\\" . $path,
+ 'NAMESPACE' => $this->getClassNamespace($module) . '\\' . $path,
'LOWER_NAME' => $module->getLowerName(),
'CLASS' => $this->getClass(),
'STUDLY_NAME' => Str::studly($module->getLowerName()),
@@ -88,6 +87,7 @@ class MakeClass extends GeneratorCommand
if ($this->option('filename')) {
return $this->option('filename');
}
+
return studly_case($this->argument('prefix')) . studly_case($this->argument('name')) . Str::studly($this->argument('class'));
}
@@ -98,7 +98,7 @@ class MakeClass extends GeneratorCommand
$str = '';
foreach ($fields as $field) {
- if ( ! $field) {
+ if (! $field) {
continue;
}
$field = explode(':', $field)[0];
@@ -120,7 +120,7 @@ class MakeClass extends GeneratorCommand
$str = '';
foreach ($fields as $field) {
- if ( ! $field) {
+ if (! $field) {
continue;
}
$parts = explode(':', $field);
@@ -144,7 +144,7 @@ class MakeClass extends GeneratorCommand
$str = '';
foreach ($fields as $field) {
- if ( ! $field) {
+ if (! $field) {
continue;
}
$field = explode(':', $field)[0];
@@ -161,7 +161,7 @@ class MakeClass extends GeneratorCommand
$str = '';
foreach ($fields as $field) {
- if ( ! $field) {
+ if (! $field) {
continue;
}
$field = explode(':', $field)[0];
@@ -169,6 +169,5 @@ class MakeClass extends GeneratorCommand
}
return rtrim($str);
-
}
}
diff --git a/app/Console/Commands/MakeModule.php b/app/Console/Commands/MakeModule.php
index b96cb9ea7674..88291b78c50f 100644
--- a/app/Console/Commands/MakeModule.php
+++ b/app/Console/Commands/MakeModule.php
@@ -45,10 +45,10 @@ class MakeModule extends Command
// convert 'name:string,description:text' to 'name,description'
$fillable = explode(',', $fields);
- $fillable = array_map(function($item) {
+ $fillable = array_map(function ($item) {
return explode(':', $item)[0];
}, $fillable);
- $fillable = join(',', $fillable);
+ $fillable = implode(',', $fillable);
$this->info("Creating module: {$name}...");
@@ -77,22 +77,21 @@ class MakeModule extends Command
Artisan::call('module:dump');
- $this->info("Done");
+ $this->info('Done');
}
protected function getArguments()
{
return [
['name', InputArgument::REQUIRED, 'The name of the module.'],
- ['fields', InputArgument::OPTIONAL, 'The fields of the module.']
+ ['fields', InputArgument::OPTIONAL, 'The fields of the module.'],
];
}
protected function getOptions()
{
- return array(
- array('migrate', null, InputOption::VALUE_OPTIONAL, 'The model attributes.', null),
- );
+ return [
+ ['migrate', null, InputOption::VALUE_OPTIONAL, 'The model attributes.', null],
+ ];
}
-
}
diff --git a/app/Console/Commands/PruneData.php b/app/Console/Commands/PruneData.php
index 1c04e1ab5fcf..33d2bd64c0a9 100644
--- a/app/Console/Commands/PruneData.php
+++ b/app/Console/Commands/PruneData.php
@@ -1,10 +1,12 @@
-info("Deleting {$result->id}");
+ $this->info("Deleting {$result->id}");
DB::table('accounts')
->where('id', '=', $result->id)
->delete();
diff --git a/app/Console/Commands/RemoveOrphanedDocuments.php b/app/Console/Commands/RemoveOrphanedDocuments.php
index edcb864564bc..489d8d94421f 100644
--- a/app/Console/Commands/RemoveOrphanedDocuments.php
+++ b/app/Console/Commands/RemoveOrphanedDocuments.php
@@ -1,11 +1,13 @@
-info(date('Y-m-d') . ' Running ResetData...');
- if (!Utils::isNinjaDev()) {
+ if (! Utils::isNinjaDev()) {
return;
}
@@ -32,4 +32,4 @@ class ResetData extends Command
Artisan::call('migrate');
Artisan::call('db:seed');
}
-}
\ No newline at end of file
+}
diff --git a/app/Console/Commands/ResetInvoiceSchemaCounter.php b/app/Console/Commands/ResetInvoiceSchemaCounter.php
index ed849a25a26f..be221c4d6390 100644
--- a/app/Console/Commands/ResetInvoiceSchemaCounter.php
+++ b/app/Console/Commands/ResetInvoiceSchemaCounter.php
@@ -62,9 +62,9 @@ class ResetInvoiceSchemaCounter extends Command
$latestInvoice = $this->invoice->latest()->first();
$invoiceYear = Carbon::parse($latestInvoice->created_at)->year;
- if(Carbon::now()->year > $invoiceYear || $force) {
+ if (Carbon::now()->year > $invoiceYear || $force) {
$accounts->transform(function ($a) {
- /** @var Account $a */
+ /* @var Account $a */
$a->invoice_number_counter = 1;
$a->update();
});
diff --git a/app/Console/Commands/SendRecurringInvoices.php b/app/Console/Commands/SendRecurringInvoices.php
index 3a546f187edf..88b317df5a69 100644
--- a/app/Console/Commands/SendRecurringInvoices.php
+++ b/app/Console/Commands/SendRecurringInvoices.php
@@ -1,14 +1,16 @@
-shouldSendToday();
$this->info('Processing Invoice '.$recurInvoice->id.' - Should send '.($shouldSendToday ? 'YES' : 'NO'));
- if ( ! $shouldSendToday) {
+ if (! $shouldSendToday) {
continue;
}
$recurInvoice->account->loadLocalizationSettings($recurInvoice->client);
$invoice = $this->invoiceRepo->createRecurringInvoice($recurInvoice);
- if ($invoice && !$invoice->isPaid()) {
+ if ($invoice && ! $invoice->isPaid()) {
$this->info('Sending Invoice');
$this->mailer->sendInvoice($invoice);
}
diff --git a/app/Console/Commands/SendReminders.php b/app/Console/Commands/SendReminders.php
index bdb239deff70..af5f9bfca2c2 100644
--- a/app/Console/Commands/SendReminders.php
+++ b/app/Console/Commands/SendReminders.php
@@ -1,13 +1,15 @@
-hasFeature(FEATURE_EMAIL_TEMPLATES_REMINDERS)) {
+ if (! $account->hasFeature(FEATURE_EMAIL_TEMPLATES_REMINDERS)) {
continue;
}
@@ -77,6 +80,14 @@ class SendReminders extends Command
}
$this->info('Done');
+
+ if ($errorEmail = env('ERROR_EMAIL')) {
+ \Mail::raw('EOM', function ($message) use ($errorEmail) {
+ $message->to($errorEmail)
+ ->from(CONTACT_EMAIL)
+ ->subject('SendReminders: Finished successfully');
+ });
+ }
}
/**
diff --git a/app/Console/Commands/SendRenewalInvoices.php b/app/Console/Commands/SendRenewalInvoices.php
index 2751e151c099..edfc2471b31d 100644
--- a/app/Console/Commands/SendRenewalInvoices.php
+++ b/app/Console/Commands/SendRenewalInvoices.php
@@ -1,13 +1,15 @@
-info(count($companies).' companies found renewing in 10 days');
foreach ($companies as $company) {
- if (!count($company->accounts)) {
+ if (! count($company->accounts)) {
continue;
}
@@ -74,7 +76,7 @@ class SendRenewalInvoices extends Command
$plan['price'] = min($company->pending_plan_price, Utils::getPlanPrice($plan));
}
- if ($plan['plan'] == PLAN_FREE || !$plan['plan'] || !$plan['term'] || !$plan['price']){
+ if ($plan['plan'] == PLAN_FREE || ! $plan['plan'] || ! $plan['term'] || ! $plan['price']) {
continue;
}
diff --git a/app/Console/Commands/TestOFX.php b/app/Console/Commands/TestOFX.php
index d21518cba7ef..08246c5f7c1b 100644
--- a/app/Console/Commands/TestOFX.php
+++ b/app/Console/Commands/TestOFX.php
@@ -1,10 +1,12 @@
-info(date('Y-m-d').' Running TestOFX...');
}
-}
\ No newline at end of file
+}
diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php
index deab7b163c53..14b26d80f515 100644
--- a/app/Console/Kernel.php
+++ b/app/Console/Kernel.php
@@ -1,8 +1,10 @@
- ['card' => 'images/credit_cards/Test-MasterCard-Icon.png', 'text' => 'Master Card'],
4 => ['card' => 'images/credit_cards/Test-AmericanExpress-Icon.png', 'text' => 'American Express'],
8 => ['card' => 'images/credit_cards/Test-Diners-Icon.png', 'text' => 'Diners'],
- 16 => ['card' => 'images/credit_cards/Test-Discover-Icon.png', 'text' => 'Discover']
+ 16 => ['card' => 'images/credit_cards/Test-Discover-Icon.png', 'text' => 'Discover'],
];
define('CREDIT_CARDS', serialize($creditCards));
@@ -540,7 +545,6 @@ if (!defined('APP_NAME'))
];
define('CACHED_TABLES', serialize($cachedTables));
-
// TODO remove these translation functions
function uctrans($text)
{
@@ -557,6 +561,7 @@ if (!defined('APP_NAME'))
} else {
$string = trans($text);
$english = trans($text, [], 'en');
+
return $string != $english ? $string : '';
}
}
@@ -564,12 +569,12 @@ if (!defined('APP_NAME'))
// include modules in translations
function mtrans($entityType, $text = false)
{
- if ( ! $text) {
+ if (! $text) {
$text = $entityType;
}
// check if this has been translated in a module language file
- if ( ! Utils::isNinjaProd() && $module = Module::find($entityType)) {
+ if (! Utils::isNinjaProd() && $module = Module::find($entityType)) {
$key = "{$module->getLowerName()}::texts.{$text}";
$value = trans($key);
if ($key != $value) {
diff --git a/app/Constants/Domain.php b/app/Constants/Domain.php
index afdcbf90c52e..d8a0ff9b043f 100644
--- a/app/Constants/Domain.php
+++ b/app/Constants/Domain.php
@@ -1,4 +1,6 @@
-credit = $credit;
}
-
}
diff --git a/app/Events/CreditWasCreated.php b/app/Events/CreditWasCreated.php
index 81ba63c450ca..81ca47d630ed 100644
--- a/app/Events/CreditWasCreated.php
+++ b/app/Events/CreditWasCreated.php
@@ -1,11 +1,12 @@
-credit = $credit;
}
-
}
diff --git a/app/Events/CreditWasDeleted.php b/app/Events/CreditWasDeleted.php
index c5f585fcf338..e1b9ee117b88 100644
--- a/app/Events/CreditWasDeleted.php
+++ b/app/Events/CreditWasDeleted.php
@@ -1,14 +1,16 @@
-credit = $credit;
}
-
}
diff --git a/app/Events/CreditWasRestored.php b/app/Events/CreditWasRestored.php
index a80c9e729b5f..87a82ff951b4 100644
--- a/app/Events/CreditWasRestored.php
+++ b/app/Events/CreditWasRestored.php
@@ -1,15 +1,16 @@
-credit = $credit;
}
-
}
diff --git a/app/Events/Event.php b/app/Events/Event.php
index 76e730a4b8e8..caf34813678d 100644
--- a/app/Events/Event.php
+++ b/app/Events/Event.php
@@ -1,4 +1,6 @@
-expense = $expense;
}
-
}
diff --git a/app/Events/ExpenseWasCreated.php b/app/Events/ExpenseWasCreated.php
index edaca9c00a82..f850c60050a5 100644
--- a/app/Events/ExpenseWasCreated.php
+++ b/app/Events/ExpenseWasCreated.php
@@ -1,10 +1,12 @@
-expense = $expense;
}
-
}
diff --git a/app/Events/ExpenseWasRestored.php b/app/Events/ExpenseWasRestored.php
index 142f41d7e9ec..2c0d17e84210 100644
--- a/app/Events/ExpenseWasRestored.php
+++ b/app/Events/ExpenseWasRestored.php
@@ -1,11 +1,12 @@
-expense = $expense;
}
-
}
diff --git a/app/Events/ExpenseWasUpdated.php b/app/Events/ExpenseWasUpdated.php
index 469a258ba1aa..79367890d10f 100644
--- a/app/Events/ExpenseWasUpdated.php
+++ b/app/Events/ExpenseWasUpdated.php
@@ -1,10 +1,12 @@
-invitation = $invitation;
$this->notes = $notes;
}
-
}
diff --git a/app/Events/InvoiceInvitationWasViewed.php b/app/Events/InvoiceInvitationWasViewed.php
index 0897895a7a82..446f3472300b 100644
--- a/app/Events/InvoiceInvitationWasViewed.php
+++ b/app/Events/InvoiceInvitationWasViewed.php
@@ -1,15 +1,17 @@
-invoice = $invoice;
}
-
}
diff --git a/app/Events/InvoiceWasCreated.php b/app/Events/InvoiceWasCreated.php
index b78d7f769f3f..2c8d65515aa7 100644
--- a/app/Events/InvoiceWasCreated.php
+++ b/app/Events/InvoiceWasCreated.php
@@ -1,10 +1,12 @@
-invoice = $invoice;
}
-
}
diff --git a/app/Events/InvoiceWasDeleted.php b/app/Events/InvoiceWasDeleted.php
index 792e693eb4eb..172c885ad59c 100644
--- a/app/Events/InvoiceWasDeleted.php
+++ b/app/Events/InvoiceWasDeleted.php
@@ -1,10 +1,12 @@
-invoice = $invoice;
$this->fromDeleted = $fromDeleted;
}
-
}
diff --git a/app/Events/InvoiceWasUpdated.php b/app/Events/InvoiceWasUpdated.php
index f929b3d5bef8..5bd8c65f2ff8 100644
--- a/app/Events/InvoiceWasUpdated.php
+++ b/app/Events/InvoiceWasUpdated.php
@@ -1,10 +1,12 @@
-payment = $payment;
}
-
}
diff --git a/app/Events/PaymentFailed.php b/app/Events/PaymentFailed.php
index 445b8ba5beaf..3c82659c30da 100644
--- a/app/Events/PaymentFailed.php
+++ b/app/Events/PaymentFailed.php
@@ -1,10 +1,12 @@
-payment = $payment;
}
-
}
diff --git a/app/Events/PaymentWasCreated.php b/app/Events/PaymentWasCreated.php
index 98e95ae43a70..c4480acb7c48 100644
--- a/app/Events/PaymentWasCreated.php
+++ b/app/Events/PaymentWasCreated.php
@@ -1,14 +1,16 @@
-invitation = $invitation;
$this->notes = $notes;
}
-
}
diff --git a/app/Events/QuoteInvitationWasViewed.php b/app/Events/QuoteInvitationWasViewed.php
index 87f5da2a0bb0..048a1ad4ad84 100644
--- a/app/Events/QuoteInvitationWasViewed.php
+++ b/app/Events/QuoteInvitationWasViewed.php
@@ -1,14 +1,16 @@
-quote = $quote;
}
-
}
diff --git a/app/Events/QuoteWasCreated.php b/app/Events/QuoteWasCreated.php
index 8077ea671634..3b294056eabf 100644
--- a/app/Events/QuoteWasCreated.php
+++ b/app/Events/QuoteWasCreated.php
@@ -1,9 +1,11 @@
-quote = $quote;
}
-
}
diff --git a/app/Events/TaskWasArchived.php b/app/Events/TaskWasArchived.php
index 74a7d1e4f6be..879430d2de05 100644
--- a/app/Events/TaskWasArchived.php
+++ b/app/Events/TaskWasArchived.php
@@ -1,10 +1,12 @@
-task = $task;
}
-
}
diff --git a/app/Events/TaskWasCreated.php b/app/Events/TaskWasCreated.php
index af1fc5c27df3..ffdedb2f0bc3 100644
--- a/app/Events/TaskWasCreated.php
+++ b/app/Events/TaskWasCreated.php
@@ -1,11 +1,12 @@
-task = $task;
}
-
}
diff --git a/app/Events/TaskWasRestored.php b/app/Events/TaskWasRestored.php
index 58891f6e3d85..438fe0dcd1f5 100644
--- a/app/Events/TaskWasRestored.php
+++ b/app/Events/TaskWasRestored.php
@@ -1,11 +1,12 @@
-task = $task;
}
-
}
diff --git a/app/Events/TaskWasUpdated.php b/app/Events/TaskWasUpdated.php
index 608f57ea7c2b..e79f9bbc7f10 100644
--- a/app/Events/TaskWasUpdated.php
+++ b/app/Events/TaskWasUpdated.php
@@ -1,11 +1,12 @@
-path() != 'get_started') {
// https://gist.github.com/jrmadsen67/bd0f9ad0ef1ed6bb594e
@@ -79,35 +82,32 @@ class Handler extends ExceptionHandler
->back()
->withInput($request->except('password', '_token'))
->with([
- 'warning' => trans('texts.token_expired')
+ 'warning' => trans('texts.token_expired'),
]);
}
}
- if($this->isHttpException($e))
- {
- switch ($e->getStatusCode())
- {
+ if ($this->isHttpException($e)) {
+ switch ($e->getStatusCode()) {
// not found
case 404:
- if($request->header('X-Ninja-Token') != '') {
+ if ($request->header('X-Ninja-Token') != '') {
//API request which has hit a route which does not exist
- $error['error'] = ['message'=>'Route does not exist'];
+ $error['error'] = ['message' => 'Route does not exist'];
$error = json_encode($error, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders();
return response()->make($error, 404, $headers);
-
}
break;
// internal error
case '500':
- if($request->header('X-Ninja-Token') != '') {
+ if ($request->header('X-Ninja-Token') != '') {
//API request which produces 500 error
- $error['error'] = ['message'=>'Internal Server Error'];
+ $error['error'] = ['message' => 'Internal Server Error'];
$error = json_encode($error, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders();
@@ -120,17 +120,17 @@ class Handler extends ExceptionHandler
// In production, except for maintenance mode, we'll show a custom error screen
if (Utils::isNinjaProd()
- && !Utils::isDownForMaintenance()
- && !($e instanceof HttpResponseException)
- && !($e instanceof ValidationException)) {
+ && ! Utils::isDownForMaintenance()
+ && ! ($e instanceof HttpResponseException)
+ && ! ($e instanceof ValidationException)) {
$data = [
'error' => get_class($e),
'hideHeader' => true,
];
- return response()->view('error', $data);
+ return response()->view('error', $data, 500);
} else {
return parent::render($request, $e);
}
- }
+ }
}
diff --git a/app/Handlers/InvoiceEventHandler.php b/app/Handlers/InvoiceEventHandler.php
index 924a9590ee36..74c410880da4 100644
--- a/app/Handlers/InvoiceEventHandler.php
+++ b/app/Handlers/InvoiceEventHandler.php
@@ -1,51 +1,51 @@
-userMailer = $userMailer;
- $this->contactMailer = $contactMailer;
- }
+ public function __construct(UserMailer $userMailer, ContactMailer $contactMailer)
+ {
+ $this->userMailer = $userMailer;
+ $this->contactMailer = $contactMailer;
+ }
- public function subscribe($events)
- {
- $events->listen('invoice.sent', 'InvoiceEventHandler@onSent');
- $events->listen('invoice.viewed', 'InvoiceEventHandler@onViewed');
- $events->listen('invoice.paid', 'InvoiceEventHandler@onPaid');
- }
+ public function subscribe($events)
+ {
+ $events->listen('invoice.sent', 'InvoiceEventHandler@onSent');
+ $events->listen('invoice.viewed', 'InvoiceEventHandler@onViewed');
+ $events->listen('invoice.paid', 'InvoiceEventHandler@onPaid');
+ }
- public function onSent($invoice)
- {
- $this->sendNotifications($invoice, 'sent');
- }
+ public function onSent($invoice)
+ {
+ $this->sendNotifications($invoice, 'sent');
+ }
- public function onViewed($invoice)
- {
- $this->sendNotifications($invoice, 'viewed');
- }
+ public function onViewed($invoice)
+ {
+ $this->sendNotifications($invoice, 'viewed');
+ }
- public function onPaid($payment)
- {
- $this->contactMailer->sendPaymentConfirmation($payment);
+ public function onPaid($payment)
+ {
+ $this->contactMailer->sendPaymentConfirmation($payment);
- $this->sendNotifications($payment->invoice, 'paid', $payment);
- }
+ $this->sendNotifications($payment->invoice, 'paid', $payment);
+ }
- private function sendNotifications($invoice, $type, $payment = null)
- {
- foreach ($invoice->account->users as $user)
- {
- if ($user->{'notify_' . $type})
- {
+ private function sendNotifications($invoice, $type, $payment = null)
+ {
+ foreach ($invoice->account->users as $user) {
+ if ($user->{'notify_' . $type}) {
$this->userMailer->sendNotification($user, $invoice, $type, $payment);
- }
- }
- }
-}
\ No newline at end of file
+ }
+ }
+ }
+}
diff --git a/app/Http/Controllers/AccountApiController.php b/app/Http/Controllers/AccountApiController.php
index e63cc24d7790..cceb58a2502f 100644
--- a/app/Http/Controllers/AccountApiController.php
+++ b/app/Http/Controllers/AccountApiController.php
@@ -1,20 +1,22 @@
-accountRepo->create($request->first_name, $request->last_name, $request->email, $request->password);
$user = $account->users()->first();
@@ -52,7 +53,8 @@ class AccountApiController extends BaseAPIController
return $this->processLogin($request);
} else {
sleep(ERROR_DELAY);
- return $this->errorResponse(['message'=>'Invalid credentials'],401);
+
+ return $this->errorResponse(['message' => 'Invalid credentials'], 401);
}
}
@@ -114,20 +116,18 @@ class AccountApiController extends BaseAPIController
$account = Auth::user()->account;
//scan if this user has a token already registered (tokens can change, so we need to use the users email as key)
- $devices = json_decode($account->devices,TRUE);
+ $devices = json_decode($account->devices, true);
-
- for($x=0; $xsudo chown www-data:www-data /path/to/ninja/.env
');
+
return Redirect::to('/settings/system_settings');
}
@@ -186,7 +185,7 @@ class AppController extends BaseController
continue;
}
if (preg_match('/\s/', $val)) {
- $val = "'{$val}'";
+ $val = "'{$val}'";
}
$config .= "{$key}={$val}\n";
}
@@ -196,6 +195,7 @@ class AppController extends BaseController
fclose($fp);
Session::flash('message', trans('texts.updated_settings'));
+
return Redirect::to('/settings/system_settings');
}
@@ -231,6 +231,7 @@ class AppController extends BaseController
$data = [
'text' => 'Test email',
+ 'fromEmail' => $email
];
try {
@@ -244,7 +245,7 @@ class AppController extends BaseController
public function install()
{
- if (!Utils::isNinjaProd() && !Utils::isDatabaseSetup()) {
+ if (! Utils::isNinjaProd() && ! Utils::isDatabaseSetup()) {
try {
set_time_limit(60 * 5); // shouldn't take this long but just in case
Artisan::call('migrate', ['--force' => true]);
@@ -254,6 +255,7 @@ class AppController extends BaseController
Artisan::call('optimize', ['--force' => true]);
} catch (Exception $e) {
Utils::logError($e);
+
return Response::make($e->getMessage(), 500);
}
}
@@ -263,7 +265,7 @@ class AppController extends BaseController
public function update()
{
- if (!Utils::isNinjaProd()) {
+ if (! Utils::isNinjaProd()) {
try {
set_time_limit(60 * 5);
Artisan::call('clear-compiled');
@@ -280,7 +282,7 @@ class AppController extends BaseController
Event::fire(new UserSettingsChanged());
// legacy fix: check cipher is in .env file
- if ( ! env('APP_CIPHER')) {
+ if (! env('APP_CIPHER')) {
$fp = fopen(base_path().'/.env', 'a');
fwrite($fp, "\nAPP_CIPHER=AES-256-CBC");
fclose($fp);
@@ -293,6 +295,7 @@ class AppController extends BaseController
Session::flash('warning', $message);
} catch (Exception $e) {
Utils::logError($e);
+
return Response::make($e->getMessage(), 500);
}
}
@@ -304,12 +307,14 @@ class AppController extends BaseController
{
$messageId = Input::get('MessageID');
$error = Input::get('Name') . ': ' . Input::get('Description');
+
return $this->emailService->markBounced($messageId, $error) ? RESULT_SUCCESS : RESULT_FAILURE;
}
public function emailOpened()
{
$messageId = Input::get('MessageID');
+
return $this->emailService->markOpened($messageId) ? RESULT_SUCCESS : RESULT_FAILURE;
return RESULT_SUCCESS;
@@ -317,8 +322,9 @@ class AppController extends BaseController
public function stats()
{
- if ( ! hash_equals(Input::get('password'), env('RESELLER_PASSWORD'))) {
+ if (! hash_equals(Input::get('password'), env('RESELLER_PASSWORD'))) {
sleep(3);
+
return '';
}
@@ -332,7 +338,7 @@ class AppController extends BaseController
'clients.public_id as client_id',
'payments.public_id as payment_id',
'payments.payment_date',
- 'payments.amount'
+ 'payments.amount',
]);
} else {
$data = DB::table('users')->count();
diff --git a/app/Http/Controllers/Auth/AuthController.php b/app/Http/Controllers/Auth/AuthController.php
index c016c6ba97ee..c5fbccb78790 100644
--- a/app/Http/Controllers/Auth/AuthController.php
+++ b/app/Http/Controllers/Auth/AuthController.php
@@ -1,20 +1,21 @@
-accountRepo->unlinkUserFromOauth(Auth::user());
Session::flash('message', trans('texts.updated_settings'));
+
return redirect()->to('/settings/' . ACCOUNT_USER_DETAILS);
}
@@ -113,7 +117,7 @@ class AuthController extends Controller
*/
public function getLoginWrapper()
{
- if (!Utils::isNinja() && !User::count()) {
+ if (! Utils::isNinja() && ! User::count()) {
return redirect()->to('invoice_now');
}
@@ -127,12 +131,12 @@ class AuthController extends Controller
*/
public function postLoginWrapper(Request $request)
{
-
$userId = Auth::check() ? Auth::user()->id : null;
$user = User::where('email', '=', $request->input('email'))->first();
if ($user && $user->failed_logins >= MAX_FAILED_LOGINS) {
Session::flash('error', trans('texts.invalid_credentials'));
+
return redirect()->to('login');
}
@@ -155,7 +159,6 @@ class AuthController extends Controller
$users = $this->accountRepo->loadAccounts(Auth::user()->id);
Session::put(SESSION_USER_ACCOUNTS, $users);
-
} elseif ($user) {
$user->failed_logins = $user->failed_logins + 1;
$user->save();
@@ -169,10 +172,11 @@ class AuthController extends Controller
*/
public function getLogoutWrapper()
{
- if (Auth::check() && !Auth::user()->registered) {
+ if (Auth::check() && ! Auth::user()->registered) {
$account = Auth::user()->account;
$this->accountRepo->unlinkAccount($account);
- if ($account->company->accounts->count() == 1) {
+
+ if (! $account->hasMultipleAccounts()) {
$account->company->forceDelete();
}
$account->forceDelete();
@@ -182,6 +186,10 @@ class AuthController extends Controller
Session::flush();
+ if ($reason = request()->reason) {
+ Session::flash('warning', trans("texts.{$reason}_logout"));
+ }
+
return $response;
}
}
diff --git a/app/Http/Controllers/Auth/PasswordController.php b/app/Http/Controllers/Auth/PasswordController.php
index e26ca7bc1fea..42fa1c76d90d 100644
--- a/app/Http/Controllers/Auth/PasswordController.php
+++ b/app/Http/Controllers/Auth/PasswordController.php
@@ -1,11 +1,12 @@
-middleware('guest');
}
-
}
diff --git a/app/Http/Controllers/BankAccountController.php b/app/Http/Controllers/BankAccountController.php
index 3a3e5d7269c3..945357e6039f 100644
--- a/app/Http/Controllers/BankAccountController.php
+++ b/app/Http/Controllers/BankAccountController.php
@@ -1,20 +1,22 @@
- null,
'bankAccount' => null,
- 'transactions' => json_encode([$data])
+ 'transactions' => json_encode([$data]),
];
return View::make('accounts.bank_account', $data);
diff --git a/app/Http/Controllers/BaseAPIController.php b/app/Http/Controllers/BaseAPIController.php
index 4022408794e3..0a07f8b0b5bd 100644
--- a/app/Http/Controllers/BaseAPIController.php
+++ b/app/Http/Controllers/BaseAPIController.php
@@ -1,17 +1,19 @@
-where('public_id', '=', $clientPublicId);
};
$query->whereHas('client', $filter);
}
- if ( ! Utils::hasPermission('view_all')){
+ if (! Utils::hasPermission('view_all')) {
if ($this->entityType == ENTITY_USER) {
$query->where('id', '=', Auth::user()->id);
} else {
@@ -128,6 +130,7 @@ class BaseAPIController extends Controller
}
$resource = new Item($data, $transformer, $entityType);
+
return $this->manager->createData($resource)->toArray();
}
@@ -159,7 +162,7 @@ class BaseAPIController extends Controller
} else {
$meta = isset($response['meta']) ? $response['meta'] : null;
$response = [
- $index => $response
+ $index => $response,
];
if ($meta) {
@@ -174,14 +177,13 @@ class BaseAPIController extends Controller
return Response::make($response, 200, $headers);
}
- protected function errorResponse($response, $httpErrorCode = 400)
+ protected function errorResponse($response, $httpErrorCode = 400)
{
$error['error'] = $response;
$error = json_encode($error, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders();
return Response::make($error, $httpErrorCode, $headers);
-
}
protected function getRequestIncludes($data)
diff --git a/app/Http/Controllers/BaseController.php b/app/Http/Controllers/BaseController.php
index 11e78f6b66c0..90e85c312f78 100644
--- a/app/Http/Controllers/BaseController.php
+++ b/app/Http/Controllers/BaseController.php
@@ -1,9 +1,11 @@
- Input::get( 'name' ),
- 'business_phone_number' => Input::get( 'phone' ),
- 'email' => Input::get( 'email' ),
- 'personal_fico_score' => intval( Input::get( 'fico_score' ) ),
- 'business_annual_revenue' => intval( Input::get( 'annual_revenue' ) ),
- 'business_monthly_average_bank_balance' => intval( Input::get( 'average_bank_balance' ) ),
- 'business_inception_date' => date( 'Y-m-d', strtotime( Input::get( 'business_inception' ) ) ),
- 'partner_internal_business_id' => 'ninja_account_' . $user->account_id,
- );
+ $data = [
+ 'personal_user_full_name' => Input::get('name'),
+ 'business_phone_number' => Input::get('phone'),
+ 'email' => Input::get('email'),
+ 'personal_fico_score' => intval(Input::get('fico_score')),
+ 'business_annual_revenue' => intval(Input::get('annual_revenue')),
+ 'business_monthly_average_bank_balance' => intval(Input::get('average_bank_balance')),
+ 'business_inception_date' => date('Y-m-d', strtotime(Input::get('business_inception'))),
+ 'partner_internal_business_id' => 'ninja_account_' . $user->account_id,
+ ];
- if ( ! empty( Input::get( 'quote_type_factoring' ) ) ) {
- $data['invoice_factoring_offer'] = true;
- $data['desired_credit_line'] = intval( Input::get( 'desired_credit_limit' )['invoice_factoring'] );
- }
+ if (! empty(Input::get('quote_type_factoring'))) {
+ $data['invoice_factoring_offer'] = true;
+ $data['desired_credit_line'] = intval(Input::get('desired_credit_limit')['invoice_factoring']);
+ }
- if ( ! empty( Input::get( 'quote_type_loc' ) ) ) {
- $data['line_of_credit_offer'] = true;
- $data['desired_credit_line_for_loc'] = intval( Input::get( 'desired_credit_limit' )['line_of_credit'] );
- }
+ if (! empty(Input::get('quote_type_loc'))) {
+ $data['line_of_credit_offer'] = true;
+ $data['desired_credit_line_for_loc'] = intval(Input::get('desired_credit_limit')['line_of_credit']);
+ }
+ $api_client = new \GuzzleHttp\Client();
+ try {
+ $response = $api_client->request('POST',
+ 'https://app.bluevine.com/api/v1/user/register_external?' . http_build_query([
+ 'external_register_token' => env('BLUEVINE_PARTNER_TOKEN'),
+ 'c' => env('BLUEVINE_PARTNER_UNIQUE_ID'),
+ 'signup_parent_url' => URL::to('/bluevine/completed'),
+ ]), [
+ 'json' => $data,
+ ]
+ );
+ } catch (\GuzzleHttp\Exception\RequestException $ex) {
+ if ($ex->getCode() == 403) {
+ $response_body = $ex->getResponse()->getBody(true);
+ $response_data = json_decode($response_body);
- $api_client = new \GuzzleHttp\Client();
- try {
- $response = $api_client->request( 'POST',
- 'https://app.bluevine.com/api/v1/user/register_external?' . http_build_query( array(
- 'external_register_token' => env( 'BLUEVINE_PARTNER_TOKEN' ),
- 'c' => env( 'BLUEVINE_PARTNER_UNIQUE_ID' ),
- 'signup_parent_url' => URL::to( '/bluevine/completed' ),
- ) ), array(
- 'json' => $data
- )
- );
- } catch ( \GuzzleHttp\Exception\RequestException $ex ) {
- if ( $ex->getCode() == 403 ) {
- $response_body = $ex->getResponse()->getBody( true );
- $response_data = json_decode( $response_body );
+ return response()->json([
+ 'error' => true,
+ 'message' => $response_data->reason,
+ ]);
+ } else {
+ return response()->json([
+ 'error' => true,
+ ]);
+ }
+ }
- return response()->json( [
- 'error' => true,
- 'message' => $response_data->reason
- ] );
- } else {
- return response()->json( [
- 'error' => true
- ] );
- }
- }
+ $company = $user->account->company;
+ $company->bluevine_status = 'signed_up';
+ $company->save();
- $company = $user->account->company;
- $company->bluevine_status = 'signed_up';
- $company->save();
+ $quote_data = json_decode($response->getBody());
- $quote_data = json_decode( $response->getBody() );
+ return response()->json($quote_data);
+ }
- return response()->json( $quote_data );
- }
+ public function hideMessage()
+ {
+ $user = Auth::user();
- public function hideMessage() {
- $user = Auth::user();
+ if ($user) {
+ $company = $user->account->company;
+ $company->bluevine_status = 'ignored';
+ $company->save();
+ }
- if ( $user ) {
- $company = $user->account->company;
- $company->bluevine_status = 'ignored';
- $company->save();
- }
+ return 'success';
+ }
- return 'success';
- }
+ public function handleCompleted()
+ {
+ Session::flash('message', trans('texts.bluevine_completed'));
- public function handleCompleted() {
- Session::flash( 'message', trans( 'texts.bluevine_completed' ) );
-
- return Redirect::to( '/dashboard' );
- }
+ return Redirect::to('/dashboard');
+ }
}
diff --git a/app/Http/Controllers/BotController.php b/app/Http/Controllers/BotController.php
index 5e5994185c87..02267924f23a 100644
--- a/app/Http/Controllers/BotController.php
+++ b/app/Http/Controllers/BotController.php
@@ -2,18 +2,18 @@
namespace App\Http\Controllers;
-use Auth;
-use DB;
-use Utils;
-use Cache;
-use Input;
-use Exception;
-use App\Libraries\Skype\SkypeResponse;
use App\Libraries\CurlUtils;
-use App\Models\User;
+use App\Libraries\Skype\SkypeResponse;
use App\Models\SecurityCode;
+use App\Models\User;
use App\Ninja\Intents\BaseIntent;
use App\Ninja\Mailers\UserMailer;
+use Auth;
+use Cache;
+use DB;
+use Exception;
+use Input;
+use Utils;
class BotController extends Controller
{
@@ -29,7 +29,7 @@ class BotController extends Controller
$input = Input::all();
$botUserId = $input['from']['id'];
- if ( ! $token = $this->authenticate($input)) {
+ if (! $token = $this->authenticate($input)) {
return SkypeResponse::message(trans('texts.not_authorized'));
}
@@ -42,6 +42,7 @@ class BotController extends Controller
} elseif ($input['action'] === 'remove') {
$this->removeBot($botUserId);
$this->saveState($token, false);
+
return RESULT_SUCCESS;
}
} else {
@@ -71,7 +72,7 @@ class BotController extends Controller
} elseif ($text == 'status') {
$response = SkypeResponse::message(trans('texts.intent_not_supported'));
} else {
- if ( ! $user = User::whereBotUserId($botUserId)->with('account')->first()) {
+ if (! $user = User::whereBotUserId($botUserId)->with('account')->first()) {
return SkypeResponse::message(trans('texts.not_authorized'));
}
@@ -102,7 +103,7 @@ class BotController extends Controller
if (Utils::isNinjaDev()) {
// skip validation for testing
- } elseif ( ! $this->validateToken($token)) {
+ } elseif (! $this->validateToken($token)) {
return false;
}
@@ -130,7 +131,7 @@ class BotController extends Controller
$url = sprintf('%s/botstate/skype/conversations/%s', MSBOT_STATE_URL, '29:1C-OsU7OWBEDOYJhQUsDkYHmycOwOq9QOg5FVTwRX9ts');
$headers = [
- 'Authorization: Bearer ' . $token
+ 'Authorization: Bearer ' . $token,
];
$response = CurlUtils::get($url, $headers);
@@ -165,7 +166,6 @@ class BotController extends Controller
$data = '{ eTag: "*", data: "' . addslashes(json_encode($data)) . '" }';
-
CurlUtils::post($url, $data, $headers);
}
@@ -186,7 +186,7 @@ class BotController extends Controller
private function validateEmail($email, $botUserId)
{
- if ( ! $email || ! $botUserId) {
+ if (! $email || ! $botUserId) {
return false;
}
@@ -203,7 +203,7 @@ class BotController extends Controller
->whereNull('bot_user_id')
->first();
- if ( ! $user) {
+ if (! $user) {
return false;
}
@@ -221,7 +221,7 @@ class BotController extends Controller
private function validateCode($input, $botUserId)
{
- if ( ! $input || ! $botUserId) {
+ if (! $input || ! $botUserId) {
return false;
}
@@ -230,13 +230,14 @@ class BotController extends Controller
->where('attempts', '<', 5)
->first();
- if ( ! $code) {
+ if (! $code) {
return false;
}
- if ( ! hash_equals($code->code, $input)) {
+ if (! hash_equals($code->code, $input)) {
$code->attempts += 1;
$code->save();
+
return false;
}
@@ -256,7 +257,7 @@ class BotController extends Controller
private function validateToken($token)
{
- if ( ! $token) {
+ if (! $token) {
return false;
}
@@ -273,17 +274,17 @@ class BotController extends Controller
$sig_enc = $token_arr[2];
// 2 base 64 url decoding
- $headers_arr = json_decode($this->base64_url_decode($headers_enc), TRUE);
- $claims_arr = json_decode($this->base64_url_decode($claims_enc), TRUE);
+ $headers_arr = json_decode($this->base64_url_decode($headers_enc), true);
+ $claims_arr = json_decode($this->base64_url_decode($claims_enc), true);
$sig = $this->base64_url_decode($sig_enc);
// 3 get key list
$keylist = file_get_contents('https://api.aps.skype.com/v1/keys');
- $keylist_arr = json_decode($keylist, TRUE);
- foreach($keylist_arr['keys'] as $key => $value) {
+ $keylist_arr = json_decode($keylist, true);
+ foreach ($keylist_arr['keys'] as $key => $value) {
// 4 select one key (which matches)
- if($value['kid'] == $headers_arr['kid']) {
+ if ($value['kid'] == $headers_arr['kid']) {
// 5 get public key from key info
$cert_txt = '-----BEGIN CERTIFICATE-----' . "\n" . chunk_split($value['x5c'][0], 64) . '-----END CERTIFICATE-----';
@@ -298,10 +299,11 @@ class BotController extends Controller
}
// 7 show result
- return ($token_valid == 1);
+ return $token_valid == 1;
}
- private function base64_url_decode($arg) {
+ private function base64_url_decode($arg)
+ {
$res = $arg;
$res = str_replace('-', '+', $res);
$res = str_replace('_', '/', $res);
@@ -309,15 +311,16 @@ class BotController extends Controller
case 0:
break;
case 2:
- $res .= "==";
+ $res .= '==';
break;
case 3:
- $res .= "=";
+ $res .= '=';
break;
default:
break;
}
$res = base64_decode($res);
+
return $res;
}
}
diff --git a/app/Http/Controllers/ClientApiController.php b/app/Http/Controllers/ClientApiController.php
index 4f6ca6521c62..928fe68b8c7c 100644
--- a/app/Http/Controllers/ClientApiController.php
+++ b/app/Http/Controllers/ClientApiController.php
@@ -1,12 +1,14 @@
-itemResponse($request->entity());
}
-
-
-
/**
* @SWG\Post(
* path="/clients",
@@ -126,8 +124,9 @@ class ClientApiController extends BaseAPIController
* description="an ""unexpected"" error"
* )
* )
+ *
+ * @param mixed $publicId
*/
-
public function update(UpdateClientRequest $request, $publicId)
{
if ($request->action) {
@@ -143,7 +142,6 @@ class ClientApiController extends BaseAPIController
return $this->itemResponse($client);
}
-
/**
* @SWG\Delete(
* path="/clients/{client_id}",
@@ -165,7 +163,6 @@ class ClientApiController extends BaseAPIController
* )
* )
*/
-
public function destroy(UpdateClientRequest $request)
{
$client = $request->entity();
@@ -174,5 +171,4 @@ class ClientApiController extends BaseAPIController
return $this->itemResponse($client);
}
-
}
diff --git a/app/Http/Controllers/ClientAuth/AuthController.php b/app/Http/Controllers/ClientAuth/AuthController.php
index fee6eeab838f..f48934b06826 100644
--- a/app/Http/Controllers/ClientAuth/AuthController.php
+++ b/app/Http/Controllers/ClientAuth/AuthController.php
@@ -1,11 +1,13 @@
-first();
- if ($contact && !$contact->is_deleted) {
- $account = $contact->account;
-
- $data['account'] = $account;
- $data['clientFontUrl'] = $account->getFontsUrl();
- }
- }
+ $data = [
+ 'clientauth' => true,
+ ];
return view('clientauth.login')->with($data);
}
@@ -45,7 +38,7 @@ class AuthController extends Controller
/**
* Get the needed authorization credentials from the request.
*
- * @param \Illuminate\Http\Request $request
+ * @param \Illuminate\Http\Request $request
*
* @return array
*/
@@ -57,7 +50,7 @@ class AuthController extends Controller
$contactKey = session('contact_key');
if ($contactKey) {
$contact = Contact::where('contact_key', '=', $contactKey)->first();
- if ($contact && !$contact->is_deleted) {
+ if ($contact && ! $contact->is_deleted) {
$credentials['id'] = $contact->id;
}
}
@@ -68,7 +61,7 @@ class AuthController extends Controller
/**
* Validate the user login request.
*
- * @param \Illuminate\Http\Request $request
+ * @param \Illuminate\Http\Request $request
*
* @return void
*/
@@ -84,6 +77,6 @@ class AuthController extends Controller
*/
public function getSessionExpired()
{
- return view('clientauth.sessionexpired');
+ return view('clientauth.sessionexpired')->with(['clientauth' => true]);
}
}
diff --git a/app/Http/Controllers/ClientAuth/PasswordController.php b/app/Http/Controllers/ClientAuth/PasswordController.php
index a7957cacf5d1..bf3f2da9c974 100644
--- a/app/Http/Controllers/ClientAuth/PasswordController.php
+++ b/app/Http/Controllers/ClientAuth/PasswordController.php
@@ -1,17 +1,18 @@
- true,
+ ];
$contactKey = session('contact_key');
- if ($contactKey) {
- $contact = Contact::where('contact_key', '=', $contactKey)->first();
- if ($contact && !$contact->is_deleted) {
- $account = $contact->account;
- $data['account'] = $account;
- $data['clientFontUrl'] = $account->getFontsUrl();
- }
- } else {
+ if (!$contactKey) {
return \Redirect::to('/client/sessionexpired');
}
@@ -66,8 +62,8 @@ class PasswordController extends Controller
/**
* Send a reset link to the given user.
*
- * @param \Illuminate\Http\Request $request
- *
+ * @param \Illuminate\Http\Request $request
+ *
* @return \Illuminate\Http\Response
*/
public function sendResetLinkEmail(Request $request)
@@ -78,7 +74,7 @@ class PasswordController extends Controller
$contactKey = session('contact_key');
if ($contactKey) {
$contact = Contact::where('contact_key', '=', $contactKey)->first();
- if ($contact && !$contact->is_deleted) {
+ if ($contact && ! $contact->is_deleted && $contact->email) {
$contactId = $contact->id;
}
}
@@ -102,9 +98,10 @@ class PasswordController extends Controller
*
* If no token is present, display the link request form.
*
- * @param \Illuminate\Http\Request $request
- * @param string|null $key
- * @param string|null $token
+ * @param \Illuminate\Http\Request $request
+ * @param string|null $key
+ * @param string|null $token
+ *
* @return \Illuminate\Http\Response
*/
public function showResetForm(Request $request, $key = null, $token = null)
@@ -113,25 +110,26 @@ class PasswordController extends Controller
return $this->getEmail();
}
- $data = compact('token');
+ $data = array(
+ 'token' => $token,
+ 'clientauth' => true,
+ );
+
if ($key) {
$contact = Contact::where('contact_key', '=', $key)->first();
- if ($contact && !$contact->is_deleted) {
+ if ($contact && ! $contact->is_deleted) {
$account = $contact->account;
$data['contact_key'] = $contact->contact_key;
} else {
// Maybe it's an invitation key
$invitation = Invitation::where('invitation_key', '=', $key)->first();
- if ($invitation && !$invitation->is_deleted) {
+ if ($invitation && ! $invitation->is_deleted) {
$account = $invitation->account;
$data['contact_key'] = $invitation->contact->contact_key;
}
}
- if (!empty($account)) {
- $data['account'] = $account;
- $data['clientFontUrl'] = $account->getFontsUrl();
- } else {
+ if ( empty($account)) {
return \Redirect::to('/client/sessionexpired');
}
}
@@ -139,15 +137,15 @@ class PasswordController extends Controller
return view('clientauth.reset')->with($data);
}
-
/**
* Display the password reset view for the given token.
*
* If no token is present, display the link request form.
*
- * @param \Illuminate\Http\Request $request
- * @param string|null $key
- * @param string|null $token
+ * @param \Illuminate\Http\Request $request
+ * @param string|null $key
+ * @param string|null $token
+ *
* @return \Illuminate\Http\Response
*/
public function getReset(Request $request, $key = null, $token = null)
@@ -158,7 +156,8 @@ class PasswordController extends Controller
/**
* Reset the given user's password.
*
- * @param \Illuminate\Http\Request $request
+ * @param \Illuminate\Http\Request $request
+ *
* @return \Illuminate\Http\Response
*/
public function reset(Request $request)
@@ -174,7 +173,7 @@ class PasswordController extends Controller
$contactKey = session('contact_key');
if ($contactKey) {
$contact = Contact::where('contact_key', '=', $contactKey)->first();
- if ($contact && !$contact->is_deleted) {
+ if ($contact && ! $contact->is_deleted) {
$credentials['id'] = $contact->id;
}
}
diff --git a/app/Http/Controllers/ClientController.php b/app/Http/Controllers/ClientController.php
index c2fd0a93d614..8a6beffcc81e 100644
--- a/app/Http/Controllers/ClientController.php
+++ b/app/Http/Controllers/ClientController.php
@@ -1,25 +1,26 @@
-can('create', ENTITY_INVOICE)){
+ if ($user->can('create', ENTITY_INVOICE)) {
$actionLinks[] = ['label' => trans('texts.new_invoice'), 'url' => URL::to('/invoices/create/'.$client->public_id)];
}
- if ($user->can('create', ENTITY_TASK)){
+ if ($user->can('create', ENTITY_TASK)) {
$actionLinks[] = ['label' => trans('texts.new_task'), 'url' => URL::to('/tasks/create/'.$client->public_id)];
}
if (Utils::hasFeature(FEATURE_QUOTES) && $user->can('create', ENTITY_QUOTE)) {
$actionLinks[] = ['label' => trans('texts.new_quote'), 'url' => URL::to('/quotes/create/'.$client->public_id)];
}
- if(!empty($actionLinks)){
+ if (! empty($actionLinks)) {
$actionLinks[] = \DropdownButton::DIVIDER;
}
- if($user->can('create', ENTITY_PAYMENT)){
+ if ($user->can('create', ENTITY_PAYMENT)) {
$actionLinks[] = ['label' => trans('texts.enter_payment'), 'url' => URL::to('/payments/create/'.$client->public_id)];
}
- if($user->can('create', ENTITY_CREDIT)){
+ if ($user->can('create', ENTITY_CREDIT)) {
$actionLinks[] = ['label' => trans('texts.enter_credit'), 'url' => URL::to('/credits/create/'.$client->public_id)];
}
- if($user->can('create', ENTITY_EXPENSE)){
+ if ($user->can('create', ENTITY_EXPENSE)) {
$actionLinks[] = ['label' => trans('texts.enter_expense'), 'url' => URL::to('/expenses/create/0/'.$client->public_id)];
}
@@ -154,7 +156,8 @@ class ClientController extends BaseController
/**
* Show the form for editing the specified resource.
*
- * @param int $id
+ * @param int $id
+ *
* @return Response
*/
public function edit(ClientRequest $request)
@@ -185,7 +188,6 @@ class ClientController extends BaseController
'data' => Input::old('data'),
'account' => Auth::user()->account,
'sizes' => Cache::get('sizes'),
- 'paymentTerms' => Cache::get('paymentTerms'),
'currencies' => Cache::get('currencies'),
'customLabel1' => Auth::user()->account->custom_client_label1,
'customLabel2' => Auth::user()->account->custom_client_label2,
@@ -195,7 +197,8 @@ class ClientController extends BaseController
/**
* Update the specified resource in storage.
*
- * @param int $id
+ * @param int $id
+ *
* @return Response
*/
public function update(UpdateClientRequest $request)
diff --git a/app/Http/Controllers/ClientPortalController.php b/app/Http/Controllers/ClientPortalController.php
index ca996ac136ea..40a46176fc59 100644
--- a/app/Http/Controllers/ClientPortalController.php
+++ b/app/Http/Controllers/ClientPortalController.php
@@ -1,32 +1,34 @@
-silent) {
- session(['silent' => true]);
- return redirect(request()->url());
- }
-
- if (!$invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) {
+ if (! $invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) {
return $this->returnError();
}
@@ -59,19 +56,21 @@ class ClientPortalController extends BaseController
$client = $invoice->client;
$account = $invoice->account;
- if (!$account->checkSubdomain(Request::server('HTTP_HOST'))) {
+ if (request()->silent) {
+ session(['silent:' . $client->id => true]);
+ return redirect(request()->url());
+ }
+
+ if (! $account->checkSubdomain(Request::server('HTTP_HOST'))) {
return response()->view('error', [
'error' => trans('texts.invoice_not_found'),
- 'hideHeader' => true,
- 'clientViewCSS' => $account->clientViewCSS(),
- 'clientFontUrl' => $account->getFontsUrl(),
]);
}
$account->loadLocalizationSettings($client);
- if (! Input::has('phantomjs') && ! session('silent') && ! Session::has($invitationKey)
- && (!Auth::check() || Auth::user()->account_id != $invoice->account_id)) {
+ if (! Input::has('phantomjs') && ! session('silent:' . $client->id) && ! Session::has($invitation->invitation_key)
+ && (! Auth::check() || Auth::user()->account_id != $invoice->account_id)) {
if ($invoice->isType(INVOICE_TYPE_QUOTE)) {
event(new QuoteInvitationWasViewed($invoice, $invitation));
} else {
@@ -79,8 +78,8 @@ class ClientPortalController extends BaseController
}
}
- Session::put($invitationKey, true); // track this invitation has been seen
- Session::put('contact_key', $invitation->contact->contact_key);// track current contact
+ Session::put($invitation->invitation_key, true); // track this invitation has been seen
+ Session::put('contact_key', $invitation->contact->contact_key); // track current contact
$invoice->invoice_date = Utils::fromSqlDate($invoice->invoice_date);
$invoice->due_date = Utils::fromSqlDate($invoice->due_date);
@@ -104,10 +103,13 @@ class ClientPortalController extends BaseController
'phone',
]);
- // translate the client country name
+ // translate the country names
if ($invoice->client->country) {
$invoice->client->country->name = trans('texts.country_' . $invoice->client->country->name);
}
+ if ($invoice->account->country) {
+ $invoice->account->country->name = trans('texts.country_' . $invoice->account->country->name);
+ }
$data = [];
$paymentTypes = $this->getPaymentTypes($account, $client, $invitation);
@@ -116,12 +118,12 @@ class ClientPortalController extends BaseController
$paymentURL = $paymentTypes[0]['url'];
if ($paymentTypes[0]['gatewayTypeId'] == GATEWAY_TYPE_CUSTOM) {
// do nothing
- } elseif (!$account->isGatewayConfigured(GATEWAY_PAYPAL_EXPRESS)) {
+ } elseif (! $account->isGatewayConfigured(GATEWAY_PAYPAL_EXPRESS)) {
$paymentURL = URL::to($paymentURL);
}
}
- if ($wepayGateway = $account->getGatewayConfig(GATEWAY_WEPAY)){
+ if ($wepayGateway = $account->getGatewayConfig(GATEWAY_WEPAY)) {
$data['enableWePayACH'] = $wepayGateway->getAchEnabled();
}
@@ -137,7 +139,6 @@ class ClientPortalController extends BaseController
'account' => $account,
'showApprove' => $showApprove,
'showBreadcrumbs' => false,
- 'clientFontUrl' => $account->getFontsUrl(),
'invoice' => $invoice->hidePrivateFields(),
'invitation' => $invitation,
'invoiceLabels' => $account->getInvoiceLabels(),
@@ -162,10 +163,10 @@ class ClientPortalController extends BaseController
];
}
- if($account->hasFeature(FEATURE_DOCUMENTS) && $this->canCreateZip()){
+ if ($account->hasFeature(FEATURE_DOCUMENTS) && $this->canCreateZip()) {
$zipDocs = $this->getInvoiceZipDocuments($invoice, $size);
- if(count($zipDocs) > 1){
+ if (count($zipDocs) > 1) {
$data['documentsZipURL'] = URL::to("client/documents/{$invitation->invitation_key}");
$data['documentsZipSize'] = $size;
}
@@ -189,7 +190,7 @@ class ClientPortalController extends BaseController
public function download($invitationKey)
{
- if (!$invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) {
+ if (! $invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) {
return response()->view('error', [
'error' => trans('texts.invoice_not_found'),
'hideHeader' => true,
@@ -210,7 +211,7 @@ class ClientPortalController extends BaseController
public function sign($invitationKey)
{
- if (!$invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) {
+ if (! $invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) {
return RESULT_FAILURE;
}
@@ -228,24 +229,29 @@ class ClientPortalController extends BaseController
public function dashboard($contactKey = false)
{
if ($contactKey) {
- if (!$contact = Contact::where('contact_key', '=', $contactKey)->first()) {
+ if (! $contact = Contact::where('contact_key', '=', $contactKey)->first()) {
return $this->returnError();
}
- Session::put('contact_key', $contactKey);// track current contact
- } else if (!$contact = $this->getContact()) {
+ Session::put('contact_key', $contactKey); // track current contact
+ } elseif (! $contact = $this->getContact()) {
return $this->returnError();
}
$client = $contact->client;
$account = $client->account;
- $account->loadLocalizationSettings($client);
+ if (request()->silent) {
+ session(['silent:' . $client->id => true]);
+ return redirect(request()->url());
+ }
+
+ $account->loadLocalizationSettings($client);
$color = $account->primary_color ? $account->primary_color : '#0b4d78';
$customer = false;
- if (!$account->enable_client_portal) {
+ if (! $account->enable_client_portal) {
return $this->returnError();
- } elseif (!$account->enable_client_portal_dashboard) {
+ } elseif (! $account->enable_client_portal_dashboard) {
return redirect()->to('/client/invoices/');
}
@@ -258,7 +264,6 @@ class ClientPortalController extends BaseController
'contact' => $contact,
'account' => $account,
'client' => $client,
- 'clientFontUrl' => $account->getFontsUrl(),
'gateway' => $account->getTokenGateway(),
'paymentMethods' => $customer ? $customer->payment_methods : false,
'transactionToken' => $paymentDriver ? $paymentDriver->createTransactionToken() : false,
@@ -269,7 +274,7 @@ class ClientPortalController extends BaseController
public function activityDatatable()
{
- if (!$contact = $this->getContact()) {
+ if (! $contact = $this->getContact()) {
return $this->returnError();
}
@@ -279,7 +284,9 @@ class ClientPortalController extends BaseController
$query->where('activities.adjustment', '!=', 0);
return Datatable::query($query)
- ->addColumn('activities.id', function ($model) { return Utils::timestampToDateTimeString(strtotime($model->created_at)); })
+ ->addColumn('activities.id', function ($model) {
+ return Utils::timestampToDateTimeString(strtotime($model->created_at));
+ })
->addColumn('activity_type_id', function ($model) {
$data = [
'client' => Utils::getClientDisplayName($model),
@@ -293,22 +300,26 @@ class ClientPortalController extends BaseController
];
return trans("texts.activity_{$model->activity_type_id}", $data);
- })
- ->addColumn('balance', function ($model) { return Utils::formatMoney($model->balance, $model->currency_id, $model->country_id); })
- ->addColumn('adjustment', function ($model) { return $model->adjustment != 0 ? Utils::wrapAdjustment($model->adjustment, $model->currency_id, $model->country_id) : ''; })
+ })
+ ->addColumn('balance', function ($model) {
+ return Utils::formatMoney($model->balance, $model->currency_id, $model->country_id);
+ })
+ ->addColumn('adjustment', function ($model) {
+ return $model->adjustment != 0 ? Utils::wrapAdjustment($model->adjustment, $model->currency_id, $model->country_id) : '';
+ })
->make();
}
public function recurringInvoiceIndex()
{
- if (!$contact = $this->getContact()) {
+ if (! $contact = $this->getContact()) {
return $this->returnError();
}
$account = $contact->account;
$account->loadLocalizationSettings($contact->client);
- if (!$account->enable_client_portal) {
+ if (! $account->enable_client_portal) {
return $this->returnError();
}
@@ -318,7 +329,6 @@ class ClientPortalController extends BaseController
'color' => $color,
'account' => $account,
'client' => $contact->client,
- 'clientFontUrl' => $account->getFontsUrl(),
'title' => trans('texts.recurring_invoices'),
'entityType' => ENTITY_RECURRING_INVOICE,
'columns' => Utils::trans(['frequency', 'start_date', 'end_date', 'invoice_total', 'auto_bill']),
@@ -329,14 +339,14 @@ class ClientPortalController extends BaseController
public function invoiceIndex()
{
- if (!$contact = $this->getContact()) {
+ if (! $contact = $this->getContact()) {
return $this->returnError();
}
$account = $contact->account;
$account->loadLocalizationSettings($contact->client);
- if (!$account->enable_client_portal) {
+ if (! $account->enable_client_portal) {
return $this->returnError();
}
@@ -346,7 +356,6 @@ class ClientPortalController extends BaseController
'color' => $color,
'account' => $account,
'client' => $contact->client,
- 'clientFontUrl' => $account->getFontsUrl(),
'title' => trans('texts.invoices'),
'entityType' => ENTITY_INVOICE,
'columns' => Utils::trans(['invoice_number', 'invoice_date', 'invoice_total', 'balance_due', 'due_date']),
@@ -357,7 +366,7 @@ class ClientPortalController extends BaseController
public function invoiceDatatable()
{
- if (!$contact = $this->getContact()) {
+ if (! $contact = $this->getContact()) {
return '';
}
@@ -366,24 +375,23 @@ class ClientPortalController extends BaseController
public function recurringInvoiceDatatable()
{
- if (!$contact = $this->getContact()) {
+ if (! $contact = $this->getContact()) {
return '';
}
return $this->invoiceRepo->getClientRecurringDatatable($contact->id);
}
-
public function paymentIndex()
{
- if (!$contact = $this->getContact()) {
+ if (! $contact = $this->getContact()) {
return $this->returnError();
}
$account = $contact->account;
$account->loadLocalizationSettings($contact->client);
- if (!$account->enable_client_portal) {
+ if (! $account->enable_client_portal) {
return $this->returnError();
}
@@ -392,10 +400,9 @@ class ClientPortalController extends BaseController
$data = [
'color' => $color,
'account' => $account,
- 'clientFontUrl' => $account->getFontsUrl(),
'entityType' => ENTITY_PAYMENT,
'title' => trans('texts.payments'),
- 'columns' => Utils::trans(['invoice', 'transaction_reference', 'method', 'payment_amount', 'payment_date', 'status'])
+ 'columns' => Utils::trans(['invoice', 'transaction_reference', 'method', 'payment_amount', 'payment_date', 'status']),
];
return response()->view('public_list', $data);
@@ -403,19 +410,31 @@ class ClientPortalController extends BaseController
public function paymentDatatable()
{
- if (!$contact = $this->getContact()) {
+ if (! $contact = $this->getContact()) {
return $this->returnError();
}
$payments = $this->paymentRepo->findForContact($contact->id, Input::get('sSearch'));
return Datatable::query($payments)
- ->addColumn('invoice_number', function ($model) { return $model->invitation_key ? link_to('/view/'.$model->invitation_key, $model->invoice_number)->toHtml() : $model->invoice_number; })
- ->addColumn('transaction_reference', function ($model) { return $model->transaction_reference ? $model->transaction_reference : ''.trans('texts.manual_entry').''; })
- ->addColumn('payment_type', function ($model) { return ($model->payment_type && !$model->last4) ? $model->payment_type : ($model->account_gateway_id ? 'Online payment' : ''); })
- ->addColumn('amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id, $model->country_id); })
- ->addColumn('payment_date', function ($model) { return Utils::dateToString($model->payment_date); })
- ->addColumn('status', function ($model) { return $this->getPaymentStatusLabel($model); })
- ->orderColumns( 'invoice_number', 'transaction_reference', 'payment_type', 'amount', 'payment_date')
+ ->addColumn('invoice_number', function ($model) {
+ return $model->invitation_key ? link_to('/view/'.$model->invitation_key, $model->invoice_number)->toHtml() : $model->invoice_number;
+ })
+ ->addColumn('transaction_reference', function ($model) {
+ return $model->transaction_reference ? $model->transaction_reference : ''.trans('texts.manual_entry').'';
+ })
+ ->addColumn('payment_type', function ($model) {
+ return ($model->payment_type && ! $model->last4) ? $model->payment_type : ($model->account_gateway_id ? 'Online payment' : '');
+ })
+ ->addColumn('amount', function ($model) {
+ return Utils::formatMoney($model->amount, $model->currency_id, $model->country_id);
+ })
+ ->addColumn('payment_date', function ($model) {
+ return Utils::dateToString($model->payment_date);
+ })
+ ->addColumn('status', function ($model) {
+ return $this->getPaymentStatusLabel($model);
+ })
+ ->orderColumns('invoice_number', 'transaction_reference', 'payment_type', 'amount', 'payment_date')
->make();
}
@@ -443,19 +462,20 @@ class ClientPortalController extends BaseController
$class = 'default';
break;
}
+
return "
";
}
public function quoteIndex()
{
- if (!$contact = $this->getContact()) {
+ if (! $contact = $this->getContact()) {
return $this->returnError();
}
$account = $contact->account;
$account->loadLocalizationSettings($contact->client);
- if (!$account->enable_client_portal) {
+ if (! $account->enable_client_portal) {
return $this->returnError();
}
@@ -464,7 +484,6 @@ class ClientPortalController extends BaseController
$data = [
'color' => $color,
'account' => $account,
- 'clientFontUrl' => $account->getFontsUrl(),
'title' => trans('texts.quotes'),
'entityType' => ENTITY_QUOTE,
'columns' => Utils::trans(['quote_number', 'quote_date', 'quote_total', 'due_date']),
@@ -473,10 +492,9 @@ class ClientPortalController extends BaseController
return response()->view('public_list', $data);
}
-
public function quoteDatatable()
{
- if (!$contact = $this->getContact()) {
+ if (! $contact = $this->getContact()) {
return false;
}
@@ -485,14 +503,14 @@ class ClientPortalController extends BaseController
public function creditIndex()
{
- if (!$contact = $this->getContact()) {
+ if (! $contact = $this->getContact()) {
return $this->returnError();
}
$account = $contact->account;
$account->loadLocalizationSettings($contact->client);
- if (!$account->enable_client_portal) {
+ if (! $account->enable_client_portal) {
return $this->returnError();
}
@@ -501,7 +519,6 @@ class ClientPortalController extends BaseController
$data = [
'color' => $color,
'account' => $account,
- 'clientFontUrl' => $account->getFontsUrl(),
'title' => trans('texts.credits'),
'entityType' => ENTITY_CREDIT,
'columns' => Utils::trans(['credit_date', 'credit_amount', 'credit_balance']),
@@ -512,7 +529,7 @@ class ClientPortalController extends BaseController
public function creditDatatable()
{
- if (!$contact = $this->getContact()) {
+ if (! $contact = $this->getContact()) {
return false;
}
@@ -521,14 +538,14 @@ class ClientPortalController extends BaseController
public function documentIndex()
{
- if (!$contact = $this->getContact()) {
+ if (! $contact = $this->getContact()) {
return $this->returnError();
}
$account = $contact->account;
$account->loadLocalizationSettings($contact->client);
- if (!$account->enable_client_portal) {
+ if (! $account->enable_client_portal) {
return $this->returnError();
}
@@ -537,7 +554,6 @@ class ClientPortalController extends BaseController
$data = [
'color' => $color,
'account' => $account,
- 'clientFontUrl' => $account->getFontsUrl(),
'title' => trans('texts.documents'),
'entityType' => ENTITY_DOCUMENT,
'columns' => Utils::trans(['invoice_number', 'name', 'document_date', 'document_size']),
@@ -546,10 +562,9 @@ class ClientPortalController extends BaseController
return response()->view('public_list', $data);
}
-
public function documentDatatable()
{
- if (!$contact = $this->getContact()) {
+ if (! $contact = $this->getContact()) {
return false;
}
@@ -565,50 +580,51 @@ class ClientPortalController extends BaseController
]);
}
- private function getContact() {
+ private function getContact()
+ {
$contactKey = session('contact_key');
- if (!$contactKey) {
+ if (! $contactKey) {
return false;
}
$contact = Contact::where('contact_key', '=', $contactKey)->first();
- if (!$contact || $contact->is_deleted) {
+ if (! $contact || $contact->is_deleted) {
return false;
}
return $contact;
}
- public function getDocumentVFSJS($publicId, $name){
- if (!$contact = $this->getContact()) {
+ public function getDocumentVFSJS($publicId, $name)
+ {
+ if (! $contact = $this->getContact()) {
return $this->returnError();
}
$document = Document::scope($publicId, $contact->account_id)->first();
-
- if(!$document->isPDFEmbeddable()){
- return Response::view('error', ['error'=>'Image does not exist!'], 404);
+ if (! $document->isPDFEmbeddable()) {
+ return Response::view('error', ['error' => 'Image does not exist!'], 404);
}
$authorized = false;
- if($document->expense && $document->expense->client_id == $contact->client_id){
+ if ($document->expense && $document->expense->client_id == $contact->client_id) {
$authorized = true;
- } else if($document->invoice && $document->invoice->client_id ==$contact->client_id){
+ } elseif ($document->invoice && $document->invoice->client_id == $contact->client_id) {
$authorized = true;
}
- if(!$authorized){
- return Response::view('error', ['error'=>'Not authorized'], 403);
+ if (! $authorized) {
+ return Response::view('error', ['error' => 'Not authorized'], 403);
}
- if(substr($name, -3)=='.js'){
+ if (substr($name, -3) == '.js') {
$name = substr($name, 0, -3);
}
- $content = $document->preview?$document->getRawPreview():$document->getRaw();
+ $content = $document->preview ? $document->getRawPreview() : $document->getRaw();
$content = 'ninjaAddVFSDoc('.json_encode(intval($publicId).'/'.strval($name)).',"'.base64_encode($content).'")';
$response = Response::make($content, 200);
$response->header('content-type', 'text/javascript');
@@ -617,14 +633,16 @@ class ClientPortalController extends BaseController
return $response;
}
- protected function canCreateZip(){
+ protected function canCreateZip()
+ {
return function_exists('gmp_init');
}
- protected function getInvoiceZipDocuments($invoice, &$size=0){
+ protected function getInvoiceZipDocuments($invoice, &$size = 0)
+ {
$documents = $invoice->documents;
- foreach($invoice->expenses as $expense){
+ foreach ($invoice->expenses as $expense) {
$documents = $documents->merge($expense->documents);
}
@@ -633,31 +651,31 @@ class ClientPortalController extends BaseController
$size = 0;
$maxSize = MAX_ZIP_DOCUMENTS_SIZE * 1000;
$toZip = [];
- foreach($documents as $document){
- if($size + $document->size > $maxSize)break;
+ foreach ($documents as $document) {
+ if ($size + $document->size > $maxSize) {
+ break;
+ }
- if(!empty($toZip[$document->name])){
+ if (! empty($toZip[$document->name])) {
// This name is taken
- if($toZip[$document->name]->hash != $document->hash){
+ if ($toZip[$document->name]->hash != $document->hash) {
// 2 different files with the same name
$nameInfo = pathinfo($document->name);
- for($i = 1;; $i++){
+ for ($i = 1; ; $i++) {
$name = $nameInfo['filename'].' ('.$i.').'.$nameInfo['extension'];
- if(empty($toZip[$name])){
+ if (empty($toZip[$name])) {
$toZip[$name] = $document;
$size += $document->size;
break;
- } else if ($toZip[$name]->hash == $document->hash){
+ } elseif ($toZip[$name]->hash == $document->hash) {
// We're not adding this after all
break;
}
}
-
}
- }
- else{
+ } else {
$toZip[$document->name] = $document;
$size += $document->size;
}
@@ -666,32 +684,35 @@ class ClientPortalController extends BaseController
return $toZip;
}
- public function getInvoiceDocumentsZip($invitationKey){
- if (!$invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) {
+ public function getInvoiceDocumentsZip($invitationKey)
+ {
+ if (! $invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) {
return $this->returnError();
}
- Session::put('contact_key', $invitation->contact->contact_key);// track current contact
+ Session::put('contact_key', $invitation->contact->contact_key); // track current contact
$invoice = $invitation->invoice;
$toZip = $this->getInvoiceZipDocuments($invoice);
- if(!count($toZip)){
- return Response::view('error', ['error'=>'No documents small enough'], 404);
+ if (! count($toZip)) {
+ return Response::view('error', ['error' => 'No documents small enough'], 404);
}
$zip = new ZipArchive($invitation->account->name.' Invoice '.$invoice->invoice_number.'.zip');
- return Response::stream(function() use ($toZip, $zip) {
- foreach($toZip as $name=>$document){
+
+ return Response::stream(function () use ($toZip, $zip) {
+ foreach ($toZip as $name => $document) {
$fileStream = $document->getStream();
- if($fileStream){
- $zip->init_file_stream_transfer($name, $document->size, ['time'=>$document->created_at->timestamp]);
- while ($buffer = fread($fileStream, 256000))$zip->stream_file_part($buffer);
+ if ($fileStream) {
+ $zip->init_file_stream_transfer($name, $document->size, ['time' => $document->created_at->timestamp]);
+ while ($buffer = fread($fileStream, 256000)) {
+ $zip->stream_file_part($buffer);
+ }
fclose($fileStream);
$zip->complete_file_stream();
- }
- else{
+ } else {
$zip->add_file($name, $document->getRaw());
}
}
@@ -699,25 +720,26 @@ class ClientPortalController extends BaseController
}, 200);
}
- public function getDocument($invitationKey, $publicId){
- if (!$invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) {
+ public function getDocument($invitationKey, $publicId)
+ {
+ if (! $invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) {
return $this->returnError();
}
- Session::put('contact_key', $invitation->contact->contact_key);// track current contact
+ Session::put('contact_key', $invitation->contact->contact_key); // track current contact
$clientId = $invitation->invoice->client_id;
$document = Document::scope($publicId, $invitation->account_id)->firstOrFail();
$authorized = false;
- if($document->expense && $document->expense->client_id == $invitation->invoice->client_id){
+ if ($document->expense && $document->expense->client_id == $invitation->invoice->client_id) {
$authorized = true;
- } else if($document->invoice && $document->invoice->client_id == $invitation->invoice->client_id){
+ } elseif ($document->invoice && $document->invoice->client_id == $invitation->invoice->client_id) {
$authorized = true;
}
- if(!$authorized){
- return Response::view('error', ['error'=>'Not authorized'], 403);
+ if (! $authorized) {
+ return Response::view('error', ['error' => 'Not authorized'], 403);
}
return DocumentController::getDownloadResponse($document);
@@ -725,7 +747,7 @@ class ClientPortalController extends BaseController
public function paymentMethods()
{
- if (!$contact = $this->getContact()) {
+ if (! $contact = $this->getContact()) {
return $this->returnError();
}
@@ -740,8 +762,6 @@ class ClientPortalController extends BaseController
'contact' => $contact,
'color' => $account->primary_color ? $account->primary_color : '#0b4d78',
'client' => $client,
- 'clientViewCSS' => $account->clientViewCSS(),
- 'clientFontUrl' => $account->getFontsUrl(),
'paymentMethods' => $customer ? $customer->payment_methods : false,
'gateway' => $account->getTokenGateway(),
'title' => trans('texts.payment_methods'),
@@ -757,7 +777,7 @@ class ClientPortalController extends BaseController
$amount1 = Input::get('verification1');
$amount2 = Input::get('verification2');
- if (!$contact = $this->getContact()) {
+ if (! $contact = $this->getContact()) {
return $this->returnError();
}
@@ -773,12 +793,12 @@ class ClientPortalController extends BaseController
Session::flash('message', trans('texts.payment_method_verified'));
}
- return redirect()->to($account->enable_client_portal_dashboard?'/client/dashboard':'/client/payment_methods/');
+ return redirect()->to($account->enable_client_portal_dashboard ? '/client/dashboard' : '/client/payment_methods/');
}
public function removePaymentMethod($publicId)
{
- if (!$contact = $this->getContact()) {
+ if (! $contact = $this->getContact()) {
return $this->returnError();
}
@@ -797,11 +817,12 @@ class ClientPortalController extends BaseController
Session::flash('error', $exception->getMessage());
}
- return redirect()->to($client->account->enable_client_portal_dashboard?'/client/dashboard':'/client/payment_methods/');
+ return redirect()->to($client->account->enable_client_portal_dashboard ? '/client/dashboard' : '/client/payment_methods/');
}
- public function setDefaultPaymentMethod(){
- if (!$contact = $this->getContact()) {
+ public function setDefaultPaymentMethod()
+ {
+ if (! $contact = $this->getContact()) {
return $this->returnError();
}
@@ -810,7 +831,7 @@ class ClientPortalController extends BaseController
$validator = Validator::make(Input::all(), ['source' => 'required']);
if ($validator->fails()) {
- return Redirect::to($client->account->enable_client_portal_dashboard?'/client/dashboard':'/client/payment_methods/');
+ return Redirect::to($client->account->enable_client_portal_dashboard ? '/client/dashboard' : '/client/payment_methods/');
}
$paymentDriver = $account->paymentDriver(false, GATEWAY_TYPE_TOKEN);
@@ -824,7 +845,7 @@ class ClientPortalController extends BaseController
Session::flash('message', trans('texts.payment_method_set_as_default'));
- return redirect()->to($client->account->enable_client_portal_dashboard?'/client/dashboard':'/client/payment_methods/');
+ return redirect()->to($client->account->enable_client_portal_dashboard ? '/client/dashboard' : '/client/payment_methods/');
}
private function paymentMethodError($type, $error, $accountGateway = false, $exception = false)
@@ -839,8 +860,9 @@ class ClientPortalController extends BaseController
Utils::logError("Payment Method Error [{$type}]: " . ($exception ? Utils::getErrorString($exception) : $message), 'PHP', true);
}
- public function setAutoBill(){
- if (!$contact = $this->getContact()) {
+ public function setAutoBill()
+ {
+ if (! $contact = $this->getContact()) {
return $this->returnError();
}
diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php
index b0c144732f6a..8c55a50d0469 100644
--- a/app/Http/Controllers/Controller.php
+++ b/app/Http/Controllers/Controller.php
@@ -1,11 +1,13 @@
-credit_date = Utils::fromSqlDate($credit->credit_date);
- $data = array(
+ $data = [
'client' => $credit->client,
'clientPublicId' => $credit->client->public_id,
'credit' => $credit,
@@ -78,7 +80,7 @@ class CreditController extends BaseController
'url' => 'credits/'.$publicId,
'title' => 'Edit Credit',
'clients' => null,
- );
+ ];
return View::make('credits.edit', $data);
}
diff --git a/app/Http/Controllers/DashboardApiController.php b/app/Http/Controllers/DashboardApiController.php
index 0db08e555010..d87ea271392a 100644
--- a/app/Http/Controllers/DashboardApiController.php
+++ b/app/Http/Controllers/DashboardApiController.php
@@ -1,9 +1,10 @@
-pastDue($accountId, $userId, $viewAll);
$upcoming = $dashboardRepo->upcoming($accountId, $userId, $viewAll);
$payments = $dashboardRepo->payments($accountId, $userId, $viewAll);
- $expenses = $dashboardRepo->expenses($accountId, $userId, $viewAll);
+ $expenses = $dashboardRepo->expenses($account, $userId, $viewAll);
$tasks = $dashboardRepo->tasks($accountId, $userId, $viewAll);
- $showBlueVinePromo = $user->is_admin
+ $showBlueVinePromo = $user->is_admin
&& env('BLUEVINE_PARTNER_UNIQUE_ID')
&& ! $account->company->bluevine_status
- && $account->created_at <= date( 'Y-m-d', strtotime( '-1 month' ));
+ && $account->created_at <= date('Y-m-d', strtotime('-1 month'));
$showWhiteLabelExpired = Utils::isSelfHost() && $account->company->hasExpiredPlan(PLAN_WHITE_LABEL);
@@ -60,8 +59,57 @@ class DashboardController extends BaseController
}
}
- // check if the account has multiple curencies
+ $data = [
+ 'account' => $user->account,
+ 'user' => $user,
+ 'paidToDate' => $paidToDate,
+ 'balances' => $balances,
+ 'averageInvoice' => $averageInvoice,
+ 'invoicesSent' => $metrics ? $metrics->invoices_sent : 0,
+ 'activeClients' => $metrics ? $metrics->active_clients : 0,
+ 'activities' => $activities,
+ 'pastDue' => $pastDue,
+ 'upcoming' => $upcoming,
+ 'payments' => $payments,
+ 'title' => trans('texts.dashboard'),
+ 'hasQuotes' => $hasQuotes,
+ 'showBreadcrumbs' => false,
+ 'currencies' => $this->getCurrencyCodes(),
+ 'expenses' => $expenses,
+ 'tasks' => $tasks,
+ 'showBlueVinePromo' => $showBlueVinePromo,
+ 'showWhiteLabelExpired' => $showWhiteLabelExpired,
+ ];
+
+ if ($showBlueVinePromo) {
+ $usdLast12Months = 0;
+ $pastYear = date('Y-m-d', strtotime('-1 year'));
+ $paidLast12Months = $dashboardRepo->paidToDate($account, $userId, $viewAll, $pastYear);
+
+ foreach ($paidLast12Months as $item) {
+ if ($item->currency_id == null) {
+ $currency = $user->account->currency_id ?: DEFAULT_CURRENCY;
+ } else {
+ $currency = $item->currency_id;
+ }
+
+ if ($currency == CURRENCY_DOLLAR) {
+ $usdLast12Months += $item->value;
+ }
+ }
+
+ $data['usdLast12Months'] = $usdLast12Months;
+ }
+
+ return View::make('dashboard', $data);
+ }
+
+ private function getCurrencyCodes()
+ {
+ $account = Auth::user()->account;
$currencyIds = $account->currency_id ? [$account->currency_id] : [DEFAULT_CURRENCY];
+
+ // get client/invoice currencies
$data = Client::scope()
->withArchived()
->distinct()
@@ -75,54 +123,26 @@ class DashboardController extends BaseController
}
}, $data);
+ // get expense currencies
+ $data = Expense::scope()
+ ->withArchived()
+ ->distinct()
+ ->get(['expense_currency_id'])
+ ->toArray();
+
+ array_map(function ($item) use (&$currencyIds) {
+ $currencyId = intval($item['expense_currency_id']);
+ if ($currencyId && ! in_array($currencyId, $currencyIds)) {
+ $currencyIds[] = $currencyId;
+ }
+ }, $data);
+
$currencies = [];
foreach ($currencyIds as $currencyId) {
$currencies[$currencyId] = Utils::getFromCache($currencyId, 'currencies')->code;
}
- $data = [
- 'account' => $user->account,
- 'user' => $user,
- 'paidToDate' => $paidToDate,
- 'balances' => $balances,
- 'averageInvoice' => $averageInvoice,
- 'invoicesSent' => $metrics ? $metrics->invoices_sent : 0,
- 'activeClients' => $metrics ? $metrics->active_clients : 0,
- 'activities' => $activities,
- 'pastDue' => $pastDue,
- 'upcoming' => $upcoming,
- 'payments' => $payments,
- 'title' => trans('texts.dashboard'),
- 'hasQuotes' => $hasQuotes,
- 'showBreadcrumbs' => false,
- 'currencies' => $currencies,
- 'expenses' => $expenses,
- 'tasks' => $tasks,
- 'showBlueVinePromo' => $showBlueVinePromo,
- 'showWhiteLabelExpired' => $showWhiteLabelExpired,
- ];
-
- if ($showBlueVinePromo) {
- $usdLast12Months = 0;
- $pastYear = date( 'Y-m-d', strtotime( '-1 year' ));
- $paidLast12Months = $dashboardRepo->paidToDate( $account, $userId, $viewAll, $pastYear );
-
- foreach ( $paidLast12Months as $item ) {
- if ( $item->currency_id == null ) {
- $currency = $user->account->currency_id ?: DEFAULT_CURRENCY;
- } else {
- $currency = $item->currency_id;
- }
-
- if ( $currency == CURRENCY_DOLLAR ) {
- $usdLast12Months += $item->value;
- }
- }
-
- $data['usdLast12Months'] = $usdLast12Months;
- }
-
- return View::make('dashboard', $data);
+ return $currencies;
}
public function chartData($groupBy, $startDate, $endDate, $currencyCode, $includeExpenses)
diff --git a/app/Http/Controllers/DocumentAPIController.php b/app/Http/Controllers/DocumentAPIController.php
index b639bb7dda65..fb85331eb1e2 100644
--- a/app/Http/Controllers/DocumentAPIController.php
+++ b/app/Http/Controllers/DocumentAPIController.php
@@ -1,12 +1,14 @@
-listResponse($documents);
-
}
/**
@@ -65,10 +66,11 @@ class DocumentAPIController extends BaseAPIController
{
$document = $request->entity();
- if(array_key_exists($document->type, Document::$types))
+ if (array_key_exists($document->type, Document::$types)) {
return DocumentController::getDownloadResponse($document);
- else
- return $this->errorResponse(['error'=>'Invalid mime type'],400);
+ } else {
+ return $this->errorResponse(['error' => 'Invalid mime type'], 400);
+ }
}
/**
@@ -94,7 +96,6 @@ class DocumentAPIController extends BaseAPIController
*/
public function store(CreateDocumentRequest $request)
{
-
$document = $this->documentRepo->upload($request->all());
return $this->itemResponse($document);
diff --git a/app/Http/Controllers/DocumentController.php b/app/Http/Controllers/DocumentController.php
index f25a027f8662..28a544cb3dc5 100644
--- a/app/Http/Controllers/DocumentController.php
+++ b/app/Http/Controllers/DocumentController.php
@@ -1,13 +1,15 @@
-entity());
}
- public static function getDownloadResponse($document){
+ public static function getDownloadResponse($document)
+ {
$direct_url = $document->getDirectUrl();
- if($direct_url){
+ if ($direct_url) {
return redirect($direct_url);
}
$stream = $document->getStream();
- if($stream){
+ if ($stream) {
$headers = [
- 'Content-Type' => Document::$types[$document->type]['mime'],
- 'Content-Length' => $document->size,
+ 'Content-Type' => Document::$types[$document->type]['mime'],
+ 'Content-Length' => $document->size,
];
- $response = Response::stream(function() use ($stream) {
+ $response = Response::stream(function () use ($stream) {
fpassthru($stream);
}, 200, $headers);
- }
- else{
+ } else {
$response = Response::make($document->getRaw(), 200);
$response->header('content-type', Document::$types[$document->type]['mime']);
}
@@ -56,12 +58,12 @@ class DocumentController extends BaseController
{
$document = $request->entity();
- if(empty($document->preview)){
- return Response::view('error', ['error'=>'Preview does not exist!'], 404);
+ if (empty($document->preview)) {
+ return Response::view('error', ['error' => 'Preview does not exist!'], 404);
}
$direct_url = $document->getDirectPreviewUrl();
- if($direct_url){
+ if ($direct_url) {
return redirect($direct_url);
}
@@ -76,15 +78,15 @@ class DocumentController extends BaseController
{
$document = $request->entity();
- if(substr($name, -3)=='.js'){
+ if (substr($name, -3) == '.js') {
$name = substr($name, 0, -3);
}
- if(!$document->isPDFEmbeddable()){
- return Response::view('error', ['error'=>'Image does not exist!'], 404);
+ if (! $document->isPDFEmbeddable()) {
+ return Response::view('error', ['error' => 'Image does not exist!'], 404);
}
- $content = $document->preview?$document->getRawPreview():$document->getRaw();
+ $content = $document->preview ? $document->getRawPreview() : $document->getRaw();
$content = 'ninjaAddVFSDoc('.json_encode(intval($publicId).'/'.strval($name)).',"'.base64_encode($content).'")';
$response = Response::make($content, 200);
$response->header('content-type', 'text/javascript');
@@ -97,16 +99,16 @@ class DocumentController extends BaseController
{
$result = $this->documentRepo->upload($request->all(), $doc_array);
- if(is_string($result)){
- return Response::json([
+ if (is_string($result)) {
+ return Response::json([
'error' => $result,
- 'code' => 400
+ 'code' => 400,
], 400);
} else {
- return Response::json([
+ return Response::json([
'error' => false,
'document' => $doc_array,
- 'code' => 200
+ 'code' => 200,
], 200);
}
}
diff --git a/app/Http/Controllers/ExpenseApiController.php b/app/Http/Controllers/ExpenseApiController.php
index 2f38a53362de..07bbcb995fce 100644
--- a/app/Http/Controllers/ExpenseApiController.php
+++ b/app/Http/Controllers/ExpenseApiController.php
@@ -1,12 +1,13 @@
-withTrashed()
->with('client', 'invoice', 'vendor', 'expense_category')
- ->orderBy('created_at','desc');
+ ->orderBy('created_at', 'desc');
return $this->listResponse($expenses);
}
@@ -102,6 +103,8 @@ class ExpenseApiController extends BaseAPIController
* description="an ""unexpected"" error"
* )
* )
+ *
+ * @param mixed $publicId
*/
public function update(UpdateExpenseRequest $request, $publicId)
{
@@ -145,8 +148,4 @@ class ExpenseApiController extends BaseAPIController
return $this->itemResponse($expense);
}
-
-
-
-
}
diff --git a/app/Http/Controllers/ExpenseCategoryApiController.php b/app/Http/Controllers/ExpenseCategoryApiController.php
index 1d7515ceed40..cbdcb3f5e1a4 100644
--- a/app/Http/Controllers/ExpenseCategoryApiController.php
+++ b/app/Http/Controllers/ExpenseCategoryApiController.php
@@ -1,13 +1,12 @@
-itemResponse($category);
}
-
/**
* @SWG\Put(
* path="/expense_categories/{expense_category_id}",
diff --git a/app/Http/Controllers/ExpenseCategoryController.php b/app/Http/Controllers/ExpenseCategoryController.php
index ebee16df7c89..6dcbd83b4c32 100644
--- a/app/Http/Controllers/ExpenseCategoryController.php
+++ b/app/Http/Controllers/ExpenseCategoryController.php
@@ -1,15 +1,16 @@
-to('/expense_categories');
}
-
}
diff --git a/app/Http/Controllers/ExpenseController.php b/app/Http/Controllers/ExpenseController.php
index e159b268f22c..d0be38fc8491 100644
--- a/app/Http/Controllers/ExpenseController.php
+++ b/app/Http/Controllers/ExpenseController.php
@@ -1,25 +1,27 @@
- 'javascript:submitAction("add_to_invoice", '.$invoice->public_id.')', 'label' => trans('texts.add_to_invoice', ['invoice' => $invoice->invoice_number])];
}
-
}
$actions[] = \DropdownButton::DIVIDER;
- if (!$expense->trashed()) {
+ if (! $expense->trashed()) {
$actions[] = ['url' => 'javascript:submitAction("archive")', 'label' => trans('texts.archive_expense')];
$actions[] = ['url' => 'javascript:onDeleteClick()', 'label' => trans('texts.delete_expense')];
} else {
@@ -144,7 +145,8 @@ class ExpenseController extends BaseController
/**
* Update the specified resource in storage.
*
- * @param int $id
+ * @param int $id
+ *
* @return Response
*/
public function update(UpdateExpenseRequest $request)
@@ -179,10 +181,9 @@ class ExpenseController extends BaseController
public function bulk()
{
$action = Input::get('action');
- $ids = Input::get('public_id') ? Input::get('public_id') : Input::get('ids');
+ $ids = Input::get('public_id') ? Input::get('public_id') : Input::get('ids');
- switch($action)
- {
+ switch ($action) {
case 'invoice':
case 'add_to_invoice':
$expenses = Expense::scope($ids)->with('client')->get();
@@ -190,26 +191,28 @@ class ExpenseController extends BaseController
$currencyId = null;
// Validate that either all expenses do not have a client or if there is a client, it is the same client
- foreach ($expenses as $expense)
- {
+ foreach ($expenses as $expense) {
if ($expense->client) {
- if (!$clientPublicId) {
+ if (! $clientPublicId) {
$clientPublicId = $expense->client->public_id;
} elseif ($clientPublicId != $expense->client->public_id) {
Session::flash('error', trans('texts.expense_error_multiple_clients'));
+
return Redirect::to('expenses');
}
}
- if (!$currencyId) {
+ if (! $currencyId) {
$currencyId = $expense->invoice_currency_id;
} elseif ($currencyId != $expense->invoice_currency_id && $expense->invoice_currency_id) {
Session::flash('error', trans('texts.expense_error_multiple_currencies'));
+
return Redirect::to('expenses');
}
if ($expense->invoice_id) {
Session::flash('error', trans('texts.expense_error_invoiced'));
+
return Redirect::to('expenses');
}
}
@@ -220,15 +223,15 @@ class ExpenseController extends BaseController
->with('expenses', $ids);
} else {
$invoiceId = Input::get('invoice_id');
+
return Redirect::to("invoices/{$invoiceId}/edit")
->with('expenseCurrencyId', $currencyId)
->with('expenses', $ids);
-
}
break;
default:
- $count = $this->expenseService->bulk($ids, $action);
+ $count = $this->expenseService->bulk($ids, $action);
}
if ($count > 0) {
diff --git a/app/Http/Controllers/ExportController.php b/app/Http/Controllers/ExportController.php
index ed0d1480e12e..9a8e54f59d17 100644
--- a/app/Http/Controllers/ExportController.php
+++ b/app/Http/Controllers/ExportController.php
@@ -1,25 +1,27 @@
-all();
$fields = array_filter(array_map(function ($key) {
- if ( ! in_array($key, ['format', 'include', '_token'])) {
+ if (! in_array($key, ['format', 'include', '_token'])) {
return $key;
} else {
return null;
}
}, array_keys($fields), $fields));
- $fileName = "invoice-ninja-" . join('-', $fields) . "-{$date}";
+ $fileName = 'invoice-ninja-' . implode('-', $fields) . "-{$date}";
}
if ($format === 'JSON') {
@@ -74,17 +76,17 @@ class ExportController extends BaseController
// eager load data, include archived but exclude deleted
$account = Auth::user()->account;
- $account->load(['clients' => function($query) {
+ $account->load(['clients' => function ($query) {
$query->withArchived()
- ->with(['contacts', 'invoices' => function($query) {
+ ->with(['contacts', 'invoices' => function ($query) {
$query->withArchived()
- ->with(['invoice_items', 'payments' => function($query) {
+ ->with(['invoice_items', 'payments' => function ($query) {
$query->withArchived();
}]);
}]);
}]);
- $resource = new Item($account, new AccountTransformer);
+ $resource = new Item($account, new AccountTransformer());
$data = $manager->parseIncludes('clients.invoices.payments')
->createData($resource)
->toArray();
@@ -102,8 +104,8 @@ class ExportController extends BaseController
{
$data = $this->getData($request);
- return Excel::create($fileName, function($excel) use ($data) {
- $excel->sheet('', function($sheet) use ($data) {
+ return Excel::create($fileName, function ($excel) use ($data) {
+ $excel->sheet('', function ($sheet) use ($data) {
$sheet->loadView('export', $data);
});
})->download('csv');
@@ -120,8 +122,7 @@ class ExportController extends BaseController
$user = Auth::user();
$data = $this->getData($request);
- return Excel::create($fileName, function($excel) use ($user, $data) {
-
+ return Excel::create($fileName, function ($excel) use ($user, $data) {
$excel->setTitle($data['title'])
->setCreator($user->getDisplayName())
->setLastModifiedBy($user->getDisplayName())
@@ -140,7 +141,7 @@ class ExportController extends BaseController
$key = 'recurring_invoices';
}
$label = trans("texts.{$key}");
- $excel->sheet($label, function($sheet) use ($key, $data) {
+ $excel->sheet($label, function ($sheet) use ($key, $data) {
if ($key === 'quotes') {
$key = 'invoices';
$data['entityType'] = ENTITY_QUOTE;
@@ -164,7 +165,7 @@ class ExportController extends BaseController
$data = [
'account' => $account,
'title' => 'Invoice Ninja v' . NINJA_VERSION . ' - ' . $account->formatDateTime($account->getDateTime()),
- 'multiUser' => $account->users->count() > 1
+ 'multiUser' => $account->users->count() > 1,
];
if ($request->input('include') === 'all' || $request->input('clients')) {
diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php
index 969dcf84cb2b..7f26529fe06d 100644
--- a/app/Http/Controllers/HomeController.php
+++ b/app/Http/Controllers/HomeController.php
@@ -1,19 +1,21 @@
-with('sign_up', Input::get('sign_up'));
} else {
return View::make('public.invoice_now');
@@ -85,6 +88,7 @@ class HomeController extends BaseController
/**
* @param $userType
* @param $version
+ *
* @return \Illuminate\Http\JsonResponse
*/
public function newsFeed($userType, $version)
@@ -134,9 +138,9 @@ class HomeController extends BaseController
*/
public function contactUs()
{
- Mail::raw(request()->message, function ($message) {
+ Mail::raw(request()->contact_us_message, function ($message) {
$subject = 'Customer Message';
- if ( ! Utils::isNinja()) {
+ if (! Utils::isNinja()) {
$subject .= ': v' . NINJA_VERSION;
}
$message->to(env('CONTACT_EMAIL', 'contact@invoiceninja.com'))
@@ -145,7 +149,6 @@ class HomeController extends BaseController
->subject($subject);
});
- return redirect(Request::server('HTTP_REFERER'))
- ->with('message', trans('texts.contact_us_response'));
+ return RESULT_SUCCESS;
}
}
diff --git a/app/Http/Controllers/ImportController.php b/app/Http/Controllers/ImportController.php
index e5b74453e4e0..6fde46cd1613 100644
--- a/app/Http/Controllers/ImportController.php
+++ b/app/Http/Controllers/ImportController.php
@@ -1,12 +1,14 @@
-importService->mapCSV($files);
+
return View::make('accounts.import_map', ['data' => $data]);
} elseif ($source === IMPORT_JSON) {
$results = $this->importService->importJSON($files[IMPORT_JSON]);
+
return $this->showResult($results);
} else {
$results = $this->importService->importFiles($source, $files);
+
return $this->showResult($results);
}
} catch (Exception $exception) {
Utils::logError($exception);
Session::flash('error', $exception->getMessage());
+
return Redirect::to('/settings/' . ACCOUNT_IMPORT_EXPORT);
}
}
@@ -61,10 +68,12 @@ class ImportController extends BaseController
try {
$results = $this->importService->importCSV($map, $headers);
+
return $this->showResult($results);
} catch (Exception $exception) {
Utils::logError($exception);
Session::flash('error', $exception->getMessage());
+
return Redirect::to('/settings/' . ACCOUNT_IMPORT_EXPORT);
}
}
diff --git a/app/Http/Controllers/IntegrationController.php b/app/Http/Controllers/IntegrationController.php
index cb1a905f3775..1437a215e8a6 100644
--- a/app/Http/Controllers/IntegrationController.php
+++ b/app/Http/Controllers/IntegrationController.php
@@ -1,13 +1,15 @@
-account_id)
->where('event_id', '=', $eventId)->first();
- if (!$subscription) {
+ if (! $subscription) {
$subscription = new Subscription();
$subscription->account_id = Auth::user()->account_id;
$subscription->event_id = $eventId;
@@ -34,7 +36,7 @@ class IntegrationController extends Controller
$subscription->target_url = trim(Input::get('target_url'));
$subscription->save();
- if (!$subscription->id) {
+ if (! $subscription->id) {
return Response::json('Failed to create subscription', 500);
}
diff --git a/app/Http/Controllers/InvoiceApiController.php b/app/Http/Controllers/InvoiceApiController.php
index a10fe91b9946..d310f6f9ee67 100644
--- a/app/Http/Controllers/InvoiceApiController.php
+++ b/app/Http/Controllers/InvoiceApiController.php
@@ -1,24 +1,26 @@
-listResponse($invoices);
}
- /**
- * @SWG\Get(
- * path="/invoices/{invoice_id}",
- * summary="Individual Invoice",
- * tags={"invoice"},
- * @SWG\Response(
- * response=200,
- * description="A single invoice",
- * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Invoice"))
- * ),
- * @SWG\Response(
- * response="default",
- * description="an ""unexpected"" error"
- * )
- * )
- */
-
+ /**
+ * @SWG\Get(
+ * path="/invoices/{invoice_id}",
+ * summary="Individual Invoice",
+ * tags={"invoice"},
+ * @SWG\Response(
+ * response=200,
+ * description="A single invoice",
+ * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Invoice"))
+ * ),
+ * @SWG\Response(
+ * response="default",
+ * description="an ""unexpected"" error"
+ * )
+ * )
+ */
public function show(InvoiceRequest $request)
{
return $this->itemResponse($request->entity());
@@ -113,14 +114,15 @@ class InvoiceApiController extends BaseAPIController
if (isset($data['email'])) {
$email = $data['email'];
- $client = Client::scope()->whereHas('contacts', function($query) use ($email) {
+ $client = Client::scope()->whereHas('contacts', function ($query) use ($email) {
$query->where('email', '=', $email);
})->first();
- if (!$client) {
- $validator = Validator::make(['email'=>$email], ['email' => 'email']);
+ if (! $client) {
+ $validator = Validator::make(['email' => $email], ['email' => 'email']);
if ($validator->fails()) {
$messages = $validator->messages();
+
return $messages->first();
}
@@ -152,7 +154,7 @@ class InvoiceApiController extends BaseAPIController
$client = $this->clientRepo->save($clientData);
}
- } else if (isset($data['client_id'])) {
+ } elseif (isset($data['client_id'])) {
$client = Client::scope($data['client_id'])->firstOrFail();
}
@@ -174,11 +176,11 @@ class InvoiceApiController extends BaseAPIController
if ($invoice->isInvoice()) {
if ($isAutoBill) {
$payment = $this->paymentService->autoBillInvoice($invoice);
- } else if ($isPaid) {
+ } elseif ($isPaid) {
$payment = $this->paymentRepo->save([
'invoice_id' => $invoice->id,
'client_id' => $client->id,
- 'amount' => $data['paid']
+ 'amount' => $data['paid'],
]);
}
}
@@ -187,7 +189,7 @@ class InvoiceApiController extends BaseAPIController
if ($payment) {
app('App\Ninja\Mailers\ContactMailer')->sendPaymentConfirmation($payment);
//$this->dispatch(new SendPaymentEmail($payment));
- } elseif ( ! $invoice->is_recurring) {
+ } elseif (! $invoice->is_recurring) {
app('App\Ninja\Mailers\ContactMailer')->sendInvoice($invoice);
//$this->dispatch(new SendInvoiceEmail($invoice));
}
@@ -223,22 +225,22 @@ class InvoiceApiController extends BaseAPIController
'custom_value2' => 0,
'custom_taxes1' => false,
'custom_taxes2' => false,
- 'partial' => 0
+ 'partial' => 0,
];
- if (!isset($data['invoice_status_id']) || $data['invoice_status_id'] == 0) {
+ if (! isset($data['invoice_status_id']) || $data['invoice_status_id'] == 0) {
$data['invoice_status_id'] = INVOICE_STATUS_DRAFT;
}
- if (!isset($data['invoice_date'])) {
+ if (! isset($data['invoice_date'])) {
$fields['invoice_date_sql'] = date_create()->format('Y-m-d');
}
- if (!isset($data['due_date'])) {
+ if (! isset($data['due_date'])) {
$fields['due_date_sql'] = false;
}
foreach ($fields as $key => $val) {
- if (!isset($data[$key])) {
+ if (! isset($data[$key])) {
$data[$key] = $val;
}
}
@@ -263,7 +265,7 @@ class InvoiceApiController extends BaseAPIController
private function prepareItem($item)
{
// if only the product key is set we'll load the cost and notes
- if (!empty($item['product_key']) && empty($item['cost']) && empty($item['notes'])) {
+ if (! empty($item['product_key']) && empty($item['cost']) && empty($item['notes'])) {
$product = Product::findProductByKey($item['product_key']);
if ($product) {
if (empty($item['cost'])) {
@@ -279,11 +281,11 @@ class InvoiceApiController extends BaseAPIController
'cost' => 0,
'product_key' => '',
'notes' => '',
- 'qty' => 1
+ 'qty' => 1,
];
foreach ($fields as $key => $val) {
- if (!isset($item[$key])) {
+ if (! isset($item[$key])) {
$item[$key] = $val;
}
}
@@ -299,35 +301,39 @@ class InvoiceApiController extends BaseAPIController
$response = json_encode(RESULT_SUCCESS, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders();
+
return Response::make($response, 200, $headers);
}
- /**
- * @SWG\Put(
- * path="/invoices",
- * tags={"invoice"},
- * summary="Update an invoice",
- * @SWG\Parameter(
- * in="body",
- * name="body",
- * @SWG\Schema(ref="#/definitions/Invoice")
- * ),
- * @SWG\Response(
- * response=200,
- * description="Update invoice",
- * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Invoice"))
- * ),
- * @SWG\Response(
- * response="default",
- * description="an ""unexpected"" error"
- * )
- * )
- */
+ /**
+ * @SWG\Put(
+ * path="/invoices",
+ * tags={"invoice"},
+ * summary="Update an invoice",
+ * @SWG\Parameter(
+ * in="body",
+ * name="body",
+ * @SWG\Schema(ref="#/definitions/Invoice")
+ * ),
+ * @SWG\Response(
+ * response=200,
+ * description="Update invoice",
+ * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Invoice"))
+ * ),
+ * @SWG\Response(
+ * response="default",
+ * description="an ""unexpected"" error"
+ * )
+ * )
+ *
+ * @param mixed $publicId
+ */
public function update(UpdateInvoiceAPIRequest $request, $publicId)
{
if ($request->action == ACTION_CONVERT) {
$quote = $request->entity();
$invoice = $this->invoiceRepo->cloneInvoice($quote, $quote->id);
+
return $this->itemResponse($invoice);
} elseif ($request->action) {
return $this->handleAction($request);
@@ -344,28 +350,27 @@ class InvoiceApiController extends BaseAPIController
return $this->itemResponse($invoice);
}
- /**
- * @SWG\Delete(
- * path="/invoices",
- * tags={"invoice"},
- * summary="Delete an invoice",
- * @SWG\Parameter(
- * in="body",
- * name="body",
- * @SWG\Schema(ref="#/definitions/Invoice")
- * ),
- * @SWG\Response(
- * response=200,
- * description="Delete invoice",
- * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Invoice"))
- * ),
- * @SWG\Response(
- * response="default",
- * description="an ""unexpected"" error"
- * )
- * )
- */
-
+ /**
+ * @SWG\Delete(
+ * path="/invoices",
+ * tags={"invoice"},
+ * summary="Delete an invoice",
+ * @SWG\Parameter(
+ * in="body",
+ * name="body",
+ * @SWG\Schema(ref="#/definitions/Invoice")
+ * ),
+ * @SWG\Response(
+ * response=200,
+ * description="Delete invoice",
+ * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Invoice"))
+ * ),
+ * @SWG\Response(
+ * response="default",
+ * description="an ""unexpected"" error"
+ * )
+ * )
+ */
public function destroy(UpdateInvoiceAPIRequest $request)
{
$invoice = $request->entity();
diff --git a/app/Http/Controllers/InvoiceController.php b/app/Http/Controllers/InvoiceController.php
index 2f46ff2d60dc..6a65c5e638c0 100644
--- a/app/Http/Controllers/InvoiceController.php
+++ b/app/Http/Controllers/InvoiceController.php
@@ -1,34 +1,36 @@
-balance = $invoice->amount;
$invoice->invoice_status_id = 0;
$invoice->invoice_date = date_create()->format('Y-m-d');
+ $invoice->deleted_at = null;
$method = 'POST';
$url = "{$entityType}s";
} else {
@@ -111,7 +114,7 @@ class InvoiceController extends BaseController
}
$invoice->invoice_date = Utils::fromSqlDate($invoice->invoice_date);
- $invoice->recurring_due_date = $invoice->due_date;// Keep in SQL form
+ $invoice->recurring_due_date = $invoice->due_date; // Keep in SQL form
$invoice->due_date = Utils::fromSqlDate($invoice->due_date);
$invoice->start_date = Utils::fromSqlDate($invoice->start_date);
$invoice->end_date = Utils::fromSqlDate($invoice->end_date);
@@ -124,7 +127,7 @@ class InvoiceController extends BaseController
$lastSent = ($invoice->is_recurring && $invoice->last_sent_date) ? $invoice->recurring_invoices->last() : null;
- if(!Auth::user()->hasPermission('view_all')){
+ if (! Auth::user()->hasPermission('view_all')) {
$clients = $clients->where('clients.user_id', '=', Auth::user()->id);
}
@@ -139,10 +142,10 @@ class InvoiceController extends BaseController
'title' => trans("texts.edit_{$entityType}"),
'client' => $invoice->client,
'isRecurring' => $invoice->is_recurring,
- 'lastSent' => $lastSent];
+ 'lastSent' => $lastSent, ];
$data = array_merge($data, self::getViewModel($invoice));
- if ($invoice->isSent() && $invoice->getAutoBillEnabled() && !$invoice->isPaid()) {
+ if ($invoice->isSent() && $invoice->getAutoBillEnabled() && ! $invoice->isPaid()) {
$data['autoBillChangeWarning'] = $invoice->client->autoBillLater();
}
@@ -151,7 +154,7 @@ class InvoiceController extends BaseController
}
// Set the invitation data on the client's contacts
- if ( ! $clone) {
+ if (! $clone) {
$clients = $data['clients'];
foreach ($clients as $client) {
if ($client->id != $invoice->client->id) {
@@ -193,7 +196,7 @@ class InvoiceController extends BaseController
$invoice->public_id = 0;
$clients = Client::scope()->with('contacts', 'country')->orderBy('name');
- if (!Auth::user()->hasPermission('view_all')) {
+ if (! Auth::user()->hasPermission('view_all')) {
$clients = $clients->where('clients.user_id', '=', Auth::user()->id);
}
@@ -217,6 +220,8 @@ class InvoiceController extends BaseController
private static function getViewModel($invoice)
{
+ $account = Auth::user()->account;
+
$recurringHelp = '';
$recurringDueDateHelp = '';
$recurringDueDates = [];
@@ -246,19 +251,21 @@ class InvoiceController extends BaseController
trans('texts.use_client_terms') => ['value' => '', 'class' => 'monthly weekly'],
];
- $ends = ['th','st','nd','rd','th','th','th','th','th','th'];
- for($i = 1; $i < 31; $i++){
- if ($i >= 11 && $i <= 13) $ordinal = $i. 'th';
- else $ordinal = $i . $ends[$i % 10];
+ $ends = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'];
+ for ($i = 1; $i < 31; $i++) {
+ if ($i >= 11 && $i <= 13) {
+ $ordinal = $i. 'th';
+ } else {
+ $ordinal = $i . $ends[$i % 10];
+ }
$dayStr = str_pad($i, 2, '0', STR_PAD_LEFT);
- $str = trans('texts.day_of_month', ['ordinal'=>$ordinal]);
+ $str = trans('texts.day_of_month', ['ordinal' => $ordinal]);
$recurringDueDates[$str] = ['value' => "1998-01-$dayStr", 'data-num' => $i, 'class' => 'monthly'];
}
$recurringDueDates[trans('texts.last_day_of_month')] = ['value' => '1998-01-31', 'data-num' => 31, 'class' => 'monthly'];
-
$daysOfWeek = [
trans('texts.sunday'),
trans('texts.monday'),
@@ -268,35 +275,16 @@ class InvoiceController extends BaseController
trans('texts.friday'),
trans('texts.saturday'),
];
- foreach(['1st','2nd','3rd','4th'] as $i=>$ordinal){
- foreach($daysOfWeek as $j=>$dayOfWeek){
+ foreach (['1st', '2nd', '3rd', '4th'] as $i => $ordinal) {
+ foreach ($daysOfWeek as $j => $dayOfWeek) {
$str = trans('texts.day_of_week_after', ['ordinal' => $ordinal, 'day' => $dayOfWeek]);
- $day = $i * 7 + $j + 1;
+ $day = $i * 7 + $j + 1;
$dayStr = str_pad($day, 2, '0', STR_PAD_LEFT);
$recurringDueDates[$str] = ['value' => "1998-02-$dayStr", 'data-num' => $day, 'class' => 'weekly'];
}
}
- // Tax rate $options
- $account = Auth::user()->account;
- $rates = TaxRate::scope()->orderBy('name')->get();
- $options = [];
- $defaultTax = false;
-
- foreach ($rates as $rate) {
- $name = $rate->name . ' ' . ($rate->rate+0) . '%';
- if ($rate->is_inclusive) {
- $name .= ' - ' . trans('texts.inclusive');
- }
- $options[($rate->is_inclusive ? '1 ' : '0 ') . $rate->rate . ' ' . $rate->name] = $name;
-
- // load default invoice tax
- if ($rate->id == $account->default_tax_rate_id) {
- $defaultTax = $rate;
- }
- }
-
// Check for any taxes which have been deleted
if ($invoice->exists) {
foreach ($invoice->getTaxes() as $key => $rate) {
@@ -311,22 +299,13 @@ class InvoiceController extends BaseController
'data' => Input::old('data'),
'account' => Auth::user()->account->load('country'),
'products' => Product::scope()->with('default_tax_rate')->orderBy('product_key')->get(),
- 'taxRateOptions' => $options,
- 'defaultTax' => $defaultTax,
+ 'taxRateOptions' => $account->present()->taxRateOptions,
+ 'defaultTax' => $account->default_tax_rate,
'currencies' => Cache::get('currencies'),
'sizes' => Cache::get('sizes'),
- 'paymentTerms' => Cache::get('paymentTerms'),
'invoiceDesigns' => InvoiceDesign::getDesigns(),
'invoiceFonts' => Cache::get('fonts'),
- 'frequencies' => [
- 1 => trans('texts.freq_weekly'),
- 2 => trans('texts.freq_two_weeks'),
- 3 => trans('texts.freq_four_weeks'),
- 4 => trans('texts.freq_monthly'),
- 5 => trans('texts.freq_three_months'),
- 6 => trans('texts.freq_six_months'),
- 7 => trans('texts.freq_annually'),
- ],
+ 'frequencies' => \App\Models\Frequency::selectOptions(),
'recurringDueDates' => $recurringDueDates,
'recurringHelp' => $recurringHelp,
'recurringDueDateHelp' => $recurringDueDateHelp,
@@ -335,7 +314,6 @@ class InvoiceController extends BaseController
'expenseCurrencyId' => Session::get('expenseCurrencyId') ?: null,
'expenses' => Session::get('expenses') ? Expense::scope(Session::get('expenses'))->with('documents', 'expense_category')->get() : [],
];
-
}
/**
@@ -364,7 +342,7 @@ class InvoiceController extends BaseController
Session::flash('message', $message);
if ($action == 'email') {
- $this->emailInvoice($invoice, Input::get('pdfupload'));
+ $this->emailInvoice($invoice);
}
return url($invoice->getRoute());
@@ -373,7 +351,8 @@ class InvoiceController extends BaseController
/**
* Update the specified resource in storage.
*
- * @param int $id
+ * @param int $id
+ *
* @return Response
*/
public function update(UpdateInvoiceRequest $request)
@@ -394,34 +373,36 @@ class InvoiceController extends BaseController
} elseif ($action == 'convert') {
return $this->convertQuote($request, $invoice->public_id);
} elseif ($action == 'email') {
- $this->emailInvoice($invoice, Input::get('pdfupload'));
+ $this->emailInvoice($invoice);
}
return url($invoice->getRoute());
}
-
- private function emailInvoice($invoice, $pdfUpload)
+ private function emailInvoice($invoice)
{
+ $reminder = Input::get('reminder');
+ $template = Input::get('template');
+ $pdfUpload = Utils::decodePDF(Input::get('pdfupload'));
$entityType = $invoice->getEntityType();
- $pdfUpload = Utils::decodePDF($pdfUpload);
- if (!Auth::user()->confirmed) {
+ if (filter_var(Input::get('save_as_default'), FILTER_VALIDATE_BOOLEAN)) {
+ $account = Auth::user()->account;
+ $account->setTemplateDefaults(Input::get('template_type'), $template['subject'], $template['body']);
+ }
+
+ if (! Auth::user()->confirmed) {
$errorMessage = trans(Auth::user()->registered ? 'texts.confirmation_required' : 'texts.registration_required');
Session::flash('error', $errorMessage);
+
return Redirect::to('invoices/'.$invoice->public_id.'/edit');
}
if ($invoice->is_recurring) {
$response = $this->emailRecurringInvoice($invoice);
} else {
- // TODO remove this with Laravel 5.3 (https://github.com/invoiceninja/invoiceninja/issues/1303)
- if (config('queue.default') === 'sync') {
- $response = app('App\Ninja\Mailers\ContactMailer')->sendInvoice($invoice, false, $pdfUpload);
- } else {
- $this->dispatch(new SendInvoiceEmail($invoice, false, $pdfUpload));
- $response = true;
- }
+ $this->dispatch(new SendInvoiceEmail($invoice, $reminder, $pdfUpload, $template));
+ $response = true;
}
if ($response === true) {
@@ -434,10 +415,11 @@ class InvoiceController extends BaseController
private function emailRecurringInvoice(&$invoice)
{
- if (!$invoice->shouldSendToday()) {
+ if (! $invoice->shouldSendToday()) {
if ($date = $invoice->getNextSendDate()) {
$date = $invoice->account->formatDate($date);
$date .= ' ' . DEFAULT_SEND_RECURRING_HOUR . ':00 am ' . $invoice->account->getTimezone();
+
return trans('texts.recurring_too_soon', ['date' => $date]);
} else {
return trans('texts.no_longer_running');
@@ -464,7 +446,9 @@ class InvoiceController extends BaseController
/**
* Display the specified resource.
*
- * @param int $id
+ * @param int $id
+ * @param mixed $publicId
+ *
* @return Response
*/
public function show($publicId)
@@ -477,12 +461,15 @@ class InvoiceController extends BaseController
/**
* Remove the specified resource from storage.
*
- * @param int $id
+ * @param int $id
+ * @param mixed $entityType
+ *
* @return Response
*/
public function bulk($entityType = ENTITY_INVOICE)
{
- $action = Input::get('bulk_action') ?: Input::get('action');;
+ $action = Input::get('bulk_action') ?: Input::get('action');
+ ;
$ids = Input::get('bulk_public_id') ?: (Input::get('public_id') ?: Input::get('ids'));
$count = $this->invoiceService->bulk($ids, $action);
@@ -569,7 +556,7 @@ class InvoiceController extends BaseController
}
// Show the current version as the last in the history
- if ( ! $paymentId) {
+ if (! $paymentId) {
$versionsSelect[$lastId] = Utils::timestampToDateTimeString(strtotime($invoice->created_at)) . ' - ' . $invoice->user->getDisplayName();
}
@@ -601,5 +588,4 @@ class InvoiceController extends BaseController
return $count ? RESULT_FAILURE : RESULT_SUCCESS;
}
-
}
diff --git a/app/Http/Controllers/NinjaController.php b/app/Http/Controllers/NinjaController.php
index cab57f9da2b5..3dce07391e98 100644
--- a/app/Http/Controllers/NinjaController.php
+++ b/app/Http/Controllers/NinjaController.php
@@ -1,20 +1,22 @@
- $input['city'],
'shippingState' => $input['state'],
'shippingPostcode' => $input['postal_code'],
- 'shippingCountry' => $country->iso_3166_2
+ 'shippingCountry' => $country->iso_3166_2,
];
$card = new CreditCard($data);
@@ -79,7 +81,7 @@ class NinjaController extends BaseController
'card' => $card,
'currency' => 'USD',
'returnUrl' => URL::to('license_complete'),
- 'cancelUrl' => URL::to('/')
+ 'cancelUrl' => URL::to('/'),
];
}
@@ -100,11 +102,11 @@ class NinjaController extends BaseController
if (Input::has('product_id')) {
Session::set('product_id', Input::get('product_id'));
- } else if (!Session::has('product_id')) {
+ } elseif (! Session::has('product_id')) {
Session::set('product_id', PRODUCT_ONE_CLICK_INSTALL);
}
- if (!Session::get('affiliate_id')) {
+ if (! Session::get('affiliate_id')) {
return Utils::fatalError();
}
@@ -190,8 +192,9 @@ class NinjaController extends BaseController
$ref = $response->getTransactionReference();
- if (!$response->isSuccessful() || !$ref) {
+ if (! $response->isSuccessful() || ! $ref) {
$this->error('License', $response->getMessage(), $accountGateway);
+
return redirect()->to('license')->withInput();
}
}
@@ -227,6 +230,7 @@ class NinjaController extends BaseController
return View::make('public.license', $data);
} catch (\Exception $e) {
$this->error('License-Uncaught', false, $accountGateway, $e);
+
return redirect()->to('license')->withInput();
}
}
@@ -284,6 +288,6 @@ class NinjaController extends BaseController
$company->plan = null;
$company->save();
- return RESULT_SUCCESS;
- }
+ return RESULT_SUCCESS;
+ }
}
diff --git a/app/Http/Controllers/OnlinePaymentController.php b/app/Http/Controllers/OnlinePaymentController.php
index ae596b89eaa7..e25defd2a0d2 100644
--- a/app/Http/Controllers/OnlinePaymentController.php
+++ b/app/Http/Controllers/OnlinePaymentController.php
@@ -1,30 +1,32 @@
-invoiceRepo->findInvoiceByInvitation($invitationKey)) {
+ if (! $invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) {
return response()->view('error', [
'error' => trans('texts.invoice_not_found'),
'hideHeader' => true,
]);
}
- if ( ! $invitation->invoice->canBePaid()) {
+ if (! $invitation->invoice->canBePaid()) {
return redirect()->to('view/' . $invitation->invitation_key);
}
@@ -84,7 +88,7 @@ class OnlinePaymentController extends BaseController
$account->loadLocalizationSettings($invitation->invoice->client);
- if ( ! $gatewayTypeAlias) {
+ if (! $gatewayTypeAlias) {
$gatewayTypeId = Session::get($invitation->id . 'gateway_type');
} elseif ($gatewayTypeAlias != GATEWAY_TYPE_TOKEN) {
$gatewayTypeId = GatewayType::getIdFromAlias($gatewayTypeAlias);
@@ -103,6 +107,7 @@ class OnlinePaymentController extends BaseController
/**
* @param CreateOnlinePaymentRequest $request
+ *
* @return \Illuminate\Http\RedirectResponse
*/
public function doPayment(CreateOnlinePaymentRequest $request)
@@ -111,7 +116,7 @@ class OnlinePaymentController extends BaseController
$gatewayTypeId = Session::get($invitation->id . 'gateway_type');
$paymentDriver = $invitation->account->paymentDriver($invitation, $gatewayTypeId);
- if ( ! $invitation->invoice->canBePaid()) {
+ if (! $invitation->invoice->canBePaid()) {
return redirect()->to('view/' . $invitation->invitation_key);
}
@@ -131,8 +136,9 @@ class OnlinePaymentController extends BaseController
}
/**
- * @param bool $invitationKey
+ * @param bool $invitationKey
* @param mixed $gatewayTypeAlias
+ *
* @return \Illuminate\Http\RedirectResponse
*/
public function offsitePayment($invitationKey = false, $gatewayTypeAlias = false)
@@ -141,7 +147,7 @@ class OnlinePaymentController extends BaseController
$invitation = Invitation::with('invoice.invoice_items', 'invoice.client.currency', 'invoice.client.account.account_gateways.gateway')
->where('invitation_key', '=', $invitationKey)->firstOrFail();
- if ( ! $gatewayTypeAlias) {
+ if (! $gatewayTypeAlias) {
$gatewayTypeId = Session::get($invitation->id . 'gateway_type');
} elseif ($gatewayTypeAlias != GATEWAY_TYPE_TOKEN) {
$gatewayTypeId = GatewayType::getIdFromAlias($gatewayTypeAlias);
@@ -159,6 +165,7 @@ class OnlinePaymentController extends BaseController
if ($paymentDriver->completeOffsitePurchase(Input::all())) {
Session::flash('message', trans('texts.applied_payment'));
}
+
return $this->completePurchase($invitation, true);
} catch (Exception $exception) {
return $this->error($paymentDriver, $exception);
@@ -169,6 +176,7 @@ class OnlinePaymentController extends BaseController
{
if ($redirectUrl = session('redirect_url:' . $invitation->invitation_key)) {
$separator = strpos($redirectUrl, '?') === false ? '?' : '&';
+
return redirect()->to($redirectUrl . $separator . 'invoice_id=' . $invitation->invoice->public_id);
} else {
// Allow redirecting to iFrame for offsite payments
@@ -184,6 +192,7 @@ class OnlinePaymentController extends BaseController
* @param $paymentDriver
* @param $exception
* @param bool $showPayment
+ *
* @return \Illuminate\Http\RedirectResponse
*/
private function error($paymentDriver, $exception, $showPayment = false)
@@ -203,15 +212,18 @@ class OnlinePaymentController extends BaseController
Utils::logError($message, 'PHP', true);
$route = $showPayment ? 'payment/' : 'view/';
+
return redirect()->to($route . $paymentDriver->invitation->invitation_key);
}
/**
* @param $routingNumber
+ *
* @return \Illuminate\Http\JsonResponse
*/
- public function getBankInfo($routingNumber) {
- if (strlen($routingNumber) != 9 || !preg_match('/\d{9}/', $routingNumber)) {
+ public function getBankInfo($routingNumber)
+ {
+ if (strlen($routingNumber) != 9 || ! preg_match('/\d{9}/', $routingNumber)) {
return response()->json([
'message' => 'Invalid routing number',
], 400);
@@ -223,7 +235,7 @@ class OnlinePaymentController extends BaseController
return response()->json([
'message' => $data,
], 500);
- } elseif (!empty($data)) {
+ } elseif (! empty($data)) {
return response()->json($data);
}
@@ -235,6 +247,7 @@ class OnlinePaymentController extends BaseController
/**
* @param $accountKey
* @param $gatewayId
+ *
* @return \Illuminate\Http\JsonResponse
*/
public function handlePaymentWebhook($accountKey, $gatewayId)
@@ -243,7 +256,7 @@ class OnlinePaymentController extends BaseController
$account = Account::where('accounts.account_key', '=', $accountKey)->first();
- if (!$account) {
+ if (! $account) {
return response()->json([
'message' => 'Unknown account',
], 404);
@@ -251,7 +264,7 @@ class OnlinePaymentController extends BaseController
$accountGateway = $account->getGatewayConfig(intval($gatewayId));
- if (!$accountGateway) {
+ if (! $accountGateway) {
return response()->json([
'message' => 'Unknown gateway',
], 404);
@@ -261,9 +274,11 @@ class OnlinePaymentController extends BaseController
try {
$result = $paymentDriver->handleWebHook(Input::all());
+
return response()->json(['message' => $result]);
} catch (Exception $exception) {
Utils::logError($exception->getMessage(), 'PHP');
+
return response()->json(['message' => $exception->getMessage()], 500);
}
}
@@ -278,14 +293,14 @@ class OnlinePaymentController extends BaseController
$redirectUrl = Input::get('redirect_url');
$failureUrl = URL::previous();
- if ( ! $account || ! $account->enable_buy_now_buttons || ! $account->hasFeature(FEATURE_BUY_NOW_BUTTONS)) {
+ if (! $account || ! $account->enable_buy_now_buttons || ! $account->hasFeature(FEATURE_BUY_NOW_BUTTONS)) {
return redirect()->to("{$failureUrl}/?error=invalid account");
}
Auth::onceUsingId($account->users[0]->id);
$product = Product::scope(Input::get('product_id'))->first();
- if ( ! $product) {
+ if (! $product) {
return redirect()->to("{$failureUrl}/?error=invalid product");
}
@@ -296,7 +311,7 @@ class OnlinePaymentController extends BaseController
$query->where('contact_key', $contactKey);
})->first();
}
- if ( ! $client) {
+ if (! $client) {
$rules = [
'first_name' => 'string|max:100',
'last_name' => 'string|max:100',
@@ -310,13 +325,18 @@ class OnlinePaymentController extends BaseController
$data = [
'currency_id' => $account->currency_id,
- 'contact' => Input::all()
+ 'contact' => Input::all(),
];
$client = $clientRepo->save($data);
}
$data = [
'client_id' => $client->id,
+ 'is_public' => true,
+ 'is_recurring' => filter_var(Input::get('is_recurring'), FILTER_VALIDATE_BOOLEAN),
+ 'frequency_id' => Input::get('frequency_id'),
+ 'auto_bill_id' => Input::get('auto_bill_id'),
+ 'start_date' => Input::get('start_date', date('Y-m-d')),
'tax_rate1' => $account->default_tax_rate ? $account->default_tax_rate->rate : 0,
'tax_name1' => $account->default_tax_rate ? $account->default_tax_rate->name : '',
'invoice_items' => [[
@@ -326,9 +346,12 @@ class OnlinePaymentController extends BaseController
'qty' => 1,
'tax_rate1' => $product->default_tax_rate ? $product->default_tax_rate->rate : 0,
'tax_name1' => $product->default_tax_rate ? $product->default_tax_rate->name : '',
- ]]
+ ]],
];
$invoice = $invoiceService->save($data);
+ if ($invoice->is_recurring) {
+ $invoice = $this->invoiceRepo->createRecurringInvoice($invoice->fresh());
+ }
$invitation = $invoice->invitations[0];
$link = $invitation->getLink();
diff --git a/app/Http/Controllers/PaymentApiController.php b/app/Http/Controllers/PaymentApiController.php
index 4daad26d0d88..207177e1747c 100644
--- a/app/Http/Controllers/PaymentApiController.php
+++ b/app/Http/Controllers/PaymentApiController.php
@@ -1,13 +1,15 @@
-action) {
@@ -84,7 +87,6 @@ class PaymentApiController extends BaseAPIController
return $this->itemResponse($payment);
}
-
/**
* @SWG\Post(
* path="/payments",
@@ -121,27 +123,26 @@ class PaymentApiController extends BaseAPIController
}
/**
- * @SWG\Delete(
- * path="/payments/{payment_id}",
- * summary="Delete a payment",
- * tags={"payment"},
- * @SWG\Parameter(
- * in="body",
- * name="body",
- * @SWG\Schema(ref="#/definitions/Payment")
- * ),
- * @SWG\Response(
- * response=200,
- * description="Delete payment",
- * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Payment"))
- * ),
- * @SWG\Response(
- * response="default",
- * description="an ""unexpected"" error"
- * )
- * )
- */
-
+ * @SWG\Delete(
+ * path="/payments/{payment_id}",
+ * summary="Delete a payment",
+ * tags={"payment"},
+ * @SWG\Parameter(
+ * in="body",
+ * name="body",
+ * @SWG\Schema(ref="#/definitions/Payment")
+ * ),
+ * @SWG\Response(
+ * response=200,
+ * description="Delete payment",
+ * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Payment"))
+ * ),
+ * @SWG\Response(
+ * response="default",
+ * description="an ""unexpected"" error"
+ * )
+ * )
+ */
public function destroy(UpdatePaymentRequest $request)
{
$payment = $request->entity();
@@ -150,5 +151,4 @@ class PaymentApiController extends BaseAPIController
return $this->itemResponse($payment);
}
-
}
diff --git a/app/Http/Controllers/PaymentController.php b/app/Http/Controllers/PaymentController.php
index bcb244f1e21d..3597c3f47734 100644
--- a/app/Http/Controllers/PaymentController.php
+++ b/app/Http/Controllers/PaymentController.php
@@ -1,20 +1,23 @@
-paymentRepo = $paymentRepo;
$this->contactMailer = $contactMailer;
$this->paymentService = $paymentService;
@@ -70,6 +72,7 @@ class PaymentController extends BaseController
/**
* @param null $clientPublicId
+ *
* @return \Illuminate\Http\JsonResponse
*/
public function getDatatable($clientPublicId = null)
@@ -79,6 +82,7 @@ class PaymentController extends BaseController
/**
* @param PaymentRequest $request
+ *
* @return \Illuminate\Contracts\View\View
*/
public function create(PaymentRequest $request)
@@ -90,6 +94,7 @@ class PaymentController extends BaseController
->orderBy('invoice_number')->get();
$data = [
+ 'account' => Auth::user()->account,
'clientPublicId' => Input::old('client') ? Input::old('client') : ($request->client_id ?: 0),
'invoicePublicId' => Input::old('invoice') ? Input::old('invoice') : ($request->invoice_id ?: 0),
'invoice' => null,
@@ -106,6 +111,7 @@ class PaymentController extends BaseController
/**
* @param $publicId
+ *
* @return \Illuminate\Http\RedirectResponse
*/
public function show($publicId)
@@ -117,6 +123,7 @@ class PaymentController extends BaseController
/**
* @param PaymentRequest $request
+ *
* @return \Illuminate\Contracts\View\View
*/
public function edit(PaymentRequest $request)
@@ -129,8 +136,13 @@ class PaymentController extends BaseController
$actions[] = ['url' => url("/invoices/invoice_history/{$payment->invoice->public_id}?payment_id={$payment->public_id}"), 'label' => trans('texts.view_invoice')];
}
$actions[] = ['url' => url("/invoices/{$payment->invoice->public_id}/edit"), 'label' => trans('texts.edit_invoice')];
+
+ if ($payment->canBeRefunded()) {
+ $actions[] = ['url' => "javascript:showRefundModal({$payment->public_id}, \"{$payment->getCompletedAmount()}\", \"{$payment->present()->completedAmount}\", \"{$payment->present()->currencySymbol}\")", 'label' => trans('texts.refund_payment')];
+ }
+
$actions[] = DropdownButton::DIVIDER;
- if ( ! $payment->trashed()) {
+ if (! $payment->trashed()) {
$actions[] = ['url' => 'javascript:submitAction("archive")', 'label' => trans('texts.archive_payment')];
$actions[] = ['url' => 'javascript:onDeleteClick()', 'label' => trans('texts.delete_payment')];
} else {
@@ -138,6 +150,7 @@ class PaymentController extends BaseController
}
$data = [
+ 'account' => Auth::user()->account,
'client' => null,
'invoice' => null,
'invoices' => Invoice::scope()
@@ -160,6 +173,7 @@ class PaymentController extends BaseController
/**
* @param CreatePaymentRequest $request
+ *
* @return \Illuminate\Http\RedirectResponse
*/
public function store(CreatePaymentRequest $request)
@@ -184,11 +198,12 @@ class PaymentController extends BaseController
/**
* @param UpdatePaymentRequest $request
+ *
* @return \Illuminate\Http\RedirectResponse
*/
public function update(UpdatePaymentRequest $request)
{
- if (in_array($request->action, ['archive', 'delete', 'restore'])) {
+ if (in_array($request->action, ['archive', 'delete', 'restore', 'refund'])) {
return self::bulk();
}
@@ -207,10 +222,10 @@ class PaymentController extends BaseController
$action = Input::get('action');
$amount = Input::get('amount');
$ids = Input::get('public_id') ? Input::get('public_id') : Input::get('ids');
- $count = $this->paymentService->bulk($ids, $action, ['amount'=>$amount]);
+ $count = $this->paymentService->bulk($ids, $action, ['amount' => $amount]);
if ($count > 0) {
- $message = Utils::pluralize($action=='refund' ? 'refunded_payment':$action.'d_payment', $count);
+ $message = Utils::pluralize($action == 'refund' ? 'refunded_payment' : $action.'d_payment', $count);
Session::flash('message', $message);
}
diff --git a/app/Http/Controllers/PaymentTermController.php b/app/Http/Controllers/PaymentTermController.php
index 30f3c5bf42d7..e92e53035675 100644
--- a/app/Http/Controllers/PaymentTermController.php
+++ b/app/Http/Controllers/PaymentTermController.php
@@ -1,13 +1,16 @@
-paymentTermService->getDatatable();
+ $accountId = Auth::user()->account_id;
+
+ return $this->paymentTermService->getDatatable($accountId);
}
/**
* @param $publicId
+ *
* @return \Illuminate\Contracts\View\View
*/
public function edit($publicId)
@@ -84,6 +91,7 @@ class PaymentTermController extends BaseController
/**
* @param $publicId
+ *
* @return \Illuminate\Http\RedirectResponse
*/
public function update($publicId)
@@ -93,6 +101,7 @@ class PaymentTermController extends BaseController
/**
* @param bool $publicId
+ *
* @return \Illuminate\Http\RedirectResponse
*/
private function save($publicId = false)
@@ -103,8 +112,8 @@ class PaymentTermController extends BaseController
$paymentTerm = PaymentTerm::createNew();
}
- $paymentTerm->name = trim(Input::get('name'));
- $paymentTerm->num_days = Utils::parseInt(Input::get('num_days'));
+ $paymentTerm->num_days = Utils::parseInt(Input::get('num_days'));
+ $paymentTerm->name = 'Net ' . $paymentTerm->num_days;
$paymentTerm->save();
$message = $publicId ? trans('texts.updated_payment_term') : trans('texts.created_payment_term');
@@ -119,12 +128,11 @@ class PaymentTermController extends BaseController
public function bulk()
{
$action = Input::get('bulk_action');
- $ids = Input::get('bulk_public_id');
- $count = $this->paymentTermService->bulk($ids, $action);
+ $ids = Input::get('bulk_public_id');
+ $count = $this->paymentTermService->bulk($ids, $action);
Session::flash('message', trans('texts.archived_payment_term'));
return Redirect::to('settings/' . ACCOUNT_PAYMENT_TERMS);
}
-
}
diff --git a/app/Http/Controllers/ProductApiController.php b/app/Http/Controllers/ProductApiController.php
index f0a0b8af43e4..9dc5915d90de 100644
--- a/app/Http/Controllers/ProductApiController.php
+++ b/app/Http/Controllers/ProductApiController.php
@@ -1,12 +1,14 @@
-product_key = trim(Input::get('product_key'));
$product->notes = trim(Input::get('notes'));
$product->cost = trim(Input::get('cost'));
- $product->default_tax_rate_id = Input::get('default_tax_rate_id');
-
+ $product->fill(Input::all());
$product->save();
$message = $productPublicId ? trans('texts.updated_product') : trans('texts.created_product');
diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php
index 9e43e2c63918..fc96d98594dd 100644
--- a/app/Http/Controllers/ProjectController.php
+++ b/app/Http/Controllers/ProjectController.php
@@ -1,17 +1,18 @@
-to('/projects');
}
-
}
diff --git a/app/Http/Controllers/QuoteApiController.php b/app/Http/Controllers/QuoteApiController.php
index d6c572ceb08e..959bc8281b35 100644
--- a/app/Http/Controllers/QuoteApiController.php
+++ b/app/Http/Controllers/QuoteApiController.php
@@ -1,8 +1,10 @@
-invoiceRepo = $invoiceRepo;
}
- /**
- * @SWG\Get(
- * path="/quotes",
- * tags={"quote"},
- * summary="List of quotes",
- * @SWG\Response(
- * response=200,
- * description="A list with quotes",
- * @SWG\Schema(type="array", @SWG\Items(ref="#/definitions/Invoice"))
- * ),
- * @SWG\Response(
- * response="default",
- * description="an ""unexpected"" error"
- * )
- * )
- */
+ /**
+ * @SWG\Get(
+ * path="/quotes",
+ * tags={"quote"},
+ * summary="List of quotes",
+ * @SWG\Response(
+ * response=200,
+ * description="A list with quotes",
+ * @SWG\Schema(type="array", @SWG\Items(ref="#/definitions/Invoice"))
+ * ),
+ * @SWG\Response(
+ * response="default",
+ * description="an ""unexpected"" error"
+ * )
+ * )
+ */
public function index()
{
$invoices = Invoice::scope()
@@ -43,5 +45,4 @@ class QuoteApiController extends BaseAPIController
return $this->listResponse($invoices);
}
-
}
diff --git a/app/Http/Controllers/QuoteController.php b/app/Http/Controllers/QuoteController.php
index 5fb20cde8559..c02e54672daa 100644
--- a/app/Http/Controllers/QuoteController.php
+++ b/app/Http/Controllers/QuoteController.php
@@ -1,26 +1,28 @@
-account;
- $rates = TaxRate::scope()->orderBy('name')->get();
- $options = [];
- $defaultTax = false;
-
- foreach ($rates as $rate) {
- $name = $rate->name . ' ' . ($rate->rate + 0) . '%';
- if ($rate->is_inclusive) {
- $name .= ' - ' . trans('texts.inclusive');
- }
- $options[($rate->is_inclusive ? '1 ' : '0 ') . $rate->rate . ' ' . $rate->name] = $name;
-
- // load default invoice tax
- if ($rate->id == $account->default_tax_rate_id) {
- $defaultTax = $rate;
- }
- }
return [
'entityType' => ENTITY_QUOTE,
- 'account' => Auth::user()->account,
+ 'account' => $account,
'products' => Product::scope()->orderBy('id')->get(['product_key', 'notes', 'cost', 'qty']),
- 'taxRateOptions' => $options,
- 'defaultTax' => $defaultTax,
+ 'taxRateOptions' => $account->present()->taxRateOptions,
+ 'defaultTax' => $account->default_tax_rate,
'countries' => Cache::get('countries'),
'clients' => Client::scope()->with('contacts', 'country')->orderBy('name')->get(),
'taxRates' => TaxRate::scope()->orderBy('name')->get(),
@@ -133,7 +118,8 @@ class QuoteController extends BaseController
public function bulk()
{
- $action = Input::get('bulk_action') ?: Input::get('action');;
+ $action = Input::get('bulk_action') ?: Input::get('action');
+ ;
$ids = Input::get('bulk_public_id') ?: (Input::get('public_id') ?: Input::get('ids'));
if ($action == 'convert') {
@@ -141,6 +127,7 @@ class QuoteController extends BaseController
$clone = $this->invoiceService->convertQuote($invoice);
Session::flash('message', trans('texts.converted_to_invoice'));
+
return Redirect::to('invoices/'.$clone->public_id);
}
diff --git a/app/Http/Controllers/RecurringInvoiceController.php b/app/Http/Controllers/RecurringInvoiceController.php
index db1b83ba3949..2b1cc2977361 100644
--- a/app/Http/Controllers/RecurringInvoiceController.php
+++ b/app/Http/Controllers/RecurringInvoiceController.php
@@ -1,11 +1,12 @@
-view('list_wrapper', $data);
}
-
}
diff --git a/app/Http/Controllers/ReportController.php b/app/Http/Controllers/ReportController.php
index f23da88bd489..69d85eecc216 100644
--- a/app/Http/Controllers/ReportController.php
+++ b/app/Http/Controllers/ReportController.php
@@ -1,17 +1,16 @@
-hasPermission('view_all')) {
+ return redirect('/');
+ }
+
$action = Input::get('action');
if (Input::get('report_type')) {
@@ -64,14 +67,13 @@ class ReportController extends BaseController
}
$reportTypes = [
- 'client',
- 'product',
- 'invoice',
- 'invoice_details',
'aging',
- 'profit_and_loss',
- 'payment',
+ 'client',
'expense',
+ 'invoice',
+ 'payment',
+ 'product',
+ 'profit_and_loss',
'task',
'tax_rate',
];
@@ -120,6 +122,10 @@ class ReportController extends BaseController
*/
private function export($reportType, $data, $columns, $totals)
{
+ if (! Auth::user()->hasPermission('view_all')) {
+ exit;
+ }
+
$output = fopen('php://output', 'w') or Utils::fatalError();
$reportType = trans("texts.{$reportType}s");
$date = date('Y-m-d');
diff --git a/app/Http/Controllers/SelfUpdateController.php b/app/Http/Controllers/SelfUpdateController.php
index a58bb1c93ca0..9f9955c8992a 100644
--- a/app/Http/Controllers/SelfUpdateController.php
+++ b/app/Http/Controllers/SelfUpdateController.php
@@ -2,14 +2,14 @@
namespace App\Http\Controllers;
-use Utils;
-use Redirect;
use Codedge\Updater\UpdaterManager;
+use Redirect;
+use Utils;
class SelfUpdateController extends BaseController
{
/**
- * @var UpdaterManager
+ * @var UpdaterManager
*/
protected $updater;
@@ -28,7 +28,7 @@ class SelfUpdateController extends BaseController
}
/**
- * Show default update page
+ * Show default update page.
*
* @return mixed
*/
@@ -42,13 +42,13 @@ class SelfUpdateController extends BaseController
[
'versionInstalled' => $versionInstalled,
'versionAvailable' => $this->updater->source()->getVersionAvailable(),
- 'updateAvailable' => $updateAvailable
+ 'updateAvailable' => $updateAvailable,
]
);
}
/**
- * Run the actual update
+ * Run the actual update.
*
* @return \Illuminate\Http\RedirectResponse
*/
diff --git a/app/Http/Controllers/TaskApiController.php b/app/Http/Controllers/TaskApiController.php
index 632a8b034d0b..ca24c03941d7 100644
--- a/app/Http/Controllers/TaskApiController.php
+++ b/app/Http/Controllers/TaskApiController.php
@@ -1,12 +1,14 @@
-response($data);
}
-
-
/**
* @SWG\Put(
* path="/task/{task_id}",
@@ -109,7 +109,6 @@ class TaskApiController extends BaseAPIController
* )
* )
*/
-
public function update(UpdateTaskRequest $request)
{
$task = $request->entity();
@@ -117,7 +116,5 @@ class TaskApiController extends BaseAPIController
$task = $this->taskRepo->save($task->public_id, \Illuminate\Support\Facades\Input::all());
return $this->itemResponse($task);
-
}
-
}
diff --git a/app/Http/Controllers/TaskController.php b/app/Http/Controllers/TaskController.php
index 452ce50ebaa6..412aeb67cec6 100644
--- a/app/Http/Controllers/TaskController.php
+++ b/app/Http/Controllers/TaskController.php
@@ -1,26 +1,28 @@
-taskRepo = $taskRepo;
@@ -77,6 +79,7 @@ class TaskController extends BaseController
/**
* @param null $clientPublicId
+ *
* @return \Illuminate\Http\JsonResponse
*/
public function getDatatable($clientPublicId = null)
@@ -98,6 +101,7 @@ class TaskController extends BaseController
/**
* @param $publicId
+ *
* @return \Illuminate\Http\RedirectResponse
*/
public function show($publicId)
@@ -162,7 +166,7 @@ class TaskController extends BaseController
}
$actions[] = DropdownButton::DIVIDER;
- if (!$task->trashed()) {
+ if (! $task->trashed()) {
$actions[] = ['url' => 'javascript:submitAction("archive")', 'label' => trans('texts.archive_task')];
$actions[] = ['url' => 'javascript:onDeleteClick()', 'label' => trans('texts.delete_task')];
} else {
@@ -215,6 +219,7 @@ class TaskController extends BaseController
/**
* @param null $publicId
+ *
* @return \Illuminate\Http\RedirectResponse
*/
private function save($publicId = null)
@@ -227,7 +232,7 @@ class TaskController extends BaseController
$task = $this->taskRepo->save($publicId, Input::all());
- if($publicId) {
+ if ($publicId) {
Session::flash('message', trans('texts.updated_task'));
} else {
Session::flash('message', trans('texts.created_task'));
@@ -251,8 +256,9 @@ class TaskController extends BaseController
if ($action == 'stop') {
$this->taskRepo->save($ids, ['action' => $action]);
Session::flash('message', trans('texts.stopped_task'));
+
return Redirect::to('tasks');
- } else if ($action == 'invoice' || $action == 'add_to_invoice') {
+ } elseif ($action == 'invoice' || $action == 'add_to_invoice') {
$tasks = Task::scope($ids)->with('client')->orderBy('project_id', 'id')->get();
$clientPublicId = false;
$data = [];
@@ -260,19 +266,22 @@ class TaskController extends BaseController
$lastProjectId = false;
foreach ($tasks as $task) {
if ($task->client) {
- if (!$clientPublicId) {
+ if (! $clientPublicId) {
$clientPublicId = $task->client->public_id;
- } else if ($clientPublicId != $task->client->public_id) {
+ } elseif ($clientPublicId != $task->client->public_id) {
Session::flash('error', trans('texts.task_error_multiple_clients'));
+
return Redirect::to('tasks');
}
}
if ($task->is_running) {
Session::flash('error', trans('texts.task_error_running'));
+
return Redirect::to('tasks');
- } else if ($task->invoice_id) {
+ } elseif ($task->invoice_id) {
Session::flash('error', trans('texts.task_error_invoiced'));
+
return Redirect::to('tasks');
}
@@ -290,6 +299,7 @@ class TaskController extends BaseController
return Redirect::to("invoices/create/{$clientPublicId}")->with('tasks', $data);
} else {
$invoiceId = Input::get('invoice_id');
+
return Redirect::to("invoices/{$invoiceId}/edit")->with('tasks', $data);
}
} else {
@@ -304,7 +314,7 @@ class TaskController extends BaseController
private function checkTimezone()
{
- if (!Auth::user()->account->timezone) {
+ if (! Auth::user()->account->timezone) {
$link = link_to('/settings/localization?focus=timezone_id', trans('texts.click_here'), ['target' => '_blank']);
Session::flash('warning', trans('texts.timezone_unset', ['link' => $link]));
}
diff --git a/app/Http/Controllers/TaxRateApiController.php b/app/Http/Controllers/TaxRateApiController.php
index 2fa442af49b2..cebab115f806 100644
--- a/app/Http/Controllers/TaxRateApiController.php
+++ b/app/Http/Controllers/TaxRateApiController.php
@@ -1,9 +1,11 @@
-taxRateRepo->save($request->input());
Session::flash('message', trans('texts.created_tax_rate'));
+
return Redirect::to('settings/' . ACCOUNT_TAX_RATES);
}
@@ -72,10 +75,10 @@ class TaxRateController extends BaseController
$this->taxRateRepo->save($request->input(), $request->entity());
Session::flash('message', trans('texts.updated_tax_rate'));
+
return Redirect::to('settings/' . ACCOUNT_TAX_RATES);
}
-
public function bulk()
{
$action = Input::get('bulk_action');
diff --git a/app/Http/Controllers/TokenController.php b/app/Http/Controllers/TokenController.php
index 51e53b5d97ed..414151fd3ee2 100644
--- a/app/Http/Controllers/TokenController.php
+++ b/app/Http/Controllers/TokenController.php
@@ -1,17 +1,19 @@
-save();
}
-
/**
* @return \Illuminate\Contracts\View\View
*/
@@ -113,9 +117,9 @@ class TokenController extends BaseController
return Redirect::to('settings/' . ACCOUNT_API_TOKENS);
}
-
/**
* @param bool $tokenPublicId
+ *
* @return $this|\Illuminate\Http\RedirectResponse
*/
public function save($tokenPublicId = false)
@@ -157,5 +161,4 @@ class TokenController extends BaseController
return Redirect::to('settings/' . ACCOUNT_API_TOKENS);
}
-
}
diff --git a/app/Http/Controllers/UserApiController.php b/app/Http/Controllers/UserApiController.php
index be37ecc66c3f..64365c910ec5 100644
--- a/app/Http/Controllers/UserApiController.php
+++ b/app/Http/Controllers/UserApiController.php
@@ -1,12 +1,14 @@
-response($data);
}
-}
\ No newline at end of file
+}
diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php
index 1646c539f8c8..70f1780d4f18 100644
--- a/app/Http/Controllers/UserController.php
+++ b/app/Http/Controllers/UserController.php
@@ -1,20 +1,22 @@
-registered) {
+ if (! Auth::user()->registered) {
Session::flash('error', trans('texts.register_to_add_user'));
+
return Redirect::to('settings/' . ACCOUNT_USER_MANAGEMENT);
}
- if ( ! Auth::user()->confirmed) {
+ if (! Auth::user()->confirmed) {
Session::flash('error', trans('texts.confirmation_required'));
+
return Redirect::to('settings/' . ACCOUNT_USER_MANAGEMENT);
}
if (Utils::isNinja() && ! Auth::user()->caddAddUsers()) {
Session::flash('error', trans('texts.max_users_reached'));
+
return Redirect::to('settings/' . ACCOUNT_USER_MANAGEMENT);
}
@@ -132,7 +136,7 @@ class UserController extends BaseController
if ($action === 'archive') {
$user->delete();
} else {
- if ( ! Auth::user()->caddAddUsers()) {
+ if (! Auth::user()->caddAddUsers()) {
return Redirect::to('settings/' . ACCOUNT_USER_MANAGEMENT)
->with('error', trans('texts.max_users_reached'));
}
@@ -146,8 +150,9 @@ class UserController extends BaseController
}
/**
- * Stores new account
+ * Stores new account.
*
+ * @param mixed $userPublicId
*/
public function save($userPublicId = false)
{
@@ -205,7 +210,7 @@ class UserController extends BaseController
$user->save();
- if (!$user->confirmed) {
+ if (! $user->confirmed) {
$this->userMailer->sendConfirmation($user, Auth::user());
$message = trans('texts.sent_invite');
} else {
@@ -229,9 +234,8 @@ class UserController extends BaseController
return Redirect::to('settings/' . ACCOUNT_USER_MANAGEMENT);
}
-
/**
- * Attempt to confirm account with code
+ * Attempt to confirm account with code.
*
* @param string $code
*/
@@ -249,6 +253,7 @@ class UserController extends BaseController
if ($user->public_id) {
Auth::logout();
$token = Password::getRepository()->create($user);
+
return Redirect::to("/password/reset/{$token}");
} else {
if (Auth::check()) {
@@ -261,6 +266,7 @@ class UserController extends BaseController
} else {
$url = '/login';
}
+
return Redirect::to($url)->with('message', $notice_msg);
}
} else {
@@ -270,37 +276,12 @@ class UserController extends BaseController
}
}
- /**
- * Log the user out of the application.
- *
- */
- /*
- public function logout()
- {
- if (Auth::check()) {
- if (!Auth::user()->registered) {
- $account = Auth::user()->account;
- $this->accountRepo->unlinkAccount($account);
- if ($account->company->accounts->count() == 1) {
- $account->company->forceDelete();
- }
- $account->forceDelete();
- }
- }
-
- Auth::logout();
- Session::flush();
-
- return Redirect::to('/')->with('clearGuestKey', true);
- }
- */
-
public function changePassword()
{
// check the current password is correct
- if (!Auth::validate([
+ if (! Auth::validate([
'email' => Auth::user()->email,
- 'password' => Input::get('current_password')
+ 'password' => Input::get('current_password'),
])) {
return trans('texts.password_error_incorrect');
}
@@ -347,6 +328,22 @@ class UserController extends BaseController
}
}
+ public function viewAccountByKey($accountKey)
+ {
+ $user = $this->accountRepo->findUser(Auth::user(), $accountKey);
+
+ if (! $user) {
+ return redirect()->to('/');
+ }
+
+ Auth::loginUsingId($user->id);
+ Auth::user()->account->loadLocalizationSettings();
+
+ $redirectTo = request()->redirect_to ?: '/';
+
+ return redirect()->to($redirectTo);
+ }
+
public function unlinkAccount($userAccountId, $userId)
{
$this->accountRepo->unlinkUser($userAccountId, $userId);
@@ -356,6 +353,7 @@ class UserController extends BaseController
Session::put(SESSION_USER_ACCOUNTS, $users);
Session::flash('message', trans('texts.unlinked_account'));
+
return Redirect::to('/manage_companies');
}
diff --git a/app/Http/Controllers/VendorApiController.php b/app/Http/Controllers/VendorApiController.php
index c38e5867e2df..f7227a97af37 100644
--- a/app/Http/Controllers/VendorApiController.php
+++ b/app/Http/Controllers/VendorApiController.php
@@ -1,13 +1,16 @@
-itemResponse($vendor);
}
- /**
- * @SWG\Put(
- * path="/vendors/{vendor_id}",
- * tags={"vendor"},
- * summary="Update a vendor",
- * @SWG\Parameter(
- * in="body",
- * name="body",
- * @SWG\Schema(ref="#/definitions/Vendor")
- * ),
- * @SWG\Response(
- * response=200,
- * description="Update vendor",
- * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Vendor"))
- * ),
- * @SWG\Response(
- * response="default",
- * description="an ""unexpected"" error"
- * )
- * )
- */
-
+ /**
+ * @SWG\Put(
+ * path="/vendors/{vendor_id}",
+ * tags={"vendor"},
+ * summary="Update a vendor",
+ * @SWG\Parameter(
+ * in="body",
+ * name="body",
+ * @SWG\Schema(ref="#/definitions/Vendor")
+ * ),
+ * @SWG\Response(
+ * response=200,
+ * description="Update vendor",
+ * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Vendor"))
+ * ),
+ * @SWG\Response(
+ * response="default",
+ * description="an ""unexpected"" error"
+ * )
+ * )
+ *
+ * @param mixed $publicId
+ */
public function update(UpdateVendorRequest $request, $publicId)
{
if ($request->action) {
@@ -123,29 +127,27 @@ class VendorApiController extends BaseAPIController
return $this->itemResponse($vendor);
}
-
- /**
- * @SWG\Delete(
- * path="/vendors/{vendor_id}",
- * tags={"vendor"},
- * summary="Delete a vendor",
- * @SWG\Parameter(
- * in="body",
- * name="body",
- * @SWG\Schema(ref="#/definitions/Vendor")
- * ),
- * @SWG\Response(
- * response=200,
- * description="Delete vendor",
- * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Vendor"))
- * ),
- * @SWG\Response(
- * response="default",
- * description="an ""unexpected"" error"
- * )
- * )
- */
-
+ /**
+ * @SWG\Delete(
+ * path="/vendors/{vendor_id}",
+ * tags={"vendor"},
+ * summary="Delete a vendor",
+ * @SWG\Parameter(
+ * in="body",
+ * name="body",
+ * @SWG\Schema(ref="#/definitions/Vendor")
+ * ),
+ * @SWG\Response(
+ * response=200,
+ * description="Delete vendor",
+ * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Vendor"))
+ * ),
+ * @SWG\Response(
+ * response="default",
+ * description="an ""unexpected"" error"
+ * )
+ * )
+ */
public function destroy(VendorRequest $request)
{
$vendor = $request->entity();
diff --git a/app/Http/Controllers/VendorController.php b/app/Http/Controllers/VendorController.php
index bc16ee9e407c..e89c0028f738 100644
--- a/app/Http/Controllers/VendorController.php
+++ b/app/Http/Controllers/VendorController.php
@@ -1,21 +1,23 @@
-entity();
$actionLinks = [
- ['label' => trans('texts.new_vendor'), 'url' => URL::to('/vendors/create/' . $vendor->public_id)]
+ ['label' => trans('texts.new_vendor'), 'url' => URL::to('/vendors/create/' . $vendor->public_id)],
];
$data = [
- 'actionLinks' => $actionLinks,
- 'showBreadcrumbs' => false,
- 'vendor' => $vendor,
- 'title' => trans('texts.view_vendor'),
- 'hasRecurringInvoices' => false,
- 'hasQuotes' => false,
- 'hasTasks' => false,
+ 'actionLinks' => $actionLinks,
+ 'showBreadcrumbs' => false,
+ 'vendor' => $vendor,
+ 'title' => trans('texts.view_vendor'),
+ 'hasRecurringInvoices' => false,
+ 'hasQuotes' => false,
+ 'hasTasks' => false,
];
return View::make('vendors.show', $data);
@@ -117,7 +120,8 @@ class VendorController extends BaseController
/**
* Show the form for editing the specified resource.
*
- * @param int $id
+ * @param int $id
+ *
* @return Response
*/
public function edit(VendorRequest $request)
@@ -155,7 +159,8 @@ class VendorController extends BaseController
/**
* Update the specified resource in storage.
*
- * @param int $id
+ * @param int $id
+ *
* @return Response
*/
public function update(UpdateVendorRequest $request)
diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php
index b20e0b754465..46a45d9ca6d6 100644
--- a/app/Http/Kernel.php
+++ b/app/Http/Kernel.php
@@ -1,38 +1,38 @@
- 'App\Http\Middleware\Authenticate',
- 'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
- 'permissions.required' => 'App\Http\Middleware\PermissionsRequired',
- 'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
+ /**
+ * The application's route middleware.
+ *
+ * @var array
+ */
+ protected $routeMiddleware = [
+ 'auth' => 'App\Http\Middleware\Authenticate',
+ 'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
+ 'permissions.required' => 'App\Http\Middleware\PermissionsRequired',
+ 'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
'api' => 'App\Http\Middleware\ApiCheck',
- ];
-
+ ];
}
diff --git a/app/Http/Middleware/ApiCheck.php b/app/Http/Middleware/ApiCheck.php
index b0c5528b9084..7f59159fe088 100644
--- a/app/Http/Middleware/ApiCheck.php
+++ b/app/Http/Middleware/ApiCheck.php
@@ -1,26 +1,29 @@
-is('api/v1/login')
@@ -37,9 +40,10 @@ class ApiCheck {
if ($loggingIn) {
// check API secret
- if ( ! $hasApiSecret) {
+ if (! $hasApiSecret) {
sleep(ERROR_DELAY);
- $error['error'] = ['message'=>'Invalid value for API_SECRET'];
+ $error['error'] = ['message' => 'Invalid value for API_SECRET'];
+
return Response::json($error, 403, $headers);
}
} else {
@@ -52,24 +56,26 @@ class ApiCheck {
Session::set('token_id', $token->id);
} else {
sleep(ERROR_DELAY);
- $error['error'] = ['message'=>'Invalid token'];
+ $error['error'] = ['message' => 'Invalid token'];
+
return Response::json($error, 403, $headers);
}
}
- if (!Utils::isNinja() && !$loggingIn) {
+ if (! Utils::isNinja() && ! $loggingIn) {
return $next($request);
}
- if (!Utils::hasFeature(FEATURE_API) && !$hasApiSecret) {
- $error['error'] = ['message'=>'API requires pro plan'];
+ if (! Utils::hasFeature(FEATURE_API) && ! $hasApiSecret) {
+ $error['error'] = ['message' => 'API requires pro plan'];
+
return Response::json($error, 403, $headers);
} else {
$key = Auth::check() ? Auth::user()->account->id : $request->getClientIp();
// http://stackoverflow.com/questions/1375501/how-do-i-throttle-my-sites-api-users
$hour = 60 * 60;
- $hour_limit = 100; # users are limited to 100 requests/hour
+ $hour_limit = 100; // users are limited to 100 requests/hour
$hour_throttle = Cache::get("hour_throttle:{$key}", null);
$last_api_request = Cache::get("last_api_request:{$key}", 0);
$last_api_diff = time() - $last_api_request;
@@ -80,13 +86,14 @@ class ApiCheck {
$new_hour_throttle = $hour_throttle - $last_api_diff;
$new_hour_throttle = $new_hour_throttle < 0 ? 0 : $new_hour_throttle;
$new_hour_throttle += $hour / $hour_limit;
- $hour_hits_remaining = floor(( $hour - $new_hour_throttle ) * $hour_limit / $hour);
+ $hour_hits_remaining = floor(($hour - $new_hour_throttle) * $hour_limit / $hour);
$hour_hits_remaining = $hour_hits_remaining >= 0 ? $hour_hits_remaining : 0;
}
if ($new_hour_throttle > $hour) {
$wait = ceil($new_hour_throttle - $hour);
sleep(1);
+
return Response::json("Please wait {$wait} second(s)", 403, $headers);
}
@@ -96,5 +103,4 @@ class ApiCheck {
return $next($request);
}
-
}
diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php
index 0aa3d1187520..0ebfbacccf63 100644
--- a/app/Http/Middleware/Authenticate.php
+++ b/app/Http/Middleware/Authenticate.php
@@ -1,22 +1,25 @@
-check();
if ($guard == 'client') {
- if (!empty($request->invitation_key)) {
+ if (! empty($request->invitation_key)) {
$contact_key = session('contact_key');
if ($contact_key) {
$contact = $this->getContact($contact_key);
$invitation = $this->getInvitation($request->invitation_key);
- if (!$invitation) {
+ if (! $invitation) {
return response()->view('error', [
'error' => trans('texts.invoice_not_found'),
'hideHeader' => true,
@@ -46,7 +49,7 @@ class Authenticate
}
}
- if (!empty($request->contact_key)) {
+ if (! empty($request->contact_key)) {
$contact_key = $request->contact_key;
Session::put('contact_key', $contact_key);
} else {
@@ -55,7 +58,7 @@ class Authenticate
if ($contact_key) {
$contact = $this->getContact($contact_key);
- } elseif (!empty($request->invitation_key)) {
+ } elseif (! empty($request->invitation_key)) {
$invitation = $this->getInvitation($request->invitation_key);
$contact = $invitation->contact;
Session::put('contact_key', $contact->contact_key);
@@ -70,11 +73,15 @@ class Authenticate
}
// Does this account require portal passwords?
- if ($account && (!$account->enable_portal_password || !$account->hasFeature(FEATURE_CLIENT_PORTAL_PASSWORD))) {
+ if ($account && (! $account->enable_portal_password || ! $account->hasFeature(FEATURE_CLIENT_PORTAL_PASSWORD))) {
$authenticated = true;
}
- if (!$authenticated && $contact && !$contact->password) {
+ if (! $authenticated && $contact && ! $contact->password) {
+ $authenticated = true;
+ }
+
+ if (env('PHANTOMJS_SECRET') && $request->phantomjs_secret && hash_equals(env('PHANTOMJS_SECRET'), $request->phantomjs_secret)) {
$authenticated = true;
}
@@ -83,7 +90,7 @@ class Authenticate
}
}
- if (!$authenticated) {
+ if (! $authenticated) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
@@ -96,12 +103,16 @@ class Authenticate
/**
* @param $key
+ *
* @return \Illuminate\Database\Eloquent\Model|null|static
*/
protected function getInvitation($key)
{
+ // check for extra params at end of value (from website feature)
+ list($key) = explode('&', $key);
+
$invitation = Invitation::withTrashed()->where('invitation_key', '=', $key)->first();
- if ($invitation && !$invitation->is_deleted) {
+ if ($invitation && ! $invitation->is_deleted) {
return $invitation;
} else {
return null;
@@ -110,12 +121,13 @@ class Authenticate
/**
* @param $key
+ *
* @return \Illuminate\Database\Eloquent\Model|null|static
*/
protected function getContact($key)
{
$contact = Contact::withTrashed()->where('contact_key', '=', $key)->first();
- if ($contact && !$contact->is_deleted) {
+ if ($contact && ! $contact->is_deleted) {
return $contact;
} else {
return null;
diff --git a/app/Http/Middleware/DuplicateSubmissionCheck.php b/app/Http/Middleware/DuplicateSubmissionCheck.php
index f92a31a48398..dc8ae4004acc 100644
--- a/app/Http/Middleware/DuplicateSubmissionCheck.php
+++ b/app/Http/Middleware/DuplicateSubmissionCheck.php
@@ -1,16 +1,19 @@
-getAction();
// Check if we have any permissions to check the user has.
- if ($permissions = !empty($actions['permissions']) ? $actions['permissions'] : null) {
- if (!Auth::user($guard)->hasPermission($permissions, !empty($actions['permissions_require_all']))) {
+ if ($permissions = ! empty($actions['permissions']) ? $actions['permissions'] : null) {
+ if (! Auth::user($guard)->hasPermission($permissions, ! empty($actions['permissions_require_all']))) {
return response('Unauthorized.', 401);
}
}
@@ -44,7 +45,7 @@ class PermissionsRequired
$action = explode('@', $request->route()->getActionName());
if (isset(static::$actions[$action[0]]) && isset(static::$actions[$action[0]][$action[1]])) {
$controller_permissions = static::$actions[$action[0]][$action[1]];
- if (!Auth::user($guard)->hasPermission($controller_permissions)) {
+ if (! Auth::user($guard)->hasPermission($controller_permissions)) {
return response('Unauthorized.', 401);
}
}
@@ -53,10 +54,10 @@ class PermissionsRequired
}
/**
- * add a controller's action permission
+ * add a controller's action permission.
*
* @param Controller $controller
- * @param array $permissions
+ * @param array $permissions
*/
public static function addPermission(Controller $controller, array $permissions)
{
diff --git a/app/Http/Middleware/QueryLogging.php b/app/Http/Middleware/QueryLogging.php
index 1bc8160dff7c..c0a4852c69ae 100644
--- a/app/Http/Middleware/QueryLogging.php
+++ b/app/Http/Middleware/QueryLogging.php
@@ -1,21 +1,24 @@
-secure()) {
+ if (Utils::requireHTTPS() && ! $request->secure()) {
return Redirect::secure($request->path());
}
// If the database doens't yet exist we'll skip the rest
- if (!Utils::isNinja() && !Utils::isDatabaseSetup()) {
+ if (! Utils::isNinja() && ! Utils::isDatabaseSetup()) {
return $next($request);
}
// Check if a new version was installed
- if (!Utils::isNinja()) {
+ if (! Utils::isNinja()) {
$file = storage_path() . '/version.txt';
$version = @file_get_contents($file);
if ($version != NINJA_VERSION) {
@@ -58,6 +61,7 @@ class StartupCheck
$handle = fopen($file, 'w');
fwrite($handle, NINJA_VERSION);
fclose($handle);
+
return Redirect::to('/update');
}
}
@@ -67,7 +71,7 @@ class StartupCheck
$count = Session::get(SESSION_COUNTER, 0);
Session::put(SESSION_COUNTER, ++$count);
- if (isset($_SERVER['REQUEST_URI']) && !Utils::startsWith($_SERVER['REQUEST_URI'], '/news_feed') && !Session::has('news_feed_id')) {
+ if (isset($_SERVER['REQUEST_URI']) && ! Utils::startsWith($_SERVER['REQUEST_URI'], '/news_feed') && ! Session::has('news_feed_id')) {
$data = false;
if (Utils::isNinja()) {
$data = Utils::getNewsFeedResponse();
@@ -117,14 +121,14 @@ class StartupCheck
}
// Make sure the account/user localization settings are in the session
- if (Auth::check() && !Session::has(SESSION_TIMEZONE)) {
+ if (Auth::check() && ! Session::has(SESSION_TIMEZONE)) {
Event::fire(new UserLoggedIn());
}
// Check if the user is claiming a license (ie, additional invoices, white label, etc.)
- if ( ! Utils::isNinjaProd() && isset($_SERVER['REQUEST_URI'])) {
+ if (! Utils::isNinjaProd() && isset($_SERVER['REQUEST_URI'])) {
$claimingLicense = Utils::startsWith($_SERVER['REQUEST_URI'], '/claim_license');
- if ( ! $claimingLicense && Input::has('license_key') && Input::has('product_id')) {
+ if (! $claimingLicense && Input::has('license_key') && Input::has('product_id')) {
$licenseKey = Input::get('license_key');
$productId = Input::get('product_id');
@@ -168,9 +172,9 @@ class StartupCheck
Session::flash('message', 'Cache cleared');
}
foreach ($cachedTables as $name => $class) {
- if (Input::has('clear_cache') || !Cache::has($name)) {
+ if (Input::has('clear_cache') || ! Cache::has($name)) {
// check that the table exists in case the migration is pending
- if ( ! Schema::hasTable((new $class)->getTable())) {
+ if (! Schema::hasTable((new $class())->getTable())) {
continue;
}
if ($name == 'paymentTerms') {
diff --git a/app/Http/Middleware/VerifyCsrfToken.php b/app/Http/Middleware/VerifyCsrfToken.php
index 3fbef6812658..2a8b178f5952 100644
--- a/app/Http/Middleware/VerifyCsrfToken.php
+++ b/app/Http/Middleware/VerifyCsrfToken.php
@@ -1,14 +1,15 @@
- 'valid_contacts',
- ];
+ $rules = [];
if ($this->user()->account->client_number_counter) {
$rules['id_number'] = 'unique:clients,id_number,,id,account_id,' . $this->user()->account_id;
diff --git a/app/Http/Requests/CreateCreditRequest.php b/app/Http/Requests/CreateCreditRequest.php
index b6f4fe3b37e3..73366081420d 100644
--- a/app/Http/Requests/CreateCreditRequest.php
+++ b/app/Http/Requests/CreateCreditRequest.php
@@ -1,4 +1,6 @@
-user()->hasFeature(FEATURE_DOCUMENTS)) {
+ if (! $this->user()->hasFeature(FEATURE_DOCUMENTS)) {
return false;
}
@@ -43,5 +45,4 @@ class CreateDocumentRequest extends DocumentRequest
//'file' => 'mimes:jpg'
];
}
-
}
diff --git a/app/Http/Requests/CreateExpenseCategoryRequest.php b/app/Http/Requests/CreateExpenseCategoryRequest.php
index c54108e225a5..347c0450a26c 100644
--- a/app/Http/Requests/CreateExpenseCategoryRequest.php
+++ b/app/Http/Requests/CreateExpenseCategoryRequest.php
@@ -1,8 +1,11 @@
- 'valid_contacts',
+ 'client' => 'required',
'invoice_items' => 'valid_invoice_items',
'invoice_number' => 'required|unique:invoices,invoice_number,,id,account_id,' . $this->user()->account_id,
'discount' => 'positive',
diff --git a/app/Http/Requests/CreateOnlinePaymentRequest.php b/app/Http/Requests/CreateOnlinePaymentRequest.php
index 815c8f5b217d..1e9910082b9d 100644
--- a/app/Http/Requests/CreateOnlinePaymentRequest.php
+++ b/app/Http/Requests/CreateOnlinePaymentRequest.php
@@ -1,4 +1,6 @@
-user()->can('create', ENTITY_PAYMENT);
@@ -26,7 +23,7 @@ class CreatePaymentAPIRequest extends PaymentRequest
*/
public function rules()
{
- if ( ! $this->invoice_id || ! $this->amount) {
+ if (! $this->invoice_id || ! $this->amount) {
return [
'invoice_id' => 'required|numeric|min:1',
'amount' => 'required|numeric|min:0.01',
@@ -52,7 +49,4 @@ class CreatePaymentAPIRequest extends PaymentRequest
return $rules;
}
-
-
-
}
diff --git a/app/Http/Requests/CreatePaymentRequest.php b/app/Http/Requests/CreatePaymentRequest.php
index 9b45b2486dd7..f2e1d468419a 100644
--- a/app/Http/Requests/CreatePaymentRequest.php
+++ b/app/Http/Requests/CreatePaymentRequest.php
@@ -1,4 +1,6 @@
- 'required',
];
- if ( ! empty($input['payment_type_id']) && $input['payment_type_id'] == PAYMENT_TYPE_CREDIT) {
+ if (! empty($input['payment_type_id']) && $input['payment_type_id'] == PAYMENT_TYPE_CREDIT) {
$rules['payment_type_id'] = 'has_credit:'.$input['client'].','.$input['amount'];
}
diff --git a/app/Http/Requests/CreateProductRequest.php b/app/Http/Requests/CreateProductRequest.php
index 0fad2af14a23..b7392cc6ac19 100644
--- a/app/Http/Requests/CreateProductRequest.php
+++ b/app/Http/Requests/CreateProductRequest.php
@@ -1,4 +1,6 @@
-entityType . '_id';
- if ( ! empty($this->$field)) {
+ if (! empty($this->$field)) {
$publicId = $this->$field;
}
- if ( ! $publicId) {
+ if (! $publicId) {
$field = Utils::pluralizeEntityType($this->entityType);
- if ( ! empty($this->$field)) {
+ if (! empty($this->$field)) {
$publicId = $this->$field;
}
}
- if ( ! $publicId) {
+ if (! $publicId) {
$publicId = Input::get('public_id') ?: Input::get('id');
}
- if ( ! $publicId) {
+ if (! $publicId) {
return null;
}
@@ -56,6 +58,7 @@ class EntityRequest extends Request {
if ($this->entity()) {
if ($this->user()->can('view', $this->entity())) {
HistoryUtils::trackViewed($this->entity());
+
return true;
}
} else {
@@ -67,5 +70,4 @@ class EntityRequest extends Request {
{
return [];
}
-
}
diff --git a/app/Http/Requests/ExpenseCategoryRequest.php b/app/Http/Requests/ExpenseCategoryRequest.php
index 810e7e56bee5..55f2ee78791a 100644
--- a/app/Http/Requests/ExpenseCategoryRequest.php
+++ b/app/Http/Requests/ExpenseCategoryRequest.php
@@ -1,7 +1,8 @@
-req = $req;
}
-
public function authorize()
{
return true;
@@ -30,7 +30,6 @@ class RegisterRequest extends Request
*/
public function rules()
{
-
$rules = [
'email' => 'required|unique:users',
'first_name' => 'required',
@@ -44,14 +43,14 @@ class RegisterRequest extends Request
public function response(array $errors)
{
/* If the user is not validating from a mobile app - pass through parent::response */
- if(!isset($this->req->api_secret))
+ if (! isset($this->req->api_secret)) {
return parent::response($errors);
+ }
/* If the user is validating from a mobile app - pass through first error string and return error */
- foreach($errors as $error) {
+ foreach ($errors as $error) {
foreach ($error as $key => $value) {
-
- $message['error'] = ['message'=>$value];
+ $message['error'] = ['message' => $value];
$message = json_encode($message, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders();
@@ -59,5 +58,4 @@ class RegisterRequest extends Request
}
}
}
-
}
diff --git a/app/Http/Requests/Request.php b/app/Http/Requests/Request.php
index f965e6af7ba3..4ce91b8540c4 100644
--- a/app/Http/Requests/Request.php
+++ b/app/Http/Requests/Request.php
@@ -1,19 +1,22 @@
-api_secret) {
+ if (! request()->api_secret) {
return parent::response($errors);
}
/* If the user is validating from a mobile app - pass through first error string and return error */
- foreach($errors as $error) {
+ foreach ($errors as $error) {
foreach ($error as $key => $value) {
-
- $message['error'] = ['message'=>$value];
+ $message['error'] = ['message' => $value];
$message = json_encode($message, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders();
diff --git a/app/Http/Requests/SaveClientPortalSettings.php b/app/Http/Requests/SaveClientPortalSettings.php
index 3c2485e7d7ef..7886722ae2f6 100644
--- a/app/Http/Requests/SaveClientPortalSettings.php
+++ b/app/Http/Requests/SaveClientPortalSettings.php
@@ -1,7 +1,9 @@
-replace($input);
return $this->all();
}
-
}
diff --git a/app/Http/Requests/SaveEmailSettings.php b/app/Http/Requests/SaveEmailSettings.php
index 84f8c5baf8d0..25696c6fff5b 100644
--- a/app/Http/Requests/SaveEmailSettings.php
+++ b/app/Http/Requests/SaveEmailSettings.php
@@ -1,4 +1,6 @@
- 'email',
];
}
-
}
diff --git a/app/Http/Requests/TaskRequest.php b/app/Http/Requests/TaskRequest.php
index 1e2783781f06..141bf89f08eb 100644
--- a/app/Http/Requests/TaskRequest.php
+++ b/app/Http/Requests/TaskRequest.php
@@ -1,7 +1,8 @@
- 'valid_contacts',
- ];
+ $rules = [];
if ($this->user()->account->client_number_counter) {
$rules['id_number'] = 'unique:clients,id_number,'.$this->entity()->id.',id,account_id,' . $this->user()->account_id;
diff --git a/app/Http/Requests/UpdateCreditRequest.php b/app/Http/Requests/UpdateCreditRequest.php
index 0bc9d64066ea..be5ebd50ff2d 100644
--- a/app/Http/Requests/UpdateCreditRequest.php
+++ b/app/Http/Requests/UpdateCreditRequest.php
@@ -1,4 +1,6 @@
- 'required',
'name' => sprintf('required|unique:expense_categories,name,%s,id,account_id,%s', $this->entity()->id, $this->user()->account_id),
];
diff --git a/app/Http/Requests/UpdateExpenseRequest.php b/app/Http/Requests/UpdateExpenseRequest.php
index 55a7ae59bf76..cd87ec5e59de 100644
--- a/app/Http/Requests/UpdateExpenseRequest.php
+++ b/app/Http/Requests/UpdateExpenseRequest.php
@@ -1,4 +1,6 @@
- 'numeric',
];
}
diff --git a/app/Http/Requests/UpdateInvoiceAPIRequest.php b/app/Http/Requests/UpdateInvoiceAPIRequest.php
index fb3f1b42a82b..f572e8bbc4b8 100644
--- a/app/Http/Requests/UpdateInvoiceAPIRequest.php
+++ b/app/Http/Requests/UpdateInvoiceAPIRequest.php
@@ -1,4 +1,6 @@
-entity()->id;
$rules = [
- 'client.contacts' => 'valid_contacts',
+ 'client' => 'required',
'invoice_items' => 'valid_invoice_items',
'invoice_number' => 'required|unique:invoices,invoice_number,' . $invoiceId . ',id,account_id,' . $this->user()->account_id,
'discount' => 'positive',
diff --git a/app/Http/Requests/UpdatePaymentRequest.php b/app/Http/Requests/UpdatePaymentRequest.php
index 70a328d26772..e569ffe2b4a1 100644
--- a/app/Http/Requests/UpdatePaymentRequest.php
+++ b/app/Http/Requests/UpdatePaymentRequest.php
@@ -1,4 +1,6 @@
- sprintf('required|unique:projects,name,%s,id,account_id,%s', $this->entity()->id, $this->user()->account_id),
];
}
diff --git a/app/Http/Requests/UpdateTaskRequest.php b/app/Http/Requests/UpdateTaskRequest.php
index 83ce23ab31ab..4131bf99ee0d 100644
--- a/app/Http/Requests/UpdateTaskRequest.php
+++ b/app/Http/Requests/UpdateTaskRequest.php
@@ -1,4 +1,6 @@
-getLocale();
- if(preg_match('/_/', $code)) {
+ if (preg_match('/_/', $code)) {
$codes = explode('_', $code);
$code = $codes[0];
}
return $code;
}
-}
\ No newline at end of file
+}
diff --git a/app/Http/ViewComposers/ClientPortalHeaderComposer.php b/app/Http/ViewComposers/ClientPortalHeaderComposer.php
index 7525b80bf699..a7a799150d59 100644
--- a/app/Http/ViewComposers/ClientPortalHeaderComposer.php
+++ b/app/Http/ViewComposers/ClientPortalHeaderComposer.php
@@ -2,10 +2,9 @@
namespace App\Http\ViewComposers;
-use DB;
-use Cache;
-use Illuminate\View\View;
use App\Models\Contact;
+use DB;
+use Illuminate\View\View;
/**
* ClientPortalHeaderComposer.php.
@@ -17,7 +16,7 @@ class ClientPortalHeaderComposer
/**
* Bind data to the view.
*
- * @param View $view
+ * @param View $view
*
* @return void
*/
@@ -25,7 +24,7 @@ class ClientPortalHeaderComposer
{
$contactKey = session('contact_key');
- if ( ! $contactKey) {
+ if (! $contactKey) {
return false;
}
@@ -33,7 +32,7 @@ class ClientPortalHeaderComposer
->with('client')
->first();
- if ( ! $contact || $contact->is_deleted) {
+ if (! $contact || $contact->is_deleted) {
return false;
}
diff --git a/app/Http/ViewComposers/TranslationComposer.php b/app/Http/ViewComposers/TranslationComposer.php
index 76a576ea5444..ff2dc954199f 100644
--- a/app/Http/ViewComposers/TranslationComposer.php
+++ b/app/Http/ViewComposers/TranslationComposer.php
@@ -15,7 +15,7 @@ class TranslationComposer
/**
* Bind data to the view.
*
- * @param View $view
+ * @param View $view
*
* @return void
*/
@@ -45,4 +45,4 @@ class TranslationComposer
return $lang->name;
}));
}
-}
\ No newline at end of file
+}
diff --git a/app/Http/routes.php b/app/Http/routes.php
index cb9acd590c18..04d17603ee25 100644
--- a/app/Http/routes.php
+++ b/app/Http/routes.php
@@ -11,7 +11,6 @@
|
*/
-
// Application setup
Route::get('/setup', 'AppController@showSetup');
Route::post('/setup', 'AppController@doSetup');
@@ -26,7 +25,7 @@ Route::get('/keep_alive', 'HomeController@keepAlive');
Route::post('/get_started', 'AccountController@getStarted');
// Client visible pages
-Route::group(['middleware' => 'auth:client'], function() {
+Route::group(['middleware' => 'auth:client'], function () {
Route::get('view/{invitation_key}', 'ClientPortalController@view');
Route::get('download/{invitation_key}', 'ClientPortalController@download');
Route::put('sign/{invitation_key}', 'ClientPortalController@sign');
@@ -54,16 +53,15 @@ Route::group(['middleware' => 'auth:client'], function() {
Route::get('client/documents/{invitation_key}/{documents}/{filename?}', 'ClientPortalController@getDocument');
Route::get('client/documents/{invitation_key}/{filename?}', 'ClientPortalController@getInvoiceDocumentsZip');
- Route::get('api/client.quotes', ['as'=>'api.client.quotes', 'uses'=>'ClientPortalController@quoteDatatable']);
- Route::get('api/client.credits', ['as'=>'api.client.credits', 'uses'=>'ClientPortalController@creditDatatable']);
- Route::get('api/client.invoices', ['as'=>'api.client.invoices', 'uses'=>'ClientPortalController@invoiceDatatable']);
- Route::get('api/client.recurring_invoices', ['as'=>'api.client.recurring_invoices', 'uses'=>'ClientPortalController@recurringInvoiceDatatable']);
- Route::get('api/client.documents', ['as'=>'api.client.documents', 'uses'=>'ClientPortalController@documentDatatable']);
- Route::get('api/client.payments', ['as'=>'api.client.payments', 'uses'=>'ClientPortalController@paymentDatatable']);
- Route::get('api/client.activity', ['as'=>'api.client.activity', 'uses'=>'ClientPortalController@activityDatatable']);
+ Route::get('api/client.quotes', ['as' => 'api.client.quotes', 'uses' => 'ClientPortalController@quoteDatatable']);
+ Route::get('api/client.credits', ['as' => 'api.client.credits', 'uses' => 'ClientPortalController@creditDatatable']);
+ Route::get('api/client.invoices', ['as' => 'api.client.invoices', 'uses' => 'ClientPortalController@invoiceDatatable']);
+ Route::get('api/client.recurring_invoices', ['as' => 'api.client.recurring_invoices', 'uses' => 'ClientPortalController@recurringInvoiceDatatable']);
+ Route::get('api/client.documents', ['as' => 'api.client.documents', 'uses' => 'ClientPortalController@documentDatatable']);
+ Route::get('api/client.payments', ['as' => 'api.client.payments', 'uses' => 'ClientPortalController@paymentDatatable']);
+ Route::get('api/client.activity', ['as' => 'api.client.activity', 'uses' => 'ClientPortalController@activityDatatable']);
});
-
Route::get('license', 'NinjaController@show_license_payment');
Route::post('license', 'NinjaController@do_license_payment');
Route::get('claim_license', 'NinjaController@claim_license');
@@ -102,7 +100,6 @@ Route::post('/client/recover_password', ['as' => 'forgot', 'uses' => 'ClientAuth
Route::get('/client/password/reset/{invitation_key}/{token}', ['as' => 'forgot', 'uses' => 'ClientAuth\PasswordController@getReset']);
Route::post('/client/password/reset', ['as' => 'forgot', 'uses' => 'ClientAuth\PasswordController@postReset']);
-
if (Utils::isNinja()) {
Route::post('/signup/register', 'AccountController@doRegister');
Route::get('/news_feed/{user_type}/{version}/', 'HomeController@newsFeed');
@@ -113,7 +110,7 @@ if (Utils::isReseller()) {
Route::post('/reseller_stats', 'AppController@stats');
}
-Route::group(['middleware' => 'auth:user'], function() {
+Route::group(['middleware' => 'auth:user'], function () {
Route::get('dashboard', 'DashboardController@index');
Route::get('dashboard_chart_data/{group_by}/{start_date}/{end_date}/{currency_id}/{include_expenses}', 'DashboardController@chartData');
Route::get('set_entity_filter/{entity_type}/{filter?}', 'AccountController@setEntityFilter');
@@ -192,11 +189,9 @@ Route::group(['middleware' => 'auth:user'], function() {
Route::resource('products', 'ProductController');
Route::post('products/bulk', 'ProductController@bulk');
-
Route::get('/resend_confirmation', 'AccountController@resendConfirmation');
Route::post('/update_setup', 'AppController@updateSetup');
-
// vendor
Route::resource('vendors', 'VendorController');
Route::get('api/vendors', 'VendorController@getDatatable');
@@ -216,22 +211,26 @@ Route::group(['middleware' => 'auth:user'], function() {
Route::get('expense_categories/{expense_categories}/edit', 'ExpenseCategoryController@edit');
Route::post('expense_categories/bulk', 'ExpenseCategoryController@bulk');
- // BlueVine
- Route::post('bluevine/signup', 'BlueVineController@signup');
- Route::get('bluevine/hide_message', 'BlueVineController@hideMessage');
- Route::get('bluevine/completed', 'BlueVineController@handleCompleted');
+ // BlueVine
+ Route::post('bluevine/signup', 'BlueVineController@signup');
+ Route::get('bluevine/hide_message', 'BlueVineController@hideMessage');
+ Route::get('bluevine/completed', 'BlueVineController@handleCompleted');
Route::get('white_label/hide_message', 'NinjaController@hideWhiteLabelMessage');
+
+ Route::get('reports', 'ReportController@showReports');
+ Route::post('reports', 'ReportController@showReports');
});
Route::group([
'middleware' => ['auth:user', 'permissions.required'],
'permissions' => 'admin',
-], function() {
+], function () {
Route::get('api/users', 'UserController@getDatatable');
Route::resource('users', 'UserController');
Route::post('users/bulk', 'UserController@bulk');
Route::get('send_confirmation/{user_id}', 'UserController@sendConfirmation');
Route::get('/switch_account/{user_id}', 'UserController@switchAccount');
+ Route::get('/account/{account_key}', 'UserController@viewAccountByKey');
Route::get('/unlink_account/{user_account_id}/{user_id}', 'UserController@unlinkAccount');
Route::get('/manage_companies', 'UserController@manageCompanies');
@@ -248,8 +247,6 @@ Route::group([
Route::post('settings/email_settings', 'AccountController@saveEmailSettings');
Route::get('company/{section}/{subSection?}', 'AccountController@redirectLegacy');
Route::get('settings/data_visualizations', 'ReportController@d3');
- Route::get('reports', 'ReportController@showReports');
- Route::post('reports', 'ReportController@showReports');
Route::post('settings/change_plan', 'AccountController@changePlan');
Route::post('settings/cancel_account', 'AccountController@cancelAccount');
@@ -269,6 +266,14 @@ Route::group([
Route::get('api/gateways', 'AccountGatewayController@getDatatable');
Route::post('account_gateways/bulk', 'AccountGatewayController@bulk');
+ Route::get('payment_terms', 'PaymentTermController@index');
+ Route::get('api/payment_terms', 'PaymentTermController@getDatatable');
+ Route::get('payment_terms/create', 'PaymentTermController@create');
+ Route::post('payment_terms', 'PaymentTermController@store');
+ Route::put('payment_terms/{payment_terms}', 'PaymentTermController@update');
+ Route::get('payment_terms/{payment_terms}/edit', 'PaymentTermController@edit');
+ Route::post('payment_terms/bulk', 'PaymentTermController@bulk');
+
Route::get('bank_accounts/import_ofx', 'BankAccountController@showImportOFX');
Route::post('bank_accounts/import_ofx', 'BankAccountController@doImportOFX');
Route::resource('bank_accounts', 'BankAccountController');
@@ -281,13 +286,12 @@ Route::group([
Route::get('self-update/download', 'SelfUpdateController@download');
});
-Route::group(['middleware' => 'auth:user'], function() {
+Route::group(['middleware' => 'auth:user'], function () {
Route::get('settings/{section?}', 'AccountController@showSection');
});
// Route groups for API
-Route::group(['middleware' => 'api', 'prefix' => 'api/v1'], function()
-{
+Route::group(['middleware' => 'api', 'prefix' => 'api/v1'], function () {
Route::get('ping', 'AccountApiController@ping');
Route::post('login', 'AccountApiController@login');
Route::post('oauth_login', 'AccountApiController@oauthLogin');
@@ -309,7 +313,7 @@ Route::group(['middleware' => 'api', 'prefix' => 'api/v1'], function()
Route::resource('products', 'ProductApiController');
Route::resource('tax_rates', 'TaxRateApiController');
Route::resource('users', 'UserApiController');
- Route::resource('expenses','ExpenseApiController');
+ Route::resource('expenses', 'ExpenseApiController');
Route::post('add_token', 'AccountApiController@addDeviceToken');
Route::post('update_notifications', 'AccountApiController@updatePushNotifications');
Route::get('dashboard', 'DashboardApiController@index');
@@ -319,37 +323,37 @@ Route::group(['middleware' => 'api', 'prefix' => 'api/v1'], function()
});
// Redirects for legacy links
-Route::get('/rocksteady', function() {
+Route::get('/rocksteady', function () {
return Redirect::to(NINJA_WEB_URL, 301);
});
-Route::get('/about', function() {
+Route::get('/about', function () {
return Redirect::to(NINJA_WEB_URL, 301);
});
-Route::get('/contact', function() {
+Route::get('/contact', function () {
return Redirect::to(NINJA_WEB_URL.'/contact', 301);
});
-Route::get('/plans', function() {
+Route::get('/plans', function () {
return Redirect::to(NINJA_WEB_URL.'/pricing', 301);
});
-Route::get('/faq', function() {
+Route::get('/faq', function () {
return Redirect::to(NINJA_WEB_URL.'/how-it-works', 301);
});
-Route::get('/features', function() {
+Route::get('/features', function () {
return Redirect::to(NINJA_WEB_URL.'/features', 301);
});
-Route::get('/testimonials', function() {
+Route::get('/testimonials', function () {
return Redirect::to(NINJA_WEB_URL, 301);
});
-Route::get('/compare-online-invoicing{sites?}', function() {
+Route::get('/compare-online-invoicing{sites?}', function () {
return Redirect::to(NINJA_WEB_URL, 301);
});
-Route::get('/forgot', function() {
+Route::get('/forgot', function () {
return Redirect::to(NINJA_APP_URL.'/recover_password', 301);
});
-Route::get('/feed', function() {
+Route::get('/feed', function () {
return Redirect::to(NINJA_WEB_URL.'/feed', 301);
});
-Route::get('/comments/feed', function() {
+Route::get('/comments/feed', function () {
return Redirect::to(NINJA_WEB_URL.'/comments/feed', 301);
});
diff --git a/app/Includes/parsecsv.lib.php b/app/Includes/parsecsv.lib.php
index 797beef30340..5c45a847d8b2 100644
--- a/app/Includes/parsecsv.lib.php
+++ b/app/Includes/parsecsv.lib.php
@@ -1,695 +1,879 @@
data);
- ----------------
- # tab delimited, and encoding conversion
- $csv = new parseCSV();
- $csv->encoding('UTF-16', 'UTF-8');
- $csv->delimiter = "\t";
- $csv->parse('data.tsv');
- print_r($csv->data);
- ----------------
- # auto-detect delimiter character
- $csv = new parseCSV();
- $csv->auto('data.csv');
- print_r($csv->data);
- ----------------
- # modify data in a csv file
- $csv = new parseCSV();
- $csv->sort_by = 'id';
- $csv->parse('data.csv');
- # "4" is the value of the "id" column of the CSV row
- $csv->data[4] = array('firstname' => 'John', 'lastname' => 'Doe', 'email' => 'john@doe.com');
- $csv->save();
- ----------------
- # add row/entry to end of CSV file
- # - only recommended when you know the extact sctructure of the file
- $csv = new parseCSV();
- $csv->save('data.csv', array('1986', 'Home', 'Nowhere', ''), true);
- ----------------
- # convert 2D array to csv data and send headers
- # to browser to treat output as a file and download it
- $csv = new parseCSV();
- $csv->output (true, 'movies.csv', $array);
- ----------------
+ Code Examples
+ ----------------
+ # general usage
+ $csv = new parseCSV('data.csv');
+ print_r($csv->data);
+ ----------------
+ # tab delimited, and encoding conversion
+ $csv = new parseCSV();
+ $csv->encoding('UTF-16', 'UTF-8');
+ $csv->delimiter = "\t";
+ $csv->parse('data.tsv');
+ print_r($csv->data);
+ ----------------
+ # auto-detect delimiter character
+ $csv = new parseCSV();
+ $csv->auto('data.csv');
+ print_r($csv->data);
+ ----------------
+ # modify data in a csv file
+ $csv = new parseCSV();
+ $csv->sort_by = 'id';
+ $csv->parse('data.csv');
+ # "4" is the value of the "id" column of the CSV row
+ $csv->data[4] = array('firstname' => 'John', 'lastname' => 'Doe', 'email' => 'john@doe.com');
+ $csv->save();
+ ----------------
+ # add row/entry to end of CSV file
+ # - only recommended when you know the extact sctructure of the file
+ $csv = new parseCSV();
+ $csv->save('data.csv', array('1986', 'Home', 'Nowhere', ''), true);
+ ----------------
+ # convert 2D array to csv data and send headers
+ # to browser to treat output as a file and download it
+ $csv = new parseCSV();
+ $csv->output (true, 'movies.csv', $array);
+ ----------------
*/
-
- /**
- * Configuration
- * - set these options with $object->var_name = 'value';
- */
-
- # use first line/entry as field names
- var $heading = true;
-
- # override field names
- var $fields = [];
-
- # sort entries by this field
- var $sort_by = null;
- var $sort_reverse = false;
-
- # delimiter (comma) and enclosure (double quote)
- var $delimiter = ',';
- var $enclosure = '"';
-
- # basic SQL-like conditions for row matching
- var $conditions = null;
-
- # number of rows to ignore from beginning of data
- var $offset = null;
-
- # limits the number of returned rows to specified amount
- var $limit = null;
-
- # number of rows to analyze when attempting to auto-detect delimiter
- var $auto_depth = 15;
-
- # characters to ignore when attempting to auto-detect delimiter
- var $auto_non_chars = "a-zA-Z0-9\n\r";
-
- # preferred delimiter characters, only used when all filtering method
- # returns multiple possible delimiters (happens very rarely)
- var $auto_preferred = ",;\t.:|";
-
- # character encoding options
- var $convert_encoding = false;
- var $input_encoding = 'ISO-8859-1';
- var $output_encoding = 'ISO-8859-1';
-
- # used by unparse(), save(), and output() functions
- var $linefeed = "\r\n";
-
- # only used by output() function
- var $output_delimiter = ',';
- var $output_filename = 'data.csv';
-
-
- /**
- * Internal variables
- */
-
- # current file
- var $file;
-
- # loaded file contents
- var $file_data;
-
- # array of field values in data parsed
- var $titles = [];
-
- # two dimentional array of CSV data
- var $data = [];
-
-
- /**
- * Constructor
- * @param input CSV file or string
- * @return nothing
- */
- function __construct ($input = null, $offset = null, $limit = null, $conditions = null) {
- if ( $offset !== null ) $this->offset = $offset;
- if ( $limit !== null ) $this->limit = $limit;
- if ( count($conditions) > 0 ) $this->conditions = $conditions;
- if ( !empty($input) ) $this->parse($input);
- }
-
-
- // ==============================================
- // ----- [ Main Functions ] ---------------------
- // ==============================================
-
- /**
- * Parse CSV file or string
- * @param input CSV file or string
- * @return nothing
- */
- function parse ($input = null, $offset = null, $limit = null, $conditions = null) {
- if ( !empty($input) ) {
- if ( $offset !== null ) $this->offset = $offset;
- if ( $limit !== null ) $this->limit = $limit;
- if ( count($conditions) > 0 ) $this->conditions = $conditions;
- if ( is_readable($input) ) {
- $this->data = $this->parse_file($input);
- } else {
- $this->file_data = &$input;
- $this->data = $this->parse_string();
- }
- if ( $this->data === false ) return false;
- }
- return true;
- }
-
- /**
- * Save changes, or new file and/or data
- * @param file file to save to
- * @param data 2D array with data
- * @param append append current data to end of target CSV if exists
- * @param fields field names
- * @return true or false
- */
- function save ($file = null, $data = [], $append = false, $fields = []) {
- if ( empty($file) ) $file = &$this->file;
- $mode = ( $append ) ? 'at' : 'wt' ;
- $is_php = ( preg_match('/\.php$/i', $file) ) ? true : false ;
- return $this->_wfile($file, $this->unparse($data, $fields, $append, $is_php), $mode);
- }
-
- /**
- * Generate CSV based string for output
- * @param output if true, prints headers and strings to browser
- * @param filename filename sent to browser in headers if output is true
- * @param data 2D array with data
- * @param fields field names
- * @param delimiter delimiter used to separate data
- * @return CSV data using delimiter of choice, or default
- */
- function output ($output = true, $filename = null, $data = [], $fields = [], $delimiter = null) {
- if ( empty($filename) ) $filename = $this->output_filename;
- if ( $delimiter === null ) $delimiter = $this->output_delimiter;
- $data = $this->unparse($data, $fields, null, null, $delimiter);
- if ( $output ) {
- header('Content-type: application/csv');
- header('Content-Disposition: inline; filename="'.$filename.'"');
- echo $data;
- }
- return $data;
- }
-
- /**
- * Convert character encoding
- * @param input input character encoding, uses default if left blank
- * @param output output character encoding, uses default if left blank
- * @return nothing
- */
- function encoding ($input = null, $output = null) {
- $this->convert_encoding = true;
- if ( $input !== null ) $this->input_encoding = $input;
- if ( $output !== null ) $this->output_encoding = $output;
- }
-
- /**
- * Auto-Detect Delimiter: Find delimiter by analyzing a specific number of
- * rows to determine most probable delimiter character
- * @param file local CSV file
- * @param parse true/false parse file directly
- * @param search_depth number of rows to analyze
- * @param preferred preferred delimiter characters
- * @param enclosure enclosure character, default is double quote (").
- * @return delimiter character
- */
- function auto ($file = null, $parse = true, $search_depth = null, $preferred = null, $enclosure = null) {
-
- if ( $file === null ) $file = $this->file;
- if ( empty($search_depth) ) $search_depth = $this->auto_depth;
- if ( $enclosure === null ) $enclosure = $this->enclosure;
-
- if ( $preferred === null ) $preferred = $this->auto_preferred;
-
- if ( empty($this->file_data) ) {
- if ( $this->_check_data($file) ) {
- $data = &$this->file_data;
- } else return false;
- } else {
- $data = &$this->file_data;
- }
-
- $chars = [];
- $strlen = strlen($data);
- $enclosed = false;
- $n = 1;
- $to_end = true;
-
- // walk specific depth finding posssible delimiter characters
- for ( $i=0; $i < $strlen; $i++ ) {
- $ch = $data{$i};
- $nch = ( isset($data{$i+1}) ) ? $data{$i+1} : false ;
- $pch = ( isset($data{$i-1}) ) ? $data{$i-1} : false ;
-
- // open and closing quotes
- if ( $ch == $enclosure && (!$enclosed || $nch != $enclosure) ) {
- $enclosed = ( $enclosed ) ? false : true ;
-
- // inline quotes
- } elseif ( $ch == $enclosure && $enclosed ) {
- $i++;
-
- // end of row
- } elseif ( ($ch == "\n" && $pch != "\r" || $ch == "\r") && !$enclosed ) {
- if ( $n >= $search_depth ) {
- $strlen = 0;
- $to_end = false;
- } else {
- $n++;
- }
-
- // count character
- } elseif (!$enclosed) {
- if ( !preg_match('/['.preg_quote($this->auto_non_chars, '/').']/i', $ch) ) {
- if ( !isset($chars[$ch][$n]) ) {
- $chars[$ch][$n] = 1;
- } else {
- $chars[$ch][$n]++;
- }
- }
- }
- }
-
- // filtering
- $depth = ( $to_end ) ? $n-1 : $n ;
- $filtered = [];
- foreach( $chars as $char => $value ) {
- if ( $match = $this->_check_count($char, $value, $depth, $preferred) ) {
- $filtered[$match] = $char;
- }
- }
-
- // capture most probable delimiter
- ksort($filtered);
- $delimiter = reset($filtered);
- $this->delimiter = $delimiter;
-
- // parse data
- if ( $parse ) $this->data = $this->parse_string();
-
- return $delimiter;
-
- }
-
-
- // ==============================================
- // ----- [ Core Functions ] ---------------------
- // ==============================================
-
- /**
- * Read file to string and call parse_string()
- * @param file local CSV file
- * @return 2D array with CSV data, or false on failure
- */
- function parse_file ($file = null) {
- if ( $file === null ) $file = $this->file;
- if ( empty($this->file_data) ) $this->load_data($file);
- return ( !empty($this->file_data) ) ? $this->parse_string() : false ;
- }
-
- /**
- * Parse CSV strings to arrays
- * @param data CSV string
- * @return 2D array with CSV data, or false on failure
- */
- function parse_string ($data = null) {
- if ( empty($data) ) {
- if ( $this->_check_data() ) {
- $data = &$this->file_data;
- } else return false;
- }
-
- $rows = [];
- $row = [];
- $row_count = 0;
- $current = '';
- $head = ( !empty($this->fields) ) ? $this->fields : [] ;
- $col = 0;
- $enclosed = false;
- $was_enclosed = false;
- $strlen = strlen($data);
-
- // walk through each character
- for ( $i=0; $i < $strlen; $i++ ) {
- $ch = $data{$i};
- $nch = ( isset($data{$i+1}) ) ? $data{$i+1} : false ;
- $pch = ( isset($data{$i-1}) ) ? $data{$i-1} : false ;
-
- // open and closing quotes
- if ( $ch == $this->enclosure && (!$enclosed || $nch != $this->enclosure) ) {
- $enclosed = ( $enclosed ) ? false : true ;
- if ( $enclosed ) $was_enclosed = true;
-
- // inline quotes
- } elseif ( $ch == $this->enclosure && $enclosed ) {
- $current .= $ch;
- $i++;
-
- // end of field/row
- } elseif ( ($ch == $this->delimiter || ($ch == "\n" && $pch != "\r") || $ch == "\r") && !$enclosed ) {
- if ( !$was_enclosed ) $current = trim($current);
- $key = ( !empty($head[$col]) ) ? $head[$col] : $col ;
- $row[$key] = $current;
- $current = '';
- $col++;
-
- // end of row
- if ( $ch == "\n" || $ch == "\r" ) {
- if ( $this->_validate_offset($row_count) && $this->_validate_row_conditions($row, $this->conditions) ) {
- if ( $this->heading && empty($head) ) {
- $head = $row;
- } elseif ( empty($this->fields) || (!empty($this->fields) && (($this->heading && $row_count > 0) || !$this->heading)) ) {
- if ( !empty($this->sort_by) && !empty($row[$this->sort_by]) ) {
- if ( isset($rows[$row[$this->sort_by]]) ) {
- $rows[$row[$this->sort_by].'_0'] = &$rows[$row[$this->sort_by]];
- unset($rows[$row[$this->sort_by]]);
- for ( $sn=1; isset($rows[$row[$this->sort_by].'_'.$sn]); $sn++ ) {}
- $rows[$row[$this->sort_by].'_'.$sn] = $row;
- } else $rows[$row[$this->sort_by]] = $row;
- } else $rows[] = $row;
- }
- }
- $row = [];
- $col = 0;
- $row_count++;
- if ( $this->sort_by === null && $this->limit !== null && count($rows) == $this->limit ) {
- $i = $strlen;
- }
- }
-
- // append character to current field
- } else {
- $current .= $ch;
- }
- }
- $this->titles = $head;
- if ( !empty($this->sort_by) ) {
- ( $this->sort_reverse ) ? krsort($rows) : ksort($rows) ;
- if ( $this->offset !== null || $this->limit !== null ) {
- $rows = array_slice($rows, ($this->offset === null ? 0 : $this->offset) , $this->limit, true);
- }
- }
- return $rows;
- }
-
- /**
- * Create CSV data from array
- * @param data 2D array with data
- * @param fields field names
- * @param append if true, field names will not be output
- * @param is_php if a php die() call should be put on the first
- * line of the file, this is later ignored when read.
- * @param delimiter field delimiter to use
- * @return CSV data (text string)
- */
- function unparse ( $data = [], $fields = [], $append = false , $is_php = false, $delimiter = null) {
- if ( !is_array($data) || empty($data) ) $data = &$this->data;
- if ( !is_array($fields) || empty($fields) ) $fields = &$this->titles;
- if ( $delimiter === null ) $delimiter = $this->delimiter;
-
- $string = ( $is_php ) ? "".$this->linefeed : '' ;
- $entry = [];
-
- // create heading
- if ( $this->heading && !$append ) {
- foreach( $fields as $key => $value ) {
- $entry[] = $this->_enclose_value($value);
- }
- $string .= implode($delimiter, $entry).$this->linefeed;
- $entry = [];
- }
-
- // create data
- foreach( $data as $key => $row ) {
- foreach( $row as $field => $value ) {
- $entry[] = $this->_enclose_value($value);
- }
- $string .= implode($delimiter, $entry).$this->linefeed;
- $entry = [];
- }
-
- return $string;
- }
-
- /**
- * Load local file or string
- * @param input local CSV file
- * @return true or false
- */
- function load_data ($input = null) {
- $data = null;
- $file = null;
- if ( $input === null ) {
- $file = $this->file;
- } elseif ( file_exists($input) ) {
- $file = $input;
- } else {
- $data = $input;
- }
- if ( !empty($data) || $data = $this->_rfile($file) ) {
- if ( $this->file != $file ) $this->file = $file;
- if ( preg_match('/\.php$/i', $file) && preg_match('/<\?.*?\?>(.*)/ims', $data, $strip) ) {
- $data = ltrim($strip[1]);
- }
- if ( $this->convert_encoding ) $data = iconv($this->input_encoding, $this->output_encoding, $data);
- if ( substr($data, -1) != "\n" ) $data .= "\n";
- $this->file_data = &$data;
- return true;
- }
- return false;
- }
-
-
- // ==============================================
- // ----- [ Internal Functions ] -----------------
- // ==============================================
-
- /**
- * Validate a row against specified conditions
- * @param row array with values from a row
- * @param conditions specified conditions that the row must match
- * @return true of false
- */
- function _validate_row_conditions ($row = [], $conditions = null) {
- if ( !empty($row) ) {
- if ( !empty($conditions) ) {
- $conditions = (strpos($conditions, ' OR ') !== false) ? explode(' OR ', $conditions) : [$conditions] ;
- $or = '';
- foreach( $conditions as $key => $value ) {
- if ( strpos($value, ' AND ') !== false ) {
- $value = explode(' AND ', $value);
- $and = '';
- foreach( $value as $k => $v ) {
- $and .= $this->_validate_row_condition($row, $v);
- }
- $or .= (strpos($and, '0') !== false) ? '0' : '1' ;
- } else {
- $or .= $this->_validate_row_condition($row, $value);
- }
- }
- return (strpos($or, '1') !== false) ? true : false ;
- }
- return true;
- }
- return false;
- }
-
- /**
- * Validate a row against a single condition
- * @param row array with values from a row
- * @param condition specified condition that the row must match
- * @return true of false
- */
- function _validate_row_condition ($row, $condition) {
- $operators = [
- '=', 'equals', 'is',
- '!=', 'is not',
- '<', 'is less than',
- '>', 'is greater than',
- '<=', 'is less than or equals',
- '>=', 'is greater than or equals',
- 'contains',
- 'does not contain',
- ];
- $operators_regex = [];
- foreach( $operators as $value ) {
- $operators_regex[] = preg_quote($value, '/');
- }
- $operators_regex = implode('|', $operators_regex);
- if ( preg_match('/^(.+) ('.$operators_regex.') (.+)$/i', trim($condition), $capture) ) {
- $field = $capture[1];
- $op = $capture[2];
- $value = $capture[3];
- if ( preg_match('/^([\'\"]{1})(.*)([\'\"]{1})$/i', $value, $capture) ) {
- if ( $capture[1] == $capture[3] ) {
- $value = $capture[2];
- $value = str_replace('\\n', "\n", $value);
- $value = str_replace('\\r', "\r", $value);
- $value = str_replace('\\t', "\t", $value);
- $value = stripslashes($value);
- }
- }
- if ( array_key_exists($field, $row) ) {
- if ( ($op == '=' || $op == 'equals' || $op == 'is') && $row[$field] == $value ) {
- return '1';
- } elseif ( ($op == '!=' || $op == 'is not') && $row[$field] != $value ) {
- return '1';
- } elseif ( ($op == '<' || $op == 'is less than' ) && $row[$field] < $value ) {
- return '1';
- } elseif ( ($op == '>' || $op == 'is greater than') && $row[$field] > $value ) {
- return '1';
- } elseif ( ($op == '<=' || $op == 'is less than or equals' ) && $row[$field] <= $value ) {
- return '1';
- } elseif ( ($op == '>=' || $op == 'is greater than or equals') && $row[$field] >= $value ) {
- return '1';
- } elseif ( $op == 'contains' && preg_match('/'.preg_quote($value, '/').'/i', $row[$field]) ) {
- return '1';
- } elseif ( $op == 'does not contain' && !preg_match('/'.preg_quote($value, '/').'/i', $row[$field]) ) {
- return '1';
- } else {
- return '0';
- }
- }
- }
- return '1';
- }
-
- /**
- * Validates if the row is within the offset or not if sorting is disabled
- * @param current_row the current row number being processed
- * @return true of false
- */
- function _validate_offset ($current_row) {
- if ( $this->sort_by === null && $this->offset !== null && $current_row < $this->offset ) return false;
- return true;
- }
-
- /**
- * Enclose values if needed
- * - only used by unparse()
- * @param value string to process
- * @return Processed value
- */
- function _enclose_value ($value = null) {
- if ( $value !== null && $value != '' ) {
- $delimiter = preg_quote($this->delimiter, '/');
- $enclosure = preg_quote($this->enclosure, '/');
- if ( preg_match('/'.$delimiter.'|'.$enclosure."|\n|\r/i", $value) || ($value{0} == ' ' || substr($value, -1) == ' ') ) {
- $value = str_replace($this->enclosure, $this->enclosure.$this->enclosure, $value);
- $value = $this->enclosure.$value.$this->enclosure;
- }
- }
- return $value;
- }
-
- /**
- * Check file data
- * @param file local filename
- * @return true or false
- */
- function _check_data ($file = null) {
- if ( empty($this->file_data) ) {
- if ( $file === null ) $file = $this->file;
- return $this->load_data($file);
- }
- return true;
- }
-
-
- /**
- * Check if passed info might be delimiter
- * - only used by find_delimiter()
- * @return special string used for delimiter selection, or false
- */
- function _check_count ($char, $array, $depth, $preferred) {
- if ( $depth == count($array) ) {
- $first = null;
- $equal = null;
- $almost = false;
- foreach( $array as $key => $value ) {
- if ( $first == null ) {
- $first = $value;
- } elseif ( $value == $first && $equal !== false) {
- $equal = true;
- } elseif ( $value == $first+1 && $equal !== false ) {
- $equal = true;
- $almost = true;
- } else {
- $equal = false;
- }
- }
- if ( $equal ) {
- $match = ( $almost ) ? 2 : 1 ;
- $pref = strpos($preferred, $char);
- $pref = ( $pref !== false ) ? str_pad($pref, 3, '0', STR_PAD_LEFT) : '999' ;
- return $pref.$match.'.'.(99999 - str_pad($first, 5, '0', STR_PAD_LEFT));
- } else return false;
- }
- }
-
- /**
- * Read local file
- * @param file local filename
- * @return Data from file, or false on failure
- */
- function _rfile ($file = null) {
- if ( is_readable($file) ) {
- if ( !($fh = fopen($file, 'r')) ) return false;
- $data = fread($fh, filesize($file));
- fclose($fh);
- return $data;
- }
- return false;
- }
-
- /**
- * Write to local file
- * @param file local filename
- * @param string data to write to file
- * @param mode fopen() mode
- * @param lock flock() mode
- * @return true or false
- */
- function _wfile ($file, $string = '', $mode = 'wb', $lock = 2) {
- if ( $fp = fopen($file, $mode) ) {
- flock($fp, $lock);
- $re = fwrite($fp, $string);
- $re2 = fclose($fp);
- if ( $re != false && $re2 != false ) return true;
- }
- return false;
- }
-
+ /**
+ * Configuration
+ * - set these options with $object->var_name = 'value';.
+ */
+
+ // use first line/entry as field names
+ public $heading = true;
+
+ // override field names
+ public $fields = [];
+
+ // sort entries by this field
+ public $sort_by = null;
+ public $sort_reverse = false;
+
+ // delimiter (comma) and enclosure (double quote)
+ public $delimiter = ',';
+ public $enclosure = '"';
+
+ // basic SQL-like conditions for row matching
+ public $conditions = null;
+
+ // number of rows to ignore from beginning of data
+ public $offset = null;
+
+ // limits the number of returned rows to specified amount
+ public $limit = null;
+
+ // number of rows to analyze when attempting to auto-detect delimiter
+ public $auto_depth = 15;
+
+ // characters to ignore when attempting to auto-detect delimiter
+ public $auto_non_chars = "a-zA-Z0-9\n\r";
+
+ // preferred delimiter characters, only used when all filtering method
+ // returns multiple possible delimiters (happens very rarely)
+ public $auto_preferred = ",;\t.:|";
+
+ // character encoding options
+ public $convert_encoding = false;
+ public $input_encoding = 'ISO-8859-1';
+ public $output_encoding = 'ISO-8859-1';
+
+ // used by unparse(), save(), and output() functions
+ public $linefeed = "\r\n";
+
+ // only used by output() function
+ public $output_delimiter = ',';
+ public $output_filename = 'data.csv';
+
+ /**
+ * Internal variables.
+ */
+
+ // current file
+ public $file;
+
+ // loaded file contents
+ public $file_data;
+
+ // array of field values in data parsed
+ public $titles = [];
+
+ // two dimentional array of CSV data
+ public $data = [];
+
+ /**
+ * Constructor.
+ *
+ * @param input CSV file or string
+ * @param null|mixed $input
+ * @param null|mixed $offset
+ * @param null|mixed $limit
+ * @param null|mixed $conditions
+ *
+ * @return nothing
+ */
+ public function __construct($input = null, $offset = null, $limit = null, $conditions = null)
+ {
+ if ($offset !== null) {
+ $this->offset = $offset;
+ }
+ if ($limit !== null) {
+ $this->limit = $limit;
+ }
+ if (count($conditions) > 0) {
+ $this->conditions = $conditions;
+ }
+ if (! empty($input)) {
+ $this->parse($input);
+ }
+ }
+
+ // ==============================================
+ // ----- [ Main Functions ] ---------------------
+ // ==============================================
+
+ /**
+ * Parse CSV file or string.
+ *
+ * @param input CSV file or string
+ * @param null|mixed $input
+ * @param null|mixed $offset
+ * @param null|mixed $limit
+ * @param null|mixed $conditions
+ *
+ * @return nothing
+ */
+ public function parse($input = null, $offset = null, $limit = null, $conditions = null)
+ {
+ if (! empty($input)) {
+ if ($offset !== null) {
+ $this->offset = $offset;
+ }
+ if ($limit !== null) {
+ $this->limit = $limit;
+ }
+ if (count($conditions) > 0) {
+ $this->conditions = $conditions;
+ }
+ if (is_readable($input)) {
+ $this->data = $this->parse_file($input);
+ } else {
+ $this->file_data = &$input;
+ $this->data = $this->parse_string();
+ }
+ if ($this->data === false) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Save changes, or new file and/or data.
+ *
+ * @param file file to save to
+ * @param data 2D array with data
+ * @param append append current data to end of target CSV if exists
+ * @param fields field names
+ * @param null|mixed $file
+ * @param mixed $data
+ * @param mixed $append
+ * @param mixed $fields
+ *
+ * @return true or false
+ */
+ public function save($file = null, $data = [], $append = false, $fields = [])
+ {
+ if (empty($file)) {
+ $file = &$this->file;
+ }
+ $mode = ($append) ? 'at' : 'wt';
+ $is_php = (preg_match('/\.php$/i', $file)) ? true : false;
+
+ return $this->_wfile($file, $this->unparse($data, $fields, $append, $is_php), $mode);
+ }
+
+ /**
+ * Generate CSV based string for output.
+ *
+ * @param output if true, prints headers and strings to browser
+ * @param filename filename sent to browser in headers if output is true
+ * @param data 2D array with data
+ * @param fields field names
+ * @param delimiter delimiter used to separate data
+ * @param mixed $output
+ * @param null|mixed $filename
+ * @param mixed $data
+ * @param mixed $fields
+ * @param null|mixed $delimiter
+ *
+ * @return CSV data using delimiter of choice, or default
+ */
+ public function output($output = true, $filename = null, $data = [], $fields = [], $delimiter = null)
+ {
+ if (empty($filename)) {
+ $filename = $this->output_filename;
+ }
+ if ($delimiter === null) {
+ $delimiter = $this->output_delimiter;
+ }
+ $data = $this->unparse($data, $fields, null, null, $delimiter);
+ if ($output) {
+ header('Content-type: application/csv');
+ header('Content-Disposition: inline; filename="'.$filename.'"');
+ echo $data;
+ }
+
+ return $data;
+ }
+
+ /**
+ * Convert character encoding.
+ *
+ * @param input input character encoding, uses default if left blank
+ * @param output output character encoding, uses default if left blank
+ * @param null|mixed $input
+ * @param null|mixed $output
+ *
+ * @return nothing
+ */
+ public function encoding($input = null, $output = null)
+ {
+ $this->convert_encoding = true;
+ if ($input !== null) {
+ $this->input_encoding = $input;
+ }
+ if ($output !== null) {
+ $this->output_encoding = $output;
+ }
+ }
+
+ /**
+ * Auto-Detect Delimiter: Find delimiter by analyzing a specific number of
+ * rows to determine most probable delimiter character.
+ *
+ * @param file local CSV file
+ * @param parse true/false parse file directly
+ * @param search_depth number of rows to analyze
+ * @param preferred preferred delimiter characters
+ * @param enclosure enclosure character, default is double quote (").
+ * @param null|mixed $file
+ * @param mixed $parse
+ * @param null|mixed $search_depth
+ * @param null|mixed $preferred
+ * @param null|mixed $enclosure
+ *
+ * @return delimiter character
+ */
+ public function auto($file = null, $parse = true, $search_depth = null, $preferred = null, $enclosure = null)
+ {
+ if ($file === null) {
+ $file = $this->file;
+ }
+ if (empty($search_depth)) {
+ $search_depth = $this->auto_depth;
+ }
+ if ($enclosure === null) {
+ $enclosure = $this->enclosure;
+ }
+
+ if ($preferred === null) {
+ $preferred = $this->auto_preferred;
+ }
+
+ if (empty($this->file_data)) {
+ if ($this->_check_data($file)) {
+ $data = &$this->file_data;
+ } else {
+ return false;
+ }
+ } else {
+ $data = &$this->file_data;
+ }
+
+ $chars = [];
+ $strlen = strlen($data);
+ $enclosed = false;
+ $n = 1;
+ $to_end = true;
+
+ // walk specific depth finding posssible delimiter characters
+ for ($i = 0; $i < $strlen; $i++) {
+ $ch = $data{$i};
+ $nch = (isset($data{$i + 1})) ? $data{$i + 1} : false;
+ $pch = (isset($data{$i - 1})) ? $data{$i - 1} : false;
+
+ // open and closing quotes
+ if ($ch == $enclosure && (! $enclosed || $nch != $enclosure)) {
+ $enclosed = ($enclosed) ? false : true;
+
+ // inline quotes
+ } elseif ($ch == $enclosure && $enclosed) {
+ $i++;
+
+ // end of row
+ } elseif (($ch == "\n" && $pch != "\r" || $ch == "\r") && ! $enclosed) {
+ if ($n >= $search_depth) {
+ $strlen = 0;
+ $to_end = false;
+ } else {
+ $n++;
+ }
+
+ // count character
+ } elseif (! $enclosed) {
+ if (! preg_match('/['.preg_quote($this->auto_non_chars, '/').']/i', $ch)) {
+ if (! isset($chars[$ch][$n])) {
+ $chars[$ch][$n] = 1;
+ } else {
+ $chars[$ch][$n]++;
+ }
+ }
+ }
+ }
+
+ // filtering
+ $depth = ($to_end) ? $n - 1 : $n;
+ $filtered = [];
+ foreach ($chars as $char => $value) {
+ if ($match = $this->_check_count($char, $value, $depth, $preferred)) {
+ $filtered[$match] = $char;
+ }
+ }
+
+ // capture most probable delimiter
+ ksort($filtered);
+ $delimiter = reset($filtered);
+ $this->delimiter = $delimiter;
+
+ // parse data
+ if ($parse) {
+ $this->data = $this->parse_string();
+ }
+
+ return $delimiter;
+ }
+
+ // ==============================================
+ // ----- [ Core Functions ] ---------------------
+ // ==============================================
+
+ /**
+ * Read file to string and call parse_string().
+ *
+ * @param file local CSV file
+ * @param null|mixed $file
+ *
+ * @return 2D array with CSV data, or false on failure
+ */
+ public function parse_file($file = null)
+ {
+ if ($file === null) {
+ $file = $this->file;
+ }
+ if (empty($this->file_data)) {
+ $this->load_data($file);
+ }
+
+ return (! empty($this->file_data)) ? $this->parse_string() : false;
+ }
+
+ /**
+ * Parse CSV strings to arrays.
+ *
+ * @param data CSV string
+ * @param null|mixed $data
+ *
+ * @return 2D array with CSV data, or false on failure
+ */
+ public function parse_string($data = null)
+ {
+ if (empty($data)) {
+ if ($this->_check_data()) {
+ $data = &$this->file_data;
+ } else {
+ return false;
+ }
+ }
+
+ $rows = [];
+ $row = [];
+ $row_count = 0;
+ $current = '';
+ $head = (! empty($this->fields)) ? $this->fields : [];
+ $col = 0;
+ $enclosed = false;
+ $was_enclosed = false;
+ $strlen = strlen($data);
+
+ // walk through each character
+ for ($i = 0; $i < $strlen; $i++) {
+ $ch = $data{$i};
+ $nch = (isset($data{$i + 1})) ? $data{$i + 1} : false;
+ $pch = (isset($data{$i - 1})) ? $data{$i - 1} : false;
+
+ // open and closing quotes
+ if ($ch == $this->enclosure && (! $enclosed || $nch != $this->enclosure)) {
+ $enclosed = ($enclosed) ? false : true;
+ if ($enclosed) {
+ $was_enclosed = true;
+ }
+
+ // inline quotes
+ } elseif ($ch == $this->enclosure && $enclosed) {
+ $current .= $ch;
+ $i++;
+
+ // end of field/row
+ } elseif (($ch == $this->delimiter || ($ch == "\n" && $pch != "\r") || $ch == "\r") && ! $enclosed) {
+ if (! $was_enclosed) {
+ $current = trim($current);
+ }
+ $key = (! empty($head[$col])) ? $head[$col] : $col;
+ $row[$key] = $current;
+ $current = '';
+ $col++;
+
+ // end of row
+ if ($ch == "\n" || $ch == "\r") {
+ if ($this->_validate_offset($row_count) && $this->_validate_row_conditions($row, $this->conditions)) {
+ if ($this->heading && empty($head)) {
+ $head = $row;
+ } elseif (empty($this->fields) || (! empty($this->fields) && (($this->heading && $row_count > 0) || ! $this->heading))) {
+ if (! empty($this->sort_by) && ! empty($row[$this->sort_by])) {
+ if (isset($rows[$row[$this->sort_by]])) {
+ $rows[$row[$this->sort_by].'_0'] = &$rows[$row[$this->sort_by]];
+ unset($rows[$row[$this->sort_by]]);
+ for ($sn = 1; isset($rows[$row[$this->sort_by].'_'.$sn]); $sn++) {
+ }
+ $rows[$row[$this->sort_by].'_'.$sn] = $row;
+ } else {
+ $rows[$row[$this->sort_by]] = $row;
+ }
+ } else {
+ $rows[] = $row;
+ }
+ }
+ }
+ $row = [];
+ $col = 0;
+ $row_count++;
+ if ($this->sort_by === null && $this->limit !== null && count($rows) == $this->limit) {
+ $i = $strlen;
+ }
+ }
+
+ // append character to current field
+ } else {
+ $current .= $ch;
+ }
+ }
+ $this->titles = $head;
+ if (! empty($this->sort_by)) {
+ ($this->sort_reverse) ? krsort($rows) : ksort($rows);
+ if ($this->offset !== null || $this->limit !== null) {
+ $rows = array_slice($rows, ($this->offset === null ? 0 : $this->offset), $this->limit, true);
+ }
+ }
+
+ return $rows;
+ }
+
+ /**
+ * Create CSV data from array.
+ *
+ * @param data 2D array with data
+ * @param fields field names
+ * @param append if true, field names will not be output
+ * @param is_php if a php die() call should be put on the first
+ * line of the file, this is later ignored when read.
+ * @param delimiter field delimiter to use
+ * @param mixed $data
+ * @param mixed $fields
+ * @param mixed $append
+ * @param mixed $is_php
+ * @param null|mixed $delimiter
+ *
+ * @return CSV data (text string)
+ */
+ public function unparse($data = [], $fields = [], $append = false, $is_php = false, $delimiter = null)
+ {
+ if (! is_array($data) || empty($data)) {
+ $data = &$this->data;
+ }
+ if (! is_array($fields) || empty($fields)) {
+ $fields = &$this->titles;
+ }
+ if ($delimiter === null) {
+ $delimiter = $this->delimiter;
+ }
+
+ $string = ($is_php) ? "".$this->linefeed : '';
+ $entry = [];
+
+ // create heading
+ if ($this->heading && ! $append) {
+ foreach ($fields as $key => $value) {
+ $entry[] = $this->_enclose_value($value);
+ }
+ $string .= implode($delimiter, $entry).$this->linefeed;
+ $entry = [];
+ }
+
+ // create data
+ foreach ($data as $key => $row) {
+ foreach ($row as $field => $value) {
+ $entry[] = $this->_enclose_value($value);
+ }
+ $string .= implode($delimiter, $entry).$this->linefeed;
+ $entry = [];
+ }
+
+ return $string;
+ }
+
+ /**
+ * Load local file or string.
+ *
+ * @param input local CSV file
+ * @param null|mixed $input
+ *
+ * @return true or false
+ */
+ public function load_data($input = null)
+ {
+ $data = null;
+ $file = null;
+ if ($input === null) {
+ $file = $this->file;
+ } elseif (file_exists($input)) {
+ $file = $input;
+ } else {
+ $data = $input;
+ }
+ if (! empty($data) || $data = $this->_rfile($file)) {
+ if ($this->file != $file) {
+ $this->file = $file;
+ }
+ if (preg_match('/\.php$/i', $file) && preg_match('/<\?.*?\?>(.*)/ims', $data, $strip)) {
+ $data = ltrim($strip[1]);
+ }
+ if ($this->convert_encoding) {
+ $data = iconv($this->input_encoding, $this->output_encoding, $data);
+ }
+ if (substr($data, -1) != "\n") {
+ $data .= "\n";
+ }
+ $this->file_data = &$data;
+
+ return true;
+ }
+
+ return false;
+ }
+
+ // ==============================================
+ // ----- [ Internal Functions ] -----------------
+ // ==============================================
+
+ /**
+ * Validate a row against specified conditions.
+ *
+ * @param row array with values from a row
+ * @param conditions specified conditions that the row must match
+ * @param mixed $row
+ * @param null|mixed $conditions
+ *
+ * @return true of false
+ */
+ public function _validate_row_conditions($row = [], $conditions = null)
+ {
+ if (! empty($row)) {
+ if (! empty($conditions)) {
+ $conditions = (strpos($conditions, ' OR ') !== false) ? explode(' OR ', $conditions) : [$conditions];
+ $or = '';
+ foreach ($conditions as $key => $value) {
+ if (strpos($value, ' AND ') !== false) {
+ $value = explode(' AND ', $value);
+ $and = '';
+ foreach ($value as $k => $v) {
+ $and .= $this->_validate_row_condition($row, $v);
+ }
+ $or .= (strpos($and, '0') !== false) ? '0' : '1';
+ } else {
+ $or .= $this->_validate_row_condition($row, $value);
+ }
+ }
+
+ return (strpos($or, '1') !== false) ? true : false;
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Validate a row against a single condition.
+ *
+ * @param row array with values from a row
+ * @param condition specified condition that the row must match
+ * @param mixed $row
+ * @param mixed $condition
+ *
+ * @return true of false
+ */
+ public function _validate_row_condition($row, $condition)
+ {
+ $operators = [
+ '=', 'equals', 'is',
+ '!=', 'is not',
+ '<', 'is less than',
+ '>', 'is greater than',
+ '<=', 'is less than or equals',
+ '>=', 'is greater than or equals',
+ 'contains',
+ 'does not contain',
+ ];
+ $operators_regex = [];
+ foreach ($operators as $value) {
+ $operators_regex[] = preg_quote($value, '/');
+ }
+ $operators_regex = implode('|', $operators_regex);
+ if (preg_match('/^(.+) ('.$operators_regex.') (.+)$/i', trim($condition), $capture)) {
+ $field = $capture[1];
+ $op = $capture[2];
+ $value = $capture[3];
+ if (preg_match('/^([\'\"]{1})(.*)([\'\"]{1})$/i', $value, $capture)) {
+ if ($capture[1] == $capture[3]) {
+ $value = $capture[2];
+ $value = str_replace('\\n', "\n", $value);
+ $value = str_replace('\\r', "\r", $value);
+ $value = str_replace('\\t', "\t", $value);
+ $value = stripslashes($value);
+ }
+ }
+ if (array_key_exists($field, $row)) {
+ if (($op == '=' || $op == 'equals' || $op == 'is') && $row[$field] == $value) {
+ return '1';
+ } elseif (($op == '!=' || $op == 'is not') && $row[$field] != $value) {
+ return '1';
+ } elseif (($op == '<' || $op == 'is less than') && $row[$field] < $value) {
+ return '1';
+ } elseif (($op == '>' || $op == 'is greater than') && $row[$field] > $value) {
+ return '1';
+ } elseif (($op == '<=' || $op == 'is less than or equals') && $row[$field] <= $value) {
+ return '1';
+ } elseif (($op == '>=' || $op == 'is greater than or equals') && $row[$field] >= $value) {
+ return '1';
+ } elseif ($op == 'contains' && preg_match('/'.preg_quote($value, '/').'/i', $row[$field])) {
+ return '1';
+ } elseif ($op == 'does not contain' && ! preg_match('/'.preg_quote($value, '/').'/i', $row[$field])) {
+ return '1';
+ } else {
+ return '0';
+ }
+ }
+ }
+
+ return '1';
+ }
+
+ /**
+ * Validates if the row is within the offset or not if sorting is disabled.
+ *
+ * @param current_row the current row number being processed
+ * @param mixed $current_row
+ *
+ * @return true of false
+ */
+ public function _validate_offset($current_row)
+ {
+ if ($this->sort_by === null && $this->offset !== null && $current_row < $this->offset) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Enclose values if needed
+ * - only used by unparse().
+ *
+ * @param value string to process
+ * @param null|mixed $value
+ *
+ * @return Processed value
+ */
+ public function _enclose_value($value = null)
+ {
+ if ($value !== null && $value != '') {
+ $delimiter = preg_quote($this->delimiter, '/');
+ $enclosure = preg_quote($this->enclosure, '/');
+ if (preg_match('/'.$delimiter.'|'.$enclosure."|\n|\r/i", $value) || ($value{0} == ' ' || substr($value, -1) == ' ')) {
+ $value = str_replace($this->enclosure, $this->enclosure.$this->enclosure, $value);
+ $value = $this->enclosure.$value.$this->enclosure;
+ }
+ }
+
+ return $value;
+ }
+
+ /**
+ * Check file data.
+ *
+ * @param file local filename
+ * @param null|mixed $file
+ *
+ * @return true or false
+ */
+ public function _check_data($file = null)
+ {
+ if (empty($this->file_data)) {
+ if ($file === null) {
+ $file = $this->file;
+ }
+
+ return $this->load_data($file);
+ }
+
+ return true;
+ }
+
+ /**
+ * Check if passed info might be delimiter
+ * - only used by find_delimiter().
+ *
+ * @param mixed $char
+ * @param mixed $array
+ * @param mixed $depth
+ * @param mixed $preferred
+ *
+ * @return special string used for delimiter selection, or false
+ */
+ public function _check_count($char, $array, $depth, $preferred)
+ {
+ if ($depth == count($array)) {
+ $first = null;
+ $equal = null;
+ $almost = false;
+ foreach ($array as $key => $value) {
+ if ($first == null) {
+ $first = $value;
+ } elseif ($value == $first && $equal !== false) {
+ $equal = true;
+ } elseif ($value == $first + 1 && $equal !== false) {
+ $equal = true;
+ $almost = true;
+ } else {
+ $equal = false;
+ }
+ }
+ if ($equal) {
+ $match = ($almost) ? 2 : 1;
+ $pref = strpos($preferred, $char);
+ $pref = ($pref !== false) ? str_pad($pref, 3, '0', STR_PAD_LEFT) : '999';
+
+ return $pref.$match.'.'.(99999 - str_pad($first, 5, '0', STR_PAD_LEFT));
+ } else {
+ return false;
+ }
+ }
+ }
+
+ /**
+ * Read local file.
+ *
+ * @param file local filename
+ * @param null|mixed $file
+ *
+ * @return Data from file, or false on failure
+ */
+ public function _rfile($file = null)
+ {
+ if (is_readable($file)) {
+ if (! ($fh = fopen($file, 'r'))) {
+ return false;
+ }
+ $data = fread($fh, filesize($file));
+ fclose($fh);
+
+ return $data;
+ }
+
+ return false;
+ }
+
+ /**
+ * Write to local file.
+ *
+ * @param file local filename
+ * @param string data to write to file
+ * @param mode fopen() mode
+ * @param lock flock() mode
+ * @param mixed $file
+ * @param mixed $string
+ * @param mixed $mode
+ * @param mixed $lock
+ *
+ * @return true or false
+ */
+ public function _wfile($file, $string = '', $mode = 'wb', $lock = 2)
+ {
+ if ($fp = fopen($file, $mode)) {
+ flock($fp, $lock);
+ $re = fwrite($fp, $string);
+ $re2 = fclose($fp);
+ if ($re != false && $re2 != false) {
+ return true;
+ }
+ }
+
+ return false;
+ }
}
-
-?>
diff --git a/app/Jobs/Job.php b/app/Jobs/Job.php
index cd1bae1ceb3d..605ad09ff400 100644
--- a/app/Jobs/Job.php
+++ b/app/Jobs/Job.php
@@ -17,7 +17,7 @@ abstract class Job
*/
protected $jobName;
- /**
+ /*
* Handle a job failure.
*
* @param ContactMailer $mailer
diff --git a/app/Jobs/SendInvoiceEmail.php b/app/Jobs/SendInvoiceEmail.php
index 8194a1c95684..a638b2b049c0 100644
--- a/app/Jobs/SendInvoiceEmail.php
+++ b/app/Jobs/SendInvoiceEmail.php
@@ -4,14 +4,13 @@ namespace App\Jobs;
use App\Models\Invoice;
use App\Ninja\Mailers\ContactMailer;
-use Illuminate\Queue\SerializesModels;
-use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Queue\SerializesModels;
use Monolog\Logger;
-use Carbon;
/**
- * Class SendInvoiceEmail
+ * Class SendInvoiceEmail.
*/
class SendInvoiceEmail extends Job implements ShouldQueue
{
@@ -32,18 +31,25 @@ class SendInvoiceEmail extends Job implements ShouldQueue
*/
protected $pdfString;
+ /**
+ * @var array
+ */
+ protected $template;
+
/**
* Create a new job instance.
*
* @param Invoice $invoice
- * @param string $pdf
- * @param bool $reminder
+ * @param string $pdf
+ * @param bool $reminder
+ * @param mixed $pdfString
*/
- public function __construct(Invoice $invoice, $reminder = false, $pdfString = false)
+ public function __construct(Invoice $invoice, $reminder = false, $pdfString = false, $template = false)
{
$this->invoice = $invoice;
$this->reminder = $reminder;
$this->pdfString = $pdfString;
+ $this->template = $template;
}
/**
@@ -53,10 +59,10 @@ class SendInvoiceEmail extends Job implements ShouldQueue
*/
public function handle(ContactMailer $mailer)
{
- $mailer->sendInvoice($this->invoice, $this->reminder, $this->pdfString);
+ $mailer->sendInvoice($this->invoice, $this->reminder, $this->pdfString, $this->template);
}
- /**
+ /*
* Handle a job failure.
*
* @param ContactMailer $mailer
diff --git a/app/Jobs/SendNotificationEmail.php b/app/Jobs/SendNotificationEmail.php
index 32eaa6c42de0..bd8e893967dd 100644
--- a/app/Jobs/SendNotificationEmail.php
+++ b/app/Jobs/SendNotificationEmail.php
@@ -4,14 +4,12 @@ namespace App\Jobs;
use App\Models\Payment;
use App\Ninja\Mailers\UserMailer;
-use Illuminate\Queue\SerializesModels;
-use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
-use Monolog\Logger;
-use Carbon;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Queue\SerializesModels;
/**
- * Class SendInvoiceEmail
+ * Class SendInvoiceEmail.
*/
class SendNotificationEmail extends Job implements ShouldQueue
{
@@ -37,13 +35,16 @@ class SendNotificationEmail extends Job implements ShouldQueue
*/
protected $payment;
-
/**
* Create a new job instance.
- * @param UserMailer $userMailer
+ * @param UserMailer $userMailer
* @param ContactMailer $contactMailer
- * @param PushService $pushService
+ * @param PushService $pushService
+ * @param mixed $user
+ * @param mixed $invoice
+ * @param mixed $type
+ * @param mixed $payment
*/
public function __construct($user, $invoice, $type, $payment)
{
@@ -62,5 +63,4 @@ class SendNotificationEmail extends Job implements ShouldQueue
{
$userMailer->sendNotification($this->user, $this->invoice, $this->type, $this->payment);
}
-
}
diff --git a/app/Jobs/SendPaymentEmail.php b/app/Jobs/SendPaymentEmail.php
index c27c0f5f44ad..e23d291efcec 100644
--- a/app/Jobs/SendPaymentEmail.php
+++ b/app/Jobs/SendPaymentEmail.php
@@ -4,14 +4,12 @@ namespace App\Jobs;
use App\Models\Payment;
use App\Ninja\Mailers\ContactMailer;
-use Illuminate\Queue\SerializesModels;
-use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
-use Monolog\Logger;
-use Carbon;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Queue\SerializesModels;
/**
- * Class SendInvoiceEmail
+ * Class SendInvoiceEmail.
*/
class SendPaymentEmail extends Job implements ShouldQueue
{
@@ -22,7 +20,6 @@ class SendPaymentEmail extends Job implements ShouldQueue
*/
protected $payment;
-
/**
* Create a new job instance.
@@ -42,6 +39,4 @@ class SendPaymentEmail extends Job implements ShouldQueue
{
$contactMailer->sendPaymentConfirmation($this->payment);
}
-
-
}
diff --git a/app/Jobs/SendPushNotification.php b/app/Jobs/SendPushNotification.php
index a9774e1f084c..88a1e59e1789 100644
--- a/app/Jobs/SendPushNotification.php
+++ b/app/Jobs/SendPushNotification.php
@@ -3,15 +3,13 @@
namespace App\Jobs;
use App\Models\Invoice;
-use Illuminate\Queue\SerializesModels;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Contracts\Queue\ShouldQueue;
use App\Services\PushService;
-use Monolog\Logger;
-use Carbon;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Queue\SerializesModels;
/**
- * Class SendInvoiceEmail
+ * Class SendInvoiceEmail.
*/
class SendPushNotification extends Job implements ShouldQueue
{
@@ -27,11 +25,11 @@ class SendPushNotification extends Job implements ShouldQueue
*/
protected $type;
-
/**
* Create a new job instance.
* @param Invoice $invoice
+ * @param mixed $type
*/
public function __construct($invoice, $type)
{
@@ -48,5 +46,4 @@ class SendPushNotification extends Job implements ShouldQueue
{
$pushService->sendNotification($this->invoice, $this->type);
}
-
}
diff --git a/app/Libraries/CurlUtils.php b/app/Libraries/CurlUtils.php
index 4a11a90939dd..263631fe5985 100644
--- a/app/Libraries/CurlUtils.php
+++ b/app/Libraries/CurlUtils.php
@@ -1,4 +1,6 @@
-send($request, $response);
-
+
if ($response->getStatus() === 200) {
return $response->getContent();
} else {
- //$response->getStatus();
+ Utils::logError('Local PhantomJS Error: ' . $response->getStatus() . ' - ' . $url);
return false;
}
-
}
}
diff --git a/app/Libraries/DateUtils.php b/app/Libraries/DateUtils.php
new file mode 100644
index 000000000000..2ee9b7596c58
--- /dev/null
+++ b/app/Libraries/DateUtils.php
@@ -0,0 +1,7 @@
+limit(100)
->get();
- foreach ($activities->reverse() as $activity)
- {
+ foreach ($activities->reverse() as $activity) {
if ($activity->activity_type_id == ACTIVITY_TYPE_CREATE_CLIENT) {
$entity = $activity->client;
- } else if ($activity->activity_type_id == ACTIVITY_TYPE_CREATE_TASK || $activity->activity_type_id == ACTIVITY_TYPE_UPDATE_TASK) {
+ } elseif ($activity->activity_type_id == ACTIVITY_TYPE_CREATE_TASK || $activity->activity_type_id == ACTIVITY_TYPE_UPDATE_TASK) {
$entity = $activity->task;
- if ( ! $entity) {
+ if (! $entity) {
continue;
}
$entity->setRelation('client', $activity->client);
- } else if ($activity->activity_type_id == ACTIVITY_TYPE_CREATE_EXPENSE || $activity->activity_type_id == ACTIVITY_TYPE_UPDATE_EXPENSE) {
+ } elseif ($activity->activity_type_id == ACTIVITY_TYPE_CREATE_EXPENSE || $activity->activity_type_id == ACTIVITY_TYPE_UPDATE_EXPENSE) {
$entity = $activity->expense;
- if ( ! $entity) {
+ if (! $entity) {
continue;
}
$entity->setRelation('client', $activity->client);
} else {
$entity = $activity->invoice;
- if ( ! $entity) {
+ if (! $entity) {
continue;
}
$entity->setRelation('client', $activity->client);
@@ -79,20 +79,20 @@ class HistoryUtils
ENTITY_INVOICE,
ENTITY_QUOTE,
ENTITY_TASK,
- ENTITY_EXPENSE
+ ENTITY_EXPENSE,
];
- if ( ! in_array($entityType, $trackedTypes)) {
+ if (! in_array($entityType, $trackedTypes)) {
return;
}
- $object = static::convertToObject($entity);
+ $object = static::convertToObject($entity);
$history = Session::get(RECENTLY_VIEWED) ?: [];
$accountHistory = isset($history[$entity->account_id]) ? $history[$entity->account_id] : [];
$data = [];
// Add to the list and make sure to only show each item once
- for ($i = 0; $i
";
}
public static function copyContext($entity1, $entity2)
{
- if (!$entity2) {
+ if (! $entity2) {
return $entity1;
}
@@ -1028,7 +1086,7 @@ class Utils
'payment_id',
'invoice_id',
'credit_id',
- 'invitation_id'
+ 'invitation_id',
];
$fields1 = $entity1->getAttributes();
@@ -1045,7 +1103,7 @@ class Utils
public static function addHttp($url)
{
- if (!preg_match('~^(?:f|ht)tps?://~i', $url)) {
+ if (! preg_match('~^(?:f|ht)tps?://~i', $url)) {
$url = 'http://' . $url;
}
@@ -1070,7 +1128,7 @@ class Utils
}
/**
- * Gets an array of weekday names (in English)
+ * Gets an array of weekday names (in English).
*
* @see getTranslatedWeekdayNames()
*
@@ -1082,14 +1140,14 @@ class Utils
}
/**
- * Gets an array of translated weekday names
+ * Gets an array of translated weekday names.
*
* @return \Illuminate\Support\Collection
*/
public static function getTranslatedWeekdayNames()
{
return collect(static::$weekdayNames)->transform(function ($day) {
- return trans('texts.'.strtolower($day));
+ return trans('texts.'.strtolower($day));
});
}
diff --git a/app/Libraries/entity.php b/app/Libraries/entity.php
index 57e447e2e271..c8802aa8008d 100644
--- a/app/Libraries/entity.php
+++ b/app/Libraries/entity.php
@@ -1,8 +1,7 @@
-
+
- # This code is licensed under the MIT license
- #
+
+ // This code is licensed under the MIT license
+ //
- ####################################################################
+ //###################################################################
- #
- # These are global options. You can set them before calling the autolinking
- # functions to change the output.
- #
+ //
+ // These are global options. You can set them before calling the autolinking
+ // functions to change the output.
+ //
- $GLOBALS['autolink_options'] = [
+ $GLOBALS['autolink_options'] = [
+
+ // Should http:// be visibly stripped from the front
+ // of URLs?
+ 'strip_protocols' => false,
+
+ ];
+
+ //###################################################################
+
+ function autolink($text, $limit = 30, $tagfill = '', $auto_title = true)
+ {
+ $text = autolink_do($text, '![a-z][a-z-]+://!i', $limit, $tagfill, $auto_title);
+ $text = autolink_do($text, '!(mailto|skype):!i', $limit, $tagfill, $auto_title);
+ $text = autolink_do($text, '!www\\.!i', $limit, $tagfill, $auto_title, 'http://');
+
+ return $text;
+ }
+
+ //###################################################################
+
+ function autolink_do($text, $sub, $limit, $tagfill, $auto_title, $force_prefix = null)
+ {
+ $text_l = strtolower($text);
+ $cursor = 0;
+ $loop = 1;
+ $buffer = '';
+
+ while (($cursor < strlen($text)) && $loop) {
+ $ok = 1;
+ $matched = preg_match($sub, $text_l, $m, PREG_OFFSET_CAPTURE, $cursor);
+
+ if (! $matched) {
+ $loop = 0;
+ $ok = 0;
+ } else {
+ $pos = $m[0][1];
+ $sub_len = strlen($m[0][0]);
+
+ $pre_hit = substr($text, $cursor, $pos - $cursor);
+ $hit = substr($text, $pos, $sub_len);
+ $pre = substr($text, 0, $pos);
+ $post = substr($text, $pos + $sub_len);
+
+ $fail_text = $pre_hit.$hit;
+ $fail_len = strlen($fail_text);
+
+ //
+ // substring found - first check to see if we're inside a link tag already...
+ //
+
+ $bits = preg_split('!
\n";
+
+ $ok = 0;
+ $cursor += $fail_len;
+ $buffer .= $fail_text;
+ }
+ }
+ }
+
+ //
+ // we want to autolink here - find the extent of the url
+ //
+
+ if ($ok) {
+ if (preg_match('/^([a-z0-9\-\.\/\-_%~!?=,:;&+*#@\(\)\$]+)/i', $post, $matches)) {
+ $url = $hit.$matches[1];
+
+ $cursor += strlen($url) + strlen($pre_hit);
+ $buffer .= $pre_hit;
+
+ $url = html_entity_decode($url);
+
+ //
+ // remove trailing punctuation from url
+ //
+
+ while (preg_match('|[.,!;:?]$|', $url)) {
+ $url = substr($url, 0, strlen($url) - 1);
+ $cursor--;
+ }
+ foreach (['()', '[]', '{}'] as $pair) {
+ $o = substr($pair, 0, 1);
+ $c = substr($pair, 1, 1);
+ if (preg_match("!^(\\$c|^)[^\\$o]+\\$c$!", $url)) {
+ $url = substr($url, 0, strlen($url) - 1);
+ $cursor--;
+ }
+ }
+
+ //
+ // nice-i-fy url here
+ //
+
+ $link_url = $url;
+ $display_url = $url;
+
+ if ($force_prefix) {
+ $link_url = $force_prefix.$link_url;
+ }
+
+ if ($GLOBALS['autolink_options']['strip_protocols']) {
+ if (preg_match('!^(http|https)://!i', $display_url, $m)) {
+ $display_url = substr($display_url, strlen($m[1]) + 3);
+ }
+ }
+
+ $display_url = autolink_label($display_url, $limit);
+
+ //
+ // add the url
+ //
+
+ $currentTagfill = $tagfill;
+ if ($display_url != $link_url && ! preg_match('@title=@msi', $currentTagfill) && $auto_title) {
+ $display_quoted = preg_quote($display_url, '!');
+
+ if (! preg_match("!^(http|https)://{$display_quoted}$!i", $link_url)) {
+ $currentTagfill .= ' title="'.$link_url.'"';
+ }
+ }
- # Should http:// be visibly stripped from the front
- # of URLs?
- 'strip_protocols' => false,
+ $link_url_enc = htmlspecialchars($link_url);
+ $display_url_enc = htmlspecialchars($display_url);
- ];
+ $buffer .= "{$display_url_enc}";
+ } else {
+ //echo "fail 3 at $cursor
\n";
- ####################################################################
+ $ok = 0;
+ $cursor += $fail_len;
+ $buffer .= $fail_text;
+ }
+ }
+ }
- function autolink($text, $limit=30, $tagfill='', $auto_title = true){
+ //
+ // add everything from the cursor to the end onto the buffer.
+ //
- $text = autolink_do($text, '![a-z][a-z-]+://!i', $limit, $tagfill, $auto_title);
- $text = autolink_do($text, '!(mailto|skype):!i', $limit, $tagfill, $auto_title);
- $text = autolink_do($text, '!www\\.!i', $limit, $tagfill, $auto_title, 'http://');
- return $text;
- }
+ $buffer .= substr($text, $cursor);
- ####################################################################
+ return $buffer;
+ }
- function autolink_do($text, $sub, $limit, $tagfill, $auto_title, $force_prefix=null){
+ //###################################################################
- $text_l = StrToLower($text);
- $cursor = 0;
- $loop = 1;
- $buffer = '';
+ function autolink_label($text, $limit)
+ {
+ if (! $limit) {
+ return $text;
+ }
- while (($cursor < strlen($text)) && $loop){
+ if (strlen($text) > $limit) {
+ return substr($text, 0, $limit - 3).'...';
+ }
- $ok = 1;
- $matched = preg_match($sub, $text_l, $m, PREG_OFFSET_CAPTURE, $cursor);
+ return $text;
+ }
- if (!$matched){
+ //###################################################################
- $loop = 0;
- $ok = 0;
+ function autolink_email($text, $tagfill = '')
+ {
+ $atom = '[^()<>@,;:\\\\".\\[\\]\\x00-\\x20\\x7f]+'; // from RFC822
- }else{
+ //die($atom);
- $pos = $m[0][1];
- $sub_len = strlen($m[0][0]);
+ $text_l = strtolower($text);
+ $cursor = 0;
+ $loop = 1;
+ $buffer = '';
- $pre_hit = substr($text, $cursor, $pos-$cursor);
- $hit = substr($text, $pos, $sub_len);
- $pre = substr($text, 0, $pos);
- $post = substr($text, $pos + $sub_len);
+ while (($cursor < strlen($text)) && $loop) {
- $fail_text = $pre_hit.$hit;
- $fail_len = strlen($fail_text);
+ //
+ // find an '@' symbol
+ //
- #
- # substring found - first check to see if we're inside a link tag already...
- #
+ $ok = 1;
+ $pos = strpos($text_l, '@', $cursor);
- $bits = preg_split('!!i', $pre);
- $last_bit = array_pop($bits);
- if (preg_match("!\n";
+ $fail_text = $pre.$hit;
+ $fail_len = strlen($fail_text);
- $ok = 0;
- $cursor += $fail_len;
- $buffer .= $fail_text;
- }
- }
+ //die("$pre::$hit::$post::$fail_text");
- #
- # looks like a nice spot to autolink from - check the pre
- # to see if there was whitespace before this match
- #
+ //
+ // substring found - first check to see if we're inside a link tag already...
+ //
- if ($ok){
+ $bits = preg_split('!!i', $pre);
+ $last_bit = array_pop($bits);
+ if (preg_match("!]$!s', $pre)){
+ //echo "fail 1 at $cursor
\n";
- #echo "fail 2 at $cursor ($pre)
\n";
+ $ok = 0;
+ $cursor += $fail_len;
+ $buffer .= $fail_text;
+ }
+ }
- $ok = 0;
- $cursor += $fail_len;
- $buffer .= $fail_text;
- }
- }
- }
+ //
+ // check backwards
+ //
- #
- # we want to autolink here - find the extent of the url
- #
+ if ($ok) {
+ if (preg_match("!($atom(\.$atom)*)\$!", $pre, $matches)) {
- if ($ok){
- if (preg_match('/^([a-z0-9\-\.\/\-_%~!?=,:;&+*#@\(\)\$]+)/i', $post, $matches)){
+ // move matched part of address into $hit
- $url = $hit.$matches[1];
+ $len = strlen($matches[1]);
+ $plen = strlen($pre);
- $cursor += strlen($url) + strlen($pre_hit);
- $buffer .= $pre_hit;
+ $hit = substr($pre, $plen - $len).$hit;
+ $pre = substr($pre, 0, $plen - $len);
+ } else {
- $url = html_entity_decode($url);
+ //echo "fail 2 at $cursor ($pre)
\n";
+ $ok = 0;
+ $cursor += $fail_len;
+ $buffer .= $fail_text;
+ }
+ }
- #
- # remove trailing punctuation from url
- #
+ //
+ // check forwards
+ //
- while (preg_match('|[.,!;:?]$|', $url)){
- $url = substr($url, 0, strlen($url)-1);
- $cursor--;
- }
- foreach (['()', '[]', '{}'] as $pair){
- $o = substr($pair, 0, 1);
- $c = substr($pair, 1, 1);
- if (preg_match("!^(\\$c|^)[^\\$o]+\\$c$!", $url)){
- $url = substr($url, 0, strlen($url)-1);
- $cursor--;
- }
- }
+ if ($ok) {
+ if (preg_match("!^($atom(\.$atom)*)!", $post, $matches)) {
+ // move matched part of address into $hit
- #
- # nice-i-fy url here
- #
+ $len = strlen($matches[1]);
- $link_url = $url;
- $display_url = $url;
+ $hit .= substr($post, 0, $len);
+ $post = substr($post, $len);
+ } else {
+ //echo "fail 3 at $cursor ($post)
\n";
- if ($force_prefix) $link_url = $force_prefix.$link_url;
+ $ok = 0;
+ $cursor += $fail_len;
+ $buffer .= $fail_text;
+ }
+ }
- if ($GLOBALS['autolink_options']['strip_protocols']){
- if (preg_match('!^(http|https)://!i', $display_url, $m)){
+ //
+ // commit
+ //
- $display_url = substr($display_url, strlen($m[1])+3);
- }
- }
+ if ($ok) {
+ $cursor += strlen($pre) + strlen($hit);
+ $buffer .= $pre;
+ $buffer .= "$hit";
+ }
+ }
- $display_url = autolink_label($display_url, $limit);
+ //
+ // add everything from the cursor to the end onto the buffer.
+ //
+ $buffer .= substr($text, $cursor);
- #
- # add the url
- #
-
- $currentTagfill = $tagfill;
- if ($display_url != $link_url && !preg_match('@title=@msi',$currentTagfill) && $auto_title) {
+ return $buffer;
+ }
- $display_quoted = preg_quote($display_url, '!');
-
- if (!preg_match("!^(http|https)://{$display_quoted}$!i", $link_url)){
-
- $currentTagfill .= ' title="'.$link_url.'"';
- }
- }
-
- $link_url_enc = HtmlSpecialChars($link_url);
- $display_url_enc = HtmlSpecialChars($display_url);
-
- $buffer .= "{$display_url_enc}";
-
- }else{
- #echo "fail 3 at $cursor
\n";
-
- $ok = 0;
- $cursor += $fail_len;
- $buffer .= $fail_text;
- }
- }
-
- }
-
- #
- # add everything from the cursor to the end onto the buffer.
- #
-
- $buffer .= substr($text, $cursor);
-
- return $buffer;
- }
-
- ####################################################################
-
- function autolink_label($text, $limit){
-
- if (!$limit){ return $text; }
-
- if (strlen($text) > $limit){
- return substr($text, 0, $limit-3).'...';
- }
-
- return $text;
- }
-
- ####################################################################
-
- function autolink_email($text, $tagfill=''){
-
- $atom = '[^()<>@,;:\\\\".\\[\\]\\x00-\\x20\\x7f]+'; # from RFC822
-
- #die($atom);
-
- $text_l = StrToLower($text);
- $cursor = 0;
- $loop = 1;
- $buffer = '';
-
- while(($cursor < strlen($text)) && $loop){
-
- #
- # find an '@' symbol
- #
-
- $ok = 1;
- $pos = strpos($text_l, '@', $cursor);
-
- if ($pos === false){
-
- $loop = 0;
- $ok = 0;
-
- }else{
-
- $pre = substr($text, $cursor, $pos-$cursor);
- $hit = substr($text, $pos, 1);
- $post = substr($text, $pos + 1);
-
- $fail_text = $pre.$hit;
- $fail_len = strlen($fail_text);
-
- #die("$pre::$hit::$post::$fail_text");
-
- #
- # substring found - first check to see if we're inside a link tag already...
- #
-
- $bits = preg_split('!!i', $pre);
- $last_bit = array_pop($bits);
- if (preg_match("!\n";
-
- $ok = 0;
- $cursor += $fail_len;
- $buffer .= $fail_text;
- }
- }
-
- #
- # check backwards
- #
-
- if ($ok){
- if (preg_match("!($atom(\.$atom)*)\$!", $pre, $matches)){
-
- # move matched part of address into $hit
-
- $len = strlen($matches[1]);
- $plen = strlen($pre);
-
- $hit = substr($pre, $plen-$len).$hit;
- $pre = substr($pre, 0, $plen-$len);
-
- }else{
-
- #echo "fail 2 at $cursor ($pre)
\n";
-
- $ok = 0;
- $cursor += $fail_len;
- $buffer .= $fail_text;
- }
- }
-
- #
- # check forwards
- #
-
- if ($ok){
- if (preg_match("!^($atom(\.$atom)*)!", $post, $matches)){
-
- # move matched part of address into $hit
-
- $len = strlen($matches[1]);
-
- $hit .= substr($post, 0, $len);
- $post = substr($post, $len);
-
- }else{
- #echo "fail 3 at $cursor ($post)
\n";
-
- $ok = 0;
- $cursor += $fail_len;
- $buffer .= $fail_text;
- }
- }
-
- #
- # commit
- #
-
- if ($ok) {
-
- $cursor += strlen($pre) + strlen($hit);
- $buffer .= $pre;
- $buffer .= "$hit";
-
- }
-
- }
-
- #
- # add everything from the cursor to the end onto the buffer.
- #
-
- $buffer .= substr($text, $cursor);
-
- return $buffer;
- }
-
- ####################################################################
-
-?>
+ //###################################################################;
diff --git a/app/Listeners/ActivityListener.php b/app/Listeners/ActivityListener.php
index 2a3985f54ff6..59acdb457b98 100644
--- a/app/Listeners/ActivityListener.php
+++ b/app/Listeners/ActivityListener.php
@@ -1,50 +1,52 @@
-task->isChanged()) {
+ if (! $event->task->isChanged()) {
return;
}
@@ -541,7 +544,6 @@ class ActivityListener
);
}
-
public function createdExpense(ExpenseWasCreated $event)
{
$this->activityRepo->create(
@@ -552,7 +554,7 @@ class ActivityListener
public function updatedExpense(ExpenseWasUpdated $event)
{
- if ( ! $event->expense->isChanged()) {
+ if (! $event->expense->isChanged()) {
return;
}
@@ -589,6 +591,4 @@ class ActivityListener
ACTIVITY_TYPE_RESTORE_EXPENSE
);
}
-
-
}
diff --git a/app/Listeners/AnalyticsListener.php b/app/Listeners/AnalyticsListener.php
index ca36fd7912f9..5b26b59ab683 100644
--- a/app/Listeners/AnalyticsListener.php
+++ b/app/Listeners/AnalyticsListener.php
@@ -1,10 +1,12 @@
-accountRepo = $accountRepo;
- }
+ }
- /**
- * Handle the event.
- *
- * @param UserLoggedIn $event
+ /**
+ * Handle the event.
*
- * @return void
- */
- public function handle(UserLoggedIn $event)
- {
+ * @param UserLoggedIn $event
+ *
+ * @return void
+ */
+ public function handle(UserLoggedIn $event)
+ {
$account = Auth::user()->account;
if (empty($account->last_login)) {
@@ -63,5 +65,5 @@ class HandleUserLoggedIn {
} elseif ($account->isLogoTooLarge()) {
Session::flash('warning', trans('texts.logo_too_large', ['size' => $account->getLogoSize() . 'KB']));
}
- }
+ }
}
diff --git a/app/Listeners/HandleUserSettingsChanged.php b/app/Listeners/HandleUserSettingsChanged.php
index 8afd72f9a392..f1910ab2f116 100644
--- a/app/Listeners/HandleUserSettingsChanged.php
+++ b/app/Listeners/HandleUserSettingsChanged.php
@@ -1,38 +1,40 @@
-accountRepo = $accountRepo;
$this->userMailer = $userMailer;
- }
+ }
- /**
- * Handle the event.
- *
- * @param UserSettingsChanged $event
- *
- * @return void
- */
- public function handle(UserSettingsChanged $event)
- {
- if (!Auth::check()) {
+ /**
+ * Handle the event.
+ *
+ * @param UserSettingsChanged $event
+ *
+ * @return void
+ */
+ public function handle(UserSettingsChanged $event)
+ {
+ if (! Auth::check()) {
return;
}
@@ -46,5 +48,5 @@ class HandleUserSettingsChanged {
$this->userMailer->sendConfirmation($event->user);
Session::flash('warning', trans('texts.verify_email'));
}
- }
+ }
}
diff --git a/app/Listeners/HandleUserSignedUp.php b/app/Listeners/HandleUserSignedUp.php
index 11fd3b90fb2c..e76f6c1c4162 100644
--- a/app/Listeners/HandleUserSignedUp.php
+++ b/app/Listeners/HandleUserSignedUp.php
@@ -1,13 +1,15 @@
-fromDeleted) {
+ if (! $event->fromDeleted) {
return;
}
diff --git a/app/Listeners/QuoteListener.php b/app/Listeners/QuoteListener.php
index d1b85bdf4ef3..0a47a049d4a0 100644
--- a/app/Listeners/QuoteListener.php
+++ b/app/Listeners/QuoteListener.php
@@ -1,9 +1,11 @@
-invoice->account);
- $this->checkSubscriptions(EVENT_UPDATE_INVOICE, $event->invoice, $transformer, ENTITY_CLIENT);
+ $transformer = new InvoiceTransformer($event->invoice->account);
+ $this->checkSubscriptions(EVENT_UPDATE_INVOICE, $event->invoice, $transformer, ENTITY_CLIENT);
}
/**
- * @param InvoiceWasDeleted $event
- */
+ * @param InvoiceWasDeleted $event
+ */
public function deletedInvoice(InvoiceWasDeleted $event)
{
- $transformer = new InvoiceTransformer($event->invoice->account);
- $this->checkSubscriptions(EVENT_DELETE_INVOICE, $event->invoice, $transformer, ENTITY_CLIENT);
+ $transformer = new InvoiceTransformer($event->invoice->account);
+ $this->checkSubscriptions(EVENT_DELETE_INVOICE, $event->invoice, $transformer, ENTITY_CLIENT);
}
/**
- * @param QuoteWasUpdated $event
- */
+ * @param QuoteWasUpdated $event
+ */
public function updatedQuote(QuoteWasUpdated $event)
{
- $transformer = new InvoiceTransformer($event->quote->account);
- $this->checkSubscriptions(EVENT_UPDATE_QUOTE, $event->quote, $transformer, ENTITY_CLIENT);
+ $transformer = new InvoiceTransformer($event->quote->account);
+ $this->checkSubscriptions(EVENT_UPDATE_QUOTE, $event->quote, $transformer, ENTITY_CLIENT);
}
/**
- * @param InvoiceWasDeleted $event
- */
+ * @param InvoiceWasDeleted $event
+ */
public function deletedQuote(QuoteWasDeleted $event)
{
- $transformer = new InvoiceTransformer($event->quote->account);
- $this->checkSubscriptions(EVENT_DELETE_QUOTE, $event->quote, $transformer, ENTITY_CLIENT);
+ $transformer = new InvoiceTransformer($event->quote->account);
+ $this->checkSubscriptions(EVENT_DELETE_QUOTE, $event->quote, $transformer, ENTITY_CLIENT);
}
/**
@@ -129,7 +128,7 @@ class SubscriptionListener
*/
private function checkSubscriptions($eventId, $entity, $transformer, $include = '')
{
- if ( ! EntityModel::$notifySubscriptions) {
+ if (! EntityModel::$notifySubscriptions) {
return;
}
diff --git a/app/Listeners/TaskListener.php b/app/Listeners/TaskListener.php
index a49a243b9f38..0e3707380a53 100644
--- a/app/Listeners/TaskListener.php
+++ b/app/Listeners/TaskListener.php
@@ -1,10 +1,12 @@
-hasMany('App\Models\Expense','account_id','id')->withTrashed();
+ return $this->hasMany('App\Models\Expense', 'account_id', 'id')->withTrashed();
}
/**
@@ -295,7 +298,7 @@ class Account extends Eloquent
*/
public function payments()
{
- return $this->hasMany('App\Models\Payment','account_id','id')->withTrashed();
+ return $this->hasMany('App\Models\Payment', 'account_id', 'id')->withTrashed();
}
/**
@@ -311,7 +314,7 @@ class Account extends Eloquent
*/
public function expense_categories()
{
- return $this->hasMany('App\Models\ExpenseCategory','account_id','id')->withTrashed();
+ return $this->hasMany('App\Models\ExpenseCategory', 'account_id', 'id')->withTrashed();
}
/**
@@ -319,7 +322,7 @@ class Account extends Eloquent
*/
public function projects()
{
- return $this->hasMany('App\Models\Project','account_id','id')->withTrashed();
+ return $this->hasMany('App\Models\Project', 'account_id', 'id')->withTrashed();
}
/**
@@ -348,11 +351,12 @@ class Account extends Eloquent
/**
* @param int $gatewayId
+ *
* @return bool
*/
public function isGatewayConfigured($gatewayId = 0)
{
- if ( ! $this->relationLoaded('account_gateways')) {
+ if (! $this->relationLoaded('account_gateways')) {
$this->load('account_gateways');
}
@@ -368,7 +372,7 @@ class Account extends Eloquent
*/
public function isEnglish()
{
- return !$this->language_id || $this->language_id == DEFAULT_LANGUAGE;
+ return ! $this->language_id || $this->language_id == DEFAULT_LANGUAGE;
}
/**
@@ -376,7 +380,7 @@ class Account extends Eloquent
*/
public function hasInvoicePrefix()
{
- if ( ! $this->invoice_number_prefix && ! $this->quote_number_prefix) {
+ if (! $this->invoice_number_prefix && ! $this->quote_number_prefix) {
return false;
}
@@ -404,6 +408,7 @@ class Account extends Eloquent
public function getCityState()
{
$swap = $this->country && $this->country->swap_postal_code;
+
return Utils::cityStateZip($this->city, $this->state, $this->postal_code, $swap);
}
@@ -447,9 +452,9 @@ class Account extends Eloquent
public function getDate($date = 'now')
{
- if ( ! $date) {
+ if (! $date) {
return null;
- } elseif ( ! $date instanceof \DateTime) {
+ } elseif (! $date instanceof \DateTime) {
$date = new \DateTime($date);
}
@@ -458,6 +463,7 @@ class Account extends Eloquent
/**
* @param string $date
+ *
* @return DateTime|null|string
*/
public function getDateTime($date = 'now')
@@ -476,7 +482,6 @@ class Account extends Eloquent
return $this->date_format ? $this->date_format->format : DEFAULT_DATE_FORMAT;
}
-
public function getSampleLink()
{
$invitation = new Invitation();
@@ -486,11 +491,12 @@ class Account extends Eloquent
return $invitation->getLink();
}
-
/**
* @param $amount
- * @param null $client
- * @param bool $hideSymbol
+ * @param null $client
+ * @param bool $hideSymbol
+ * @param mixed $decorator
+ *
* @return string
*/
public function formatMoney($amount, $client = null, $decorator = false)
@@ -511,7 +517,7 @@ class Account extends Eloquent
$countryId = false;
}
- if ( ! $decorator) {
+ if (! $decorator) {
$decorator = $this->show_currency_code ? CURRENCY_DECORATOR_CODE : CURRENCY_DECORATOR_SYMBOL;
}
@@ -528,13 +534,14 @@ class Account extends Eloquent
/**
* @param $date
+ *
* @return null|string
*/
public function formatDate($date)
{
$date = $this->getDate($date);
- if ( ! $date) {
+ if (! $date) {
return null;
}
@@ -543,13 +550,14 @@ class Account extends Eloquent
/**
* @param $date
+ *
* @return null|string
*/
public function formatDateTime($date)
{
$date = $this->getDateTime($date);
- if ( ! $date) {
+ if (! $date) {
return null;
}
@@ -558,13 +566,14 @@ class Account extends Eloquent
/**
* @param $date
+ *
* @return null|string
*/
public function formatTime($date)
{
$date = $this->getDateTime($date);
- if ( ! $date) {
+ if (! $date) {
return null;
}
@@ -605,17 +614,18 @@ class Account extends Eloquent
/**
* @param bool $type
+ *
* @return AccountGateway|bool
*/
public function getGatewayByType($type = false)
{
- if ( ! $this->relationLoaded('account_gateways')) {
+ if (! $this->relationLoaded('account_gateways')) {
$this->load('account_gateways');
}
/** @var AccountGateway $accountGateway */
foreach ($this->account_gateways as $accountGateway) {
- if ( ! $type) {
+ if (! $type) {
return $accountGateway;
}
@@ -634,7 +644,7 @@ class Account extends Eloquent
*/
public function availableGatewaysIds()
{
- if ( ! $this->relationLoaded('account_gateways')) {
+ if (! $this->relationLoaded('account_gateways')) {
$this->load('account_gateways');
}
@@ -666,8 +676,9 @@ class Account extends Eloquent
}
/**
- * @param bool $invitation
+ * @param bool $invitation
* @param mixed $gatewayTypeId
+ *
* @return bool
*/
public function paymentDriver($invitation = false, $gatewayTypeId = false)
@@ -690,6 +701,7 @@ class Account extends Eloquent
/**
* @param $gatewayId
+ *
* @return bool
*/
public function hasGatewayId($gatewayId)
@@ -699,6 +711,7 @@ class Account extends Eloquent
/**
* @param $gatewayId
+ *
* @return bool
*/
public function getGatewayConfig($gatewayId)
@@ -717,26 +730,28 @@ class Account extends Eloquent
*/
public function hasLogo()
{
- return !empty($this->logo);
+ return ! empty($this->logo);
}
/**
* @return mixed
*/
- public function getLogoDisk(){
+ public function getLogoDisk()
+ {
return Storage::disk(env('LOGO_FILESYSTEM', 'logos'));
}
- protected function calculateLogoDetails(){
+ protected function calculateLogoDetails()
+ {
$disk = $this->getLogoDisk();
- if($disk->exists($this->account_key.'.png')){
+ if ($disk->exists($this->account_key.'.png')) {
$this->logo = $this->account_key.'.png';
- } else if($disk->exists($this->account_key.'.jpg')) {
+ } elseif ($disk->exists($this->account_key.'.jpg')) {
$this->logo = $this->account_key.'.jpg';
}
- if(!empty($this->logo)){
+ if (! empty($this->logo)) {
$image = imagecreatefromstring($disk->get($this->logo));
$this->logo_width = imagesx($image);
$this->logo_height = imagesy($image);
@@ -750,29 +765,32 @@ class Account extends Eloquent
/**
* @return null
*/
- public function getLogoRaw(){
- if(!$this->hasLogo()){
+ public function getLogoRaw()
+ {
+ if (! $this->hasLogo()) {
return null;
}
$disk = $this->getLogoDisk();
+
return $disk->get($this->logo);
}
/**
* @param bool $cachebuster
+ *
* @return null|string
*/
public function getLogoURL($cachebuster = false)
{
- if(!$this->hasLogo()){
+ if (! $this->hasLogo()) {
return null;
}
$disk = $this->getLogoDisk();
$adapter = $disk->getAdapter();
- if($adapter instanceof \League\Flysystem\Adapter\Local) {
+ if ($adapter instanceof \League\Flysystem\Adapter\Local) {
// Stored locally
$logoUrl = url('/logo/' . $this->logo);
@@ -788,7 +806,7 @@ class Account extends Eloquent
public function getLogoPath()
{
- if ( ! $this->hasLogo()){
+ if (! $this->hasLogo()) {
return null;
}
@@ -815,6 +833,7 @@ class Account extends Eloquent
/**
* @param $userId
* @param $name
+ *
* @return null
*/
public function getToken($userId, $name)
@@ -833,7 +852,7 @@ class Account extends Eloquent
*/
public function getLogoWidth()
{
- if(!$this->hasLogo()){
+ if (! $this->hasLogo()) {
return null;
}
@@ -845,7 +864,7 @@ class Account extends Eloquent
*/
public function getLogoHeight()
{
- if(!$this->hasLogo()){
+ if (! $this->hasLogo()) {
return null;
}
@@ -855,6 +874,7 @@ class Account extends Eloquent
/**
* @param $entityType
* @param null $clientId
+ *
* @return mixed
*/
public function createInvoice($entityType = ENTITY_INVOICE, $clientId = null)
@@ -876,14 +896,14 @@ class Account extends Eloquent
$invoice->invoice_type_id = INVOICE_TYPE_QUOTE;
}
- if ($this->hasClientNumberPattern($invoice) && !$clientId) {
+ if ($this->hasClientNumberPattern($invoice) && ! $clientId) {
// do nothing, we don't yet know the value
- } elseif ( ! $invoice->invoice_number) {
+ } elseif (! $invoice->invoice_number) {
$invoice->invoice_number = $this->getNextNumber($invoice);
}
}
- if (!$clientId) {
+ if (! $clientId) {
$invoice->client = Client::createNew();
$invoice->client->public_id = 0;
}
@@ -935,7 +955,7 @@ class Account extends Eloquent
*/
public function startTrial($plan)
{
- if ( ! Utils::isNinja()) {
+ if (! Utils::isNinja()) {
return;
}
@@ -950,6 +970,7 @@ class Account extends Eloquent
/**
* @param $feature
+ *
* @return bool
*/
public function hasFeature($feature)
@@ -959,9 +980,9 @@ class Account extends Eloquent
}
$planDetails = $this->getPlanDetails();
- $selfHost = !Utils::isNinjaProd();
+ $selfHost = ! Utils::isNinjaProd();
- if (!$selfHost && function_exists('ninja_account_features')) {
+ if (! $selfHost && function_exists('ninja_account_features')) {
$result = ninja_account_features($this, $feature);
if ($result != null) {
@@ -990,34 +1011,34 @@ class Account extends Eloquent
case FEATURE_API:
case FEATURE_CLIENT_PORTAL_PASSWORD:
case FEATURE_CUSTOM_URL:
- return $selfHost || !empty($planDetails);
+ return $selfHost || ! empty($planDetails);
// Pro; No trial allowed, unless they're trialing enterprise with an active pro plan
case FEATURE_MORE_CLIENTS:
- return $selfHost || !empty($planDetails) && (!$planDetails['trial'] || !empty($this->getPlanDetails(false, false)));
+ return $selfHost || ! empty($planDetails) && (! $planDetails['trial'] || ! empty($this->getPlanDetails(false, false)));
// White Label
case FEATURE_WHITE_LABEL:
- if ($this->isNinjaAccount() || (!$selfHost && $planDetails && !$planDetails['expires'])) {
+ if ($this->isNinjaAccount() || (! $selfHost && $planDetails && ! $planDetails['expires'])) {
return false;
}
// Fallthrough
case FEATURE_REMOVE_CREATED_BY:
- return !empty($planDetails);// A plan is required even for self-hosted users
+ return ! empty($planDetails); // A plan is required even for self-hosted users
// Enterprise; No Trial allowed; grandfathered for old pro users
case FEATURE_USERS:// Grandfathered for old Pro users
- if($planDetails && $planDetails['trial']) {
+ if ($planDetails && $planDetails['trial']) {
// Do they have a non-trial plan?
$planDetails = $this->getPlanDetails(false, false);
}
- return $selfHost || !empty($planDetails) && ($planDetails['plan'] == PLAN_ENTERPRISE || $planDetails['started'] <= date_create(PRO_USERS_GRANDFATHER_DEADLINE));
+ return $selfHost || ! empty($planDetails) && ($planDetails['plan'] == PLAN_ENTERPRISE || $planDetails['started'] <= date_create(PRO_USERS_GRANDFATHER_DEADLINE));
// Enterprise; No Trial allowed
case FEATURE_DOCUMENTS:
case FEATURE_USER_PERMISSIONS:
- return $selfHost || !empty($planDetails) && $planDetails['plan'] == PLAN_ENTERPRISE && !$planDetails['trial'];
+ return $selfHost || ! empty($planDetails) && $planDetails['plan'] == PLAN_ENTERPRISE && ! $planDetails['trial'];
default:
return false;
@@ -1026,11 +1047,12 @@ class Account extends Eloquent
/**
* @param null $plan_details
+ *
* @return bool
*/
public function isPro(&$plan_details = null)
{
- if (!Utils::isNinjaProd()) {
+ if (! Utils::isNinjaProd()) {
return true;
}
@@ -1040,16 +1062,17 @@ class Account extends Eloquent
$plan_details = $this->getPlanDetails();
- return !empty($plan_details);
+ return ! empty($plan_details);
}
/**
* @param null $plan_details
+ *
* @return bool
*/
public function isEnterprise(&$plan_details = null)
{
- if (!Utils::isNinjaProd()) {
+ if (! Utils::isNinjaProd()) {
return true;
}
@@ -1065,11 +1088,12 @@ class Account extends Eloquent
/**
* @param bool $include_inactive
* @param bool $include_trial
+ *
* @return array|null
*/
public function getPlanDetails($include_inactive = false, $include_trial = true)
{
- if (!$this->company) {
+ if (! $this->company) {
return null;
}
@@ -1077,7 +1101,7 @@ class Account extends Eloquent
$price = $this->company->plan_price;
$trial_plan = $this->company->trial_plan;
- if((!$plan || $plan == PLAN_FREE) && (!$trial_plan || !$include_trial)) {
+ if ((! $plan || $plan == PLAN_FREE) && (! $trial_plan || ! $include_trial)) {
return null;
}
@@ -1088,7 +1112,7 @@ class Account extends Eloquent
$trial_expires->modify('+2 weeks');
if ($trial_expires >= date_create()) {
- $trial_active = true;
+ $trial_active = true;
}
}
@@ -1105,22 +1129,22 @@ class Account extends Eloquent
}
}
- if (!$include_inactive && !$plan_active && !$trial_active) {
+ if (! $include_inactive && ! $plan_active && ! $trial_active) {
return null;
}
// Should we show plan details or trial details?
- if (($plan && !$trial_plan) || !$include_trial) {
+ if (($plan && ! $trial_plan) || ! $include_trial) {
$use_plan = true;
- } elseif (!$plan && $trial_plan) {
+ } elseif (! $plan && $trial_plan) {
$use_plan = false;
} else {
// There is both a plan and a trial
- if (!empty($plan_active) && empty($trial_active)) {
+ if (! empty($plan_active) && empty($trial_active)) {
$use_plan = true;
- } elseif (empty($plan_active) && !empty($trial_active)) {
+ } elseif (empty($plan_active) && ! empty($trial_active)) {
$use_plan = false;
- } elseif (!empty($plan_active) && !empty($trial_active)) {
+ } elseif (! empty($plan_active) && ! empty($trial_active)) {
// Both are active; use whichever is a better plan
if ($plan == PLAN_ENTERPRISE) {
$use_plan = true;
@@ -1168,7 +1192,7 @@ class Account extends Eloquent
*/
public function isTrial()
{
- if (!Utils::isNinjaProd()) {
+ if (! Utils::isNinjaProd()) {
return false;
}
@@ -1184,7 +1208,7 @@ class Account extends Eloquent
{
$planDetails = $this->getPlanDetails(true);
- if(!$planDetails || !$planDetails['trial']) {
+ if (! $planDetails || ! $planDetails['trial']) {
return 0;
}
@@ -1216,7 +1240,7 @@ class Account extends Eloquent
*/
public function getLogoSize()
{
- if(!$this->hasLogo()){
+ if (! $this->hasLogo()) {
return null;
}
@@ -1233,6 +1257,7 @@ class Account extends Eloquent
/**
* @param $eventId
+ *
* @return \Illuminate\Database\Eloquent\Model|null|static
*/
public function getSubscription($eventId)
@@ -1289,150 +1314,14 @@ class Account extends Eloquent
return $this;
}
- /**
- * @param $entityType
- * @return mixed
- */
- public function getDefaultEmailSubject($entityType)
- {
- if (strpos($entityType, 'reminder') !== false) {
- $entityType = 'reminder';
- }
-
- return trans("texts.{$entityType}_subject", ['invoice' => '$invoice', 'account' => '$account']);
- }
-
- /**
- * @param $entityType
- * @return mixed
- */
- public function getEmailSubject($entityType)
- {
- if ($this->hasFeature(FEATURE_CUSTOM_EMAILS)) {
- $field = "email_subject_{$entityType}";
- $value = $this->$field;
-
- if ($value) {
- return $value;
- }
- }
-
- return $this->getDefaultEmailSubject($entityType);
- }
-
- /**
- * @param $entityType
- * @param bool $message
- * @return string
- */
- public function getDefaultEmailTemplate($entityType, $message = false)
- {
- if (strpos($entityType, 'reminder') !== false) {
- $entityType = ENTITY_INVOICE;
- }
-
- $template = '
';
-
- if ($this->hasFeature(FEATURE_CUSTOM_EMAILS) && $this->email_design_id != EMAIL_DESIGN_PLAIN) {
- $template .= '
' .
- '
';
- } else {
- $template .= '
' .
- '
';
- }
-
- if ($message) {
- $template .= "$message\r\n\r\n";
- }
-
- return $template . '$footer';
- }
-
- /**
- * @param $entityType
- * @param bool $message
- * @return mixed
- */
- public function getEmailTemplate($entityType, $message = false)
- {
- $template = false;
-
- if ($this->hasFeature(FEATURE_CUSTOM_EMAILS)) {
- $field = "email_template_{$entityType}";
- $template = $this->$field;
- }
-
- if (!$template) {
- $template = $this->getDefaultEmailTemplate($entityType, $message);
- }
-
- //
is causing page breaks with the email designs
- return str_replace('/>', ' />', $template);
- }
-
- /**
- * @param string $view
- * @return string
- */
- public function getTemplateView($view = '')
- {
- return $this->getEmailDesignId() == EMAIL_DESIGN_PLAIN ? $view : 'design' . $this->getEmailDesignId();
- }
-
- /**
- * @return mixed|string
- */
- public function getEmailFooter()
- {
- if ($this->email_footer) {
- // Add line breaks if HTML isn't already being used
- return strip_tags($this->email_footer) == $this->email_footer ? nl2br($this->email_footer) : $this->email_footer;
- } else {
- return '
\$account
"; - if ( ! class_exists($className)) { + if (! class_exists($className)) { throw new Exception(trans('texts.intent_not_supported')); } - return (new $className($state, $data)); + return new $className($state, $data); } - public function process() { throw new Exception(trans('texts.intent_not_supported')); @@ -72,7 +72,7 @@ class BaseIntent public function setStateEntities($entityType, $entities) { - if ( ! is_array($entities)) { + if (! is_array($entities)) { $entities = [$entities]; } @@ -116,7 +116,6 @@ class BaseIntent return $this->state->current->entityType; } - public function getState() { return $this->state; @@ -140,7 +139,7 @@ class BaseIntent { $data = []; - if ( ! isset($this->data->compositeEntities)) { + if (! isset($this->data->compositeEntities)) { return []; } @@ -154,7 +153,8 @@ class BaseIntent foreach ($compositeEntity->children as $child) { if ($child->type == 'Field') { - $field = $child->value;; + $field = $child->value; + ; } elseif ($child->type == 'Value') { $value = $child->value; } @@ -213,7 +213,7 @@ class BaseIntent } else { if ($content instanceof \Illuminate\Database\Eloquent\Collection) { // do nothing - } elseif ( ! is_array($content)) { + } elseif (! is_array($content)) { $content = [$content]; } diff --git a/app/Ninja/Intents/CreateInvoiceIntent.php b/app/Ninja/Intents/CreateInvoiceIntent.php index 96a1b9d64d0a..915bfae0883e 100644 --- a/app/Ninja/Intents/CreateInvoiceIntent.php +++ b/app/Ninja/Intents/CreateInvoiceIntent.php @@ -1,7 +1,9 @@ -requestClient(); $invoiceItems = $this->requestInvoiceItems(); - if ( ! $client) { + if (! $client) { throw new Exception(trans('texts.client_not_found')); } @@ -30,7 +32,7 @@ class CreateInvoiceIntent extends InvoiceIntent $invoiceService = app('App\Services\InvoiceService'); $invoice = $invoiceService->save($data); - $invoiceItemIds = array_map(function($item) { + $invoiceItemIds = array_map(function ($item) { return $item['public_id']; }, $invoice->invoice_items->toArray()); diff --git a/app/Ninja/Intents/DownloadInvoiceIntent.php b/app/Ninja/Intents/DownloadInvoiceIntent.php index 400519155ff4..48e649a37434 100644 --- a/app/Ninja/Intents/DownloadInvoiceIntent.php +++ b/app/Ninja/Intents/DownloadInvoiceIntent.php @@ -1,9 +1,9 @@ -stateInvoice(); - if ( ! Auth::user()->can('edit', $invoice)) { + if (! Auth::user()->can('edit', $invoice)) { throw new Exception(trans('texts.not_allowed')); } diff --git a/app/Ninja/Intents/InvoiceIntent.php b/app/Ninja/Intents/InvoiceIntent.php index fdba48a5609a..9421e32e0a4e 100644 --- a/app/Ninja/Intents/InvoiceIntent.php +++ b/app/Ninja/Intents/InvoiceIntent.php @@ -1,8 +1,10 @@ -stateEntity(ENTITY_INVOICE); - if ( ! $invoiceId) { + if (! $invoiceId) { throw new Exception(trans('texts.intent_not_supported')); } $invoice = Invoice::scope($invoiceId)->first(); - if ( ! $invoice) { + if (! $invoice) { throw new Exception(trans('texts.intent_not_supported')); } - if ( ! Auth::user()->can('view', $invoice)) { + if (! Auth::user()->can('view', $invoice)) { throw new Exception(trans('texts.not_allowed')); } @@ -46,7 +48,7 @@ class InvoiceIntent extends BaseIntent $invoiceItems = []; $offset = 0; - if ( ! isset($this->data->compositeEntities) || ! count($this->data->compositeEntities)) { + if (! isset($this->data->compositeEntities) || ! count($this->data->compositeEntities)) { return []; } @@ -102,5 +104,4 @@ class InvoiceIntent extends BaseIntent return $invoiceItems; } - } diff --git a/app/Ninja/Intents/ListProductsIntent.php b/app/Ninja/Intents/ListProductsIntent.php index fc8c17490be6..5216708519fe 100644 --- a/app/Ninja/Intents/ListProductsIntent.php +++ b/app/Ninja/Intents/ListProductsIntent.php @@ -1,9 +1,9 @@ -orderBy('product_key') ->limit(5) ->get() - ->transform(function($item, $key) use ($account) { + ->transform(function ($item, $key) use ($account) { $card = $item->present()->skypeBot($account); if ($this->stateEntity(ENTITY_INVOICE)) { $card->addButton('imBack', trans('texts.add_to_invoice', ['invoice' => '']), trans('texts.add_product_to_invoice', ['product' => $item->product_key])); } + return $card; }); diff --git a/app/Ninja/Intents/ProductIntent.php b/app/Ninja/Intents/ProductIntent.php index bf8b72405b6a..cc7a9ff316ed 100644 --- a/app/Ninja/Intents/ProductIntent.php +++ b/app/Ninja/Intents/ProductIntent.php @@ -1,8 +1,6 @@ -invoiceRepo->save($data, $invoice); $invoiceItems = array_slice($invoice->invoice_items->toArray(), count($invoiceItems) * -1); - $invoiceItemIds = array_map(function($item) { + $invoiceItemIds = array_map(function ($item) { return $item['public_id']; }, $invoiceItems); diff --git a/app/Ninja/Mailers/ContactMailer.php b/app/Ninja/Mailers/ContactMailer.php index 2512f94af787..12939f5ecce8 100644 --- a/app/Ninja/Mailers/ContactMailer.php +++ b/app/Ninja/Mailers/ContactMailer.php @@ -1,42 +1,19 @@ -is_recurring) { return false; @@ -78,12 +57,12 @@ class ContactMailer extends Mailer } $account->loadLocalizationSettings($client); - $emailTemplate = $account->getEmailTemplate($reminder ?: $entityType); - $emailSubject = $account->getEmailSubject($reminder ?: $entityType); + $emailTemplate = !empty($template['body']) ? $template['body'] : $account->getEmailTemplate($reminder ?: $entityType); + $emailSubject = !empty($template['subject']) ? $template['subject'] : $account->getEmailSubject($reminder ?: $entityType); $sent = false; - if ($account->attachPDF() && !$pdfString) { + if ($account->attachPDF() && ! $pdfString) { $pdfString = $invoice->getPDFString(); } @@ -91,7 +70,7 @@ class ContactMailer extends Mailer if ($account->document_email_attachment && $invoice->hasDocuments()) { $documents = $invoice->documents; - foreach($invoice->expenses as $expense){ + foreach ($invoice->expenses as $expense) { $documents = $documents->merge($expense->documents); } @@ -99,9 +78,11 @@ class ContactMailer extends Mailer $size = 0; $maxSize = MAX_EMAIL_DOCUMENTS_SIZE * 1000; - foreach($documents as $document){ + foreach ($documents as $document) { $size += $document->size; - if($size > $maxSize)break; + if ($size > $maxSize) { + break; + } $documentStrings[] = [ 'name' => $document->name, @@ -134,13 +115,16 @@ class ContactMailer extends Mailer /** * @param Invitation $invitation - * @param Invoice $invoice + * @param Invoice $invoice * @param $body * @param $subject * @param $pdfString * @param $documentStrings - * @return bool|string + * @param mixed $reminder + * * @throws \Laracasts\Presenter\Exceptions\PresenterException + * + * @return bool|string */ private function sendInvitation( Invitation $invitation, @@ -151,9 +135,7 @@ class ContactMailer extends Mailer $documentStrings, $reminder, $isFirst - ) - { - + ) { $client = $invoice->client; $account = $invoice->account; @@ -166,11 +148,11 @@ class ContactMailer extends Mailer } } - if (!$user->email || !$user->registered) { + if (! $user->email || ! $user->registered) { return trans('texts.email_error_user_unregistered'); - } elseif (!$user->confirmed) { + } elseif (! $user->confirmed) { return trans('texts.email_error_user_unconfirmed'); - } elseif (!$invitation->contact->email) { + } elseif (! $invitation->contact->email) { return trans('texts.email_error_invalid_contact_email'); } elseif ($invitation->contact->trashed()) { return trans('texts.email_error_inactive_contact'); @@ -180,7 +162,7 @@ class ContactMailer extends Mailer 'account' => $account, 'client' => $client, 'invitation' => $invitation, - 'amount' => $invoice->getRequestedAmount() + 'amount' => $invoice->getRequestedAmount(), ]; // Let the client know they'll be billed later @@ -230,6 +212,7 @@ class ContactMailer extends Mailer /** * @param int $length + * * @return string */ protected function generatePassword($length = 9) @@ -241,14 +224,14 @@ class ContactMailer extends Mailer ]; $all = ''; $password = ''; - foreach($sets as $set) - { + foreach ($sets as $set) { $password .= $set[array_rand(str_split($set))]; $all .= $set; } $all = str_split($all); - for($i = 0; $i < $length - count($sets); $i++) + for ($i = 0; $i < $length - count($sets); $i++) { $password .= $all[array_rand($all)]; + } $password = str_shuffle($password); return $password; @@ -338,10 +321,9 @@ class ContactMailer extends Mailer $data = [ 'client' => $name, 'amount' => Utils::formatMoney($amount, DEFAULT_CURRENCY, DEFAULT_COUNTRY), - 'license' => $license + 'license' => $license, ]; $this->sendTo($email, CONTACT_EMAIL, CONTACT_NAME, $subject, $view, $data); } - } diff --git a/app/Ninja/Mailers/Mailer.php b/app/Ninja/Mailers/Mailer.php index 5451653473de..5b4d34c23302 100644 --- a/app/Ninja/Mailers/Mailer.php +++ b/app/Ninja/Mailers/Mailer.php @@ -1,12 +1,14 @@ -subject($subject); // Optionally BCC the email - if (!empty($data['bccEmail'])) { + if (! empty($data['bccEmail'])) { $message->bcc($data['bccEmail']); } // Attach the PDF to the email - if (!empty($data['pdfString']) && !empty($data['pdfFileName'])) { + if (! empty($data['pdfString']) && ! empty($data['pdfFileName'])) { $message->attachData($data['pdfString'], $data['pdfFileName']); } // Attach documents to the email - if (!empty($data['documents'])){ - foreach($data['documents'] as $document){ + if (! empty($data['documents'])) { + foreach ($data['documents'] as $document) { $message->attachData($document['data'], $document['name']); } } @@ -79,6 +82,7 @@ class Mailer /** * @param $response * @param $data + * * @return bool */ private function handleSuccess($response, $data) @@ -94,7 +98,7 @@ class Mailer $messageId = $json->MessageID; } - $notes = isset($data['notes']) ? $data['notes']: false; + $notes = isset($data['notes']) ? $data['notes'] : false; $invoice->markInvitationSent($invitation, $messageId, true, $notes); } @@ -103,6 +107,7 @@ class Mailer /** * @param $exception + * * @return string */ private function handleFailure($exception) @@ -114,8 +119,11 @@ class Mailer $error = trans('texts.postmark_error', ['link' => link_to('https://status.postmarkapp.com/')]); Utils::logError($error); - // TODO throw the exception once all emails are sent using the queue - return $error; + if (config('queue.default') === 'sync') { + return $error; + } else { + throw $exception; + } } $response = $response->getBody()->getContents(); @@ -129,7 +137,7 @@ class Mailer $invitation = $data['invitation']; $invitation->email_error = $emailError; $invitation->save(); - } elseif ( ! Utils::isNinjaProd()) { + } elseif (! Utils::isNinjaProd()) { Utils::logError(Utils::getErrorString($exception)); } diff --git a/app/Ninja/Mailers/UserMailer.php b/app/Ninja/Mailers/UserMailer.php index 2508a7f93f74..c509bd66afcb 100644 --- a/app/Ninja/Mailers/UserMailer.php +++ b/app/Ninja/Mailers/UserMailer.php @@ -1,5 +1,6 @@ -email) { + if (! $user->email) { return; } @@ -38,7 +39,7 @@ class UserMailer extends Mailer } /** - * @param User $user + * @param User $user * @param Invoice $invoice * @param $notificationType * @param Payment|null $payment @@ -48,8 +49,7 @@ class UserMailer extends Mailer Invoice $invoice, $notificationType, Payment $payment = null - ) - { + ) { if (! $user->email || $user->cannot('view', $invoice)) { return; } @@ -59,6 +59,12 @@ class UserMailer extends Mailer $account = $user->account; $client = $invoice->client; + if ($account->hasMultipleAccounts()) { + $link = url(sprintf('/account/%s?redirect_to=%s', $account->account_key, $invoice->present()->path)); + } else { + $link = $invoice->present()->url; + } + $data = [ 'entityType' => $entityType, 'clientName' => $client->getDisplayName(), @@ -66,7 +72,7 @@ class UserMailer extends Mailer 'userName' => $user->getDisplayName(), 'invoiceAmount' => $account->formatMoney($invoice->getRequestedAmount(), $client), 'invoiceNumber' => $invoice->invoice_number, - 'invoiceLink' => SITE_URL."/{$entityType}s/{$invoice->public_id}", + 'invoiceLink' => $link, 'account' => $account, ]; @@ -77,7 +83,7 @@ class UserMailer extends Mailer $subject = trans("texts.notification_{$entityType}_{$notificationType}_subject", [ 'invoice' => $invoice->invoice_number, - 'client' => $client->getDisplayName() + 'client' => $client->getDisplayName(), ]); $this->sendTo($user->email, CONTACT_EMAIL, CONTACT_NAME, $subject, $view, $data); @@ -93,7 +99,7 @@ class UserMailer extends Mailer $invoice = $invitation->invoice; $entityType = $invoice->getEntityType(); - if (!$user->email) { + if (! $user->email) { return; } @@ -112,7 +118,7 @@ class UserMailer extends Mailer public function sendSecurityCode($user, $code) { - if (!$user->email) { + if (! $user->email) { return; } diff --git a/app/Ninja/Notifications/PushFactory.php b/app/Ninja/Notifications/PushFactory.php index 6e69ac80bb7a..1fa973fa5706 100644 --- a/app/Ninja/Notifications/PushFactory.php +++ b/app/Ninja/Notifications/PushFactory.php @@ -6,9 +6,8 @@ use Davibennun\LaravelPushNotification\Facades\PushNotification; use Illuminate\Support\Facades\Log; /** - * Class PushFactory + * Class PushFactory. */ - class PushFactory { /** @@ -19,11 +18,10 @@ class PushFactory } /** - * customMessage function + * customMessage function. * * Send a message with a nested custom payload to perform additional trickery within application * - * @access public * * @param $token * @param $message @@ -40,48 +38,44 @@ class PushFactory } /** - * message function + * message function. * * Send a plain text only message to a single device. * - * @access public * * @param $token - device token * @param $message - user specific message + * @param mixed $device * * @return void */ - public function message($token, $message, $device) { try { PushNotification::app($device) ->to($token) ->send($message); - } - catch(\Exception $e) { + } catch (\Exception $e) { Log::error($e->getMessage()); } - } /** - * getFeedback function + * getFeedback function. * * Returns an array of expired/invalid tokens to be removed from iOS PUSH notifications. * * We need to run this once ~ 24hrs * - * @access public * - * @param string $token - A valid token (can be any valid token) + * @param string $token - A valid token (can be any valid token) * @param string $message - Nil value for message - * @param string $device - Type of device the message is being pushed to. + * @param string $device - Type of device the message is being pushed to. + * * @return array */ - public function getFeedback($token, $message = '', $device) + public function getFeedback($token, $message, $device) { - $feedback = PushNotification::app($device) ->to($token) ->send($message); diff --git a/app/Ninja/PaymentDrivers/AuthorizeNetAIMPaymentDriver.php b/app/Ninja/PaymentDrivers/AuthorizeNetAIMPaymentDriver.php index 00ba9421ce03..9bec8c2426bb 100644 --- a/app/Ninja/PaymentDrivers/AuthorizeNetAIMPaymentDriver.php +++ b/app/Ninja/PaymentDrivers/AuthorizeNetAIMPaymentDriver.php @@ -1,4 +1,6 @@ -accountGateway->gateway; - if ( ! $this->meetsGatewayTypeLimits($this->gatewayType)) { + if (! $this->meetsGatewayTypeLimits($this->gatewayType)) { // The customer must have hacked the URL Session::flash('error', trans('texts.limits_not_met')); + return redirect()->to('view/' . $this->invitation->invitation_key); } @@ -136,6 +139,7 @@ class BasePaymentDriver $this->completeOnsitePurchase(); if ($redirectUrl = session('redirect_url:' . $this->invitation->invitation_key)) { $separator = strpos($redirectUrl, '?') === false ? '?' : '&'; + return redirect()->to($redirectUrl . $separator . 'invoice_id=' . $this->invoice()->public_id); } else { Session::flash('message', trans('texts.applied_payment')); @@ -162,7 +166,6 @@ class BasePaymentDriver 'currencyCode' => $this->client()->getCurrencyCode(), 'account' => $this->account(), 'sourceId' => $sourceId, - 'clientFontUrl' => $this->account()->getFontsUrl(), 'tokenize' => $this->tokenize(), 'transactionToken' => $this->createTransactionToken(), ]; @@ -201,14 +204,13 @@ class BasePaymentDriver $rules = []; if ($this->isGatewayType(GATEWAY_TYPE_CREDIT_CARD)) { - $rules = array_merge($rules, [ 'first_name' => 'required', 'last_name' => 'required', ]); // TODO check this is always true - if ( ! $this->tokenize()) { + if (! $this->tokenize()) { $rules = array_merge($rules, [ 'card_number' => 'required', 'expiration_month' => 'required', @@ -254,15 +256,16 @@ class BasePaymentDriver // load or create token if ($this->isGatewayType(GATEWAY_TYPE_TOKEN)) { - if ( ! $paymentMethod) { + if (! $paymentMethod) { $paymentMethod = PaymentMethod::clientId($this->client()->id) ->wherePublicId($this->sourceId) ->firstOrFail(); } - if ( ! $this->meetsGatewayTypeLimits($paymentMethod->payment_type->gateway_type_id)) { + if (! $this->meetsGatewayTypeLimits($paymentMethod->payment_type->gateway_type_id)) { // The customer must have hacked the URL Session::flash('error', trans('texts.limits_not_met')); + return redirect()->to('view/' . $this->invitation->invitation_key); } } else { @@ -270,9 +273,10 @@ class BasePaymentDriver $paymentMethod = $this->createToken(); } - if ( ! $this->meetsGatewayTypeLimits($this->gatewayType)) { + if (! $this->meetsGatewayTypeLimits($this->gatewayType)) { // The customer must have hacked the URL Session::flash('error', trans('texts.limits_not_met')); + return redirect()->to('view/' . $this->invitation->invitation_key); } } @@ -318,17 +322,17 @@ class BasePaymentDriver private function updateClient() { - if ( ! $this->isGatewayType(GATEWAY_TYPE_CREDIT_CARD)) { + if (! $this->isGatewayType(GATEWAY_TYPE_CREDIT_CARD)) { return; } // update the contact info - if ( ! $this->contact()->getFullName()) { + if (! $this->contact()->getFullName()) { $this->contact()->first_name = $this->input['first_name']; $this->contact()->last_name = $this->input['last_name']; } - if ( ! $this->contact()->email) { + if (! $this->contact()->email) { $this->contact()->email = $this->input['email']; } @@ -336,7 +340,7 @@ class BasePaymentDriver $this->contact()->save(); } - if ( ! $this->accountGateway->show_address || ! $this->accountGateway->update_address) { + if (! $this->accountGateway->show_address || ! $this->accountGateway->update_address) { return; } @@ -365,7 +369,7 @@ class BasePaymentDriver 'description' => trans('texts.' . $invoice->getEntityType()) . " {$invoice->invoice_number}", 'transactionId' => $invoice->invoice_number, 'transactionType' => 'Purchase', - 'ip' => Request::ip() + 'ip' => Request::ip(), ]; if ($paymentMethod) { @@ -418,7 +422,7 @@ class BasePaymentDriver 'shippingCity' => $input['city'], 'shippingState' => $input['state'], 'shippingPostcode' => $input['postal_code'], - 'shippingCountry' => $country->iso_3166_2 + 'shippingCountry' => $country->iso_3166_2, ]); } @@ -459,7 +463,7 @@ class BasePaymentDriver return true; } - if ( ! $this->handles(GATEWAY_TYPE_TOKEN)) { + if (! $this->handles(GATEWAY_TYPE_TOKEN)) { return false; } @@ -489,7 +493,7 @@ class BasePaymentDriver return $this->customer; } - if ( ! $clientId) { + if (! $clientId) { $clientId = $this->client()->id; } @@ -529,7 +533,7 @@ class BasePaymentDriver { $account = $this->account(); - if ( ! $customer = $this->customer()) { + if (! $customer = $this->customer()) { $customer = new AccountGatewayToken(); $customer->account_id = $account->id; $customer->contact_id = $this->invitation->contact_id; @@ -595,7 +599,6 @@ class BasePaymentDriver public function deleteToken() { - } public function createPayment($ref = false, $paymentMethod = null) @@ -655,11 +658,11 @@ class BasePaymentDriver } } - if (!empty($plan)) { + if (! empty($plan)) { $account = Account::with('users')->find($invoice->client->public_id); $company = $account->company; - if( + if ( $company->plan != $plan || DateTime::createFromFormat('Y-m-d', $account->company->plan_expires) <= date_create('-7 days') ) { @@ -744,7 +747,7 @@ class BasePaymentDriver $amount = $payment->getCompletedAmount(); } - if ( ! $amount) { + if (! $amount) { return false; } @@ -793,20 +796,19 @@ class BasePaymentDriver $ref = array_get($this->input, 'token') ?: $this->invitation->transaction_reference; if (method_exists($this->gateway(), 'completePurchase')) { - $details = $this->paymentDetails(); $response = $this->gateway()->completePurchase($details)->send(); $ref = $response->getTransactionReference() ?: $ref; if ($response->isCancelled()) { return false; - } elseif ( ! $response->isSuccessful()) { + } elseif (! $response->isSuccessful()) { throw new Exception($response->getMessage()); } } // check invoice still has balance - if ( ! floatval($this->invoice()->balance)) { + if (! floatval($this->invoice()->balance)) { throw new Exception(trans('texts.payment_error_code', ['code' => 'NB'])); } @@ -822,7 +824,7 @@ class BasePaymentDriver public function tokenLinks() { - if ( ! $this->customer()) { + if (! $this->customer()) { return []; } @@ -834,7 +836,7 @@ class BasePaymentDriver continue; } - if ( ! $this->meetsGatewayTypeLimits($paymentMethod->payment_type->gateway_type_id)) { + if (! $this->meetsGatewayTypeLimits($paymentMethod->payment_type->gateway_type_id)) { continue; } @@ -870,14 +872,14 @@ class BasePaymentDriver continue; } - if ( ! $this->meetsGatewayTypeLimits($gatewayTypeId)) { + if (! $this->meetsGatewayTypeLimits($gatewayTypeId)) { continue; } $gatewayTypeAlias = GatewayType::getAliasFromId($gatewayTypeId); if ($gatewayTypeId == GATEWAY_TYPE_CUSTOM) { - $url = "javascript:showCustomModal();"; + $url = 'javascript:showCustomModal();'; $label = e($this->accountGateway->getConfigField('name')); } else { $url = $this->paymentUrl($gatewayTypeAlias); @@ -896,7 +898,7 @@ class BasePaymentDriver protected function meetsGatewayTypeLimits($gatewayTypeId) { - if ( !$gatewayTypeId ) { + if (! $gatewayTypeId) { return true; } @@ -910,7 +912,7 @@ class BasePaymentDriver return false; } - if ($accountGatewaySettings->max_limit !== null && $invoice->balance > $accountGatewaySettings->max_limit) { + if ($accountGatewaySettings->max_limit !== null && $invoice->balance > $accountGatewaySettings->max_limit) { return false; } } @@ -937,7 +939,8 @@ class BasePaymentDriver return $url; } - protected function parseCardType($cardName) { + protected function parseCardType($cardName) + { $cardTypes = [ 'visa' => PAYMENT_TYPE_VISA, 'americanexpress' => PAYMENT_TYPE_AMERICAN_EXPRESS, @@ -952,7 +955,7 @@ class BasePaymentDriver 'laser' => PAYMENT_TYPE_LASER, 'maestro' => PAYMENT_TYPE_MAESTRO, 'solo' => PAYMENT_TYPE_SOLO, - 'switch' => PAYMENT_TYPE_SWITCH + 'switch' => PAYMENT_TYPE_SWITCH, ]; $cardName = strtolower(str_replace([' ', '-', '_'], '', $cardName)); @@ -962,7 +965,7 @@ class BasePaymentDriver $cardName = $matches[1]; } - if (!empty($cardTypes[$cardName])) { + if (! empty($cardTypes[$cardName])) { return $cardTypes[$cardName]; } else { return PAYMENT_TYPE_CREDIT_CARD_OTHER; diff --git a/app/Ninja/PaymentDrivers/BitPayPaymentDriver.php b/app/Ninja/PaymentDrivers/BitPayPaymentDriver.php index df1821acdb96..47c3213a1116 100644 --- a/app/Ninja/PaymentDrivers/BitPayPaymentDriver.php +++ b/app/Ninja/PaymentDrivers/BitPayPaymentDriver.php @@ -1,12 +1,13 @@ -send() ->getData(); - return ($customer instanceof Customer); + return $customer instanceof Customer; } protected function paymentDetails($paymentMethod = false) @@ -74,7 +76,7 @@ class BraintreePaymentDriver extends BasePaymentDriver $data['ButtonSource'] = 'InvoiceNinja_SP'; } - if ( ! $paymentMethod && ! empty($this->input['sourceToken'])) { + if (! $paymentMethod && ! empty($this->input['sourceToken'])) { $data['token'] = $this->input['sourceToken']; } @@ -121,7 +123,7 @@ class BraintreePaymentDriver extends BasePaymentDriver 'company' => $this->client()->name, 'email' => $this->contact()->email, 'phone' => $this->contact()->phone, - 'website' => $this->client()->website + 'website' => $this->client()->website, ]; } @@ -157,7 +159,7 @@ class BraintreePaymentDriver extends BasePaymentDriver parent::removePaymentMethod($paymentMethod); $response = $this->gateway()->deletePaymentMethod([ - 'token' => $paymentMethod->source_reference + 'token' => $paymentMethod->source_reference, ])->send(); if ($response->isSuccessful()) { @@ -169,7 +171,7 @@ class BraintreePaymentDriver extends BasePaymentDriver protected function attemptVoidPayment($response, $payment, $amount) { - if ( ! parent::attemptVoidPayment($response, $payment, $amount)) { + if (! parent::attemptVoidPayment($response, $payment, $amount)) { return false; } diff --git a/app/Ninja/PaymentDrivers/CheckoutComPaymentDriver.php b/app/Ninja/PaymentDrivers/CheckoutComPaymentDriver.php index ede0b678234b..47eed79ab921 100644 --- a/app/Ninja/PaymentDrivers/CheckoutComPaymentDriver.php +++ b/app/Ninja/PaymentDrivers/CheckoutComPaymentDriver.php @@ -1,4 +1,6 @@ -gateway()->purchase([ 'amount' => $this->invoice()->getRequestedAmount(), - 'currency' => $this->client()->getCurrencyCode() + 'currency' => $this->client()->getCurrencyCode(), ])->send(); if ($response->isRedirect()) { @@ -31,5 +33,4 @@ class CheckoutComPaymentDriver extends BasePaymentDriver return $data; } - } diff --git a/app/Ninja/PaymentDrivers/CustomPaymentDriver.php b/app/Ninja/PaymentDrivers/CustomPaymentDriver.php index 1dcbc7095b1e..a09d7e129f33 100644 --- a/app/Ninja/PaymentDrivers/CustomPaymentDriver.php +++ b/app/Ninja/PaymentDrivers/CustomPaymentDriver.php @@ -1,12 +1,13 @@ -isCancelled()) { return false; - } elseif ( ! $response->isSuccessful()) { + } elseif (! $response->isSuccessful()) { throw new Exception($response->getMessage()); } return $this->createPayment($response->getTransactionReference()); } - } diff --git a/app/Ninja/PaymentDrivers/PayFastPaymentDriver.php b/app/Ninja/PaymentDrivers/PayFastPaymentDriver.php index 6768de7b2df8..6016afe39458 100644 --- a/app/Ninja/PaymentDrivers/PayFastPaymentDriver.php +++ b/app/Ninja/PaymentDrivers/PayFastPaymentDriver.php @@ -1,4 +1,6 @@ - Request::query('pt') + 'token' => Request::query('pt'), ]); } } diff --git a/app/Ninja/PaymentDrivers/PayPalExpressPaymentDriver.php b/app/Ninja/PaymentDrivers/PayPalExpressPaymentDriver.php index 74f98635e27f..ac3d0c847b24 100644 --- a/app/Ninja/PaymentDrivers/PayPalExpressPaymentDriver.php +++ b/app/Ninja/PaymentDrivers/PayPalExpressPaymentDriver.php @@ -1,12 +1,13 @@ -accountGateway && $this->accountGateway->getAchEnabled()) { @@ -60,14 +62,14 @@ class StripePaymentDriver extends BasePaymentDriver ->fetchCustomer(['customerReference' => $customer->token]) ->send(); - if ( ! $response->isSuccessful()) { + if (! $response->isSuccessful()) { return false; } $this->tokenResponse = $response->getData(); // import Stripe tokens created before payment methods table was added - if ( ! count($customer->payment_methods)) { + if (! count($customer->payment_methods)) { if ($paymentMethod = $this->createPaymentMethod($customer)) { $customer->default_payment_method_id = $paymentMethod->id; $customer->save(); @@ -94,12 +96,12 @@ class StripePaymentDriver extends BasePaymentDriver // Stripe complains if the email field is set unset($data['email']); - if ( ! empty($this->input['sourceToken'])) { + if (! empty($this->input['sourceToken'])) { $data['token'] = $this->input['sourceToken']; unset($data['card']); } - if ( ! empty($this->input['plaidPublicToken'])) { + if (! empty($this->input['plaidPublicToken'])) { $data['plaidPublicToken'] = $this->input['plaidPublicToken']; $data['plaidAccountId'] = $this->input['plaidAccountId']; unset($data['card']); @@ -116,7 +118,7 @@ class StripePaymentDriver extends BasePaymentDriver $data = $this->paymentDetails(); $data['description'] = $client->getDisplayName(); - if ( ! empty($data['plaidPublicToken'])) { + if (! empty($data['plaidPublicToken'])) { $plaidResult = $this->getPlaidToken($data['plaidPublicToken'], $data['plaidAccountId']); unset($data['plaidPublicToken']); unset($data['plaidAccountId']); @@ -153,18 +155,18 @@ class StripePaymentDriver extends BasePaymentDriver $data = $this->tokenResponse; $source = false; - if (!empty($data['object']) && ($data['object'] == 'card' || $data['object'] == 'bank_account')) { + if (! empty($data['object']) && ($data['object'] == 'card' || $data['object'] == 'bank_account')) { $source = $data; - } elseif (!empty($data['object']) && $data['object'] == 'customer') { - $sources = !empty($data['sources']) ? $data['sources'] : $data['cards']; + } elseif (! empty($data['object']) && $data['object'] == 'customer') { + $sources = ! empty($data['sources']) ? $data['sources'] : $data['cards']; $source = reset($sources['data']); - } elseif (!empty($data['source'])) { + } elseif (! empty($data['source'])) { $source = $data['source']; - } elseif (!empty($data['card'])) { + } elseif (! empty($data['card'])) { $source = $data['card']; } - if ( ! $source) { + if (! $source) { return false; } @@ -174,12 +176,9 @@ class StripePaymentDriver extends BasePaymentDriver // For older users the Stripe account may just have the customer token but not the card version // In that case we'd use GATEWAY_TYPE_TOKEN even though we're creating the credit card if ($this->isGatewayType(GATEWAY_TYPE_CREDIT_CARD) || $this->isGatewayType(GATEWAY_TYPE_TOKEN)) { - $paymentMethod->expiration = $source['exp_year'] . '-' . $source['exp_month'] . '-01'; $paymentMethod->payment_type_id = $this->parseCardType($source['brand']); - } elseif ($this->isGatewayType(GATEWAY_TYPE_BANK_TRANSFER)) { - $paymentMethod->routing_number = $source['routing_number']; $paymentMethod->payment_type_id = PAYMENT_TYPE_ACH; $paymentMethod->status = $source['status']; @@ -189,7 +188,6 @@ class StripePaymentDriver extends BasePaymentDriver $paymentMethod->currency_id = $currency->id; $paymentMethod->setRelation('currency', $currency); } - } return $paymentMethod; @@ -208,13 +206,13 @@ class StripePaymentDriver extends BasePaymentDriver { parent::removePaymentMethod($paymentMethod); - if ( ! $paymentMethod->relationLoaded('account_gateway_token')) { + if (! $paymentMethod->relationLoaded('account_gateway_token')) { $paymentMethod->load('account_gateway_token'); } $response = $this->gateway()->deleteCard([ 'customerReference' => $paymentMethod->account_gateway_token->token, - 'cardReference' => $paymentMethod->source_reference + 'cardReference' => $paymentMethod->source_reference, ])->send(); if ($response->isSuccessful()) { @@ -229,36 +227,37 @@ class StripePaymentDriver extends BasePaymentDriver $clientId = $this->accountGateway->getPlaidClientId(); $secret = $this->accountGateway->getPlaidSecret(); - if (!$clientId) { + if (! $clientId) { throw new Exception('plaid client id not set'); // TODO use text strings } - if (!$secret) { + if (! $secret) { throw new Exception('plaid secret not set'); } try { $subdomain = $this->accountGateway->getPlaidEnvironment() == 'production' ? 'api' : 'tartan'; - $response = (new \GuzzleHttp\Client(['base_uri'=>"https://{$subdomain}.plaid.com"]))->request( + $response = (new \GuzzleHttp\Client(['base_uri' => "https://{$subdomain}.plaid.com"]))->request( 'POST', 'exchange_token', [ 'allow_redirects' => false, - 'headers' => ['content-type' => 'application/x-www-form-urlencoded'], + 'headers' => ['content-type' => 'application/x-www-form-urlencoded'], 'body' => http_build_query([ 'client_id' => $clientId, 'secret' => $secret, 'public_token' => $publicToken, 'account_id' => $accountId, - ]) + ]), ] ); + return json_decode($response->getBody(), true); } catch (\GuzzleHttp\Exception\BadResponseException $e) { $response = $e->getResponse(); $body = json_decode($response->getBody(), true); - if ($body && !empty($body['message'])) { + if ($body && ! empty($body['message'])) { throw new Exception($body['message']); } else { throw new Exception($e->getMessage()); @@ -288,7 +287,7 @@ class StripePaymentDriver extends BasePaymentDriver $paymentMethod->status = PAYMENT_METHOD_STATUS_VERIFIED; $paymentMethod->save(); - if ( ! $customer->default_payment_method_id) { + if (! $customer->default_payment_method_id) { $customer->default_payment_method_id = $paymentMethod->id; $customer->save(); } @@ -300,13 +299,13 @@ class StripePaymentDriver extends BasePaymentDriver { $apiKey = $this->accountGateway->getConfig()->apiKey; - if (!$apiKey) { + if (! $apiKey) { return 'No API key set'; } - try{ + try { $options = [ - 'headers' => ['content-type' => 'application/x-www-form-urlencoded'], + 'headers' => ['content-type' => 'application/x-www-form-urlencoded'], 'auth' => [$apiKey, ''], ]; @@ -314,11 +313,12 @@ class StripePaymentDriver extends BasePaymentDriver $options['body'] = $body; } - $response = (new \GuzzleHttp\Client(['base_uri'=>'https://api.stripe.com/v1/']))->request( + $response = (new \GuzzleHttp\Client(['base_uri' => 'https://api.stripe.com/v1/']))->request( $method, $url, $options ); + return json_decode($response->getBody(), true); } catch (\GuzzleHttp\Exception\BadResponseException $e) { $response = $e->getResponse(); @@ -335,16 +335,16 @@ class StripePaymentDriver extends BasePaymentDriver public function handleWebHook($input) { $eventId = array_get($input, 'id'); - $eventType= array_get($input, 'type'); + $eventType = array_get($input, 'type'); $accountGateway = $this->accountGateway; $accountId = $accountGateway->account_id; - if (!$eventId) { + if (! $eventId) { throw new Exception('Missing event id'); } - if (!$eventType) { + if (! $eventType) { throw new Exception('Missing event type'); } @@ -357,14 +357,14 @@ class StripePaymentDriver extends BasePaymentDriver 'customer.bank_account.deleted', ]; - if (!in_array($eventType, $supportedEvents)) { + if (! in_array($eventType, $supportedEvents)) { return ['message' => 'Ignoring event']; } // Fetch the event directly from Stripe for security $eventDetails = $this->makeStripeCall('GET', 'events/'.$eventId); - if (is_string($eventDetails) || !$eventDetails) { + if (is_string($eventDetails) || ! $eventDetails) { return false; } @@ -372,7 +372,7 @@ class StripePaymentDriver extends BasePaymentDriver return false; } - if (!$eventDetails['pending_webhooks']) { + if (! $eventDetails['pending_webhooks']) { return false; } @@ -382,12 +382,12 @@ class StripePaymentDriver extends BasePaymentDriver $payment = Payment::scope(false, $accountId)->where('transaction_reference', '=', $transactionRef)->first(); - if (!$payment) { + if (! $payment) { return false; } if ($eventType == 'charge.failed') { - if (!$payment->isFailed()) { + if (! $payment->isFailed()) { $payment->markFailed($charge['failure_message']); $userMailer = app('App\Ninja\Mailers\UserMailer'); @@ -398,13 +398,13 @@ class StripePaymentDriver extends BasePaymentDriver } elseif ($eventType == 'charge.refunded') { $payment->recordRefund($charge['amount_refunded'] / 100 - $payment->refunded); } - } elseif($eventType == 'customer.source.updated' || $eventType == 'customer.source.deleted' || $eventType == 'customer.bank_account.deleted') { + } elseif ($eventType == 'customer.source.updated' || $eventType == 'customer.source.deleted' || $eventType == 'customer.bank_account.deleted') { $source = $eventDetails['data']['object']; $sourceRef = $source['id']; $paymentMethod = PaymentMethod::scope(false, $accountId)->where('source_reference', '=', $sourceRef)->first(); - if (!$paymentMethod) { + if (! $paymentMethod) { return false; } diff --git a/app/Ninja/PaymentDrivers/TwoCheckoutPaymentDriver.php b/app/Ninja/PaymentDrivers/TwoCheckoutPaymentDriver.php index 005611d4a034..fca754ac79a8 100644 --- a/app/Ninja/PaymentDrivers/TwoCheckoutPaymentDriver.php +++ b/app/Ninja/PaymentDrivers/TwoCheckoutPaymentDriver.php @@ -1,4 +1,6 @@ -createPayment($input['order_number']); } - } diff --git a/app/Ninja/PaymentDrivers/WePayPaymentDriver.php b/app/Ninja/PaymentDrivers/WePayPaymentDriver.php index 755c0397620b..1ebdc69e79e9 100644 --- a/app/Ninja/PaymentDrivers/WePayPaymentDriver.php +++ b/app/Ninja/PaymentDrivers/WePayPaymentDriver.php @@ -1,18 +1,20 @@ -accountGateway && $this->accountGateway->getAchEnabled()) { @@ -132,7 +134,7 @@ class WePayPaymentDriver extends BasePaymentDriver $paymentMethod->bank_name = $source->bank_name; $paymentMethod->source_reference = $source->payment_bank_id; - switch($source->state) { + switch ($source->state) { case 'new': case 'pending': $paymentMethod->status = 'new'; @@ -187,7 +189,7 @@ class WePayPaymentDriver extends BasePaymentDriver protected function attemptVoidPayment($response, $payment, $amount) { - if ( ! parent::attemptVoidPayment($response, $payment, $amount)) { + if (! parent::attemptVoidPayment($response, $payment, $amount)) { return false; } @@ -207,14 +209,14 @@ class WePayPaymentDriver extends BasePaymentDriver } } - if (!isset($objectType)) { + if (! isset($objectType)) { throw new Exception('Could not find object id parameter'); } if ($objectType == 'credit_card') { $paymentMethod = PaymentMethod::scope(false, $accountId)->where('source_reference', '=', $objectId)->first(); - if (!$paymentMethod) { + if (! $paymentMethod) { throw new Exception('Unknown payment method'); } @@ -255,7 +257,7 @@ class WePayPaymentDriver extends BasePaymentDriver } elseif ($objectType == 'checkout') { $payment = Payment::scope(false, $accountId)->where('transaction_reference', '=', $objectId)->first(); - if (!$payment) { + if (! $payment) { throw new Exception('Unknown payment'); } @@ -266,7 +268,7 @@ class WePayPaymentDriver extends BasePaymentDriver if ($checkout->state == 'refunded') { $payment->recordRefund(); - } elseif (!empty($checkout->refund) && !empty($checkout->refund->amount_refunded) && ($checkout->refund->amount_refunded - $payment->refunded) > 0) { + } elseif (! empty($checkout->refund) && ! empty($checkout->refund->amount_refunded) && ($checkout->refund->amount_refunded - $payment->refunded) > 0) { $payment->recordRefund($checkout->refund->amount_refunded - $payment->refunded); } @@ -283,5 +285,4 @@ class WePayPaymentDriver extends BasePaymentDriver return 'Ignoring event'; } } - } diff --git a/app/Ninja/Presenters/AccountPresenter.php b/app/Ninja/Presenters/AccountPresenter.php index 7c6c0d0fb32b..8dce6bdcd1b1 100644 --- a/app/Ninja/Presenters/AccountPresenter.php +++ b/app/Ninja/Presenters/AccountPresenter.php @@ -1,16 +1,19 @@ -entity->getCurrencyId(); $currency = Utils::getFromCache($currencyId, 'currencies'); + return $currency->code; } @@ -110,4 +114,39 @@ class AccountPresenter extends Presenter return $data; } + + public function dateRangeOptions() + { + $yearStart = Carbon::parse($this->entity->financialYearStart() ?: date('Y') . '-01-01'); + $month = $yearStart->month - 1; + $year = $yearStart->year; + $lastYear = $year - 1; + + $str = '{ + "' . trans('texts.last_7_days') . '": [moment().subtract(6, "days"), moment()], + "' . trans('texts.last_30_days') . '": [moment().subtract(29, "days"), moment()], + "' . trans('texts.this_month') . '": [moment().startOf("month"), moment().endOf("month")], + "' . trans('texts.last_month') . '": [moment().subtract(1, "month").startOf("month"), moment().subtract(1, "month").endOf("month")], + "' . trans('texts.this_year') . '": [moment().date(1).month(' . $month . ').year(' . $year . '), moment()], + "' . trans('texts.last_year') . '": [moment().date(1).month(' . $month . ').year(' . $lastYear . '), moment().date(1).month(' . $month . ').year(' . $year . ').subtract(1, "day")], + }'; + + return $str; + } + + public function taxRateOptions() + { + $rates = TaxRate::scope()->orderBy('name')->get(); + $options = []; + + foreach ($rates as $rate) { + $name = $rate->name . ' ' . ($rate->rate + 0) . '%'; + if ($rate->is_inclusive) { + $name .= ' - ' . trans('texts.inclusive'); + } + $options[($rate->is_inclusive ? '1 ' : '0 ') . $rate->rate . ' ' . $rate->name] = $name; + } + + return $options; + } } diff --git a/app/Ninja/Presenters/ActivityPresenter.php b/app/Ninja/Presenters/ActivityPresenter.php new file mode 100644 index 000000000000..6978ce8695b0 --- /dev/null +++ b/app/Ninja/Presenters/ActivityPresenter.php @@ -0,0 +1,39 @@ +entity->created_at)); + } + + public function createdAtDate() + { + return Utils::dateToString($this->entity->created_at); + } + + public function user() + { + if ($this->entity->is_system) { + return '' . trans('texts.system') . ''; + } else { + return $this->entity->user->getDisplayName(); + } + } + + public function notes() + { + if ($this->entity->notes) { + return trans('texts.notes_' . $this->entity->notes); + } elseif (in_array($this->entity->activity_type_id, [ACTIVITY_TYPE_EMAIL_INVOICE, ACTIVITY_TYPE_EMAIL_QUOTE])) { + return trans('texts.initial_email'); + } else { + return ''; + } + } +} diff --git a/app/Ninja/Presenters/ClientPresenter.php b/app/Ninja/Presenters/ClientPresenter.php index f4c8adeb051b..5493b3751c0c 100644 --- a/app/Ninja/Presenters/ClientPresenter.php +++ b/app/Ninja/Presenters/ClientPresenter.php @@ -1,8 +1,9 @@ -entity->country ? $this->entity->country->name : ''; @@ -23,4 +24,15 @@ class ClientPresenter extends EntityPresenter { return $account->formatMoney($client->paid_to_date, $client); } + + public function paymentTerms() + { + $client = $this->entity; + + if (! $client->payment_terms) { + return ''; + } + + return sprintf('%s: %s %s', trans('texts.payment_terms'), trans('texts.payment_terms_net'), $client->defaultDaysDue()); + } } diff --git a/app/Ninja/Presenters/CompanyPresenter.php b/app/Ninja/Presenters/CompanyPresenter.php index 46ba7ab9f51d..7160d5d850ab 100644 --- a/app/Ninja/Presenters/CompanyPresenter.php +++ b/app/Ninja/Presenters/CompanyPresenter.php @@ -1,29 +1,30 @@ -entity->hasActivePromo()) { + if (! $this->entity->hasActivePromo()) { return ''; } return trans('texts.promo_message', [ 'expires' => $this->entity->promo_expires->format('M dS, Y'), - 'amount' => (int)($this->discount * 100) . '%' + 'amount' => (int) ($this->discount * 100) . '%', ]); } public function discountMessage() { - if ( ! $this->entity->hasActiveDiscount()) { + if (! $this->entity->hasActiveDiscount()) { return ''; } return trans('texts.discount_message', [ 'expires' => $this->entity->discount_expires->format('M dS, Y'), - 'amount' => (int)($this->discount * 100) . '%' + 'amount' => (int) ($this->discount * 100) . '%', ]); } - } diff --git a/app/Ninja/Presenters/CreditPresenter.php b/app/Ninja/Presenters/CreditPresenter.php index 8bcafe58d74c..2a2ee78f270c 100644 --- a/app/Ninja/Presenters/CreditPresenter.php +++ b/app/Ninja/Presenters/CreditPresenter.php @@ -1,9 +1,11 @@ -path()); + } + + public function path() { $type = Utils::pluralizeEntityType($this->entity->getEntityType()); $id = $this->entity->public_id; - $link = sprintf('/%s/%s', $type, $id); - return URL::to($link); + return sprintf('/%s/%s', $type, $id); } public function editUrl() @@ -23,7 +29,7 @@ class EntityPresenter extends Presenter return $this->url() . '/edit'; } - public function statusLabel() + public function statusLabel($label = false) { $class = $text = ''; @@ -35,7 +41,7 @@ class EntityPresenter extends Presenter $label = trans('texts.archived'); } else { $class = $this->entity->statusClass(); - $label = $this->entity->statusLabel(); + $label = $label ?: $this->entity->statusLabel(); } return "{$label}"; diff --git a/app/Ninja/Presenters/ExpensePresenter.php b/app/Ninja/Presenters/ExpensePresenter.php index d014374a72f7..9f8ac4c5506b 100644 --- a/app/Ninja/Presenters/ExpensePresenter.php +++ b/app/Ninja/Presenters/ExpensePresenter.php @@ -1,14 +1,15 @@ -entity->expense_category ? $this->entity->expense_category->name : ''; } - } diff --git a/app/Ninja/Presenters/InvoiceItemPresenter.php b/app/Ninja/Presenters/InvoiceItemPresenter.php index 67150df771ca..daa898602610 100644 --- a/app/Ninja/Presenters/InvoiceItemPresenter.php +++ b/app/Ninja/Presenters/InvoiceItemPresenter.php @@ -1,4 +1,6 @@ -entity->client ? $this->entity->client->getDisplayName() : ''; @@ -47,7 +50,7 @@ class InvoicePresenter extends EntityPresenter { public function age() { - if ( ! $this->entity->due_date || $this->entity->date_date == '0000-00-00') { + if (! $this->entity->due_date || $this->entity->date_date == '0000-00-00') { return 0; } @@ -100,7 +103,7 @@ class InvoicePresenter extends EntityPresenter { // https://schema.org/PaymentStatusType public function paymentStatus() { - if ( ! $this->entity->balance) { + if (! $this->entity->balance) { return 'PaymentComplete'; } elseif ($this->entity->isOverdue()) { return 'PaymentPastDue'; @@ -120,6 +123,7 @@ class InvoicePresenter extends EntityPresenter { } else { $status = $this->entity->invoice_status ? $this->entity->invoice_status->name : 'draft'; $status = strtolower($status); + return trans("texts.status_{$status}"); } } @@ -138,12 +142,14 @@ class InvoicePresenter extends EntityPresenter { { $frequency = $this->entity->frequency ? $this->entity->frequency->name : ''; $frequency = strtolower($frequency); + return trans('texts.freq_'.$frequency); } public function email() { $client = $this->entity->client; + return count($client->contacts) ? $client->contacts[0]->email : ''; } @@ -152,7 +158,7 @@ class InvoicePresenter extends EntityPresenter { $client = $this->entity->client; $paymentMethod = $client->defaultPaymentMethod(); - if ( ! $paymentMethod) { + if (! $paymentMethod) { return false; } @@ -205,7 +211,7 @@ class InvoicePresenter extends EntityPresenter { $actions = [ ['url' => 'javascript:onCloneClick()', 'label' => trans("texts.clone_{$entityType}")], ['url' => url("{$entityType}s/{$entityType}_history/{$invoice->public_id}"), 'label' => trans('texts.view_history')], - DropdownButton::DIVIDER + DropdownButton::DIVIDER, ]; if ($entityType == ENTITY_QUOTE) { @@ -219,7 +225,7 @@ class InvoicePresenter extends EntityPresenter { $actions[] = ['url' => url("quotes/{$invoice->quote_id}/edit"), 'label' => trans('texts.view_quote')]; } - if (!$invoice->is_recurring && $invoice->balance > 0) { + if (!$invoice->deleted_at && ! $invoice->is_recurring && $invoice->balance > 0) { $actions[] = ['url' => 'javascript:submitBulkAction("markPaid")', 'label' => trans('texts.mark_paid')]; $actions[] = ['url' => 'javascript:onPaymentClick()', 'label' => trans('texts.enter_payment')]; } @@ -237,8 +243,12 @@ class InvoicePresenter extends EntityPresenter { $actions[] = DropdownButton::DIVIDER; } - $actions[] = ['url' => 'javascript:onArchiveClick()', 'label' => trans("texts.archive_{$entityType}")]; - $actions[] = ['url' => 'javascript:onDeleteClick()', 'label' => trans("texts.delete_{$entityType}")]; + if (! $invoice->trashed()) { + $actions[] = ['url' => 'javascript:onArchiveClick()', 'label' => trans("texts.archive_{$entityType}")]; + } + if (! $invoice->is_deleted) { + $actions[] = ['url' => 'javascript:onDeleteClick()', 'label' => trans("texts.delete_{$entityType}")]; + } return $actions; } diff --git a/app/Ninja/Presenters/PaymentPresenter.php b/app/Ninja/Presenters/PaymentPresenter.php index 29f15189f2b8..a2c15c478ce5 100644 --- a/app/Ninja/Presenters/PaymentPresenter.php +++ b/app/Ninja/Presenters/PaymentPresenter.php @@ -1,15 +1,27 @@ -entity->amount, $this->entity->client->currency_id); } + public function completedAmount() + { + return Utils::formatMoney($this->entity->getCompletedAmount(), $this->entity->client->currency_id); + } + + public function currencySymbol() + { + return Utils::getFromCache($this->entity->currency_id ? $this->entity->currency_id : DEFAULT_CURRENCY, 'currencies')->symbol; + } + public function client() { return $this->entity->client ? $this->entity->client->getDisplayName() : ''; @@ -30,7 +42,7 @@ class PaymentPresenter extends EntityPresenter { if ($this->entity->account_gateway) { return $this->entity->account_gateway->gateway->name; } elseif ($this->entity->payment_type) { - return $this->entity->payment_type->name; + return trans('texts.payment_type_' . $this->entity->payment_type->name); } } } diff --git a/app/Ninja/Presenters/ProductPresenter.php b/app/Ninja/Presenters/ProductPresenter.php index 786e61cba75c..8d6091f06c9d 100644 --- a/app/Ninja/Presenters/ProductPresenter.php +++ b/app/Ninja/Presenters/ProductPresenter.php @@ -1,4 +1,6 @@ -account->getCurrencyId(); - if ( ! isset($this->totals[$currencyId][$dimension])) { + if (! isset($this->totals[$currencyId][$dimension])) { $this->totals[$currencyId][$dimension] = []; } - if ( ! isset($this->totals[$currencyId][$dimension][$field])) { + if (! isset($this->totals[$currencyId][$dimension][$field])) { $this->totals[$currencyId][$dimension][$field] = 0; } @@ -66,9 +65,8 @@ class AbstractReport } if (strpos($field, 'date') !== false) { - //$class[] = 'group-date-monthyear'; $class[] = 'group-date-' . (isset($this->options['group_dates_by']) ? $this->options['group_dates_by'] : 'monthyear'); - } elseif (in_array($field, ['client', 'method'])) { + } elseif (in_array($field, ['client', 'vendor', 'product', 'method', 'category'])) { $class[] = 'group-letter-100'; } elseif (in_array($field, ['amount', 'paid', 'balance'])) { $class[] = 'group-number-50'; diff --git a/app/Ninja/Reports/AgingReport.php b/app/Ninja/Reports/AgingReport.php index aaf87c47d07d..a7d1213d9c96 100644 --- a/app/Ninja/Reports/AgingReport.php +++ b/app/Ninja/Reports/AgingReport.php @@ -2,8 +2,8 @@ namespace App\Ninja\Reports; -use Auth; use App\Models\Client; +use Auth; class AgingReport extends AbstractReport { @@ -24,7 +24,7 @@ class AgingReport extends AbstractReport $clients = Client::scope() ->withArchived() ->with('contacts') - ->with(['invoices' => function($query) { + ->with(['invoices' => function ($query) { $query->invoices() ->whereIsPublic(true) ->withArchived() @@ -36,7 +36,6 @@ class AgingReport extends AbstractReport foreach ($clients->get() as $client) { foreach ($client->invoices as $invoice) { - $this->data[] = [ $this->isExport ? $client->getDisplayName() : $client->present()->link, $this->isExport ? $invoice->invoice_number : $invoice->present()->link, diff --git a/app/Ninja/Reports/ClientReport.php b/app/Ninja/Reports/ClientReport.php index a511def1258e..b0f12f63ea90 100644 --- a/app/Ninja/Reports/ClientReport.php +++ b/app/Ninja/Reports/ClientReport.php @@ -2,8 +2,8 @@ namespace App\Ninja\Reports; -use Auth; use App\Models\Client; +use Auth; class ClientReport extends AbstractReport { @@ -21,7 +21,7 @@ class ClientReport extends AbstractReport $clients = Client::scope() ->withArchived() ->with('contacts') - ->with(['invoices' => function($query) { + ->with(['invoices' => function ($query) { $query->where('invoice_date', '>=', $this->startDate) ->where('invoice_date', '<=', $this->endDate) ->where('invoice_type_id', '=', INVOICE_TYPE_STANDARD) @@ -42,7 +42,7 @@ class ClientReport extends AbstractReport $this->isExport ? $client->getDisplayName() : $client->present()->link, $account->formatMoney($amount, $client), $account->formatMoney($paid, $client), - $account->formatMoney($amount - $paid, $client) + $account->formatMoney($amount - $paid, $client), ]; $this->addToTotals($client->currency_id, 'amount', $amount); diff --git a/app/Ninja/Reports/ExpenseReport.php b/app/Ninja/Reports/ExpenseReport.php index 80e1dbf68d1f..880845f07555 100644 --- a/app/Ninja/Reports/ExpenseReport.php +++ b/app/Ninja/Reports/ExpenseReport.php @@ -2,9 +2,9 @@ namespace App\Ninja\Reports; +use App\Models\Expense; use Auth; use Utils; -use App\Models\Expense; class ExpenseReport extends AbstractReport { @@ -13,7 +13,7 @@ class ExpenseReport extends AbstractReport 'client', 'date', 'category', - 'expense_amount', + 'amount', ]; public function run() @@ -32,7 +32,7 @@ class ExpenseReport extends AbstractReport $this->data[] = [ $expense->vendor ? ($this->isExport ? $expense->vendor->name : $expense->vendor->present()->link) : '', $expense->client ? ($this->isExport ? $expense->client->getDisplayName() : $expense->client->present()->link) : '', - $expense->present()->expense_date, + $this->isExport ? $expense->present()->expense_date : link_to($expense->present()->url, $expense->present()->expense_date), $expense->present()->category, Utils::formatMoney($amount, $expense->currency_id), ]; diff --git a/app/Ninja/Reports/InvoiceDetailsReport.php b/app/Ninja/Reports/InvoiceDetailsReport.php deleted file mode 100644 index 4a100a16ca07..000000000000 --- a/app/Ninja/Reports/InvoiceDetailsReport.php +++ /dev/null @@ -1,61 +0,0 @@ -account; - $status = $this->options['invoice_status']; - - $clients = Client::scope() - ->withArchived() - ->with('contacts') - ->with(['invoices' => function($query) use ($status) { - if ($status == 'draft') { - $query->whereIsPublic(false); - } elseif ($status == 'unpaid' || $status == 'paid') { - $query->whereIsPublic(true); - } - $query->invoices() - ->withArchived() - ->where('invoice_date', '>=', $this->startDate) - ->where('invoice_date', '<=', $this->endDate) - ->with(['invoice_items']); - }]); - - foreach ($clients->get() as $client) { - foreach ($client->invoices as $invoice) { - foreach ($invoice->invoice_items as $item) { - $this->data[] = [ - $this->isExport ? $client->getDisplayName() : $client->present()->link, - $this->isExport ? $invoice->invoice_number : $invoice->present()->link, - $invoice->present()->invoice_date, - $item->product_key, - $item->qty, - $account->formatMoney($item->cost, $client), - ]; - } - - //$this->addToTotals($client->currency_id, 'paid', $payment ? $payment->getCompletedAmount() : 0); - //$this->addToTotals($client->currency_id, 'amount', $invoice->amount); - //$this->addToTotals($client->currency_id, 'balance', $invoice->balance); - } - } - } -} diff --git a/app/Ninja/Reports/InvoiceReport.php b/app/Ninja/Reports/InvoiceReport.php index b9c1c1f0286e..908e01e96a55 100644 --- a/app/Ninja/Reports/InvoiceReport.php +++ b/app/Ninja/Reports/InvoiceReport.php @@ -2,8 +2,8 @@ namespace App\Ninja\Reports; -use Auth; use App\Models\Client; +use Auth; class InvoiceReport extends AbstractReport { @@ -14,7 +14,7 @@ class InvoiceReport extends AbstractReport 'amount', 'payment_date', 'paid', - 'method' + 'method', ]; public function run() @@ -25,7 +25,7 @@ class InvoiceReport extends AbstractReport $clients = Client::scope() ->withArchived() ->with('contacts') - ->with(['invoices' => function($query) use ($status) { + ->with(['invoices' => function ($query) use ($status) { if ($status == 'draft') { $query->whereIsPublic(false); } elseif ($status == 'unpaid' || $status == 'paid') { @@ -35,8 +35,8 @@ class InvoiceReport extends AbstractReport ->withArchived() ->where('invoice_date', '>=', $this->startDate) ->where('invoice_date', '<=', $this->endDate) - ->with(['payments' => function($query) { - $query->withArchived() + ->with(['payments' => function ($query) { + $query->withArchived() ->excludeFailed() ->with('payment_type', 'account_gateway.gateway'); }, 'invoice_items']); @@ -44,10 +44,9 @@ class InvoiceReport extends AbstractReport foreach ($clients->get() as $client) { foreach ($client->invoices as $invoice) { - $payments = count($invoice->payments) ? $invoice->payments : [false]; foreach ($payments as $payment) { - if ( ! $payment && $status == 'paid') { + if (! $payment && $status == 'paid') { continue; } elseif ($payment && $status == 'unpaid') { continue; diff --git a/app/Ninja/Reports/PaymentReport.php b/app/Ninja/Reports/PaymentReport.php index 7521af2e3eb4..5df24a1d1659 100644 --- a/app/Ninja/Reports/PaymentReport.php +++ b/app/Ninja/Reports/PaymentReport.php @@ -2,8 +2,8 @@ namespace App\Ninja\Reports; -use Auth; use App\Models\Payment; +use Auth; class PaymentReport extends AbstractReport { @@ -24,10 +24,10 @@ class PaymentReport extends AbstractReport $payments = Payment::scope() ->withArchived() ->excludeFailed() - ->whereHas('client', function($query) { + ->whereHas('client', function ($query) { $query->where('is_deleted', '=', false); }) - ->whereHas('invoice', function($query) { + ->whereHas('invoice', function ($query) { $query->where('is_deleted', '=', false); }) ->with('client.contacts', 'invoice', 'payment_type', 'account_gateway.gateway') diff --git a/app/Ninja/Reports/ProductReport.php b/app/Ninja/Reports/ProductReport.php index c611f9a20198..19bb5c1fcc81 100644 --- a/app/Ninja/Reports/ProductReport.php +++ b/app/Ninja/Reports/ProductReport.php @@ -2,8 +2,8 @@ namespace App\Ninja\Reports; -use Auth; use App\Models\Client; +use Auth; class ProductReport extends AbstractReport { @@ -11,44 +11,50 @@ class ProductReport extends AbstractReport 'client', 'invoice_number', 'invoice_date', - 'quantity', 'product', + 'qty', + 'cost', + //'tax_rate1', + //'tax_rate2', ]; public function run() { $account = Auth::user()->account; + $status = $this->options['invoice_status']; $clients = Client::scope() - ->withTrashed() + ->withArchived() ->with('contacts') - ->where('is_deleted', '=', false) - ->with(['invoices' => function($query) { - $query->where('invoice_date', '>=', $this->startDate) + ->with(['invoices' => function ($query) use ($status) { + if ($status == 'draft') { + $query->whereIsPublic(false); + } elseif ($status == 'unpaid' || $status == 'paid') { + $query->whereIsPublic(true); + } + $query->invoices() + ->withArchived() + ->where('invoice_date', '>=', $this->startDate) ->where('invoice_date', '<=', $this->endDate) - ->where('is_deleted', '=', false) - ->where('is_recurring', '=', false) - ->where('invoice_type_id', '=', INVOICE_TYPE_STANDARD) - ->with(['invoice_items']) - ->withTrashed(); + ->with(['invoice_items']); }]); foreach ($clients->get() as $client) { foreach ($client->invoices as $invoice) { - - foreach ($invoice->invoice_items as $invoiceItem) { + foreach ($invoice->invoice_items as $item) { $this->data[] = [ $this->isExport ? $client->getDisplayName() : $client->present()->link, $this->isExport ? $invoice->invoice_number : $invoice->present()->link, $invoice->present()->invoice_date, - round($invoiceItem->qty, 2), - $invoiceItem->product_key, + $item->product_key, + $item->qty, + $account->formatMoney($item->cost, $client), ]; - //$reportTotals = $this->addToTotals($reportTotals, $client->currency_id, 'paid', $payment ? $payment->amount : 0); } - //$reportTotals = $this->addToTotals($reportTotals, $client->currency_id, 'amount', $invoice->amount); - //$reportTotals = $this->addToTotals($reportTotals, $client->currency_id, 'balance', $invoice->balance); + //$this->addToTotals($client->currency_id, 'paid', $payment ? $payment->getCompletedAmount() : 0); + //$this->addToTotals($client->currency_id, 'amount', $invoice->amount); + //$this->addToTotals($client->currency_id, 'balance', $invoice->balance); } } } diff --git a/app/Ninja/Reports/ProfitAndLossReport.php b/app/Ninja/Reports/ProfitAndLossReport.php index 23c6e10f534e..919c57153792 100644 --- a/app/Ninja/Reports/ProfitAndLossReport.php +++ b/app/Ninja/Reports/ProfitAndLossReport.php @@ -2,9 +2,9 @@ namespace App\Ninja\Reports; -use Auth; -use App\Models\Payment; use App\Models\Expense; +use App\Models\Payment; +use Auth; class ProfitAndLossReport extends AbstractReport { @@ -42,7 +42,6 @@ class ProfitAndLossReport extends AbstractReport $this->addToTotals($client->currency_id, 'profit', $payment->getCompletedAmount(), $payment->present()->month); } - $expenses = Expense::scope() ->with('client.contacts') ->withArchived() @@ -64,7 +63,6 @@ class ProfitAndLossReport extends AbstractReport $this->addToTotals($expense->expense_currency_id, 'profit', $expense->amount * -1, $expense->present()->month); } - //$this->addToTotals($client->currency_id, 'paid', $payment ? $payment->getCompletedAmount() : 0); //$this->addToTotals($client->currency_id, 'amount', $invoice->amount); //$this->addToTotals($client->currency_id, 'balance', $invoice->balance); diff --git a/app/Ninja/Reports/TaskReport.php b/app/Ninja/Reports/TaskReport.php index 4d7b7398b7ce..803f799a2a6f 100644 --- a/app/Ninja/Reports/TaskReport.php +++ b/app/Ninja/Reports/TaskReport.php @@ -2,9 +2,8 @@ namespace App\Ninja\Reports; -use Auth; -use Utils; use App\Models\Task; +use Utils; class TaskReport extends AbstractReport { diff --git a/app/Ninja/Repositories/AccountGatewayRepository.php b/app/Ninja/Repositories/AccountGatewayRepository.php index 03b41be7e92c..f338ccb316cf 100644 --- a/app/Ninja/Repositories/AccountGatewayRepository.php +++ b/app/Ninja/Repositories/AccountGatewayRepository.php @@ -1,4 +1,6 @@ -save(); $user = new User(); - if (!$firstName && !$lastName && !$email && !$password) { + if (! $firstName && ! $lastName && ! $email && ! $password) { $user->password = str_random(RANDOM_KEY_LENGTH); $user->username = str_random(RANDOM_KEY_LENGTH); } else { $user->first_name = $firstName; $user->last_name = $lastName; $user->email = $user->username = $email; - if (!$password) { + if (! $password) { $password = str_random(RANDOM_KEY_LENGTH); } $user->password = bcrypt($password); } - $user->confirmed = !Utils::isNinja(); - $user->registered = !Utils::isNinja() || $email; + $user->confirmed = ! Utils::isNinja(); + $user->registered = ! Utils::isNinja() || $email; - if (!$user->confirmed) { + if (! $user->confirmed) { $user->confirmation_code = str_random(RANDOM_KEY_LENGTH); } @@ -116,7 +118,7 @@ class AccountRepository } else { $clients = Client::scope() ->where('user_id', '=', $user->id) - ->with(['contacts', 'invoices' => function($query) use ($user) { + ->with(['contacts', 'invoices' => function ($query) use ($user) { $query->where('user_id', '=', $user->id); }])->get(); } @@ -185,11 +187,11 @@ class AccountRepository foreach ($entityTypes as $entityType) { $features[] = [ "new_{$entityType}", - Utils::pluralizeEntityType($entityType) . '/create' + Utils::pluralizeEntityType($entityType) . '/create', ]; $features[] = [ 'list_' . Utils::pluralizeEntityType($entityType), - Utils::pluralizeEntityType($entityType) + Utils::pluralizeEntityType($entityType), ]; } @@ -208,7 +210,7 @@ class AccountRepository $settings = array_merge(Account::$basicSettings, Account::$advancedSettings); - if ( ! Utils::isNinjaProd()) { + if (! Utils::isNinjaProd()) { $settings[] = ACCOUNT_SYSTEM_SETTINGS; } @@ -223,7 +225,7 @@ class AccountRepository $data[] = [ 'value' => trans('texts.' . $feature[0]), 'tokens' => trans('texts.' . $feature[0]), - 'url' => URL::to($feature[1]) + 'url' => URL::to($feature[1]), ]; } @@ -384,7 +386,7 @@ class AccountRepository ->first(); $clientExists = $client ? true : false; - if (!$client) { + if (! $client) { $client = new Client(); $client->public_id = $account->id; $client->account_id = $ninjaAccount->id; @@ -436,11 +438,12 @@ class AccountRepository public function updateUserFromOauth($user, $firstName, $lastName, $email, $providerId, $oauthUserId) { - if (!$user->registered) { + if (! $user->registered) { $rules = ['email' => 'email|required|unique:users,email,'.$user->id.',id']; $validator = Validator::make(['email' => $email], $rules); if ($validator->fails()) { $messages = $validator->messages(); + return $messages->first('email'); } @@ -505,9 +508,22 @@ class AccountRepository } } + public function findUser($user, $accountKey) + { + $users = $this->findUsers($user, 'account'); + + foreach ($users as $user) { + if ($accountKey && hash_equals($user->account->account_key, $accountKey)) { + return $user; + } + } + + return false; + } + public function findUserAccounts($userId1, $userId2 = false) { - if (!Schema::hasTable('user_accounts')) { + if (! Schema::hasTable('user_accounts')) { return false; } @@ -530,12 +546,12 @@ class AccountRepository public function getUserAccounts($record, $with = null) { - if (!$record) { + if (! $record) { return false; } $userIds = []; - for ($i=1; $i<=5; $i++) { + for ($i = 1; $i <= 5; $i++) { $field = "user_id$i"; if ($record->$field) { $userIds[] = $record->$field; @@ -554,7 +570,7 @@ class AccountRepository public function prepareUsersData($record) { - if (!$record) { + if (! $record) { return false; } @@ -576,18 +592,20 @@ class AccountRepository return $data; } - public function loadAccounts($userId) { + public function loadAccounts($userId) + { $record = self::findUserAccounts($userId); + return self::prepareUsersData($record); } - public function associateAccounts($userId1, $userId2) { - + public function associateAccounts($userId1, $userId2) + { $record = self::findUserAccounts($userId1, $userId2); if ($record) { foreach ([$userId1, $userId2] as $userId) { - if (!$record->hasUserId($userId)) { + if (! $record->hasUserId($userId)) { $record->setUserId($userId); } } @@ -603,9 +621,9 @@ class AccountRepository // Pick the primary user foreach ($users as $user) { - if (!$user->public_id) { + if (! $user->public_id) { $useAsPrimary = false; - if(empty($primaryUser)) { + if (empty($primaryUser)) { $useAsPrimary = true; } @@ -618,7 +636,7 @@ class AccountRepository $planLevel = 2; } - if (!$useAsPrimary && ( + if (! $useAsPrimary && ( $planLevel > $primaryUserPlanLevel || ($planLevel == $primaryUserPlanLevel && $planDetails['expires'] > $primaryUserPlanExpires) )) { @@ -626,7 +644,7 @@ class AccountRepository } } - if ($useAsPrimary) { + if ($useAsPrimary) { $primaryUser = $user; $primaryUserPlanLevel = $planLevel; if ($planDetails) { @@ -637,7 +655,7 @@ class AccountRepository } // Merge other companies into the primary user's company - if (!empty($primaryUser)) { + if (! empty($primaryUser)) { foreach ($users as $user) { if ($user == $primaryUser || $user->public_id) { continue; @@ -656,7 +674,8 @@ class AccountRepository return $users; } - public function unlinkAccount($account) { + public function unlinkAccount($account) + { foreach ($account->users as $user) { if ($userAccount = self::findUserAccounts($user->id)) { $userAccount->removeUserId($user->id); @@ -665,7 +684,8 @@ class AccountRepository } } - public function unlinkUser($userAccountId, $userId) { + public function unlinkUser($userAccountId, $userId) + { $userAccount = UserAccount::whereId($userAccountId)->first(); if ($userAccount->hasUserId($userId)) { $userAccount->removeUserId($userId); @@ -674,7 +694,7 @@ class AccountRepository $user = User::whereId($userId)->first(); - if (!$user->public_id && $user->account->company->accounts->count() > 1) { + if (! $user->public_id && $user->account->hasMultipleAccounts()) { $company = Company::create(); $company->save(); $user->account->company_id = $company->id; diff --git a/app/Ninja/Repositories/ActivityRepository.php b/app/Ninja/Repositories/ActivityRepository.php index 6a1b1a1740f1..e8538a988ed6 100644 --- a/app/Ninja/Repositories/ActivityRepository.php +++ b/app/Ninja/Repositories/ActivityRepository.php @@ -1,12 +1,14 @@ -bank_accounts()->save($bankAccount); foreach ($input['bank_accounts'] as $data) { - if ( ! isset($data['include']) || ! filter_var($data['include'], FILTER_VALIDATE_BOOLEAN)) { + if (! isset($data['include']) || ! filter_var($data['include'], FILTER_VALIDATE_BOOLEAN)) { continue; } diff --git a/app/Ninja/Repositories/BaseRepository.php b/app/Ninja/Repositories/BaseRepository.php index 71d8c1b9fbdc..39c9cb76efc6 100644 --- a/app/Ninja/Repositories/BaseRepository.php +++ b/app/Ninja/Repositories/BaseRepository.php @@ -1,10 +1,12 @@ -getClassName(); + return new $className(); } /** * @param $entity * @param $type + * * @return string */ private function getEventClass($entity, $type) @@ -58,7 +62,7 @@ class BaseRepository */ public function restore($entity) { - if ( ! $entity->trashed()) { + if (! $entity->trashed()) { return; } @@ -102,11 +106,12 @@ class BaseRepository /** * @param $ids * @param $action + * * @return int */ public function bulk($ids, $action) { - if ( ! $ids ) { + if (! $ids) { return 0; } @@ -123,6 +128,7 @@ class BaseRepository /** * @param $ids + * * @return mixed */ public function findByPublicIds($ids) @@ -132,6 +138,7 @@ class BaseRepository /** * @param $ids + * * @return mixed */ public function findByPublicIdsWithTrashed($ids) @@ -155,7 +162,7 @@ class BaseRepository $query->orWhere(function ($query) use ($table) { $query->whereNotNull($table . '.deleted_at'); - if ( ! in_array($table, ['users'])) { + if (! in_array($table, ['users'])) { $query->where($table . '.is_deleted', '=', 0); } }); diff --git a/app/Ninja/Repositories/ClientRepository.php b/app/Ninja/Repositories/ClientRepository.php index 5156298e453b..f2c3d19a1fcc 100644 --- a/app/Ninja/Repositories/ClientRepository.php +++ b/app/Ninja/Repositories/ClientRepository.php @@ -1,12 +1,14 @@ -account->client_number_counter && empty($data['id_number'])) { $data['id_number'] = Auth::user()->account->getNextNumber(); @@ -92,7 +94,7 @@ class ClientRepository extends BaseRepository // convert currency code to id if (isset($data['currency_code'])) { $currencyCode = strtolower($data['currency_code']); - $currency = Cache::get('currencies')->filter(function($item) use ($currencyCode) { + $currency = Cache::get('currencies')->filter(function ($item) use ($currencyCode) { return strtolower($item->code) == $currencyCode; })->first(); if ($currency) { @@ -128,15 +130,15 @@ class ClientRepository extends BaseRepository $first = false; } - if ( ! $client->wasRecentlyCreated) { + if (! $client->wasRecentlyCreated) { foreach ($client->contacts as $contact) { - if (!in_array($contact->public_id, $contactIds)) { + if (! in_array($contact->public_id, $contactIds)) { $contact->delete(); } } } - if (!$publicId || $publicId == '-1') { + if (! $publicId || $publicId == '-1') { event(new ClientWasCreated($client)); } else { event(new ClientWasUpdated($client)); @@ -158,7 +160,7 @@ class ClientRepository extends BaseRepository foreach ($clients as $client) { $map[$client->id] = $client; - if ( ! $client->name) { + if (! $client->name) { continue; } @@ -173,7 +175,7 @@ class ClientRepository extends BaseRepository $contacts = Contact::scope()->get(['client_id', 'first_name', 'last_name', 'public_id']); foreach ($contacts as $contact) { - if ( ! $contact->getFullName() || ! isset($map[$contact->client_id])) { + if (! $contact->getFullName() || ! isset($map[$contact->client_id])) { continue; } @@ -187,5 +189,4 @@ class ClientRepository extends BaseRepository return ($clientId && isset($map[$clientId])) ? $map[$clientId] : null; } - } diff --git a/app/Ninja/Repositories/ContactRepository.php b/app/Ninja/Repositories/ContactRepository.php index 6f157c1c40b8..51a30bec46d4 100644 --- a/app/Ninja/Repositories/ContactRepository.php +++ b/app/Ninja/Repositories/ContactRepository.php @@ -1,4 +1,6 @@ -send_invoice = true; $contact->client_id = $data['client_id']; @@ -23,4 +25,4 @@ class ContactRepository extends BaseRepository return $contact; } -} \ No newline at end of file +} diff --git a/app/Ninja/Repositories/CreditRepository.php b/app/Ninja/Repositories/CreditRepository.php index f7f4637ca3a0..adf89a709a38 100644 --- a/app/Ninja/Repositories/CreditRepository.php +++ b/app/Ninja/Repositories/CreditRepository.php @@ -1,9 +1,11 @@ -addColumn('credit_date', function ($model) { return Utils::fromSqlDate($model->credit_date); }) - ->addColumn('amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id, $model->country_id); }) - ->addColumn('balance', function ($model) { return Utils::formatMoney($model->balance, $model->currency_id, $model->country_id); }) + ->addColumn('credit_date', function ($model) { + return Utils::fromSqlDate($model->credit_date); + }) + ->addColumn('amount', function ($model) { + return Utils::formatMoney($model->amount, $model->currency_id, $model->country_id); + }) + ->addColumn('balance', function ($model) { + return Utils::formatMoney($model->balance, $model->currency_id, $model->country_id); + }) ->make(); return $table; @@ -88,18 +96,19 @@ class CreditRepository extends BaseRepository $publicId = isset($data['public_id']) ? $data['public_id'] : false; if ($credit) { - // do nothing + $credit->balance = Utils::parseFloat($input['balance']); } elseif ($publicId) { $credit = Credit::scope($publicId)->firstOrFail(); + $credit->balance = Utils::parseFloat($input['balance']); \Log::warning('Entity not set in credit repo save'); } else { $credit = Credit::createNew(); + $credit->balance = Utils::parseFloat($input['amount']); $credit->client_id = Client::getPrivateId($input['client']); } $credit->credit_date = Utils::toSqlDate($input['credit_date']); $credit->amount = Utils::parseFloat($input['amount']); - $credit->balance = Utils::parseFloat($input['amount']); $credit->private_notes = trim($input['private_notes']); $credit->save(); diff --git a/app/Ninja/Repositories/DashboardRepository.php b/app/Ninja/Repositories/DashboardRepository.php index 27524cf6625f..e1fce0310cf3 100644 --- a/app/Ninja/Repositories/DashboardRepository.php +++ b/app/Ninja/Repositories/DashboardRepository.php @@ -1,12 +1,14 @@ -data = $records; $record->label = trans("texts.{$entityType}s"); $record->lineTension = 0; @@ -102,11 +107,11 @@ class DashboardRepository } } - $data = new stdClass; + $data = new stdClass(); $data->labels = $labels; $data->datasets = $datasets; - $response = new stdClass; + $response = new stdClass(); $response->data = $data; $response->totals = $totals; @@ -115,7 +120,7 @@ class DashboardRepository private function rawChartData($entityType, $account, $groupBy, $startDate, $endDate, $currencyId) { - if ( ! in_array($groupBy, ['DAYOFYEAR', 'WEEK', 'MONTH'])) { + if (! in_array($groupBy, ['DAYOFYEAR', 'WEEK', 'MONTH'])) { return []; } @@ -177,10 +182,10 @@ class DashboardRepository ->where('invoices.is_public', '=', true) ->where('invoices.invoice_type_id', '=', INVOICE_TYPE_STANDARD); - if (!$viewAll){ - $metrics = $metrics->where(function($query) use($userId){ + if (! $viewAll) { + $metrics = $metrics->where(function ($query) use ($userId) { $query->where('invoices.user_id', '=', $userId); - $query->orwhere(function($query) use($userId){ + $query->orwhere(function ($query) use ($userId) { $query->where('invoices.user_id', '=', null); $query->where('clients.user_id', '=', $userId); }); @@ -207,14 +212,14 @@ class DashboardRepository ->where('payments.is_deleted', '=', false) ->whereNotIn('payments.payment_status_id', [PAYMENT_STATUS_VOIDED, PAYMENT_STATUS_FAILED]); - if (!$viewAll){ + if (! $viewAll) { $paidToDate->where('invoices.user_id', '=', $userId); } if ($startDate) { $paidToDate->where('payments.payment_date', '>=', $startDate); - } elseif ($account->financial_year_start) { - $paidToDate->where('payments.payment_date', '>=', $account->financialYearStart()); + } elseif ($startDate = $account->financialYearStart()) { + //$paidToDate->where('payments.payment_date', '>=', $startDate); } return $paidToDate->groupBy('payments.account_id') @@ -240,12 +245,12 @@ class DashboardRepository ->where('invoices.invoice_type_id', '=', INVOICE_TYPE_STANDARD) ->where('invoices.is_recurring', '=', false); - if (!$viewAll){ + if (! $viewAll) { $averageInvoice->where('invoices.user_id', '=', $userId); } - if ($account->financial_year_start) { - $averageInvoice->where('invoices.invoice_date', '>=', $account->financialYearStart()); + if ($startDate = $account->financialYearStart()) { + //$averageInvoice->where('invoices.invoice_date', '>=', $startDate); } return $averageInvoice->groupBy('accounts.id') @@ -267,7 +272,7 @@ class DashboardRepository ->groupBy('accounts.id') ->groupBy(DB::raw('CASE WHEN '.DB::getQueryGrammar()->wrap('clients.currency_id', true).' IS NULL THEN CASE WHEN '.DB::getQueryGrammar()->wrap('accounts.currency_id', true).' IS NULL THEN 1 ELSE '.DB::getQueryGrammar()->wrap('accounts.currency_id', true).' END ELSE '.DB::getQueryGrammar()->wrap('clients.currency_id', true).' END')); - if (!$viewAll) { + if (! $viewAll) { $balances->where('clients.user_id', '=', $userId); } @@ -279,7 +284,7 @@ class DashboardRepository $activities = Activity::where('activities.account_id', '=', $accountId) ->where('activities.activity_type_id', '>', 0); - if (!$viewAll){ + if (! $viewAll) { $activities = $activities->where('activities.user_id', '=', $userId); } @@ -306,7 +311,7 @@ class DashboardRepository ->where('contacts.is_primary', '=', true) ->where('invoices.due_date', '<', date('Y-m-d')); - if (!$viewAll){ + if (! $viewAll) { $pastDue = $pastDue->where('invoices.user_id', '=', $userId); } @@ -331,10 +336,13 @@ class DashboardRepository ->where('invoices.is_deleted', '=', false) ->where('invoices.is_public', '=', true) ->where('contacts.is_primary', '=', true) - ->where('invoices.due_date', '>=', date('Y-m-d')) + ->where(function($query) { + $query->where('invoices.due_date', '>=', date('Y-m-d')) + ->orWhereNull('invoices.due_date'); + }) ->orderBy('invoices.due_date', 'asc'); - if (!$viewAll){ + if (! $viewAll) { $upcoming = $upcoming->where('invoices.user_id', '=', $userId); } @@ -357,7 +365,7 @@ class DashboardRepository ->where('contacts.is_primary', '=', true) ->whereNotIn('payments.payment_status_id', [PAYMENT_STATUS_VOIDED, PAYMENT_STATUS_FAILED]); - if (!$viewAll){ + if (! $viewAll) { $payments = $payments->where('payments.user_id', '=', $userId); } @@ -367,7 +375,7 @@ class DashboardRepository ->get(); } - public function expenses($accountId, $userId, $viewAll) + public function expenses($account, $userId, $viewAll) { $amountField = DB::getQueryGrammar()->wrap('expenses.amount', true); $taxRate1Field = DB::getQueryGrammar()->wrap('expenses.tax_rate1', true); @@ -377,17 +385,21 @@ class DashboardRepository "SUM({$amountField} + ({$amountField} * {$taxRate1Field} / 100) + ({$amountField} * {$taxRate2Field} / 100)) as value," .DB::getQueryGrammar()->wrap('expenses.expense_currency_id', true).' as currency_id' ); - $paidToDate = DB::table('accounts') + $expenses = DB::table('accounts') ->select($select) ->leftJoin('expenses', 'accounts.id', '=', 'expenses.account_id') - ->where('accounts.id', '=', $accountId) + ->where('accounts.id', '=', $account->id) ->where('expenses.is_deleted', '=', false); - if (!$viewAll){ - $paidToDate = $paidToDate->where('expenses.user_id', '=', $userId); + if (! $viewAll) { + $expenses = $expenses->where('expenses.user_id', '=', $userId); } - return $paidToDate->groupBy('accounts.id') + if ($startDate = $account->financialYearStart()) { + //$expenses->where('expenses.expense_date', '>=', $startDate); + } + + return $expenses->groupBy('accounts.id') ->groupBy('expenses.expense_currency_id') ->get(); } diff --git a/app/Ninja/Repositories/DocumentRepository.php b/app/Ninja/Repositories/DocumentRepository.php index 2a950a7726e8..cd575ddcf382 100644 --- a/app/Ninja/Repositories/DocumentRepository.php +++ b/app/Ninja/Repositories/DocumentRepository.php @@ -1,10 +1,12 @@ -getClientOriginalExtension()); - if(empty(Document::$types[$extension]) && !empty(Document::$extraExtensions[$extension])){ + if (empty(Document::$types[$extension]) && ! empty(Document::$extraExtensions[$extension])) { $documentType = Document::$extraExtensions[$extension]; - } - else{ + } else { $documentType = $extension; } - if(empty(Document::$types[$documentType])){ + if (empty(Document::$types[$documentType])) { return 'Unsupported file type'; } @@ -71,7 +72,7 @@ class DocumentRepository extends BaseRepository $name = $uploaded->getClientOriginalName(); $size = filesize($filePath); - if($size/1000 > MAX_DOCUMENT_SIZE){ + if ($size / 1000 > MAX_DOCUMENT_SIZE) { return 'File too large'; } @@ -87,28 +88,28 @@ class DocumentRepository extends BaseRepository $document->fill($data); $disk = $document->getDisk(); - if(!$disk->exists($filename)){// Have we already stored the same file + if (! $disk->exists($filename)) {// Have we already stored the same file $stream = fopen($filePath, 'r'); - $disk->getDriver()->putStream($filename, $stream, ['mimetype'=>$documentTypeData['mime']]); + $disk->getDriver()->putStream($filename, $stream, ['mimetype' => $documentTypeData['mime']]); fclose($stream); } // This is an image; check if we need to create a preview - if(in_array($documentType, ['jpeg','png','gif','bmp','tiff','psd'])){ + if (in_array($documentType, ['jpeg', 'png', 'gif', 'bmp', 'tiff', 'psd'])) { $makePreview = false; $imageSize = getimagesize($filePath); $width = $imageSize[0]; $height = $imageSize[1]; $imgManagerConfig = []; - if(in_array($documentType, ['gif','bmp','tiff','psd'])){ + if (in_array($documentType, ['gif', 'bmp', 'tiff', 'psd'])) { // Needs to be converted $makePreview = true; - } else if($width > DOCUMENT_PREVIEW_SIZE || $height > DOCUMENT_PREVIEW_SIZE){ + } elseif ($width > DOCUMENT_PREVIEW_SIZE || $height > DOCUMENT_PREVIEW_SIZE) { $makePreview = true; } - if(in_array($documentType,['bmp','tiff','psd'])){ - if(!class_exists('Imagick')){ + if (in_array($documentType, ['bmp', 'tiff', 'psd'])) { + if (! class_exists('Imagick')) { // Cant't read this $makePreview = false; } else { @@ -116,24 +117,24 @@ class DocumentRepository extends BaseRepository } } - if($makePreview){ + if ($makePreview) { $previewType = 'jpeg'; - if(in_array($documentType, ['png','gif','tiff','psd'])){ + if (in_array($documentType, ['png', 'gif', 'tiff', 'psd'])) { // Has transparency $previewType = 'png'; } $document->preview = \Auth::user()->account->account_key.'/'.$hash.'.'.$documentType.'.x'.DOCUMENT_PREVIEW_SIZE.'.'.$previewType; - if(!$disk->exists($document->preview)){ + if (! $disk->exists($document->preview)) { // We haven't created a preview yet $imgManager = new ImageManager($imgManagerConfig); $img = $imgManager->make($filePath); - if($width <= DOCUMENT_PREVIEW_SIZE && $height <= DOCUMENT_PREVIEW_SIZE){ + if ($width <= DOCUMENT_PREVIEW_SIZE && $height <= DOCUMENT_PREVIEW_SIZE) { $previewWidth = $width; $previewHeight = $height; - } else if($width > $height) { + } elseif ($width > $height) { $previewWidth = DOCUMENT_PREVIEW_SIZE; $previewHeight = $height * DOCUMENT_PREVIEW_SIZE / $width; } else { @@ -146,11 +147,10 @@ class DocumentRepository extends BaseRepository $previewContent = (string) $img->encode($previewType); $disk->put($document->preview, $previewContent); $base64 = base64_encode($previewContent); - } - else{ + } else { $base64 = base64_encode($disk->get($document->preview)); } - }else{ + } else { $base64 = base64_encode(file_get_contents($filePath)); } } @@ -161,7 +161,7 @@ class DocumentRepository extends BaseRepository $document->hash = $hash; $document->name = substr($name, -255); - if(!empty($imageSize)){ + if (! empty($imageSize)) { $document->width = $imageSize[0]; $document->height = $imageSize[1]; } @@ -169,8 +169,8 @@ class DocumentRepository extends BaseRepository $document->save(); $doc_array = $document->toArray(); - if(!empty($base64)){ - $mime = Document::$types[!empty($previewType)?$previewType:$documentType]['mime']; + if (! empty($base64)) { + $mime = Document::$types[! empty($previewType) ? $previewType : $documentType]['mime']; $doc_array['base64'] = 'data:'.$mime.';base64,'.$base64; } @@ -179,8 +179,7 @@ class DocumentRepository extends BaseRepository public function getClientDatatable($contactId, $entityType, $search) { - - $query = DB::table('invitations') + $query = DB::table('invitations') ->join('accounts', 'accounts.id', '=', 'invitations.account_id') ->join('invoices', 'invoices.id', '=', 'invitations.invoice_id') ->join('documents', 'documents.invoice_id', '=', 'invitations.invoice_id') @@ -213,7 +212,7 @@ class DocumentRepository extends BaseRepository return link_to( '/client/documents/'.$model->invitation_key.'/'.$model->public_id.'/'.$model->name, $model->name, - ['target'=>'_blank'] + ['target' => '_blank'] )->toHtml(); }) ->addColumn('document_date', function ($model) { diff --git a/app/Ninja/Repositories/ExpenseCategoryRepository.php b/app/Ninja/Repositories/ExpenseCategoryRepository.php index a9224b4266a5..8ef629a17487 100644 --- a/app/Ninja/Repositories/ExpenseCategoryRepository.php +++ b/app/Ninja/Repositories/ExpenseCategoryRepository.php @@ -1,9 +1,10 @@ -orWhere('expenses.invoice_id', '>', 0); - if ( ! in_array(EXPENSE_STATUS_PAID, $statuses)) { + if (! in_array(EXPENSE_STATUS_PAID, $statuses)) { $query->where('invoices.balance', '>', 0); } } @@ -123,7 +125,8 @@ class ExpenseRepository extends BaseRepository $query->where('expenses.public_notes', 'like', '%'.$filter.'%') ->orWhere('clients.name', 'like', '%'.$filter.'%') ->orWhere('vendors.name', 'like', '%'.$filter.'%') - ->orWhere('expense_categories.name', 'like', '%'.$filter.'%');; + ->orWhere('expense_categories.name', 'like', '%'.$filter.'%'); + ; }); } @@ -158,10 +161,10 @@ class ExpenseRepository extends BaseRepository $expense->should_be_invoiced = isset($input['should_be_invoiced']) && floatval($input['should_be_invoiced']) || $expense->client_id ? true : false; - if ( ! $expense->expense_currency_id) { + if (! $expense->expense_currency_id) { $expense->expense_currency_id = \Auth::user()->account->getCurrencyId(); } - if ( ! $expense->invoice_currency_id) { + if (! $expense->invoice_currency_id) { $expense->invoice_currency_id = \Auth::user()->account->getCurrencyId(); } @@ -174,12 +177,13 @@ class ExpenseRepository extends BaseRepository $expense->save(); // Documents - $document_ids = !empty($input['document_ids'])?array_map('intval', $input['document_ids']):[];; - foreach ($document_ids as $document_id){ + $document_ids = ! empty($input['document_ids']) ? array_map('intval', $input['document_ids']) : []; + ; + foreach ($document_ids as $document_id) { // check document completed upload before user submitted form if ($document_id) { $document = Document::scope($document_id)->first(); - if($document && Auth::user()->can('edit', $document)){ + if ($document && Auth::user()->can('edit', $document)) { $document->invoice_id = null; $document->expense_id = $expense->id; $document->save(); @@ -188,9 +192,9 @@ class ExpenseRepository extends BaseRepository } // prevent loading all of the documents if we don't have to - if ( ! $expense->wasRecentlyCreated) { - foreach ($expense->documents as $document){ - if ( ! in_array($document->public_id, $document_ids)){ + if (! $expense->wasRecentlyCreated) { + foreach ($expense->documents as $document) { + if (! in_array($document->public_id, $document_ids)) { // Not checking permissions; deleting a document is just editing the invoice $document->delete(); } diff --git a/app/Ninja/Repositories/InvoiceRepository.php b/app/Ninja/Repositories/InvoiceRepository.php index 2527a601e7a7..6169835bc5e4 100644 --- a/app/Ninja/Repositories/InvoiceRepository.php +++ b/app/Ninja/Repositories/InvoiceRepository.php @@ -1,19 +1,21 @@ -orWhere('invoice_status_id', '=', $status); } + if (in_array(INVOICE_STATUS_UNPAID, $statuses)) { + $query->orWhere(function ($query) use ($statuses) { + $query->where('invoices.balance', '>', 0) + ->where('invoices.is_public', '=', true); + }); + } if (in_array(INVOICE_STATUS_OVERDUE, $statuses)) { $query->orWhere(function ($query) use ($statuses) { $query->where('invoices.balance', '>', 0) @@ -209,10 +217,18 @@ class InvoiceRepository extends BaseRepository ); $table = \Datatable::query($query) - ->addColumn('frequency', function ($model) { return $model->frequency; }) - ->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, $model->country_id); }) + ->addColumn('frequency', function ($model) { + return $model->frequency; + }) + ->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, $model->country_id); + }) ->addColumn('client_enable_auto_bill', function ($model) { if ($model->client_enable_auto_bill) { return trans('texts.enabled') . ' - '.trans('texts.disable').''; @@ -260,28 +276,37 @@ class InvoiceRepository extends BaseRepository ); $table = \Datatable::query($query) - ->addColumn('invoice_number', function ($model) use ($entityType) { return link_to('/view/'.$model->invitation_key, $model->invoice_number)->toHtml(); }) - ->addColumn('invoice_date', function ($model) { return Utils::fromSqlDate($model->invoice_date); }) - ->addColumn('amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id, $model->country_id); }); + ->addColumn('invoice_number', function ($model) use ($entityType) { + return link_to('/view/'.$model->invitation_key, $model->invoice_number)->toHtml(); + }) + ->addColumn('invoice_date', function ($model) { + return Utils::fromSqlDate($model->invoice_date); + }) + ->addColumn('amount', function ($model) { + return Utils::formatMoney($model->amount, $model->currency_id, $model->country_id); + }); if ($entityType == ENTITY_INVOICE) { $table->addColumn('balance', function ($model) { return $model->partial > 0 ? trans('texts.partial_remaining', [ 'partial' => Utils::formatMoney($model->partial, $model->currency_id, $model->country_id), - 'balance' => Utils::formatMoney($model->balance, $model->currency_id, $model->country_id) + 'balance' => Utils::formatMoney($model->balance, $model->currency_id, $model->country_id), ]) : Utils::formatMoney($model->balance, $model->currency_id, $model->country_id); }); } - return $table->addColumn('due_date', function ($model) { return Utils::fromSqlDate($model->due_date); }) + return $table->addColumn('due_date', function ($model) { + return Utils::fromSqlDate($model->due_date); + }) ->make(); } /** - * @param array $data + * @param array $data * @param Invoice|null $invoice + * * @return Invoice|mixed */ public function save(array $data, Invoice $invoice = null) @@ -290,7 +315,7 @@ class InvoiceRepository extends BaseRepository $account = \Auth::user()->account; $publicId = isset($data['public_id']) ? $data['public_id'] : false; - $isNew = !$publicId || $publicId == '-1'; + $isNew = ! $publicId || $publicId == '-1'; if ($invoice) { // do nothing @@ -310,8 +335,11 @@ class InvoiceRepository extends BaseRepository if (isset($data['has_expenses']) && filter_var($data['has_expenses'], FILTER_VALIDATE_BOOLEAN)) { $invoice->has_expenses = true; } - if ($account->payment_terms != 0) { - $invoice->due_date = $account->defaultDueDate(); + + // set the default due date + if ($entityType == ENTITY_INVOICE) { + $client = Client::scope()->whereId($data['client_id'])->first(); + $invoice->due_date = $account->defaultDueDate($client); } } else { $invoice = Invoice::scope($publicId)->firstOrFail(); @@ -326,7 +354,7 @@ class InvoiceRepository extends BaseRepository if (isset($data['is_public']) && filter_var($data['is_public'], FILTER_VALIDATE_BOOLEAN)) { $invoice->is_public = true; - if ( ! $invoice->isSent()) { + if (! $invoice->isSent()) { $invoice->invoice_status_id = INVOICE_STATUS_SENT; } } @@ -344,7 +372,7 @@ class InvoiceRepository extends BaseRepository $account->save(); } - if (!empty($data['invoice_number']) && !$invoice->is_recurring) { + if (! empty($data['invoice_number']) && ! $invoice->is_recurring) { $invoice->invoice_number = trim($data['invoice_number']); } @@ -360,8 +388,8 @@ class InvoiceRepository extends BaseRepository $invoice->invoice_date = Utils::toSqlDate($data['invoice_date']); } - if(isset($data['invoice_status_id'])) { - if($data['invoice_status_id'] == 0) { + if (isset($data['invoice_status_id'])) { + if ($data['invoice_status_id'] == 0) { $data['invoice_status_id'] = INVOICE_STATUS_DRAFT; } $invoice->invoice_status_id = $data['invoice_status_id']; @@ -378,7 +406,7 @@ class InvoiceRepository extends BaseRepository $invoice->client_enable_auto_bill = isset($data['client_enable_auto_bill']) && $data['client_enable_auto_bill'] ? true : false; $invoice->auto_bill = array_get($data, 'auto_bill_id') ?: array_get($data, 'auto_bill', AUTO_BILL_OFF); - if ($invoice->auto_bill < AUTO_BILL_OFF || $invoice->auto_bill > AUTO_BILL_ALWAYS ) { + if ($invoice->auto_bill < AUTO_BILL_OFF || $invoice->auto_bill > AUTO_BILL_ALWAYS) { $invoice->auto_bill = AUTO_BILL_OFF; } @@ -388,7 +416,7 @@ class InvoiceRepository extends BaseRepository $invoice->due_date = $data['due_date']; } } else { - if (!empty($data['due_date']) || !empty($data['due_date_sql'])) { + if (! empty($data['due_date']) || ! empty($data['due_date_sql'])) { $invoice->due_date = isset($data['due_date_sql']) ? $data['due_date_sql'] : Utils::toSqlDate($data['due_date']); } $invoice->frequency_id = 0; @@ -404,11 +432,11 @@ class InvoiceRepository extends BaseRepository $invoice->terms = ''; } - $invoice->invoice_footer = (isset($data['invoice_footer']) && trim($data['invoice_footer'])) ? trim($data['invoice_footer']) : (!$publicId && $account->invoice_footer ? $account->invoice_footer : ''); - $invoice->public_notes = isset($data['public_notes']) ? trim($data['public_notes']) : null; + $invoice->invoice_footer = (isset($data['invoice_footer']) && trim($data['invoice_footer'])) ? trim($data['invoice_footer']) : (! $publicId && $account->invoice_footer ? $account->invoice_footer : ''); + $invoice->public_notes = isset($data['public_notes']) ? trim($data['public_notes']) : ''; // process date variables if not recurring - if(!$invoice->is_recurring) { + if (! $invoice->is_recurring) { $invoice->terms = Utils::processVariables($invoice->terms); $invoice->invoice_footer = Utils::processVariables($invoice->invoice_footer); $invoice->public_notes = Utils::processVariables($invoice->public_notes); @@ -431,7 +459,7 @@ class InvoiceRepository extends BaseRepository foreach ($data['invoice_items'] as $item) { $item = (array) $item; - if (!$item['cost'] && !$item['product_key'] && !$item['notes']) { + if (! $item['cost'] && ! $item['product_key'] && ! $item['notes']) { continue; } @@ -450,9 +478,9 @@ class InvoiceRepository extends BaseRepository if ($invoice->discount > 0) { if ($invoice->is_amount_discount) { - $lineTotal -= round(($lineTotal/$total) * $invoice->discount, 2); + $lineTotal -= round(($lineTotal / $total) * $invoice->discount, 2); } else { - $lineTotal -= round($lineTotal * ($invoice->discount/100), 2); + $lineTotal -= round($lineTotal * ($invoice->discount / 100), 2); } } @@ -470,7 +498,7 @@ class InvoiceRepository extends BaseRepository if ($invoice->is_amount_discount) { $total -= $invoice->discount; } else { - $discount = round($total * ($invoice->discount/100), 2); + $discount = round($total * ($invoice->discount / 100), 2); $total -= $discount; } } @@ -509,10 +537,10 @@ class InvoiceRepository extends BaseRepository $total += $itemTax; // custom fields not charged taxes - if ($invoice->custom_value1 && !$invoice->custom_taxes1) { + if ($invoice->custom_value1 && ! $invoice->custom_taxes1) { $total += $invoice->custom_value1; } - if ($invoice->custom_value2 && !$invoice->custom_taxes2) { + if ($invoice->custom_value2 && ! $invoice->custom_taxes2) { $total += $invoice->custom_value2; } @@ -523,7 +551,7 @@ class InvoiceRepository extends BaseRepository } if (isset($data['partial'])) { - $invoice->partial = max(0,min(round(Utils::parseFloat($data['partial']), 2), $invoice->balance)); + $invoice->partial = max(0, min(round(Utils::parseFloat($data['partial']), 2), $invoice->balance)); } $invoice->amount = $total; @@ -533,16 +561,15 @@ class InvoiceRepository extends BaseRepository $invoice->invoice_items()->forceDelete(); } - if ( ! empty($data['document_ids'])) { + if (! empty($data['document_ids'])) { $document_ids = array_map('intval', $data['document_ids']); - foreach ($document_ids as $document_id){ + foreach ($document_ids as $document_id) { $document = Document::scope($document_id)->first(); - if($document && Auth::user()->can('edit', $document)){ - - if($document->invoice_id && $document->invoice_id != $invoice->id){ + if ($document && Auth::user()->can('edit', $document)) { + if ($document->invoice_id && $document->invoice_id != $invoice->id) { // From a clone $document = $document->cloneDocument(); - $document_ids[] = $document->public_id;// Don't remove this document + $document_ids[] = $document->public_id; // Don't remove this document } $document->invoice_id = $invoice->id; @@ -551,12 +578,12 @@ class InvoiceRepository extends BaseRepository } } - if ( ! $invoice->wasRecentlyCreated) { - foreach ($invoice->documents as $document){ - if(!in_array($document->public_id, $document_ids)){ + if (! $invoice->wasRecentlyCreated) { + foreach ($invoice->documents as $document) { + if (! in_array($document->public_id, $document_ids)) { // Removed // Not checking permissions; deleting a document is just editing the invoice - if($document->invoice_id == $invoice->id){ + if ($document->invoice_id == $invoice->id) { // Make sure the document isn't on a clone $document->delete(); } @@ -574,7 +601,7 @@ class InvoiceRepository extends BaseRepository $task = false; if (isset($item['task_public_id']) && $item['task_public_id']) { $task = Task::scope($item['task_public_id'])->where('invoice_id', '=', null)->firstOrFail(); - if(Auth::user()->can('edit', $task)){ + if (Auth::user()->can('edit', $task)) { $task->invoice_id = $invoice->id; $task->client_id = $invoice->client_id; $task->save(); @@ -584,7 +611,7 @@ class InvoiceRepository extends BaseRepository $expense = false; if (isset($item['expense_public_id']) && $item['expense_public_id']) { $expense = Expense::scope($item['expense_public_id'])->where('invoice_id', '=', null)->firstOrFail(); - if(Auth::user()->can('edit', $expense)){ + if (Auth::user()->can('edit', $expense)) { $expense->invoice_id = $invoice->id; $expense->client_id = $invoice->client_id; $expense->save(); @@ -594,18 +621,19 @@ class InvoiceRepository extends BaseRepository if ($productKey = trim($item['product_key'])) { if (\Auth::user()->account->update_products && ! $invoice->has_tasks && ! $invoice->has_expenses) { $product = Product::findProductByKey($productKey); - if (!$product) { + if (! $product) { if (Auth::user()->can('create', ENTITY_PRODUCT)) { $product = Product::createNew(); $product->product_key = trim($item['product_key']); - } - else{ + } else { $product = null; } } if ($product && (Auth::user()->can('edit', $product))) { $product->notes = ($task || $expense) ? '' : $item['notes']; $product->cost = $expense ? 0 : $item['cost']; + $product->custom_value1 = isset($item['custom_value1']) ? $item['custom_value1'] : null; + $product->custom_value2 = isset($item['custom_value2']) ? $item['custom_value2'] : null; $product->save(); } } @@ -641,7 +669,8 @@ class InvoiceRepository extends BaseRepository /** * @param Invoice $invoice - * @param null $quotePublicId + * @param null $quotePublicId + * * @return mixed */ public function cloneInvoice(Invoice $invoice, $quotePublicId = null) @@ -669,6 +698,7 @@ class InvoiceRepository extends BaseRepository } $clone->invoice_number = $invoiceNumber ?: $account->getNextNumber($clone); $clone->invoice_date = date_create()->format('Y-m-d'); + $clone->due_date = $account->defaultDueDate($invoice->client); foreach ([ 'client_id', @@ -782,7 +812,7 @@ class InvoiceRepository extends BaseRepository */ public function markPaid(Invoice $invoice) { - if ( ! $invoice->canBePaid()) { + if (! $invoice->canBePaid()) { return; } @@ -799,26 +829,30 @@ class InvoiceRepository extends BaseRepository /** * @param $invitationKey + * * @return Invitation|bool */ public function findInvoiceByInvitation($invitationKey) { + // check for extra params at end of value (from website feature) + list($invitationKey) = explode('&', $invitationKey); + /** @var \App\Models\Invitation $invitation */ $invitation = Invitation::where('invitation_key', '=', $invitationKey)->first(); - if (!$invitation) { + if (! $invitation) { return false; } $invoice = $invitation->invoice; - if (!$invoice || $invoice->is_deleted) { + if (! $invoice || $invoice->is_deleted) { return false; } $invoice->load('user', 'invoice_items', 'documents', 'invoice_design', 'account.country', 'client.contacts', 'client.country'); $client = $invoice->client; - if (!$client || $client->is_deleted) { + if (! $client || $client->is_deleted) { return false; } @@ -827,6 +861,8 @@ class InvoiceRepository extends BaseRepository /** * @param $clientId + * @param mixed $entityType + * * @return mixed */ public function findOpenInvoices($clientId, $entityType = false) @@ -851,6 +887,7 @@ class InvoiceRepository extends BaseRepository /** * @param Invoice $recurInvoice + * * @return mixed */ public function createRecurringInvoice(Invoice $recurInvoice) @@ -861,11 +898,11 @@ class InvoiceRepository extends BaseRepository return false; } - if (!$recurInvoice->user->confirmed) { + if (! $recurInvoice->user->confirmed) { return false; } - if (!$recurInvoice->shouldSendToday()) { + if (! $recurInvoice->shouldSendToday()) { return false; } @@ -929,7 +966,7 @@ class InvoiceRepository extends BaseRepository $recurInvoice->last_sent_date = date('Y-m-d'); $recurInvoice->save(); - if ($recurInvoice->getAutoBillEnabled() && !$recurInvoice->account->auto_bill_on_due_date) { + if ($recurInvoice->getAutoBillEnabled() && ! $recurInvoice->account->auto_bill_on_due_date) { // autoBillInvoice will check for ACH, so we're not checking here if ($this->paymentService->autoBillInvoice($invoice)) { // update the invoice reference to match its actual state @@ -943,13 +980,14 @@ class InvoiceRepository extends BaseRepository /** * @param Account $account + * * @return mixed */ public function findNeedingReminding(Account $account) { $dates = []; - for ($i=1; $i<=3; $i++) { + for ($i = 1; $i <= 3; $i++) { if ($date = $account->getReminderDate($i)) { $field = $account->{"field_reminder{$i}"} == REMINDER_FIELD_DUE_DATE ? 'due_date' : 'invoice_date'; $dates[] = "$field = '$date'"; diff --git a/app/Ninja/Repositories/NinjaRepository.php b/app/Ninja/Repositories/NinjaRepository.php index d1dc7abede6e..20921ce07934 100644 --- a/app/Ninja/Repositories/NinjaRepository.php +++ b/app/Ninja/Repositories/NinjaRepository.php @@ -1,4 +1,6 @@ -first(); - if (!$account) { + if (! $account) { return; } $company = $account->company; - $company->plan = !empty($data['plan']) && $data['plan'] != PLAN_FREE?$data['plan']:null; - $company->plan_term = !empty($data['plan_term'])?$data['plan_term']:null; - $company->plan_paid = !empty($data['plan_paid'])?$data['plan_paid']:null; - $company->plan_started = !empty($data['plan_started'])?$data['plan_started']:null; - $company->plan_expires = !empty($data['plan_expires'])?$data['plan_expires']:null; + $company->plan = ! empty($data['plan']) && $data['plan'] != PLAN_FREE ? $data['plan'] : null; + $company->plan_term = ! empty($data['plan_term']) ? $data['plan_term'] : null; + $company->plan_paid = ! empty($data['plan_paid']) ? $data['plan_paid'] : null; + $company->plan_started = ! empty($data['plan_started']) ? $data['plan_started'] : null; + $company->plan_expires = ! empty($data['plan_expires']) ? $data['plan_expires'] : null; $company->save(); } diff --git a/app/Ninja/Repositories/PaymentRepository.php b/app/Ninja/Repositories/PaymentRepository.php index b6f37de72420..84b0c440b380 100644 --- a/app/Ninja/Repositories/PaymentRepository.php +++ b/app/Ninja/Repositories/PaymentRepository.php @@ -1,10 +1,12 @@ -transaction_reference = trim($input['transaction_reference']); } - if (!$publicId) { + if (! $publicId) { $clientId = $input['client_id']; $amount = Utils::parseFloat($input['amount']); @@ -193,7 +195,7 @@ class PaymentRepository extends BaseRepository $remaining = $amount; foreach ($credits as $credit) { $remaining -= $credit->apply($remaining); - if ( ! $remaining) { + if (! $remaining) { break; } } diff --git a/app/Ninja/Repositories/PaymentTermRepository.php b/app/Ninja/Repositories/PaymentTermRepository.php index bde31c20a81d..5562f68524a7 100644 --- a/app/Ninja/Repositories/PaymentTermRepository.php +++ b/app/Ninja/Repositories/PaymentTermRepository.php @@ -1,4 +1,6 @@ -where('payment_terms.account_id', '=', $accountId) + ->where('payment_terms.account_id', '=', $accountId) ->where('payment_terms.deleted_at', '=', null) ->select('payment_terms.public_id', 'payment_terms.name', 'payment_terms.num_days', 'payment_terms.deleted_at'); } diff --git a/app/Ninja/Repositories/ProductRepository.php b/app/Ninja/Repositories/ProductRepository.php index 6500124c513a..3e01d885669b 100644 --- a/app/Ninja/Repositories/ProductRepository.php +++ b/app/Ninja/Repositories/ProductRepository.php @@ -1,7 +1,9 @@ -leftJoin('tax_rates', function($join) { + ->leftJoin('tax_rates', function ($join) { $join->on('tax_rates.id', '=', 'products.default_tax_rate_id') ->whereNull('tax_rates.deleted_at'); }) @@ -80,7 +82,7 @@ class ProductRepository extends BaseRepository ->get(); foreach ($products as $product) { - if ( ! $product->product_key) { + if (! $product->product_key) { continue; } @@ -95,6 +97,4 @@ class ProductRepository extends BaseRepository return ($productId && isset($map[$productId])) ? $map[$productId] : null; } - - } diff --git a/app/Ninja/Repositories/ProjectRepository.php b/app/Ninja/Repositories/ProjectRepository.php index 64ba210ba3a9..8e1bedb5b14e 100644 --- a/app/Ninja/Repositories/ProjectRepository.php +++ b/app/Ninja/Repositories/ProjectRepository.php @@ -1,9 +1,10 @@ - 0, 'pro' => 0, - 'enterprise' => 0 + 'enterprise' => 0, ]; foreach ($accounts as $account) { diff --git a/app/Ninja/Repositories/TaskRepository.php b/app/Ninja/Repositories/TaskRepository.php index 579ef71e684c..e0dbc298ad24 100644 --- a/app/Ninja/Repositories/TaskRepository.php +++ b/app/Ninja/Repositories/TaskRepository.php @@ -1,10 +1,12 @@ -orWhere('tasks.invoice_id', '>', 0); - if ( ! in_array(TASK_STATUS_PAID, $statuses)) { + if (! in_array(TASK_STATUS_PAID, $statuses)) { $query->where('invoices.balance', '>', 0); } } @@ -137,11 +139,11 @@ class TaskRepository extends BaseRepository if ($data['action'] == 'start') { $task->is_running = true; $timeLog[] = [strtotime('now'), false]; - } else if ($data['action'] == 'resume') { + } elseif ($data['action'] == 'resume') { $task->is_running = true; $timeLog[] = [strtotime('now'), false]; - } else if ($data['action'] == 'stop' && $task->is_running) { - $timeLog[count($timeLog)-1][1] = time(); + } elseif ($data['action'] == 'stop' && $task->is_running) { + $timeLog[count($timeLog) - 1][1] = time(); $task->is_running = false; } } @@ -151,5 +153,4 @@ class TaskRepository extends BaseRepository return $task; } - } diff --git a/app/Ninja/Repositories/TaxRateRepository.php b/app/Ninja/Repositories/TaxRateRepository.php index 52f229afd9af..d16973941b50 100644 --- a/app/Ninja/Repositories/TaxRateRepository.php +++ b/app/Ninja/Repositories/TaxRateRepository.php @@ -1,8 +1,10 @@ -where('account_tokens.user_id', '=', $userId) - ->whereNull('account_tokens.deleted_at');; + ->whereNull('account_tokens.deleted_at'); + ; return $query->select('account_tokens.public_id', 'account_tokens.name', 'account_tokens.token', 'account_tokens.public_id', 'account_tokens.deleted_at'); } diff --git a/app/Ninja/Repositories/UserRepository.php b/app/Ninja/Repositories/UserRepository.php index 0d634aaed99b..3e9e3182c0dd 100644 --- a/app/Ninja/Repositories/UserRepository.php +++ b/app/Ninja/Repositories/UserRepository.php @@ -1,8 +1,8 @@ -send_invoice = true; $contact->vendor_id = $data['vendor_id']; @@ -24,4 +26,4 @@ class VendorContactRepository extends BaseRepository return $contact; } -} \ No newline at end of file +} diff --git a/app/Ninja/Repositories/VendorRepository.php b/app/Ninja/Repositories/VendorRepository.php index b64716fe7b63..0b5364841753 100644 --- a/app/Ninja/Repositories/VendorRepository.php +++ b/app/Ninja/Repositories/VendorRepository.php @@ -1,8 +1,10 @@ -with('vendor_contacts')->firstOrFail(); @@ -82,19 +84,19 @@ class VendorRepository extends BaseRepository $vendor->fill($data); $vendor->save(); - $first = true; - $vendorcontacts = isset($data['vendor_contact']) ? [$data['vendor_contact']] : $data['vendor_contacts']; - $vendorcontactIds = []; + $first = true; + $vendorcontacts = isset($data['vendor_contact']) ? [$data['vendor_contact']] : $data['vendor_contacts']; + $vendorcontactIds = []; foreach ($vendorcontacts as $vendorcontact) { - $vendorcontact = $vendor->addVendorContact($vendorcontact, $first); + $vendorcontact = $vendor->addVendorContact($vendorcontact, $first); $vendorcontactIds[] = $vendorcontact->public_id; - $first = false; + $first = false; } - if ( ! $vendor->wasRecentlyCreated) { + if (! $vendor->wasRecentlyCreated) { foreach ($vendor->vendor_contacts as $contact) { - if (!in_array($contact->public_id, $vendorcontactIds)) { + if (! in_array($contact->public_id, $vendorcontactIds)) { $contact->delete(); } } diff --git a/app/Ninja/Serializers/ArraySerializer.php b/app/Ninja/Serializers/ArraySerializer.php index a759ffc9e69c..071e697ce18a 100644 --- a/app/Ninja/Serializers/ArraySerializer.php +++ b/app/Ninja/Serializers/ArraySerializer.php @@ -1,15 +1,18 @@ - $account_token->name, - 'token' => $account_token->token + 'token' => $account_token->token, ]; } -} \ No newline at end of file +} diff --git a/app/Ninja/Transformers/AccountTransformer.php b/app/Ninja/Transformers/AccountTransformer.php index 434d9e7e3aeb..2dcecfe002c7 100644 --- a/app/Ninja/Transformers/AccountTransformer.php +++ b/app/Ninja/Transformers/AccountTransformer.php @@ -1,9 +1,11 @@ -serializer); + return $this->includeCollection($account->expense_categories, $transformer, 'expense_categories'); } /** * @param Account $account + * * @return \League\Fractal\Resource\Collection */ public function includeProjects(Account $account) { $transformer = new ProjectTransformer($account, $this->serializer); + return $this->includeCollection($account->projects, $transformer, 'projects'); } /** * @param Account $account + * * @return \League\Fractal\Resource\Collection */ public function includeUsers(Account $account) { $transformer = new UserTransformer($account, $this->serializer); + return $this->includeCollection($account->users, $transformer, 'users'); } /** * @param Account $account + * * @return \League\Fractal\Resource\Collection */ public function includeClients(Account $account) { $transformer = new ClientTransformer($account, $this->serializer); + return $this->includeCollection($account->clients, $transformer, 'clients'); } /** * @param Account $account + * * @return \League\Fractal\Resource\Collection */ public function includeInvoices(Account $account) { $transformer = new InvoiceTransformer($account, $this->serializer); + return $this->includeCollection($account->invoices, $transformer, 'invoices'); } /** * @param Account $account + * * @return \League\Fractal\Resource\Collection */ public function includeProducts(Account $account) { $transformer = new ProductTransformer($account, $this->serializer); + return $this->includeCollection($account->products, $transformer, 'products'); } /** * @param Account $account + * * @return \League\Fractal\Resource\Collection */ public function includeTaxRates(Account $account) { $transformer = new TaxRateTransformer($account, $this->serializer); + return $this->includeCollection($account->tax_rates, $transformer, 'taxRates'); } /** * @param Account $account + * * @return \League\Fractal\Resource\Collection */ public function includePayments(Account $account) { $transformer = new PaymentTransformer($account, $this->serializer); + return $this->includeCollection($account->payments, $transformer, 'payments'); } /** * @param Account $account - * @return array + * * @throws \Laracasts\Presenter\Exceptions\PresenterException + * + * @return array */ public function transform(Account $account) { diff --git a/app/Ninja/Transformers/ActivityTransformer.php b/app/Ninja/Transformers/ActivityTransformer.php index 44a5a712b472..5c0ea3e3ab41 100644 --- a/app/Ninja/Transformers/ActivityTransformer.php +++ b/app/Ninja/Transformers/ActivityTransformer.php @@ -1,22 +1,24 @@ - $this->getTimestamp($activity->updated_at), 'expense_id' => $activity->expense_id ? $activity->expense->public_id : null, 'is_system' => $activity->is_system ? (bool) $activity->is_system : null, - 'contact_id' => $activity->contact_id ? $activity->contact->public_id : null + 'contact_id' => $activity->contact_id ? $activity->contact->public_id : null, ]; } } diff --git a/app/Ninja/Transformers/ClientTransformer.php b/app/Ninja/Transformers/ClientTransformer.php index 67239fa9b28d..2986eb73c1fb 100644 --- a/app/Ninja/Transformers/ClientTransformer.php +++ b/app/Ninja/Transformers/ClientTransformer.php @@ -1,42 +1,42 @@ -account, $this->serializer); + return $this->includeCollection($client->contacts, $transformer, ENTITY_CONTACT); } /** * @param Client $client + * * @return \League\Fractal\Resource\Collection */ public function includeInvoices(Client $client) { $transformer = new InvoiceTransformer($this->account, $this->serializer, $client); + return $this->includeCollection($client->invoices, $transformer, ENTITY_INVOICE); } /** * @param Client $client + * * @return \League\Fractal\Resource\Collection */ public function includeCredits(Client $client) { $transformer = new CreditTransformer($this->account, $this->serializer); + return $this->includeCollection($client->credits, $transformer, ENTITY_CREDIT); } /** * @param Client $client + * * @return \League\Fractal\Resource\Collection */ public function includeExpenses(Client $client) { $transformer = new ExpenseTransformer($this->account, $this->serializer); + return $this->includeCollection($client->expenses, $transformer, ENTITY_EXPENSE); } - /** * @param Client $client + * * @return array */ public function transform(Client $client) @@ -125,4 +133,4 @@ class ClientTransformer extends EntityTransformer 'custom_value2' => $client->custom_value2, ]); } -} \ No newline at end of file +} diff --git a/app/Ninja/Transformers/ContactTransformer.php b/app/Ninja/Transformers/ContactTransformer.php index 279658979ef3..4fd72ffde690 100644 --- a/app/Ninja/Transformers/ContactTransformer.php +++ b/app/Ninja/Transformers/ContactTransformer.php @@ -1,14 +1,17 @@ - $credit->private_notes, ]); } -} \ No newline at end of file +} diff --git a/app/Ninja/Transformers/DocumentTransformer.php b/app/Ninja/Transformers/DocumentTransformer.php index 2a9ac2abbc30..99ee24a6d1f2 100644 --- a/app/Ninja/Transformers/DocumentTransformer.php +++ b/app/Ninja/Transformers/DocumentTransformer.php @@ -1,4 +1,6 @@ -getDefaults($document), [ 'id' => (int) $document->public_id, 'name' => $document->name, - 'type' => $document->type, + 'type' => $document->type, 'invoice_id' => isset($document->invoice->public_id) ? (int) $document->invoice->public_id : null, 'expense_id' => isset($document->expense->public_id) ? (int) $document->expense->public_id : null, 'updated_at' => $this->getTimestamp($document->updated_at), diff --git a/app/Ninja/Transformers/EntityTransformer.php b/app/Ninja/Transformers/EntityTransformer.php index e40225af275e..4be378e72fc2 100644 --- a/app/Ninja/Transformers/EntityTransformer.php +++ b/app/Ninja/Transformers/EntityTransformer.php @@ -1,7 +1,9 @@ -getDefaults($expenseCategory), [ diff --git a/app/Ninja/Transformers/ExpenseTransformer.php b/app/Ninja/Transformers/ExpenseTransformer.php index 953eac338aee..0937f25f45f6 100644 --- a/app/Ninja/Transformers/ExpenseTransformer.php +++ b/app/Ninja/Transformers/ExpenseTransformer.php @@ -1,4 +1,6 @@ -account, $this->serializer); + return $this->includeCollection($invoice->invoice_items, $transformer, ENTITY_INVOICE_ITEM); } public function includeInvitations(Invoice $invoice) { $transformer = new InvitationTransformer($this->account, $this->serializer); + return $this->includeCollection($invoice->invitations, $transformer, ENTITY_INVITATION); } public function includePayments(Invoice $invoice) { $transformer = new PaymentTransformer($this->account, $this->serializer, $invoice); + return $this->includeCollection($invoice->payments, $transformer, ENTITY_PAYMENT); } public function includeClient(Invoice $invoice) { $transformer = new ClientTransformer($this->account, $this->serializer); + return $this->includeItem($invoice->client, $transformer, ENTITY_CLIENT); } public function includeExpenses(Invoice $invoice) { $transformer = new ExpenseTransformer($this->account, $this->serializer); + return $this->includeCollection($invoice->expenses, $transformer, ENTITY_EXPENSE); } public function includeDocuments(Invoice $invoice) { $transformer = new DocumentTransformer($this->account, $this->serializer); + return $this->includeCollection($invoice->documents, $transformer, ENTITY_DOCUMENT); } - public function transform(Invoice $invoice) { return array_merge($this->getDefaults($invoice), [ @@ -85,7 +90,7 @@ class InvoiceTransformer extends EntityTransformer 'updated_at' => $this->getTimestamp($invoice->updated_at), 'archived_at' => $this->getTimestamp($invoice->deleted_at), 'invoice_number' => $invoice->invoice_number, - 'discount' => (double) $invoice->discount, + 'discount' => (float) $invoice->discount, 'po_number' => $invoice->po_number, 'invoice_date' => $invoice->invoice_date, 'due_date' => $invoice->due_date, diff --git a/app/Ninja/Transformers/PaymentTransformer.php b/app/Ninja/Transformers/PaymentTransformer.php index ce8826a6c7ac..81e014de4b66 100644 --- a/app/Ninja/Transformers/PaymentTransformer.php +++ b/app/Ninja/Transformers/PaymentTransformer.php @@ -1,21 +1,22 @@ -account, $this->serializer); + return $this->includeItem($payment->invoice, $transformer, 'invoice'); } public function includeClient(Payment $payment) { $transformer = new ClientTransformer($this->account, $this->serializer); + return $this->includeItem($payment->client, $transformer, 'client'); } diff --git a/app/Ninja/Transformers/ProductTransformer.php b/app/Ninja/Transformers/ProductTransformer.php index 00a0a7c06281..fd7e47c039c5 100644 --- a/app/Ninja/Transformers/ProductTransformer.php +++ b/app/Ninja/Transformers/ProductTransformer.php @@ -1,24 +1,24 @@ -getDefaults($product), [ @@ -27,8 +27,8 @@ class ProductTransformer extends EntityTransformer 'notes' => $product->notes, 'cost' => $product->cost, 'qty' => $product->qty, - 'default_tax_rate_id' =>$product->default_tax_rate_id, - 'updated_at' =>$this->getTimestamp($product->updated_at), + 'default_tax_rate_id' => $product->default_tax_rate_id, + 'updated_at' => $this->getTimestamp($product->updated_at), 'archived_at' => $this->getTimestamp($product->deleted_at), ]); } diff --git a/app/Ninja/Transformers/ProjectTransformer.php b/app/Ninja/Transformers/ProjectTransformer.php index e17b3cafcd3f..ae2a1acb92f6 100644 --- a/app/Ninja/Transformers/ProjectTransformer.php +++ b/app/Ninja/Transformers/ProjectTransformer.php @@ -1,22 +1,22 @@ -getDefaults($project), [ diff --git a/app/Ninja/Transformers/TaskTransformer.php b/app/Ninja/Transformers/TaskTransformer.php index 24acd0d977e6..d7c695588e36 100644 --- a/app/Ninja/Transformers/TaskTransformer.php +++ b/app/Ninja/Transformers/TaskTransformer.php @@ -1,35 +1,35 @@ -client) { $transformer = new ClientTransformer($this->account, $this->serializer); + return $this->includeItem($task->client, $transformer, 'client'); } else { return null; diff --git a/app/Ninja/Transformers/TaxRateTransformer.php b/app/Ninja/Transformers/TaxRateTransformer.php index 07b8aa565ad0..8e3bf57e69c0 100644 --- a/app/Ninja/Transformers/TaxRateTransformer.php +++ b/app/Ninja/Transformers/TaxRateTransformer.php @@ -1,23 +1,23 @@ -getDefaults($taxRate), [ diff --git a/app/Ninja/Transformers/UserAccountTransformer.php b/app/Ninja/Transformers/UserAccountTransformer.php index 0009b250e4c2..57a8a9f65214 100644 --- a/app/Ninja/Transformers/UserAccountTransformer.php +++ b/app/Ninja/Transformers/UserAccountTransformer.php @@ -1,12 +1,14 @@ -account, $this->serializer); + return $this->includeItem($user, $transformer, 'user'); } diff --git a/app/Ninja/Transformers/UserTransformer.php b/app/Ninja/Transformers/UserTransformer.php index a22308f096da..af2de116f801 100644 --- a/app/Ninja/Transformers/UserTransformer.php +++ b/app/Ninja/Transformers/UserTransformer.php @@ -1,4 +1,6 @@ - (int) $user->getOriginal('permissions'), ]; } -} \ No newline at end of file +} diff --git a/app/Ninja/Transformers/VendorContactTransformer.php b/app/Ninja/Transformers/VendorContactTransformer.php index b06981475fb3..1374e1c0f48f 100644 --- a/app/Ninja/Transformers/VendorContactTransformer.php +++ b/app/Ninja/Transformers/VendorContactTransformer.php @@ -1,4 +1,6 @@ - $contact->phone, ]); } -} \ No newline at end of file +} diff --git a/app/Ninja/Transformers/VendorTransformer.php b/app/Ninja/Transformers/VendorTransformer.php index 81eb6f5d51be..ed44cd4c42cc 100644 --- a/app/Ninja/Transformers/VendorTransformer.php +++ b/app/Ninja/Transformers/VendorTransformer.php @@ -1,4 +1,6 @@ -account, $this->serializer); + return $this->includeCollection($vendor->vendor_contacts, $transformer, ENTITY_CONTACT); } public function includeInvoices(Vendor $vendor) { $transformer = new InvoiceTransformer($this->account, $this->serializer); + return $this->includeCollection($vendor->invoices, $transformer, ENTITY_INVOICE); } public function includeExpenses(Vendor $vendor) { $transformer = new ExpenseTransformer($this->account, $this->serializer); + return $this->includeCollection($vendor->expenses, $transformer, ENTITY_EXPENSE); } @@ -82,7 +85,7 @@ class VendorTransformer extends EntityTransformer 'is_deleted' => (bool) $vendor->is_deleted, 'vat_number' => $vendor->vat_number, 'id_number' => $vendor->id_number, - 'currency_id' => (int) $vendor->currency_id + 'currency_id' => (int) $vendor->currency_id, ]); } -} \ No newline at end of file +} diff --git a/app/Policies/AccountGatewayPolicy.php b/app/Policies/AccountGatewayPolicy.php index 0cfd2951367a..4a6388b22688 100644 --- a/app/Policies/AccountGatewayPolicy.php +++ b/app/Policies/AccountGatewayPolicy.php @@ -5,25 +5,29 @@ namespace App\Policies; use App\Models\User; /** - * Class AccountGatewayPolicy + * Class AccountGatewayPolicy. */ class AccountGatewayPolicy extends EntityPolicy { - /** * @param User $user * @param $item + * * @return bool */ - public static function edit(User $user, $item) { + public static function edit(User $user, $item) + { return $user->hasPermission('admin'); } /** - * @param User $user + * @param User $user + * @param mixed $item + * * @return bool */ - public static function create(User $user, $item) { + public static function create(User $user, $item) + { return $user->hasPermission('admin'); } } diff --git a/app/Policies/BankAccountPolicy.php b/app/Policies/BankAccountPolicy.php index 9c8e6794dc57..335c14e21d02 100644 --- a/app/Policies/BankAccountPolicy.php +++ b/app/Policies/BankAccountPolicy.php @@ -5,24 +5,29 @@ namespace App\Policies; use App\Models\User; /** - * Class BankAccountPolicy + * Class BankAccountPolicy. */ class BankAccountPolicy extends EntityPolicy { /** * @param User $user * @param $item + * * @return bool */ - public static function edit(User $user, $item) { + public static function edit(User $user, $item) + { return $user->hasPermission('admin'); } /** - * @param User $user + * @param User $user + * @param mixed $item + * * @return bool */ - public static function create(User $user, $item) { + public static function create(User $user, $item) + { return $user->hasPermission('admin'); } } diff --git a/app/Policies/ClientPolicy.php b/app/Policies/ClientPolicy.php index 4610c139fbfa..c33343a576fa 100644 --- a/app/Policies/ClientPolicy.php +++ b/app/Policies/ClientPolicy.php @@ -2,4 +2,6 @@ namespace App\Policies; -class ClientPolicy extends EntityPolicy {} \ No newline at end of file +class ClientPolicy extends EntityPolicy +{ +} diff --git a/app/Policies/CreditPolicy.php b/app/Policies/CreditPolicy.php index 539bc7e51889..6699810023f9 100644 --- a/app/Policies/CreditPolicy.php +++ b/app/Policies/CreditPolicy.php @@ -2,4 +2,6 @@ namespace App\Policies; -class CreditPolicy extends EntityPolicy {} \ No newline at end of file +class CreditPolicy extends EntityPolicy +{ +} diff --git a/app/Policies/DocumentPolicy.php b/app/Policies/DocumentPolicy.php index abb440800412..1a668c77b24d 100644 --- a/app/Policies/DocumentPolicy.php +++ b/app/Policies/DocumentPolicy.php @@ -5,22 +5,25 @@ namespace App\Policies; use App\Models\User; /** - * Class DocumentPolicy + * Class DocumentPolicy. */ class DocumentPolicy extends EntityPolicy { /** - * @param User $user + * @param User $user + * @param mixed $item + * * @return bool */ public static function create(User $user, $item) { - return !empty($user); + return ! empty($user); } /** - * @param User $user + * @param User $user * @param Document $document + * * @return bool */ public static function view(User $user, $document) @@ -32,6 +35,7 @@ class DocumentPolicy extends EntityPolicy if ($document->expense->invoice) { return $user->can('view', $document->expense->invoice); } + return $user->can('view', $document->expense); } if ($document->invoice) { diff --git a/app/Policies/EntityPolicy.php b/app/Policies/EntityPolicy.php index e2fa9af8e6de..19e2cf5ac97e 100644 --- a/app/Policies/EntityPolicy.php +++ b/app/Policies/EntityPolicy.php @@ -6,18 +6,21 @@ use App\Models\User; use Illuminate\Auth\Access\HandlesAuthorization; /** - * Class EntityPolicy + * Class EntityPolicy. */ class EntityPolicy { use HandlesAuthorization; /** - * @param User $user + * @param User $user + * @param mixed $item + * * @return bool */ - public static function create(User $user, $item) { - if ( ! static::checkModuleEnabled($user, $item)) { + public static function create(User $user, $item) + { + if (! static::checkModuleEnabled($user, $item)) { return false; } @@ -30,8 +33,9 @@ class EntityPolicy * * @return bool */ - public static function edit(User $user, $item) { - if ( ! static::checkModuleEnabled($user, $item)) { + public static function edit(User $user, $item) + { + if (! static::checkModuleEnabled($user, $item)) { return false; } @@ -44,8 +48,9 @@ class EntityPolicy * * @return bool */ - public static function view(User $user, $item) { - if ( ! static::checkModuleEnabled($user, $item)) { + public static function view(User $user, $item) + { + if (! static::checkModuleEnabled($user, $item)) { return false; } @@ -55,18 +60,22 @@ class EntityPolicy /** * @param User $user * @param $ownerUserId + * * @return bool */ - public static function viewByOwner(User $user, $ownerUserId) { + public static function viewByOwner(User $user, $ownerUserId) + { return $user->hasPermission('view_all') || $user->id == $ownerUserId; } /** * @param User $user * @param $ownerUserId + * * @return bool */ - public static function editByOwner(User $user, $ownerUserId) { + public static function editByOwner(User $user, $ownerUserId) + { return $user->hasPermission('edit_all') || $user->id == $ownerUserId; } diff --git a/app/Policies/ExpenseCategoryPolicy.php b/app/Policies/ExpenseCategoryPolicy.php index 2eeb3d7e968b..da7b9f09487f 100644 --- a/app/Policies/ExpenseCategoryPolicy.php +++ b/app/Policies/ExpenseCategoryPolicy.php @@ -6,12 +6,14 @@ use App\Models\User; class ExpenseCategoryPolicy extends EntityPolicy { - /** - * @param User $user + * @param User $user + * @param mixed $item + * * @return bool */ - public static function create(User $user, $item) { + public static function create(User $user, $item) + { return $user->is_admin; } @@ -21,7 +23,8 @@ class ExpenseCategoryPolicy extends EntityPolicy * * @return bool */ - public static function edit(User $user, $item) { + public static function edit(User $user, $item) + { return $user->is_admin; } @@ -31,26 +34,30 @@ class ExpenseCategoryPolicy extends EntityPolicy * * @return bool */ - public static function view(User $user, $item) { + public static function view(User $user, $item) + { return true; } /** * @param User $user * @param $ownerUserId + * * @return bool */ - public static function viewByOwner(User$user, $ownerUserId) { + public static function viewByOwner(User $user, $ownerUserId) + { return true; } /** * @param User $user * @param $ownerUserId + * * @return bool */ - public static function editByOwner(User $user, $ownerUserId) { + public static function editByOwner(User $user, $ownerUserId) + { return $user->is_admin; } - } diff --git a/app/Policies/ExpensePolicy.php b/app/Policies/ExpensePolicy.php index 92a22ac5807f..cbf9bf9b6011 100644 --- a/app/Policies/ExpensePolicy.php +++ b/app/Policies/ExpensePolicy.php @@ -7,15 +7,17 @@ use App\Models\User; class ExpensePolicy extends EntityPolicy { /** - * @param User $user + * @param User $user + * @param mixed $item + * * @return bool */ - public static function create(User $user, $item) { - if ( ! parent::create($user, $item)) { + public static function create(User $user, $item) + { + if (! parent::create($user, $item)) { return false; } return $user->hasFeature(FEATURE_EXPENSES); } - } diff --git a/app/Policies/GenericEntityPolicy.php b/app/Policies/GenericEntityPolicy.php index e2afc039e45c..24cfad36178d 100644 --- a/app/Policies/GenericEntityPolicy.php +++ b/app/Policies/GenericEntityPolicy.php @@ -2,14 +2,13 @@ namespace App\Policies; - -use Utils; use App\Models\User; -use Illuminate\Support\Str; use Illuminate\Auth\Access\HandlesAuthorization; +use Illuminate\Support\Str; +use Utils; /** - * Class GenericEntityPolicy + * Class GenericEntityPolicy. */ class GenericEntityPolicy { @@ -19,9 +18,11 @@ class GenericEntityPolicy * @param User $user * @param $entityType * @param $ownerUserId + * * @return bool|mixed */ - public static function editByOwner(User $user, $entityType, $ownerUserId) { + public static function editByOwner(User $user, $entityType, $ownerUserId) + { $className = static::className($entityType); if (method_exists($className, 'editByOwner')) { return call_user_func([$className, 'editByOwner'], $user, $ownerUserId); @@ -34,9 +35,12 @@ class GenericEntityPolicy * @param User $user * @param $entityTypee * @param $ownerUserId + * @param mixed $entityType + * * @return bool|mixed */ - public static function viewByOwner(User $user, $entityType, $ownerUserId) { + public static function viewByOwner(User $user, $entityType, $ownerUserId) + { $className = static::className($entityType); if (method_exists($className, 'viewByOwner')) { return call_user_func([$className, 'viewByOwner'], $user, $ownerUserId); @@ -48,9 +52,11 @@ class GenericEntityPolicy /** * @param User $user * @param $entityType + * * @return bool|mixed */ - public static function create(User $user, $entityType) { + public static function create(User $user, $entityType) + { $className = static::className($entityType); if (method_exists($className, 'create')) { return call_user_func([$className, 'create'], $user, $entityType); @@ -62,9 +68,11 @@ class GenericEntityPolicy /** * @param User $user * @param $entityType + * * @return bool|mixed */ - public static function view(User $user, $entityType) { + public static function view(User $user, $entityType) + { $className = static::className($entityType); if (method_exists($className, 'view')) { return call_user_func([$className, 'view'], $user, $entityType); @@ -75,14 +83,14 @@ class GenericEntityPolicy private static function className($entityType) { - if ( ! Utils::isNinjaProd()) { + if (! Utils::isNinjaProd()) { if ($module = \Module::find($entityType)) { return "Modules\\{$module->getName()}\\Policies\\{$module->getName()}Policy"; } } $studly = Str::studly($entityType); + return "App\\Policies\\{$studly}Policy"; } - } diff --git a/app/Policies/InvoicePolicy.php b/app/Policies/InvoicePolicy.php index aa72b4c0533c..f06b147d083f 100644 --- a/app/Policies/InvoicePolicy.php +++ b/app/Policies/InvoicePolicy.php @@ -2,4 +2,6 @@ namespace App\Policies; -class InvoicePolicy extends EntityPolicy {} +class InvoicePolicy extends EntityPolicy +{ +} diff --git a/app/Policies/PaymentPolicy.php b/app/Policies/PaymentPolicy.php index e9c3fc582a3f..97763936b1b4 100644 --- a/app/Policies/PaymentPolicy.php +++ b/app/Policies/PaymentPolicy.php @@ -2,4 +2,6 @@ namespace App\Policies; -class PaymentPolicy extends EntityPolicy {} \ No newline at end of file +class PaymentPolicy extends EntityPolicy +{ +} diff --git a/app/Policies/PaymentTermPolicy.php b/app/Policies/PaymentTermPolicy.php index e1ee2e494bdd..b1b9c12a44e3 100644 --- a/app/Policies/PaymentTermPolicy.php +++ b/app/Policies/PaymentTermPolicy.php @@ -5,25 +5,29 @@ namespace App\Policies; use App\Models\User; /** - * Class PaymentTermPolicy + * Class PaymentTermPolicy. */ class PaymentTermPolicy extends EntityPolicy { - /** * @param User $user * @param $item + * * @return mixed */ - public static function edit(User $user, $item) { + public static function edit(User $user, $item) + { return $user->hasPermission('admin'); } /** - * @param User $user + * @param User $user + * @param mixed $item + * * @return bool */ - public static function create(User $user, $item) { + public static function create(User $user, $item) + { return $user->hasPermission('admin'); } } diff --git a/app/Policies/ProductPolicy.php b/app/Policies/ProductPolicy.php index 23ce11fc7570..6c40ebc7e15e 100644 --- a/app/Policies/ProductPolicy.php +++ b/app/Policies/ProductPolicy.php @@ -2,12 +2,9 @@ namespace App\Policies; -use App\Models\User; - /** - * Class ProductPolicy + * Class ProductPolicy. */ class ProductPolicy extends EntityPolicy { - } diff --git a/app/Policies/ProjectPolicy.php b/app/Policies/ProjectPolicy.php index a88d3a37902a..9f8ddd666d36 100644 --- a/app/Policies/ProjectPolicy.php +++ b/app/Policies/ProjectPolicy.php @@ -2,9 +2,6 @@ namespace App\Policies; -use App\Models\User; - class ProjectPolicy extends EntityPolicy { - } diff --git a/app/Policies/QuotePolicy.php b/app/Policies/QuotePolicy.php index 6d1920d16c95..55b39ddd46bd 100644 --- a/app/Policies/QuotePolicy.php +++ b/app/Policies/QuotePolicy.php @@ -7,15 +7,17 @@ use App\Models\User; class QuotePolicy extends EntityPolicy { /** - * @param User $user + * @param User $user + * @param mixed $item + * * @return bool */ - public static function create(User $user, $item) { - if ( ! parent::create($user, $item)) { + public static function create(User $user, $item) + { + if (! parent::create($user, $item)) { return false; } return $user->hasFeature(FEATURE_QUOTES); } - } diff --git a/app/Policies/RecurringInvoicePolicy.php b/app/Policies/RecurringInvoicePolicy.php index 85e7037f886f..20113fb0a669 100644 --- a/app/Policies/RecurringInvoicePolicy.php +++ b/app/Policies/RecurringInvoicePolicy.php @@ -2,4 +2,6 @@ namespace App\Policies; -class RecurringInvoicePolicy extends EntityPolicy {} +class RecurringInvoicePolicy extends EntityPolicy +{ +} diff --git a/app/Policies/TaskPolicy.php b/app/Policies/TaskPolicy.php index aa0a2ef76239..a5d635090250 100644 --- a/app/Policies/TaskPolicy.php +++ b/app/Policies/TaskPolicy.php @@ -7,15 +7,17 @@ use App\Models\User; class TaskPolicy extends EntityPolicy { /** - * @param User $user + * @param User $user + * @param mixed $item + * * @return bool */ - public static function create(User $user, $item) { - if ( ! parent::create($user, $item)) { + public static function create(User $user, $item) + { + if (! parent::create($user, $item)) { return false; } return $user->hasFeature(FEATURE_TASKS); } - } diff --git a/app/Policies/TaxRatePolicy.php b/app/Policies/TaxRatePolicy.php index 5f70694890fa..0cfb4596346c 100644 --- a/app/Policies/TaxRatePolicy.php +++ b/app/Policies/TaxRatePolicy.php @@ -9,17 +9,22 @@ class TaxRatePolicy extends EntityPolicy /** * @param User $user * @param $item + * * @return bool */ - public static function edit(User $user, $item) { + public static function edit(User $user, $item) + { return $user->hasPermission('admin'); } /** - * @param User $user + * @param User $user + * @param mixed $item + * * @return bool */ - public static function create(User $user, $item) { + public static function create(User $user, $item) + { return $user->hasPermission('admin'); } } diff --git a/app/Policies/TokenPolicy.php b/app/Policies/TokenPolicy.php index 419a288262cb..c620e5889cf8 100644 --- a/app/Policies/TokenPolicy.php +++ b/app/Policies/TokenPolicy.php @@ -4,12 +4,15 @@ namespace App\Policies; use App\Models\User; -class TokenPolicy extends EntityPolicy { - public static function edit(User $user, $item) { +class TokenPolicy extends EntityPolicy +{ + public static function edit(User $user, $item) + { return $user->hasPermission('admin'); } - public static function create(User $user, $item) { + public static function create(User $user, $item) + { return $user->hasPermission('admin'); } } diff --git a/app/Policies/VendorPolicy.php b/app/Policies/VendorPolicy.php index f806ae826048..0e679b3de355 100644 --- a/app/Policies/VendorPolicy.php +++ b/app/Policies/VendorPolicy.php @@ -7,15 +7,17 @@ use App\Models\User; class VendorPolicy extends EntityPolicy { /** - * @param User $user + * @param User $user + * @param mixed $item + * * @return bool */ - public static function create(User $user, $item) { - if ( ! parent::create($user, $item)) { + public static function create(User $user, $item) + { + if (! parent::create($user, $item)) { return false; } return $user->hasFeature(FEATURE_EXPENSES); } - } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 1a0a7751d62c..5f1d5dad7a81 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -1,66 +1,66 @@ -'.$title.''; }); - Form::macro('tab_link', function($url, $text, $active = false) { + Form::macro('tab_link', function ($url, $text, $active = false) { $class = $active ? ' class="active"' : ''; + return '