diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 468c791745a8..5bf89ecafa62 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -12,7 +12,7 @@ jobs:
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
- php-version: 7.4
+ php-version: 8.1
extensions: mysql, mysqlnd, sqlite3, bcmath, gd, curl, zip, openssl, mbstring, xml
- name: Checkout code
@@ -50,7 +50,7 @@ jobs:
cd ..
rm -rf ui
php artisan ninja:react
-
+
- name: Prepare JS/CSS assets
run: |
npm i
diff --git a/.gitignore b/.gitignore
index 807279c6ceeb..460032ba1b89 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,6 +3,7 @@
/public/storage
/public/react
/storage/*.key
+/storage/debugbar
/vendor
/.idea
/.vscode
diff --git a/VERSION.txt b/VERSION.txt
index 35986ea71677..32b0e1eace3c 100644
--- a/VERSION.txt
+++ b/VERSION.txt
@@ -1 +1 @@
-5.4.12
\ No newline at end of file
+5.5.8
\ No newline at end of file
diff --git a/app/Console/Commands/BackupUpdate.php b/app/Console/Commands/BackupUpdate.php
index 33f8b3d6abe8..fcd1e6fa04d5 100644
--- a/app/Console/Commands/BackupUpdate.php
+++ b/app/Console/Commands/BackupUpdate.php
@@ -66,39 +66,25 @@ class BackupUpdate extends Command
$this->handleOnDb();
}
- MultiDB::setDB($current_db);
-
+ MultiDB::setDB($current_db);
}
-
-
}
private function handleOnDb()
{
set_time_limit(0);
-
- Backup::whereHas('activity')->whereRaw('html_backup IS NOT NULL')->cursor()->each( function ($backup) {
-
- if(strlen($backup->html_backup) > 1 && $backup->activity->invoice->exists()){
-
- $client = $backup->activity->invoice->client;
- $backup->storeRemotely($backup->html_backup, $client);
-
- }else if(strlen($backup->html_backup) > 1 && $backup->activity->quote->exists()){
-
- $client = $backup->activity->quote->client;
- $backup->storeRemotely($backup->html_backup, $client);
-
- }else if(strlen($backup->html_backup) > 1 && $backup->activity->credit->exists()){
-
- $client = $backup->activity->credit->client;
- $backup->storeRemotely($backup->html_backup, $client);
-
- }
-
-
+ Backup::whereHas('activity')->whereRaw('html_backup IS NOT NULL')->cursor()->each(function ($backup) {
+ if (strlen($backup->html_backup) > 1 && $backup->activity->invoice->exists()) {
+ $client = $backup->activity->invoice->client;
+ $backup->storeRemotely($backup->html_backup, $client);
+ } elseif (strlen($backup->html_backup) > 1 && $backup->activity->quote->exists()) {
+ $client = $backup->activity->quote->client;
+ $backup->storeRemotely($backup->html_backup, $client);
+ } elseif (strlen($backup->html_backup) > 1 && $backup->activity->credit->exists()) {
+ $client = $backup->activity->credit->client;
+ $backup->storeRemotely($backup->html_backup, $client);
+ }
});
-
}
}
diff --git a/app/Console/Commands/CheckData.php b/app/Console/Commands/CheckData.php
index 848e347a4359..80ff44a1329f 100644
--- a/app/Console/Commands/CheckData.php
+++ b/app/Console/Commands/CheckData.php
@@ -12,6 +12,7 @@
namespace App\Console\Commands;
use App;
+use App\DataMapper\ClientSettings;
use App\Factory\ClientContactFactory;
use App\Factory\VendorContactFactory;
use App\Models\Account;
@@ -126,7 +127,7 @@ class CheckData extends Command
$errorEmail = config('ninja.error_email');
- if ($errorEmail) {
+ if (strlen($errorEmail) > 1) {
Mail::raw($this->log, function ($message) use ($errorEmail, $database) {
$message->to($errorEmail)
->from(config('mail.from.address'), config('mail.from.name'))
@@ -893,6 +894,45 @@ class CheckData extends Command
});
}
+
+ public function checkClientSettings()
+ {
+
+ if ($this->option('fix') == 'true') {
+
+ Client::query()->whereNull('settings->currency_id')->cursor()->each(function ($client){
+
+ if(is_array($client->settings) && count($client->settings) == 0)
+ {
+ $settings = ClientSettings::defaults();
+ $settings->currency_id = $client->company->settings->currency_id;
+ }
+ else {
+ $settings = $client->settings;
+ $settings->currency_id = $client->company->settings->currency_id;
+ }
+
+ $client->settings = $settings;
+ $client->save();
+
+ $this->logMessage("Fixing currency for # {$client->id}");
+
+ });
+
+
+ Client::query()->whereNull('country_id')->cursor()->each(function ($client){
+
+ $client->country_id = $client->company->settings->country_id;
+ $client->save();
+
+ $this->logMessage("Fixing country for # {$client->id}");
+
+ });
+
+ }
+
+ }
+
public function checkBalanceVsPaidStatus()
{
$this->wrong_paid_status = 0;
diff --git a/app/Console/Commands/CheckDb.php b/app/Console/Commands/CheckDb.php
index b626e193c646..5f8fd0a1a0f9 100644
--- a/app/Console/Commands/CheckDb.php
+++ b/app/Console/Commands/CheckDb.php
@@ -36,8 +36,8 @@ use App\Models\GroupSetting;
use App\Models\Invoice;
use App\Models\InvoiceInvitation;
use App\Models\Payment;
-use App\Models\PaymentHash;
use App\Models\Paymentable;
+use App\Models\PaymentHash;
use App\Models\Product;
use App\Models\Project;
use App\Models\Quote;
@@ -61,13 +61,11 @@ use Illuminate\Support\Str;
use Mail;
use Symfony\Component\Console\Input\InputOption;
-
/**
* Class CheckDb.
*/
class CheckDb extends Command
{
-
protected $signature = 'ninja:check-db';
protected $description = 'Check MultiDB';
@@ -118,33 +116,30 @@ class CheckDb extends Command
public function handle()
{
+ $this->LogMessage('Checking - V5_DB1');
- $this->LogMessage("Checking - V5_DB1");
-
- foreach($this->entities as $entity) {
-
+ foreach ($this->entities as $entity) {
$count_db_1 = $entity::on('db-ninja-01')->count();
$count_db_2 = $entity::on('db-ninja-02a')->count();
$diff = $count_db_1 - $count_db_2;
- if($diff != 0)
+ if ($diff != 0) {
$this->logMessage("{$entity} DB1: {$count_db_1} - DB2: {$count_db_2} - diff = {$diff}");
-
+ }
}
- $this->LogMessage("Checking - V5_DB2");
-
- foreach($this->entities as $entity) {
+ $this->LogMessage('Checking - V5_DB2');
+ foreach ($this->entities as $entity) {
$count_db_1 = $entity::on('db-ninja-02')->count();
$count_db_2 = $entity::on('db-ninja-01a')->count();
$diff = $count_db_1 - $count_db_2;
- if($diff != 0)
+ if ($diff != 0) {
$this->logMessage("{$entity} DB1: {$count_db_1} - DB2: {$count_db_2} - diff = {$diff}");
-
+ }
}
}
@@ -154,5 +149,4 @@ class CheckDb extends Command
$this->info($str);
$this->log .= $str."\n";
}
-
}
diff --git a/app/Console/Commands/CreateAccount.php b/app/Console/Commands/CreateAccount.php
index 0def06c5d5bd..c0eaed16bc59 100644
--- a/app/Console/Commands/CreateAccount.php
+++ b/app/Console/Commands/CreateAccount.php
@@ -51,10 +51,12 @@ use Illuminate\Support\Str;
class CreateAccount extends Command
{
use MakesHash, GeneratesCounter;
+
/**
* @var string
*/
protected $description = 'Create Single Account';
+
/**
* @var string
*/
@@ -82,12 +84,10 @@ class CreateAccount extends Command
$this->warmCache();
$this->createAccount();
-
}
private function createAccount()
{
-
$account = Account::factory()->create();
$company = Company::factory()->create([
'account_id' => $account->id,
@@ -131,10 +131,9 @@ class CreateAccount extends Command
'settings' => null,
]);
- CreateCompanyPaymentTerms::dispatchNow($company, $user);
- CreateCompanyTaskStatuses::dispatchNow($company, $user);
- VersionCheck::dispatchNow();
-
+ (new CreateCompanyPaymentTerms($company, $user))->handle();
+ (new CreateCompanyTaskStatuses($company, $user))->handle();
+ (new VersionCheck())->handle();
}
private function warmCache()
@@ -164,5 +163,4 @@ class CreateAccount extends Command
}
}
}
-
}
diff --git a/app/Console/Commands/CreateTestData.php b/app/Console/Commands/CreateTestData.php
index ecd6ab2018f3..866c3588ccfe 100644
--- a/app/Console/Commands/CreateTestData.php
+++ b/app/Console/Commands/CreateTestData.php
@@ -48,10 +48,12 @@ use Illuminate\Support\Str;
class CreateTestData extends Command
{
use MakesHash, GeneratesCounter;
+
/**
* @var string
*/
protected $description = 'Create Test Data';
+
/**
* @var string
*/
@@ -66,14 +68,16 @@ class CreateTestData extends Command
*/
public function handle()
{
- if(config('ninja.is_docker'))
+ if (config('ninja.is_docker')) {
return;
+ }
- if (!$this->confirm('Are you sure you want to inject dummy data?'))
- return;
+ if (! $this->confirm('Are you sure you want to inject dummy data?')) {
+ return;
+ }
$this->invoice_repo = new InvoiceRepository();
-
+
$this->info(date('r').' Running CreateTestData...');
$this->count = $this->argument('count');
@@ -125,14 +129,14 @@ class CreateTestData extends Command
'is_admin' => 1,
'is_locked' => 0,
'notifications' => CompanySettings::notificationDefaults(),
- // 'permissions' => '',
+ // 'permissions' => '',
'settings' => null,
]);
Product::factory()->count(50)->create([
- 'user_id' => $user->id,
- 'company_id' => $company->id,
- ]);
+ 'user_id' => $user->id,
+ 'company_id' => $company->id,
+ ]);
$this->info('Creating '.$this->count.' clients');
@@ -219,15 +223,14 @@ class CreateTestData extends Command
'is_admin' => 1,
'is_locked' => 0,
'notifications' => CompanySettings::notificationDefaults(),
- // 'permissions' => '',
+ // 'permissions' => '',
'settings' => null,
]);
Product::factory()->count(50)->create([
- 'user_id' => $user->id,
- 'company_id' => $company->id,
- ]);
-
+ 'user_id' => $user->id,
+ 'company_id' => $company->id,
+ ]);
$this->count = $this->count * 10;
@@ -317,14 +320,14 @@ class CreateTestData extends Command
'is_admin' => 1,
'is_locked' => 0,
'notifications' => CompanySettings::notificationDefaults(),
- // 'permissions' => '',
+ // 'permissions' => '',
'settings' => null,
]);
Product::factory()->count(15000)->create([
- 'user_id' => $user->id,
- 'company_id' => $company->id,
- ]);
+ 'user_id' => $user->id,
+ 'company_id' => $company->id,
+ ]);
$this->count = $this->count * 10;
@@ -382,30 +385,29 @@ class CreateTestData extends Command
// });
$client = Client::factory()->create([
- 'user_id' => $user->id,
- 'company_id' => $company->id,
- ]);
-
+ 'user_id' => $user->id,
+ 'company_id' => $company->id,
+ ]);
Document::factory()->count(50)->create([
- 'user_id' => $user->id,
- 'company_id' => $company->id,
- 'documentable_type' => Client::class,
- 'documentable_id' => $client->id
- ]);
+ 'user_id' => $user->id,
+ 'company_id' => $company->id,
+ 'documentable_type' => Client::class,
+ 'documentable_id' => $client->id,
+ ]);
ClientContact::factory()->create([
- 'user_id' => $user->id,
- 'client_id' => $client->id,
- 'company_id' => $company->id,
- 'is_primary' => 1,
- ]);
+ 'user_id' => $user->id,
+ 'client_id' => $client->id,
+ 'company_id' => $company->id,
+ 'is_primary' => 1,
+ ]);
ClientContact::factory()->count(rand(1, 5))->create([
- 'user_id' => $user->id,
- 'client_id' => $client->id,
- 'company_id' => $company->id,
- ]);
+ 'user_id' => $user->id,
+ 'client_id' => $client->id,
+ 'company_id' => $company->id,
+ ]);
$client->number = $this->getNextClientNumber($client);
@@ -422,70 +424,69 @@ class CreateTestData extends Command
private function createExpense($client)
{
Expense::factory()->count(rand(1, 5))->create([
- 'user_id' => $client->user->id,
- 'client_id' => $client->id,
- 'company_id' => $client->company->id,
- ]);
+ 'user_id' => $client->user->id,
+ 'client_id' => $client->id,
+ 'company_id' => $client->company->id,
+ ]);
}
private function createVendor($client)
{
$vendor = Vendor::factory()->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company->id,
- ]);
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company->id,
+ ]);
Document::factory()->count(50)->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company_id,
- 'documentable_type' => Vendor::class,
- 'documentable_id' => $vendor->id
- ]);
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company_id,
+ 'documentable_type' => Vendor::class,
+ 'documentable_id' => $vendor->id,
+ ]);
VendorContact::factory()->create([
- 'user_id' => $client->user->id,
- 'vendor_id' => $vendor->id,
- 'company_id' => $client->company->id,
- 'is_primary' => 1,
- ]);
+ 'user_id' => $client->user->id,
+ 'vendor_id' => $vendor->id,
+ 'company_id' => $client->company->id,
+ 'is_primary' => 1,
+ ]);
VendorContact::factory()->count(rand(1, 5))->create([
- 'user_id' => $client->user->id,
- 'vendor_id' => $vendor->id,
- 'company_id' => $client->company->id,
- 'is_primary' => 0,
- ]);
+ 'user_id' => $client->user->id,
+ 'vendor_id' => $vendor->id,
+ 'company_id' => $client->company->id,
+ 'is_primary' => 0,
+ ]);
}
private function createTask($client)
{
$vendor = Task::factory()->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company->id,
- ]);
-
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company->id,
+ ]);
Document::factory()->count(5)->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company_id,
- 'documentable_type' => Task::class,
- 'documentable_id' => $vendor->id
- ]);
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company_id,
+ 'documentable_type' => Task::class,
+ 'documentable_id' => $vendor->id,
+ ]);
}
private function createProject($client)
{
$vendor = Project::factory()->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company->id,
- ]);
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company->id,
+ ]);
- Document::factory()->count(5)->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company_id,
- 'documentable_type' => Project::class,
- 'documentable_id' => $vendor->id
- ]);
+ Document::factory()->count(5)->create([
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company_id,
+ 'documentable_type' => Project::class,
+ 'documentable_id' => $vendor->id,
+ ]);
}
private function createInvoice($client)
@@ -516,7 +517,7 @@ class CreateTestData extends Command
$invoice->tax_rate3 = 5;
}
- $invoice->custom_value1 = $faker->date;
+ $invoice->custom_value1 = $faker->date();
$invoice->custom_value2 = rand(0, 1) ? 'yes' : 'no';
$invoice->save();
@@ -537,16 +538,15 @@ class CreateTestData extends Command
$invoice = $invoice->service()->markPaid()->save();
}
- Document::factory()->count(5)->create([
- 'user_id' => $invoice->user->id,
- 'company_id' => $invoice->company_id,
- 'documentable_type' => Invoice::class,
- 'documentable_id' => $invoice->id
- ]);
+ Document::factory()->count(5)->create([
+ 'user_id' => $invoice->user->id,
+ 'company_id' => $invoice->company_id,
+ 'documentable_type' => Invoice::class,
+ 'documentable_id' => $invoice->id,
+ ]);
RecurringInvoice::factory()->create(['user_id' => $invoice->user->id, 'company_id' => $invoice->company->id, 'client_id' => $invoice->client_id]);
-
event(new InvoiceWasCreated($invoice, $invoice->company, Ninja::eventVars()));
}
diff --git a/app/Console/Commands/DemoMode.php b/app/Console/Commands/DemoMode.php
index bbb24e2a89db..8a5864a6440a 100644
--- a/app/Console/Commands/DemoMode.php
+++ b/app/Console/Commands/DemoMode.php
@@ -73,8 +73,9 @@ class DemoMode extends Command
{
set_time_limit(0);
- if(config('ninja.is_docker'))
+ if (config('ninja.is_docker')) {
return;
+ }
$this->invoice_repo = new InvoiceRepository();
@@ -111,9 +112,9 @@ class DemoMode extends Command
$this->info('Seeding Random Data');
$this->createSmallAccount();
- VersionCheck::dispatchNow();
+ (new VersionCheck())->handle();
- CompanySizeCheck::dispatchNow();
+ (new CompanySizeCheck())->handle();
}
private function createSmallAccount()
@@ -136,15 +137,15 @@ class DemoMode extends Command
$settings = $company->settings;
- $settings->name = $faker->company;
- $settings->address1 = $faker->buildingNumber;
- $settings->address2 = $faker->streetAddress;
- $settings->city = $faker->city;
- $settings->state = $faker->state;
- $settings->postal_code = $faker->postcode;
- $settings->website = $faker->url;
+ $settings->name = $faker->company();
+ $settings->address1 = $faker->buildingNumber();
+ $settings->address2 = $faker->streetAddress();
+ $settings->city = $faker->city();
+ $settings->state = $faker->state();
+ $settings->postal_code = $faker->postcode();
+ $settings->website = $faker->url();
$settings->vat_number = (string) $faker->numberBetween(123456789, 987654321);
- $settings->phone = (string) $faker->phoneNumber;
+ $settings->phone = (string) $faker->phoneNumber();
$company->settings = $settings;
$company->save();
@@ -163,8 +164,8 @@ class DemoMode extends Command
]);
}
- CreateCompanyPaymentTerms::dispatchNow($company, $user);
- CreateCompanyTaskStatuses::dispatchNow($company, $user);
+ (new CreateCompanyPaymentTerms($company, $user))->handle();
+ (new CreateCompanyTaskStatuses($company, $user))->handle();
$company_token = new CompanyToken;
$company_token->user_id = $user->id;
@@ -182,7 +183,7 @@ class DemoMode extends Command
'is_admin' => 1,
'is_locked' => 0,
'notifications' => CompanySettings::notificationDefaults(),
- // 'permissions' => '',
+ // 'permissions' => '',
'settings' => null,
]);
@@ -217,9 +218,9 @@ class DemoMode extends Command
}
Product::factory()->count(50)->create([
- 'user_id' => $user->id,
- 'company_id' => $company->id,
- ]);
+ 'user_id' => $user->id,
+ 'company_id' => $company->id,
+ ]);
$this->info('Creating '.$this->count.' clients');
@@ -265,22 +266,22 @@ class DemoMode extends Command
// });
$client = Client::factory()->create([
- 'user_id' => $user->id,
- 'company_id' => $company->id,
- ]);
+ 'user_id' => $user->id,
+ 'company_id' => $company->id,
+ ]);
ClientContact::factory()->create([
- 'user_id' => $user->id,
- 'client_id' => $client->id,
- 'company_id' => $company->id,
- 'is_primary' => 1,
- ]);
+ 'user_id' => $user->id,
+ 'client_id' => $client->id,
+ 'company_id' => $company->id,
+ 'is_primary' => 1,
+ ]);
ClientContact::factory()->count(rand(1, 5))->create([
- 'user_id' => $user->id,
- 'client_id' => $client->id,
- 'company_id' => $company->id,
- ]);
+ 'user_id' => $user->id,
+ 'client_id' => $client->id,
+ 'company_id' => $company->id,
+ ]);
$client->number = $this->getNextClientNumber($client);
@@ -299,41 +300,37 @@ class DemoMode extends Command
private function createExpense($client)
{
Expense::factory()->count(rand(1, 5))->create([
- 'user_id' => $client->user_id,
- 'client_id' => $client->id,
- 'company_id' => $client->company_id,
- ]);
-
- Expense::all()->each(function ($expense){
+ 'user_id' => $client->user_id,
+ 'client_id' => $client->id,
+ 'company_id' => $client->company_id,
+ ]);
+ Expense::all()->each(function ($expense) {
$expense->number = $this->getNextExpenseNumber($expense);
$expense->save();
-
});
-
}
private function createVendor($client, $assigned_user_id = null)
{
$vendor = Vendor::factory()->create([
- 'user_id' => $client->user_id,
- 'company_id' => $client->company_id,
- ]);
+ 'user_id' => $client->user_id,
+ 'company_id' => $client->company_id,
+ ]);
VendorContact::factory()->create([
- 'user_id' => $client->user->id,
- 'vendor_id' => $vendor->id,
- 'company_id' => $client->company_id,
- 'is_primary' => 1,
- ]);
+ 'user_id' => $client->user->id,
+ 'vendor_id' => $vendor->id,
+ 'company_id' => $client->company_id,
+ 'is_primary' => 1,
+ ]);
VendorContact::factory()->count(rand(1, 5))->create([
- 'user_id' => $client->user->id,
- 'vendor_id' => $vendor->id,
- 'company_id' => $client->company_id,
- 'is_primary' => 0,
- ]);
-
+ 'user_id' => $client->user->id,
+ 'vendor_id' => $vendor->id,
+ 'company_id' => $client->company_id,
+ 'is_primary' => 0,
+ ]);
$vendor->number = $this->getNextVendorNumber($vendor);
$vendor->save();
@@ -342,25 +339,24 @@ class DemoMode extends Command
private function createTask($client, $assigned_user_id = null)
{
$task = Task::factory()->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company_id,
- 'client_id' => $client->id
- ]);
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company_id,
+ 'client_id' => $client->id,
+ ]);
$task->status_id = TaskStatus::all()->random()->id;
$task->number = $this->getNextTaskNumber($task);
$task->save();
-
}
private function createProject($client, $assigned_user_id = null)
{
$project = Project::factory()->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company_id,
- 'client_id' => $client->id,
- ]);
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company_id,
+ 'client_id' => $client->id,
+ ]);
$project->number = $this->getNextProjectNumber($project);
$project->save();
@@ -399,7 +395,7 @@ class DemoMode extends Command
// $invoice->tax_rate3 = 5;
// }
- // $invoice->custom_value1 = $faker->date;
+ // $invoice->custom_value1 = $faker->date();
// $invoice->custom_value2 = rand(0, 1) ? 'yes' : 'no';
$invoice->save();
@@ -466,7 +462,7 @@ class DemoMode extends Command
// $invoice->tax_rate3 = 5;
// }
- // $invoice->custom_value1 = $faker->date;
+ // $invoice->custom_value1 = $faker->date();
// $invoice->custom_value2 = rand(0, 1) ? 'yes' : 'no';
$invoice->save();
diff --git a/app/Console/Commands/DesignUpdate.php b/app/Console/Commands/DesignUpdate.php
index cada484be4bb..caccb3bd7c42 100644
--- a/app/Console/Commands/DesignUpdate.php
+++ b/app/Console/Commands/DesignUpdate.php
@@ -64,11 +64,8 @@ class DesignUpdate extends Command
$this->handleOnDb($db);
}
- MultiDB::setDB($current_db);
-
+ MultiDB::setDB($current_db);
}
-
-
}
private function handleOnDb()
diff --git a/app/Console/Commands/HostedMigrations.php b/app/Console/Commands/HostedMigrations.php
index e8540a9c4431..0e303129a7ec 100644
--- a/app/Console/Commands/HostedMigrations.php
+++ b/app/Console/Commands/HostedMigrations.php
@@ -71,26 +71,27 @@ class HostedMigrations extends Command
public function handle()
{
$this->buildCache();
-
- if(!MultiDB::userFindAndSetDb($this->option('email'))){
- $this->info("Could not find a user with that email address");
+
+ if (! MultiDB::userFindAndSetDb($this->option('email'))) {
+ $this->info('Could not find a user with that email address');
+
return;
}
$user = User::where('email', $this->option('email'))->first();
- if(!$user){
- $this->info("There was a problem getting the user, did you set the right DB?");
+ if (! $user) {
+ $this->info('There was a problem getting the user, did you set the right DB?');
+
return;
}
$path = public_path('storage/migrations/import');
-
+
$directory = new DirectoryIterator($path);
foreach ($directory as $file) {
if ($file->getExtension() === 'zip') {
-
$company = $user->companies()->first();
$this->info('Started processing: '.$file->getBasename().' at '.now());
@@ -104,14 +105,13 @@ class HostedMigrations extends Command
}
$filename = pathinfo($file->getRealPath(), PATHINFO_FILENAME);
-
+
$zip->extractTo(public_path("storage/migrations/{$filename}"));
$zip->close();
$import_file = public_path("storage/migrations/$filename/migration.json");
Import::dispatch($import_file, $user->companies()->first(), $user);
-
} catch (NonExistingMigrationFile | ProcessingMigrationArchiveFailed | ResourceNotAvailableForMigration | MigrationValidatorFailed | ResourceDependencyMissing $e) {
\Mail::to($this->user)->send(new MigrationFailed($e, $e->getMessage()));
@@ -122,5 +122,4 @@ class HostedMigrations extends Command
}
}
}
-
}
diff --git a/app/Console/Commands/HostedUsers.php b/app/Console/Commands/HostedUsers.php
index 621102382e2f..63a1b94e7e35 100644
--- a/app/Console/Commands/HostedUsers.php
+++ b/app/Console/Commands/HostedUsers.php
@@ -41,21 +41,16 @@ class HostedUsers extends Command
*/
public function handle()
{
-
- Company::on('db-ninja-01')->each(function ($company){
-
- if(Ninja::isHosted())
- \Modules\Admin\Jobs\Account\NinjaUser::dispatchNow([], $company);
-
+ Company::on('db-ninja-01')->each(function ($company) {
+ if (Ninja::isHosted()) {
+ (new \Modules\Admin\Jobs\Account\NinjaUser([], $company))->handle();
+ }
});
- Company::on('db-ninja-02')->each(function ($company){
-
- if(Ninja::isHosted())
- \Modules\Admin\Jobs\Account\NinjaUser::dispatchNow([], $company);
-
+ Company::on('db-ninja-02')->each(function ($company) {
+ if (Ninja::isHosted()) {
+ (new \Modules\Admin\Jobs\Account\NinjaUser([], $company))->handle();
+ }
});
-
}
-
}
diff --git a/app/Console/Commands/ImportMigrations.php b/app/Console/Commands/ImportMigrations.php
index dcd184a2f1a9..594d447469cf 100644
--- a/app/Console/Commands/ImportMigrations.php
+++ b/app/Console/Commands/ImportMigrations.php
@@ -77,9 +77,9 @@ class ImportMigrations extends Command
public function handle()
{
$this->buildCache();
-
+
$path = $this->option('path') ?? public_path('storage/migrations/import');
-
+
$directory = new DirectoryIterator($path);
foreach ($directory as $file) {
@@ -98,7 +98,7 @@ class ImportMigrations extends Command
}
$filename = pathinfo($file->getRealPath(), PATHINFO_FILENAME);
-
+
$zip->extractTo(public_path("storage/migrations/{$filename}"));
$zip->close();
@@ -124,7 +124,7 @@ class ImportMigrations extends Command
$user = User::factory()->create([
'account_id' => $account->id,
- 'email' => Str::random(10) . "@example.com",
+ 'email' => Str::random(10).'@example.com',
'confirmation_code' => $this->createDbHash($company->db),
]);
@@ -137,7 +137,7 @@ class ImportMigrations extends Command
'name' => 'First token',
'token' => Str::random(64),
]);
-
+
$user->companies()->attach($company->id, [
'account_id' => $account->id,
'is_owner' => 1,
diff --git a/app/Console/Commands/MobileLocalization.php b/app/Console/Commands/MobileLocalization.php
index 7ae72f6cd1bc..0277fb75adce 100644
--- a/app/Console/Commands/MobileLocalization.php
+++ b/app/Console/Commands/MobileLocalization.php
@@ -23,7 +23,6 @@ class MobileLocalization extends Command
*/
protected $description = 'Generate mobile localization resources';
-
/**
* Create a new command instance.
*
@@ -83,9 +82,9 @@ class MobileLocalization extends Command
$text = $resources->$key;
}
- $text = str_replace(array('', ''), '', $text);
- $text = str_replace(array('', ''), '', $text);
- $text = str_replace(array('', ''), '', $text);
+ $text = str_replace(['', ''], '', $text);
+ $text = str_replace(['', ''], '', $text);
+ $text = str_replace(['', ''], '', $text);
echo "'$key': '$text',\n";
}
@@ -103,11 +102,11 @@ class MobileLocalization extends Command
$end = strpos($data, '},', $start);
$data = substr($data, $start, $end - $start - 5);
- $data = str_replace("\n", "", $data);
- $data = str_replace("\"", "\'", $data);
- $data = str_replace("'", "\"", $data);
+ $data = str_replace("\n", '', $data);
+ $data = str_replace('"', "\'", $data);
+ $data = str_replace("'", '"', $data);
- return json_decode('{' . rtrim($data, ',') . '}');
+ return json_decode('{'.rtrim($data, ',').'}');
}
protected function getOptions()
@@ -116,5 +115,4 @@ class MobileLocalization extends Command
['type', null, InputOption::VALUE_OPTIONAL, 'Type', null],
];
}
-
}
diff --git a/app/Console/Commands/ParallelCheckData.php b/app/Console/Commands/ParallelCheckData.php
index 1879202cb432..c79161632835 100644
--- a/app/Console/Commands/ParallelCheckData.php
+++ b/app/Console/Commands/ParallelCheckData.php
@@ -52,15 +52,10 @@ class ParallelCheckData extends Command
public function handle()
{
-
- $hash = Str::random(32);
-
- Company::cursor()->each(function ($company) use ($hash){
-
- CheckCompanyData::dispatch($company, $hash)->onQueue('checkdata');
-
- });
+ $hash = Str::random(32);
+ Company::cursor()->each(function ($company) use ($hash) {
+ CheckCompanyData::dispatch($company, $hash)->onQueue('checkdata');
+ });
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Console/Commands/PostUpdate.php b/app/Console/Commands/PostUpdate.php
index 5eeadb84ac88..007a9bed6211 100644
--- a/app/Console/Commands/PostUpdate.php
+++ b/app/Console/Commands/PostUpdate.php
@@ -50,24 +50,22 @@ class PostUpdate extends Command
info("I wasn't able to migrate the data.");
}
- info("finished migrating");
+ info('finished migrating');
$output = [];
// exec('vendor/bin/composer install --no-dev -o', $output);
- info(print_r($output,1));
- info("finished running composer install ");
+ info(print_r($output, 1));
+ info('finished running composer install ');
try {
-
Artisan::call('optimize');
-
} catch (\Exception $e) {
info("I wasn't able to optimize.");
}
- info("optimized");
+ info('optimized');
try {
Artisan::call('view:clear');
@@ -75,7 +73,7 @@ class PostUpdate extends Command
info("I wasn't able to clear the views.");
}
- info("view cleared");
+ info('view cleared');
try {
Artisan::call('queue:restart');
@@ -83,11 +81,10 @@ class PostUpdate extends Command
info("I wasn't able to restart the queue.");
}
- info("queue restarted");
+ info('queue restarted');
VersionCheck::dispatch();
- info("Sent for version check");
-
+ info('Sent for version check');
}
}
diff --git a/app/Console/Commands/ReactBuilder.php b/app/Console/Commands/ReactBuilder.php
index 4081e76846e6..15a2f6520f46 100644
--- a/app/Console/Commands/ReactBuilder.php
+++ b/app/Console/Commands/ReactBuilder.php
@@ -56,33 +56,19 @@ class ReactBuilder extends Command
$directoryIterator = new \RecursiveDirectoryIterator(public_path('react'), \RecursiveDirectoryIterator::SKIP_DOTS);
foreach (new \RecursiveIteratorIterator($directoryIterator) as $file) {
-
- if(str_contains($file->getFileName(), '.js')) {
-
- if(str_contains($file->getFileName(), 'index.')){
-
- $includes .= ''."\n";
-
- }
- else{
-
- $includes .= ''."\n";
+ if (str_contains($file->getFileName(), '.js')) {
+ if (str_contains($file->getFileName(), 'index.')) {
+ $includes .= ''."\n";
+ } else {
+ $includes .= ''."\n";
+ }
}
- }
-
-
- if(str_contains($file->getFileName(), '.css')) {
-
- $includes .= ''."\n";
-
- }
-
+ if (str_contains($file->getFileName(), '.css')) {
+ $includes .= ''."\n";
+ }
}
file_put_contents(resource_path('views/react/head.blade.php'), $includes);
-
}
-
-
}
diff --git a/app/Console/Commands/RecurringCommand.php b/app/Console/Commands/RecurringCommand.php
index 325100d82a08..2bc62d79dee5 100644
--- a/app/Console/Commands/RecurringCommand.php
+++ b/app/Console/Commands/RecurringCommand.php
@@ -47,6 +47,6 @@ class RecurringCommand extends Command
*/
public function handle()
{
- RecurringInvoicesCron::dispatchNow();
+ (new RecurringInvoicesCron())->handle();
}
}
diff --git a/app/Console/Commands/S3Cleanup.php b/app/Console/Commands/S3Cleanup.php
index 9b29ee692a63..12b998dd5697 100644
--- a/app/Console/Commands/S3Cleanup.php
+++ b/app/Console/Commands/S3Cleanup.php
@@ -42,10 +42,10 @@ class S3Cleanup extends Command
*/
public function handle()
{
-
- if(!Ninja::isHosted())
+ if (! Ninja::isHosted()) {
return;
-
+ }
+
$c1 = Company::on('db-ninja-01')->pluck('company_key');
$c2 = Company::on('db-ninja-02')->pluck('company_key');
@@ -53,23 +53,20 @@ class S3Cleanup extends Command
$directories = Storage::disk(config('filesystems.default'))->directories();
- $this->LogMessage("Disk Cleanup");
+ $this->LogMessage('Disk Cleanup');
- foreach($directories as $dir)
- {
- if(!in_array($dir, $merged))
- {
- $this->logMessage("Deleting $dir");
+ foreach ($directories as $dir) {
+ if (! in_array($dir, $merged)) {
+ $this->logMessage("Deleting $dir");
- /* Ensure we are not deleting the root folder */
- if(strlen($dir) > 1)
- Storage::disk(config('filesystems.default'))->deleteDirectory($dir);
-
+ /* Ensure we are not deleting the root folder */
+ if (strlen($dir) > 1) {
+ Storage::disk(config('filesystems.default'))->deleteDirectory($dir);
}
- }
-
- $this->logMessage("exiting");
+ }
+ }
+ $this->logMessage('exiting');
}
private function logMessage($str)
diff --git a/app/Console/Commands/SendRemindersCron.php b/app/Console/Commands/SendRemindersCron.php
index cd16da8ecae2..cdbdad6b37ab 100644
--- a/app/Console/Commands/SendRemindersCron.php
+++ b/app/Console/Commands/SendRemindersCron.php
@@ -29,6 +29,7 @@ use Illuminate\Support\Facades\App;
class SendRemindersCron extends Command
{
use MakesReminders, MakesDates;
+
/**
* The name and signature of the console command.
*
@@ -60,56 +61,49 @@ class SendRemindersCron extends Command
*/
public function handle()
{
-
Invoice::where('next_send_date', '<=', now()->toDateTimeString())
->whereNull('deleted_at')
->where('is_deleted', 0)
->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL])
->where('balance', '>', 0)
->whereHas('client', function ($query) {
- $query->where('is_deleted',0)
- ->where('deleted_at', NULL);
+ $query->where('is_deleted', 0)
+ ->where('deleted_at', null);
})
->whereHas('company', function ($query) {
- $query->where('is_disabled',0);
+ $query->where('is_disabled', 0);
})
->with('invitations')->cursor()->each(function ($invoice) {
+ if ($invoice->isPayable()) {
+ $reminder_template = $invoice->calculateTemplate('invoice');
+ $invoice->service()->touchReminder($reminder_template)->save();
+ $invoice = $this->calcLateFee($invoice, $reminder_template);
- if ($invoice->isPayable()) {
- $reminder_template = $invoice->calculateTemplate('invoice');
- $invoice->service()->touchReminder($reminder_template)->save();
- $invoice = $this->calcLateFee($invoice, $reminder_template);
+ //check if this reminder needs to be emailed
+ if (in_array($reminder_template, ['reminder1', 'reminder2', 'reminder3']) && $invoice->client->getSetting('enable_'.$reminder_template)) {
+ $invoice->invitations->each(function ($invitation) use ($invoice, $reminder_template) {
+ EmailEntity::dispatch($invitation, $invitation->company, $reminder_template);
+ nlog("Firing reminder email for invoice {$invoice->number}");
+ });
- //check if this reminder needs to be emailed
- if(in_array($reminder_template, ['reminder1','reminder2','reminder3']) && $invoice->client->getSetting("enable_".$reminder_template))
- {
- $invoice->invitations->each(function ($invitation) use ($invoice, $reminder_template) {
- EmailEntity::dispatch($invitation, $invitation->company, $reminder_template);
- nlog("Firing reminder email for invoice {$invoice->number}");
- });
+ if ($invoice->invitations->count() > 0) {
+ event(new InvoiceWasEmailed($invoice->invitations->first(), $invoice->company, Ninja::eventVars(), $reminder_template));
+ }
+ }
+ $invoice->service()->setReminder()->save();
+ } else {
+ $invoice->next_send_date = null;
+ $invoice->save();
+ }
+ });
- if ($invoice->invitations->count() > 0) {
- event(new InvoiceWasEmailed($invoice->invitations->first(), $invoice->company, Ninja::eventVars(), $reminder_template));
- }
- }
- $invoice->service()->setReminder()->save();
-
- } else {
- $invoice->next_send_date = null;
- $invoice->save();
- }
-
- });
-
-
- // SendReminders::dispatchNow();
+ // SendReminders::dispatchNow();
// $this->webHookOverdueInvoices();
// $this->webHookExpiredQuotes();
}
-
- private function calcLateFee($invoice, $template) :Invoice
+ private function calcLateFee($invoice, $template) :Invoice
{
$late_fee_amount = 0;
$late_fee_percent = 0;
@@ -151,7 +145,6 @@ class SendRemindersCron extends Command
*/
private function setLateFee($invoice, $amount, $percent) :Invoice
{
-
App::forgetInstance('translator');
$t = app('translator');
$t->replace(Ninja::transformTranslations($invoice->client->getMergedSettings()));
@@ -187,49 +180,20 @@ class SendRemindersCron extends Command
$invoice->calc()->getInvoice()->save();
$invoice->fresh();
$invoice->service()->deletePdf();
-
+
/* Refresh the client here to ensure the balance is fresh */
$client = $invoice->client;
$client = $client->fresh();
- nlog("adjusting client balance and invoice balance by ". ($invoice->balance - $temp_invoice_balance));
+ nlog('adjusting client balance and invoice balance by '.($invoice->balance - $temp_invoice_balance));
$client->service()->updateBalance($invoice->balance - $temp_invoice_balance)->save();
$invoice->ledger()->updateInvoiceBalance($invoice->balance - $temp_invoice_balance, "Late Fee Adjustment for invoice {$invoice->number}");
return $invoice;
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
private function webHookOverdueInvoices()
{
-
-
if (! config('ninja.db.multi_db_enabled')) {
$this->executeWebhooks();
} else {
@@ -240,12 +204,10 @@ class SendRemindersCron extends Command
$this->executeWebhooks();
}
}
-
}
private function webHookExpiredQuotes()
{
-
}
private function executeWebhooks()
@@ -255,21 +217,18 @@ class SendRemindersCron extends Command
->where('balance', '>', 0)
->whereDate('due_date', '<=', now()->subDays(1)->startOfDay())
->cursor();
-
+
$invoices->each(function ($invoice) {
WebhookHandler::dispatch(Webhook::EVENT_LATE_INVOICE, $invoice, $invoice->company);
-
});
$quotes = Quote::where('is_deleted', 0)
->where('status_id', Quote::STATUS_SENT)
->whereDate('due_date', '<=', now()->subDays(1)->startOfDay())
->cursor();
-
+
$quotes->each(function ($quote) {
WebhookHandler::dispatch(Webhook::EVENT_EXPIRED_QUOTE, $quote, $quote->company);
});
}
-
-
}
diff --git a/app/Console/Commands/SendTestEmails.php b/app/Console/Commands/SendTestEmails.php
index e47ec4c8a420..aa10cd582234 100644
--- a/app/Console/Commands/SendTestEmails.php
+++ b/app/Console/Commands/SendTestEmails.php
@@ -70,7 +70,7 @@ class SendTestEmails extends Command
$user = User::factory()->create([
'account_id' => $account->id,
'confirmation_code' => '123',
- 'email' => $faker->safeEmail,
+ 'email' => $faker->safeEmail(),
'first_name' => 'John',
'last_name' => 'Doe',
]);
@@ -96,6 +96,6 @@ class SendTestEmails extends Command
$nmo->settings = $user->account->companies()->first()->settings;
$nmo->to_user = $user;
- NinjaMailerJob::dispatchNow($nmo);
+ (new NinjaMailerJob($nmo))->handle();
}
}
diff --git a/app/Console/Commands/SubdomainFill.php b/app/Console/Commands/SubdomainFill.php
index ad5471d7866c..aa099a57a51e 100644
--- a/app/Console/Commands/SubdomainFill.php
+++ b/app/Console/Commands/SubdomainFill.php
@@ -40,25 +40,17 @@ class SubdomainFill extends Command
*/
public function handle()
{
-
$c1 = Company::on('db-ninja-01')->whereNull('subdomain')->orWhere('subdomain', '')->get();
$c2 = Company::on('db-ninja-02')->whereNull('subdomain')->orWhere('subdomain', '')->get();
-
- $c1->each(function ($company){
-
+ $c1->each(function ($company) {
$company->subdomain = MultiDB::randomSubdomainGenerator();
$company->save();
-
});
- $c2->each(function ($company){
-
+ $c2->each(function ($company) {
$company->subdomain = MultiDB::randomSubdomainGenerator();
$company->save();
-
});
-
}
-
}
diff --git a/app/Console/Commands/TranslationsExport.php b/app/Console/Commands/TranslationsExport.php
index bfc7ffe3f370..5fcf588b0ff5 100644
--- a/app/Console/Commands/TranslationsExport.php
+++ b/app/Console/Commands/TranslationsExport.php
@@ -69,8 +69,9 @@ class TranslationsExport extends Command
'sv',
'th',
'tr_TR',
- 'zh_TW'
+ 'zh_TW',
];
+
/**
* Create a new command instance.
*
@@ -88,19 +89,14 @@ class TranslationsExport extends Command
*/
public function handle()
{
-
Storage::makeDirectory(storage_path('lang'));
- foreach($this->langs as $lang)
- {
+ foreach ($this->langs as $lang) {
Storage::makeDirectory(storage_path("lang/{$lang}"));
- $translations = Lang::getLoader()->load($lang,'texts');
+ $translations = Lang::getLoader()->load($lang, 'texts');
Storage::put(storage_path("lang/{$lang}/{$lang}.json"), json_encode(Arr::dot($translations), JSON_UNESCAPED_UNICODE));
-
}
-
}
-
}
diff --git a/app/Console/Commands/TypeCheck.php b/app/Console/Commands/TypeCheck.php
index 0c7c3b97ed29..3ec6a339c34d 100644
--- a/app/Console/Commands/TypeCheck.php
+++ b/app/Console/Commands/TypeCheck.php
@@ -43,7 +43,6 @@ class TypeCheck extends Command
protected $log = '';
-
/**
* Create a new command instance.
*
@@ -65,91 +64,74 @@ class TypeCheck extends Command
$current_db = config('database.default');
- if($this->option('all'))
- {
+ if ($this->option('all')) {
if (! config('ninja.db.multi_db_enabled')) {
- $this->checkAll();
+ $this->checkAll();
} else {
-
- foreach (MultiDB::$dbs as $db)
- {
+ foreach (MultiDB::$dbs as $db) {
MultiDB::setDB($db);
$this->checkAll();
}
MultiDB::setDB($current_db);
-
}
-
}
- if($this->option('client_id'))
- {
+ if ($this->option('client_id')) {
$client = MultiDB::findAndSetDbByClientId($this->option('client_id'));
- if($client)
+ if ($client) {
$this->checkClient($client);
- else
+ } else {
$this->logMessage(date('Y-m-d h:i:s').' Could not find this client');
-
+ }
}
- if($this->option('company_id'))
- {
+ if ($this->option('company_id')) {
$company = MultiDB::findAndSetDbByCompanyId($this->option('company_id'));
-
- if($company)
+ if ($company) {
$this->checkCompany($company);
- else
+ } else {
$this->logMessage(date('Y-m-d h:i:s').' Could not find this company');
+ }
}
-
}
-
private function checkClient($client)
{
- $this->logMessage(date('Y-m-d h:i:s').' Checking Client => ' . $client->present()->name(). " " . $client->id);
-
-
- $entity_settings = $this->checkSettingType($client->settings);
- $entity_settings->md5 = md5(time());
- $client->settings = $entity_settings;
- $client->save();
+ $this->logMessage(date('Y-m-d h:i:s').' Checking Client => '.$client->present()->name().' '.$client->id);
+ $entity_settings = $this->checkSettingType($client->settings);
+ $entity_settings->md5 = md5(time());
+ $client->settings = $entity_settings;
+ $client->save();
}
private function checkCompany($company)
{
- $this->logMessage(date('Y-m-d h:i:s').' Checking Company => ' . $company->present()->name(). " " . $company->id);
-
- $company->saveSettings((array)$company->settings, $company);
+ $this->logMessage(date('Y-m-d h:i:s').' Checking Company => '.$company->present()->name().' '.$company->id);
+ $company->saveSettings((array) $company->settings, $company);
}
private function checkAll()
{
-
$this->logMessage(date('Y-m-d h:i:s').' Checking all clients and companies.');
- Client::withTrashed()->cursor()->each( function ($client) {
+ Client::withTrashed()->cursor()->each(function ($client) {
$this->logMessage("Checking client {$client->id}");
$entity_settings = $this->checkSettingType($client->settings);
$entity_settings->md5 = md5(time());
$client->settings = $entity_settings;
$client->save();
-
});
- Company::cursor()->each( function ($company) {
+ Company::cursor()->each(function ($company) {
$this->logMessage("Checking company {$company->id}");
$company->saveSettings($company->settings, $company);
-
});
-
-
}
private function logMessage($str)
@@ -159,4 +141,3 @@ class TypeCheck extends Command
$this->log .= $str."\n";
}
}
-
diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php
index e6ebbdc808c3..4ee1a351dda1 100644
--- a/app/Console/Kernel.php
+++ b/app/Console/Kernel.php
@@ -34,15 +34,6 @@ use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
- /**
- * The Artisan commands provided by your application.
- *
- * @var array
- */
- protected $commands = [
- //
- ];
-
/**
* Define the application's command schedule.
*
@@ -51,7 +42,6 @@ class Kernel extends ConsoleKernel
*/
protected function schedule(Schedule $schedule)
{
-
$schedule->job(new VersionCheck)->daily();
$schedule->job(new DiskCleanup)->daily()->withoutOverlapping();
@@ -78,17 +68,14 @@ class Kernel extends ConsoleKernel
$schedule->job(new SystemMaintenance)->weekly()->withoutOverlapping();
- if(Ninja::isSelfHost())
- {
+ if (Ninja::isSelfHost()) {
$schedule->call(function () {
Account::whereNotNull('id')->update(['is_scheduler_running' => true]);
})->everyFiveMinutes();
-
}
/* Run hosted specific jobs */
if (Ninja::isHosted()) {
-
$schedule->job(new AdjustEmailQuota)->dailyAt('23:30')->withoutOverlapping();
$schedule->job(new SendFailedEmails)->daily()->withoutOverlapping();
@@ -98,17 +85,13 @@ class Kernel extends ConsoleKernel
$schedule->command('ninja:check-data --database=db-ninja-02')->dailyAt('02:05')->withoutOverlapping();
$schedule->command('ninja:s3-cleanup')->dailyAt('23:15')->withoutOverlapping();
-
}
- if (config('queue.default') == 'database' && Ninja::isSelfHost() && config('ninja.internal_queue_enabled') && !config('ninja.is_docker')) {
-
+ if (config('queue.default') == 'database' && Ninja::isSelfHost() && config('ninja.internal_queue_enabled') && ! config('ninja.is_docker')) {
$schedule->command('queue:work database --stop-when-empty --memory=256')->everyMinute()->withoutOverlapping();
$schedule->command('queue:restart')->everyFiveMinutes()->withoutOverlapping();
-
}
-
}
/**
@@ -118,7 +101,7 @@ class Kernel extends ConsoleKernel
*/
protected function commands()
{
- $this->load(__DIR__ . '/Commands');
+ $this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
diff --git a/app/DataMapper/Analytics/AccountPlatform.php b/app/DataMapper/Analytics/AccountPlatform.php
index 40f0e2abf9f2..2e696ab50172 100644
--- a/app/DataMapper/Analytics/AccountPlatform.php
+++ b/app/DataMapper/Analytics/AccountPlatform.php
@@ -53,7 +53,8 @@ class AccountPlatform extends GenericMixedMetric
public $string_metric7 = 'ip_address';
- public function __construct($string_metric5, $string_metric6, $string_metric7) {
+ public function __construct($string_metric5, $string_metric6, $string_metric7)
+ {
$this->string_metric5 = $string_metric5;
$this->string_metric6 = $string_metric6;
$this->string_metric7 = $string_metric7;
diff --git a/app/DataMapper/Analytics/DbQuery.php b/app/DataMapper/Analytics/DbQuery.php
index 52ffbe646444..05d8b232b75e 100644
--- a/app/DataMapper/Analytics/DbQuery.php
+++ b/app/DataMapper/Analytics/DbQuery.php
@@ -52,6 +52,7 @@ class DbQuery extends GenericMixedMetric
public $string_metric6 = 'url';
public $string_metric7 = 'ip_address';
+
/**
* The counter
* set to 1.
@@ -62,7 +63,8 @@ class DbQuery extends GenericMixedMetric
public $double_metric2 = 1;
- public function __construct($string_metric5, $string_metric6, $int_metric1, $double_metric2, $string_metric7) {
+ public function __construct($string_metric5, $string_metric6, $int_metric1, $double_metric2, $string_metric7)
+ {
$this->int_metric1 = $int_metric1;
$this->string_metric5 = $string_metric5;
$this->string_metric6 = $string_metric6;
diff --git a/app/DataMapper/Analytics/EmailFailure.php b/app/DataMapper/Analytics/EmailFailure.php
index 077e0a15be9b..43cfc97fae32 100644
--- a/app/DataMapper/Analytics/EmailFailure.php
+++ b/app/DataMapper/Analytics/EmailFailure.php
@@ -71,7 +71,8 @@ class EmailFailure extends GenericMixedMetric
*/
public $string_metric7 = '';
- public function __construct($string_metric7) {
+ public function __construct($string_metric7)
+ {
$this->string_metric7 = $string_metric7;
}
}
diff --git a/app/DataMapper/Analytics/EmailSuccess.php b/app/DataMapper/Analytics/EmailSuccess.php
index 1d2160cb58e8..9f566eaa752a 100644
--- a/app/DataMapper/Analytics/EmailSuccess.php
+++ b/app/DataMapper/Analytics/EmailSuccess.php
@@ -15,7 +15,6 @@ use Turbo124\Beacon\ExampleMetric\GenericMixedMetric;
class EmailSuccess extends GenericMixedMetric
{
-
/**
* The type of Sample.
*
@@ -72,8 +71,8 @@ class EmailSuccess extends GenericMixedMetric
*/
public $string_metric7 = '';
- public function __construct($string_metric7) {
+ public function __construct($string_metric7)
+ {
$this->string_metric7 = $string_metric7;
}
-
}
diff --git a/app/DataMapper/Analytics/Mail/EmailBounce.php b/app/DataMapper/Analytics/Mail/EmailBounce.php
index 010a77ab3413..90a115a2ad53 100644
--- a/app/DataMapper/Analytics/Mail/EmailBounce.php
+++ b/app/DataMapper/Analytics/Mail/EmailBounce.php
@@ -71,7 +71,8 @@ class EmailBounce extends GenericMixedMetric
*/
public $int_metric1 = 1;
- public function __construct($string_metric5,$string_metric6,$string_metric7) {
+ public function __construct($string_metric5, $string_metric6, $string_metric7)
+ {
$this->string_metric5 = $string_metric5;
$this->string_metric6 = $string_metric6;
$this->string_metric7 = $string_metric7;
diff --git a/app/DataMapper/Analytics/Mail/EmailSpam.php b/app/DataMapper/Analytics/Mail/EmailSpam.php
index 1e63b6ba4b69..9d658d1243d9 100644
--- a/app/DataMapper/Analytics/Mail/EmailSpam.php
+++ b/app/DataMapper/Analytics/Mail/EmailSpam.php
@@ -71,7 +71,8 @@ class EmailSpam extends GenericMixedMetric
*/
public $int_metric1 = 1;
- public function __construct($string_metric5,$string_metric6,$string_metric7) {
+ public function __construct($string_metric5, $string_metric6, $string_metric7)
+ {
$this->string_metric5 = $string_metric5;
$this->string_metric6 = $string_metric6;
$this->string_metric7 = $string_metric7;
diff --git a/app/DataMapper/Analytics/QueueSize.php b/app/DataMapper/Analytics/QueueSize.php
index 3266f38645e2..0a356785f7a3 100644
--- a/app/DataMapper/Analytics/QueueSize.php
+++ b/app/DataMapper/Analytics/QueueSize.php
@@ -15,7 +15,6 @@ use Turbo124\Beacon\ExampleMetric\GenericMixedMetric;
class QueueSize extends GenericMixedMetric
{
-
/**
* The type of Sample.
*
@@ -72,8 +71,8 @@ class QueueSize extends GenericMixedMetric
*/
public $string_metric7 = '';
- public function __construct($int_metric1) {
+ public function __construct($int_metric1)
+ {
$this->int_metric1 = $int_metric1;
}
-
}
diff --git a/app/DataMapper/Billing/SubscriptionContextMapper.php b/app/DataMapper/Billing/SubscriptionContextMapper.php
index e45c6d1587e1..c86738a9162b 100644
--- a/app/DataMapper/Billing/SubscriptionContextMapper.php
+++ b/app/DataMapper/Billing/SubscriptionContextMapper.php
@@ -12,7 +12,6 @@
namespace App\DataMapper\Billing;
-
class SubscriptionContextMapper
{
/**
diff --git a/app/DataMapper/Billing/WebhookConfiguration.php b/app/DataMapper/Billing/WebhookConfiguration.php
index 1e0edd246417..08560d5ce1a1 100644
--- a/app/DataMapper/Billing/WebhookConfiguration.php
+++ b/app/DataMapper/Billing/WebhookConfiguration.php
@@ -12,7 +12,6 @@
namespace App\DataMapper\Billing;
-
class WebhookConfiguration
{
/**
@@ -33,11 +32,11 @@ class WebhookConfiguration
/**
* @var string
*/
- public $post_purchase_body = '';
+ public $post_purchase_body = '';
/**
* @var string
- */
+ */
public $post_purchase_rest_method = 'POST';
/**
diff --git a/app/DataMapper/ClientRegistrationFields.php b/app/DataMapper/ClientRegistrationFields.php
index a70871163f76..5e6397267dfe 100644
--- a/app/DataMapper/ClientRegistrationFields.php
+++ b/app/DataMapper/ClientRegistrationFields.php
@@ -13,89 +13,88 @@ namespace App\DataMapper;
class ClientRegistrationFields
{
-
public static function generate()
{
- $data =
+ $data =
[
[
'key' => 'first_name',
- 'required' => true
+ 'required' => true,
],
[
'key' => 'last_name',
- 'required' => true
+ 'required' => true,
],
[
'key' => 'email',
- 'required' => true
+ 'required' => true,
],
[
'key' => 'phone',
- 'required' => false
+ 'required' => false,
],
[
'key' => 'password',
- 'required' => true
- ],
+ 'required' => true,
+ ],
[
'key' => 'name',
- 'required' => false
+ 'required' => false,
],
[
'key' => 'website',
- 'required' => false
+ 'required' => false,
],
[
'key' => 'address1',
- 'required' => false
+ 'required' => false,
],
[
'key' => 'address2',
- 'required' => false
+ 'required' => false,
],
[
'key' => 'city',
- 'required' => false
+ 'required' => false,
],
[
'key' => 'state',
- 'required' => false
+ 'required' => false,
],
[
'key' => 'postal_code',
- 'required' => false
- ],
+ 'required' => false,
+ ],
[
'key' => 'country_id',
- 'required' => false
- ],
+ 'required' => false,
+ ],
[
'key' => 'custom_value1',
- 'required' => false
- ],
+ 'required' => false,
+ ],
[
'key' => 'custom_value2',
- 'required' => false
+ 'required' => false,
],
[
'key' => 'custom_value3',
- 'required' => false
- ],
+ 'required' => false,
+ ],
[
'key' => 'custom_value4',
- 'required' => false
- ],
+ 'required' => false,
+ ],
[
'key' => 'public_notes',
- 'required' => false
- ],
+ 'required' => false,
+ ],
[
'key' => 'vat_number',
- 'required' => false
- ],
+ 'required' => false,
+ ],
];
return $data;
}
-}
\ No newline at end of file
+}
diff --git a/app/DataMapper/ClientSettings.php b/app/DataMapper/ClientSettings.php
index 334b1c5936bd..2f10f03b655f 100644
--- a/app/DataMapper/ClientSettings.php
+++ b/app/DataMapper/ClientSettings.php
@@ -30,6 +30,7 @@ class ClientSettings extends BaseSettings
* Settings which which are unique to client settings.
*/
public $industry_id;
+
public $size_id;
public static $casts = [
diff --git a/app/DataMapper/CompanySettings.php b/app/DataMapper/CompanySettings.php
index 758c494e15c8..92a0ae31a2cc 100644
--- a/app/DataMapper/CompanySettings.php
+++ b/app/DataMapper/CompanySettings.php
@@ -31,20 +31,29 @@ class CompanySettings extends BaseSettings
public $lock_invoices = 'off'; //off,when_sent,when_paid //@implemented
public $enable_client_portal_tasks = false; //@ben to implement
+
public $show_all_tasks_client_portal = 'invoiced'; // all, uninvoiced, invoiced
+
public $enable_client_portal_password = false; //@implemented
+
public $enable_client_portal = true; //@implemented
+
public $enable_client_portal_dashboard = false; // @TODO There currently is no dashboard so this is pending
+
public $signature_on_pdf = false; //@implemented
+
public $document_email_attachment = false; //@TODO I assume this is 3rd party attachments on the entity to be included
public $portal_design_id = '1'; //?@deprecated
public $timezone_id = ''; //@implemented
+
public $date_format_id = ''; //@implemented
+
public $military_time = false; // @TODOImplemented in Tasks only?
public $language_id = ''; //@implemented
+
public $show_currency_code = false; //@implemented
public $company_gateway_ids = ''; //@implemented
@@ -52,243 +61,379 @@ class CompanySettings extends BaseSettings
public $currency_id = '1'; //@implemented
public $custom_value1 = ''; //@implemented
+
public $custom_value2 = ''; //@implemented
+
public $custom_value3 = ''; //@implemented
+
public $custom_value4 = ''; //@implemented
public $default_task_rate = 0; // @TODO Where do we inject this?
public $payment_terms = ''; //@implemented
+
public $send_reminders = true; //@TODO
public $custom_message_dashboard = ''; // @TODO There currently is no dashboard so this is pending
+
public $custom_message_unpaid_invoice = '';
+
public $custom_message_paid_invoice = '';
+
public $custom_message_unapproved_quote = '';
+
public $auto_archive_quote = false; //@implemented
+
public $auto_convert_quote = true; //@implemented
+
public $auto_email_invoice = true; //@only used for Recurring Invoices, if set to false, we never send?
public $entity_send_time = 6;
public $inclusive_taxes = false; //@implemented
+
public $quote_footer = ''; //@implmented
public $translations;
public $counter_number_applied = 'when_saved'; // when_saved , when_sent //@implemented
+
public $quote_number_applied = 'when_saved'; // when_saved , when_sent //@implemented
/* Counters */
public $invoice_number_pattern = ''; //@implemented
+
public $invoice_number_counter = 1; //@implemented
public $recurring_invoice_number_pattern = ''; //@implemented
+
public $recurring_invoice_number_counter = 1; //@implemented
public $quote_number_pattern = ''; //@implemented
+
public $quote_number_counter = 1; //@implemented
public $client_number_pattern = ''; //@implemented
+
public $client_number_counter = 1; //@implemented
public $credit_number_pattern = ''; //@implemented
+
public $credit_number_counter = 1; //@implemented
public $task_number_pattern = ''; //@implemented
+
public $task_number_counter = 1; //@implemented
public $expense_number_pattern = ''; //@implemented
+
public $expense_number_counter = 1; //@implemented
public $recurring_expense_number_pattern = '';
+
public $recurring_expense_number_counter = 1;
public $recurring_quote_number_pattern = '';
+
public $recurring_quote_number_counter = 1;
public $vendor_number_pattern = ''; //@implemented
+
public $vendor_number_counter = 1; //@implemented
public $ticket_number_pattern = ''; //@implemented
+
public $ticket_number_counter = 1; //@implemented
public $payment_number_pattern = ''; //@implemented
+
public $payment_number_counter = 1; //@implemented
public $project_number_pattern = ''; //@implemented
+
public $project_number_counter = 1; //@implemented
public $purchase_order_number_pattern = ''; //@implemented
+
public $purchase_order_number_counter = 1; //@implemented
public $shared_invoice_quote_counter = false; //@implemented
+
public $shared_invoice_credit_counter = false; //@implemented
+
public $recurring_number_prefix = ''; //@implemented
+
public $reset_counter_frequency_id = '0'; //@implemented
+
public $reset_counter_date = ''; //@implemented
+
public $counter_padding = 4; //@implemented
public $auto_bill = 'off'; //off,always,optin,optout //@implemented
+
public $auto_bill_date = 'on_due_date'; // on_due_date , on_send_date //@implemented
public $invoice_terms = ''; //@implemented
+
public $quote_terms = ''; //@implemented
+
public $invoice_taxes = 0; // ? used in AP only?
public $invoice_design_id = 'Wpmbk5ezJn'; //@implemented
+
public $quote_design_id = 'Wpmbk5ezJn'; //@implemented
+
public $credit_design_id = 'Wpmbk5ezJn'; //@implemented
public $purchase_order_design_id = 'Wpmbk5ezJn';
+
public $purchase_order_footer = ''; //@implemented
+
public $purchase_order_terms = ''; //@implemented
+
public $purchase_order_public_notes = ''; //@implemented
+
public $require_purchase_order_signature = false; //@TODO ben to confirm
-
+
public $invoice_footer = ''; //@implemented
+
public $credit_footer = ''; //@implemented
+
public $credit_terms = ''; //@implemented
+
public $invoice_labels = ''; //@TODO used in AP only?
+
public $tax_name1 = ''; //@TODO where do we use this?
+
public $tax_rate1 = 0; //@TODO where do we use this?
+
public $tax_name2 = ''; //@TODO where do we use this?
+
public $tax_rate2 = 0; //@TODO where do we use this?
+
public $tax_name3 = ''; //@TODO where do we use this?
+
public $tax_rate3 = 0; //@TODO where do we use this?
+
public $payment_type_id = '0'; //@TODO where do we use this?
public $valid_until = ''; //@implemented
public $show_accept_invoice_terms = false; //@TODO ben to confirm
+
public $show_accept_quote_terms = false; //@TODO ben to confirm
+
public $require_invoice_signature = false; //@TODO ben to confirm
+
public $require_quote_signature = false; //@TODO ben to confirm
//email settings
public $email_sending_method = 'default'; //enum 'default','gmail','office365' //@implemented
+
public $gmail_sending_user_id = '0'; //@implemented
public $reply_to_email = ''; //@implemented
+
public $reply_to_name = ''; //@implemented
+
public $bcc_email = ''; //@TODO
+
public $pdf_email_attachment = false; //@implemented
+
public $ubl_email_attachment = false; //@implemented
public $email_style = 'light'; //plain, light, dark, custom //@implemented
+
public $email_style_custom = ''; //the template itself //@implemented
+
public $email_subject_invoice = ''; //@implemented
+
public $email_subject_quote = ''; //@implemented
+
public $email_subject_credit = ''; //@implemented
+
public $email_subject_payment = ''; //@implemented
+
public $email_subject_payment_partial = ''; //@implemented
+
public $email_subject_statement = ''; //@implemented
+
public $email_subject_purchase_order = ''; //@implemented
+
public $email_template_purchase_order = ''; //@implemented
+
public $email_template_invoice = ''; //@implemented
+
public $email_template_credit = ''; //@implemented
+
public $email_template_quote = ''; //@implemented
+
public $email_template_payment = ''; //@implemented
+
public $email_template_payment_partial = ''; //@implemented
+
public $email_template_statement = ''; //@implemented
+
public $email_subject_reminder1 = ''; //@implemented
+
public $email_subject_reminder2 = ''; //@implemented
+
public $email_subject_reminder3 = ''; //@implemented
+
public $email_subject_reminder_endless = ''; //@implemented
+
public $email_template_reminder1 = ''; //@implemented
+
public $email_template_reminder2 = ''; //@implemented
+
public $email_template_reminder3 = ''; //@implemented
+
public $email_template_reminder_endless = ''; //@implemented
+
public $email_signature = ''; //@implemented
+
public $enable_email_markup = true; //@TODO -
public $email_subject_custom1 = ''; //@TODO
+
public $email_subject_custom2 = ''; //@TODO
+
public $email_subject_custom3 = ''; //@TODO
public $email_template_custom1 = ''; //@TODO
+
public $email_template_custom2 = ''; //@TODO
+
public $email_template_custom3 = ''; //@TODO
public $enable_reminder1 = false; //@implmemented
+
public $enable_reminder2 = false; //@implmemented
+
public $enable_reminder3 = false; //@implmemented
+
public $enable_reminder_endless = false; //@implmemented
- public $num_days_reminder1 = 0;//@implmemented
- public $num_days_reminder2 = 0;//@implmemented
- public $num_days_reminder3 = 0;//@implmemented
+ public $num_days_reminder1 = 0; //@implmemented
+
+ public $num_days_reminder2 = 0; //@implmemented
+
+ public $num_days_reminder3 = 0; //@implmemented
public $schedule_reminder1 = ''; // (enum: after_invoice_date, before_due_date, after_due_date) implmemented
+
public $schedule_reminder2 = ''; // (enum: after_invoice_date, before_due_date, after_due_date) implmemented
+
public $schedule_reminder3 = ''; // (enum: after_invoice_date, before_due_date, after_due_date) implmemented
public $reminder_send_time = 0; //number of seconds from UTC +0 to send reminders @TODO
public $late_fee_amount1 = 0; //@implemented
+
public $late_fee_amount2 = 0; //@implemented
+
public $late_fee_amount3 = 0; //@implemented
public $late_fee_percent1 = 0; //@implemented
+
public $late_fee_percent2 = 0; //@implemented
+
public $late_fee_percent3 = 0; //@implemented
public $endless_reminder_frequency_id = '0'; //@implemented
+
public $late_fee_endless_amount = 0; //@implemented
+
public $late_fee_endless_percent = 0; //@implemented
public $client_online_payment_notification = true; //@todo implement in notifications check this bool prior to sending payment notification to client
+
public $client_manual_payment_notification = true; //@todo implement in notifications check this bool prior to sending manual payment notification to client
/* Company Meta data that we can use to build sub companies*/
public $name = ''; //@implemented
+
public $company_logo = ''; //@implemented
+
public $website = ''; //@implemented
+
public $address1 = ''; //@implemented
+
public $address2 = ''; //@implemented
+
public $city = ''; //@implemented
+
public $state = ''; //@implemented
+
public $postal_code = ''; //@implemented
+
public $phone = ''; //@implemented
+
public $email = ''; //@implemented
+
public $country_id; //@implemented
+
public $vat_number = ''; //@implemented
+
public $id_number = ''; //@implemented
public $page_size = 'A4'; //Letter, Legal, Tabloid, Ledger, A0, A1, A2, A3, A4, A5, A6
+
public $page_layout = 'portrait';
+
public $font_size = 7; //@implemented
+
public $primary_font = 'Roboto';
+
public $secondary_font = 'Roboto';
+
public $primary_color = '#298AAB';
+
public $secondary_color = '#7081e0';
public $page_numbering = false;
+
public $page_numbering_alignment = 'C'; //C,R,L
public $hide_paid_to_date = false; //@TODO where?
+
public $embed_documents = false; //@TODO where?
+
public $all_pages_header = false; //@deprecated 31-05-2021
+
public $all_pages_footer = false; //@deprecated 31-05-2021
+
public $pdf_variables = ''; //@implemented
public $portal_custom_head = ''; //@TODO @BEN
+
public $portal_custom_css = ''; //@TODO @BEN
+
public $portal_custom_footer = ''; //@TODO @BEN
+
public $portal_custom_js = ''; //@TODO @BEN
public $client_can_register = false; //@deorecated 04/06/2021
+
public $client_portal_terms = ''; //@TODO @BEN
+
public $client_portal_privacy_policy = ''; //@TODO @BEN
+
public $client_portal_enable_uploads = false; //@implemented
+
public $client_portal_allow_under_payment = false; //@implemented
+
public $client_portal_under_payment_minimum = 0; //@implemented
+
public $client_portal_allow_over_payment = false; //@implemented
public $use_credits_payment = 'off'; //always, option, off //@implemented
+
public $hide_empty_columns_on_pdf = false;
+
public $email_from_name = '';
+
public $auto_archive_invoice_cancelled = false;
public $vendor_portal_enable_uploads=false;
diff --git a/app/DataMapper/DefaultSettings.php b/app/DataMapper/DefaultSettings.php
index e2b4d45b9d52..2c0ebef43bcf 100644
--- a/app/DataMapper/DefaultSettings.php
+++ b/app/DataMapper/DefaultSettings.php
@@ -26,12 +26,11 @@ class DefaultSettings extends BaseSettings
/**
* @return stdClass
- *
*/
public static function userSettings() : stdClass
{
return (object) [
- // class_basename(User::class) => self::userSettingsObject(),
+ // class_basename(User::class) => self::userSettingsObject(),
];
}
@@ -41,7 +40,7 @@ class DefaultSettings extends BaseSettings
private static function userSettingsObject() : stdClass
{
return (object) [
- // 'per_page' => self::$per_page,
+ // 'per_page' => self::$per_page,
];
}
}
diff --git a/app/DataMapper/EmailTemplateDefaults.php b/app/DataMapper/EmailTemplateDefaults.php
index 5cdc7b915c23..3ce6ab53ac96 100644
--- a/app/DataMapper/EmailTemplateDefaults.php
+++ b/app/DataMapper/EmailTemplateDefaults.php
@@ -162,11 +162,9 @@ class EmailTemplateDefaults
public static function emailPurchaseOrderTemplate()
{
-
$purchase_order_message = '
$vendor
'.self::transformText('purchase_order_message').'
$view_button
';
return $purchase_order_message;
-
}
public static function emailPaymentTemplate()
@@ -249,6 +247,6 @@ class EmailTemplateDefaults
{
//preformat the string, removing trailing colons.
- return str_replace(':', '$', rtrim( ctrans('texts.'.$string), ":"));
+ return str_replace(':', '$', rtrim(ctrans('texts.'.$string), ':'));
}
}
diff --git a/app/DataMapper/FreeCompanySettings.php b/app/DataMapper/FreeCompanySettings.php
index fceab936b176..cecea6bf606d 100644
--- a/app/DataMapper/FreeCompanySettings.php
+++ b/app/DataMapper/FreeCompanySettings.php
@@ -20,67 +20,123 @@ use stdClass;
class FreeCompanySettings extends BaseSettings
{
use MakesHash;
+
/*Group settings based on functionality*/
public $credit_design_id = 'VolejRejNm';
+
public $client_number_pattern = '';
+
public $client_number_counter = 1;
+
public $credit_number_pattern = '';
+
public $credit_number_counter = 1;
+
public $currency_id = '1';
+
public $custom_value1 = '';
+
public $custom_value2 = '';
+
public $custom_value3 = '';
+
public $custom_value4 = '';
+
public $date_format_id = '';
+
// public $enabled_item_tax_rates = 0;
public $expense_number_pattern = '';
+
public $expense_number_counter = 1;
+
public $inclusive_taxes = false;
+
public $invoice_design_id = 'VolejRejNm';
+
public $invoice_number_pattern = '';
+
public $invoice_number_counter = 1;
+
public $invoice_taxes = 0;
+
public $language_id = '';
+
public $military_time = false;
+
public $payment_number_pattern = '';
+
public $payment_number_counter = 1;
+
public $payment_terms = '';
+
public $payment_type_id = '0';
+
public $portal_design_id = '1';
+
public $quote_design_id = 'VolejRejNm';
+
public $quote_number_pattern = '';
+
public $quote_number_counter = 1;
+
public $timezone_id = '';
+
public $show_currency_code = false;
+
public $company_gateway_ids = '';
+
public $task_number_pattern = '';
+
public $task_number_counter = 1;
+
public $tax_name1 = '';
+
public $tax_rate1 = 0;
+
public $tax_name2 = '';
+
public $tax_rate2 = 0;
+
public $tax_name3 = '';
+
public $tax_rate3 = 0;
+
public $ticket_number_pattern = '';
+
public $ticket_number_counter = 1;
+
public $translations;
+
public $vendor_number_pattern = '';
+
public $vendor_number_counter = 1;
/* Company Meta data that we can use to build sub companies*/
public $address1 = '';
+
public $address2 = '';
+
public $city = '';
+
public $company_logo = '';
+
public $country_id;
+
public $email = '';
+
public $id_number = '';
+
public $name = '';
+
public $phone = '';
+
public $postal_code = '';
+
public $state = '';
+
public $vat_number = '';
+
public $website = '';
public static $casts = [
diff --git a/app/DataMapper/Transactions/BaseTransaction.php b/app/DataMapper/Transactions/BaseTransaction.php
index 88c49b8cdb3c..7546ebbae740 100644
--- a/app/DataMapper/Transactions/BaseTransaction.php
+++ b/app/DataMapper/Transactions/BaseTransaction.php
@@ -22,8 +22,7 @@ use App\Models\TransactionEvent;
*/
class BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::INVOICE_MARK_PAID;
+ public $event_id = TransactionEvent::INVOICE_MARK_PAID;
public array $model = [
'client_id',
@@ -56,7 +55,7 @@ class BaseTransaction implements TransactionInterface
{
// $invoice = $data['invoice'];
// $payment = $data['payment'];
- // $client = $data['client'];
+ // $client = $data['client'];
// $credit = $data['credit'];
// $payment_request = $data['payment']['payment_request'];
// $metadata = $data['metadata'];
@@ -95,6 +94,5 @@ class BaseTransaction implements TransactionInterface
// 'credit_status' => $credit?->status_id,
// 'timestamp' => time(),
// ];
-
}
}
diff --git a/app/DataMapper/Transactions/ClientStatusTransaction.php b/app/DataMapper/Transactions/ClientStatusTransaction.php
index 0670c3f0fd89..0c28e4a8dc16 100644
--- a/app/DataMapper/Transactions/ClientStatusTransaction.php
+++ b/app/DataMapper/Transactions/ClientStatusTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class ClientStatusTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::CLIENT_STATUS;
-
+ public $event_id = TransactionEvent::CLIENT_STATUS;
}
diff --git a/app/DataMapper/Transactions/GatewayPaymentMadeTransaction.php b/app/DataMapper/Transactions/GatewayPaymentMadeTransaction.php
index 26af2acd3b65..f41d91b7a8b8 100644
--- a/app/DataMapper/Transactions/GatewayPaymentMadeTransaction.php
+++ b/app/DataMapper/Transactions/GatewayPaymentMadeTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class GatewayPaymentMadeTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::GATEWAY_PAYMENT_MADE;
-
+ public $event_id = TransactionEvent::GATEWAY_PAYMENT_MADE;
}
diff --git a/app/DataMapper/Transactions/InvoiceCancelledTransaction.php b/app/DataMapper/Transactions/InvoiceCancelledTransaction.php
index 1e7438513285..9dcd28b09b03 100644
--- a/app/DataMapper/Transactions/InvoiceCancelledTransaction.php
+++ b/app/DataMapper/Transactions/InvoiceCancelledTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class InvoiceCancelledTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::INVOICE_CANCELLED;
-
+ public $event_id = TransactionEvent::INVOICE_CANCELLED;
}
diff --git a/app/DataMapper/Transactions/InvoiceDeletedTransaction.php b/app/DataMapper/Transactions/InvoiceDeletedTransaction.php
index 7a1d6c89ae35..a7ef833ad764 100644
--- a/app/DataMapper/Transactions/InvoiceDeletedTransaction.php
+++ b/app/DataMapper/Transactions/InvoiceDeletedTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class InvoiceDeletedTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::INVOICE_DELETED;
-
+ public $event_id = TransactionEvent::INVOICE_DELETED;
}
diff --git a/app/DataMapper/Transactions/InvoiceFeeAppliedTransaction.php b/app/DataMapper/Transactions/InvoiceFeeAppliedTransaction.php
index fdc9b4f67f7d..ab3a41fe9e3f 100644
--- a/app/DataMapper/Transactions/InvoiceFeeAppliedTransaction.php
+++ b/app/DataMapper/Transactions/InvoiceFeeAppliedTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class InvoiceFeeAppliedTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::INVOICE_FEE_APPLIED;
-
+ public $event_id = TransactionEvent::INVOICE_FEE_APPLIED;
}
diff --git a/app/DataMapper/Transactions/InvoicePaymentTransaction.php b/app/DataMapper/Transactions/InvoicePaymentTransaction.php
index af1c86f1d2cc..43c39d365288 100644
--- a/app/DataMapper/Transactions/InvoicePaymentTransaction.php
+++ b/app/DataMapper/Transactions/InvoicePaymentTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class InvoicePaymentTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::INVOICE_PAYMENT_APPLIED;
-
+ public $event_id = TransactionEvent::INVOICE_PAYMENT_APPLIED;
}
diff --git a/app/DataMapper/Transactions/InvoiceReversalTransaction.php b/app/DataMapper/Transactions/InvoiceReversalTransaction.php
index 4577b99434d8..afe2fb6dbf0c 100644
--- a/app/DataMapper/Transactions/InvoiceReversalTransaction.php
+++ b/app/DataMapper/Transactions/InvoiceReversalTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class InvoiceReversalTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::INVOICE_REVERSED;
-
+ public $event_id = TransactionEvent::INVOICE_REVERSED;
}
diff --git a/app/DataMapper/Transactions/InvoiceUpdatedTransaction.php b/app/DataMapper/Transactions/InvoiceUpdatedTransaction.php
index 675df7c230c7..fb0343aa9d15 100644
--- a/app/DataMapper/Transactions/InvoiceUpdatedTransaction.php
+++ b/app/DataMapper/Transactions/InvoiceUpdatedTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class InvoiceUpdatedTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::INVOICE_UPDATED;
-
+ public $event_id = TransactionEvent::INVOICE_UPDATED;
}
diff --git a/app/DataMapper/Transactions/MarkPaidTransaction.php b/app/DataMapper/Transactions/MarkPaidTransaction.php
index b1a5c2f6425f..78506c0c1503 100644
--- a/app/DataMapper/Transactions/MarkPaidTransaction.php
+++ b/app/DataMapper/Transactions/MarkPaidTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class MarkPaidTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::INVOICE_MARK_PAID;
-
+ public $event_id = TransactionEvent::INVOICE_MARK_PAID;
}
diff --git a/app/DataMapper/Transactions/PaymentAppliedTransaction.php b/app/DataMapper/Transactions/PaymentAppliedTransaction.php
index c00e3a828d1a..b0f9a32172d0 100644
--- a/app/DataMapper/Transactions/PaymentAppliedTransaction.php
+++ b/app/DataMapper/Transactions/PaymentAppliedTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class PaymentAppliedTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::PAYMENT_APPLIED;
-
+ public $event_id = TransactionEvent::PAYMENT_APPLIED;
}
diff --git a/app/DataMapper/Transactions/PaymentDeletedTransaction.php b/app/DataMapper/Transactions/PaymentDeletedTransaction.php
index f1d6e51cd8dc..e9cca01cce16 100644
--- a/app/DataMapper/Transactions/PaymentDeletedTransaction.php
+++ b/app/DataMapper/Transactions/PaymentDeletedTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class PaymentDeletedTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::PAYMENT_DELETED;
-
+ public $event_id = TransactionEvent::PAYMENT_DELETED;
}
diff --git a/app/DataMapper/Transactions/PaymentFailedTransaction.php b/app/DataMapper/Transactions/PaymentFailedTransaction.php
index a215c08815ac..d46bd83b16ff 100644
--- a/app/DataMapper/Transactions/PaymentFailedTransaction.php
+++ b/app/DataMapper/Transactions/PaymentFailedTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class PaymentFailedTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::PAYMENT_FAILED;
-
+ public $event_id = TransactionEvent::PAYMENT_FAILED;
}
diff --git a/app/DataMapper/Transactions/PaymentMadeTransaction.php b/app/DataMapper/Transactions/PaymentMadeTransaction.php
index a96b923eb746..427f59edc16a 100644
--- a/app/DataMapper/Transactions/PaymentMadeTransaction.php
+++ b/app/DataMapper/Transactions/PaymentMadeTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class PaymentMadeTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::PAYMENT_MADE;
-
+ public $event_id = TransactionEvent::PAYMENT_MADE;
}
diff --git a/app/DataMapper/Transactions/PaymentRefundedTransaction.php b/app/DataMapper/Transactions/PaymentRefundedTransaction.php
index a7c696d8e3b8..f2b2b92ad587 100644
--- a/app/DataMapper/Transactions/PaymentRefundedTransaction.php
+++ b/app/DataMapper/Transactions/PaymentRefundedTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class PaymentRefundedTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::PAYMENT_REFUND;
-
+ public $event_id = TransactionEvent::PAYMENT_REFUND;
}
diff --git a/app/Events/Client/ClientWasRestored.php b/app/Events/Client/ClientWasRestored.php
index 4a1fc529736b..41cf7fd04e50 100644
--- a/app/Events/Client/ClientWasRestored.php
+++ b/app/Events/Client/ClientWasRestored.php
@@ -28,7 +28,7 @@ class ClientWasRestored
public $client;
public $fromDeleted;
-
+
public $company;
public $event_vars;
diff --git a/app/Events/Credit/CreditWasEmailed.php b/app/Events/Credit/CreditWasEmailed.php
index fc567516c6b0..3c17c71da343 100644
--- a/app/Events/Credit/CreditWasEmailed.php
+++ b/app/Events/Credit/CreditWasEmailed.php
@@ -28,6 +28,7 @@ class CreditWasEmailed
public $event_vars;
public $template;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Credit/CreditWasMarkedSent.php b/app/Events/Credit/CreditWasMarkedSent.php
index 48f0ca791a48..60ce1a4e84cf 100644
--- a/app/Events/Credit/CreditWasMarkedSent.php
+++ b/app/Events/Credit/CreditWasMarkedSent.php
@@ -21,6 +21,7 @@ use Illuminate\Queue\SerializesModels;
class CreditWasMarkedSent
{
use SerializesModels;
+
/**
* @var Credit
*/
diff --git a/app/Events/Credit/CreditWasRestored.php b/app/Events/Credit/CreditWasRestored.php
index 1f515ac41625..cb564bc006ca 100644
--- a/app/Events/Credit/CreditWasRestored.php
+++ b/app/Events/Credit/CreditWasRestored.php
@@ -32,6 +32,7 @@ class CreditWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Design/DesignWasRestored.php b/app/Events/Design/DesignWasRestored.php
index bca0757aa152..42525602fa86 100644
--- a/app/Events/Design/DesignWasRestored.php
+++ b/app/Events/Design/DesignWasRestored.php
@@ -32,6 +32,7 @@ class DesignWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Document/DocumentWasRestored.php b/app/Events/Document/DocumentWasRestored.php
index 4941db97cfe1..3fc9580e7828 100644
--- a/app/Events/Document/DocumentWasRestored.php
+++ b/app/Events/Document/DocumentWasRestored.php
@@ -32,6 +32,7 @@ class DocumentWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Expense/ExpenseWasRestored.php b/app/Events/Expense/ExpenseWasRestored.php
index 2c74bf5e6d86..5341329823c1 100644
--- a/app/Events/Expense/ExpenseWasRestored.php
+++ b/app/Events/Expense/ExpenseWasRestored.php
@@ -32,6 +32,7 @@ class ExpenseWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Invoice/InvoiceWasRestored.php b/app/Events/Invoice/InvoiceWasRestored.php
index d848d4cb0e59..489e47b1a173 100644
--- a/app/Events/Invoice/InvoiceWasRestored.php
+++ b/app/Events/Invoice/InvoiceWasRestored.php
@@ -32,7 +32,7 @@ class InvoiceWasRestored
public $company;
public $event_vars;
-
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Payment/PaymentWasRestored.php b/app/Events/Payment/PaymentWasRestored.php
index 390e3e193c92..378e3a956613 100644
--- a/app/Events/Payment/PaymentWasRestored.php
+++ b/app/Events/Payment/PaymentWasRestored.php
@@ -26,8 +26,11 @@ class PaymentWasRestored
* @var Payment
*/
public $payment;
+
public $fromDeleted;
+
public $company;
+
public $event_vars;
/**
diff --git a/app/Events/Product/ProductWasRestored.php b/app/Events/Product/ProductWasRestored.php
index 9949bf21b396..16432c6ce8b3 100644
--- a/app/Events/Product/ProductWasRestored.php
+++ b/app/Events/Product/ProductWasRestored.php
@@ -32,6 +32,7 @@ class ProductWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/PurchaseOrder/PurchaseOrderWasAccepted.php b/app/Events/PurchaseOrder/PurchaseOrderWasAccepted.php
index ed2147b5fdb1..d903911cfda9 100644
--- a/app/Events/PurchaseOrder/PurchaseOrderWasAccepted.php
+++ b/app/Events/PurchaseOrder/PurchaseOrderWasAccepted.php
@@ -34,6 +34,7 @@ class PurchaseOrderWasAccepted
public $event_vars;
public $contact;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/PurchaseOrder/PurchaseOrderWasRestored.php b/app/Events/PurchaseOrder/PurchaseOrderWasRestored.php
index c957c52a75b9..c0a40f7838a4 100644
--- a/app/Events/PurchaseOrder/PurchaseOrderWasRestored.php
+++ b/app/Events/PurchaseOrder/PurchaseOrderWasRestored.php
@@ -32,6 +32,7 @@ class PurchaseOrderWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Quote/QuoteWasEmailed.php b/app/Events/Quote/QuoteWasEmailed.php
index 02f6ea7c376b..5cd9ad36a19e 100644
--- a/app/Events/Quote/QuoteWasEmailed.php
+++ b/app/Events/Quote/QuoteWasEmailed.php
@@ -30,6 +30,7 @@ class QuoteWasEmailed
public $event_vars;
public $template;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Quote/QuoteWasRestored.php b/app/Events/Quote/QuoteWasRestored.php
index 162cec73d7d3..4f4f550e4e8f 100644
--- a/app/Events/Quote/QuoteWasRestored.php
+++ b/app/Events/Quote/QuoteWasRestored.php
@@ -29,6 +29,7 @@ class QuoteWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/RecurringExpense/RecurringExpenseWasRestored.php b/app/Events/RecurringExpense/RecurringExpenseWasRestored.php
index 7134e211800c..903c041c49eb 100644
--- a/app/Events/RecurringExpense/RecurringExpenseWasRestored.php
+++ b/app/Events/RecurringExpense/RecurringExpenseWasRestored.php
@@ -32,6 +32,7 @@ class RecurringExpenseWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/RecurringInvoice/RecurringInvoiceWasRestored.php b/app/Events/RecurringInvoice/RecurringInvoiceWasRestored.php
index e6441eae6143..4e31892c1f1c 100644
--- a/app/Events/RecurringInvoice/RecurringInvoiceWasRestored.php
+++ b/app/Events/RecurringInvoice/RecurringInvoiceWasRestored.php
@@ -32,7 +32,7 @@ class RecurringInvoiceWasRestored
public $company;
public $event_vars;
-
+
/**
* Create a new event instance.
*
diff --git a/app/Events/RecurringQuote/RecurringQuoteWasRestored.php b/app/Events/RecurringQuote/RecurringQuoteWasRestored.php
index 400bf11aa858..d84bc692e562 100644
--- a/app/Events/RecurringQuote/RecurringQuoteWasRestored.php
+++ b/app/Events/RecurringQuote/RecurringQuoteWasRestored.php
@@ -32,7 +32,7 @@ class RecurringQuoteWasRestored
public $company;
public $event_vars;
-
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Subscription/SubscriptionWasCreated.php b/app/Events/Subscription/SubscriptionWasCreated.php
index 67d061f6738d..1da537bbbf1f 100644
--- a/app/Events/Subscription/SubscriptionWasCreated.php
+++ b/app/Events/Subscription/SubscriptionWasCreated.php
@@ -2,8 +2,8 @@
namespace App\Events\Subscription;
-use App\Models\Subscription;
use App\Models\Company;
+use App\Models\Subscription;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
diff --git a/app/Events/Subscription/SubscriptionWasRestored.php b/app/Events/Subscription/SubscriptionWasRestored.php
index d205a5c2f702..54029013febb 100644
--- a/app/Events/Subscription/SubscriptionWasRestored.php
+++ b/app/Events/Subscription/SubscriptionWasRestored.php
@@ -32,6 +32,7 @@ class SubscriptionWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Task/TaskWasRestored.php b/app/Events/Task/TaskWasRestored.php
index a6c68e5d2367..54f9b087e197 100644
--- a/app/Events/Task/TaskWasRestored.php
+++ b/app/Events/Task/TaskWasRestored.php
@@ -32,6 +32,7 @@ class TaskWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Vendor/VendorWasRestored.php b/app/Events/Vendor/VendorWasRestored.php
index 00f44cd8ae84..9d402240b504 100644
--- a/app/Events/Vendor/VendorWasRestored.php
+++ b/app/Events/Vendor/VendorWasRestored.php
@@ -32,6 +32,7 @@ class VendorWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php
index f9bc844a31da..9bfbc70930c5 100644
--- a/app/Exceptions/Handler.php
+++ b/app/Exceptions/Handler.php
@@ -62,6 +62,7 @@ class Handler extends ExceptionHandler
* @var array
*/
protected $dontFlash = [
+ 'current_password',
'password',
'password_confirmation',
];
@@ -77,37 +78,33 @@ class Handler extends ExceptionHandler
{
if (! Schema::hasTable('accounts')) {
info('account table not found');
+
return;
}
- if(Ninja::isHosted() && !($exception instanceof ValidationException)){
-
+ if (Ninja::isHosted() && ! ($exception instanceof ValidationException)) {
app('sentry')->configureScope(function (Scope $scope): void {
-
$name = 'hosted@invoiceninja.com';
- if(auth()->guard('contact') && auth()->guard('contact')->user()){
- $name = "Contact = ".auth()->guard('contact')->user()->email;
+ if (auth()->guard('contact') && auth()->guard('contact')->user()) {
+ $name = 'Contact = '.auth()->guard('contact')->user()->email;
$key = auth()->guard('contact')->user()->company->account->key;
- }
- elseif (auth()->guard('user') && auth()->guard('user')->user()){
- $name = "Admin = ".auth()->guard('user')->user()->email;
+ } elseif (auth()->guard('user') && auth()->guard('user')->user()) {
+ $name = 'Admin = '.auth()->guard('user')->user()->email;
$key = auth()->user()->account->key;
- }
- else
+ } else {
$key = 'Anonymous';
-
- $scope->setUser([
- 'id' => $key,
- 'email' => 'hosted@invoiceninja.com',
- 'name' => $name,
- ]);
+ }
+
+ $scope->setUser([
+ 'id' => $key,
+ 'email' => 'hosted@invoiceninja.com',
+ 'name' => $name,
+ ]);
});
- app('sentry')->captureException($exception);
-
- }
- elseif (app()->bound('sentry') && $this->shouldReport($exception)) {
+ app('sentry')->captureException($exception);
+ } elseif (app()->bound('sentry') && $this->shouldReport($exception)) {
app('sentry')->configureScope(function (Scope $scope): void {
if (auth()->guard('contact') && auth()->guard('contact')->user() && auth()->guard('contact')->user()->company->account->report_errors) {
$scope->setUser([
@@ -130,28 +127,33 @@ class Handler extends ExceptionHandler
}
parent::report($exception);
-
}
private function validException($exception)
{
- if (strpos($exception->getMessage(), 'file_put_contents') !== false)
+ if (strpos($exception->getMessage(), 'file_put_contents') !== false) {
return false;
+ }
- if (strpos($exception->getMessage(), 'Permission denied') !== false)
- return false;
-
- if (strpos($exception->getMessage(), 'flock') !== false)
+ if (strpos($exception->getMessage(), 'Permission denied') !== false) {
return false;
+ }
- if (strpos($exception->getMessage(), 'expects parameter 1 to be resource') !== false)
+ if (strpos($exception->getMessage(), 'flock') !== false) {
return false;
+ }
- if (strpos($exception->getMessage(), 'fwrite()') !== false)
+ if (strpos($exception->getMessage(), 'expects parameter 1 to be resource') !== false) {
return false;
-
- if(strpos($exception->getMessage(), 'LockableFile') !== false)
+ }
+
+ if (strpos($exception->getMessage(), 'fwrite()') !== false) {
return false;
+ }
+
+ if (strpos($exception->getMessage(), 'LockableFile') !== false) {
+ return false;
+ }
return true;
}
@@ -168,11 +170,11 @@ class Handler extends ExceptionHandler
{
if ($exception instanceof ModelNotFoundException && $request->expectsJson()) {
return response()->json(['message'=>$exception->getMessage()], 400);
- }elseif($exception instanceof InternalPDFFailure && $request->expectsJson()){
+ } elseif ($exception instanceof InternalPDFFailure && $request->expectsJson()) {
return response()->json(['message' => $exception->getMessage()], 500);
- }elseif($exception instanceof PhantomPDFFailure && $request->expectsJson()){
+ } elseif ($exception instanceof PhantomPDFFailure && $request->expectsJson()) {
return response()->json(['message' => $exception->getMessage()], 500);
- }elseif($exception instanceof FilePermissionsFailure) {
+ } elseif ($exception instanceof FilePermissionsFailure) {
return response()->json(['message' => $exception->getMessage()], 500);
} elseif ($exception instanceof ThrottleRequestsException && $request->expectsJson()) {
return response()->json(['message'=>'Too many requests'], 429);
@@ -202,7 +204,7 @@ class Handler extends ExceptionHandler
return response()->json(['message' => $exception->getMessage()], 400);
} elseif ($exception instanceof StripeConnectFailure) {
return response()->json(['message' => $exception->getMessage()], 400);
- }
+ }
return parent::render($request, $exception);
}
diff --git a/app/Exceptions/PaymentFailed.php b/app/Exceptions/PaymentFailed.php
index b509df02fa77..108e1071f6dc 100644
--- a/app/Exceptions/PaymentFailed.php
+++ b/app/Exceptions/PaymentFailed.php
@@ -14,6 +14,7 @@ class PaymentFailed extends Exception
public function render($request)
{
if (auth()->guard('contact')->user() || ($request->has('cko-session-id') && $request->query('cko-session-id') )) {
+
return render('gateways.unsuccessful', [
'message' => $this->getMessage(),
'code' => $this->getCode(),
diff --git a/app/Exceptions/PaymentRefundFailed.php b/app/Exceptions/PaymentRefundFailed.php
index 94a6fe455e01..d2be5cadc8b2 100644
--- a/app/Exceptions/PaymentRefundFailed.php
+++ b/app/Exceptions/PaymentRefundFailed.php
@@ -30,12 +30,12 @@ class PaymentRefundFailed extends Exception
// $msg = 'Unable to refund the transaction';
$msg = ctrans('texts.warning_local_refund');
- if($this->getMessage() && strlen($this->getMessage()) >=1 )
+ if ($this->getMessage() && strlen($this->getMessage()) >= 1) {
$msg = $this->getMessage();
+ }
return response()->json([
- 'message' => $msg,
- ], 401);
-
+ 'message' => $msg,
+ ], 401);
}
}
diff --git a/app/Exceptions/SystemError.php b/app/Exceptions/SystemError.php
index f15cf8cf1333..03b0aaabe0c7 100644
--- a/app/Exceptions/SystemError.php
+++ b/app/Exceptions/SystemError.php
@@ -13,12 +13,9 @@ class SystemError extends Exception
public function render($request)
{
-
return view('errors.guest', [
'message' => $this->getMessage(),
'code' => $this->getCode(),
]);
-
-
}
}
diff --git a/app/Export/CSV/BaseExport.php b/app/Export/CSV/BaseExport.php
index 250bba51d10c..4d0271b767d3 100644
--- a/app/Export/CSV/BaseExport.php
+++ b/app/Export/CSV/BaseExport.php
@@ -15,28 +15,22 @@ use Illuminate\Support\Carbon;
class BaseExport
{
-
protected function addDateRange($query)
{
-
$date_range = $this->input['date_range'];
- if(array_key_exists('date_key', $this->input) && strlen($this->input['date_key']) > 1)
+ if (array_key_exists('date_key', $this->input) && strlen($this->input['date_key']) > 1) {
$this->date_key = $this->input['date_key'];
-
- try{
-
- $custom_start_date = Carbon::parse($this->input['start_date']);
- $custom_end_date = Carbon::parse($this->input['end_date']);
-
}
- catch(\Exception $e){
+ try {
+ $custom_start_date = Carbon::parse($this->input['start_date']);
+ $custom_end_date = Carbon::parse($this->input['end_date']);
+ } catch (\Exception $e) {
$custom_start_date = now()->startOfYear();
$custom_end_date = now();
-
}
-
+
switch ($date_range) {
case 'all':
@@ -61,26 +55,23 @@ class BaseExport
return $query->whereBetween($this->date_key, [now()->startOfYear(), now()])->orderBy($this->date_key, 'ASC');
}
-
}
protected function buildHeader() :array
{
-
$header = [];
- foreach($this->input['report_keys'] as $value){
+ foreach ($this->input['report_keys'] as $value) {
+ $key = array_search($value, $this->entity_keys);
- $key = array_search ($value, $this->entity_keys);
-
- $key = str_replace("item.", "", $key);
- $key = str_replace("invoice.", "", $key);
- $key = str_replace("client.", "", $key);
- $key = str_replace("contact.", "", $key);
+ $key = str_replace('item.', '', $key);
+ $key = str_replace('invoice.', '', $key);
+ $key = str_replace('client.', '', $key);
+ $key = str_replace('contact.', '', $key);
$header[] = ctrans("texts.{$key}");
}
return $header;
}
-}
\ No newline at end of file
+}
diff --git a/app/Export/CSV/ClientExport.php b/app/Export/CSV/ClientExport.php
index b4d4df64e67e..5ba69ed72622 100644
--- a/app/Export/CSV/ClientExport.php
+++ b/app/Export/CSV/ClientExport.php
@@ -17,9 +17,9 @@ use App\Models\Company;
use App\Transformers\ClientContactTransformer;
use App\Transformers\ClientTransformer;
use App\Utils\Ninja;
+use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\App;
use League\Csv\Writer;
-use Illuminate\Support\Carbon;
class ClientExport extends BaseExport
{
@@ -95,7 +95,6 @@ class ClientExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -105,8 +104,9 @@ class ClientExport extends BaseExport
//load the CSV document from a string
$this->csv = Writer::createFromString();
- if(count($this->input['report_keys']) == 0)
+ if (count($this->input['report_keys']) == 0) {
$this->input['report_keys'] = array_values($this->entity_keys);
+ }
//insert the header
$this->csv->insertOne($this->buildHeader());
@@ -114,69 +114,65 @@ class ClientExport extends BaseExport
$query = Client::query()->with('contacts')
->withTrashed()
->where('company_id', $this->company->id)
- ->where('is_deleted',0);
-
+ ->where('is_deleted', 0);
+
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($client){
- $this->csv->insertOne($this->buildRow($client));
- });
-
-
- return $this->csv->toString();
+ ->each(function ($client) {
+ $this->csv->insertOne($this->buildRow($client));
+ });
+ return $this->csv->toString();
}
private function buildRow(Client $client) :array
{
-
$transformed_contact = false;
$transformed_client = $this->client_transformer->transform($client);
- if($contact = $client->contacts()->first())
+ if ($contact = $client->contacts()->first()) {
$transformed_contact = $this->contact_transformer->transform($contact);
+ }
$entity = [];
- foreach(array_values($this->input['report_keys']) as $key){
+ foreach (array_values($this->input['report_keys']) as $key) {
+ $parts = explode('.', $key);
- $parts = explode(".",$key);
-
$keyval = array_search($key, $this->entity_keys);
- if($parts[0] == 'client' && array_key_exists($parts[1], $transformed_client)) {
+ if ($parts[0] == 'client' && array_key_exists($parts[1], $transformed_client)) {
$entity[$keyval] = $transformed_client[$parts[1]];
- }
- elseif($parts[0] == 'contact' && array_key_exists($parts[1], $transformed_contact)) {
+ } elseif ($parts[0] == 'contact' && array_key_exists($parts[1], $transformed_contact)) {
$entity[$keyval] = $transformed_contact[$parts[1]];
+ } else {
+ $entity[$keyval] = '';
}
- else
- $entity[$keyval] = "";
-
}
return $this->decorateAdvancedFields($client, $entity);
-
}
private function decorateAdvancedFields(Client $client, array $entity) :array
{
+ if (in_array('client.country_id', $this->input['report_keys'])) {
+ $entity['country'] = $client->country ? ctrans("texts.country_{$client->country->name}") : '';
+ }
- if(in_array('client.country_id', $this->input['report_keys']))
- $entity['country'] = $client->country ? ctrans("texts.country_{$client->country->name}") : "";
+ if (in_array('client.shipping_country_id', $this->input['report_keys'])) {
+ $entity['shipping_country'] = $client->shipping_country ? ctrans("texts.country_{$client->shipping_country->name}") : '';
+ }
- if(in_array('client.shipping_country_id', $this->input['report_keys']))
- $entity['shipping_country'] = $client->shipping_country ? ctrans("texts.country_{$client->shipping_country->name}") : "";
-
- if(in_array('client.currency', $this->input['report_keys']))
+ if (in_array('client.currency', $this->input['report_keys'])) {
$entity['currency'] = $client->currency() ? $client->currency()->code : $client->company->currency()->code;
+ }
- if(in_array('client.industry_id', $this->input['report_keys']))
- $entity['industry_id'] = $client->industry ? ctrans("texts.industry_{$client->industry->name}") : "";
+ if (in_array('client.industry_id', $this->input['report_keys'])) {
+ $entity['industry_id'] = $client->industry ? ctrans("texts.industry_{$client->industry->name}") : '';
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/ContactExport.php b/app/Export/CSV/ContactExport.php
index 1c938b187f46..a96974cba829 100644
--- a/app/Export/CSV/ContactExport.php
+++ b/app/Export/CSV/ContactExport.php
@@ -91,7 +91,6 @@ class ContactExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -101,8 +100,9 @@ class ContactExport extends BaseExport
//load the CSV document from a string
$this->csv = Writer::createFromString();
- if(count($this->input['report_keys']) == 0)
+ if (count($this->input['report_keys']) == 0) {
$this->input['report_keys'] = array_values($this->entity_keys);
+ }
//insert the header
$this->csv->insertOne($this->buildHeader());
@@ -112,19 +112,15 @@ class ContactExport extends BaseExport
$query = $this->addDateRange($query);
- $query->cursor()->each(function ($contact){
-
- $this->csv->insertOne($this->buildRow($contact));
-
+ $query->cursor()->each(function ($contact) {
+ $this->csv->insertOne($this->buildRow($contact));
});
- return $this->csv->toString();
-
+ return $this->csv->toString();
}
private function buildRow(ClientContact $contact) :array
{
-
$transformed_contact = false;
$transformed_client = $this->client_transformer->transform($contact->client);
@@ -132,41 +128,40 @@ class ContactExport extends BaseExport
$entity = [];
- foreach(array_values($this->input['report_keys']) as $key){
-
- $parts = explode(".",$key);
+ foreach (array_values($this->input['report_keys']) as $key) {
+ $parts = explode('.', $key);
$keyval = array_search($key, $this->entity_keys);
- if($parts[0] == 'client' && array_key_exists($parts[1], $transformed_client)) {
+ if ($parts[0] == 'client' && array_key_exists($parts[1], $transformed_client)) {
$entity[$keyval] = $transformed_client[$parts[1]];
- }
- elseif($parts[0] == 'contact' && array_key_exists($parts[1], $transformed_contact)) {
+ } elseif ($parts[0] == 'contact' && array_key_exists($parts[1], $transformed_contact)) {
$entity[$keyval] = $transformed_contact[$parts[1]];
+ } else {
+ $entity[$keyval] = '';
}
- else
- $entity[$keyval] = "";
}
return $this->decorateAdvancedFields($contact->client, $entity);
-
}
private function decorateAdvancedFields(Client $client, array $entity) :array
{
+ if (in_array('client.country_id', $this->input['report_keys'])) {
+ $entity['country'] = $client->country ? ctrans("texts.country_{$client->country->name}") : '';
+ }
- if(in_array('client.country_id', $this->input['report_keys']))
- $entity['country'] = $client->country ? ctrans("texts.country_{$client->country->name}") : "";
+ if (in_array('client.shipping_country_id', $this->input['report_keys'])) {
+ $entity['shipping_country'] = $client->shipping_country ? ctrans("texts.country_{$client->shipping_country->name}") : '';
+ }
- if(in_array('client.shipping_country_id', $this->input['report_keys']))
- $entity['shipping_country'] = $client->shipping_country ? ctrans("texts.country_{$client->shipping_country->name}") : "";
-
- if(in_array('client.currency', $this->input['report_keys']))
+ if (in_array('client.currency', $this->input['report_keys'])) {
$entity['currency'] = $client->currency() ? $client->currency()->code : $client->company->currency()->code;
+ }
- if(in_array('client.industry_id', $this->input['report_keys']))
- $entity['industry_id'] = $client->industry ? ctrans("texts.industry_{$client->industry->name}") : "";
+ if (in_array('client.industry_id', $this->input['report_keys'])) {
+ $entity['industry_id'] = $client->industry ? ctrans("texts.industry_{$client->industry->name}") : '';
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/CreditExport.php b/app/Export/CSV/CreditExport.php
index e28711bfe111..8a552a991300 100644
--- a/app/Export/CSV/CreditExport.php
+++ b/app/Export/CSV/CreditExport.php
@@ -65,7 +65,7 @@ class CreditExport extends BaseExport
'tax_rate3' => 'tax_rate3',
'terms' => 'terms',
'total_taxes' => 'total_taxes',
- 'currency' => 'currency'
+ 'currency' => 'currency',
];
private array $decorate_keys = [
@@ -84,7 +84,6 @@ class CreditExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -94,71 +93,69 @@ class CreditExport extends BaseExport
//load the CSV document from a string
$this->csv = Writer::createFromString();
- if(count($this->input['report_keys']) == 0)
+ if (count($this->input['report_keys']) == 0) {
$this->input['report_keys'] = array_values($this->entity_keys);
-
+ }
+
//insert the header
$this->csv->insertOne($this->buildHeader());
$query = Credit::query()
->withTrashed()
->with('client')->where('company_id', $this->company->id)
- ->where('is_deleted',0);
+ ->where('is_deleted', 0);
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($credit){
-
- $this->csv->insertOne($this->buildRow($credit));
-
- });
-
- return $this->csv->toString();
+ ->each(function ($credit) {
+ $this->csv->insertOne($this->buildRow($credit));
+ });
+ return $this->csv->toString();
}
private function buildRow(Credit $credit) :array
{
-
$transformed_credit = $this->credit_transformer->transform($credit);
$entity = [];
- foreach(array_values($this->input['report_keys']) as $key){
-
+ foreach (array_values($this->input['report_keys']) as $key) {
$keyval = array_search($key, $this->entity_keys);
- if(array_key_exists($key, $transformed_credit))
+ if (array_key_exists($key, $transformed_credit)) {
$entity[$keyval] = $transformed_credit[$key];
- else
+ } else {
$entity[$keyval] = '';
-
+ }
}
return $this->decorateAdvancedFields($credit, $entity);
-
}
private function decorateAdvancedFields(Credit $credit, array $entity) :array
{
+ if (in_array('country_id', $this->input['report_keys'])) {
+ $entity['country'] = $credit->client->country ? ctrans("texts.country_{$credit->client->country->name}") : '';
+ }
- if(in_array('country_id', $this->input['report_keys']))
- $entity['country'] = $credit->client->country ? ctrans("texts.country_{$credit->client->country->name}") : "";
+ if (in_array('currency_id', $this->input['report_keys'])) {
+ $entity['currency_id'] = $credit->client->currency() ? $credit->client->currency()->code : $invoice->company->currency()->code;
+ }
- if(in_array('currency_id', $this->input['report_keys']))
- $entity['currency_id'] = $credit->client->currency() ? $credit->client->currency()->code : $invoice->company->currency()->code;;
+ if (in_array('invoice_id', $this->input['report_keys'])) {
+ $entity['invoice'] = $credit->invoice ? $credit->invoice->number : '';
+ }
- if(in_array('invoice_id', $this->input['report_keys']))
- $entity['invoice'] = $credit->invoice ? $credit->invoice->number : "";
-
- if(in_array('client_id', $this->input['report_keys']))
+ if (in_array('client_id', $this->input['report_keys'])) {
$entity['client'] = $credit->client->present()->name();
+ }
- if(in_array('status_id',$this->input['report_keys']))
+ if (in_array('status_id', $this->input['report_keys'])) {
$entity['status'] = $credit->stringStatus($credit->status_id);
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/DocumentExport.php b/app/Export/CSV/DocumentExport.php
index b70a854af7bd..dae5f6509c74 100644
--- a/app/Export/CSV/DocumentExport.php
+++ b/app/Export/CSV/DocumentExport.php
@@ -52,7 +52,6 @@ class DocumentExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -62,8 +61,9 @@ class DocumentExport extends BaseExport
//load the CSV document from a string
$this->csv = Writer::createFromString();
- if(count($this->input['report_keys']) == 0)
+ if (count($this->input['report_keys']) == 0) {
$this->input['report_keys'] = array_values($this->entity_keys);
+ }
//insert the header
$this->csv->insertOne($this->buildHeader());
@@ -73,47 +73,41 @@ class DocumentExport extends BaseExport
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($entity){
-
- $this->csv->insertOne($this->buildRow($entity));
-
- });
-
- return $this->csv->toString();
+ ->each(function ($entity) {
+ $this->csv->insertOne($this->buildRow($entity));
+ });
+ return $this->csv->toString();
}
private function buildRow(Document $document) :array
{
-
$transformed_entity = $this->entity_transformer->transform($document);
$entity = [];
- foreach(array_values($this->input['report_keys']) as $key){
-
+ foreach (array_values($this->input['report_keys']) as $key) {
$keyval = array_search($key, $this->entity_keys);
- if(array_key_exists($key, $transformed_entity))
+ if (array_key_exists($key, $transformed_entity)) {
$entity[$keyval] = $transformed_entity[$key];
- else
- $entity[$keyval] = '';
+ } else {
+ $entity[$keyval] = '';
+ }
}
return $this->decorateAdvancedFields($document, $entity);
-
}
private function decorateAdvancedFields(Document $document, array $entity) :array
{
-
- if(in_array('record_type', $this->input['report_keys']))
+ if (in_array('record_type', $this->input['report_keys'])) {
$entity['record_type'] = class_basename($document->documentable);
+ }
// if(in_array('record_name', $this->input['report_keys']))
// $entity['record_name'] = $document->hashed_id;
return $entity;
}
-
}
diff --git a/app/Export/CSV/ExpenseExport.php b/app/Export/CSV/ExpenseExport.php
index d4ccaaa23674..dced738d742c 100644
--- a/app/Export/CSV/ExpenseExport.php
+++ b/app/Export/CSV/ExpenseExport.php
@@ -82,7 +82,6 @@ class ExpenseExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -92,8 +91,9 @@ class ExpenseExport extends BaseExport
//load the CSV document from a string
$this->csv = Writer::createFromString();
- if(count($this->input['report_keys']) == 0)
+ if (count($this->input['report_keys']) == 0) {
$this->input['report_keys'] = array_values($this->entity_keys);
+ }
//insert the header
$this->csv->insertOne($this->buildHeader());
@@ -102,69 +102,67 @@ class ExpenseExport extends BaseExport
->with('client')
->withTrashed()
->where('company_id', $this->company->id)
- ->where('is_deleted',0);
+ ->where('is_deleted', 0);
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($expense){
-
- $this->csv->insertOne($this->buildRow($expense));
-
- });
-
-
- return $this->csv->toString();
+ ->each(function ($expense) {
+ $this->csv->insertOne($this->buildRow($expense));
+ });
+ return $this->csv->toString();
}
private function buildRow(Expense $expense) :array
{
-
$transformed_expense = $this->expense_transformer->transform($expense);
$entity = [];
- foreach(array_values($this->input['report_keys']) as $key){
-
+ foreach (array_values($this->input['report_keys']) as $key) {
$keyval = array_search($key, $this->entity_keys);
- if(array_key_exists($key, $transformed_expense))
+ if (array_key_exists($key, $transformed_expense)) {
$entity[$keyval] = $transformed_expense[$key];
- else
+ } else {
$entity[$keyval] = '';
-
+ }
}
return $this->decorateAdvancedFields($expense, $entity);
-
}
private function decorateAdvancedFields(Expense $expense, array $entity) :array
{
- if(in_array('currency_id', $this->input['report_keys']))
- $entity['currency'] = $expense->currency ? $expense->currency->code : "";
+ if (in_array('currency_id', $this->input['report_keys'])) {
+ $entity['currency'] = $expense->currency ? $expense->currency->code : '';
+ }
- if(in_array('client_id', $this->input['report_keys']))
- $entity['client'] = $expense->client ? $expense->client->present()->name() : "";
+ if (in_array('client_id', $this->input['report_keys'])) {
+ $entity['client'] = $expense->client ? $expense->client->present()->name() : '';
+ }
- if(in_array('invoice_id', $this->input['report_keys']))
- $entity['invoice'] = $expense->invoice ? $expense->invoice->number : "";
+ if (in_array('invoice_id', $this->input['report_keys'])) {
+ $entity['invoice'] = $expense->invoice ? $expense->invoice->number : '';
+ }
- if(in_array('category_id', $this->input['report_keys']))
- $entity['category'] = $expense->category ? $expense->category->name : "";
+ if (in_array('category_id', $this->input['report_keys'])) {
+ $entity['category'] = $expense->category ? $expense->category->name : '';
+ }
- if(in_array('vendor_id', $this->input['report_keys']))
- $entity['vendor'] = $expense->vendor ? $expense->vendor->name : "";
+ if (in_array('vendor_id', $this->input['report_keys'])) {
+ $entity['vendor'] = $expense->vendor ? $expense->vendor->name : '';
+ }
- if(in_array('payment_type_id', $this->input['report_keys']))
- $entity['payment_type'] = $expense->payment_type ? $expense->payment_type->name : "";
-
- if(in_array('project_id', $this->input['report_keys']))
- $entity['project'] = $expense->project ? $expense->project->name : "";
+ if (in_array('payment_type_id', $this->input['report_keys'])) {
+ $entity['payment_type'] = $expense->payment_type ? $expense->payment_type->name : '';
+ }
+ if (in_array('project_id', $this->input['report_keys'])) {
+ $entity['project'] = $expense->project ? $expense->project->name : '';
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/InvoiceExport.php b/app/Export/CSV/InvoiceExport.php
index 76ecf16a18c4..be13d99c3a9f 100644
--- a/app/Export/CSV/InvoiceExport.php
+++ b/app/Export/CSV/InvoiceExport.php
@@ -63,7 +63,7 @@ class InvoiceExport extends BaseExport
'tax_rate3' => 'tax_rate3',
'terms' => 'terms',
'total_taxes' => 'total_taxes',
- 'currency_id' => 'currency_id'
+ 'currency_id' => 'currency_id',
];
private array $decorate_keys = [
@@ -84,7 +84,6 @@ class InvoiceExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -94,9 +93,10 @@ class InvoiceExport extends BaseExport
//load the CSV document from a string
$this->csv = Writer::createFromString();
- if(count($this->input['report_keys']) == 0)
+ if (count($this->input['report_keys']) == 0) {
$this->input['report_keys'] = array_values($this->entity_keys);
-
+ }
+
//insert the header
$this->csv->insertOne($this->buildHeader());
@@ -104,57 +104,55 @@ class InvoiceExport extends BaseExport
->withTrashed()
->with('client')
->where('company_id', $this->company->id)
- ->where('is_deleted',0);
+ ->where('is_deleted', 0);
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($invoice){
-
- $this->csv->insertOne($this->buildRow($invoice));
-
- });
-
- return $this->csv->toString();
+ ->each(function ($invoice) {
+ $this->csv->insertOne($this->buildRow($invoice));
+ });
+ return $this->csv->toString();
}
private function buildRow(Invoice $invoice) :array
{
-
$transformed_invoice = $this->invoice_transformer->transform($invoice);
$entity = [];
- foreach(array_values($this->input['report_keys']) as $key){
-
+ foreach (array_values($this->input['report_keys']) as $key) {
$keyval = array_search($key, $this->entity_keys);
- if(array_key_exists($key, $transformed_invoice))
+ if (array_key_exists($key, $transformed_invoice)) {
$entity[$keyval] = $transformed_invoice[$key];
- else
+ } else {
$entity[$keyval] = '';
+ }
}
return $this->decorateAdvancedFields($invoice, $entity);
-
}
private function decorateAdvancedFields(Invoice $invoice, array $entity) :array
{
- if(in_array('country_id', $this->input['report_keys']))
- $entity['country'] = $invoice->client->country ? ctrans("texts.country_{$invoice->client->country->name}") : "";
+ if (in_array('country_id', $this->input['report_keys'])) {
+ $entity['country'] = $invoice->client->country ? ctrans("texts.country_{$invoice->client->country->name}") : '';
+ }
- if(in_array('currency_id', $this->input['report_keys']))
+ if (in_array('currency_id', $this->input['report_keys'])) {
$entity['currency_id'] = $invoice->client->currency() ? $invoice->client->currency()->code : $invoice->company->currency()->code;
+ }
- if(in_array('client_id', $this->input['report_keys']))
+ if (in_array('client_id', $this->input['report_keys'])) {
$entity['client'] = $invoice->client->present()->name();
+ }
- if(in_array('status_id',$this->input['report_keys']))
+ if (in_array('status_id', $this->input['report_keys'])) {
$entity['status'] = $invoice->stringStatus($invoice->status_id);
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/PaymentExport.php b/app/Export/CSV/PaymentExport.php
index 0b5b4f309772..ccd49d84e109 100644
--- a/app/Export/CSV/PaymentExport.php
+++ b/app/Export/CSV/PaymentExport.php
@@ -73,7 +73,6 @@ class PaymentExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -83,8 +82,9 @@ class PaymentExport extends BaseExport
//load the CSV document from a string
$this->csv = Writer::createFromString();
- if(count($this->input['report_keys']) == 0)
+ if (count($this->input['report_keys']) == 0) {
$this->input['report_keys'] = array_values($this->entity_keys);
+ }
//insert the header
$this->csv->insertOne($this->buildHeader());
@@ -94,66 +94,66 @@ class PaymentExport extends BaseExport
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($entity){
-
- $this->csv->insertOne($this->buildRow($entity));
-
- });
-
- return $this->csv->toString();
+ ->each(function ($entity) {
+ $this->csv->insertOne($this->buildRow($entity));
+ });
+ return $this->csv->toString();
}
private function buildRow(Payment $payment) :array
{
-
$transformed_entity = $this->entity_transformer->transform($payment);
$entity = [];
- foreach(array_values($this->input['report_keys']) as $key){
-
+ foreach (array_values($this->input['report_keys']) as $key) {
$keyval = array_search($key, $this->entity_keys);
- if(array_key_exists($key, $transformed_entity))
+ if (array_key_exists($key, $transformed_entity)) {
$entity[$keyval] = $transformed_entity[$key];
- else
+ } else {
$entity[$keyval] = '';
-
+ }
}
return $this->decorateAdvancedFields($payment, $entity);
-
}
private function decorateAdvancedFields(Payment $payment, array $entity) :array
{
-
- if(in_array('status_id', $this->input['report_keys']))
+ if (in_array('status_id', $this->input['report_keys'])) {
$entity['status'] = $payment->stringStatus($payment->status_id);
+ }
- if(in_array('vendor_id', $this->input['report_keys']))
+ if (in_array('vendor_id', $this->input['report_keys'])) {
$entity['vendor'] = $payment->vendor()->exists() ? $payment->vendor->name : '';
+ }
- if(in_array('project_id', $this->input['report_keys']))
+ if (in_array('project_id', $this->input['report_keys'])) {
$entity['project'] = $payment->project()->exists() ? $payment->project->name : '';
+ }
- if(in_array('currency_id', $this->input['report_keys']))
+ if (in_array('currency_id', $this->input['report_keys'])) {
$entity['currency'] = $payment->currency()->exists() ? $payment->currency->code : '';
+ }
- if(in_array('exchange_currency_id', $this->input['report_keys']))
+ if (in_array('exchange_currency_id', $this->input['report_keys'])) {
$entity['exchange_currency'] = $payment->exchange_currency()->exists() ? $payment->exchange_currency->code : '';
+ }
- if(in_array('client_id', $this->input['report_keys']))
+ if (in_array('client_id', $this->input['report_keys'])) {
$entity['client'] = $payment->client->present()->name();
+ }
- if(in_array('type_id', $this->input['report_keys']))
+ if (in_array('type_id', $this->input['report_keys'])) {
$entity['type'] = $payment->translatedType();
+ }
- if(in_array('gateway_type_id', $this->input['report_keys']))
- $entity['gateway'] = $payment->gateway_type ? $payment->gateway_type->name : "Unknown Type";
+ if (in_array('gateway_type_id', $this->input['report_keys'])) {
+ $entity['gateway'] = $payment->gateway_type ? $payment->gateway_type->name : 'Unknown Type';
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/ProductExport.php b/app/Export/CSV/ProductExport.php
index 9523f8ad050a..ff96841951d0 100644
--- a/app/Export/CSV/ProductExport.php
+++ b/app/Export/CSV/ProductExport.php
@@ -66,7 +66,6 @@ class ProductExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -76,8 +75,9 @@ class ProductExport extends BaseExport
//load the CSV document from a string
$this->csv = Writer::createFromString();
- if(count($this->input['report_keys']) == 0)
+ if (count($this->input['report_keys']) == 0) {
$this->input['report_keys'] = array_values($this->entity_keys);
+ }
//insert the header
$this->csv->insertOne($this->buildHeader());
@@ -87,49 +87,42 @@ class ProductExport extends BaseExport
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($entity){
-
- $this->csv->insertOne($this->buildRow($entity));
-
- });
-
- return $this->csv->toString();
+ ->each(function ($entity) {
+ $this->csv->insertOne($this->buildRow($entity));
+ });
+ return $this->csv->toString();
}
private function buildRow(Product $product) :array
{
-
$transformed_entity = $this->entity_transformer->transform($product);
$entity = [];
- foreach(array_values($this->input['report_keys']) as $key){
-
+ foreach (array_values($this->input['report_keys']) as $key) {
$keyval = array_search($key, $this->entity_keys);
- if(array_key_exists($key, $transformed_entity))
+ if (array_key_exists($key, $transformed_entity)) {
$entity[$keyval] = $transformed_entity[$key];
- else
+ } else {
$entity[$keyval] = '';
-
-
+ }
}
return $this->decorateAdvancedFields($product, $entity);
-
}
private function decorateAdvancedFields(Product $product, array $entity) :array
{
-
- if(in_array('vendor_id', $this->input['report_keys']))
+ if (in_array('vendor_id', $this->input['report_keys'])) {
$entity['vendor'] = $product->vendor()->exists() ? $product->vendor->name : '';
+ }
- if(array_key_exists('project_id', $this->input['report_keys']))
+ if (array_key_exists('project_id', $this->input['report_keys'])) {
$entity['project'] = $product->project()->exists() ? $product->project->name : '';
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/QuoteExport.php b/app/Export/CSV/QuoteExport.php
index fe1dff206eb6..a48f4c4ef4a8 100644
--- a/app/Export/CSV/QuoteExport.php
+++ b/app/Export/CSV/QuoteExport.php
@@ -70,7 +70,7 @@ class QuoteExport extends BaseExport
private array $decorate_keys = [
'client',
'currency',
- 'invoice'
+ 'invoice',
];
public function __construct(Company $company, array $input)
@@ -82,7 +82,6 @@ class QuoteExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -92,8 +91,9 @@ class QuoteExport extends BaseExport
//load the CSV document from a string
$this->csv = Writer::createFromString();
- if(count($this->input['report_keys']) == 0)
+ if (count($this->input['report_keys']) == 0) {
$this->input['report_keys'] = array_values($this->entity_keys);
+ }
//insert the header
$this->csv->insertOne($this->buildHeader());
@@ -101,58 +101,55 @@ class QuoteExport extends BaseExport
$query = Quote::query()
->with('client')
->where('company_id', $this->company->id)
- ->where('is_deleted',0);
+ ->where('is_deleted', 0);
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($quote){
-
- $this->csv->insertOne($this->buildRow($quote));
-
- });
-
-
- return $this->csv->toString();
+ ->each(function ($quote) {
+ $this->csv->insertOne($this->buildRow($quote));
+ });
+ return $this->csv->toString();
}
private function buildRow(Quote $quote) :array
{
-
$transformed_quote = $this->quote_transformer->transform($quote);
$entity = [];
- foreach(array_values($this->input['report_keys']) as $key){
-
+ foreach (array_values($this->input['report_keys']) as $key) {
$keyval = array_search($key, $this->entity_keys);
- if(array_key_exists($key, $transformed_quote))
+ if (array_key_exists($key, $transformed_quote)) {
$entity[$keyval] = $transformed_quote[$key];
- else
+ } else {
$entity[$keyval] = '';
+ }
}
return $this->decorateAdvancedFields($quote, $entity);
-
}
private function decorateAdvancedFields(Quote $quote, array $entity) :array
{
- if(in_array('currency_id', $this->input['report_keys']))
+ if (in_array('currency_id', $this->input['report_keys'])) {
$entity['currency'] = $quote->client->currency()->code;
+ }
- if(in_array('client_id', $this->input['report_keys']))
+ if (in_array('client_id', $this->input['report_keys'])) {
$entity['client'] = $quote->client->present()->name();
+ }
- if(in_array('status_id',$this->input['report_keys']))
+ if (in_array('status_id', $this->input['report_keys'])) {
$entity['status'] = $quote->stringStatus($quote->status_id);
+ }
- if(in_array('invoice_id', $this->input['report_keys']))
- $entity['invoice'] = $quote->invoice ? $quote->invoice->number : "";
+ if (in_array('invoice_id', $this->input['report_keys'])) {
+ $entity['invoice'] = $quote->invoice ? $quote->invoice->number : '';
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/QuoteItemExport.php b/app/Export/CSV/QuoteItemExport.php
index ad1ded90ca73..e89d56311601 100644
--- a/app/Export/CSV/QuoteItemExport.php
+++ b/app/Export/CSV/QuoteItemExport.php
@@ -85,7 +85,6 @@ class QuoteItemExport extends BaseExport
'custom_value4' => 'item.custom_value4',
];
-
private array $decorate_keys = [
'client',
'currency',
@@ -100,7 +99,6 @@ class QuoteItemExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -110,28 +108,25 @@ class QuoteItemExport extends BaseExport
//load the CSV document from a string
$this->csv = Writer::createFromString();
- if(count($this->input['report_keys']) == 0)
+ if (count($this->input['report_keys']) == 0) {
$this->input['report_keys'] = array_values($this->entity_keys);
-
+ }
//insert the header
$this->csv->insertOne($this->buildHeader());
$query = Quote::query()
->with('client')->where('company_id', $this->company->id)
- ->where('is_deleted',0);
+ ->where('is_deleted', 0);
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($quote){
-
+ ->each(function ($quote) {
$this->iterateItems($quote);
+ });
- });
-
- return $this->csv->toString();
-
+ return $this->csv->toString();
}
private function iterateItems(Quote $quote)
@@ -140,76 +135,68 @@ class QuoteItemExport extends BaseExport
$transformed_items = [];
- foreach($quote->line_items as $item)
- {
+ foreach ($quote->line_items as $item) {
$item_array = [];
- foreach(array_values($this->input['report_keys']) as $key){
-
- if(str_contains($key, "item.")){
-
- $key = str_replace("item.", "", $key);
+ foreach (array_values($this->input['report_keys']) as $key) {
+ if (str_contains($key, 'item.')) {
+ $key = str_replace('item.', '', $key);
$item_array[$key] = $item->{$key};
}
-
}
$entity = [];
- foreach(array_values($this->input['report_keys']) as $key)
- {
+ foreach (array_values($this->input['report_keys']) as $key) {
$keyval = array_search($key, $this->entity_keys);
- if(array_key_exists($key, $transformed_items))
+ if (array_key_exists($key, $transformed_items)) {
$entity[$keyval] = $transformed_items[$key];
- else
- $entity[$keyval] = "";
+ } else {
+ $entity[$keyval] = '';
+ }
}
-
$transformed_items = array_merge($transformed_quote, $item_array);
$entity = $this->decorateAdvancedFields($quote, $transformed_items);
- $this->csv->insertOne($entity);
-
+ $this->csv->insertOne($entity);
}
-
}
private function buildRow(Quote $quote) :array
{
-
$transformed_quote = $this->quote_transformer->transform($quote);
$entity = [];
- foreach(array_values($this->input['report_keys']) as $key){
-
+ foreach (array_values($this->input['report_keys']) as $key) {
$keyval = array_search($key, $this->entity_keys);
- if(array_key_exists($key, $transformed_quote))
+ if (array_key_exists($key, $transformed_quote)) {
$entity[$keyval] = $transformed_quote[$key];
- else
- $entity[$keyval] = "";
-
+ } else {
+ $entity[$keyval] = '';
+ }
}
return $this->decorateAdvancedFields($quote, $entity);
-
}
private function decorateAdvancedFields(Quote $quote, array $entity) :array
{
- if(in_array('currency_id', $this->input['report_keys']))
+ if (in_array('currency_id', $this->input['report_keys'])) {
$entity['currency'] = $quote->client->currency() ? $quote->client->currency()->code : $quote->company->currency()->code;
+ }
- if(in_array('client_id', $this->input['report_keys']))
+ if (in_array('client_id', $this->input['report_keys'])) {
$entity['client'] = $quote->client->present()->name();
+ }
- if(in_array('status_id', $this->input['report_keys']))
+ if (in_array('status_id', $this->input['report_keys'])) {
$entity['status'] = $quote->stringStatus($quote->status_id);
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/RecurringInvoiceExport.php b/app/Export/CSV/RecurringInvoiceExport.php
index 47232ebcfa12..30accbd22511 100644
--- a/app/Export/CSV/RecurringInvoiceExport.php
+++ b/app/Export/CSV/RecurringInvoiceExport.php
@@ -74,7 +74,7 @@ class RecurringInvoiceExport extends BaseExport
'currency',
'status',
'vendor',
- 'project'
+ 'project',
];
public function __construct(Company $company, array $input)
@@ -86,7 +86,6 @@ class RecurringInvoiceExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -96,8 +95,9 @@ class RecurringInvoiceExport extends BaseExport
//load the CSV document from a string
$this->csv = Writer::createFromString();
- if(count($this->input['report_keys']) == 0)
+ if (count($this->input['report_keys']) == 0) {
$this->input['report_keys'] = array_values($this->entity_keys);
+ }
//insert the header
$this->csv->insertOne($this->buildHeader());
@@ -105,64 +105,63 @@ class RecurringInvoiceExport extends BaseExport
$query = RecurringInvoice::query()
->withTrashed()
->with('client')->where('company_id', $this->company->id)
- ->where('is_deleted',0);
+ ->where('is_deleted', 0);
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($invoice){
-
- $this->csv->insertOne($this->buildRow($invoice));
-
- });
-
- return $this->csv->toString();
+ ->each(function ($invoice) {
+ $this->csv->insertOne($this->buildRow($invoice));
+ });
+ return $this->csv->toString();
}
private function buildRow(RecurringInvoice $invoice) :array
{
-
$transformed_invoice = $this->invoice_transformer->transform($invoice);
$entity = [];
- foreach(array_values($this->input['report_keys']) as $key){
-
+ foreach (array_values($this->input['report_keys']) as $key) {
$keyval = array_search($key, $this->entity_keys);
- if(array_key_exists($key, $transformed_invoice))
+ if (array_key_exists($key, $transformed_invoice)) {
$entity[$keyval] = $transformed_invoice[$key];
- else
+ } else {
$entity[$keyval] = '';
-
+ }
}
return $this->decorateAdvancedFields($invoice, $entity);
-
}
private function decorateAdvancedFields(RecurringInvoice $invoice, array $entity) :array
{
- if(in_array('country_id', $this->input['report_keys']))
- $entity['country'] = $invoice->client->country ? ctrans("texts.country_{$invoice->client->country->name}") : "";
+ if (in_array('country_id', $this->input['report_keys'])) {
+ $entity['country'] = $invoice->client->country ? ctrans("texts.country_{$invoice->client->country->name}") : '';
+ }
- if(in_array('currency_id', $this->input['report_keys']))
+ if (in_array('currency_id', $this->input['report_keys'])) {
$entity['currency'] = $invoice->client->currency() ? $invoice->client->currency()->code : $invoice->company->currency()->code;
+ }
- if(in_array('client_id', $this->input['report_keys']))
+ if (in_array('client_id', $this->input['report_keys'])) {
$entity['client'] = $invoice->client->present()->name();
+ }
- if(in_array('status_id',$this->input['report_keys']))
+ if (in_array('status_id', $this->input['report_keys'])) {
$entity['status'] = $invoice->stringStatus($invoice->status_id);
+ }
- if(in_array('project_id',$this->input['report_keys']))
- $entity['project'] = $invoice->project ? $invoice->project->name : "";
+ if (in_array('project_id', $this->input['report_keys'])) {
+ $entity['project'] = $invoice->project ? $invoice->project->name : '';
+ }
- if(in_array('vendor_id',$this->input['report_keys']))
- $entity['vendor'] = $invoice->vendor ? $invoice->vendor->name : "";
+ if (in_array('vendor_id', $this->input['report_keys'])) {
+ $entity['vendor'] = $invoice->vendor ? $invoice->vendor->name : '';
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/TaskExport.php b/app/Export/CSV/TaskExport.php
index f700c8c83063..7ee9007f520c 100644
--- a/app/Export/CSV/TaskExport.php
+++ b/app/Export/CSV/TaskExport.php
@@ -71,7 +71,6 @@ class TaskExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -79,15 +78,15 @@ class TaskExport extends BaseExport
$t->replace(Ninja::transformTranslations($this->company->settings));
$this->date_format = DateFormat::find($this->company->settings->date_format_id)->format;
-
+
//load the CSV document from a string
$this->csv = Writer::createFromString();
-
+
ksort($this->entity_keys);
- if(count($this->input['report_keys']) == 0)
+ if (count($this->input['report_keys']) == 0) {
$this->input['report_keys'] = array_values($this->entity_keys);
-
+ }
//insert the header
$this->csv->insertOne($this->buildHeader());
@@ -97,59 +96,50 @@ class TaskExport extends BaseExport
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($entity){
-
- $this->buildRow($entity);
-
- });
-
- return $this->csv->toString();
+ ->each(function ($entity) {
+ $this->buildRow($entity);
+ });
+ return $this->csv->toString();
}
- private function buildRow(Task $task)
+ private function buildRow(Task $task)
{
-
$entity = [];
$transformed_entity = $this->entity_transformer->transform($task);
- if(is_null($task->time_log) || (is_array(json_decode($task->time_log,1)) && count(json_decode($task->time_log,1)) == 0)){
-
- foreach(array_values($this->input['report_keys']) as $key){
-
+ if (is_null($task->time_log) || (is_array(json_decode($task->time_log, 1)) && count(json_decode($task->time_log, 1)) == 0)) {
+ foreach (array_values($this->input['report_keys']) as $key) {
$keyval = array_search($key, $this->entity_keys);
- if(array_key_exists($key, $transformed_entity))
+ if (array_key_exists($key, $transformed_entity)) {
$entity[$keyval] = $transformed_entity[$key];
- else
- $entity[$keyval] = '';
+ } else {
+ $entity[$keyval] = '';
+ }
}
- $entity['start_date'] = "";
- $entity['end_date'] = "";
- $entity['duration'] = "";
+ $entity['start_date'] = '';
+ $entity['end_date'] = '';
+ $entity['duration'] = '';
$entity = $this->decorateAdvancedFields($task, $entity);
ksort($entity);
$this->csv->insertOne($entity);
-
- }
- elseif(is_array(json_decode($task->time_log,1)) && count(json_decode($task->time_log,1)) > 0) {
-
- foreach(array_values($this->input['report_keys']) as $key){
-
+ } elseif (is_array(json_decode($task->time_log, 1)) && count(json_decode($task->time_log, 1)) > 0) {
+ foreach (array_values($this->input['report_keys']) as $key) {
$keyval = array_search($key, $this->entity_keys);
- if(array_key_exists($key, $transformed_entity))
+ if (array_key_exists($key, $transformed_entity)) {
$entity[$keyval] = $transformed_entity[$key];
- else
- $entity[$keyval] = '';
+ } else {
+ $entity[$keyval] = '';
+ }
}
$this->iterateLogs($task, $entity);
}
-
}
private function iterateLogs(Task $task, array $entity)
@@ -157,48 +147,51 @@ class TaskExport extends BaseExport
$timezone = Timezone::find($task->company->settings->timezone_id);
$timezone_name = 'US/Eastern';
- if($timezone)
+ if ($timezone) {
$timezone_name = $timezone->name;
+ }
- $logs = json_decode($task->time_log,1);
-
- $date_format_default = "Y-m-d";
+ $logs = json_decode($task->time_log, 1);
+
+ $date_format_default = 'Y-m-d';
$date_format = DateFormat::find($task->company->settings->date_format_id);
- if($date_format)
+ if ($date_format) {
$date_format_default = $date_format->format;
+ }
- foreach($logs as $key => $item)
- {
-
- if(in_array("start_date", $this->input['report_keys'])){
+ foreach ($logs as $key => $item) {
+ if (in_array('start_date', $this->input['report_keys'])) {
$entity['start_date'] = Carbon::createFromTimeStamp($item[0])->setTimezone($timezone_name)->format($date_format_default);
}
- if(in_array("end_date", $this->input['report_keys']) && $item[1] > 0){
+ if (in_array('end_date', $this->input['report_keys']) && $item[1] > 0) {
$entity['end_date'] = Carbon::createFromTimeStamp($item[1])->setTimezone($timezone_name)->format($date_format_default);
}
- if(in_array("end_date", $this->input['report_keys']) && $item[1] == 0){
+ if (in_array('end_date', $this->input['report_keys']) && $item[1] == 0) {
$entity['end_date'] = ctrans('texts.is_running');
}
- if(in_array("duration", $this->input['report_keys'])){
+ if (in_array('duration', $this->input['report_keys'])) {
$entity['duration'] = $task->calcDuration();
}
- if(!array_key_exists('duration', $entity))
- $entity['duration'] = "";
+ if (! array_key_exists('duration', $entity)) {
+ $entity['duration'] = '';
+ }
- if(!array_key_exists('start_date', $entity))
- $entity['start_date'] = "";
+ if (! array_key_exists('start_date', $entity)) {
+ $entity['start_date'] = '';
+ }
- if(!array_key_exists('end_date', $entity))
- $entity['end_date'] = "";
+ if (! array_key_exists('end_date', $entity)) {
+ $entity['end_date'] = '';
+ }
$entity = $this->decorateAdvancedFields($task, $entity);
-
+
ksort($entity);
$this->csv->insertOne($entity);
@@ -206,25 +199,26 @@ class TaskExport extends BaseExport
unset($entity['end_date']);
unset($entity['duration']);
}
-
}
private function decorateAdvancedFields(Task $task, array $entity) :array
{
-
- if(in_array('status_id', $this->input['report_keys']))
+ if (in_array('status_id', $this->input['report_keys'])) {
$entity['status'] = $task->status()->exists() ? $task->status->name : '';
+ }
- if(in_array('project_id', $this->input['report_keys']))
+ if (in_array('project_id', $this->input['report_keys'])) {
$entity['project'] = $task->project()->exists() ? $task->project->name : '';
+ }
- if(in_array('client_id', $this->input['report_keys']))
- $entity['client'] = $task->client ? $task->client->present()->name() : "";
+ if (in_array('client_id', $this->input['report_keys'])) {
+ $entity['client'] = $task->client ? $task->client->present()->name() : '';
+ }
- if(in_array('invoice_id', $this->input['report_keys']))
- $entity['invoice'] = $task->invoice ? $task->invoice->number : "";
+ if (in_array('invoice_id', $this->input['report_keys'])) {
+ $entity['invoice'] = $task->invoice ? $task->invoice->number : '';
+ }
return $entity;
}
-
}
diff --git a/app/Factory/ClientGatewayTokenFactory.php b/app/Factory/ClientGatewayTokenFactory.php
index fa46b327b020..0b3196ef4b73 100644
--- a/app/Factory/ClientGatewayTokenFactory.php
+++ b/app/Factory/ClientGatewayTokenFactory.php
@@ -25,7 +25,7 @@ class ClientGatewayTokenFactory
$client_gateway_token->is_deleted = false;
$client_gateway_token->token = '';
$client_gateway_token->routing_number = '';
-
+
return $client_gateway_token;
}
}
diff --git a/app/Factory/CloneQuoteToInvoiceFactory.php b/app/Factory/CloneQuoteToInvoiceFactory.php
index 03d057987a99..9cb03ff22c83 100644
--- a/app/Factory/CloneQuoteToInvoiceFactory.php
+++ b/app/Factory/CloneQuoteToInvoiceFactory.php
@@ -28,11 +28,12 @@ class CloneQuoteToInvoiceFactory
unset($quote_array['invoice_id']);
unset($quote_array['id']);
unset($quote_array['invitations']);
-
+
//preserve terms if they exist on Quotes
//if(array_key_exists('terms', $quote_array) && strlen($quote_array['terms']) < 2)
- if(!$quote->company->use_quote_terms_on_conversion)
+ if (! $quote->company->use_quote_terms_on_conversion) {
unset($quote_array['terms']);
+ }
// unset($quote_array['public_notes']);
unset($quote_array['footer']);
diff --git a/app/Factory/CompanyFactory.php b/app/Factory/CompanyFactory.php
index e1a21a92ad04..bfb04daf1bc5 100644
--- a/app/Factory/CompanyFactory.php
+++ b/app/Factory/CompanyFactory.php
@@ -37,12 +37,13 @@ class CompanyFactory
//$company->custom_fields = (object) ['invoice1' => '1', 'invoice2' => '2', 'client1'=>'3'];
$company->custom_fields = (object) [];
$company->client_registration_fields = ClientRegistrationFields::generate();
-
- if(Ninja::isHosted())
+
+ if (Ninja::isHosted()) {
$company->subdomain = MultiDB::randomSubdomainGenerator();
- else
+ } else {
$company->subdomain = '';
-
+ }
+
$company->enabled_modules = config('ninja.enabled_modules'); //32767;//8191; //4095
$company->default_password_timeout = 1800000;
$company->markdown_email_enabled = false;
diff --git a/app/Factory/CompanyGatewayFactory.php b/app/Factory/CompanyGatewayFactory.php
index d3030484d300..8f4743072cbe 100644
--- a/app/Factory/CompanyGatewayFactory.php
+++ b/app/Factory/CompanyGatewayFactory.php
@@ -24,7 +24,7 @@ class CompanyGatewayFactory
$company_gateway->require_billing_address = false;
$company_gateway->require_shipping_address = false;
$company_gateway->config = encrypt(json_encode(new \stdClass));
-
+
return $company_gateway;
}
}
diff --git a/app/Factory/ExpenseCategoryFactory.php b/app/Factory/ExpenseCategoryFactory.php
index 88a702ca5fcf..f39da086d2a8 100644
--- a/app/Factory/ExpenseCategoryFactory.php
+++ b/app/Factory/ExpenseCategoryFactory.php
@@ -23,7 +23,7 @@ class ExpenseCategoryFactory
$expense->name = '';
$expense->is_deleted = false;
$expense->color = '';
-
+
return $expense;
}
}
diff --git a/app/Factory/ExpenseFactory.php b/app/Factory/ExpenseFactory.php
index 997412ef1b5f..0ca0e0e1ba18 100644
--- a/app/Factory/ExpenseFactory.php
+++ b/app/Factory/ExpenseFactory.php
@@ -42,7 +42,7 @@ class ExpenseFactory
$expense->tax_amount1 = 0;
$expense->tax_amount2 = 0;
$expense->tax_amount3 = 0;
-
+
return $expense;
}
}
diff --git a/app/Factory/GroupSettingFactory.php b/app/Factory/GroupSettingFactory.php
index 88c1c6f615cb..acea47af60f9 100644
--- a/app/Factory/GroupSettingFactory.php
+++ b/app/Factory/GroupSettingFactory.php
@@ -18,8 +18,8 @@ class GroupSettingFactory
{
public static function create(int $company_id, int $user_id) :GroupSetting
{
- $settings = new \stdClass;
- $settings->entity = Client::class;
+ $settings = new \stdClass;
+ $settings->entity = Client::class;
$gs = new GroupSetting;
$gs->name = '';
diff --git a/app/Factory/InvoiceItemFactory.php b/app/Factory/InvoiceItemFactory.php
index 713035dce9e6..d88674f19adc 100644
--- a/app/Factory/InvoiceItemFactory.php
+++ b/app/Factory/InvoiceItemFactory.php
@@ -40,7 +40,7 @@ class InvoiceItemFactory
$item->custom_value2 = '';
$item->custom_value3 = '';
$item->custom_value4 = '';
- $item->type_id = "1";
+ $item->type_id = '1';
return $item;
}
@@ -71,7 +71,7 @@ class InvoiceItemFactory
// $item->custom_value4 = $faker->realText(10);
$item->tax_name1 = 'GST';
$item->tax_rate1 = 10.00;
- $item->type_id = "1";
+ $item->type_id = '1';
$data[] = $item;
}
@@ -105,7 +105,7 @@ class InvoiceItemFactory
// $item->custom_value4 = $faker->realText(10);
$item->tax_name1 = '';
$item->tax_rate1 = 0;
- $item->type_id = "1";
+ $item->type_id = '1';
$data[] = $item;
}
diff --git a/app/Factory/ProjectFactory.php b/app/Factory/ProjectFactory.php
index 77f9c7b8c81e..68cb9b04a88e 100644
--- a/app/Factory/ProjectFactory.php
+++ b/app/Factory/ProjectFactory.php
@@ -31,7 +31,7 @@ class ProjectFactory
$project->custom_value3 = '';
$project->custom_value4 = '';
$project->is_deleted = 0;
-
+
return $project;
}
}
diff --git a/app/Factory/PurchaseOrderInvitationFactory.php b/app/Factory/PurchaseOrderInvitationFactory.php
index ee3987ea7e39..8d354d244c8e 100644
--- a/app/Factory/PurchaseOrderInvitationFactory.php
+++ b/app/Factory/PurchaseOrderInvitationFactory.php
@@ -1,6 +1,5 @@
custom_value4 = '';
$recurring_expense->uses_inclusive_taxes = true;
$recurring_expense->calculate_tax_by_amount = true;
-
+
return $recurring_expense;
}
}
diff --git a/app/Factory/RecurringExpenseToExpenseFactory.php b/app/Factory/RecurringExpenseToExpenseFactory.php
index 503a167a2cf3..1f44a75d5a77 100644
--- a/app/Factory/RecurringExpenseToExpenseFactory.php
+++ b/app/Factory/RecurringExpenseToExpenseFactory.php
@@ -65,27 +65,25 @@ class RecurringExpenseToExpenseFactory
$expense->tax_amount3 = $recurring_expense->tax_amount3 ?: 0;
$expense->uses_inclusive_taxes = $recurring_expense->uses_inclusive_taxes;
$expense->calculate_tax_by_amount = $recurring_expense->calculate_tax_by_amount;
-
+
return $expense;
}
public static function transformObject(?string $value, $recurring_expense): ?string
{
- if(!$value)
+ if (! $value) {
return '';
-
- if($recurring_expense->client){
-
+ }
+
+ if ($recurring_expense->client) {
$locale = $recurring_expense->client->locale();
$date_format = $recurring_expense->client->date_format();
-
- }
- else {
+ } else {
$locale = $recurring_expense->company->locale();
$date_formats = Cache::get('date_formats');
- $date_format = $date_formats->filter(function ($item) use($recurring_expense){
+ $date_format = $date_formats->filter(function ($item) use ($recurring_expense) {
return $item->id == $recurring_expense->company->settings->date_format_id;
})->first()->format;
}
@@ -96,7 +94,7 @@ class RecurringExpenseToExpenseFactory
'literal' => [
':MONTH' => Carbon::createFromDate(now()->year, now()->month)->translatedFormat('F'),
':YEAR' => now()->year,
- ':QUARTER' => 'Q' . now()->quarter,
+ ':QUARTER' => 'Q'.now()->quarter,
':WEEK_BEFORE' => \sprintf(
'%s %s %s',
Carbon::now()->subDays(7)->translatedFormat($date_format),
@@ -110,9 +108,9 @@ class RecurringExpenseToExpenseFactory
Carbon::now()->addDays(14)->translatedFormat($date_format)
),
':WEEK' => \sprintf(
- '%s %s %s',
- Carbon::now()->translatedFormat($date_format),
- ctrans('texts.to'),
+ '%s %s %s',
+ Carbon::now()->translatedFormat($date_format),
+ ctrans('texts.to'),
Carbon::now()->addDays(7)->translatedFormat($date_format)
),
],
@@ -122,7 +120,7 @@ class RecurringExpenseToExpenseFactory
':QUARTER' => now()->quarter,
],
'ranges' => [
- 'MONTHYEAR' => Carbon::createFromDate(now()->year, now()->month),
+ 'MONTHYEAR' => Carbon::createFromDate(now()->year, now()->month),
],
'ranges_raw' => [
'MONTH' => now()->month,
@@ -136,7 +134,7 @@ class RecurringExpenseToExpenseFactory
$matches = array_shift($ranges);
foreach ($matches as $match) {
- if (!Str::contains($match, '|')) {
+ if (! Str::contains($match, '|')) {
continue;
}
@@ -147,7 +145,7 @@ class RecurringExpenseToExpenseFactory
$right = substr($parts[1], 0, -1); // MONTH+2
// If left side is not part of replacements, skip.
- if (!array_key_exists($left, $replacements['ranges'])) {
+ if (! array_key_exists($left, $replacements['ranges'])) {
continue;
}
@@ -155,7 +153,7 @@ class RecurringExpenseToExpenseFactory
$_right = '';
// If right side doesn't have any calculations, replace with raw ranges keyword.
- if (!Str::contains($right, ['-', '+', '/', '*'])) {
+ if (! Str::contains($right, ['-', '+', '/', '*'])) {
$_right = Carbon::createFromDate(now()->year, now()->month)->translatedFormat('F Y');
}
@@ -178,7 +176,6 @@ class RecurringExpenseToExpenseFactory
}
}
-
// Second case with more common calculations.
preg_match_all('/:([^:\s]+)/', $value, $common);
@@ -193,7 +190,7 @@ class RecurringExpenseToExpenseFactory
continue;
}
- if (!Str::contains($match, ['-', '+', '/', '*'])) {
+ if (! Str::contains($match, ['-', '+', '/', '*'])) {
$value = preg_replace(
sprintf('/%s/', $matches->keys()->first()), $replacements['literal'][$matches->keys()->first()], $value, 1
);
@@ -208,26 +205,26 @@ class RecurringExpenseToExpenseFactory
$raw = strtr($matches->keys()->first(), $replacements['raw']); // :MONTH => 1
- $number = $res = preg_replace("/[^0-9]/", '', $_value[1]); // :MONTH+1. || :MONTH+2! => 1 || 2
+ $number = $res = preg_replace('/[^0-9]/', '', $_value[1]); // :MONTH+1. || :MONTH+2! => 1 || 2
$target = "/{$matches->keys()->first()}\\{$_operation}{$number}/"; // /:$KEYWORD\\$OPERATION$VALUE => /:MONTH\\+1
- $output = (int) $raw + (int)$_value[1];
+ $output = (int) $raw + (int) $_value[1];
if ($operation == '+') {
- $output = (int) $raw + (int)$_value[1]; // 1 (:MONTH) + 4
+ $output = (int) $raw + (int) $_value[1]; // 1 (:MONTH) + 4
}
if ($_operation == '-') {
- $output = (int)$raw - (int)$_value[1]; // 1 (:MONTH) - 4
+ $output = (int) $raw - (int) $_value[1]; // 1 (:MONTH) - 4
}
- if ($_operation == '/' && (int)$_value[1] != 0) {
- $output = (int)$raw / (int)$_value[1]; // 1 (:MONTH) / 4
+ if ($_operation == '/' && (int) $_value[1] != 0) {
+ $output = (int) $raw / (int) $_value[1]; // 1 (:MONTH) / 4
}
if ($_operation == '*') {
- $output = (int)$raw * (int)$_value[1]; // 1 (:MONTH) * 4
+ $output = (int) $raw * (int) $_value[1]; // 1 (:MONTH) * 4
}
if ($matches->keys()->first() == ':MONTH') {
@@ -242,5 +239,4 @@ class RecurringExpenseToExpenseFactory
return $value;
}
-
}
diff --git a/app/Factory/RecurringInvoiceToInvoiceFactory.php b/app/Factory/RecurringInvoiceToInvoiceFactory.php
index a4b428d230ea..a1101972dd6b 100644
--- a/app/Factory/RecurringInvoiceToInvoiceFactory.php
+++ b/app/Factory/RecurringInvoiceToInvoiceFactory.php
@@ -67,24 +67,21 @@ class RecurringInvoiceToInvoiceFactory
$invoice->auto_bill_enabled = $recurring_invoice->auto_bill_enabled;
$invoice->paid_to_date = 0;
$invoice->design_id = $recurring_invoice->design_id;
-
+
return $invoice;
}
private static function transformItems($recurring_invoice, $client)
{
-
$line_items = $recurring_invoice->line_items;
- foreach($line_items as $key => $item){
-
- if(property_exists($line_items[$key], 'notes'))
+ foreach ($line_items as $key => $item) {
+ if (property_exists($line_items[$key], 'notes')) {
$line_items[$key]->notes = Helpers::processReservedKeywords($item->notes, $client);
-
+ }
}
return $line_items;
-
}
private static function tranformObject($object, $client)
diff --git a/app/Factory/RecurringQuoteToQuoteFactory.php b/app/Factory/RecurringQuoteToQuoteFactory.php
index b23e2567b93e..f5e0f765db44 100644
--- a/app/Factory/RecurringQuoteToQuoteFactory.php
+++ b/app/Factory/RecurringQuoteToQuoteFactory.php
@@ -54,7 +54,7 @@ class RecurringQuoteToQuoteFactory
$quote->auto_bill_enabled = $recurring_quote->auto_bill_enabled;
$quote->paid_to_date = 0;
$quote->design_id = $recurring_quote->design_id;
-
+
return $quote;
}
}
diff --git a/app/Factory/TaskStatusFactory.php b/app/Factory/TaskStatusFactory.php
index a59d2e9247ff..4f98d76e14f0 100644
--- a/app/Factory/TaskStatusFactory.php
+++ b/app/Factory/TaskStatusFactory.php
@@ -23,7 +23,7 @@ class TaskStatusFactory
$task_status->name = '';
$task_status->color = '';
$task_status->status_order = 9999;
-
+
return $task_status;
}
}
diff --git a/app/Factory/UserFactory.php b/app/Factory/UserFactory.php
index da56a183875e..bee6a6d6070d 100644
--- a/app/Factory/UserFactory.php
+++ b/app/Factory/UserFactory.php
@@ -29,7 +29,7 @@ class UserFactory
$user->failed_logins = 0;
$user->signature = '';
$user->theme_id = 0;
-
+
return $user;
}
}
diff --git a/app/Factory/VendorContactFactory.php b/app/Factory/VendorContactFactory.php
index 196694e36bc2..b46ce74de13d 100644
--- a/app/Factory/VendorContactFactory.php
+++ b/app/Factory/VendorContactFactory.php
@@ -12,6 +12,7 @@
namespace App\Factory;
use App\Models\VendorContact;
+use Illuminate\Support\Str;
class VendorContactFactory
{
@@ -21,6 +22,7 @@ class VendorContactFactory
$vendor_contact->first_name = '';
$vendor_contact->user_id = $user_id;
$vendor_contact->company_id = $company_id;
+ $vendor_contact->contact_key = Str::random(40);
$vendor_contact->id = 0;
return $vendor_contact;
diff --git a/app/Factory/WebhookFactory.php b/app/Factory/WebhookFactory.php
index a9e8ce04d0f8..4d61c00f3d8e 100644
--- a/app/Factory/WebhookFactory.php
+++ b/app/Factory/WebhookFactory.php
@@ -25,7 +25,7 @@ class WebhookFactory
$webhook->format = 'JSON';
$webhook->rest_method = 'post';
$webhook->headers = [];
-
+
return $webhook;
}
}
diff --git a/app/Filters/ClientFilters.php b/app/Filters/ClientFilters.php
index a373038667ec..d7b63d7d74a5 100644
--- a/app/Filters/ClientFilters.php
+++ b/app/Filters/ClientFilters.php
@@ -22,7 +22,6 @@ use Illuminate\Support\Facades\Gate;
*/
class ClientFilters extends QueryFilters
{
-
/**
* Filter by name.
*
@@ -57,8 +56,9 @@ class ClientFilters extends QueryFilters
{
$parts = explode(':', $balance);
- if(!is_array($parts))
+ if (! is_array($parts)) {
return $this->builder;
+ }
return $this->builder->whereBetween('balance', [$parts[0], $parts[1]]);
}
@@ -70,7 +70,6 @@ class ClientFilters extends QueryFilters
$this->builder->whereHas('contacts', function ($query) use ($email) {
$query->where('email', $email);
});
-
}
public function client_id(string $client_id = '') :Builder
@@ -80,7 +79,6 @@ class ClientFilters extends QueryFilters
}
return $this->builder->where('id', $this->decodePrimaryKey($client_id));
-
}
public function id_number(string $id_number = ''):Builder
@@ -109,10 +107,10 @@ class ClientFilters extends QueryFilters
return $this->builder->where(function ($query) use ($filter) {
$query->where('clients.name', 'like', '%'.$filter.'%')
->orWhere('clients.id_number', 'like', '%'.$filter.'%')
- ->orWhereHas('contacts', function ($query) use($filter){
- $query->where('first_name', 'like', '%'.$filter.'%');
- $query->orWhere('last_name', 'like', '%'.$filter.'%');
- $query->orWhere('email', 'like', '%'.$filter.'%');
+ ->orWhereHas('contacts', function ($query) use ($filter) {
+ $query->where('first_name', 'like', '%'.$filter.'%');
+ $query->orWhere('last_name', 'like', '%'.$filter.'%');
+ $query->orWhere('email', 'like', '%'.$filter.'%');
})
->orWhere('clients.custom_value1', 'like', '%'.$filter.'%')
->orWhere('clients.custom_value2', 'like', '%'.$filter.'%')
diff --git a/app/Filters/CompanyGatewayFilters.php b/app/Filters/CompanyGatewayFilters.php
index 7bff1b2a3144..ef2d6594da87 100644
--- a/app/Filters/CompanyGatewayFilters.php
+++ b/app/Filters/CompanyGatewayFilters.php
@@ -35,7 +35,6 @@ class CompanyGatewayFilters extends QueryFilters
return $this->builder->where(function ($query) use ($filter) {
$query->where('company_gateways.label', 'like', '%'.$filter.'%');
});
-
}
/**
diff --git a/app/Filters/DocumentFilters.php b/app/Filters/DocumentFilters.php
index 195d6a18ffed..fade4950705a 100644
--- a/app/Filters/DocumentFilters.php
+++ b/app/Filters/DocumentFilters.php
@@ -19,7 +19,6 @@ use Illuminate\Database\Eloquent\Builder;
*/
class DocumentFilters extends QueryFilters
{
-
/**
* Filter based on search text.
*
@@ -39,9 +38,7 @@ class DocumentFilters extends QueryFilters
/* If client ID passed to this entity, simply return */
public function client_id(string $client_id = '') :Builder
{
-
return $this->builder;
-
}
/**
diff --git a/app/Filters/ExpenseFilters.php b/app/Filters/ExpenseFilters.php
index c0c3ef362185..174acff790af 100644
--- a/app/Filters/ExpenseFilters.php
+++ b/app/Filters/ExpenseFilters.php
@@ -93,8 +93,9 @@ class ExpenseFilters extends QueryFilters
{
$sort_col = explode('|', $sort);
- if(is_array($sort_col) && in_array($sort_col[1], ['asc', 'desc']) && in_array($sort_col[0], ['public_notes', 'date', 'id_number', 'custom_value1', 'custom_value2', 'custom_value3', 'custom_value4']))
+ if (is_array($sort_col) && in_array($sort_col[1], ['asc', 'desc']) && in_array($sort_col[0], ['public_notes', 'date', 'id_number', 'custom_value1', 'custom_value2', 'custom_value3', 'custom_value4'])) {
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
+ }
return $this->builder;
}
diff --git a/app/Filters/InvoiceFilters.php b/app/Filters/InvoiceFilters.php
index d46a9b058848..c155d2061516 100644
--- a/app/Filters/InvoiceFilters.php
+++ b/app/Filters/InvoiceFilters.php
@@ -23,6 +23,7 @@ use Illuminate\Support\Carbon;
class InvoiceFilters extends QueryFilters
{
use MakesHash;
+
/**
* Filter based on client status.
*
@@ -98,7 +99,6 @@ class InvoiceFilters extends QueryFilters
});
}
-
/**
* Filters the list based on the status
* archived, active, deleted - legacy from V1.
@@ -161,7 +161,7 @@ class InvoiceFilters extends QueryFilters
$this->builder->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL])
->where('is_deleted', 0)
->where(function ($query) {
- $query->where('due_date', '<', now())
+ $query->where('due_date', '<', now())
->orWhere('partial_due_date', '<', now());
})
->orderBy('due_date', 'ASC');
@@ -190,8 +190,9 @@ class InvoiceFilters extends QueryFilters
$sort_col = explode('|', $sort);
//catch invalid explode array count
- if(count($sort_col) == 1)
+ if (count($sort_col) == 1) {
return $this->builder;
+ }
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
diff --git a/app/Filters/PaymentFilters.php b/app/Filters/PaymentFilters.php
index 8667583c59a8..823cb9fcf741 100644
--- a/app/Filters/PaymentFilters.php
+++ b/app/Filters/PaymentFilters.php
@@ -94,7 +94,6 @@ class PaymentFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
-
public function number(string $number) : Builder
{
return $this->builder->where('number', $number);
diff --git a/app/Filters/ProductFilters.php b/app/Filters/ProductFilters.php
index e4e98f2a415b..a406b6521f19 100644
--- a/app/Filters/ProductFilters.php
+++ b/app/Filters/ProductFilters.php
@@ -19,6 +19,8 @@ use Illuminate\Database\Eloquent\Builder;
*/
class ProductFilters extends QueryFilters
{
+ protected $with_property = 'product_key';
+
/**
* Filter based on search text.
*
@@ -42,6 +44,15 @@ class ProductFilters extends QueryFilters
});
}
+ public function product_key(string $filter = '') : Builder
+ {
+ if (strlen($filter) == 0) {
+ return $this->builder;
+ }
+
+ return $this->builder->where('product_key', $filter);
+ }
+
/**
* Filters the list based on the status
* archived, active, deleted.
diff --git a/app/Filters/ProjectFilters.php b/app/Filters/ProjectFilters.php
index 8c17b6c3a836..f6202c25ee60 100644
--- a/app/Filters/ProjectFilters.php
+++ b/app/Filters/ProjectFilters.php
@@ -141,6 +141,5 @@ class ProjectFilters extends QueryFilters
//return $this->builder->whereCompanyId(auth()->user()->company()->id);
// return $this->builder->whereCompanyId(auth()->user()->company()->id)->orWhere('company_id', null);
return $this->builder->company();
-
}
}
diff --git a/app/Filters/PurchaseOrderFilters.php b/app/Filters/PurchaseOrderFilters.php
index 38be4155d694..3aa91958ef36 100644
--- a/app/Filters/PurchaseOrderFilters.php
+++ b/app/Filters/PurchaseOrderFilters.php
@@ -11,8 +11,6 @@
namespace App\Filters;
-
-
use App\Models\PurchaseOrder;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
@@ -157,7 +155,6 @@ class PurchaseOrderFilters extends QueryFilters
*
* We need to ensure we are using the correct company ID
* as we could be hitting this from either the client or company auth guard
- *
*/
public function entityFilter()
{
diff --git a/app/Filters/QueryFilters.php b/app/Filters/QueryFilters.php
index d16619ce85a0..83fb8a36fdc6 100644
--- a/app/Filters/QueryFilters.php
+++ b/app/Filters/QueryFilters.php
@@ -22,7 +22,7 @@ use Illuminate\Http\Request;
abstract class QueryFilters
{
use MakesHash;
-
+
/**
* active status.
*/
@@ -52,6 +52,13 @@ abstract class QueryFilters
*/
protected $builder;
+ /**
+ * The "with" filter property column.
+ *
+ * var string
+ */
+ protected $with_property = 'id';
+
/**
* Create a new QueryFilters instance.
*
@@ -168,7 +175,7 @@ abstract class QueryFilters
public function created_at($value)
{
- $created_at = $value ? (int)$value : 0;
+ $created_at = $value ? (int) $value : 0;
$created_at = date('Y-m-d H:i:s', $value);
@@ -177,11 +184,11 @@ abstract class QueryFilters
public function is_deleted($value)
{
- if($value == 'true')
+ if ($value == 'true') {
return $this->builder->where('is_deleted', $value)->withTrashed();
+ }
return $this->builder->where('is_deleted', $value);
-
}
public function client_id(string $client_id = '') :Builder
@@ -191,20 +198,14 @@ abstract class QueryFilters
}
return $this->builder->where('client_id', $this->decodePrimaryKey($client_id));
-
}
public function filter_deleted_clients($value)
{
-
- if($value == 'true'){
-
+ if ($value == 'true') {
return $this->builder->whereHas('client', function (Builder $query) {
-
- $query->where('is_deleted', 0);
-
+ $query->where('is_deleted', 0);
});
-
}
return $this->builder;
@@ -212,11 +213,8 @@ abstract class QueryFilters
public function with_trashed($value)
{
-
- if($value == 'false'){
-
+ if ($value == 'false') {
return $this->builder->where('is_deleted', 0);
-
}
// if($value == 'true'){
@@ -226,6 +224,12 @@ abstract class QueryFilters
// }
return $this->builder;
+ }
+ public function with(string $value): Builder
+ {
+ return $this->builder
+ ->orWhere($this->with_property, $value)
+ ->orderByRaw("{$this->with_property} = ? DESC", [$value]);
}
}
diff --git a/app/Filters/TaskStatusFilters.php b/app/Filters/TaskStatusFilters.php
index d77f353be677..67886d83aad4 100644
--- a/app/Filters/TaskStatusFilters.php
+++ b/app/Filters/TaskStatusFilters.php
@@ -35,7 +35,6 @@ class TaskStatusFilters extends QueryFilters
return $this->builder->where(function ($query) use ($filter) {
$query->where('task_statuses.name', 'like', '%'.$filter.'%');
});
-
}
/**
diff --git a/app/Filters/TaxRateFilters.php b/app/Filters/TaxRateFilters.php
index 31d21084f726..ab8bdbfc79b9 100644
--- a/app/Filters/TaxRateFilters.php
+++ b/app/Filters/TaxRateFilters.php
@@ -35,7 +35,6 @@ class TaxRateFilters extends QueryFilters
return $this->builder->where(function ($query) use ($filter) {
$query->where('tax_rates.name', 'like', '%'.$filter.'%');
});
-
}
/**
diff --git a/app/Filters/VendorFilters.php b/app/Filters/VendorFilters.php
index 2e8daa253969..dd2c7e885824 100644
--- a/app/Filters/VendorFilters.php
+++ b/app/Filters/VendorFilters.php
@@ -38,7 +38,7 @@ class VendorFilters extends QueryFilters
return $this->builder->where(function ($query) use ($filter) {
$query->where('vendors.name', 'like', '%'.$filter.'%')
->orWhere('vendors.id_number', 'like', '%'.$filter.'%')
- ->orWhereHas('contacts', function ($query) use($filter){
+ ->orWhereHas('contacts', function ($query) use ($filter) {
$query->where('vendor_contacts.first_name', 'like', '%'.$filter.'%');
$query->orWhere('vendor_contacts.last_name', 'like', '%'.$filter.'%');
$query->orWhere('vendor_contacts.email', 'like', '%'.$filter.'%');
diff --git a/app/Helpers/Document/WithTypeHelpers.php b/app/Helpers/Document/WithTypeHelpers.php
index 45984e12d6d1..eb43316f68c8 100644
--- a/app/Helpers/Document/WithTypeHelpers.php
+++ b/app/Helpers/Document/WithTypeHelpers.php
@@ -16,8 +16,8 @@ trait WithTypeHelpers
{
/**
* Returns boolean based on checks for image.
- *
- * @return bool
+ *
+ * @return bool
*/
public function isImage(): bool
{
diff --git a/app/Helpers/Generic.php b/app/Helpers/Generic.php
index 87cbb4a3c803..feb40dd030e9 100644
--- a/app/Helpers/Generic.php
+++ b/app/Helpers/Generic.php
@@ -22,34 +22,22 @@ use App\Utils\Ninja;
*/
function nlog($output, $context = []): void
{
-
- if (!config('ninja.expanded_logging'))
+ if (! config('ninja.expanded_logging')) {
return;
+ }
- if (gettype($output) == 'object') {
- $output = print_r($output, 1);
- }
+ if (gettype($output) == 'object') {
+ $output = print_r($output, 1);
+ }
- $trace = debug_backtrace();
- //nlog( debug_backtrace()[1]['function']);
- // \Illuminate\Support\Facades\Log::channel('invoiceninja')->info(print_r($trace[1]['class'],1), []);
- if(Ninja::isHosted()) {
- try{
- info($output);
- }
- catch(\Exception $e){
-
- }
- }
- else
- \Illuminate\Support\Facades\Log::channel('invoiceninja')->info($output, $context);
+ // $trace = debug_backtrace();
-}
-
-// if (!function_exists('ray')) {
-// function ray($payload)
-// {
-// return true;
-// }
-// }
-
+ if (Ninja::isHosted()) {
+ try {
+ info($output);
+ } catch (\Exception $e) {
+ }
+ } else {
+ \Illuminate\Support\Facades\Log::channel('invoiceninja')->info($output, $context);
+ }
+}
\ No newline at end of file
diff --git a/app/Helpers/Invoice/CustomValuer.php b/app/Helpers/Invoice/CustomValuer.php
index b4df53a725ee..378e418ceb3f 100644
--- a/app/Helpers/Invoice/CustomValuer.php
+++ b/app/Helpers/Invoice/CustomValuer.php
@@ -27,7 +27,6 @@ trait CustomValuer
public function valuerTax($custom_value, $has_custom_invoice_taxes)
{
-
if (isset($custom_value) && is_numeric($custom_value) && $has_custom_invoice_taxes) {
return round($custom_value * ($this->invoice->tax_rate1 / 100), 2) + round($custom_value * ($this->invoice->tax_rate2 / 100), 2) + round($custom_value * ($this->invoice->tax_rate3 / 100), 2);
}
diff --git a/app/Helpers/Invoice/InvoiceItemSum.php b/app/Helpers/Invoice/InvoiceItemSum.php
index ba6e378a9ea2..8e3b702d7f6f 100644
--- a/app/Helpers/Invoice/InvoiceItemSum.php
+++ b/app/Helpers/Invoice/InvoiceItemSum.php
@@ -52,10 +52,11 @@ class InvoiceItemSum
$this->invoice = $invoice;
- if($this->invoice->client)
+ if ($this->invoice->client) {
$this->currency = $this->invoice->client->currency();
- else
+ } else {
$this->currency = $this->invoice->vendor->currency();
+ }
$this->line_items = [];
}
@@ -98,7 +99,7 @@ class InvoiceItemSum
}
private function sumLineItem()
- {
+ {
$this->setLineTotal($this->item->cost * $this->item->quantity);
return $this;
@@ -134,23 +135,26 @@ class InvoiceItemSum
$item_tax += $item_tax_rate1_total;
- // if($item_tax_rate1_total != 0)
- if (strlen($this->item->tax_name1) > 1)
- $this->groupTax($this->item->tax_name1, $this->item->tax_rate1, $item_tax_rate1_total);
-
+ // if($item_tax_rate1_total != 0)
+ if (strlen($this->item->tax_name1) > 1) {
+ $this->groupTax($this->item->tax_name1, $this->item->tax_rate1, $item_tax_rate1_total);
+ }
+
$item_tax_rate2_total = $this->calcAmountLineTax($this->item->tax_rate2, $amount);
$item_tax += $item_tax_rate2_total;
- if (strlen($this->item->tax_name2) > 1)
+ if (strlen($this->item->tax_name2) > 1) {
$this->groupTax($this->item->tax_name2, $this->item->tax_rate2, $item_tax_rate2_total);
-
+ }
+
$item_tax_rate3_total = $this->calcAmountLineTax($this->item->tax_rate3, $amount);
$item_tax += $item_tax_rate3_total;
- if (strlen($this->item->tax_name3) > 1)
+ if (strlen($this->item->tax_name3) > 1) {
$this->groupTax($this->item->tax_name3, $this->item->tax_rate3, $item_tax_rate3_total);
+ }
$this->setTotalTaxes($this->formatValue($item_tax, $this->currency->precision));
@@ -280,7 +284,6 @@ class InvoiceItemSum
if ($item_tax_rate3_total != 0) {
$this->groupTax($this->item->tax_name3, $this->item->tax_rate3, $item_tax_rate3_total);
}
-
}
$this->setTotalTaxes($item_tax);
diff --git a/app/Helpers/Invoice/InvoiceItemSumInclusive.php b/app/Helpers/Invoice/InvoiceItemSumInclusive.php
index 0b5628229353..213600d3501f 100644
--- a/app/Helpers/Invoice/InvoiceItemSumInclusive.php
+++ b/app/Helpers/Invoice/InvoiceItemSumInclusive.php
@@ -46,10 +46,11 @@ class InvoiceItemSumInclusive
$this->invoice = $invoice;
- if($this->invoice->client)
+ if ($this->invoice->client) {
$this->currency = $this->invoice->client->currency();
- else
+ } else {
$this->currency = $this->invoice->vendor->currency();
+ }
$this->line_items = [];
}
@@ -122,24 +123,26 @@ class InvoiceItemSumInclusive
$item_tax += $this->formatValue($item_tax_rate1_total, $this->currency->precision);
- // if($item_tax_rate1_total != 0)
- if (strlen($this->item->tax_name1) > 1)
- $this->groupTax($this->item->tax_name1, $this->item->tax_rate1, $item_tax_rate1_total);
+ // if($item_tax_rate1_total != 0)
+ if (strlen($this->item->tax_name1) > 1) {
+ $this->groupTax($this->item->tax_name1, $this->item->tax_rate1, $item_tax_rate1_total);
+ }
$item_tax_rate2_total = $this->calcInclusiveLineTax($this->item->tax_rate2, $amount);
$item_tax += $this->formatValue($item_tax_rate2_total, $this->currency->precision);
- if (strlen($this->item->tax_name2) > 1)
+ if (strlen($this->item->tax_name2) > 1) {
$this->groupTax($this->item->tax_name2, $this->item->tax_rate2, $item_tax_rate2_total);
-
+ }
+
$item_tax_rate3_total = $this->calcInclusiveLineTax($this->item->tax_rate3, $amount);
$item_tax += $this->formatValue($item_tax_rate3_total, $this->currency->precision);
- if (strlen($this->item->tax_name3) > 1)
+ if (strlen($this->item->tax_name3) > 1) {
$this->groupTax($this->item->tax_name3, $this->item->tax_rate3, $item_tax_rate3_total);
-
+ }
$this->setTotalTaxes($this->formatValue($item_tax, $this->currency->precision));
@@ -239,12 +242,12 @@ class InvoiceItemSumInclusive
$item_tax = 0;
foreach ($this->line_items as $this->item) {
-
- if($this->sub_total == 0)
+ if ($this->sub_total == 0) {
$amount = $this->item->line_total;
- else
+ } else {
$amount = $this->item->line_total - ($this->item->line_total * ($this->invoice->discount / $this->sub_total));
-
+ }
+
$item_tax_rate1_total = $this->calcInclusiveLineTax($this->item->tax_rate1, $amount);
$item_tax += $item_tax_rate1_total;
diff --git a/app/Helpers/Invoice/InvoiceSum.php b/app/Helpers/Invoice/InvoiceSum.php
index 40fb99e0a128..b1c170a26736 100644
--- a/app/Helpers/Invoice/InvoiceSum.php
+++ b/app/Helpers/Invoice/InvoiceSum.php
@@ -55,10 +55,11 @@ class InvoiceSum
{
$this->invoice = $invoice;
- if($this->invoice->client)
+ if ($this->invoice->client) {
$this->precision = $this->invoice->client->currency()->precision;
- else
+ } else {
$this->precision = $this->invoice->vendor->currency()->precision;
+ }
$this->tax_map = new Collection;
}
@@ -85,7 +86,7 @@ class InvoiceSum
$this->total = $this->invoice_items->getSubTotal();
$this->setSubTotal($this->invoice_items->getSubTotal());
$this->setGrossSubTotal($this->invoice_items->getGrossSubTotal());
-
+
return $this;
}
@@ -116,8 +117,7 @@ class InvoiceSum
private function calculateInvoiceTaxes()
{
-
- if (strlen($this->invoice->tax_name1) > 1) {
+ if (is_string($this->invoice->tax_name1) && strlen($this->invoice->tax_name1) > 1) {
$tax = $this->taxer($this->total, $this->invoice->tax_rate1);
$tax += $this->getSurchargeTaxTotalForKey($this->invoice->tax_name1, $this->invoice->tax_rate1);
@@ -125,7 +125,7 @@ class InvoiceSum
$this->total_tax_map[] = ['name' => $this->invoice->tax_name1.' '.floatval($this->invoice->tax_rate1).'%', 'total' => $tax];
}
- if (strlen($this->invoice->tax_name2) > 1) {
+ if (is_string($this->invoice->tax_name2) && strlen($this->invoice->tax_name2) > 1) {
$tax = $this->taxer($this->total, $this->invoice->tax_rate2);
$tax += $this->getSurchargeTaxTotalForKey($this->invoice->tax_name2, $this->invoice->tax_rate2);
@@ -133,14 +133,14 @@ class InvoiceSum
$this->total_tax_map[] = ['name' => $this->invoice->tax_name2.' '.floatval($this->invoice->tax_rate2).'%', 'total' => $tax];
}
- if (strlen($this->invoice->tax_name3) > 1) {
+ if (is_string($this->invoice->tax_name3) && strlen($this->invoice->tax_name3) > 1) {
$tax = $this->taxer($this->total, $this->invoice->tax_rate3);
$tax += $this->getSurchargeTaxTotalForKey($this->invoice->tax_name3, $this->invoice->tax_rate3);
$this->total_taxes += $tax;
$this->total_tax_map[] = ['name' => $this->invoice->tax_name3.' '.floatval($this->invoice->tax_rate3).'%', 'total' => $tax];
}
-
+
return $this;
}
@@ -180,6 +180,7 @@ class InvoiceSum
public function getTempEntity()
{
$this->setCalculatedAttributes();
+
return $this->invoice;
}
@@ -329,37 +330,29 @@ class InvoiceSum
private function getSurchargeTaxTotalForKey($key, $rate)
{
-
$tax_component = 0;
- if($this->invoice->custom_surcharge_tax1)
- {
+ if ($this->invoice->custom_surcharge_tax1) {
$tax_component += round($this->invoice->custom_surcharge1 * ($rate / 100), 2);
}
- if($this->invoice->custom_surcharge_tax2)
- {
+ if ($this->invoice->custom_surcharge_tax2) {
$tax_component += round($this->invoice->custom_surcharge2 * ($rate / 100), 2);
}
- if($this->invoice->custom_surcharge_tax3)
- {
+ if ($this->invoice->custom_surcharge_tax3) {
$tax_component += round($this->invoice->custom_surcharge3 * ($rate / 100), 2);
}
- if($this->invoice->custom_surcharge_tax4)
- {
+ if ($this->invoice->custom_surcharge_tax4) {
$tax_component += round($this->invoice->custom_surcharge4 * ($rate / 100), 2);
}
-
+
return $tax_component;
-
}
-
-
public function getTaxMap()
- {
+ {
return $this->tax_map;
}
diff --git a/app/Helpers/Invoice/InvoiceSumInclusive.php b/app/Helpers/Invoice/InvoiceSumInclusive.php
index 5e09187303cc..ad38f2754691 100644
--- a/app/Helpers/Invoice/InvoiceSumInclusive.php
+++ b/app/Helpers/Invoice/InvoiceSumInclusive.php
@@ -42,6 +42,7 @@ class InvoiceSumInclusive
private $sub_total;
private $precision;
+
/**
* Constructs the object with Invoice and Settings object.
*
@@ -51,10 +52,11 @@ class InvoiceSumInclusive
{
$this->invoice = $invoice;
- if($this->invoice->client)
+ if ($this->invoice->client) {
$this->precision = $this->invoice->client->currency()->precision;
- else
+ } else {
$this->precision = $this->invoice->vendor->currency()->precision;
+ }
$this->tax_map = new Collection;
}
@@ -170,7 +172,6 @@ class InvoiceSumInclusive
private function calculateTotals()
{
-
return $this;
}
@@ -188,6 +189,7 @@ class InvoiceSumInclusive
public function getTempEntity()
{
$this->setCalculatedAttributes();
+
return $this->invoice;
}
@@ -243,7 +245,7 @@ class InvoiceSumInclusive
$this->invoice->balance = $this->formatValue($this->getTotal(), $this->precision);
}
}
-
+
/* Set new calculated total */
$this->invoice->amount = $this->formatValue($this->getTotal(), $this->precision);
diff --git a/app/Helpers/Invoice/ProRata.php b/app/Helpers/Invoice/ProRata.php
index 50b3fa108613..d79ae48d7d64 100644
--- a/app/Helpers/Invoice/ProRata.php
+++ b/app/Helpers/Invoice/ProRata.php
@@ -20,62 +20,62 @@ use Illuminate\Support\Carbon;
class ProRata
{
-
-
/**
* Returns the amount to refund based on
* the time interval and the frequency duration
- *
- * @param float $amount
- * @param Carbon $from_date
- * @param Carbon $to_date
- * @param int $frequency
- * @return float
+ *
+ * @param float $amount
+ * @param Carbon $from_date
+ * @param Carbon $to_date
+ * @param int $frequency
+ * @return float
*/
public function refund(float $amount, Carbon $from_date, Carbon $to_date, int $frequency) :float
{
$days = $from_date->copy()->diffInDays($to_date);
$days_in_frequency = $this->getDaysInFrequency($frequency);
- return round( (($days/$days_in_frequency) * $amount),2);
+ return round((($days / $days_in_frequency) * $amount), 2);
}
/**
* Returns the amount to charge based on
* the time interval and the frequency duration
- *
- * @param float $amount
- * @param Carbon $from_date
- * @param Carbon $to_date
- * @param int $frequency
- * @return float
+ *
+ * @param float $amount
+ * @param Carbon $from_date
+ * @param Carbon $to_date
+ * @param int $frequency
+ * @return float
*/
public function charge(float $amount, Carbon $from_date, Carbon $to_date, int $frequency) :float
{
$days = $from_date->copy()->diffInDays($to_date);
$days_in_frequency = $this->getDaysInFrequency($frequency);
- return round( (($days/$days_in_frequency) * $amount),2);
+ return round((($days / $days_in_frequency) * $amount), 2);
}
/**
* Prepares the line items of an invoice
* to be pro rata refunded.
- *
- * @param Invoice $invoice
- * @param bool $is_credit
- * @return array
- * @throws Exception
+ *
+ * @param Invoice $invoice
+ * @param bool $is_credit
+ * @return array
+ * @throws Exception
*/
public function refundItems(Invoice $invoice, $is_credit = false) :array
{
- if(!$invoice)
+ if (! $invoice) {
return [];
+ }
$recurring_invoice = RecurringInvoice::find($invoice->recurring_id)->first();
- if(!$recurring_invoice)
+ if (! $recurring_invoice) {
throw new \Exception("Invoice isn't attached to a recurring invoice");
+ }
/* depending on whether we are creating an invoice or a credit*/
$multiplier = $is_credit ? 1 : -1;
@@ -84,29 +84,22 @@ class ProRata
$line_items = [];
- foreach($invoice->line_items as $item)
- {
-
- if($item->product_key != ctrans('texts.refund'))
- {
+ foreach ($invoice->line_items as $item) {
+ if ($item->product_key != ctrans('texts.refund')) {
$item->quantity = 1;
- $item->cost = $this->refund($item->cost*$multiplier, $start_date, now(), $recurring_invoice->frequency_id);
+ $item->cost = $this->refund($item->cost * $multiplier, $start_date, now(), $recurring_invoice->frequency_id);
$item->product_key = ctrans('texts.refund');
- $item->notes = ctrans('texts.refund') . ": ". $item->notes;
+ $item->notes = ctrans('texts.refund').': '.$item->notes;
$line_items[] = $item;
-
}
}
return $line_items;
-
}
-
private function getDaysInFrequency($frequency)
{
-
switch ($frequency) {
case RecurringInvoice::FREQUENCY_DAILY:
return 1;
@@ -135,7 +128,5 @@ class ProRata
default:
return 0;
}
-
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Helpers/Mail/GmailTransport.php b/app/Helpers/Mail/GmailTransport.php
index 711c15e22d6e..6e36804720b4 100644
--- a/app/Helpers/Mail/GmailTransport.php
+++ b/app/Helpers/Mail/GmailTransport.php
@@ -11,92 +11,72 @@
namespace App\Helpers\Mail;
-use App\Utils\TempFile;
-use Dacastro4\LaravelGmail\Facade\LaravelGmail;
-use Dacastro4\LaravelGmail\Services\Message\Mail;
-use Illuminate\Mail\Transport\Transport;
-use Swift_Mime_SimpleMessage;
+use Google\Service\Gmail;
+use Google\Service\Gmail\Message;
+use Google\Client;
+use Symfony\Component\Mailer\SentMessage;
+use Symfony\Component\Mailer\Transport\AbstractTransport;
+use Symfony\Component\Mime\MessageConverter;
/**
* GmailTransport.
*/
-class GmailTransport extends Transport
+class GmailTransport extends AbstractTransport
{
- /**
- * The Gmail instance.
- *
- * @var Mail
- */
- protected $gmail;
- /**
- * Create a new Gmail transport instance.
- *
- * @param Mail $gmail
- * @param string $token
- */
- public function __construct(Mail $gmail)
+ public function __construct()
{
- $this->gmail = $gmail;
+ parent::__construct();
}
- public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null)
+ protected function doSend(SentMessage $message): void
{
- /* For some reason the Injected Mail class carries cached tokens, so we need to reinit the Mail class*/
- $this->gmail = null;
- $this->gmail = new Mail;
+ nlog("In Do Send");
+ $message = MessageConverter::toEmail($message->getOriginalMessage());
- /*We should nest the token in the message and then discard it as needed*/
- $token = $message->getHeaders()->get('GmailToken')->getValue();
+ $token = $message->getHeaders()->get('gmailtoken')->getValue();
+ $message->getHeaders()->remove('gmailtoken');
+
+ $client = new Client();
+ $client->setClientId(config('ninja.auth.google.client_id'));
+ $client->setClientSecret(config('ninja.auth.google.client_secret'));
+ $client->setAccessToken($token);
- $message->getHeaders()->remove('GmailToken');
+ $service = new Gmail($client);
- $this->beforeSendPerformed($message);
+ $body = new Message();
- $this->gmail->using($token);
- $this->gmail->to($message->getTo());
- $this->gmail->from($message->getFrom());
- $this->gmail->subject($message->getSubject());
- $this->gmail->message($message->getBody());
+ $bccs = $message->getHeaders()->get('Bcc');
- $this->gmail->cc($message->getCc());
+ $bcc_list = '';
- if(is_array($message->getBcc()))
- $this->gmail->bcc(array_keys($message->getBcc()));
-
- foreach ($message->getChildren() as $child)
+ if($bccs)
{
+ $bcc_list = 'Bcc: ';
- if($child->getContentType() != 'text/plain')
- {
+ foreach($bccs->getAddresses() as $address){
+
+ $bcc_list .= $address->getAddress() .',';
- $this->gmail->attach(TempFile::filePath($child->getBody(), $child->getHeaders()->get('Content-Type')->getParameter('name') ));
-
}
- }
+ $bcc_list = rtrim($bcc_list, ",") . "\r\n";
+ }
- /**
- * Google is very strict with their
- * sending limits, if we hit 429s, sleep and
- * retry again later.
- */
- try{
+ $body->setRaw($this->base64_encode($bcc_list.$message->toString()));
- $this->gmail->send();
-
- }
- catch(\Google\Service\Exception $e)
- {
- nlog("gmail exception");
- nlog($e->getErrors());
-
- sleep(5);
- $this->gmail->send();
- }
-
- $this->sendPerformed($message);
-
- return $this->numberOfRecipients($message);
+ $service->users_messages->send('me', $body, []);
+
}
+
+ private function base64_encode($data)
+ {
+ return rtrim(strtr(base64_encode($data), ['+' => '-', '/' => '_']), '=');
+ }
+
+ public function __toString(): string
+ {
+ return 'gmail';
+ }
+
}
diff --git a/app/Helpers/Mail/GmailTransportManager.php b/app/Helpers/Mail/GmailTransportManager.php
deleted file mode 100644
index b6f574427f50..000000000000
--- a/app/Helpers/Mail/GmailTransportManager.php
+++ /dev/null
@@ -1,31 +0,0 @@
-beforeSendPerformed($message);
+ $symfony_message = MessageConverter::toEmail($message->getOriginalMessage());
$graph = new Graph();
- $token = $message->getHeaders()->get('GmailToken')->getValue();
+ $token = $symfony_message->getHeaders()->get('gmailtoken')->getValue();
+ $symfony_message->getHeaders()->remove('gmailtoken');
$graph->setAccessToken($token);
- // Special treatment if the message has too large attachments
- $messageBody = $this->getBody($message, true);
- $messageBodySizeMb = json_encode($messageBody);
- $messageBodySizeMb = strlen($messageBodySizeMb);
- $messageBodySizeMb = $messageBodySizeMb / 1048576; //byte -> mb
+ $bccs = $symfony_message->getHeaders()->get('Bcc');
- if ($messageBodySizeMb >= 4) {
- unset($messageBody);
- $graphMessage = $graph->createRequest("POST", "/users/" . key($message->getFrom()) . "/messages")
- ->attachBody($this->getBody($message))
+ $bcc_list = '';
+
+ if($bccs)
+ {
+
+ foreach($bccs->getAddresses() as $address){
+
+ $bcc_list .= 'Bcc: "'.$address->getAddress().'" <'.$address->getAddress().'>\r\n';
+
+ }
+
+ }
+
+ try {
+ $graphMessage = $graph->createRequest('POST', '/users/'.$symfony_message->getFrom()[0]->getAddress().'/sendmail')
+ ->attachBody(base64_encode($bcc_list.$message->toString()))
+ ->addHeaders(['Content-Type' => 'text/plain'])
+ ->setReturnType(\Microsoft\Graph\Model\Message::class)
+ ->execute();
+ } catch (\Exception $e) {
+ sleep(5);
+ $graphMessage = $graph->createRequest('POST', '/users/'.$symfony_message->getFrom()[0]->getAddress().'/sendmail')
+ ->attachBody(base64_encode($bcc_list.$message->toString()))
+ ->addHeaders(['Content-Type' => 'text/plain'])
->setReturnType(\Microsoft\Graph\Model\Message::class)
->execute();
-
- foreach ($message->getChildren() as $attachment) {
- if ($attachment instanceof \Swift_Mime_SimpleMimeEntity) {
- $fileName = $attachment->getHeaders()->get('Content-Type')->getParameter('name');
- $content = $attachment->getBody();
- $fileSize = strlen($content);
- $size = $fileSize / 1048576; //byte -> mb
- $id = $attachment->getId();
- $attachmentMessage = [
- 'AttachmentItem' => [
- 'attachmentType' => 'file',
- 'name' => $fileName,
- 'size' => strlen($content)
- ]
- ];
-
- if ($size <= 3) { //ErrorAttachmentSizeShouldNotBeLessThanMinimumSize if attachment <= 3mb, then we need to add this
- $attachmentBody = [
- "@odata.type" => "#microsoft.graph.fileAttachment",
- "name" => $attachment->getHeaders()->get('Content-Type')->getParameter('name'),
- "contentType" => $attachment->getBodyContentType(),
- "contentBytes" => base64_encode($attachment->getBody()),
- 'contentId' => $id
- ];
-
- $addAttachment = $graph->createRequest("POST", "/users/" . key($message->getFrom()) . "/messages/" . $graphMessage->getId() . "/attachments")
- ->attachBody($attachmentBody)
- ->setReturnType(UploadSession::class)
- ->execute();
- } else {
- //upload the files in chunks of 4mb....
- $uploadSession = $graph->createRequest("POST", "/users/" . key($message->getFrom()) . "/messages/" . $graphMessage->getId() . "/attachments/createUploadSession")
- ->attachBody($attachmentMessage)
- ->setReturnType(UploadSession::class)
- ->execute();
-
- $fragSize = 1024 * 1024 * 4; //4mb at once...
- $numFragments = ceil($fileSize / $fragSize);
- $contentChunked = str_split($content, $fragSize);
- $bytesRemaining = $fileSize;
-
- $i = 0;
- while ($i < $numFragments) {
- $chunkSize = $numBytes = $fragSize;
- $start = $i * $fragSize;
- $end = $i * $fragSize + $chunkSize - 1;
- if ($bytesRemaining < $chunkSize) {
- $chunkSize = $numBytes = $bytesRemaining;
- $end = $fileSize - 1;
- }
- $data = $contentChunked[$i];
- $content_range = "bytes " . $start . "-" . $end . "/" . $fileSize;
- $headers = [
- "Content-Length" => $numBytes,
- "Content-Range" => $content_range
- ];
- $client = new \GuzzleHttp\Client();
- $tmp = $client->put($uploadSession->getUploadUrl(), [
- 'headers' => $headers,
- 'body' => $data,
- 'allow_redirects' => false,
- 'timeout' => 1000
- ]);
- $result = $tmp->getBody() . '';
- $result = json_decode($result); //if body == empty, then the file was successfully uploaded
- $bytesRemaining = $bytesRemaining - $chunkSize;
- $i++;
- }
- }
- }
- }
-
- //definetly send the message
- $graph->createRequest("POST", "/users/" . key($message->getFrom()) . "/messages/" . $graphMessage->getId() . "/send")->execute();
- } else {
-
- try {
- $graphMessage = $graph->createRequest("POST", "/users/" . key($message->getFrom()) . "/sendmail")
- ->attachBody($messageBody)
- ->setReturnType(\Microsoft\Graph\Model\Message::class)
- ->execute();
- }
- catch(\Exception $e){
-
- sleep(5);
- $graphMessage = $graph->createRequest("POST", "/users/" . key($message->getFrom()) . "/sendmail")
- ->attachBody($messageBody)
- ->setReturnType(\Microsoft\Graph\Model\Message::class)
- ->execute();
- }
}
-
- $this->sendPerformed($message);
-
- return $this->numberOfRecipients($message);
+
}
- /**
- * Get body for the message.
- *
- * @param \Swift_Mime_SimpleMessage $message
- * @param bool $withAttachments
- * @return array
- */
-
- protected function getBody(Swift_Mime_SimpleMessage $message, $withAttachments = false)
+ public function __toString(): string
{
- $messageData = [
- 'from' => [
- 'emailAddress' => [
- 'address' => key($message->getFrom()),
- 'name' => current($message->getFrom())
- ]
- ],
- 'toRecipients' => $this->getTo($message),
- 'ccRecipients' => $this->getCc($message),
- 'bccRecipients' => $this->getBcc($message),
- 'replyTo' => $this->getReplyTo($message),
- 'subject' => $message->getSubject(),
- 'body' => [
- 'contentType' => $message->getBodyContentType() == "text/html" ? 'html' : 'text',
- 'content' => $message->getBody()
- ]
- ];
-
- if ($withAttachments) {
- $messageData = ['message' => $messageData];
- //add attachments if any
- $attachments = [];
- foreach ($message->getChildren() as $attachment) {
- if ($attachment instanceof \Swift_Mime_SimpleMimeEntity && $attachment->getContentType() != 'text/plain') {
- $attachments[] = [
- "@odata.type" => "#microsoft.graph.fileAttachment",
- "name" => $attachment->getHeaders()->get('Content-Type')->getParameter('name'),
- "contentType" => $attachment->getBodyContentType(),
- "contentBytes" => base64_encode($attachment->getBody()),
- 'contentId' => $attachment->getId()
- ];
- }
- }
- if (count($attachments) > 0) {
- $messageData['message']['attachments'] = $attachments;
- }
- }
-
- return $messageData;
+ return 'office365';
}
- /**
- * Get the "to" payload field for the API request.
- *
- * @param \Swift_Mime_SimpleMessage $message
- * @return string
- */
- protected function getTo(Swift_Mime_SimpleMessage $message)
- {
- return collect((array) $message->getTo())->map(function ($display, $address) {
- return $display ? [
- 'emailAddress' => [
- 'address' => $address,
- 'name' => $display
- ]
- ] : [
- 'emailAddress' => [
- 'address' => $address
- ]
- ];
- })->values()->toArray();
- }
-
- /**
- * Get the "Cc" payload field for the API request.
- *
- * @param \Swift_Mime_SimpleMessage $message
- * @return string
- */
- protected function getCc(Swift_Mime_SimpleMessage $message)
- {
- return collect((array) $message->getCc())->map(function ($display, $address) {
- return $display ? [
- 'emailAddress' => [
- 'address' => $address,
- 'name' => $display
- ]
- ] : [
- 'emailAddress' => [
- 'address' => $address
- ]
- ];
- })->values()->toArray();
- }
-
- /**
- * Get the "replyTo" payload field for the API request.
- *
- * @param \Swift_Mime_SimpleMessage $message
- * @return string
- */
- protected function getReplyTo(Swift_Mime_SimpleMessage $message)
- {
- return collect((array) $message->getReplyTo())->map(function ($display, $address) {
- return $display ? [
- 'emailAddress' => [
- 'address' => $address,
- 'name' => $display
- ]
- ] : [
- 'emailAddress' => [
- 'address' => $address
- ]
- ];
- })->values()->toArray();
- }
-
- /**
- * Get the "Bcc" payload field for the API request.
- *
- * @param \Swift_Mime_SimpleMessage $message
- * @return string
- */
- protected function getBcc(Swift_Mime_SimpleMessage $message)
- {
- return collect((array) $message->getBcc())->map(function ($display, $address) {
- return $display ? [
- 'emailAddress' => [
- 'address' => $address,
- 'name' => $display
- ]
- ] : [
- 'emailAddress' => [
- 'address' => $address
- ]
- ];
- })->values()->toArray();
- }
-
- /**
- * Get all of the contacts for the message.
- *
- * @param \Swift_Mime_SimpleMessage $message
- * @return array
- */
- protected function allContacts(Swift_Mime_SimpleMessage $message)
- {
- return array_merge(
- (array) $message->getTo(),
- (array) $message->getCc(),
- (array) $message->getBcc(),
- (array) $message->getReplyTo()
- );
- }
-
-}
\ No newline at end of file
+}
diff --git a/app/Helpers/Mail/Office365TransportManager.php b/app/Helpers/Mail/Office365TransportManager.php
deleted file mode 100644
index 3c88383820e4..000000000000
--- a/app/Helpers/Mail/Office365TransportManager.php
+++ /dev/null
@@ -1,23 +0,0 @@
-where('subscription_id', $this->invoice->subscription_id)
->where('client_id', $this->invoice->client_id)
->where('balance', '>', 0)
->exists();
- return ! $outstanding_invoices_exist;
-
+ return ! $outstanding_invoices_exist;
}
public function calcUpgradePlan()
@@ -63,21 +60,21 @@ class SubscriptionCalculator
//are they paid up to date.
//yes - calculate refund
- if($this->isPaidUp())
+ if ($this->isPaidUp()) {
$refund_invoice = $this->getRefundInvoice();
+ }
- if($refund_invoice)
- {
+ if ($refund_invoice) {
$subscription = Subscription::find($this->invoice->subscription_id);
$pro_rata = new ProRata;
- $to_date = $subscription->service()->getNextDateForFrequency(Carbon::parse($refund_invoice->date), $subscription->frequency_id);
+ $to_date = $subscription->service()->getNextDateForFrequency(Carbon::parse($refund_invoice->date), $subscription->frequency_id);
$refund_amount = $pro_rata->refund($refund_invoice->amount, now(), $to_date, $subscription->frequency_id);
$charge_amount = $pro_rata->charge($this->target_subscription->price, now(), $to_date, $this->target_subscription->frequency_id);
-
- return ($charge_amount - $refund_amount);
+
+ return $charge_amount - $refund_amount;
}
//no - return full freight charge.
@@ -86,7 +83,6 @@ class SubscriptionCalculator
public function executeUpgradePlan()
{
-
}
private function getRefundInvoice()
@@ -96,7 +92,5 @@ class SubscriptionCalculator
->where('is_deleted', 0)
->orderBy('id', 'desc')
->first();
-
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Http/Controllers/AccountController.php b/app/Http/Controllers/AccountController.php
index 67d2ffca77a2..48dddbb64428 100644
--- a/app/Http/Controllers/AccountController.php
+++ b/app/Http/Controllers/AccountController.php
@@ -143,30 +143,28 @@ class AccountController extends BaseController
*/
public function store(CreateAccountRequest $request)
{
- $account = CreateAccount::dispatchNow($request->all(), $request->getClientIp());
-
+ $account = (new CreateAccount($request->all(), $request->getClientIp()))->handle();
if (! ($account instanceof Account)) {
return $account;
}
$ct = CompanyUser::whereUserId(auth()->user()->id);
- $truth = app()->make(TruthSource::class);
- $truth->setCompanyUser($ct->first());
- $truth->setUser(auth()->user());
- $truth->setCompany($ct->first()->company);
-
+ $truth = app()->make(TruthSource::class);
+ $truth->setCompanyUser($ct->first());
+ $truth->setUser(auth()->user());
+ $truth->setCompany($ct->first()->company);
return $this->listResponse($ct);
}
public function update(UpdateAccountRequest $request, Account $account)
{
-
$fi = new \FilesystemIterator(public_path('react'), \FilesystemIterator::SKIP_DOTS);
- if(iterator_count($fi) < 30)
+ if (iterator_count($fi) < 30) {
return response()->json(['message' => 'React App Not Installed, Please install the React app before attempting to switch.'], 400);
+ }
$account->fill($request->all());
$account->save();
diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php
index e216355c9d14..e64f3df8bec5 100644
--- a/app/Http/Controllers/ActivityController.php
+++ b/app/Http/Controllers/ActivityController.php
@@ -23,8 +23,8 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
-use Symfony\Component\HttpFoundation\StreamedResponse;
use stdClass;
+use Symfony\Component\HttpFoundation\StreamedResponse;
class ActivityController extends BaseController
{
@@ -91,28 +91,25 @@ class ActivityController extends BaseController
$activities = Activity::orderBy('created_at', 'DESC')->company()
->take($default_activities);
- if($request->has('react')){
-
+ if ($request->has('react')) {
$system = ctrans('texts.system');
- $data = $activities->cursor()->map(function ($activity) use($system){
-
- $arr=
+ $data = $activities->cursor()->map(function ($activity) use ($system) {
+ $arr =
[
- 'client' => $activity->client ? $activity->client : '',
- 'contact' => $activity->contact ? $activity->contact : '',
- 'quote' => $activity->quote ? $activity->quote : '',
- 'user' => $activity->user ? $activity->user : '',
- 'expense' => $activity->expense ? $activity->expense : '',
- 'invoice' => $activity->invoice ? $activity->invoice : '',
- 'recurring_invoice' => $activity->recurring_invoice ? $activity->recurring_invoice : '',
- 'payment' => $activity->payment ? $activity->payment : '',
- 'credit' => $activity->credit ? $activity->credit : '',
- 'task' => $activity->task ? $activity->task : '',
+ 'client' => $activity->client ? $activity->client : '',
+ 'contact' => $activity->contact ? $activity->contact : '',
+ 'quote' => $activity->quote ? $activity->quote : '',
+ 'user' => $activity->user ? $activity->user : '',
+ 'expense' => $activity->expense ? $activity->expense : '',
+ 'invoice' => $activity->invoice ? $activity->invoice : '',
+ 'recurring_invoice' => $activity->recurring_invoice ? $activity->recurring_invoice : '',
+ 'payment' => $activity->payment ? $activity->payment : '',
+ 'credit' => $activity->credit ? $activity->credit : '',
+ 'task' => $activity->task ? $activity->task : '',
];
return array_merge($arr, $activity->toArray());
-
});
return response()->json(['data' => $data->toArray()], 200);
@@ -168,25 +165,23 @@ class ActivityController extends BaseController
$backup = $activity->backup;
$html_backup = '';
- /* Refactor 20-10-2021
+ /* Refactor 20-10-2021
*
* We have moved the backups out of the database and into object storage.
- * In order to handle edge cases, we still check for the database backup
+ * In order to handle edge cases, we still check for the database backup
* in case the file no longer exists
*/
- if($backup && $backup->filename && Storage::disk(config('filesystems.default'))->exists($backup->filename)){ //disk
+ if ($backup && $backup->filename && Storage::disk(config('filesystems.default'))->exists($backup->filename)) { //disk
- if(Ninja::isHosted())
+ if (Ninja::isHosted()) {
$html_backup = file_get_contents(Storage::disk(config('filesystems.default'))->url($backup->filename));
- else
+ } else {
$html_backup = file_get_contents(Storage::disk(config('filesystems.default'))->path($backup->filename));
-
- }
- elseif($backup && $backup->html_backup){ //db
+ }
+ } elseif ($backup && $backup->html_backup) { //db
$html_backup = $backup->html_backup;
- }
- elseif (! $backup || ! $backup->html_backup) { //failed
+ } elseif (! $backup || ! $backup->html_backup) { //failed
return response()->json(['message'=> ctrans('texts.no_backup_exists'), 'errors' => new stdClass], 404);
}
@@ -195,32 +190,25 @@ class ActivityController extends BaseController
$numbered_pdf = $this->pageNumbering($pdf, $activity->company);
- if($numbered_pdf)
- $pdf = $numbered_pdf;
-
-
- }
- elseif(config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja'){
+ if ($numbered_pdf) {
+ $pdf = $numbered_pdf;
+ }
+ } elseif (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') {
$pdf = (new NinjaPdf())->build($html_backup);
- $numbered_pdf = $this->pageNumbering($pdf, $activity->company);
+ $numbered_pdf = $this->pageNumbering($pdf, $activity->company);
- if($numbered_pdf)
- $pdf = $numbered_pdf;
-
-
-
- }
- else {
+ if ($numbered_pdf) {
+ $pdf = $numbered_pdf;
+ }
+ } else {
$pdf = $this->makePdf(null, null, $html_backup);
- $numbered_pdf = $this->pageNumbering($pdf, $activity->company);
-
- if($numbered_pdf)
- $pdf = $numbered_pdf;
-
-
+ $numbered_pdf = $this->pageNumbering($pdf, $activity->company);
+ if ($numbered_pdf) {
+ $pdf = $numbered_pdf;
+ }
}
if (isset($activity->invoice_id)) {
diff --git a/app/Http/Controllers/Auth/ContactForgotPasswordController.php b/app/Http/Controllers/Auth/ContactForgotPasswordController.php
index 84d4139b33ca..e26fbfc672c8 100644
--- a/app/Http/Controllers/Auth/ContactForgotPasswordController.php
+++ b/app/Http/Controllers/Auth/ContactForgotPasswordController.php
@@ -58,26 +58,24 @@ class ContactForgotPasswordController extends Controller
*/
public function showLinkRequestForm(Request $request)
{
-
$account = false;
-
- if(Ninja::isHosted() && $request->session()->has('company_key'))
- {
+
+ if (Ninja::isHosted() && $request->session()->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->session()->get('company_key'));
$company = Company::where('company_key', $request->session()->get('company_key'))->first();
$account = $company->account;
}
- if(!$account){
+ if (! $account) {
$account = Account::first();
$company = $account->companies->first();
}
-
+
return $this->render('auth.passwords.request', [
'title' => 'Client Password Reset',
'passwordEmailRoute' => 'client.password.email',
'account' => $account,
- 'company' => $company
+ 'company' => $company,
]);
}
@@ -93,44 +91,41 @@ class ContactForgotPasswordController extends Controller
public function sendResetLinkEmail(ContactPasswordResetRequest $request)
{
- if(Ninja::isHosted() && $request->has('company_key'))
+ if (Ninja::isHosted() && $request->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->input('company_key'));
-
+ }
+
$this->validateEmail($request);
- if(Ninja::isHosted() && $company = Company::where('company_key', $request->input('company_key'))->first())
- {
+ if (Ninja::isHosted() && $company = Company::where('company_key', $request->input('company_key'))->first()) {
$contact = ClientContact::where(['email' => $request->input('email'), 'company_id' => $company->id])
->whereHas('client', function ($query) {
- $query->where('is_deleted',0);
- })->first();
- }
- else {
-
+ $query->where('is_deleted', 0);
+ })->first();
+ } else {
$contact = ClientContact::where(['email' => $request->input('email')])
->whereHas('client', function ($query) {
- $query->where('is_deleted',0);
- })->first();
+ $query->where('is_deleted', 0);
+ })->first();
}
$response = false;
- if($contact){
+ if ($contact) {
/* Update all instances of the client */
$token = Str::random(60);
ClientContact::where('email', $contact->email)->update(['token' => $token]);
$contact->sendPasswordResetNotification($token);
$response = Password::RESET_LINK_SENT;
-
- }
- else
+ } else {
return $this->sendResetLinkFailedResponse($request, Password::INVALID_USER);
+ }
if ($request->ajax()) {
-
- if($response == Password::RESET_THROTTLED)
+ if ($response == Password::RESET_THROTTLED) {
return response()->json(['message' => ctrans('passwords.throttled'), 'status' => false], 429);
+ }
return $response == Password::RESET_LINK_SENT
? response()->json(['message' => 'Reset link sent to your email.', 'status' => true], 201)
@@ -141,5 +136,4 @@ class ContactForgotPasswordController extends Controller
? $this->sendResetLinkResponse($request, $response)
: $this->sendResetLinkFailedResponse($request, $response);
}
-
}
diff --git a/app/Http/Controllers/Auth/ContactLoginController.php b/app/Http/Controllers/Auth/ContactLoginController.php
index e3118cb0fb73..e64acd510d6e 100644
--- a/app/Http/Controllers/Auth/ContactLoginController.php
+++ b/app/Http/Controllers/Auth/ContactLoginController.php
@@ -37,54 +37,55 @@ class ContactLoginController extends Controller
$this->middleware('guest:contact', ['except' => ['logout']]);
}
- public function showLoginForm(Request $request)
+ public function showLoginForm(Request $request, $company_key = false)
{
-
$company = false;
$account = false;
- if($request->session()->has('company_key')){
+ if ($request->session()->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->session()->get('company_key'));
$company = Company::where('company_key', $request->input('company_key'))->first();
}
-
- if($company){
- $account = $company->account;
+ elseif($request->has('company_key')){
+ MultiDB::findAndSetDbByCompanyKey($request->input('company_key'));
+ $company = Company::where('company_key', $request->input('company_key'))->first();
+ }elseif($company_key){
+ MultiDB::findAndSetDbByCompanyKey($company_key);
+ $company = Company::where('company_key', $company_key)->first();
}
- elseif (!$company && strpos($request->getHost(), 'invoicing.co') !== false) {
+
+ if ($company) {
+ $account = $company->account;
+ } elseif (! $company && strpos($request->getHost(), 'invoicing.co') !== false) {
$subdomain = explode('.', $request->getHost())[0];
MultiDB::findAndSetDbByDomain(['subdomain' => $subdomain]);
$company = Company::where('subdomain', $subdomain)->first();
-
- } elseif(Ninja::isHosted()){
-
+ } elseif (Ninja::isHosted()) {
MultiDB::findAndSetDbByDomain(['portal_domain' => $request->getSchemeAndHttpHost()]);
$company = Company::where('portal_domain', $request->getSchemeAndHttpHost())->first();
-
- }
- elseif (Ninja::isSelfHost()) {
+ } elseif (Ninja::isSelfHost()) {
$account = Account::first();
$company = $account->default_company;
} else {
$company = null;
}
- if(!$account){
+ if (! $account) {
$account_id = $request->get('account_id');
$account = Account::find($account_id);
}
return $this->render('auth.login', ['account' => $account, 'company' => $company]);
-
}
public function login(Request $request)
{
Auth::shouldUse('contact');
- if(Ninja::isHosted() && $request->has('company_key'))
+ if (Ninja::isHosted() && $request->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->input('company_key'));
+ }
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
@@ -97,21 +98,20 @@ class ContactLoginController extends Controller
return $this->sendLockoutResponse($request);
}
- if(Ninja::isHosted() && $request->has('password') && $company = Company::where('company_key', $request->input('company_key'))->first()){
-
+ if (Ninja::isHosted() && $request->has('password') && $company = Company::where('company_key', $request->input('company_key'))->first()) {
$contact = ClientContact::where(['email' => $request->input('email'), 'company_id' => $company->id])
->whereHas('client', function ($query) {
- $query->where('is_deleted',0);
- })->first();
+ $query->where('is_deleted', 0);
+ })->first();
- if(!$contact)
+ if (! $contact) {
return $this->sendFailedLoginResponse($request);
+ }
- if(Hash::check($request->input('password'), $contact->password))
+ if (Hash::check($request->input('password'), $contact->password)) {
return $this->authenticated($request, $contact);
-
- }
- elseif ($this->attemptLogin($request)) {
+ }
+ } elseif ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
@@ -164,19 +164,18 @@ class ContactLoginController extends Controller
private function setRedirectPath()
{
-
- if(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_INVOICES)
+ if (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_INVOICES) {
$this->redirectTo = '/client/invoices';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_RECURRING_INVOICES)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_RECURRING_INVOICES) {
$this->redirectTo = '/client/recurring_invoices';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_QUOTES)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_QUOTES) {
$this->redirectTo = '/client/quotes';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_CREDITS)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_CREDITS) {
$this->redirectTo = '/client/credits';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_TASKS)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_TASKS) {
$this->redirectTo = '/client/tasks';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_EXPENSES)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_EXPENSES) {
$this->redirectTo = '/client/expenses';
-
+ }
}
}
diff --git a/app/Http/Controllers/Auth/ContactRegisterController.php b/app/Http/Controllers/Auth/ContactRegisterController.php
index 6d34694ce2c7..4bb551017a7d 100644
--- a/app/Http/Controllers/Auth/ContactRegisterController.php
+++ b/app/Http/Controllers/Auth/ContactRegisterController.php
@@ -19,9 +19,9 @@ use App\Models\Client;
use App\Models\Company;
use App\Utils\Ninja;
use App\Utils\Traits\GeneratesCounter;
+use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
-use Illuminate\Support\Facades\App;
class ContactRegisterController extends Controller
{
@@ -34,11 +34,11 @@ class ContactRegisterController extends Controller
public function showRegisterForm(string $company_key = '')
{
-
- if(strlen($company_key) > 2)
+ if (strlen($company_key) > 2) {
$key = $company_key;
- else
+ } else {
$key = request()->session()->has('company_key') ? request()->session()->get('company_key') : $company_key;
+ }
$company = Company::where('company_key', $key)->firstOrFail();
@@ -63,7 +63,6 @@ class ContactRegisterController extends Controller
private function getClient(array $data)
{
-
$client = ClientFactory::create($data['company']->id, $data['company']->owner()->id);
$client->fill($data);
@@ -71,10 +70,8 @@ class ContactRegisterController extends Controller
$client->number = $this->getNextClientNumber($client);
$client->save();
- if(!array_key_exists('country_id', $data) && strlen($client->company->settings->country_id) > 1){
-
+ if (! array_key_exists('country_id', $data) && strlen($client->company->settings->country_id) > 1) {
$client->update(['country_id' => $client->company->settings->country_id]);
-
}
return $client;
@@ -88,8 +85,9 @@ class ContactRegisterController extends Controller
$client_contact->client_id = $client->id;
$client_contact->is_primary = true;
- if(array_key_exists('password', $data))
+ if (array_key_exists('password', $data)) {
$client_contact->password = Hash::make($data['password']);
+ }
$client_contact->save();
diff --git a/app/Http/Controllers/Auth/ContactResetPasswordController.php b/app/Http/Controllers/Auth/ContactResetPasswordController.php
index 44ab7909ab20..2b060d0bb5b8 100644
--- a/app/Http/Controllers/Auth/ContactResetPasswordController.php
+++ b/app/Http/Controllers/Auth/ContactResetPasswordController.php
@@ -69,63 +69,56 @@ class ContactResetPasswordController extends Controller
*/
public function showResetForm(Request $request, $token = null)
{
-
- if($request->session()->has('company_key')){
+ if ($request->session()->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->session()->get('company_key'));
$company = Company::where('company_key', $request->session()->get('company_key'))->first();
$db = $company->db;
$account = $company->account;
- }
- else {
-
+ } else {
$account_key = $request->session()->has('account_key') ? $request->session()->get('account_key') : false;
- if($account_key){
-
+ if ($account_key) {
MultiDB::findAndSetDbByAccountKey($account_key);
$account = Account::where('key', $account_key)->first();
$db = $account->companies->first()->db;
$company = $account->companies->first();
- }
- else{
-
+ } else {
$account = Account::first();
$db = $account->companies->first()->db;
$company = $account->companies->first();
}
-
}
-
return $this->render('auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email, 'account' => $account, 'db' => $db, 'company' => $company]
);
-
}
public function reset(Request $request)
{
- if($request->session()->has('company_key'))
+ if ($request->session()->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->session()->get('company_key'));
-
+ }
+
$request->validate($this->rules(), $this->validationErrorMessages());
- $user = ClientContact::where($request->only(['email','token']))->first();
+ $user = ClientContact::where($request->only(['email', 'token']))->first();
- if(!$user)
+ if (! $user) {
return $this->sendResetFailedResponse($request, PASSWORD::INVALID_USER);
+ }
$hashed_password = Hash::make($request->input('password'));
ClientContact::where('email', $user->email)->update([
'password' => $hashed_password,
- 'remember_token' => Str::random(60)
+ 'remember_token' => Str::random(60),
]);
event(new PasswordReset($user));
auth()->login($user, true);
-
+
$response = Password::PASSWORD_RESET;
// Added this because it collides the session between
diff --git a/app/Http/Controllers/Auth/ForgotPasswordController.php b/app/Http/Controllers/Auth/ForgotPasswordController.php
index ba041fc661f3..c8ce54988eb3 100644
--- a/app/Http/Controllers/Auth/ForgotPasswordController.php
+++ b/app/Http/Controllers/Auth/ForgotPasswordController.php
@@ -60,12 +60,12 @@ class ForgotPasswordController extends Controller
// need to show to the user. Finally, we'll send out a proper response.
$response = $this->broker()->sendResetLink(
$this->credentials($request)
- );
+ );
if ($request->ajax()) {
-
- if($response == Password::RESET_THROTTLED)
+ if ($response == Password::RESET_THROTTLED) {
return response()->json(['message' => ctrans('passwords.throttled'), 'status' => false], 429);
+ }
return $response == Password::RESET_LINK_SENT
? response()->json(['message' => 'Reset link sent to your email.', 'status' => true], 201)
@@ -79,16 +79,15 @@ class ForgotPasswordController extends Controller
public function showLinkRequestForm(Request $request)
{
- if($request->has('company_key')){
+ if ($request->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->input('company_key'));
$company = Company::where('company_key', $request->input('company_key'))->first();
$account = $company->account;
- }
- else{
+ } else {
$account_id = $request->get('account_id');
$account = Account::find($account_id);
}
-
+
return $this->render('auth.passwords.request', ['root' => 'themes', 'account' => $account]);
}
}
diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php
index 7a473bbc9173..9f702bbe3174 100644
--- a/app/Http/Controllers/Auth/LoginController.php
+++ b/app/Http/Controllers/Auth/LoginController.php
@@ -32,8 +32,8 @@ use App\Models\SystemLog;
use App\Models\User;
use App\Transformers\CompanyUserTransformer;
use App\Utils\Ninja;
-use App\Utils\Traits\UserSessionAttributes;
use App\Utils\Traits\User\LoginCache;
+use App\Utils\Traits\UserSessionAttributes;
use App\Utils\TruthSource;
use Google_Client;
use Illuminate\Database\Eloquent\Builder;
@@ -43,26 +43,25 @@ use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite;
+use Microsoft\Graph\Model;
use PragmaRX\Google2FA\Google2FA;
use Turbo124\Beacon\Facades\LightLogs;
-use Microsoft\Graph\Model;
use Illuminate\Support\Facades\Http;
-
class LoginController extends BaseController
{
/**
- * @OA\Tag(
- * name="login",
- * description="Authentication",
- * @OA\ExternalDocumentation(
- * description="Find out more",
- * url="http://docs.invoiceninja.com"
- * )
- * )
- */
-
+ * @OA\Tag(
+ * name="login",
+ * description="Authentication",
+ * @OA\ExternalDocumentation(
+ * description="Find out more",
+ * url="http://docs.invoiceninja.com"
+ * )
+ * )
+ */
use AuthenticatesUsers;
+
use UserSessionAttributes;
use LoginCache;
@@ -178,7 +177,6 @@ class LoginController extends BaseController
}
if ($this->attemptLogin($request)) {
-
LightLogs::create(new LoginSuccess())
->increment()
->queue();
@@ -186,29 +184,24 @@ class LoginController extends BaseController
$user = $this->guard()->user();
//2FA
- if($user->google_2fa_secret && $request->has('one_time_password'))
- {
+ if ($user->google_2fa_secret && $request->has('one_time_password')) {
$google2fa = new Google2FA();
- if(strlen($request->input('one_time_password')) == 0 || !$google2fa->verifyKey(decrypt($user->google_2fa_secret), $request->input('one_time_password')))
- {
+ if (strlen($request->input('one_time_password')) == 0 || !$google2fa->verifyKey(decrypt($user->google_2fa_secret), $request->input('one_time_password'))) {
return response()
- ->json(['message' => ctrans('texts.invalid_one_time_password')], 401)
- ->header('X-App-Version', config('ninja.app_version'))
- ->header('X-Api-Version', config('ninja.minimum_client_version'));
+ ->json(['message' => ctrans('texts.invalid_one_time_password')], 401)
+ ->header('X-App-Version', config('ninja.app_version'))
+ ->header('X-Api-Version', config('ninja.minimum_client_version'));
}
-
- }
- elseif($user->google_2fa_secret && !$request->has('one_time_password')) {
-
- return response()
+ } elseif ($user->google_2fa_secret && !$request->has('one_time_password')) {
+ return response()
->json(['message' => ctrans('texts.invalid_one_time_password')], 401)
->header('X-App-Version', config('ninja.app_version'))
->header('X-Api-Version', config('ninja.minimum_client_version'));
}
/* If for some reason we lose state on the default company ie. a company is deleted - always make sure we can default to a company*/
- if(!$user->account->default_company){
+ if (!$user->account->default_company) {
$account = $user->account;
$account->default_company_id = $user->companies->first()->id;
$account->save();
@@ -217,20 +210,19 @@ class LoginController extends BaseController
$cu = $this->hydrateCompanyUser();
- if($cu->count() == 0)
+ if ($cu->count() == 0) {
return response()->json(['message' => 'User found, but not attached to any companies, please see your administrator'], 400);
+ }
/*On the hosted platform, only owners can login for free/pro accounts*/
- if (Ninja::isHosted() && !$cu->first()->is_owner && !$user->account->isEnterpriseClient())
+ if (Ninja::isHosted() && !$cu->first()->is_owner && !$user->account->isEnterpriseClient()) {
return response()->json(['message' => 'Pro / Free accounts only the owner can log in. Please upgrade'], 403);
+ }
event(new UserLoggedIn($user, $user->account->default_company, Ninja::eventVars($user->id)));
return $this->timeConstrainedResponse($cu);
-
-
} else {
-
LightLogs::create(new LoginFailure())
->increment()
->queue();
@@ -241,7 +233,6 @@ class LoginController extends BaseController
->json(['message' => ctrans('texts.invalid_credentials')], 401)
->header('X-App-Version', config('ninja.app_version'))
->header('X-Api-Version', config('ninja.minimum_client_version'));
-
}
}
@@ -288,29 +279,32 @@ class LoginController extends BaseController
{
$truth = app()->make(TruthSource::class);
- if ($truth->getCompanyToken())
+ if ($truth->getCompanyToken()) {
$company_token = $truth->getCompanyToken();
- else
+ } else {
$company_token = CompanyToken::where('token', $request->header('X-API-TOKEN'))->first();
+ }
$cu = CompanyUser::query()
->where('user_id', $company_token->user_id);
- if ($cu->count() == 0)
+ if ($cu->count() == 0) {
return response()->json(['message' => 'User found, but not attached to any companies, please see your administrator'], 400);
+ }
$cu->first()->account->companies->each(function ($company) use ($cu, $request) {
-
if ($company->tokens()->where('is_system', true)->count() == 0) {
- CreateCompanyToken::dispatchNow($company, $cu->first()->user, $request->server('HTTP_USER_AGENT'));
+ (new CreateCompanyToken($company, $cu->first()->user, $request->server('HTTP_USER_AGENT')))->handle();
}
});
- if ($request->has('current_company') && $request->input('current_company') == 'true')
- $cu->where("company_id", $company_token->company_id);
+ if ($request->has('current_company') && $request->input('current_company') == 'true') {
+ $cu->where('company_id', $company_token->company_id);
+ }
- if (Ninja::isHosted() && !$cu->first()->is_owner && !$cu->first()->user->account->isEnterpriseClient())
+ if (Ninja::isHosted() && !$cu->first()->is_owner && !$cu->first()->user->account->isEnterpriseClient()) {
return response()->json(['message' => 'Pro / Free accounts only the owner can log in. Please upgrade'], 403);
+ }
return $this->refreshResponse($cu);
}
@@ -329,7 +323,6 @@ class LoginController extends BaseController
*/
public function oauthApiLogin()
{
-
$message = 'Provider not supported';
if (request()->input('provider') == 'google') {
return $this->handleGoogleOauth();
@@ -362,14 +355,13 @@ class LoginController extends BaseController
if ($user) {
return $this->loginOrCreateFromSocialite($user, $provider);
}
+
return response()
->json(['message' => ctrans('texts.invalid_credentials')], 401)
->header('X-App-Version', config('ninja.app_version'))
->header('X-Api-Version', config('ninja.minimum_client_version'));
-
}
-
private function loginOrCreateFromSocialite($user, $provider)
{
$query = [
@@ -377,27 +369,29 @@ class LoginController extends BaseController
'oauth_provider_id' => $provider,
];
if ($existing_user = MultiDB::hasUser($query)) {
-
- if (!$existing_user->account)
+ if (!$existing_user->account) {
return response()->json(['message' => 'User exists, but not attached to any companies! Orphaned user!'], 400);
+ }
Auth::login($existing_user, true);
$cu = $this->hydrateCompanyUser();
- if ($cu->count() == 0)
+ if ($cu->count() == 0) {
return response()->json(['message' => 'User found, but not attached to any companies, please see your administrator'], 400);
+ }
- if (Ninja::isHosted() && !$cu->first()->is_owner && !$existing_user->account->isEnterpriseClient())
+ if (Ninja::isHosted() && !$cu->first()->is_owner && !$existing_user->account->isEnterpriseClient()) {
return response()->json(['message' => 'Pro / Free accounts only the owner can log in. Please upgrade'], 403);
+ }
return $this->timeConstrainedResponse($cu);
-
}
//If this is a result user/email combo - lets add their OAuth details details
if ($existing_login_user = MultiDB::hasUser(['email' => $user->email])) {
- if (!$existing_login_user->account)
+ if (!$existing_login_user->account) {
return response()->json(['message' => 'User exists, but not attached to any companies! Orphaned user!'], 400);
+ }
Auth::login($existing_login_user, true);
@@ -408,11 +402,13 @@ class LoginController extends BaseController
$cu = $this->hydrateCompanyUser();
- if ($cu->count() == 0)
+ if ($cu->count() == 0) {
return response()->json(['message' => 'User found, but not attached to any companies, please see your administrator'], 400);
+ }
- if (Ninja::isHosted() && !$cu->first()->is_owner && !$existing_login_user->account->isEnterpriseClient())
+ if (Ninja::isHosted() && !$cu->first()->is_owner && !$existing_login_user->account->isEnterpriseClient()) {
return response()->json(['message' => 'Pro / Free accounts only the owner can log in. Please upgrade'], 403);
+ }
return $this->timeConstrainedResponse($cu);
}
@@ -429,7 +425,7 @@ class LoginController extends BaseController
MultiDB::setDefaultDatabase();
- $account = CreateAccount::dispatchNow($new_account, request()->getClientIp());
+ $account = (new CreateAccount($new_account, request()->getClientIp()))->handle();
Auth::login($account->default_company->owner(), true);
auth()->user()->email_verified_at = now();
@@ -437,27 +433,28 @@ class LoginController extends BaseController
$cu = $this->hydrateCompanyUser();
- if ($cu->count() == 0)
+ if ($cu->count() == 0) {
return response()->json(['message' => 'User found, but not attached to any companies, please see your administrator'], 400);
+ }
- if (Ninja::isHosted() && !$cu->first()->is_owner && !auth()->user()->account->isEnterpriseClient())
+ if (Ninja::isHosted() && !$cu->first()->is_owner && !auth()->user()->account->isEnterpriseClient()) {
return response()->json(['message' => 'Pro / Free accounts only the owner can log in. Please upgrade'], 403);
+ }
return $this->timeConstrainedResponse($cu);
}
-
private function hydrateCompanyUser(): Builder
{
-
$cu = CompanyUser::query()->where('user_id', auth()->user()->id);
- if($cu->count() == 0)
+ if ($cu->count() == 0) {
return $cu;
+ }
- if (CompanyUser::query()->where('user_id', auth()->user()->id)->where('company_id', auth()->user()->account->default_company_id)->exists())
+ if (CompanyUser::query()->where('user_id', auth()->user()->id)->where('company_id', auth()->user()->account->default_company_id)->exists()) {
$set_company = auth()->user()->account->default_company;
- else {
+ } else {
$set_company = $cu->first()->company;
}
@@ -470,67 +467,63 @@ class LoginController extends BaseController
$truth->setUser(auth()->user());
$truth->setCompany($set_company);
- if($cu->count() == 0)
+ if ($cu->count() == 0) {
return $cu;
+ }
if (auth()->user()->company_users()->count() != auth()->user()->tokens()->distinct('company_id')->count()) {
-
auth()->user()->companies->each(function ($company) {
-
if (!CompanyToken::where('user_id', auth()->user()->id)->where('company_id', $company->id)->exists()) {
-
- CreateCompanyToken::dispatchNow($company, auth()->user(), "Google_O_Auth");
-
+ (new CreateCompanyToken($company, auth()->user(), 'Google_O_Auth'))->handle();
}
-
- });
-
+ });
}
$truth->setCompanyToken(CompanyToken::where('user_id', auth()->user()->id)->where('company_id', $set_company->id)->first());
return $cu;
-
}
private function handleMicrosoftOauth()
{
- if(request()->has('accessToken'))
+ if (request()->has('accessToken'))
$accessToken = request()->input('accessToken');
elseif(request()->has('access_token'))
$accessToken = request()->input('access_token');
else
return response()->json(['message' => 'Invalid response from oauth server, no access token in response.'], 400);
+
$graph = new \Microsoft\Graph\Graph();
$graph->setAccessToken($accessToken);
- $user = $graph->createRequest("GET", "/me")
- ->setReturnType(Model\User::class)
- ->execute();
+ $user = $graph->createRequest('GET', '/me')
+ ->setReturnType(Model\User::class)
+ ->execute();
- if($user){
+ if ($user) {
+ $account = request()->input('account');
$email = $user->getMail() ?: $user->getUserPrincipalName();
$query = [
'oauth_user_id' => $user->getId(),
- 'oauth_provider_id'=> 'microsoft',
+ 'oauth_provider_id' => 'microsoft',
];
if ($existing_user = MultiDB::hasUser($query)) {
-
- if(!$existing_user->account)
+ if (!$existing_user->account) {
return response()->json(['message' => 'User exists, but not attached to any companies! Orphaned user!'], 400);
+ }
return $this->existingOauthUser($existing_user);
}
//If this is a result user/email combo - lets add their OAuth details details
- if($existing_login_user = MultiDB::hasUser(['email' => $email]))
- {
- if(!$existing_login_user->account)
+ if ($existing_login_user = MultiDB::hasUser(['email' => $email])) {
+ if (!$existing_login_user->account) {
return response()->json(['message' => 'User exists, but not attached to any companies! Orphaned user!'], 400);
+ }
Auth::login($existing_login_user, true);
@@ -540,7 +533,7 @@ class LoginController extends BaseController
// Signup!
$new_account = [
'first_name' => $user->getGivenName() ?: '',
- 'last_name' => $user->getSurname() ?: '' ,
+ 'last_name' => $user->getSurname() ?: '',
'password' => '',
'email' => $email,
'oauth_user_id' => $user->getId(),
@@ -548,9 +541,9 @@ class LoginController extends BaseController
];
return $this->createNewAccount($new_account);
-
}
+
return response()->json(['message' => 'Unable to authenticate this user'], 400);
}
@@ -561,33 +554,35 @@ class LoginController extends BaseController
$cu = $this->hydrateCompanyUser();
- if($cu->count() == 0)
+ if ($cu->count() == 0) {
return response()->json(['message' => 'User found, but not attached to any companies, please see your administrator'], 400);
+ }
- if(Ninja::isHosted() && !$cu->first()->is_owner && !$existing_user->account->isEnterpriseClient())
+ if (Ninja::isHosted() && !$cu->first()->is_owner && !$existing_user->account->isEnterpriseClient()) {
return response()->json(['message' => 'Pro / Free accounts only the owner can log in. Please upgrade'], 403);
+ }
return $this->timeConstrainedResponse($cu);
}
private function existingLoginUser($oauth_user_id, $provider)
{
-
auth()->user()->update([
'oauth_user_id' => $oauth_user_id,
- 'oauth_provider_id'=> $provider,
- ]);
+ 'oauth_provider_id' => $provider,
+ ]);
$cu = $this->hydrateCompanyUser();
- if($cu->count() == 0)
+ if ($cu->count() == 0) {
return response()->json(['message' => 'User found, but not attached to any companies, please see your administrator'], 400);
+ }
- if(Ninja::isHosted() && !$cu->first()->is_owner && !auth()->user()->account->isEnterpriseClient())
+ if (Ninja::isHosted() && !$cu->first()->is_owner && !auth()->user()->account->isEnterpriseClient()) {
return response()->json(['message' => 'Pro / Free accounts only the owner can log in. Please upgrade'], 403);
+ }
return $this->timeConstrainedResponse($cu);
-
}
private function handleGoogleOauth()
@@ -599,40 +594,38 @@ class LoginController extends BaseController
$user = $google->getTokenResponse(request()->input('id_token'));
if (is_array($user)) {
-
$query = [
'oauth_user_id' => $google->harvestSubField($user),
- 'oauth_provider_id'=> 'google',
+ 'oauth_provider_id' => 'google',
];
if ($existing_user = MultiDB::hasUser($query)) {
-
- if(!$existing_user->account)
+ if (!$existing_user->account) {
return response()->json(['message' => 'User exists, but not attached to any companies! Orphaned user!'], 400);
+ }
return $this->existingOauthUser($existing_user);
}
//If this is a result user/email combo - lets add their OAuth details details
- if($existing_login_user = MultiDB::hasUser(['email' => $google->harvestEmail($user)]))
- {
- if(!$existing_login_user->account)
+ if ($existing_login_user = MultiDB::hasUser(['email' => $google->harvestEmail($user)])) {
+ if (!$existing_login_user->account) {
return response()->json(['message' => 'User exists, but not attached to any companies! Orphaned user!'], 400);
+ }
Auth::login($existing_login_user, true);
return $this->existingLoginUser($google->harvestSubField($user), 'google');
}
-
}
if ($user) {
//check the user doesn't already exist in some form
- if($existing_login_user = MultiDB::hasUser(['email' => $google->harvestEmail($user)]))
- {
- if(!$existing_login_user->account)
+ if ($existing_login_user = MultiDB::hasUser(['email' => $google->harvestEmail($user)])) {
+ if (!$existing_login_user->account) {
return response()->json(['message' => 'User exists, but not attached to any companies! Orphaned user!'], 400);
+ }
Auth::login($existing_login_user, true);
@@ -655,20 +648,19 @@ class LoginController extends BaseController
}
return response()
- ->json(['message' => ctrans('texts.invalid_credentials')], 401)
- ->header('X-App-Version', config('ninja.app_version'))
- ->header('X-Api-Version', config('ninja.minimum_client_version'));
+ ->json(['message' => ctrans('texts.invalid_credentials')], 401)
+ ->header('X-App-Version', config('ninja.app_version'))
+ ->header('X-Api-Version', config('ninja.minimum_client_version'));
}
private function createNewAccount($new_account)
{
-
MultiDB::setDefaultDatabase();
- $account = CreateAccount::dispatchNow($new_account, request()->getClientIp());
-
- if(!$account instanceOf Account)
+ $account = (new CreateAccount($new_account, request()->getClientIp()))->handle();
+ if (!$account instanceof Account) {
return $account;
+ }
Auth::login($account->default_company->owner(), true);
auth()->user()->email_verified_at = now();
@@ -676,27 +668,26 @@ class LoginController extends BaseController
$cu = $this->hydrateCompanyUser();
- if($cu->count() == 0)
+ if ($cu->count() == 0) {
return response()->json(['message' => 'User found, but not attached to any companies, please see your administrator'], 400);
+ }
- if(Ninja::isHosted() && !$cu->first()->is_owner && !auth()->user()->account->isEnterpriseClient())
+ if (Ninja::isHosted() && !$cu->first()->is_owner && !auth()->user()->account->isEnterpriseClient()) {
return response()->json(['message' => 'Pro / Free accounts only the owner can log in. Please upgrade'], 403);
+ }
return $this->timeConstrainedResponse($cu);
-
}
public function redirectToProvider(string $provider)
{
-
$scopes = [];
$parameters = [];
- if($provider == 'google'){
-
- $scopes = ['https://www.googleapis.com/auth/gmail.send','email','profile','openid'];
- $parameters = ['access_type' => 'offline', "prompt" => "consent select_account", 'redirect_uri' => config('ninja.app_url')."/auth/google"];
+ if ($provider == 'google') {
+ $scopes = ['https://www.googleapis.com/auth/gmail.send', 'email', 'profile', 'openid'];
+ $parameters = ['access_type' => 'offline', 'prompt' => 'consent select_account', 'redirect_uri' => config('ninja.app_url') . '/auth/google'];
}
if($provider == 'microsoft'){
@@ -707,9 +698,9 @@ class LoginController extends BaseController
if (request()->has('code')) {
return $this->handleProviderCallback($provider);
} else {
-
- if(!in_array($provider, ['google','microsoft']))
+ if (!in_array($provider, ['google', 'microsoft'])) {
return abort(400, 'Invalid provider');
+ }
return Socialite::driver($provider)->with($parameters)->scopes($scopes)->redirect();
}
@@ -717,27 +708,23 @@ class LoginController extends BaseController
public function handleProviderCallback(string $provider)
{
-
- if($provider == 'microsoft')
+ if ($provider == 'microsoft') {
return $this->handleMicrosoftProviderCallback();
+ }
$socialite_user = Socialite::driver($provider)->user();
$oauth_user_token = '';
- if($socialite_user->refreshToken){
-
- $client = new Google_Client();
- $client->setClientId(config('ninja.auth.google.client_id'));
- $client->setClientSecret(config('ninja.auth.google.client_secret'));
- $client->fetchAccessTokenWithRefreshToken($socialite_user->refreshToken);
- $oauth_user_token = $client->getAccessToken();
-
- }
-
- if($user = OAuth::handleAuth($socialite_user, $provider))
- {
+ if ($socialite_user->refreshToken) {
+ $client = new Google_Client();
+ $client->setClientId(config('ninja.auth.google.client_id'));
+ $client->setClientSecret(config('ninja.auth.google.client_secret'));
+ $client->fetchAccessTokenWithRefreshToken($socialite_user->refreshToken);
+ $oauth_user_token = $client->getAccessToken();
+ }
+ if ($user = OAuth::handleAuth($socialite_user, $provider)) {
nlog('found user and updating their user record');
$name = OAuth::splitName($socialite_user->getName());
@@ -748,14 +735,12 @@ class LoginController extends BaseController
'oauth_user_id' => $socialite_user->getId(),
'oauth_provider_id' => $provider,
'oauth_user_token' => $oauth_user_token,
- 'oauth_user_refresh_token' => $socialite_user->refreshToken
+ 'oauth_user_refresh_token' => $socialite_user->refreshToken,
];
$user->update($update_user);
-
- }
- else {
- nlog("user not found for oauth");
+ } else {
+ nlog('user not found for oauth');
}
return redirect('/#/');
@@ -763,12 +748,11 @@ class LoginController extends BaseController
public function handleMicrosoftProviderCallback($provider = 'microsoft')
{
-
$socialite_user = Socialite::driver($provider)->user();
nlog($socialite_user);
- nlog("refresh token " . $socialite_user->accessTokenResponseBody['refresh_token']);
- nlog("access token " . $socialite_user->accessTokenResponseBody['access_token']);
+ nlog('refresh token ' . $socialite_user->accessTokenResponseBody['refresh_token']);
+ nlog('access token ' . $socialite_user->accessTokenResponseBody['access_token']);
$oauth_user_token = $socialite_user->accessTokenResponseBody['access_token'];
@@ -776,7 +760,6 @@ class LoginController extends BaseController
if($user = OAuth::handleAuth($socialite_user, $provider))
{
-
nlog('found user and updating their user record');
$name = OAuth::splitName($socialite_user->getName());
@@ -792,14 +775,10 @@ class LoginController extends BaseController
];
$user->update($update_user);
-
- }
- else {
- nlog("user not found for oauth");
+ } else {
+ nlog('user not found for oauth');
}
return redirect('/#/');
-
}
-
}
diff --git a/app/Http/Controllers/Auth/ResetPasswordController.php b/app/Http/Controllers/Auth/ResetPasswordController.php
index 43b20fb795de..63b850d38c13 100644
--- a/app/Http/Controllers/Auth/ResetPasswordController.php
+++ b/app/Http/Controllers/Auth/ResetPasswordController.php
@@ -57,19 +57,18 @@ class ResetPasswordController extends Controller
public function showResetForm(Request $request, $token = null)
{
$company = false;
-
- if(Ninja::isHosted()){
+ if (Ninja::isHosted()) {
MultiDB::findAndSetDbByCompanyKey($request->session()->get('company_key'));
$company = Company::where('company_key', $request->session()->get('company_key'))->first();
-
}
- if($company)
+ if ($company) {
$account = $company->account;
- else
+ } else {
$account = Account::first();
-
+ }
+
return $this->render('auth.passwords.reset', ['root' => 'themes', 'token' => $token, 'account' => $account]);
}
diff --git a/app/Http/Controllers/Auth/VendorContactLoginController.php b/app/Http/Controllers/Auth/VendorContactLoginController.php
index 59fb20004e8f..212a2b2630be 100644
--- a/app/Http/Controllers/Auth/VendorContactLoginController.php
+++ b/app/Http/Controllers/Auth/VendorContactLoginController.php
@@ -40,7 +40,7 @@ class VendorContactLoginController extends Controller
public function catch()
{
$data = [
-
+
];
return $this->render('purchase_orders.catch');
@@ -53,6 +53,4 @@ class VendorContactLoginController extends Controller
return redirect('/vendors');
}
-
-
}
diff --git a/app/Http/Controllers/BaseController.php b/app/Http/Controllers/BaseController.php
index 7137e2e75a8b..b142609f9986 100644
--- a/app/Http/Controllers/BaseController.php
+++ b/app/Http/Controllers/BaseController.php
@@ -36,6 +36,7 @@ use League\Fractal\Serializer\JsonApiSerializer;
class BaseController extends Controller
{
use AppSetup;
+
/**
* Passed from the parent when we need to force
* includes internally rather than externally via
@@ -107,21 +108,21 @@ class BaseController extends Controller
];
private $mini_load = [
- 'account',
- 'user.company_user',
- 'token',
- 'company.activities',
- 'company.tax_rates',
- 'company.documents',
- 'company.company_gateways.gateway',
- 'company.users.company_user',
- 'company.task_statuses',
- 'company.payment_terms',
- 'company.groups',
- 'company.designs.company',
- 'company.expense_categories',
- 'company.subscriptions',
- ];
+ 'account',
+ 'user.company_user',
+ 'token',
+ 'company.activities',
+ 'company.tax_rates',
+ 'company.documents',
+ 'company.company_gateways.gateway',
+ 'company.users.company_user',
+ 'company.task_statuses',
+ 'company.payment_terms',
+ 'company.groups',
+ 'company.designs.company',
+ 'company.expense_categories',
+ 'company.subscriptions',
+ ];
public function __construct()
{
@@ -216,159 +217,160 @@ class BaseController extends Controller
$transformer = new $this->entity_transformer($this->serializer);
$updated_at = request()->has('updated_at') ? request()->input('updated_at') : 0;
- if ($user->getCompany()->is_large && $updated_at == 0){
- $updated_at = time();
+ if ($user->getCompany()->is_large && $updated_at == 0) {
+ $updated_at = time();
}
$updated_at = date('Y-m-d H:i:s', $updated_at);
$query->with(
[
- 'company' => function ($query) use ($updated_at, $user) {
- $query->whereNotNull('updated_at')->with('documents','users');
- },
- 'company.clients' => function ($query) use ($updated_at, $user) {
- $query->where('clients.updated_at', '>=', $updated_at)->with('contacts.company', 'gateway_tokens', 'documents');
+ 'company' => function ($query) use ($updated_at, $user) {
+ $query->whereNotNull('updated_at')->with('documents', 'users');
+ },
+ 'company.clients' => function ($query) use ($updated_at, $user) {
+ $query->where('clients.updated_at', '>=', $updated_at)->with('contacts.company', 'gateway_tokens', 'documents');
- if(!$user->hasPermission('view_client'))
- $query->where('clients.user_id', $user->id)->orWhere('clients.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_client')) {
+ $query->where('clients.user_id', $user->id)->orWhere('clients.assigned_user_id', $user->id);
+ }
+ },
+ 'company.company_gateways' => function ($query) use ($user) {
+ $query->whereNotNull('updated_at')->with('gateway');
- },
- 'company.company_gateways' => function ($query) use ($user) {
- $query->whereNotNull('updated_at')->with('gateway');
+ if (! $user->isAdmin()) {
+ $query->where('company_gateways.user_id', $user->id);
+ }
+ },
+ 'company.credits'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents');
- if(!$user->isAdmin())
- $query->where('company_gateways.user_id', $user->id);
+ if (! $user->hasPermission('view_credit')) {
+ $query->where('credits.user_id', $user->id)->orWhere('credits.assigned_user_id', $user->id);
+ }
+ },
+ 'company.designs'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('company');
- },
- 'company.credits'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents');
+ if (! $user->isAdmin()) {
+ $query->where('designs.user_id', $user->id);
+ }
+ },
+ 'company.documents'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at);
+ },
+ 'company.expenses'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('documents');
- if(!$user->hasPermission('view_credit'))
- $query->where('credits.user_id', $user->id)->orWhere('credits.assigned_user_id', $user->id);
-
- },
- 'company.designs'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('company');
-
- if(!$user->isAdmin())
- $query->where('designs.user_id', $user->id);
- },
- 'company.documents'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at);
- },
- 'company.expenses'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('documents');
-
- if(!$user->hasPermission('view_expense'))
- $query->where('expenses.user_id', $user->id)->orWhere('expenses.assigned_user_id', $user->id);
- },
- 'company.groups' => function ($query) use ($updated_at, $user) {
- $query->whereNotNull('updated_at')->with('documents');
+ if (! $user->hasPermission('view_expense')) {
+ $query->where('expenses.user_id', $user->id)->orWhere('expenses.assigned_user_id', $user->id);
+ }
+ },
+ 'company.groups' => function ($query) use ($updated_at, $user) {
+ $query->whereNotNull('updated_at')->with('documents');
// if(!$user->isAdmin())
- // $query->where('group_settings.user_id', $user->id);
- },
- 'company.invoices'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents');
+ // $query->where('group_settings.user_id', $user->id);
+ },
+ 'company.invoices'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents');
- if(!$user->hasPermission('view_invoice'))
- $query->where('invoices.user_id', $user->id)->orWhere('invoices.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_invoice')) {
+ $query->where('invoices.user_id', $user->id)->orWhere('invoices.assigned_user_id', $user->id);
+ }
+ },
+ 'company.payments'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('paymentables', 'documents');
- },
- 'company.payments'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('paymentables', 'documents');
+ if (! $user->hasPermission('view_payment')) {
+ $query->where('payments.user_id', $user->id)->orWhere('payments.assigned_user_id', $user->id);
+ }
+ },
+ 'company.payment_terms'=> function ($query) use ($updated_at, $user) {
+ $query->whereNotNull('updated_at');
- if(!$user->hasPermission('view_payment'))
- $query->where('payments.user_id', $user->id)->orWhere('payments.assigned_user_id', $user->id);
+ if (! $user->isAdmin()) {
+ $query->where('payment_terms.user_id', $user->id);
+ }
+ },
+ 'company.products' => function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('documents');
- },
- 'company.payment_terms'=> function ($query) use ($updated_at, $user) {
- $query->whereNotNull('updated_at');
+ if (! $user->hasPermission('view_product')) {
+ $query->where('products.user_id', $user->id)->orWhere('products.assigned_user_id', $user->id);
+ }
+ },
+ 'company.projects'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('documents');
- if(!$user->isAdmin())
- $query->where('payment_terms.user_id', $user->id);
+ if (! $user->hasPermission('view_project')) {
+ $query->where('projects.user_id', $user->id)->orWhere('projects.assigned_user_id', $user->id);
+ }
+ },
+ 'company.purchase_orders'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('documents');
- },
- 'company.products' => function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('documents');
+ if (! $user->hasPermission('view_purchase_order')) {
+ $query->where('purchase_orders.user_id', $user->id)->orWhere('purchase_orders.assigned_user_id', $user->id);
+ }
+ },
+ 'company.quotes'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents');
- if(!$user->hasPermission('view_product'))
- $query->where('products.user_id', $user->id)->orWhere('products.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_quote')) {
+ $query->where('quotes.user_id', $user->id)->orWhere('quotes.assigned_user_id', $user->id);
+ }
+ },
+ 'company.recurring_invoices'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents', 'client.gateway_tokens', 'client.group_settings', 'client.company');
- },
- 'company.projects'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('documents');
+ if (! $user->hasPermission('view_recurring_invoice')) {
+ $query->where('recurring_invoices.user_id', $user->id)->orWhere('recurring_invoices.assigned_user_id', $user->id);
+ }
+ },
+ 'company.recurring_expenses'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('documents');
- if(!$user->hasPermission('view_project'))
- $query->where('projects.user_id', $user->id)->orWhere('projects.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_recurring_expense')) {
+ $query->where('recurring_expenses.user_id', $user->id)->orWhere('recurring_expenses.assigned_user_id', $user->id);
+ }
+ },
+ 'company.tasks'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('documents');
- },
- 'company.purchase_orders'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('documents');
+ if (! $user->hasPermission('view_task')) {
+ $query->where('tasks.user_id', $user->id)->orWhere('tasks.assigned_user_id', $user->id);
+ }
+ },
+ 'company.tax_rates'=> function ($query) use ($updated_at, $user) {
+ $query->whereNotNull('updated_at');
+ },
+ 'company.vendors'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('contacts', 'documents');
- if(!$user->hasPermission('view_purchase_order'))
- $query->where('purchase_orders.user_id', $user->id)->orWhere('purchase_orders.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_vendor')) {
+ $query->where('vendors.user_id', $user->id)->orWhere('vendors.assigned_user_id', $user->id);
+ }
+ },
+ 'company.expense_categories'=> function ($query) use ($updated_at, $user) {
+ $query->whereNotNull('updated_at');
+ },
+ 'company.task_statuses'=> function ($query) use ($updated_at, $user) {
+ $query->whereNotNull('updated_at');
+ },
+ 'company.activities'=> function ($query) use ($user) {
+ if (! $user->isAdmin()) {
+ $query->where('activities.user_id', $user->id);
+ }
+ },
+ 'company.subscriptions'=> function ($query) use ($updated_at, $user) {
+ $query->whereNotNull('updated_at');
- },
- 'company.quotes'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents');
-
- if(!$user->hasPermission('view_quote'))
- $query->where('quotes.user_id', $user->id)->orWhere('quotes.assigned_user_id', $user->id);
-
- },
- 'company.recurring_invoices'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents', 'client.gateway_tokens', 'client.group_settings', 'client.company');
-
- if(!$user->hasPermission('view_recurring_invoice'))
- $query->where('recurring_invoices.user_id', $user->id)->orWhere('recurring_invoices.assigned_user_id', $user->id);
-
- },
- 'company.recurring_expenses'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('documents');
-
- if(!$user->hasPermission('view_recurring_expense'))
- $query->where('recurring_expenses.user_id', $user->id)->orWhere('recurring_expenses.assigned_user_id', $user->id);
-
- },
- 'company.tasks'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('documents');
-
- if(!$user->hasPermission('view_task'))
- $query->where('tasks.user_id', $user->id)->orWhere('tasks.assigned_user_id', $user->id);
-
- },
- 'company.tax_rates'=> function ($query) use ($updated_at, $user) {
- $query->whereNotNull('updated_at');
- },
- 'company.vendors'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('contacts', 'documents');
-
- if(!$user->hasPermission('view_vendor'))
- $query->where('vendors.user_id', $user->id)->orWhere('vendors.assigned_user_id', $user->id);
-
- },
- 'company.expense_categories'=> function ($query) use ($updated_at, $user) {
- $query->whereNotNull('updated_at');
- },
- 'company.task_statuses'=> function ($query) use ($updated_at, $user) {
- $query->whereNotNull('updated_at');
- },
- 'company.activities'=> function ($query) use($user) {
-
- if(!$user->isAdmin())
- $query->where('activities.user_id', $user->id);
-
- },
- 'company.subscriptions'=> function ($query) use($updated_at, $user) {
- $query->whereNotNull('updated_at');
-
- if(!$user->isAdmin())
- $query->where('subscriptions.user_id', $user->id);
-
- }
- ]
+ if (! $user->isAdmin()) {
+ $query->where('subscriptions.user_id', $user->id);
+ }
+ },
+ ]
);
if ($query instanceof Builder) {
@@ -387,8 +389,7 @@ class BaseController extends Controller
protected function miniLoadResponse($query)
{
- $user = auth()->user();
-
+ $user = auth()->user();
$this->serializer = request()->input('serializer') ?: EntityTransformer::API_SERIALIZER_ARRAY;
@@ -405,35 +406,30 @@ class BaseController extends Controller
$query->with(
[
- 'company' => function ($query) use ($created_at, $user) {
- $query->whereNotNull('created_at')->with('documents','users');
- },
- 'company.designs'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('company');
-
- },
- 'company.documents'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at);
- },
- 'company.groups'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('documents');
-
- },
- 'company.payment_terms'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at);
-
- },
- 'company.tax_rates'=> function ($query) use ($created_at, $user) {
- $query->whereNotNull('created_at');
-
- },
- 'company.activities'=> function ($query) use($user) {
-
- if(!$user->isAdmin())
- $query->where('activities.user_id', $user->id);
-
- }
- ]
+ 'company' => function ($query) use ($created_at, $user) {
+ $query->whereNotNull('created_at')->with('documents', 'users');
+ },
+ 'company.designs'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('company');
+ },
+ 'company.documents'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at);
+ },
+ 'company.groups'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('documents');
+ },
+ 'company.payment_terms'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at);
+ },
+ 'company.tax_rates'=> function ($query) use ($created_at, $user) {
+ $query->whereNotNull('created_at');
+ },
+ 'company.activities'=> function ($query) use ($user) {
+ if (! $user->isAdmin()) {
+ $query->where('activities.user_id', $user->id);
+ }
+ },
+ ]
);
if ($query instanceof Builder) {
@@ -448,21 +444,19 @@ class BaseController extends Controller
}
return $this->response($this->manager->createData($resource)->toArray());
-
-
}
protected function timeConstrainedResponse($query)
{
-
$user = auth()->user();
- if ($user->getCompany()->is_large){
- $this->manager->parseIncludes($this->mini_load);
- return $this->miniLoadResponse($query);
+ if ($user->getCompany()->is_large) {
+ $this->manager->parseIncludes($this->mini_load);
+
+ return $this->miniLoadResponse($query);
+ } else {
+ $this->manager->parseIncludes($this->first_load);
}
- else
- $this->manager->parseIncludes($this->first_load);
$this->serializer = request()->input('serializer') ?: EntityTransformer::API_SERIALIZER_ARRAY;
@@ -479,153 +473,147 @@ class BaseController extends Controller
$query->with(
[
- 'company' => function ($query) use ($created_at, $user) {
- $query->whereNotNull('created_at')->with('documents','users');
- },
- 'company.clients' => function ($query) use ($created_at, $user) {
- $query->where('clients.created_at', '>=', $created_at)->with('contacts.company', 'gateway_tokens', 'documents');
+ 'company' => function ($query) use ($created_at, $user) {
+ $query->whereNotNull('created_at')->with('documents', 'users');
+ },
+ 'company.clients' => function ($query) use ($created_at, $user) {
+ $query->where('clients.created_at', '>=', $created_at)->with('contacts.company', 'gateway_tokens', 'documents');
- if(!$user->hasPermission('view_client'))
- $query->where('clients.user_id', $user->id)->orWhere('clients.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_client')) {
+ $query->where('clients.user_id', $user->id)->orWhere('clients.assigned_user_id', $user->id);
+ }
+ },
+ 'company.company_gateways' => function ($query) use ($user) {
+ $query->whereNotNull('created_at')->with('gateway');
- },
- 'company.company_gateways' => function ($query) use ($user) {
- $query->whereNotNull('created_at')->with('gateway');
+ if (! $user->isAdmin()) {
+ $query->where('company_gateways.user_id', $user->id);
+ }
+ },
+ 'company.credits'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('invitations', 'documents');
- if(!$user->isAdmin())
- $query->where('company_gateways.user_id', $user->id);
+ if (! $user->hasPermission('view_credit')) {
+ $query->where('credits.user_id', $user->id)->orWhere('credits.assigned_user_id', $user->id);
+ }
+ },
+ 'company.documents'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at);
+ },
+ 'company.expenses'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('documents');
- },
- 'company.credits'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('invitations', 'documents');
+ if (! $user->hasPermission('view_expense')) {
+ $query->where('expenses.user_id', $user->id)->orWhere('expenses.assigned_user_id', $user->id);
+ }
+ },
+ 'company.groups' => function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('documents');
+ },
+ 'company.invoices'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('invitations', 'documents');
- if(!$user->hasPermission('view_credit'))
- $query->where('credits.user_id', $user->id)->orWhere('credits.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_invoice')) {
+ $query->where('invoices.user_id', $user->id)->orWhere('invoices.assigned_user_id', $user->id);
+ }
+ },
+ 'company.payments'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('paymentables', 'documents');
- },
- 'company.documents'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at);
- },
- 'company.expenses'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('documents');
+ if (! $user->hasPermission('view_payment')) {
+ $query->where('payments.user_id', $user->id)->orWhere('payments.assigned_user_id', $user->id);
+ }
+ },
+ 'company.payment_terms'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at);
+ },
+ 'company.products' => function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('documents');
- if(!$user->hasPermission('view_expense'))
- $query->where('expenses.user_id', $user->id)->orWhere('expenses.assigned_user_id', $user->id);
- },
- 'company.groups' => function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('documents');
- },
- 'company.invoices'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('invitations', 'documents');
+ if (! $user->hasPermission('view_product')) {
+ $query->where('products.user_id', $user->id)->orWhere('products.assigned_user_id', $user->id);
+ }
+ },
+ 'company.projects'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('documents');
- if(!$user->hasPermission('view_invoice'))
- $query->where('invoices.user_id', $user->id)->orWhere('invoices.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_project')) {
+ $query->where('projects.user_id', $user->id)->orWhere('projects.assigned_user_id', $user->id);
+ }
+ },
+ 'company.purchase_orders'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('documents');
- },
- 'company.payments'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('paymentables', 'documents');
+ if (! $user->hasPermission('view_purchase_order')) {
+ $query->where('purchase_orders.user_id', $user->id)->orWhere('purchase_orders.assigned_user_id', $user->id);
+ }
+ },
+ 'company.quotes'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('invitations', 'documents');
- if(!$user->hasPermission('view_payment'))
- $query->where('payments.user_id', $user->id)->orWhere('payments.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_quote')) {
+ $query->where('quotes.user_id', $user->id)->orWhere('quotes.assigned_user_id', $user->id);
+ }
+ },
+ 'company.recurring_invoices'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('invitations', 'documents', 'client.gateway_tokens', 'client.group_settings', 'client.company');
- },
- 'company.payment_terms'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at);
+ if (! $user->hasPermission('view_recurring_invoice')) {
+ $query->where('recurring_invoices.user_id', $user->id)->orWhere('recurring_invoices.assigned_user_id', $user->id);
+ }
+ },
+ 'company.tasks'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('documents');
+ if (! $user->hasPermission('view_task')) {
+ $query->where('tasks.user_id', $user->id)->orWhere('tasks.assigned_user_id', $user->id);
+ }
+ },
+ 'company.tax_rates' => function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at);
+ },
+ 'company.vendors'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('contacts', 'documents');
- },
- 'company.products' => function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('documents');
+ if (! $user->hasPermission('view_vendor')) {
+ $query->where('vendors.user_id', $user->id)->orWhere('vendors.assigned_user_id', $user->id);
+ }
+ },
+ 'company.expense_categories'=> function ($query) use ($created_at, $user) {
+ $query->whereNotNull('created_at');
+ },
+ 'company.task_statuses'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at);
+ },
+ 'company.activities'=> function ($query) use ($user) {
+ if (! $user->isAdmin()) {
+ $query->where('activities.user_id', $user->id);
+ }
+ },
+ 'company.webhooks'=> function ($query) use ($user) {
+ if (! $user->isAdmin()) {
+ $query->where('webhooks.user_id', $user->id);
+ }
+ },
+ 'company.tokens'=> function ($query) use ($user) {
+ $query->where('company_tokens.user_id', $user->id);
+ },
+ 'company.system_logs',
+ 'company.subscriptions'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at);
- if(!$user->hasPermission('view_product'))
- $query->where('products.user_id', $user->id)->orWhere('products.assigned_user_id', $user->id);
+ if (! $user->isAdmin()) {
+ $query->where('subscriptions.user_id', $user->id);
+ }
+ },
+ 'company.recurring_expenses'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('documents');
- },
- 'company.projects'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('documents');
-
- if(!$user->hasPermission('view_project'))
- $query->where('projects.user_id', $user->id)->orWhere('projects.assigned_user_id', $user->id);
-
- },
- 'company.purchase_orders'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('documents');
-
- if(!$user->hasPermission('view_purchase_order'))
- $query->where('purchase_orders.user_id', $user->id)->orWhere('purchase_orders.assigned_user_id', $user->id);
-
- },
- 'company.quotes'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('invitations', 'documents');
-
- if(!$user->hasPermission('view_quote'))
- $query->where('quotes.user_id', $user->id)->orWhere('quotes.assigned_user_id', $user->id);
-
- },
- 'company.recurring_invoices'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('invitations', 'documents', 'client.gateway_tokens', 'client.group_settings', 'client.company');
-
- if(!$user->hasPermission('view_recurring_invoice'))
- $query->where('recurring_invoices.user_id', $user->id)->orWhere('recurring_invoices.assigned_user_id', $user->id);
-
- },
- 'company.tasks'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('documents');
-
- if(!$user->hasPermission('view_task'))
- $query->where('tasks.user_id', $user->id)->orWhere('tasks.assigned_user_id', $user->id);
-
- },
- 'company.tax_rates' => function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at);
-
- },
- 'company.vendors'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('contacts', 'documents');
-
- if(!$user->hasPermission('view_vendor'))
- $query->where('vendors.user_id', $user->id)->orWhere('vendors.assigned_user_id', $user->id);
-
- },
- 'company.expense_categories'=> function ($query) use ($created_at, $user) {
- $query->whereNotNull('created_at');
-
- },
- 'company.task_statuses'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at);
-
- },
- 'company.activities'=> function ($query) use($user) {
-
- if(!$user->isAdmin())
- $query->where('activities.user_id', $user->id);
-
- },
- 'company.webhooks'=> function ($query) use($user) {
-
- if(!$user->isAdmin())
- $query->where('webhooks.user_id', $user->id);
-
- },
- 'company.tokens'=> function ($query) use($user) {
- $query->where('company_tokens.user_id', $user->id);
- },
- 'company.system_logs',
- 'company.subscriptions'=> function ($query) use($created_at, $user) {
- $query->where('created_at', '>=', $created_at);
-
- if(!$user->isAdmin())
- $query->where('subscriptions.user_id', $user->id);
-
- },
- 'company.recurring_expenses'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('documents');
-
- if(!$user->hasPermission('view_recurring_expense'))
- $query->where('recurring_expenses.user_id', $user->id)->orWhere('recurring_expenses.assigned_user_id', $user->id);
-
- },
- ]
+ if (! $user->hasPermission('view_recurring_expense')) {
+ $query->where('recurring_expenses.user_id', $user->id)->orWhere('recurring_expenses.assigned_user_id', $user->id);
+ }
+ },
+ ]
);
if ($query instanceof Builder) {
@@ -640,13 +628,10 @@ class BaseController extends Controller
}
return $this->response($this->manager->createData($resource)->toArray());
-
-
}
protected function listResponse($query)
{
-
$this->buildManager();
$transformer = new $this->entity_transformer(request()->input('serializer'));
@@ -737,9 +722,9 @@ class BaseController extends Controller
public static function getApiHeaders($count = 0)
{
return [
- 'Content-Type' => 'application/json',
- 'X-Api-Version' => config('ninja.minimum_client_version'),
- 'X-App-Version' => config('ninja.app_version'),
+ 'Content-Type' => 'application/json',
+ 'X-Api-Version' => config('ninja.minimum_client_version'),
+ 'X-App-Version' => config('ninja.app_version'),
];
}
@@ -812,11 +797,11 @@ class BaseController extends Controller
$this->buildCache();
- if(Ninja::isSelfHost() && $account->set_react_as_default_ap)
+ if (Ninja::isSelfHost() && $account->set_react_as_default_ap) {
return response()->view('react.index', $data)->header('X-Frame-Options', 'SAMEORIGIN', false);
- else
+ } else {
return response()->view('index.index', $data)->header('X-Frame-Options', 'SAMEORIGIN', false);
-
+ }
}
return redirect('/setup');
@@ -826,10 +811,9 @@ class BaseController extends Controller
{
$build = '';
- if(request()->has('build')) {
+ if (request()->has('build')) {
$build = request()->input('build');
- }
- elseif(Ninja::isHosted()){
+ } elseif (Ninja::isHosted()) {
return 'main.dart.js';
}
@@ -841,29 +825,28 @@ class BaseController extends Controller
case 'last':
return 'main.last.dart.js';
case 'next':
- return 'main.next.dart.js';
+ return 'main.next.dart.js';
case 'profile':
- return 'main.profile.dart.js';
- case 'html':
- return 'main.html.dart.js';
+ return 'main.profile.dart.js';
+ case 'html':
+ return 'main.html.dart.js';
default:
return 'main.foss.dart.js';
}
-
}
public function checkFeature($feature)
{
+ if (auth()->user()->account->hasFeature($feature)) {
+ return true;
+ }
- if(auth()->user()->account->hasFeature($feature))
- return true;
-
- return false;
+ return false;
}
public function featureFailure()
{
- return response()->json(['message' => 'Upgrade to a paid plan for this feature.'], 403);
+ return response()->json(['message' => 'Upgrade to a paid plan for this feature.'], 403);
}
}
diff --git a/app/Http/Controllers/ChartController.php b/app/Http/Controllers/ChartController.php
index 2e39aa4fd736..8dac67dafdf4 100644
--- a/app/Http/Controllers/ChartController.php
+++ b/app/Http/Controllers/ChartController.php
@@ -18,7 +18,6 @@ use Illuminate\Http\Response;
class ChartController extends BaseController
{
-
public function __construct()
{
parent::__construct();
@@ -81,5 +80,4 @@ class ChartController extends BaseController
return response()->json($cs->chart_summary($request->input('start_date'), $request->input('end_date')), 200);
}
-
}
diff --git a/app/Http/Controllers/ClientController.php b/app/Http/Controllers/ClientController.php
index 6006987f6fdf..b99917040a0e 100644
--- a/app/Http/Controllers/ClientController.php
+++ b/app/Http/Controllers/ClientController.php
@@ -38,6 +38,7 @@ use App\Utils\Traits\Uploadable;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
+
/**
* Class ClientController.
* @covers App\Http\Controllers\ClientController
@@ -277,7 +278,6 @@ class ClientController extends BaseController
*/
public function update(UpdateClientRequest $request, Client $client)
{
-
if ($request->entityIsDeleted($client)) {
return $request->disallowUpdate();
}
@@ -383,10 +383,8 @@ class ClientController extends BaseController
$client->load('contacts', 'primary_contact');
/* Set the client country to the company if none is set */
- if(!$client->country_id && strlen($client->company->settings->country_id) > 1){
-
+ if (! $client->country_id && strlen($client->company->settings->country_id) > 1) {
$client->update(['country_id' => $client->company->settings->country_id]);
-
}
$this->uploadLogo($request->file('company_logo'), $client->company, $client);
@@ -448,11 +446,9 @@ class ClientController extends BaseController
*/
public function destroy(DestroyClientRequest $request, Client $client)
{
+ $this->client_repo->delete($client);
- $this->client_repo->delete($client);
-
- return $this->itemResponse($client->fresh());
-
+ return $this->itemResponse($client->fresh());
}
/**
@@ -513,8 +509,9 @@ class ClientController extends BaseController
$ids = request()->input('ids');
$clients = Client::withTrashed()->whereIn('id', $this->transformKeys($ids))->cursor();
- if(!in_array($action, ['restore','archive','delete']))
+ if (! in_array($action, ['restore', 'archive', 'delete'])) {
return response()->json(['message' => 'That action is not available.'], 400);
+ }
$clients->each(function ($client, $key) use ($action) {
if (auth()->user()->can('edit', $client)) {
@@ -578,15 +575,15 @@ class ClientController extends BaseController
*/
public function upload(UploadClientRequest $request, Client $client)
{
-
- if(!$this->checkFeature(Account::FEATURE_DOCUMENTS))
+ if (! $this->checkFeature(Account::FEATURE_DOCUMENTS)) {
return $this->featureFailure();
-
- if ($request->has('documents'))
+ }
+
+ if ($request->has('documents')) {
$this->saveDocuments($request->file('documents'), $client);
+ }
return $this->itemResponse($client->fresh());
-
}
/**
@@ -642,10 +639,8 @@ class ClientController extends BaseController
public function purge(PurgeClientRequest $request, Client $client)
{
//delete all documents
- $client->documents->each(function ($document){
-
+ $client->documents->each(function ($document) {
Storage::disk(config('filesystems.default'))->delete($document->url);
-
});
//force delete the client
diff --git a/app/Http/Controllers/ClientGatewayTokenController.php b/app/Http/Controllers/ClientGatewayTokenController.php
index 83242b744691..44912c5647a4 100644
--- a/app/Http/Controllers/ClientGatewayTokenController.php
+++ b/app/Http/Controllers/ClientGatewayTokenController.php
@@ -273,7 +273,6 @@ class ClientGatewayTokenController extends BaseController
*/
public function update(UpdateClientGatewayTokenRequest $request, ClientGatewayToken $client_gateway_token)
{
-
$client_gateway_token = $this->client_gateway_token_repo->save($request->all(), $client_gateway_token);
return $this->itemResponse($client_gateway_token->fresh());
@@ -427,11 +426,8 @@ class ClientGatewayTokenController extends BaseController
*/
public function destroy(DestroyClientGatewayTokenRequest $request, ClientGatewayToken $client_gateway_token)
{
+ $this->client_gateway_token_repo->delete($client_gateway_token);
- $this->client_gateway_token_repo->delete($client_gateway_token);
-
- return $this->itemResponse($client_gateway_token->fresh());
-
+ return $this->itemResponse($client_gateway_token->fresh());
}
-
}
diff --git a/app/Http/Controllers/ClientPortal/ApplePayDomainController.php b/app/Http/Controllers/ClientPortal/ApplePayDomainController.php
index 2565c7f57942..199f500016e4 100644
--- a/app/Http/Controllers/ClientPortal/ApplePayDomainController.php
+++ b/app/Http/Controllers/ClientPortal/ApplePayDomainController.php
@@ -21,7 +21,6 @@ use Illuminate\Support\Facades\Storage;
class ApplePayDomainController extends Controller
{
-
private array $stripe_keys = ['d14dd26a47cecc30fdd65700bfb67b34', 'd14dd26a37cecc30fdd65700bfb55b23'];
public function showAppleMerchantId(Request $request)
@@ -29,20 +28,15 @@ class ApplePayDomainController extends Controller
/* Self Host */
- if(Ninja::isSelfHost()){
-
+ if (Ninja::isSelfHost()) {
$cgs = CompanyGateway::whereIn('gateway_key', $this->stripe_keys)
->where('is_deleted', false)
->get();
- foreach($cgs as $cg)
- {
-
- if($cg->getConfigField('appleDomainVerification')){
- return response($cg->getConfigField('appleDomainVerification'),200);
-
+ foreach ($cgs as $cg) {
+ if ($cg->getConfigField('appleDomainVerification')) {
+ return response($cg->getConfigField('appleDomainVerification'), 200);
}
-
}
return response('', 400);
@@ -52,52 +46,44 @@ class ApplePayDomainController extends Controller
$domain_name = $request->getHost();
- if (strpos($domain_name, 'invoicing.co') !== false)
- {
+ if (strpos($domain_name, 'invoicing.co') !== false) {
$subdomain = explode('.', $domain_name)[0];
-
+
$query = [
'subdomain' => $subdomain,
'portal_mode' => 'subdomain',
];
- if($company = MultiDB::findAndSetDbByDomain($query)){
- return $this->resolveAppleMerchantId($company);
+ if ($company = MultiDB::findAndSetDbByDomain($query)) {
+ return $this->resolveAppleMerchantId($company);
}
}
- $query = [
+ $query = [
'portal_domain' => $request->getSchemeAndHttpHost(),
'portal_mode' => 'domain',
];
- if($company = MultiDB::findAndSetDbByDomain($query)){
+ if ($company = MultiDB::findAndSetDbByDomain($query)) {
return $this->resolveAppleMerchantId($company);
}
return response('', 400);
-
}
private function resolveAppleMerchantId($company)
{
-
$cgs = $company->company_gateways()
->whereIn('gateway_key', $this->stripe_keys)
->where('is_deleted', false)
->get();
- foreach($cgs as $cg)
- {
-
- if($cg->getConfigField('appleDomainVerification')){
- return response($cg->getConfigField('appleDomainVerification'),200);
+ foreach ($cgs as $cg) {
+ if ($cg->getConfigField('appleDomainVerification')) {
+ return response($cg->getConfigField('appleDomainVerification'), 200);
}
-
}
return response('', 400);
-
}
-
}
diff --git a/app/Http/Controllers/ClientPortal/ContactHashLoginController.php b/app/Http/Controllers/ClientPortal/ContactHashLoginController.php
index 4bff4678c92b..1b97219077f0 100644
--- a/app/Http/Controllers/ClientPortal/ContactHashLoginController.php
+++ b/app/Http/Controllers/ClientPortal/ContactHashLoginController.php
@@ -18,7 +18,6 @@ use Auth;
class ContactHashLoginController extends Controller
{
-
/**
* Logs a user into the client portal using their contact_key
* @param string $contact_key The contact key
@@ -26,23 +25,20 @@ class ContactHashLoginController extends Controller
*/
public function login(string $contact_key)
{
- if(request()->has('subscription') && request()->subscription == 'true') {
-
+ if (request()->has('subscription') && request()->subscription == 'true') {
$recurring_invoice = RecurringInvoice::where('client_id', auth()->guard('contact')->client->id)
->whereNotNull('subscription_id')
->whereNull('deleted_at')
->first();
return redirect()->route('client.recurring_invoice.show', $recurring_invoice->hashed_id);
-
}
- return redirect($this->setRedirectPath());
+ return redirect($this->setRedirectPath());
}
public function magicLink(string $magic_link)
{
-
return redirect($this->setRedirectPath());
}
@@ -53,20 +49,18 @@ class ContactHashLoginController extends Controller
private function setRedirectPath()
{
-
- if(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_INVOICES)
+ if (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_INVOICES) {
return '/client/invoices';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_RECURRING_INVOICES)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_RECURRING_INVOICES) {
return '/client/recurring_invoices';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_QUOTES)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_QUOTES) {
return '/client/quotes';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_CREDITS)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_CREDITS) {
return '/client/credits';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_TASKS)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_TASKS) {
return '/client/tasks';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_EXPENSES)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_EXPENSES) {
return '/client/expenses';
-
+ }
}
-
}
diff --git a/app/Http/Controllers/ClientPortal/CreditController.php b/app/Http/Controllers/ClientPortal/CreditController.php
index 9bf792ef76a2..9b6ee3fefed8 100644
--- a/app/Http/Controllers/ClientPortal/CreditController.php
+++ b/app/Http/Controllers/ClientPortal/CreditController.php
@@ -34,17 +34,15 @@ class CreditController extends Controller
$data = [
'credit' => $credit,
- 'key' => $invitation ? $invitation->key : false
+ 'key' => $invitation ? $invitation->key : false,
];
- if ($invitation && auth()->guard('contact') && ! request()->has('silent') && ! $invitation->viewed_date) {
+ if ($invitation && auth()->guard('contact') && ! request()->has('silent') && ! $invitation->viewed_date) {
+ $invitation->markViewed();
- $invitation->markViewed();
-
- event(new InvitationWasViewed($credit, $invitation, $credit->company, Ninja::eventVars()));
- event(new CreditWasViewed($invitation, $invitation->company, Ninja::eventVars()));
-
- }
+ event(new InvitationWasViewed($credit, $invitation, $credit->company, Ninja::eventVars()));
+ event(new CreditWasViewed($invitation, $invitation->company, Ninja::eventVars()));
+ }
if ($request->query('mode') === 'fullscreen') {
return render('credits.show-fullscreen', $data);
diff --git a/app/Http/Controllers/ClientPortal/DashboardController.php b/app/Http/Controllers/ClientPortal/DashboardController.php
index 3e58d53166cc..fbf159ecd461 100644
--- a/app/Http/Controllers/ClientPortal/DashboardController.php
+++ b/app/Http/Controllers/ClientPortal/DashboardController.php
@@ -22,7 +22,7 @@ class DashboardController extends Controller
*/
public function index()
{
- return redirect()->route('client.invoices.index');
+ return redirect()->route('client.invoices.index');
//return $this->render('dashboard.index');
}
}
diff --git a/app/Http/Controllers/ClientPortal/DocumentController.php b/app/Http/Controllers/ClientPortal/DocumentController.php
index 60a087a29d4c..835c1bb640c1 100644
--- a/app/Http/Controllers/ClientPortal/DocumentController.php
+++ b/app/Http/Controllers/ClientPortal/DocumentController.php
@@ -60,8 +60,9 @@ class DocumentController extends Controller
$headers = [];
- if(request()->input('inline') == 'true')
+ if (request()->input('inline') == 'true') {
$headers = array_merge($headers, ['Content-Disposition' => 'inline']);
+ }
return Storage::disk($document->disk)->download($document->url, $document->name, $headers);
}
@@ -74,29 +75,22 @@ class DocumentController extends Controller
$zipFile = new \PhpZip\ZipFile();
- try{
-
+ try {
foreach ($documents as $document) {
$zipFile->addFile(TempFile::path($document->filePath()), $document->name);
}
- $filename = now() . '-documents.zip';
- $filepath = sys_get_temp_dir() . '/' . $filename;
+ $filename = now().'-documents.zip';
+ $filepath = sys_get_temp_dir().'/'.$filename;
- $zipFile->saveAsFile($filepath) // save the archive to a file
+ $zipFile->saveAsFile($filepath) // save the archive to a file
->close(); // close archive
-
- return response()->download($filepath, $filename)->deleteFileAfterSend(true);
- }
- catch(\PhpZip\Exception\ZipException $e){
+ return response()->download($filepath, $filename)->deleteFileAfterSend(true);
+ } catch (\PhpZip\Exception\ZipException $e) {
// handle exception
- }
- finally{
+ } finally {
$zipFile->close();
}
-
}
-
-
}
diff --git a/app/Http/Controllers/ClientPortal/EntityViewController.php b/app/Http/Controllers/ClientPortal/EntityViewController.php
index f521f21fa736..fb73c3ce4a07 100644
--- a/app/Http/Controllers/ClientPortal/EntityViewController.php
+++ b/app/Http/Controllers/ClientPortal/EntityViewController.php
@@ -45,7 +45,6 @@ class EntityViewController extends Controller
$key = $entity_type.'_id';
-
$invitation = $invitation_entity::where('key', $invitation_key)
->with('contact.client')
->firstOrFail();
@@ -139,7 +138,7 @@ class EntityViewController extends Controller
$invitation = $entity_obj::where('key', $request->invitation_key)
->whereHas($request->entity_type, function ($query) {
- $query->where('is_deleted',0);
+ $query->where('is_deleted', 0);
})
->with('contact.client')
->first();
@@ -154,15 +153,16 @@ class EntityViewController extends Controller
if (! $invitation->viewed_date) {
$invitation->markViewed();
- if(!session()->get('is_silent'))
+ if (! session()->get('is_silent')) {
event(new InvitationWasViewed($invitation->{$request->entity_type}, $invitation, $invitation->{$request->entity_type}->company, Ninja::eventVars()));
+ }
- if(!session()->get('is_silent'))
+ if (! session()->get('is_silent')) {
$this->fireEntityViewedEvent($invitation, $request->entity_type);
+ }
}
-
+
return redirect()->route('client.'.$request->entity_type.'.show', [$request->entity_type => $this->encodePrimaryKey($invitation->{$key})]);
-
}
private function fireEntityViewedEvent($invitation, $entity_string)
@@ -182,5 +182,4 @@ class EntityViewController extends Controller
break;
}
}
-
}
diff --git a/app/Http/Controllers/ClientPortal/InvitationController.php b/app/Http/Controllers/ClientPortal/InvitationController.php
index ab353600c698..5d421a2f026a 100644
--- a/app/Http/Controllers/ClientPortal/InvitationController.php
+++ b/app/Http/Controllers/ClientPortal/InvitationController.php
@@ -83,11 +83,8 @@ class InvitationController extends Controller
$invitation = $entity_obj::withTrashed()
->with($entity)
->where('key', $invitation_key)
- // ->whereHas($entity, function ($query) {
- // $query->where('is_deleted',0);
- // })
->with('contact.client')
- ->first();
+ ->firstOrFail();
if($invitation->{$entity}->is_deleted)
return $this->render('generic.not_available', ['account' => $invitation->company->account, 'company' => $invitation->company]);
@@ -122,7 +119,6 @@ class InvitationController extends Controller
return redirect()->route('client.login');
} else {
- nlog("else - default - login contact");
request()->session()->invalidate();
auth()->guard('contact')->loginUsingId($client_contact->id, true);
}
@@ -198,7 +194,7 @@ class InvitationController extends Controller
$file_name = $invitation->{$entity}->numberFormatter().'.pdf';
- $file = CreateRawPdf::dispatchNow($invitation, $invitation->company->db);
+ $file = (new CreateRawPdf($invitation, $invitation->company->db))->handle();
$headers = ['Content-Type' => 'application/pdf'];
diff --git a/app/Http/Controllers/ClientPortal/InvoiceController.php b/app/Http/Controllers/ClientPortal/InvoiceController.php
index f3a49b20ead1..b5f42beb0783 100644
--- a/app/Http/Controllers/ClientPortal/InvoiceController.php
+++ b/app/Http/Controllers/ClientPortal/InvoiceController.php
@@ -26,9 +26,9 @@ use App\Utils\Traits\MakesHash;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
+use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
-use Illuminate\Http\Request;
class InvoiceController extends Controller
{
@@ -41,7 +41,6 @@ class InvoiceController extends Controller
*/
public function index(ShowInvoicesRequest $request)
{
-
return $this->render('invoices.index');
}
@@ -61,23 +60,22 @@ class InvoiceController extends Controller
$invitation = $invoice->invitations()->where('client_contact_id', auth()->guard('contact')->user()->id)->first();
- if ($invitation && auth()->guard('contact') && !session()->get('is_silent') && ! $invitation->viewed_date) {
+ if ($invitation && auth()->guard('contact') && ! session()->get('is_silent') && ! $invitation->viewed_date) {
+ $invitation->markViewed();
- $invitation->markViewed();
-
- event(new InvitationWasViewed($invoice, $invitation, $invoice->company, Ninja::eventVars()));
- event(new InvoiceWasViewed($invitation, $invitation->company, Ninja::eventVars()));
-
- }
+ event(new InvitationWasViewed($invoice, $invitation, $invoice->company, Ninja::eventVars()));
+ event(new InvoiceWasViewed($invitation, $invitation->company, Ninja::eventVars()));
+ }
$data = [
'invoice' => $invoice,
- 'key' => $invitation ? $invitation->key : false
+ 'key' => $invitation ? $invitation->key : false,
];
if ($request->query('mode') === 'fullscreen') {
return render('invoices.show-fullscreen', $data);
}
+
return $this->render('invoices.show', $data);
}
@@ -87,7 +85,6 @@ class InvoiceController extends Controller
* @param ProcessInvoicesInBulkRequest $request
* @return mixed
*/
-
public function catch_bulk()
{
return $this->render('invoices.index');
@@ -110,14 +107,14 @@ class InvoiceController extends Controller
public function downloadInvoices($ids)
{
-
$data['invoices'] = Invoice::whereIn('id', $ids)
->whereClientId(auth()->guard('contact')->user()->client->id)
->withTrashed()
->get();
- if(count($data['invoices']) == 0)
+ if (count($data['invoices']) == 0) {
return back()->with(['message' => ctrans('texts.no_items_selected')]);
+ }
return $this->render('invoices.download', $data);
}
@@ -125,11 +122,13 @@ class InvoiceController extends Controller
public function download(Request $request)
{
$transformed_ids = $this->transformKeys($request->invoices);
+
return $this->downloadInvoicePDF((array) $transformed_ids);
}
+
/**
- * @param array $ids
- * @return Factory|View|RedirectResponse
+ * @param array $ids
+ * @return Factory|View|RedirectResponse
*/
private function makePayment(array $ids)
{
@@ -151,21 +150,19 @@ class InvoiceController extends Controller
//iterate and sum the payable amounts either partial or balance
$total = 0;
- foreach($invoices as $invoice)
- {
-
- if($invoice->partial > 0)
+ foreach ($invoices as $invoice) {
+ if ($invoice->partial > 0) {
$total += $invoice->partial;
- else
+ } else {
$total += $invoice->balance;
-
+ }
}
//format data
$invoices->map(function ($invoice) {
$invoice->service()->removeUnpaidGatewayFees();
$invoice->balance = $invoice->balance > 0 ? Number::formatValue($invoice->balance, $invoice->client->currency()) : 0;
- $invoice->partial = $invoice->partial > 0 ? Number::formatValue($invoice->partial, $invoice->client->currency()) : 0;
+ $invoice->partial = $invoice->partial > 0 ? Number::formatValue($invoice->partial, $invoice->client->currency()) : 0;
return $invoice;
});
@@ -212,46 +209,39 @@ class InvoiceController extends Controller
if ($invoices->count() == 1) {
$invoice = $invoices->first();
- $file = $invoice->service()->getInvoicePdf(auth()->guard('contact')->user());
+ $file = $invoice->service()->getInvoicePdf(auth()->guard('contact')->user());
- // return response()->download(file_get_contents(public_path($file)));
+ // return response()->download(file_get_contents(public_path($file)));
- return response()->streamDownload(function () use($file) {
- echo Storage::get($file);
- }, basename($file), ['Content-Type' => 'application/pdf']);
+ return response()->streamDownload(function () use ($file) {
+ echo Storage::get($file);
+ }, basename($file), ['Content-Type' => 'application/pdf']);
}
return $this->buildZip($invoices);
-
}
-
private function buildZip($invoices)
{
// create new archive
$zipFile = new \PhpZip\ZipFile();
- try{
-
+ try {
foreach ($invoices as $invoice) {
- #add it to the zip
+ //add it to the zip
$zipFile->addFromString(basename($invoice->pdf_file_path()), file_get_contents($invoice->pdf_file_path(null, 'url', true)));
-
}
$filename = date('Y-m-d').'_'.str_replace(' ', '_', trans('texts.invoices')).'.zip';
- $filepath = sys_get_temp_dir() . '/' . $filename;
+ $filepath = sys_get_temp_dir().'/'.$filename;
- $zipFile->saveAsFile($filepath) // save the archive to a file
+ $zipFile->saveAsFile($filepath) // save the archive to a file
->close(); // close archive
-
- return response()->download($filepath, $filename)->deleteFileAfterSend(true);
- }
- catch(\PhpZip\Exception\ZipException $e){
+ return response()->download($filepath, $filename)->deleteFileAfterSend(true);
+ } catch (\PhpZip\Exception\ZipException $e) {
// handle exception
- }
- finally{
+ } finally {
$zipFile->close();
}
}
diff --git a/app/Http/Controllers/ClientPortal/NinjaPlanController.php b/app/Http/Controllers/ClientPortal/NinjaPlanController.php
index 144834898480..15e497d62024 100644
--- a/app/Http/Controllers/ClientPortal/NinjaPlanController.php
+++ b/app/Http/Controllers/ClientPortal/NinjaPlanController.php
@@ -42,35 +42,29 @@ class NinjaPlanController extends Controller
public function index(string $contact_key, string $account_or_company_key)
{
-
MultiDB::findAndSetDbByCompanyKey($account_or_company_key);
$company = Company::where('company_key', $account_or_company_key)->first();
- if(!$company){
+ if (! $company) {
MultiDB::findAndSetDbByAccountKey($account_or_company_key);
$account = Account::where('key', $account_or_company_key)->first();
- }
- else
+ } else {
$account = $company->account;
+ }
- if (MultiDB::findAndSetDbByContactKey($contact_key) && $client_contact = ClientContact::where('contact_key', $contact_key)->first())
- {
-
- nlog("Ninja Plan Controller - Found and set Client Contact");
-
- Auth::guard('contact')->loginUsingId($client_contact->id,true);
+ if (MultiDB::findAndSetDbByContactKey($contact_key) && $client_contact = ClientContact::where('contact_key', $contact_key)->first()) {
+ nlog('Ninja Plan Controller - Found and set Client Contact');
+
+ Auth::guard('contact')->loginUsingId($client_contact->id, true);
return $this->plan();
-
}
return redirect()->route('client.catchall');
-
}
public function trial()
{
-
$gateway = CompanyGateway::on('db-ninja-01')->find(config('ninja.ninja_default_company_gateway_id'));
$data['gateway'] = $gateway;
@@ -80,22 +74,19 @@ class NinjaPlanController extends Controller
$customer = $gateway_driver->findOrCreateCustomer();
$setupIntent = \Stripe\SetupIntent::create([
- 'payment_method_types' => ['card'],
- 'usage' => 'off_session',
- 'customer' => $customer->id
+ 'payment_method_types' => ['card'],
+ 'usage' => 'off_session',
+ 'customer' => $customer->id,
]);
$data['intent'] = $setupIntent;
- $data['client'] = Auth::guard('contact')->user()->client;
+ $data['client'] = Auth::guard('contact')->user()->client;
return $this->render('plan.trial', $data);
-
-
}
public function trial_confirmation(Request $request)
{
-
$client = auth()->guard('contact')->user()->client;
$client->fill($request->all());
$client->save();
@@ -126,7 +117,7 @@ class NinjaPlanController extends Controller
$gateway_driver->storeGatewayToken($data, ['gateway_customer_reference' => $customer->id]);
//set free trial
- if(auth()->guard('contact')->user()->client->custom_value2){
+ if (auth()->guard('contact')->user()->client->custom_value2) {
MultiDB::findAndSetDbByAccountKey(auth()->guard('contact')->user()->client->custom_value2);
$account = Account::where('key', auth()->guard('contact')->user()->client->custom_value2)->first();
// $account->trial_started = now();
@@ -139,7 +130,7 @@ class NinjaPlanController extends Controller
}
MultiDB::setDB('db-ninja-01');
-
+
//create recurring invoice
$subscription_repo = new SubscriptionRepository();
$subscription = Subscription::find(6);
@@ -152,7 +143,7 @@ class NinjaPlanController extends Controller
$recurring_invoice->date = now()->addDays(14);
$recurring_invoice->remaining_cycles = -1;
$recurring_invoice->auto_bill = $client->getSetting('auto_bill');
- $recurring_invoice->auto_bill_enabled = $this->setAutoBillFlag($recurring_invoice->auto_bill);
+ $recurring_invoice->auto_bill_enabled = $this->setAutoBillFlag($recurring_invoice->auto_bill);
$recurring_invoice->due_date_days = 'terms';
$recurring_invoice->next_send_date = now()->addDays(14)->format('Y-m-d');
$recurring_invoice->next_send_date_client = now()->addDays(14)->format('Y-m-d');
@@ -170,10 +161,8 @@ class NinjaPlanController extends Controller
$ninja_company->notification(new NewAccountNotification($account, $client))->ninja();
return $this->render('plan.trial_confirmed', $data);
-
}
-
private function setAutoBillFlag($auto_bill)
{
if ($auto_bill == 'always' || $auto_bill == 'optout') {
@@ -181,7 +170,6 @@ class NinjaPlanController extends Controller
}
return false;
-
}
public function plan()
@@ -190,18 +178,17 @@ class NinjaPlanController extends Controller
//harvest the current plan
$data = [];
$data['late_invoice'] = false;
-
- if(MultiDB::findAndSetDbByAccountKey(Auth::guard('contact')->user()->client->custom_value2))
- {
+
+ if (MultiDB::findAndSetDbByAccountKey(Auth::guard('contact')->user()->client->custom_value2)) {
$account = Account::where('key', Auth::guard('contact')->user()->client->custom_value2)->first();
- if($account)
- {
+ if ($account) {
//offer the option to have a free trial
- if(!$account->trial_started && !$account->plan)
+ if (! $account->trial_started && ! $account->plan) {
return $this->trial();
+ }
- if(Carbon::parse($account->plan_expires)->lt(now())){
+ if (Carbon::parse($account->plan_expires)->lt(now())) {
//expired get the most recent invoice for payment
$late_invoice = Invoice::on('db-ninja-01')
@@ -215,12 +202,11 @@ class NinjaPlanController extends Controller
//account status means user cannot perform upgrades until they pay their account.
// $data['late_invoice'] = $late_invoice;
- //14-01-2022 remove late invoices from blocking upgrades
- $data['late_invoice'] = false;
-
+ //14-01-2022 remove late invoices from blocking upgrades
+ $data['late_invoice'] = false;
}
- $recurring_invoice = RecurringInvoice::on('db-ninja-01')
+ $recurring_invoice = RecurringInvoice::on('db-ninja-01')
->where('client_id', auth()->guard('contact')->user()->client->id)
->where('company_id', Auth::guard('contact')->user()->company->id)
->whereNotNull('subscription_id')
@@ -245,27 +231,22 @@ class NinjaPlanController extends Controller
$current_subscription_id = $recurring_invoice ? $this->encodePrimaryKey($recurring_invoice->subscription_id) : false;
//remove existing subscription
- if($current_subscription_id){
-
- $monthly_plans = $monthly_plans->filter(function ($plan) use($current_subscription_id){
- return (string)$plan->hashed_id != (string)$current_subscription_id;
- });
-
+ if ($current_subscription_id) {
+ $monthly_plans = $monthly_plans->filter(function ($plan) use ($current_subscription_id) {
+ return (string) $plan->hashed_id != (string) $current_subscription_id;
+ });
}
$data['account'] = $account;
- $data['client'] = Auth::guard('contact')->user()->client;
+ $data['client'] = Auth::guard('contact')->user()->client;
$data['plans'] = $monthly_plans;
$data['current_subscription_id'] = $current_subscription_id;
$data['current_recurring_id'] = $recurring_invoice ? $recurring_invoice->hashed_id : false;
return $this->render('plan.index', $data);
-
}
-
- }
- else
+ } else {
return redirect('/client/dashboard');
-
+ }
}
}
diff --git a/app/Http/Controllers/ClientPortal/PaymentController.php b/app/Http/Controllers/ClientPortal/PaymentController.php
index b2401a99683c..ff5a95aa13ea 100644
--- a/app/Http/Controllers/ClientPortal/PaymentController.php
+++ b/app/Http/Controllers/ClientPortal/PaymentController.php
@@ -127,8 +127,7 @@ class PaymentController extends Controller
* @return Response The response view
*/
public function credit_response(Request $request)
- {
-
+ {
$payment_hash = PaymentHash::where('hash', $request->input('payment_hash'))->first();
/* Hydrate the $payment */
diff --git a/app/Http/Controllers/ClientPortal/PaymentMethodController.php b/app/Http/Controllers/ClientPortal/PaymentMethodController.php
index 778723809956..4dbf694c3b17 100644
--- a/app/Http/Controllers/ClientPortal/PaymentMethodController.php
+++ b/app/Http/Controllers/ClientPortal/PaymentMethodController.php
@@ -97,7 +97,6 @@ class PaymentMethodController extends Controller
public function verify(ClientGatewayToken $payment_method)
{
-
return $payment_method->gateway
->driver(auth()->user()->client)
->setPaymentMethod(request()->query('method'))
@@ -122,24 +121,18 @@ class PaymentMethodController extends Controller
*/
public function destroy(ClientGatewayToken $payment_method)
{
-
- if($payment_method->gateway()->exists()){
-
+ if ($payment_method->gateway()->exists()) {
$payment_method->gateway
->driver(auth()->user()->client)
->setPaymentMethod(request()->query('method'))
->detach($payment_method);
-
}
try {
-
event(new MethodDeleted($payment_method, auth()->guard('contact')->user()->company, Ninja::eventVars(auth()->guard('contact')->user()->id)));
-
+
$payment_method->delete();
-
} catch (Exception $e) {
-
nlog($e->getMessage());
return back();
diff --git a/app/Http/Controllers/ClientPortal/ProfileController.php b/app/Http/Controllers/ClientPortal/ProfileController.php
index 193eb9fe47f1..5fa5f14c1de2 100644
--- a/app/Http/Controllers/ClientPortal/ProfileController.php
+++ b/app/Http/Controllers/ClientPortal/ProfileController.php
@@ -63,7 +63,7 @@ class ProfileController extends Controller
//update avatar if needed
if ($request->file('logo')) {
- $path = UploadAvatar::dispatchNow($request->file('logo'), auth()->user()->client->client_hash);
+ $path = (new UploadAvatar($request->file('logo'), auth()->user()->client->client_hash))->handle();
if ($path) {
$client->logo = $path;
diff --git a/app/Http/Controllers/ClientPortal/QuoteController.php b/app/Http/Controllers/ClientPortal/QuoteController.php
index adb863d40ca4..8cf4d3d9a06f 100644
--- a/app/Http/Controllers/ClientPortal/QuoteController.php
+++ b/app/Http/Controllers/ClientPortal/QuoteController.php
@@ -25,11 +25,11 @@ use App\Utils\Ninja;
use App\Utils\TempFile;
use App\Utils\Traits\MakesHash;
use Illuminate\Contracts\View\Factory;
+use Illuminate\Http\Request;
+use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
-use Illuminate\Http\Request;
-use Illuminate\Support\Carbon;
class QuoteController extends Controller
{
@@ -53,10 +53,9 @@ class QuoteController extends Controller
* @return Factory|View|BinaryFileResponse
*/
public function show(ShowQuoteRequest $request, Quote $quote)
- {
+ {
/* If the quote is expired, convert the status here */
-
$invitation = $quote->invitations()->where('client_contact_id', auth()->user()->id)->first();
$data = [
@@ -65,12 +64,10 @@ class QuoteController extends Controller
];
if ($invitation && auth()->guard('contact') && ! request()->has('silent') && ! $invitation->viewed_date) {
-
$invitation->markViewed();
event(new InvitationWasViewed($quote, $invitation, $quote->company, Ninja::eventVars()));
event(new QuoteWasViewed($invitation, $invitation->company, Ninja::eventVars()));
-
}
if ($request->query('mode') === 'fullscreen') {
@@ -97,14 +94,14 @@ class QuoteController extends Controller
public function downloadQuotes($ids)
{
-
$data['quotes'] = Quote::whereIn('id', $ids)
->whereClientId(auth()->user()->client->id)
->withTrashed()
->get();
- if(count($data['quotes']) == 0)
+ if (count($data['quotes']) == 0) {
return back()->with(['message' => ctrans('texts.no_items_selected')]);
+ }
return $this->render('quotes.download', $data);
}
@@ -112,7 +109,7 @@ class QuoteController extends Controller
public function download(Request $request)
{
$transformed_ids = $this->transformKeys($request->quotes);
-
+
return $this->downloadQuotePdf((array) $transformed_ids);
}
@@ -130,44 +127,37 @@ class QuoteController extends Controller
}
if ($quotes->count() == 1) {
-
- $file = $quotes->first()->service()->getQuotePdf();
- // return response()->download($file, basename($file), ['Cache-Control:' => 'no-cache'])->deleteFileAfterSend(true);
- return response()->streamDownload(function () use($file) {
- echo Storage::get($file);
- }, basename($file), ['Content-Type' => 'application/pdf']);
+ $file = $quotes->first()->service()->getQuotePdf();
+ // return response()->download($file, basename($file), ['Cache-Control:' => 'no-cache'])->deleteFileAfterSend(true);
+ return response()->streamDownload(function () use ($file) {
+ echo Storage::get($file);
+ }, basename($file), ['Content-Type' => 'application/pdf']);
}
return $this->buildZip($quotes);
-
}
private function buildZip($quotes)
{
// create new archive
$zipFile = new \PhpZip\ZipFile();
- try{
-
+ try {
foreach ($quotes as $quote) {
- #add it to the zip
+ //add it to the zip
$zipFile->addFromString(basename($quote->pdf_file_path()), file_get_contents($quote->pdf_file_path(null, 'url', true)));
-
}
$filename = date('Y-m-d').'_'.str_replace(' ', '_', trans('texts.quotes')).'.zip';
- $filepath = sys_get_temp_dir() . '/' . $filename;
+ $filepath = sys_get_temp_dir().'/'.$filename;
- $zipFile->saveAsFile($filepath) // save the archive to a file
+ $zipFile->saveAsFile($filepath) // save the archive to a file
->close(); // close archive
-
- return response()->download($filepath, $filename)->deleteFileAfterSend(true);
- }
- catch(\PhpZip\Exception\ZipException $e){
+ return response()->download($filepath, $filename)->deleteFileAfterSend(true);
+ } catch (\PhpZip\Exception\ZipException $e) {
// handle exception
- }
- finally{
+ } finally {
$zipFile->close();
}
}
@@ -181,7 +171,7 @@ class QuoteController extends Controller
->withTrashed()
->get();
- if (!$quotes || $quotes->count() == 0) {
+ if (! $quotes || $quotes->count() == 0) {
return redirect()
->route('client.quotes.index')
->with('message', ctrans('texts.quotes_with_status_sent_can_be_approved'));
@@ -192,19 +182,20 @@ class QuoteController extends Controller
$quote->service()->approve(auth()->user())->save();
// event(new QuoteWasApproved(auth()->guard('contact')->user(), $quote, $quote->company, Ninja::eventVars()));
- if (request()->has('signature') && !is_null(request()->signature) && !empty(request()->signature)) {
+ if (request()->has('signature') && ! is_null(request()->signature) && ! empty(request()->signature)) {
InjectSignature::dispatch($quote, request()->signature);
}
}
- if(count($ids) == 1){
+ if (count($ids) == 1) {
//forward client to the invoice if it exists
- if($quote->invoice()->exists())
- return redirect()->route('client.invoice.show', $quote->invoice->hashed_id);
-
- return redirect()->route('client.quote.show', $quotes->first()->hashed_id);
- }
+ if ($quote->invoice()->exists()) {
+ return redirect()->route('client.invoice.show', $quote->invoice->hashed_id);
+ }
+
+ return redirect()->route('client.quote.show', $quotes->first()->hashed_id);
+ }
return redirect()
->route('client.quotes.index')
diff --git a/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php b/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php
index 5c4bd6747961..d610d4515f82 100644
--- a/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php
+++ b/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php
@@ -13,8 +13,8 @@ namespace App\Http\Controllers\ClientPortal;
use App\Http\Controllers\Controller;
use App\Http\Requests\ClientPortal\RecurringInvoices\RequestCancellationRequest;
-use App\Http\Requests\ClientPortal\RecurringInvoices\ShowRecurringInvoicesRequest;
use App\Http\Requests\ClientPortal\RecurringInvoices\ShowRecurringInvoiceRequest;
+use App\Http\Requests\ClientPortal\RecurringInvoices\ShowRecurringInvoicesRequest;
use App\Jobs\Mail\NinjaMailer;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
@@ -62,11 +62,10 @@ class RecurringInvoiceController extends Controller
public function requestCancellation(RequestCancellationRequest $request, RecurringInvoice $recurring_invoice)
{
- nlog("outside cancellation");
+ nlog('outside cancellation');
- if (optional($recurring_invoice->subscription)->allow_cancellation) {
-
- nlog("inside the cancellation");
+ if ($recurring_invoice->subscription?->allow_cancellation) {
+ nlog('inside the cancellation');
$nmo = new NinjaMailerObject;
$nmo->mailable = (new NinjaMailer((new ClientContactRequestCancellationObject($recurring_invoice, auth()->user()))->build()));
@@ -75,24 +74,16 @@ class RecurringInvoiceController extends Controller
// $notifiable_users = $this->filterUsersByPermissions($recurring_invoice->company->company_users, $recurring_invoice, ['recurring_cancellation']);
- $recurring_invoice->company->company_users->each(function ($company_user) use ($nmo){
-
-
+ $recurring_invoice->company->company_users->each(function ($company_user) use ($nmo) {
$methods = $this->findCompanyUserNotificationType($company_user, ['recurring_cancellation', 'all_notifications']);
-
//if mail is a method type -fire mail!!
if (($key = array_search('mail', $methods)) !== false) {
unset($methods[$key]);
-
$nmo->to_user = $company_user->user;
NinjaMailerJob::dispatch($nmo);
-
}
-
-
-
});
// $notifiable_users->each(function ($company_user) use($nmo){
diff --git a/app/Http/Controllers/ClientPortal/SubscriptionController.php b/app/Http/Controllers/ClientPortal/SubscriptionController.php
index 0710beccc734..21fa9116c23e 100644
--- a/app/Http/Controllers/ClientPortal/SubscriptionController.php
+++ b/app/Http/Controllers/ClientPortal/SubscriptionController.php
@@ -21,10 +21,7 @@ class SubscriptionController extends Controller
{
public function index()
{
-
- if(Ninja::isHosted()){
-
-
+ if (Ninja::isHosted()) {
$count = RecurringInvoice::query()
->where('client_id', auth()->guard('contact')->user()->client->id)
->where('company_id', auth()->guard('contact')->user()->client->company_id)
@@ -34,12 +31,11 @@ class SubscriptionController extends Controller
->withTrashed()
->count();
- if($count == 0)
- return redirect()->route('client.ninja_contact_login', ['contact_key' => auth()->guard('contact')->user()->contact_key, 'company_key' => auth()->guard('contact')->user()->company->company_key]);
-
+ if ($count == 0) {
+ return redirect()->route('client.ninja_contact_login', ['contact_key' => auth()->guard('contact')->user()->contact_key, 'company_key' => auth()->guard('contact')->user()->company->company_key]);
+ }
}
-
return render('subscriptions.index');
}
}
diff --git a/app/Http/Controllers/ClientPortal/SubscriptionPlanSwitchController.php b/app/Http/Controllers/ClientPortal/SubscriptionPlanSwitchController.php
index 0af33a6954a8..b5b4593a52fa 100644
--- a/app/Http/Controllers/ClientPortal/SubscriptionPlanSwitchController.php
+++ b/app/Http/Controllers/ClientPortal/SubscriptionPlanSwitchController.php
@@ -31,19 +31,17 @@ class SubscriptionPlanSwitchController extends Controller
*/
public function index(ShowPlanSwitchRequest $request, RecurringInvoice $recurring_invoice, Subscription $target)
{
-
$amount = $recurring_invoice->subscription
->service()
->calculateUpgradePrice($recurring_invoice, $target);
/**
- *
* Null value here is a proxy for
* denying the user a change plan option
- *
*/
- if(is_null($amount))
+ if (is_null($amount)) {
render('subscriptions.denied');
-
+ }
+
return render('subscriptions.switch', [
'subscription' => $recurring_invoice->subscription,
'recurring_invoice' => $recurring_invoice,
diff --git a/app/Http/Controllers/ClientPortal/SubscriptionPurchaseController.php b/app/Http/Controllers/ClientPortal/SubscriptionPurchaseController.php
index cb8d272aa29b..09825123d32a 100644
--- a/app/Http/Controllers/ClientPortal/SubscriptionPurchaseController.php
+++ b/app/Http/Controllers/ClientPortal/SubscriptionPurchaseController.php
@@ -25,7 +25,7 @@ class SubscriptionPurchaseController extends Controller
public function index(Subscription $subscription, Request $request)
{
/* Make sure the contact is logged into the correct company for this subscription */
- if(auth()->guard('contact')->user() && auth()->guard('contact')->user()->company_id != $subscription->company_id){
+ if (auth()->guard('contact')->user() && auth()->guard('contact')->user()->company_id != $subscription->company_id) {
auth()->guard('contact')->logout();
$request->session()->invalidate();
}
diff --git a/app/Http/Controllers/ClientPortal/SwitchCompanyController.php b/app/Http/Controllers/ClientPortal/SwitchCompanyController.php
index 804720d466be..d0f92ffa459c 100644
--- a/app/Http/Controllers/ClientPortal/SwitchCompanyController.php
+++ b/app/Http/Controllers/ClientPortal/SwitchCompanyController.php
@@ -30,7 +30,7 @@ class SwitchCompanyController extends Controller
auth()->guard('contact')->loginUsingId($client_contact->id, true);
request()->session()->regenerate();
-
+
return redirect('/client/dashboard');
}
}
diff --git a/app/Http/Controllers/ClientPortal/TempRouteController.php b/app/Http/Controllers/ClientPortal/TempRouteController.php
index a35f6defdb8f..db5be7f680ce 100644
--- a/app/Http/Controllers/ClientPortal/TempRouteController.php
+++ b/app/Http/Controllers/ClientPortal/TempRouteController.php
@@ -17,7 +17,6 @@ use Illuminate\Support\Facades\Cache;
class TempRouteController extends Controller
{
-
/**
* Logs a user into the client portal using their contact_key
* @param string $contact_key The contact key
diff --git a/app/Http/Controllers/ClientStatementController.php b/app/Http/Controllers/ClientStatementController.php
index 00d0b4c3acfd..052ddc91a9de 100644
--- a/app/Http/Controllers/ClientStatementController.php
+++ b/app/Http/Controllers/ClientStatementController.php
@@ -77,7 +77,7 @@ class ClientStatementController extends BaseController
* property="show_payments_table",
* description="Flag which determines if the payments table is shown",
* type="boolean",
- * ),
+ * ),
* @OA\Property(
* property="show_aging_table",
* description="Flag which determines if the aging table is shown",
@@ -107,17 +107,16 @@ class ClientStatementController extends BaseController
* ),
* )
*/
-
public function statement(CreateStatementRequest $request)
- {
+ {
$pdf = $request->client()->service()->statement(
$request->only(['start_date', 'end_date', 'show_payments_table', 'show_aging_table', 'status'])
);
-
+
if ($pdf) {
return response()->streamDownload(function () use ($pdf) {
echo $pdf;
- }, ctrans('texts.statement') . '.pdf', ['Content-Type' => 'application/pdf']);
+ }, ctrans('texts.statement').'.pdf', ['Content-Type' => 'application/pdf']);
}
return response()->json(['message' => 'Something went wrong. Please check logs.']);
diff --git a/app/Http/Controllers/CompanyController.php b/app/Http/Controllers/CompanyController.php
index c780d66f3007..86fc01c732c7 100644
--- a/app/Http/Controllers/CompanyController.php
+++ b/app/Http/Controllers/CompanyController.php
@@ -71,13 +71,11 @@ class CompanyController extends BaseController
*/
public function __construct(CompanyRepository $company_repo)
{
-
parent::__construct();
$this->company_repo = $company_repo;
$this->middleware('password_protected')->only(['destroy']);
-
}
/**
@@ -213,10 +211,9 @@ class CompanyController extends BaseController
{
$this->forced_includes = ['company_user'];
- $company = CreateCompany::dispatchNow($request->all(), auth()->user()->company()->account);
-
- CreateCompanyPaymentTerms::dispatchNow($company, auth()->user());
- CreateCompanyTaskStatuses::dispatchNow($company, auth()->user());
+ $company = (new CreateCompany($request->all(), auth()->user()->company()->account))->handle();
+ (new CreateCompanyPaymentTerms($company, auth()->user()))->handle();
+ (new CreateCompanyTaskStatuses($company, auth()->user()))->handle();
$company = $this->company_repo->save($request->all(), $company);
@@ -232,8 +229,7 @@ class CompanyController extends BaseController
'notifications' => CompanySettings::notificationDefaults(),
]);
- if($company->account->companies()->where('is_large', 1)->exists())
- {
+ if ($company->account->companies()->where('is_large', 1)->exists()) {
$company->account->companies()->update(['is_large' => true]);
}
@@ -247,8 +243,7 @@ class CompanyController extends BaseController
*/
$user_agent = request()->has('token_name') ? request()->input('token_name') : request()->server('HTTP_USER_AGENT');
- $company_token = CreateCompanyToken::dispatchNow($company, auth()->user(), $user_agent);
-
+ $company_token = (new CreateCompanyToken($company, auth()->user(), $user_agent))->handle();
$this->entity_transformer = CompanyUserTransformer::class;
$this->entity_type = CompanyUser::class;
@@ -419,16 +414,18 @@ class CompanyController extends BaseController
*/
public function update(UpdateCompanyRequest $request, Company $company)
{
- if ($request->hasFile('company_logo') || (is_array($request->input('settings')) && !array_key_exists('company_logo', $request->input('settings'))))
+ if ($request->hasFile('company_logo') || (is_array($request->input('settings')) && ! array_key_exists('company_logo', $request->input('settings')))) {
$this->removeLogo($company);
-
+ }
+
$company = $this->company_repo->save($request->all(), $company);
$company->saveSettings($request->input('settings'), $company);
- if ($request->has('documents'))
+ if ($request->has('documents')) {
$this->saveDocuments($request->input('documents'), $company, false);
-
+ }
+
$this->uploadLogo($request->file('company_logo'), $company, $company);
return $this->itemResponse($company);
@@ -486,16 +483,15 @@ class CompanyController extends BaseController
*/
public function destroy(DestroyCompanyRequest $request, Company $company)
{
-
- if(Ninja::isHosted() && config('ninja.ninja_default_company_id') == $company->id)
+ if (Ninja::isHosted() && config('ninja.ninja_default_company_id') == $company->id) {
return response()->json(['message' => 'Cannot purge this company'], 400);
-
+ }
+
$company_count = $company->account->companies->count();
$account = $company->account;
$account_key = $account->key;
if ($company_count == 1) {
-
$company->company_users->each(function ($company_user) {
$company_user->user->forceDelete();
$company_user->forceDelete();
@@ -503,28 +499,28 @@ class CompanyController extends BaseController
$account->delete();
- if(Ninja::isHosted())
+ if (Ninja::isHosted()) {
\Modules\Admin\Jobs\Account\NinjaDeletedAccount::dispatch($account_key, $request->all());
+ }
LightLogs::create(new AccountDeleted())
->increment()
->queue();
-
} else {
$company_id = $company->id;
- $company->company_users->each(function ($company_user){
+ $company->company_users->each(function ($company_user) {
$company_user->forceDelete();
});
-
- $other_company = $company->account->companies->where('id', '!=', $company->id)->first();
- $nmo = new NinjaMailerObject;
- $nmo->mailable = new CompanyDeleted($company->present()->name, auth()->user(), $company->account, $company->settings);
- $nmo->company = $other_company;
- $nmo->settings = $other_company->settings;
- $nmo->to_user = auth()->user();
- NinjaMailerJob::dispatch($nmo);
+ $other_company = $company->account->companies->where('id', '!=', $company->id)->first();
+
+ $nmo = new NinjaMailerObject;
+ $nmo->mailable = new CompanyDeleted($company->present()->name, auth()->user(), $company->account, $company->settings);
+ $nmo->company = $other_company;
+ $nmo->settings = $other_company->settings;
+ $nmo->to_user = auth()->user();
+ NinjaMailerJob::dispatch($nmo, true);
$company->delete();
@@ -592,18 +588,18 @@ class CompanyController extends BaseController
*/
public function upload(UploadCompanyRequest $request, Company $company)
{
-
- if(!$this->checkFeature(Account::FEATURE_DOCUMENTS))
+ if (! $this->checkFeature(Account::FEATURE_DOCUMENTS)) {
return $this->featureFailure();
-
- if ($request->has('documents'))
+ }
+
+ if ($request->has('documents')) {
$this->saveDocuments($request->file('documents'), $company);
+ }
return $this->itemResponse($company->fresh());
-
}
-/**
+ /**
* Update the specified resource in storage.
*
* @param UploadCompanyRequest $request
@@ -656,13 +652,10 @@ class CompanyController extends BaseController
*/
public function default(DefaultCompanyRequest $request, Company $company)
{
-
$account = $company->account;
$account->default_company_id = $company->id;
- $account->save();
+ $account->save();
return $this->itemResponse($company->fresh());
-
}
-
}
diff --git a/app/Http/Controllers/CompanyGatewayController.php b/app/Http/Controllers/CompanyGatewayController.php
index ec3858b48225..d957238d4179 100644
--- a/app/Http/Controllers/CompanyGatewayController.php
+++ b/app/Http/Controllers/CompanyGatewayController.php
@@ -49,7 +49,6 @@ class CompanyGatewayController extends BaseController
private array $stripe_keys = ['d14dd26a47cecc30fdd65700bfb67b34', 'd14dd26a37cecc30fdd65700bfb55b23'];
-
/**
* CompanyGatewayController constructor.
* @param CompanyRepository $company_repo
@@ -200,8 +199,7 @@ class CompanyGatewayController extends BaseController
$company_gateway->save();
/*Always ensure at least one fees and limits object is set per gateway*/
- if(!isset($company_gateway->fees_and_limits)) {
-
+ if (! isset($company_gateway->fees_and_limits)) {
$gateway_types = $company_gateway->driver(new Client)->gatewayTypes();
$fees_and_limits = new \stdClass;
@@ -213,8 +211,7 @@ class CompanyGatewayController extends BaseController
ApplePayDomain::dispatch($company_gateway, $company_gateway->company->db);
- if(in_array($company_gateway->gateway_key, $this->stripe_keys))
- {
+ if (in_array($company_gateway->gateway_key, $this->stripe_keys)) {
StripeWebhook::dispatch($company_gateway->company->company_key, $company_gateway->id);
}
@@ -448,14 +445,12 @@ class CompanyGatewayController extends BaseController
*/
public function destroy(DestroyCompanyGatewayRequest $request, CompanyGateway $company_gateway)
{
-
$company_gateway->driver(new Client)
->disconnect();
$company_gateway->delete();
return $this->itemResponse($company_gateway->fresh());
-
}
/**
diff --git a/app/Http/Controllers/ConnectedAccountController.php b/app/Http/Controllers/ConnectedAccountController.php
index 5097ed1f090d..7895024020d7 100644
--- a/app/Http/Controllers/ConnectedAccountController.php
+++ b/app/Http/Controllers/ConnectedAccountController.php
@@ -31,7 +31,7 @@ class ConnectedAccountController extends BaseController
protected $entity_type = User::class;
protected $entity_transformer = UserTransformer::class;
-
+
public function __construct()
{
parent::__construct();
@@ -146,7 +146,6 @@ class ConnectedAccountController extends BaseController
$user = $google->getTokenResponse(request()->input('id_token'));
if ($user) {
-
$client = new Google_Client();
$client->setClientId(config('ninja.auth.google.client_id'));
$client->setClientSecret(config('ninja.auth.google.client_secret'));
@@ -156,24 +155,24 @@ class ConnectedAccountController extends BaseController
$email = $google->harvestEmail($user);
- if(auth()->user()->email != $email && MultiDB::checkUserEmailExists($email))
+ if (auth()->user()->email != $email && MultiDB::checkUserEmailExists($email)) {
return response()->json(['message' => ctrans('texts.email_already_register')], 400);
+ }
$connected_account = [
'email' => $email,
'oauth_user_id' => $google->harvestSubField($user),
'oauth_provider_id' => 'google',
- 'email_verified_at' =>now()
+ 'email_verified_at' =>now(),
];
auth()->user()->update($connected_account);
auth()->user()->email_verified_at = now();
auth()->user()->save();
-
- $this->setLoginCache(auth()->user());
-
- return $this->itemResponse(auth()->user());
+ $this->setLoginCache(auth()->user());
+
+ return $this->itemResponse(auth()->user());
}
return response()
@@ -182,11 +181,8 @@ class ConnectedAccountController extends BaseController
->header('X-Api-Version', config('ninja.minimum_client_version'));
}
-
-
public function handleGmailOauth(Request $request)
{
-
$user = false;
$google = new Google();
@@ -194,7 +190,6 @@ class ConnectedAccountController extends BaseController
$user = $google->getTokenResponse($request->input('id_token'));
if ($user) {
-
$client = new Google_Client();
$client->setClientId(config('ninja.auth.google.client_id'));
$client->setClientSecret(config('ninja.auth.google.client_secret'));
@@ -213,27 +208,26 @@ class ConnectedAccountController extends BaseController
'oauth_user_token' => $token,
'oauth_user_refresh_token' => $refresh_token,
'oauth_provider_id' => 'google',
- 'email_verified_at' =>now()
+ 'email_verified_at' =>now(),
];
- if(auth()->user()->email != $google->harvestEmail($user))
+ if (auth()->user()->email != $google->harvestEmail($user)) {
return response()->json(['message' => 'Primary Email differs to OAuth email. Emails must match.'], 400);
+ }
auth()->user()->update($connected_account);
auth()->user()->email_verified_at = now();
auth()->user()->save();
-
+
$this->activateGmail(auth()->user());
return $this->itemResponse(auth()->user());
-
}
return response()
->json(['message' => ctrans('texts.invalid_credentials')], 401)
->header('X-App-Version', config('ninja.app_version'))
->header('X-Api-Version', config('ninja.minimum_client_version'));
-
}
private function activateGmail(User $user)
@@ -241,13 +235,12 @@ class ConnectedAccountController extends BaseController
$company = $user->company();
$settings = $company->settings;
- if($settings->email_sending_method == 'default')
- {
+ if ($settings->email_sending_method == 'default') {
$settings->email_sending_method = 'gmail';
- $settings->gmail_sending_user_id = (string)$user->hashed_id;
+ $settings->gmail_sending_user_id = (string) $user->hashed_id;
$company->settings = $settings;
$company->save();
- }
+ }
}
}
diff --git a/app/Http/Controllers/Contact/LoginController.php b/app/Http/Controllers/Contact/LoginController.php
index 97d8444f190d..9ce864735e4f 100644
--- a/app/Http/Controllers/Contact/LoginController.php
+++ b/app/Http/Controllers/Contact/LoginController.php
@@ -94,9 +94,9 @@ class LoginController extends BaseController
{
//'https://www.googleapis.com/auth/gmail.send','email','profile','openid'
$scopes = [];
-
- if($provider == 'google'){
- $scopes = ['https://www.googleapis.com/auth/gmail.send','email','profile','openid'];
+
+ if ($provider == 'google') {
+ $scopes = ['https://www.googleapis.com/auth/gmail.send', 'email', 'profile', 'openid'];
}
if (request()->has('code')) {
@@ -117,98 +117,6 @@ class LoginController extends BaseController
}
}
- /*
- public function handleProviderCallbackAndCreate(string $provider)
- {
- $socialite_user = Socialite::driver($provider)
- ->stateless()
- ->user();
-
- if($user = OAuth::handleAuth($socialite_user, $provider))
- {
- Auth::login($user, true);
-
- return redirect($this->redirectTo);
- }
- else if(MultiDB::checkUserEmailExists($socialite_user->getEmail()))
- {
- Session::flash('error', 'User exists in system, but not with this authentication method'); //todo add translations
-
- return view('auth.login');
- }
- else {
- //todo
- $name = OAuth::splitName($socialite_user->getName());
-
- $new_account = [
- 'first_name' => $name[0],
- 'last_name' => $name[1],
- 'password' => '',
- 'email' => $socialite_user->getEmail(),
- 'oauth_user_id' => $socialite_user->getId(),
- 'oauth_provider_id' => $provider
- ];
-
- $account = CreateAccount::dispatchNow($new_account);
-
- Auth::login($account->default_company->owner(), true);
-
- $cookie = cookie('db', $account->default_company->db);
-
- return redirect($this->redirectTo)->withCookie($cookie);
- }
-
- }
- */
-
- /**
- * We use this function when OAUTHING via the web interface.
- *
- * @return redirect
-
- public function handleProviderCallback(string $provider)
- {
- $socialite_user = Socialite::driver($provider)
- ->stateless()
- ->user();
-
- if($user = OAuth::handleAuth($socialite_user, $provider))
- {
- Auth::login($user, true);
-
- return redirect($this->redirectTo);
- }
- else if(MultiDB::checkUserEmailExists($socialite_user->getEmail()))
- {
- Session::flash('error', 'User exists in system, but not with this authentication method'); //todo add translations
-
- return view('auth.login');
- }
- else {
- //todo
- $name = OAuth::splitName($socialite_user->getName());
-
- $new_account = [
- 'first_name' => $name[0],
- 'last_name' => $name[1],
- 'password' => '',
- 'email' => $socialite_user->getEmail(),
- 'oauth_user_id' => $socialite_user->getId(),
- 'oauth_provider_id' => $provider
- ];
-
- $account = CreateAccount::dispatchNow($new_account);
-
- Auth::login($account->default_company->owner(), true);
-
- $cookie = cookie('db', $account->default_company->db);
-
- return redirect($this->redirectTo)->withCookie($cookie);
- }
-
- }
- */
-
/**
* A client side authentication has taken place.
* We now digest the token and confirm authentication with
@@ -235,6 +143,4 @@ class LoginController extends BaseController
return $this->errorResponse(['message' => 'Invalid credentials'], 401);
}
}
-
-
}
diff --git a/app/Http/Controllers/CreditController.php b/app/Http/Controllers/CreditController.php
index 80d5d9e417ac..e0c72b90d598 100644
--- a/app/Http/Controllers/CreditController.php
+++ b/app/Http/Controllers/CreditController.php
@@ -48,7 +48,7 @@ class CreditController extends BaseController
{
use MakesHash;
use SavesDocuments;
-
+
protected $entity_type = Credit::class;
protected $entity_transformer = CreditTransformer::class;
@@ -205,7 +205,7 @@ class CreditController extends BaseController
->triggeredActions($request)
->save();
- if($credit->invoice_id){
+ if ($credit->invoice_id) {
$credit = $credit->service()->markSent()->save();
$credit->client->service()->updatePaidToDate(-1 * $credit->balance)->save();
}
@@ -388,7 +388,7 @@ class CreditController extends BaseController
$credit->service()
->triggeredActions($request)
->deletePdf();
-
+
event(new CreditWasUpdated($credit, $credit->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
return $this->itemResponse($credit);
@@ -507,6 +507,9 @@ class CreditController extends BaseController
$ids = request()->input('ids');
+ if(Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified)
+ return response(['message' => 'Please verify your account to send emails.'], 400);
+
$credits = Credit::withTrashed()->whereIn('id', $this->transformKeys($ids))->company()->get();
if (! $credits) {
@@ -520,7 +523,8 @@ class CreditController extends BaseController
if ($action == 'bulk_download' && $credits->count() > 1) {
$credits->each(function ($credit) {
if (auth()->user()->cannot('view', $credit)) {
- nlog("access denied");
+ nlog('access denied');
+
return response()->json(['message' => ctrans('text.access_denied')]);
}
});
@@ -530,7 +534,6 @@ class CreditController extends BaseController
return response()->json(['message' => ctrans('texts.sent_message')], 200);
}
-
$credits->each(function ($credit, $key) use ($action) {
if (auth()->user()->can('edit', $credit)) {
$this->performAction($credit, $action, true);
@@ -551,6 +554,7 @@ class CreditController extends BaseController
switch ($action) {
case 'mark_paid':
$credit->service()->markPaid()->save();
+
return $this->itemResponse($credit);
break;
@@ -569,15 +573,15 @@ class CreditController extends BaseController
return $this->itemResponse($credit);
}
break;
- case 'download':
+ case 'download':
// $file = $credit->pdf_file_path();
$file = $credit->service()->getCreditPdf($credit->invitations->first());
// return response()->download($file, basename($file), ['Cache-Control:' => 'no-cache'])->deleteFileAfterSend(true);
- return response()->streamDownload(function () use($file) {
- echo Storage::get($file);
- }, basename($file), ['Content-Type' => 'application/pdf']);
+ return response()->streamDownload(function () use ($file) {
+ echo Storage::get($file);
+ }, basename($file), ['Content-Type' => 'application/pdf']);
break;
case 'archive':
$this->credit_repository->archive($credit);
@@ -618,7 +622,6 @@ class CreditController extends BaseController
EmailEntity::dispatch($invitation, $credit->company, 'credit');
});
-
if (! $bulk) {
return response()->json(['message'=>'email sent'], 200);
}
@@ -637,17 +640,16 @@ class CreditController extends BaseController
$credit = $invitation->credit;
$file = $credit->service()->getCreditPdf($invitation);
-
+
$headers = ['Content-Type' => 'application/pdf'];
- if(request()->input('inline') == 'true')
+ if (request()->input('inline') == 'true') {
$headers = array_merge($headers, ['Content-Disposition' => 'inline']);
+ }
- return response()->streamDownload(function () use($file) {
- echo Storage::get($file);
- }, basename($file), $headers);
-
-
+ return response()->streamDownload(function () use ($file) {
+ echo Storage::get($file);
+ }, basename($file), $headers);
}
/**
@@ -703,15 +705,14 @@ class CreditController extends BaseController
*/
public function upload(UploadCreditRequest $request, Credit $credit)
{
-
- if(!$this->checkFeature(Account::FEATURE_DOCUMENTS))
+ if (! $this->checkFeature(Account::FEATURE_DOCUMENTS)) {
return $this->featureFailure();
-
- if ($request->has('documents'))
+ }
+
+ if ($request->has('documents')) {
$this->saveDocuments($request->file('documents'), $credit);
+ }
return $this->itemResponse($credit->fresh());
-
}
-
}
diff --git a/app/Http/Controllers/DesignController.php b/app/Http/Controllers/DesignController.php
index dbb22226c761..56544e276c5e 100644
--- a/app/Http/Controllers/DesignController.php
+++ b/app/Http/Controllers/DesignController.php
@@ -357,11 +357,11 @@ class DesignController extends BaseController
$design->fill($request->all());
$design->save();
-/*
- This is required as the base template does not know to inject the table elements
-*/
+ /*
+ This is required as the base template does not know to inject the table elements
+ */
- $properties = ['includes','header','body','footer'];
+ $properties = ['includes', 'header', 'body', 'footer'];
$d = $design->design;
@@ -395,18 +395,17 @@ class DesignController extends BaseController