diff --git a/app/Console/Commands/CreateTestData.php b/app/Console/Commands/CreateTestData.php index 0a828d0ceeaa..53250d97e4a7 100644 --- a/app/Console/Commands/CreateTestData.php +++ b/app/Console/Commands/CreateTestData.php @@ -51,8 +51,6 @@ class CreateTestData extends Command parent::__construct(); $this->invoice_repo = $invoice_repo; - - } /** @@ -72,13 +70,11 @@ class CreateTestData extends Command $this->createSmallAccount(); $this->createMediumAccount(); $this->createLargeAccount(); - } private function createSmallAccount() { - $this->info('Creating Small Account and Company'); $account = factory(\App\Models\Account::class)->create(); @@ -91,8 +87,7 @@ class CreateTestData extends Command $user = User::whereEmail('small@example.com')->first(); - if(!$user) - { + if (!$user) { $user = factory(\App\Models\User::class)->create([ // 'account_id' => $account->id, 'email' => 'small@example.com', @@ -123,13 +118,12 @@ class CreateTestData extends Command $this->info('Creating '.$this->count. ' clients'); - for($x=0; $x<$this->count; $x++) { + for ($x=0; $x<$this->count; $x++) { $z = $x+1; $this->info("Creating client # ".$z); - $this->createClient($company, $user); + $this->createClient($company, $user); } - } private function createMediumAccount() @@ -146,8 +140,7 @@ class CreateTestData extends Command $user = User::whereEmail('medium@example.com')->first(); - if(!$user) - { + if (!$user) { $user = factory(\App\Models\User::class)->create([ // 'account_id' => $account->id, 'email' => 'medium@example.com', @@ -179,18 +172,17 @@ class CreateTestData extends Command $this->info('Creating '.$this->count. ' clients'); - for($x=0; $x<$this->count; $x++) { + for ($x=0; $x<$this->count; $x++) { $z = $x+1; $this->info("Creating client # ".$z); - $this->createClient($company, $user); + $this->createClient($company, $user); } - } private function createLargeAccount() { - $this->info('Creating Large Account and Company'); + $this->info('Creating Large Account and Company'); $account = factory(\App\Models\Account::class)->create(); $company = factory(\App\Models\Company::class)->create([ @@ -202,8 +194,7 @@ class CreateTestData extends Command $user = User::whereEmail('large@example.com')->first(); - if(!$user) - { + if (!$user) { $user = factory(\App\Models\User::class)->create([ // 'account_id' => $account->id, 'email' => 'large@example.com', @@ -235,13 +226,12 @@ class CreateTestData extends Command $this->info('Creating '.$this->count. ' clients'); - for($x=0; $x<$this->count; $x++) { + for ($x=0; $x<$this->count; $x++) { $z = $x+1; $this->info("Creating client # ".$z); - $this->createClient($company, $user); + $this->createClient($company, $user); } - } private function createClient($company, $user) @@ -252,25 +242,24 @@ class CreateTestData extends Command ]); - factory(\App\Models\ClientContact::class,1)->create([ + factory(\App\Models\ClientContact::class, 1)->create([ 'user_id' => $user->id, 'client_id' => $client->id, 'company_id' => $company->id, 'is_primary' => 1 ]); - factory(\App\Models\ClientContact::class,rand(1,5))->create([ + factory(\App\Models\ClientContact::class, rand(1, 5))->create([ 'user_id' => $user->id, 'client_id' => $client->id, 'company_id' => $company->id ]); - $y = $this->count * rand(1,5); + $y = $this->count * rand(1, 5); $this->info("Creating {$y} invoices & quotes"); - for($x=0; $x<$y; $x++){ - + for ($x=0; $x<$y; $x++) { $this->createInvoice($client); $this->createQuote($client); } @@ -280,27 +269,24 @@ class CreateTestData extends Command { $faker = \Faker\Factory::create(); - $invoice = InvoiceFactory::create($client->company->id,$client->user->id);//stub the company and user_id + $invoice = InvoiceFactory::create($client->company->id, $client->user->id);//stub the company and user_id $invoice->client_id = $client->id; $invoice->date = $faker->date(); $invoice->line_items = $this->buildLineItems(); $invoice->uses_inclusive_taxes = false; - if(rand(0,1)) - { + if (rand(0, 1)) { $invoice->tax_name1 = 'GST'; $invoice->tax_rate1 = 10.00; } - if(rand(0,1)) - { + if (rand(0, 1)) { $invoice->tax_name2 = 'VAT'; $invoice->tax_rate2 = 17.50; } - if(rand(0,1)) - { + if (rand(0, 1)) { $invoice->tax_name3 = 'CA Sales Tax'; $invoice->tax_rate3 = 5; } @@ -314,31 +300,30 @@ class CreateTestData extends Command $invoice->save(); - event(new CreateInvoiceInvitation($invoice)); + event(new CreateInvoiceInvitation($invoice)); - UpdateCompanyLedgerWithInvoice::dispatchNow($invoice, $invoice->balance, $invoice->company); + UpdateCompanyLedgerWithInvoice::dispatchNow($invoice, $invoice->balance, $invoice->company); - $this->invoice_repo->markSent($invoice); + $this->invoice_repo->markSent($invoice); - CreateInvoiceInvitations::dispatch($invoice, $invoice->company); + CreateInvoiceInvitations::dispatch($invoice, $invoice->company); - if(rand(0, 1)) { + if (rand(0, 1)) { + $payment = PaymentFactory::create($client->company->id, $client->user->id); + $payment->date = now(); + $payment->client_id = $client->id; + $payment->amount = $invoice->balance; + $payment->transaction_reference = rand(0, 500); + $payment->type_id = PaymentType::CREDIT_CARD_OTHER; + $payment->status_id = Payment::STATUS_COMPLETED; + $payment->save(); - $payment = PaymentFactory::create($client->company->id, $client->user->id); - $payment->date = now(); - $payment->client_id = $client->id; - $payment->amount = $invoice->balance; - $payment->transaction_reference = rand(0,500); - $payment->type_id = PaymentType::CREDIT_CARD_OTHER; - $payment->status_id = Payment::STATUS_COMPLETED; - $payment->save(); + $payment->invoices()->save($invoice); - $payment->invoices()->save($invoice); + event(new PaymentWasCreated($payment, $payment->company)); - event(new PaymentWasCreated($payment, $payment->company)); - - UpdateInvoicePayment::dispatchNow($payment, $payment->company); - } + UpdateInvoicePayment::dispatchNow($payment, $payment->company); + } } @@ -346,27 +331,24 @@ class CreateTestData extends Command { $faker = \Faker\Factory::create(); - $quote = QuoteFactory::create($client->company->id,$client->user->id);//stub the company and user_id + $quote = QuoteFactory::create($client->company->id, $client->user->id);//stub the company and user_id $quote->client_id = $client->id; $quote->date = $faker->date(); $quote->line_items = $this->buildLineItems(); $quote->uses_inclusive_taxes = false; - if(rand(0,1)) - { + if (rand(0, 1)) { $quote->tax_name1 = 'GST'; $quote->tax_rate1 = 10.00; } - if(rand(0,1)) - { + if (rand(0, 1)) { $quote->tax_name2 = 'VAT'; $quote->tax_rate2 = 17.50; } - if(rand(0,1)) - { + if (rand(0, 1)) { $quote->tax_name3 = 'CA Sales Tax'; $quote->tax_rate3 = 5; } @@ -380,9 +362,7 @@ class CreateTestData extends Command $quote->save(); - CreateQuoteInvitations::dispatch($quote, $quote->company); - - + CreateQuoteInvitations::dispatch($quote, $quote->company); } private function buildLineItems() @@ -393,20 +373,17 @@ class CreateTestData extends Command $item->quantity = 1; $item->cost =10; - if(rand(0, 1)) - { + if (rand(0, 1)) { $item->tax_name1 = 'GST'; $item->tax_rate1 = 10.00; } - if(rand(0, 1)) - { + if (rand(0, 1)) { $item->tax_name1 = 'VAT'; $item->tax_rate1 = 17.50; } - if(rand(0, 1)) - { + if (rand(0, 1)) { $item->tax_name1 = 'Sales Tax'; $item->tax_rate1 = 5; } @@ -414,12 +391,11 @@ class CreateTestData extends Command $line_items[] = $item; return $line_items; - } private function warmCache() { - /* Warm up the cache !*/ + /* Warm up the cache !*/ $cached_tables = config('ninja.cached_tables'); foreach ($cached_tables as $name => $class) { diff --git a/app/Console/Commands/SendTestEmails.php b/app/Console/Commands/SendTestEmails.php index f46f14e62d85..3356d7b194f5 100644 --- a/app/Console/Commands/SendTestEmails.php +++ b/app/Console/Commands/SendTestEmails.php @@ -64,7 +64,7 @@ class SendTestEmails extends Command $user = User::whereEmail('user@example.com')->first(); $client = Client::all()->first(); - if(!$user){ + if (!$user) { $user = factory(\App\Models\User::class)->create([ 'confirmation_code' => '123', 'email' => 'admin@business.com', @@ -73,12 +73,11 @@ class SendTestEmails extends Command ]); } - if(!$client) { - - $client = ClientFactory::create($user->company()->id, $user->id); - $client->save(); + if (!$client) { + $client = ClientFactory::create($user->company()->id, $user->id); + $client->save(); - factory(\App\Models\ClientContact::class,1)->create([ + factory(\App\Models\ClientContact::class, 1)->create([ 'user_id' => $user->id, 'client_id' => $client->id, 'company_id' => $company->id, @@ -87,7 +86,7 @@ class SendTestEmails extends Command 'email' => 'exy@example.com', ]); - factory(\App\Models\ClientContact::class,1)->create([ + factory(\App\Models\ClientContact::class, 1)->create([ 'user_id' => $user->id, 'client_id' => $client->id, 'company_id' => $company->id, @@ -96,14 +95,13 @@ class SendTestEmails extends Command ]); } - $cc_emails = [config('ninja.testvars.test_email')]; - $bcc_emails = [config('ninja.testvars.test_email')]; + $cc_emails = [config('ninja.testvars.test_email')]; + $bcc_emails = [config('ninja.testvars.test_email')]; - Mail::to(config('ninja.testvars.test_email'),'Mr Test') + Mail::to(config('ninja.testvars.test_email'), 'Mr Test') ->cc($cc_emails) ->bcc($bcc_emails) //->replyTo(also_available_if_needed) ->send(new TemplateEmail($message, $template, $user, $client)); } - } diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 8fcf06167227..e10e34625cc5 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -38,8 +38,6 @@ class Kernel extends ConsoleKernel // ->hourly(); $schedule->job(new RecurringInvoicesCron)->hourly(); - - } /** diff --git a/app/DataMapper/BaseSettings.php b/app/DataMapper/BaseSettings.php index ae767a7cc4ff..5175cd70195b 100644 --- a/app/DataMapper/BaseSettings.php +++ b/app/DataMapper/BaseSettings.php @@ -16,50 +16,48 @@ namespace App\DataMapper; */ class BaseSettings { + public function __construct($obj) + { + foreach ($obj as $key => $value) { + $obj->{$key} = $value; + } + } + + public static function setCasts($obj, $casts) + { + foreach ($casts as $key => $value) { + $obj->{$key} = self::castAttribute($key, $obj->{$key}); + } - public function __construct($obj) - { - foreach($obj as $key => $value) - $obj->{$key} = $value; - } - - public static function setCasts($obj, $casts) - { - foreach ($casts as $key => $value) - $obj->{$key} = self::castAttribute($key, $obj->{$key}); + return $obj; + } - return $obj; - } + public static function castAttribute($key, $value) + { + switch ($key) { + case 'int': + case 'integer': + return (int) $value; + case 'real': + case 'float': + case 'double': + return (float) $value; + case 'string': + return is_null($value) ? '' : (string) $value; + case 'bool': + case 'boolean': + return (bool)($value); + case 'object': + return json_decode($value); + case 'array': + case 'json': + return json_decode($value, true); + default: + return $value; + } + } - public static function castAttribute($key, $value) - { - switch ($key) - { - case 'int': - case 'integer': - return (int) $value; - case 'real': - case 'float': - case 'double': - return (float) $value; - case 'string': - return is_null($value) ? '' : (string) $value; - case 'bool': - case 'boolean': - return (bool)($value); - case 'object': - return json_decode($value); - case 'array': - case 'json': - return json_decode($value, true); - default: - return $value; - } - } - - public static function castSingleAttribute($key, $data) - { - - } - -} \ No newline at end of file + public static function castSingleAttribute($key, $data) + { + } +} diff --git a/app/DataMapper/ClientSettings.php b/app/DataMapper/ClientSettings.php index 133220a0d3dd..96e591ece220 100644 --- a/app/DataMapper/ClientSettings.php +++ b/app/DataMapper/ClientSettings.php @@ -20,88 +20,82 @@ use App\Utils\TranslationHelper; * ClientSettings * * Client settings are built as a superset of Company Settings - * + * * If no client settings is specified, the default company setting is used. - * + * * Client settings are passed down to the entity level where they can be further customized and then saved * into the settings column of the entity, so there is no need to create additional entity level settings handlers. - * + * */ class ClientSettings extends BaseSettings { - /** - * Settings which which are unique to client settings - */ - public $industry_id; - public $size_id; - - public static $casts = [ - 'industry_id' => 'string', - 'size_id' => 'string', - ]; - - /** - * Cast object values and return entire class - * prevents missing properties from not being returned - * and always ensure an up to date class is returned - * - * @return \stdClass + /** + * Settings which which are unique to client settings */ - public function __construct($obj) - { - parent::__construct($obj); - } + public $industry_id; + public $size_id; - /** - * - * Default Client Settings scaffold - * - * @return \stdClass - * + public static $casts = [ + 'industry_id' => 'string', + 'size_id' => 'string', + ]; + + /** + * Cast object values and return entire class + * prevents missing properties from not being returned + * and always ensure an up to date class is returned + * + * @return \stdClass */ - public static function defaults() : \stdClass - { + public function __construct($obj) + { + parent::__construct($obj); + } - $data = (object)[ - 'entity' => (string)Client::class, - 'industry_id' => '', - 'size_id' => '', - ]; + /** + * + * Default Client Settings scaffold + * + * @return \stdClass + * + */ + public static function defaults() : \stdClass + { + $data = (object)[ + 'entity' => (string)Client::class, + 'industry_id' => '', + 'size_id' => '', + ]; - return self::setCasts($data, self::$casts); - - } + return self::setCasts($data, self::$casts); + } - /** - * Merges settings from Company to Client - * - * @param \stdClass $company_settings - * @param \stdClass $client_settings - * @return \stdClass of merged settings - */ - public static function buildClientSettings($company_settings, $client_settings) - { - - if(!$client_settings) - return $company_settings; - - foreach($company_settings as $key => $value) - { - /* pseudo code - if the property exists and is a string BUT has no length, treat it as TRUE - */ - if( ( (property_exists($client_settings, $key) && is_string($client_settings->{$key}) && (iconv_strlen($client_settings->{$key}) <1))) - || !isset($client_settings->{$key}) - && property_exists($company_settings, $key)) { - $client_settings->{$key} = $company_settings->{$key}; - } - - } - - return $client_settings; - } - + /** + * Merges settings from Company to Client + * + * @param \stdClass $company_settings + * @param \stdClass $client_settings + * @return \stdClass of merged settings + */ + public static function buildClientSettings($company_settings, $client_settings) + { + if (!$client_settings) { + return $company_settings; + } + + foreach ($company_settings as $key => $value) { + /* pseudo code + if the property exists and is a string BUT has no length, treat it as TRUE + */ + if (((property_exists($client_settings, $key) && is_string($client_settings->{$key}) && (iconv_strlen($client_settings->{$key}) <1))) + || !isset($client_settings->{$key}) + && property_exists($company_settings, $key)) { + $client_settings->{$key} = $company_settings->{$key}; + } + } + + return $client_settings; + } } - diff --git a/app/DataMapper/CompanySettings.php b/app/DataMapper/CompanySettings.php index cb9777257544..75c0c4b9b6e4 100644 --- a/app/DataMapper/CompanySettings.php +++ b/app/DataMapper/CompanySettings.php @@ -21,442 +21,435 @@ use App\Models\Company; class CompanySettings extends BaseSettings { - /*Group settings based on functionality*/ + /*Group settings based on functionality*/ - /*Invoice*/ - public $auto_archive_invoice = false; - public $lock_sent_invoices = false; + /*Invoice*/ + public $auto_archive_invoice = false; + public $lock_sent_invoices = false; - public $enable_client_portal_tasks = false; - public $enable_client_portal_password = false; - public $enable_client_portal = true; //implemented - public $enable_client_portal_dashboard = true; //implemented - public $signature_on_pdf = false; - public $document_email_attachment = false; - public $send_portal_password = false; + public $enable_client_portal_tasks = false; + public $enable_client_portal_password = false; + public $enable_client_portal = true; //implemented + public $enable_client_portal_dashboard = true; //implemented + public $signature_on_pdf = false; + public $document_email_attachment = false; + public $send_portal_password = false; - public $timezone_id = ''; - public $date_format_id = ''; - public $military_time = false; + public $timezone_id = ''; + public $date_format_id = ''; + public $military_time = false; - public $language_id = ''; - public $show_currency_code = false; + public $language_id = ''; + public $show_currency_code = false; - public $company_gateway_ids = ''; + public $company_gateway_ids = ''; - public $currency_id = '1'; + public $currency_id = '1'; - public $custom_value1 = ''; - public $custom_value2 = ''; - public $custom_value3 = ''; - public $custom_value4 = ''; + public $custom_value1 = ''; + public $custom_value2 = ''; + public $custom_value3 = ''; + public $custom_value4 = ''; - public $default_task_rate = 0; + public $default_task_rate = 0; - public $payment_terms = 1; - public $send_reminders = false; + public $payment_terms = 1; + public $send_reminders = false; - public $custom_message_dashboard = ''; - public $custom_message_unpaid_invoice = ''; - public $custom_message_paid_invoice = ''; - public $custom_message_unapproved_quote = ''; - public $auto_archive_quote = false; - public $auto_convert_quote = true; - public $auto_email_invoice = true; + public $custom_message_dashboard = ''; + public $custom_message_unpaid_invoice = ''; + public $custom_message_paid_invoice = ''; + public $custom_message_unapproved_quote = ''; + public $auto_archive_quote = false; + public $auto_convert_quote = true; + public $auto_email_invoice = true; - public $inclusive_taxes = false; - public $quote_footer = ''; + public $inclusive_taxes = false; + public $quote_footer = ''; - public $translations; + public $translations; - public $counter_number_applied = 'when_saved'; // when_saved , when_sent , when_paid - public $quote_number_applied = 'when_saved'; // when_saved , when_sent - /* Counters */ - public $invoice_number_pattern = ''; - public $invoice_number_counter = 1; + public $counter_number_applied = 'when_saved'; // when_saved , when_sent , when_paid + public $quote_number_applied = 'when_saved'; // when_saved , when_sent + /* Counters */ + public $invoice_number_pattern = ''; + public $invoice_number_counter = 1; - public $quote_number_pattern = ''; - public $quote_number_counter = 1; + public $quote_number_pattern = ''; + public $quote_number_counter = 1; - public $client_number_pattern = ''; - public $client_number_counter = 1; + public $client_number_pattern = ''; + public $client_number_counter = 1; - public $credit_number_pattern = ''; - public $credit_number_counter = 1; + public $credit_number_pattern = ''; + public $credit_number_counter = 1; - public $task_number_pattern = ''; - public $task_number_counter = 1; + public $task_number_pattern = ''; + public $task_number_counter = 1; - public $expense_number_pattern = ''; - public $expense_number_counter = 1; + public $expense_number_pattern = ''; + public $expense_number_counter = 1; - public $vendor_number_pattern = ''; - public $vendor_number_counter = 1; + public $vendor_number_pattern = ''; + public $vendor_number_counter = 1; - public $ticket_number_pattern = ''; - public $ticket_number_counter = 1; + public $ticket_number_pattern = ''; + public $ticket_number_counter = 1; - public $payment_number_pattern = ''; - public $payment_number_counter = 1; + public $payment_number_pattern = ''; + public $payment_number_counter = 1; - public $shared_invoice_quote_counter = false; - public $recurring_number_prefix = 'R'; - public $reset_counter_frequency_id = '0'; - public $reset_counter_date = ''; - public $counter_padding = 4; + public $shared_invoice_quote_counter = false; + public $recurring_number_prefix = 'R'; + public $reset_counter_frequency_id = '0'; + public $reset_counter_date = ''; + public $counter_padding = 4; - public $design = 'views/pdf/design1.blade.php'; + public $design = 'views/pdf/design1.blade.php'; - public $invoice_terms = ''; - public $quote_terms = ''; - public $invoice_taxes = 0; - public $enabled_item_tax_rates = 0; - public $invoice_design_id = '1'; - public $quote_design_id = '1'; - public $invoice_footer = ''; - public $invoice_labels = ''; - public $tax_name1 = ''; - public $tax_rate1 = 0; - public $tax_name2 = ''; - public $tax_rate2 = 0; - public $tax_name3 = ''; - public $tax_rate3 = 0; - public $payment_type_id = '1'; - public $invoice_fields = ''; + public $invoice_terms = ''; + public $quote_terms = ''; + public $invoice_taxes = 0; + public $enabled_item_tax_rates = 0; + public $invoice_design_id = '1'; + public $quote_design_id = '1'; + public $invoice_footer = ''; + public $invoice_labels = ''; + public $tax_name1 = ''; + public $tax_rate1 = 0; + public $tax_name2 = ''; + public $tax_rate2 = 0; + public $tax_name3 = ''; + public $tax_rate3 = 0; + public $payment_type_id = '1'; + public $invoice_fields = ''; - public $show_accept_invoice_terms = false; - public $show_accept_quote_terms = false; - public $require_invoice_signature = false; - public $require_quote_signature = false; + public $show_accept_invoice_terms = false; + public $show_accept_quote_terms = false; + public $require_invoice_signature = false; + public $require_quote_signature = false; - //email settings - public $email_sending_method = 'default'; //enum 'default','gmail' - public $gmail_sending_user_id = '0'; - - public $reply_to_email = ''; - public $bcc_email = ''; - public $pdf_email_attachment = false; - public $ubl_email_attachment = false; + //email settings + public $email_sending_method = 'default'; //enum 'default','gmail' + public $gmail_sending_user_id = '0'; + + public $reply_to_email = ''; + public $bcc_email = ''; + public $pdf_email_attachment = false; + public $ubl_email_attachment = false; - public $email_style = 'plain'; //plain, light, dark, custom - public $email_style_custom = ''; //the template itself - public $email_subject_invoice = ''; - public $email_subject_quote = ''; - public $email_subject_payment = ''; - public $email_subject_statement = ''; - public $email_template_invoice = ''; - public $email_template_quote = ''; - public $email_template_payment = ''; - public $email_template_statement = ''; - public $email_subject_reminder1 = ''; - public $email_subject_reminder2 = ''; - public $email_subject_reminder3 = ''; - public $email_subject_reminder_endless = ''; - public $email_template_reminder1 = ''; - public $email_template_reminder2 = ''; - public $email_template_reminder3 = ''; - public $email_template_reminder_endless = ''; - public $email_signature = ''; - public $enable_email_markup = true; + public $email_style = 'plain'; //plain, light, dark, custom + public $email_style_custom = ''; //the template itself + public $email_subject_invoice = ''; + public $email_subject_quote = ''; + public $email_subject_payment = ''; + public $email_subject_statement = ''; + public $email_template_invoice = ''; + public $email_template_quote = ''; + public $email_template_payment = ''; + public $email_template_statement = ''; + public $email_subject_reminder1 = ''; + public $email_subject_reminder2 = ''; + public $email_subject_reminder3 = ''; + public $email_subject_reminder_endless = ''; + public $email_template_reminder1 = ''; + public $email_template_reminder2 = ''; + public $email_template_reminder3 = ''; + public $email_template_reminder_endless = ''; + public $email_signature = ''; + public $enable_email_markup = true; - public $email_subject_custom1 = ''; - public $email_subject_custom2 = ''; - public $email_subject_custom3 = ''; + public $email_subject_custom1 = ''; + public $email_subject_custom2 = ''; + public $email_subject_custom3 = ''; - public $email_template_custom1 = ''; - public $email_template_custom2 = ''; - public $email_template_custom3 = ''; + public $email_template_custom1 = ''; + public $email_template_custom2 = ''; + public $email_template_custom3 = ''; - public $enable_reminder1 = false; - public $enable_reminder2 = false; - public $enable_reminder3 = false; + public $enable_reminder1 = false; + public $enable_reminder2 = false; + public $enable_reminder3 = false; - public $num_days_reminder1 = 0; - public $num_days_reminder2 = 0; - public $num_days_reminder3 = 0; + public $num_days_reminder1 = 0; + public $num_days_reminder2 = 0; + public $num_days_reminder3 = 0; - public $schedule_reminder1 = ''; // (enum: after_invoice_date, before_due_date, after_due_date) - public $schedule_reminder2 = ''; // (enum: after_invoice_date, before_due_date, after_due_date) - public $schedule_reminder3 = ''; // (enum: after_invoice_date, before_due_date, after_due_date) + public $schedule_reminder1 = ''; // (enum: after_invoice_date, before_due_date, after_due_date) + public $schedule_reminder2 = ''; // (enum: after_invoice_date, before_due_date, after_due_date) + public $schedule_reminder3 = ''; // (enum: after_invoice_date, before_due_date, after_due_date) - public $reminder_send_time = 32400; //number of seconds from UTC +0 to send reminders + public $reminder_send_time = 32400; //number of seconds from UTC +0 to send reminders - public $late_fee_amount1 = 0; - public $late_fee_amount2 = 0; - public $late_fee_amount3 = 0; + public $late_fee_amount1 = 0; + public $late_fee_amount2 = 0; + public $late_fee_amount3 = 0; - public $endless_reminder_frequency_id = '0'; + public $endless_reminder_frequency_id = '0'; - public $client_online_payment_notification = true; - public $client_manual_payment_notification = true; + public $client_online_payment_notification = true; + public $client_manual_payment_notification = true; - /* Company Meta data that we can use to build sub companies*/ + /* Company Meta data that we can use to build sub companies*/ - public $name = ''; - public $company_logo = ''; - public $website = ''; - public $address1 = ''; - public $address2 = ''; - public $city = ''; - public $state = ''; - public $postal_code = ''; - public $phone = ''; - public $email = ''; - public $country_id; - public $vat_number = ''; - public $id_number = ''; + public $name = ''; + public $company_logo = ''; + public $website = ''; + public $address1 = ''; + public $address2 = ''; + public $city = ''; + public $state = ''; + public $postal_code = ''; + public $phone = ''; + public $email = ''; + public $country_id; + public $vat_number = ''; + public $id_number = ''; - public $page_size = 'A4'; - public $font_size = 9; + public $page_size = 'A4'; + public $font_size = 9; public $primary_font = 'Roboto'; public $secondary_font = 'Roboto'; public $hide_paid_to_date = false; - public $embed_documents = false; + public $embed_documents = false; public $all_pages_header = true; public $all_pages_footer = true; - public static $casts = [ - 'auto_email_invoice' => 'bool', - 'reminder_send_time' => 'int', - 'email_sending_method' => 'string', - 'gmail_sending_user_id' => 'string', - 'currency_id' => 'string', - 'counter_number_applied' => 'string', - 'quote_number_applied' => 'string', - 'email_subject_custom1' => 'string', - 'email_subject_custom2' => 'string', - 'email_subject_custom3' => 'string', - 'email_template_custom1' => 'string', - 'email_template_custom2' => 'string', - 'email_template_custom3' => 'string', - 'enable_reminder1' => 'bool', - 'enable_reminder2' => 'bool', - 'enable_reminder3' => 'bool', - 'num_days_reminder1' => 'int', - 'num_days_reminder2' => 'int', - 'num_days_reminder3' => 'int', - 'schedule_reminder1' => 'string', // (enum: after_invoice_date, before_due_date, after_due_date) - 'schedule_reminder2' => 'string', // (enum: after_invoice_date, before_due_date, after_due_date) - 'schedule_reminder3' => 'string', // (enum: after_invoice_date, before_due_date, after_due_date) - 'late_fee_amount1' => 'float', - 'late_fee_amount2' => 'float', - 'late_fee_amount3' => 'float', - 'endless_reminder_frequency_id' => 'integer', - 'client_online_payment_notification' => 'bool', - 'client_manual_payment_notification' => 'bool', - 'document_email_attachment' => 'bool', - 'enable_client_portal_password' => 'bool', - 'enable_email_markup' => 'bool', - 'enable_client_portal_dashboard' => 'bool', - 'enable_client_portal' => 'bool', - 'email_template_statement' => 'string', - 'email_subject_statement' => 'string', - 'signature_on_pdf' => 'bool', - 'send_portal_password' => 'bool', - 'quote_footer' => 'string', - 'page_size' => 'string', - 'font_size' => 'int', - 'primary_font' => 'string', - 'secondary_font' => 'string', - 'hide_paid_to_date' => 'bool', - 'embed_documents' => 'bool', - 'all_pages_header' => 'bool', - 'all_pages_footer' => 'bool', - 'task_number_pattern' => 'string', - 'task_number_counter' => 'int', - 'expense_number_pattern' => 'string', - 'expense_number_counter' => 'int', - 'vendor_number_pattern' => 'string', - 'vendor_number_counter' => 'int', - 'ticket_number_pattern' => 'string', - 'ticket_number_counter' => 'int', - 'payment_number_pattern' => 'string', - 'payment_number_counter' => 'int', - 'reply_to_email' => 'string', - 'bcc_email' => 'string', - 'pdf_email_attachment' => 'bool', - 'ubl_email_attachment' => 'bool', - 'email_style' => 'string', - 'email_style_custom' => 'string', - 'company_gateway_ids' => 'string', - 'address1' => 'string', - 'address2' => 'string', - 'city' => 'string', - 'company_logo' => 'string', - 'country_id' => 'string', - 'client_number_pattern' => 'string', - 'client_number_counter' => 'integer', - 'credit_number_pattern' => 'string', - 'credit_number_counter' => 'integer', - 'currency_id' => 'string', - 'custom_value1' => 'string', - 'custom_value2' => 'string', - 'custom_value3' => 'string', - 'custom_value4' => 'string', - 'custom_message_dashboard' => 'string', - 'custom_message_unpaid_invoice' => 'string', - 'custom_message_paid_invoice' => 'string', - 'custom_message_unapproved_quote' => 'string', - 'default_task_rate' => 'float', - 'email_signature' => 'string', - 'email_subject_invoice' => 'string', - 'email_subject_quote' => 'string', - 'email_subject_payment' => 'string', - 'email_template_invoice' => 'string', - 'email_template_quote' => 'string', - 'email_template_payment' => 'string', - 'email_subject_reminder1' => 'string', - 'email_subject_reminder2' => 'string', - 'email_subject_reminder3' => 'string', - 'email_subject_reminder_endless' => 'string', - 'email_template_reminder1' => 'string', - 'email_template_reminder2' => 'string', - 'email_template_reminder3' => 'string', - 'email_template_reminder_endless' => 'string', - 'enable_client_portal_password' => 'bool', - 'inclusive_taxes' => 'bool', - 'invoice_number_pattern' => 'string', - 'invoice_number_counter' => 'integer', - 'invoice_design_id' => 'string', - 'invoice_fields' => 'string', - 'invoice_taxes' => 'int', - 'enabled_item_tax_rates' => 'int', - 'invoice_footer' => 'string', - 'invoice_labels' => 'string', - 'invoice_terms' => 'string', - 'name' => 'string', - 'payment_terms' => 'integer', - 'payment_type_id' => 'string', - 'phone' => 'string', - 'postal_code' => 'string', - 'quote_design_id' => 'string', - 'quote_number_pattern' => 'string', - 'quote_number_counter' => 'integer', - 'quote_terms' => 'string', - 'recurring_number_prefix' => 'string', - 'reset_counter_frequency_id' => 'integer', - 'reset_counter_date' => 'string', - 'require_invoice_signature' => 'bool', - 'require_quote_signature' => 'bool', - 'state' => 'string', - 'email' => 'string', - 'vat_number' => 'string', - 'id_number' => 'string', - 'tax_name1' => 'string', - 'tax_name2' => 'string', - 'tax_name3' => 'string', - 'tax_rate1' => 'float', - 'tax_rate2' => 'float', - 'tax_rate3' => 'float', - 'show_accept_quote_terms' => 'bool', - 'show_accept_invoice_terms' => 'bool', - 'timezone_id' => 'string', - 'date_format_id' => 'string', - 'military_time' => 'bool', - 'language_id' => 'string', - 'show_currency_code' => 'bool', - 'send_reminders' => 'bool', - 'enable_client_portal_tasks' => 'bool', - 'lock_sent_invoices' => 'bool', - 'auto_archive_invoice' => 'bool', - 'auto_archive_quote' => 'bool', - 'auto_convert_quote' => 'bool', - 'shared_invoice_quote_counter' => 'bool', - 'counter_padding' => 'integer', - 'design' => 'string', - 'website' => 'string', - ]; + public static $casts = [ + 'auto_email_invoice' => 'bool', + 'reminder_send_time' => 'int', + 'email_sending_method' => 'string', + 'gmail_sending_user_id' => 'string', + 'currency_id' => 'string', + 'counter_number_applied' => 'string', + 'quote_number_applied' => 'string', + 'email_subject_custom1' => 'string', + 'email_subject_custom2' => 'string', + 'email_subject_custom3' => 'string', + 'email_template_custom1' => 'string', + 'email_template_custom2' => 'string', + 'email_template_custom3' => 'string', + 'enable_reminder1' => 'bool', + 'enable_reminder2' => 'bool', + 'enable_reminder3' => 'bool', + 'num_days_reminder1' => 'int', + 'num_days_reminder2' => 'int', + 'num_days_reminder3' => 'int', + 'schedule_reminder1' => 'string', // (enum: after_invoice_date, before_due_date, after_due_date) + 'schedule_reminder2' => 'string', // (enum: after_invoice_date, before_due_date, after_due_date) + 'schedule_reminder3' => 'string', // (enum: after_invoice_date, before_due_date, after_due_date) + 'late_fee_amount1' => 'float', + 'late_fee_amount2' => 'float', + 'late_fee_amount3' => 'float', + 'endless_reminder_frequency_id' => 'integer', + 'client_online_payment_notification' => 'bool', + 'client_manual_payment_notification' => 'bool', + 'document_email_attachment' => 'bool', + 'enable_client_portal_password' => 'bool', + 'enable_email_markup' => 'bool', + 'enable_client_portal_dashboard' => 'bool', + 'enable_client_portal' => 'bool', + 'email_template_statement' => 'string', + 'email_subject_statement' => 'string', + 'signature_on_pdf' => 'bool', + 'send_portal_password' => 'bool', + 'quote_footer' => 'string', + 'page_size' => 'string', + 'font_size' => 'int', + 'primary_font' => 'string', + 'secondary_font' => 'string', + 'hide_paid_to_date' => 'bool', + 'embed_documents' => 'bool', + 'all_pages_header' => 'bool', + 'all_pages_footer' => 'bool', + 'task_number_pattern' => 'string', + 'task_number_counter' => 'int', + 'expense_number_pattern' => 'string', + 'expense_number_counter' => 'int', + 'vendor_number_pattern' => 'string', + 'vendor_number_counter' => 'int', + 'ticket_number_pattern' => 'string', + 'ticket_number_counter' => 'int', + 'payment_number_pattern' => 'string', + 'payment_number_counter' => 'int', + 'reply_to_email' => 'string', + 'bcc_email' => 'string', + 'pdf_email_attachment' => 'bool', + 'ubl_email_attachment' => 'bool', + 'email_style' => 'string', + 'email_style_custom' => 'string', + 'company_gateway_ids' => 'string', + 'address1' => 'string', + 'address2' => 'string', + 'city' => 'string', + 'company_logo' => 'string', + 'country_id' => 'string', + 'client_number_pattern' => 'string', + 'client_number_counter' => 'integer', + 'credit_number_pattern' => 'string', + 'credit_number_counter' => 'integer', + 'currency_id' => 'string', + 'custom_value1' => 'string', + 'custom_value2' => 'string', + 'custom_value3' => 'string', + 'custom_value4' => 'string', + 'custom_message_dashboard' => 'string', + 'custom_message_unpaid_invoice' => 'string', + 'custom_message_paid_invoice' => 'string', + 'custom_message_unapproved_quote' => 'string', + 'default_task_rate' => 'float', + 'email_signature' => 'string', + 'email_subject_invoice' => 'string', + 'email_subject_quote' => 'string', + 'email_subject_payment' => 'string', + 'email_template_invoice' => 'string', + 'email_template_quote' => 'string', + 'email_template_payment' => 'string', + 'email_subject_reminder1' => 'string', + 'email_subject_reminder2' => 'string', + 'email_subject_reminder3' => 'string', + 'email_subject_reminder_endless' => 'string', + 'email_template_reminder1' => 'string', + 'email_template_reminder2' => 'string', + 'email_template_reminder3' => 'string', + 'email_template_reminder_endless' => 'string', + 'enable_client_portal_password' => 'bool', + 'inclusive_taxes' => 'bool', + 'invoice_number_pattern' => 'string', + 'invoice_number_counter' => 'integer', + 'invoice_design_id' => 'string', + 'invoice_fields' => 'string', + 'invoice_taxes' => 'int', + 'enabled_item_tax_rates' => 'int', + 'invoice_footer' => 'string', + 'invoice_labels' => 'string', + 'invoice_terms' => 'string', + 'name' => 'string', + 'payment_terms' => 'integer', + 'payment_type_id' => 'string', + 'phone' => 'string', + 'postal_code' => 'string', + 'quote_design_id' => 'string', + 'quote_number_pattern' => 'string', + 'quote_number_counter' => 'integer', + 'quote_terms' => 'string', + 'recurring_number_prefix' => 'string', + 'reset_counter_frequency_id' => 'integer', + 'reset_counter_date' => 'string', + 'require_invoice_signature' => 'bool', + 'require_quote_signature' => 'bool', + 'state' => 'string', + 'email' => 'string', + 'vat_number' => 'string', + 'id_number' => 'string', + 'tax_name1' => 'string', + 'tax_name2' => 'string', + 'tax_name3' => 'string', + 'tax_rate1' => 'float', + 'tax_rate2' => 'float', + 'tax_rate3' => 'float', + 'show_accept_quote_terms' => 'bool', + 'show_accept_invoice_terms' => 'bool', + 'timezone_id' => 'string', + 'date_format_id' => 'string', + 'military_time' => 'bool', + 'language_id' => 'string', + 'show_currency_code' => 'bool', + 'send_reminders' => 'bool', + 'enable_client_portal_tasks' => 'bool', + 'lock_sent_invoices' => 'bool', + 'auto_archive_invoice' => 'bool', + 'auto_archive_quote' => 'bool', + 'auto_convert_quote' => 'bool', + 'shared_invoice_quote_counter' => 'bool', + 'counter_padding' => 'integer', + 'design' => 'string', + 'website' => 'string', + ]; - /** - * Array of variables which - * cannot be modified client side - */ - public static $protected_fields = [ - // 'credit_number_counter', - // 'invoice_number_counter', - // 'quote_number_counter', - ]; - - /** - * Cast object values and return entire class - * prevents missing properties from not being returned - * and always ensure an up to date class is returned - * - * @return \stdClass + /** + * Array of variables which + * cannot be modified client side */ - public function __construct($obj) - { - // parent::__construct($obj); - } + public static $protected_fields = [ + // 'credit_number_counter', + // 'invoice_number_counter', + // 'quote_number_counter', + ]; - /** - * Provides class defaults on init - * @return object - */ - public static function defaults() : \stdClass - { - - $config = json_decode(config('ninja.settings')); - - $data = (object)get_class_vars(CompanySettings::class); - unset($data->casts); - unset($data->protected_fields); + /** + * Cast object values and return entire class + * prevents missing properties from not being returned + * and always ensure an up to date class is returned + * + * @return \stdClass + */ + public function __construct($obj) + { + // parent::__construct($obj); + } - $data->timezone_id = (string)config('ninja.i18n.timezone_id'); - $data->currency_id = (string)config('ninja.i18n.currency_id'); - $data->language_id = (string)config('ninja.i18n.language_id'); - $data->payment_terms = (int)config('ninja.i18n.payment_terms'); - $data->military_time = (bool)config('ninja.i18n.military_time'); - $data->date_format_id = (string)config('ninja.i18n.date_format_id'); - $data->country_id = (string)config('ninja.i18n.country_id'); - $data->translations = (object) []; - - // $data->email_subject_invoice = EmailTemplateDefaults::emailInvoiceSubject(); - // $data->email_template_invoice = EmailTemplateDefaults:: emailInvoiceTemplate(); - // $data->email_subject_quote = EmailTemplateDefaults::emailQuoteSubject(); - // $data->email_subject_payment = EmailTemplateDefaults::emailPaymentSubject(); - // $data->email_subject_statement = EmailTemplateDefaults::emailStatementSubject(); - // $data->email_template_quote = EmailTemplateDefaults::emailQuoteTemplate(); - // $data->email_template_payment = EmailTemplateDefaults::emailPaymentTemplate(); - // $data->email_template_statement = EmailTemplateDefaults::emailStatementTemplate(); - // $data->email_subject_reminder1 = EmailTemplateDefaults::emailReminder1Subject(); - // $data->email_subject_reminder2 = EmailTemplateDefaults::emailReminder2Subject(); - // $data->email_subject_reminder3 = EmailTemplateDefaults::emailReminder3Subject(); - // $data->email_subject_reminder_endless = EmailTemplateDefaults::emailReminderEndlessSubject(); - // $data->email_template_reminder1 = EmailTemplateDefaults::emailReminder1Template(); - // $data->email_template_reminder2 = EmailTemplateDefaults::emailReminder2Template(); - // $data->email_template_reminder3 = EmailTemplateDefaults::emailReminder3Template(); - // $data->email_template_reminder_endless = EmailTemplateDefaults::emailReminderEndlessTemplate(); - - return self::setCasts($data, self::$casts); + /** + * Provides class defaults on init + * @return object + */ + public static function defaults() : \stdClass + { + $config = json_decode(config('ninja.settings')); + + $data = (object)get_class_vars(CompanySettings::class); + unset($data->casts); + unset($data->protected_fields); - } + $data->timezone_id = (string)config('ninja.i18n.timezone_id'); + $data->currency_id = (string)config('ninja.i18n.currency_id'); + $data->language_id = (string)config('ninja.i18n.language_id'); + $data->payment_terms = (int)config('ninja.i18n.payment_terms'); + $data->military_time = (bool)config('ninja.i18n.military_time'); + $data->date_format_id = (string)config('ninja.i18n.date_format_id'); + $data->country_id = (string)config('ninja.i18n.country_id'); + $data->translations = (object) []; + + // $data->email_subject_invoice = EmailTemplateDefaults::emailInvoiceSubject(); + // $data->email_template_invoice = EmailTemplateDefaults:: emailInvoiceTemplate(); + // $data->email_subject_quote = EmailTemplateDefaults::emailQuoteSubject(); + // $data->email_subject_payment = EmailTemplateDefaults::emailPaymentSubject(); + // $data->email_subject_statement = EmailTemplateDefaults::emailStatementSubject(); + // $data->email_template_quote = EmailTemplateDefaults::emailQuoteTemplate(); + // $data->email_template_payment = EmailTemplateDefaults::emailPaymentTemplate(); + // $data->email_template_statement = EmailTemplateDefaults::emailStatementTemplate(); + // $data->email_subject_reminder1 = EmailTemplateDefaults::emailReminder1Subject(); + // $data->email_subject_reminder2 = EmailTemplateDefaults::emailReminder2Subject(); + // $data->email_subject_reminder3 = EmailTemplateDefaults::emailReminder3Subject(); + // $data->email_subject_reminder_endless = EmailTemplateDefaults::emailReminderEndlessSubject(); + // $data->email_template_reminder1 = EmailTemplateDefaults::emailReminder1Template(); + // $data->email_template_reminder2 = EmailTemplateDefaults::emailReminder2Template(); + // $data->email_template_reminder3 = EmailTemplateDefaults::emailReminder3Template(); + // $data->email_template_reminder_endless = EmailTemplateDefaults::emailReminderEndlessTemplate(); + + return self::setCasts($data, self::$casts); + } - /** - * In case we update the settings object in the future we - * need to provide a fallback catch on old settings objects which will - * set new properties to the object prior to being returned. - * - * @param object $data The settings object to be checked - */ - public static function setProperties($settings) :\stdClass - { + /** + * In case we update the settings object in the future we + * need to provide a fallback catch on old settings objects which will + * set new properties to the object prior to being returned. + * + * @param object $data The settings object to be checked + */ + public static function setProperties($settings) :\stdClass + { + $company_settings = (object)get_class_vars(CompanySettings::class); - $company_settings = (object)get_class_vars(CompanySettings::class); - - foreach($company_settings as $key => $value) - { - - if(!property_exists($settings, $key)) - $settings->{$key} = self::castAttribute($key, $company_settings->{$key}); - - } - - return $settings; - - } + foreach ($company_settings as $key => $value) { + if (!property_exists($settings, $key)) { + $settings->{$key} = self::castAttribute($key, $company_settings->{$key}); + } + } + return $settings; + } } diff --git a/app/DataMapper/DefaultSettings.php b/app/DataMapper/DefaultSettings.php index f4f91223600f..f73bdc7df4ed 100644 --- a/app/DataMapper/DefaultSettings.php +++ b/app/DataMapper/DefaultSettings.php @@ -21,33 +21,30 @@ use App\Models\User; class DefaultSettings extends BaseSettings { - /** - * @var int + /** + * @var int */ - public static $per_page = 25; + public static $per_page = 25; - /** - * @return \stdClass - * - * //todo user specific settings / preferences. + /** + * @return \stdClass + * + * //todo user specific settings / preferences. */ - public static function userSettings() : \stdClass - { - return (object)[ - class_basename(User::class) => self::userSettingsObject(), - ]; - } + public static function userSettings() : \stdClass + { + return (object)[ + class_basename(User::class) => self::userSettingsObject(), + ]; + } - /** - * @return \stdClass + /** + * @return \stdClass */ - private static function userSettingsObject() : \stdClass - { - - return (object)[ - 'per_page' => self::$per_page, - ]; - - } - -} \ No newline at end of file + private static function userSettingsObject() : \stdClass + { + return (object)[ + 'per_page' => self::$per_page, + ]; + } +} diff --git a/app/DataMapper/EmailTemplateDefaults.php b/app/DataMapper/EmailTemplateDefaults.php index 9cbdafa19aaa..423c465fae1e 100644 --- a/app/DataMapper/EmailTemplateDefaults.php +++ b/app/DataMapper/EmailTemplateDefaults.php @@ -108,5 +108,3 @@ class EmailTemplateDefaults return str_replace(":", "$", ctrans('texts.'.$string)); } } - - diff --git a/app/DataMapper/FeesAndLimits.php b/app/DataMapper/FeesAndLimits.php index 94a45d46ef85..370ed326ef67 100644 --- a/app/DataMapper/FeesAndLimits.php +++ b/app/DataMapper/FeesAndLimits.php @@ -13,29 +13,29 @@ namespace App\DataMapper; class FeesAndLimits { - public $min_limit = -1; //equivalent to null + public $min_limit = -1; //equivalent to null - public $max_limit = -1; //equivalent to null + public $max_limit = -1; //equivalent to null - public $fee_amount = 0; + public $fee_amount = 0; - public $fee_percent = 0; + public $fee_percent = 0; - public $fee_tax_name1 = ''; + public $fee_tax_name1 = ''; - public $fee_tax_name2 = ''; + public $fee_tax_name2 = ''; - public $fee_tax_name3 = ''; + public $fee_tax_name3 = ''; - public $fee_tax_rate1 = 0; + public $fee_tax_rate1 = 0; - public $fee_tax_rate2 = 0; + public $fee_tax_rate2 = 0; - public $fee_tax_rate3 = 0; + public $fee_tax_rate3 = 0; - public $fee_cap = 0; + public $fee_cap = 0; - public $adjust_fee_percent = false; + public $adjust_fee_percent = false; //public $gateway_type_id = 1; diff --git a/app/DataMapper/InvoiceItem.php b/app/DataMapper/InvoiceItem.php index 7ec375a5e24f..e66b18f39cdd 100644 --- a/app/DataMapper/InvoiceItem.php +++ b/app/DataMapper/InvoiceItem.php @@ -13,7 +13,6 @@ namespace App\DataMapper; class InvoiceItem { - public $quantity = 0; public $cost = 0; diff --git a/app/DataMapper/PaymentMethodMeta.php b/app/DataMapper/PaymentMethodMeta.php index d4431e69b982..28c8a0c8ab7e 100644 --- a/app/DataMapper/PaymentMethodMeta.php +++ b/app/DataMapper/PaymentMethodMeta.php @@ -13,13 +13,13 @@ namespace App\DataMapper; class PaymentMethodMeta { - public $exp_month; + public $exp_month; - public $exp_year; + public $exp_year; - public $brand; + public $brand; - public $last4; + public $last4; - public $type; -} \ No newline at end of file + public $type; +} diff --git a/app/DataMapper/PaymentTransaction.php b/app/DataMapper/PaymentTransaction.php index 358cd0f7b4c4..dd4b9645d507 100644 --- a/app/DataMapper/PaymentTransaction.php +++ b/app/DataMapper/PaymentTransaction.php @@ -13,17 +13,15 @@ namespace App\DataMapper; class PaymentTransaction { + public $transaction_id; - public $transaction_id; + public $gateway_response; - public $gateway_response; + public $account_gateway_id; - public $account_gateway_id; + public $type_id; - public $type_id; + public $status; // prepayment|payment|response|completed - public $status; // prepayment|payment|response|completed - - public $invoices; - -} \ No newline at end of file + public $invoices; +} diff --git a/app/Events/Client/ClientWasArchived.php b/app/Events/Client/ClientWasArchived.php index d49dffddf211..2d675766f8d7 100644 --- a/app/Events/Client/ClientWasArchived.php +++ b/app/Events/Client/ClientWasArchived.php @@ -19,6 +19,7 @@ use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; + /** * Class ClientWasArchived. */ diff --git a/app/Events/Contact/ContactLoggedIn.php b/app/Events/Contact/ContactLoggedIn.php index de677dfcbb4a..7b7082a8c7c1 100644 --- a/app/Events/Contact/ContactLoggedIn.php +++ b/app/Events/Contact/ContactLoggedIn.php @@ -40,9 +40,7 @@ class ContactLoggedIn */ public function __construct(ClientContact $client_contact) { - $this->client_contact = $client_contact; - } /** diff --git a/app/Events/Expense/ExpenseWasArchived.php b/app/Events/Expense/ExpenseWasArchived.php index 22f9f895c7e3..26b86c7c1b06 100644 --- a/app/Events/Expense/ExpenseWasArchived.php +++ b/app/Events/Expense/ExpenseWasArchived.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class ExpenseWasArchived. */ -class ExpenseWasArchived +class ExpenseWasArchived { use SerializesModels; diff --git a/app/Events/Expense/ExpenseWasCreated.php b/app/Events/Expense/ExpenseWasCreated.php index 4ac48a3355f7..495a9701f47d 100644 --- a/app/Events/Expense/ExpenseWasCreated.php +++ b/app/Events/Expense/ExpenseWasCreated.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class ExpenseWasCreated. */ -class ExpenseWasCreated +class ExpenseWasCreated { use SerializesModels; diff --git a/app/Events/Expense/ExpenseWasRestored.php b/app/Events/Expense/ExpenseWasRestored.php index be451031de58..39e057f65010 100644 --- a/app/Events/Expense/ExpenseWasRestored.php +++ b/app/Events/Expense/ExpenseWasRestored.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class ExpenseWasRestored. */ -class ExpenseWasRestored +class ExpenseWasRestored { use SerializesModels; diff --git a/app/Events/Expense/ExpenseWasUpdated.php b/app/Events/Expense/ExpenseWasUpdated.php index 4754a634e422..bf57048f6ae1 100644 --- a/app/Events/Expense/ExpenseWasUpdated.php +++ b/app/Events/Expense/ExpenseWasUpdated.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class ExpenseWasUpdated. */ -class ExpenseWasUpdated +class ExpenseWasUpdated { use SerializesModels; diff --git a/app/Events/Invoice/InvoiceWasArchived.php b/app/Events/Invoice/InvoiceWasArchived.php index befa600bf373..15c52e8a9cf2 100644 --- a/app/Events/Invoice/InvoiceWasArchived.php +++ b/app/Events/Invoice/InvoiceWasArchived.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class InvoiceWasArchived. */ -class InvoiceWasArchived +class InvoiceWasArchived { use SerializesModels; diff --git a/app/Events/Invoice/InvoiceWasCreated.php b/app/Events/Invoice/InvoiceWasCreated.php index 07b560b7aa37..f2eeb94a96dd 100644 --- a/app/Events/Invoice/InvoiceWasCreated.php +++ b/app/Events/Invoice/InvoiceWasCreated.php @@ -18,7 +18,7 @@ use Illuminate\Queue\SerializesModels; /** * Class InvoiceWasCreated. */ -class InvoiceWasCreated +class InvoiceWasCreated { use SerializesModels; diff --git a/app/Events/Invoice/InvoiceWasDeleted.php b/app/Events/Invoice/InvoiceWasDeleted.php index db43b1e3bef5..b9d3b33fbf49 100644 --- a/app/Events/Invoice/InvoiceWasDeleted.php +++ b/app/Events/Invoice/InvoiceWasDeleted.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class InvoiceWasDeleted. */ -class InvoiceWasDeleted +class InvoiceWasDeleted { use SerializesModels; diff --git a/app/Events/Invoice/InvoiceWasEmailed.php b/app/Events/Invoice/InvoiceWasEmailed.php index 86c1ab7610c4..c6344db9a907 100644 --- a/app/Events/Invoice/InvoiceWasEmailed.php +++ b/app/Events/Invoice/InvoiceWasEmailed.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class InvoiceWasEmailed. */ -class InvoiceWasEmailed +class InvoiceWasEmailed { use SerializesModels; diff --git a/app/Events/Invoice/InvoiceWasEmailedAndFailed.php b/app/Events/Invoice/InvoiceWasEmailedAndFailed.php index f8a814ff1bcf..da729b2058c6 100644 --- a/app/Events/Invoice/InvoiceWasEmailedAndFailed.php +++ b/app/Events/Invoice/InvoiceWasEmailedAndFailed.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class InvoiceWasEmailedAndFailed. */ -class InvoiceWasEmailedAndFailed +class InvoiceWasEmailedAndFailed { use SerializesModels; diff --git a/app/Events/Invoice/InvoiceWasMarkedSent.php b/app/Events/Invoice/InvoiceWasMarkedSent.php index 5042c8a600bf..ba8e457ed288 100644 --- a/app/Events/Invoice/InvoiceWasMarkedSent.php +++ b/app/Events/Invoice/InvoiceWasMarkedSent.php @@ -18,7 +18,7 @@ use Illuminate\Queue\SerializesModels; /** * Class InvoiceWasMarkedSent. */ -class InvoiceWasMarkedSent +class InvoiceWasMarkedSent { use SerializesModels; diff --git a/app/Events/Invoice/InvoiceWasPaid.php b/app/Events/Invoice/InvoiceWasPaid.php index dfdd115e69a3..64d52c8ec461 100644 --- a/app/Events/Invoice/InvoiceWasPaid.php +++ b/app/Events/Invoice/InvoiceWasPaid.php @@ -18,7 +18,7 @@ use Illuminate\Queue\SerializesModels; /** * Class InvoiceWasPaid. */ -class InvoiceWasPaid +class InvoiceWasPaid { use SerializesModels; diff --git a/app/Events/Invoice/InvoiceWasUpdated.php b/app/Events/Invoice/InvoiceWasUpdated.php index 4351c9eb088b..dd95c7a1c1f8 100644 --- a/app/Events/Invoice/InvoiceWasUpdated.php +++ b/app/Events/Invoice/InvoiceWasUpdated.php @@ -11,13 +11,14 @@ namespace App\Events\Invoice; +use App\Models\Company; use App\Models\Invoice; use Illuminate\Queue\SerializesModels; /** * Class InvoiceWasUpdated. */ -class InvoiceWasUpdated +class InvoiceWasUpdated { use SerializesModels; @@ -26,13 +27,15 @@ class InvoiceWasUpdated */ public $invoice; + public $company; /** * Create a new event instance. * * @param Invoice $invoice */ - public function __construct(Invoice $invoice) + public function __construct(Invoice $invoice, Company $company) { $this->invoice = $invoice; + $this->company = $company; } } diff --git a/app/Events/Payment/PaymentCompleted.php b/app/Events/Payment/PaymentCompleted.php index 8bb579c0ee5f..d9a1701e5871 100644 --- a/app/Events/Payment/PaymentCompleted.php +++ b/app/Events/Payment/PaymentCompleted.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class PaymentCompleted. */ -class PaymentCompleted +class PaymentCompleted { use SerializesModels; diff --git a/app/Events/Payment/PaymentFailed.php b/app/Events/Payment/PaymentFailed.php index fed62ca500b5..7c0e4ed62b56 100644 --- a/app/Events/Payment/PaymentFailed.php +++ b/app/Events/Payment/PaymentFailed.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class PaymentFailed. */ -class PaymentFailed +class PaymentFailed { use SerializesModels; diff --git a/app/Events/Payment/PaymentWasArchived.php b/app/Events/Payment/PaymentWasArchived.php index 5064ddf14427..c5626f322e90 100644 --- a/app/Events/Payment/PaymentWasArchived.php +++ b/app/Events/Payment/PaymentWasArchived.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class PaymentWasArchived. */ -class PaymentWasArchived +class PaymentWasArchived { use SerializesModels; diff --git a/app/Events/Payment/PaymentWasCreated.php b/app/Events/Payment/PaymentWasCreated.php index e5496802d16c..fc08999c7cb1 100644 --- a/app/Events/Payment/PaymentWasCreated.php +++ b/app/Events/Payment/PaymentWasCreated.php @@ -18,7 +18,7 @@ use Illuminate\Queue\SerializesModels; /** * Class PaymentWasCreated. */ -class PaymentWasCreated +class PaymentWasCreated { use SerializesModels; diff --git a/app/Events/Payment/PaymentWasDeleted.php b/app/Events/Payment/PaymentWasDeleted.php index 073e77ff1c69..8eff5c59c792 100644 --- a/app/Events/Payment/PaymentWasDeleted.php +++ b/app/Events/Payment/PaymentWasDeleted.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class PaymentWasDeleted. */ -class PaymentWasDeleted +class PaymentWasDeleted { use SerializesModels; diff --git a/app/Events/Payment/PaymentWasRefunded.php b/app/Events/Payment/PaymentWasRefunded.php index d2109f6609d3..21f6f9d24e98 100644 --- a/app/Events/Payment/PaymentWasRefunded.php +++ b/app/Events/Payment/PaymentWasRefunded.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class PaymentWasRefunded. */ -class PaymentWasRefunded +class PaymentWasRefunded { use SerializesModels; diff --git a/app/Events/Payment/PaymentWasRestored.php b/app/Events/Payment/PaymentWasRestored.php index 72dfdbe74c6d..feed1a9f5fba 100644 --- a/app/Events/Payment/PaymentWasRestored.php +++ b/app/Events/Payment/PaymentWasRestored.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class PaymentWasRestored. */ -class PaymentWasRestored +class PaymentWasRestored { use SerializesModels; diff --git a/app/Events/Payment/PaymentWasVoided.php b/app/Events/Payment/PaymentWasVoided.php index e95957968de4..7d5cfde1083a 100644 --- a/app/Events/Payment/PaymentWasVoided.php +++ b/app/Events/Payment/PaymentWasVoided.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class PaymentWasVoided. */ -class PaymentWasVoided +class PaymentWasVoided { use SerializesModels; diff --git a/app/Events/Product/ProductWasDeleted.php b/app/Events/Product/ProductWasDeleted.php index bceee545bc0b..aed262ceab5c 100644 --- a/app/Events/Product/ProductWasDeleted.php +++ b/app/Events/Product/ProductWasDeleted.php @@ -14,7 +14,7 @@ namespace App\Events\Product; use App\Models\Product; use Illuminate\Queue\SerializesModels; -class ProductWasDeleted +class ProductWasDeleted { use SerializesModels; diff --git a/app/Events/Quote/QuoteWasCreated.php b/app/Events/Quote/QuoteWasCreated.php index 31a77b152fdc..58f66a8542d3 100644 --- a/app/Events/Quote/QuoteWasCreated.php +++ b/app/Events/Quote/QuoteWasCreated.php @@ -16,7 +16,7 @@ use Illuminate\Queue\SerializesModels; /** * Class QuoteWasCreated. */ -class QuoteWasCreated +class QuoteWasCreated { use SerializesModels; public $quote; diff --git a/app/Events/Quote/QuoteWasDeleted.php b/app/Events/Quote/QuoteWasDeleted.php index 4f43ff091783..dad2f051566c 100644 --- a/app/Events/Quote/QuoteWasDeleted.php +++ b/app/Events/Quote/QuoteWasDeleted.php @@ -16,7 +16,7 @@ use Illuminate\Queue\SerializesModels; /** * Class QuoteWasDeleted. */ -class QuoteWasDeleted +class QuoteWasDeleted { use SerializesModels; public $quote; diff --git a/app/Events/Quote/QuoteWasEmailed.php b/app/Events/Quote/QuoteWasEmailed.php index 5431a79afac5..de5cf8d566b8 100644 --- a/app/Events/Quote/QuoteWasEmailed.php +++ b/app/Events/Quote/QuoteWasEmailed.php @@ -16,7 +16,7 @@ use Illuminate\Queue\SerializesModels; /** * Class QuoteWasEmailed. */ -class QuoteWasEmailed +class QuoteWasEmailed { use SerializesModels; public $quote; diff --git a/app/Events/Quote/QuoteWasRestored.php b/app/Events/Quote/QuoteWasRestored.php index 40bf4fd90bae..9e001d573deb 100644 --- a/app/Events/Quote/QuoteWasRestored.php +++ b/app/Events/Quote/QuoteWasRestored.php @@ -16,7 +16,7 @@ use Illuminate\Queue\SerializesModels; /** * Class QuoteWasRestored. */ -class QuoteWasRestored +class QuoteWasRestored { use SerializesModels; public $quote; diff --git a/app/Events/Task/TaskWasArchived.php b/app/Events/Task/TaskWasArchived.php index f8c3ae520233..456a351f278b 100644 --- a/app/Events/Task/TaskWasArchived.php +++ b/app/Events/Task/TaskWasArchived.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class TaskWasArchived. */ -class TaskWasArchived +class TaskWasArchived { use SerializesModels; diff --git a/app/Events/Task/TaskWasCreated.php b/app/Events/Task/TaskWasCreated.php index c5fc957fb590..e519e9d37263 100644 --- a/app/Events/Task/TaskWasCreated.php +++ b/app/Events/Task/TaskWasCreated.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class TaskWasCreated. */ -class TaskWasCreated +class TaskWasCreated { use SerializesModels; diff --git a/app/Events/Task/TaskWasDeleted.php b/app/Events/Task/TaskWasDeleted.php index c6f9f0f65954..135a0ab305d9 100644 --- a/app/Events/Task/TaskWasDeleted.php +++ b/app/Events/Task/TaskWasDeleted.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class TaskWasDeleted. */ -class TaskWasDeleted +class TaskWasDeleted { use SerializesModels; diff --git a/app/Events/Task/TaskWasRestored.php b/app/Events/Task/TaskWasRestored.php index baef317486fb..09b065ffdf13 100644 --- a/app/Events/Task/TaskWasRestored.php +++ b/app/Events/Task/TaskWasRestored.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class TaskWasRestored. */ -class TaskWasRestored +class TaskWasRestored { use SerializesModels; diff --git a/app/Events/Task/TaskWasUpdated.php b/app/Events/Task/TaskWasUpdated.php index d36d38d0bac7..fe305a22b837 100644 --- a/app/Events/Task/TaskWasUpdated.php +++ b/app/Events/Task/TaskWasUpdated.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class TaskWasUpdated. */ -class TaskWasUpdated +class TaskWasUpdated { use SerializesModels; diff --git a/app/Events/User/UserLoggedIn.php b/app/Events/User/UserLoggedIn.php index 462f37dba3c3..ffe70e9b3a36 100644 --- a/app/Events/User/UserLoggedIn.php +++ b/app/Events/User/UserLoggedIn.php @@ -39,9 +39,7 @@ class UserLoggedIn */ public function __construct($user) { - $this->user = $user; - } /** diff --git a/app/Events/Vendor/VendorWasArchived.php b/app/Events/Vendor/VendorWasArchived.php index d416c203e0c0..16858d4ccabd 100644 --- a/app/Events/Vendor/VendorWasArchived.php +++ b/app/Events/Vendor/VendorWasArchived.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class VendorWasArchived. */ -class VendorWasArchived +class VendorWasArchived { // vendor use SerializesModels; diff --git a/app/Events/Vendor/VendorWasCreated.php b/app/Events/Vendor/VendorWasCreated.php index 967cf32b54ba..287913969d49 100644 --- a/app/Events/Vendor/VendorWasCreated.php +++ b/app/Events/Vendor/VendorWasCreated.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class VendorWasCreated. */ -class VendorWasCreated +class VendorWasCreated { use SerializesModels; diff --git a/app/Events/Vendor/VendorWasDeleted.php b/app/Events/Vendor/VendorWasDeleted.php index ec43a0d359cc..7f8cd99a8035 100644 --- a/app/Events/Vendor/VendorWasDeleted.php +++ b/app/Events/Vendor/VendorWasDeleted.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class VendorWasDeleted. */ -class VendorWasDeleted +class VendorWasDeleted { use SerializesModels; diff --git a/app/Events/Vendor/VendorWasRestored.php b/app/Events/Vendor/VendorWasRestored.php index 9a355cbcbef5..6a7b8d22e769 100644 --- a/app/Events/Vendor/VendorWasRestored.php +++ b/app/Events/Vendor/VendorWasRestored.php @@ -17,7 +17,7 @@ use Illuminate\Queue\SerializesModels; /** * Class VendorWasRestored. */ -class VendorWasRestored +class VendorWasRestored { use SerializesModels; diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index 2779526c0eb5..eb0c9533d68c 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -70,47 +70,32 @@ class Handler extends ExceptionHandler public function render($request, Exception $exception) { - - if ($exception instanceof ModelNotFoundException && $request->expectsJson()) - { - return response()->json(['message'=>'Record not found'],400); - } - else if($exception instanceof ThrottleRequestsException && $request->expectsJson()) - { - return response()->json(['message'=>'Too many requests'],429); - } - else if($exception instanceof FatalThrowableError && $request->expectsJson()) - { + if ($exception instanceof ModelNotFoundException && $request->expectsJson()) { + return response()->json(['message'=>'Record not found'], 400); + } elseif ($exception instanceof ThrottleRequestsException && $request->expectsJson()) { + return response()->json(['message'=>'Too many requests'], 429); + } elseif ($exception instanceof FatalThrowableError && $request->expectsJson()) { return response()->json(['message'=>'Fatal error'], 500); - } - else if($exception instanceof AuthorizationException) - { - return response()->json(['message'=>'You are not authorized to view or perform this action'],401); - } - else if ($exception instanceof \Illuminate\Session\TokenMismatchException) - { + } elseif ($exception instanceof AuthorizationException) { + return response()->json(['message'=>'You are not authorized to view or perform this action'], 401); + } elseif ($exception instanceof \Illuminate\Session\TokenMismatchException) { return redirect() ->back() ->withInput($request->except('password', 'password_confirmation', '_token')) ->with([ 'message' => ctrans('texts.token_expired'), 'message-type' => 'danger']); - } - else if ($exception instanceof NotFoundHttpException && $request->expectsJson()) { - return response()->json(['message'=>'Route does not exist'],404); - } - else if($exception instanceof MethodNotAllowedHttpException && $request->expectsJson()){ - return response()->json(['message'=>'Method not support for this route'],404); - } - else if ($exception instanceof ValidationException && $request->expectsJson()) { + } elseif ($exception instanceof NotFoundHttpException && $request->expectsJson()) { + return response()->json(['message'=>'Route does not exist'], 404); + } elseif ($exception instanceof MethodNotAllowedHttpException && $request->expectsJson()) { + return response()->json(['message'=>'Method not support for this route'], 404); + } elseif ($exception instanceof ValidationException && $request->expectsJson()) { return response()->json(['message' => 'The given data was invalid.', 'errors' => $exception->validator->getMessageBag()], 422); - } - else if ($exception instanceof RelationNotFoundException && $request->expectsJson()) { + } elseif ($exception instanceof RelationNotFoundException && $request->expectsJson()) { return response()->json(['message' => $exception->getMessage()], 400); } return parent::render($request, $exception); - } diff --git a/app/Factory/ClientContactFactory.php b/app/Factory/ClientContactFactory.php index 2eab3d90efa2..68089779227f 100644 --- a/app/Factory/ClientContactFactory.php +++ b/app/Factory/ClientContactFactory.php @@ -15,15 +15,15 @@ use App\Models\ClientContact; class ClientContactFactory { - public static function create(int $company_id, int $user_id) :ClientContact - { - $client_contact = new ClientContact; + public static function create(int $company_id, int $user_id) :ClientContact + { + $client_contact = new ClientContact; $client_contact->first_name = ""; $client_contact->user_id = $user_id; $client_contact->company_id = $company_id; $client_contact->contact_key = \Illuminate\Support\Str::random(40); $client_contact->id = 0; - return $client_contact; - } + return $client_contact; + } } diff --git a/app/Factory/ClientFactory.php b/app/Factory/ClientFactory.php index ba29f0729c46..fdc1fb746c99 100644 --- a/app/Factory/ClientFactory.php +++ b/app/Factory/ClientFactory.php @@ -17,24 +17,24 @@ use Illuminate\Support\Str; class ClientFactory { - public static function create(int $company_id, int $user_id) :Client - { - $client = new Client; - $client->company_id = $company_id; - $client->user_id = $user_id; - $client->name = ''; - $client->website = ''; - $client->private_notes = ''; - $client->balance = 0; - $client->paid_to_date = 0; - $client->country_id = 4; - $client->is_deleted = 0; - $client->client_hash = Str::random(40); - $client->settings = ClientSettings::defaults(); - - $client_contact = ClientContactFactory::create($company_id, $user_id); + public static function create(int $company_id, int $user_id) :Client + { + $client = new Client; + $client->company_id = $company_id; + $client->user_id = $user_id; + $client->name = ''; + $client->website = ''; + $client->private_notes = ''; + $client->balance = 0; + $client->paid_to_date = 0; + $client->country_id = 4; + $client->is_deleted = 0; + $client->client_hash = Str::random(40); + $client->settings = ClientSettings::defaults(); + + $client_contact = ClientContactFactory::create($company_id, $user_id); $client->contacts->add($client_contact); - return $client; - } + return $client; + } } diff --git a/app/Factory/CloneInvoiceFactory.php b/app/Factory/CloneInvoiceFactory.php index c6c46228b31b..4bd7b24ca628 100644 --- a/app/Factory/CloneInvoiceFactory.php +++ b/app/Factory/CloneInvoiceFactory.php @@ -15,20 +15,19 @@ use App\Models\Invoice; class CloneInvoiceFactory { - public static function create(Invoice $invoice, $user_id) : ?Invoice - { - $clone_invoice = $invoice->replicate(); - $clone_invoice->status_id = Invoice::STATUS_DRAFT; - $clone_invoice->number = NULL; - $clone_invoice->date = null; - $clone_invoice->due_date = null; - $clone_invoice->partial_due_date = null; - $clone_invoice->user_id = $user_id; - $clone_invoice->balance = $invoice->amount; - $clone_invoice->line_items = $invoice->line_items; - $clone_invoice->backup = null; - - return $clone_invoice; - } - -} \ No newline at end of file + public static function create(Invoice $invoice, $user_id) : ?Invoice + { + $clone_invoice = $invoice->replicate(); + $clone_invoice->status_id = Invoice::STATUS_DRAFT; + $clone_invoice->number = null; + $clone_invoice->date = null; + $clone_invoice->due_date = null; + $clone_invoice->partial_due_date = null; + $clone_invoice->user_id = $user_id; + $clone_invoice->balance = $invoice->amount; + $clone_invoice->line_items = $invoice->line_items; + $clone_invoice->backup = null; + + return $clone_invoice; + } +} diff --git a/app/Factory/CloneInvoiceToQuoteFactory.php b/app/Factory/CloneInvoiceToQuoteFactory.php index f92c3328f2cf..fe029540c95a 100644 --- a/app/Factory/CloneInvoiceToQuoteFactory.php +++ b/app/Factory/CloneInvoiceToQuoteFactory.php @@ -16,45 +16,43 @@ use App\Models\Quote; class CloneInvoiceToQuoteFactory { - public static function create(Invoice $invoice, $user_id) : ?Quote - { + public static function create(Invoice $invoice, $user_id) : ?Quote + { + $quote = new Quote(); + $quote->client_id = $invoice->client_id; + $quote->user_id = $user_id; + $quote->company_id = $invoice->company_id; + $quote->discount = $invoice->discount; + $quote->is_amount_discount = $invoice->is_amount_discount; + $quote->po_number = $invoice->po_number; + $quote->is_deleted = false; + $quote->backup = null; + $quote->footer = $invoice->footer; + $quote->public_notes = $invoice->public_notes; + $quote->private_notes = $invoice->private_notes; + $quote->terms = $invoice->terms; + $quote->tax_name1 = $invoice->tax_name1; + $quote->tax_rate1 = $invoice->tax_rate1; + $quote->tax_name2 = $invoice->tax_name2; + $quote->tax_rate2 = $invoice->tax_rate2; + $quote->custom_value1 = $invoice->custom_value1; + $quote->custom_value2 = $invoice->custom_value2; + $quote->custom_value3 = $invoice->custom_value3; + $quote->custom_value4 = $invoice->custom_value4; + $quote->amount = $invoice->amount; + $quote->balance = $invoice->balance; + $quote->partial = $invoice->partial; + $quote->partial_due_date = $invoice->partial_due_date; + $quote->last_viewed = $invoice->last_viewed; - $quote = new Quote(); - $quote->client_id = $invoice->client_id; - $quote->user_id = $user_id; - $quote->company_id = $invoice->company_id; - $quote->discount = $invoice->discount; - $quote->is_amount_discount = $invoice->is_amount_discount; - $quote->po_number = $invoice->po_number; - $quote->is_deleted = false; - $quote->backup = null; - $quote->footer = $invoice->footer; - $quote->public_notes = $invoice->public_notes; - $quote->private_notes = $invoice->private_notes; - $quote->terms = $invoice->terms; - $quote->tax_name1 = $invoice->tax_name1; - $quote->tax_rate1 = $invoice->tax_rate1; - $quote->tax_name2 = $invoice->tax_name2; - $quote->tax_rate2 = $invoice->tax_rate2; - $quote->custom_value1 = $invoice->custom_value1; - $quote->custom_value2 = $invoice->custom_value2; - $quote->custom_value3 = $invoice->custom_value3; - $quote->custom_value4 = $invoice->custom_value4; - $quote->amount = $invoice->amount; - $quote->balance = $invoice->balance; - $quote->partial = $invoice->partial; - $quote->partial_due_date = $invoice->partial_due_date; - $quote->last_viewed = $invoice->last_viewed; + $quote->status_id = Quote::STATUS_DRAFT; + $quote->number = ''; + $quote->date = null; + $quote->due_date = null; + $quote->partial_due_date = null; + $quote->balance = $invoice->amount; + $quote->line_items = $invoice->line_items; - $quote->status_id = Quote::STATUS_DRAFT; - $quote->number = ''; - $quote->date = null; - $quote->due_date = null; - $quote->partial_due_date = null; - $quote->balance = $invoice->amount; - $quote->line_items = $invoice->line_items; - - return $quote; - } - -} + return $quote; + } +} diff --git a/app/Factory/CompanyFactory.php b/app/Factory/CompanyFactory.php index 17692af4e071..0503c215fe4d 100644 --- a/app/Factory/CompanyFactory.php +++ b/app/Factory/CompanyFactory.php @@ -17,14 +17,14 @@ use App\Utils\Traits\MakesHash; class CompanyFactory { - use MakesHash; + use MakesHash; /** * @param int $account_id * @return Company */ public function create(int $account_id) :Company - { + { $company = new Company; // $company->name = ''; $company->account_id = $account_id; diff --git a/app/Factory/CompanyGatewayFactory.php b/app/Factory/CompanyGatewayFactory.php index f593b037e238..0462c897aa87 100644 --- a/app/Factory/CompanyGatewayFactory.php +++ b/app/Factory/CompanyGatewayFactory.php @@ -15,15 +15,12 @@ use App\Models\CompanyGateway; class CompanyGatewayFactory { - - public static function create(int $company_id, int $user_id) :CompanyGateway - { - + public static function create(int $company_id, int $user_id) :CompanyGateway + { $company_gateway = new CompanyGateway; $company_gateway->company_id = $company_id; $company_gateway->user_id = $user_id; return $company_gateway; - } -} \ No newline at end of file +} diff --git a/app/Factory/CompanyLedgerFactory.php b/app/Factory/CompanyLedgerFactory.php index c884c6a70b82..e92e0de1bd35 100644 --- a/app/Factory/CompanyLedgerFactory.php +++ b/app/Factory/CompanyLedgerFactory.php @@ -15,17 +15,17 @@ use App\Models\CompanyLedger; class CompanyLedgerFactory { - public static function create(int $company_id, int $user_id) :CompanyLedger - { - $company_ledger = new CompanyLedger; - $company_ledger->company_id = $company_id; - $company_ledger->user_id = $user_id; - $company_ledger->adjustment = 0; - $company_ledger->balance = 0; - $company_ledger->notes = ''; - $company_ledger->hash = ''; - $company_ledger->client_id = 0; + public static function create(int $company_id, int $user_id) :CompanyLedger + { + $company_ledger = new CompanyLedger; + $company_ledger->company_id = $company_id; + $company_ledger->user_id = $user_id; + $company_ledger->adjustment = 0; + $company_ledger->balance = 0; + $company_ledger->notes = ''; + $company_ledger->hash = ''; + $company_ledger->client_id = 0; - return $company_ledger; - } + return $company_ledger; + } } diff --git a/app/Factory/CompanyUserFactory.php b/app/Factory/CompanyUserFactory.php index c80e1aa61a47..6f94eb613036 100644 --- a/app/Factory/CompanyUserFactory.php +++ b/app/Factory/CompanyUserFactory.php @@ -15,16 +15,13 @@ use App\Models\CompanyUser; class CompanyUserFactory { - - public static function create($user_id, $company_id, $account_id) :CompanyUser - { - + public static function create($user_id, $company_id, $account_id) :CompanyUser + { $company_user = new CompanyUser; $company_user->user_id = $user_id; $company_user->company_id = $company_id; $company_user->account_id = $account_id; return $company_user; - } -} \ No newline at end of file +} diff --git a/app/Factory/GroupSettingFactory.php b/app/Factory/GroupSettingFactory.php index b065d8535388..9c7d4b52e235 100644 --- a/app/Factory/GroupSettingFactory.php +++ b/app/Factory/GroupSettingFactory.php @@ -15,10 +15,8 @@ use App\Models\GroupSetting; class GroupSettingFactory { - - public static function create(int $company_id, int $user_id) :GroupSetting - { - + public static function create(int $company_id, int $user_id) :GroupSetting + { $gs = new GroupSetting; $gs->name = ''; $gs->company_id = $company_id; @@ -26,6 +24,5 @@ class GroupSettingFactory $gs->settings = '{}'; return $gs; - } -} \ No newline at end of file +} diff --git a/app/Factory/InvoiceFactory.php b/app/Factory/InvoiceFactory.php index 28c8ac2a90cd..93f468e898f2 100644 --- a/app/Factory/InvoiceFactory.php +++ b/app/Factory/InvoiceFactory.php @@ -18,39 +18,39 @@ use Illuminate\Support\Facades\Log; class InvoiceFactory { - public static function create(int $company_id, int $user_id) :Invoice - { - $invoice = new Invoice(); - $invoice->status_id = Invoice::STATUS_DRAFT; - $invoice->number = null; - $invoice->discount = 0; - $invoice->is_amount_discount = true; - $invoice->po_number = ''; - $invoice->footer = ''; - $invoice->terms = ''; - $invoice->public_notes = ''; - $invoice->private_notes = ''; - $invoice->date = null; - $invoice->due_date = null; - $invoice->partial_due_date = null; - $invoice->is_deleted = false; - $invoice->line_items = json_encode([]); - $invoice->backup = json_encode([]); - $invoice->tax_name1 = ''; - $invoice->tax_rate1 = 0; - $invoice->tax_name2 = ''; - $invoice->tax_rate2 = 0; - $invoice->custom_value1 = 0; - $invoice->custom_value2 = 0; - $invoice->custom_value3 = 0; - $invoice->custom_value4 = 0; - $invoice->amount = 0; - $invoice->balance = 0; - $invoice->partial = 0; - $invoice->user_id = $user_id; - $invoice->company_id = $company_id; - $invoice->recurring_id = null; - - return $invoice; - } + public static function create(int $company_id, int $user_id) :Invoice + { + $invoice = new Invoice(); + $invoice->status_id = Invoice::STATUS_DRAFT; + $invoice->number = null; + $invoice->discount = 0; + $invoice->is_amount_discount = true; + $invoice->po_number = ''; + $invoice->footer = ''; + $invoice->terms = ''; + $invoice->public_notes = ''; + $invoice->private_notes = ''; + $invoice->date = null; + $invoice->due_date = null; + $invoice->partial_due_date = null; + $invoice->is_deleted = false; + $invoice->line_items = json_encode([]); + $invoice->backup = json_encode([]); + $invoice->tax_name1 = ''; + $invoice->tax_rate1 = 0; + $invoice->tax_name2 = ''; + $invoice->tax_rate2 = 0; + $invoice->custom_value1 = 0; + $invoice->custom_value2 = 0; + $invoice->custom_value3 = 0; + $invoice->custom_value4 = 0; + $invoice->amount = 0; + $invoice->balance = 0; + $invoice->partial = 0; + $invoice->user_id = $user_id; + $invoice->company_id = $company_id; + $invoice->recurring_id = null; + + return $invoice; + } } diff --git a/app/Factory/InvoiceInvitationFactory.php b/app/Factory/InvoiceInvitationFactory.php index 5860e366331c..b3b99db7b500 100644 --- a/app/Factory/InvoiceInvitationFactory.php +++ b/app/Factory/InvoiceInvitationFactory.php @@ -16,27 +16,23 @@ use Illuminate\Support\Str; class InvoiceInvitationFactory { + public static function create(int $company_id, int $user_id) :InvoiceInvitation + { + $ii = new InvoiceInvitation; + $ii->company_id = $company_id; + $ii->user_id = $user_id; + $ii->client_contact_id = null; + $ii->invoice_id = null; + $ii->key = Str::random(config('ninja.key_length')); + $ii->transaction_reference = null; + $ii->message_id = null; + $ii->email_error = ''; + $ii->signature_base64 = ''; + $ii->signature_date = null; + $ii->sent_date = null; + $ii->viewed_date = null; + $ii->opened_date = null; - public static function create(int $company_id, int $user_id) :InvoiceInvitation - { - $ii = new InvoiceInvitation; - $ii->company_id = $company_id; - $ii->user_id = $user_id; - $ii->client_contact_id = null; - $ii->invoice_id = null; - $ii->key = Str::random(config('ninja.key_length')); - $ii->transaction_reference = null; - $ii->message_id = null; - $ii->email_error = ''; - $ii->signature_base64 = ''; - $ii->signature_date = null; - $ii->sent_date = null; - $ii->viewed_date = null; - $ii->opened_date = null; - - return $ii; - } - + return $ii; + } } - - \ No newline at end of file diff --git a/app/Factory/InvoiceItemFactory.php b/app/Factory/InvoiceItemFactory.php index 80f5add9e58f..9848c8ba9e51 100644 --- a/app/Factory/InvoiceItemFactory.php +++ b/app/Factory/InvoiceItemFactory.php @@ -12,70 +12,67 @@ namespace App\Factory; use Illuminate\Support\Carbon; + //use Faker\Generator as Faker; class InvoiceItemFactory { - public static function create() :\stdClass - { - $item = new \stdClass; - $item->quantity = 0; - $item->cost = 0; - $item->product_key = ''; - $item->notes = ''; - $item->discount = 0; - $item->is_amount_discount = true; - $item->tax_name1 = ''; - $item->tax_rate1 = 0; - $item->tax_name2 = ''; - $item->tax_rate2 = 0; - $item->tax_name3 = ''; - $item->tax_rate3 = 0; - $item->sort_id = 0; - $item->line_total = 0; - $item->date = Carbon::now(); - $item->custom_value1 = NULL; - $item->custom_value2 = NULL; - $item->custom_value3 = NULL; - $item->custom_value4 = NULL; + public static function create() :\stdClass + { + $item = new \stdClass; + $item->quantity = 0; + $item->cost = 0; + $item->product_key = ''; + $item->notes = ''; + $item->discount = 0; + $item->is_amount_discount = true; + $item->tax_name1 = ''; + $item->tax_rate1 = 0; + $item->tax_name2 = ''; + $item->tax_rate2 = 0; + $item->tax_name3 = ''; + $item->tax_rate3 = 0; + $item->sort_id = 0; + $item->line_total = 0; + $item->date = Carbon::now(); + $item->custom_value1 = null; + $item->custom_value2 = null; + $item->custom_value3 = null; + $item->custom_value4 = null; - return $item; + return $item; + } - } + /** + * Generates an array of dummy data for invoice items + * @param int $items Number of line items to create + * @return array array of objects + */ + public static function generate(int $items = 1) :array + { + $faker = \Faker\Factory::create(); - /** - * Generates an array of dummy data for invoice items - * @param int $items Number of line items to create - * @return array array of objects - */ - public static function generate(int $items = 1) :array - { - $faker = \Faker\Factory::create(); - - $data = []; - - for($x=0; $x<$items; $x++) - { - - $item = self::create(); - $item->quantity = $faker->numberBetween(1,10); - $item->cost = $faker->randomFloat(2, 1, 1000); - $item->line_total = $item->quantity * $item->cost; - $item->is_amount_discount = true; - $item->discount = $faker->numberBetween(1,10); - $item->notes = $faker->realText(20); - $item->product_key = $faker->word(); - $item->custom_value1 = $faker->realText(10); - $item->custom_value2 = $faker->realText(10); - $item->custom_value3 = $faker->realText(10); - $item->custom_value4 = $faker->realText(10); - $item->tax_name1 = 'GST'; - $item->tax_rate1 = '10.00'; - - $data[] = $item; - } - - return $data; - } + $data = []; + for ($x=0; $x<$items; $x++) { + $item = self::create(); + $item->quantity = $faker->numberBetween(1, 10); + $item->cost = $faker->randomFloat(2, 1, 1000); + $item->line_total = $item->quantity * $item->cost; + $item->is_amount_discount = true; + $item->discount = $faker->numberBetween(1, 10); + $item->notes = $faker->realText(20); + $item->product_key = $faker->word(); + $item->custom_value1 = $faker->realText(10); + $item->custom_value2 = $faker->realText(10); + $item->custom_value3 = $faker->realText(10); + $item->custom_value4 = $faker->realText(10); + $item->tax_name1 = 'GST'; + $item->tax_rate1 = '10.00'; + + $data[] = $item; + } + + return $data; + } } diff --git a/app/Factory/InvoiceToRecurringInvoiceFactory.php b/app/Factory/InvoiceToRecurringInvoiceFactory.php index c70a5ae8716d..e21b7727f4b0 100644 --- a/app/Factory/InvoiceToRecurringInvoiceFactory.php +++ b/app/Factory/InvoiceToRecurringInvoiceFactory.php @@ -18,44 +18,42 @@ use App\Models\RecurringInvoice; class InvoiceToRecurringInvoiceFactory { + public static function create(Invoice $invoice) :RecurringInvoice + { + $recurring_invoice = new RecurringInvoice; - public static function create(Invoice $invoice) :RecurringInvoice - { - $recurring_invoice = new RecurringInvoice; - - $recurring_invoice->status_id = RecurringInvoice::STATUS_DRAFT; - $recurring_invoice->discount = $invoice->discount; - $recurring_invoice->number = ''; - $recurring_invoice->is_amount_discount = $invoice->is_amount_discount; - $recurring_invoice->po_number = $invoice->po_number; - $recurring_invoice->footer = $invoice->footer; - $recurring_invoice->terms = $invoice->terms; - $recurring_invoice->public_notes = $invoice->public_notes; - $recurring_invoice->private_notes = $invoice->private_notes; - $recurring_invoice->date = date_create()->format($invoice->client->date_format()); - $recurring_invoice->due_date = $invoice->due_date; //todo calculate based on terms - $recurring_invoice->is_deleted = $invoice->is_deleted; - $recurring_invoice->line_items = $invoice->line_items; - $recurring_invoice->tax_name1 = $invoice->tax_name1; - $recurring_invoice->tax_rate1 = $invoice->tax_rate1; - $recurring_invoice->tax_name2 = $invoice->tax_name2; - $recurring_invoice->tax_rate2 = $invoice->tax_rate2; - $recurring_invoice->custom_value1 = $invoice->custom_value1; - $recurring_invoice->custom_value2 = $invoice->custom_value2; - $recurring_invoice->custom_value3 = $invoice->custom_value3; - $recurring_invoice->custom_value4 = $invoice->custom_value4; - $recurring_invoice->amount = $invoice->amount; - $recurring_invoice->balance = $invoice->balance; - $recurring_invoice->user_id = $invoice->user_id; - $recurring_invoice->client_id = $invoice->client_id; - $recurring_invoice->company_id = $invoice->company_id; - $recurring_invoice->frequency_id = RecurringInvoice::FREQUENCY_MONTHLY; - $recurring_invoice->start_date = null; - $recurring_invoice->last_sent_date = null; - $recurring_invoice->next_send_date = null; - $recurring_invoice->remaining_cycles = 0; - - return $recurring_invoice; - } + $recurring_invoice->status_id = RecurringInvoice::STATUS_DRAFT; + $recurring_invoice->discount = $invoice->discount; + $recurring_invoice->number = ''; + $recurring_invoice->is_amount_discount = $invoice->is_amount_discount; + $recurring_invoice->po_number = $invoice->po_number; + $recurring_invoice->footer = $invoice->footer; + $recurring_invoice->terms = $invoice->terms; + $recurring_invoice->public_notes = $invoice->public_notes; + $recurring_invoice->private_notes = $invoice->private_notes; + $recurring_invoice->date = date_create()->format($invoice->client->date_format()); + $recurring_invoice->due_date = $invoice->due_date; //todo calculate based on terms + $recurring_invoice->is_deleted = $invoice->is_deleted; + $recurring_invoice->line_items = $invoice->line_items; + $recurring_invoice->tax_name1 = $invoice->tax_name1; + $recurring_invoice->tax_rate1 = $invoice->tax_rate1; + $recurring_invoice->tax_name2 = $invoice->tax_name2; + $recurring_invoice->tax_rate2 = $invoice->tax_rate2; + $recurring_invoice->custom_value1 = $invoice->custom_value1; + $recurring_invoice->custom_value2 = $invoice->custom_value2; + $recurring_invoice->custom_value3 = $invoice->custom_value3; + $recurring_invoice->custom_value4 = $invoice->custom_value4; + $recurring_invoice->amount = $invoice->amount; + $recurring_invoice->balance = $invoice->balance; + $recurring_invoice->user_id = $invoice->user_id; + $recurring_invoice->client_id = $invoice->client_id; + $recurring_invoice->company_id = $invoice->company_id; + $recurring_invoice->frequency_id = RecurringInvoice::FREQUENCY_MONTHLY; + $recurring_invoice->start_date = null; + $recurring_invoice->last_sent_date = null; + $recurring_invoice->next_send_date = null; + $recurring_invoice->remaining_cycles = 0; + return $recurring_invoice; + } } diff --git a/app/Factory/PaymentFactory.php b/app/Factory/PaymentFactory.php index d16715541baa..35fe2f8646dc 100644 --- a/app/Factory/PaymentFactory.php +++ b/app/Factory/PaymentFactory.php @@ -19,27 +19,24 @@ use Illuminate\Support\Facades\Log; class PaymentFactory { - public static function create(int $company_id, int $user_id) :Payment - { - $payment = new Payment; - - $payment->company_id = $company_id; - $payment->user_id = $user_id; - $payment->client_id = 0; - $payment->client_contact_id = null; - $payment->invitation_id = null; - $payment->company_gateway_id = null; - $payment->type_id = null; - $payment->is_deleted = false; - $payment->amount = 0; - $payment->date = Carbon::now()->format('Y-m-d'); - $payment->transaction_reference = null; - $payment->payer_id = null; - $payment->status_id = Payment::STATUS_PENDING; - - return $payment; - } + public static function create(int $company_id, int $user_id) :Payment + { + $payment = new Payment; + + $payment->company_id = $company_id; + $payment->user_id = $user_id; + $payment->client_id = 0; + $payment->client_contact_id = null; + $payment->invitation_id = null; + $payment->company_gateway_id = null; + $payment->type_id = null; + $payment->is_deleted = false; + $payment->amount = 0; + $payment->date = Carbon::now()->format('Y-m-d'); + $payment->transaction_reference = null; + $payment->payer_id = null; + $payment->status_id = Payment::STATUS_PENDING; + + return $payment; + } } - - - diff --git a/app/Factory/ProductFactory.php b/app/Factory/ProductFactory.php index e3708a096af4..bfe381fa121e 100644 --- a/app/Factory/ProductFactory.php +++ b/app/Factory/ProductFactory.php @@ -15,29 +15,27 @@ use App\Models\Product; class ProductFactory { - public static function create(int $company_id, int $user_id) :Product - { - $product = new Product; - $product->company_id = $company_id; - $product->user_id = $user_id; + public static function create(int $company_id, int $user_id) :Product + { + $product = new Product; + $product->company_id = $company_id; + $product->user_id = $user_id; - $product->product_key = ''; - $product->notes = ''; - $product->cost = 0; - $product->price = 0; - $product->quantity = 1; - $product->tax_name1 = ''; - $product->tax_rate1 = 0; - $product->tax_name2 = ''; - $product->tax_rate2 = 0; - $product->custom_value1 = ''; - $product->custom_value2 = ''; - $product->custom_value3 = ''; - $product->custom_value4 = ''; - $product->is_deleted = 0; + $product->product_key = ''; + $product->notes = ''; + $product->cost = 0; + $product->price = 0; + $product->quantity = 1; + $product->tax_name1 = ''; + $product->tax_rate1 = 0; + $product->tax_name2 = ''; + $product->tax_rate2 = 0; + $product->custom_value1 = ''; + $product->custom_value2 = ''; + $product->custom_value3 = ''; + $product->custom_value4 = ''; + $product->is_deleted = 0; - return $product; - } + return $product; + } } - - diff --git a/app/Factory/QuoteFactory.php b/app/Factory/QuoteFactory.php index a535b400dc3f..a2e3c74aa073 100644 --- a/app/Factory/QuoteFactory.php +++ b/app/Factory/QuoteFactory.php @@ -18,38 +18,38 @@ use Illuminate\Support\Facades\Log; class QuoteFactory { - public static function create(int $company_id, int $user_id) :Quote - { - $quote = new Quote(); - $quote->status_id = Quote::STATUS_DRAFT; - $quote->number = null; - $quote->discount = 0; - $quote->is_amount_discount = true; - $quote->po_number = ''; - $quote->footer = ''; - $quote->terms = ''; - $quote->public_notes = ''; - $quote->private_notes = ''; - $quote->date = null; - $quote->due_date = null; - $quote->partial_due_date = null; - $quote->is_deleted = false; - $quote->line_items = json_encode([]); - $quote->backup = json_encode([]); - $quote->tax_name1 = ''; - $quote->tax_rate1 = 0; - $quote->tax_name2 = ''; - $quote->tax_rate2 = 0; - $quote->custom_value1 = 0; - $quote->custom_value2 = 0; - $quote->custom_value3 = 0; - $quote->custom_value4 = 0; - $quote->amount = 0; - $quote->balance = 0; - $quote->partial = 0; - $quote->user_id = $user_id; - $quote->company_id = $company_id; - - return $quote; - } + public static function create(int $company_id, int $user_id) :Quote + { + $quote = new Quote(); + $quote->status_id = Quote::STATUS_DRAFT; + $quote->number = null; + $quote->discount = 0; + $quote->is_amount_discount = true; + $quote->po_number = ''; + $quote->footer = ''; + $quote->terms = ''; + $quote->public_notes = ''; + $quote->private_notes = ''; + $quote->date = null; + $quote->due_date = null; + $quote->partial_due_date = null; + $quote->is_deleted = false; + $quote->line_items = json_encode([]); + $quote->backup = json_encode([]); + $quote->tax_name1 = ''; + $quote->tax_rate1 = 0; + $quote->tax_name2 = ''; + $quote->tax_rate2 = 0; + $quote->custom_value1 = 0; + $quote->custom_value2 = 0; + $quote->custom_value3 = 0; + $quote->custom_value4 = 0; + $quote->amount = 0; + $quote->balance = 0; + $quote->partial = 0; + $quote->user_id = $user_id; + $quote->company_id = $company_id; + + return $quote; + } } diff --git a/app/Factory/QuoteInvitationFactory.php b/app/Factory/QuoteInvitationFactory.php index bad3e31da873..2553cfb5bdf1 100644 --- a/app/Factory/QuoteInvitationFactory.php +++ b/app/Factory/QuoteInvitationFactory.php @@ -16,27 +16,23 @@ use Illuminate\Support\Str; class QuoteInvitationFactory { + public static function create(int $company_id, int $user_id) :QuoteInvitation + { + $qi = new QuoteInvitation; + $qi->company_id = $company_id; + $qi->user_id = $user_id; + $qi->client_contact_id = null; + $qi->quote_id = null; + $qi->key = Str::random(config('ninja.key_length')); + $qi->transaction_reference = null; + $qi->message_id = null; + $qi->email_error = ''; + $qi->signature_base64 = ''; + $qi->signature_date = null; + $qi->sent_date = null; + $qi->viewed_date = null; + $qi->opened_date = null; - public static function create(int $company_id, int $user_id) :QuoteInvitation - { - $qi = new QuoteInvitation; - $qi->company_id = $company_id; - $qi->user_id = $user_id; - $qi->client_contact_id = null; - $qi->quote_id = null; - $qi->key = Str::random(config('ninja.key_length')); - $qi->transaction_reference = null; - $qi->message_id = null; - $qi->email_error = ''; - $qi->signature_base64 = ''; - $qi->signature_date = null; - $qi->sent_date = null; - $qi->viewed_date = null; - $qi->opened_date = null; - - return $qi; - } - + return $qi; + } } - - \ No newline at end of file diff --git a/app/Factory/RecurringInvoiceFactory.php b/app/Factory/RecurringInvoiceFactory.php index 9f98b936b1e0..40a89e925ab8 100644 --- a/app/Factory/RecurringInvoiceFactory.php +++ b/app/Factory/RecurringInvoiceFactory.php @@ -17,44 +17,43 @@ use App\Models\RecurringInvoice; class RecurringInvoiceFactory { - public static function create(int $company_id, int $user_id) :RecurringInvoice - { - $invoice = new RecurringInvoice(); - $invoice->status_id = RecurringInvoice::STATUS_DRAFT; - $invoice->discount = 0; - $invoice->is_amount_discount = true; - $invoice->po_number = ''; - $invoice->number = ''; - $invoice->footer = ''; - $invoice->terms = ''; - $invoice->public_notes = ''; - $invoice->private_notes = ''; - $invoice->date = null; - $invoice->due_date = null; - $invoice->partial_due_date = null; - $invoice->is_deleted = false; - $invoice->line_items = json_encode([]); - $invoice->backup = json_encode([]); - $invoice->tax_name1 = ''; - $invoice->tax_rate1 = 0; - $invoice->tax_name2 = ''; - $invoice->tax_rate2 = 0; - $invoice->custom_value1 = 0; - $invoice->custom_value2 = 0; - $invoice->custom_value3 = 0; - $invoice->custom_value4 = 0; - $invoice->amount = 0; - $invoice->balance = 0; - $invoice->partial = 0; - $invoice->user_id = $user_id; - $invoice->company_id = $company_id; - $invoice->frequency_id = RecurringInvoice::FREQUENCY_MONTHLY; - $invoice->start_date = null; - $invoice->last_sent_date = null; - $invoice->next_send_date = null; - $invoice->remaining_cycles = 0; - - return $invoice; - } + public static function create(int $company_id, int $user_id) :RecurringInvoice + { + $invoice = new RecurringInvoice(); + $invoice->status_id = RecurringInvoice::STATUS_DRAFT; + $invoice->discount = 0; + $invoice->is_amount_discount = true; + $invoice->po_number = ''; + $invoice->number = ''; + $invoice->footer = ''; + $invoice->terms = ''; + $invoice->public_notes = ''; + $invoice->private_notes = ''; + $invoice->date = null; + $invoice->due_date = null; + $invoice->partial_due_date = null; + $invoice->is_deleted = false; + $invoice->line_items = json_encode([]); + $invoice->backup = json_encode([]); + $invoice->tax_name1 = ''; + $invoice->tax_rate1 = 0; + $invoice->tax_name2 = ''; + $invoice->tax_rate2 = 0; + $invoice->custom_value1 = 0; + $invoice->custom_value2 = 0; + $invoice->custom_value3 = 0; + $invoice->custom_value4 = 0; + $invoice->amount = 0; + $invoice->balance = 0; + $invoice->partial = 0; + $invoice->user_id = $user_id; + $invoice->company_id = $company_id; + $invoice->frequency_id = RecurringInvoice::FREQUENCY_MONTHLY; + $invoice->start_date = null; + $invoice->last_sent_date = null; + $invoice->next_send_date = null; + $invoice->remaining_cycles = 0; + return $invoice; + } } diff --git a/app/Factory/RecurringInvoiceToInvoiceFactory.php b/app/Factory/RecurringInvoiceToInvoiceFactory.php index f987a57b7110..62c8f1666cf6 100644 --- a/app/Factory/RecurringInvoiceToInvoiceFactory.php +++ b/app/Factory/RecurringInvoiceToInvoiceFactory.php @@ -18,38 +18,36 @@ use App\Models\RecurringInvoice; class recurring_invoiceToInvoiceFactory { - - public static function create(RecurringInvoice $recurring_invoice) :Invoice - { - $invoice = new Invoice(); - $invoice->status_id = Invoice::STATUS_DRAFT; - $invoice->discount = $recurring_invoice->discount; - $invoice->is_amount_discount = $recurring_invoice->is_amount_discount; - $invoice->po_number = $recurring_invoice->po_number; - $invoice->footer = $recurring_invoice->footer; - $invoice->terms = $recurring_invoice->terms; - $invoice->public_notes = $recurring_invoice->public_notes; - $invoice->private_notes = $recurring_invoice->private_notes; - $invoice->date = date_create()->format($client->date_format()); - $invoice->due_date = $recurring_invoice->due_date; //todo calculate based on terms - $invoice->is_deleted = $recurring_invoice->is_deleted; - $invoice->line_items = $recurring_invoice->line_items; - $invoice->backup = json_encode([]); - $invoice->tax_name1 = $recurring_invoice->tax_name1; - $invoice->tax_rate1 = $recurring_invoice->tax_rate1; - $invoice->tax_name2 = $recurring_invoice->tax_name2; - $invoice->tax_rate2 = $recurring_invoice->tax_rate2; - $invoice->custom_value1 = $recurring_invoice->custom_value1; - $invoice->custom_value2 = $recurring_invoice->custom_value2; - $invoice->custom_value3 = $recurring_invoice->custom_value3; - $invoice->custom_value4 = $recurring_invoice->custom_value4; - $invoice->amount = $recurring_invoice->amount; - $invoice->balance = $recurring_invoice->balance; - $invoice->user_id = $recurring_invoice->user_id; - $invoice->company_id = $recurring_invoice->company_id; - $invoice->recurring_id = $recurring_invoice->id; - - return $invoice; - } - + public static function create(RecurringInvoice $recurring_invoice) :Invoice + { + $invoice = new Invoice(); + $invoice->status_id = Invoice::STATUS_DRAFT; + $invoice->discount = $recurring_invoice->discount; + $invoice->is_amount_discount = $recurring_invoice->is_amount_discount; + $invoice->po_number = $recurring_invoice->po_number; + $invoice->footer = $recurring_invoice->footer; + $invoice->terms = $recurring_invoice->terms; + $invoice->public_notes = $recurring_invoice->public_notes; + $invoice->private_notes = $recurring_invoice->private_notes; + $invoice->date = date_create()->format($client->date_format()); + $invoice->due_date = $recurring_invoice->due_date; //todo calculate based on terms + $invoice->is_deleted = $recurring_invoice->is_deleted; + $invoice->line_items = $recurring_invoice->line_items; + $invoice->backup = json_encode([]); + $invoice->tax_name1 = $recurring_invoice->tax_name1; + $invoice->tax_rate1 = $recurring_invoice->tax_rate1; + $invoice->tax_name2 = $recurring_invoice->tax_name2; + $invoice->tax_rate2 = $recurring_invoice->tax_rate2; + $invoice->custom_value1 = $recurring_invoice->custom_value1; + $invoice->custom_value2 = $recurring_invoice->custom_value2; + $invoice->custom_value3 = $recurring_invoice->custom_value3; + $invoice->custom_value4 = $recurring_invoice->custom_value4; + $invoice->amount = $recurring_invoice->amount; + $invoice->balance = $recurring_invoice->balance; + $invoice->user_id = $recurring_invoice->user_id; + $invoice->company_id = $recurring_invoice->company_id; + $invoice->recurring_id = $recurring_invoice->id; + + return $invoice; + } } diff --git a/app/Factory/RecurringQuoteFactory.php b/app/Factory/RecurringQuoteFactory.php index 1da8b1c66912..c7e2b9902ac5 100644 --- a/app/Factory/RecurringQuoteFactory.php +++ b/app/Factory/RecurringQuoteFactory.php @@ -17,43 +17,42 @@ use App\Models\RecurringQuote; class RecurringQuoteFactory { - public static function create(int $company_id, int $user_id) :RecurringQuote - { - $quote = new RecurringQuote(); - $quote->status_id = RecurringQuote::STATUS_DRAFT; - $quote->discount = 0; - $quote->is_amount_discount = true; - $quote->po_number = ''; - $quote->footer = ''; - $quote->terms = ''; - $quote->public_notes = ''; - $quote->private_notes = ''; - $quote->date = null; - $quote->due_date = null; - $quote->partial_due_date = null; - $quote->is_deleted = false; - $quote->line_items = json_encode([]); - $quote->backup = json_encode([]); - $quote->tax_name1 = ''; - $quote->tax_rate1 = 0; - $quote->tax_name2 = ''; - $quote->tax_rate2 = 0; - $quote->custom_value1 = 0; - $quote->custom_value2 = 0; - $quote->custom_value3 = 0; - $quote->custom_value4 = 0; - $quote->amount = 0; - $quote->balance = 0; - $quote->partial = 0; - $quote->user_id = $user_id; - $quote->company_id = $company_id; - $quote->frequency_id = RecurringQuote::FREQUENCY_MONTHLY; - $quote->start_date = null; - $quote->last_sent_date = null; - $quote->next_send_date = null; - $quote->remaining_cycles = 0; - - return $quote; - } + public static function create(int $company_id, int $user_id) :RecurringQuote + { + $quote = new RecurringQuote(); + $quote->status_id = RecurringQuote::STATUS_DRAFT; + $quote->discount = 0; + $quote->is_amount_discount = true; + $quote->po_number = ''; + $quote->footer = ''; + $quote->terms = ''; + $quote->public_notes = ''; + $quote->private_notes = ''; + $quote->date = null; + $quote->due_date = null; + $quote->partial_due_date = null; + $quote->is_deleted = false; + $quote->line_items = json_encode([]); + $quote->backup = json_encode([]); + $quote->tax_name1 = ''; + $quote->tax_rate1 = 0; + $quote->tax_name2 = ''; + $quote->tax_rate2 = 0; + $quote->custom_value1 = 0; + $quote->custom_value2 = 0; + $quote->custom_value3 = 0; + $quote->custom_value4 = 0; + $quote->amount = 0; + $quote->balance = 0; + $quote->partial = 0; + $quote->user_id = $user_id; + $quote->company_id = $company_id; + $quote->frequency_id = RecurringQuote::FREQUENCY_MONTHLY; + $quote->start_date = null; + $quote->last_sent_date = null; + $quote->next_send_date = null; + $quote->remaining_cycles = 0; + return $quote; + } } diff --git a/app/Factory/TaxRateFactory.php b/app/Factory/TaxRateFactory.php index 21a629f020ee..df2038840463 100644 --- a/app/Factory/TaxRateFactory.php +++ b/app/Factory/TaxRateFactory.php @@ -15,17 +15,15 @@ use App\Models\TaxRate; class TaxRateFactory { + public static function create($company_id, $user_id) :TaxRate + { + $tax_rate = new TaxRate; - public static function create($company_id, $user_id) :TaxRate - { - $tax_rate = new TaxRate; + $tax_rate->name = ''; + $tax_rate->rate = ''; + $tax_rate->company_id = $company_id; + $tax_rate->user_id = $user_id; - $tax_rate->name = ''; - $tax_rate->rate = ''; - $tax_rate->company_id = $company_id; - $tax_rate->user_id = $user_id; - - return $tax_rate; - } - -} \ No newline at end of file + return $tax_rate; + } +} diff --git a/app/Factory/UserFactory.php b/app/Factory/UserFactory.php index 09ebee1395dd..03fa2101febd 100644 --- a/app/Factory/UserFactory.php +++ b/app/Factory/UserFactory.php @@ -15,19 +15,19 @@ use App\Models\User; class UserFactory { - public static function create() :User - { - $user = new User; + public static function create() :User + { + $user = new User; - $user->first_name = ''; - $user->last_name = ''; - $user->phone = ''; - $user->email = ''; - $user->last_login = now(); - $user->failed_logins = 0; - $user->signature = ''; - $user->theme_id = 0; - - return $user; - } -} \ No newline at end of file + $user->first_name = ''; + $user->last_name = ''; + $user->phone = ''; + $user->email = ''; + $user->last_login = now(); + $user->failed_logins = 0; + $user->signature = ''; + $user->theme_id = 0; + + return $user; + } +} diff --git a/app/Filters/ClientFilters.php b/app/Filters/ClientFilters.php index f00a07ee1a0d..2e8bd93c3287 100644 --- a/app/Filters/ClientFilters.php +++ b/app/Filters/ClientFilters.php @@ -25,9 +25,9 @@ class ClientFilters extends QueryFilters /** * Filter by balance - * - * @param string $balance - * @return Illuminate\Database\Query\Builder + * + * @param string $balance + * @return Illuminate\Database\Query\Builder */ public function balance(string $balance): Builder { @@ -38,7 +38,7 @@ class ClientFilters extends QueryFilters /** * Filter between balances - * + * * @param string balance * @return Illuminate\Database\Query\Builder */ @@ -51,41 +51,43 @@ class ClientFilters extends QueryFilters /** * Filter based on search text - * + * * @param string query filter * @return Illuminate\Database\Query\Builder * @deprecated - * + * */ public function filter(string $filter = '') : Builder { - if(strlen($filter) == 0) + if (strlen($filter) == 0) { return $this->builder; + } return $this->builder->where(function ($query) use ($filter) { - $query->where('clients.name', 'like', '%'.$filter.'%') + $query->where('clients.name', 'like', '%'.$filter.'%') ->orWhere('clients.id_number', 'like', '%'.$filter.'%') ->orWhere('client_contacts.first_name', 'like', '%'.$filter.'%') ->orWhere('client_contacts.last_name', 'like', '%'.$filter.'%') ->orWhere('client_contacts.email', 'like', '%'.$filter.'%') - ->orWhere('clients.custom_value1', 'like' , '%'.$filter.'%') - ->orWhere('clients.custom_value2', 'like' , '%'.$filter.'%') - ->orWhere('clients.custom_value3', 'like' , '%'.$filter.'%') - ->orWhere('clients.custom_value4', 'like' , '%'.$filter.'%'); - }); + ->orWhere('clients.custom_value1', 'like', '%'.$filter.'%') + ->orWhere('clients.custom_value2', 'like', '%'.$filter.'%') + ->orWhere('clients.custom_value3', 'like', '%'.$filter.'%') + ->orWhere('clients.custom_value4', 'like', '%'.$filter.'%'); + }); } /** * Filters the list based on the status * archived, active, deleted - * + * * @param string filter * @return Illuminate\Database\Query\Builder */ public function status(string $filter = '') : Builder { - if(strlen($filter) == 0) + if (strlen($filter) == 0) { return $this->builder; + } $table = 'clients'; $filters = explode(',', $filter); @@ -115,7 +117,7 @@ class ClientFilters extends QueryFilters /** * Sorts the list based on $sort - * + * * @param string sort formatted as column|asc * @return Illuminate\Database\Query\Builder */ @@ -127,7 +129,7 @@ class ClientFilters extends QueryFilters /** * Returns the base query - * + * * @param int company_id * @return Illuminate\Database\Query\Builder * @deprecated @@ -181,16 +183,14 @@ class ClientFilters extends QueryFilters /** * Filters the query by the users company ID - * + * * @param $company_id The company Id * @return Illuminate\Database\Query\Builder */ - public function entityFilter() + public function entityFilter() { //return $this->builder->whereCompanyId(auth()->user()->company()->id); return $this->builder->company(); - } - -} \ No newline at end of file +} diff --git a/app/Filters/InvoiceFilters.php b/app/Filters/InvoiceFilters.php index ccdc33b835c9..c6ad15433686 100644 --- a/app/Filters/InvoiceFilters.php +++ b/app/Filters/InvoiceFilters.php @@ -33,7 +33,7 @@ class InvoiceFilters extends QueryFilters * - unpaid * - overdue * - reversed - * + * * @param string client_status The invoice status as seen by the client * @return Illuminate\Database\Query\Builder * @@ -41,67 +41,74 @@ class InvoiceFilters extends QueryFilters public function client_status(string $value = '') :Builder { - if(strlen($value) == 0) + if (strlen($value) == 0) { return $this->builder; + } $status_parameters = explode(",", $value); - if (in_array('all', $status_parameters)) + if (in_array('all', $status_parameters)) { return $this->builder; + } - if(in_array('paid', $status_parameters)) + if (in_array('paid', $status_parameters)) { $this->builder->where('status_id', Invoice::STATUS_PAID); + } - if(in_array('unpaid', $status_parameters)) + if (in_array('unpaid', $status_parameters)) { $this->builder->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]); - //->where('due_date', '>', Carbon::now()) - //->orWhere('partial_due_date', '>', Carbon::now()); + } + //->where('due_date', '>', Carbon::now()) + //->orWhere('partial_due_date', '>', Carbon::now()); - if(in_array('overdue', $status_parameters)) + if (in_array('overdue', $status_parameters)) { $this->builder->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]) ->where('due_date', '<', Carbon::now()) ->orWhere('partial_due_date', '<', Carbon::now()); + } return $this->builder; } /** * Filter based on search text - * + * * @param string query filter * @return Illuminate\Database\Query\Builder * @deprecated - * + * */ public function filter(string $filter = '') : Builder { - if(strlen($filter) == 0) + if (strlen($filter) == 0) { return $this->builder; + } return $this->builder->where(function ($query) use ($filter) { - $query->where('invoices.number', 'like', '%'.$filter.'%') + $query->where('invoices.number', 'like', '%'.$filter.'%') ->orWhere('invoices.po_number', 'like', '%'.$filter.'%') ->orWhere('invoices.date', 'like', '%'.$filter.'%') ->orWhere('invoices.amount', 'like', '%'.$filter.'%') ->orWhere('invoices.balance', 'like', '%'.$filter.'%') ->orWhere('invoices.custom_value1', 'like', '%'.$filter.'%') - ->orWhere('invoices.custom_value2', 'like' , '%'.$filter.'%') - ->orWhere('invoices.custom_value3', 'like' , '%'.$filter.'%') - ->orWhere('invoices.custom_value4', 'like' , '%'.$filter.'%'); - }); + ->orWhere('invoices.custom_value2', 'like', '%'.$filter.'%') + ->orWhere('invoices.custom_value3', 'like', '%'.$filter.'%') + ->orWhere('invoices.custom_value4', 'like', '%'.$filter.'%'); + }); } /** * Filters the list based on the status * archived, active, deleted - legacy from V1 - * + * * @param string filter * @return Illuminate\Database\Query\Builder */ public function status(string $filter = '') : Builder { - if(strlen($filter) == 0) + if (strlen($filter) == 0) { return $this->builder; + } $table = 'invoices'; $filters = explode(',', $filter); @@ -131,7 +138,7 @@ class InvoiceFilters extends QueryFilters /** * Sorts the list based on $sort - * + * * @param string sort formatted as column|asc * @return Illuminate\Database\Query\Builder */ @@ -143,14 +150,13 @@ class InvoiceFilters extends QueryFilters /** * Returns the base query - * + * * @param int company_id * @return Illuminate\Database\Query\Builder * @deprecated */ public function baseQuery(int $company_id, User $user) : Builder { - } /** @@ -158,37 +164,31 @@ class InvoiceFilters 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 - * + * * @param $company_id The company Id * @return Illuminate\Database\Query\Builder */ public function entityFilter() { - - if(auth('contact')->user()) + if (auth('contact')->user()) { return $this->contactViewFilter(); - else + } else { return $this->builder->company(); + } // return $this->builder->whereCompanyId(auth()->user()->company()->id); - } /** * We need additional filters when showing invoices for the * client portal. Need to automatically exclude drafts and cancelled invoices - * + * * @return Illuminate\Database\Query\Builder */ private function contactViewFilter() : Builder { - return $this->builder ->whereCompanyId(auth('contact')->user()->company->id) ->whereNotIn('status_id', [Invoice::STATUS_DRAFT, Invoice::STATUS_CANCELLED]); - } - - - -} \ No newline at end of file +} diff --git a/app/Filters/PaymentFilters.php b/app/Filters/PaymentFilters.php index 90d83cd5ef90..6efc87c3fe4b 100644 --- a/app/Filters/PaymentFilters.php +++ b/app/Filters/PaymentFilters.php @@ -24,38 +24,40 @@ class PaymentFilters extends QueryFilters /** * Filter based on search text - * + * * @param string query filter * @return Illuminate\Database\Query\Builder * @deprecated - * + * */ public function filter(string $filter = '') : Builder { - if(strlen($filter) == 0) + if (strlen($filter) == 0) { return $this->builder; + } return $this->builder->where(function ($query) use ($filter) { - $query->where('payments.amount', 'like', '%'.$filter.'%') + $query->where('payments.amount', 'like', '%'.$filter.'%') ->orWhere('payments.date', 'like', '%'.$filter.'%') ->orWhere('payments.custom_value1', 'like', '%'.$filter.'%') - ->orWhere('payments.custom_value2', 'like' , '%'.$filter.'%') - ->orWhere('payments.custom_value3', 'like' , '%'.$filter.'%') - ->orWhere('payments.custom_value4', 'like' , '%'.$filter.'%'); - }); + ->orWhere('payments.custom_value2', 'like', '%'.$filter.'%') + ->orWhere('payments.custom_value3', 'like', '%'.$filter.'%') + ->orWhere('payments.custom_value4', 'like', '%'.$filter.'%'); + }); } /** * Filters the list based on the status * archived, active, deleted - * + * * @param string filter * @return Illuminate\Database\Query\Builder */ public function status(string $filter = '') : Builder { - if(strlen($filter) == 0) + if (strlen($filter) == 0) { return $this->builder; + } $table = 'payments'; $filters = explode(',', $filter); @@ -85,7 +87,7 @@ class PaymentFilters extends QueryFilters /** * Sorts the list based on $sort - * + * * @param string sort formatted as column|asc * @return Illuminate\Database\Query\Builder */ @@ -97,29 +99,28 @@ class PaymentFilters extends QueryFilters /** * Returns the base query - * + * * @param int company_id * @return Illuminate\Database\Query\Builder * @deprecated */ public function baseQuery(int $company_id, User $user) : Builder { - } /** * Filters the query by the users company ID - * + * * @param $company_id The company Id * @return Illuminate\Database\Query\Builder */ - public function entityFilter() + public function entityFilter() { - - if(auth('contact')->user()) + if (auth('contact')->user()) { return $this->contactViewFilter(); - else + } else { return $this->builder->company(); + } } @@ -127,15 +128,13 @@ class PaymentFilters extends QueryFilters /** * We need additional filters when showing invoices for the * client portal. Need to automatically exclude drafts and cancelled invoices - * + * * @return Illuminate\Database\Query\Builder */ private function contactViewFilter() : Builder { - return $this->builder ->whereCompanyId(auth('contact')->user()->company->id) ->whereIsDeleted(false); - } } diff --git a/app/Filters/ProductFilters.php b/app/Filters/ProductFilters.php index 866d357680ef..ed0939baf7f8 100644 --- a/app/Filters/ProductFilters.php +++ b/app/Filters/ProductFilters.php @@ -23,38 +23,40 @@ class ProductFilters extends QueryFilters /** * Filter based on search text - * + * * @param string query filter * @return Illuminate\Database\Query\Builder * @deprecated - * + * */ public function filter(string $filter = '') : Builder { - if(strlen($filter) == 0) + if (strlen($filter) == 0) { return $this->builder; + } return $this->builder->where(function ($query) use ($filter) { - $query->where('products.product_key', 'like', '%'.$filter.'%') + $query->where('products.product_key', 'like', '%'.$filter.'%') ->orWhere('products.notes', 'like', '%'.$filter.'%') - ->orWhere('products.custom_value1', 'like' , '%'.$filter.'%') - ->orWhere('products.custom_value2', 'like' , '%'.$filter.'%') - ->orWhere('products.custom_value3', 'like' , '%'.$filter.'%') - ->orWhere('products.custom_value4', 'like' , '%'.$filter.'%'); - }); + ->orWhere('products.custom_value1', 'like', '%'.$filter.'%') + ->orWhere('products.custom_value2', 'like', '%'.$filter.'%') + ->orWhere('products.custom_value3', 'like', '%'.$filter.'%') + ->orWhere('products.custom_value4', 'like', '%'.$filter.'%'); + }); } /** * Filters the list based on the status * archived, active, deleted - * + * * @param string filter * @return Illuminate\Database\Query\Builder */ public function status(string $filter = '') : Builder { - if(strlen($filter) == 0) + if (strlen($filter) == 0) { return $this->builder; + } $table = 'products'; $filters = explode(',', $filter); @@ -84,7 +86,7 @@ class ProductFilters extends QueryFilters /** * Sorts the list based on $sort - * + * * @param string sort formatted as column|asc * @return Illuminate\Database\Query\Builder */ @@ -96,27 +98,23 @@ class ProductFilters extends QueryFilters /** * Returns the base query - * + * * @param int company_id * @return Illuminate\Database\Query\Builder * @deprecated */ public function baseQuery(int $company_id, User $user) : Builder { - } /** * Filters the query by the users company ID - * + * * @param $company_id The company Id * @return Illuminate\Database\Query\Builder */ - public function entityFilter() + public function entityFilter() { - - return $this->builder->company(); - + return $this->builder->company(); } - -} \ No newline at end of file +} diff --git a/app/Filters/QueryFilters.php b/app/Filters/QueryFilters.php index 53e6c9933dc6..e4804ee66aff 100644 --- a/app/Filters/QueryFilters.php +++ b/app/Filters/QueryFilters.php @@ -59,9 +59,7 @@ abstract class QueryFilters */ public function __construct(Request $request) { - $this->request = $request; - } /** @@ -100,20 +98,17 @@ abstract class QueryFilters */ public function filters() { - return $this->request->all(); - } /** * Explodes the value by delimiter - * + * * @param string $value - * @return stdClass + * @return stdClass */ public function split($value) : stdClass { - $exploded_array = explode(":", $value); $parts = new stdClass; @@ -122,18 +117,16 @@ abstract class QueryFilters $parts->operator = $this->operatorConvertor($exploded_array[1]); return $parts; - } /** * String to operator convertor - * + * * @param string $value * @return string */ private function operatorConvertor(string $operator) : string { - switch ($operator) { case 'lt': return '<'; @@ -159,15 +152,16 @@ abstract class QueryFilters /** * Filters the query by the contact's client_id. - * + * * -Can only be used on contact routes - * + * * @param $client_id The client Id * @param Illuminate\Database\Query\Builder */ public function clientFilter() { - if(auth('contact')->user()) + if (auth('contact')->user()) { return $this->builder->whereClientId(auth('contact')->user()->client->id); + } } -} \ No newline at end of file +} diff --git a/app/Filters/QuoteFilters.php b/app/Filters/QuoteFilters.php index 22196cd60cea..0a478078b25f 100644 --- a/app/Filters/QuoteFilters.php +++ b/app/Filters/QuoteFilters.php @@ -23,36 +23,38 @@ class QuoteFilters extends QueryFilters /** * Filter based on search text - * + * * @param string query filter * @return Illuminate\Database\Query\Builder * @deprecated - * + * */ public function filter(string $filter = '') : Builder { - if(strlen($filter) == 0) + if (strlen($filter) == 0) { return $this->builder; + } return $this->builder->where(function ($query) use ($filter) { - $query->where('quotes.custom_value1', 'like', '%'.$filter.'%') - ->orWhere('quotes.custom_value2', 'like' , '%'.$filter.'%') - ->orWhere('quotes.custom_value3', 'like' , '%'.$filter.'%') - ->orWhere('quotes.custom_value4', 'like' , '%'.$filter.'%'); - }); + $query->where('quotes.custom_value1', 'like', '%'.$filter.'%') + ->orWhere('quotes.custom_value2', 'like', '%'.$filter.'%') + ->orWhere('quotes.custom_value3', 'like', '%'.$filter.'%') + ->orWhere('quotes.custom_value4', 'like', '%'.$filter.'%'); + }); } /** * Filters the list based on the status * archived, active, deleted - * + * * @param string filter * @return Illuminate\Database\Query\Builder */ public function status(string $filter = '') : Builder { - if(strlen($filter) == 0) + if (strlen($filter) == 0) { return $this->builder; + } $table = 'quotes'; $filters = explode(',', $filter); @@ -82,7 +84,7 @@ class QuoteFilters extends QueryFilters /** * Sorts the list based on $sort - * + * * @param string sort formatted as column|asc * @return Illuminate\Database\Query\Builder */ @@ -94,27 +96,23 @@ class QuoteFilters extends QueryFilters /** * Returns the base query - * + * * @param int company_id * @return Illuminate\Database\Query\Builder * @deprecated */ public function baseQuery(int $company_id, User $user) : Builder { - } /** * Filters the query by the users company ID - * + * * @param $company_id The company Id * @return Illuminate\Database\Query\Builder */ - public function entityFilter() + public function entityFilter() { - - return $this->builder->company(); - + return $this->builder->company(); } - -} \ No newline at end of file +} diff --git a/app/Filters/RecurringInvoiceFilters.php b/app/Filters/RecurringInvoiceFilters.php index 068000bc2f37..9a0f9d603a32 100644 --- a/app/Filters/RecurringInvoiceFilters.php +++ b/app/Filters/RecurringInvoiceFilters.php @@ -23,36 +23,38 @@ class RecurringInvoiceFilters extends QueryFilters /** * Filter based on search text - * + * * @param string query filter * @return Illuminate\Database\Query\Builder * @deprecated - * + * */ public function filter(string $filter = '') : Builder { - if(strlen($filter) == 0) + if (strlen($filter) == 0) { return $this->builder; + } return $this->builder->where(function ($query) use ($filter) { - $query->where('recurring_invoices.custom_value1', 'like', '%'.$filter.'%') - ->orWhere('recurring_invoices.custom_value2', 'like' , '%'.$filter.'%') - ->orWhere('recurring_invoices.custom_value3', 'like' , '%'.$filter.'%') - ->orWhere('recurring_invoices.custom_value4', 'like' , '%'.$filter.'%'); - }); + $query->where('recurring_invoices.custom_value1', 'like', '%'.$filter.'%') + ->orWhere('recurring_invoices.custom_value2', 'like', '%'.$filter.'%') + ->orWhere('recurring_invoices.custom_value3', 'like', '%'.$filter.'%') + ->orWhere('recurring_invoices.custom_value4', 'like', '%'.$filter.'%'); + }); } /** * Filters the list based on the status * archived, active, deleted - * + * * @param string filter * @return Illuminate\Database\Query\Builder */ public function status(string $filter = '') : Builder { - if(strlen($filter) == 0) + if (strlen($filter) == 0) { return $this->builder; + } $table = 'recurring_'; $filters = explode(',', $filter); @@ -82,7 +84,7 @@ class RecurringInvoiceFilters extends QueryFilters /** * Sorts the list based on $sort - * + * * @param string sort formatted as column|asc * @return Illuminate\Database\Query\Builder */ @@ -94,27 +96,23 @@ class RecurringInvoiceFilters extends QueryFilters /** * Returns the base query - * + * * @param int company_id * @return Illuminate\Database\Query\Builder * @deprecated */ public function baseQuery(int $company_id, User $user) : Builder { - } /** * Filters the query by the users company ID - * + * * @param $company_id The company Id * @return Illuminate\Database\Query\Builder */ - public function entityFilter() + public function entityFilter() { - - return $this->builder->company(); - + return $this->builder->company(); } - -} \ No newline at end of file +} diff --git a/app/Filters/RecurringQuoteFilters.php b/app/Filters/RecurringQuoteFilters.php index 1f3dbd64502f..c44cd656d0be 100644 --- a/app/Filters/RecurringQuoteFilters.php +++ b/app/Filters/RecurringQuoteFilters.php @@ -23,36 +23,38 @@ class RecurringQuoteFilters extends QueryFilters /** * Filter based on search text - * + * * @param string query filter * @return Illuminate\Database\Query\Builder * @deprecated - * + * */ public function filter(string $filter = '') : Builder { - if(strlen($filter) == 0) + if (strlen($filter) == 0) { return $this->builder; + } return $this->builder->where(function ($query) use ($filter) { - $query->where('recurring_quotes.custom_value1', 'like', '%'.$filter.'%') - ->orWhere('recurring_quotes.custom_value2', 'like' , '%'.$filter.'%') - ->orWhere('recurring_quotes.custom_value3', 'like' , '%'.$filter.'%') - ->orWhere('recurring_quotes.custom_value4', 'like' , '%'.$filter.'%'); - }); + $query->where('recurring_quotes.custom_value1', 'like', '%'.$filter.'%') + ->orWhere('recurring_quotes.custom_value2', 'like', '%'.$filter.'%') + ->orWhere('recurring_quotes.custom_value3', 'like', '%'.$filter.'%') + ->orWhere('recurring_quotes.custom_value4', 'like', '%'.$filter.'%'); + }); } /** * Filters the list based on the status * archived, active, deleted - * + * * @param string filter * @return Illuminate\Database\Query\Builder */ public function status(string $filter = '') : Builder { - if(strlen($filter) == 0) + if (strlen($filter) == 0) { return $this->builder; + } $table = 'recurring_'; $filters = explode(',', $filter); @@ -82,7 +84,7 @@ class RecurringQuoteFilters extends QueryFilters /** * Sorts the list based on $sort - * + * * @param string sort formatted as column|asc * @return Illuminate\Database\Query\Builder */ @@ -94,27 +96,23 @@ class RecurringQuoteFilters extends QueryFilters /** * Returns the base query - * + * * @param int company_id * @return Illuminate\Database\Query\Builder * @deprecated */ public function baseQuery(int $company_id, User $user) : Builder { - } /** * Filters the query by the users company ID - * + * * @param $company_id The company Id * @return Illuminate\Database\Query\Builder */ - public function entityFilter() + public function entityFilter() { - - return $this->builder->company(); - + return $this->builder->company(); } - -} \ No newline at end of file +} diff --git a/app/Filters/UserFilters.php b/app/Filters/UserFilters.php index e8aede08ed6a..0dfd5363e1a8 100644 --- a/app/Filters/UserFilters.php +++ b/app/Filters/UserFilters.php @@ -23,36 +23,38 @@ class UserFilters extends QueryFilters /** * Filter based on search text - * + * * @param string query filter * @return Illuminate\Database\Query\Builder * @deprecated - * + * */ public function filter(string $filter = '') : Builder { - if(strlen($filter) == 0) + if (strlen($filter) == 0) { return $this->builder; + } return $this->builder->where(function ($query) use ($filter) { - $query->where('users.first_name', 'like', '%'.$filter.'%') - ->orWhere('users.last_name', 'like' , '%'.$filter.'%') - ->orWhere('users.email', 'like' , '%'.$filter.'%') - ->orWhere('users.signature', 'like' , '%'.$filter.'%'); - }); + $query->where('users.first_name', 'like', '%'.$filter.'%') + ->orWhere('users.last_name', 'like', '%'.$filter.'%') + ->orWhere('users.email', 'like', '%'.$filter.'%') + ->orWhere('users.signature', 'like', '%'.$filter.'%'); + }); } /** * Filters the list based on the status * archived, active, deleted - * + * * @param string filter * @return Illuminate\Database\Query\Builder */ public function status(string $filter = '') : Builder { - if(strlen($filter) == 0) + if (strlen($filter) == 0) { return $this->builder; + } $table = 'users'; $filters = explode(',', $filter); @@ -82,7 +84,7 @@ class UserFilters extends QueryFilters /** * Sorts the list based on $sort - * + * * @param string sort formatted as column|asc * @return Illuminate\Database\Query\Builder */ @@ -94,31 +96,27 @@ class UserFilters extends QueryFilters /** * Returns the base query - * + * * @param int company_id * @return Illuminate\Database\Query\Builder * @deprecated */ public function baseQuery(int $company_id, User $user) : Builder { - } /** * Filters the query by the users company ID - * + * * @param $company_id The company Id * @return Illuminate\Database\Query\Builder */ - public function entityFilter() + public function entityFilter() { //return $this->builder->user_companies()->whereCompanyId(auth()->user()->company()->id); //return $this->builder->whereCompanyId(auth()->user()->company()->id); - return $this->builder->whereHas('company_users', function($q) - { + return $this->builder->whereHas('company_users', function ($q) { $q->where('company_id', '=', auth()->user()->company()->id); - }); } - -} \ No newline at end of file +} diff --git a/app/Helpers/Invoice/Balancer.php b/app/Helpers/Invoice/Balancer.php index e0d5deed8b08..70b953f6b46e 100644 --- a/app/Helpers/Invoice/Balancer.php +++ b/app/Helpers/Invoice/Balancer.php @@ -16,17 +16,12 @@ namespace App\Helpers\Invoice; */ trait Balancer { - - public function balance($total, $invoice) - { - - if(isset($this->invoice->id) && $this->invoice->id >= 1) - { + public function balance($total, $invoice) + { + if (isset($this->invoice->id) && $this->invoice->id >= 1) { return round($total - ($this->invoice->amount - $this->invoice->balance), 2); - } + } return $total; - - } - + } } diff --git a/app/Helpers/Invoice/CustomValuer.php b/app/Helpers/Invoice/CustomValuer.php index 5903e6c7c190..0c67418701d5 100644 --- a/app/Helpers/Invoice/CustomValuer.php +++ b/app/Helpers/Invoice/CustomValuer.php @@ -16,23 +16,21 @@ namespace App\Helpers\Invoice; */ trait CustomValuer { - - public function valuer($custom_value) - { - - if(isset($custom_value) && is_numeric($custom_value)) - return $custom_value; + public function valuer($custom_value) + { + if (isset($custom_value) && is_numeric($custom_value)) { + return $custom_value; + } return 0; - } + } - public function valuerTax($custom_value, $has_custom_invoice_taxes) - { - if(isset($custom_value) && is_numeric($custom_value) && $has_custom_invoice_taxes === true) - 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); - - return 0; - } + public function valuerTax($custom_value, $has_custom_invoice_taxes) + { + if (isset($custom_value) && is_numeric($custom_value) && $has_custom_invoice_taxes === true) { + 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); + } + return 0; + } } - diff --git a/app/Helpers/Invoice/Discounter.php b/app/Helpers/Invoice/Discounter.php index 792b20f192f2..4e7ec8b744f9 100644 --- a/app/Helpers/Invoice/Discounter.php +++ b/app/Helpers/Invoice/Discounter.php @@ -16,18 +16,13 @@ namespace App\Helpers\Invoice; */ trait Discounter { + public function discount($amount) + { + if ($this->invoice->is_amount_discount == true) { + return $this->invoice->discount; + } - public function discount($amount) - { - - if($this->invoice->is_amount_discount == true){ - return $this->invoice->discount; - } - - - return round($amount * ($this->invoice->discount / 100), 2); - - } - - + + return round($amount * ($this->invoice->discount / 100), 2); + } } diff --git a/app/Helpers/Invoice/InvoiceItemSum.php b/app/Helpers/Invoice/InvoiceItemSum.php index 6e9a7f53a5a0..6f770d1798dd 100644 --- a/app/Helpers/Invoice/InvoiceItemSum.php +++ b/app/Helpers/Invoice/InvoiceItemSum.php @@ -21,275 +21,261 @@ use Illuminate\Support\Collection; class InvoiceItemSum { + use NumberFormatter; + use Discounter; + use Taxer; - use NumberFormatter; - use Discounter; - use Taxer; + protected $invoice; - protected $invoice; + private $items; - private $items; + private $line_total; - private $line_total; + private $currency; - private $currency; + private $total_taxes; - private $total_taxes; + private $item; - private $item; + private $line_items; - private $line_items; + private $sub_total; - private $sub_total; + private $total_discount; - private $total_discount; + private $tax_collection; - private $tax_collection; + public function __construct($invoice) + { + $this->tax_collection = collect([]); - public function __construct($invoice) - { + $this->invoice = $invoice; - $this->tax_collection = collect([]); + $this->currency = $this->invoice->client->currency(); - $this->invoice = $invoice; + $this->line_items = []; + } - $this->currency = $this->invoice->client->currency(); + public function process() + { + if (!$this->invoice->line_items || !isset($this->invoice->line_items) || count($this->invoice->line_items) == 0) { + $this->items = []; + return $this; + } - $this->line_items = []; - } + $this->calcLineItems(); - public function process() - { + return $this; + } - if(!$this->invoice->line_items || !isset($this->invoice->line_items) || count($this->invoice->line_items) == 0){ - $this->items = []; - return $this; - } + private function calcLineItems() + { + foreach ($this->invoice->line_items as $this->item) { + $this->cleanLineItem() + ->sumLineItem() + ->setDiscount() + ->calcTaxes() + ->push(); + } - $this->calcLineItems(); + return $this; + } - return $this; - } + private function push() + { + $this->sub_total += $this->getLineTotal(); - private function calcLineItems() - { - foreach($this->invoice->line_items as $this->item) - { - $this->cleanLineItem() - ->sumLineItem() - ->setDiscount() - ->calcTaxes() - ->push(); - } + $this->line_items[] = $this->item; - return $this; - } + return $this; + } - private function push() - { + private function sumLineItem() + { + $this->setLineTotal($this->formatValue($this->item->cost, $this->currency->precision) * $this->formatValue($this->item->quantity, $this->currency->precision)); + return $this; + } - $this->sub_total += $this->getLineTotal(); + private function setDiscount() + { + if ($this->invoice->is_amount_discount) { + $this->setLineTotal($this->getLineTotal() - $this->formatValue($this->item->discount, $this->currency->precision)); + } else { + $this->setLineTotal($this->getLineTotal() - $this->formatValue(round($this->item->line_total * ($this->item->discount / 100), 2), $this->currency->precision)); + } - $this->line_items[] = $this->item; + $this->item->is_amount_discount = $this->invoice->is_amount_discount; - return $this; - } + return $this; + } - private function sumLineItem() - { - $this->setLineTotal($this->formatValue($this->item->cost, $this->currency->precision) * $this->formatValue($this->item->quantity, $this->currency->precision)); - return $this; - } + private function calcTaxes() + { + $item_tax = 0; - private function setDiscount() - { + $amount = $this->item->line_total - ($this->item->line_total * ($this->invoice->discount/100)); + $item_tax_rate1_total = $this->calcAmountLineTax($this->item->tax_rate1, $amount); - if($this->invoice->is_amount_discount) - { - $this->setLineTotal($this->getLineTotal() - $this->formatValue($this->item->discount, $this->currency->precision)); - } - else - { - $this->setLineTotal($this->getLineTotal() - $this->formatValue(round($this->item->line_total * ($this->item->discount / 100),2), $this->currency->precision)); - } + $item_tax += $item_tax_rate1_total; - $this->item->is_amount_discount = $this->invoice->is_amount_discount; - - return $this; + if ($item_tax_rate1_total > 0) { + $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); - private function calcTaxes() - { + $item_tax += $item_tax_rate2_total; - $item_tax = 0; + if ($item_tax_rate2_total > 0) { + $this->groupTax($this->item->tax_name2, $this->item->tax_rate2, $item_tax_rate2_total); + } - $amount = $this->item->line_total - ($this->item->line_total * ($this->invoice->discount/100)); - $item_tax_rate1_total = $this->calcAmountLineTax($this->item->tax_rate1, $amount); + $item_tax_rate3_total = $this->calcAmountLineTax($this->item->tax_rate3, $amount); - $item_tax += $item_tax_rate1_total; + $item_tax += $item_tax_rate3_total; - if($item_tax_rate1_total > 0) - $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($item_tax_rate2_total > 0) - $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($item_tax_rate3_total > 0) - $this->groupTax($this->item->tax_name3, $this->item->tax_rate3, $item_tax_rate3_total); + if ($item_tax_rate3_total > 0) { + $this->groupTax($this->item->tax_name3, $this->item->tax_rate3, $item_tax_rate3_total); + } - $this->setTotalTaxes($this->formatValue($item_tax, $this->currency->precision)); + $this->setTotalTaxes($this->formatValue($item_tax, $this->currency->precision)); - return $this; - } + return $this; + } - private function groupTax($tax_name, $tax_rate, $tax_total) - { - $group_tax = []; + private function groupTax($tax_name, $tax_rate, $tax_total) + { + $group_tax = []; - $key = str_replace(" ", "", $tax_name.$tax_rate); + $key = str_replace(" ", "", $tax_name.$tax_rate); - $group_tax = ['key' => $key, 'total' => $tax_total, 'tax_name' => $tax_name . ' ' . $tax_rate.'%']; + $group_tax = ['key' => $key, 'total' => $tax_total, 'tax_name' => $tax_name . ' ' . $tax_rate.'%']; - $this->tax_collection->push(collect($group_tax)); - - } + $this->tax_collection->push(collect($group_tax)); + } - public function getTotalTaxes() - { - return $this->total_taxes; - } + public function getTotalTaxes() + { + return $this->total_taxes; + } - public function setTotalTaxes($total) - { - $this->total_taxes = $total; + public function setTotalTaxes($total) + { + $this->total_taxes = $total; - return $this; - } + return $this; + } - public function setLineTotal($total) - { - $this->item->line_total = $total; + public function setLineTotal($total) + { + $this->item->line_total = $total; - return $this; - } + return $this; + } - public function getLineTotal() - { - return $this->item->line_total; - } + public function getLineTotal() + { + return $this->item->line_total; + } - public function getLineItems() - { - return $this->line_items; - } + public function getLineItems() + { + return $this->line_items; + } - public function getGroupedTaxes() - { - return $this->tax_collection; - } + public function getGroupedTaxes() + { + return $this->tax_collection; + } - public function setGroupedTaxes($group_taxes) - { - $this->tax_collection = $group_taxes; + public function setGroupedTaxes($group_taxes) + { + $this->tax_collection = $group_taxes; - return $this; - } + return $this; + } - public function getSubTotal() - { - return $this->sub_total; - } + public function getSubTotal() + { + return $this->sub_total; + } - public function setSubTotal($value) - { - $this->sub_total = $value; - return $this; - } + public function setSubTotal($value) + { + $this->sub_total = $value; + return $this; + } - /** - * Invoice Amount Discount - * - * The problem, when calculating invoice level discounts, - * the tax collected changes. - * - * We need to synthetically reduce the line_total amounts - * and recalculate the taxes and then pass back - * the updated map - */ - - public function calcTaxesWithAmountDiscount() - { - $this->setGroupedTaxes(collect([])); + /** + * Invoice Amount Discount + * + * The problem, when calculating invoice level discounts, + * the tax collected changes. + * + * We need to synthetically reduce the line_total amounts + * and recalculate the taxes and then pass back + * the updated map + */ + + public function calcTaxesWithAmountDiscount() + { + $this->setGroupedTaxes(collect([])); - $item_tax = 0; + $item_tax = 0; - foreach($this->line_items as $this->item) - { + foreach ($this->line_items as $this->item) { + if ($this->item->line_total == 0) { + continue; + } - if($this->item->line_total == 0) - continue; + $amount = $this->item->line_total - ($this->item->line_total * ($this->invoice->discount/$this->sub_total)); + $item_tax_rate1_total = $this->calcAmountLineTax($this->item->tax_rate1, $amount); - $amount = $this->item->line_total - ($this->item->line_total * ($this->invoice->discount/$this->sub_total)); - $item_tax_rate1_total = $this->calcAmountLineTax($this->item->tax_rate1, $amount); + $item_tax += $item_tax_rate1_total; - $item_tax += $item_tax_rate1_total; + if ($item_tax_rate1_total > 0) { + $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); - if($item_tax_rate1_total > 0) - $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; - $item_tax += $item_tax_rate2_total; + if ($item_tax_rate2_total > 0) { + $this->groupTax($this->item->tax_name2, $this->item->tax_rate2, $item_tax_rate2_total); + } - if($item_tax_rate2_total > 0) - $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_rate3_total = $this->calcAmountLineTax($this->item->tax_rate3, $amount); + $item_tax += $item_tax_rate3_total; - $item_tax += $item_tax_rate3_total; + if ($item_tax_rate3_total > 0) { + $this->groupTax($this->item->tax_name3, $this->item->tax_rate3, $item_tax_rate3_total); + } + } - if($item_tax_rate3_total > 0) - $this->groupTax($this->item->tax_name3, $this->item->tax_rate3, $item_tax_rate3_total); + $this->setTotalTaxes($item_tax); + } + + /** + * Sets default values for the line_items + * @return $this + */ + private function cleanLineItem() + { + $invoice_item = (object)get_class_vars(InvoiceItem::class); + unset($invoice_item->casts); + + foreach ($invoice_item as $key => $value) { + if (!property_exists($this->item, $key) || !isset($this->item->{$key})) { + $this->item->{$key} = $value; + $this->item->{$key} = BaseSettings::castAttribute(InvoiceItem::$casts[$key], $value); + } + } - } - - $this->setTotalTaxes($item_tax); - - } - - /** - * Sets default values for the line_items - * @return $this - */ - private function cleanLineItem() - { - $invoice_item = (object)get_class_vars(InvoiceItem::class); - unset($invoice_item->casts); - - foreach($invoice_item as $key => $value) - { - - if(!property_exists($this->item, $key) || !isset($this->item->{$key})){ - $this->item->{$key} = $value; - $this->item->{$key} = BaseSettings::castAttribute(InvoiceItem::$casts[$key], $value); - } - - - } - - - return $this; - } -} \ No newline at end of file + return $this; + } +} diff --git a/app/Helpers/Invoice/InvoiceItemSumInclusive.php b/app/Helpers/Invoice/InvoiceItemSumInclusive.php index 09bea6a85780..3bdf5d2efcae 100644 --- a/app/Helpers/Invoice/InvoiceItemSumInclusive.php +++ b/app/Helpers/Invoice/InvoiceItemSumInclusive.php @@ -19,255 +19,243 @@ use Illuminate\Support\Collection; class InvoiceItemSumInclusive { - - use NumberFormatter; - use Discounter; - use Taxer; + use NumberFormatter; + use Discounter; + use Taxer; - protected $invoice; + protected $invoice; - private $items; + private $items; - private $line_total; + private $line_total; - private $currency; + private $currency; - private $total_taxes; + private $total_taxes; - private $item; + private $item; - private $line_items; + private $line_items; - private $sub_total; + private $sub_total; - private $total_discount; + private $total_discount; - private $tax_collection; + private $tax_collection; - public function __construct($invoice) - { + public function __construct($invoice) + { + $this->tax_collection = collect([]); + + $this->invoice = $invoice; + + $this->currency = $this->invoice->client->currency(); + + $this->line_items = []; + } + + public function process() + { + if (!$this->invoice->line_items || count($this->invoice->line_items) == 0) { + $this->items = []; + return $this; + } + + $this->calcLineItems(); + + return $this; + } + + private function calcLineItems() + { + foreach ($this->invoice->line_items as $this->item) { + $this->sumLineItem() + ->setDiscount() + ->calcTaxes() + ->push(); + } + + return $this; + } + + private function push() + { + $this->sub_total += $this->getLineTotal(); + + $this->line_items[] = $this->item; + + return $this; + } - $this->tax_collection = collect([]); + private function sumLineItem() + { + $this->setLineTotal($this->formatValue($this->item->cost, $this->currency->precision) * $this->formatValue($this->item->quantity, $this->currency->precision)); - $this->invoice = $invoice; + return $this; + } - $this->currency = $this->invoice->client->currency(); + private function setDiscount() + { + if ($this->invoice->is_amount_discount) { + $this->setLineTotal($this->getLineTotal() - $this->formatValue($this->item->discount, $this->currency->precision)); + } else { + $this->setLineTotal($this->getLineTotal() - $this->formatValue(($this->item->line_total * ($this->item->discount / 100)), $this->currency->precision)); + } - $this->line_items = []; - } + $this->item->is_amount_discount = $this->invoice->is_amount_discount; - public function process() - { + return $this; + } - if(!$this->invoice->line_items || count($this->invoice->line_items) == 0){ - $this->items = []; - return $this; - } + /** + * Taxes effect the line totals and item costs. we decrement both on + * application of inclusive tax rates. + * + */ + private function calcTaxes() + { + $item_tax = 0; - $this->calcLineItems(); + $amount = $this->item->line_total - ($this->item->line_total * ($this->invoice->discount/100)); - return $this; - } + $item_tax_rate1_total = $this->calcInclusiveLineTax($this->item->tax_rate1, $amount); - private function calcLineItems() - { - foreach($this->invoice->line_items as $this->item) - { - $this->sumLineItem() - ->setDiscount() - ->calcTaxes() - ->push(); - } + $item_tax += $this->formatValue($item_tax_rate1_total, $this->currency->precision); - return $this; - } - - private function push() - { - - $this->sub_total += $this->getLineTotal(); - - $this->line_items[] = $this->item; - - return $this; - } - - - private function sumLineItem() - { - $this->setLineTotal($this->formatValue($this->item->cost, $this->currency->precision) * $this->formatValue($this->item->quantity, $this->currency->precision)); - - return $this; - } - - private function setDiscount() - { - - if($this->invoice->is_amount_discount) - { - $this->setLineTotal($this->getLineTotal() - $this->formatValue($this->item->discount, $this->currency->precision)); - } - else - { - $this->setLineTotal($this->getLineTotal() - $this->formatValue(($this->item->line_total * ($this->item->discount / 100)), $this->currency->precision)); - } - - $this->item->is_amount_discount = $this->invoice->is_amount_discount; - - return $this; + if ($item_tax_rate1_total > 0) { + $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); - /** - * Taxes effect the line totals and item costs. we decrement both on - * application of inclusive tax rates. - * - */ - private function calcTaxes() - { + $item_tax += $this->formatValue($item_tax_rate2_total, $this->currency->precision); - $item_tax = 0; + if ($item_tax_rate2_total > 0) { + $this->groupTax($this->item->tax_name2, $this->item->tax_rate2, $item_tax_rate2_total); + } - $amount = $this->item->line_total - ($this->item->line_total * ($this->invoice->discount/100)); + $item_tax_rate3_total = $this->calcInclusiveLineTax($this->item->tax_rate3, $amount); - $item_tax_rate1_total = $this->calcInclusiveLineTax($this->item->tax_rate1, $amount); + $item_tax += $this->formatValue($item_tax_rate3_total, $this->currency->precision); - $item_tax += $this->formatValue($item_tax_rate1_total, $this->currency->precision); + if ($item_tax_rate3_total > 0) { + $this->groupTax($this->item->tax_name3, $this->item->tax_rate3, $item_tax_rate3_total); + } - if($item_tax_rate1_total > 0) - $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); + $this->setTotalTaxes($this->formatValue($item_tax, $this->currency->precision)); - $item_tax += $this->formatValue($item_tax_rate2_total, $this->currency->precision); + return $this; + } - if($item_tax_rate2_total > 0) - $this->groupTax($this->item->tax_name2, $this->item->tax_rate2, $item_tax_rate2_total); + private function groupTax($tax_name, $tax_rate, $tax_total) + { + $group_tax = []; - $item_tax_rate3_total = $this->calcInclusiveLineTax($this->item->tax_rate3, $amount); + $key = str_replace(" ", "", $tax_name.$tax_rate); - $item_tax += $this->formatValue($item_tax_rate3_total, $this->currency->precision); + $group_tax = ['key' => $key, 'total' => $tax_total, 'tax_name' => $tax_name . ' ' . $tax_rate.'%']; - if($item_tax_rate3_total > 0) - $this->groupTax($this->item->tax_name3, $this->item->tax_rate3, $item_tax_rate3_total); + $this->tax_collection->push(collect($group_tax)); + } - $this->setTotalTaxes($this->formatValue($item_tax, $this->currency->precision)); + public function getTotalTaxes() + { + return $this->total_taxes; + } - return $this; - } + public function setTotalTaxes($total) + { + $this->total_taxes = $total; - private function groupTax($tax_name, $tax_rate, $tax_total) - { - $group_tax = []; + return $this; + } - $key = str_replace(" ", "", $tax_name.$tax_rate); + public function setLineTotal($total) + { + $this->item->line_total = $total; - $group_tax = ['key' => $key, 'total' => $tax_total, 'tax_name' => $tax_name . ' ' . $tax_rate.'%']; + return $this; + } - $this->tax_collection->push(collect($group_tax)); - - } + public function getLineTotal() + { + return $this->item->line_total; + } - public function getTotalTaxes() - { - return $this->total_taxes; - } + public function getLineItems() + { + return $this->line_items; + } - public function setTotalTaxes($total) - { - $this->total_taxes = $total; + public function getGroupedTaxes() + { + return $this->tax_collection; + } - return $this; - } + public function setGroupedTaxes($group_taxes) + { + $this->tax_collection = $group_taxes; - public function setLineTotal($total) - { - $this->item->line_total = $total; + return $this; + } - return $this; - } + public function getSubTotal() + { + return $this->sub_total; + } - public function getLineTotal() - { - return $this->item->line_total; - } + public function setSubTotal($value) + { + $this->sub_total = $value; + return $this; + } - public function getLineItems() - { - return $this->line_items; - } + /** + * Invoice Amount Discount + * + * The problem, when calculating invoice level discounts, + * the tax collected changes. + * + * We need to synthetically reduce the line_total amounts + * and recalculate the taxes and then pass back + * the updated map + */ + + public function calcTaxesWithAmountDiscount() + { + $this->setGroupedTaxes(collect([])); - public function getGroupedTaxes() - { - return $this->tax_collection; - } + $item_tax = 0; - public function setGroupedTaxes($group_taxes) - { - $this->tax_collection = $group_taxes; + foreach ($this->line_items as $this->item) { + $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); - return $this; - } + $item_tax += $item_tax_rate1_total; - public function getSubTotal() - { - return $this->sub_total; - } + if ($item_tax_rate1_total > 0) { + $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); - public function setSubTotal($value) - { - $this->sub_total = $value; - return $this; - } + $item_tax += $item_tax_rate2_total; - /** - * Invoice Amount Discount - * - * The problem, when calculating invoice level discounts, - * the tax collected changes. - * - * We need to synthetically reduce the line_total amounts - * and recalculate the taxes and then pass back - * the updated map - */ - - public function calcTaxesWithAmountDiscount() - { - $this->setGroupedTaxes(collect([])); + if ($item_tax_rate2_total > 0) { + $this->groupTax($this->item->tax_name2, $this->item->tax_rate2, $item_tax_rate2_total); + } - $item_tax = 0; + $item_tax_rate3_total = $this->calcInclusiveLineTax($this->item->tax_rate3, $amount); - foreach($this->line_items as $this->item) - { + $item_tax += $item_tax_rate3_total; - $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); + if ($item_tax_rate3_total > 0) { + $this->groupTax($this->item->tax_name3, $this->item->tax_rate3, $item_tax_rate3_total); + } + } - $item_tax += $item_tax_rate1_total; - - if($item_tax_rate1_total > 0) - $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 += $item_tax_rate2_total; - - if($item_tax_rate2_total > 0) - $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 += $item_tax_rate3_total; - - if($item_tax_rate3_total > 0) - $this->groupTax($this->item->tax_name3, $this->item->tax_rate3, $item_tax_rate3_total); - - - } - - $this->setTotalTaxes($item_tax); - - } -} \ No newline at end of file + $this->setTotalTaxes($item_tax); + } +} diff --git a/app/Helpers/Invoice/InvoiceSum.php b/app/Helpers/Invoice/InvoiceSum.php index 828fa3a4bb02..9e31c8897903 100644 --- a/app/Helpers/Invoice/InvoiceSum.php +++ b/app/Helpers/Invoice/InvoiceSum.php @@ -21,88 +21,85 @@ use Illuminate\Support\Collection; class InvoiceSum { - use Taxer; - use Balancer; - use CustomValuer; - use Discounter; + use Taxer; + use Balancer; + use CustomValuer; + use Discounter; - use NumberFormatter; + use NumberFormatter; - protected $invoice; + protected $invoice; - public $tax_map; + public $tax_map; - public $invoice_item; + public $invoice_item; - public $total_taxes; + public $total_taxes; - private $total; + private $total; - private $total_discount; + private $total_discount; - private $total_custom_values; + private $total_custom_values; - private $total_tax_map; + private $total_tax_map; - private $sub_total; - /** - * Constructs the object with Invoice and Settings object - * - * @param \App\Models\Invoice $invoice The invoice - */ - public function __construct($invoice) - { - - $this->invoice = $invoice; + private $sub_total; + /** + * Constructs the object with Invoice and Settings object + * + * @param \App\Models\Invoice $invoice The invoice + */ + public function __construct($invoice) + { + $this->invoice = $invoice; - $this->tax_map = new Collection; + $this->tax_map = new Collection; + } - } + public function build() + { + $this->calculateLineItems() + ->calculateDiscount() + ->calculateCustomValues() + ->calculateInvoiceTaxes() + ->setTaxMap() + ->calculateTotals() + ->calculateBalance() + ->calculatePartial(); - public function build() - { + return $this; + } - $this->calculateLineItems() - ->calculateDiscount() - ->calculateCustomValues() - ->calculateInvoiceTaxes() - ->setTaxMap() - ->calculateTotals() - ->calculateBalance() - ->calculatePartial(); + private function calculateLineItems() + { + $this->invoice_items = new InvoiceItemSum($this->invoice); + $this->invoice_items->process(); + $this->invoice->line_items = $this->invoice_items->getLineItems(); + $this->total = $this->invoice_items->getSubTotal(); + $this->setSubTotal($this->invoice_items->getSubTotal()); - return $this; - } + return $this; + } - private function calculateLineItems() - { - $this->invoice_items = new InvoiceItemSum($this->invoice); - $this->invoice_items->process(); - $this->invoice->line_items = $this->invoice_items->getLineItems(); - $this->total = $this->invoice_items->getSubTotal(); - $this->setSubTotal($this->invoice_items->getSubTotal()); + private function calculateDiscount() + { + $this->total_discount = $this->discount($this->invoice_items->getSubTotal()); - return $this; - } + $this->total -= $this->total_discount; - private function calculateDiscount() - { - $this->total_discount = $this->discount($this->invoice_items->getSubTotal()); + return $this; + } - $this->total -= $this->total_discount; - - return $this; - } - - private function calculateCustomValues() - { - $this->total_taxes += $this->valuerTax($this->invoice->custom_surcharge1, $this->invoice->custom_surcharge_taxes1); + private function calculateCustomValues() + { + $this->total_taxes += $this->valuerTax($this->invoice->custom_surcharge1, $this->invoice->custom_surcharge_taxes1); $this->total_custom_values += $this->valuer($this->invoice->custom_surcharge1); - $this->total_taxes += $this->valuerTax($this->invoice->custom_surcharge2, $this->invoice->custom_surcharge_taxes2); + $this->total_taxes += $this->valuerTax($this->invoice->custom_surcharge2, $this->invoice->custom_surcharge_taxes2); $this->total_custom_values += $this->valuer($this->invoice->custom_surcharge2); - $this->total_taxes += $this->valuerTax($this->invoice->custom_surcharge3, $this->invoice->custom_surcharge_taxes3); + $this->total_taxes += $this->valuerTax($this->invoice->custom_surcharge3, $this->invoice->custom_surcharge_taxes3); $this->total_custom_values += $this->valuer($this->invoice->custom_surcharge3); $this->total_taxes += $this->valuerTax($this->invoice->custom_surcharge4, $this->invoice->custom_surcharge_taxes4); @@ -111,145 +108,142 @@ class InvoiceSum $this->total += $this->total_custom_values; return $this; - } + } - private function calculateInvoiceTaxes() - { - - if($this->invoice->tax_rate1 > 0){ - $tax = $this->taxer($this->total, $this->invoice->tax_rate1); - $this->total_taxes += $tax; - $this->total_tax_map[] = ['name' => $this->invoice->tax_name1 . ' ' . $this->invoice->tax_rate1.'%', 'total' => $tax]; + private function calculateInvoiceTaxes() + { + if ($this->invoice->tax_rate1 > 0) { + $tax = $this->taxer($this->total, $this->invoice->tax_rate1); + $this->total_taxes += $tax; + $this->total_tax_map[] = ['name' => $this->invoice->tax_name1 . ' ' . $this->invoice->tax_rate1.'%', 'total' => $tax]; } - if($this->invoice->tax_rate2 > 0){ - $tax = $this->taxer($this->total, $this->invoice->tax_rate2); - $this->total_taxes += $tax; - $this->total_tax_map[] = ['name' => $this->invoice->tax_name2. ' ' . $this->invoice->tax_rate2.'%', 'total' => $tax]; + if ($this->invoice->tax_rate2 > 0) { + $tax = $this->taxer($this->total, $this->invoice->tax_rate2); + $this->total_taxes += $tax; + $this->total_tax_map[] = ['name' => $this->invoice->tax_name2. ' ' . $this->invoice->tax_rate2.'%', 'total' => $tax]; } - if($this->invoice->tax_rate3 > 0){ - $tax = $this->taxer($this->total, $this->invoice->tax_rate3); - $this->total_taxes += $tax; - $this->total_tax_map[] = ['name' => $this->invoice->tax_name3 . ' ' . $this->invoice->tax_rate3.'%', 'total' => $tax]; + if ($this->invoice->tax_rate3 > 0) { + $tax = $this->taxer($this->total, $this->invoice->tax_rate3); + $this->total_taxes += $tax; + $this->total_tax_map[] = ['name' => $this->invoice->tax_name3 . ' ' . $this->invoice->tax_rate3.'%', 'total' => $tax]; } return $this; - } + } - /** - * Calculates the balance. - * - * @return self The balance. - */ - private function calculateBalance() - { - //$this->invoice->balance = $this->balance($this->getTotal(), $this->invoice); - $this->setCalculatedAttributes(); + /** + * Calculates the balance. + * + * @return self The balance. + */ + private function calculateBalance() + { + //$this->invoice->balance = $this->balance($this->getTotal(), $this->invoice); + $this->setCalculatedAttributes(); - return $this; - } + return $this; + } - private function calculatePartial() - { - if ( !isset($this->invoice->id) && isset($this->invoice->partial) ) { + private function calculatePartial() + { + if (!isset($this->invoice->id) && isset($this->invoice->partial)) { $this->invoice->partial = max(0, min($this->formatValue($this->invoice->partial, 2), $this->invoice->balance)); } return $this; - } + } - private function calculateTotals() - { - $this->total += $this->total_taxes; + private function calculateTotals() + { + $this->total += $this->total_taxes; return $this; - } + } - public function getInvoice() - { - //Build invoice values here and return Invoice - $this->setCalculatedAttributes(); - $this->invoice->save(); - - return $this->invoice; - } + public function getInvoice() + { + //Build invoice values here and return Invoice + $this->setCalculatedAttributes(); + $this->invoice->save(); + + return $this->invoice; + } - /** - * Build $this->invoice variables after - * calculations have been performed. - */ - private function setCalculatedAttributes() - { - /* If amount != balance then some money has been paid on the invoice, need to subtract this difference from the total to set the new balance */ - if($this->invoice->amount != $this->invoice->balance) - { - $paid_to_date = $this->invoice->amount - $this->invoice->balance; + /** + * Build $this->invoice variables after + * calculations have been performed. + */ + private function setCalculatedAttributes() + { + /* If amount != balance then some money has been paid on the invoice, need to subtract this difference from the total to set the new balance */ + if ($this->invoice->amount != $this->invoice->balance) { + $paid_to_date = $this->invoice->amount - $this->invoice->balance; - $this->invoice->balance = $this->formatValue($this->getTotal(), $this->invoice->client->currency()->precision) - $paid_to_date; - } - else - $this->invoice->balance = $this->formatValue($this->getTotal(), $this->invoice->client->currency()->precision); + $this->invoice->balance = $this->formatValue($this->getTotal(), $this->invoice->client->currency()->precision) - $paid_to_date; + } else { + $this->invoice->balance = $this->formatValue($this->getTotal(), $this->invoice->client->currency()->precision); + } - /* Set new calculated total */ - $this->invoice->amount = $this->formatValue($this->getTotal(), $this->invoice->client->currency()->precision); + /* Set new calculated total */ + $this->invoice->amount = $this->formatValue($this->getTotal(), $this->invoice->client->currency()->precision); - $this->invoice->total_taxes = $this->getTotalTaxes(); + $this->invoice->total_taxes = $this->getTotalTaxes(); - return $this; - } + return $this; + } - public function getSubTotal() - { - return $this->sub_total; - } + public function getSubTotal() + { + return $this->sub_total; + } - public function setSubTotal($value) - { - $this->sub_total = $value; - return $this; - } + public function setSubTotal($value) + { + $this->sub_total = $value; + return $this; + } - public function getTotalDiscount() - { - return $this->total_discount; - } + public function getTotalDiscount() + { + return $this->total_discount; + } - public function getTotalTaxes() - { - return $this->total_taxes; - } + public function getTotalTaxes() + { + return $this->total_taxes; + } - public function getTotalTaxMap() - { - return $this->total_tax_map; - } + public function getTotalTaxMap() + { + return $this->total_tax_map; + } - public function getTotal() - { - return $this->total; - } + public function getTotal() + { + return $this->total; + } - public function setTaxMap() - { - if($this->invoice->is_amount_discount == true) - $this->invoice_items->calcTaxesWithAmountDiscount(); + public function setTaxMap() + { + if ($this->invoice->is_amount_discount == true) { + $this->invoice_items->calcTaxesWithAmountDiscount(); + } - $this->tax_map = collect(); + $this->tax_map = collect(); $keys = $this->invoice_items->getGroupedTaxes()->pluck('key')->unique(); $values = $this->invoice_items->getGroupedTaxes(); - foreach($keys as $key) - { - - $tax_name = $values->filter(function ($value, $k) use($key){ + foreach ($keys as $key) { + $tax_name = $values->filter(function ($value, $k) use ($key) { return $value['key'] == $key; })->pluck('tax_name')->first(); - $total_line_tax = $values->filter(function ($value, $k) use($key){ + $total_line_tax = $values->filter(function ($value, $k) use ($key) { return $value['key'] == $key; })->sum('total'); @@ -261,21 +255,20 @@ class InvoiceSum } return $this; - - } + } - public function getTaxMap() - { - return $this->tax_map; - } + public function getTaxMap() + { + return $this->tax_map; + } - public function getBalance() - { - return $this->invoice->balance; - } + public function getBalance() + { + return $this->invoice->balance; + } - public function getItemTotalTaxes() - { - return $this->getTotalTaxes(); - } -} \ No newline at end of file + public function getItemTotalTaxes() + { + return $this->getTotalTaxes(); + } +} diff --git a/app/Helpers/Invoice/InvoiceSumInclusive.php b/app/Helpers/Invoice/InvoiceSumInclusive.php index 56c31c32d35e..1c3965491824 100644 --- a/app/Helpers/Invoice/InvoiceSumInclusive.php +++ b/app/Helpers/Invoice/InvoiceSumInclusive.php @@ -22,88 +22,86 @@ use Illuminate\Support\Collection; class InvoiceSumInclusive { - use Taxer; - use Balancer; - use CustomValuer; - use Discounter; + use Taxer; + use Balancer; + use CustomValuer; + use Discounter; - use NumberFormatter; + use NumberFormatter; - protected $invoice; + protected $invoice; - public $tax_map; + public $tax_map; - public $invoice_item; + public $invoice_item; - public $total_taxes; + public $total_taxes; - private $total; + private $total; - private $total_discount; + private $total_discount; - private $total_custom_values; + private $total_custom_values; - private $total_tax_map; + private $total_tax_map; - private $sub_total; - /** - * Constructs the object with Invoice and Settings object - * - * @param \App\Models\Invoice $invoice The invoice - */ - public function __construct($invoice) - { - - $this->invoice = $invoice; + private $sub_total; + /** + * Constructs the object with Invoice and Settings object + * + * @param \App\Models\Invoice $invoice The invoice + */ + public function __construct($invoice) + { + $this->invoice = $invoice; - $this->tax_map = new Collection; + $this->tax_map = new Collection; + } - } - - public function build() - { - $this->calculateLineItems() - ->calculateDiscount() - ->calculateCustomValues() - ->calculateInvoiceTaxes() - ->setTaxMap() + public function build() + { + $this->calculateLineItems() + ->calculateDiscount() + ->calculateCustomValues() + ->calculateInvoiceTaxes() + ->setTaxMap() // ->calculateTotals() - ->calculateBalance() - ->calculatePartial(); + ->calculateBalance() + ->calculatePartial(); - return $this; - } + return $this; + } - private function calculateLineItems() - { - $this->invoice_items = new InvoiceItemSumInclusive($this->invoice); - $this->invoice_items->process(); - $this->invoice->line_items = $this->invoice_items->getLineItems(); - $this->total = $this->invoice_items->getSubTotal(); - $this->setSubTotal($this->invoice_items->getSubTotal()); + private function calculateLineItems() + { + $this->invoice_items = new InvoiceItemSumInclusive($this->invoice); + $this->invoice_items->process(); + $this->invoice->line_items = $this->invoice_items->getLineItems(); + $this->total = $this->invoice_items->getSubTotal(); + $this->setSubTotal($this->invoice_items->getSubTotal()); - return $this; - } + return $this; + } - private function calculateDiscount() - { - $this->total_discount = $this->discount($this->invoice_items->getSubTotal()); + private function calculateDiscount() + { + $this->total_discount = $this->discount($this->invoice_items->getSubTotal()); - $this->total -= $this->total_discount; + $this->total -= $this->total_discount; - return $this; - } + return $this; + } - private function calculateCustomValues() - { - $this->total_taxes += $this->valuerTax($this->invoice->custom_surcharge1, $this->invoice->custom_surcharge_taxes1); + private function calculateCustomValues() + { + $this->total_taxes += $this->valuerTax($this->invoice->custom_surcharge1, $this->invoice->custom_surcharge_taxes1); $this->total_custom_values += $this->valuer($this->invoice->custom_surcharge1); - $this->total_taxes += $this->valuerTax($this->invoice->custom_surcharge2, $this->invoice->custom_surcharge_taxes2); + $this->total_taxes += $this->valuerTax($this->invoice->custom_surcharge2, $this->invoice->custom_surcharge_taxes2); $this->total_custom_values += $this->valuer($this->invoice->custom_surcharge2); - $this->total_taxes += $this->valuerTax($this->invoice->custom_surcharge3, $this->invoice->custom_surcharge_taxes3); + $this->total_taxes += $this->valuerTax($this->invoice->custom_surcharge3, $this->invoice->custom_surcharge_taxes3); $this->total_custom_values += $this->valuer($this->invoice->custom_surcharge3); $this->total_taxes += $this->valuerTax($this->invoice->custom_surcharge4, $this->invoice->custom_surcharge_taxes4); @@ -112,156 +110,154 @@ class InvoiceSumInclusive $this->total += $this->total_custom_values; return $this; - } + } - private function calculateInvoiceTaxes() - { - $amount = $this->total; + private function calculateInvoiceTaxes() + { + $amount = $this->total; - if($this->invoice->discount > 0 && $this->invoice->is_amount_discount) - $amount = $this->formatValue(($this->sub_total - $this->invoice->discount),2); + if ($this->invoice->discount > 0 && $this->invoice->is_amount_discount) { + $amount = $this->formatValue(($this->sub_total - $this->invoice->discount), 2); + } - if($this->invoice->discount > 0 && !$this->invoice->is_amount_discount) - $amount = $this->formatValue(($this->sub_total - ($this->sub_total * ($this->invoice->discount/100))),2); + if ($this->invoice->discount > 0 && !$this->invoice->is_amount_discount) { + $amount = $this->formatValue(($this->sub_total - ($this->sub_total * ($this->invoice->discount/100))), 2); + } - if($this->invoice->tax_rate1 > 0){ - $tax = $this->calcInclusiveLineTax($this->invoice->tax_rate1, $amount); - $this->total_taxes += $tax; - - $this->total_tax_map[] = ['name' => $this->invoice->tax_name1 . ' ' . $this->invoice->tax_rate1.'%', 'total' => $tax]; + if ($this->invoice->tax_rate1 > 0) { + $tax = $this->calcInclusiveLineTax($this->invoice->tax_rate1, $amount); + $this->total_taxes += $tax; + $this->total_tax_map[] = ['name' => $this->invoice->tax_name1 . ' ' . $this->invoice->tax_rate1.'%', 'total' => $tax]; } - if($this->invoice->tax_rate2 > 0){ - $tax = $this->calcInclusiveLineTax($this->invoice->tax_rate2, $amount); - $this->total_taxes += $tax; - $this->total_tax_map[] = ['name' => $this->invoice->tax_name2. ' ' . $this->invoice->tax_rate2.'%', 'total' => $tax]; - + if ($this->invoice->tax_rate2 > 0) { + $tax = $this->calcInclusiveLineTax($this->invoice->tax_rate2, $amount); + $this->total_taxes += $tax; + $this->total_tax_map[] = ['name' => $this->invoice->tax_name2. ' ' . $this->invoice->tax_rate2.'%', 'total' => $tax]; } - if($this->invoice->tax_rate3 > 0){ - $tax = $this->calcInclusiveLineTax($this->invoice->tax_rate3, $amount); - $this->total_taxes += $tax; - $this->total_tax_map[] = ['name' => $this->invoice->tax_name3 . ' ' . $this->invoice->tax_rate3.'%', 'total' => $tax]; + if ($this->invoice->tax_rate3 > 0) { + $tax = $this->calcInclusiveLineTax($this->invoice->tax_rate3, $amount); + $this->total_taxes += $tax; + $this->total_tax_map[] = ['name' => $this->invoice->tax_name3 . ' ' . $this->invoice->tax_rate3.'%', 'total' => $tax]; } return $this; - } + } - /** - * Calculates the balance. - * - * @return self The balance. - */ - private function calculateBalance() - { - //$this->invoice->balance = $this->balance($this->getTotal(), $this->invoice); - $this->setCalculatedAttributes(); + /** + * Calculates the balance. + * + * @return self The balance. + */ + private function calculateBalance() + { + //$this->invoice->balance = $this->balance($this->getTotal(), $this->invoice); + $this->setCalculatedAttributes(); - return $this; - } + return $this; + } - private function calculatePartial() - { - if ( !isset($this->invoice->id) && isset($this->invoice->partial) ) { + private function calculatePartial() + { + if (!isset($this->invoice->id) && isset($this->invoice->partial)) { $this->invoice->partial = max(0, min($this->formatValue($this->invoice->partial, 2), $this->invoice->balance)); } return $this; - } + } - private function calculateTotals() - { - $this->total += $this->total_taxes; + private function calculateTotals() + { + $this->total += $this->total_taxes; return $this; - } + } - public function getInvoice() - { - //Build invoice values here and return Invoice - $this->setCalculatedAttributes(); - $this->invoice->save(); - - return $this->invoice; - } + public function getInvoice() + { + //Build invoice values here and return Invoice + $this->setCalculatedAttributes(); + $this->invoice->save(); + + return $this->invoice; + } - /** - * Build $this->invoice variables after - * calculations have been performed. - */ - private function setCalculatedAttributes() - { - /* If amount != balance then some money has been paid on the invoice, need to subtract this difference from the total to set the new balance */ - if($this->invoice->amount != $this->invoice->balance) - { - $paid_to_date = $this->invoice->amount - $this->invoice->balance; + /** + * Build $this->invoice variables after + * calculations have been performed. + */ + private function setCalculatedAttributes() + { + /* If amount != balance then some money has been paid on the invoice, need to subtract this difference from the total to set the new balance */ + if ($this->invoice->amount != $this->invoice->balance) { + $paid_to_date = $this->invoice->amount - $this->invoice->balance; - $this->invoice->balance = $this->formatValue($this->getTotal(), $this->invoice->client->currency()->precision) - $paid_to_date; - } - else - $this->invoice->balance = $this->formatValue($this->getTotal(), $this->invoice->client->currency()->precision); + $this->invoice->balance = $this->formatValue($this->getTotal(), $this->invoice->client->currency()->precision) - $paid_to_date; + } else { + $this->invoice->balance = $this->formatValue($this->getTotal(), $this->invoice->client->currency()->precision); + } - /* Set new calculated total */ - $this->invoice->amount = $this->formatValue($this->getTotal(), $this->invoice->client->currency()->precision); + /* Set new calculated total */ + $this->invoice->amount = $this->formatValue($this->getTotal(), $this->invoice->client->currency()->precision); - $this->invoice->total_taxes = $this->getTotalTaxes(); + $this->invoice->total_taxes = $this->getTotalTaxes(); - return $this; - } + return $this; + } - public function getSubTotal() - { - return $this->sub_total; - } + public function getSubTotal() + { + return $this->sub_total; + } - public function setSubTotal($value) - { - $this->sub_total = $value; - return $this; - } + public function setSubTotal($value) + { + $this->sub_total = $value; + return $this; + } - public function getTotalDiscount() - { - return $this->total_discount; - } + public function getTotalDiscount() + { + return $this->total_discount; + } - public function getTotalTaxes() - { - return $this->total_taxes; - } + public function getTotalTaxes() + { + return $this->total_taxes; + } - public function getTotalTaxMap() - { - return $this->total_tax_map; - } + public function getTotalTaxMap() + { + return $this->total_tax_map; + } - public function getTotal() - { - return $this->total; - } + public function getTotal() + { + return $this->total; + } - public function setTaxMap() - { - if($this->invoice->is_amount_discount == true) - $this->invoice_items->calcTaxesWithAmountDiscount(); + public function setTaxMap() + { + if ($this->invoice->is_amount_discount == true) { + $this->invoice_items->calcTaxesWithAmountDiscount(); + } - $this->tax_map = collect(); + $this->tax_map = collect(); $keys = $this->invoice_items->getGroupedTaxes()->pluck('key')->unique(); $values = $this->invoice_items->getGroupedTaxes(); - foreach($keys as $key) - { - - $tax_name = $values->filter(function ($value, $k) use($key){ + foreach ($keys as $key) { + $tax_name = $values->filter(function ($value, $k) use ($key) { return $value['key'] == $key; })->pluck('tax_name')->first(); - $total_line_tax = $values->filter(function ($value, $k) use($key){ + $total_line_tax = $values->filter(function ($value, $k) use ($key) { return $value['key'] == $key; })->sum('total'); @@ -273,23 +269,20 @@ class InvoiceSumInclusive } return $this; - - } + } - public function getTaxMap() - { - return $this->tax_map; - } + public function getTaxMap() + { + return $this->tax_map; + } - public function getBalance() - { - return $this->invoice->balance; - } + public function getBalance() + { + return $this->invoice->balance; + } - public function getItemTotalTaxes() - { - return $this->getTotalTaxes(); - } - - -} \ No newline at end of file + public function getItemTotalTaxes() + { + return $this->getTotalTaxes(); + } +} diff --git a/app/Helpers/Invoice/Taxer.php b/app/Helpers/Invoice/Taxer.php index f95296318b81..0433f6c6a175 100644 --- a/app/Helpers/Invoice/Taxer.php +++ b/app/Helpers/Invoice/Taxer.php @@ -16,21 +16,18 @@ namespace App\Helpers\Invoice; */ trait Taxer { + public function taxer($amount, $tax_rate) + { + return round($amount * (($tax_rate ? $tax_rate : 0) / 100), 2); + } - public function taxer($amount, $tax_rate) - { - return round($amount * (($tax_rate ? $tax_rate : 0) / 100), 2); - } - - public function calcAmountLineTax($tax_rate, $amount) - { - return $this->formatValue(($amount * $tax_rate/100), 2); - } - - public function calcInclusiveLineTax($tax_rate, $amount) - { - return $this->formatValue($amount - ($amount / (1 + ($tax_rate/100))), 2); - } - + public function calcAmountLineTax($tax_rate, $amount) + { + return $this->formatValue(($amount * $tax_rate/100), 2); + } + public function calcInclusiveLineTax($tax_rate, $amount) + { + return $this->formatValue($amount - ($amount / (1 + ($tax_rate/100))), 2); + } } diff --git a/app/Helpers/Mail/GmailTransport.php b/app/Helpers/Mail/GmailTransport.php index 8d2875112063..df53d578b776 100644 --- a/app/Helpers/Mail/GmailTransport.php +++ b/app/Helpers/Mail/GmailTransport.php @@ -66,4 +66,4 @@ class GmailTransport extends Transport return $this->numberOfRecipients($message); } -} \ No newline at end of file +} diff --git a/app/Helpers/Mail/GmailTransportConfig.php b/app/Helpers/Mail/GmailTransportConfig.php index 119d374582e5..944f7759f62e 100644 --- a/app/Helpers/Mail/GmailTransportConfig.php +++ b/app/Helpers/Mail/GmailTransportConfig.php @@ -24,13 +24,12 @@ use Laravel\Socialite\Facades\Socialite; */ class GmailTransportConfig { - public function test() { -/********************* We may need to fetch a new token on behalf of the client ******************************/ - $query = [ - 'email' => 'david@invoiceninja.com', - ]; + /********************* We may need to fetch a new token on behalf of the client ******************************/ + $query = [ + 'email' => 'david@invoiceninja.com', + ]; $user = MultiDB::hasUser($query); // $oauth_user = Socialite::driver('google')->stateless()->userFromToken($user->oauth_user_token); @@ -38,25 +37,12 @@ class GmailTransportConfig // $user->oauth_user_token = $oauth_user->refreshToken; // $user->save(); - Config::set('mail.driver', 'gmail'); - Config::set('services.gmail.token', $user->oauth_user_token); - (new MailServiceProvider(app()))->register(); + Config::set('mail.driver', 'gmail'); + Config::set('services.gmail.token', $user->oauth_user_token); + (new MailServiceProvider(app()))->register(); - Mail::to('david@romulus.com.au') - ->send(new SupportMessageSent('a cool message')); + Mail::to('david@romulus.com.au') + ->send(new SupportMessageSent('a cool message')); } - - } - - - - - - - - - - - diff --git a/app/Helpers/Mail/GmailTransportManager.php b/app/Helpers/Mail/GmailTransportManager.php index d6fed2d2fb8d..357e697f4adf 100644 --- a/app/Helpers/Mail/GmailTransportManager.php +++ b/app/Helpers/Mail/GmailTransportManager.php @@ -15,5 +15,4 @@ class GmailTransportManager extends TransportManager return new GmailTransport($mail, $token); } - -} \ No newline at end of file +} diff --git a/app/Helpers/TranslationHelper.php b/app/Helpers/TranslationHelper.php index 281836d0d0b0..b81286f850b7 100644 --- a/app/Helpers/TranslationHelper.php +++ b/app/Helpers/TranslationHelper.php @@ -16,14 +16,13 @@ use Illuminate\Support\Facades\Cache; * falls back on defaults if no string exists * * //Cache::forever($custom_company_translated_string, 'mogly'); - * + * * @param string translation string key * @return string */ function ctrans(string $string, $replace = [], $locale = null) : string { - //todo pass through the cached version of the custom strings here else return trans(); - + //todo pass through the cached version of the custom strings here else return trans(); + return trans($string, $replace, $locale); - -} \ No newline at end of file +} diff --git a/app/Http/Controllers/AccountController.php b/app/Http/Controllers/AccountController.php index bd47e4e7e814..6dbed0708b58 100644 --- a/app/Http/Controllers/AccountController.php +++ b/app/Http/Controllers/AccountController.php @@ -43,8 +43,7 @@ class AccountController extends BaseController */ public function index() { - // return view('signup.index'); - + // return view('signup.index'); } /** @@ -113,7 +112,7 @@ class AccountController extends BaseController * property="privacy_policy", * description="The user accepted the privacy policy", * type="boolean", - * ), + * ), * @OA\Property( * property="password", * example="1234567", @@ -138,7 +137,7 @@ class AccountController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -146,13 +145,11 @@ class AccountController extends BaseController */ public function store(CreateAccountRequest $request) { - $account = CreateAccount::dispatchNow($request->all()); $ct = CompanyUser::whereUserId(auth()->user()->id); return $this->listResponse($ct); - } /** diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php index e9f0e58056e6..9d769fc14233 100644 --- a/app/Http/Controllers/ActivityController.php +++ b/app/Http/Controllers/ActivityController.php @@ -11,14 +11,12 @@ namespace App\Http\Controllers; - use App\Models\Activity; use App\Transformers\ActivityTransformer; use Illuminate\Http\Request; class ActivityController extends BaseController { - protected $entity_type = Activity::class; protected $entity_transformer = ActivityTransformer::class; @@ -66,7 +64,7 @@ class ActivityController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -83,5 +81,4 @@ class ActivityController extends BaseController return $this->listResponse($activities); } - -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Auth/ContactForgotPasswordController.php b/app/Http/Controllers/Auth/ContactForgotPasswordController.php index 7cfce622c6e6..90f0cdf3482d 100644 --- a/app/Http/Controllers/Auth/ContactForgotPasswordController.php +++ b/app/Http/Controllers/Auth/ContactForgotPasswordController.php @@ -41,13 +41,14 @@ class ContactForgotPasswordController extends Controller $this->middleware('guest:contact'); } - /** - * Show the reset email form. - * - * @return \Illuminate\Http\Response - */ - public function showLinkRequestForm(){ - return view('portal.default.auth.passwords.email',[ + /** + * Show the reset email form. + * + * @return \Illuminate\Http\Response + */ + public function showLinkRequestForm() + { + return view('portal.default.auth.passwords.email', [ 'title' => 'Client Password Reset', 'passwordEmailRoute' => 'client.password.email' ]); @@ -60,6 +61,6 @@ class ContactForgotPasswordController extends Controller public function broker() { - return Password::broker('contacts'); + return Password::broker('contacts'); } } diff --git a/app/Http/Controllers/Auth/ContactLoginController.php b/app/Http/Controllers/Auth/ContactLoginController.php index 10af2c12bd73..7031ad6b4dfa 100644 --- a/app/Http/Controllers/Auth/ContactLoginController.php +++ b/app/Http/Controllers/Auth/ContactLoginController.php @@ -20,7 +20,6 @@ use Route; class ContactLoginController extends Controller { - use AuthenticatesUsers; protected $redirectTo = '/client/dashboard'; @@ -32,9 +31,7 @@ class ContactLoginController extends Controller public function showLoginForm() { - - return view('portal.default.auth.login'); - + return view('portal.default.auth.login'); } @@ -63,20 +60,19 @@ class ContactLoginController extends Controller public function authenticated(Request $request, ClientContact $client) { - Auth::guard('contact')->login($client, true); - if(session()->get('url.intended')) + if (session()->get('url.intended')) { return redirect(session()->get('url.intended')); + } return redirect(route('client.dashboard')); } public function logout() { - Auth::guard('contact')->logout(); return redirect('/client/login'); } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Auth/ContactResetPasswordController.php b/app/Http/Controllers/Auth/ContactResetPasswordController.php index 87c3052ab056..58f24959016f 100644 --- a/app/Http/Controllers/Auth/ContactResetPasswordController.php +++ b/app/Http/Controllers/Auth/ContactResetPasswordController.php @@ -72,6 +72,6 @@ class ContactResetPasswordController extends Controller public function broker() { - return Password::broker('contacts'); + return Password::broker('contacts'); } } diff --git a/app/Http/Controllers/Auth/ForgotPasswordController.php b/app/Http/Controllers/Auth/ForgotPasswordController.php index c7493a5b0da4..eed1e59839f4 100644 --- a/app/Http/Controllers/Auth/ForgotPasswordController.php +++ b/app/Http/Controllers/Auth/ForgotPasswordController.php @@ -44,7 +44,7 @@ class ForgotPasswordController extends Controller /** * Password Reset * - * + * * @OA\Post( * path="/api/v1/reset_password", * operationId="reset_password", @@ -93,7 +93,7 @@ class ForgotPasswordController extends Controller * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -115,5 +115,4 @@ class ForgotPasswordController extends Controller ? response()->json(['message' => 'Reset link sent to your email.', 'status' => true], 201) : response()->json(['message' => 'Email not found', 'status' => false], 401); } - } diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index 437533d524e2..123f7c9e3793 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -40,16 +40,16 @@ 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; @@ -72,9 +72,7 @@ class LoginController extends BaseController */ public function __construct() { - parent::__construct(); - } /** @@ -97,7 +95,7 @@ class LoginController extends BaseController * * @return Response|User Process user login. * - * + * * @OA\Post( * path="/api/v1/login", * operationId="postLogin", @@ -146,7 +144,7 @@ class LoginController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -170,17 +168,13 @@ class LoginController extends BaseController } if ($this->attemptLogin($request)) { - $user = $this->guard()->user(); $user->setCompany($user->company_user->account->default_company); $ct = CompanyUser::whereUserId($user->id); return $this->listResponse($ct); - - } - else { - + } else { $this->incrementLoginAttempts($request); return response() @@ -188,15 +182,14 @@ class LoginController extends BaseController ->header('X-App-Version', config('ninja.app_version')) ->header('X-Api-Version', config('ninja.api_version')); } - } /** * Refreshes the data feed with the current Company User - * + * * @return CompanyUser Refresh Feed. * - * + * * @OA\Post( * path="/api/v1/refresh", * operationId="refresh", @@ -224,7 +217,7 @@ class LoginController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -233,8 +226,8 @@ class LoginController extends BaseController */ public function refresh(Request $request) { - $ct = CompanyUser::whereUserId(auth()->user()->id); - return $this->listResponse($ct); + $ct = CompanyUser::whereUserId(auth()->user()->id); + return $this->listResponse($ct); } /** @@ -242,28 +235,27 @@ class LoginController extends BaseController * * @return void */ - public function redirectToProvider(string $provider) + public function redirectToProvider(string $provider) { //'https://www.googleapis.com/auth/gmail.send','email','profile','openid' // - if(request()->has('code')) + if (request()->has('code')) { return $this->handleProviderCallback($provider); - else + } else { return Socialite::driver($provider)->scopes('https://www.googleapis.com/auth/gmail.send')->redirect(); + } } public function redirectToProviderAndCreate(string $provider) { - $redirect_url = config('services.' . $provider . '.redirect') . '/create'; - if(request()->has('code')) + if (request()->has('code')) { return $this->handleProviderCallbackAndCreate($provider); - else + } else { return Socialite::driver($provider)->scopes('https://www.googleapis.com/auth/gmail.send')->redirectUrl($redirect_url)->redirect(); - - + } } @@ -278,23 +270,20 @@ class LoginController extends BaseController ->user(); /* Handle existing users who attempt to create another account with existing OAuth credentials */ - if($user = OAuth::handleAuth($socialite_user, $provider)) - { + if ($user = OAuth::handleAuth($socialite_user, $provider)) { $user->oauth_user_token = $socialite_user->refreshToken; $user->save(); Auth::login($user, true); return redirect($this->redirectTo); - } - else if(MultiDB::checkUserEmailExists($socialite_user->getEmail())) - { + } elseif (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'); - } + } /** 3. Automagically creating a new account here. */ else { - //todo + //todo $name = OAuth::splitName($socialite_user->getName()); $new_account = [ @@ -317,17 +306,15 @@ class LoginController extends BaseController return redirect($this->redirectTo)->withCookie($cookie); } - } /** * We use this function when OAUTHING via the web interface - * - * @return redirect + * + * @return redirect */ - public function handleProviderCallback(string $provider) + public function handleProviderCallback(string $provider) { - $redirect_url = config('services.' . $provider . '.redirect'); $socialite_user = Socialite::driver($provider) @@ -335,23 +322,20 @@ class LoginController extends BaseController ->stateless() ->user(); - if($user = OAuth::handleAuth($socialite_user, $provider)) - { + if ($user = OAuth::handleAuth($socialite_user, $provider)) { $user->oauth_user_token = $socialite_user->token; $user->save(); Auth::login($user, true); return redirect($this->redirectTo); - } - else if(MultiDB::checkUserEmailExists($socialite_user->getEmail())) - { + } elseif (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'); - } + } /** 3. Automagically creating a new account here. */ else { - //todo + //todo $name = OAuth::splitName($socialite_user->getName()); $new_account = [ @@ -372,25 +356,22 @@ class LoginController extends BaseController return redirect($this->redirectTo)->withCookie($cookie); } - - } /** - * A client side authentication has taken place. + * A client side authentication has taken place. * We now digest the token and confirm authentication with * the authentication server, the correct user object * is returned to us here and we send back the correct * user object payload - or error. * - * This can be extended to a create route also - need to pass a ?create query parameter and + * This can be extended to a create route also - need to pass a ?create query parameter and * then process the signup - * + * * return User $user */ public function oauthApiLogin() { - $user = false; $oauth = new OAuth(); @@ -400,12 +381,9 @@ class LoginController extends BaseController if ($user) { $ct = CompanyUser::whereUserId($user); return $this->listResponse($ct); - // return $this->itemResponse($user); - } - else + // return $this->itemResponse($user); + } else { return $this->errorResponse(['message' => 'Invalid credentials'], 401); - + } } - - } diff --git a/app/Http/Controllers/BaseController.php b/app/Http/Controllers/BaseController.php index da0f59a9021a..3cc4aa63c76c 100644 --- a/app/Http/Controllers/BaseController.php +++ b/app/Http/Controllers/BaseController.php @@ -33,9 +33,9 @@ class BaseController extends Controller /** * Passed from the parent when we need to force - * includes internally rather than externally via + * includes internally rather than externally via * the $_REQUEST 'include' variable. - * + * * @var array */ public $forced_includes; @@ -54,28 +54,23 @@ class BaseController extends Controller protected $manager; - public function __construct() + public function __construct() { - $this->manager = new Manager(); $this->forced_includes = []; $this->forced_index = 'data'; - } private function buildManager() { $include = ''; - if(request()->has('first_load') && request()->input('first_load') == 'true') - { + if (request()->has('first_load') && request()->input('first_load') == 'true') { /* For very large accounts, we reduce the includes automatically */ - if(auth()->user()->getCompany()->clients->count() > 1000) - { - + if (auth()->user()->getCompany()->clients->count() > 1000) { $include = [ 'account', 'user.company_user', @@ -91,11 +86,7 @@ class BaseController extends Controller 'company.payments', 'company.quotes', ]; - - } - else - { - + } else { $include = [ 'account', 'user.company_user', @@ -111,84 +102,59 @@ class BaseController extends Controller // 'company.payments', // 'company.quotes', ]; - } $include = array_merge($this->forced_includes, $include); $include = implode(",", $include); - - } - else if(request()->input('include') !== null) - { - + } elseif (request()->input('include') !== null) { $request_include = explode(",", request()->input('include')); $include = array_merge($this->forced_includes, $request_include); $include = implode(",", $include); - - } - else if(count($this->forced_includes) >= 1) - { - + } elseif (count($this->forced_includes) >= 1) { $include = implode(",", $this->forced_includes); - } $this->manager->parseIncludes($include); $this->serializer = request()->input('serializer') ?: EntityTransformer::API_SERIALIZER_ARRAY; - if ($this->serializer === EntityTransformer::API_SERIALIZER_JSON) - { - + if ($this->serializer === EntityTransformer::API_SERIALIZER_JSON) { $this->manager->setSerializer(new JsonApiSerializer()); - - } - else - { - + } else { $this->manager->setSerializer(new ArraySerializer()); - } - } /** - * Catch all fallback route + * Catch all fallback route * for non-existant route */ public function notFound() { - return response()->json(['message' => '404 | Nothing to see here!'], 404) ->header('X-API-VERSION', config('ninja.api_version')) ->header('X-APP-VERSION', config('ninja.app_version')); - } public function notFoundClient() { - return abort(404); - } protected function errorResponse($response, $httpErrorCode = 400) { - $error['error'] = $response; $error = json_encode($error, JSON_PRETTY_PRINT); $headers = self::getApiHeaders(); return response()->make($error, $httpErrorCode, $headers); - } - protected function listResponse($query) + protected function listResponse($query) { - $this->buildManager(); $transformer = new $this->entity_transformer(Input::get('serializer')); @@ -199,16 +165,12 @@ class BaseController extends Controller $query->with($includes); - if (auth()->user()->cannot('view_'.$this->entity_type)) - { - - if($this->entity_type == Company::class){ + if (auth()->user()->cannot('view_'.$this->entity_type)) { + if ($this->entity_type == Company::class) { //no user keys exist on the company table, so we need to skip - } - else if ($this->entity_type == User::class) { + } elseif ($this->entity_type == User::class) { $query->where('id', '=', auth()->user()->id); - } - else { + } else { $query->where('user_id', '=', auth()->user()->id); } } @@ -216,12 +178,10 @@ class BaseController extends Controller $data = $this->createCollection($query, $transformer, $this->entity_type); return $this->response($data); - } protected function createCollection($query, $transformer, $entity_type) { - $this->buildManager(); if ($this->serializer && $this->serializer != EntityTransformer::API_SERIALIZER_JSON) { @@ -240,12 +200,10 @@ class BaseController extends Controller } return $this->manager->createData($resource)->toArray(); - } protected function response($response) { - $index = request()->input('index') ?: $this->forced_index; if ($index == 'none') { @@ -261,9 +219,9 @@ class BaseController extends Controller unset($response[$index]['meta']); } - if(request()->include_static) + if (request()->include_static) { $response['static'] = Statics::company(auth()->user()->getCompany()->getLocale()); - + } } ksort($response); @@ -273,42 +231,38 @@ class BaseController extends Controller return response()->make($response, 200, $headers); - } protected function itemResponse($item) { - $this->buildManager(); $transformer = new $this->entity_transformer(Input::get('serializer')); $data = $this->createItem($item, $transformer, $this->entity_type); - if(request()->include_static) + if (request()->include_static) { $data['static'] = Statics::company(auth()->user()->getCompany()->getLocale()); + } return $this->response($data); - } protected function createItem($data, $transformer, $entity_type) { - - if ($this->serializer && $this->serializer != EntityTransformer::API_SERIALIZER_JSON) + if ($this->serializer && $this->serializer != EntityTransformer::API_SERIALIZER_JSON) { $entity_type = null; + } $resource = new Item($data, $transformer, $entity_type); return $this->manager->createData($resource)->toArray(); - } public static function getApiHeaders($count = 0) { - return [ 'Content-Type' => 'application/json', //'Access-Control-Allow-Origin' => '*', @@ -322,12 +276,10 @@ class BaseController extends Controller //'X-Rate-Limit-Remaining' - The number of remaining requests in the current period //'X-Rate-Limit-Reset' - The number of seconds left in the current period, ]; - } protected function getRequestIncludes($data) { - $included = request()->input('include'); $included = explode(',', $included); @@ -341,5 +293,4 @@ class BaseController extends Controller return $data; } - -} \ No newline at end of file +} diff --git a/app/Http/Controllers/ClientController.php b/app/Http/Controllers/ClientController.php index 681a77697d43..a66285f6a4ab 100644 --- a/app/Http/Controllers/ClientController.php +++ b/app/Http/Controllers/ClientController.php @@ -70,7 +70,6 @@ class ClientController extends BaseController parent::__construct(); $this->client_repo = $client_repo; - } /** @@ -111,11 +110,9 @@ class ClientController extends BaseController */ public function index(ClientFilters $filters) { - $clients = Client::filter($filters); return $this->listResponse($clients); - } /** @@ -170,9 +167,7 @@ class ClientController extends BaseController */ public function show(ShowClientRequest $request, Client $client) { - return $this->itemResponse($client); - } /** @@ -227,9 +222,7 @@ class ClientController extends BaseController */ public function edit(EditClientRequest $request, Client $client) { - return $this->itemResponse($client); - } /** @@ -286,13 +279,14 @@ class ClientController extends BaseController */ public function update(UpdateClientRequest $request, Client $client) { + if($request->entityIsDeleted($client)) + return $request->disallowUpdate(); $client = $this->client_repo->save($request->all(), $client); $this->uploadLogo($request->file('company_logo'), $client->company, $client); return $this->itemResponse($client->fresh()); - } /** @@ -336,11 +330,9 @@ class ClientController extends BaseController */ public function create(CreateClientRequest $request) { - $client = ClientFactory::create(auth()->user()->company()->id, auth()->user()->id); return $this->itemResponse($client); - } /** @@ -385,7 +377,6 @@ class ClientController extends BaseController */ public function store(StoreClientRequest $request) { - $client = $this->client_repo->save($request->all(), ClientFactory::create(auth()->user()->company()->id, auth()->user()->id)); $client->load('contacts', 'primary_contact'); @@ -393,7 +384,6 @@ class ClientController extends BaseController $this->uploadLogo($request->file('company_logo'), $client->company, $client); return $this->itemResponse($client); - } /** @@ -507,15 +497,15 @@ class ClientController extends BaseController */ public function bulk() { - $action = request()->input('action'); $ids = request()->input('ids'); $clients = Client::withTrashed()->find($this->transformKeys($ids)); - $clients->each(function ($client, $key) use($action){ - if(auth()->user()->can('edit', $client)) + $clients->each(function ($client, $key) use ($action) { + if (auth()->user()->can('edit', $client)) { $this->client_repo->{$action}($client); + } }); return $this->listResponse(Client::withTrashed()->whereIn('id', $this->transformKeys($ids))); @@ -530,5 +520,4 @@ class ClientController extends BaseController { //todo } - } diff --git a/app/Http/Controllers/ClientPortal/DocumentController.php b/app/Http/Controllers/ClientPortal/DocumentController.php index d0e295d9b990..43e86afc5afd 100644 --- a/app/Http/Controllers/ClientPortal/DocumentController.php +++ b/app/Http/Controllers/ClientPortal/DocumentController.php @@ -27,7 +27,6 @@ class DocumentController extends Controller */ public function index() { - } /** @@ -68,7 +67,7 @@ class DocumentController extends Controller '_token' => '7KoEVRjB2Fq8XBVFRUFbhQFjKm4rY9h0AGSlpdj3', 'is_avatar' => '1', 'q' => '/client/document', - 'file' => + 'file' => Illuminate\Http\UploadedFile::__set_state(array( 'test' => false, 'originalName' => 'family.jpg', @@ -76,7 +75,7 @@ class DocumentController extends Controller 'error' => 0, 'hashName' => NULL, )), - ) + ) */ } diff --git a/app/Http/Controllers/ClientPortal/InvitationController.php b/app/Http/Controllers/ClientPortal/InvitationController.php index 393df9b290fa..765f4793fa37 100644 --- a/app/Http/Controllers/ClientPortal/InvitationController.php +++ b/app/Http/Controllers/ClientPortal/InvitationController.php @@ -25,7 +25,6 @@ use Illuminate\Support\Facades\Auth; class InvitationController extends Controller { - use MakesHash; use MakesDates; @@ -36,26 +35,22 @@ class InvitationController extends Controller $invitation = $entity_obj::whereRaw("BINARY `key`= ?", [$invitation_key])->first(); - if($invitation){ - - if((bool)$invitation->contact->client->getSetting('enable_client_portal_password') !== false) + if ($invitation) { + if ((bool)$invitation->contact->client->getSetting('enable_client_portal_password') !== false) { $this->middleware('auth:contact'); - else + } else { auth()->guard('contact')->login($invitation->contact, false); + } $invitation->markViewed(); return redirect()->route('client.'.$entity.'.show', [$entity => $this->encodePrimaryKey($invitation->{$key})]); - - } - else - abort(404); - + } else { + abort(404); + } } public function routerForIframe(string $entity, string $client_hash, string $invitation_key) { - } - } diff --git a/app/Http/Controllers/ClientPortal/InvoiceController.php b/app/Http/Controllers/ClientPortal/InvoiceController.php index 0d6709d8707e..e47cb0236c09 100644 --- a/app/Http/Controllers/ClientPortal/InvoiceController.php +++ b/app/Http/Controllers/ClientPortal/InvoiceController.php @@ -36,7 +36,6 @@ use ZipStream\ZipStream; class InvoiceController extends Controller { - use MakesHash; use MakesDates; /** @@ -51,18 +50,17 @@ class InvoiceController extends Controller $invoices = Invoice::filter($filters)->with('client', 'client.country'); if (request()->ajax()) { - return DataTables::of($invoices)->addColumn('action', function ($invoice) { - return $this->buildClientButtons($invoice); - }) - ->addColumn('checkbox', function ($invoice){ + return $this->buildClientButtons($invoice); + }) + ->addColumn('checkbox', function ($invoice) { return ''; }) - ->editColumn('status_id', function ($invoice){ + ->editColumn('status_id', function ($invoice) { return Invoice::badgeForStatus($invoice->status); - })->editColumn('date', function ($invoice){ + })->editColumn('date', function ($invoice) { return $this->formatDate($invoice->date, $invoice->client->date_format()); - })->editColumn('due_date', function ($invoice){ + })->editColumn('due_date', function ($invoice) { return $this->formatDate($invoice->due_date, $invoice->client->date_format()); })->editColumn('balance', function ($invoice) { return Number::formatMoney($invoice->balance, $invoice->client); @@ -76,16 +74,15 @@ class InvoiceController extends Controller $data['html'] = $builder; return view('portal.default.invoices.index', $data); - } private function buildClientButtons($invoice) { $buttons = '
'; - if($invoice->isPayable()){ + if ($invoice->isPayable()) { $buttons .= ""; - // $buttons .= ''.ctrans('texts.pay_now').''; + // $buttons .= ''.ctrans('texts.pay_now').''; } $buttons .= ''.ctrans('texts.view').''; @@ -112,39 +109,38 @@ class InvoiceController extends Controller /** * Pay one or more invoices - * + * * @return View */ public function bulk() { + $transformed_ids = $this->transformKeys(explode(",", request()->input('hashed_ids'))); - $transformed_ids = $this->transformKeys(explode(",",request()->input('hashed_ids'))); - - if(request()->input('action') == 'payment') + if (request()->input('action') == 'payment') { return $this->makePayment($transformed_ids); - else if(request()->input('action') == 'download') + } elseif (request()->input('action') == 'download') { return $this->downloadInvoicePDF($transformed_ids); - + } } private function makePayment(array $ids) { - $invoices = Invoice::whereIn('id', $ids) ->whereClientId(auth()->user()->client->id) ->get(); - $total = $invoices->sum('balance'); + $total = $invoices->sum('balance'); - $invoices = $invoices->filter(function ($invoice){ + $invoices = $invoices->filter(function ($invoice) { return $invoice->isPayable(); }); - if($invoices->count() == 0) + if ($invoices->count() == 0) { return back()->with(['warning' => 'No payable invoices selected']); + } - $invoices->map(function ($invoice){ + $invoices->map(function ($invoice) { $invoice->balance = Number::formatMoney($invoice->balance, $invoice->client); $invoice->due_date = $this->formatDate($invoice->due_date, $invoice->client->date_format()); return $invoice; @@ -164,7 +160,6 @@ class InvoiceController extends Controller ]; return view('portal.default.invoices.payment', $data); - } private function downloadInvoicePDF(array $ids) @@ -174,12 +169,14 @@ class InvoiceController extends Controller ->get(); //generate pdf's of invoices locally - if(!$invoices || $invoices->count() == 0) + if (!$invoices || $invoices->count() == 0) { return; + } //if only 1 pdf, output to buffer for download - if($invoices->count() == 1) + if ($invoices->count() == 1) { return response()->download(public_path($invoices->first()->pdf_file_path())); + } # enable output of HTTP headers @@ -189,15 +186,11 @@ class InvoiceController extends Controller # create a new zipstream object $zip = new ZipStream(date('Y-m-d') . '_' . str_replace(' ', '_', trans('texts.invoices')).".zip", $options); - foreach($invoices as $invoice){ - - $zip->addFileFromPath(basename($invoice->pdf_file_path()), public_path($invoice->pdf_file_path())); - } + foreach ($invoices as $invoice) { + $zip->addFileFromPath(basename($invoice->pdf_file_path()), public_path($invoice->pdf_file_path())); + } # finish the zip stream $zip->finish(); - } - - } diff --git a/app/Http/Controllers/ClientPortal/PaymentController.php b/app/Http/Controllers/ClientPortal/PaymentController.php index e1a873898e9e..f109d1592047 100644 --- a/app/Http/Controllers/ClientPortal/PaymentController.php +++ b/app/Http/Controllers/ClientPortal/PaymentController.php @@ -32,7 +32,6 @@ use Yajra\DataTables\Html\Builder; class PaymentController extends Controller { - use MakesHash; use MakesDates; @@ -46,19 +45,18 @@ class PaymentController extends Controller public function index(PaymentFilters $filters, Builder $builder) { //$payments = Payment::filter($filters); - $payments = Payment::with('type','client'); + $payments = Payment::with('type', 'client'); if (request()->ajax()) { - return DataTables::of($payments)->addColumn('action', function ($payment) { - return ''.ctrans('texts.view').''; - })->editColumn('type_id', function ($payment) { - return $payment->type->name; - }) - ->editColumn('status_id', function ($payment){ + return ''.ctrans('texts.view').''; + })->editColumn('type_id', function ($payment) { + return $payment->type->name; + }) + ->editColumn('status_id', function ($payment) { return Payment::badgeForStatus($payment->status_id); }) - ->editColumn('date', function ($payment){ + ->editColumn('date', function ($payment) { //return $payment->date; return $payment->formatDate($payment->date, $payment->client->date_format()); }) @@ -67,13 +65,11 @@ class PaymentController extends Controller }) ->rawColumns(['action', 'status_id','type_id']) ->make(true); - } $data['html'] = $builder; return view('portal.default.payments.index', $data); - } /** @@ -90,7 +86,6 @@ class PaymentController extends Controller $data['payment'] = $payment; return view('portal.default.payments.show', $data); - } /** @@ -98,26 +93,26 @@ class PaymentController extends Controller * gateway and payment method. * The request will also contain the amount * and invoice ids for reference. - * - * @return void + * + * @return void */ public function process() { - - $invoices = Invoice::whereIn('id', $this->transformKeys(explode(",",request()->input('hashed_ids')))) + $invoices = Invoice::whereIn('id', $this->transformKeys(explode(",", request()->input('hashed_ids')))) ->whereClientId(auth()->user()->client->id) ->get(); - $amount = $invoices->sum('balance'); + $amount = $invoices->sum('balance'); - $invoices = $invoices->filter(function ($invoice){ + $invoices = $invoices->filter(function ($invoice) { return $invoice->isPayable(); }); - if($invoices->count() == 0) + if ($invoices->count() == 0) { return back()->with(['warning' => 'No payable invoices selected']); + } - $invoices->map(function ($invoice){ + $invoices->map(function ($invoice) { $invoice->balance = Number::formatMoney($invoice->balance, $invoice->client); $invoice->due_date = $this->formatDate($invoice->due_date, $invoice->client->date_format()); return $invoice; @@ -130,7 +125,7 @@ class PaymentController extends Controller $payment_method_id = request()->input('payment_method_id'); - //if there is a gateway fee, now is the time to calculate it + //if there is a gateway fee, now is the time to calculate it //and add it to the invoice $data = [ @@ -140,12 +135,11 @@ class PaymentController extends Controller 'amount_with_fee' => $amount + $gateway->calcGatewayFee($amount), 'token' => auth()->user()->client->gateway_token($gateway->id, $payment_method_id), 'payment_method_id' => $payment_method_id, - 'hashed_ids' => explode(",",request()->input('hashed_ids')), + 'hashed_ids' => explode(",", request()->input('hashed_ids')), ]; return $gateway->driver(auth()->user()->client)->processPaymentView($data); - } public function response(Request $request) @@ -153,7 +147,5 @@ class PaymentController extends Controller $gateway = CompanyGateway::find($request->input('company_gateway_id')); return $gateway->driver(auth()->user()->client)->processPaymentResponse($request); - } - } diff --git a/app/Http/Controllers/ClientPortal/PaymentHookController.php b/app/Http/Controllers/ClientPortal/PaymentHookController.php index abfac3b30dc8..d24add3e2a2c 100644 --- a/app/Http/Controllers/ClientPortal/PaymentHookController.php +++ b/app/Http/Controllers/ClientPortal/PaymentHookController.php @@ -17,14 +17,10 @@ use Illuminate\Http\Request; class PaymentHookController extends Controller { + public function process($company_gateway_id, $gateway_type_id) + { + $gateway = Gateway::find($company_gateway_id); - public function process($company_gateway_id, $gateway_type_id) - { - - $gateway = Gateway::find($company_gateway_id); - - dd(request()->input()); - - } - -} \ No newline at end of file + dd(request()->input()); + } +} diff --git a/app/Http/Controllers/ClientPortal/PaymentMethodController.php b/app/Http/Controllers/ClientPortal/PaymentMethodController.php index d0d409da841c..d0e151201005 100644 --- a/app/Http/Controllers/ClientPortal/PaymentMethodController.php +++ b/app/Http/Controllers/ClientPortal/PaymentMethodController.php @@ -36,7 +36,6 @@ class PaymentMethodController extends Controller $payment_methods->with('gateway_type'); if (request()->ajax()) { - return DataTables::of($payment_methods)->addColumn('action', function ($payment_method) { return '' . ctrans('texts.view') . ''; }) @@ -47,24 +46,26 @@ class PaymentMethodController extends Controller })->editColumn('is_default', function ($payment_method) { return $payment_method->is_default ? ctrans('texts.default') : ''; })->editColumn('meta', function ($payment_method) { - if (isset($payment_method->meta->exp_month) && isset($payment_method->meta->exp_year)) + if (isset($payment_method->meta->exp_month) && isset($payment_method->meta->exp_year)) { return "{$payment_method->meta->exp_month}/{$payment_method->meta->exp_year}"; - else + } else { return ""; + } })->addColumn('last4', function ($payment_method) { - if (isset($payment_method->meta->last4)) + if (isset($payment_method->meta->last4)) { return $payment_method->meta->last4; - else + } else { return ""; + } })->addColumn('brand', function ($payment_method) { - if (isset($payment_method->meta->brand)) + if (isset($payment_method->meta->brand)) { return $payment_method->meta->brand; - else + } else { return ""; + } }) ->rawColumns(['action', 'status_id', 'last4', 'brand']) ->make(true); - } $data['html'] = $builder; @@ -101,7 +102,6 @@ class PaymentMethodController extends Controller $gateway = auth()->user()->client->getCreditCardGateway(); return $gateway->driver(auth()->user()->client)->authorizeCreditCardResponse($request); - } /** diff --git a/app/Http/Controllers/ClientPortal/ProfileController.php b/app/Http/Controllers/ClientPortal/ProfileController.php index 79b0f44cf72f..189323d643c6 100644 --- a/app/Http/Controllers/ClientPortal/ProfileController.php +++ b/app/Http/Controllers/ClientPortal/ProfileController.php @@ -45,10 +45,10 @@ class ProfileController extends Controller /* Dropzone configuration */ $data = [ 'params' => [ - 'is_avatar' => TRUE, + 'is_avatar' => true, ], 'url' => '/client/document', - 'multi_upload' => FALSE, + 'multi_upload' => false, ]; return view('portal.default.profile.index', $data); @@ -63,33 +63,31 @@ class ProfileController extends Controller */ public function update(UpdateContactRequest $request, ClientContact $client_contact) { - $client_contact->fill($request->all()); //update password if needed - if($request->input('password')) + if ($request->input('password')) { $client_contact->password = Hash::make($request->input('password')); + } $client_contact->save(); - // auth()->user()->fresh(); + // auth()->user()->fresh(); return back(); } public function updateClient(UpdateClientRequest $request, ClientContact $client_contact) { - $client = $client_contact->client; //update avatar if needed - if($request->file('logo')) - { + if ($request->file('logo')) { $path = UploadAvatar::dispatchNow($request->file('logo'), auth()->user()->client->client_hash); - if($path) + if ($path) { $client->logo = $path; - + } } $client->fill($request->all()); diff --git a/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php b/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php index 58c3b77b8929..1725a6242e89 100644 --- a/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php +++ b/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php @@ -33,7 +33,6 @@ use Yajra\DataTables\Html\Builder; class RecurringInvoiceController extends Controller { - use MakesHash; use MakesDates; /** @@ -52,33 +51,30 @@ class RecurringInvoiceController extends Controller ->get(); if (request()->ajax()) { - return DataTables::of($invoices)->addColumn('action', function ($invoice) { - return ''.ctrans('texts.view').''; - })->addColumn('frequency_id', function ($invoice) { - return RecurringInvoice::frequencyForKey($invoice->frequency_id); - }) - ->editColumn('status_id', function ($invoice){ + return ''.ctrans('texts.view').''; + })->addColumn('frequency_id', function ($invoice) { + return RecurringInvoice::frequencyForKey($invoice->frequency_id); + }) + ->editColumn('status_id', function ($invoice) { return RecurringInvoice::badgeForStatus($invoice->status); }) - ->editColumn('start_date', function ($invoice){ + ->editColumn('start_date', function ($invoice) { return $this->formatDate($invoice->date, $invoice->client->date_format()); }) - ->editColumn('next_send_date', function ($invoice){ + ->editColumn('next_send_date', function ($invoice) { return $this->formatDate($invoice->next_send_date, $invoice->client->date_format()); }) - ->editColumn('amount', function ($invoice){ + ->editColumn('amount', function ($invoice) { return Number::formatMoney($invoice->amount, $invoice->client); }) ->rawColumns(['action', 'status_id']) ->make(true); - } $data['html'] = $builder; return view('portal.default.recurring_invoices.index', $data); - } /** @@ -90,19 +86,16 @@ class RecurringInvoiceController extends Controller */ public function show(ShowRecurringInvoiceRequest $request, RecurringInvoice $recurring_invoice) { - $data = [ 'invoice' => $recurring_invoice->load('invoices'), ]; return view('portal.default.recurring_invoices.show', $data); - } public function requestCancellation(Request $request, RecurringInvoice $recurring_invoice) { - $data = [ 'invoice' => $recurring_invoice ]; @@ -112,7 +105,5 @@ class RecurringInvoiceController extends Controller $recurring_invoice->user->notify(new ClientContactRequestCancellation($recurring_invoice, auth()->user())); return view('portal.default.recurring_invoices.request_cancellation', $data); - } - } diff --git a/app/Http/Controllers/ClientStatementController.php b/app/Http/Controllers/ClientStatementController.php index 5569560bb1f6..b555b5857051 100644 --- a/app/Http/Controllers/ClientStatementController.php +++ b/app/Http/Controllers/ClientStatementController.php @@ -17,32 +17,26 @@ namespace App\Http\Controllers; */ class ClientStatementController extends BaseController { - - public function __construct() + public function __construct() { - parent::__construct(); - } - /** - * Displays a client statement view for a given - * client_id. - * @return view - */ - public function show() - { + /** + * Displays a client statement view for a given + * client_id. + * @return view + */ + public function show() + { + } - } - - /** - * Updates the show view data dependent on - * configured variables - * @return json - */ - public function update() - { - - } - -} \ No newline at end of file + /** + * Updates the show view data dependent on + * configured variables + * @return json + */ + public function update() + { + } +} diff --git a/app/Http/Controllers/CompanyController.php b/app/Http/Controllers/CompanyController.php index ec2e3fe93611..64d2a0466f6a 100644 --- a/app/Http/Controllers/CompanyController.php +++ b/app/Http/Controllers/CompanyController.php @@ -60,11 +60,9 @@ class CompanyController extends BaseController */ public function __construct(CompanyRepository $company_repo) { - parent::__construct(); $this->company_repo = $company_repo; - } /** @@ -99,7 +97,7 @@ class CompanyController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -108,11 +106,9 @@ class CompanyController extends BaseController */ public function index() { - $companies = Company::whereAccountId(auth()->user()->company()->account->id); return $this->listResponse($companies); - } /** @@ -120,8 +116,8 @@ class CompanyController extends BaseController * * @return \Illuminate\Http\Response * - * - * + * + * * @OA\Get( * path="/api/v1/companies/create", * operationId="getCompaniesCreate", @@ -147,7 +143,7 @@ class CompanyController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -156,7 +152,6 @@ class CompanyController extends BaseController */ public function create(CreateCompanyRequest $request) { - $company = CompanyFactory::create(auth()->user()->company()->account->id); return $this->itemResponse($company); @@ -194,7 +189,7 @@ class CompanyController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -240,7 +235,6 @@ class CompanyController extends BaseController $ct = CompanyUser::whereUserId(auth()->user()->id)->whereCompanyId($company->id); return $this->listResponse($ct); - } /** @@ -286,7 +280,7 @@ class CompanyController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -295,9 +289,7 @@ class CompanyController extends BaseController */ public function show(ShowCompanyRequest $request, Company $company) { - return $this->itemResponse($company); - } /** @@ -306,7 +298,7 @@ class CompanyController extends BaseController * @param int $id * @return \Illuminate\Http\Response * - * + * * @OA\Get( * path="/api/v1/companies/{id}/edit", * operationId="editCompany", @@ -343,7 +335,7 @@ class CompanyController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -352,9 +344,7 @@ class CompanyController extends BaseController */ public function edit(EditCompanyRequest $request, Company $company) { - - return $this->itemResponse($company); - + return $this->itemResponse($company); } /** @@ -364,7 +354,7 @@ class CompanyController extends BaseController * @param int $id * @return \Illuminate\Http\Response * - * + * * @OA\Put( * path="/api/v1/companies/{id}", * operationId="updateCompany", @@ -401,7 +391,7 @@ class CompanyController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -425,7 +415,7 @@ class CompanyController extends BaseController * @param int $id * @return \Illuminate\Http\Response * - * + * * @OA\Delete( * path="/api/v1/companies/{id}", * operationId="deleteCompany", @@ -461,7 +451,7 @@ class CompanyController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -470,7 +460,6 @@ class CompanyController extends BaseController */ public function destroy(DestroyCompanyRequest $request, Company $company) { - $company->delete(); return response()->json([], 200); diff --git a/app/Http/Controllers/CompanyGatewayController.php b/app/Http/Controllers/CompanyGatewayController.php index 73f52dc41648..c2bea86c18cd 100644 --- a/app/Http/Controllers/CompanyGatewayController.php +++ b/app/Http/Controllers/CompanyGatewayController.php @@ -47,11 +47,9 @@ class CompanyGatewayController extends BaseController */ public function __construct(CompanyRepository $company_repo) { - parent::__construct(); $this->company_repo = $company_repo; - } /** @@ -59,8 +57,8 @@ class CompanyGatewayController extends BaseController * * @return \Illuminate\Http\Response * - * - * + * + * * @OA\Get( * path="/api/v1/company_gateways", * operationId="getCompanyGateways", @@ -88,7 +86,7 @@ class CompanyGatewayController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -100,7 +98,6 @@ class CompanyGatewayController extends BaseController $company_gateways = CompanyGateway::whereCompanyId(auth()->user()->company()->id); return $this->listResponse($company_gateways); - } /** @@ -108,8 +105,8 @@ class CompanyGatewayController extends BaseController * * @return \Illuminate\Http\Response * - * - * + * + * * @OA\Get( * path="/api/v1/company_gateways/create", * operationId="getCompanyGatewaysCreate", @@ -135,7 +132,7 @@ class CompanyGatewayController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -144,7 +141,6 @@ class CompanyGatewayController extends BaseController */ public function create(CreateCompanyGatewayRequest $request) { - $company_gateway = CompanyGatewayFactory::create(auth()->user()->company()->id, auth()->user()->id); return $this->itemResponse($company_gateway); @@ -183,7 +179,7 @@ class CompanyGatewayController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -192,13 +188,11 @@ class CompanyGatewayController extends BaseController */ public function store(StoreCompanyGatewayRequest $request) { - $company_gateway = CompanyGatewayFactory::create(auth()->user()->company()->id, auth()->user()->id); $company_gateway->fill($request->all()); $company_gateway->save(); return $this->itemResponse($company_gateway); - } /** @@ -244,18 +238,16 @@ class CompanyGatewayController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), * ) * - */ + */ public function show(ShowCompanyGatewayRequest $request, CompanyGateway $company_gateway) { - return $this->itemResponse($company_gateway); - } /** @@ -264,7 +256,7 @@ class CompanyGatewayController extends BaseController * @param int $id * @return \Illuminate\Http\Response * - * + * * @OA\Get( * path="/api/v1/company_gateways/{id}/edit", * operationId="editCompanyGateway", @@ -301,7 +293,7 @@ class CompanyGatewayController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -310,9 +302,7 @@ class CompanyGatewayController extends BaseController */ public function edit(EditCompanyGatewayRequest $request, CompanyGateway $company_gateway) { - - return $this->itemResponse($company_gateway); - + return $this->itemResponse($company_gateway); } /** @@ -322,7 +312,7 @@ class CompanyGatewayController extends BaseController * @param int $id * @return \Illuminate\Http\Response * - * + * * @OA\Put( * path="/api/v1/company_gateways/{id}", * operationId="updateCompanyGateway", @@ -359,20 +349,20 @@ class CompanyGatewayController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), * ) * - */ + */ public function update(UpdateCompanyGatewayRequest $request, CompanyGateway $company_gateway) { - $company_gateway->fill($request->all()); - if(!$request->has('fees_and_limits')) + if (!$request->has('fees_and_limits')) { $company_gateway->fees_and_limits = ''; + } $company_gateway->save(); @@ -385,7 +375,7 @@ class CompanyGatewayController extends BaseController * @param int $id * @return \Illuminate\Http\Response * - * + * * @OA\Delete( * path="/api/v1/company_gateways/{id}", * operationId="deleteCompanyGateway", @@ -421,7 +411,7 @@ class CompanyGatewayController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -430,10 +420,8 @@ class CompanyGatewayController extends BaseController */ public function destroy(DestroyCompanyGatewayRequest $request, CompanyGateway $company_gateway) { - $company_gateway->delete(); return response()->json([], 200); - } } diff --git a/app/Http/Controllers/Contact/InvoiceController.php b/app/Http/Controllers/Contact/InvoiceController.php index d8d5e3c0cdf1..db5056496c11 100644 --- a/app/Http/Controllers/Contact/InvoiceController.php +++ b/app/Http/Controllers/Contact/InvoiceController.php @@ -28,9 +28,7 @@ class InvoiceController extends BaseController public function __construct() { - parent::__construct(); - } /** @@ -42,10 +40,8 @@ class InvoiceController extends BaseController */ public function index(InvoiceFilters $filters) { - $invoices = Invoice::filter($filters); return $this->listResponse($invoices); - } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Contact/LoginController.php b/app/Http/Controllers/Contact/LoginController.php index e64df99b38f7..8bfe2a7a039b 100644 --- a/app/Http/Controllers/Contact/LoginController.php +++ b/app/Http/Controllers/Contact/LoginController.php @@ -54,9 +54,7 @@ class LoginController extends BaseController */ public function __construct() { - parent::__construct(); - } /** @@ -68,7 +66,6 @@ class LoginController extends BaseController */ public function apiLogin(Request $request) { - Auth::shouldUse('contact'); $this->validateLogin($request); @@ -79,15 +76,13 @@ class LoginController extends BaseController return response()->json(['message' => 'Too many login attempts, you are being throttled']); } - if ($this->attemptLogin($request)) + if ($this->attemptLogin($request)) { return $this->itemResponse($this->guard()->user()); - else { - + } else { $this->incrementLoginAttempts($request); return response()->json(['message' => ctrans('texts.invalid_credentials')]); } - } /** @@ -95,28 +90,27 @@ class LoginController extends BaseController * * @return void */ - public function redirectToProvider(string $provider) + public function redirectToProvider(string $provider) { //'https://www.googleapis.com/auth/gmail.send','email','profile','openid' // - if(request()->has('code')) + if (request()->has('code')) { return $this->handleProviderCallback($provider); - else + } else { return Socialite::driver($provider)->scopes()->redirect(); + } } public function redirectToProviderAndCreate(string $provider) { - $redirect_url = config('services.' . $provider . '.redirect') . '/create'; - if(request()->has('code')) + if (request()->has('code')) { return $this->handleProviderCallbackAndCreate($provider); - else + } else { return Socialite::driver($provider)->redirectUrl($redirect_url)->redirect(); - - + } } @@ -130,7 +124,7 @@ class LoginController extends BaseController if($user = OAuth::handleAuth($socialite_user, $provider)) { Auth::login($user, true); - + return redirect($this->redirectTo); } else if(MultiDB::checkUserEmailExists($socialite_user->getEmail())) @@ -138,9 +132,9 @@ class LoginController extends BaseController Session::flash('error', 'User exists in system, but not with this authentication method'); //todo add translations return view('auth.login'); - } + } else { - //todo + //todo $name = OAuth::splitName($socialite_user->getName()); $new_account = [ @@ -155,7 +149,7 @@ class LoginController extends BaseController $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); @@ -166,10 +160,10 @@ class LoginController extends BaseController /** * We use this function when OAUTHING via the web interface - * - * @return redirect - - public function handleProviderCallback(string $provider) + * + * @return redirect + + public function handleProviderCallback(string $provider) { $socialite_user = Socialite::driver($provider) ->stateless() @@ -178,7 +172,7 @@ class LoginController extends BaseController if($user = OAuth::handleAuth($socialite_user, $provider)) { Auth::login($user, true); - + return redirect($this->redirectTo); } else if(MultiDB::checkUserEmailExists($socialite_user->getEmail())) @@ -186,9 +180,9 @@ class LoginController extends BaseController Session::flash('error', 'User exists in system, but not with this authentication method'); //todo add translations return view('auth.login'); - } + } else { - //todo + //todo $name = OAuth::splitName($socialite_user->getName()); $new_account = [ @@ -203,7 +197,7 @@ class LoginController extends BaseController $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); @@ -212,31 +206,30 @@ class LoginController extends BaseController } */ /** - * A client side authentication has taken place. + * A client side authentication has taken place. * We now digest the token and confirm authentication with * the authentication server, the correct user object * is returned to us here and we send back the correct * user object payload - or error. * - * This can be extended to a create route also - need to pass a ?create query parameter and + * This can be extended to a create route also - need to pass a ?create query parameter and * then process the signup - * + * * return User $user */ public function oauthApiLogin() { - $user = false; $oauth = new OAuth(); $user = $oauth->getProvider(request()->input('provider'))->getTokenResponse(request()->input('token')); - if ($user) + if ($user) { return $this->itemResponse($user); - else + } else { return $this->errorResponse(['message' => 'Invalid credentials'], 401); - + } } @@ -245,8 +238,8 @@ class LoginController extends BaseController * which we will use to resolve the user, we return the response in JSON format * * @return json - - public function handleProviderCallbackApiUser(string $provider) + + public function handleProviderCallbackApiUser(string $provider) { $socialite_user = Socialite::driver($provider)->stateless()->user(); @@ -259,9 +252,9 @@ class LoginController extends BaseController return $this->errorResponse(['message'=>'User exists in system, but not with this authentication method'], 400); - } + } else { - //todo + //todo $name = OAuth::splitName($socialite_user->getName()); $new_account = [ diff --git a/app/Http/Controllers/DashboardController.php b/app/Http/Controllers/DashboardController.php index ef45392a008f..091a3036029d 100644 --- a/app/Http/Controllers/DashboardController.php +++ b/app/Http/Controllers/DashboardController.php @@ -11,7 +11,6 @@ namespace App\Http\Controllers; - class DashboardController extends BaseController { /** @@ -22,7 +21,6 @@ class DashboardController extends BaseController public function __construct() { $this->middleware('auth:user'); - } /** @@ -32,9 +30,7 @@ class DashboardController extends BaseController */ public function index() { - // dd(json_decode(auth()->user()->permissions(),true)); + // dd(json_decode(auth()->user()->permissions(),true)); return view('dashboard.index'); } - - } diff --git a/app/Http/Controllers/GroupSettingController.php b/app/Http/Controllers/GroupSettingController.php index cdc260c7b100..f1b8fd36ce42 100644 --- a/app/Http/Controllers/GroupSettingController.php +++ b/app/Http/Controllers/GroupSettingController.php @@ -11,7 +11,6 @@ namespace App\Http\Controllers; - use App\Factory\GroupSettingFactory; use App\Http\Requests\GroupSetting\CreateGroupSettingRequest; use App\Http\Requests\GroupSetting\DestroyGroupSettingRequest; @@ -49,7 +48,7 @@ class GroupSettingController extends BaseController * * @return \Illuminate\Http\Response * - * + * * @OA\Get( * path="/api/v1/group_settings", * operationId="getGroupSettings", @@ -77,7 +76,7 @@ class GroupSettingController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -96,8 +95,8 @@ class GroupSettingController extends BaseController * * @return \Illuminate\Http\Response * - * - * + * + * * @OA\Get( * path="/api/v1/group_settings/create", * operationId="getGroupSettingsCreate", @@ -123,7 +122,7 @@ class GroupSettingController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -170,7 +169,7 @@ class GroupSettingController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -189,7 +188,6 @@ class GroupSettingController extends BaseController $this->uploadLogo($request->file('company_logo'), $group_setting->company, $group_setting); return $this->itemResponse($group_setting); - } /** @@ -235,7 +233,7 @@ class GroupSettingController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -253,7 +251,7 @@ class GroupSettingController extends BaseController * @param int $id * @return \Illuminate\Http\Response * - * + * * @OA\Get( * path="/api/v1/group_settings/{id}/edit", * operationId="editGroupSetting", @@ -290,7 +288,7 @@ class GroupSettingController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -309,7 +307,7 @@ class GroupSettingController extends BaseController * @param int $id * @return \Illuminate\Http\Response * - * + * * @OA\Put( * path="/api/v1/group_settings/{id}", * operationId="updateGroupSetting", @@ -346,7 +344,7 @@ class GroupSettingController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -355,13 +353,11 @@ class GroupSettingController extends BaseController */ public function update(UpdateGroupSettingRequest $request, GroupSetting $group_setting) { - $group_setting = $this->group_setting_repo->save($request->all(), $group_setting); $this->uploadLogo($request->file('company_logo'), $group_setting->company, $group_setting); - return $this->itemResponse($group_setting); - + return $this->itemResponse($group_setting); } /** @@ -370,7 +366,7 @@ class GroupSettingController extends BaseController * @param int $id * @return \Illuminate\Http\Response * - * + * * @OA\Delete( * path="/api/v1/group_settings/{id}", * operationId="deleteGroupSetting", @@ -406,7 +402,7 @@ class GroupSettingController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -418,6 +414,5 @@ class GroupSettingController extends BaseController $group_setting->delete(); return response()->json([], 200); - } } diff --git a/app/Http/Controllers/InvoiceController.php b/app/Http/Controllers/InvoiceController.php index 69df1c6e4a2b..f46ea51fef65 100644 --- a/app/Http/Controllers/InvoiceController.php +++ b/app/Http/Controllers/InvoiceController.php @@ -43,7 +43,6 @@ use Illuminate\Support\Facades\Log; class InvoiceController extends BaseController { - use MakesHash; protected $entity_type = Invoice::class; @@ -62,11 +61,9 @@ class InvoiceController extends BaseController */ public function __construct(InvoiceRepository $invoice_repo) { - parent::__construct(); $this->invoice_repo = $invoice_repo; - } /** @@ -75,7 +72,7 @@ class InvoiceController extends BaseController * @param \App\Filters\InvoiceFilters $filters The filters * * @return \Illuminate\Http\Response - * + * * @OA\Get( * path="/api/v1/invoices", * operationId="getInvoices", @@ -103,7 +100,7 @@ class InvoiceController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -112,11 +109,9 @@ class InvoiceController extends BaseController */ public function index(InvoiceFilters $filters) { - $invoices = Invoice::filter($filters); return $this->listResponse($invoices); - } /** @@ -125,8 +120,8 @@ class InvoiceController extends BaseController * @param \App\Http\Requests\Invoice\CreateInvoiceRequest $request The request * * @return \Illuminate\Http\Response - * - * + * + * * @OA\Get( * path="/api/v1/invoices/create", * operationId="getInvoicesCreate", @@ -152,7 +147,7 @@ class InvoiceController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -161,11 +156,9 @@ class InvoiceController extends BaseController */ public function create(CreateInvoiceRequest $request) { - $invoice = InvoiceFactory::create(auth()->user()->company()->id, auth()->user()->id); return $this->itemResponse($invoice); - } @@ -175,8 +168,8 @@ class InvoiceController extends BaseController * @param \App\Http\Requests\Invoice\StoreInvoiceRequest $request The request * * @return \Illuminate\Http\Response - * - * + * + * * @OA\Post( * path="/api/v1/invoices", * operationId="storeInvoice", @@ -202,16 +195,15 @@ class InvoiceController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), * ) * - */ + */ public function store(StoreInvoiceRequest $request) { - $invoice = $this->invoice_repo->save($request->all(), InvoiceFactory::create(auth()->user()->company()->id, auth()->user()->id)); $invoice = StoreInvoice::dispatchNow($invoice, $request->all(), $invoice->company); //todo potentially this may return mixed ie PDF/$invoice... need to revisit when we implement UI @@ -219,7 +211,6 @@ class InvoiceController extends BaseController event(new InvoiceWasCreated($invoice, $invoice->company)); return $this->itemResponse($invoice); - } /** @@ -229,8 +220,8 @@ class InvoiceController extends BaseController * @param \App\Models\Invoice $invoice The invoice * * @return \Illuminate\Http\Response - * - * + * + * * @OA\Get( * path="/api/v1/invoices/{id}", * operationId="showInvoice", @@ -267,18 +258,16 @@ class InvoiceController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), * ) * - */ + */ public function show(ShowInvoiceRequest $request, Invoice $invoice) { - return $this->itemResponse($invoice); - } /** @@ -288,7 +277,7 @@ class InvoiceController extends BaseController * @param \App\Models\Invoice $invoice The invoice * * @return \Illuminate\Http\Response - * + * * @OA\Get( * path="/api/v1/invoices/{id}/edit", * operationId="editInvoice", @@ -325,18 +314,16 @@ class InvoiceController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), * ) * - */ + */ public function edit(EditInvoiceRequest $request, Invoice $invoice) { - return $this->itemResponse($invoice); - } /** @@ -346,8 +333,8 @@ class InvoiceController extends BaseController * @param \App\Models\Invoice $invoice The invoice * * @return \Illuminate\Http\Response - * - * + * + * * @OA\Put( * path="/api/v1/invoices/{id}", * operationId="updateInvoice", @@ -384,32 +371,33 @@ class InvoiceController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), * ) * - */ + */ public function update(UpdateInvoiceRequest $request, Invoice $invoice) { + if($request->entityIsDeleted($invoice)) + return $request->disallowUpdate(); $invoice = $this->invoice_repo->save($request->all(), $invoice); event(new InvoiceWasUpdated($invoice, $invoice->company)); return $this->itemResponse($invoice); - } /** * Remove the specified resource from storage. * - * @param \App\Http\Requests\Invoice\DestroyInvoiceRequest $request - * @param \App\Models\Invoice $invoice + * @param \App\Http\Requests\Invoice\DestroyInvoiceRequest $request + * @param \App\Models\Invoice $invoice * * @return \Illuminate\Http\Response - * + * * @OA\Delete( * path="/api/v1/invoices/{id}", * operationId="deleteInvoice", @@ -445,7 +433,7 @@ class InvoiceController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -454,18 +442,16 @@ class InvoiceController extends BaseController */ public function destroy(DestroyInvoiceRequest $request, Invoice $invoice) { - $invoice->delete(); return response()->json([], 200); - } /** * Perform bulk actions on the list view - * + * * @return Collection - * + * * @OA\Post( * path="/api/v1/invoices/bulk", * operationId="bulkInvoices", @@ -506,7 +492,7 @@ class InvoiceController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -515,38 +501,37 @@ class InvoiceController extends BaseController */ public function bulk() { - $action = request()->input('action'); $ids = request()->input('ids'); $invoices = Invoice::withTrashed()->whereIn('id', $this->transformKeys($ids)); - if(!$invoices) + if (!$invoices) { return response()->json(['message'=>'No Invoices Found']); + } - $invoices->each(function ($invoice, $key) use($action){ + $invoices->each(function ($invoice, $key) use ($action) { // $this->invoice_repo->{$action}($invoice); - if(auth()->user()->can('edit', $invoice)) + if (auth()->user()->can('edit', $invoice)) { $this->performAction($invoice, $action, true); - + } }); return $this->listResponse(Invoice::withTrashed()->whereIn('id', $this->transformKeys($ids))); - } /** - * + * * @OA\Get( * path="/api/v1/invoices/{id}/{action}", * operationId="actionInvoice", * tags={"invoices"}, * summary="Performs a custom action on an invoice", * description="Performs a custom action on an invoice. - + The current range of actions are as follows - clone_to_invoice - clone_to_quote @@ -582,7 +567,7 @@ class InvoiceController extends BaseController * type="string", * format="string", * ), - * ), + * ), * @OA\Response( * response=200, * description="Returns the invoice object", @@ -598,7 +583,7 @@ class InvoiceController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -607,9 +592,7 @@ class InvoiceController extends BaseController */ public function action(ActionInvoiceRequest $request, Invoice $invoice, $action) { - return $this->performAction($invoice, $action); - } private function performAction(Invoice $invoice, $action, $bulk = false) @@ -622,7 +605,7 @@ class InvoiceController extends BaseController break; case 'clone_to_quote': $quote = CloneInvoiceToQuoteFactory::create($invoice, auth()->user()->id); - // todo build the quote transformer and return response here + // todo build the quote transformer and return response here break; case 'history': # code... @@ -631,19 +614,22 @@ class InvoiceController extends BaseController # code... break; case 'mark_paid': - if($invoice->balance <= 0 || $invoice->status_id == Invoice::STATUS_PAID) + if ($invoice->balance <= 0 || $invoice->status_id == Invoice::STATUS_PAID) { return $this->errorResponse(['message' => 'Invoice has no balance owing'], 400); + } $invoice = MarkInvoicePaid::dispatchNow($invoice, $invoice->company); - if(!$bulk) + if (!$bulk) { return $this->itemResponse($invoice); + } break; case 'mark_sent': $invoice->markSent(); - if(!$bulk) + if (!$bulk) { return $this->itemResponse($invoice); + } break; case 'download': return response()->download(public_path($invoice->pdf_file_path())); @@ -651,25 +637,27 @@ class InvoiceController extends BaseController case 'archive': $this->invoice_repo->archive($invoice); - if(!$bulk) - return $this->listResponse($invoice); + if (!$bulk) { + return $this->listResponse($invoice); + } break; case 'delete': $this->invoice_repo->delete($invoice); - if(!$bulk) - return $this->listResponse($invoice); + if (!$bulk) { + return $this->listResponse($invoice); + } break; case 'email': EmailInvoice::dispatch($invoice, $invoice->company); - if(!$bulk) - return response()->json(['message'=>'email sent'],200); + if (!$bulk) { + return response()->json(['message'=>'email sent'], 200); + } break; default: - return response()->json(['message' => "The requested action `{$action}` is not available."],400); + return response()->json(['message' => "The requested action `{$action}` is not available."], 400); break; } } - } diff --git a/app/Http/Controllers/MigrationController.php b/app/Http/Controllers/MigrationController.php index bcaa70a3da74..dd1546a8e6ab 100644 --- a/app/Http/Controllers/MigrationController.php +++ b/app/Http/Controllers/MigrationController.php @@ -29,14 +29,13 @@ class MigrationController extends BaseController public function __construct() { parent::__construct(); - } /** * * Purge Company - * + * * @OA\Post( * path="/api/v1/migration/purge/{company}", * operationId="postPurgeCompany", @@ -71,7 +70,7 @@ class MigrationController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -79,10 +78,9 @@ class MigrationController extends BaseController */ public function purgeCompany(Company $company) { - - $company->delete(); + $company->delete(); - return response()->json(['message'=>'Company purged'], 200); + return response()->json(['message'=>'Company purged'], 200); } @@ -90,7 +88,7 @@ class MigrationController extends BaseController /** * * Purge Company but save settings - * + * * @OA\Post( * path="/api/v1/migration/purge_save_settings/{company}", * operationId="postPurgeCompanySaveSettings", @@ -125,7 +123,7 @@ class MigrationController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -136,9 +134,6 @@ class MigrationController extends BaseController $company->client->delete(); $company->save(); - return response()->json(['message'=>'Settings preserved'], 200); - + return response()->json(['message'=>'Settings preserved'], 200); } - - } diff --git a/app/Http/Controllers/OpenAPI/ActivitySchema.php b/app/Http/Controllers/OpenAPI/ActivitySchema.php index 4db09e1c18fc..2c14067a2fa2 100644 --- a/app/Http/Controllers/OpenAPI/ActivitySchema.php +++ b/app/Http/Controllers/OpenAPI/ActivitySchema.php @@ -19,4 +19,4 @@ * @OA\Property(property="notes", type="string", example="2", description="______"), * @OA\Property(property="ip", type="string", example="2", description="______"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/BulkActionSchema.php b/app/Http/Controllers/OpenAPI/BulkActionSchema.php index 3fca84c36d0d..0a544861436a 100644 --- a/app/Http/Controllers/OpenAPI/BulkActionSchema.php +++ b/app/Http/Controllers/OpenAPI/BulkActionSchema.php @@ -8,4 +8,4 @@ * example="[0,1,2,3,]" * ), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/ClientContactSchema.php b/app/Http/Controllers/OpenAPI/ClientContactSchema.php index 50346bf6aaf8..85f0dcfa62bd 100644 --- a/app/Http/Controllers/OpenAPI/ClientContactSchema.php +++ b/app/Http/Controllers/OpenAPI/ClientContactSchema.php @@ -30,4 +30,4 @@ * @OA\Property(property="updated_at", type="number", format="integer", example="134341234234", description="Timestamp"), * @OA\Property(property="deleted_at", type="number", format="integer", example="134341234234", description="Timestamp"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/ClientGatewayToken.php b/app/Http/Controllers/OpenAPI/ClientGatewayToken.php index 56b90d11a46a..e2e9694fc56f 100644 --- a/app/Http/Controllers/OpenAPI/ClientGatewayToken.php +++ b/app/Http/Controllers/OpenAPI/ClientGatewayToken.php @@ -10,4 +10,4 @@ * @OA\Property(property="company_gateway_id", type="string", example="2", description="______"), * @OA\Property(property="is_default", type="boolean", example="true", description="______"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/ClientSchema.php b/app/Http/Controllers/OpenAPI/ClientSchema.php index 86049e5d2e1d..b96e84220e92 100644 --- a/app/Http/Controllers/OpenAPI/ClientSchema.php +++ b/app/Http/Controllers/OpenAPI/ClientSchema.php @@ -8,10 +8,10 @@ * @OA\Property(property="company_id", type="string", example="", description="________"), * @OA\Property(property="client_id", type="string", example="", description="________"), * @OA\Property( - * property="contacts", + * property="contacts", * type="array", * @OA\Items( - * + * * ref="#/components/schemas/ClientContact", * ), * ), @@ -49,4 +49,4 @@ * @OA\Property(property="updated_at", type="number", format="integer", example="134341234234", description="Timestamp"), * @OA\Property(property="settings",ref="#/components/schemas/CompanySettings"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/CompanyGatewaySchema.php b/app/Http/Controllers/OpenAPI/CompanyGatewaySchema.php index 38f8a896d19d..a5009d01b461 100644 --- a/app/Http/Controllers/OpenAPI/CompanyGatewaySchema.php +++ b/app/Http/Controllers/OpenAPI/CompanyGatewaySchema.php @@ -12,7 +12,7 @@ * @OA\Property(property="config", type="string", example="dfadsfdsafsafd", description="The configuration map for the gateway"), * @OA\Property(property="update_details", type="boolean", example=true, description="______"), * @OA\Property( - * property="fees_and_limits", + * property="fees_and_limits", * type="array", * description="A mapped collection of the fees and limits for the configured gateway", * @OA\Items( @@ -21,4 +21,3 @@ * ), * ) */ - \ No newline at end of file diff --git a/app/Http/Controllers/OpenAPI/CompanySchema.php b/app/Http/Controllers/OpenAPI/CompanySchema.php index c120bc00cebd..4f70608f0944 100644 --- a/app/Http/Controllers/OpenAPI/CompanySchema.php +++ b/app/Http/Controllers/OpenAPI/CompanySchema.php @@ -27,4 +27,3 @@ * @OA\Property(property="settings",ref="#/components/schemas/CompanySettings"), * ) */ - diff --git a/app/Http/Controllers/OpenAPI/CompanySettingsSchema.php b/app/Http/Controllers/OpenAPI/CompanySettingsSchema.php index 71aee10d09bc..f6a27f9374b2 100644 --- a/app/Http/Controllers/OpenAPI/CompanySettingsSchema.php +++ b/app/Http/Controllers/OpenAPI/CompanySettingsSchema.php @@ -154,4 +154,4 @@ * @OA\Property(property="client_online_payment_notification", type="boolean", example=false, description="____________"), * @OA\Property(property="client_manual_payment_notification", type="boolean", example=false, description="____________"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/CompanyUserSchema.php b/app/Http/Controllers/OpenAPI/CompanyUserSchema.php index 7b208941c5aa..5a77131d252e 100644 --- a/app/Http/Controllers/OpenAPI/CompanyUserSchema.php +++ b/app/Http/Controllers/OpenAPI/CompanyUserSchema.php @@ -15,4 +15,4 @@ * @OA\Property(property="user",ref="#/components/schemas/User"), * @OA\Property(property="token",ref="#/components/schemas/CompanyToken"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/FeesAndLimitsSchema.php b/app/Http/Controllers/OpenAPI/FeesAndLimitsSchema.php index 3808bd25f1d3..eaeaec5ca708 100644 --- a/app/Http/Controllers/OpenAPI/FeesAndLimitsSchema.php +++ b/app/Http/Controllers/OpenAPI/FeesAndLimitsSchema.php @@ -16,4 +16,4 @@ * @OA\Property(property="fee_cap", type="number", format="float", example="2.0", description="______"), * @OA\Property(property="adjust_fee_percent", type="boolean", example=true, description="______"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/GroupSettingSchema.php b/app/Http/Controllers/OpenAPI/GroupSettingSchema.php index 1417af9658bb..2da966cd3c24 100644 --- a/app/Http/Controllers/OpenAPI/GroupSettingSchema.php +++ b/app/Http/Controllers/OpenAPI/GroupSettingSchema.php @@ -9,4 +9,4 @@ * @OA\Property(property="name", type="string", example="", description="________"), * @OA\Property(property="settings", type="object", example="", description="________"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/Headers.php b/app/Http/Controllers/OpenAPI/Headers.php index 17d5d923f0f2..549c3f0fce24 100644 --- a/app/Http/Controllers/OpenAPI/Headers.php +++ b/app/Http/Controllers/OpenAPI/Headers.php @@ -5,16 +5,16 @@ * description="The API version", * @OA\Schema( type="number" ) * ), - * + * * @OA\Header( * header="X-RateLimit-Remaining", * description="The number of requests left for the time window.", * @OA\Schema( type="integer" ) * ), - * + * * @OA\Header( * header="X-RateLimit-Limit", * description="The total number of requests in a given time window.", * @OA\Schema( type="integer" ) * ), - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/InvoiceSchema.php b/app/Http/Controllers/OpenAPI/InvoiceSchema.php index d5acc258330e..6eb2d0e21e35 100644 --- a/app/Http/Controllers/OpenAPI/InvoiceSchema.php +++ b/app/Http/Controllers/OpenAPI/InvoiceSchema.php @@ -49,4 +49,4 @@ * @OA\Property(property="custom_surcharge4", type="number", format="float", example="10.00", description="Fourth Custom Surcharge"), * @OA\Property(property="custom_surcharge_taxes", type="boolean", example=true, description="Toggles charging taxes on custom surcharge amounts"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/Parameters.php b/app/Http/Controllers/OpenAPI/Parameters.php index 40f0634ae42f..78712e4aa26b 100644 --- a/app/Http/Controllers/OpenAPI/Parameters.php +++ b/app/Http/Controllers/OpenAPI/Parameters.php @@ -53,7 +53,7 @@ * example="include_static=true" * ) * ), - * + * * @OA\Parameter( * name="clear_cache", * in="query", @@ -73,7 +73,7 @@ * example="user" * ) * ), - * + * * @OA\Parameter( * name="", * in="query", @@ -83,7 +83,5 @@ * example="user" * ) * ), - * + * */ - - diff --git a/app/Http/Controllers/OpenAPI/PaymentSchema.php b/app/Http/Controllers/OpenAPI/PaymentSchema.php index 6d6896ff4531..90d0c950dd8d 100644 --- a/app/Http/Controllers/OpenAPI/PaymentSchema.php +++ b/app/Http/Controllers/OpenAPI/PaymentSchema.php @@ -20,4 +20,4 @@ * @OA\Property(property="archived_at", type="number", format="integer", example="1434342123", description="Timestamp"), * @OA\Property(property="company_gateway_id", type="string", example="3", description="The company gateway id"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/ProductSchema.php b/app/Http/Controllers/OpenAPI/ProductSchema.php index d3bb8d0aba90..506fd381f4e2 100644 --- a/app/Http/Controllers/OpenAPI/ProductSchema.php +++ b/app/Http/Controllers/OpenAPI/ProductSchema.php @@ -5,4 +5,4 @@ * type="object", * @OA\Property(property="id", type="string", example="Opnel5aKBz", description="______"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/QuoteSchema.php b/app/Http/Controllers/OpenAPI/QuoteSchema.php index ef78305a8bab..10118f74892d 100644 --- a/app/Http/Controllers/OpenAPI/QuoteSchema.php +++ b/app/Http/Controllers/OpenAPI/QuoteSchema.php @@ -49,4 +49,4 @@ * @OA\Property(property="custom_surcharge4", type="number", format="float", example="10.00", description="Fourth Custom Surcharge"), * @OA\Property(property="custom_surcharge_taxes", type="boolean", example=true, description="Toggles charging taxes on custom surcharge amounts"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/RecurringInvoice.php b/app/Http/Controllers/OpenAPI/RecurringInvoice.php index fbb80363384a..81e71de1c54c 100644 --- a/app/Http/Controllers/OpenAPI/RecurringInvoice.php +++ b/app/Http/Controllers/OpenAPI/RecurringInvoice.php @@ -5,4 +5,4 @@ * type="object", * @OA\Property(property="id", type="string", example="Opnel5aKBz", description="______"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/RecurringQuote.php b/app/Http/Controllers/OpenAPI/RecurringQuote.php index acff067242d5..7d752a184844 100644 --- a/app/Http/Controllers/OpenAPI/RecurringQuote.php +++ b/app/Http/Controllers/OpenAPI/RecurringQuote.php @@ -5,4 +5,4 @@ * type="object", * @OA\Property(property="id", type="string", example="Opnel5aKBz", description="______"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/TaxRateSchema.php b/app/Http/Controllers/OpenAPI/TaxRateSchema.php index 22c137be8430..17ae45587f00 100644 --- a/app/Http/Controllers/OpenAPI/TaxRateSchema.php +++ b/app/Http/Controllers/OpenAPI/TaxRateSchema.php @@ -7,4 +7,4 @@ * @OA\Property(property="name", type="string", example="GST", description="______"), * @OA\Property(property="rate", type="number", example="10", description="______"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/UserSchema.php b/app/Http/Controllers/OpenAPI/UserSchema.php index f47d896c58bc..fd0a571d8b3f 100644 --- a/app/Http/Controllers/OpenAPI/UserSchema.php +++ b/app/Http/Controllers/OpenAPI/UserSchema.php @@ -14,4 +14,4 @@ * @OA\Property(property="oauth_user_id", type="string", example="jkhasdf789as6f675sdf768sdfs", description="_________"), * @OA\Property(property="oauth_provider_id", type="string", example="google", description="_________"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/OpenAPI/ValidationErrorSchema.php b/app/Http/Controllers/OpenAPI/ValidationErrorSchema.php index 55ce7fb40fe8..8965d9cf3b24 100644 --- a/app/Http/Controllers/OpenAPI/ValidationErrorSchema.php +++ b/app/Http/Controllers/OpenAPI/ValidationErrorSchema.php @@ -5,10 +5,10 @@ * type="object", * @OA\Property(property="message", type="string", example="The given data was invalid.", description="The error message"), * @OA\Property( - * property="errors", - * type="object", + * property="errors", + * type="object", * @OA\Property( - * property="value", + * property="value", * type="array", * @OA\Items( * type="string", diff --git a/app/Http/Controllers/OpenAPI/swagger-v3.php b/app/Http/Controllers/OpenAPI/swagger-v3.php index 37be0741a977..a303168e890b 100644 --- a/app/Http/Controllers/OpenAPI/swagger-v3.php +++ b/app/Http/Controllers/OpenAPI/swagger-v3.php @@ -23,4 +23,4 @@ * url="http://docs.invoiceninja.com" * ) * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/PaymentController.php b/app/Http/Controllers/PaymentController.php index c89527ea0103..346322caee7f 100644 --- a/app/Http/Controllers/PaymentController.php +++ b/app/Http/Controllers/PaymentController.php @@ -11,7 +11,6 @@ namespace App\Http\Controllers; - use App\Factory\PaymentFactory; use App\Filters\PaymentFilters; use App\Http\Requests\Payment\ActionPaymentRequest; @@ -37,7 +36,6 @@ use Illuminate\Http\Request; class PaymentController extends BaseController { - use MakesHash; protected $entity_type = Payment::class; @@ -57,11 +55,9 @@ class PaymentController extends BaseController */ public function __construct(PaymentRepository $payment_repo) { - parent::__construct(); $this->payment_repo = $payment_repo; - } /** @@ -71,8 +67,8 @@ class PaymentController extends BaseController * * @return \Illuminate\Http\Response * - * - * + * + * * @OA\Get( * path="/api/v1/payments", * operationId="getPayments", @@ -100,7 +96,7 @@ class PaymentController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -109,11 +105,9 @@ class PaymentController extends BaseController */ public function index(PaymentFilters $filters) { - $payments = Payment::filter($filters); return $this->listResponse($payments); - } /** @@ -123,8 +117,8 @@ class PaymentController extends BaseController * * @return \Illuminate\Http\Response * - * - * + * + * * @OA\Get( * path="/api/v1/payments/create", * operationId="getPaymentsCreate", @@ -150,7 +144,7 @@ class PaymentController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -159,11 +153,9 @@ class PaymentController extends BaseController */ public function create(CreatePaymentRequest $request) { - $payment = PaymentFactory::create(auth()->user()->company()->id, auth()->user()->id); return $this->itemResponse($payment); - } @@ -235,7 +227,7 @@ class PaymentController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -244,11 +236,9 @@ class PaymentController extends BaseController */ public function store(StorePaymentRequest $request) { - $payment = $this->payment_repo->save($request, PaymentFactory::create(auth()->user()->company()->id, auth()->user()->id)); return $this->itemResponse($payment); - } /** @@ -296,7 +286,7 @@ class PaymentController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -305,9 +295,7 @@ class PaymentController extends BaseController */ public function show(ShowPaymentRequest $request, Payment $payment) { - return $this->itemResponse($payment); - } /** @@ -318,7 +306,7 @@ class PaymentController extends BaseController * * @return \Illuminate\Http\Response * - * + * * @OA\Get( * path="/api/v1/payments/{id}/edit", * operationId="editPayment", @@ -355,7 +343,7 @@ class PaymentController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -364,9 +352,7 @@ class PaymentController extends BaseController */ public function edit(EditPaymentRequest $request, Payment $payment) { - return $this->itemResponse($payment); - } /** @@ -377,7 +363,7 @@ class PaymentController extends BaseController * * @return \Illuminate\Http\Response * - * + * * @OA\Put( * path="/api/v1/payments/{id}", * operationId="updatePayment", @@ -414,7 +400,7 @@ class PaymentController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -423,22 +409,23 @@ class PaymentController extends BaseController */ public function update(UpdatePaymentRequest $request, Payment $payment) { - + if($request->entityIsDeleted($payment)) + return $request->disallowUpdate(); + $payment = $this->payment_repo->save(request(), $payment); return $this->itemResponse($payment); - } /** * Remove the specified resource from storage. * - * @param \App\Http\Requests\Payment\DestroyPaymentRequest $request - * @param \App\Models\Invoice $payment + * @param \App\Http\Requests\Payment\DestroyPaymentRequest $request + * @param \App\Models\Invoice $payment * * @return \Illuminate\Http\Response * - * + * * @OA\Delete( * path="/api/v1/payments/{id}", * operationId="deletePayment", @@ -474,7 +461,7 @@ class PaymentController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -483,7 +470,6 @@ class PaymentController extends BaseController */ public function destroy(DestroyPaymentRequest $request, Payment $payment) { - ReverseInvoicePayment::dispatchNow($payment, $payment->company); $payment->is_deleted = true; @@ -491,15 +477,14 @@ class PaymentController extends BaseController $payment->delete(); return $this->itemResponse($payment); - } /** * Perform bulk actions on the list view - * + * * @return Collection * - * + * * @OA\Post( * path="/api/v1/payments/bulk", * operationId="bulkPayments", @@ -540,7 +525,7 @@ class PaymentController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -549,35 +534,32 @@ class PaymentController extends BaseController */ public function bulk() { - $action = request()->input('action'); $ids = request()->input('ids'); $payments = Payment::withTrashed()->find($this->transformKeys($ids)); - $payments->each(function ($payment, $key) use($action){ - - if(auth()->user()->can('edit', $payment)) + $payments->each(function ($payment, $key) use ($action) { + if (auth()->user()->can('edit', $payment)) { $this->payment_repo->{$action}($payment); - + } }); return $this->listResponse(Payment::withTrashed()->whereIn('id', $this->transformKeys($ids))); - } /** * Payment Actions * - * + * * @OA\Get( * path="/api/v1/payments/{id}/{action}", * operationId="actionPayment", * tags={"payments"}, * summary="Performs a custom action on an Payment", * description="Performs a custom action on an Payment. - + The current range of actions are as follows - clone_to_Payment - clone_to_quote @@ -613,7 +595,7 @@ class PaymentController extends BaseController * type="string", * format="string", * ), - * ), + * ), * @OA\Response( * response=200, * description="Returns the Payment object", @@ -629,7 +611,7 @@ class PaymentController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -638,7 +620,6 @@ class PaymentController extends BaseController */ public function action(ActionPaymentRequest $request, Payment $payment, $action) { - switch ($action) { case 'clone_to_invoice': //$payment = CloneInvoiceFactory::create($payment, auth()->user()->id); @@ -646,7 +627,7 @@ class PaymentController extends BaseController break; case 'clone_to_quote': //$quote = CloneInvoiceToQuoteFactory::create($payment, auth()->user()->id); - // todo build the quote transformer and return response here + // todo build the quote transformer and return response here break; case 'history': # code... @@ -672,5 +653,4 @@ class PaymentController extends BaseController break; } } - } diff --git a/app/Http/Controllers/ProductController.php b/app/Http/Controllers/ProductController.php index f0ba485a070a..c1f6128da385 100644 --- a/app/Http/Controllers/ProductController.php +++ b/app/Http/Controllers/ProductController.php @@ -27,7 +27,6 @@ use Illuminate\Http\Request; class ProductController extends BaseController { - use MakesHash; protected $entity_type = Product::class; @@ -36,12 +35,11 @@ class ProductController extends BaseController protected $product_repo; - /** - * ProductController constructor. - */ + /** + * ProductController constructor. + */ public function __construct(ProductRepository $product_repo) { - parent::__construct(); $this->product_repo = $product_repo; @@ -49,7 +47,7 @@ class ProductController extends BaseController /** * - * + * * @OA\Get( * path="/api/v1/products", * operationId="getProducts", @@ -77,7 +75,7 @@ class ProductController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -86,11 +84,9 @@ class ProductController extends BaseController */ public function index(ProductFilters $filters) { - $products = Product::filter($filters); return $this->listResponse($products); - } @@ -99,8 +95,8 @@ class ProductController extends BaseController * * @return \Illuminate\Http\Response * - * - * + * + * * @OA\Get( * path="/api/v1/products/create", * operationId="getProductsCreate", @@ -126,7 +122,7 @@ class ProductController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -173,7 +169,7 @@ class ProductController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -230,7 +226,7 @@ class ProductController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -247,7 +243,7 @@ class ProductController extends BaseController * * @param Product $product * @return \Illuminate\Http\Response - * + * * @OA\Get( * path="/api/v1/products/{id}/edit", * operationId="editProduct", @@ -284,7 +280,7 @@ class ProductController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -303,7 +299,7 @@ class ProductController extends BaseController * @param Product $product * @return \Illuminate\Http\Response * - * + * * @OA\Put( * path="/api/v1/products/{id}", * operationId="updateProduct", @@ -340,15 +336,19 @@ class ProductController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), * ) * - */ + */ public function update(UpdateProductRequest $request, Product $product) { + + if($request->entityIsDeleted($product)) + return $request->disallowUpdate(); + $product = $this->product_repo->save($request, $product); return $this->itemResponse($product); @@ -360,7 +360,7 @@ class ProductController extends BaseController * @param Product $product * @return \Illuminate\Http\Response * - * + * * @OA\Delete( * path="/api/v1/products/{id}", * operationId="deleteProduct", @@ -396,7 +396,7 @@ class ProductController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -412,10 +412,10 @@ class ProductController extends BaseController /** * Perform bulk actions on the list view - * + * * @return Collection * - * + * * @OA\Post( * path="/api/v1/products/bulk", * operationId="bulkProducts", @@ -456,7 +456,7 @@ class ProductController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -465,21 +465,18 @@ class ProductController extends BaseController */ public function bulk() { - $action = request()->input('action'); $ids = request()->input('ids'); $products = Product::withTrashed()->find($this->transformKeys($ids)); - $products->each(function ($product, $key) use($action){ - - if(auth()->user()->can('edit', $product)) + $products->each(function ($product, $key) use ($action) { + if (auth()->user()->can('edit', $product)) { $this->product_repo->{$action}($product); - + } }); return $this->listResponse(Product::withTrashed()->whereIn('id', $this->transformKeys($ids))); - } } diff --git a/app/Http/Controllers/QuoteController.php b/app/Http/Controllers/QuoteController.php index 0c6fdb22e61c..a3a741427ab6 100644 --- a/app/Http/Controllers/QuoteController.php +++ b/app/Http/Controllers/QuoteController.php @@ -33,7 +33,6 @@ use Illuminate\Http\Request; class QuoteController extends BaseController { - use MakesHash; protected $entity_type = Quote::class; @@ -54,11 +53,9 @@ class QuoteController extends BaseController */ public function __construct(QuoteRepository $quote_repo) { - parent::__construct(); $this->quote_repo = $quote_repo; - } /** @@ -66,7 +63,7 @@ class QuoteController extends BaseController * * @return \Illuminate\Http\Response * - * + * * @OA\Get( * path="/api/v1/quotes", * operationId="getQuotes", @@ -94,7 +91,7 @@ class QuoteController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -104,7 +101,6 @@ class QuoteController extends BaseController public function index(QuoteFilters $filters) { - $quotes = Quote::filter($filters); return $this->listResponse($quotes); @@ -115,8 +111,8 @@ class QuoteController extends BaseController * * @return \Illuminate\Http\Response * - * - * + * + * * @OA\Get( * path="/api/v1/quotes/create", * operationId="getQuotesCreate", @@ -142,7 +138,7 @@ class QuoteController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -151,11 +147,9 @@ class QuoteController extends BaseController */ public function create(CreateQuoteRequest $request) { - $quote = QuoteFactory::create(auth()->user()->company()->id, auth()->user()->id); return $this->itemResponse($quote); - } /** @@ -192,7 +186,7 @@ class QuoteController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -201,11 +195,9 @@ class QuoteController extends BaseController */ public function store(StoreQuoteRequest $request) { - $quote = $this->quote_repo->save($request->all(), QuoteFactory::create(auth()->user()->company()->id, auth()->user()->id)); return $this->itemResponse($quote); - } /** @@ -253,7 +245,7 @@ class QuoteController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -262,9 +254,7 @@ class QuoteController extends BaseController */ public function show(ShowQuoteRequest $request, Quote $quote) { - return $this->itemResponse($quote); - } /** @@ -275,7 +265,7 @@ class QuoteController extends BaseController * * @return \Illuminate\Http\Response * - * + * * @OA\Get( * path="/api/v1/quotes/{id}/edit", * operationId="editQuote", @@ -312,18 +302,16 @@ class QuoteController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), * ) * - */ + */ public function edit(EditQuoteRequest $request, Quote $quote) { - return $this->itemResponse($quote); - } /** @@ -334,7 +322,7 @@ class QuoteController extends BaseController * * @return \Illuminate\Http\Response * - * + * * @OA\Put( * path="/api/v1/quotes/{id}", * operationId="updateQuote", @@ -371,7 +359,7 @@ class QuoteController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -380,22 +368,23 @@ class QuoteController extends BaseController */ public function update(UpdateQuoteRequest $request, Quote $quote) { - + if($request->entityIsDeleted($quote)) + return $request->disallowUpdate(); + $quote = $this->quote_repo->save($request->all(), $quote); return $this->itemResponse($quote); - } /** * Remove the specified resource from storage. * - * @param \App\Http\Requests\Quote\DestroyQuoteRequest $request - * @param \App\Models\Quote $quote + * @param \App\Http\Requests\Quote\DestroyQuoteRequest $request + * @param \App\Models\Quote $quote * * @return \Illuminate\Http\Response * - * + * * @OA\Delete( * path="/api/v1/quotes/{id}", * operationId="deleteQuote", @@ -431,7 +420,7 @@ class QuoteController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -440,19 +429,17 @@ class QuoteController extends BaseController */ public function destroy(DestroyQuoteRequest $request, Quote $quote) { - $quote->delete(); return response()->json([], 200); - } /** * Perform bulk actions on the list view - * + * * @return Collection * - * + * * @OA\Post( * path="/api/v1/quotes/bulk", * operationId="bulkQuotes", @@ -493,7 +480,7 @@ class QuoteController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -502,36 +489,33 @@ class QuoteController extends BaseController */ public function bulk() { - $action = request()->input('action'); $ids = request()->input('ids'); $quotes = Quote::withTrashed()->find($this->transformKeys($ids)); - $quotes->each(function ($quote, $key) use($action){ - - if(auth()->user()->can('edit', $quote)) + $quotes->each(function ($quote, $key) use ($action) { + if (auth()->user()->can('edit', $quote)) { $this->quote_repo->{$action}($quote); - + } }); return $this->listResponse(Quote::withTrashed()->whereIn('id', $this->transformKeys($ids))); - } /** * Quote Actions - * * - * + * + * * @OA\Get( * path="/api/v1/quotes/{id}/{action}", * operationId="actionQuote", * tags={"quotes"}, * summary="Performs a custom action on an Quote", * description="Performs a custom action on an Quote. - + The current range of actions are as follows - clone_to_Quote - clone_to_quote @@ -567,7 +551,7 @@ class QuoteController extends BaseController * type="string", * format="string", * ), - * ), + * ), * @OA\Response( * response=200, * description="Returns the Quote object", @@ -583,16 +567,15 @@ class QuoteController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), * ) * - */ + */ public function action(ActionQuoteRequest $request, Quote $quote, $action) { - switch ($action) { case 'clone_to_invoice': //$quote = CloneInvoiceFactory::create($quote, auth()->user()->id); @@ -600,7 +583,7 @@ class QuoteController extends BaseController break; case 'clone_to_quote': //$quote = CloneInvoiceToQuoteFactory::create($quote, auth()->user()->id); - // todo build the quote transformer and return response here + // todo build the quote transformer and return response here break; case 'history': # code... @@ -623,12 +606,11 @@ class QuoteController extends BaseController return $this->listResponse($quote); break; case 'email': - return response()->json(['message'=>'email sent'],200); + return response()->json(['message'=>'email sent'], 200); break; default: - return response()->json(['message' => "The requested action `{$action}` is not available."],400); + return response()->json(['message' => "The requested action `{$action}` is not available."], 400); break; } } - -} \ No newline at end of file +} diff --git a/app/Http/Controllers/RecurringInvoiceController.php b/app/Http/Controllers/RecurringInvoiceController.php index 1edac32e2bec..271f668bd5fa 100644 --- a/app/Http/Controllers/RecurringInvoiceController.php +++ b/app/Http/Controllers/RecurringInvoiceController.php @@ -38,7 +38,6 @@ use Illuminate\Support\Facades\Log; class RecurringInvoiceController extends BaseController { - use MakesHash; protected $entity_type = RecurringInvoice::class; @@ -59,11 +58,9 @@ class RecurringInvoiceController extends BaseController */ public function __construct(RecurringInvoiceRepository $recurring_invoice_repo) { - parent::__construct(); $this->recurring_invoice_repo = $recurring_invoice_repo; - } /** @@ -73,7 +70,7 @@ class RecurringInvoiceController extends BaseController * * @return \Illuminate\Http\Response * - * + * * @OA\Get( * path="/api/v1/recurring_invoices", * operationId="getRecurringInvoices", @@ -101,7 +98,7 @@ class RecurringInvoiceController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -110,11 +107,9 @@ class RecurringInvoiceController extends BaseController */ public function index(RecurringInvoiceFilters $filters) { - $recurring_invoices = RecurringInvoice::filter($filters); return $this->listResponse($recurring_invoices); - } /** @@ -124,8 +119,8 @@ class RecurringInvoiceController extends BaseController * * @return \Illuminate\Http\Response * - * - * + * + * * @OA\Get( * path="/api/v1/recurring_invoices/create", * operationId="getRecurringInvoicesCreate", @@ -151,7 +146,7 @@ class RecurringInvoiceController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -160,11 +155,9 @@ class RecurringInvoiceController extends BaseController */ public function create(CreateRecurringInvoiceRequest $request) { - $recurring_invoice = RecurringInvoiceFactory::create(auth()->user()->company()->id, auth()->user()->id); return $this->itemResponse($recurring_invoice); - } @@ -202,7 +195,7 @@ class RecurringInvoiceController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -211,11 +204,9 @@ class RecurringInvoiceController extends BaseController */ public function store(StoreRecurringInvoiceRequest $request) { - $recurring_invoice = $this->recurring_invoice_repo->save($request->all(), RecurringInvoiceFactory::create(auth()->user()->company()->id, auth()->user()->id)); return $this->itemResponse($recurring_invoice); - } /** @@ -263,18 +254,16 @@ class RecurringInvoiceController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), * ) * - */ + */ public function show(ShowRecurringInvoiceRequest $request, RecurringInvoice $recurring_invoice) { - return $this->itemResponse($recurring_invoice); - } /** @@ -285,7 +274,7 @@ class RecurringInvoiceController extends BaseController * * @return \Illuminate\Http\Response * - * + * * @OA\Get( * path="/api/v1/recurring_invoices/{id}/edit", * operationId="editRecurringInvoice", @@ -322,7 +311,7 @@ class RecurringInvoiceController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -331,9 +320,7 @@ class RecurringInvoiceController extends BaseController */ public function edit(EditRecurringInvoiceRequest $request, RecurringInvoice $recurring_invoice) { - return $this->itemResponse($recurring_invoice); - } /** @@ -344,7 +331,7 @@ class RecurringInvoiceController extends BaseController * * @return \Illuminate\Http\Response * - * + * * @OA\Put( * path="/api/v1/recurring_invoices/{id}", * operationId="updateRecurringInvoice", @@ -381,7 +368,7 @@ class RecurringInvoiceController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -390,22 +377,23 @@ class RecurringInvoiceController extends BaseController */ public function update(UpdateRecurringInvoiceRequest $request, RecurringInvoice $recurring_invoice) { - + if($request->entityIsDeleted($recurring_invoice)) + return $request->disallowUpdate(); + $recurring_invoice = $this->recurring_invoice_repo->save($request->all(), $recurring_invoice); return $this->itemResponse($recurring_invoice); - } /** * Remove the specified resource from storage. * - * @param \App\Http\Requests\RecurringInvoice\DestroyRecurringInvoiceRequest $request - * @param \App\Models\RecurringInvoice $recurring_invoice + * @param \App\Http\Requests\RecurringInvoice\DestroyRecurringInvoiceRequest $request + * @param \App\Models\RecurringInvoice $recurring_invoice * * @return \Illuminate\Http\Response * - * + * * @OA\Delete( * path="/api/v1/recurring_invoices/{id}", * operationId="deleteRecurringInvoice", @@ -441,7 +429,7 @@ class RecurringInvoiceController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -450,19 +438,17 @@ class RecurringInvoiceController extends BaseController */ public function destroy(DestroyRecurringInvoiceRequest $request, RecurringInvoice $recurring_invoice) { - $recurring_invoice->delete(); return response()->json([], 200); - } /** * Perform bulk actions on the list view - * + * * @return Collection * - * + * * @OA\Post( * path="/api/v1/recurring_invoices/bulk", * operationId="bulkRecurringInvoices", @@ -503,7 +489,7 @@ class RecurringInvoiceController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -512,35 +498,32 @@ class RecurringInvoiceController extends BaseController */ public function bulk() { - $action = request()->input('action'); $ids = request()->input('ids'); $recurring_invoices = RecurringInvoice::withTrashed()->find($this->transformKeys($ids)); - $recurring_invoices->each(function ($recurring_invoice, $key) use($action){ - - if(auth()->user()->can('edit', $recurring_invoice)) + $recurring_invoices->each(function ($recurring_invoice, $key) use ($action) { + if (auth()->user()->can('edit', $recurring_invoice)) { $this->recurring_invoice_repo->{$action}($recurring_invoice); - + } }); return $this->listResponse(RecurringInvoice::withTrashed()->whereIn('id', $this->transformKeys($ids))); - } /** * Recurring Invoice Actions * - * + * * @OA\Get( * path="/api/v1/recurring_invoices/{id}/{action}", * operationId="actionRecurringInvoice", * tags={"recurring_invoices"}, * summary="Performs a custom action on an RecurringInvoice", * description="Performs a custom action on an RecurringInvoice. - + The current range of actions are as follows - clone_to_RecurringInvoice - clone_to_quote @@ -576,7 +559,7 @@ class RecurringInvoiceController extends BaseController * type="string", * format="string", * ), - * ), + * ), * @OA\Response( * response=200, * description="Returns the RecurringInvoice object", @@ -592,17 +575,16 @@ class RecurringInvoiceController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), * ) * - */ + */ public function action(ActionRecurringInvoiceRequest $request, RecurringInvoice $recurring_invoice, $action) { - switch ($action) { case 'clone_to_RecurringInvoice': // $recurring_invoice = CloneRecurringInvoiceFactory::create($recurring_invoice, auth()->user()->id); @@ -610,7 +592,7 @@ class RecurringInvoiceController extends BaseController break; case 'clone_to_quote': // $recurring_invoice = CloneRecurringInvoiceToQuoteFactory::create($recurring_invoice, auth()->user()->id); - // todo build the quote transformer and return response here + // todo build the quote transformer and return response here break; case 'history': # code... @@ -636,5 +618,4 @@ class RecurringInvoiceController extends BaseController break; } } - } diff --git a/app/Http/Controllers/RecurringQuoteController.php b/app/Http/Controllers/RecurringQuoteController.php index 4dccabe7b496..a6ffc50ff0c2 100644 --- a/app/Http/Controllers/RecurringQuoteController.php +++ b/app/Http/Controllers/RecurringQuoteController.php @@ -38,7 +38,6 @@ use Illuminate\Support\Facades\Log; class RecurringQuoteController extends BaseController { - use MakesHash; protected $entity_type = RecurringQuote::class; @@ -59,11 +58,9 @@ class RecurringQuoteController extends BaseController */ public function __construct(RecurringQuoteRepository $recurring_quote_repo) { - parent::__construct(); $this->recurring_quote_repo = $recurring_quote_repo; - } /** @@ -73,7 +70,7 @@ class RecurringQuoteController extends BaseController * * @return \Illuminate\Http\Response * - * + * * @OA\Get( * path="/api/v1/recurring_quotes", * operationId="getRecurringQuotes", @@ -101,7 +98,7 @@ class RecurringQuoteController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -110,11 +107,9 @@ class RecurringQuoteController extends BaseController */ public function index(RecurringQuoteFilters $filters) { - $recurring_quotes = RecurringQuote::filter($filters); return $this->listResponse($recurring_quotes); - } /** @@ -123,8 +118,8 @@ class RecurringQuoteController extends BaseController * @param \App\Http\Requests\RecurringQuote\CreateRecurringQuoteRequest $request The request * * @return \Illuminate\Http\Response - * - * + * + * * @OA\Get( * path="/api/v1/recurring_quotes/create", * operationId="getRecurringQuotesCreate", @@ -150,7 +145,7 @@ class RecurringQuoteController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -159,11 +154,9 @@ class RecurringQuoteController extends BaseController */ public function create(CreateRecurringQuoteRequest $request) { - $recurring_quote = RecurringQuoteFactory::create(auth()->user()->company()->id, auth()->user()->id); return $this->itemResponse($recurring_quote); - } @@ -200,7 +193,7 @@ class RecurringQuoteController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -209,11 +202,9 @@ class RecurringQuoteController extends BaseController */ public function store(StoreRecurringQuoteRequest $request) { - $recurring_quote = $this->recurring_quote_repo->save($request, RecurringQuoteFactory::create(auth()->user()->company()->id, auth()->user()->id)); return $this->itemResponse($recurring_quote); - } /** @@ -261,7 +252,7 @@ class RecurringQuoteController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -270,9 +261,7 @@ class RecurringQuoteController extends BaseController */ public function show(ShowRecurringQuoteRequest $request, RecurringQuote $recurring_quote) { - return $this->itemResponse($recurring_quote); - } /** @@ -283,7 +272,7 @@ class RecurringQuoteController extends BaseController * * @return \Illuminate\Http\Response * - * + * * @OA\Get( * path="/api/v1/recurring_quotes/{id}/edit", * operationId="editRecurringQuote", @@ -320,18 +309,16 @@ class RecurringQuoteController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), * ) * - */ + */ public function edit(EditRecurringQuoteRequest $request, RecurringQuote $recurring_quote) { - return $this->itemResponse($recurring_quote); - } /** @@ -342,7 +329,7 @@ class RecurringQuoteController extends BaseController * * @return \Illuminate\Http\Response * - * + * * @OA\Put( * path="/api/v1/recurring_quotes/{id}", * operationId="updateRecurringQuote", @@ -379,31 +366,33 @@ class RecurringQuoteController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), * ) * - */ + */ public function update(UpdateRecurringQuoteRequest $request, RecurringQuote $recurring_quote) { + if($request->entityIsDeleted($recurring_quote)) + return $request->disallowUpdate(); + $recurring_quote = $this->recurring_quote_repo->save(request(), $recurring_quote); return $this->itemResponse($recurring_quote); - } /** * Remove the specified resource from storage. * - * @param \App\Http\Requests\RecurringQuote\DestroyRecurringQuoteRequest $request - * @param \App\Models\RecurringQuote $recurring_quote + * @param \App\Http\Requests\RecurringQuote\DestroyRecurringQuoteRequest $request + * @param \App\Models\RecurringQuote $recurring_quote * * @return \Illuminate\Http\Response * - * + * * @OA\Delete( * path="/api/v1/recurring_quotes/{id}", * operationId="deleteRecurringQuote", @@ -439,7 +428,7 @@ class RecurringQuoteController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -448,19 +437,17 @@ class RecurringQuoteController extends BaseController */ public function destroy(DestroyRecurringQuoteRequest $request, RecurringQuote $recurring_quote) { - $recurring_quote->delete(); return response()->json([], 200); - } /** * Perform bulk actions on the list view - * + * * @return Collection * - * + * * @OA\Post( * path="/api/v1/recurring_quotes/bulk", * operationId="bulkRecurringQuotes", @@ -501,7 +488,7 @@ class RecurringQuoteController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -510,36 +497,33 @@ class RecurringQuoteController extends BaseController */ public function bulk() { - $action = request()->input('action'); $ids = request()->input('ids'); $recurring_quotes = RecurringQuote::withTrashed()->find($this->transformKeys($ids)); - $recurring_quotes->each(function ($recurring_quote, $key) use($action){ - - if(auth()->user()->can('edit', $recurring_quote)) + $recurring_quotes->each(function ($recurring_quote, $key) use ($action) { + if (auth()->user()->can('edit', $recurring_quote)) { $this->recurring_quote_repo->{$action}($recurring_quote); - + } }); return $this->listResponse(RecurringQuote::withTrashed()->whereIn('id', $this->transformKeys($ids))); - } /** * Recurring Quote Actions - * * - * + * + * * @OA\Get( * path="/api/v1/recurring_quotes/{id}/{action}", * operationId="actionRecurringQuote", * tags={"recurring_quotes"}, * summary="Performs a custom action on an RecurringQuote", * description="Performs a custom action on an RecurringQuote. - + The current range of actions are as follows - clone_to_RecurringQuote - clone_to_quote @@ -575,7 +559,7 @@ class RecurringQuoteController extends BaseController * type="string", * format="string", * ), - * ), + * ), * @OA\Response( * response=200, * description="Returns the RecurringQuote object", @@ -591,7 +575,7 @@ class RecurringQuoteController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -600,7 +584,6 @@ class RecurringQuoteController extends BaseController */ public function action(ActionRecurringQuoteRequest $request, RecurringQuote $recurring_quote, $action) { - switch ($action) { case 'clone_to_RecurringQuote': // $recurring_invoice = CloneRecurringQuoteFactory::create($recurring_invoice, auth()->user()->id); @@ -608,7 +591,7 @@ class RecurringQuoteController extends BaseController break; case 'clone_to_quote': // $quote = CloneRecurringQuoteToQuoteFactory::create($recurring_invoice, auth()->user()->id); - // todo build the quote transformer and return response here + // todo build the quote transformer and return response here break; case 'history': # code... @@ -634,5 +617,4 @@ class RecurringQuoteController extends BaseController break; } } - } diff --git a/app/Http/Controllers/SettingsController.php b/app/Http/Controllers/SettingsController.php index 53e66530ea6a..9c1dc09108dd 100644 --- a/app/Http/Controllers/SettingsController.php +++ b/app/Http/Controllers/SettingsController.php @@ -21,9 +21,7 @@ class SettingsController extends BaseController { public function __construct() { - parent::__construct(); - } /** diff --git a/app/Http/Controllers/Support/Messages/SendingController.php b/app/Http/Controllers/Support/Messages/SendingController.php index 7e0f96fe3cbd..b5031d667e0c 100644 --- a/app/Http/Controllers/Support/Messages/SendingController.php +++ b/app/Http/Controllers/Support/Messages/SendingController.php @@ -56,7 +56,7 @@ class SendingController extends Controller * ) * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -76,5 +76,4 @@ class SendingController extends Controller 'success' => true ]); } - } diff --git a/app/Http/Controllers/TaxRateController.php b/app/Http/Controllers/TaxRateController.php index 46cb3da8f3ed..183f9d114c7e 100644 --- a/app/Http/Controllers/TaxRateController.php +++ b/app/Http/Controllers/TaxRateController.php @@ -28,7 +28,6 @@ use Illuminate\Http\Request; */ class TaxRateController extends BaseController { - protected $entity_type = TaxRate::class; protected $entity_transformer = TaxRateTransformer::class; @@ -36,7 +35,6 @@ class TaxRateController extends BaseController public function __construct() { parent::__construct(); - } /** @@ -62,7 +60,7 @@ class TaxRateController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -85,8 +83,8 @@ class TaxRateController extends BaseController * * @return \Illuminate\Http\Response * - * - * + * + * * @OA\Get( * path="/api/v1/tax_rates/create", * operationId="getTaxRateCreate", @@ -111,7 +109,7 @@ class TaxRateController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -122,7 +120,6 @@ class TaxRateController extends BaseController { $tax_rate = TaxRateFactory::create(auth()->user()->company()->id, auth()->user()->id); return $this->itemResponse($tax_rate); - } /** @@ -182,7 +179,7 @@ class TaxRateController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -200,7 +197,7 @@ class TaxRateController extends BaseController * @param int $id * @return \Illuminate\Http\Response * - * + * * @OA\Get( * path="/api/v1/tax_rates/{id}/edit", * operationId="editTaxRate", @@ -236,7 +233,7 @@ class TaxRateController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -255,8 +252,8 @@ class TaxRateController extends BaseController * @param App\Models\Client $client * @return \Illuminate\Http\Response * - * - * + * + * * @OA\Put( * path="/api/v1/tax_rates/{id}", * operationId="updateTaxRate", @@ -292,7 +289,7 @@ class TaxRateController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -305,7 +302,6 @@ class TaxRateController extends BaseController $tax_rate->save(); return $this->itemResponse($tax_rate); - } /** @@ -314,7 +310,7 @@ class TaxRateController extends BaseController * @param int $id * @return \Illuminate\Http\Response * - * + * * @OA\Delete( * path="/api/v1/tax_rates/{id}", * operationId="deleteTaxRate", @@ -349,7 +345,7 @@ class TaxRateController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -361,6 +357,5 @@ class TaxRateController extends BaseController $tax_rate->delete(); return response()->json([], 200); - } } diff --git a/app/Http/Controllers/TemplateController.php b/app/Http/Controllers/TemplateController.php index f428649dde84..4a0c75b8b15a 100644 --- a/app/Http/Controllers/TemplateController.php +++ b/app/Http/Controllers/TemplateController.php @@ -15,11 +15,9 @@ use Parsedown; class TemplateController extends BaseController { - public function __construct() { parent::__construct(); - } /** @@ -92,7 +90,7 @@ class TemplateController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -100,12 +98,9 @@ class TemplateController extends BaseController */ public function show() { - - if(request()->has('entity') && request()->has('entity_id')){ - + if (request()->has('entity') && request()->has('entity_id')) { $class = 'App\Models\\'.ucfirst(request()->input('entity')); $entity_obj = $class::whereId(request()->input('entity_id'))->company()->first(); - } $subject = request()->input('subject'); @@ -117,7 +112,5 @@ class TemplateController extends BaseController ]; return response()->json($data, 200); - } - -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Traits/VerifiesUserEmail.php b/app/Http/Controllers/Traits/VerifiesUserEmail.php index 4b2cde81ff67..f4866a331061 100644 --- a/app/Http/Controllers/Traits/VerifiesUserEmail.php +++ b/app/Http/Controllers/Traits/VerifiesUserEmail.php @@ -31,20 +31,17 @@ trait VerifiesUserEmail { //$user = User::where('confirmation_code', $code)->first(); - if ($user = User::whereRaw("BINARY `confirmation_code`= ?",$code)->first()) { - + if ($user = User::whereRaw("BINARY `confirmation_code`= ?", $code)->first()) { $user->email_verified_at = now(); $user->confirmation_code = null; $user->save(); return response()->json(['message' => ctrans('texts.security_confirmation')]); //return redirect()->route('dashboard.index')->with('message', ctrans('texts.security_confirmation')); - } return response()->json(['message' => ctrans('texts.wrong_confirmation')]); //return redirect()->route('login')->with('message', ctrans('texts.wrong_confirmation')); - } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/TranslationController.php b/app/Http/Controllers/TranslationController.php index 2b28269b18a3..fe8ab33ea605 100644 --- a/app/Http/Controllers/TranslationController.php +++ b/app/Http/Controllers/TranslationController.php @@ -22,9 +22,7 @@ class TranslationController extends BaseController { public function __construct() { - parent::__construct(); - } /** @@ -53,7 +51,8 @@ class TranslationController extends BaseController exit(); } - private function easyMinify($javascript){ + private function easyMinify($javascript) + { return preg_replace(array("/\s+\n/", "/\n\s+/", "/ +/"), array("\n", "\n ", " "), $javascript); } diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php index 7be0c917169d..ab048b92dd9d 100644 --- a/app/Http/Controllers/UserController.php +++ b/app/Http/Controllers/UserController.php @@ -40,7 +40,7 @@ class UserController extends BaseController { use VerifiesUserEmail; - use MakesHash; + use MakesHash; protected $entity_type = User::class; @@ -48,18 +48,16 @@ class UserController extends BaseController protected $user_repo; - /** + /** * Constructor * * @param \App\Repositories\UserRepository $user_repo The user repo */ public function __construct(UserRepository $user_repo) { - parent::__construct(); $this->user_repo = $user_repo; - } /** @@ -67,7 +65,7 @@ class UserController extends BaseController * * @return \Illuminate\Http\Response * - * + * * @OA\Get( * path="/api/v1/users", * operationId="getUsers", @@ -95,7 +93,7 @@ class UserController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -105,11 +103,9 @@ class UserController extends BaseController public function index(UserFilters $filters) { - $users = User::filter($filters); return $this->listResponse($users); - } /** @@ -117,8 +113,8 @@ class UserController extends BaseController * * @return \Illuminate\Http\Response * - * - * + * + * * @OA\Get( * path="/api/v1/users/create", * operationId="getUsersCreate", @@ -144,7 +140,7 @@ class UserController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -153,11 +149,9 @@ class UserController extends BaseController */ public function create(CreateUserRequest $request) { - $user = UserFactory::create(); return $this->itemResponse($user); - } /** @@ -193,7 +187,7 @@ class UserController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -202,7 +196,6 @@ class UserController extends BaseController */ public function store(StoreUserRequest $request) { - $company = auth()->user()->company(); $user = $this->user_repo->save($request->all(), $request->fetchUser()); @@ -212,7 +205,6 @@ class UserController extends BaseController $ct = CreateCompanyToken::dispatchNow($company, $user, $user_agent); return $this->itemResponse($user->fresh()); - } /** @@ -258,18 +250,16 @@ class UserController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), * ) * - */ + */ public function show(ShowUserRequest $request, User $user) { - return $this->itemResponse($user); - } /** @@ -278,7 +268,7 @@ class UserController extends BaseController * @param int $id * @return \Illuminate\Http\Response * - * + * * @OA\Get( * path="/api/v1/users/{id}/edit", * operationId="editUser", @@ -315,18 +305,16 @@ class UserController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), * ) * - */ + */ public function edit(EditUserRequest $request, User $user) { - return $this->itemResponse($user); - } /** @@ -336,7 +324,7 @@ class UserController extends BaseController * @param int $id * @return \Illuminate\Http\Response * - * + * * @OA\Put( * path="/api/v1/users/{id}", * operationId="updateUser", @@ -373,20 +361,18 @@ class UserController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), * ) * - */ + */ public function update(UpdateUserRequest $request, User $user) { - $user = $this->user_repo->save($request->all(), $user); return $this->itemResponse($user); - } /** @@ -395,7 +381,7 @@ class UserController extends BaseController * @param int $id * @return \Illuminate\Http\Response * - * + * * @OA\Delete( * path="/api/v1/users/{id}", * operationId="deleteUser", @@ -442,7 +428,7 @@ class UserController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -451,20 +437,18 @@ class UserController extends BaseController */ public function destroy(DestroyUserRequest $request, User $user) { - $user->delete(); return response()->json([], 200); - } /** * Perform bulk actions on the list view - * + * * @return Collection * - * - * + * + * * @OA\Post( * path="/api/v1/users/bulk", * operationId="bulkUsers", @@ -505,7 +489,7 @@ class UserController extends BaseController * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -514,22 +498,19 @@ class UserController extends BaseController */ public function bulk() { - $action = request()->input('action'); $ids = request()->input('ids'); $users = User::withTrashed()->find($this->transformKeys($ids)); - $users->each(function ($user, $key) use($action){ - - if(auth()->user()->can('edit', $user)) + $users->each(function ($user, $key) use ($action) { + if (auth()->user()->can('edit', $user)) { $this->user_repo->{$action}($user); - + } }); return $this->listResponse(User::withTrashed()->whereIn('id', $this->transformKeys($ids))); - } @@ -562,7 +543,7 @@ class UserController extends BaseController * description="The company user object", * required=true, * @OA\JsonContent(ref="#/components/schemas/CompanyUser"), - * ), + * ), * @OA\Response( * response=200, * description="Returns the saved User object", @@ -578,7 +559,7 @@ class UserController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -587,7 +568,6 @@ class UserController extends BaseController */ public function attach(AttachCompanyUserRequest $request, User $user) { - $company = auth()->user()->company(); $user->companies()->attach($company->id, array_merge($request->all(), ['account_id' => $company->account->id])); @@ -595,7 +575,6 @@ class UserController extends BaseController $ct = CreateCompanyToken::dispatchNow($company, $user, 'User token created by'.auth()->user()->present()->name()); return $this->itemResponse($user->fresh()); - } /** @@ -636,7 +615,7 @@ class UserController extends BaseController * * ), * @OA\Response( - * response="default", + * response="default", * description="Unexpected Error", * @OA\JsonContent(ref="#/components/schemas/Error"), * ), @@ -652,6 +631,5 @@ class UserController extends BaseController $company_user->delete(); return response()->json(['message' => 'User detached from company'], 200); - } } diff --git a/app/Http/Controllers/UserProfileController.php b/app/Http/Controllers/UserProfileController.php index 0738f3241e9b..19a16562a19d 100644 --- a/app/Http/Controllers/UserProfileController.php +++ b/app/Http/Controllers/UserProfileController.php @@ -17,9 +17,7 @@ class UserProfileController extends BaseController { public function __construct() { - parent::__construct(); - } /** diff --git a/app/Http/Middleware/ApiSecretCheck.php b/app/Http/Middleware/ApiSecretCheck.php index a76df2f54602..0747ff8114ff 100644 --- a/app/Http/Middleware/ApiSecretCheck.php +++ b/app/Http/Middleware/ApiSecretCheck.php @@ -25,21 +25,17 @@ class ApiSecretCheck */ public function handle($request, Closure $next) { - - if( $request->header('X-API-SECRET') && ($request->header('X-API-SECRET') == config('ninja.api_secret')) ) + if ($request->header('X-API-SECRET') && ($request->header('X-API-SECRET') == config('ninja.api_secret'))) { return $next($request); - else { - + } else { $error = [ 'message' => 'Invalid secret', 'errors' => [] ]; return response() - ->json(json_encode($error, JSON_PRETTY_PRINT) ,403) + ->json(json_encode($error, JSON_PRETTY_PRINT), 403) ->header('X-App-Version', config('ninja.app_version')) ->header('X-Api-Version', config('ninja.api_version')); } - - } } diff --git a/app/Http/Middleware/ClientPortalEnabled.php b/app/Http/Middleware/ClientPortalEnabled.php index 778f8dcd4e9e..55f4592127bc 100644 --- a/app/Http/Middleware/ClientPortalEnabled.php +++ b/app/Http/Middleware/ClientPortalEnabled.php @@ -25,12 +25,11 @@ class ClientPortalEnabled */ public function handle($request, Closure $next) { - - if(auth()->user()->client->getSetting('enable_client_portal') === false) + if (auth()->user()->client->getSetting('enable_client_portal') === false) { return redirect()->to('client/dashboard'); + } return $next($request); - } } diff --git a/app/Http/Middleware/ContactSetDb.php b/app/Http/Middleware/ContactSetDb.php index 78641267938c..092020d2f366 100644 --- a/app/Http/Middleware/ContactSetDb.php +++ b/app/Http/Middleware/ContactSetDb.php @@ -27,33 +27,19 @@ class ContactSetDb public function handle($request, Closure $next) { - - $error = [ 'message' => 'Invalid Token', 'errors' => [] ]; - if( $request->header('X-API-TOKEN') && config('ninja.db.multi_db_enabled')) - { - - if(! MultiDB::contactFindAndSetDb($request->header('X-API-TOKEN'))) - { - - return response()->json(json_encode($error, JSON_PRETTY_PRINT) ,403); - + if ($request->header('X-API-TOKEN') && config('ninja.db.multi_db_enabled')) { + if (! MultiDB::contactFindAndSetDb($request->header('X-API-TOKEN'))) { + return response()->json(json_encode($error, JSON_PRETTY_PRINT), 403); } - - } - else { - - - return response()->json(json_encode($error, JSON_PRETTY_PRINT) ,403); - + } else { + return response()->json(json_encode($error, JSON_PRETTY_PRINT), 403); } return $next($request); } - - } diff --git a/app/Http/Middleware/ContactTokenAuth.php b/app/Http/Middleware/ContactTokenAuth.php index 5291566f1f0e..1f0d56ba697b 100644 --- a/app/Http/Middleware/ContactTokenAuth.php +++ b/app/Http/Middleware/ContactTokenAuth.php @@ -28,18 +28,16 @@ class ContactTokenAuth */ public function handle($request, Closure $next) { - - if( $request->header('X-API-TOKEN') && ($client_contact = ClientContact::with(['company'])->whereRaw("BINARY `token`= ?",[$request->header('X-API-TOKEN')])->first() ) ) - { - + if ($request->header('X-API-TOKEN') && ($client_contact = ClientContact::with(['company'])->whereRaw("BINARY `token`= ?", [$request->header('X-API-TOKEN')])->first())) { $error = [ 'message' => 'Authentication disabled for user.', 'errors' => [] ]; - //client_contact who once existed, but has been soft deleted - if(!$client_contact) - return response()->json(json_encode($error, JSON_PRETTY_PRINT) ,403); + //client_contact who once existed, but has been soft deleted + if (!$client_contact) { + return response()->json(json_encode($error, JSON_PRETTY_PRINT), 403); + } $error = [ @@ -48,26 +46,23 @@ class ContactTokenAuth ]; //client_contact who has been disabled - if($client_contact->is_locked) - return response()->json(json_encode($error, JSON_PRETTY_PRINT) ,403); + if ($client_contact->is_locked) { + return response()->json(json_encode($error, JSON_PRETTY_PRINT), 403); + } //stateless, don't remember the contact. - auth()->guard('contact')->login($client_contact, false); + auth()->guard('contact')->login($client_contact, false); event(new ContactLoggedIn($client_contact)); //todo - - } - else { - + } else { $error = [ 'message' => 'Invalid token', 'errors' => [] ]; - return response()->json(json_encode($error, JSON_PRETTY_PRINT) ,403); + return response()->json(json_encode($error, JSON_PRETTY_PRINT), 403); } return $next($request); } - } diff --git a/app/Http/Middleware/Cors.php b/app/Http/Middleware/Cors.php index 732b7716748b..88c4c613f13b 100644 --- a/app/Http/Middleware/Cors.php +++ b/app/Http/Middleware/Cors.php @@ -8,41 +8,36 @@ use Symfony\Component\HttpFoundation\BinaryFileResponse; class Cors { + public function handle($request, Closure $next) + { + if ($request->getMethod() == "OPTIONS") { + header("Access-Control-Allow-Origin: *"); - public function handle($request, Closure $next) - { - - if($request->getMethod() == "OPTIONS") { - header("Access-Control-Allow-Origin: *"); - - // ALLOW OPTIONS METHOD - $headers = [ - 'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE', - 'Access-Control-Allow-Headers'=> 'X-API-SECRET,X-API-TOKEN,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' - ]; + // ALLOW OPTIONS METHOD + $headers = [ + 'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE', + 'Access-Control-Allow-Headers'=> 'X-API-SECRET,X-API-TOKEN,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' + ]; return Response::make('OK', 200, $headers); - } - /* Work around for file downloads where the response cannot contain have headers set */ - // if($request instanceOf BinaryFileResponse) - // return $next($request); - // else - // return $next($request) - // ->header('Access-Control-Allow-Origin', '*') - // ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS') - // ->header('Access-Control-Allow-Headers', 'X-API-SECRET,X-API-TOKEN,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'); + /* Work around for file downloads where the response cannot contain have headers set */ + // if($request instanceOf BinaryFileResponse) + // return $next($request); + // else + // return $next($request) + // ->header('Access-Control-Allow-Origin', '*') + // ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS') + // ->header('Access-Control-Allow-Headers', 'X-API-SECRET,X-API-TOKEN,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'); - $response = $next($request); + $response = $next($request); - $response->headers->set('Access-Control-Allow-Origin' , '*'); - $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); - $response->headers->set('Access-Control-Allow-Headers', 'X-API-SECRET,X-API-TOKEN,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'); + $response->headers->set('Access-Control-Allow-Origin', '*'); + $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); + $response->headers->set('Access-Control-Allow-Headers', 'X-API-SECRET,X-API-TOKEN,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'); - return $response; - - } - -} \ No newline at end of file + return $response; + } +} diff --git a/app/Http/Middleware/Locale.php b/app/Http/Middleware/Locale.php index cac47a70c35b..e9610eea5650 100644 --- a/app/Http/Middleware/Locale.php +++ b/app/Http/Middleware/Locale.php @@ -27,9 +27,9 @@ class Locale App::setLocale(auth('contact')->user()->client->locale()); } elseif (auth()->user()) { App::setLocale(auth()->user()->company()->getLocale()); - } - else + } else { App::setLocale(config('ninja.i18n.locale')); + } return $next($request); } diff --git a/app/Http/Middleware/PasswordProtection.php b/app/Http/Middleware/PasswordProtection.php index 939784bb7762..ee9f308ccc2d 100644 --- a/app/Http/Middleware/PasswordProtection.php +++ b/app/Http/Middleware/PasswordProtection.php @@ -30,36 +30,27 @@ class PasswordProtection public function handle($request, Closure $next) { - $error = [ 'message' => 'Invalid Password', 'errors' => [] ]; - if( $request->header('X-API-PASSWORD') ) - { - - if(!Hash::check($request->header('X-API-PASSWORD'), auth()->user()->password)) + if ($request->header('X-API-PASSWORD')) { + if ($request->header('X-API-PASSWORD') != auth()->user()->password) { return response()->json($error, 403); - - } - elseif (Cache::get(auth()->user()->email."_logged_in")) { + } + } elseif (Cache::get(auth()->user()->email."_logged_in")) { return $next($request); - } - else { - + } else { $error = [ 'message' => 'Access denied', 'errors' => [] ]; - return response()->json($error, 412); - + return response()->json($error, 412); } Cache::add(auth()->user()->email."_logged_in", Str::random(64), now()->addMinutes(10)); return $next($request); } - - } diff --git a/app/Http/Middleware/QueryLogging.php b/app/Http/Middleware/QueryLogging.php index 128144656e87..e4c84cc88bab 100644 --- a/app/Http/Middleware/QueryLogging.php +++ b/app/Http/Middleware/QueryLogging.php @@ -32,14 +32,14 @@ class QueryLogging public function handle(Request $request, Closure $next) { // Enable query logging for development - if(config('ninja.app_env') != 'production') { + if (config('ninja.app_env') != 'production') { DB::enableQueryLog(); $timeStart = microtime(true); } $response = $next($request); - if(config('ninja.app_env') != 'production') { + if (config('ninja.app_env') != 'production') { // hide requests made by debugbar if (strstr($request->url(), '_debugbar') === false) { @@ -49,10 +49,9 @@ class QueryLogging $time = $timeEnd - $timeStart; Log::info($request->method() . ' - ' . $request->url() . ": $count queries - " . $time); - // if($count > 50) + // if($count > 50) // Log::info($queries); } - } return $response; diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php index da284e3bb176..a3805acaec5a 100644 --- a/app/Http/Middleware/RedirectIfAuthenticated.php +++ b/app/Http/Middleware/RedirectIfAuthenticated.php @@ -26,15 +26,15 @@ class RedirectIfAuthenticated */ public function handle($request, Closure $next, $guard = null) { - switch ($guard) { + switch ($guard) { case 'contact': if (Auth::guard($guard)->check()) { - return redirect()->route('client.dashboard'); + return redirect()->route('client.dashboard'); } break; case 'user': if (Auth::guard($guard)->check()) { - return redirect()->route('dashboard.index'); + return redirect()->route('dashboard.index'); } break; default: @@ -43,6 +43,6 @@ class RedirectIfAuthenticated } break; } - return $next($request); + return $next($request); } } diff --git a/app/Http/Middleware/SetDb.php b/app/Http/Middleware/SetDb.php index 036da2e4722d..6a0abe80c56f 100644 --- a/app/Http/Middleware/SetDb.php +++ b/app/Http/Middleware/SetDb.php @@ -27,37 +27,22 @@ class SetDb public function handle($request, Closure $next) { - $error = [ 'message' => 'Invalid Token', 'errors' => [] ]; - if( $request->header('X-API-TOKEN') && config('ninja.db.multi_db_enabled')) - { - - if(! MultiDB::findAndSetDb($request->header('X-API-TOKEN'))) - { - + if ($request->header('X-API-TOKEN') && config('ninja.db.multi_db_enabled')) { + if (! MultiDB::findAndSetDb($request->header('X-API-TOKEN'))) { return response()->json($error, 403); - } - - } - else if(!config('ninja.db.multi_db_enabled')){ - + } elseif (!config('ninja.db.multi_db_enabled')) { return $next($request); - } - else { - - - return response()->json($error, 403); - + } else { + return response()->json($error, 403); } return $next($request); } - - } diff --git a/app/Http/Middleware/SetDomainNameDb.php b/app/Http/Middleware/SetDomainNameDb.php index 54bd3459244c..4d8b78f49a73 100644 --- a/app/Http/Middleware/SetDomainNameDb.php +++ b/app/Http/Middleware/SetDomainNameDb.php @@ -26,24 +26,21 @@ class SetDomainNameDb public function handle($request, Closure $next) { - - $error = [ + $error = [ 'message' => 'Invalid token', 'errors' => [] ]; - /* + /* * Use the host name to set the active DB **/ - if( $request->getSchemeAndHttpHost() && config('ninja.db.multi_db_enabled') && ! MultiDB::findAndSetDbByDomain($request->getSchemeAndHttpHost())) - { - if(request()->json) - return response()->json(json_encode($error, JSON_PRETTY_PRINT) ,403); - else + if ($request->getSchemeAndHttpHost() && config('ninja.db.multi_db_enabled') && ! MultiDB::findAndSetDbByDomain($request->getSchemeAndHttpHost())) { + if (request()->json) { + return response()->json(json_encode($error, JSON_PRETTY_PRINT), 403); + } else { abort(404); + } } return $next($request); } - - } diff --git a/app/Http/Middleware/SetEmailDb.php b/app/Http/Middleware/SetEmailDb.php index 39d12ca0b997..349692674294 100644 --- a/app/Http/Middleware/SetEmailDb.php +++ b/app/Http/Middleware/SetEmailDb.php @@ -27,32 +27,19 @@ class SetEmailDb public function handle($request, Closure $next) { - $error = [ 'message' => 'Email not set or not found', 'errors' => [] ]; - if( $request->input('email') && config('ninja.db.multi_db_enabled')) - { - - if(! MultiDB::userFindAndSetDb($request->input('email'))) - { - + if ($request->input('email') && config('ninja.db.multi_db_enabled')) { + if (! MultiDB::userFindAndSetDb($request->input('email'))) { return response()->json($error, 403); - } - - } - else { - - - return response()->json($error, 403); - + } else { + return response()->json($error, 403); } return $next($request); } - - } diff --git a/app/Http/Middleware/SetInviteDb.php b/app/Http/Middleware/SetInviteDb.php index ef2e7764ece3..518c9a0ba95c 100644 --- a/app/Http/Middleware/SetInviteDb.php +++ b/app/Http/Middleware/SetInviteDb.php @@ -26,24 +26,21 @@ class SetInviteDb public function handle($request, Closure $next) { - - $error = [ + $error = [ 'message' => 'Invalid URL', 'errors' => [] ]; - /* + /* * Use the host name to set the active DB **/ - if( $request->getSchemeAndHttpHost() && config('ninja.db.multi_db_enabled') && ! MultiDB::findAndSetDbByInvitation($request->route('entity'),$request->route('invitation_key'))) - { - if(request()->json) - return response()->json(json_encode($error, JSON_PRETTY_PRINT) ,403); - else + if ($request->getSchemeAndHttpHost() && config('ninja.db.multi_db_enabled') && ! MultiDB::findAndSetDbByInvitation($request->route('entity'), $request->route('invitation_key'))) { + if (request()->json) { + return response()->json(json_encode($error, JSON_PRETTY_PRINT), 403); + } else { abort(404); + } } return $next($request); } - - } diff --git a/app/Http/Middleware/SetWebDb.php b/app/Http/Middleware/SetWebDb.php index f7a1e6b8290a..5b8da4165cdf 100644 --- a/app/Http/Middleware/SetWebDb.php +++ b/app/Http/Middleware/SetWebDb.php @@ -17,15 +17,11 @@ class SetWebDb */ public function handle($request, Closure $next) { - - if (config('ninja.db.multi_db_enabled')) - { - + if (config('ninja.db.multi_db_enabled')) { MultiDB::setDB(Cookie::get('db')); - } return $next($request); } -} \ No newline at end of file +} diff --git a/app/Http/Middleware/StartupCheck.php b/app/Http/Middleware/StartupCheck.php index 51d01b4f0eef..a10e6f03c8d3 100644 --- a/app/Http/Middleware/StartupCheck.php +++ b/app/Http/Middleware/StartupCheck.php @@ -21,7 +21,6 @@ use Illuminate\Support\Facades\Request as Input; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Session; - /** * Class StartupCheck. */ @@ -37,13 +36,14 @@ class StartupCheck */ public function handle(Request $request, Closure $next) { - // $start = microtime(true); - // Log::error('start up check'); + // $start = microtime(true); + // Log::error('start up check'); $cached_tables = config('ninja.cached_tables'); - if (Input::has('clear_cache')) + if (Input::has('clear_cache')) { Session::flash('message', 'Cache cleared'); + } foreach ($cached_tables as $name => $class) { if (Input::has('clear_cache') || ! Cache::has($name)) { diff --git a/app/Http/Middleware/TokenAuth.php b/app/Http/Middleware/TokenAuth.php index 5ae780f20936..6843f6eecf0e 100644 --- a/app/Http/Middleware/TokenAuth.php +++ b/app/Http/Middleware/TokenAuth.php @@ -27,10 +27,7 @@ class TokenAuth */ public function handle($request, Closure $next) { - - if( $request->header('X-API-TOKEN') && ($company_token = CompanyToken::with(['user','company'])->whereRaw("BINARY `token`= ?",[$request->header('X-API-TOKEN')])->first() ) ) - { - + if ($request->header('X-API-TOKEN') && ($company_token = CompanyToken::with(['user','company'])->whereRaw("BINARY `token`= ?", [$request->header('X-API-TOKEN')])->first())) { $user = $company_token->user; @@ -39,46 +36,42 @@ class TokenAuth 'errors' => [] ]; //user who once existed, but has been soft deleted - if(!$user) - return response()->json(json_encode($error, JSON_PRETTY_PRINT) ,403); + if (!$user) { + return response()->json(json_encode($error, JSON_PRETTY_PRINT), 403); + } /* | - | Necessary evil here: As we are authenticating on CompanyToken, + | Necessary evil here: As we are authenticating on CompanyToken, | we need to link the company to the user manually. This allows | us to decouple a $user and their attached companies completely. | */ - $user->setCompany($company_token->company); - - //user who once existed, but has been soft deleted - if($user->company_user->is_locked){ + $user->setCompany($company_token->company); + //user who once existed, but has been soft deleted + if ($user->company_user->is_locked) { $error = [ 'message' => 'User access locked', 'errors' => [] ]; - return response()->json(json_encode($error, JSON_PRETTY_PRINT) ,403); + return response()->json(json_encode($error, JSON_PRETTY_PRINT), 403); } //stateless, don't remember the user. - auth()->login($user, false); + auth()->login($user, false); event(new UserLoggedIn($user)); - - } - else { - + } else { $error = [ 'message' => 'Invalid token', 'errors' => [] ]; - return response()->json(json_encode($error, JSON_PRETTY_PRINT) ,403); + return response()->json(json_encode($error, JSON_PRETTY_PRINT), 403); } return $next($request); } - } diff --git a/app/Http/Middleware/UrlSetDb.php b/app/Http/Middleware/UrlSetDb.php index 0e8bb10903c5..6b21d683fe22 100644 --- a/app/Http/Middleware/UrlSetDb.php +++ b/app/Http/Middleware/UrlSetDb.php @@ -31,9 +31,7 @@ class UrlSetDb public function handle($request, Closure $next) { - - if (config('ninja.db.multi_db_enabled')) - { + if (config('ninja.db.multi_db_enabled')) { $hashids = new Hashids('', 10); //decoded output is _always_ an array. //parse URL hash and set DB @@ -41,7 +39,7 @@ class UrlSetDb $hashed_db = $hashids->decode($segments[0]); - MultiDB::setDB(MultiDB::DB_PREFIX . str_pad($hashed_db[0], 2 , "0", STR_PAD_LEFT)); + MultiDB::setDB(MultiDB::DB_PREFIX . str_pad($hashed_db[0], 2, "0", STR_PAD_LEFT)); } return $next($request); diff --git a/app/Http/Requests/Account/CreateAccountRequest.php b/app/Http/Requests/Account/CreateAccountRequest.php index 4c6f8d2478d9..288a0ba2aded 100644 --- a/app/Http/Requests/Account/CreateAccountRequest.php +++ b/app/Http/Requests/Account/CreateAccountRequest.php @@ -35,7 +35,6 @@ class CreateAccountRequest extends Request */ public function rules() { - return [ //'email' => 'required|string|email|max:100', 'first_name' => 'required|string|max:100', @@ -50,13 +49,10 @@ class CreateAccountRequest extends Request protected function prepareForValidation() { - $input = $this->all(); $input['user_agent'] = request()->server('HTTP_USER_AGENT'); $this->replace($input); - } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Activity/ShowActivityRequest.php b/app/Http/Requests/Activity/ShowActivityRequest.php index 525be51acb1a..13f7306b5e1e 100644 --- a/app/Http/Requests/Activity/ShowActivityRequest.php +++ b/app/Http/Requests/Activity/ShowActivityRequest.php @@ -26,5 +26,4 @@ class ShowActivityRequest extends Request { return auth()->user()->can('view', Activity::class); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Client/CreateClientRequest.php b/app/Http/Requests/Client/CreateClientRequest.php index b768509bd6f6..1e7d4ffd9ad7 100644 --- a/app/Http/Requests/Client/CreateClientRequest.php +++ b/app/Http/Requests/Client/CreateClientRequest.php @@ -26,5 +26,4 @@ class CreateClientRequest extends Request { return auth()->user()->can('create', Client::class); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Client/DestroyClientRequest.php b/app/Http/Requests/Client/DestroyClientRequest.php index cbd23b545198..2f5890db9dff 100644 --- a/app/Http/Requests/Client/DestroyClientRequest.php +++ b/app/Http/Requests/Client/DestroyClientRequest.php @@ -26,5 +26,4 @@ class DestroyClientRequest extends Request { return auth()->user()->can('edit', $this->client); } - } diff --git a/app/Http/Requests/Client/EditClientRequest.php b/app/Http/Requests/Client/EditClientRequest.php index 65d5e6e496fc..ed392ee904ee 100644 --- a/app/Http/Requests/Client/EditClientRequest.php +++ b/app/Http/Requests/Client/EditClientRequest.php @@ -36,5 +36,4 @@ class EditClientRequest extends Request // $this->replace($input); // } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Client/ShowClientRequest.php b/app/Http/Requests/Client/ShowClientRequest.php index 6d002b029f58..8a0e1c2e409c 100644 --- a/app/Http/Requests/Client/ShowClientRequest.php +++ b/app/Http/Requests/Client/ShowClientRequest.php @@ -26,5 +26,4 @@ class ShowClientRequest extends Request { return auth()->user()->can('view', $this->client); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Client/StoreClientRequest.php b/app/Http/Requests/Client/StoreClientRequest.php index b31d850a12bb..ab9dd6ef1ef3 100644 --- a/app/Http/Requests/Client/StoreClientRequest.php +++ b/app/Http/Requests/Client/StoreClientRequest.php @@ -31,9 +31,7 @@ class StoreClientRequest extends Request public function authorize() : bool { - return auth()->user()->can('create', Client::class); - } public function rules() @@ -47,18 +45,14 @@ class StoreClientRequest extends Request $contacts = request('contacts'); - if(is_array($contacts)) - { - + if (is_array($contacts)) { for ($i = 0; $i < count($contacts); $i++) { //$rules['contacts.' . $i . '.email'] = 'nullable|email|distinct'; } - } return $rules; - } @@ -66,13 +60,15 @@ class StoreClientRequest extends Request { $input = $this->all(); - if(!isset($input['settings'])) + if (!isset($input['settings'])) { $input['settings'] = ClientSettings::defaults(); + } - if(isset($input['group_settings_id'])) + if (isset($input['group_settings_id'])) { $input['group_settings_id'] = $this->decodePrimaryKey($input['group_settings_id']); + } - $this->replace($input); + $this->replace($input); } public function messages() @@ -83,6 +79,4 @@ class StoreClientRequest extends Request 'contacts.*.email.required' => ctrans('validation.email', ['attribute' => 'email']), ]; } - - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Client/UpdateClientRequest.php b/app/Http/Requests/Client/UpdateClientRequest.php index bdec9aa649e5..07eb49d580a2 100644 --- a/app/Http/Requests/Client/UpdateClientRequest.php +++ b/app/Http/Requests/Client/UpdateClientRequest.php @@ -12,7 +12,9 @@ namespace App\Http\Requests\Client; use App\Http\Requests\Request; +use App\Http\ValidationRules\IsDeletedRule; use App\Http\ValidationRules\ValidClientGroupSettingsRule; +use App\Utils\Traits\ChecksEntityStatus; use App\Utils\Traits\MakesHash; use Illuminate\Support\Facades\Log; use Illuminate\Validation\Rule; @@ -20,6 +22,7 @@ use Illuminate\Validation\Rule; class UpdateClientRequest extends Request { use MakesHash; + use ChecksEntityStatus; /** * Determine if the user is authorized to make this request. * @@ -47,16 +50,13 @@ class UpdateClientRequest extends Request $contacts = request('contacts'); - if(is_array($contacts)) - { - // for ($i = 0; $i < count($contacts); $i++) { + if (is_array($contacts)) { + // for ($i = 0; $i < count($contacts); $i++) { // // $rules['contacts.' . $i . '.email'] = 'nullable|email|unique:client_contacts,email,' . isset($contacts[$i]['id'].',company_id,'.$this->company_id); // //$rules['contacts.' . $i . '.email'] = 'nullable|email'; // } - } - return $rules; - - + } + return $rules; } public function messages() @@ -74,11 +74,10 @@ class UpdateClientRequest extends Request $input = $this->all(); - if(isset($input['group_settings_id'])) + if (isset($input['group_settings_id'])) { $input['group_settings_id'] = $this->decodePrimaryKey($input['group_settings_id']); + } $this->replace($input); - } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/ClientPortal/ShowInvoiceRequest.php b/app/Http/Requests/ClientPortal/ShowInvoiceRequest.php index d36b264ce5a0..0220d529909c 100644 --- a/app/Http/Requests/ClientPortal/ShowInvoiceRequest.php +++ b/app/Http/Requests/ClientPortal/ShowInvoiceRequest.php @@ -26,5 +26,4 @@ class ShowInvoiceRequest extends Request { return auth()->user()->client->id === $this->invoice->client_id; } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/ClientPortal/ShowRecurringInvoiceRequest.php b/app/Http/Requests/ClientPortal/ShowRecurringInvoiceRequest.php index 92aee323e93d..1fe08d43c2c2 100644 --- a/app/Http/Requests/ClientPortal/ShowRecurringInvoiceRequest.php +++ b/app/Http/Requests/ClientPortal/ShowRecurringInvoiceRequest.php @@ -26,5 +26,4 @@ class ShowRecurringInvoiceRequest extends Request { return auth()->user()->client->id === $this->recurring_invoice->client_id; } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/ClientPortal/StoreDocumentRequest.php b/app/Http/Requests/ClientPortal/StoreDocumentRequest.php index d69d69caa29d..3b7bcfb3c072 100644 --- a/app/Http/Requests/ClientPortal/StoreDocumentRequest.php +++ b/app/Http/Requests/ClientPortal/StoreDocumentRequest.php @@ -29,17 +29,13 @@ class StoreDocumentRequest extends Request public function rules() { - return [ 'file' => 'required|max:10000|mimes:png,svg,jpeg,gif,jpg,bmp' ]; - } public function response(array $errors) { return new JsonResponse(['error' => $errors], 400); } - } - diff --git a/app/Http/Requests/ClientPortal/UpdateClientRequest.php b/app/Http/Requests/ClientPortal/UpdateClientRequest.php index 563b980af206..f7b26bde71a3 100644 --- a/app/Http/Requests/ClientPortal/UpdateClientRequest.php +++ b/app/Http/Requests/ClientPortal/UpdateClientRequest.php @@ -31,15 +31,9 @@ class UpdateClientRequest extends Request public function rules() { - return [ 'name' => 'required', 'file' => 'sometimes|nullable|max:100000|mimes:png,svg,jpeg,gif,jpg,bmp' ]; - } - - - } - diff --git a/app/Http/Requests/ClientPortal/UpdateContactRequest.php b/app/Http/Requests/ClientPortal/UpdateContactRequest.php index bd07dd11dd85..1a0a113f3a29 100644 --- a/app/Http/Requests/ClientPortal/UpdateContactRequest.php +++ b/app/Http/Requests/ClientPortal/UpdateContactRequest.php @@ -32,17 +32,11 @@ class UpdateContactRequest extends Request public function rules() { - return [ 'first_name' => 'required', 'last_name' => 'required', 'email' => 'required|email|unique:client_contacts,email,' . auth()->user()->id, 'password' => 'sometimes|nullable|min:6|confirmed', ]; - } - - - } - diff --git a/app/Http/Requests/Company/CreateCompanyRequest.php b/app/Http/Requests/Company/CreateCompanyRequest.php index 88471b9b7d6e..137cc2d12cc8 100644 --- a/app/Http/Requests/Company/CreateCompanyRequest.php +++ b/app/Http/Requests/Company/CreateCompanyRequest.php @@ -24,9 +24,6 @@ class CreateCompanyRequest extends Request public function authorize() : bool { - return auth()->user()->can('create', Company::class); - } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Company/DestroyCompanyRequest.php b/app/Http/Requests/Company/DestroyCompanyRequest.php index 7a76b1df6fff..715394dae10e 100644 --- a/app/Http/Requests/Company/DestroyCompanyRequest.php +++ b/app/Http/Requests/Company/DestroyCompanyRequest.php @@ -26,5 +26,4 @@ class DestroyCompanyRequest extends Request { return auth()->user()->isOwner(); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Company/EditCompanyRequest.php b/app/Http/Requests/Company/EditCompanyRequest.php index 2d4f39bfb619..525d33c1acfe 100644 --- a/app/Http/Requests/Company/EditCompanyRequest.php +++ b/app/Http/Requests/Company/EditCompanyRequest.php @@ -43,5 +43,4 @@ class EditCompanyRequest extends Request $this->replace($input); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Company/ShowCompanyRequest.php b/app/Http/Requests/Company/ShowCompanyRequest.php index 6a2785ae2fc3..ff65b17cb78d 100644 --- a/app/Http/Requests/Company/ShowCompanyRequest.php +++ b/app/Http/Requests/Company/ShowCompanyRequest.php @@ -26,5 +26,4 @@ class ShowCompanyRequest extends Request { return auth()->user()->can('view', $this->company); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Company/StoreCompanyRequest.php b/app/Http/Requests/Company/StoreCompanyRequest.php index 148e5a50424a..da723f53d000 100644 --- a/app/Http/Requests/Company/StoreCompanyRequest.php +++ b/app/Http/Requests/Company/StoreCompanyRequest.php @@ -35,16 +35,14 @@ class StoreCompanyRequest extends Request //$rules['name'] = 'required'; $rules['company_logo'] = 'mimes:jpeg,jpg,png,gif|max:10000'; // max 10000kb - $rules['settings'] = new ValidSettingsRule(); + $rules['settings'] = new ValidSettingsRule(); - if(isset($rules['portal_mode']) && ($rules['portal_mode'] == 'domain' || $rules['portal_mode'] == 'iframe')) + if (isset($rules['portal_mode']) && ($rules['portal_mode'] == 'domain' || $rules['portal_mode'] == 'iframe')) { $rules['portal_domain'] = 'sometimes|url'; - else + } else { $rules['portal_domain'] = 'nullable|alpha_num'; + } return $rules; } - - } - diff --git a/app/Http/Requests/Company/UpdateCompanyRequest.php b/app/Http/Requests/Company/UpdateCompanyRequest.php index 4a5b0d44956e..5499d6262fdd 100644 --- a/app/Http/Requests/Company/UpdateCompanyRequest.php +++ b/app/Http/Requests/Company/UpdateCompanyRequest.php @@ -26,15 +26,12 @@ class UpdateCompanyRequest extends Request public function authorize() : bool { - return auth()->user()->can('edit', $this->company); - } public function rules() { - $rules = []; $rules['company_logo'] = 'mimes:jpeg,jpg,png,gif|max:10000'; // max 10000kb @@ -44,15 +41,12 @@ class UpdateCompanyRequest extends Request $rules['country_id'] = 'integer|nullable'; $rules['work_email'] = 'email|nullable'; - if(isset($rules['portal_mode']) && ($rules['portal_mode'] == 'domain' || $rules['portal_mode'] == 'iframe')) + if (isset($rules['portal_mode']) && ($rules['portal_mode'] == 'domain' || $rules['portal_mode'] == 'iframe')) { $rules['portal_domain'] = 'sometimes|url'; - else + } else { $rules['portal_domain'] = 'nullable|alpha_num'; + } return $rules; - } - } - - diff --git a/app/Http/Requests/CompanyGateway/CreateCompanyGatewayRequest.php b/app/Http/Requests/CompanyGateway/CreateCompanyGatewayRequest.php index 54c9c4ec0d2b..12429bab3041 100644 --- a/app/Http/Requests/CompanyGateway/CreateCompanyGatewayRequest.php +++ b/app/Http/Requests/CompanyGateway/CreateCompanyGatewayRequest.php @@ -24,10 +24,6 @@ class CreateCompanyGatewayRequest extends Request public function authorize() : bool { - return auth()->user()->isAdmin(); - } - - -} \ No newline at end of file +} diff --git a/app/Http/Requests/CompanyGateway/DestroyCompanyGatewayRequest.php b/app/Http/Requests/CompanyGateway/DestroyCompanyGatewayRequest.php index 3e209eb6073c..fee928c43460 100644 --- a/app/Http/Requests/CompanyGateway/DestroyCompanyGatewayRequest.php +++ b/app/Http/Requests/CompanyGateway/DestroyCompanyGatewayRequest.php @@ -42,7 +42,5 @@ class DestroyCompanyGatewayRequest extends Request //$input['id'] = $this->encodePrimaryKey($input['id']); $this->replace($input); - } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/CompanyGateway/EditCompanyGatewayRequest.php b/app/Http/Requests/CompanyGateway/EditCompanyGatewayRequest.php index f961092cca1f..3f691b6ae325 100644 --- a/app/Http/Requests/CompanyGateway/EditCompanyGatewayRequest.php +++ b/app/Http/Requests/CompanyGateway/EditCompanyGatewayRequest.php @@ -43,5 +43,4 @@ class EditCompanyGatewayRequest extends Request $this->replace($input); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/CompanyGateway/ShowCompanyGatewayRequest.php b/app/Http/Requests/CompanyGateway/ShowCompanyGatewayRequest.php index 6d345143e270..8d9240b8a0e7 100644 --- a/app/Http/Requests/CompanyGateway/ShowCompanyGatewayRequest.php +++ b/app/Http/Requests/CompanyGateway/ShowCompanyGatewayRequest.php @@ -43,5 +43,4 @@ class ShowCompanyGatewayRequest extends Request $this->replace($input); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/CompanyGateway/StoreCompanyGatewayRequest.php b/app/Http/Requests/CompanyGateway/StoreCompanyGatewayRequest.php index a1902944175e..e7941f4596a1 100644 --- a/app/Http/Requests/CompanyGateway/StoreCompanyGatewayRequest.php +++ b/app/Http/Requests/CompanyGateway/StoreCompanyGatewayRequest.php @@ -26,14 +26,11 @@ class StoreCompanyGatewayRequest extends Request public function authorize() : bool { - return auth()->user()->isAdmin(); - } public function rules() { - $rules = [ 'gateway_key' => 'required', 'fees_and_limits' => new ValidCompanyGatewayFeesAndLimitsRule(), @@ -46,14 +43,14 @@ class StoreCompanyGatewayRequest extends Request { $input = $this->all(); - if(isset($input['config'])) + if (isset($input['config'])) { $input['config'] = encrypt($input['config']); + } - if(isset($input['fees_and_limits'])) + if (isset($input['fees_and_limits'])) { $input['fees_and_limits'] = $this->cleanFeesAndLimits($input['fees_and_limits']); + } $this->replace($input); - } } - diff --git a/app/Http/Requests/CompanyGateway/UpdateCompanyGatewayRequest.php b/app/Http/Requests/CompanyGateway/UpdateCompanyGatewayRequest.php index 4bd1f51dccb3..5749ef0a5abd 100644 --- a/app/Http/Requests/CompanyGateway/UpdateCompanyGatewayRequest.php +++ b/app/Http/Requests/CompanyGateway/UpdateCompanyGatewayRequest.php @@ -33,7 +33,6 @@ class UpdateCompanyGatewayRequest extends Request public function rules() { - $rules = [ 'fees_and_limits' => new ValidCompanyGatewayFeesAndLimitsRule(), ]; @@ -47,12 +46,10 @@ class UpdateCompanyGatewayRequest extends Request $input['config'] = encrypt($input['config']); - if(isset($input['fees_and_limits'])) + if (isset($input['fees_and_limits'])) { $input['fees_and_limits'] = $this->cleanFeesAndLimits($input['fees_and_limits']); + } $this->replace($input); } - } - - diff --git a/app/Http/Requests/GroupSetting/CreateGroupSettingRequest.php b/app/Http/Requests/GroupSetting/CreateGroupSettingRequest.php index 672a6e425b4e..34d52ccaa2c3 100644 --- a/app/Http/Requests/GroupSetting/CreateGroupSettingRequest.php +++ b/app/Http/Requests/GroupSetting/CreateGroupSettingRequest.php @@ -27,6 +27,4 @@ class CreateGroupSettingRequest extends Request { return auth()->user()->can('create', GroupSetting::class); } - - -} \ No newline at end of file +} diff --git a/app/Http/Requests/GroupSetting/DestroyGroupSettingRequest.php b/app/Http/Requests/GroupSetting/DestroyGroupSettingRequest.php index 3ef0a126296a..55c5640af9ba 100644 --- a/app/Http/Requests/GroupSetting/DestroyGroupSettingRequest.php +++ b/app/Http/Requests/GroupSetting/DestroyGroupSettingRequest.php @@ -26,5 +26,4 @@ class DestroyGroupSettingRequest extends Request { return auth()->user()->can('edit', $this->group_setting); } - } diff --git a/app/Http/Requests/GroupSetting/EditGroupSettingRequest.php b/app/Http/Requests/GroupSetting/EditGroupSettingRequest.php index 5ce73e99dbf3..da191fd69765 100644 --- a/app/Http/Requests/GroupSetting/EditGroupSettingRequest.php +++ b/app/Http/Requests/GroupSetting/EditGroupSettingRequest.php @@ -26,6 +26,4 @@ class EditGroupSettingRequest extends Request { return auth()->user()->can('edit', $this->group_setting); } - - -} \ No newline at end of file +} diff --git a/app/Http/Requests/GroupSetting/ShowGroupSettingRequest.php b/app/Http/Requests/GroupSetting/ShowGroupSettingRequest.php index d22c50ca67ff..4021ac8a707f 100644 --- a/app/Http/Requests/GroupSetting/ShowGroupSettingRequest.php +++ b/app/Http/Requests/GroupSetting/ShowGroupSettingRequest.php @@ -26,5 +26,4 @@ class ShowGroupSettingRequest extends Request { return auth()->user()->can('view', $this->group_setting); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php b/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php index daf09f94a91d..45688fafdc1a 100644 --- a/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php +++ b/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php @@ -27,14 +27,11 @@ class StoreGroupSettingRequest extends Request public function authorize() : bool { - return auth()->user()->can('create', GroupSetting::class); - } public function rules() { - $rules['name'] = 'required'; $rules['settings'] = new ValidClientGroupSettingsRule(); @@ -47,8 +44,7 @@ class StoreGroupSettingRequest extends Request $input['settings'] = ClientSettings::defaults(); - $this->replace($input); - + $this->replace($input); } @@ -58,6 +54,4 @@ class StoreGroupSettingRequest extends Request 'settings' => 'settings must be a valid json structure' ]; } - - -} \ No newline at end of file +} diff --git a/app/Http/Requests/GroupSetting/UpdateGroupSettingRequest.php b/app/Http/Requests/GroupSetting/UpdateGroupSettingRequest.php index ba57f7cda404..b9d1d8e931b1 100644 --- a/app/Http/Requests/GroupSetting/UpdateGroupSettingRequest.php +++ b/app/Http/Requests/GroupSetting/UpdateGroupSettingRequest.php @@ -31,21 +31,15 @@ class UpdateGroupSettingRequest extends Request public function rules() { - $rules['settings'] = new ValidClientGroupSettingsRule(); return $rules; - } protected function prepareForValidation() { $input = $this->all(); - $this->replace($input); - + $this->replace($input); } - - - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Invoice/ActionInvoiceRequest.php b/app/Http/Requests/Invoice/ActionInvoiceRequest.php index c34c26fd57b5..843654c4e877 100644 --- a/app/Http/Requests/Invoice/ActionInvoiceRequest.php +++ b/app/Http/Requests/Invoice/ActionInvoiceRequest.php @@ -26,5 +26,4 @@ class ActionInvoiceRequest extends Request { return auth()->user()->can('edit', $this->invoice); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Invoice/CreateInvoiceRequest.php b/app/Http/Requests/Invoice/CreateInvoiceRequest.php index dc0ea87d8f70..425d56b52949 100644 --- a/app/Http/Requests/Invoice/CreateInvoiceRequest.php +++ b/app/Http/Requests/Invoice/CreateInvoiceRequest.php @@ -26,5 +26,4 @@ class CreateInvoiceRequest extends Request { return auth()->user()->can('create', Invoice::class); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Invoice/DestroyInvoiceRequest.php b/app/Http/Requests/Invoice/DestroyInvoiceRequest.php index bab08b2ac272..4957b167e21b 100644 --- a/app/Http/Requests/Invoice/DestroyInvoiceRequest.php +++ b/app/Http/Requests/Invoice/DestroyInvoiceRequest.php @@ -26,5 +26,4 @@ class DestroyInvoiceRequest extends Request { return auth()->user()->can('edit', $this->invoice); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Invoice/EditInvoiceRequest.php b/app/Http/Requests/Invoice/EditInvoiceRequest.php index 298119fac236..c268cd27463a 100644 --- a/app/Http/Requests/Invoice/EditInvoiceRequest.php +++ b/app/Http/Requests/Invoice/EditInvoiceRequest.php @@ -33,5 +33,4 @@ class EditInvoiceRequest extends Request return $rules; } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Invoice/ShowInvoiceRequest.php b/app/Http/Requests/Invoice/ShowInvoiceRequest.php index 9821409fc8eb..15afbf323f65 100644 --- a/app/Http/Requests/Invoice/ShowInvoiceRequest.php +++ b/app/Http/Requests/Invoice/ShowInvoiceRequest.php @@ -26,5 +26,4 @@ class ShowInvoiceRequest extends Request { return auth()->user()->can('view', $this->invoice); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Invoice/StoreInvoiceRequest.php b/app/Http/Requests/Invoice/StoreInvoiceRequest.php index 4de673df18c9..d17f1e970b34 100644 --- a/app/Http/Requests/Invoice/StoreInvoiceRequest.php +++ b/app/Http/Requests/Invoice/StoreInvoiceRequest.php @@ -51,6 +51,4 @@ class StoreInvoiceRequest extends Request //$input['line_items'] = json_encode($input['line_items']); $this->replace($input); } - } - diff --git a/app/Http/Requests/Invoice/UpdateInvoiceRequest.php b/app/Http/Requests/Invoice/UpdateInvoiceRequest.php index afd8cd66e188..133540fe111c 100644 --- a/app/Http/Requests/Invoice/UpdateInvoiceRequest.php +++ b/app/Http/Requests/Invoice/UpdateInvoiceRequest.php @@ -12,6 +12,7 @@ namespace App\Http\Requests\Invoice; use App\Http\Requests\Request; +use App\Utils\Traits\ChecksEntityStatus; use App\Utils\Traits\CleanLineItems; use App\Utils\Traits\MakesHash; use Illuminate\Support\Facades\Log; @@ -21,6 +22,8 @@ class UpdateInvoiceRequest extends Request { use MakesHash; use CleanLineItems; + use ChecksEntityStatus; + /** * Determine if the user is authorized to make this request. * @@ -29,15 +32,12 @@ class UpdateInvoiceRequest extends Request public function authorize() : bool { - return auth()->user()->can('edit', $this->invoice); - } public function rules() { - return [ 'documents' => 'mimes:png,ai,svg,jpeg,tiff,pdf,gif,psd,txt,doc,xls,ppt,xlsx,docx,pptx', //'client_id' => 'required|integer', @@ -49,11 +49,12 @@ class UpdateInvoiceRequest extends Request { $input = $this->all(); - if(isset($input['client_id'])) + if (isset($input['client_id'])) { $input['client_id'] = $this->decodePrimaryKey($input['client_id']); + } $input['line_items'] = isset($input['line_items']) ? $this->cleanItems($input['line_items']) : []; $this->replace($input); } -} \ No newline at end of file +} diff --git a/app/Http/Requests/Payment/ActionPaymentRequest.php b/app/Http/Requests/Payment/ActionPaymentRequest.php index 07c39eb924b9..a69312b5a19d 100644 --- a/app/Http/Requests/Payment/ActionPaymentRequest.php +++ b/app/Http/Requests/Payment/ActionPaymentRequest.php @@ -26,5 +26,4 @@ class ActionPaymentRequest extends Request { return auth()->user()->can('edit', $this->payment); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Payment/CreatePaymentRequest.php b/app/Http/Requests/Payment/CreatePaymentRequest.php index c721b260bf94..7385b356bca0 100644 --- a/app/Http/Requests/Payment/CreatePaymentRequest.php +++ b/app/Http/Requests/Payment/CreatePaymentRequest.php @@ -26,5 +26,4 @@ class CreatePaymentRequest extends Request { return auth()->user()->can('create', Payment::class); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Payment/DestroyPaymentRequest.php b/app/Http/Requests/Payment/DestroyPaymentRequest.php index ac2fc9252485..cfafcb269f5c 100644 --- a/app/Http/Requests/Payment/DestroyPaymentRequest.php +++ b/app/Http/Requests/Payment/DestroyPaymentRequest.php @@ -26,6 +26,4 @@ class DestroyPaymentRequest extends Request { return auth()->user()->can('edit', $this->payment) && $this->payment->is_deleted === false; } - - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Payment/EditPaymentRequest.php b/app/Http/Requests/Payment/EditPaymentRequest.php index 0bebf8005f1d..ef0490f4cdb1 100644 --- a/app/Http/Requests/Payment/EditPaymentRequest.php +++ b/app/Http/Requests/Payment/EditPaymentRequest.php @@ -43,5 +43,4 @@ class EditPaymentRequest extends Request $this->replace($input); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Payment/ShowPaymentRequest.php b/app/Http/Requests/Payment/ShowPaymentRequest.php index e8e25f13aa85..6cdcbc5d6a73 100644 --- a/app/Http/Requests/Payment/ShowPaymentRequest.php +++ b/app/Http/Requests/Payment/ShowPaymentRequest.php @@ -26,5 +26,4 @@ class ShowPaymentRequest extends Request { return auth()->user()->can('view', $this->payment); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Payment/StorePaymentRequest.php b/app/Http/Requests/Payment/StorePaymentRequest.php index d5120183ad73..74df0050fc7e 100644 --- a/app/Http/Requests/Payment/StorePaymentRequest.php +++ b/app/Http/Requests/Payment/StorePaymentRequest.php @@ -28,39 +28,33 @@ class StorePaymentRequest extends Request public function authorize() : bool { - return auth()->user()->can('create', Payment::class); - } protected function prepareForValidation() { - $input = $this->all(); - if(isset($input['client_id'])) + if (isset($input['client_id'])) { $input['client_id'] = $this->decodePrimaryKey($input['client_id']); + } - if(isset($input['invoices'])){ - - foreach($input['invoices'] as $key => $value) - { - $input['invoices'][$key]['id'] = $this->decodePrimaryKey($value['id']); + if (isset($input['invoices'])) { + foreach ($input['invoices'] as $key => $value) { + $input['invoices'][$key]['id'] = $this->decodePrimaryKey($value['id']); } - } - if(isset($input['invoices']) && is_array($input['invoices']) === false) + if (isset($input['invoices']) && is_array($input['invoices']) === false) { $input['invoices'] = null; + } $this->replace($input); - } public function rules() { - $rules = [ 'amount' => 'numeric|required', 'date' => 'required', @@ -70,8 +64,5 @@ class StorePaymentRequest extends Request ]; return $rules; - } - - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Payment/UpdatePaymentRequest.php b/app/Http/Requests/Payment/UpdatePaymentRequest.php index b63c65e2dfbe..a4f82ac930d2 100644 --- a/app/Http/Requests/Payment/UpdatePaymentRequest.php +++ b/app/Http/Requests/Payment/UpdatePaymentRequest.php @@ -12,10 +12,13 @@ namespace App\Http\Requests\Payment; use App\Http\Requests\Request; +use App\Utils\Traits\ChecksEntityStatus; use Illuminate\Validation\Rule; class UpdatePaymentRequest extends Request { + use ChecksEntityStatus; + /** * Determine if the user is authorized to make this request. * @@ -24,9 +27,7 @@ class UpdatePaymentRequest extends Request public function authorize() : bool { - return auth()->user()->can('edit', $this->payment); - } @@ -40,5 +41,4 @@ class UpdatePaymentRequest extends Request 'date' => 'required', ]; } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Product/CreateProductRequest.php b/app/Http/Requests/Product/CreateProductRequest.php index 455701769461..207dd5ff6e04 100644 --- a/app/Http/Requests/Product/CreateProductRequest.php +++ b/app/Http/Requests/Product/CreateProductRequest.php @@ -24,14 +24,13 @@ class CreateProductRequest extends Request public function authorize() : bool { - return auth()->user()->can('create', Product::Class); + return auth()->user()->can('create', Product::class); } public function rules() : array { - return [ - 'product_key' => 'required', - ]; + return [ + 'product_key' => 'required', + ]; } - } diff --git a/app/Http/Requests/Product/ShowProductRequest.php b/app/Http/Requests/Product/ShowProductRequest.php index 316fc0eabda7..919a88cb570f 100644 --- a/app/Http/Requests/Product/ShowProductRequest.php +++ b/app/Http/Requests/Product/ShowProductRequest.php @@ -10,6 +10,7 @@ */ namespace App\Http\Requests\Product; + use App\Http\Requests\Request; class ShowProductRequest extends Request diff --git a/app/Http/Requests/Product/StoreProductRequest.php b/app/Http/Requests/Product/StoreProductRequest.php index 8ad944ec6400..49361848d5f3 100644 --- a/app/Http/Requests/Product/StoreProductRequest.php +++ b/app/Http/Requests/Product/StoreProductRequest.php @@ -29,7 +29,6 @@ class StoreProductRequest extends Request public function rules() { - return [ 'product_key' => 'required|unique:products,product_key,null,null,company_id,'.auth()->user()->companyId(), 'cost' => 'numeric', @@ -42,11 +41,10 @@ class StoreProductRequest extends Request { $input = $this->all(); - if(!isset($input['quantity']) || $input['quantity'] < 1) + if (!isset($input['quantity']) || $input['quantity'] < 1) { $input['quantity'] = 1; + } $this->replace($input); - } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Product/UpdateProductRequest.php b/app/Http/Requests/Product/UpdateProductRequest.php index 18c460f53656..743057037359 100644 --- a/app/Http/Requests/Product/UpdateProductRequest.php +++ b/app/Http/Requests/Product/UpdateProductRequest.php @@ -13,10 +13,12 @@ namespace App\Http\Requests\Product; use App\Http\Requests\Request; use App\Models\Product; +use App\Utils\Traits\ChecksEntityStatus; use Illuminate\Support\Facades\Log; class UpdateProductRequest extends Request { + use ChecksEntityStatus; /** * Determine if the user is authorized to make this request. * @@ -25,9 +27,7 @@ class UpdateProductRequest extends Request public function authorize() : bool { - return auth()->user()->can('create', Product::class); - } public function rules() @@ -45,11 +45,10 @@ class UpdateProductRequest extends Request { $input = $this->all(); - if(!isset($input['quantity']) || $input['quantity'] < 1) + if (!isset($input['quantity']) || $input['quantity'] < 1) { $input['quantity'] = 1; + } $this->replace($input); - } } - diff --git a/app/Http/Requests/Quote/ActionQuoteRequest.php b/app/Http/Requests/Quote/ActionQuoteRequest.php index 1f7a8770e9dc..570d46428485 100644 --- a/app/Http/Requests/Quote/ActionQuoteRequest.php +++ b/app/Http/Requests/Quote/ActionQuoteRequest.php @@ -26,5 +26,4 @@ class ActionQuoteRequest extends Request { return auth()->user()->can('edit', $this->quote); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Quote/CreateQuoteRequest.php b/app/Http/Requests/Quote/CreateQuoteRequest.php index a19aa65f1fe3..f4c2293933eb 100644 --- a/app/Http/Requests/Quote/CreateQuoteRequest.php +++ b/app/Http/Requests/Quote/CreateQuoteRequest.php @@ -26,5 +26,4 @@ class CreateQuoteRequest extends Request { return auth()->user()->can('create', Quote::class); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Quote/DestroyQuoteRequest.php b/app/Http/Requests/Quote/DestroyQuoteRequest.php index 8db996058872..91d185488296 100644 --- a/app/Http/Requests/Quote/DestroyQuoteRequest.php +++ b/app/Http/Requests/Quote/DestroyQuoteRequest.php @@ -26,5 +26,4 @@ class DestroyQuoteRequest extends Request { return auth()->user()->can('edit', $this->quote); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Quote/EditQuoteRequest.php b/app/Http/Requests/Quote/EditQuoteRequest.php index 2ee4253f525b..3b1552329f48 100644 --- a/app/Http/Requests/Quote/EditQuoteRequest.php +++ b/app/Http/Requests/Quote/EditQuoteRequest.php @@ -42,7 +42,5 @@ class EditQuoteRequest extends Request //$input['id'] = $this->encodePrimaryKey($input['id']); $this->replace($input); - } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Quote/ShowQuoteRequest.php b/app/Http/Requests/Quote/ShowQuoteRequest.php index f07c4cd0cfd6..d7d6ad36b488 100644 --- a/app/Http/Requests/Quote/ShowQuoteRequest.php +++ b/app/Http/Requests/Quote/ShowQuoteRequest.php @@ -26,5 +26,4 @@ class ShowQuoteRequest extends Request { return auth()->user()->can('view', $this->quote); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Quote/StoreQuoteRequest.php b/app/Http/Requests/Quote/StoreQuoteRequest.php index f8be7cfe5c43..2169e23c072a 100644 --- a/app/Http/Requests/Quote/StoreQuoteRequest.php +++ b/app/Http/Requests/Quote/StoreQuoteRequest.php @@ -34,11 +34,11 @@ class StoreQuoteRequest extends Request { $input = $this->all(); - if(isset($input['client_id'])) + if (isset($input['client_id'])) { $input['client_id'] = $this->decodePrimaryKey($input['client_id']); + } $this->replace($input); - } public function rules() @@ -48,7 +48,4 @@ class StoreQuoteRequest extends Request 'client_id' => 'required', ]; } - - } - diff --git a/app/Http/Requests/Quote/UpdateQuoteRequest.php b/app/Http/Requests/Quote/UpdateQuoteRequest.php index dbe32bf9517f..4538bd7cbc49 100644 --- a/app/Http/Requests/Quote/UpdateQuoteRequest.php +++ b/app/Http/Requests/Quote/UpdateQuoteRequest.php @@ -12,6 +12,7 @@ namespace App\Http\Requests\Quote; use App\Http\Requests\Request; +use App\Utils\Traits\ChecksEntityStatus; use App\Utils\Traits\CleanLineItems; use App\Utils\Traits\MakesHash; use Illuminate\Support\Facades\Log; @@ -21,6 +22,7 @@ class UpdateQuoteRequest extends Request { use MakesHash; use CleanLineItems; + use ChecksEntityStatus; /** * Determine if the user is authorized to make this request. @@ -30,9 +32,7 @@ class UpdateQuoteRequest extends Request public function authorize() : bool { - return auth()->user()->can('edit', $this->quote); - } @@ -50,10 +50,10 @@ class UpdateQuoteRequest extends Request // if(isset($input['client_id'])) // $input['client_id'] = $this->decodePrimaryKey($input['client_id']); - if(isset($input['line_items'])) + if (isset($input['line_items'])) { $input['line_items'] = isset($input['line_items']) ? $this->cleanItems($input['line_items']) : []; + } $this->replace($input); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/RecurringInvoice/ActionRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/ActionRecurringInvoiceRequest.php index 41b1d50db721..9555dae5f48c 100644 --- a/app/Http/Requests/RecurringInvoice/ActionRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/ActionRecurringInvoiceRequest.php @@ -26,5 +26,4 @@ class ActionRecurringInvoiceRequest extends Request { return auth()->user()->can('edit', $this->recurring_invoice); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/RecurringInvoice/CreateRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/CreateRecurringInvoiceRequest.php index 41c9cf7ad4f9..7ca35b66cab7 100644 --- a/app/Http/Requests/RecurringInvoice/CreateRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/CreateRecurringInvoiceRequest.php @@ -26,5 +26,4 @@ class CreateRecurringInvoiceRequest extends Request { return auth()->user()->can('create', RecurringInvoice::class); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/RecurringInvoice/DestroyRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/DestroyRecurringInvoiceRequest.php index b87cdc263825..3f8bf1ca3095 100644 --- a/app/Http/Requests/RecurringInvoice/DestroyRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/DestroyRecurringInvoiceRequest.php @@ -26,5 +26,4 @@ class DestroyRecurringInvoiceRequest extends Request { return auth()->user()->can('edit', $this->recurring_invoice); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/RecurringInvoice/EditRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/EditRecurringInvoiceRequest.php index 4e447a5e1235..a4c00e982af2 100644 --- a/app/Http/Requests/RecurringInvoice/EditRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/EditRecurringInvoiceRequest.php @@ -43,5 +43,4 @@ class EditRecurringInvoiceRequest extends Request $this->replace($input); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/RecurringInvoice/ShowRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/ShowRecurringInvoiceRequest.php index 4145757c5974..2d21e60c53d7 100644 --- a/app/Http/Requests/RecurringInvoice/ShowRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/ShowRecurringInvoiceRequest.php @@ -26,5 +26,4 @@ class ShowRecurringInvoiceRequest extends Request { return auth()->user()->can('view', $this->recurring_invoice); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php index b7fb12f9a00e..8bbb20eae6a1 100644 --- a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php @@ -43,9 +43,5 @@ class StoreRecurringInvoiceRequest extends Request public function messages() { - } - - } - diff --git a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php index 5e652b570e15..9dfc1a5b101d 100644 --- a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php @@ -12,11 +12,13 @@ namespace App\Http\Requests\RecurringInvoice; use App\Http\Requests\Request; +use App\Utils\Traits\ChecksEntityStatus; use Illuminate\Support\Facades\Log; use Illuminate\Validation\Rule; class UpdateRecurringInvoiceRequest extends Request { + use ChecksEntityStatus; /** * Determine if the user is authorized to make this request. * @@ -25,9 +27,7 @@ class UpdateRecurringInvoiceRequest extends Request public function authorize() : bool { - return auth()->user()->can('edit', $this->recurring_invoice); - } @@ -39,5 +39,4 @@ class UpdateRecurringInvoiceRequest extends Request ]; } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/RecurringQuote/ActionRecurringQuoteRequest.php b/app/Http/Requests/RecurringQuote/ActionRecurringQuoteRequest.php index 5687b256bf91..4466284baf51 100644 --- a/app/Http/Requests/RecurringQuote/ActionRecurringQuoteRequest.php +++ b/app/Http/Requests/RecurringQuote/ActionRecurringQuoteRequest.php @@ -26,5 +26,4 @@ class ActionRecurringQuoteRequest extends Request { return auth()->user()->can('edit', $this->recurring_quote); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/RecurringQuote/CreateRecurringQuoteRequest.php b/app/Http/Requests/RecurringQuote/CreateRecurringQuoteRequest.php index 96519efef876..1267cf0166e0 100644 --- a/app/Http/Requests/RecurringQuote/CreateRecurringQuoteRequest.php +++ b/app/Http/Requests/RecurringQuote/CreateRecurringQuoteRequest.php @@ -26,5 +26,4 @@ class CreateRecurringQuoteRequest extends Request { return auth()->user()->can('create', RecurringQuote::class); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/RecurringQuote/DestroyRecurringQuoteRequest.php b/app/Http/Requests/RecurringQuote/DestroyRecurringQuoteRequest.php index c78218706f07..e5d0ef756768 100644 --- a/app/Http/Requests/RecurringQuote/DestroyRecurringQuoteRequest.php +++ b/app/Http/Requests/RecurringQuote/DestroyRecurringQuoteRequest.php @@ -26,5 +26,4 @@ class DestroyRecurringQuoteRequest extends Request { return auth()->user()->can('edit', $this->recurring_quote); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/RecurringQuote/EditRecurringQuoteRequest.php b/app/Http/Requests/RecurringQuote/EditRecurringQuoteRequest.php index 0ee5e0684081..92bbcbea4378 100644 --- a/app/Http/Requests/RecurringQuote/EditRecurringQuoteRequest.php +++ b/app/Http/Requests/RecurringQuote/EditRecurringQuoteRequest.php @@ -43,5 +43,4 @@ class EditRecurringQuoteRequest extends Request $this->replace($input); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/RecurringQuote/ShowRecurringQuoteRequest.php b/app/Http/Requests/RecurringQuote/ShowRecurringQuoteRequest.php index 5c5498020424..5aae595c800c 100644 --- a/app/Http/Requests/RecurringQuote/ShowRecurringQuoteRequest.php +++ b/app/Http/Requests/RecurringQuote/ShowRecurringQuoteRequest.php @@ -26,5 +26,4 @@ class ShowRecurringQuoteRequest extends Request { return auth()->user()->can('view', $this->recurring_quote); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php b/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php index 06f469541a7e..d9ca38404f34 100644 --- a/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php +++ b/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php @@ -35,7 +35,4 @@ class StoreRecurringQuoteRequest extends Request ]; } - - } - diff --git a/app/Http/Requests/RecurringQuote/UpdateRecurringQuoteRequest.php b/app/Http/Requests/RecurringQuote/UpdateRecurringQuoteRequest.php index b27f9687810c..e3cad6ccffe7 100644 --- a/app/Http/Requests/RecurringQuote/UpdateRecurringQuoteRequest.php +++ b/app/Http/Requests/RecurringQuote/UpdateRecurringQuoteRequest.php @@ -12,11 +12,14 @@ namespace App\Http\Requests\RecurringQuote; use App\Http\Requests\Request; +use App\Utils\Traits\ChecksEntityStatus; use Illuminate\Support\Facades\Log; use Illuminate\Validation\Rule; class UpdateRecurringQuoteRequest extends Request { + use ChecksEntityStatus; + /** * Determine if the user is authorized to make this request. * @@ -25,9 +28,7 @@ class UpdateRecurringQuoteRequest extends Request public function authorize() : bool { - return auth()->user()->can('edit', $this->recurring_quote); - } @@ -39,5 +40,4 @@ class UpdateRecurringQuoteRequest extends Request ]; } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Request.php b/app/Http/Requests/Request.php index 20691fde0189..fb6e17cd03b3 100644 --- a/app/Http/Requests/Request.php +++ b/app/Http/Requests/Request.php @@ -25,5 +25,4 @@ class Request extends FormRequest { return []; } - } diff --git a/app/Http/Requests/TaxRate/CreateTaxRateRequest.php b/app/Http/Requests/TaxRate/CreateTaxRateRequest.php index 859d8dfd691f..b1c872aa829b 100644 --- a/app/Http/Requests/TaxRate/CreateTaxRateRequest.php +++ b/app/Http/Requests/TaxRate/CreateTaxRateRequest.php @@ -26,6 +26,4 @@ class CreateTaxRateRequest extends Request { return auth()->user()->isAdmin(); } - - -} \ No newline at end of file +} diff --git a/app/Http/Requests/TaxRate/DestroyTaxRateRequest.php b/app/Http/Requests/TaxRate/DestroyTaxRateRequest.php index 6c5853e2d5f6..f9887f53c1c2 100644 --- a/app/Http/Requests/TaxRate/DestroyTaxRateRequest.php +++ b/app/Http/Requests/TaxRate/DestroyTaxRateRequest.php @@ -25,5 +25,4 @@ class DestroyTaxRateRequest extends Request { return auth()->user()->isAdmin(); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/TaxRate/ShowTaxRateRequest.php b/app/Http/Requests/TaxRate/ShowTaxRateRequest.php index 2a202556f57a..97c92aadac10 100644 --- a/app/Http/Requests/TaxRate/ShowTaxRateRequest.php +++ b/app/Http/Requests/TaxRate/ShowTaxRateRequest.php @@ -10,6 +10,7 @@ */ namespace App\Http\Requests\TaxRate; + use App\Http\Requests\Request; class ShowTaxRateRequest extends Request diff --git a/app/Http/Requests/TaxRate/StoreTaxRateRequest.php b/app/Http/Requests/TaxRate/StoreTaxRateRequest.php index a070c0f7f9a2..d1d6ab58edc3 100644 --- a/app/Http/Requests/TaxRate/StoreTaxRateRequest.php +++ b/app/Http/Requests/TaxRate/StoreTaxRateRequest.php @@ -35,6 +35,4 @@ class StoreTaxRateRequest extends Request 'rate' => 'required|numeric', ]; } - - -} \ No newline at end of file +} diff --git a/app/Http/Requests/TaxRate/UpdateTaxRateRequest.php b/app/Http/Requests/TaxRate/UpdateTaxRateRequest.php index 920449c2b48e..f96e98630f4b 100644 --- a/app/Http/Requests/TaxRate/UpdateTaxRateRequest.php +++ b/app/Http/Requests/TaxRate/UpdateTaxRateRequest.php @@ -35,7 +35,4 @@ class UpdateTaxRateRequest extends Request 'rate' => 'numeric', ]; } - - } - diff --git a/app/Http/Requests/User/AttachCompanyUserRequest.php b/app/Http/Requests/User/AttachCompanyUserRequest.php index 879827af8db9..f64f7e10c204 100644 --- a/app/Http/Requests/User/AttachCompanyUserRequest.php +++ b/app/Http/Requests/User/AttachCompanyUserRequest.php @@ -45,6 +45,4 @@ class AttachCompanyUserRequest extends Request 'is_owner' => false, ]); } - - -} \ No newline at end of file +} diff --git a/app/Http/Requests/User/CreateUserRequest.php b/app/Http/Requests/User/CreateUserRequest.php index 0c5cd8176fd1..8b2d775b614a 100644 --- a/app/Http/Requests/User/CreateUserRequest.php +++ b/app/Http/Requests/User/CreateUserRequest.php @@ -24,7 +24,6 @@ class CreateUserRequest extends Request public function authorize() : bool { - return auth()->user()->can('create', User::class); + return auth()->user()->isAdmin(); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/User/DestroyUserRequest.php b/app/Http/Requests/User/DestroyUserRequest.php index 7eb489b373e9..30c9bad3ca8f 100644 --- a/app/Http/Requests/User/DestroyUserRequest.php +++ b/app/Http/Requests/User/DestroyUserRequest.php @@ -26,5 +26,4 @@ class DestroyUserRequest extends Request { return auth()->user()->isOwner(); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/User/DetachCompanyUserRequest.php b/app/Http/Requests/User/DetachCompanyUserRequest.php index 7b315ff684fb..bdc4ff1cc8a6 100644 --- a/app/Http/Requests/User/DetachCompanyUserRequest.php +++ b/app/Http/Requests/User/DetachCompanyUserRequest.php @@ -28,5 +28,4 @@ class DetachCompanyUserRequest extends Request { return auth()->user()->isAdmin(); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/User/EditUserRequest.php b/app/Http/Requests/User/EditUserRequest.php index 9bd5d24892e8..3d32481574a7 100644 --- a/app/Http/Requests/User/EditUserRequest.php +++ b/app/Http/Requests/User/EditUserRequest.php @@ -33,7 +33,4 @@ class EditUserRequest extends Request return $rules; } - - - -} \ No newline at end of file +} diff --git a/app/Http/Requests/User/ShowUserRequest.php b/app/Http/Requests/User/ShowUserRequest.php index 62d8b0202a57..51b45923e3ca 100644 --- a/app/Http/Requests/User/ShowUserRequest.php +++ b/app/Http/Requests/User/ShowUserRequest.php @@ -27,5 +27,4 @@ class ShowUserRequest extends Request //return auth()->user()->can('view', $this->user); return auth()->user()->isAdmin(); } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/User/StoreUserRequest.php b/app/Http/Requests/User/StoreUserRequest.php index 1871248c4ead..2ae504d13587 100644 --- a/app/Http/Requests/User/StoreUserRequest.php +++ b/app/Http/Requests/User/StoreUserRequest.php @@ -29,53 +29,47 @@ class StoreUserRequest extends Request public function authorize() : bool { - return auth()->user()->isAdmin(); - } public function rules() { - $rules = []; $rules['first_name'] = 'required|string|max:100'; $rules['last_name'] = 'required|string|max:100'; - if (config('ninja.db.multi_db_enabled')) - { + if (config('ninja.db.multi_db_enabled')) { $rules['email'] = new ValidUserForCompany(); } return $rules; - } protected function prepareForValidation() { $input = $this->all(); - if(isset($input['company_user'])) - { - if(!isset($input['company_user']['is_admin'])) + if (isset($input['company_user'])) { + if (!isset($input['company_user']['is_admin'])) { $input['company_user']['is_admin'] = false; + } - if(!isset($input['company_user']['permissions'])) + if (!isset($input['company_user']['permissions'])) { $input['company_user']['permissions'] = ''; + } - if(!isset($input['company_user']['settings'])) - $input['company_user']['settings'] = json_encode(DefaultSettings::userSettings()); - - } - else{ + if (!isset($input['company_user']['settings'])) { + $input['company_user']['settings'] = DefaultSettings::userSettings(); + } + } else { $input['company_user'] = [ - 'settings' => json_encode(DefaultSettings::userSettings()), + 'settings' => DefaultSettings::userSettings(), 'permissions' => '', ]; } - $this->replace($input); - + $this->replace($input); } @@ -83,10 +77,10 @@ class StoreUserRequest extends Request { $user = MultiDB::hasUser(['email' => $this->input('email')]); - if(!$user) + if (!$user) { $user = UserFactory::create(); + } return $user; } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/User/UpdateUserRequest.php b/app/Http/Requests/User/UpdateUserRequest.php index 5677b13788e7..d28f9909335e 100644 --- a/app/Http/Requests/User/UpdateUserRequest.php +++ b/app/Http/Requests/User/UpdateUserRequest.php @@ -25,18 +25,17 @@ class UpdateUserRequest extends Request public function authorize() : bool { return auth()->user()->id === $this->id || auth()->user()->isAdmin(); - } public function rules() { - $input = $this->all(); $rules = []; - if(isset($input['email'])) + if (isset($input['email'])) { $rules['email'] = ['sometimes', new UniqueUserRule($this->user, $input['email'])]; + } return $rules; } @@ -45,11 +44,10 @@ class UpdateUserRequest extends Request { $input = $this->all(); - if(isset($input['company_user']) && !auth()->user()->isAdmin()) + if (isset($input['company_user']) && !auth()->user()->isAdmin()) { unset($input['company_user']); + } - $this->replace($input); + $this->replace($input); } - - -} \ No newline at end of file +} diff --git a/app/Http/ValidationRules/NewUniqueUserRule.php b/app/Http/ValidationRules/NewUniqueUserRule.php index 816b3b3f1281..53545bf5ec2d 100644 --- a/app/Http/ValidationRules/NewUniqueUserRule.php +++ b/app/Http/ValidationRules/NewUniqueUserRule.php @@ -48,5 +48,4 @@ class NewUniqueUserRule implements Rule { return MultiDB::checkUserEmailExists($email); } - } diff --git a/app/Http/ValidationRules/UniqueUserRule.php b/app/Http/ValidationRules/UniqueUserRule.php index 10bbf9c2c763..b4855905ea07 100644 --- a/app/Http/ValidationRules/UniqueUserRule.php +++ b/app/Http/ValidationRules/UniqueUserRule.php @@ -21,14 +21,12 @@ use Illuminate\Contracts\Validation\Rule; */ class UniqueUserRule implements Rule { - public $user; public $new_email; public function __construct($user, $new_email) { - $this->user= $user; $this->new_email = $new_email; @@ -43,10 +41,11 @@ class UniqueUserRule implements Rule { /* If the input has not changed, return early! */ - if($this->user->email == $this->new_email) + if ($this->user->email == $this->new_email) { return true; - else - return ! $this->checkIfEmailExists($value); //if it exists, return false! + } else { + return ! $this->checkIfEmailExists($value); + } //if it exists, return false! } /** @@ -65,5 +64,4 @@ class UniqueUserRule implements Rule { return MultiDB::checkUserEmailExists($email); } - } diff --git a/app/Http/ValidationRules/ValidClientGroupSettingsRule.php b/app/Http/ValidationRules/ValidClientGroupSettingsRule.php index cfe8cfb9a0fe..4df868050ec9 100644 --- a/app/Http/ValidationRules/ValidClientGroupSettingsRule.php +++ b/app/Http/ValidationRules/ValidClientGroupSettingsRule.php @@ -35,13 +35,12 @@ class ValidClientGroupSettingsRule implements Rule { $data = $this->validateSettings($value); - if (is_array($data)) - { + if (is_array($data)) { $this->return_data = $data; return false; - } - else + } else { return true; + } } /** @@ -50,9 +49,5 @@ class ValidClientGroupSettingsRule implements Rule public function message() { return $this->return_data[0]." is not a valid ".$this->return_data[1]; - } - - - } diff --git a/app/Http/ValidationRules/ValidCompanyGatewayFeesAndLimitsRule.php b/app/Http/ValidationRules/ValidCompanyGatewayFeesAndLimitsRule.php index e6f6d3f7fd8b..1fb48de906a9 100644 --- a/app/Http/ValidationRules/ValidCompanyGatewayFeesAndLimitsRule.php +++ b/app/Http/ValidationRules/ValidCompanyGatewayFeesAndLimitsRule.php @@ -20,7 +20,7 @@ use Illuminate\Contracts\Validation\Rule; */ class ValidCompanyGatewayFeesAndLimitsRule implements Rule { - use CompanyGatewayFeesAndLimitsSaver; + use CompanyGatewayFeesAndLimitsSaver; /** * @param string $attribute @@ -34,13 +34,12 @@ class ValidCompanyGatewayFeesAndLimitsRule implements Rule { $data = $this->validateFeesAndLimits($value); - if (is_array($data)) - { + if (is_array($data)) { $this->return_data = $data; return false; - } - else + } else { return true; + } } /** @@ -48,8 +47,6 @@ class ValidCompanyGatewayFeesAndLimitsRule implements Rule */ public function message() { - return $this->return_data[0]." is not a valid ".$this->return_data[1]; - } } diff --git a/app/Http/ValidationRules/ValidPayableInvoicesRule.php b/app/Http/ValidationRules/ValidPayableInvoicesRule.php index c6964b2f75cd..7d1256e1b136 100644 --- a/app/Http/ValidationRules/ValidPayableInvoicesRule.php +++ b/app/Http/ValidationRules/ValidPayableInvoicesRule.php @@ -36,12 +36,12 @@ class ValidPayableInvoicesRule implements Rule /*If no invoices has been sent, then we apply the payment to the client account*/ $invoices = []; - if(is_array($value)) - $invoices = Invoice::whereIn('id', array_column($value,'id'))->company()->get(); + if (is_array($value)) { + $invoices = Invoice::whereIn('id', array_column($value, 'id'))->company()->get(); + } foreach ($invoices as $invoice) { - - if(! $invoice->isPayable()) { + if (! $invoice->isPayable()) { $this->error_msg = "One or more of these invoices have been paid"; return false; } @@ -57,5 +57,4 @@ class ValidPayableInvoicesRule implements Rule { return $this->error_msg; } - } diff --git a/app/Http/ValidationRules/ValidSettingsRule.php b/app/Http/ValidationRules/ValidSettingsRule.php index 5f22a48c9dec..5e0d634a3214 100644 --- a/app/Http/ValidationRules/ValidSettingsRule.php +++ b/app/Http/ValidationRules/ValidSettingsRule.php @@ -35,13 +35,12 @@ class ValidSettingsRule implements Rule { $data = $this->validateSettings($value); - if (is_array($data)) - { + if (is_array($data)) { $this->return_data = $data; return false; - } - else + } else { return true; + } } /** @@ -50,9 +49,5 @@ class ValidSettingsRule implements Rule public function message() { return $this->return_data[0]." is not a valid ".$this->return_data[1]; - } - - - } diff --git a/app/Http/ValidationRules/ValidUserForCompany.php b/app/Http/ValidationRules/ValidUserForCompany.php index c7c74294c99d..0c9168b5cdbd 100644 --- a/app/Http/ValidationRules/ValidUserForCompany.php +++ b/app/Http/ValidationRules/ValidUserForCompany.php @@ -40,6 +40,4 @@ class ValidUserForCompany implements Rule return 'This user is unable to be attached to this company. Perhaps they have already registered a user on another account?'; //return ctrans('texts.email_already_register'); } - - } diff --git a/app/Http/ViewComposers/HeaderComposer.php b/app/Http/ViewComposers/HeaderComposer.php index ebb992666b0b..4e657ac5b1c5 100644 --- a/app/Http/ViewComposers/HeaderComposer.php +++ b/app/Http/ViewComposers/HeaderComposer.php @@ -36,24 +36,24 @@ class HeaderComposer */ private function headerData() { - if(!auth()->user()) + if (!auth()->user()) { return []; + } $companies = auth()->user()->companies; //companies $data['current_company'] = $companies->first(); $data['companies'] = $companies; -/* - $data['current_company'] = $companies->first(function ($company){ - return $company->id == auth()->user()->company()->id; - }); - - $data['companies'] = $companies->reject(function ($company){ - return $company->id == auth()->user()->company()->id; - }); -*/ + /* + $data['current_company'] = $companies->first(function ($company){ + return $company->id == auth()->user()->company()->id; + }); + + $data['companies'] = $companies->reject(function ($company){ + return $company->id == auth()->user()->company()->id; + }); + */ return $data; } - -} \ No newline at end of file +} diff --git a/app/Http/ViewComposers/PortalComposer.php b/app/Http/ViewComposers/PortalComposer.php index 84e36381e42a..6d0caf6280a5 100644 --- a/app/Http/ViewComposers/PortalComposer.php +++ b/app/Http/ViewComposers/PortalComposer.php @@ -29,9 +29,7 @@ class PortalComposer */ public function compose(View $view) :void { - - $view->with($this->portalData()); - + $view->with($this->portalData()); } /** @@ -39,9 +37,9 @@ class PortalComposer */ private function portalData() :array { - - if(!auth()->user()) + if (!auth()->user()) { return []; + } $data['sidebar'] = $this->sidebarMenu(); $data['header'] = []; @@ -51,15 +49,13 @@ class PortalComposer $data['client'] = auth()->user()->client; $data['settings'] = auth()->user()->client->getMergedSettings(); -//\Log::error(print_r($data['settings'],1)); + //\Log::error(print_r($data['settings'],1)); return $data; - } private function sidebarMenu() :array { - $data = []; $data[] = [ 'title' => ctrans('texts.dashboard'), 'url' => 'client.dashboard', 'icon' => 'fa fa-tachometer fa-fw fa-2x']; @@ -69,7 +65,5 @@ class PortalComposer $data[] = [ 'title' => ctrans('texts.payment_methods'), 'url' => 'client.payment_methods.index', 'icon' => 'fa fa-cc-stripe fa-fw fa-2x']; return $data; - } - -} \ No newline at end of file +} diff --git a/app/Http/ViewComposers/TranslationComposer.php b/app/Http/ViewComposers/TranslationComposer.php index 348e2041ac87..e426d1f7853b 100644 --- a/app/Http/ViewComposers/TranslationComposer.php +++ b/app/Http/ViewComposers/TranslationComposer.php @@ -19,7 +19,6 @@ use Cache; use Illuminate\Support\Str; use Illuminate\View\View; - class TranslationComposer { /** @@ -31,7 +30,6 @@ class TranslationComposer */ public function compose(View $view) :void { - $view->with('industries', TranslationHelper::getIndustries()); $view->with('countries', TranslationHelper::getCountries()); @@ -43,7 +41,5 @@ class TranslationComposer $view->with('currencies', TranslationHelper::getCurrencies()); $view->with('payment_terms', TranslationHelper::getPaymentTerms()); - } - } diff --git a/app/Jobs/Account/CreateAccount.php b/app/Jobs/Account/CreateAccount.php index de73e58928ef..dec11a211b6d 100644 --- a/app/Jobs/Account/CreateAccount.php +++ b/app/Jobs/Account/CreateAccount.php @@ -27,7 +27,6 @@ use Illuminate\Support\Facades\Notification; class CreateAccount { - use Dispatchable; protected $request; @@ -40,9 +39,7 @@ class CreateAccount public function __construct(array $request) { - $this->request = $request; - } /** @@ -73,8 +70,9 @@ class CreateAccount /* * Required dependencies */ - if($user) - auth()->login($user, false); + if ($user) { + auth()->login($user, false); + } $user->setCompany($company); @@ -88,8 +86,9 @@ class CreateAccount /* * Fire related events */ - if($user) + if ($user) { event(new AccountCreated($user)); + } $user->fresh(); diff --git a/app/Jobs/Client/UpdateClientBalance.php b/app/Jobs/Client/UpdateClientBalance.php index 247ab6f89c4b..07884bed837e 100644 --- a/app/Jobs/Client/UpdateClientBalance.php +++ b/app/Jobs/Client/UpdateClientBalance.php @@ -11,7 +11,6 @@ namespace App\Jobs\Client; - use App\Libraries\MultiDB; use App\Models\Client; use App\Models\Company; @@ -45,12 +44,11 @@ class UpdateClientBalance * * @return void */ - public function handle() + public function handle() { MultiDB::setDB($this->company->db); $this->client->balance += $this->amount; $this->client->save(); - } } diff --git a/app/Jobs/Client/UpdateClientPaidToDate.php b/app/Jobs/Client/UpdateClientPaidToDate.php index 35fc1262a935..9f308b4b41e0 100644 --- a/app/Jobs/Client/UpdateClientPaidToDate.php +++ b/app/Jobs/Client/UpdateClientPaidToDate.php @@ -11,7 +11,6 @@ namespace App\Jobs\Client; - use App\Libraries\MultiDB; use App\Models\Client; use App\Models\Company; @@ -44,12 +43,11 @@ class UpdateClientPaidToDate * * @return void */ - public function handle() + public function handle() { MultiDB::setDB($this->company->db); $this->client->paid_to_date += $this->amount; $this->client->save(); - } } diff --git a/app/Jobs/Company/CreateCompany.php b/app/Jobs/Company/CreateCompany.php index b13cb5cd27f3..6ab42cef4692 100644 --- a/app/Jobs/Company/CreateCompany.php +++ b/app/Jobs/Company/CreateCompany.php @@ -35,11 +35,9 @@ class CreateCompany public function __construct(array $request, $account) { - $this->request = $request; $this->account = $account; - } /** diff --git a/app/Jobs/Company/UpdateCompanyLedgerWithInvoice.php b/app/Jobs/Company/UpdateCompanyLedgerWithInvoice.php index 6c18e670fc24..9356e2234117 100644 --- a/app/Jobs/Company/UpdateCompanyLedgerWithInvoice.php +++ b/app/Jobs/Company/UpdateCompanyLedgerWithInvoice.php @@ -36,7 +36,6 @@ class UpdateCompanyLedgerWithInvoice public function __construct(Invoice $invoice, float $adjustment, Company $company) { - $this->invoice = $invoice; $this->adjustment = $adjustment; @@ -49,7 +48,7 @@ class UpdateCompanyLedgerWithInvoice * * @return void */ - public function handle() + public function handle() { MultiDB::setDB($this->company->db); @@ -60,8 +59,9 @@ class UpdateCompanyLedgerWithInvoice ->orderBy('id', 'DESC') ->first(); - if($ledger) + if ($ledger) { $balance = $ledger->balance; + } $adjustment = $balance + $this->adjustment; @@ -72,6 +72,5 @@ class UpdateCompanyLedgerWithInvoice $company_ledger->save(); $this->invoice->company_ledger()->save($company_ledger); - } } diff --git a/app/Jobs/Company/UpdateCompanyLedgerWithPayment.php b/app/Jobs/Company/UpdateCompanyLedgerWithPayment.php index fc367adefb2a..c553766819f0 100644 --- a/app/Jobs/Company/UpdateCompanyLedgerWithPayment.php +++ b/app/Jobs/Company/UpdateCompanyLedgerWithPayment.php @@ -39,7 +39,6 @@ class UpdateCompanyLedgerWithPayment public function __construct(Payment $payment, float $adjustment, Company $company) { - $this->payment = $payment; $this->adjustment = $adjustment; @@ -52,7 +51,7 @@ class UpdateCompanyLedgerWithPayment * * @return void */ - public function handle() + public function handle() { MultiDB::setDB($this->company->db); @@ -65,8 +64,9 @@ class UpdateCompanyLedgerWithPayment ->orderBy('id', 'DESC') ->first(); - if($ledger) + if ($ledger) { $balance = $ledger->balance; + } $company_ledger = CompanyLedgerFactory::create($this->payment->company_id, $this->payment->user_id); @@ -76,6 +76,5 @@ class UpdateCompanyLedgerWithPayment $company_ledger->save(); $this->payment->company_ledger()->save($company_ledger); //todo add model directive here - } } diff --git a/app/Jobs/Cron/RecurringInvoicesCron.php b/app/Jobs/Cron/RecurringInvoicesCron.php index b56bdd52195a..1065e67742c4 100644 --- a/app/Jobs/Cron/RecurringInvoicesCron.php +++ b/app/Jobs/Cron/RecurringInvoicesCron.php @@ -28,7 +28,6 @@ class RecurringInvoicesCron public function __construct() { - } /** @@ -40,43 +39,27 @@ class RecurringInvoicesCron { /* Get all invoices where the send date is less than NOW + 30 minutes() */ - if (! config('ninja.db.multi_db_enabled')) - { + if (! config('ninja.db.multi_db_enabled')) { $recurring_invoices = RecurringInvoice::where('next_send_date', '<=', Carbon::now()->addMinutes(30))->get(); - Log::info(Carbon::now()->addMinutes(30) . ' Sending Recurring Invoices. Count = '. $recurring_invoices->count() ); + Log::info(Carbon::now()->addMinutes(30) . ' Sending Recurring Invoices. Count = '. $recurring_invoices->count()); $recurring_invoices->each(function ($recurring_invoice, $key) { - SendRecurring::dispatch($recurring_invoice, $recurring_invoice->company->db); - }); - } - else - { - //multiDB environment, need to - foreach (MultiDB::$dbs as $db) - { + } else { + //multiDB environment, need to + foreach (MultiDB::$dbs as $db) { MultiDB::setDB($db); - $recurring_invoices = RecurringInvoice::where('next_send_date', '<=', Carbon::now()->addMinutes(30))->get(); + $recurring_invoices = RecurringInvoice::where('next_send_date', '<=', Carbon::now()->addMinutes(30))->get(); Log::info(Carbon::now()->addMinutes(30) . ' Sending Recurring Invoices. Count = '. $recurring_invoices->count() . 'On Database # '. $db); $recurring_invoices->each(function ($recurring_invoice, $key) { - SendRecurring::dispatch($recurring_invoice, $recurring_invoice->company->db); - }); - } } - } - - - - - - } diff --git a/app/Jobs/Invitation/MarkOpened.php b/app/Jobs/Invitation/MarkOpened.php index 92ef9301dd1d..d57e2e4f1ffd 100644 --- a/app/Jobs/Invitation/MarkOpened.php +++ b/app/Jobs/Invitation/MarkOpened.php @@ -40,17 +40,15 @@ class MarkOpened implements ShouldQueue */ public function __construct(string $message_id, string $entity) { - $this->message_id = $message_id; $this->entity = $entity; - } /** * Execute the job. * - * + * * @return void */ public function handle() @@ -65,6 +63,5 @@ class MarkOpened implements ShouldQueue $invitation->email_error = $error; $invitation->save(); - } } diff --git a/app/Jobs/Invoice/ApplyClientPayment.php b/app/Jobs/Invoice/ApplyClientPayment.php index 586aa843c491..18b2ced2776a 100644 --- a/app/Jobs/Invoice/ApplyClientPayment.php +++ b/app/Jobs/Invoice/ApplyClientPayment.php @@ -43,27 +43,23 @@ class ApplyClientPayment implements ShouldQueue */ public function __construct(Payment $payment, Company $company) { - $this->payment = $payment; $this->company = $company; - } /** * Execute the job. * - * + * * @return void */ public function handle() { - MultiDB::setDB($this->company->db); $client = $this->payment->client; $client->credit_balance += $this->payment->amount; + $client->paid_to_date += $this->payment->amount; $client->save(); - } - -} \ No newline at end of file +} diff --git a/app/Jobs/Invoice/ApplyInvoiceNumber.php b/app/Jobs/Invoice/ApplyInvoiceNumber.php index c58d9e782100..3542c4206aa8 100644 --- a/app/Jobs/Invoice/ApplyInvoiceNumber.php +++ b/app/Jobs/Invoice/ApplyInvoiceNumber.php @@ -41,7 +41,6 @@ class ApplyInvoiceNumber implements ShouldQueue */ public function __construct(Invoice $invoice, $settings, $company) { - $this->invoice = $invoice; $this->settings = $settings; @@ -52,26 +51,27 @@ class ApplyInvoiceNumber implements ShouldQueue /** * Execute the job. * - * + * * @return void */ public function handle() { - MultiDB::setDB($this->company->db); //return early - if($this->invoice->number != '') + if ($this->invoice->number != '') { return $this->invoice; + } switch ($this->settings->counter_number_applied) { case 'when_saved': $this->invoice->number = $this->getNextInvoiceNumber($this->invoice->client); break; case 'when_sent': - if($this->invoice->status_id == Invoice::STATUS_SENT) + if ($this->invoice->status_id == Invoice::STATUS_SENT) { $this->invoice->number = $this->getNextInvoiceNumber($this->invoice->client); + } break; default: @@ -82,8 +82,5 @@ class ApplyInvoiceNumber implements ShouldQueue $this->invoice->save(); return $this->invoice; - } - - } diff --git a/app/Jobs/Invoice/ApplyInvoicePayment.php b/app/Jobs/Invoice/ApplyInvoicePayment.php index 4e378cd9c043..d3d4106c2ce5 100644 --- a/app/Jobs/Invoice/ApplyInvoicePayment.php +++ b/app/Jobs/Invoice/ApplyInvoicePayment.php @@ -47,23 +47,20 @@ class ApplyInvoicePayment implements ShouldQueue */ public function __construct(Invoice $invoice, Payment $payment, float $amount, Company $company) { - $this->invoice = $invoice; $this->payment = $payment; $this->amount = $amount; $this->company = $company; - } /** * Execute the job. * - * + * * @return void */ public function handle() { - MultiDB::setDB($this->company->db); UpdateCompanyLedgerWithPayment::dispatchNow($this->payment, ($this->amount*-1), $this->company); @@ -71,56 +68,40 @@ class ApplyInvoicePayment implements ShouldQueue UpdateClientPaidToDate::dispatchNow($this->payment->client, $this->amount, $this->company); /* Update Pivot Record amount */ - $this->payment->invoices->each(function ($inv){ - - if($inv->id == $this->invoice->id){ + $this->payment->invoices->each(function ($inv) { + if ($inv->id == $this->invoice->id) { $inv->pivot->amount = $this->amount; $inv->pivot->save(); } - }); - - if($this->invoice->hasPartial()) - { - //is partial and amount is exactly the partial amount - if($this->invoice->partial == $this->amount) - { - + if ($this->invoice->hasPartial()) { + //is partial and amount is exactly the partial amount + if ($this->invoice->partial == $this->amount) { $this->invoice->clearPartial(); $this->invoice->setDueDate(); $this->invoice->setStatus(Invoice::STATUS_PARTIAL); $this->invoice->updateBalance($this->amount*-1); - - } - elseif($this->invoice->partial > 0 && $this->invoice->partial > $this->amount) //partial amount exists, but the amount is less than the partial amount - { - + } elseif ($this->invoice->partial > 0 && $this->invoice->partial > $this->amount) { //partial amount exists, but the amount is less than the partial amount $this->invoice->partial -= $this->amount; $this->invoice->updateBalance($this->amount*-1); - - } - elseif($this->invoice->partial > 0 && $this->invoice->partial < $this->amount) //partial exists and the amount paid is GREATER than the partial amount - { - + } elseif ($this->invoice->partial > 0 && $this->invoice->partial < $this->amount) { //partial exists and the amount paid is GREATER than the partial amount $this->invoice->clearPartial(); $this->invoice->setDueDate(); $this->invoice->setStatus(Invoice::STATUS_PARTIAL); $this->invoice->updateBalance($this->amount*-1); - } - - } - elseif($this->invoice->amount == $this->invoice->balance) //total invoice paid. - { - + } elseif ($this->invoice->amount == $this->invoice->balance) { //total invoice paid. $this->invoice->clearPartial(); $this->invoice->setDueDate(); $this->invoice->setStatus(Invoice::STATUS_PAID); $this->invoice->updateBalance($this->amount*-1); - } - - + + /* Update Payment Applied Amount*/ + $this->payment->applied += $this->amount; + $this->payment->save(); } -} \ No newline at end of file + + +} diff --git a/app/Jobs/Invoice/ApplyPaymentToInvoice.php b/app/Jobs/Invoice/ApplyPaymentToInvoice.php index 8c00d8602edb..3adfea8d6ef6 100644 --- a/app/Jobs/Invoice/ApplyPaymentToInvoice.php +++ b/app/Jobs/Invoice/ApplyPaymentToInvoice.php @@ -44,7 +44,6 @@ class ApplyPaymentToInvoice implements ShouldQueue */ public function __construct(Payment $payment, Invoice $invoice, Company $company) { - $this->invoice = $invoice; $this->payment = $payment; @@ -55,12 +54,11 @@ class ApplyPaymentToInvoice implements ShouldQueue /** * Execute the job. * - * + * * @return void */ public function handle() { - MultiDB::setDB($this->company->db); /* The amount we are adjusting the invoice by*/ @@ -74,46 +72,41 @@ class ApplyPaymentToInvoice implements ShouldQueue $partial = max(0, $this->invoice->partial - $this->payment->amount); /* check if partial exists */ - if($this->invoice->partial > 0) - { + if ($this->invoice->partial > 0) { //if payment amount = partial - if( $this->formatvalue($this->invoice->partial,4) == $this->formatValue($this->payment->amount,4) ) - { + if ($this->formatvalue($this->invoice->partial, 4) == $this->formatValue($this->payment->amount, 4)) { $this->invoice->partial = 0; $this->invoice->partial_due_date = null; - } //if payment amount < partial amount - if( $this->formatvalue($this->invoice->partial,4) > $this->formatValue($this->payment->amount,4) ) - { + if ($this->formatvalue($this->invoice->partial, 4) > $this->formatValue($this->payment->amount, 4)) { //set the new partial amount to the balance $this->invoice->partial = $partial; } - if(!$this->invoice->due_date) + if (!$this->invoice->due_date) { $this->invoice->due_date = Carbon::now()->addDays(PaymentTerm::find($this->invoice->settings->payment_terms)->num_days); - - } + } + } /* Update Invoice Balance */ $this->invoice->balance = $this->invoice->balance + $adjustment; /* Update Invoice Status */ - if($this->invoice->balance == 0){ + if ($this->invoice->balance == 0) { $this->invoice->status_id = Invoice::STATUS_PAID; $this->invoice->save(); event(new InvoiceWasPaid($this->invoice, $this->invoice->company)); - } - elseif($this->payment->amount > 0 && $this->invoice->balance > 0) + } elseif ($this->payment->amount > 0 && $this->invoice->balance > 0) { $this->invoice->status_id = Invoice::STATUS_PARTIAL; + } /*If auto-archive is enabled, and balance = 0 - archive invoice */ - if($this->invoice->settings->auto_archive_invoice && $this->invoice->balance == 0) - { + if ($this->invoice->settings->auto_archive_invoice && $this->invoice->balance == 0) { $invoiceRepo = app('App\Repositories\InvoiceRepository'); $invoiceRepo->archive($this->invoice); } diff --git a/app/Jobs/Invoice/CreateInvoiceInvitations.php b/app/Jobs/Invoice/CreateInvoiceInvitations.php index 518966273967..3cc8310e237a 100644 --- a/app/Jobs/Invoice/CreateInvoiceInvitations.php +++ b/app/Jobs/Invoice/CreateInvoiceInvitations.php @@ -38,10 +38,8 @@ class CreateInvoiceInvitations implements ShouldQueue */ public function __construct(Invoice $invoice, Company $company) { - $this->invoice = $invoice; $this->company = $company; - } public function handle() @@ -51,23 +49,19 @@ class CreateInvoiceInvitations implements ShouldQueue $contacts = $this->invoice->client->contacts; $contacts->each(function ($contact) { - $invitation = InvoiceInvitation::whereCompanyId($this->invoice->company_id) ->whereClientContactId($contact->id) ->whereInvoiceId($this->invoice->id) ->first(); - if(!$invitation && $contact->send_invoice) { + if (!$invitation && $contact->send_invoice) { $ii = InvoiceInvitationFactory::create($this->invoice->company_id, $this->invoice->user_id); $ii->invoice_id = $this->invoice->id; $ii->client_contact_id = $contact->id; $ii->save(); - } - else if($invitation && !$contact->send_invoice) { + } elseif ($invitation && !$contact->send_invoice) { $invitation->delete(); } - }); - } -} \ No newline at end of file +} diff --git a/app/Jobs/Invoice/CreateInvoicePdf.php b/app/Jobs/Invoice/CreateInvoicePdf.php index f61a2ec44a89..74d9953ee76f 100644 --- a/app/Jobs/Invoice/CreateInvoicePdf.php +++ b/app/Jobs/Invoice/CreateInvoicePdf.php @@ -44,7 +44,6 @@ class CreateInvoicePdf implements ShouldQueue */ public function __construct(Invoice $invoice, Company $company) { - $this->invoice = $invoice; $this->company = $company; @@ -52,11 +51,10 @@ class CreateInvoicePdf implements ShouldQueue public function handle() { - MultiDB::setDB($this->company->db); $this->invoice->load('client'); - $path = 'public/' . $this->invoice->client->client_hash . '/invoices/'; + $path = 'public/' . $this->invoice->client->client_hash . '/invoices/'; $file_path = $path . $this->invoice->number . '.pdf'; //get invoice design @@ -66,32 +64,28 @@ class CreateInvoicePdf implements ShouldQueue Storage::makeDirectory($path, 0755); //create pdf - $pdf = $this->makePdf(null,null,$html); + $pdf = $this->makePdf(null, null, $html); $path = Storage::put($file_path, $pdf); - - } /** * Returns a PDF stream - * + * * @param string $header Header to be included in PDF * @param string $footer Footer to be included in PDF * @param string $html The HTML object to be converted into PDF - * + * * @return string The PDF string */ - private function makePdf($header, $footer, $html) + private function makePdf($header, $footer, $html) { - return Browsershot::html($html) + return Browsershot::html($html) //->showBrowserHeaderAndFooter() //->headerHtml($header) //->footerHtml($footer) ->waitUntilNetworkIdle(false)->pdf(); - //->margins(10,10,10,10) + //->margins(10,10,10,10) //->savePdf('test.pdf'); } - - } diff --git a/app/Jobs/Invoice/EmailInvoice.php b/app/Jobs/Invoice/EmailInvoice.php index fede4eeede5c..85ee18670ac0 100644 --- a/app/Jobs/Invoice/EmailInvoice.php +++ b/app/Jobs/Invoice/EmailInvoice.php @@ -42,17 +42,15 @@ class EmailInvoice implements ShouldQueue */ public function __construct(Invoice $invoice, Company $company) { - $this->invoice = $invoice; $this->company = $company; - } /** * Execute the job. * - * + * * @return void */ public function handle() @@ -64,11 +62,8 @@ class EmailInvoice implements ShouldQueue $template_style = $this->invoice->client->getSetting('email_style'); - $this->invoice->invitations->each(function ($invitation) use($template_style){ - - if($invitation->contact->send_invoice && $invitation->contact->email) - { - + $this->invoice->invitations->each(function ($invitation) use ($template_style) { + if ($invitation->contact->send_invoice && $invitation->contact->email) { $message_array = $this->invoice->getEmailData('', $invitation->contact); $message_array['title'] = &$message_array['subject']; $message_array['footer'] = "Sent to ".$invitation->contact->present()->name(); @@ -79,28 +74,22 @@ class EmailInvoice implements ShouldQueue Mail::to($invitation->contact->email, $invitation->contact->present()->name()) ->send(new TemplateEmail($message_array, $template_style, $invitation->contact->user, $invitation->contact->client)); - if( count(Mail::failures()) > 0 ) { - + if (count(Mail::failures()) > 0) { event(new InvoiceWasEmailedAndFailed($this->invoice, Mail::failures())); return $this->logMailError($errors); - } //fire any events event(new InvoiceWasEmailed($this->invoice)); //sleep(5); - } - }); - } private function logMailError($errors) { - SystemLogger::dispatch( $errors, SystemLog::CATEGORY_MAIL, @@ -108,7 +97,5 @@ class EmailInvoice implements ShouldQueue SystemLog::TYPE_FAILURE, $this->invoice->client ); - } - -} \ No newline at end of file +} diff --git a/app/Jobs/Invoice/InvoiceNotification.php b/app/Jobs/Invoice/InvoiceNotification.php index 3087ef134280..f710e10329b9 100644 --- a/app/Jobs/Invoice/InvoiceNotification.php +++ b/app/Jobs/Invoice/InvoiceNotification.php @@ -32,15 +32,13 @@ class InvoiceNotification implements ShouldQueue */ public function __construct(Invoice $invoice) { - $this->invoice = $invoice; - } /** * Execute the job. * - * + * * @return void */ public function handle() @@ -49,6 +47,5 @@ class InvoiceNotification implements ShouldQueue //notification for the invoice. // //could mean a email, sms, slack, push - } } diff --git a/app/Jobs/Invoice/MarkInvoicePaid.php b/app/Jobs/Invoice/MarkInvoicePaid.php index 230a72d33e31..5ccf42c32575 100644 --- a/app/Jobs/Invoice/MarkInvoicePaid.php +++ b/app/Jobs/Invoice/MarkInvoicePaid.php @@ -42,16 +42,14 @@ class MarkInvoicePaid implements ShouldQueue */ public function __construct(Invoice $invoice, Company $company) { - $this->invoice = $invoice; $this->company = $company; - } /** * Execute the job. * - * + * * @return void */ public function handle() @@ -69,7 +67,7 @@ class MarkInvoicePaid implements ShouldQueue /* Create a payment relationship to the invoice entity */ $payment->save(); - $payment->invoices()->attach($this->invoice->id,[ + $payment->invoices()->attach($this->invoice->id, [ 'amount' => $payment->amount ]); diff --git a/app/Jobs/Invoice/ReverseInvoicePayment.php b/app/Jobs/Invoice/ReverseInvoicePayment.php index 1ef1338207b1..c50945f6625b 100644 --- a/app/Jobs/Invoice/ReverseInvoicePayment.php +++ b/app/Jobs/Invoice/ReverseInvoicePayment.php @@ -60,15 +60,12 @@ class ReverseInvoicePayment implements ShouldQueue $invoices = $this->payment->invoices()->get(); $client = $this->payment->client; - $invoices->each(function($invoice){ - - if($invoice->pivot->amount > 0) - { + $invoices->each(function ($invoice) { + if ($invoice->pivot->amount > 0) { $invoice->status_id = Invoice::STATUS_SENT; $invoice->balance = $invoice->pivot->amount; $invoice->save(); } - }); UpdateCompanyLedgerWithPayment::dispatchNow($this->payment, ($this->payment->amount), $this->company); @@ -77,5 +74,4 @@ class ReverseInvoicePayment implements ShouldQueue UpdateClientPaidToDate::dispatchNow($client, $this->payment->amount*-1, $this->company); } - -} \ No newline at end of file +} diff --git a/app/Jobs/Invoice/StoreInvoice.php b/app/Jobs/Invoice/StoreInvoice.php index 1e9e8ca84388..782590c9dbda 100644 --- a/app/Jobs/Invoice/StoreInvoice.php +++ b/app/Jobs/Invoice/StoreInvoice.php @@ -39,7 +39,6 @@ class StoreInvoice implements ShouldQueue */ public function __construct(Invoice $invoice, array $data, Company $company) { - $this->invoice = $invoice; $this->data = $data; @@ -80,41 +79,31 @@ class StoreInvoice implements ShouldQueue // } - if(isset($this->data['email_invoice']) && (bool)$this->data['email_invoice']) - { - + if (isset($this->data['email_invoice']) && (bool)$this->data['email_invoice']) { $this->invoice = $invoice_repo->markSent($this->invoice); //fire invoice job (the job performs the filtering logic of the email recipients... if any.) InvoiceNotification::dispatch($invoice, $invoice->company); - } - if(isset($this->data['mark_paid']) && (bool)$this->data['mark_paid']) - { - + if (isset($this->data['mark_paid']) && (bool)$this->data['mark_paid']) { $this->invoice = $invoice_repo->markSent($this->invoice); // generate a manual payment against the invoice // the PAYMENT class will update the INVOICE status. //$payment = - } /* Payment Notifications */ - if($payment) - { + if ($payment) { //fire payment notifications here PaymentNotification::dispatch($payment, $payment->company); - } - if(isset($data['download_invoice']) && (bool)$this->data['download_invoice']) - { + if (isset($data['download_invoice']) && (bool)$this->data['download_invoice']) { //fire invoice download and return PDF response from here } return $this->invoice; - } } diff --git a/app/Jobs/Invoice/UpdateInvoicePayment.php b/app/Jobs/Invoice/UpdateInvoicePayment.php index 473df12a3e3e..7fc8b95e991e 100644 --- a/app/Jobs/Invoice/UpdateInvoicePayment.php +++ b/app/Jobs/Invoice/UpdateInvoicePayment.php @@ -61,10 +61,8 @@ class UpdateInvoicePayment implements ShouldQueue $invoices_total = $invoices->sum('balance'); /* Simplest scenario - All invoices are paid in full*/ - if(strval($invoices_total) === strval($this->payment->amount)) - { - $invoices->each(function ($invoice){ - + if (strval($invoices_total) === strval($this->payment->amount)) { + $invoices->each(function ($invoice) { UpdateCompanyLedgerWithPayment::dispatchNow($this->payment, ($invoice->balance*-1), $this->company); UpdateClientBalance::dispatchNow($this->payment->client, $invoice->balance*-1, $this->company); UpdateClientPaidToDate::dispatchNow($this->payment->client, $invoice->balance, $this->company); @@ -74,34 +72,25 @@ class UpdateInvoicePayment implements ShouldQueue $invoice->clearPartial(); $invoice->updateBalance($invoice->balance*-1); - }); - } /*Combination of partials and full invoices are being paid*/ else { - $total = 0; /* Calculate the grand total of the invoices*/ - foreach($invoices as $invoice) - { - - if($invoice->hasPartial()) + foreach ($invoices as $invoice) { + if ($invoice->hasPartial()) { $total += $invoice->partial; - else + } else { $total += $invoice->balance; - + } } /*Test if there is a batch of partial invoices that have been paid */ - if($this->payment->amount == $total) - { - - $invoices->each(function ($invoice){ - - if($invoice->hasPartial()) { - + if ($this->payment->amount == $total) { + $invoices->each(function ($invoice) { + if ($invoice->hasPartial()) { UpdateCompanyLedgerWithPayment::dispatchNow($this->payment, ($invoice->partial*-1), $this->company); UpdateClientBalance::dispatchNow($this->payment->client, $invoice->partial*-1, $this->company); UpdateClientPaidToDate::dispatchNow($this->payment->client, $invoice->partial, $this->company); @@ -112,13 +101,7 @@ class UpdateInvoicePayment implements ShouldQueue $invoice->clearPartial(); $invoice->setDueDate(); $invoice->setStatus(Invoice::STATUS_PARTIAL); - - - - } - else - { - + } else { UpdateCompanyLedgerWithPayment::dispatchNow($this->payment, ($invoice->balance*-1), $this->company); UpdateClientBalance::dispatchNow($this->payment->client, $invoice->balance*-1, $this->company); UpdateClientPaidToDate::dispatchNow($this->payment->client, $invoice->balance, $this->company); @@ -128,16 +111,9 @@ class UpdateInvoicePayment implements ShouldQueue $invoice->clearPartial(); $invoice->updateBalance($invoice->balance*-1); - - - } - }); - - } - else { - + } else { SystemLogger::dispatch( [ 'payment' => $this->payment, @@ -145,7 +121,7 @@ class UpdateInvoicePayment implements ShouldQueue 'invoices_total' => $invoices_total, 'payment_amount' => $this->payment->amount, 'partial_check_amount' => $total, - ], + ], SystemLog::CATEGORY_GATEWAY_RESPONSE, SystemLog::EVENT_PAYMENT_RECONCILIATION_FAILURE, SystemLog::TYPE_LEDGER, @@ -159,11 +135,9 @@ class UpdateInvoicePayment implements ShouldQueue $this->payment->save(); $this->payment->delete(); } - - } } -} +} /* $this->payment = $event->payment; @@ -185,4 +159,4 @@ class UpdateInvoicePayment implements ShouldQueue $invoiceRepo = app('App\Ninja\Repositories\InvoiceRepository'); $invoiceRepo->archive($invoice); } -*/ \ No newline at end of file +*/ diff --git a/app/Jobs/Payment/PaymentNotification.php b/app/Jobs/Payment/PaymentNotification.php index 84552eb2b3fe..ea7f8d2fb1f5 100644 --- a/app/Jobs/Payment/PaymentNotification.php +++ b/app/Jobs/Payment/PaymentNotification.php @@ -35,17 +35,15 @@ class PaymentNotification implements ShouldQueue */ public function __construct(Payment $payment, Company $company) { - $this->payment = $payment; $this->company = $company; - } /** * Execute the job. * - * + * * @return void */ public function handle() @@ -55,6 +53,5 @@ class PaymentNotification implements ShouldQueue //notification for the payment. // //could mean a email, sms, slack, push - } } diff --git a/app/Jobs/Product/UpdateOrCreateProduct.php b/app/Jobs/Product/UpdateOrCreateProduct.php index 089793b648c8..46add4a55f2c 100644 --- a/app/Jobs/Product/UpdateOrCreateProduct.php +++ b/app/Jobs/Product/UpdateOrCreateProduct.php @@ -40,7 +40,6 @@ class UpdateOrCreateProduct implements ShouldQueue */ public function __construct($products, $invoice, $company) { - $this->products = $products; $this->invoice = $invoice; @@ -51,16 +50,14 @@ class UpdateOrCreateProduct implements ShouldQueue /** * Execute the job. * - * + * * @return void */ public function handle() { MultiDB::setDB($this->company->db); - foreach($this->products as $item) - { - + foreach ($this->products as $item) { $product = Product::firstOrNew(['product_key' => $item->product_key, 'company_id' => $this->invoice->company->id]); $product->product_key = $item->product_key; @@ -75,15 +72,12 @@ class UpdateOrCreateProduct implements ShouldQueue $product->custom_value1 = isset($item->custom_value1) ? $item->custom_value1 : ''; $product->custom_value2 = isset($item->custom_value2) ? $item->custom_value2 : ''; $product->custom_value3 = isset($item->custom_value3) ? $item->custom_value3 : ''; - $product->custom_value4 = isset($item->custom_value4) ? $item->custom_value4 : ''; + $product->custom_value4 = isset($item->custom_value4) ? $item->custom_value4 : ''; $product->user_id = $this->invoice->user_id; $product->company_id = $this->invoice->company_id; $product->project_id = $this->invoice->project_id; $product->vendor_id = $this->invoice->vendor_id; $product->save(); - } - } - } diff --git a/app/Jobs/Quote/ApplyQuoteNumber.php b/app/Jobs/Quote/ApplyQuoteNumber.php index a12b6b2c6e5e..06ce21b0d30e 100644 --- a/app/Jobs/Quote/ApplyQuoteNumber.php +++ b/app/Jobs/Quote/ApplyQuoteNumber.php @@ -42,7 +42,6 @@ class ApplyQuoteNumber implements ShouldQueue */ public function __construct(Quote $quote, $settings, Company $company) { - $this->quote = $quote; $this->settings = $settings; @@ -53,7 +52,7 @@ class ApplyQuoteNumber implements ShouldQueue /** * Execute the job. * - * + * * @return void */ public function handle() @@ -61,16 +60,18 @@ class ApplyQuoteNumber implements ShouldQueue MultiDB::setDB($this->company->db); //return early - if($this->quote->number != '') + if ($this->quote->number != '') { return $this->quote; + } switch ($this->settings->quote_number_applied) { case 'when_saved': $this->quote->number = $this->getNextQuoteNumber($this->quote->client); break; case 'when_sent': - if($this->quote->status_id == Quote::STATUS_SENT) + if ($this->quote->status_id == Quote::STATUS_SENT) { $this->quote->number = $this->getNextQuoteNumber($this->quote->client); + } break; default: @@ -81,8 +82,5 @@ class ApplyQuoteNumber implements ShouldQueue $this->quote->save(); return $this->quote; - } - - } diff --git a/app/Jobs/Quote/CreateQuoteInvitations.php b/app/Jobs/Quote/CreateQuoteInvitations.php index 8767a8413779..09caa5d94515 100644 --- a/app/Jobs/Quote/CreateQuoteInvitations.php +++ b/app/Jobs/Quote/CreateQuoteInvitations.php @@ -38,11 +38,9 @@ class CreateQuoteInvitations implements ShouldQueue */ public function __construct(Quote $quote, Company $company) { - $this->quote = $quote; $this->company = $company; - } public function handle() @@ -52,23 +50,19 @@ class CreateQuoteInvitations implements ShouldQueue $contacts = $this->quote->client->contacts; $contacts->each(function ($contact) { - $invitation = QuoteInvitation::whereCompanyId($this->quote->company_id) ->whereClientContactId($contact->id) ->whereQuoteId($this->quote->id) ->first(); - if(!$invitation && $contact->send_invoice) { + if (!$invitation && $contact->send_invoice) { $ii = QuoteInvitationFactory::create($this->quote->company_id, $this->quote->user_id); $ii->quote_id = $this->quote->id; $ii->client_contact_id = $contact->id; $ii->save(); - } - else if($invitation && !$contact->send_invoice) { + } elseif ($invitation && !$contact->send_invoice) { $invitation->delete(); } - }); - } -} \ No newline at end of file +} diff --git a/app/Jobs/RecurringInvoice/SendRecurring.php b/app/Jobs/RecurringInvoice/SendRecurring.php index c2811e31f79c..1a8801d2c40c 100644 --- a/app/Jobs/RecurringInvoice/SendRecurring.php +++ b/app/Jobs/RecurringInvoice/SendRecurring.php @@ -21,7 +21,6 @@ use Illuminate\Support\Facades\Log; class SendRecurring { - use GeneratesCounter; public $recurring_invoice; @@ -36,10 +35,8 @@ class SendRecurring public function __construct(RecurringInvoice $recurring_invoice, string $db = 'db-ninja-01') { - $this->recurring_invoice = $recurring_invoice; $this->db = $db; - } /** @@ -57,30 +54,25 @@ class SendRecurring $invoice->status_id = Invoice::STATUS_SENT; $invoice->save(); - // Queue: Emails for invoice + // Queue: Emails for invoice // foreach invoice->invitations // Fire Payment if auto-bill is enabled - if($this->recurring_invoice->settings->auto_bill) + if ($this->recurring_invoice->settings->auto_bill) { //PAYMENT ACTION HERE TODO - // Clean up recurring invoice object + // Clean up recurring invoice object - $this->recurring_invoice->remaining_cycles = $this->recurring_invoice->remainingCycles(); + $this->recurring_invoice->remaining_cycles = $this->recurring_invoice->remainingCycles(); + } $this->recurring_invoice->last_sent_date = date('Y-m-d'); - if($this->recurring_invoice->remaining_cycles != 0) + if ($this->recurring_invoice->remaining_cycles != 0) { $this->recurring_invoice->next_send_date = $this->recurring_invoice->nextSendDate(); - else + } else { $this->recurring_invoice->setCompleted(); + } - $this->recurring_invoice->save(); - + $this->recurring_invoice->save(); } - - - - - - } diff --git a/app/Jobs/User/CreateUser.php b/app/Jobs/User/CreateUser.php index b8173cb5f1ee..7acef0fc2451 100644 --- a/app/Jobs/User/CreateUser.php +++ b/app/Jobs/User/CreateUser.php @@ -54,7 +54,6 @@ class CreateUser */ public function handle() : ?User { - $user = new User(); $user->password = bcrypt($this->request['password']); $user->accepted_terms_version = config('ninja.terms_version'); diff --git a/app/Jobs/Util/ProcessBulk.php b/app/Jobs/Util/ProcessBulk.php index 25e53488d949..4d892d3bbfa9 100644 --- a/app/Jobs/Util/ProcessBulk.php +++ b/app/Jobs/Util/ProcessBulk.php @@ -39,7 +39,7 @@ class ProcessBulk implements ShouldQueue * @param $repo * @param string $method */ - public function __construct(array $data, $repo, string $method) + public function __construct(array $data, $repo, string $method) { $this->repo = $repo; $this->method = $method; @@ -53,7 +53,7 @@ class ProcessBulk implements ShouldQueue */ public function handle() { - foreach($this->data as $resource) { + foreach ($this->data as $resource) { $this->repo->{$this->method}($resource); } } diff --git a/app/Jobs/Util/SystemLogger.php b/app/Jobs/Util/SystemLogger.php index e8a3fa29068f..9be35e866468 100644 --- a/app/Jobs/Util/SystemLogger.php +++ b/app/Jobs/Util/SystemLogger.php @@ -48,8 +48,7 @@ class SystemLogger implements ShouldQueue public function handle() :void { - - $sl = [ + $sl = [ 'client_id' => $this->client->id, 'company_id' => $this->client->company->id, 'user_id' => $this->client->user_id, @@ -61,5 +60,4 @@ class SystemLogger implements ShouldQueue SystemLog::create($sl); } - -} \ No newline at end of file +} diff --git a/app/Jobs/Util/UploadAvatar.php b/app/Jobs/Util/UploadAvatar.php index 1d85e9397025..e4f0c499a7bb 100644 --- a/app/Jobs/Util/UploadAvatar.php +++ b/app/Jobs/Util/UploadAvatar.php @@ -38,22 +38,22 @@ class UploadAvatar implements ShouldQueue public function handle() : ?string { - //make dir - Storage::makeDirectory('public/' . $this->directory, 0755); + //make dir + Storage::makeDirectory('public/' . $this->directory, 0755); $tmp_file = sha1(time()).".png"; - $file_png = imagepng( imagecreatefromstring(file_get_contents($this->file)) , sys_get_temp_dir().'/'.$tmp_file); - - $path = Storage::putFile('public/' . $this->directory, new File( sys_get_temp_dir().'/'.$tmp_file )); + $file_png = imagepng(imagecreatefromstring(file_get_contents($this->file)), sys_get_temp_dir().'/'.$tmp_file); + + $path = Storage::putFile('public/' . $this->directory, new File(sys_get_temp_dir().'/'.$tmp_file)); $url = Storage::url($path); - //return file path - if($url) - return $url; - else - return null; - + //return file path + if ($url) { + return $url; + } else { + return null; + } } -} \ No newline at end of file +} diff --git a/app/Jobs/Util/UploadFile.php b/app/Jobs/Util/UploadFile.php index c1a5d4a96c8f..9462cb5db8a7 100644 --- a/app/Jobs/Util/UploadFile.php +++ b/app/Jobs/Util/UploadFile.php @@ -64,21 +64,18 @@ class UploadFile implements ShouldQueue $file_path = $path . '/' . $this->file->hashName(); - Storage::put($path, $this->file); + Storage::put($path, $this->file); $width = 0; $height = 0; - if (in_array($this->file->getClientOriginalExtension(),['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'psd'])) - { - + if (in_array($this->file->getClientOriginalExtension(), ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'psd'])) { $imageSize = getimagesize($this->file); $width = $imageSize[0]; $height = $imageSize[1]; - } $document = new Document(); @@ -99,8 +96,7 @@ class UploadFile implements ShouldQueue $this->entity->documents()->save($document); - return $document; - + return $document; } private function generatePreview($preview_path) : string @@ -119,36 +115,29 @@ class UploadFile implements ShouldQueue $preview = ''; - if (in_array($this->file->getClientOriginalExtension(),['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'psd'])) - { + if (in_array($this->file->getClientOriginalExtension(), ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'psd'])) { $makePreview = false; $imageSize = getimagesize($this->file); $width = $imageSize[0]; $height = $imageSize[1]; $imgManagerConfig = []; - if (in_array($this->file->getClientOriginalExtension(), ['gif', 'bmp', 'tiff', 'psd'])) - { + if (in_array($this->file->getClientOriginalExtension(), ['gif', 'bmp', 'tiff', 'psd'])) { // Needs to be converted $makePreview = true; - } elseif ($width > Document::DOCUMENT_PREVIEW_SIZE || $height > Document::DOCUMENT_PREVIEW_SIZE) - { + } elseif ($width > Document::DOCUMENT_PREVIEW_SIZE || $height > Document::DOCUMENT_PREVIEW_SIZE) { $makePreview = true; } - if (in_array($documentType, ['bmp', 'tiff', 'psd'])) - { - if (! class_exists('Imagick')) - { + if (in_array($documentType, ['bmp', 'tiff', 'psd'])) { + if (! class_exists('Imagick')) { // Cant't read this $makePreview = false; - } else - { + } else { $imgManagerConfig['driver'] = 'imagick'; } } - if ($makePreview) - { + if ($makePreview) { // We haven't created a preview yet $imgManager = new ImageManager($imgManagerConfig); @@ -169,17 +158,12 @@ class UploadFile implements ShouldQueue $previewContent = (string) $img->encode($this->file->getClientOriginalExtension()); - Storage::put($preview_path, $previewContent); - - $preview = $preview_path; - } + Storage::put($preview_path, $previewContent); + $preview = $preview_path; + } } return $preview; - } - - - } diff --git a/app/Libraries/MultiDB.php b/app/Libraries/MultiDB.php index cb8e3137a668..9a2a56efc440 100644 --- a/app/Libraries/MultiDB.php +++ b/app/Libraries/MultiDB.php @@ -20,19 +20,19 @@ use App\Models\User; * Class MultiDB * * Caution! - * - * When we perform scans across databases, - * we need to remember that if we don't + * + * When we perform scans across databases, + * we need to remember that if we don't * return a DB 'HIT' the DB connection will * be set to the last DB in the chain, - * + * * So for these cases, we need to reset the * DB connection to the default connection. - * + * * Even that may be problematic, and we * may need to know the current DB connection * so that we can fall back gracefully. - * + * * @package App\Libraries */ class MultiDB @@ -48,73 +48,63 @@ class MultiDB public static function getDbs() : array { - return self::$dbs; - } public static function checkDomainAvailable($subdomain) : bool { - - if (! config('ninja.db.multi_db_enabled')) - { + if (! config('ninja.db.multi_db_enabled')) { return Company::whereSubdomain($subdomain)->get()->count() == 0; } - //multi-db active - foreach (self::$dbs as $db) - { - if(Company::whereSubdomain($subdomain)->get()->count() >=1) - return false; + //multi-db active + foreach (self::$dbs as $db) { + if (Company::whereSubdomain($subdomain)->get()->count() >=1) { + return false; } + } - self::setDefaultDatabase(); - return true; + self::setDefaultDatabase(); + return true; } public static function checkUserEmailExists($email) : bool { - - if (! config('ninja.db.multi_db_enabled')) - { + if (! config('ninja.db.multi_db_enabled')) { return User::where(['email' => $email])->get()->count() >= 1 ?? false; // true >= 1 emails found / false -> == emails found } - //multi-db active - foreach (self::$dbs as $db) - { - if(User::on($db)->where(['email' => $email])->get()->count() >=1) // if user already exists, validation will fail - return true; + //multi-db active + foreach (self::$dbs as $db) { + if (User::on($db)->where(['email' => $email])->get()->count() >=1) { // if user already exists, validation will fail + return true; } + } - self::setDefaultDatabase(); - return false; - + self::setDefaultDatabase(); + return false; } /** * A user and company must co exists on the same database. - * + * * This function will check that if a user exists on the system, * the company is also located on the same database. - * - * If no user is found, then we also return true as this must be + * + * If no user is found, then we also return true as this must be * a new user request. - * + * * @param string $email The user email * @param stirng $company_key The company key * @return bool True|False */ public static function checkUserAndCompanyCoExist($email, $company_key) :bool { - - foreach (self::$dbs as $db) - { - if(User::on($db)->where(['email' => $email])->get()->count() >=1) // if user already exists, validation will fail - { - if(Company::on($db)->where(['company_key' => $company_key])->get()->count() >=1) + foreach (self::$dbs as $db) { + if (User::on($db)->where(['email' => $email])->get()->count() >=1) { // if user already exists, validation will fail + if (Company::on($db)->where(['company_key' => $company_key])->get()->count() >=1) { return true; - else{ + } else { self::setDefaultDatabase(); return false; } @@ -131,49 +121,36 @@ class MultiDB */ public static function hasUser(array $data) : ?User { - - if (! config('ninja.db.multi_db_enabled')) - { + if (! config('ninja.db.multi_db_enabled')) { return User::where($data)->first(); } - foreach (self::$dbs as $db) - { - self::setDB($db); + foreach (self::$dbs as $db) { + self::setDB($db); - $user = User::where($data)->first(); - - if($user) { - - return $user; - - } + $user = User::where($data)->first(); + if ($user) { + return $user; } + } - self::setDefaultDatabase(); - return null; + self::setDefaultDatabase(); + return null; } public static function contactFindAndSetDb($token) :bool { - - foreach (self::$dbs as $db) - { - - if($ct = ClientContact::on($db)->whereRaw("BINARY `token`= ?", [$token])->first()) - { - + foreach (self::$dbs as $db) { + if ($ct = ClientContact::on($db)->whereRaw("BINARY `token`= ?", [$token])->first()) { self::setDb($ct->company->db); return true; } - } self::setDefaultDatabase(); return false; - } public static function userFindAndSetDb($email) : bool @@ -181,65 +158,47 @@ class MultiDB //multi-db active - foreach (self::$dbs as $db) - { - if(User::on($db)->where(['email' => $email])->get()->count() >=1) // if user already exists, validation will fail - return true; + foreach (self::$dbs as $db) { + if (User::on($db)->where(['email' => $email])->get()->count() >=1) { // if user already exists, validation will fail + return true; } + } - return false; - + return false; } public static function findAndSetDb($token) :bool { - - foreach (self::$dbs as $db) - { - - if($ct = CompanyToken::on($db)->whereRaw("BINARY `token`= ?", [$token])->first()) - { - + foreach (self::$dbs as $db) { + if ($ct = CompanyToken::on($db)->whereRaw("BINARY `token`= ?", [$token])->first()) { self::setDb($ct->company->db); return true; } - } return false; - } public static function findAndSetDbByDomain($subdomain) :bool { - //\Log::error("searching for {$domain}"); - - foreach (self::$dbs as $db) - { - - if($company = Company::on($db)->whereSubdomain($subdomain)->first()) - { + //\Log::error("searching for {$domain}"); + foreach (self::$dbs as $db) { + if ($company = Company::on($db)->whereSubdomain($subdomain)->first()) { self::setDb($company->db); return true; - } - } self::setDefaultDatabase(); return false; - } public static function findAndSetDbByInvitation($entity, $invitation_key) { - $class = 'App\Models\\'.ucfirst($entity).'Invitation'; - foreach (self::$dbs as $db) - { - if($invite = $class::on($db)->whereRaw("BINARY `key`= ?",[$invitation_key])->first()) - { + foreach (self::$dbs as $db) { + if ($invite = $class::on($db)->whereRaw("BINARY `key`= ?", [$invitation_key])->first()) { self::setDb($db); return true; } @@ -262,6 +221,4 @@ class MultiDB { config(['database.default' => config('ninja.db.default')]); } - - -} \ No newline at end of file +} diff --git a/app/Libraries/OAuth.php b/app/Libraries/OAuth.php index a3b474c16a17..eb923245fe4a 100644 --- a/app/Libraries/OAuth.php +++ b/app/Libraries/OAuth.php @@ -21,7 +21,6 @@ use Laravel\Socialite\Facades\Socialite; */ class OAuth { - protected $provider_instance; protected $provider_id; @@ -49,13 +48,11 @@ class OAuth 'oauth_provider_id'=>$provider ]; - if($user = MultiDB::hasUser($query)) - { + if ($user = MultiDB::hasUser($query)) { return $user; - } - else + } else { return false; - + } } /* Splits a socialite user name into first and last names */ @@ -70,8 +67,7 @@ class OAuth public static function providerToString(int $social_provider) : string { - switch ($social_provider) - { + switch ($social_provider) { case SOCIAL_GOOGLE: return 'google'; case SOCIAL_FACEBOOK: @@ -89,8 +85,7 @@ class OAuth public static function providerToInt(string $social_provider) : int { - switch ($social_provider) - { + switch ($social_provider) { case 'google': return SOCIAL_GOOGLE; case 'facebook': @@ -108,9 +103,8 @@ class OAuth public function getProvider($provider) { - switch ($provider) - { - case 'google'; + switch ($provider) { + case 'google': $this->provider_instance = new Providers\Google(); $this->provider_id = self::SOCIAL_GOOGLE; return $this; @@ -129,17 +123,15 @@ class OAuth $oauth_user_id = $this->provider_instance->harvestSubField($payload); - $query = [ + $query = [ 'oauth_user_id' => $oauth_user_id, 'oauth_provider_id'=> $this->provider_id ]; - if($user = MultiDB::hasUser($query)) - { + if ($user = MultiDB::hasUser($query)) { return $user; - } - else + } else { return false; - + } } -} \ No newline at end of file +} diff --git a/app/Libraries/OAuth/OAuth.php b/app/Libraries/OAuth/OAuth.php index 62cd14e469d5..81c413ec56a9 100644 --- a/app/Libraries/OAuth/OAuth.php +++ b/app/Libraries/OAuth/OAuth.php @@ -11,7 +11,6 @@ namespace App\Libraries\OAuth; - use App\Libraries\MultiDB; use App\Ninja\OAuth\Providers\Google; use Laravel\Socialite\Facades\Socialite; @@ -46,13 +45,11 @@ class OAuth 'oauth_provider_id'=>$provider ]; - if($user = MultiDB::hasUser($query)) - { + if ($user = MultiDB::hasUser($query)) { return $user; - } - else + } else { return false; - + } } /* Splits a socialite user name into first and last names */ @@ -67,8 +64,7 @@ class OAuth public static function providerToString(int $social_provider) : string { - switch ($social_provider) - { + switch ($social_provider) { case SOCIAL_GOOGLE: return 'google'; case SOCIAL_FACEBOOK: @@ -86,8 +82,7 @@ class OAuth public static function providerToInt(string $social_provider) : int { - switch ($social_provider) - { + switch ($social_provider) { case 'google': return SOCIAL_GOOGLE; case 'facebook': @@ -105,9 +100,8 @@ class OAuth public function getProvider($provider) { - switch ($provider) - { - case 'google'; + switch ($provider) { + case 'google': $this->provider_instance = new Google(); $this->provider_id = self::SOCIAL_GOOGLE; return $this; @@ -131,10 +125,10 @@ class OAuth 'oauth_provider_id' => $this->provider_id ]; - if($this->provider_instance) + if ($this->provider_instance) { $user = MultiDB::hasUser($data); + } return $user; - } -} \ No newline at end of file +} diff --git a/app/Libraries/OAuth/Providers/Google.php b/app/Libraries/OAuth/Providers/Google.php index 2debd7a8b178..d26b75ec9be5 100644 --- a/app/Libraries/OAuth/Providers/Google.php +++ b/app/Libraries/OAuth/Providers/Google.php @@ -2,10 +2,8 @@ class Google implements ProviderInterface { - public function getTokenResponse($token) { - $client = new \Google_Client(); return $client->verifyIdToken($token); } diff --git a/app/Libraries/OAuth/Providers/ProviderInterface.php b/app/Libraries/OAuth/Providers/ProviderInterface.php index 689130f38c67..9aad6bd7052f 100644 --- a/app/Libraries/OAuth/Providers/ProviderInterface.php +++ b/app/Libraries/OAuth/Providers/ProviderInterface.php @@ -5,5 +5,4 @@ interface ProviderInterface public function getTokenResponse($token); public function harvestEmail($response); - } diff --git a/app/Listeners/Activity/CreatedClientActivity.php b/app/Listeners/Activity/CreatedClientActivity.php index 065b4c40c979..a2d7aeb8c279 100644 --- a/app/Listeners/Activity/CreatedClientActivity.php +++ b/app/Listeners/Activity/CreatedClientActivity.php @@ -37,7 +37,6 @@ class CreatedClientActivity implements ShouldQueue */ public function handle($event) { - $fields = new \stdClass; $fields->client_id = $event->client->id; diff --git a/app/Listeners/Activity/PaymentCreatedActivity.php b/app/Listeners/Activity/PaymentCreatedActivity.php index cd6dc7d01821..f0669840479e 100644 --- a/app/Listeners/Activity/PaymentCreatedActivity.php +++ b/app/Listeners/Activity/PaymentCreatedActivity.php @@ -51,15 +51,14 @@ class PaymentCreatedActivity implements ShouldQueue $fields->activity_type_id = Activity::CREATE_PAYMENT; - foreach($invoices as $invoice) //todo we may need to add additional logic if in the future we apply payments to other entity Types, not just invoices - { - + foreach ($invoices as $invoice) { //todo we may need to add additional logic if in the future we apply payments to other entity Types, not just invoices $fields->invoice_id = $invoice->id; $this->activityRepo->save($fields, $invoice); } - if( count( $invoices ) == 0 ) + if (count($invoices) == 0) { $this->activityRepo->save($fields, $payment); + } } } diff --git a/app/Listeners/Activity/PaymentDeletedActivity.php b/app/Listeners/Activity/PaymentDeletedActivity.php index 29d2e9bdf537..9196b3083fa1 100644 --- a/app/Listeners/Activity/PaymentDeletedActivity.php +++ b/app/Listeners/Activity/PaymentDeletedActivity.php @@ -51,15 +51,14 @@ class PaymentDeletedActivity implements ShouldQueue $fields->activity_type_id = Activity::DELETE_PAYMENT; - foreach($invoices as $invoice) //todo we may need to add additional logic if in the future we apply payments to other entity Types, not just invoices - { - + foreach ($invoices as $invoice) { //todo we may need to add additional logic if in the future we apply payments to other entity Types, not just invoices $fields->invoice_id = $invoice->id; $this->activityRepo->save($fields, $invoice); } - if( count( $invoices ) == 0 ) + if (count($invoices) == 0) { $this->activityRepo->save($fields, $payment); + } } } diff --git a/app/Listeners/Contact/UpdateContactLastLogin.php b/app/Listeners/Contact/UpdateContactLastLogin.php index 3a8f7138489d..217cc402a394 100644 --- a/app/Listeners/Contact/UpdateContactLastLogin.php +++ b/app/Listeners/Contact/UpdateContactLastLogin.php @@ -35,11 +35,9 @@ class UpdateContactLastLogin implements ShouldQueue */ public function handle($event) { + $client_contact = $event->client_contact; - $client_contact = $event->client_contact; - - $client_contact->last_login = now(); - $client_contact->save(); - + $client_contact->last_login = now(); + $client_contact->save(); } } diff --git a/app/Listeners/Invoice/CreateInvoiceActivity.php b/app/Listeners/Invoice/CreateInvoiceActivity.php index 15edf7b4f4db..00ac39e26238 100644 --- a/app/Listeners/Invoice/CreateInvoiceActivity.php +++ b/app/Listeners/Invoice/CreateInvoiceActivity.php @@ -41,7 +41,6 @@ class CreateInvoiceActivity implements ShouldQueue */ public function handle($event) { - $fields = new \stdClass; $fields->invoice_id = $event->invoice->id; diff --git a/app/Listeners/Invoice/CreateInvoiceInvitation.php b/app/Listeners/Invoice/CreateInvoiceInvitation.php index 97794045941c..8efe56436534 100644 --- a/app/Listeners/Invoice/CreateInvoiceInvitation.php +++ b/app/Listeners/Invoice/CreateInvoiceInvitation.php @@ -24,7 +24,7 @@ use Symfony\Component\Debug\Exception\FatalThrowableError; class CreateInvoiceInvitation implements ShouldQueue { - /** + /** * Handle the event. * * @param object $event @@ -32,29 +32,24 @@ class CreateInvoiceInvitation implements ShouldQueue */ public function handle($event) { - $invoice = $event->invoice; $contacts = $invoice->client->contacts; - $contacts->each(function ($contact) use($invoice){ - + $contacts->each(function ($contact) use ($invoice) { $invitation = InvoiceInvitation::whereCompanyId($invoice->company_id) - ->whereClientContactId($contact->id) - ->whereInvoiceId($invoice->id) - ->first(); - - if(!$invitation && $contact->send_invoice) { - $ii = InvoiceInvitationFactory::create($invoice->company_id, $invoice->user_id); - $ii->invoice_id = $invoice->id; - $ii->client_contact_id = $contact->id; - $ii->save(); - } - else if($invitation && !$contact->send_invoice) { - $invitation->delete(); - } + ->whereClientContactId($contact->id) + ->whereInvoiceId($invoice->id) + ->first(); + if (!$invitation && $contact->send_invoice) { + $ii = InvoiceInvitationFactory::create($invoice->company_id, $invoice->user_id); + $ii->invoice_id = $invoice->id; + $ii->client_contact_id = $contact->id; + $ii->save(); + } elseif ($invitation && !$contact->send_invoice) { + $invitation->delete(); + } }); - } -} \ No newline at end of file +} diff --git a/app/Listeners/Invoice/InvoiceEmailActivity.php b/app/Listeners/Invoice/InvoiceEmailActivity.php index b382adcfd9f8..2c02e93d3ecc 100644 --- a/app/Listeners/Invoice/InvoiceEmailActivity.php +++ b/app/Listeners/Invoice/InvoiceEmailActivity.php @@ -41,7 +41,6 @@ class InvoiceEmailActivity implements ShouldQueue */ public function handle($event) { - $fields = new \stdClass; $fields->invoice_id = $event->invoice->id; diff --git a/app/Listeners/Invoice/InvoiceEmailFailedActivity.php b/app/Listeners/Invoice/InvoiceEmailFailedActivity.php index 0f653e5c43fe..b5bb53557575 100644 --- a/app/Listeners/Invoice/InvoiceEmailFailedActivity.php +++ b/app/Listeners/Invoice/InvoiceEmailFailedActivity.php @@ -41,7 +41,6 @@ class InvoiceEmailFailedActivity implements ShouldQueue */ public function handle($event) { - $fields = new \stdClass; $fields->invoice_id = $event->invoice->id; diff --git a/app/Listeners/Invoice/UpdateInvoiceInvitations.php b/app/Listeners/Invoice/UpdateInvoiceInvitations.php index f97cd39ee12c..564098b59814 100644 --- a/app/Listeners/Invoice/UpdateInvoiceInvitations.php +++ b/app/Listeners/Invoice/UpdateInvoiceInvitations.php @@ -35,19 +35,15 @@ class UpdateInvoiceInvitations implements ShouldQueue */ public function handle($event) { - - $payment = $event->payment; - $invoices = $payment->invoices; + $payment = $event->payment; + $invoices = $payment->invoices; - /** - * Move this into an event - */ - $invoices->each(function ($invoice) use($payment) { - - $invoice->invitations()->update(['transaction_reference' => $payment->transaction_reference]); - - }); - + /** + * Move this into an event + */ + $invoices->each(function ($invoice) use ($payment) { + $invoice->invitations()->update(['transaction_reference' => $payment->transaction_reference]); + }); } } diff --git a/app/Listeners/SendVerificationNotification.php b/app/Listeners/SendVerificationNotification.php index 1e319233076f..454cec57c3e2 100644 --- a/app/Listeners/SendVerificationNotification.php +++ b/app/Listeners/SendVerificationNotification.php @@ -51,6 +51,5 @@ class SendVerificationNotification implements ShouldQueue //->cc('') //->bcc('') ->queue(new VerifyUser($event->user)); - } } diff --git a/app/Listeners/User/ArchivedUserActivity.php b/app/Listeners/User/ArchivedUserActivity.php index 6ec6378e919d..72c917047319 100644 --- a/app/Listeners/User/ArchivedUserActivity.php +++ b/app/Listeners/User/ArchivedUserActivity.php @@ -37,13 +37,13 @@ class ArchivedUserActivity */ public function handle($event) { - $fields = new \stdClass; - if(auth()->user()->id) + if (auth()->user()->id) { $fields->user_id = auth()->user()->id; - else + } else { $fields->user_id = $event->user->id; + } $fields->company_id = $event->user->company_id; $fields->activity_type_id = Activity::ARCHIVE_USER; diff --git a/app/Listeners/User/CreatedUserActivity.php b/app/Listeners/User/CreatedUserActivity.php index 628d60ad75ba..ca6f8174d636 100644 --- a/app/Listeners/User/CreatedUserActivity.php +++ b/app/Listeners/User/CreatedUserActivity.php @@ -37,13 +37,13 @@ class CreatedUserActivity */ public function handle($event) { - $fields = new \stdClass; - if(auth()->user()) + if (auth()->user()) { $fields->user_id = auth()->user()->id; - else + } else { $fields->user_id = $event->user->id; + } $fields->company_id = $event->user->company_id; $fields->activity_type_id = Activity::CREATE_USER; diff --git a/app/Listeners/User/DeletedUserActivity.php b/app/Listeners/User/DeletedUserActivity.php index 1a4f0597e08b..0ea74bc19d6b 100644 --- a/app/Listeners/User/DeletedUserActivity.php +++ b/app/Listeners/User/DeletedUserActivity.php @@ -37,13 +37,13 @@ class DeletedUserActivity */ public function handle($event) { - $fields = new \stdClass; - if(auth()->user()->id) + if (auth()->user()->id) { $fields->user_id = auth()->user()->id; - else + } else { $fields->user_id = $event->user->id; + } $fields->company_id = $event->user->company_id; $fields->activity_type_id = Activity::DELETE_USER; diff --git a/app/Listeners/User/RestoredUserActivity.php b/app/Listeners/User/RestoredUserActivity.php index 233193eff691..71f41a85c19e 100644 --- a/app/Listeners/User/RestoredUserActivity.php +++ b/app/Listeners/User/RestoredUserActivity.php @@ -37,13 +37,13 @@ class RestoredUserActivity */ public function handle($event) { - $fields = new \stdClass; - if(auth()->user()->id) + if (auth()->user()->id) { $fields->user_id = auth()->user()->id; - else + } else { $fields->user_id = $event->user->id; + } $fields->company_id = $event->user->company_id; $fields->activity_type_id = Activity::RESTORE_USER; diff --git a/app/Listeners/User/UpdateUserLastLogin.php b/app/Listeners/User/UpdateUserLastLogin.php index 12d112e8b454..407c4874055b 100644 --- a/app/Listeners/User/UpdateUserLastLogin.php +++ b/app/Listeners/User/UpdateUserLastLogin.php @@ -35,11 +35,9 @@ class UpdateUserLastLogin */ public function handle($event) { + $user = $event->user; - $user = $event->user; - - $user->last_login = now(); - $user->save(); - + $user->last_login = now(); + $user->save(); } } diff --git a/app/Listeners/User/UpdatedUserActivity.php b/app/Listeners/User/UpdatedUserActivity.php index d75147d1d2b7..4aeafd8c7df4 100644 --- a/app/Listeners/User/UpdatedUserActivity.php +++ b/app/Listeners/User/UpdatedUserActivity.php @@ -37,13 +37,13 @@ class UpdatedUserActivity */ public function handle($event) { - $fields = new \stdClass; - if(auth()->user()->id) + if (auth()->user()->id) { $fields->user_id = auth()->user()->id; - else + } else { $fields->user_id = $event->user->id; + } $fields->company_id = $event->user->company_id; $fields->activity_type_id = Activity::UPDATE_USER; diff --git a/app/Mail/BouncedEmail.php b/app/Mail/BouncedEmail.php index 3afbeafea3fe..7b1bbcaadb6d 100644 --- a/app/Mail/BouncedEmail.php +++ b/app/Mail/BouncedEmail.php @@ -48,7 +48,7 @@ class BouncedEmail extends Mailable implements ShouldQueue ->text() ->subject($subject); - //todo + //todo /* @@ -58,7 +58,7 @@ class BouncedEmail extends Mailable implements ShouldQueue //->cc('') //->bcc('') ->queue(new BouncedEmail($invitation)); - + return $this->from('turbo124@gmail.com') //todo ->subject(ctrans('texts.confirmation_subject')) ->markdown('email.auth.verify', ['user' => $this->user]) diff --git a/app/Mail/SupportMessageSent.php b/app/Mail/SupportMessageSent.php index 2a95599427aa..34a17f8c1166 100644 --- a/app/Mail/SupportMessageSent.php +++ b/app/Mail/SupportMessageSent.php @@ -17,7 +17,6 @@ class SupportMessageSent extends Mailable public function __construct($message) { $this->message = $message; - } /** @@ -35,7 +34,7 @@ class SupportMessageSent extends Mailable * we are going to bundle system-level info * and last 10 lines of laravel.log file. */ - if(Ninja::isSelfHost()) { + if (Ninja::isSelfHost()) { $system_info = Ninja::getDebugInfo(); $log_file = new \SplFileObject(sprintf('%s/laravel.log', base_path('storage/logs'))); @@ -56,4 +55,3 @@ class SupportMessageSent extends Mailable ]); } } - diff --git a/app/Mail/TemplateEmail.php b/app/Mail/TemplateEmail.php index c8a4ced4a1c8..083c86e79cd3 100644 --- a/app/Mail/TemplateEmail.php +++ b/app/Mail/TemplateEmail.php @@ -58,12 +58,12 @@ class TemplateEmail extends Mailable //conditionally attach files - if($settings->pdf_email_attachment !== false && array_key_exists($this->message['files'])){ - - foreach($this->message['files'] as $file) + if ($settings->pdf_email_attachment !== false && array_key_exists($this->message['files'])) { + foreach ($this->message['files'] as $file) { $message->attach($file); + } } return $message; } -} \ No newline at end of file +} diff --git a/app/Mail/VerifyUser.php b/app/Mail/VerifyUser.php index a260ef365542..442bbfe2fc65 100644 --- a/app/Mail/VerifyUser.php +++ b/app/Mail/VerifyUser.php @@ -39,7 +39,6 @@ class VerifyUser extends Mailable implements ShouldQueue */ public function build() { - return $this->from('turbo124@gmail.com') //todo ->subject(ctrans('texts.confirmation_subject')) ->markdown('email.auth.verify', ['user' => $this->user]) diff --git a/app/Models/Activity.php b/app/Models/Activity.php index fe9f62df56cd..99e9c49cab86 100644 --- a/app/Models/Activity.php +++ b/app/Models/Activity.php @@ -15,7 +15,6 @@ use Illuminate\Database\Eloquent\Model; class Activity extends StaticModel { - const CREATE_CLIENT=1; const ARCHIVE_CLIENT=2; const DELETE_CLIENT=3; @@ -80,7 +79,7 @@ class Activity extends StaticModel public function backup() { - return $this->hasOne(Backup::class); + return $this->hasOne(Backup::class); } /** diff --git a/app/Models/Backup.php b/app/Models/Backup.php index d3c80ea126cc..1e634d92f6cb 100644 --- a/app/Models/Backup.php +++ b/app/Models/Backup.php @@ -18,8 +18,8 @@ use Laracasts\Presenter\PresentableTrait; class Backup extends BaseModel { - public function activity() - { - return $this->belongsTo(Activity::class); - } -} \ No newline at end of file + public function activity() + { + return $this->belongsTo(Activity::class); + } +} diff --git a/app/Models/Bank.php b/app/Models/Bank.php index 544cf2a532ab..807263168355 100644 --- a/app/Models/Bank.php +++ b/app/Models/Bank.php @@ -11,7 +11,6 @@ namespace App\Models; - /** * Class Bank. */ diff --git a/app/Models/BaseModel.php b/app/Models/BaseModel.php index 2c649c15ae69..df5d61d2774b 100644 --- a/app/Models/BaseModel.php +++ b/app/Models/BaseModel.php @@ -57,7 +57,7 @@ class BaseModel extends Model if (config()->has($configPath)) { $function = config()->get($configPath); - return call_user_func_array(array($this, $function[0]), $function[1]); + return call_user_func_array(array($this, $function[0]), $function[1]); } } @@ -79,7 +79,6 @@ class BaseModel extends Model */ public function scopeScope($query) { - $query->where($this->getTable() .'.company_id', '=', auth()->user()->company()->id); return $query; @@ -95,8 +94,8 @@ class BaseModel extends Model * The following method will return the entire object of the property searched for * where a value exists for $key. * - * This object can then be mutated by the handling class, - * to persist the new settings we will also need to pass back a + * This object can then be mutated by the handling class, + * to persist the new settings we will also need to pass back a * reference to the parent class. * * @param mixes $key The key of property @@ -104,14 +103,11 @@ class BaseModel extends Model public function getSettingsByKey($key) { /* Does Setting Exist @ client level */ - if(isset($this->getSettings()->{$key})) - { + if (isset($this->getSettings()->{$key})) { return $this->getSettings()->{$key}; + } else { + return (new CompanySettings($this->company->settings))->{$key}; } - else { - return (new CompanySettings($this->company->settings))->{$key}; - } - } @@ -141,7 +137,7 @@ class BaseModel extends Model * Gets the settings. * * Generic getter for client settings - * + * * @return ClientSettings The settings. */ public function getSettings() diff --git a/app/Models/Client.php b/app/Models/Client.php index 535ce1b1ca81..ec159d5dca1e 100644 --- a/app/Models/Client.php +++ b/app/Models/Client.php @@ -91,14 +91,15 @@ class Client extends BaseModel protected $with = [ - //'currency', - // 'primary_contact', - 'country', - // 'shipping_country', + //'currency', + // 'primary_contact', + 'country', + // 'shipping_country', // 'company' ]; protected $casts = [ + 'is_deleted' => 'boolean', 'country_id' => 'string', 'settings' => 'object', 'updated_at' => 'timestamp', @@ -117,7 +118,7 @@ class Client extends BaseModel * * Allows the storage of multiple tokens * per client per gateway per payment_method - * + * * @param int $company_gateway_id The company gateway ID * @param int $payment_method_id The payment method ID * @return ClientGatewayToken The client token record @@ -157,7 +158,7 @@ class Client extends BaseModel public function assigned_user() { - return $this->belongsTo(User::class ,'assigned_user_id', 'id'); + return $this->belongsTo(User::class, 'assigned_user_id', 'id'); } public function country() @@ -186,10 +187,10 @@ class Client extends BaseModel } public function date_format() - { + { $date_formats = Cache::get('date_formats'); - return $date_formats->filter(function($item) { + return $date_formats->filter(function ($item) { return $item->id == $this->getSetting('date_format_id'); })->first()->format; @@ -198,94 +199,86 @@ class Client extends BaseModel public function currency() { - $currencies = Cache::get('currencies'); - return $currencies->filter(function($item) { + return $currencies->filter(function ($item) { return $item->id == $this->getSetting('currency_id'); })->first(); - } /** - * - * Returns the entire filtered set + * + * Returns the entire filtered set * of settings which have been merged from * Client > Group > Company levels - * + * * @return object stdClass object of settings */ public function getMergedSettings() :object { - - if($this->group_settings !== null) - { - + if ($this->group_settings !== null) { $group_settings = ClientSettings::buildClientSettings($this->group_settings->settings, $this->settings); return ClientSettings::buildClientSettings($this->company->settings, $group_settings); - } return CompanySettings::setProperties(ClientSettings::buildClientSettings($this->company->settings, $this->settings)); } /** - * + * * Returns a single setting * which cascades from * Client > Group > Company - * + * * @param string $setting The Setting parameter * @return mixed The setting requested */ public function getSetting($setting) { /*Client Settings*/ - if($this->settings && (property_exists($this->settings, $setting) !== false) && (isset($this->settings->{$setting}) !== false) ){ + if ($this->settings && (property_exists($this->settings, $setting) !== false) && (isset($this->settings->{$setting}) !== false)) { /*need to catch empty string here*/ - if(is_string($this->settings->{$setting}) && (iconv_strlen($this->settings->{$setting}) >=1)){ + if (is_string($this->settings->{$setting}) && (iconv_strlen($this->settings->{$setting}) >=1)) { return $this->settings->{$setting}; } } /*Group Settings*/ - if($this->group_settings && (property_exists($this->group_settings->settings, $setting) !== false) && (isset($this->group_settings->settings->{$setting}) !== false)){ - return $this->group_settings->settings->{$setting}; + if ($this->group_settings && (property_exists($this->group_settings->settings, $setting) !== false) && (isset($this->group_settings->settings->{$setting}) !== false)) { + return $this->group_settings->settings->{$setting}; } /*Company Settings*/ - if((property_exists($this->company->settings, $setting) != false ) && (isset($this->company->settings->{$setting}) !== false) ){ + if ((property_exists($this->company->settings, $setting) != false) && (isset($this->company->settings->{$setting}) !== false)) { return $this->company->settings->{$setting}; } throw new \Exception("Settings corrupted", 1); - } public function getSettingEntity($setting) { /*Client Settings*/ - if($this->settings && (property_exists($this->settings, $setting) !== false) && (isset($this->settings->{$setting}) !== false) ){ + if ($this->settings && (property_exists($this->settings, $setting) !== false) && (isset($this->settings->{$setting}) !== false)) { /*need to catch empty string here*/ - if(is_string($this->settings->{$setting}) && (iconv_strlen($this->settings->{$setting}) >=1)){ + if (is_string($this->settings->{$setting}) && (iconv_strlen($this->settings->{$setting}) >=1)) { return $this; } } /*Group Settings*/ - if($this->group_settings && (property_exists($this->group_settings->settings, $setting) !== false) && (isset($this->group_settings->settings->{$setting}) !== false)){ - return $this->group_settings; + if ($this->group_settings && (property_exists($this->group_settings->settings, $setting) !== false) && (isset($this->group_settings->settings->{$setting}) !== false)) { + return $this->group_settings; } /*Company Settings*/ - if((property_exists($this->company->settings, $setting) != false ) && (isset($this->company->settings->{$setting}) !== false) ){ + if ((property_exists($this->company->settings, $setting) != false) && (isset($this->company->settings->{$setting}) !== false)) { return $this->company; } throw new \Exception("Could not find a settings object", 1); - } public function documents() @@ -300,24 +293,23 @@ class Client extends BaseModel /** * Returns the first Credit Card Gateway - * + * * @return NULL|CompanyGateway The Priority Credit Card gateway */ public function getCreditCardGateway() :?CompanyGateway { $company_gateways = $this->getSetting('company_gateway_ids'); - if($company_gateways) + if ($company_gateways) { $gateways = $this->company->company_gateways->whereIn('id', $payment_gateways); - else + } else { $gateways = $this->company->company_gateways; + } - foreach($gateways as $gateway) - { - - if(in_array(GatewayType::CREDIT_CARD, $gateway->driver($this)->gatewayTypes())) + foreach ($gateways as $gateway) { + if (in_array(GatewayType::CREDIT_CARD, $gateway->driver($this)->gatewayTypes())) { return $gateway; - + } } return null; @@ -335,62 +327,64 @@ class Client extends BaseModel * Generates an array of payment urls per client * for a given amount. * - * The route produced will provide the + * The route produced will provide the * company_gateway and payment_type ids * * The invoice/s will need to be injected - * upstream of this method as they are not + * upstream of this method as they are not * included in this logic. - * + * * @param float $amount The amount to be charged * @return array Array of payment labels and urls */ public function getPaymentMethods($amount) :array { -//this method will get all the possible gateways a client can pay with -//but we also need to consider payment methods that are already stored -//so we MUST filter the company gateways and remove duplicates. + //this method will get all the possible gateways a client can pay with + //but we also need to consider payment methods that are already stored + //so we MUST filter the company gateways and remove duplicates. // -//Also need to harvest the list of client gateway tokens and present these -//for instant payment + //Also need to harvest the list of client gateway tokens and present these + //for instant payment $company_gateways = $this->getSetting('company_gateway_ids'); - if($company_gateways) + if ($company_gateways) { $gateways = $this->company->company_gateways->whereIn('id', $payment_gateways); - else + } else { $gateways = $this->company->company_gateways; + } - $gateways->filter(function ($method) use ($amount){ - if($method->min_limit !== null && $amount < $method->min_limit) + $gateways->filter(function ($method) use ($amount) { + if ($method->min_limit !== null && $amount < $method->min_limit) { return false; + } - if($method->max_limit !== null && $amount > $method->min_limit) + if ($method->max_limit !== null && $amount > $method->min_limit) { return false; - }); + } + }); $payment_methods = []; - foreach($gateways as $gateway) - foreach($gateway->driver($this)->gatewayTypes() as $type) - $payment_methods[] = [$gateway->id => $type]; + foreach ($gateways as $gateway) { + foreach ($gateway->driver($this)->gatewayTypes() as $type) { + $payment_methods[] = [$gateway->id => $type]; + } + } $payment_methods_collections = collect($payment_methods); //** Plucks the remaining keys into its own collection - $payment_methods_intersect = $payment_methods_collections->intersectByKeys( $payment_methods_collections->flatten(1)->unique() ); + $payment_methods_intersect = $payment_methods_collections->intersectByKeys($payment_methods_collections->flatten(1)->unique()); $payment_urls = []; - foreach($payment_methods_intersect as $key => $child_array) - { - foreach($child_array as $gateway_id => $gateway_type_id) - { + foreach ($payment_methods_intersect as $key => $child_array) { + foreach ($child_array as $gateway_id => $gateway_type_id) { + $gateway = $gateways->where('id', $gateway_id)->first(); - $gateway = $gateways->where('id', $gateway_id)->first(); - - $fee_label = $gateway->calcGatewayFeeLabel($amount, $this); + $fee_label = $gateway->calcGatewayFeeLabel($amount, $this); $payment_urls[] = [ 'label' => ctrans('texts.' . $gateway->getTypeAlias($gateway_type_id)) . $fee_label, @@ -398,11 +392,8 @@ class Client extends BaseModel 'gateway_type_id' => $gateway_type_id ]; } - } - return $payment_urls; + return $payment_urls; } - - } diff --git a/app/Models/ClientContact.php b/app/Models/ClientContact.php index d4db22eef46d..329ee9656213 100644 --- a/app/Models/ClientContact.php +++ b/app/Models/ClientContact.php @@ -27,7 +27,6 @@ use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Log; use Laracasts\Presenter\PresentableTrait; - class ClientContact extends Authenticatable implements HasLocalePreference { use Notifiable; @@ -63,7 +62,7 @@ class ClientContact extends Authenticatable implements HasLocalePreference ]; protected $hidden = [ - 'password', + 'password', 'remember_token', 'user_id', 'company_id', @@ -105,12 +104,11 @@ class ClientContact extends Authenticatable implements HasLocalePreference public function setAvatarAttribute($value) { - - if(!filter_var($value, FILTER_VALIDATE_URL) && $value) + if (!filter_var($value, FILTER_VALIDATE_URL) && $value) { $this->attributes['avatar'] = url('/') . $value; - else + } else { $this->attributes['avatar'] = $value; - + } } public function client() @@ -142,7 +140,7 @@ class ClientContact extends Authenticatable implements HasLocalePreference { $languages = Cache::get('languages'); - return $languages->filter(function($item) { + return $languages->filter(function ($item) { return $item->id == $this->client->getSetting('language_id'); })->first()->locale; diff --git a/app/Models/ClientGatewayToken.php b/app/Models/ClientGatewayToken.php index 43a1dfa82908..4675317b03de 100644 --- a/app/Models/ClientGatewayToken.php +++ b/app/Models/ClientGatewayToken.php @@ -19,38 +19,37 @@ use App\Models\User; class ClientGatewayToken extends BaseModel { - - protected $casts = [ - 'meta' => 'object', + protected $casts = [ + 'meta' => 'object', 'updated_at' => 'timestamp', 'created_at' => 'timestamp', 'deleted_at' => 'timestamp', - ]; + ]; - public function client() - { - return $this->hasOne(Client::class)->withTrashed(); - } + public function client() + { + return $this->hasOne(Client::class)->withTrashed(); + } - public function gateway() - { - return $this->hasOne(CompanyGateway::class); - } + public function gateway() + { + return $this->hasOne(CompanyGateway::class); + } - public function gateway_type() - { - return $this->hasOne(GatewayType::class, 'id','gateway_type_id'); - } + public function gateway_type() + { + return $this->hasOne(GatewayType::class, 'id', 'gateway_type_id'); + } - public function company() - { - return $this->hasOne(Company::class); - } + public function company() + { + return $this->hasOne(Company::class); + } - public function user() - { - return $this->hasOne(User::class)->withTrashed(); - } + public function user() + { + return $this->hasOne(User::class)->withTrashed(); + } /** * Retrieve the model for a bound value. @@ -63,4 +62,4 @@ class ClientGatewayToken extends BaseModel return $this ->where('id', $this->decodePrimaryKey($value))->firstOrFail(); } -} \ No newline at end of file +} diff --git a/app/Models/Company.php b/app/Models/Company.php index c8c976c8af6f..dbaaf5a3a270 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -196,7 +196,7 @@ class Company extends BaseModel } /** - * + * */ public function timezone() { @@ -273,7 +273,7 @@ class Company extends BaseModel public function owner() { - $c = $this->company_users->where('is_owner',true)->first(); + $c = $this->company_users->where('is_owner', true)->first(); return User::find($c->user_id); } @@ -288,5 +288,4 @@ class Company extends BaseModel { return 'https://' . $this->subdomain . config('ninja.app_domain'); } - } diff --git a/app/Models/CompanyGateway.php b/app/Models/CompanyGateway.php index 5ac7b7ec4f90..e977687ba450 100644 --- a/app/Models/CompanyGateway.php +++ b/app/Models/CompanyGateway.php @@ -20,7 +20,6 @@ use Illuminate\Database\Eloquent\Model; class CompanyGateway extends BaseModel { - protected $casts = [ 'fees_and_limits' => 'object', 'updated_at' => 'timestamp', @@ -58,21 +57,21 @@ class CompanyGateway extends BaseModel public function company() { - return $this->belongsTo(Company::class); + return $this->belongsTo(Company::class); } public function gateway() { - return $this->belongsTo(Gateway::class, 'gateway_key', 'key'); + return $this->belongsTo(Gateway::class, 'gateway_key', 'key'); } public function getTypeAlias($gateway_type_id) { - - if($gateway_type_id == 'token') + if ($gateway_type_id == 'token') { $gateway_type_id = 1; + } - return GatewayType::find($gateway_type_id)->alias; + return GatewayType::find($gateway_type_id)->alias; } /* This is the public entry point into the payment superclass */ @@ -202,7 +201,7 @@ class CompanyGateway extends BaseModel /** * Returns the formatted fee amount for the gateway - * + * * @param float $amount The payment amount * @param Client $client The client object * @return string The fee amount formatted in the client currency @@ -211,12 +210,13 @@ class CompanyGateway extends BaseModel { $label = ''; - if(!$this->feesEnabled()) + if (!$this->feesEnabled()) { return $label; + } $fee = $this->calcGatewayFee($amount); - if($fee > 0 ){ + if ($fee > 0) { $fee = Number::formatMoney(round($fee, 2), $client); $label = ' - ' . $fee . ' ' . ctrans('texts.fee'); } @@ -228,19 +228,23 @@ class CompanyGateway extends BaseModel { $fee = 0; - if ($this->fee_amount) + if ($this->fee_amount) { $fee += $this->fee_amount; + } - if ($this->fee_percent) + if ($this->fee_percent) { $fee += $amount * $this->fee_percent / 100; + } $pre_tax_fee = $fee; - if ($this->fee_tax_rate1) + if ($this->fee_tax_rate1) { $fee += $pre_tax_fee * $this->fee_tax_rate1 / 100; + } - if ($this->fee_tax_rate2) + if ($this->fee_tax_rate2) { $fee += $pre_tax_fee * $this->fee_tax_rate2 / 100; + } return $fee; diff --git a/app/Models/CompanyLedger.php b/app/Models/CompanyLedger.php index 5f268dcc01f5..f23a72275d47 100644 --- a/app/Models/CompanyLedger.php +++ b/app/Models/CompanyLedger.php @@ -15,7 +15,6 @@ use Illuminate\Database\Eloquent\Model; class CompanyLedger extends Model { - protected $dateFormat = 'Y-m-d H:i:s.u'; protected $guarded = [ @@ -30,12 +29,12 @@ class CompanyLedger extends Model public function user() { - return $this->belongsTo(User::class); + return $this->belongsTo(User::class); } public function company() { - return $this->belongsTo(Company::class); + return $this->belongsTo(Company::class); } public function company_ledgerable() diff --git a/app/Models/CompanyToken.php b/app/Models/CompanyToken.php index c0cb5b5cd600..93e373cafc9c 100644 --- a/app/Models/CompanyToken.php +++ b/app/Models/CompanyToken.php @@ -42,11 +42,11 @@ class CompanyToken extends Model public function user() { - return $this->belongsTo(User::class); + return $this->belongsTo(User::class); } public function company() { - return $this->belongsTo(Company::class); + return $this->belongsTo(Company::class); } } diff --git a/app/Models/CompanyUser.php b/app/Models/CompanyUser.php index 1f8b5414015c..1b3528d45358 100644 --- a/app/Models/CompanyUser.php +++ b/app/Models/CompanyUser.php @@ -15,7 +15,7 @@ use Illuminate\Database\Eloquent\Relations\Pivot; class CompanyUser extends Pivot { - // protected $guarded = ['id']; + // protected $guarded = ['id']; protected $dateFormat = 'Y-m-d H:i:s.u'; @@ -53,7 +53,7 @@ class CompanyUser extends Pivot public function company_pivot() { - return $this->hasOne(Company::class)->withPivot('permissions', 'settings', 'is_admin', 'is_owner', 'is_locked'); + return $this->hasOne(Company::class)->withPivot('permissions', 'settings', 'is_admin', 'is_owner', 'is_locked'); } public function user() @@ -74,7 +74,7 @@ class CompanyUser extends Pivot /*todo monitor this function - may fail under certain conditions*/ public function token() { - return $this->belongsTo(CompanyToken::class, 'user_id','user_id'); + return $this->belongsTo(CompanyToken::class, 'user_id', 'user_id'); /* diff --git a/app/Models/Country.php b/app/Models/Country.php index 139f07ab468d..827a861ca667 100644 --- a/app/Models/Country.php +++ b/app/Models/Country.php @@ -28,14 +28,11 @@ class Country extends StaticModel /** * Localizes the country name for the clients language. - * + * * @return string The translated country name */ public function getName() :string { return trans('texts.country_' . $this->name); } - - } - diff --git a/app/Models/Credit.php b/app/Models/Credit.php index 655d8d8a8aae..99d3a7eb0493 100644 --- a/app/Models/Credit.php +++ b/app/Models/Credit.php @@ -27,6 +27,6 @@ class Credit extends BaseModel public function assigned_user() { - return $this->belongsTo(User::class ,'assigned_user_id', 'id'); + return $this->belongsTo(User::class, 'assigned_user_id', 'id'); } } diff --git a/app/Models/Currency.php b/app/Models/Currency.php index c9636390f166..49ca2e496d49 100644 --- a/app/Models/Currency.php +++ b/app/Models/Currency.php @@ -23,5 +23,4 @@ class Currency extends StaticModel 'created_at' => 'timestamp', 'deleted_at' => 'timestamp', ]; - } diff --git a/app/Models/DateFormat.php b/app/Models/DateFormat.php index 87b560c6f215..d8ba5d4e5b7f 100644 --- a/app/Models/DateFormat.php +++ b/app/Models/DateFormat.php @@ -7,7 +7,6 @@ namespace App\Models; */ class DateFormat extends StaticModel { - public static $days_of_the_week = [ 0 => 'sunday', 1 => 'monday', diff --git a/app/Models/Document.php b/app/Models/Document.php index 63de91a9874b..e1c5e2a63fc7 100644 --- a/app/Models/Document.php +++ b/app/Models/Document.php @@ -25,7 +25,7 @@ class Document extends BaseModel ]; - /** + /** * @var array */ public static $types = [ @@ -89,5 +89,4 @@ class Document extends BaseModel { return $this->morphTo(); } - } diff --git a/app/Models/Expense.php b/app/Models/Expense.php index aa07618e3338..e30997e3f30c 100644 --- a/app/Models/Expense.php +++ b/app/Models/Expense.php @@ -19,7 +19,7 @@ class Expense extends BaseModel use MakesHash; protected $guarded = [ - 'id', + 'id', ]; protected $appends = ['expense_id']; @@ -41,6 +41,6 @@ class Expense extends BaseModel public function assigned_user() { - return $this->belongsTo(User::class ,'assigned_user_id', 'id'); + return $this->belongsTo(User::class, 'assigned_user_id', 'id'); } } diff --git a/app/Models/Filterable.php b/app/Models/Filterable.php index c7c7ec9cae30..a88d5a219897 100644 --- a/app/Models/Filterable.php +++ b/app/Models/Filterable.php @@ -27,4 +27,4 @@ trait Filterable { return $filters->apply($query); } -} \ No newline at end of file +} diff --git a/app/Models/Gateway.php b/app/Models/Gateway.php index b99fb90e73d0..2d2ae06e5072 100644 --- a/app/Models/Gateway.php +++ b/app/Models/Gateway.php @@ -16,7 +16,6 @@ use Omnipay\Omnipay; class Gateway extends StaticModel { - protected $casts = [ 'is_offsite' => 'boolean', 'is_secure' => 'boolean', @@ -33,18 +32,14 @@ class Gateway extends StaticModel */ public function getFields() { - - if ($this->isCustom()) - { + if ($this->isCustom()) { return [ 'name' => '', 'text' => '', ]; - } else - { + } else { return Omnipay::create($this->provider)->getDefaultParameters(); } - } /** @@ -53,11 +48,6 @@ class Gateway extends StaticModel */ public function isCustom() :bool { - return in_array($this->id, [62, 67, 68]); //static table ids of the custom gateways - } - } - - diff --git a/app/Models/GatewayType.php b/app/Models/GatewayType.php index a7c78ba04d01..9e8251569e7d 100644 --- a/app/Models/GatewayType.php +++ b/app/Models/GatewayType.php @@ -16,7 +16,6 @@ use Illuminate\Database\Eloquent\Model; class GatewayType extends StaticModel { - public $timestamps = false; const CREDIT_CARD = 1; @@ -34,11 +33,8 @@ class GatewayType extends StaticModel const CUSTOM3 = 13; const TOKEN = 'token'; - public function gateway() - { - return $this->belongsTo(Gateway::class); - } - + public function gateway() + { + return $this->belongsTo(Gateway::class); + } } - - diff --git a/app/Models/GroupSetting.php b/app/Models/GroupSetting.php index c938776ba318..f0dd4d58031d 100644 --- a/app/Models/GroupSetting.php +++ b/app/Models/GroupSetting.php @@ -23,9 +23,9 @@ use Illuminate\Database\Eloquent\Model; class GroupSetting extends StaticModel { - use MakesHash; - - public $timestamps = false; + use MakesHash; + + public $timestamps = false; protected $casts = [ 'settings' => 'object', @@ -35,24 +35,24 @@ class GroupSetting extends StaticModel ]; protected $fillable = [ - 'name', - 'settings' + 'name', + 'settings' ]; - public function company() - { - return $this->belongsTo(Company::class); - } + public function company() + { + return $this->belongsTo(Company::class); + } - public function user() - { - return $this->belongsTo(User::class); - } + public function user() + { + return $this->belongsTo(User::class); + } - public function clients() - { - return $this->hasMany(Client::class, 'id', 'group_settings_id'); - } + public function clients() + { + return $this->hasMany(Client::class, 'id', 'group_settings_id'); + } /** * Retrieve the model for a bound value. @@ -65,4 +65,4 @@ class GroupSetting extends StaticModel return $this ->where('id', $this->decodePrimaryKey($value))->firstOrFail(); } -} \ No newline at end of file +} diff --git a/app/Models/Invoice.php b/app/Models/Invoice.php index 0fd0ae9d639c..6d0f178a868d 100644 --- a/app/Models/Invoice.php +++ b/app/Models/Invoice.php @@ -118,18 +118,17 @@ class Invoice extends BaseModel public function getStatusAttribute() { - - if($this->status_id == Invoice::STATUS_SENT && $this->due_date > Carbon::now()) + if ($this->status_id == Invoice::STATUS_SENT && $this->due_date > Carbon::now()) { return Invoice::STATUS_UNPAID; - else if($this->status_id == Invoice::STATUS_PARTIAL && $this->partial_due_date > Carbon::now()) + } elseif ($this->status_id == Invoice::STATUS_PARTIAL && $this->partial_due_date > Carbon::now()) { return Invoice::STATUS_UNPAID; - else if($this->status_id == Invoice::STATUS_SENT && $this->due_date < Carbon::now()) + } elseif ($this->status_id == Invoice::STATUS_SENT && $this->due_date < Carbon::now()) { return Invoice::STATUS_OVERDUE; - else if($this->status_id == Invoice::STATUS_PARTIAL && $this->partial_due_date < Carbon::now()) + } elseif ($this->status_id == Invoice::STATUS_PARTIAL && $this->partial_due_date < Carbon::now()) { return Invoice::STATUS_OVERDUE; - else + } else { return $this->status_id; - + } } public function company() @@ -144,7 +143,7 @@ class Invoice extends BaseModel public function assigned_user() { - return $this->belongsTo(User::class ,'assigned_user_id', 'id')->withTrashed(); + return $this->belongsTo(User::class, 'assigned_user_id', 'id')->withTrashed(); } public function invitations() @@ -213,17 +212,17 @@ class Invoice extends BaseModel public function isPayable() : bool { - - if($this->status_id == Invoice::STATUS_SENT && $this->due_date > Carbon::now()) + if ($this->status_id == Invoice::STATUS_SENT && $this->due_date > Carbon::now()) { return true; - else if($this->status_id == Invoice::STATUS_PARTIAL && $this->partial_due_date > Carbon::now()) + } elseif ($this->status_id == Invoice::STATUS_PARTIAL && $this->partial_due_date > Carbon::now()) { return true; - else if($this->status_id == Invoice::STATUS_SENT && $this->due_date < Carbon::now()) + } elseif ($this->status_id == Invoice::STATUS_SENT && $this->due_date < Carbon::now()) { return true; - else if($this->status_id == Invoice::STATUS_PARTIAL && $this->partial_due_date < Carbon::now()) + } elseif ($this->status_id == Invoice::STATUS_PARTIAL && $this->partial_due_date < Carbon::now()) { return true; - else + } else { return false; + } } public static function badgeForStatus(int $status) @@ -299,10 +298,11 @@ class Invoice extends BaseModel */ public function design() :string { - if($this->client->getSetting('design')) + if ($this->client->getSetting('design')) { return File::exists(resource_path($this->client->getSetting('design'))) ? File::get(resource_path($this->client->getSetting('design'))) : File::get(resource_path('views/pdf/design1.blade.php')); - else + } else { return File::get(resource_path('views/pdf/design1.blade.php')); + } } /** @@ -314,13 +314,13 @@ class Invoice extends BaseModel { $invoice_calc = null; - if($this->uses_inclusive_taxes) + if ($this->uses_inclusive_taxes) { $invoice_calc = new InvoiceSumInclusive($this); - else + } else { $invoice_calc = new InvoiceSum($this); + } return $invoice_calc->build(); - } /** TODO// DOCUMENT THIS FUNCTIONALITY */ @@ -330,7 +330,7 @@ class Invoice extends BaseModel $storage_path = 'public/' . $this->client->client_hash . '/invoices/'. $this->number . '.pdf'; - if(!Storage::exists($storage_path)) { + if (!Storage::exists($storage_path)) { event(new InvoiceWasUpdated($this, $this->company)); CreateInvoicePdf::dispatch($this, $this->company); } @@ -342,7 +342,7 @@ class Invoice extends BaseModel { $storage_path = 'storage/' . $this->client->client_hash . '/invoices/'. $this->number . '.pdf'; - if(!Storage::exists($storage_path)) { + if (!Storage::exists($storage_path)) { CreateInvoicePdf::dispatchNow($this, $this->company); } @@ -403,15 +403,15 @@ class Invoice extends BaseModel */ public function updateBalance($balance_adjustment) { - - if ($this->is_deleted) + if ($this->is_deleted) { return; + } $balance_adjustment = floatval($balance_adjustment); $this->balance = $this->balance + $balance_adjustment; - if($this->balance == 0) { + if ($this->balance == 0) { $this->status_id = self::STATUS_PAID; $this->save(); event(new InvoiceWasPaid($this, $this->company)); @@ -437,8 +437,9 @@ class Invoice extends BaseModel public function markSent() { /* Return immediately if status is not draft */ - if($this->status_id != Invoice::STATUS_DRAFT) + if ($this->status_id != Invoice::STATUS_DRAFT) { return $this; + } $this->status_id = Invoice::STATUS_SENT; @@ -465,15 +466,11 @@ class Invoice extends BaseModel */ private function markInvitationsSent() { - $this->invitations->each(function($invitation) { - - if(!isset($invitation->sent_date)) - { + $this->invitations->each(function ($invitation) { + if (!isset($invitation->sent_date)) { $invitation->sent_date = Carbon::now(); $invitation->save(); } - }); } - } diff --git a/app/Models/InvoiceInvitation.php b/app/Models/InvoiceInvitation.php index 37d1125898f4..669c13892ce2 100644 --- a/app/Models/InvoiceInvitation.php +++ b/app/Models/InvoiceInvitation.php @@ -20,8 +20,7 @@ use Illuminate\Support\Carbon; class InvoiceInvitation extends BaseModel { - - use MakesDates; + use MakesDates; use SoftDeletes; use Inviteable; @@ -52,7 +51,7 @@ class InvoiceInvitation extends BaseModel */ public function contact() { - return $this->belongsTo(ClientContact::class,'client_contact_id','id')->withTrashed(); + return $this->belongsTo(ClientContact::class, 'client_contact_id', 'id')->withTrashed(); } /** diff --git a/app/Models/Language.php b/app/Models/Language.php index 6a53f340eb8d..fd6ebe82b987 100644 --- a/app/Models/Language.php +++ b/app/Models/Language.php @@ -16,5 +16,4 @@ use Illuminate\Database\Eloquent\Model; class Language extends StaticModel { public $timestamps = false; - } diff --git a/app/Models/Payment.php b/app/Models/Payment.php index 60d83307ff9f..2356ecaacbfe 100644 --- a/app/Models/Payment.php +++ b/app/Models/Payment.php @@ -51,13 +51,13 @@ class Payment extends BaseModel const TYPE_TOKEN = 'token'; protected $fillable = [ - 'client_id', + 'client_id', 'type_id', 'amount', 'date', 'transaction_reference', 'number' - ]; + ]; protected $casts = [ 'settings' => 'object', @@ -84,7 +84,7 @@ class Payment extends BaseModel public function assigned_user() { - return $this->belongsTo(User::class ,'assigned_user_id', 'id')->withTrashed(); + return $this->belongsTo(User::class, 'assigned_user_id', 'id')->withTrashed(); } public function documents() @@ -119,8 +119,9 @@ class Payment extends BaseModel public function clientPaymentDate() { - if(!$this->date) + if (!$this->date) { return ''; + } $date_format = DateFormat::find($this->client->getSetting('date_format_id')); @@ -147,7 +148,7 @@ class Payment extends BaseModel break; case self::STATUS_REFUNDED: return '
'.ctrans('texts.payment_status_6').'
'; - break; + break; default: # code... break; diff --git a/app/Models/PaymentLibrary.php b/app/Models/PaymentLibrary.php index a17026bc373a..9c8e11e3e485 100644 --- a/app/Models/PaymentLibrary.php +++ b/app/Models/PaymentLibrary.php @@ -18,13 +18,10 @@ use Illuminate\Database\Eloquent\Model; */ class PaymentLibrary extends BaseModel { - protected $casts = [ 'visible' => 'boolean', 'updated_at' => 'timestamp', 'created_at' => 'timestamp', 'deleted_at' => 'timestamp', ]; - - } diff --git a/app/Models/PaymentTerm.php b/app/Models/PaymentTerm.php index 3afff9fae155..d46a07b3d913 100644 --- a/app/Models/PaymentTerm.php +++ b/app/Models/PaymentTerm.php @@ -41,7 +41,7 @@ class PaymentTerm extends BaseModel $terms = self::scope()->get(); - $terms->map(function($term) { + $terms->map(function ($term) { return $term['num_days']; }); @@ -51,7 +51,6 @@ class PaymentTerm extends BaseModel ->all(); return $default_terms; - } public static function getSelectOptions() diff --git a/app/Models/Paymentable.php b/app/Models/Paymentable.php index 65b77493b5bb..d18d5de4a6b7 100644 --- a/app/Models/Paymentable.php +++ b/app/Models/Paymentable.php @@ -20,6 +20,4 @@ class Paymentable extends Pivot // public $incrementing = true; protected $table = 'paymentables'; - - -} \ No newline at end of file +} diff --git a/app/Models/Presenters/AccountPresenter.php b/app/Models/Presenters/AccountPresenter.php index 11f37e8f88ad..4caa06dfd1da 100644 --- a/app/Models/Presenters/AccountPresenter.php +++ b/app/Models/Presenters/AccountPresenter.php @@ -18,6 +18,4 @@ use Laracasts\Presenter\Presenter; */ class AccountPresenter extends Presenter { - - } diff --git a/app/Models/Presenters/ClientContactPresenter.php b/app/Models/Presenters/ClientContactPresenter.php index 2f0f2d9c1695..470159049e51 100644 --- a/app/Models/Presenters/ClientContactPresenter.php +++ b/app/Models/Presenters/ClientContactPresenter.php @@ -25,5 +25,4 @@ class ClientContactPresenter extends EntityPresenter { return $this->entity->first_name . ' ' . $this->entity->last_name; } - } diff --git a/app/Models/Presenters/ClientPresenter.php b/app/Models/Presenters/ClientPresenter.php index 7cb4b62bc320..84b66f13fdaa 100644 --- a/app/Models/Presenters/ClientPresenter.php +++ b/app/Models/Presenters/ClientPresenter.php @@ -29,8 +29,9 @@ class ClientPresenter extends EntityPresenter $contact_name = 'No Contact Set'; - if($contact) + if ($contact) { $contact_name = $contact->first_name. ' '. $contact->last_name; + } return $this->entity->name ?: $contact_name; } @@ -98,12 +99,11 @@ class ClientPresenter extends EntityPresenter } /** - * Calculated company data fields + * Calculated company data fields * using settings */ public function company_name() { - $settings = $this->entity->getMergedSettings(); return $settings->name ?: ctrans('texts.untitled_account'); @@ -111,7 +111,6 @@ class ClientPresenter extends EntityPresenter public function company_address() { - $settings = $this->entity->getMergedSettings(); $str = ''; @@ -130,7 +129,6 @@ class ClientPresenter extends EntityPresenter } return $str; - } public function getCityState() @@ -139,8 +137,9 @@ class ClientPresenter extends EntityPresenter $country = false; - if($settings->country_id) + if ($settings->country_id) { $country = Country::find($settings->country_id); + } $swap = $country && $country->swap_postal_code; diff --git a/app/Models/Presenters/CompanyPresenter.php b/app/Models/Presenters/CompanyPresenter.php index c821da4b4fff..7898a2d9fd13 100644 --- a/app/Models/Presenters/CompanyPresenter.php +++ b/app/Models/Presenters/CompanyPresenter.php @@ -30,8 +30,9 @@ class CompanyPresenter extends EntityPresenter public function logo($settings = null) { - if(!$settings) + if (!$settings) { $settings = $this->entity->settings; + } return iconv_strlen($settings->company_logo > 0) ? $settings->company_logo : 'https://www.invoiceninja.com/wp-content/uploads/2019/01/InvoiceNinja-Logo-Round-300x300.png'; } @@ -41,8 +42,9 @@ class CompanyPresenter extends EntityPresenter $str = ''; $company = $this->entity; - if(!$settings) + if (!$settings) { $settings = $this->entity->settings; + } if ($address1 = $settings->address1) { $str .= e($address1) . '
'; @@ -68,8 +70,9 @@ class CompanyPresenter extends EntityPresenter public function getCompanyCityState($settings = null) { - if(!$settings) + if (!$settings) { $settings = $this->entity->settings; + } $country = Country::find($settings->country_id)->first(); @@ -85,5 +88,4 @@ class CompanyPresenter extends EntityPresenter return false; } } - } diff --git a/app/Models/Presenters/EntityPresenter.php b/app/Models/Presenters/EntityPresenter.php index 84754355a8ee..f41fa6f77479 100644 --- a/app/Models/Presenters/EntityPresenter.php +++ b/app/Models/Presenters/EntityPresenter.php @@ -39,7 +39,6 @@ class EntityPresenter extends Presenter */ public function url() { - } /** @@ -47,7 +46,6 @@ class EntityPresenter extends Presenter */ public function path() { - } /** @@ -62,7 +60,6 @@ class EntityPresenter extends Presenter */ public function statusLabel($label = false) { - } /** @@ -70,7 +67,6 @@ class EntityPresenter extends Presenter */ public function statusColor() { - } /** @@ -78,7 +74,6 @@ class EntityPresenter extends Presenter */ public function link() { - } /** @@ -86,7 +81,6 @@ class EntityPresenter extends Presenter */ public function titledName() { - } /** @@ -94,7 +88,6 @@ class EntityPresenter extends Presenter */ public function calendarEvent($subColors = false) { - } public function getCityState() diff --git a/app/Models/Presenters/InvoicePresenter.php b/app/Models/Presenters/InvoicePresenter.php index 6c91bab2c7d3..01c2b7e55152 100644 --- a/app/Models/Presenters/InvoicePresenter.php +++ b/app/Models/Presenters/InvoicePresenter.php @@ -17,68 +17,66 @@ use App\Utils\Traits\MakesDates; /** * Class InvoicePresenter * - * For convenience and to allow users to easiliy + * For convenience and to allow users to easiliy * customise their invoices, we provide all possible * invoice variables to be available from this presenter. * - * Shortcuts to other presenters are here to facilitate + * Shortcuts to other presenters are here to facilitate * a clean UI / UX - * + * * @package App\Models\Presenters */ class InvoicePresenter extends EntityPresenter { - use MakesDates; + use MakesDates; - public function amount() - { - return Number::formatMoney($this->balance, $this->client); - } + public function amount() + { + return Number::formatMoney($this->balance, $this->client); + } - public function invoice_number() - { + public function invoice_number() + { + if ($this->number != '') { + return $this->number; + } else { + return ''; + } + } - if($this->number != '') - return $this->number; - else - return ''; + public function clientName() + { + return $this->client->present()->name(); + } - } + public function address() + { + return $this->client->present()->address(); + } - public function clientName() - { - return $this->client->present()->name(); - } + public function shippingAddress() + { + return $this->client->present()->shipping_address(); + } - public function address() - { - return $this->client->present()->address(); - } + public function companyLogo() + { + return $this->company->logo; + } - public function shippingAddress() - { - return $this->client->present()->shipping_address(); - } + public function clientLogo() + { + return $this->client->logo; + } - public function companyLogo() - { - return $this->company->logo; - } - - public function clientLogo() - { - return $this->client->logo; - } - - public function companyName() - { - return $this->company->present()->name(); - } - - public function companyAddress() - { - return $this->company->present()->address(); - } + public function companyName() + { + return $this->company->present()->name(); + } + public function companyAddress() + { + return $this->company->present()->address(); + } } diff --git a/app/Models/Presenters/UserPresenter.php b/app/Models/Presenters/UserPresenter.php index 3fb1ab612e4b..693d8c169e93 100644 --- a/app/Models/Presenters/UserPresenter.php +++ b/app/Models/Presenters/UserPresenter.php @@ -23,10 +23,9 @@ class UserPresenter extends EntityPresenter */ public function name() { - $first_name = isset($this->entity->first_name) ? $this->entity->first_name : ''; - $last_name = isset($this->entity->last_name) ? $this->entity->last_name : ''; - + $first_name = isset($this->entity->first_name) ? $this->entity->first_name : ''; + $last_name = isset($this->entity->last_name) ? $this->entity->last_name : ''; + return $first_name . ' ' . $last_name; } - } diff --git a/app/Models/Product.php b/app/Models/Product.php index 8a33f656af47..e1c3e3211126 100644 --- a/app/Models/Product.php +++ b/app/Models/Product.php @@ -26,7 +26,7 @@ class Product extends BaseModel 'custom_value1', 'custom_value2', 'custom_value3', - 'custom_value4', + 'custom_value4', 'product_key', 'notes', 'cost', @@ -52,13 +52,11 @@ class Product extends BaseModel public function assigned_user() { - return $this->belongsTo(User::class ,'assigned_user_id', 'id')->withTrashed(); + return $this->belongsTo(User::class, 'assigned_user_id', 'id')->withTrashed(); } public function documents() { return $this->morphMany(Document::class, 'documentable'); } - - } diff --git a/app/Models/Proposal.php b/app/Models/Proposal.php index c954cd11e8a0..a26d298c76b5 100644 --- a/app/Models/Proposal.php +++ b/app/Models/Proposal.php @@ -18,9 +18,9 @@ class Proposal extends BaseModel { use MakesHash; - protected $guarded = [ - 'id', - ]; + protected $guarded = [ + 'id', + ]; protected $appends = ['proposal_id']; @@ -41,7 +41,6 @@ class Proposal extends BaseModel public function assigned_user() { - return $this->belongsTo(User::class ,'assigned_user_id', 'id'); + return $this->belongsTo(User::class, 'assigned_user_id', 'id'); } - } diff --git a/app/Models/Quote.php b/app/Models/Quote.php index f083f21568ef..b45e64b51dd2 100644 --- a/app/Models/Quote.php +++ b/app/Models/Quote.php @@ -83,7 +83,7 @@ class Quote extends BaseModel public function assigned_user() { - return $this->belongsTo(User::class ,'assigned_user_id', 'id')->withTrashed(); + return $this->belongsTo(User::class, 'assigned_user_id', 'id')->withTrashed(); } public function invitations() @@ -105,13 +105,12 @@ class Quote extends BaseModel { $quote_calc = null; - if($this->uses_inclusive_taxes) + if ($this->uses_inclusive_taxes) { $quote_calc = new InvoiceSumInclusive($this); - else + } else { $quote_calc = new InvoiceSum($this); + } return $quote_calc->build(); - } - } diff --git a/app/Models/QuoteInvitation.php b/app/Models/QuoteInvitation.php index 72040c4d862c..165c13aa7f70 100644 --- a/app/Models/QuoteInvitation.php +++ b/app/Models/QuoteInvitation.php @@ -17,8 +17,7 @@ use Illuminate\Database\Eloquent\Model; class QuoteInvitation extends BaseModel { - - use MakesDates; + use MakesDates; protected $fillable = [ 'id', @@ -71,5 +70,4 @@ class QuoteInvitation extends BaseModel return sprintf('

%s: %s', $this->signature_base64, ctrans('texts.signed'), $this->createClientDate($this->signature_date, $this->contact->client->timezone()->name)); } - } diff --git a/app/Models/RecurringInvoice.php b/app/Models/RecurringInvoice.php index ad7656b01cd8..b0545e3bc878 100644 --- a/app/Models/RecurringInvoice.php +++ b/app/Models/RecurringInvoice.php @@ -41,16 +41,16 @@ class RecurringInvoice extends BaseModel * Recurring intervals //todo MAP WHEN WE MIGRATE */ -/* Make sure we support overflow!!!!!!!!!! -$start = Carbon::today(); -$subscription = Carbon::parse('2017-12-31'); - -foreach (range(1, 12) as $month) { - $day = $start->addMonthNoOverflow()->thisDayOrLast($subscription->day); - - echo "You will be billed on {$day} in month {$month}\n"; -} - */ + /* Make sure we support overflow!!!!!!!!!! + $start = Carbon::today(); + $subscription = Carbon::parse('2017-12-31'); + + foreach (range(1, 12) as $month) { + $day = $start->addMonthNoOverflow()->thisDayOrLast($subscription->day); + + echo "You will be billed on {$day} in month {$month}\n"; + } + */ const FREQUENCY_DAILY = 1; @@ -68,8 +68,8 @@ foreach (range(1, 12) as $month) { const RECURS_INDEFINITELY = -1; - protected $fillable = [ - 'client_id', + protected $fillable = [ + 'client_id', 'number', 'discount', 'is_amount_discount', @@ -96,7 +96,7 @@ foreach (range(1, 12) as $month) { 'partial', 'frequency_id', 'start_date', - ]; + ]; protected $casts = [ 'settings' => 'object', @@ -128,7 +128,7 @@ foreach (range(1, 12) as $month) { public function assigned_user() { - return $this->belongsTo(User::class ,'assigned_user_id', 'id')->withTrashed(); + return $this->belongsTo(User::class, 'assigned_user_id', 'id')->withTrashed(); } public function invoices() @@ -143,21 +143,18 @@ foreach (range(1, 12) as $month) { public function getStatusAttribute() { - - if($this->status_id == RecurringInvoice::STATUS_ACTIVE && $this->start_date > Carbon::now()) //marked as active, but yet to fire first cycle + if ($this->status_id == RecurringInvoice::STATUS_ACTIVE && $this->start_date > Carbon::now()) { //marked as active, but yet to fire first cycle return RecurringInvoice::STATUS_PENDING; - else if($this->status_id == RecurringInvoice::STATUS_ACTIVE && $this->next_send_date > Carbon::now()) + } elseif ($this->status_id == RecurringInvoice::STATUS_ACTIVE && $this->next_send_date > Carbon::now()) { return RecurringInvoice::STATUS_COMPLETED; - else + } else { return $this->status_id; - + } } public function nextSendDate() :?Carbon { - - switch ($this->frequency_id) - { + switch ($this->frequency_id) { case RecurringInvoice::FREQUENCY_WEEKLY: return Carbon::parse($this->next_send_date->addWeek()); case RecurringInvoice::FREQUENCY_TWO_WEEKS: @@ -183,27 +180,23 @@ foreach (range(1, 12) as $month) { default: return null; } - } public function remainingCycles() : int { - - if($this->remaining_cycles == 0) + if ($this->remaining_cycles == 0) { return 0; - else + } else { return $this->remaining_cycles - 1; - + } } public function setCompleted() : void { - $this->status_id = self::STATUS_COMPLETED; $this->next_send_date = null; $this->remaining_cycles = 0; $this->save(); - } public static function badgeForStatus(int $status) @@ -223,7 +216,7 @@ foreach (range(1, 12) as $month) { break; case RecurringInvoice::STATUS_CANCELLED: return '

'.ctrans('texts.overdue').'

'; - break; + break; default: # code... break; @@ -262,14 +255,13 @@ foreach (range(1, 12) as $month) { break; case RecurringInvoice::FREQUENCY_TWO_YEARS: return ctrans('texts.freq_two_years'); - break; + break; case RecurringInvoice::RECURS_INDEFINITELY: return ctrans('texts.freq_indefinitely'); - break; + break; default: # code... break; } } - } diff --git a/app/Models/RecurringInvoiceInvitation.php b/app/Models/RecurringInvoiceInvitation.php index 04d1aafc84d5..ec75f2581a1f 100644 --- a/app/Models/RecurringInvoiceInvitation.php +++ b/app/Models/RecurringInvoiceInvitation.php @@ -16,8 +16,7 @@ use Illuminate\Database\Eloquent\Model; class RecurringInvoiceInvitation extends BaseModel { - - use MakesDates; + use MakesDates; /** * @return mixed @@ -59,5 +58,4 @@ class RecurringInvoiceInvitation extends BaseModel return sprintf('

%s: %s', $this->signature_base64, ctrans('texts.signed'), $this->createClientDate($this->signature_date, $this->contact->client->timezone()->name)); } - } diff --git a/app/Models/RecurringQuote.php b/app/Models/RecurringQuote.php index d241c175399f..34281b9681ff 100644 --- a/app/Models/RecurringQuote.php +++ b/app/Models/RecurringQuote.php @@ -109,12 +109,11 @@ class RecurringQuote extends BaseModel public function assigned_user() { - return $this->belongsTo(User::class ,'assigned_user_id', 'id')->withTrashed(); + return $this->belongsTo(User::class, 'assigned_user_id', 'id')->withTrashed(); } public function invitations() { $this->morphMany(RecurringQuoteInvitation::class); } - } diff --git a/app/Models/Size.php b/app/Models/Size.php index ded59032338d..355c89e29810 100644 --- a/app/Models/Size.php +++ b/app/Models/Size.php @@ -10,8 +10,8 @@ */ namespace App\Models; -use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Model; /** * Class Size. @@ -23,5 +23,4 @@ class Size extends StaticModel * @var bool */ public $timestamps = false; - } diff --git a/app/Models/StaticModel.php b/app/Models/StaticModel.php index aaef1d147423..a544b6419ce8 100644 --- a/app/Models/StaticModel.php +++ b/app/Models/StaticModel.php @@ -15,14 +15,13 @@ use Illuminate\Database\Eloquent\Model; class StaticModel extends Model { - protected $casts = [ 'updated_at' => 'timestamp', 'created_at' => 'timestamp', 'deleted_at' => 'timestamp', ]; - protected $dateFormat = 'Y-m-d H:i:s.u'; + protected $dateFormat = 'Y-m-d H:i:s.u'; public function getIdAttribute() { @@ -38,5 +37,4 @@ class StaticModel extends Model return $query; } - } diff --git a/app/Models/Task.php b/app/Models/Task.php index c94af6350f96..20d7d6e21850 100644 --- a/app/Models/Task.php +++ b/app/Models/Task.php @@ -19,14 +19,14 @@ class Task extends BaseModel use MakesHash; protected $fillable = [ - 'client_id', + 'client_id', 'invoice_id', 'custom_value1', 'custom_value2', 'description', 'is_running', 'time_log', - ]; + ]; protected $appends = ['task_id']; @@ -47,7 +47,7 @@ class Task extends BaseModel public function assigned_user() { - return $this->belongsTo(User::class ,'assigned_user_id', 'id')->withTrashed(); + return $this->belongsTo(User::class, 'assigned_user_id', 'id')->withTrashed(); } public function user() @@ -59,6 +59,4 @@ class Task extends BaseModel { return $this->belongsTo(Client::class); } - - } diff --git a/app/Models/TaxRate.php b/app/Models/TaxRate.php index 213b897fac3b..0831e600d781 100644 --- a/app/Models/TaxRate.php +++ b/app/Models/TaxRate.php @@ -19,9 +19,9 @@ class TaxRate extends BaseModel use MakesHash; protected $fillable = [ - 'name', + 'name', 'rate' - ]; + ]; protected $appends = ['tax_rate_id']; @@ -34,5 +34,4 @@ class TaxRate extends BaseModel { return $this->encodePrimaryKey($this->id); } - } diff --git a/app/Models/User.php b/app/Models/User.php index 63664e6da357..7dfccd521ba6 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -107,7 +107,7 @@ class User extends Authenticatable implements MustVerifyEmail /** * Returns a account. - * + * * @return Collection */ public function account() @@ -117,7 +117,7 @@ class User extends Authenticatable implements MustVerifyEmail /** * Returns all company tokens. - * + * * @return Collection */ public function tokens() @@ -127,7 +127,7 @@ class User extends Authenticatable implements MustVerifyEmail /** * Returns all companies a user has access to. - * + * * @return Collection */ public function companies() @@ -137,7 +137,7 @@ class User extends Authenticatable implements MustVerifyEmail /** * - * As we are authenticating on CompanyToken, + * As we are authenticating on CompanyToken, * we need to link the company to the user manually. This allows * us to decouple a $user and their attached companies. * @@ -157,9 +157,9 @@ class User extends Authenticatable implements MustVerifyEmail /** * Returns the current company - * + * * @return Collection - */ + */ public function company() { return $this->getCompany(); @@ -167,10 +167,9 @@ class User extends Authenticatable implements MustVerifyEmail private function setCompanyByGuard() { - - if(Auth::guard('contact')->check()) + if (Auth::guard('contact')->check()) { $this->setCompany(auth()->user()->client->company); - + } } public function company_users() @@ -180,22 +179,21 @@ class User extends Authenticatable implements MustVerifyEmail public function company_user() { - if(!$this->id) + if (!$this->id) { $this->id = auth()->user()->id; + } - return $this->hasOneThrough(CompanyUser::class, CompanyToken::class, 'user_id', 'company_id','id','company_id')->where('company_user.user_id', $this->id); + return $this->hasOneThrough(CompanyUser::class, CompanyToken::class, 'user_id', 'company_id', 'id', 'company_id')->where('company_user.user_id', $this->id); } /** * Returns the currently set company id for the user - * + * * @return int */ public function companyId() :int { - return $this->company()->id; - } public function clients() @@ -205,97 +203,81 @@ class User extends Authenticatable implements MustVerifyEmail /** * Returns a comma separated list of user permissions - * + * * @return comma separated list */ public function permissions() { - return $this->company_user->permissions; - } /** * Returns a object of User Settings - * + * * @return stdClass */ public function settings() { - return json_decode($this->company_user->settings); - } /** * Returns a boolean of the administrator status of the user - * + * * @return bool */ public function isAdmin() : bool { - return $this->company_user->is_admin; - } public function isOwner() : bool { - return $this->company_user->is_owner; - } /** * Returns all user created contacts - * + * * @return Collection */ public function contacts() { - return $this->hasMany(ClientContact::class); - } /** * Returns a boolean value if the user owns the current Entity - * + * * @param string Entity * @return bool */ public function owns($entity) : bool { - return ! empty($entity->user_id) && $entity->user_id == $this->id; - } /** * Returns a boolean value if the user is assigned to the current Entity - * + * * @param string Entity * @return bool */ public function assigned($entity) : bool { - return ! empty($entity->assigned_user_id) && $entity->assigned_user_id == $this->id; - } /** * Returns true if permissions exist in the map - * + * * @param string permission * @return boolean */ public function hasPermission($permission) : bool - { - + { return (stripos($this->company_user->permissions, $permission) !== false); - } public function documents() @@ -305,12 +287,11 @@ class User extends Authenticatable implements MustVerifyEmail public function getEmailVerifiedAt() { - - if($this->email_verified_at) + if ($this->email_verified_at) { return Carbon::parse($this->email_verified_at)->timestamp; - else + } else { return null; - + } } public function routeNotificationForSlack($notification) @@ -339,4 +320,3 @@ class User extends Authenticatable implements MustVerifyEmail ->where('id', $this->decodePrimaryKey($value))->firstOrFail(); } } - diff --git a/app/Notifications/ClientContactRequestCancellation.php b/app/Notifications/ClientContactRequestCancellation.php index 53c8fa2cd059..80b6b89dc1cb 100644 --- a/app/Notifications/ClientContactRequestCancellation.php +++ b/app/Notifications/ClientContactRequestCancellation.php @@ -72,7 +72,6 @@ class ClientContactRequestCancellation extends Notification implements ShouldQue ->markdown('email.support.cancellation', [ 'message' => "Contact [{$client_contact_name}] from Client [{$client_name}] requested to cancel Recurring Invoice [#{$recurring_invoice_number}]", ]); - } /** @@ -90,12 +89,11 @@ class ClientContactRequestCancellation extends Notification implements ShouldQue public function toSlack($notifiable) { + $name = $this->client_contact->present()->name(); + $client_name = $this->client_contact->client->present()->name(); + $recurring_invoice_number = $this->recurring_invoice->number; - $name = $this->client_contact->present()->name(); - $client_name = $this->client_contact->client->present()->name(); - $recurring_invoice_number = $this->recurring_invoice->number; - - return (new SlackMessage) + return (new SlackMessage) ->success() ->to("#devv2") ->from("System") diff --git a/app/Notifications/ClientContactResetPassword.php b/app/Notifications/ClientContactResetPassword.php index 9a005116aab1..72dec688d2f5 100644 --- a/app/Notifications/ClientContactResetPassword.php +++ b/app/Notifications/ClientContactResetPassword.php @@ -11,11 +11,11 @@ use Illuminate\Support\Facades\Lang; class ClientContactResetPassword extends Notification { use Queueable; - /** - * The password reset token. - * - * @var string - */ + /** + * The password reset token. + * + * @var string + */ public $token; /** diff --git a/app/Notifications/NewAccountCreated.php b/app/Notifications/NewAccountCreated.php index 7db995f8f5d7..d10818bfa645 100644 --- a/app/Notifications/NewAccountCreated.php +++ b/app/Notifications/NewAccountCreated.php @@ -68,17 +68,15 @@ class NewAccountCreated extends Notification implements ShouldQueue public function toSlack($notifiable) { + $user_name = $this->user->first_name . " " . $this->user->last_name; + $email = $this->user->email; + $ip = $this->user->ip; - $user_name = $this->user->first_name . " " . $this->user->last_name; - $email = $this->user->email; - $ip = $this->user->ip; - - return (new SlackMessage) + return (new SlackMessage) ->success() ->to("#devv2") ->from("System") ->image('https://app.invoiceninja.com/favicon.png') ->content("A new account has been created by {$user_name} - {$email} - from IP: {$ip}"); } - } diff --git a/app/Observers/UserObserver.php b/app/Observers/UserObserver.php index afffd4af9067..b0fe2b0877a1 100644 --- a/app/Observers/UserObserver.php +++ b/app/Observers/UserObserver.php @@ -35,7 +35,6 @@ class UserObserver */ public function updated(User $user) { - } /** diff --git a/app/PaymentDrivers/BasePaymentDriver.php b/app/PaymentDrivers/BasePaymentDriver.php index 13a0d2f23e74..c5479fa17a39 100644 --- a/app/PaymentDrivers/BasePaymentDriver.php +++ b/app/PaymentDrivers/BasePaymentDriver.php @@ -23,7 +23,6 @@ use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Auth; use Omnipay\Omnipay; - /** * Class BasePaymentDriver * @package App\PaymentDrivers @@ -44,66 +43,62 @@ use Omnipay\Omnipay; */ class BasePaymentDriver { - use SystemLogTrait; - - /* The company gateway instance*/ - protected $company_gateway; + use SystemLogTrait; + + /* The company gateway instance*/ + protected $company_gateway; - /* The Omnipay payment driver instance*/ - protected $gateway; + /* The Omnipay payment driver instance*/ + protected $gateway; - /* The Invitation */ - protected $invitation; + /* The Invitation */ + protected $invitation; - /* Gateway capabilities */ - protected $refundable = false; - - /* Token billing */ - protected $token_billing = false; + /* Gateway capabilities */ + protected $refundable = false; + + /* Token billing */ + protected $token_billing = false; - /* Authorise payment methods */ + /* Authorise payment methods */ protected $can_authorise_credit_card = false; public function __construct(CompanyGateway $company_gateway, Client $client, $invitation = false) { - $this->company_gateway = $company_gateway; $this->invitation = $invitation; $this->client = $client; - } - /** - * Returns the Omnipay driver - * @return object Omnipay initialized object - */ - protected function gateway() + /** + * Returns the Omnipay driver + * @return object Omnipay initialized object + */ + protected function gateway() { - $this->gateway = Omnipay::create($this->company_gateway->gateway->provider); $this->gateway->initialize((array) $this->company_gateway->getConfig()); return $this; - - } + } - /** - * Return the configuration fields for the - * Gatway - * @return array The configuration fields - */ - public function getFields() - { - return $this->gateway->getDefaultParameters(); - } + /** + * Return the configuration fields for the + * Gatway + * @return array The configuration fields + */ + public function getFields() + { + return $this->gateway->getDefaultParameters(); + } - /** - * Returns the default gateway type - */ - public function gatewayTypes() + /** + * Returns the default gateway type + */ + public function gatewayTypes() { return [ GatewayType::CREDIT_CARD, @@ -112,79 +107,89 @@ class BasePaymentDriver public function getCompanyGatewayId() :int { - return $this->company_gateway->id; + return $this->company_gateway->id; + } + /** + * Returns whether refunds are possible with the gateway + * @return boolean TRUE|FALSE + */ + public function getRefundable() :bool + { + return $this->refundable; } - /** - * Returns whether refunds are possible with the gateway - * @return boolean TRUE|FALSE - */ - public function getRefundable() :bool - { - return $this->refundable; - } - /** - * Returns whether token billing is possible with the gateway - * @return boolean TRUE|FALSE - */ - public function getTokenBilling() :bool - { - return $this->token_billing; - } + /** + * Returns whether token billing is possible with the gateway + * @return boolean TRUE|FALSE + */ + public function getTokenBilling() :bool + { + return $this->token_billing; + } - /** - * Returns whether gateway can - * authorise and credit card. - * @return [type] [description] - */ - public function canAuthoriseCreditCard() :bool - { - return $this->can_authorise_credit_card; - } + /** + * Returns whether gateway can + * authorise and credit card. + * @return [type] [description] + */ + public function canAuthoriseCreditCard() :bool + { + return $this->can_authorise_credit_card; + } - /** - * Refunds a given payment - * @return void - */ - public function refundPayment() {} + /** + * Refunds a given payment + * @return void + */ + public function refundPayment() + { + } - public function authorizeCreditCardView(array $data) {} + public function authorizeCreditCardView(array $data) + { + } - public function authorizeCreditCardResponse($request) {} + public function authorizeCreditCardResponse($request) + { + } - public function processPaymentView(array $data) {} - - public function processPaymentResponse($request) {} + public function processPaymentView(array $data) + { + } + + public function processPaymentResponse($request) + { + } - /** - * Return the contact if possible - * - * @return ClientContact The ClientContact object - */ - public function getContact() - { - if($this->invitation) - return ClientContact::find($this->invitation->client_contact_id); - elseif(auth()->guard('contact')->user()) - return auth()->user(); - else - return false; - } + /** + * Return the contact if possible + * + * @return ClientContact The ClientContact object + */ + public function getContact() + { + if ($this->invitation) { + return ClientContact::find($this->invitation->client_contact_id); + } elseif (auth()->guard('contact')->user()) { + return auth()->user(); + } else { + return false; + } + } - /************************************* Omnipay ****************************************** - authorize($options) - authorize an amount on the customer's card - completeAuthorize($options) - handle return from off-site gateways after authorization - capture($options) - capture an amount you have previously authorized - purchase($options) - authorize and immediately capture an amount on the customer's card - completePurchase($options) - handle return from off-site gateways after purchase - refund($options) - refund an already processed transaction - void($options) - generally can only be called up to 24 hours after submitting a transaction - acceptNotification() - convert an incoming request from an off-site gateway to a generic notification object for further processing - */ + /************************************* Omnipay ****************************************** + authorize($options) - authorize an amount on the customer's card + completeAuthorize($options) - handle return from off-site gateways after authorization + capture($options) - capture an amount you have previously authorized + purchase($options) - authorize and immediately capture an amount on the customer's card + completePurchase($options) - handle return from off-site gateways after purchase + refund($options) - refund an already processed transaction + void($options) - generally can only be called up to 24 hours after submitting a transaction + acceptNotification() - convert an incoming request from an off-site gateway to a generic notification object for further processing + */ protected function paymentDetails($input) : array { - $data = [ 'currency' => $this->client->getCurrencyCode(), 'transactionType' => 'Purchase', @@ -195,52 +200,50 @@ class BasePaymentDriver return $data; } - public function purchase($data, $items) - { - $this->gateway(); + public function purchase($data, $items) + { + $this->gateway(); - $response = $this->gateway - ->purchase($data) - ->setItems($items) - ->send(); + $response = $this->gateway + ->purchase($data) + ->setItems($items) + ->send(); - return $response; - /* - $this->purchaseResponse = (array)$response->getData();*/ - } + return $response; + /* + $this->purchaseResponse = (array)$response->getData();*/ + } - public function completePurchase($data) - { - $this->gateway(); + public function completePurchase($data) + { + $this->gateway(); - return $this->gateway - ->completePurchase($data) - ->send(); - } + return $this->gateway + ->completePurchase($data) + ->send(); + } - public function createPayment($data) : Payment - { + public function createPayment($data) : Payment + { + $payment = PaymentFactory::create($this->client->company->id, $this->client->user->id); + $payment->client_id = $this->client->id; + $payment->company_gateway_id = $this->company_gateway->id; + $payment->status_id = Payment::STATUS_COMPLETED; + $payment->date = Carbon::now(); + + return $payment; + } - $payment = PaymentFactory::create($this->client->company->id, $this->client->user->id); - $payment->client_id = $this->client->id; - $payment->company_gateway_id = $this->company_gateway->id; - $payment->status_id = Payment::STATUS_COMPLETED; - $payment->date = Carbon::now(); - - return $payment; - - } - - + public function attachInvoices(Payment $payment, $hashed_ids) : Payment { - $invoices = Invoice::whereIn('id', $this->transformKeys(explode(",",$hashed_ids))) + $invoices = Invoice::whereIn('id', $this->transformKeys(explode(",", $hashed_ids))) ->whereClientId($this->client->id) ->get(); - $payment->invoices()->sync($invoices); + $payment->invoices()->sync($invoices); $payment->save(); return $payment; - } -} \ No newline at end of file + } +} diff --git a/app/PaymentDrivers/PayPalExpressPaymentDriver.php b/app/PaymentDrivers/PayPalExpressPaymentDriver.php index 73b6f1fd73b1..f64f877a4d11 100644 --- a/app/PaymentDrivers/PayPalExpressPaymentDriver.php +++ b/app/PaymentDrivers/PayPalExpressPaymentDriver.php @@ -59,8 +59,7 @@ use Omnipay\Common\Item; class PayPalExpressPaymentDriver extends BasePaymentDriver { - - use MakesHash; + use MakesHash; protected $refundable = false; @@ -94,7 +93,6 @@ class PayPalExpressPaymentDriver extends BasePaymentDriver */ public function processPaymentView(array $data) { - $response = $this->purchase($this->paymentDetails($data), $this->paymentItems($data)); @@ -107,55 +105,51 @@ class PayPalExpressPaymentDriver extends BasePaymentDriver } else { // payment failed: display message to customer - SystemLogger::dispatch([ + SystemLogger::dispatch( + [ 'server_response' => $response->getData(), 'data' => $data ], - SystemLog::CATEGORY_GATEWAY_RESPONSE, - SystemLog::EVENT_GATEWAY_FAILURE, - SystemLog::TYPE_PAYPAL, - $this->client + SystemLog::CATEGORY_GATEWAY_RESPONSE, + SystemLog::EVENT_GATEWAY_FAILURE, + SystemLog::TYPE_PAYPAL, + $this->client ); throw new \Exception("Error Processing Payment", 1); - } } public function processPaymentResponse($request) { - $response = $this->completePurchase($request->all()); $transaction_reference = $response->getTransactionReference() ?: $request->input('token'); if ($response->isCancelled()) { - return redirect()->route('client.invoices.index')->with('warning',ctrans('texts.status_voided')); - } - elseif($response->isSuccessful()){ - - SystemLogger::dispatch([ + return redirect()->route('client.invoices.index')->with('warning', ctrans('texts.status_voided')); + } elseif ($response->isSuccessful()) { + SystemLogger::dispatch( + [ 'server_response' => $response->getData(), 'data' => $request->all() ], - SystemLog::CATEGORY_GATEWAY_RESPONSE, - SystemLog::EVENT_GATEWAY_SUCCESS, - SystemLog::TYPE_PAYPAL, - $this->client + SystemLog::CATEGORY_GATEWAY_RESPONSE, + SystemLog::EVENT_GATEWAY_SUCCESS, + SystemLog::TYPE_PAYPAL, + $this->client ); - } - elseif (! $response->isSuccessful()) { - - - SystemLogger::dispatch([ + } elseif (! $response->isSuccessful()) { + SystemLogger::dispatch( + [ 'data' => $request->all(), 'server_response' => $response->getData() ], - SystemLog::CATEGORY_GATEWAY_RESPONSE, - SystemLog::EVENT_GATEWAY_FAILURE, - SystemLog::TYPE_PAYPAL, - $this->client - ); + SystemLog::CATEGORY_GATEWAY_RESPONSE, + SystemLog::EVENT_GATEWAY_FAILURE, + SystemLog::TYPE_PAYPAL, + $this->client + ); throw new \Exception($response->getMessage()); } @@ -169,7 +163,6 @@ class PayPalExpressPaymentDriver extends BasePaymentDriver UpdateInvoicePayment::dispatchNow($payment, $payment->company); return redirect()->route('client.payments.show', ['payment'=>$this->encodePrimaryKey($payment->id)]); - } protected function paymentDetails($input) :array @@ -211,13 +204,11 @@ class PayPalExpressPaymentDriver extends BasePaymentDriver { $invoice_numbers = ""; - foreach($input['invoices'] as $invoice) - { + foreach ($input['invoices'] as $invoice) { $invoice_numbers .= $invoice->number." "; } return ctrans('texts.invoice_number'). ": {$invoice_numbers}"; - } private function buildTransactionId($input) : string @@ -227,14 +218,11 @@ class PayPalExpressPaymentDriver extends BasePaymentDriver private function paymentItems($input) : array { - $items = []; $total = 0; - foreach ($input['invoices'] as $invoice) - { - foreach($invoice->line_items as $invoiceItem) - { + foreach ($input['invoices'] as $invoice) { + foreach ($invoice->line_items as $invoiceItem) { // Some gateways require quantity is an integer if (floatval($invoiceItem->quantity) != intval($invoiceItem->quantity)) { return null; @@ -269,7 +257,6 @@ class PayPalExpressPaymentDriver extends BasePaymentDriver public function createPayment($data) : Payment { - $payment = parent::createPayment($data); $client_contact = $this->getContact(); @@ -282,6 +269,5 @@ class PayPalExpressPaymentDriver extends BasePaymentDriver $payment->save(); return $payment; - } } diff --git a/app/PaymentDrivers/StripePaymentDriver.php b/app/PaymentDrivers/StripePaymentDriver.php index 4457a9059dfd..b17a555897ec 100644 --- a/app/PaymentDrivers/StripePaymentDriver.php +++ b/app/PaymentDrivers/StripePaymentDriver.php @@ -30,41 +30,41 @@ use Stripe\Stripe; class StripePaymentDriver extends BasePaymentDriver { - use MakesHash; + use MakesHash; - protected $refundable = true; + protected $refundable = true; - protected $token_billing = true; + protected $token_billing = true; - protected $can_authorise_credit_card = true; + protected $can_authorise_credit_card = true; - protected $customer_reference = 'customerReferenceParam'; + protected $customer_reference = 'customerReferenceParam'; - /** - * Methods in this class are divided into - * two separate streams - * - * 1. Omnipay Specific - * 2. Stripe Specific - * - * Our Stripe integration is deeper than - * other gateways and therefore - * relies on direct calls to the API - */ - /************************************** Stripe API methods **********************************************************/ + /** + * Methods in this class are divided into + * two separate streams + * + * 1. Omnipay Specific + * 2. Stripe Specific + * + * Our Stripe integration is deeper than + * other gateways and therefore + * relies on direct calls to the API + */ + /************************************** Stripe API methods **********************************************************/ /** * Initializes the Stripe API * @return void */ - public function init() :void - { + public function init() :void + { Stripe::setApiKey($this->company_gateway->getConfigField('23_apiKey')); - } + } - /** - * Returns the gateway types - */ + /** + * Returns the gateway types + */ public function gatewayTypes() :array { $types = [ @@ -72,78 +72,81 @@ class StripePaymentDriver extends BasePaymentDriver //GatewayType::TOKEN, ]; - if($this->company_gateway->getSofortEnabled() && $this->invitation && $this->client() && isset($this->client()->country) && in_array($this->client()->country, ['AUT', 'BEL', 'DEU', 'ITA', 'NLD', 'ESP'])) + if ($this->company_gateway->getSofortEnabled() && $this->invitation && $this->client() && isset($this->client()->country) && in_array($this->client()->country, ['AUT', 'BEL', 'DEU', 'ITA', 'NLD', 'ESP'])) { $types[] = GatewayType::SOFORT; + } - if($this->company_gateway->getAchEnabled()) - $types[] = GatewayType::BANK_TRANSFER; + if ($this->company_gateway->getAchEnabled()) { + $types[] = GatewayType::BANK_TRANSFER; + } - if ($this->company_gateway->getSepaEnabled()) + if ($this->company_gateway->getSepaEnabled()) { $types[] = GatewayType::SEPA; + } - if ($this->company_gateway->getBitcoinEnabled()) + if ($this->company_gateway->getBitcoinEnabled()) { $types[] = GatewayType::CRYPTO; + } - if ($this->company_gateway->getAlipayEnabled()) + if ($this->company_gateway->getAlipayEnabled()) { $types[] = GatewayType::ALIPAY; + } - if ($this->company_gateway->getApplePayEnabled()) + if ($this->company_gateway->getApplePayEnabled()) { $types[] = GatewayType::APPLE_PAY; + } return $types; - } public function viewForType($gateway_type_id) { - switch ($gateway_type_id) { - case GatewayType::CREDIT_CARD: - return 'portal.default.gateways.stripe.credit_card'; - break; - case GatewayType::TOKEN: - return 'portal.default.gateways.stripe.credit_card'; - break; - case GatewayType::SOFORT: - return 'portal.default.gateways.stripe.sofort'; - break; - case GatewayType::BANK_TRANSFER: - return 'portal.default.gateways.stripe.ach'; - break; - case GatewayType::SEPA: - return 'portal.default.gateways.stripe.sepa'; - break; - case GatewayType::CRYPTO: - return 'portal.default.gateways.stripe.other'; - break; - case GatewayType::ALIPAY: - return 'portal.default.gateways.stripe.other'; - break; - case GatewayType::APPLE_PAY: - return 'portal.default.gateways.stripe.other'; - break; + switch ($gateway_type_id) { + case GatewayType::CREDIT_CARD: + return 'portal.default.gateways.stripe.credit_card'; + break; + case GatewayType::TOKEN: + return 'portal.default.gateways.stripe.credit_card'; + break; + case GatewayType::SOFORT: + return 'portal.default.gateways.stripe.sofort'; + break; + case GatewayType::BANK_TRANSFER: + return 'portal.default.gateways.stripe.ach'; + break; + case GatewayType::SEPA: + return 'portal.default.gateways.stripe.sepa'; + break; + case GatewayType::CRYPTO: + return 'portal.default.gateways.stripe.other'; + break; + case GatewayType::ALIPAY: + return 'portal.default.gateways.stripe.other'; + break; + case GatewayType::APPLE_PAY: + return 'portal.default.gateways.stripe.other'; + break; - default: - # code... - break; - } + default: + # code... + break; + } } /** - * + * * Authorises a credit card for future use * @param array $data Array of variables needed for the view - * + * * @return view The gateway specific partial to be rendered - * + * */ public function authorizeCreditCardView(array $data) { - $intent['intent'] = $this->getSetupIntent(); return view('portal.default.gateways.stripe.add_credit_card', array_merge($data, $intent)); - } /** @@ -153,7 +156,6 @@ class StripePaymentDriver extends BasePaymentDriver */ public function authorizeCreditCardResponse($request) { - $server_response = json_decode($request->input('gateway_response')); $gateway_id = $request->input('gateway_id'); @@ -171,7 +173,7 @@ class StripePaymentDriver extends BasePaymentDriver $payment_meta = new \stdClass; - if($stripe_payment_method_obj['type'] == 'card') { + if ($stripe_payment_method_obj['type'] == 'card') { $payment_meta->exp_month = $stripe_payment_method_obj['card']['exp_month']; $payment_meta->exp_year = $stripe_payment_method_obj['card']['exp_year']; $payment_meta->brand = $stripe_payment_method_obj['card']['brand']; @@ -189,8 +191,7 @@ class StripePaymentDriver extends BasePaymentDriver $cgt->meta = $payment_meta; $cgt->save(); - if($is_default == 'true' || $this->client->gateway_tokens->count() == 1) - { + if ($is_default == 'true' || $this->client->gateway_tokens->count() == 1) { $this->client->gateway_tokens()->update(['is_default'=>0]); $cgt->is_default = 1; @@ -202,7 +203,7 @@ class StripePaymentDriver extends BasePaymentDriver /** * Processes the payment with this gateway - * + * * @var invoices * @var amount * @var fee @@ -210,7 +211,7 @@ class StripePaymentDriver extends BasePaymentDriver * @var token * @var payment_method_id * @var hashed_ids - * + * * @param array $data variables required to build payment page * @return view Gateway and payment method specific view */ @@ -223,9 +224,9 @@ class StripePaymentDriver extends BasePaymentDriver 'description' => $data['invoices']->pluck('id'), //todo more meaningful description here: ]; - if($data['token']) + if ($data['token']) { $payment_intent_data['payment_method'] = $data['token']->token; - else{ + } else { $payment_intent_data['setup_future_usage'] = 'off_session'; // $payment_intent_data['save_payment_method'] = true; // $payment_intent_data['confirm'] = true; @@ -237,7 +238,6 @@ class StripePaymentDriver extends BasePaymentDriver $data['gateway'] = $this; return view($this->viewForType($data['payment_method_id']), $data); - } /** @@ -278,41 +278,39 @@ class StripePaymentDriver extends BasePaymentDriver $gateway_type_id = $request->input('payment_method_id'); $hashed_ids = $request->input('hashed_ids'); - $invoices = Invoice::whereIn('id', $this->transformKeys(explode(",",$hashed_ids))) + $invoices = Invoice::whereIn('id', $this->transformKeys(explode(",", $hashed_ids))) ->whereClientId($this->client->id) ->get(); /** * Potential statuses that can be returned - * + * * requires_action * processing * canceled * requires_action * requires_confirmation - * requires_payment_method - * + * requires_payment_method + * */ - if($this->getContact()){ - $client_contact = $this->getContact(); - } - else{ - $client_contact = $invoices->first()->invitations->first()->contact; + if ($this->getContact()) { + $client_contact = $this->getContact(); + } else { + $client_contact = $invoices->first()->invitations->first()->contact; } $this->init(); $payment_intent = \Stripe\PaymentIntent::retrieve($server_response->id); $customer = $payment_intent->customer; - if($payment_status == 'succeeded') - { + if ($payment_status == 'succeeded') { $this->init(); $stripe_payment_method = \Stripe\PaymentMethod::retrieve($payment_method); $stripe_payment_method_obj = $stripe_payment_method->jsonSerialize(); $payment_meta = new \stdClass; - if($stripe_payment_method_obj['type'] == 'card') { + if ($stripe_payment_method_obj['type'] == 'card') { $payment_meta->exp_month = $stripe_payment_method_obj['card']['exp_month']; $payment_meta->exp_year = $stripe_payment_method_obj['card']['exp_year']; $payment_meta->brand = $stripe_payment_method_obj['card']['brand']; @@ -322,9 +320,7 @@ class StripePaymentDriver extends BasePaymentDriver $payment_type = PaymentType::parseCardType($stripe_payment_method_obj['card']['brand']); } - if($save_card == 'true') - { - + if ($save_card == 'true') { $stripe_payment_method->attach(['customer' => $customer]); $cgt = new ClientGatewayToken; @@ -337,18 +333,18 @@ class StripePaymentDriver extends BasePaymentDriver $cgt->meta = $payment_meta; $cgt->save(); - if($this->client->gateway_tokens->count() == 1) - { + if ($this->client->gateway_tokens->count() == 1) { $this->client->gateway_tokens()->update(['is_default'=>0]); $cgt->is_default = 1; $cgt->save(); - } + } } //todo need to fix this to support payment types other than credit card.... sepa etc etc - if(!$payment_type) - $payment_type = PaymentType::CREDIT_CARD_OTHER; + if (!$payment_type) { + $payment_type = PaymentType::CREDIT_CARD_OTHER; + } $data = [ @@ -367,41 +363,37 @@ class StripePaymentDriver extends BasePaymentDriver UpdateInvoicePayment::dispatchNow($payment, $payment->company); - SystemLogger::dispatch([ + SystemLogger::dispatch( + [ 'server_response' => $payment_intent, 'data' => $data - ], - SystemLog::CATEGORY_GATEWAY_RESPONSE, - SystemLog::EVENT_GATEWAY_SUCCESS, - SystemLog::TYPE_STRIPE, - $this->client + ], + SystemLog::CATEGORY_GATEWAY_RESPONSE, + SystemLog::EVENT_GATEWAY_SUCCESS, + SystemLog::TYPE_STRIPE, + $this->client ); return redirect()->route('client.payments.show', ['payment' => $this->encodePrimaryKey($payment->id)]); - - } - else - { - /*Fail and log*/ - SystemLogger::dispatch([ + } else { + /*Fail and log*/ + SystemLogger::dispatch( + [ 'server_response' => $server_response, 'data' => $data - ], - SystemLog::CATEGORY_GATEWAY_RESPONSE, - SystemLog::EVENT_GATEWAY_FAILURE, - SystemLog::TYPE_STRIPE, - $this->client + ], + SystemLog::CATEGORY_GATEWAY_RESPONSE, + SystemLog::EVENT_GATEWAY_FAILURE, + SystemLog::TYPE_STRIPE, + $this->client ); - throw new \Exception("Failed to process payment", 1); - + throw new \Exception("Failed to process payment", 1); } - } public function createPayment($data) :Payment { - $payment = parent::createPayment($data); $client_contact = $this->getContact(); @@ -414,46 +406,41 @@ class StripePaymentDriver extends BasePaymentDriver $payment->save(); return $payment; - } private function convertFromStripeAmount($amount, $precision) { - return $amount / pow(10, $precision); + return $amount / pow(10, $precision); } private function convertToStripeAmount($amount, $precision) { - return $amount * pow(10, $precision); + return $amount * pow(10, $precision); } /** * Creates a new String Payment Intent - * + * * @param array $data The data array to be passed to Stripe * @return PaymentIntent The Stripe payment intent object */ public function createPaymentIntent($data) :?\Stripe\PaymentIntent { - $this->init(); return PaymentIntent::create($data); - } /** - * Returns a setup intent that allows the user + * Returns a setup intent that allows the user * to enter card details without initiating a transaction. * * @return \Stripe\SetupIntent */ public function getSetupIntent() :\Stripe\SetupIntent { - $this->init(); return SetupIntent::create(); - } @@ -463,55 +450,42 @@ class StripePaymentDriver extends BasePaymentDriver */ public function getPublishableKey() :?string { - return $this->company_gateway->getPublishableKey(); - } /** * Finds or creates a Stripe Customer object - * + * * @return NULL|\Stripe\Customer A Stripe customer object */ public function findOrCreateCustomer() :?\Stripe\Customer - { - + { $customer = null; $this->init(); $client_gateway_token = ClientGatewayToken::whereClientId($this->client->id)->whereCompanyGatewayId($this->company_gateway->id)->first(); - if($client_gateway_token && $client_gateway_token->gateway_customer_reference){ - + if ($client_gateway_token && $client_gateway_token->gateway_customer_reference) { $customer = \Stripe\Customer::retrieve($client_gateway_token->gateway_customer_reference); - - } - else{ - + } else { $data['name'] = $this->client->present()->name(); $data['phone'] = $this->client->present()->phone(); - if(filter_var($this->client->present()->email(), FILTER_VALIDATE_EMAIL)) + if (filter_var($this->client->present()->email(), FILTER_VALIDATE_EMAIL)) { $data['email'] = $this->client->present()->email(); + } $customer = \Stripe\Customer::create($data); - } - if(!$customer) + if (!$customer) { throw new \Exception('Unable to create gateway customer'); + } return $customer; } - /************************************** Omnipay API methods **********************************************************/ - - - - - - - -} \ No newline at end of file + /************************************** Omnipay API methods **********************************************************/ +} diff --git a/app/Policies/ActivityPolicy.php b/app/Policies/ActivityPolicy.php index b535a76d9987..d449ab9e67bf 100644 --- a/app/Policies/ActivityPolicy.php +++ b/app/Policies/ActivityPolicy.php @@ -19,6 +19,4 @@ use App\Models\User; */ class ActivityPolicy extends EntityPolicy { - - } diff --git a/app/Policies/ClientPolicy.php b/app/Policies/ClientPolicy.php index afe6d9ca4aff..20f47f8c665d 100644 --- a/app/Policies/ClientPolicy.php +++ b/app/Policies/ClientPolicy.php @@ -20,15 +20,14 @@ use App\Models\User; */ class ClientPolicy extends EntityPolicy { - /** - * Checks if the user has create permissions - * - * @param User $user - * @return bool - */ - public function create(User $user) : bool - { - return $user->isAdmin() || $user->hasPermission('create_client') || $user->hasPermission('create_all'); - } - + /** + * Checks if the user has create permissions + * + * @param User $user + * @return bool + */ + public function create(User $user) : bool + { + return $user->isAdmin() || $user->hasPermission('create_client') || $user->hasPermission('create_all'); + } } diff --git a/app/Policies/CompanyGatewayPolicy.php b/app/Policies/CompanyGatewayPolicy.php index 317c652e87e2..1f4f24b29a1b 100644 --- a/app/Policies/CompanyGatewayPolicy.php +++ b/app/Policies/CompanyGatewayPolicy.php @@ -20,15 +20,14 @@ use App\Models\User; */ class CompanyGatewayPolicy extends EntityPolicy { - /** - * Checks if the user has create permissions - * - * @param User $user - * @return bool - */ - public function create(User $user) : bool - { - return $user->isAdmin(); - } - + /** + * Checks if the user has create permissions + * + * @param User $user + * @return bool + */ + public function create(User $user) : bool + { + return $user->isAdmin(); + } } diff --git a/app/Policies/CompanyPolicy.php b/app/Policies/CompanyPolicy.php index 5a27f24cf347..27266b1c3cd8 100644 --- a/app/Policies/CompanyPolicy.php +++ b/app/Policies/CompanyPolicy.php @@ -21,53 +21,48 @@ use Illuminate\Support\Facades\Log; */ class CompanyPolicy extends EntityPolicy { - /** - * Checks if the user has create permissions - * - * @param User $user - * @return bool - */ - public function create(User $user) : bool - { + /** + * Checks if the user has create permissions + * + * @param User $user + * @return bool + */ + public function create(User $user) : bool + { + return $user->isAdmin() || $user->hasPermission('create_company') || $user->hasPermission('create_all'); + } - return $user->isAdmin() || $user->hasPermission('create_company') || $user->hasPermission('create_all'); - - } - - /** - * Checks if the user has view permissions - * - * We MUST also check that the user can both view a entity and also check the entity belongs to the users company!!!!!! - * @param User $user - * @param $entity - * @return bool - */ - public function view(User $user, $entity) : bool - { - - return ($user->isAdmin() && $entity->id == $user->companyId()) - || ($user->hasPermission('view_' . strtolower(class_basename($entity))) && $entity->id == $user->companyId()) - || ($user->hasPermission('view_all') && $entity->id == $user->companyId()) - || $user->owns($entity); - } + /** + * Checks if the user has view permissions + * + * We MUST also check that the user can both view a entity and also check the entity belongs to the users company!!!!!! + * @param User $user + * @param $entity + * @return bool + */ + public function view(User $user, $entity) : bool + { + return ($user->isAdmin() && $entity->id == $user->companyId()) + || ($user->hasPermission('view_' . strtolower(class_basename($entity))) && $entity->id == $user->companyId()) + || ($user->hasPermission('view_all') && $entity->id == $user->companyId()) + || $user->owns($entity); + } - /** - * Checks if the user has edit permissions - * - * We MUST also check that the user can both edit a entity and also check the entity belongs to the users company!!!!!! - * - * @param User $user - * @param $entity - * @return bool - */ - public function edit(User $user, $entity) : bool - { - - return ($user->isAdmin() && $entity->id == $user->companyId()) - || ($user->hasPermission('edit_' . strtolower(class_basename($entity))) && $entity->id == $user->companyId()) - || ($user->hasPermission('edit_all') && $entity->id == $user->companyId()) - || $user->owns($entity); - - } + /** + * Checks if the user has edit permissions + * + * We MUST also check that the user can both edit a entity and also check the entity belongs to the users company!!!!!! + * + * @param User $user + * @param $entity + * @return bool + */ + public function edit(User $user, $entity) : bool + { + return ($user->isAdmin() && $entity->id == $user->companyId()) + || ($user->hasPermission('edit_' . strtolower(class_basename($entity))) && $entity->id == $user->companyId()) + || ($user->hasPermission('edit_all') && $entity->id == $user->companyId()) + || $user->owns($entity); + } } diff --git a/app/Policies/EntityPolicy.php b/app/Policies/EntityPolicy.php index 4d3f1f0ebd75..9325a422f884 100644 --- a/app/Policies/EntityPolicy.php +++ b/app/Policies/EntityPolicy.php @@ -19,61 +19,56 @@ use App\Models\User; */ class EntityPolicy { - /** - * Fires before any of the custom policy methods - * - * Only fires if true, if false we continue..... - * - * Do not use this function!!!! We MUST also check company_id, - * - * @param User $user - * @param $ability - * @return bool/void - */ - public function before($user, $ability) - { - //if($user->isAdmin()) - // return true; - } + /** + * Fires before any of the custom policy methods + * + * Only fires if true, if false we continue..... + * + * Do not use this function!!!! We MUST also check company_id, + * + * @param User $user + * @param $ability + * @return bool/void + */ + public function before($user, $ability) + { + //if($user->isAdmin()) + // return true; + } - /** - * Checks if the user has edit permissions - * - * We MUST also check that the user can both edit a entity and also check the entity belongs to the users company!!!!!! - * - * @param User $user - * @param $entity - * @return bool - */ - public function edit(User $user, $entity) : bool - { - - return ($user->isAdmin() && $entity->company_id == $user->companyId()) - || ($user->hasPermission('edit_' . strtolower(class_basename($entity))) && $entity->company_id == $user->companyId()) - || ($user->hasPermission('edit_all') && $entity->company_id == $user->companyId()) - || $user->owns($entity) - || $user->assigned($entity); - - } - - - /** - * Checks if the user has view permissions - * - * We MUST also check that the user can both view a entity and also check the entity belongs to the users company!!!!!! - * @param User $user - * @param $entity - * @return bool - */ - public function view(User $user, $entity) : bool - { - - return ($user->isAdmin() && $entity->company_id == $user->companyId()) - || ($user->hasPermission('view_' . strtolower(class_basename($entity))) && $entity->company_id == $user->companyId()) - || ($user->hasPermission('view_all') && $entity->company_id == $user->companyId()) - || $user->owns($entity) - || $user->assigned($entity); - } + /** + * Checks if the user has edit permissions + * + * We MUST also check that the user can both edit a entity and also check the entity belongs to the users company!!!!!! + * + * @param User $user + * @param $entity + * @return bool + */ + public function edit(User $user, $entity) : bool + { + return ($user->isAdmin() && $entity->company_id == $user->companyId()) + || ($user->hasPermission('edit_' . strtolower(class_basename($entity))) && $entity->company_id == $user->companyId()) + || ($user->hasPermission('edit_all') && $entity->company_id == $user->companyId()) + || $user->owns($entity) + || $user->assigned($entity); + } + /** + * Checks if the user has view permissions + * + * We MUST also check that the user can both view a entity and also check the entity belongs to the users company!!!!!! + * @param User $user + * @param $entity + * @return bool + */ + public function view(User $user, $entity) : bool + { + return ($user->isAdmin() && $entity->company_id == $user->companyId()) + || ($user->hasPermission('view_' . strtolower(class_basename($entity))) && $entity->company_id == $user->companyId()) + || ($user->hasPermission('view_all') && $entity->company_id == $user->companyId()) + || $user->owns($entity) + || $user->assigned($entity); + } } diff --git a/app/Policies/GroupSettingPolicy.php b/app/Policies/GroupSettingPolicy.php index e314eb4eecf1..82f41f1b588f 100644 --- a/app/Policies/GroupSettingPolicy.php +++ b/app/Policies/GroupSettingPolicy.php @@ -19,15 +19,14 @@ use App\Models\User; */ class GroupSettingPolicy extends EntityPolicy { - /** - * Checks if the user has create permissions - * - * @param User $user - * @return bool - */ - public function create(User $user) : bool - { - return $user->isAdmin(); - } - + /** + * Checks if the user has create permissions + * + * @param User $user + * @return bool + */ + public function create(User $user) : bool + { + return $user->isAdmin(); + } } diff --git a/app/Policies/InvoicePolicy.php b/app/Policies/InvoicePolicy.php index 38fd88f6e088..92677b932dad 100644 --- a/app/Policies/InvoicePolicy.php +++ b/app/Policies/InvoicePolicy.php @@ -20,15 +20,14 @@ use App\Models\User; */ class InvoicePolicy extends EntityPolicy { - /** - * Checks if the user has create permissions - * - * @param User $user - * @return bool - */ - public function create(User $user) : bool - { - return $user->isAdmin() || $user->hasPermission('create_invoice') || $user->hasPermission('create_all'); - } - + /** + * Checks if the user has create permissions + * + * @param User $user + * @return bool + */ + public function create(User $user) : bool + { + return $user->isAdmin() || $user->hasPermission('create_invoice') || $user->hasPermission('create_all'); + } } diff --git a/app/Policies/PaymentPolicy.php b/app/Policies/PaymentPolicy.php index 29bdad12e4f9..220170d2d4f8 100644 --- a/app/Policies/PaymentPolicy.php +++ b/app/Policies/PaymentPolicy.php @@ -20,15 +20,14 @@ use App\Models\User; */ class PaymentPolicy extends EntityPolicy { - /** - * Checks if the user has create permissions - * - * @param User $user - * @return bool - */ - public function create(User $user) : bool - { - return $user->isAdmin() || $user->hasPermission('create_payment') || $user->hasPermission('create_all'); - } - + /** + * Checks if the user has create permissions + * + * @param User $user + * @return bool + */ + public function create(User $user) : bool + { + return $user->isAdmin() || $user->hasPermission('create_payment') || $user->hasPermission('create_all'); + } } diff --git a/app/Policies/ProductPolicy.php b/app/Policies/ProductPolicy.php index f7c81037fe6a..9e61130fc071 100644 --- a/app/Policies/ProductPolicy.php +++ b/app/Policies/ProductPolicy.php @@ -30,7 +30,7 @@ class ProductPolicy extends EntityPolicy /** * Checks if the user has create permissions - * + * * @param User $user * @return bool */ @@ -38,5 +38,4 @@ class ProductPolicy extends EntityPolicy { return $user->isAdmin() || $user->hasPermission('create_product') || $user->hasPermission('create_all'); } - } diff --git a/app/Policies/QuotePolicy.php b/app/Policies/QuotePolicy.php index 0761b029c98c..5b09bb91e99b 100644 --- a/app/Policies/QuotePolicy.php +++ b/app/Policies/QuotePolicy.php @@ -20,15 +20,14 @@ use App\Models\User; */ class QuotePolicy extends EntityPolicy { - /** - * Checks if the user has create permissions - * - * @param User $user - * @return bool - */ - public function create(User $user) : bool - { - return $user->isAdmin() || $user->hasPermission('create_quote') || $user->hasPermission('create_all'); - } - + /** + * Checks if the user has create permissions + * + * @param User $user + * @return bool + */ + public function create(User $user) : bool + { + return $user->isAdmin() || $user->hasPermission('create_quote') || $user->hasPermission('create_all'); + } } diff --git a/app/Policies/RecurringInvoicePolicy.php b/app/Policies/RecurringInvoicePolicy.php index e79eb9668ca9..04679e2dc4d8 100644 --- a/app/Policies/RecurringInvoicePolicy.php +++ b/app/Policies/RecurringInvoicePolicy.php @@ -20,15 +20,14 @@ use App\Models\User; */ class RecurringInvoicePolicy extends EntityPolicy { - /** - * Checks if the user has create permissions - * - * @param User $user - * @return bool - */ - public function create(User $user) : bool - { - return $user->isAdmin() || $user->hasPermission('create_recurring_invoice') || $user->hasPermission('create_all'); - } - + /** + * Checks if the user has create permissions + * + * @param User $user + * @return bool + */ + public function create(User $user) : bool + { + return $user->isAdmin() || $user->hasPermission('create_recurring_invoice') || $user->hasPermission('create_all'); + } } diff --git a/app/Policies/RecurringQuotePolicy.php b/app/Policies/RecurringQuotePolicy.php index ad8dfcde368e..a0afdadfb731 100644 --- a/app/Policies/RecurringQuotePolicy.php +++ b/app/Policies/RecurringQuotePolicy.php @@ -20,15 +20,14 @@ use App\Models\User; */ class RecurringQuotePolicy extends EntityPolicy { - /** - * Checks if the user has create permissions - * - * @param User $user - * @return bool - */ - public function create(User $user) : bool - { - return $user->isAdmin() || $user->hasPermission('create_recurring_quote') || $user->hasPermission('create_all'); - } - + /** + * Checks if the user has create permissions + * + * @param User $user + * @return bool + */ + public function create(User $user) : bool + { + return $user->isAdmin() || $user->hasPermission('create_recurring_quote') || $user->hasPermission('create_all'); + } } diff --git a/app/Policies/TaxRatePolicy.php b/app/Policies/TaxRatePolicy.php index d09a8fb6cd9a..2ad96dc4f4a7 100644 --- a/app/Policies/TaxRatePolicy.php +++ b/app/Policies/TaxRatePolicy.php @@ -19,12 +19,8 @@ use App\Models\TaxRate; */ class TaxRatePolicy extends EntityPolicy { - - public function create(User $user) : bool - { - - return $user->isAdmin(); - - } - + public function create(User $user) : bool + { + return $user->isAdmin(); + } } diff --git a/app/Policies/UserPolicy.php b/app/Policies/UserPolicy.php index f3bafd70e533..cac7cd89f422 100644 --- a/app/Policies/UserPolicy.php +++ b/app/Policies/UserPolicy.php @@ -21,32 +21,28 @@ use App\Models\User; */ class UserPolicy extends EntityPolicy { - /** - * Checks if the user has create permissions - * - * @param User $user - * @return bool - */ - public function create(User $user) : bool - { - - return $user->isAdmin() || $user->hasPermission('create_user') || $user->hasPermission('create_all'); - - } + /** + * Checks if the user has create permissions + * + * @param User $user + * @return bool + */ + public function create(User $user) : bool + { + return $user->isAdmin() || $user->hasPermission('create_user') || $user->hasPermission('create_all'); + } - /* - * - * We need to override as User does not have the company_id property!!!!! - * - * We use the CompanyUser table as a proxy - */ - public function edit(User $user, $user_entity) : bool - { - $company_user = CompanyUser::whereUserId($user_entity->id)->company()->first(); - - return ($user->isAdmin() && $company_user); - - } + /* + * + * We need to override as User does not have the company_id property!!!!! + * + * We use the CompanyUser table as a proxy + */ + public function edit(User $user, $user_entity) : bool + { + $company_user = CompanyUser::whereUserId($user_entity->id)->company()->first(); + return ($user->isAdmin() && $company_user); + } } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 0f7819774516..db56172bdfb6 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -54,7 +54,7 @@ class AppServiceProvider extends ServiceProvider 'proposals' => '\App\Models\Proposal', ]); - Blade::if('env', function($environment){ + Blade::if('env', function ($environment) { return config('ninja.environment') === $environment; }); @@ -72,7 +72,6 @@ class AppServiceProvider extends ServiceProvider Proposal::observe(ProposalObserver::class); Quote::observe(QuoteObserver::class); Task::observe(TaskObserver::class); - } /** diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index ef867e34a0b3..4102fe0db83f 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -73,24 +73,20 @@ class AuthServiceProvider extends ServiceProvider public function boot() { $this->registerPolicies(); -/* - Auth::provider('users', function ($app, array $config) { - return new MultiDatabaseUserProvider($this->app['hash'], $config['model']); - }); - - Auth::provider('contacts', function ($app, array $config) { - return new MultiDatabaseUserProvider($this->app['hash'], $config['model']); - - }); -*/ + /* + Auth::provider('users', function ($app, array $config) { + return new MultiDatabaseUserProvider($this->app['hash'], $config['model']); + }); + + Auth::provider('contacts', function ($app, array $config) { + return new MultiDatabaseUserProvider($this->app['hash'], $config['model']); + + }); + */ Gate::define('view-list', function ($user, $entity) { - $entity = strtolower(class_basename($entity)); - return $user->hasPermission('view_' . $entity) || $user->isAdmin(); - + return $user->hasPermission('view_' . $entity) || $user->isAdmin(); }); - } - } diff --git a/app/Providers/ComposerServiceProvider.php b/app/Providers/ComposerServiceProvider.php index 711c1d555dd3..669d518a4b61 100644 --- a/app/Providers/ComposerServiceProvider.php +++ b/app/Providers/ComposerServiceProvider.php @@ -22,7 +22,6 @@ class ComposerServiceProvider extends ServiceProvider */ public function boot() { - view()->composer('portal.*', 'App\Http\ViewComposers\PortalComposer'); //view()->composer('*', 'App\Http\ViewComposers\HeaderComposer'); @@ -34,7 +33,6 @@ class ComposerServiceProvider extends ServiceProvider 'App\Http\ViewComposers\TranslationComposer' ); */ - } /** diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index de7bc12fb648..3c066cac771f 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -125,8 +125,6 @@ class EventServiceProvider extends ServiceProvider */ public function boot() { - parent::boot(); - } } diff --git a/app/Providers/MailServiceProvider.php b/app/Providers/MailServiceProvider.php index 0dde7863d433..30c8253b7e6b 100644 --- a/app/Providers/MailServiceProvider.php +++ b/app/Providers/MailServiceProvider.php @@ -1,4 +1,4 @@ -hasher->check($plain, $user->getAuthPassword()); @@ -224,43 +222,37 @@ class MultiDatabaseUserProvider implements UserProvider */ private function setDefaultDatabase($id = false, $email = false, $token = false) : void { - foreach (MultiDB::getDbs() as $database) { - $this->setDB($database); /** Make sure we hook into the correct guard class */ $query = $this->conn->table((new $this->model)->getTable()); - if ($id) + if ($id) { $query->where('id', '=', $id); + } - if ($email) + if ($email) { $query->where('email', '=', $email); + } $user = $query->get(); - if (count($user) >= 1) - { + if (count($user) >= 1) { break; } $query = $this->conn->table('company_tokens'); - if ($token) - { - + if ($token) { $query->whereRaw("BINARY `token`= ?", $token); $token = $query->get(); - if (count($token) >= 1) - { + if (count($token) >= 1) { break; } - } - } } @@ -277,7 +269,5 @@ class MultiDatabaseUserProvider implements UserProvider /* Set the connection to complete the user authentication */ $this->conn = app('db')->connection(config('database.connections.database.'.$database)); - } - } diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index 324b870a2598..4285a6056bab 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -39,7 +39,7 @@ class RouteServiceProvider extends ServiceProvider */ public function boot() { - // + // parent::boot(); } @@ -88,13 +88,13 @@ class RouteServiceProvider extends ServiceProvider ->group(base_path('routes/api.php')); } - /** - * Define the "api" routes for the application. - * - * These routes are typically stateless. - * - * @return void - */ + /** + * Define the "api" routes for the application. + * + * These routes are typically stateless. + * + * @return void + */ protected function mapContactApiRoutes() { Route::prefix('') @@ -117,5 +117,4 @@ class RouteServiceProvider extends ServiceProvider ->namespace($this->namespace) ->group(base_path('routes/client.php')); } - } diff --git a/app/Repositories/AccountRepository.php b/app/Repositories/AccountRepository.php index a4bf78d4ed05..e307c3f9cf4c 100644 --- a/app/Repositories/AccountRepository.php +++ b/app/Repositories/AccountRepository.php @@ -13,5 +13,4 @@ namespace App\Repositories; class AccountRepository { - -} \ No newline at end of file +} diff --git a/app/Repositories/ActivityRepository.php b/app/Repositories/ActivityRepository.php index 3a0ef9b2688d..77cf6f6b1908 100644 --- a/app/Repositories/ActivityRepository.php +++ b/app/Repositories/ActivityRepository.php @@ -23,59 +23,59 @@ use Illuminate\Support\Facades\Log; */ class ActivityRepository extends BaseRepository { - use MakesInvoiceHtml; - /** - * Save the Activity - * - * @param stdClass $fields The fields - * @param Collection $entity The entity that you wish to have backed up (typically Invoice, Quote etc etc rather than Payment) - */ - public function save($fields, $entity) - { - $activity = new Activity(); + use MakesInvoiceHtml; + /** + * Save the Activity + * + * @param stdClass $fields The fields + * @param Collection $entity The entity that you wish to have backed up (typically Invoice, Quote etc etc rather than Payment) + */ + public function save($fields, $entity) + { + $activity = new Activity(); - $activity->is_system = app()->runningInConsole(); + $activity->is_system = app()->runningInConsole(); $activity->ip = request()->getClientIp(); - foreach($fields as $key => $value) { - - $activity->{$key} = $value; + foreach ($fields as $key => $value) { + $activity->{$key} = $value; } - $activity->save(); + $activity->save(); - $this->createBackup($entity, $activity); - } + $this->createBackup($entity, $activity); + } - /** - * Creates a backup. - * - * @param Collection $entity The entity - * @param Collection $activity The activity - */ - public function createBackup($entity, $activity) - { - $backup = new Backup(); + /** + * Creates a backup. + * + * @param Collection $entity The entity + * @param Collection $activity The activity + */ + public function createBackup($entity, $activity) + { + $backup = new Backup(); - // if(get_class($entity) == Client::class) - // $settings = $entity->getMergedSettings(); - // else - // $settings = $entity->client->getMergedSettings(); -// $entity->clientMergedDettings = $settings; + // if(get_class($entity) == Client::class) + // $settings = $entity->getMergedSettings(); + // else + // $settings = $entity->client->getMergedSettings(); + // $entity->clientMergedDettings = $settings; - if(get_class($entity) == Client::class) - $entity->load('company'); - else - $entity->load('company','client'); + if (get_class($entity) == Client::class) { + $entity->load('company'); + } else { + $entity->load('company', 'client'); + } - if(get_class($entity) == Invoice::class && ($activity->activity_type_id == Activity::MARK_SENT_INVOICE || $activity->activity_type_id == Activity::PAID_INVOICE)) - $backup->html_backup = $this->generateInvoiceHtml($entity->design(), $entity); + if (get_class($entity) == Invoice::class && ($activity->activity_type_id == Activity::MARK_SENT_INVOICE || $activity->activity_type_id == Activity::PAID_INVOICE)) { + $backup->html_backup = $this->generateInvoiceHtml($entity->design(), $entity); + } - $backup->activity_id = $activity->id; - $backup->json_backup = $entity->toJson(); - $backup->save(); - } - -} \ No newline at end of file + $backup->activity_id = $activity->id; + $backup->json_backup = $entity->toJson(); + $backup->save(); + } +} diff --git a/app/Repositories/BaseRepository.php b/app/Repositories/BaseRepository.php index 6fd550c3f9ff..ac0e0b659ad5 100644 --- a/app/Repositories/BaseRepository.php +++ b/app/Repositories/BaseRepository.php @@ -15,9 +15,9 @@ use App\Models\Client; use App\Utils\Traits\MakesHash; /** - * + * */ -class BaseRepository +class BaseRepository { use MakesHash; /** @@ -54,16 +54,17 @@ class BaseRepository */ public function archive($entity) { - if ($entity->trashed()) + if ($entity->trashed()) { return; + } $entity->delete(); $className = $this->getEventClass($entity, 'Archived'); - if (class_exists($className)) + if (class_exists($className)) { event(new $className($entity)); - + } } /** @@ -87,9 +88,9 @@ class BaseRepository $className = $this->getEventClass($entity, 'Restored'); - if (class_exists($className)) + if (class_exists($className)) { event(new $className($entity, $fromDeleted)); - + } } /** @@ -156,6 +157,5 @@ class BaseRepository public function findByPublicIdsWithTrashed($ids) { return $this->getInstance()->scope($ids)->withTrashed()->get(); - } - -} \ No newline at end of file + } +} diff --git a/app/Repositories/ClientContactRepository.php b/app/Repositories/ClientContactRepository.php index e4233522dd9f..d859e48a7687 100644 --- a/app/Repositories/ClientContactRepository.php +++ b/app/Repositories/ClientContactRepository.php @@ -20,66 +20,57 @@ use Illuminate\Support\Str; */ class ClientContactRepository extends BaseRepository { + public function save($contacts, Client $client) : void + { - public function save($contacts, Client $client) : void - { + /* Convert array to collection */ + $contacts = collect($contacts); - /* Convert array to collection */ - $contacts = collect($contacts); + /* Get array of IDs which have been removed from the contacts array and soft delete each contact */ + collect($client->contacts->pluck('id'))->diff($contacts->pluck('id'))->each(function ($contact) { + ClientContact::destroy($contact); + }); - /* Get array of IDs which have been removed from the contacts array and soft delete each contact */ - collect($client->contacts->pluck('id'))->diff($contacts->pluck('id'))->each(function($contact){ + $this->is_primary = true; + /* Set first record to primary - always */ + $contacts = $contacts->sortByDesc('is_primary')->map(function ($contact) { + $contact['is_primary'] = $this->is_primary; + $this->is_primary = false; + return $contact; + }); - ClientContact::destroy($contact); + //loop and update/create contacts + $contacts->each(function ($contact) use ($client) { + $update_contact = null; - }); + if (isset($contact['id'])) { + $update_contact = ClientContact::find($this->decodePrimaryKey($contact['id'])); + } - $this->is_primary = true; - /* Set first record to primary - always */ - $contacts = $contacts->sortByDesc('is_primary')->map(function ($contact){ - $contact['is_primary'] = $this->is_primary; - $this->is_primary = false; - return $contact; - }); + if (!$update_contact) { + $update_contact = new ClientContact; + $update_contact->client_id = $client->id; + $update_contact->company_id = $client->company_id; + $update_contact->user_id = $client->user_id; + $update_contact->contact_key = Str::random(40); + } - //loop and update/create contacts - $contacts->each(function ($contact) use ($client){ - - $update_contact = null; + $update_contact->fill($contact); - if(isset($contact['id'])) - $update_contact = ClientContact::find($this->decodePrimaryKey($contact['id'])); - - if(!$update_contact){ - - $update_contact = new ClientContact; - $update_contact->client_id = $client->id; - $update_contact->company_id = $client->company_id; - $update_contact->user_id = $client->user_id; - $update_contact->contact_key = Str::random(40); - } - - $update_contact->fill($contact); - - $update_contact->save(); - }); + $update_contact->save(); + }); - //always made sure we have one blank contact to maintain state - if($contacts->count() == 0) - { - - $new_contact = new ClientContact; - $new_contact->client_id = $client->id; - $new_contact->company_id = $client->company_id; - $new_contact->user_id = $client->user_id; - $new_contact->contact_key = Str::random(40); - $new_contact->is_primary = true; - $new_contact->save(); - - } - - } - -} \ No newline at end of file + //always made sure we have one blank contact to maintain state + if ($contacts->count() == 0) { + $new_contact = new ClientContact; + $new_contact->client_id = $client->id; + $new_contact->company_id = $client->company_id; + $new_contact->user_id = $client->user_id; + $new_contact->contact_key = Str::random(40); + $new_contact->is_primary = true; + $new_contact->save(); + } + } +} diff --git a/app/Repositories/ClientRepository.php b/app/Repositories/ClientRepository.php index 06d28231596d..fff0f02adb7f 100644 --- a/app/Repositories/ClientRepository.php +++ b/app/Repositories/ClientRepository.php @@ -34,9 +34,7 @@ class ClientRepository extends BaseRepository */ public function __construct(ClientContactRepository $contact_repo) { - $this->contact_repo = $contact_repo; - } /** @@ -46,12 +44,10 @@ class ClientRepository extends BaseRepository */ public function getClassName() { - return Client::class; - } - /** + /** * Saves the client and its contacts * * @param array $data The data @@ -60,26 +56,28 @@ class ClientRepository extends BaseRepository * @return Client|\App\Models\Client|null Client Object */ public function save(array $data, Client $client) : ?Client - { + { $client->fill($data); $client->save(); - if($client->id_number == "" || !$client->id_number) - $client->id_number = $this->getNextClientNumber($client); //todo write tests for this and make sure that custom client numbers also works as expected from here + if ($client->id_number == "" || !$client->id_number) { + $client->id_number = $this->getNextClientNumber($client); + } //todo write tests for this and make sure that custom client numbers also works as expected from here $client->save(); - if(isset($data['contacts'])) + if (isset($data['contacts'])) { $contacts = $this->contact_repo->save($data['contacts'], $client); + } - if(empty($data['name'])) + if (empty($data['name'])) { $data['name'] = $client->present()->name(); + } return $client; - - } + } /** * Store clients in bulk. @@ -87,11 +85,11 @@ class ClientRepository extends BaseRepository * @param array $client * @return Client|null */ - public function create($client): ?Client + public function create($client): ?Client { return $this->save( - $client, ClientFactory::create(auth()->user()->company()->id, auth()->user()->id) + $client, + ClientFactory::create(auth()->user()->company()->id, auth()->user()->id) ); } - } diff --git a/app/Repositories/CompanyRepository.php b/app/Repositories/CompanyRepository.php index cbe22a1c6002..3302dc6c73b2 100644 --- a/app/Repositories/CompanyRepository.php +++ b/app/Repositories/CompanyRepository.php @@ -19,10 +19,8 @@ use Illuminate\Http\Request; */ class CompanyRepository extends BaseRepository { - public function __construct() { - } /** @@ -32,12 +30,10 @@ class CompanyRepository extends BaseRepository */ public function getClassName() { - return Company::class; - } - /** + /** * Saves the client and its contacts * * @param array $data The data @@ -46,27 +42,24 @@ class CompanyRepository extends BaseRepository * @return Client|\App\Models\Company|null Company Object */ public function save(array $data, Company $company) : ?Company - { - - if(isset($data['custom_fields']) && is_array($data['custom_fields'])) - $data['custom_fields'] = $this->parseCustomFields($data['custom_fields']); + { + if (isset($data['custom_fields']) && is_array($data['custom_fields'])) { + $data['custom_fields'] = $this->parseCustomFields($data['custom_fields']); + } $company->fill($data); $company->save(); return $company; - - } + } private function parseCustomFields($fields) :array { - foreach($fields as &$value) - { - $value = (string)$value; + foreach ($fields as &$value) { + $value = (string)$value; } return $fields; } - -} \ No newline at end of file +} diff --git a/app/Repositories/GroupSettingRepository.php b/app/Repositories/GroupSettingRepository.php index 1bf1942b277a..ce3510c05382 100644 --- a/app/Repositories/GroupSettingRepository.php +++ b/app/Repositories/GroupSettingRepository.php @@ -16,7 +16,6 @@ use App\Utils\Traits\MakesHash; class GroupSettingRepository { - use MakesHash; /** * Gets the class name. @@ -25,28 +24,21 @@ class GroupSettingRepository */ public function getClassName() { - return GroupSetting::class; - } - public function save($data, GroupSetting $group_setting) :?GroupSetting - { + public function save($data, GroupSetting $group_setting) :?GroupSetting + { + $group_setting->fill($data); + $group_setting->save(); - $group_setting->fill($data); - $group_setting->save(); - - if(array_key_exists('company_logo', $data) && $data['company_logo'] == '') - { - + if (array_key_exists('company_logo', $data) && $data['company_logo'] == '') { $settings = $group_setting->settings; unset($settings->company_logo); $group_setting->settings = $settings; $group_setting->save(); - } - return $group_setting; - } - -} \ No newline at end of file + return $group_setting; + } +} diff --git a/app/Repositories/InvoiceRepository.php b/app/Repositories/InvoiceRepository.php index a2888baa0b10..f6adfad22418 100644 --- a/app/Repositories/InvoiceRepository.php +++ b/app/Repositories/InvoiceRepository.php @@ -40,12 +40,10 @@ class InvoiceRepository extends BaseRepository */ public function getClassName() { - return Invoice::class; - } - /** + /** * Saves the invoices * * @param array. $data The invoice data @@ -54,7 +52,7 @@ class InvoiceRepository extends BaseRepository * @return Invoice|InvoiceSum|\App\Models\Invoice|null Returns the invoice object */ public function save($data, Invoice $invoice) : ?Invoice - { + { /* Always carry forward the initial invoice amount this is important for tracking client balance changes later......*/ $starting_amount = $invoice->amount; @@ -63,12 +61,9 @@ class InvoiceRepository extends BaseRepository $invoice->save(); - if(isset($data['client_contacts'])) - { - foreach($data['client_contacts'] as $contact) - { - if($contact['send_invoice'] == 1) - { + if (isset($data['client_contacts'])) { + foreach ($data['client_contacts'] as $contact) { + if ($contact['send_invoice'] == 1) { $client_contact = ClientContact::find($this->decodePrimaryKey($contact['id'])); $client_contact->send_invoice = true; $client_contact->save(); @@ -77,43 +72,37 @@ class InvoiceRepository extends BaseRepository } - if(isset($data['invitations'])) - { - + if (isset($data['invitations'])) { $invitations = collect($data['invitations']); /* Get array of Keyss which have been removed from the invitations array and soft delete each invitation */ - collect($invoice->invitations->pluck('key'))->diff($invitations->pluck('key'))->each(function($invitation){ - + collect($invoice->invitations->pluck('key'))->diff($invitations->pluck('key'))->each(function ($invitation) { InvoiceInvitation::destroy($invitation); - }); - foreach($data['invitations'] as $invitation) - { + foreach ($data['invitations'] as $invitation) { $inv = false; - if(array_key_exists ('key', $invitation)) + if (array_key_exists('key', $invitation)) { $inv = InvoiceInvitation::whereKey($invitation['key'])->first(); + } - if(!$inv) - { + if (!$inv) { $invitation['client_contact_id'] = $this->decodePrimaryKey($invitation['client_contact_id']); $new_invitation = InvoiceInvitationFactory::create($invoice->company_id, $invoice->user_id); $new_invitation->fill($invitation); $new_invitation->invoice_id = $invoice->id; $new_invitation->save(); - } } - } /* If no invitations have been created, this is our fail safe to maintain state*/ - if($invoice->invitations->count() == 0) + if ($invoice->invitations->count() == 0) { CreateInvoiceInvitations::dispatchNow($invoice, $invoice->company); + } $invoice = $invoice->calc()->getInvoice(); @@ -122,17 +111,18 @@ class InvoiceRepository extends BaseRepository $finished_amount = $invoice->amount; /**/ - if(($finished_amount != $starting_amount) && ($invoice->status_id != Invoice::STATUS_DRAFT)) + if (($finished_amount != $starting_amount) && ($invoice->status_id != Invoice::STATUS_DRAFT)) { UpdateCompanyLedgerWithInvoice::dispatchNow($invoice, ($finished_amount - $starting_amount), $invoice->company); + } $invoice = ApplyInvoiceNumber::dispatchNow($invoice, $invoice->client->getMergedSettings(), $invoice->company); - if($invoice->company->update_products !== false) + if ($invoice->company->update_products !== false) { UpdateOrCreateProduct::dispatch($invoice->line_items, $invoice, $invoice->company); + } return $invoice->fresh(); - - } + } /** * Mark the invoice as sent. @@ -143,12 +133,6 @@ class InvoiceRepository extends BaseRepository */ public function markSent(Invoice $invoice) : ?Invoice { - return $invoice->markSent(); - } - - - - -} \ No newline at end of file +} diff --git a/app/Repositories/PaymentRepository.php b/app/Repositories/PaymentRepository.php index 93743344316e..d8ae2f5a2645 100644 --- a/app/Repositories/PaymentRepository.php +++ b/app/Repositories/PaymentRepository.php @@ -25,7 +25,6 @@ use Illuminate\Http\Request; */ class PaymentRepository extends BaseRepository { - public function getClassName() { return Payment::class; @@ -33,36 +32,30 @@ class PaymentRepository extends BaseRepository /** * Saves - * @param Request $request [description] - * @param Payment $payment [description] - * @return [type] [description] + * @param Request $request the request object + * @param Payment $payment The Payment object + * @return Object Payment $payment */ - public function save(Request $request, Payment $payment) : ?Payment - { + public function save(Request $request, Payment $payment) : ?Payment + { //todo this save() only works for new payments... will fail if a Payment is updated and saved through here. $payment->fill($request->input()); $payment->save(); - if($request->input('invoices')) - { - - $invoices = Invoice::whereIn('id', array_column($request->input('invoices'),'id'))->company()->get(); + if ($request->input('invoices')) { + $invoices = Invoice::whereIn('id', array_column($request->input('invoices'), 'id'))->company()->get(); $payment->invoices()->saveMany($invoices); - foreach($request->input('invoices') as $paid_invoice) - { - + foreach ($request->input('invoices') as $paid_invoice) { $invoice = Invoice::whereId($paid_invoice['id'])->company()->first(); - if($invoice) + if ($invoice) { ApplyInvoicePayment::dispatchNow($invoice, $payment, $paid_invoice['amount'], $invoice->company); - + } } - - } - else { + } else { //paid is made, but not to any invoice, therefore we are applying the payment to the clients credit ApplyClientPayment::dispatchNow($payment, $payment->company); } @@ -72,7 +65,5 @@ class PaymentRepository extends BaseRepository //UpdateInvoicePayment::dispatchNow($payment); return $payment->fresh(); - - } - -} \ No newline at end of file + } +} diff --git a/app/Repositories/ProductRepository.php b/app/Repositories/ProductRepository.php index 0e99a7237f93..babd71be6dcb 100644 --- a/app/Repositories/ProductRepository.php +++ b/app/Repositories/ProductRepository.php @@ -15,22 +15,20 @@ use App\Models\Product; use Illuminate\Http\Request; /** - * + * */ class ProductRepository extends BaseRepository { - public function getClassName() { return Product::class; } - public function save(Request $request, Product $product) : ?Product - { + public function save(Request $request, Product $product) : ?Product + { $product->fill($request->input()); $product->save(); return $product; - } - -} \ No newline at end of file + } +} diff --git a/app/Repositories/QuoteRepository.php b/app/Repositories/QuoteRepository.php index 3cf5eb9e855c..0cfd9d614639 100644 --- a/app/Repositories/QuoteRepository.php +++ b/app/Repositories/QuoteRepository.php @@ -26,15 +26,13 @@ use Illuminate\Http\Request; */ class QuoteRepository extends BaseRepository { - - public function getClassName() { return Quote::class; } - public function save($data, Quote $quote) : ?Quote - { + public function save($data, Quote $quote) : ?Quote + { /* Always carry forward the initial invoice amount this is important for tracking client balance changes later......*/ $starting_amount = $quote->amount; @@ -43,12 +41,9 @@ class QuoteRepository extends BaseRepository $quote->save(); - if(isset($data['client_contacts'])) - { - foreach($data['client_contacts'] as $contact) - { - if($contact['send_invoice'] == 1) - { + if (isset($data['client_contacts'])) { + foreach ($data['client_contacts'] as $contact) { + if ($contact['send_invoice'] == 1) { $client_contact = ClientContact::find($this->decodePrimaryKey($contact['id'])); $client_contact->send_invoice = true; $client_contact->save(); @@ -57,43 +52,37 @@ class QuoteRepository extends BaseRepository } - if(isset($data['invitations'])) - { - + if (isset($data['invitations'])) { $invitations = collect($data['invitations']); /* Get array of Keyss which have been removed from the invitations array and soft delete each invitation */ - collect($quote->invitations->pluck('key'))->diff($invitations->pluck('key'))->each(function($invitation){ - + collect($quote->invitations->pluck('key'))->diff($invitations->pluck('key'))->each(function ($invitation) { QuoteInvitation::destroy($invitation); - }); - foreach($data['invitations'] as $invitation) - { + foreach ($data['invitations'] as $invitation) { $inv = false; - if(array_key_exists ('key', $invitation)) + if (array_key_exists('key', $invitation)) { $inv = QuoteInvitation::whereKey($invitation['key'])->first(); + } - if(!$inv) - { + if (!$inv) { $invitation['client_contact_id'] = $this->decodePrimaryKey($invitation['client_contact_id']); $new_invitation = QuoteInvitationFactory::create($quote->company_id, $quote->user_id); $new_invitation->fill($invitation); $new_invitation->quote_id = $quote->id; $new_invitation->save(); - } } - } /* If no invitations have been created, this is our fail safe to maintain state*/ - if($quote->invitations->count() == 0) + if ($quote->invitations->count() == 0) { CreateQuoteInvitations::dispatchNow($quote, $quote->company); + } $quote = $quote->calc()->getInvoice(); @@ -104,6 +93,5 @@ class QuoteRepository extends BaseRepository $quote = ApplyQuoteNumber::dispatchNow($quote, $quote->client->getMergedSettings(), $quote->company); return $quote->fresh(); - } - -} \ No newline at end of file + } +} diff --git a/app/Repositories/RecurringInvoiceRepository.php b/app/Repositories/RecurringInvoiceRepository.php index b164132ff16d..a10155d0d117 100644 --- a/app/Repositories/RecurringInvoiceRepository.php +++ b/app/Repositories/RecurringInvoiceRepository.php @@ -20,15 +20,13 @@ use Illuminate\Http\Request; */ class RecurringInvoiceRepository extends BaseRepository { - - public function getClassName() { return RecurringInvoice::class; } - public function save($data, RecurringInvoice $invoice) : ?RecurringInvoice - { + public function save($data, RecurringInvoice $invoice) : ?RecurringInvoice + { $invoice->fill($data); $invoice->save(); @@ -41,6 +39,5 @@ class RecurringInvoiceRepository extends BaseRepository //ie. client balance update... return $invoice; - } - -} \ No newline at end of file + } +} diff --git a/app/Repositories/RecurringQuoteRepository.php b/app/Repositories/RecurringQuoteRepository.php index 0e655b37a8ed..74cede0a96e6 100644 --- a/app/Repositories/RecurringQuoteRepository.php +++ b/app/Repositories/RecurringQuoteRepository.php @@ -20,15 +20,13 @@ use Illuminate\Http\Request; */ class RecurringQuoteRepository extends BaseRepository { - - public function getClassName() { return RecurringQuote::class; } - public function save(Request $request, RecurringQuote $quote) : ?RecurringQuote - { + public function save(Request $request, RecurringQuote $quote) : ?RecurringQuote + { $quote->fill($request->input()); $quote->save(); @@ -42,6 +40,5 @@ class RecurringQuoteRepository extends BaseRepository //ie. client balance update... return $quote; - } - -} \ No newline at end of file + } +} diff --git a/app/Repositories/UserRepository.php b/app/Repositories/UserRepository.php index 7ce2fe42b990..6e7d7af17ab2 100644 --- a/app/Repositories/UserRepository.php +++ b/app/Repositories/UserRepository.php @@ -21,11 +21,8 @@ use Illuminate\Http\Request; */ class UserRepository extends BaseRepository { - public function __construct() { - - } /** @@ -35,12 +32,10 @@ class UserRepository extends BaseRepository */ public function getClassName() { - return User::class; - } - /** + /** * Saves the user and its contacts * * @param array $data The data @@ -49,36 +44,26 @@ class UserRepository extends BaseRepository * @return user|\App\Models\user|null user Object */ public function save(array $data, User $user) : ?User - { - + { $user->fill($data); $user->save(); - if(isset($data['company_user'])) - { - + if (isset($data['company_user'])) { $company = auth()->user()->company(); $account_id = $company->account->id; $cu = CompanyUser::whereUserId($user->id)->whereCompanyId($company->id)->first(); /*No company user exists - attach the user*/ - if(!$cu){ - - $data['company_user']['account_id'] = $account_id; + if (!$cu) { + $data['company_user']['account_id'] = $account_id; $user->companies()->attach($company->id, $data['company_user']); - - } - else - { + } else { $cu->fill($data['company_user']); $cu->save(); } - } return $user; - - } - -} \ No newline at end of file + } +} diff --git a/app/Transformers/AccountTransformer.php b/app/Transformers/AccountTransformer.php index 724860a67d72..7954c3afc412 100644 --- a/app/Transformers/AccountTransformer.php +++ b/app/Transformers/AccountTransformer.php @@ -56,40 +56,32 @@ class AccountTransformer extends EntityTransformer */ public function transform(Account $account) { - return [ 'id' => (string)$this->encodePrimaryKey($account->id), 'default_url' => config('ninja.site_url'), 'plan' => $account->getPlan(), ]; - } public function includeCompanyUsers(Account $account) { - $transformer = new CompanyUserTransformer($this->serializer); return $this->includeCollection($account->company_users, $transformer, CompanyUser::class); - } public function includeDefaultCompany(Account $account) { - $transformer = new CompanyTransformer($this->serializer); return $this->includeItem($account->default_company, $transformer, Company::class); - } public function includeUser(Account $account) { - $transformer = new UserTransformer($this->serializer); return $this->includeItem(auth()->user(), $transformer, User::class); // return $this->includeItem($account->default_company->owner(), $transformer, User::class); - } } diff --git a/app/Transformers/ActivityTransformer.php b/app/Transformers/ActivityTransformer.php index a63189ee9d78..4f3e39534871 100644 --- a/app/Transformers/ActivityTransformer.php +++ b/app/Transformers/ActivityTransformer.php @@ -5,7 +5,6 @@ namespace App\Transformers; use App\Models\Activity; use App\Utils\Traits\MakesHash; - class ActivityTransformer extends EntityTransformer { use MakesHash; @@ -38,8 +37,8 @@ class ActivityTransformer extends EntityTransformer 'is_system' => (bool) $activity->is_system, 'contact_id' => $activity->contact_id ? (string) $this->encodePrimaryKey($activity->contact_id) : '', 'task_id' => $activity->task_id ? (string) $this->encodePrimaryKey($activity->task_id) : '', - 'notes' => $activity->notes ? (string) $activity->notes : '', - 'ip' => (string) $activity->ip, + 'notes' => $activity->notes ? (string) $activity->notes : '', + 'ip' => (string) $activity->ip, ]; } diff --git a/app/Transformers/ClientContactLoginTransformer.php b/app/Transformers/ClientContactLoginTransformer.php index 2c0bcad70944..b6762968b7ee 100644 --- a/app/Transformers/ClientContactLoginTransformer.php +++ b/app/Transformers/ClientContactLoginTransformer.php @@ -28,7 +28,6 @@ class ClientContactLoginTransformer extends EntityTransformer */ public function transform(ClientContact $contact) { - return [ 'id' => $this->encodePrimaryKey($contact->id), 'first_name' => $contact->first_name ?: '', diff --git a/app/Transformers/ClientContactTransformer.php b/app/Transformers/ClientContactTransformer.php index c850b1c9fbab..8c7b7edcac9d 100644 --- a/app/Transformers/ClientContactTransformer.php +++ b/app/Transformers/ClientContactTransformer.php @@ -29,7 +29,6 @@ class ClientContactTransformer extends EntityTransformer */ public function transform(ClientContact $contact) { - return [ 'id' => $this->encodePrimaryKey($contact->id), 'first_name' => $contact->first_name ?: '', diff --git a/app/Transformers/ClientGatewayTokenTransformer.php b/app/Transformers/ClientGatewayTokenTransformer.php index d947e1aee4f4..faf1e9db9b9c 100644 --- a/app/Transformers/ClientGatewayTokenTransformer.php +++ b/app/Transformers/ClientGatewayTokenTransformer.php @@ -29,7 +29,6 @@ class ClientGatewayTokenTransformer extends EntityTransformer */ public function transform(ClientGatewayToken $cgt) { - return [ 'id' => $this->encodePrimaryKey($cgt->id), 'token' => (string)$cgt->token ?: '', diff --git a/app/Transformers/ClientTransformer.php b/app/Transformers/ClientTransformer.php index 2ac5f7e8546c..afa874ea9d94 100644 --- a/app/Transformers/ClientTransformer.php +++ b/app/Transformers/ClientTransformer.php @@ -116,4 +116,4 @@ class ClientTransformer extends EntityTransformer 'display_name' => $client->present()->name() ]; } -} \ No newline at end of file +} diff --git a/app/Transformers/CompanyGatewayTransformer.php b/app/Transformers/CompanyGatewayTransformer.php index 749fd643d4cf..423c1c94331a 100644 --- a/app/Transformers/CompanyGatewayTransformer.php +++ b/app/Transformers/CompanyGatewayTransformer.php @@ -68,5 +68,4 @@ class CompanyGatewayTransformer extends EntityTransformer return $this->includeItem($company_gateway->gateway, $transformer, Gateway::class); } - } diff --git a/app/Transformers/CompanyTokenTransformer.php b/app/Transformers/CompanyTokenTransformer.php index e68494b9a0a2..64c82883b7b6 100644 --- a/app/Transformers/CompanyTokenTransformer.php +++ b/app/Transformers/CompanyTokenTransformer.php @@ -46,6 +46,4 @@ class CompanyTokenTransformer extends EntityTransformer 'name' => $company_token->name ?: '', ]; } - - } diff --git a/app/Transformers/CompanyTransformer.php b/app/Transformers/CompanyTransformer.php index fa5a7aa9296c..0df7d07ab163 100644 --- a/app/Transformers/CompanyTransformer.php +++ b/app/Transformers/CompanyTransformer.php @@ -11,7 +11,6 @@ namespace App\Transformers; - use App\Models\Account; use App\Models\Activity; use App\Models\Client; @@ -142,7 +141,7 @@ class CompanyTransformer extends EntityTransformer { $transformer = new GroupSettingTransformer($this->serializer); - return $this->includeCollection($company->groups, $transformer, GroupSetting::class); + return $this->includeCollection($company->groups, $transformer, GroupSetting::class); } public function includeInvoices(Company $company) @@ -161,37 +160,29 @@ class CompanyTransformer extends EntityTransformer public function includeAccount(Company $company) { - $transformer = new AccountTransformer($this->serializer); return $this->includeItem($company->account, $transformer, Account::class); - } public function includeTaxRates(Company $company) { - $transformer = new TaxRateTransformer($this->serializer); return $this->includeCollection($company->tax_rates, $transformer, TaxRate::class); - } public function includeProducts(Company $company) { - $transformer = new ProductTransformer($this->serializer); return $this->includeCollection($company->products, $transformer, Product::class); - } public function includePayments(Company $company) { - $transformer = new PaymentTransformer($this->serializer); return $this->includeCollection($company->payments, $transformer, Payment::class); - } } diff --git a/app/Transformers/CompanyUserTransformer.php b/app/Transformers/CompanyUserTransformer.php index c0ccbb004b5c..c044bbf737a0 100644 --- a/app/Transformers/CompanyUserTransformer.php +++ b/app/Transformers/CompanyUserTransformer.php @@ -65,7 +65,6 @@ class CompanyUserTransformer extends EntityTransformer public function includeAccount(CompanyUser $company_user) { - $transformer = new AccountTransformer($this->serializer); return $this->includeItem($company_user->account, $transformer, Account::class); @@ -73,29 +72,22 @@ class CompanyUserTransformer extends EntityTransformer public function includeCompany(CompanyUser $company_user) { - $transformer = new CompanyTransformer($this->serializer); return $this->includeItem($company_user->company, $transformer, Company::class); - } public function includeUser(CompanyUser $company_user) { - $transformer = new UserTransformer($this->serializer); return $this->includeItem($company_user->user, $transformer, User::class); - } public function includeToken(CompanyUser $company_user) { - $transformer = new CompanyTokenTransformer($this->serializer); return $this->includeItem($company_user->token, $transformer, CompanyToken::class); - } - } diff --git a/app/Transformers/Contact/InvoiceTransformer.php b/app/Transformers/Contact/InvoiceTransformer.php index 7deaca6f1cbb..31df09f9fc26 100644 --- a/app/Transformers/Contact/InvoiceTransformer.php +++ b/app/Transformers/Contact/InvoiceTransformer.php @@ -65,4 +65,4 @@ class InvoiceTransformer extends EntityTransformer 'line_items' => $invoice->line_items ]; } -} \ No newline at end of file +} diff --git a/app/Transformers/DocumentTransformer.php b/app/Transformers/DocumentTransformer.php index 42c13a6edcd8..c725f7c55687 100644 --- a/app/Transformers/DocumentTransformer.php +++ b/app/Transformers/DocumentTransformer.php @@ -53,4 +53,3 @@ class DocumentTransformer extends EntityTransformer ]; } } - \ No newline at end of file diff --git a/app/Transformers/EntityTransformer.php b/app/Transformers/EntityTransformer.php index ee1f1b38164d..a28898586d69 100644 --- a/app/Transformers/EntityTransformer.php +++ b/app/Transformers/EntityTransformer.php @@ -50,6 +50,5 @@ class EntityTransformer extends TransformerAbstract protected function getDefaults($entity) { - } } diff --git a/app/Transformers/GatewayTransformer.php b/app/Transformers/GatewayTransformer.php index ca70c8085deb..32833c76e396 100644 --- a/app/Transformers/GatewayTransformer.php +++ b/app/Transformers/GatewayTransformer.php @@ -53,4 +53,4 @@ class GatewayTransformer extends EntityTransformer 'updated_at' => (int)$gateway->updated_at, ]; } -} \ No newline at end of file +} diff --git a/app/Transformers/GroupSettingTransformer.php b/app/Transformers/GroupSettingTransformer.php index 35107a21e316..4163fcf8d070 100644 --- a/app/Transformers/GroupSettingTransformer.php +++ b/app/Transformers/GroupSettingTransformer.php @@ -44,4 +44,4 @@ class GroupSettingTransformer extends EntityTransformer 'settings' => $group_setting->settings ?: new \stdClass, ]; } -} \ No newline at end of file +} diff --git a/app/Transformers/InvoiceInvitationTransformer.php b/app/Transformers/InvoiceInvitationTransformer.php index 63bcdb94f707..19082cc5a9ad 100644 --- a/app/Transformers/InvoiceInvitationTransformer.php +++ b/app/Transformers/InvoiceInvitationTransformer.php @@ -21,7 +21,6 @@ class InvoiceInvitationTransformer extends EntityTransformer public function transform(InvoiceInvitation $invitation) { - return [ 'id' => $this->encodePrimaryKey($invitation->id), 'client_contact_id' => $this->encodePrimaryKey($invitation->client_contact_id), diff --git a/app/Transformers/InvoiceItemTransformer.php b/app/Transformers/InvoiceItemTransformer.php index 3dab28423730..843a1880a342 100644 --- a/app/Transformers/InvoiceItemTransformer.php +++ b/app/Transformers/InvoiceItemTransformer.php @@ -13,7 +13,6 @@ namespace App\Transformers; class InvoiceItemTransformer extends EntityTransformer { - public function transform($item) { return [ diff --git a/app/Transformers/InvoiceTransformer.php b/app/Transformers/InvoiceTransformer.php index 0315a523a3b0..3eafb20e9e49 100644 --- a/app/Transformers/InvoiceTransformer.php +++ b/app/Transformers/InvoiceTransformer.php @@ -37,48 +37,48 @@ class InvoiceTransformer extends EntityTransformer return $this->includeCollection($invoice->invitations, $transformer, InvoiceInvitation::class); } -/* - public function includeInvoiceItems(Invoice $invoice) - { - $transformer = new InvoiceItemTransformer($this->serializer); - - return $this->includeCollection($invoice->invoice_items, $transformer, ENTITY_INVOICE_ITEM); - } - - - - public function includePayments(Invoice $invoice) - { - $transformer = new PaymentTransformer($this->account, $this->serializer, $invoice); - - return $this->includeCollection($invoice->payments, $transformer, ENTITY_PAYMENT); - } - - public function includeClient(Invoice $invoice) - { - $transformer = new ClientTransformer($this->account, $this->serializer); - - return $this->includeItem($invoice->client, $transformer, ENTITY_CLIENT); - } - - public function includeExpenses(Invoice $invoice) - { - $transformer = new ExpenseTransformer($this->account, $this->serializer); - - return $this->includeCollection($invoice->expenses, $transformer, ENTITY_EXPENSE); - } - - public function includeDocuments(Invoice $invoice) - { - $transformer = new DocumentTransformer($this->account, $this->serializer); - - $invoice->documents->each(function ($document) use ($invoice) { - $document->setRelation('invoice', $invoice); - }); - - return $this->includeCollection($invoice->documents, $transformer, ENTITY_DOCUMENT); - } -*/ + /* + public function includeInvoiceItems(Invoice $invoice) + { + $transformer = new InvoiceItemTransformer($this->serializer); + + return $this->includeCollection($invoice->invoice_items, $transformer, ENTITY_INVOICE_ITEM); + } + + + + public function includePayments(Invoice $invoice) + { + $transformer = new PaymentTransformer($this->account, $this->serializer, $invoice); + + return $this->includeCollection($invoice->payments, $transformer, ENTITY_PAYMENT); + } + + public function includeClient(Invoice $invoice) + { + $transformer = new ClientTransformer($this->account, $this->serializer); + + return $this->includeItem($invoice->client, $transformer, ENTITY_CLIENT); + } + + public function includeExpenses(Invoice $invoice) + { + $transformer = new ExpenseTransformer($this->account, $this->serializer); + + return $this->includeCollection($invoice->expenses, $transformer, ENTITY_EXPENSE); + } + + public function includeDocuments(Invoice $invoice) + { + $transformer = new DocumentTransformer($this->account, $this->serializer); + + $invoice->documents->each(function ($document) use ($invoice) { + $document->setRelation('invoice', $invoice); + }); + + return $this->includeCollection($invoice->documents, $transformer, ENTITY_DOCUMENT); + } + */ public function transform(Invoice $invoice) { return [ @@ -130,4 +130,4 @@ class InvoiceTransformer extends EntityTransformer 'backup' => $invoice->backup ?: '', ]; } -} \ No newline at end of file +} diff --git a/app/Transformers/PaymentTransformer.php b/app/Transformers/PaymentTransformer.php index 091afb650a8b..b2af3afce27f 100644 --- a/app/Transformers/PaymentTransformer.php +++ b/app/Transformers/PaymentTransformer.php @@ -35,9 +35,7 @@ class PaymentTransformer extends EntityTransformer public function __construct($serializer = null) { - $this->serializer = $serializer; - } public function includeInvoices(Payment $payment) diff --git a/app/Transformers/PaymentableTransformer.php b/app/Transformers/PaymentableTransformer.php index 989d26838cc3..2cb9e53d2d54 100644 --- a/app/Transformers/PaymentableTransformer.php +++ b/app/Transformers/PaymentableTransformer.php @@ -27,9 +27,7 @@ class PaymentableTransformer extends EntityTransformer public function __construct($serializer = null) { - $this->serializer = $serializer; - } public function transform(Paymentable $paymentable) diff --git a/app/Transformers/QuoteInvitationTransformer.php b/app/Transformers/QuoteInvitationTransformer.php index 71446447fe86..35a29140e978 100644 --- a/app/Transformers/QuoteInvitationTransformer.php +++ b/app/Transformers/QuoteInvitationTransformer.php @@ -21,7 +21,6 @@ class QuoteInvitationTransformer extends EntityTransformer public function transform(QuoteInvitation $invitation) { - return [ 'id' => $this->encodePrimaryKey($invitation->id), 'client_contact_id' => $this->encodePrimaryKey($invitation->client_contact_id), diff --git a/app/Transformers/QuoteTransformer.php b/app/Transformers/QuoteTransformer.php index fea5b5811af4..a393502331cf 100644 --- a/app/Transformers/QuoteTransformer.php +++ b/app/Transformers/QuoteTransformer.php @@ -35,39 +35,39 @@ class QuoteTransformer extends EntityTransformer return $this->includeCollection($quote->invitations, $transformer, QuoteInvitation::class); } -/* - public function includePayments(quote $quote) - { - $transformer = new PaymentTransformer($this->account, $this->serializer, $quote); - - return $this->includeCollection($quote->payments, $transformer, ENTITY_PAYMENT); - } - - public function includeClient(quote $quote) - { - $transformer = new ClientTransformer($this->account, $this->serializer); - - return $this->includeItem($quote->client, $transformer, ENTITY_CLIENT); - } - - public function includeExpenses(quote $quote) - { - $transformer = new ExpenseTransformer($this->account, $this->serializer); - - return $this->includeCollection($quote->expenses, $transformer, ENTITY_EXPENSE); - } - - public function includeDocuments(quote $quote) - { - $transformer = new DocumentTransformer($this->account, $this->serializer); - - $quote->documents->each(function ($document) use ($quote) { - $document->setRelation('quote', $quote); - }); - - return $this->includeCollection($quote->documents, $transformer, ENTITY_DOCUMENT); - } -*/ + /* + public function includePayments(quote $quote) + { + $transformer = new PaymentTransformer($this->account, $this->serializer, $quote); + + return $this->includeCollection($quote->payments, $transformer, ENTITY_PAYMENT); + } + + public function includeClient(quote $quote) + { + $transformer = new ClientTransformer($this->account, $this->serializer); + + return $this->includeItem($quote->client, $transformer, ENTITY_CLIENT); + } + + public function includeExpenses(quote $quote) + { + $transformer = new ExpenseTransformer($this->account, $this->serializer); + + return $this->includeCollection($quote->expenses, $transformer, ENTITY_EXPENSE); + } + + public function includeDocuments(quote $quote) + { + $transformer = new DocumentTransformer($this->account, $this->serializer); + + $quote->documents->each(function ($document) use ($quote) { + $document->setRelation('quote', $quote); + }); + + return $this->includeCollection($quote->documents, $transformer, ENTITY_DOCUMENT); + } + */ public function transform(Quote $quote) { return [ @@ -119,4 +119,4 @@ class QuoteTransformer extends EntityTransformer 'backup' => $quote->backup ?: '', ]; } -} \ No newline at end of file +} diff --git a/app/Transformers/RecurringInvoiceTransformer.php b/app/Transformers/RecurringInvoiceTransformer.php index 0734cbe173a5..b1cf9f7d64e9 100644 --- a/app/Transformers/RecurringInvoiceTransformer.php +++ b/app/Transformers/RecurringInvoiceTransformer.php @@ -30,53 +30,53 @@ class RecurringInvoiceTransformer extends EntityTransformer // 'documents', ]; -/* - public function includeInvoiceItems(Invoice $invoice) - { - $transformer = new InvoiceItemTransformer($this->serializer); - - return $this->includeCollection($invoice->invoice_items, $transformer, ENTITY_INVOICE_ITEM); - } - - public function includeInvitations(Invoice $invoice) - { - $transformer = new InvitationTransformer($this->account, $this->serializer); - - return $this->includeCollection($invoice->invitations, $transformer, ENTITY_INVITATION); - } - - public function includePayments(Invoice $invoice) - { - $transformer = new PaymentTransformer($this->account, $this->serializer, $invoice); - - return $this->includeCollection($invoice->payments, $transformer, ENTITY_PAYMENT); - } - - public function includeClient(Invoice $invoice) - { - $transformer = new ClientTransformer($this->account, $this->serializer); - - return $this->includeItem($invoice->client, $transformer, ENTITY_CLIENT); - } - - public function includeExpenses(Invoice $invoice) - { - $transformer = new ExpenseTransformer($this->account, $this->serializer); - - return $this->includeCollection($invoice->expenses, $transformer, ENTITY_EXPENSE); - } - - public function includeDocuments(Invoice $invoice) - { - $transformer = new DocumentTransformer($this->account, $this->serializer); - - $invoice->documents->each(function ($document) use ($invoice) { - $document->setRelation('invoice', $invoice); - }); - - return $this->includeCollection($invoice->documents, $transformer, ENTITY_DOCUMENT); - } -*/ + /* + public function includeInvoiceItems(Invoice $invoice) + { + $transformer = new InvoiceItemTransformer($this->serializer); + + return $this->includeCollection($invoice->invoice_items, $transformer, ENTITY_INVOICE_ITEM); + } + + public function includeInvitations(Invoice $invoice) + { + $transformer = new InvitationTransformer($this->account, $this->serializer); + + return $this->includeCollection($invoice->invitations, $transformer, ENTITY_INVITATION); + } + + public function includePayments(Invoice $invoice) + { + $transformer = new PaymentTransformer($this->account, $this->serializer, $invoice); + + return $this->includeCollection($invoice->payments, $transformer, ENTITY_PAYMENT); + } + + public function includeClient(Invoice $invoice) + { + $transformer = new ClientTransformer($this->account, $this->serializer); + + return $this->includeItem($invoice->client, $transformer, ENTITY_CLIENT); + } + + public function includeExpenses(Invoice $invoice) + { + $transformer = new ExpenseTransformer($this->account, $this->serializer); + + return $this->includeCollection($invoice->expenses, $transformer, ENTITY_EXPENSE); + } + + public function includeDocuments(Invoice $invoice) + { + $transformer = new DocumentTransformer($this->account, $this->serializer); + + $invoice->documents->each(function ($document) use ($invoice) { + $document->setRelation('invoice', $invoice); + }); + + return $this->includeCollection($invoice->documents, $transformer, ENTITY_DOCUMENT); + } + */ public function transform(RecurringInvoice $invoice) { return [ diff --git a/app/Transformers/RecurringQuoteTransformer.php b/app/Transformers/RecurringQuoteTransformer.php index bdb1e9e48299..8e0eb8d5ebd3 100644 --- a/app/Transformers/RecurringQuoteTransformer.php +++ b/app/Transformers/RecurringQuoteTransformer.php @@ -30,53 +30,53 @@ class RecurringQuoteTransformer extends EntityTransformer // 'documents', ]; -/* - public function includeInvoiceItems(Invoice $quote) - { - $transformer = new InvoiceItemTransformer($this->serializer); - - return $this->includeCollection($quote->invoice_items, $transformer, ENTITY_INVOICE_ITEM); - } - - public function includeInvitations(Invoice $quote) - { - $transformer = new InvitationTransformer($this->account, $this->serializer); - - return $this->includeCollection($quote->invitations, $transformer, ENTITY_INVITATION); - } - - public function includePayments(Invoice $quote) - { - $transformer = new PaymentTransformer($this->account, $this->serializer, $quote); - - return $this->includeCollection($quote->payments, $transformer, ENTITY_PAYMENT); - } - - public function includeClient(Invoice $quote) - { - $transformer = new ClientTransformer($this->account, $this->serializer); - - return $this->includeItem($quote->client, $transformer, ENTITY_CLIENT); - } - - public function includeExpenses(Invoice $quote) - { - $transformer = new ExpenseTransformer($this->account, $this->serializer); - - return $this->includeCollection($quote->expenses, $transformer, ENTITY_EXPENSE); - } - - public function includeDocuments(Invoice $quote) - { - $transformer = new DocumentTransformer($this->account, $this->serializer); - - $quote->documents->each(function ($document) use ($quote) { - $document->setRelation('invoice', $quote); - }); - - return $this->includeCollection($quote->documents, $transformer, ENTITY_DOCUMENT); - } -*/ + /* + public function includeInvoiceItems(Invoice $quote) + { + $transformer = new InvoiceItemTransformer($this->serializer); + + return $this->includeCollection($quote->invoice_items, $transformer, ENTITY_INVOICE_ITEM); + } + + public function includeInvitations(Invoice $quote) + { + $transformer = new InvitationTransformer($this->account, $this->serializer); + + return $this->includeCollection($quote->invitations, $transformer, ENTITY_INVITATION); + } + + public function includePayments(Invoice $quote) + { + $transformer = new PaymentTransformer($this->account, $this->serializer, $quote); + + return $this->includeCollection($quote->payments, $transformer, ENTITY_PAYMENT); + } + + public function includeClient(Invoice $quote) + { + $transformer = new ClientTransformer($this->account, $this->serializer); + + return $this->includeItem($quote->client, $transformer, ENTITY_CLIENT); + } + + public function includeExpenses(Invoice $quote) + { + $transformer = new ExpenseTransformer($this->account, $this->serializer); + + return $this->includeCollection($quote->expenses, $transformer, ENTITY_EXPENSE); + } + + public function includeDocuments(Invoice $quote) + { + $transformer = new DocumentTransformer($this->account, $this->serializer); + + $quote->documents->each(function ($document) use ($quote) { + $document->setRelation('invoice', $quote); + }); + + return $this->includeCollection($quote->documents, $transformer, ENTITY_DOCUMENT); + } + */ public function transform(RecurringQuote $quote) { return [ diff --git a/app/Transformers/UserTransformer.php b/app/Transformers/UserTransformer.php index 91e2cfe5eddf..6c2ee782989f 100644 --- a/app/Transformers/UserTransformer.php +++ b/app/Transformers/UserTransformer.php @@ -46,7 +46,6 @@ class UserTransformer extends EntityTransformer public function transform(User $user) { - return [ 'id' => $this->encodePrimaryKey($user->id), 'first_name' => $user->first_name ?: '', @@ -67,38 +66,30 @@ class UserTransformer extends EntityTransformer public function includeCompanies(User $user) { - $transformer = new CompanyTransformer($this->serializer); return $this->includeCollection($user->companies, $transformer, Company::class); - } public function includeToken(User $user) { - $transformer = new CompanyTokenTransformer($this->serializer); return $this->includeItem($user->token, $transformer, CompanyToken::class); - } public function includeCompanyTokens(User $user) { - $transformer = new CompanyTokenTransformer($this->serializer); return $this->includeCollection($user->tokens, $transformer, CompanyToken::class); - } public function includeCompanyUsers(User $user) { - $transformer = new CompanyUserTransformer($this->serializer); return $this->includeCollection($user->company_users, $transformer, CompanyUser::class); - } public function includeCompanyUser(User $user) @@ -106,6 +97,5 @@ class UserTransformer extends EntityTransformer $transformer = new CompanyUserTransformer($this->serializer); return $this->includeItem($user->company_user, $transformer, CompanyUser::class); - } } diff --git a/app/Utils/Number.php b/app/Utils/Number.php index da50c2f3b20a..192f9829f519 100644 --- a/app/Utils/Number.php +++ b/app/Utils/Number.php @@ -32,10 +32,10 @@ class Number /** * Formats a given value based on the clients currency - * + * * @param float $value The number to be formatted * @param object $currency The client currency object - * + * * @return float The formatted value */ public static function formatValue($value, $currency) : float @@ -47,16 +47,15 @@ class Number $precision = $currency->precision; return number_format($value, $precision, $decimal, $thousand); - } /** * Formats a given value based on the clients currency AND country - * + * * @param floatval $value The number to be formatted * @param object $currency The client currency object * @param object $country The client country - * + * * @return string The formatted value */ public static function formatMoney($value, $client) :string @@ -69,15 +68,18 @@ class Number $code = $currency->code; $swapSymbol = $currency->swap_currency_symbol; - /* Country settings override client settings */ - if(isset($client->country->thousand_separator)) - $thousand = $client->country->thousand_separator; + /* Country settings override client settings */ + if (isset($client->country->thousand_separator)) { + $thousand = $client->country->thousand_separator; + } - if(isset($client->country->decimal_separator)) - $decimal = $client->country->decimal_separator; + if (isset($client->country->decimal_separator)) { + $decimal = $client->country->decimal_separator; + } - if(isset($client->country->swap_currency_symbol)) - $swapSymbol = $client->country->swap_currency_symbol; + if (isset($client->country->swap_currency_symbol)) { + $swapSymbol = $client->country->swap_currency_symbol; + } $value = number_format($value, $precision, $decimal, $thousand); $symbol = $currency->symbol; diff --git a/app/Utils/Statics.php b/app/Utils/Statics.php index 9d3c5886db41..d7a94fcc6b74 100644 --- a/app/Utils/Statics.php +++ b/app/Utils/Statics.php @@ -21,10 +21,10 @@ use Illuminate\Support\Str; */ class Statics { - /** - * Date format types - * @var array - */ + /** + * Date format types + * @var array + */ public static $date = [ ['format' => 'd/M/Y', 'picker_format' => 'dd/M/yyyy', 'format_moment' => 'DD/MMM/YYYY', 'format_dart' => 'dd/MMM/yyyy'], ['format' => 'd-M-Y', 'picker_format' => 'dd-M-yyyy', 'format_moment' => 'DD-MMM-YYYY', 'format_dart' => 'dd-MMM-yyyy'], @@ -45,7 +45,7 @@ class Statics * Date Time Format types * @var array */ - public static $date_time = [ + public static $date_time = [ ['format' => 'd/M/Y g:i a', 'format_moment' => 'DD/MMM/YYYY h:mm:ss a', 'format_dart' => 'dd/MMM/yyyy h:mm a'], ['format' => 'd-M-Y g:i a', 'format_moment' => 'DD-MMM-YYYY h:mm:ss a', 'format_dart' => 'dd-MMM-yyyy h:mm a'], ['format' => 'd/F/Y g:i a', 'format_moment' => 'DD/MMMM/YYYY h:mm:ss a', 'format_dart' => 'dd/MMMM/yyyy h:mm a'], @@ -60,7 +60,7 @@ class Statics ['format' => 'j. M. Y g:i a', 'format_moment' => 'DD. MMM. YYYY h:mm:ss a', 'format_dart' => 'd. MMM. yyyy h:mm a'], ['format' => 'j. F Y g:i a', 'format_moment' => 'DD. MMMM YYYY h:mm:ss a', 'format_dart' => 'd. MMMM yyyy h:mm a'], ]; - + /** * Company statics @@ -69,7 +69,6 @@ class Statics */ public static function company($locale = false) :array { - $data = []; foreach (config('ninja.cached_tables') as $name => $class) { @@ -77,7 +76,6 @@ class Statics } if ($locale) { - $data['industries'] = Cache::get('industries')->each(function ($industry) { $industry->name = ctrans('texts.industry_'.$industry->name); })->sortBy(function ($industry) { @@ -107,15 +105,8 @@ class Statics })->sortBy(function ($currency) { return $currency->name; })->values(); - } return $data; - } - } - - - - diff --git a/app/Utils/SystemHealth.php b/app/Utils/SystemHealth.php index f141919985d7..7776facc8037 100644 --- a/app/Utils/SystemHealth.php +++ b/app/Utils/SystemHealth.php @@ -19,96 +19,79 @@ use Illuminate\Support\Facades\DB; */ class SystemHealth { - - private static $extensions = [ - 'mysqli', - 'gd', - 'curl', - 'zip', - 'gmp' - ]; + private static $extensions = [ + 'mysqli', + 'gd', + 'curl', + 'zip', + 'gmp' + ]; private static $php_version = 7.3; - /** - * Check loaded extensions / PHP version / DB Connections - * - * @return array Result set of checks - */ - public static function check() : array - { - $system_health = TRUE; + /** + * Check loaded extensions / PHP version / DB Connections + * + * @return array Result set of checks + */ + public static function check() : array + { + $system_health = true; - if (in_array(FALSE, self::extensions())) - { - $system_health = FALSE; - } - elseif (phpversion() < self::$php_version) - { - $system_health = FALSE; - } + if (in_array(false, self::extensions())) { + $system_health = false; + } elseif (phpversion() < self::$php_version) { + $system_health = false; + } - return [ - 'system_health' => $system_health, - 'extensions' => self::extensions(), - 'php_version' => phpversion(), - 'min_php_version' => self::$php_version, - 'dbs' => self::dbCheck(), - ]; + return [ + 'system_health' => $system_health, + 'extensions' => self::extensions(), + 'php_version' => phpversion(), + 'min_php_version' => self::$php_version, + 'dbs' => self::dbCheck(), + ]; + } - } + private static function extensions() :array + { + $loaded_extensions = []; - private static function extensions() :array - { + foreach (self::$extensions as $extension) { + $loaded_extensions[] = [$extension => extension_loaded($extension)]; + } - $loaded_extensions = []; + return $loaded_extensions; + } - foreach(self::$extensions as $extension) - { + private static function dbCheck() :array + { + $result = []; - $loaded_extensions[] = [$extension => extension_loaded($extension)]; - - } - - return $loaded_extensions; - - } - - private static function dbCheck() :array - { - - $result = []; - - if (! config('ninja.db.multi_db_enabled')) - { + if (! config('ninja.db.multi_db_enabled')) { $pdo = DB::connection()->getPdo(); - if($pdo) - $result[] = [ DB::connection()->getDatabaseName() => TRUE ]; - else - $result[] = [ config('database.connections.' . config('database.default') . '.database') => FALSE ]; - - } - else - { - - foreach (MultiDB::$dbs as $db) - { + if ($pdo) { + $result[] = [ DB::connection()->getDatabaseName() => true ]; + } else { + $result[] = [ config('database.connections.' . config('database.default') . '.database') => false ]; + } + } else { + foreach (MultiDB::$dbs as $db) { MultiDB::setDB($db); - $pdo = DB::connection()->getPdo(); + $pdo = DB::connection()->getPdo(); - if($pdo) - $result[] = [ DB::connection()->getDatabaseName() => TRUE ]; - else - $result[] = [ config('database.connections.' . config('database.default') . '.database') => FALSE ]; + if ($pdo) { + $result[] = [ DB::connection()->getDatabaseName() => true ]; + } else { + $result[] = [ config('database.connections.' . config('database.default') . '.database') => false ]; + } } return $result; } - - } - + } } diff --git a/app/Utils/Traits/BulkOptions.php b/app/Utils/Traits/BulkOptions.php index eb39c63dde98..a18035626e9f 100644 --- a/app/Utils/Traits/BulkOptions.php +++ b/app/Utils/Traits/BulkOptions.php @@ -3,7 +3,6 @@ namespace App\Utils\Traits; - trait BulkOptions { /** diff --git a/app/Utils/Traits/ChecksEntityStatus.php b/app/Utils/Traits/ChecksEntityStatus.php new file mode 100644 index 000000000000..325a4d97de1b --- /dev/null +++ b/app/Utils/Traits/ChecksEntityStatus.php @@ -0,0 +1,34 @@ +is_deleted; + + } + + public function disallowUpdate() + { + return response()->json(['message'=>'Record is deleted and cannot be edited. Restore the record to enable editing'], 400); + + } + +} \ No newline at end of file diff --git a/app/Utils/Traits/CleanLineItems.php b/app/Utils/Traits/CleanLineItems.php index 815af4216189..7bf859a59367 100644 --- a/app/Utils/Traits/CleanLineItems.php +++ b/app/Utils/Traits/CleanLineItems.php @@ -14,55 +14,47 @@ namespace App\Utils\Traits; use App\DataMapper\BaseSettings; use App\DataMapper\InvoiceItem; - /** * Class CleanLineItems. */ trait CleanLineItems { - public function cleanItems($items) :array { - - if(!isset($items)) + if (!isset($items)) { return []; + } $cleaned_items = []; - foreach($items as $item) + foreach ($items as $item) { $cleaned_items[] = $this->cleanLineItem($item); + } return $cleaned_items; - } /** * Sets default values for the line_items - * @return $this + * @return $this */ private function cleanLineItem($item) { $invoice_item = (object)get_class_vars(InvoiceItem::class); unset($invoice_item->casts); - foreach($invoice_item as $key => $value) - { - - if(!array_key_exists($key, $item) || !isset($item[$key])){ + foreach ($invoice_item as $key => $value) { + if (!array_key_exists($key, $item) || !isset($item[$key])) { $item[$key] = $value; $item[$key] = BaseSettings::castAttribute(InvoiceItem::$casts[$key], $value); - } - + } } - if(array_key_exists("id", $item)) - { + if (array_key_exists("id", $item)) { unset($item['id']); - } + } return $item; } - } - diff --git a/app/Utils/Traits/ClientGroupSettingsSaver.php b/app/Utils/Traits/ClientGroupSettingsSaver.php index f0412b21d250..714d9eb59f86 100644 --- a/app/Utils/Traits/ClientGroupSettingsSaver.php +++ b/app/Utils/Traits/ClientGroupSettingsSaver.php @@ -20,201 +20,191 @@ use App\DataMapper\CompanySettings; trait ClientGroupSettingsSaver { - /** - * Saves a setting object - * - * Works for groups|clients|companies - * @param array $settings The request input settings array - * @param object $entity The entity which the settings belongs to - * @return void - */ - public function saveSettings($settings, $entity) - { + /** + * Saves a setting object + * + * Works for groups|clients|companies + * @param array $settings The request input settings array + * @param object $entity The entity which the settings belongs to + * @return void + */ + public function saveSettings($settings, $entity) + { + if (!$settings) { + return; + } - if(!$settings) - return; + $entity_settings = $this->settings; - $entity_settings = $this->settings; - - //unset protected properties. - foreach(CompanySettings::$protected_fields as $field) - unset($settings[$field]); + //unset protected properties. + foreach (CompanySettings::$protected_fields as $field) { + unset($settings[$field]); + } - /** - * for clients and group settings, if a field is not set or is set to a blank value, - * we unset it from the settings object - */ - foreach($settings as $key => $value) - { - - if(!isset($settings->{$key}) || empty($settings->{$key}) || (!is_object($settings->{$key}) && strlen($settings->{$key}) == 0)) - unset($settings->{$key}); - - } + /** + * for clients and group settings, if a field is not set or is set to a blank value, + * we unset it from the settings object + */ + foreach ($settings as $key => $value) { + if (!isset($settings->{$key}) || empty($settings->{$key}) || (!is_object($settings->{$key}) && strlen($settings->{$key}) == 0)) { + unset($settings->{$key}); + } + } - $settings = $this->checkSettingType($settings); + $settings = $this->checkSettingType($settings); - //iterate through set properties with new values; - foreach($settings as $key => $value) - $entity_settings->{$key} = $value; + //iterate through set properties with new values; + foreach ($settings as $key => $value) { + $entity_settings->{$key} = $value; + } - $entity->settings = $entity_settings; - $entity->save(); + $entity->settings = $entity_settings; + $entity->save(); - return $entity_settings; - } + return $entity_settings; + } - /** - * Used for custom validation of inbound - * settings request. - * - * Returns an array of errors, or boolean TRUE - * on successful validation - * @param array $settings The request() settings array - * @return array|bool Array on failure, boolean TRUE on success - */ - public function validateSettings($settings) - { - $settings = (object)$settings; - $casts = CompanySettings::$casts; + /** + * Used for custom validation of inbound + * settings request. + * + * Returns an array of errors, or boolean TRUE + * on successful validation + * @param array $settings The request() settings array + * @return array|bool Array on failure, boolean TRUE on success + */ + public function validateSettings($settings) + { + $settings = (object)$settings; + $casts = CompanySettings::$casts; - ksort($casts); + ksort($casts); - foreach($settings as $key => $value) - { + foreach ($settings as $key => $value) { + if (!isset($settings->{$key}) || empty($settings->{$key}) || (!is_object($settings->{$key}) && strlen($settings->{$key}) == 0)) { + unset($settings->{$key}); + } + } - if(!isset($settings->{$key}) || empty($settings->{$key}) || (!is_object($settings->{$key}) && strlen($settings->{$key}) == 0)) - unset($settings->{$key}); - - } + foreach ($casts as $key => $value) { - foreach ($casts as $key => $value){ + /*Separate loop if it is a _id field which is an integer cast as a string*/ + if (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter') { + $value = "integer"; + + if (!property_exists($settings, $key)) { + continue; + } elseif (!$this->checkAttribute($value, $settings->{$key})) { + return [$key, $value]; + } - /*Separate loop if it is a _id field which is an integer cast as a string*/ - if(substr($key, -3) == '_id' || substr($key, -14) == 'number_counter'){ - $value = "integer"; - - if(!property_exists($settings, $key)){ - continue; - } - else if(!$this->checkAttribute($value, $settings->{$key})){ - return [$key, $value]; - } + continue; + } - continue; - } + /* Handles unset settings or blank strings */ + if (!property_exists($settings, $key) || is_null($settings->{$key}) || !isset($settings->{$key}) || $settings->{$key} == '') { + continue; + } + - /* Handles unset settings or blank strings */ - if(!property_exists($settings, $key) || is_null($settings->{$key}) || !isset($settings->{$key}) || $settings->{$key} == '') - continue; - + /*Catch all filter */ + if (!$this->checkAttribute($value, $settings->{$key})) { + return [$key, $value]; + } + } - /*Catch all filter */ - if(!$this->checkAttribute($value, $settings->{$key})) - return [$key, $value]; - + return true; + } - } + /** + * Checks the settings object for + * correct property types. + * + * The method will drop invalid types from + * the object and will also settype() the property + * so that it can be saved cleanly + * + * @param array $settings The settings request() array + * @return object stdClass object + */ + private function checkSettingType($settings) : \stdClass + { + $settings = (object)$settings; + $casts = CompanySettings::$casts; + + foreach ($casts as $key => $value) { - return true; - } + /*Separate loop if it is a _id field which is an integer cast as a string*/ + if (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter') { + $value = "integer"; + + if (!property_exists($settings, $key)) { + continue; + } elseif ($this->checkAttribute($value, $settings->{$key})) { + if (substr($key, -3) == '_id') { + settype($settings->{$key}, 'string'); + } else { + settype($settings->{$key}, $value); + } + } else { + unset($settings->{$key}); + } - /** - * Checks the settings object for - * correct property types. - * - * The method will drop invalid types from - * the object and will also settype() the property - * so that it can be saved cleanly - * - * @param array $settings The settings request() array - * @return object stdClass object - */ - private function checkSettingType($settings) : \stdClass - { - $settings = (object)$settings; - $casts = CompanySettings::$casts; - - foreach ($casts as $key => $value){ + continue; + } - /*Separate loop if it is a _id field which is an integer cast as a string*/ - if(substr($key, -3) == '_id' || substr($key, -14) == 'number_counter'){ - $value = "integer"; - - if(!property_exists($settings, $key)){ - continue; - } - elseif($this->checkAttribute($value, $settings->{$key})){ + /* Handles unset settings or blank strings */ + if (!property_exists($settings, $key) || is_null($settings->{$key}) || !isset($settings->{$key}) || $settings->{$key} == '') { + continue; + } - if(substr($key, -3) == '_id') - settype($settings->{$key}, 'string'); - else - settype($settings->{$key}, $value); - - } - else { - unset($settings->{$key}); - } + /*Catch all filter */ + if ($this->checkAttribute($value, $settings->{$key})) { + if ($value == 'string' && is_null($settings->{$key})) { + $settings->{$key} = ''; + } - continue; - } + settype($settings->{$key}, $value); + } else { + unset($settings->{$key}); + } + } + return $settings; + } + - /* Handles unset settings or blank strings */ - if(!property_exists($settings, $key) || is_null($settings->{$key}) || !isset($settings->{$key}) || $settings->{$key} == ''){ - continue; - } - - /*Catch all filter */ - if($this->checkAttribute($value, $settings->{$key})){ - - if($value == 'string' && is_null($settings->{$key})) - $settings->{$key} = ''; - - settype($settings->{$key}, $value); - } - else { - unset($settings->{$key}); - } - - } - return $settings; - } - - - /** - * Type checks a object property. - * @param string $key The type - * @param string $value The object property - * @return bool TRUE if the property is the expected type - */ - private function checkAttribute($key, $value) :bool - { - switch ($key) - { - case 'int': - case 'integer': - return ctype_digit(strval($value)); - case 'real': - case 'float': - case 'double': - return is_float($value) || is_numeric(strval($value)); - case 'string': - return method_exists($value, '__toString' ) || is_null($value) || is_string($value); - case 'bool': - case 'boolean': - return is_bool($value) || (int) filter_var($value, FILTER_VALIDATE_BOOLEAN); - case 'object': - return is_object($value); - case 'array': - return is_array($value); - case 'json': - json_decode($string); - return (json_last_error() == JSON_ERROR_NONE); - default: - return false; - } - } - -} \ No newline at end of file + /** + * Type checks a object property. + * @param string $key The type + * @param string $value The object property + * @return bool TRUE if the property is the expected type + */ + private function checkAttribute($key, $value) :bool + { + switch ($key) { + case 'int': + case 'integer': + return ctype_digit(strval($value)); + case 'real': + case 'float': + case 'double': + return is_float($value) || is_numeric(strval($value)); + case 'string': + return method_exists($value, '__toString') || is_null($value) || is_string($value); + case 'bool': + case 'boolean': + return is_bool($value) || (int) filter_var($value, FILTER_VALIDATE_BOOLEAN); + case 'object': + return is_object($value); + case 'array': + return is_array($value); + case 'json': + json_decode($string); + return (json_last_error() == JSON_ERROR_NONE); + default: + return false; + } + } +} diff --git a/app/Utils/Traits/CompanyGatewayFeesAndLimitsSaver.php b/app/Utils/Traits/CompanyGatewayFeesAndLimitsSaver.php index 05c676fff4ef..85f2b614d4aa 100644 --- a/app/Utils/Traits/CompanyGatewayFeesAndLimitsSaver.php +++ b/app/Utils/Traits/CompanyGatewayFeesAndLimitsSaver.php @@ -20,90 +20,79 @@ use App\DataMapper\FeesAndLimits; */ trait CompanyGatewayFeesAndLimitsSaver { + public function validateFeesAndLimits($fees_and_limits) + { + $fees_and_limits = (object)$fees_and_limits; + $casts = FeesAndLimits::$casts; - public function validateFeesAndLimits($fees_and_limits) - { - $fees_and_limits = (object)$fees_and_limits; - $casts = FeesAndLimits::$casts; + foreach ($fees_and_limits as $fee_and_limit) { + $fee_and_limit = (object)$fee_and_limit; - foreach($fees_and_limits as $fee_and_limit) - { - - $fee_and_limit = (object)$fee_and_limit; - - foreach ($casts as $key => $value) - { + foreach ($casts as $key => $value) { - /* Handles unset settings or blank strings */ - if(!property_exists($fee_and_limit, $key) || is_null($fee_and_limit->{$key}) || !isset($fee_and_limit->{$key}) || $fee_and_limit->{$key} == '') - continue; - - /*Catch all filter */ - if(!$this->checkAttribute($value, $fee_and_limit->{$key})) - return [$key, $value]; - - } - - } + /* Handles unset settings or blank strings */ + if (!property_exists($fee_and_limit, $key) || is_null($fee_and_limit->{$key}) || !isset($fee_and_limit->{$key}) || $fee_and_limit->{$key} == '') { + continue; + } + + /*Catch all filter */ + if (!$this->checkAttribute($value, $fee_and_limit->{$key})) { + return [$key, $value]; + } + } + } - return true; - } + return true; + } - /** - * Type checks a object property. - * @param string $key The type - * @param string $value The object property - * @return bool TRUE if the property is the expected type - */ - private function checkAttribute($key, $value) :bool - { - switch ($key) - { - case 'int': - case 'integer': - return ctype_digit(strval($value)); - case 'real': - case 'float': - case 'double': - return is_float($value) || is_numeric(strval($value)); - case 'string': - return method_exists($value, '__toString' ) || is_null($value) || is_string($value); - case 'bool': - case 'boolean': - return is_bool($value) || (int) filter_var($value, FILTER_VALIDATE_BOOLEAN); - case 'object': - return is_object($value); - case 'array': - return is_array($value); - case 'json': - json_decode($string); - return (json_last_error() == JSON_ERROR_NONE); - default: - return false; - } - } + /** + * Type checks a object property. + * @param string $key The type + * @param string $value The object property + * @return bool TRUE if the property is the expected type + */ + private function checkAttribute($key, $value) :bool + { + switch ($key) { + case 'int': + case 'integer': + return ctype_digit(strval($value)); + case 'real': + case 'float': + case 'double': + return is_float($value) || is_numeric(strval($value)); + case 'string': + return method_exists($value, '__toString') || is_null($value) || is_string($value); + case 'bool': + case 'boolean': + return is_bool($value) || (int) filter_var($value, FILTER_VALIDATE_BOOLEAN); + case 'object': + return is_object($value); + case 'array': + return is_array($value); + case 'json': + json_decode($string); + return (json_last_error() == JSON_ERROR_NONE); + default: + return false; + } + } - public function cleanFeesAndLimits($fees_and_limits) - { - $new_arr = []; + public function cleanFeesAndLimits($fees_and_limits) + { + $new_arr = []; - foreach($fees_and_limits as $key => $value) - { + foreach ($fees_and_limits as $key => $value) { + $fal = new FeesAndLimits; - $fal = new FeesAndLimits; + foreach ($value as $k => $v) { + $fal->{$k} = $v; + } - foreach($value as $k => $v) - { - $fal->{$k} = $v; - } + $new_arr[$key] = (array)$fal; + } - $new_arr[$key] = (array)$fal; - - } - - return $new_arr; - - } - -} \ No newline at end of file + return $new_arr; + } +} diff --git a/app/Utils/Traits/CompanySettingsSaver.php b/app/Utils/Traits/CompanySettingsSaver.php index 4e56ad912abb..98e8420d1778 100644 --- a/app/Utils/Traits/CompanySettingsSaver.php +++ b/app/Utils/Traits/CompanySettingsSaver.php @@ -20,185 +20,178 @@ use App\DataMapper\CompanySettings; trait CompanySettingsSaver { - /** - * Saves a setting object - * - * Works for groups|clients|companies - * @param array $settings The request input settings array - * @param object $entity The entity which the settings belongs to - * @return void - */ - public function saveSettings($settings, $entity) - { + /** + * Saves a setting object + * + * Works for groups|clients|companies + * @param array $settings The request input settings array + * @param object $entity The entity which the settings belongs to + * @return void + */ + public function saveSettings($settings, $entity) + { + if (!$settings) { + return; + } - if(!$settings) - return; + //unset protected properties. + foreach (CompanySettings::$protected_fields as $field) { + unset($settings[$field]); + } - //unset protected properties. - foreach(CompanySettings::$protected_fields as $field) - unset($settings[$field]); + $settings = $this->checkSettingType($settings); - $settings = $this->checkSettingType($settings); + $company_settings = CompanySettings::defaults(); - $company_settings = CompanySettings::defaults(); + //Iterate and set CURRENT settings + // foreach($this->settings as $key => $value) + // $company_settings->{$key} = $value; - //Iterate and set CURRENT settings - // foreach($this->settings as $key => $value) - // $company_settings->{$key} = $value; + //Iterate and set NEW settings + foreach ($settings as $key => $value) { + if (is_null($settings->{$key})) { + $company_settings->{$key} = ''; + } else { + $company_settings->{$key} = $value; + } + } - //Iterate and set NEW settings - foreach($settings as $key => $value) { + $entity->settings = $company_settings; + $entity->save(); + } - if(is_null($settings->{$key})) - $company_settings->{$key} = ''; - else - $company_settings->{$key} = $value; - } + /** + * Used for custom validation of inbound + * settings request. + * + * Returns an array of errors, or boolean TRUE + * on successful validation + * @param array $settings The request() settings array + * @return array|bool Array on failure, boolean TRUE on success + */ + public function validateSettings($settings) + { + $settings = (object)$settings; + $casts = CompanySettings::$casts; - $entity->settings = $company_settings; - $entity->save(); - } + ksort($casts); - /** - * Used for custom validation of inbound - * settings request. - * - * Returns an array of errors, or boolean TRUE - * on successful validation - * @param array $settings The request() settings array - * @return array|bool Array on failure, boolean TRUE on success - */ - public function validateSettings($settings) - { - $settings = (object)$settings; - $casts = CompanySettings::$casts; + foreach ($casts as $key => $value) { - ksort($casts); + /*Separate loop if it is a _id field which is an integer cast as a string*/ + if (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter') { + $value = "integer"; + + if (!property_exists($settings, $key)) { + continue; + } elseif (!$this->checkAttribute($value, $settings->{$key})) { + return [$key, $value]; + } - foreach ($casts as $key => $value){ + continue; + } - /*Separate loop if it is a _id field which is an integer cast as a string*/ - if(substr($key, -3) == '_id' || substr($key, -14) == 'number_counter'){ - $value = "integer"; - - if(!property_exists($settings, $key)){ - continue; - } - else if(!$this->checkAttribute($value, $settings->{$key})){ - return [$key, $value]; - } + /* Handles unset settings or blank strings */ + if (!property_exists($settings, $key) || is_null($settings->{$key}) || !isset($settings->{$key}) || $settings->{$key} == '') { + continue; + } + - continue; - } + /*Catch all filter */ + if (!$this->checkAttribute($value, $settings->{$key})) { + return [$key, $value]; + } + } - /* Handles unset settings or blank strings */ - if(!property_exists($settings, $key) || is_null($settings->{$key}) || !isset($settings->{$key}) || $settings->{$key} == '') - continue; - + return true; + } - /*Catch all filter */ - if(!$this->checkAttribute($value, $settings->{$key})) - return [$key, $value]; - + /** + * Checks the settings object for + * correct property types. + * + * The method will drop invalid types from + * the object and will also settype() the property + * so that it can be saved cleanly + * + * @param array $settings The settings request() array + * @return object stdClass object + */ + private function checkSettingType($settings) : \stdClass + { + $settings = (object)$settings; + $casts = CompanySettings::$casts; + + foreach ($casts as $key => $value) { - } + /*Separate loop if it is a _id field which is an integer cast as a string*/ + if (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter') { + $value = "integer"; + + if (!property_exists($settings, $key)) { + continue; + } elseif ($this->checkAttribute($value, $settings->{$key})) { + if (substr($key, -3) == '_id') { + settype($settings->{$key}, 'string'); + } else { + settype($settings->{$key}, $value); + } + } else { + unset($settings->{$key}); + } - return true; - } + continue; + } - /** - * Checks the settings object for - * correct property types. - * - * The method will drop invalid types from - * the object and will also settype() the property - * so that it can be saved cleanly - * - * @param array $settings The settings request() array - * @return object stdClass object - */ - private function checkSettingType($settings) : \stdClass - { - $settings = (object)$settings; - $casts = CompanySettings::$casts; - - foreach ($casts as $key => $value){ + /* Handles unset settings or blank strings */ + if (!property_exists($settings, $key) || is_null($settings->{$key}) || !isset($settings->{$key}) || $settings->{$key} == '') { + continue; + } - /*Separate loop if it is a _id field which is an integer cast as a string*/ - if(substr($key, -3) == '_id' || substr($key, -14) == 'number_counter'){ - $value = "integer"; - - if(!property_exists($settings, $key)){ - continue; - } - elseif($this->checkAttribute($value, $settings->{$key})){ + /*Catch all filter */ + if ($this->checkAttribute($value, $settings->{$key})) { + if ($value == 'string' && is_null($settings->{$key})) { + $settings->{$key} = ''; + } - if(substr($key, -3) == '_id') - settype($settings->{$key}, 'string'); - else - settype($settings->{$key}, $value); - - } - else { - unset($settings->{$key}); - } + settype($settings->{$key}, $value); + } else { + unset($settings->{$key}); + } + } + return $settings; + } - continue; - } - - /* Handles unset settings or blank strings */ - if(!property_exists($settings, $key) || is_null($settings->{$key}) || !isset($settings->{$key}) || $settings->{$key} == ''){ - continue; - } - - /*Catch all filter */ - if($this->checkAttribute($value, $settings->{$key})){ - - if($value == 'string' && is_null($settings->{$key})) - $settings->{$key} = ''; - - settype($settings->{$key}, $value); - } - else { - unset($settings->{$key}); - } - - } - return $settings; - } - - /** - * Type checks a object property. - * @param string $key The type - * @param string $value The object property - * @return bool TRUE if the property is the expected type - */ - private function checkAttribute($key, $value) :bool - { - switch ($key) - { - case 'int': - case 'integer': - return ctype_digit(strval($value)); - case 'real': - case 'float': - case 'double': - return is_float($value) || is_numeric(strval($value)); - case 'string': - return method_exists($value, '__toString' ) || is_null($value) || is_string($value); - case 'bool': - case 'boolean': - return is_bool($value) || (int) filter_var($value, FILTER_VALIDATE_BOOLEAN); - case 'object': - return is_object($value); - case 'array': - return is_array($value); - case 'json': - json_decode($string); - return (json_last_error() == JSON_ERROR_NONE); - default: - return false; - } - } - -} \ No newline at end of file + /** + * Type checks a object property. + * @param string $key The type + * @param string $value The object property + * @return bool TRUE if the property is the expected type + */ + private function checkAttribute($key, $value) :bool + { + switch ($key) { + case 'int': + case 'integer': + return ctype_digit(strval($value)); + case 'real': + case 'float': + case 'double': + return is_float($value) || is_numeric(strval($value)); + case 'string': + return method_exists($value, '__toString') || is_null($value) || is_string($value); + case 'bool': + case 'boolean': + return is_bool($value) || (int) filter_var($value, FILTER_VALIDATE_BOOLEAN); + case 'object': + return is_object($value); + case 'array': + return is_array($value); + case 'json': + json_decode($string); + return (json_last_error() == JSON_ERROR_NONE); + default: + return false; + } + } +} diff --git a/app/Utils/Traits/GeneratesCounter.php b/app/Utils/Traits/GeneratesCounter.php index 1883b57686c2..7e9438aa9ef0 100644 --- a/app/Utils/Traits/GeneratesCounter.php +++ b/app/Utils/Traits/GeneratesCounter.php @@ -25,288 +25,269 @@ use Illuminate\Support\Carbon; */ trait GeneratesCounter { -//todo in the form validation, we need to ensure that if a prefix and pattern is set we throw a validation error, -//only one type is allow else this will cause confusion to the end user + //todo in the form validation, we need to ensure that if a prefix and pattern is set we throw a validation error, + //only one type is allow else this will cause confusion to the end user - /** - * Gets the next invoice number. - * - * @param \App\Models\Client $client The client - * - * @return string The next invoice number. - */ - public function getNextInvoiceNumber(Client $client) :string - { - //Reset counters if enabled - $this->resetCounters($client); + /** + * Gets the next invoice number. + * + * @param \App\Models\Client $client The client + * + * @return string The next invoice number. + */ + public function getNextInvoiceNumber(Client $client) :string + { + //Reset counters if enabled + $this->resetCounters($client); - //todo handle if we have specific client patterns in the future - $pattern = $client->getSetting('invoice_number_pattern'); - //Determine if we are using client_counters - if(strpos($pattern, 'clientCounter')) - { - $counter = $client->settings->invoice_number_counter; - $counter_entity = $client; - } - elseif(strpos($pattern, 'groupCounter')) - { - $counter = $client->group_settings->invoice_number_counter; - $counter_entity = $client->group_settings; - } - else - { - $counter = $client->company->settings->invoice_number_counter; - $counter_entity = $client->company; - } + //todo handle if we have specific client patterns in the future + $pattern = $client->getSetting('invoice_number_pattern'); + //Determine if we are using client_counters + if (strpos($pattern, 'clientCounter')) { + $counter = $client->settings->invoice_number_counter; + $counter_entity = $client; + } elseif (strpos($pattern, 'groupCounter')) { + $counter = $client->group_settings->invoice_number_counter; + $counter_entity = $client->group_settings; + } else { + $counter = $client->company->settings->invoice_number_counter; + $counter_entity = $client->company; + } - //Return a valid counter - $pattern = $client->getSetting('invoice_number_pattern'); - $padding = $client->getSetting('counter_padding'); - - $invoice_number = $this->checkEntityNumber(Invoice::class, $client, $counter, $padding, $pattern); + //Return a valid counter + $pattern = $client->getSetting('invoice_number_pattern'); + $padding = $client->getSetting('counter_padding'); + + $invoice_number = $this->checkEntityNumber(Invoice::class, $client, $counter, $padding, $pattern); - $this->incrementCounter($counter_entity, 'invoice_number_counter'); + $this->incrementCounter($counter_entity, 'invoice_number_counter'); - return $invoice_number; - } + return $invoice_number; + } - /** - * Gets the next credit number. - * - * @param \App\Models\Client $client The client - * - * @return string The next credit number. - */ - public function getNextCreditNumber(Client $client) :string - { - //Reset counters if enabled - $this->resetCounters($client); + /** + * Gets the next credit number. + * + * @param \App\Models\Client $client The client + * + * @return string The next credit number. + */ + public function getNextCreditNumber(Client $client) :string + { + //Reset counters if enabled + $this->resetCounters($client); - //todo handle if we have specific client patterns in the future - $pattern = $client->company->settings->credit_number_pattern; - $prefix = $client->company->settings->credit_number_pattern; - $padding = $client->company->settings->credit_number_pattern; + //todo handle if we have specific client patterns in the future + $pattern = $client->company->settings->credit_number_pattern; + $prefix = $client->company->settings->credit_number_pattern; + $padding = $client->company->settings->credit_number_pattern; - $credit_number = $this->checkEntityNumber(Credit::class, $client, $counter, $padding, $prefix, $pattern); + $credit_number = $this->checkEntityNumber(Credit::class, $client, $counter, $padding, $prefix, $pattern); - $this->incrementCounter($client->company, 'credit_number_counter'); + $this->incrementCounter($client->company, 'credit_number_counter'); - return $credit_number; - } + return $credit_number; + } - public function getNextQuoteNumber(Client $client) - { - //Reset counters if enabled - $this->resetCounters($client); + public function getNextQuoteNumber(Client $client) + { + //Reset counters if enabled + $this->resetCounters($client); - $used_counter = 'quote_number_counter'; + $used_counter = 'quote_number_counter'; - if($this->hasSharedCounter($client)) - $used_counter = 'invoice_number_counter'; + if ($this->hasSharedCounter($client)) { + $used_counter = 'invoice_number_counter'; + } - //todo handle if we have specific client patterns in the future - $pattern = $client->getSetting('quote_number_pattern'); - //Determine if we are using client_counters - if(strpos($pattern, 'clientCounter')) - { - $counter = $client->settings->{$used_counter}; - $counter_entity = $client; - } - elseif(strpos($pattern, 'groupCounter')) - { - $counter = $client->group_settings->{$used_counter}; - $counter_entity = $client->group_settings; - } - else - { - $counter = $client->company->settings->{$used_counter}; - $counter_entity = $client->company; - } + //todo handle if we have specific client patterns in the future + $pattern = $client->getSetting('quote_number_pattern'); + //Determine if we are using client_counters + if (strpos($pattern, 'clientCounter')) { + $counter = $client->settings->{$used_counter}; + $counter_entity = $client; + } elseif (strpos($pattern, 'groupCounter')) { + $counter = $client->group_settings->{$used_counter}; + $counter_entity = $client->group_settings; + } else { + $counter = $client->company->settings->{$used_counter}; + $counter_entity = $client->company; + } - //Return a valid counter - $pattern = $client->getSetting('quote_number_pattern'); - $padding = $client->getSetting('counter_padding'); - - $quote_number = $this->checkEntityNumber(Quote::class, $client, $counter, $padding, $pattern); + //Return a valid counter + $pattern = $client->getSetting('quote_number_pattern'); + $padding = $client->getSetting('counter_padding'); + + $quote_number = $this->checkEntityNumber(Quote::class, $client, $counter, $padding, $pattern); - $this->incrementCounter($counter_entity, $used_counter); + $this->incrementCounter($counter_entity, $used_counter); - return $quote_number; - } + return $quote_number; + } - public function getNextRecurringInvoiceNumber() - { + public function getNextRecurringInvoiceNumber() + { //Reset counters if enabled - $this->resetCounters($client); + $this->resetCounters($client); - $is_client_counter = false; + $is_client_counter = false; - //todo handle if we have specific client patterns in the future - $pattern = $client->company->settings->invoice_number_pattern; + //todo handle if we have specific client patterns in the future + $pattern = $client->company->settings->invoice_number_pattern; - //Determine if we are using client_counters - if(strpos($pattern, 'client_counter') === false) - { - $counter = $client->company->settings->invoice_number_counter; - } - else - { - $counter = $client->settings->invoice_number_counter; - $is_client_counter = true; - } + //Determine if we are using client_counters + if (strpos($pattern, 'client_counter') === false) { + $counter = $client->company->settings->invoice_number_counter; + } else { + $counter = $client->settings->invoice_number_counter; + $is_client_counter = true; + } - //Return a valid counter - $pattern = ''; - $padding = $client->getSetting('counter_padding'); - $invoice_number = $this->checkEntityNumber(Invoice::class, $client, $counter, $padding, $pattern); - $invoice_number = $this->prefixCounter($invoice_number, $client->getSetting('recurring_number_prefix')); + //Return a valid counter + $pattern = ''; + $padding = $client->getSetting('counter_padding'); + $invoice_number = $this->checkEntityNumber(Invoice::class, $client, $counter, $padding, $pattern); + $invoice_number = $this->prefixCounter($invoice_number, $client->getSetting('recurring_number_prefix')); - //increment the correct invoice_number Counter (company vs client) - if($is_client_counter) - $this->incrementCounter($client, 'invoice_number_counter'); - else - $this->incrementCounter($client->company, 'invoice_number_counter'); + //increment the correct invoice_number Counter (company vs client) + if ($is_client_counter) { + $this->incrementCounter($client, 'invoice_number_counter'); + } else { + $this->incrementCounter($client->company, 'invoice_number_counter'); + } - return $invoice_number; + return $invoice_number; + } - } - - /** - * Gets the next client number. - * - * @param \App\Models\Client $client The client - * - * @return string The next client number. - */ - public function getNextClientNumber(Client $client) :string - { + /** + * Gets the next client number. + * + * @param \App\Models\Client $client The client + * + * @return string The next client number. + */ + public function getNextClientNumber(Client $client) :string + { //Reset counters if enabled - $this->resetCounters($client); + $this->resetCounters($client); - $counter = $client->getSetting('client_number_counter' ); + $counter = $client->getSetting('client_number_counter'); $setting_entity = $client->getSettingEntity('client_number_counter'); - $client_number = $this->checkEntityNumber(Client::class, $client, $counter, $client->getSetting('counter_padding'), $client->getSetting('client_number_pattern')); + $client_number = $this->checkEntityNumber(Client::class, $client, $counter, $client->getSetting('counter_padding'), $client->getSetting('client_number_pattern')); - $this->incrementCounter($setting_entity, 'client_number_counter'); + $this->incrementCounter($setting_entity, 'client_number_counter'); - return $client_number; - } + return $client_number; + } - - /** - * Determines if it has shared counter. - * - * @param \App\Models\Client $client The client - * - * @return boolean True if has shared counter, False otherwise. - */ - public function hasSharedCounter(Client $client) : bool - { -// \Log::error((bool) $client->getSetting('shared_invoice_quote_counter')); -// \Log::error($client->getSetting('shared_invoice_quote_counter')); - return (bool) $client->getSetting('shared_invoice_quote_counter'); + + /** + * Determines if it has shared counter. + * + * @param \App\Models\Client $client The client + * + * @return boolean True if has shared counter, False otherwise. + */ + public function hasSharedCounter(Client $client) : bool + { + // \Log::error((bool) $client->getSetting('shared_invoice_quote_counter')); + // \Log::error($client->getSetting('shared_invoice_quote_counter')); + return (bool) $client->getSetting('shared_invoice_quote_counter'); + } - } + /** + * Checks that the number has not already been used + * + * @param Collection $entity The entity ie App\Models\Client, Invoice, Quote etc + * @param integer $counter The counter + * @param integer $padding The padding + * + * @return string The padded and prefixed invoice number + */ + private function checkEntityNumber($class, $client, $counter, $padding, $pattern) + { + $check = false; - /** - * Checks that the number has not already been used - * - * @param Collection $entity The entity ie App\Models\Client, Invoice, Quote etc - * @param integer $counter The counter - * @param integer $padding The padding - * - * @return string The padded and prefixed invoice number - */ - private function checkEntityNumber($class, $client, $counter, $padding, $pattern) - { - $check = false; + do { + $number = $this->padCounter($counter, $padding); - do { + $number = $this->applyNumberPattern($client, $number, $pattern); + + if ($class == Invoice::class || $class == RecurringInvoice::class) { + $check = $class::whereCompanyId($client->company_id)->whereNumber($number)->withTrashed()->first(); + } elseif ($class == Client::class) { + $check = $class::whereCompanyId($client->company_id)->whereIdNumber($number)->withTrashed()->first(); + } elseif ($class == Credit::class) { + $check = $class::whereCompanyId($client->company_id)->whereNumber($number)->withTrashed()->first(); + } elseif ($class == Quote::class) { + $check = $class::whereCompanyId($client->company_id)->whereNumber($number)->withTrashed()->first(); + } - $number = $this->padCounter($counter, $padding); - - $number = $this->applyNumberPattern($client, $number, $pattern); - - if($class == Invoice::class || $class == RecurringInvoice::class) - $check = $class::whereCompanyId($client->company_id)->whereNumber($number)->withTrashed()->first(); - elseif($class == Client::class) - $check = $class::whereCompanyId($client->company_id)->whereIdNumber($number)->withTrashed()->first(); - elseif($class == Credit::class) - $check = $class::whereCompanyId($client->company_id)->whereNumber($number)->withTrashed()->first(); - elseif($class == Quote::class) - $check = $class::whereCompanyId($client->company_id)->whereNumber($number)->withTrashed()->first(); - - $counter++; - - } while ($check); + $counter++; + } while ($check); return $number; - } + } - /** - * Saves counters at both the company and client level - * - * @param \App\Models\Client $client The client - * @param \App\Models\Client|integer|string $counter_name The counter name - */ - private function incrementCounter($entity, string $counter_name) :void - { - - $settings = $entity->settings; - $settings->$counter_name = $settings->$counter_name + 1; - $entity->settings = $settings; - $entity->save(); - - } - - private function prefixCounter($counter, $prefix) : string - { - - if(strlen($prefix) == 0) - return $counter; - - return $prefix . $counter; - - } - - /** - * Pads a number with leading 000000's - * - * @param int $counter The counter - * @param int $padding The padding - * - * @return int the padded counter - */ - private function padCounter($counter, $padding) :string - { - - return str_pad($counter, $padding, '0', STR_PAD_LEFT); - - } - - - /** - * If we are using counter reset, - * check if we need to reset here - * - * @param Client $client client entity - * @return void - */ - private function resetCounters(Client $client) + /** + * Saves counters at both the company and client level + * + * @param \App\Models\Client $client The client + * @param \App\Models\Client|integer|string $counter_name The counter name + */ + private function incrementCounter($entity, string $counter_name) :void { + $settings = $entity->settings; + $settings->$counter_name = $settings->$counter_name + 1; + $entity->settings = $settings; + $entity->save(); + } + private function prefixCounter($counter, $prefix) : string + { + if (strlen($prefix) == 0) { + return $counter; + } + + return $prefix . $counter; + } + + /** + * Pads a number with leading 000000's + * + * @param int $counter The counter + * @param int $padding The padding + * + * @return int the padded counter + */ + private function padCounter($counter, $padding) :string + { + return str_pad($counter, $padding, '0', STR_PAD_LEFT); + } + + + /** + * If we are using counter reset, + * check if we need to reset here + * + * @param Client $client client entity + * @return void + */ + private function resetCounters(Client $client) + { $timezone = Timezone::find($client->getSetting('timezone_id')); $reset_date = Carbon::parse($client->getSetting('reset_counter_date'), $timezone->name); - if (! $reset_date->isToday() || ! $client->getSetting('reset_counter_date')) + if (! $reset_date->isToday() || ! $client->getSetting('reset_counter_date')) { return false; + } switch ($client->company->reset_counter_frequency_id) { case RecurringInvoice::FREQUENCY_WEEKLY: @@ -363,9 +344,9 @@ trait GeneratesCounter */ private function applyNumberPattern(Client $client, string $counter, $pattern) :string { - - if(!$pattern) - return $counter; + if (!$pattern) { + return $counter; + } $search = ['{$year}']; $replace = [date('Y')]; @@ -410,9 +391,7 @@ trait GeneratesCounter $search[] = '{$id_number}'; $replace[] = $client->id_number; - + return str_replace($search, $replace, $pattern); - } - -} \ No newline at end of file +} diff --git a/app/Utils/Traits/Inviteable.php b/app/Utils/Traits/Inviteable.php index 1a9988e8096e..b4c580a5b722 100644 --- a/app/Utils/Traits/Inviteable.php +++ b/app/Utils/Traits/Inviteable.php @@ -19,52 +19,52 @@ trait Inviteable { - /** - * Gets the status. - * - * @return string The status. - */ - public function getStatus() : string - { - $status = ''; + /** + * Gets the status. + * + * @return string The status. + */ + public function getStatus() : string + { + $status = ''; - if(isset($this->sent_date)) - $status = ctrans('texts.invitation_status_sent'); + if (isset($this->sent_date)) { + $status = ctrans('texts.invitation_status_sent'); + } - if(isset($this->opened_date)) - $status = ctrans('texts.invitation_status_opened'); + if (isset($this->opened_date)) { + $status = ctrans('texts.invitation_status_opened'); + } - if(isset($this->viewed_date)) - $status = ctrans('texts.invitation_status_viewed'); + if (isset($this->viewed_date)) { + $status = ctrans('texts.invitation_status_viewed'); + } - return $status; - } + return $status; + } - public function getLink() : string - { - $entity_type = strtolower(class_basename($this->entityType())); + public function getLink() : string + { + $entity_type = strtolower(class_basename($this->entityType())); - //$this->with('company','contact',$this->entity_type); - $this->with('company'); + //$this->with('company','contact',$this->entity_type); + $this->with('company'); - $domain = isset($this->company->portal_domain) ?: $this->company->domain(); + $domain = isset($this->company->portal_domain) ?: $this->company->domain(); - switch ($this->company->portal_mode) { - case 'subdomain': - return $domain .'/client/'. $entity_type .'/'. $this->key; - break; - case 'iframe': - return $domain .'/client/'. $entity_type .'/'. $this->key; - //return $domain . $entity_type .'/'. $this->contact->client->client_hash .'/'. $this->key; - break; - case 'domain': - return $domain .'/client/'. $entity_type .'/'. $this->key; - break; + switch ($this->company->portal_mode) { + case 'subdomain': + return $domain .'/client/'. $entity_type .'/'. $this->key; + break; + case 'iframe': + return $domain .'/client/'. $entity_type .'/'. $this->key; + //return $domain . $entity_type .'/'. $this->contact->client->client_hash .'/'. $this->key; + break; + case 'domain': + return $domain .'/client/'. $entity_type .'/'. $this->key; + break; - } - - } - - -} \ No newline at end of file + } + } +} diff --git a/app/Utils/Traits/InvoiceEmailBuilder.php b/app/Utils/Traits/InvoiceEmailBuilder.php index e3f0612d7854..d93ae022d866 100644 --- a/app/Utils/Traits/InvoiceEmailBuilder.php +++ b/app/Utils/Traits/InvoiceEmailBuilder.php @@ -27,19 +27,19 @@ trait InvoiceEmailBuilder /** * Builds the correct template to send * @param string $reminder_template The template name ie reminder1 - * @return array + * @return array */ public function getEmailData($reminder_template = null, $contact = null) :array { //client //$client = $this->client; - if(!$reminder_template) + if (!$reminder_template) { $reminder_template = $this->calculateTemplate(); + } //Need to determine which email template we are producing return $this->generateTemplateData($reminder_template, $contact); - } private function generateTemplateData(string $reminder_template, $contact) :array @@ -51,26 +51,26 @@ trait InvoiceEmailBuilder $body_template = $client->getSetting('email_template_'.$reminder_template); /* Use default translations if a custom message has not been set*/ - if(iconv_strlen($body_template) == 0){ + if (iconv_strlen($body_template) == 0) { $body_template = trans('texts.invoice_message', ['amount'=>$this->present()->amount(),'account'=>$this->company->present()->name()], null, $this->client->locale()); } $subject_template = $client->getSetting('email_subject_'.$reminder_template); - if(iconv_strlen($subject_template) == 0){ - - if($reminder_template == 'invoice') + if (iconv_strlen($subject_template) == 0) { + if ($reminder_template == 'invoice') { $subject_template = trans('texts.invoice_subject', ['number'=>$this->present()->invoice_number(),'account'=>$this->company->present()->name()], null, $this->client->locale()); - else + } else { $subject_template = trans('texts.reminder_subject', ['number'=>$this->present()->invoice_number(),'account'=>$this->company->present()->name()], null, $this->client->locale()); - + } } $data['body'] = $this->parseTemplate($body_template, false, $contact); $data['subject'] = $this->parseTemplate($subject_template, true, $contact); - if($client->getSetting('pdf_email_attachment') !== false) + if ($client->getSetting('pdf_email_attachment') !== false) { $data['files'][] = $this->pdf_file_path(); + } return $data; } @@ -83,8 +83,9 @@ trait InvoiceEmailBuilder $data = str_replace(array_keys($invoice_variables), array_values($invoice_variables), $template_data); //process markdown - if($is_markdown) + if ($is_markdown) { $data = Parsedown::instance()->line($data); + } return $data; } @@ -94,29 +95,20 @@ trait InvoiceEmailBuilder //if invoice is currently a draft, or being marked as sent, this will be the initial email $client = $this->client; - //if the invoice - if($this->status_id == Invoice::STATUS_DRAFT || Carbon::parse($this->due_date) > now()) - { + //if the invoice + if ($this->status_id == Invoice::STATUS_DRAFT || Carbon::parse($this->due_date) > now()) { return 'invoice'; - } - else if($client->getSetting('enable_reminder1') !== false && $this->inReminderWindow($client->getSetting('schedule_reminder1'), $client->getSetting('num_days_reminder1'))) - { + } elseif ($client->getSetting('enable_reminder1') !== false && $this->inReminderWindow($client->getSetting('schedule_reminder1'), $client->getSetting('num_days_reminder1'))) { return 'template1'; - } - else if($client->getSetting('enable_reminder2') !== false && $this->inReminderWindow($client->getSetting('schedule_reminder2'), $client->getSetting('num_days_reminder2'))) - { + } elseif ($client->getSetting('enable_reminder2') !== false && $this->inReminderWindow($client->getSetting('schedule_reminder2'), $client->getSetting('num_days_reminder2'))) { return 'template2'; - } - else if($client->getSetting('enable_reminder3') !== false && $this->inReminderWindow($client->getSetting('schedule_reminder3'), $client->getSetting('num_days_reminder3'))) - { + } elseif ($client->getSetting('enable_reminder3') !== false && $this->inReminderWindow($client->getSetting('schedule_reminder3'), $client->getSetting('num_days_reminder3'))) { return 'template3'; - } - else + } else { return 'invoice'; + } //also implement endless reminders here - - } private function inReminderWindow($schedule_reminder, $num_days_reminder) @@ -136,5 +128,4 @@ trait InvoiceEmailBuilder break; } } - -} \ No newline at end of file +} diff --git a/app/Utils/Traits/MakesDates.php b/app/Utils/Traits/MakesDates.php index 623af46926c6..0bf0d554b03f 100644 --- a/app/Utils/Traits/MakesDates.php +++ b/app/Utils/Traits/MakesDates.php @@ -21,75 +21,65 @@ use Illuminate\Support\Facades\Log; trait MakesDates { - /** - * Converts from UTC to client timezone - * @param datetime object $utc_date - * @param string $timezone ie Australia/Sydney - * @return Carbon Carbon object - */ - public function createClientDate($utc_date , $timezone) - { - - if(is_string($utc_date)) - $utc_date = $this->convertToDateObject($utc_date); - - return $utc_date->setTimezone(new \DateTimeZone($timezone)); + /** + * Converts from UTC to client timezone + * @param datetime object $utc_date + * @param string $timezone ie Australia/Sydney + * @return Carbon Carbon object + */ + public function createClientDate($utc_date, $timezone) + { + if (is_string($utc_date)) { + $utc_date = $this->convertToDateObject($utc_date); + } + + return $utc_date->setTimezone(new \DateTimeZone($timezone)); + } - } + /** + * Converts from client timezone to UTC + * @param datetime object $utc_date + * @param string $timezone ie Australia/Sydney + * @return Carbon Carbon object + */ + public function createUtcDate($client_date) + { + if (is_string($client_date)) { + $client_date = $this->convertToDateObject($client_date); + } - /** - * Converts from client timezone to UTC - * @param datetime object $utc_date - * @param string $timezone ie Australia/Sydney - * @return Carbon Carbon object - */ - public function createUtcDate($client_date) - { + return $client_date->setTimezone(new \DateTimeZone('GMT')); + } - if(is_string($client_date)) - $client_date = $this->convertToDateObject($client_date); + /** + * Formats a date + * @param Carbon/String $date Carbon object or date string + * @param string $format The date display format + * @return string The formatted date + */ + public function formatDate($date, string $format) :string + { + if (is_string($date)) { + $date = $this->convertToDateObject($date); + } - return $client_date->setTimezone(new \DateTimeZone('GMT')); - - } - - /** - * Formats a date - * @param Carbon/String $date Carbon object or date string - * @param string $format The date display format - * @return string The formatted date - */ - public function formatDate($date, string $format) :string - { - - if(is_string($date)) - $date = $this->convertToDateObject($date); - - return $date->format($format); - - } + return $date->format($format); + } - /** - * Formats a date - * @param Carbon/String $date Carbon object or date string - * @param string $format The date display format - * @return string The formatted date - */ - public function formatDateTimestamp($timestamp, string $format) :string - { - - return Carbon::createFromTimestamp($timestamp)->format($format); + /** + * Formats a date + * @param Carbon/String $date Carbon object or date string + * @param string $format The date display format + * @return string The formatted date + */ + public function formatDateTimestamp($timestamp, string $format) :string + { + return Carbon::createFromTimestamp($timestamp)->format($format); + } - } - - private function convertToDateObject($date) - { - - return new \DateTime($date); - - } - - - -} \ No newline at end of file + private function convertToDateObject($date) + { + return new \DateTime($date); + } +} diff --git a/app/Utils/Traits/MakesHash.php b/app/Utils/Traits/MakesHash.php index d59b4ce1eab2..a32000ceb17f 100644 --- a/app/Utils/Traits/MakesHash.php +++ b/app/Utils/Traits/MakesHash.php @@ -31,7 +31,7 @@ trait MakesHash /** * Creates a simple alphanumeric Hash which is prepended with a encoded database prefix - * + * * @param $db - Full database name * @return string 01-asfas8df76a78f6a78dfsdf */ @@ -48,7 +48,7 @@ trait MakesHash { $hashids = new Hashids('', 10); - return $hashids->encode( str_replace( MultiDB::DB_PREFIX, "", $db ) ); + return $hashids->encode(str_replace(MultiDB::DB_PREFIX, "", $db)); } public function encodePrimaryKey($value) : string @@ -60,33 +60,27 @@ trait MakesHash public function decodePrimaryKey($value) : string { - try{ + try { $hashids = new Hashids('', 10); $decoded_array = $hashids->decode($value); return $decoded_array[0]; - } - catch(\Exception $e) - { - return response()->json(['error'=>'Invalid primary key'],400); + } catch (\Exception $e) { + return response()->json(['error'=>'Invalid primary key'], 400); } } public function transformKeys($keys) { - - if(is_array($keys)) - { - foreach($keys as &$value) - { - $value = $this->decodePrimaryKey($value); + if (is_array($keys)) { + foreach ($keys as &$value) { + $value = $this->decodePrimaryKey($value); } return $keys; - } - else + } else { return $this->decodePrimaryKey($keys); - + } } -} \ No newline at end of file +} diff --git a/app/Utils/Traits/MakesHeaderData.php b/app/Utils/Traits/MakesHeaderData.php index 6b0f844816c7..d94b2515a712 100644 --- a/app/Utils/Traits/MakesHeaderData.php +++ b/app/Utils/Traits/MakesHeaderData.php @@ -11,14 +11,12 @@ namespace App\Utils\Traits; - /** * Class MakesHeaderData * @package App\Utils\Traits */ trait MakesHeaderData { - use UserSessionAttributes; /** @@ -29,15 +27,14 @@ trait MakesHeaderData //companies $companies = auth()->user()->companies; - $data['current_company'] = $companies->first(function ($company){ + $data['current_company'] = $companies->first(function ($company) { return $company->id == auth()->user()->company()->id; }); - $data['companies'] = $companies->reject(function ($company){ + $data['companies'] = $companies->reject(function ($company) { return $company->id == auth()->user()->company()->id; }); return $data; } - -} \ No newline at end of file +} diff --git a/app/Utils/Traits/MakesInvoiceHtml.php b/app/Utils/Traits/MakesInvoiceHtml.php index 9f00db7d1a40..b385dc86b396 100644 --- a/app/Utils/Traits/MakesInvoiceHtml.php +++ b/app/Utils/Traits/MakesInvoiceHtml.php @@ -14,7 +14,6 @@ namespace App\Utils\Traits; use Illuminate\Support\Facades\Blade; use Symfony\Component\Debug\Exception\FatalThrowableError; - /** * Class MakesInvoiceHtml. */ @@ -22,20 +21,19 @@ trait MakesInvoiceHtml { /** - * Generate the HTML invoice parsing variables + * Generate the HTML invoice parsing variables * and generating the final invoice HTML - * + * * @param string $design either the path to the design template, OR the full design template string * @param Collection $invoice The invoice object - * + * * @return string The invoice string in HTML format */ public function generateInvoiceHtml($design, $invoice) :string { - $variables = array_merge($invoice->makeLabels(), $invoice->makeValues()); - // uasort($variables, 'arraySort'); + // uasort($variables, 'arraySort'); $design = str_replace(array_keys($variables), array_values($variables), $design); @@ -44,21 +42,20 @@ trait MakesInvoiceHtml return $this->renderView($design, $data); //return view($design, $data)->render(); - } /** * Parses the blade file string and processes the template variables - * + * * @param string $string The Blade file string * @param array $data The array of template variables * @return string The return HTML string - * + * */ public function renderView($string, $data) :string { if (!$data) { - $data = []; + $data = []; } $data['__env'] = app(\Illuminate\View\Factory::class); @@ -87,5 +84,4 @@ trait MakesInvoiceHtml return ob_get_clean(); } - -} \ No newline at end of file +} diff --git a/app/Utils/Traits/MakesInvoiceValues.php b/app/Utils/Traits/MakesInvoiceValues.php index a439cc024ca2..9039b39c26b1 100644 --- a/app/Utils/Traits/MakesInvoiceValues.php +++ b/app/Utils/Traits/MakesInvoiceValues.php @@ -20,11 +20,11 @@ use App\Utils\Number; */ trait MakesInvoiceValues { - /** - * Master list of columns used - * for invoice tables - * @var array - */ + /** + * Master list of columns used + * for invoice tables + * @var array + */ private static $master_columns = [ 'date', 'discount', @@ -46,7 +46,7 @@ trait MakesInvoiceValues * Master list of invoice labels * @var array */ - private static $labels = [ + private static $labels = [ 'date', 'due_date', 'invoice_number', @@ -130,34 +130,35 @@ trait MakesInvoiceValues 'amount_paid', ]; - /** + /** * Iterates and translates all labels * - * @return array returns an array of + * @return array returns an array of * keyed labels (appended with _label) */ public function makeLabels() :array { //todo we might want to translate like this //trans('texts.labe', [], null, $this->client->locale()); - $data = []; + $data = []; - foreach(self::$labels as $label) - $data['$'.$label . '_label'] = ctrans('texts.'.$label); + foreach (self::$labels as $label) { + $data['$'.$label . '_label'] = ctrans('texts.'.$label); + } - return $data; - } + return $data; + } - /** - * Transforms all placeholders + /** + * Transforms all placeholders * to invoice values - * - * @return array returns an array + * + * @return array returns an array * of keyed labels (appended with _label) */ public function makeValues($contact = null) :array { - if(!$this->client->currency() || !$this->client){ + if (!$this->client->currency() || !$this->client) { throw new Exception(debug_backtrace()[1]['function'], 1); exit; } @@ -166,142 +167,141 @@ trait MakesInvoiceValues $data = []; - $data['$date'] = $this->date; - $data['$invoice.date'] = &$data['$date']; - $data['$due_date'] = $this->due_date; - $data['$invoice.due_date'] = &$data['$due_date']; - $data['$number'] = $this->number; - $data['$invoice.number'] = &$data['$number']; - $data['$po_number'] = $this->po_number; - $data['$invoice.po_number'] = &$data['$po_number']; - $data['$line_taxes'] = $this->makeLineTaxes(); - $data['$invoice.line_taxes'] = &$data['$line_taxes']; - $data['$total_taxes'] = $this->makeTotalTaxes(); - $data['$invoice.total_taxes'] = &$data['$total_taxes']; - // $data['$tax'] = ; - // $data['$item'] = ; - // $data['$description'] = ; - // $data['$unit_cost'] = ; - // $data['$quantity'] = ; - // $data['$line_total'] = ; - // $data['$paid_to_date'] = ; - $data['$discount'] = Number::formatMoney($this->calc()->getTotalDiscount(), $this->client); - $data['$invoice.discount'] = &$data['$discount']; - $data['$subtotal'] = Number::formatMoney($this->calc()->getSubTotal(), $this->client); - $data['$invoice.subtotal'] = &$data['$subtotal']; - $data['$balance_due'] = Number::formatMoney($this->balance, $this->client); - $data['$invoice.balance_due'] = &$data['$balance_due']; - $data['$partial_due'] = Number::formatMoney($this->partial, $this->client); - $data['$invoice.partial_due'] = &$data['$partial_due']; - $data['$total'] = Number::formatMoney($this->calc()->getTotal(), $this->client); - $data['$invoice.total'] = &$data['$total']; - $data['$amount'] = &$data['$total']; - $data['$invoice.amount'] = &$data['$total']; + $data['$date'] = $this->date; + $data['$invoice.date'] = &$data['$date']; + $data['$due_date'] = $this->due_date; + $data['$invoice.due_date'] = &$data['$due_date']; + $data['$number'] = $this->number; + $data['$invoice.number'] = &$data['$number']; + $data['$po_number'] = $this->po_number; + $data['$invoice.po_number'] = &$data['$po_number']; + $data['$line_taxes'] = $this->makeLineTaxes(); + $data['$invoice.line_taxes'] = &$data['$line_taxes']; + $data['$total_taxes'] = $this->makeTotalTaxes(); + $data['$invoice.total_taxes'] = &$data['$total_taxes']; + // $data['$tax'] = ; + // $data['$item'] = ; + // $data['$description'] = ; + // $data['$unit_cost'] = ; + // $data['$quantity'] = ; + // $data['$line_total'] = ; + // $data['$paid_to_date'] = ; + $data['$discount'] = Number::formatMoney($this->calc()->getTotalDiscount(), $this->client); + $data['$invoice.discount'] = &$data['$discount']; + $data['$subtotal'] = Number::formatMoney($this->calc()->getSubTotal(), $this->client); + $data['$invoice.subtotal'] = &$data['$subtotal']; + $data['$balance_due'] = Number::formatMoney($this->balance, $this->client); + $data['$invoice.balance_due'] = &$data['$balance_due']; + $data['$partial_due'] = Number::formatMoney($this->partial, $this->client); + $data['$invoice.partial_due'] = &$data['$partial_due']; + $data['$total'] = Number::formatMoney($this->calc()->getTotal(), $this->client); + $data['$invoice.total'] = &$data['$total']; + $data['$amount'] = &$data['$total']; + $data['$invoice.amount'] = &$data['$total']; - $data['$balance'] = Number::formatMoney($this->calc()->getBalance(), $this->client); - $data['$invoice.balance'] = &$data['$balance']; - $data['$taxes'] = Number::formatMoney($this->calc()->getItemTotalTaxes(), $this->client); - $data['$invoice.taxes'] = &$data['$taxes']; - $data['$terms'] = $this->terms; - $data['$invoice.terms'] = &$data['$terms']; - // $data['$your_invoice'] = ; - // $data['$quote'] = ; - // $data['$your_quote'] = ; - // $data['$quote_date'] = ; - // $data['$quote_number'] = ; - // $data['$invoice_issued_to'] = ; - // $data['$quote_issued_to'] = ; - // $data['$rate'] = ; - // $data['$hours'] = ; - // $data['$from'] = ; - // $data['$to'] = ; - // $data['$invoice_to'] = ; - // $data['$quote_to'] = ; - // $data['$details'] = ; - $data['$invoice_no'] = $this->number; - $data['$invoice.invoice_no'] = &$data['$invoice_no']; - // $data['$quote_no'] = ; - // $data['$valid_until'] = ; - $data['$client_name'] = $this->present()->clientName(); - $data['$client.name'] = &$data['$client_name']; - $data['$client_address'] = $this->present()->address(); - $data['$client.address'] = &$data['$client_address']; - $data['$address1'] = $this->client->address1; - $data['$client.address1'] = &$data['$address1']; - $data['$address2'] = $this->client->address2; - $data['$client.address2'] = &$data['$address2']; - $data['$id_number'] = $this->client->id_number; - $data['$client.id_number'] = &$data['$id_number']; - $data['$vat_number'] = $this->client->vat_number; - $data['$client.vat_number'] = &$data['$vat_number']; - $data['$website'] = $this->client->present()->website(); - $data['$client.website'] = &$data['$website']; - $data['$phone'] = $this->client->present()->phone(); - $data['$client.phone'] = &$data['$phone']; - $data['$city_state_postal'] = $this->present()->cityStateZip($this->client->city, $this->client->state, $this->client->postal_code, FALSE); - $data['$client.city_state_postal'] = &$data['$city_state_postal']; - $data['$postal_city_state'] = $this->present()->cityStateZip($this->client->city, $this->client->state, $this->client->postal_code, TRUE); - $data['$client.postal_city_state'] = &$data['$postal_city_state']; - $data['$country'] = isset($this->client->country->name) ?: 'No Country Set'; - $data['$client.country'] = &$data['$country']; - $data['$email'] = isset($this->client->primary_contact()->first()->email) ?: 'no contact email on record'; - $data['$client.email'] = &$data['$email']; + $data['$balance'] = Number::formatMoney($this->calc()->getBalance(), $this->client); + $data['$invoice.balance'] = &$data['$balance']; + $data['$taxes'] = Number::formatMoney($this->calc()->getItemTotalTaxes(), $this->client); + $data['$invoice.taxes'] = &$data['$taxes']; + $data['$terms'] = $this->terms; + $data['$invoice.terms'] = &$data['$terms']; + // $data['$your_invoice'] = ; + // $data['$quote'] = ; + // $data['$your_quote'] = ; + // $data['$quote_date'] = ; + // $data['$quote_number'] = ; + // $data['$invoice_issued_to'] = ; + // $data['$quote_issued_to'] = ; + // $data['$rate'] = ; + // $data['$hours'] = ; + // $data['$from'] = ; + // $data['$to'] = ; + // $data['$invoice_to'] = ; + // $data['$quote_to'] = ; + // $data['$details'] = ; + $data['$invoice_no'] = $this->number; + $data['$invoice.invoice_no'] = &$data['$invoice_no']; + // $data['$quote_no'] = ; + // $data['$valid_until'] = ; + $data['$client_name'] = $this->present()->clientName(); + $data['$client.name'] = &$data['$client_name']; + $data['$client_address'] = $this->present()->address(); + $data['$client.address'] = &$data['$client_address']; + $data['$address1'] = $this->client->address1; + $data['$client.address1'] = &$data['$address1']; + $data['$address2'] = $this->client->address2; + $data['$client.address2'] = &$data['$address2']; + $data['$id_number'] = $this->client->id_number; + $data['$client.id_number'] = &$data['$id_number']; + $data['$vat_number'] = $this->client->vat_number; + $data['$client.vat_number'] = &$data['$vat_number']; + $data['$website'] = $this->client->present()->website(); + $data['$client.website'] = &$data['$website']; + $data['$phone'] = $this->client->present()->phone(); + $data['$client.phone'] = &$data['$phone']; + $data['$city_state_postal'] = $this->present()->cityStateZip($this->client->city, $this->client->state, $this->client->postal_code, false); + $data['$client.city_state_postal'] = &$data['$city_state_postal']; + $data['$postal_city_state'] = $this->present()->cityStateZip($this->client->city, $this->client->state, $this->client->postal_code, true); + $data['$client.postal_city_state'] = &$data['$postal_city_state']; + $data['$country'] = isset($this->client->country->name) ?: 'No Country Set'; + $data['$client.country'] = &$data['$country']; + $data['$email'] = isset($this->client->primary_contact()->first()->email) ?: 'no contact email on record'; + $data['$client.email'] = &$data['$email']; - if($contact) { + if ($contact) { $data['$contact_name'] = $contact->present()->name(); $data['$contact.name'] = &$data['$contact_name']; - } - else { + } else { $data['$contact_name'] = $this->client->present()->primary_contact_name(); $data['$contact.name'] = &$data['$contact_name']; - } + } - $data['$company.name'] = $this->company->present()->name(); - $data['$company.address1'] = $settings->address1; - $data['$company.address2'] = $settings->address2; - $data['$company.city'] = $settings->city; - $data['$company.state'] = $settings->state; - $data['$company.postal_code'] = $settings->postal_code; - $data['$company.country'] = Country::find($settings->country_id)->first()->name; - $data['$company.phone'] = $settings->phone; - $data['$company.email'] = $settings->email; - $data['$company.vat_number'] = $settings->vat_number; - $data['$company.id_number'] = $settings->id_number; - $data['$company.address'] = $this->company->present()->address($settings); - $data['$company.logo'] = $this->company->present()->logo($settings); - //$data['$blank'] = ; - //$data['$surcharge'] = ; - /* - $data['$tax_invoice'] = - $data['$tax_quote'] = - $data['$statement'] = ; - $data['$statement_date'] = ; - $data['$your_statement'] = ; - $data['$statement_issued_to'] = ; - $data['$statement_to'] = ; - $data['$credit_note'] = ; - $data['$credit_date'] = ; - $data['$credit_number'] = ; - $data['$credit_issued_to'] = ; - $data['$credit_to'] = ; - $data['$your_credit'] = ; - $data['$phone'] = ; - $data['$invoice_total'] = ; - $data['$outstanding'] = ; - $data['$invoice_due_date'] = ; - $data['$quote_due_date'] = ; - $data['$service'] = ; - $data['$product_key'] = ; - $data['$unit_cost'] = ; - $data['$custom_value1'] = ; - $data['$custom_value2'] = ; - $data['$delivery_note'] = ; - $data['$date'] = ; - $data['$method'] = ; - $data['$payment_date'] = ; - $data['$reference'] = ; - $data['$amount'] = ; - $data['$amount_paid'] =; + $data['$company.name'] = $this->company->present()->name(); + $data['$company.address1'] = $settings->address1; + $data['$company.address2'] = $settings->address2; + $data['$company.city'] = $settings->city; + $data['$company.state'] = $settings->state; + $data['$company.postal_code'] = $settings->postal_code; + $data['$company.country'] = Country::find($settings->country_id)->first()->name; + $data['$company.phone'] = $settings->phone; + $data['$company.email'] = $settings->email; + $data['$company.vat_number'] = $settings->vat_number; + $data['$company.id_number'] = $settings->id_number; + $data['$company.address'] = $this->company->present()->address($settings); + $data['$company.logo'] = $this->company->present()->logo($settings); + //$data['$blank'] = ; + //$data['$surcharge'] = ; + /* + $data['$tax_invoice'] = + $data['$tax_quote'] = + $data['$statement'] = ; + $data['$statement_date'] = ; + $data['$your_statement'] = ; + $data['$statement_issued_to'] = ; + $data['$statement_to'] = ; + $data['$credit_note'] = ; + $data['$credit_date'] = ; + $data['$credit_number'] = ; + $data['$credit_issued_to'] = ; + $data['$credit_to'] = ; + $data['$your_credit'] = ; + $data['$phone'] = ; + $data['$invoice_total'] = ; + $data['$outstanding'] = ; + $data['$invoice_due_date'] = ; + $data['$quote_due_date'] = ; + $data['$service'] = ; + $data['$product_key'] = ; + $data['$unit_cost'] = ; + $data['$custom_value1'] = ; + $data['$custom_value2'] = ; + $data['$delivery_note'] = ; + $data['$date'] = ; + $data['$method'] = ; + $data['$payment_date'] = ; + $data['$reference'] = ; + $data['$amount'] = ; + $data['$amount_paid'] =; */ return $data; } @@ -310,40 +310,36 @@ trait MakesInvoiceValues * Returns a formatted HTML table of invoice line items * * @param array $columns The columns to be displayed - * + * * @return string[HTML string */ public function table(array $columns) :?string { - - $data = ''; - $data .= ''; + $data = '
'; + $data .= ''; $column_headers = $this->transformColumnsForHeader($columns); - foreach($column_headers as $column) - $data .= ''; + foreach ($column_headers as $column) { + $data .= ''; + } - $data .= ''; + $data .= ''; - $columns = $this->transformColumnsForLineItems($columns); + $columns = $this->transformColumnsForLineItems($columns); - $items = $this->transformLineItems($this->line_items); + $items = $this->transformLineItems($this->line_items); - foreach($items as $item) - { + foreach ($items as $item) { + $data .= ''; - $data .= ''; + foreach ($columns as $column) { + $data .= ''; + } + $data .= ''; + } - foreach($columns as $column) - { - $data .= ''; - } - $data .= ''; - - } - - $data .= '
' . ctrans('texts.'.$column.'') . '' . ctrans('texts.'.$column.'') . '
'. $item->{$column} . '
'. $item->{$column} . '
'; + $data .= ''; return $data; } @@ -351,32 +347,32 @@ trait MakesInvoiceValues /** * Transform the column headers into translated header values - * + * * @param array $columns The column header values * @return array The new column header variables */ private function transformColumnsForHeader(array $columns) :array { - $pre_columns = $columns; $columns = array_intersect($columns, self::$master_columns); - return str_replace([ + return str_replace( + [ 'tax_name1', 'tax_name2' - ], + ], [ 'tax', 'tax', - ], - $columns); - + ], + $columns + ); } /** - * + * * Transform the column headers into invoice variables - * + * * @param array $columns The column header values * @return array The invoice variables */ @@ -385,24 +381,25 @@ trait MakesInvoiceValues /* Removes any invalid columns the user has entered. */ $columns = array_intersect($columns, self::$master_columns); - return str_replace([ - 'custom_invoice_label1', - 'custom_invoice_label2', - 'custom_invoice_label3', - 'custom_invoice_label4', - 'tax_name1', - 'tax_name2' - ], - [ + return str_replace( + [ + 'custom_invoice_label1', + 'custom_invoice_label2', + 'custom_invoice_label3', + 'custom_invoice_label4', + 'tax_name1', + 'tax_name2' + ], + [ 'custom_invoice_value1', 'custom_invoice_value2', 'custom_invoice_value3', 'custom_invoice_value4', 'tax_rate1', 'tax_rate2' - ], - $columns); - + ], + $columns + ); } /** @@ -412,46 +409,39 @@ trait MakesInvoiceValues */ private function transformLineItems(array $items) :array { - - foreach($items as $item) - { - + foreach ($items as $item) { $item->cost = Number::formatMoney($item->cost, $this->client); $item->line_total = Number::formatMoney($item->line_total, $this->client); - if(isset($item->discount) && $item->discount > 0) - { - - if($item->is_amount_discount) + if (isset($item->discount) && $item->discount > 0) { + if ($item->is_amount_discount) { $item->discount = Number::formatMoney($item->discount, $this->client); - else + } else { $item->discount = $item->discount . '%'; + } } - } - return $items; + return $items; } /** - * Due to the way we are compiling the blade template we + * Due to the way we are compiling the blade template we * have no ability to iterate, so in the case - * of line taxes where there are multiple rows, + * of line taxes where there are multiple rows, * we use this function to format a section of rows - * - * @return string a collection of rows with line item + * + * @return string a collection of rows with line item * aggregate data */ private function makeLineTaxes() :string { - $tax_map = $this->calc()->getTaxMap(); $data = ''; - foreach($tax_map as $tax) - { + foreach ($tax_map as $tax) { $data .= ''; $data .= ''. $tax['name'] .''; $data .= ''. Number::formatMoney($tax['total'], $this->client) .''; @@ -461,26 +451,24 @@ trait MakesInvoiceValues } /** - * @return string a collectino of with + * @return string a collectino of with * itemised total tax data */ private function makeTotalTaxes() :string { - $data = ''; - if(!$this->calc()->getTotalTaxMap()) + if (!$this->calc()->getTotalTaxMap()) { return $data; + } - foreach($this->calc()->getTotalTaxMap() as $tax) - { + foreach ($this->calc()->getTotalTaxMap() as $tax) { $data .= ''; $data .= ''. $tax['name'] .''; $data .= ''. Number::formatMoney($tax['total'], $this->client) .''; } return $data; - } -} \ No newline at end of file +} diff --git a/app/Utils/Traits/MakesMenu.php b/app/Utils/Traits/MakesMenu.php index bf387e779704..9a2c52ea4ecc 100644 --- a/app/Utils/Traits/MakesMenu.php +++ b/app/Utils/Traits/MakesMenu.php @@ -19,38 +19,32 @@ use Nwidart\Modules\Facades\Module; */ trait MakesMenu { - - /** - * Builds an array of available modules for this view - * @param string $entity Class name - * @return array of modules - */ - public function makeEntityTabMenu(string $entity) : array - { - + + /** + * Builds an array of available modules for this view + * @param string $entity Class name + * @return array of modules + */ + public function makeEntityTabMenu(string $entity) : array + { $tabs = []; - foreach (Module::getCached() as $module) - { - if(!$module['sidebar'] + foreach (Module::getCached() as $module) { + if (!$module['sidebar'] && $module['active'] == 1 - && in_array( strtolower( class_basename($entity) ), $module['views'])) - { + && in_array(strtolower(class_basename($entity)), $module['views'])) { $tabs[] = $module; - } - } + } + } - return $tabs; + return $tabs; + } - } - - /** - * Builds an array items to be presented on the sidebar - * @return array menu items - */ - public function makeSideBarMenu() - { - - } - -} \ No newline at end of file + /** + * Builds an array items to be presented on the sidebar + * @return array menu items + */ + public function makeSideBarMenu() + { + } +} diff --git a/app/Utils/Traits/MakesReminders.php b/app/Utils/Traits/MakesReminders.php index 1c694b9ef518..9dce452e0581 100644 --- a/app/Utils/Traits/MakesReminders.php +++ b/app/Utils/Traits/MakesReminders.php @@ -18,14 +18,13 @@ use Illuminate\Support\Carbon; */ trait MakesReminders { - public function setReminder($settings = null) { - if(!$settings) + if (!$settings) { $settings = $this->client->getMergedSettings(); + } - if(!$this->isPayable()) - { + if (!$this->isPayable()) { $this->next_send_date = null; $this->save(); return; //exit early @@ -33,133 +32,136 @@ trait MakesReminders $nsd = null; - if($settings->enable_reminder1 !== false && + if ($settings->enable_reminder1 !== false && $settings->schedule_reminder1 == 'after_invoice_date' && - $settings->num_days_reminder1 > 0) - { + $settings->num_days_reminder1 > 0) { $reminder_date = Carbon::parse($this->date)->addDays($settings->num_days_reminder1); - if(!$nsd) + if (!$nsd) { $nsd = $reminder_date; + } - if($reminder_date->lt($nsd)) + if ($reminder_date->lt($nsd)) { $nsd = $reminder_date; - + } } - if($settings->enable_reminder1 !== false && + if ($settings->enable_reminder1 !== false && $settings->schedule_reminder1 == 'before_due_date' && - $settings->num_days_reminder1 > 0) - { + $settings->num_days_reminder1 > 0) { $reminder_date = Carbon::parse($this->due_date)->subDays($settings->num_days_reminder1); - if(!$nsd) + if (!$nsd) { $nsd = $reminder_date; + } - if($reminder_date->lt($nsd)) + if ($reminder_date->lt($nsd)) { $nsd = $reminder_date; + } } - if($settings->enable_reminder1 !== false && + if ($settings->enable_reminder1 !== false && $settings->schedule_reminder1 == 'after_due_date' && - $settings->num_days_reminder1 > 0) - { + $settings->num_days_reminder1 > 0) { $reminder_date = Carbon::parse($this->due_date)->addDays($settings->num_days_reminder1); - if(!$nsd) + if (!$nsd) { $nsd = $reminder_date; + } - if($reminder_date->lt($nsd)) + if ($reminder_date->lt($nsd)) { $nsd = $reminder_date; + } } - if($settings->enable_reminder2 !== false && + if ($settings->enable_reminder2 !== false && $settings->schedule_reminder2 == 'after_invoice_date' && - $settings->num_days_reminder2 > 0) - { + $settings->num_days_reminder2 > 0) { $reminder_date = Carbon::parse($this->date)->addDays($settings->num_days_reminder2); - if(!$nsd) + if (!$nsd) { $nsd = $reminder_date; + } - if($reminder_date->lt($nsd)) + if ($reminder_date->lt($nsd)) { $nsd = $reminder_date; - + } } - if($settings->enable_reminder2 !== false && + if ($settings->enable_reminder2 !== false && $settings->schedule_reminder2 == 'before_due_date' && - $settings->num_days_reminder2 > 0) - { + $settings->num_days_reminder2 > 0) { $reminder_date = Carbon::parse($this->due_date)->subDays($settings->num_days_reminder2); - if(!$nsd) + if (!$nsd) { $nsd = $reminder_date; + } - if($reminder_date->lt($nsd)) + if ($reminder_date->lt($nsd)) { $nsd = $reminder_date; + } } - if($settings->enable_reminder2 !== false && + if ($settings->enable_reminder2 !== false && $settings->schedule_reminder2 == 'after_due_date' && - $settings->num_days_reminder2 > 0) - { + $settings->num_days_reminder2 > 0) { $reminder_date = Carbon::parse($this->due_date)->addDays($settings->num_days_reminder2); - if(!$nsd) + if (!$nsd) { $nsd = $reminder_date; + } - if($reminder_date->lt($nsd)) + if ($reminder_date->lt($nsd)) { $nsd = $reminder_date; + } } - if($settings->enable_reminder3 !== false && + if ($settings->enable_reminder3 !== false && $settings->schedule_reminder3 == 'after_invoice_date' && - $settings->num_days_reminder3 > 0) - { + $settings->num_days_reminder3 > 0) { $reminder_date = Carbon::parse($this->date)->addDays($settings->num_days_reminder3); - if(!$nsd) + if (!$nsd) { $nsd = $reminder_date; + } - if($reminder_date->lt($nsd)) + if ($reminder_date->lt($nsd)) { $nsd = $reminder_date; - + } } - if($settings->enable_reminder3 !== false && + if ($settings->enable_reminder3 !== false && $settings->schedule_reminder3 == 'before_due_date' && - $settings->num_days_reminder3 > 0) - { + $settings->num_days_reminder3 > 0) { $reminder_date = Carbon::parse($this->due_date)->subDays($settings->num_days_reminder3); - if(!$nsd) + if (!$nsd) { $nsd = $reminder_date; + } - if($reminder_date->lt($nsd)) + if ($reminder_date->lt($nsd)) { $nsd = $reminder_date; + } } - if($settings->enable_reminder3 !== false && + if ($settings->enable_reminder3 !== false && $settings->schedule_reminder3 == 'after_due_date' && - $settings->num_days_reminder3 > 0) - { + $settings->num_days_reminder3 > 0) { $reminder_date = Carbon::parse($this->due_date)->addDays($settings->num_days_reminder3); - if(!$nsd) + if (!$nsd) { $nsd = $reminder_date; + } - if($reminder_date->lt($nsd)) + if ($reminder_date->lt($nsd)) { $nsd = $reminder_date; + } } $this->next_send_date = $nsd; $this->save(); - } - } - diff --git a/app/Utils/Traits/NumberFormatter.php b/app/Utils/Traits/NumberFormatter.php index a5de01b17cf9..1a34f37e35ee 100644 --- a/app/Utils/Traits/NumberFormatter.php +++ b/app/Utils/Traits/NumberFormatter.php @@ -17,16 +17,13 @@ namespace App\Utils\Traits; */ trait NumberFormatter { - - private function formatValue($value, $precision) : string - { - + private function formatValue($value, $precision) : string + { return number_format($this->parseFloat($value), $precision, '.', ''); - - } + } - /** + /** * Parse a float value that may be delimited with either a comma or decimal point * * @param string $value The value @@ -44,7 +41,5 @@ trait NumberFormatter $value = preg_replace('/[^0-9\.\-]/', '', $value); return floatval($value); - } - -} \ No newline at end of file +} diff --git a/app/Utils/Traits/SettingsSaver.php b/app/Utils/Traits/SettingsSaver.php index 66b107d0a56e..603b6b976c64 100644 --- a/app/Utils/Traits/SettingsSaver.php +++ b/app/Utils/Traits/SettingsSaver.php @@ -20,177 +20,171 @@ use App\DataMapper\CompanySettings; trait SettingsSaver { - /** - * Saves a setting object - * - * Works for groups|clients|companies - * @param array $settings The request input settings array - * @param object $entity The entity which the settings belongs to - * @return void - */ - public function saveSettings($settings, $entity) - { + /** + * Saves a setting object + * + * Works for groups|clients|companies + * @param array $settings The request input settings array + * @param object $entity The entity which the settings belongs to + * @return void + */ + public function saveSettings($settings, $entity) + { + if (!$settings) { + return; + } - if(!$settings) - return; + $entity_settings = $this->settings; - $entity_settings = $this->settings; + //unset protected properties. + foreach (CompanySettings::$protected_fields as $field) { + unset($settings[$field]); + } - //unset protected properties. - foreach(CompanySettings::$protected_fields as $field) - unset($settings[$field]); + $settings = $this->checkSettingType($settings); - $settings = $this->checkSettingType($settings); + //iterate through set properties with new values; + foreach ($settings as $key => $value) { + $entity_settings->{$key} = $value; + } - //iterate through set properties with new values; - foreach($settings as $key => $value) - $entity_settings->{$key} = $value; + $entity->settings = $entity_settings; + $entity->save(); + } - $entity->settings = $entity_settings; - $entity->save(); - } + /** + * Used for custom validation of inbound + * settings request. + * + * Returns an array of errors, or boolean TRUE + * on successful validation + * @param array $settings The request() settings array + * @return array|bool Array on failure, boolean TRUE on success + */ + public function validateSettings($settings) + { + $settings = (object)$settings; + $casts = CompanySettings::$casts; - /** - * Used for custom validation of inbound - * settings request. - * - * Returns an array of errors, or boolean TRUE - * on successful validation - * @param array $settings The request() settings array - * @return array|bool Array on failure, boolean TRUE on success - */ - public function validateSettings($settings) - { - $settings = (object)$settings; - $casts = CompanySettings::$casts; + ksort($casts); - ksort($casts); + foreach ($casts as $key => $value) { - foreach ($casts as $key => $value){ + /*Separate loop if it is a _id field which is an integer cast as a string*/ + if (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter') { + $value = "integer"; + + if (!property_exists($settings, $key)) { + continue; + } elseif (!$this->checkAttribute($value, $settings->{$key})) { + return [$key, $value]; + } - /*Separate loop if it is a _id field which is an integer cast as a string*/ - if(substr($key, -3) == '_id' || substr($key, -14) == 'number_counter'){ - $value = "integer"; - - if(!property_exists($settings, $key)){ - continue; - } - else if(!$this->checkAttribute($value, $settings->{$key})){ - return [$key, $value]; - } + continue; + } - continue; - } + /* Handles unset settings or blank strings */ + if (!property_exists($settings, $key) || is_null($settings->{$key}) || !isset($settings->{$key}) || $settings->{$key} == '') { + continue; + } + - /* Handles unset settings or blank strings */ - if(!property_exists($settings, $key) || is_null($settings->{$key}) || !isset($settings->{$key}) || $settings->{$key} == '') - continue; - + /*Catch all filter */ + if (!$this->checkAttribute($value, $settings->{$key})) { + return [$key, $value]; + } + } - /*Catch all filter */ - if(!$this->checkAttribute($value, $settings->{$key})) - return [$key, $value]; - + return true; + } - } + /** + * Checks the settings object for + * correct property types. + * + * The method will drop invalid types from + * the object and will also settype() the property + * so that it can be saved cleanly + * + * @param array $settings The settings request() array + * @return object stdClass object + */ + private function checkSettingType($settings) : \stdClass + { + $settings = (object)$settings; + $casts = CompanySettings::$casts; + + foreach ($casts as $key => $value) { - return true; - } + /*Separate loop if it is a _id field which is an integer cast as a string*/ + if (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter') { + $value = "integer"; + + if (!property_exists($settings, $key)) { + continue; + } elseif ($this->checkAttribute($value, $settings->{$key})) { + if (substr($key, -3) == '_id') { + settype($settings->{$key}, 'string'); + } else { + settype($settings->{$key}, $value); + } + } else { + unset($settings->{$key}); + } - /** - * Checks the settings object for - * correct property types. - * - * The method will drop invalid types from - * the object and will also settype() the property - * so that it can be saved cleanly - * - * @param array $settings The settings request() array - * @return object stdClass object - */ - private function checkSettingType($settings) : \stdClass - { - $settings = (object)$settings; - $casts = CompanySettings::$casts; - - foreach ($casts as $key => $value){ + continue; + } - /*Separate loop if it is a _id field which is an integer cast as a string*/ - if(substr($key, -3) == '_id' || substr($key, -14) == 'number_counter'){ - $value = "integer"; - - if(!property_exists($settings, $key)){ - continue; - } - elseif($this->checkAttribute($value, $settings->{$key})){ + /* Handles unset settings or blank strings */ + if (!property_exists($settings, $key) || is_null($settings->{$key}) || !isset($settings->{$key}) || $settings->{$key} == '') { + continue; + } - if(substr($key, -3) == '_id') - settype($settings->{$key}, 'string'); - else - settype($settings->{$key}, $value); - - } - else { - unset($settings->{$key}); - } + /*Catch all filter */ + if ($this->checkAttribute($value, $settings->{$key})) { + if ($value == 'string' && is_null($settings->{$key})) { + $settings->{$key} = ''; + } - continue; - } + settype($settings->{$key}, $value); + } else { + unset($settings->{$key}); + } + } + return $settings; + } + - /* Handles unset settings or blank strings */ - if(!property_exists($settings, $key) || is_null($settings->{$key}) || !isset($settings->{$key}) || $settings->{$key} == ''){ - continue; - } - - /*Catch all filter */ - if($this->checkAttribute($value, $settings->{$key})){ - - if($value == 'string' && is_null($settings->{$key})) - $settings->{$key} = ''; - - settype($settings->{$key}, $value); - } - else { - unset($settings->{$key}); - } - - } - return $settings; - } - - - /** - * Type checks a object property. - * @param string $key The type - * @param string $value The object property - * @return bool TRUE if the property is the expected type - */ - private function checkAttribute($key, $value) :bool - { - switch ($key) - { - case 'int': - case 'integer': - return ctype_digit(strval($value)); - case 'real': - case 'float': - case 'double': - return is_float($value) || is_numeric(strval($value)); - case 'string': - return method_exists($value, '__toString' ) || is_null($value) || is_string($value); - case 'bool': - case 'boolean': - return is_bool($value) || (int) filter_var($value, FILTER_VALIDATE_BOOLEAN); - case 'object': - return is_object($value); - case 'array': - return is_array($value); - case 'json': - json_decode($string); - return (json_last_error() == JSON_ERROR_NONE); - default: - return false; - } - } - -} \ No newline at end of file + /** + * Type checks a object property. + * @param string $key The type + * @param string $value The object property + * @return bool TRUE if the property is the expected type + */ + private function checkAttribute($key, $value) :bool + { + switch ($key) { + case 'int': + case 'integer': + return ctype_digit(strval($value)); + case 'real': + case 'float': + case 'double': + return is_float($value) || is_numeric(strval($value)); + case 'string': + return method_exists($value, '__toString') || is_null($value) || is_string($value); + case 'bool': + case 'boolean': + return is_bool($value) || (int) filter_var($value, FILTER_VALIDATE_BOOLEAN); + case 'object': + return is_object($value); + case 'array': + return is_array($value); + case 'json': + json_decode($string); + return (json_last_error() == JSON_ERROR_NONE); + default: + return false; + } + } +} diff --git a/app/Utils/Traits/SystemLogTrait.php b/app/Utils/Traits/SystemLogTrait.php index 3604bea3755a..4a46e4fda618 100644 --- a/app/Utils/Traits/SystemLogTrait.php +++ b/app/Utils/Traits/SystemLogTrait.php @@ -20,24 +20,21 @@ use App\Models\SystemLog; */ trait SystemLogTrait { + public function sysLog($log, $category_id = SystemLog::GATEWAY_RESPONSE, $event_id = SystemLog::GATEWAY_FAILURE, Client $client = null) + { + if ($client != null) { + $this->client = $client; + } - public function sysLog($log, $category_id = SystemLog::GATEWAY_RESPONSE, $event_id = SystemLog::GATEWAY_FAILURE, Client $client = null) - { + $sl = [ + 'client_id' => $this->client->id, + 'company_id' => $this->client->company->id, + 'user_id' => $this->client->user_id, + 'log' => $log, + 'category_id' => $category_id, + 'event_id' => $event_id, + ]; - if($client != null) - $this->client = $client; - - $sl = [ - 'client_id' => $this->client->id, - 'company_id' => $this->client->company->id, - 'user_id' => $this->client->user_id, - 'log' => $log, - 'category_id' => $category_id, - 'event_id' => $event_id, - ]; - - SystemLog::create($sl); - - } - -} \ No newline at end of file + SystemLog::create($sl); + } +} diff --git a/app/Utils/Traits/ThrottlesEmail.php b/app/Utils/Traits/ThrottlesEmail.php index 7cdd35433371..8f495c230aec 100644 --- a/app/Utils/Traits/ThrottlesEmail.php +++ b/app/Utils/Traits/ThrottlesEmail.php @@ -21,20 +21,17 @@ use Illuminate\Support\Facades\Mail; */ trait ThrottlesEmail { - - - public function getDailyEmailLimit(Company $company) - { - $limit = config('ninja.daily_email_limit'); + public function getDailyEmailLimit(Company $company) + { + $limit = config('ninja.daily_email_limit'); $limit += $company->created_at->diffInMonths() * 100; return min($limit, 5000); - } + } - public function isThrottled(Company $company) + public function isThrottled(Company $company) { - $key = $company->company_key; // http://stackoverflow.com/questions/1375501/how-do-i-throttle-my-sites-api-users @@ -73,4 +70,4 @@ trait ThrottlesEmail return false; } -} \ No newline at end of file +} diff --git a/app/Utils/Traits/Uploadable.php b/app/Utils/Traits/Uploadable.php index 685f6778b5e1..dd0531a6d9f1 100644 --- a/app/Utils/Traits/Uploadable.php +++ b/app/Utils/Traits/Uploadable.php @@ -13,28 +13,23 @@ namespace App\Utils\Traits; use App\Jobs\Util\UploadAvatar; - /** * Class Uploadable * @package App\Utils\Traits */ trait Uploadable { - public function uploadLogo($file, $company, $entity) - { - if($file) - { - + public function uploadLogo($file, $company, $entity) + { + if ($file) { $path = UploadAvatar::dispatchNow($file, $company->company_key); - if($path){ - + if ($path) { $settings = $entity->settings; $settings->company_logo = $company->domain() . $path; $entity->settings = $settings; $entity->save(); } - } - } -} \ No newline at end of file + } +} diff --git a/app/Utils/Traits/UserSessionAttributes.php b/app/Utils/Traits/UserSessionAttributes.php index 2d49cbc11dd9..4ab15428f115 100644 --- a/app/Utils/Traits/UserSessionAttributes.php +++ b/app/Utils/Traits/UserSessionAttributes.php @@ -11,7 +11,6 @@ namespace App\Utils\Traits; - /** * Class UserSessionAttributes * @package App\Utils\Traits @@ -34,5 +33,4 @@ trait UserSessionAttributes { return session('current_company_id'); } - } diff --git a/app/Utils/Traits/UserSettings.php b/app/Utils/Traits/UserSettings.php index 96e0b792a764..115dc6cac184 100644 --- a/app/Utils/Traits/UserSettings.php +++ b/app/Utils/Traits/UserSettings.php @@ -18,21 +18,21 @@ namespace App\Utils\Traits; trait UserSettings { - /** - * @param string $entity - * @return \stdClass + /** + * @param string $entity + * @return \stdClass */ - public function getEntity(string $entity) : \stdClass - { - return $this->settings()->{$entity}; - } + public function getEntity(string $entity) : \stdClass + { + return $this->settings()->{$entity}; + } - /** - * @param string $entity - * @return \stdClass + /** + * @param string $entity + * @return \stdClass */ - public function getColumnVisibility(string $entity) : \stdClass - { - return $this->settings()->{class_basename($entity)}->datatable->column_visibility; - } -} \ No newline at end of file + public function getColumnVisibility(string $entity) : \stdClass + { + return $this->settings()->{class_basename($entity)}->datatable->column_visibility; + } +} diff --git a/app/Utils/TranslationHelper.php b/app/Utils/TranslationHelper.php index 41c7018b451a..1ba1f5545d7b 100644 --- a/app/Utils/TranslationHelper.php +++ b/app/Utils/TranslationHelper.php @@ -17,57 +17,56 @@ use Illuminate\Support\Str; class TranslationHelper { - - public static function getIndustries() - { - return Cache::get('industries')->each(function ($industry) { + public static function getIndustries() + { + return Cache::get('industries')->each(function ($industry) { $industry->name = ctrans('texts.industry_'.$industry->name); })->sortBy(function ($industry) { return $industry->name; }); - } + } - public static function getCountries() - { - return Cache::get('countries')->each(function ($country) { + public static function getCountries() + { + return Cache::get('countries')->each(function ($country) { $country->name = ctrans('texts.country_'.$country->name); })->sortBy(function ($country) { return $country->name; }); - } + } - public static function getPaymentTypes() - { - return Cache::get('payment_types')->each(function ($pType) { + public static function getPaymentTypes() + { + return Cache::get('payment_types')->each(function ($pType) { $pType->name = ctrans('texts.payment_type_'.$pType->name); })->sortBy(function ($pType) { return $pType->name; }); - } + } - public static function getLanguages() - { - return Cache::get('languages')->each(function ($lang) { + public static function getLanguages() + { + return Cache::get('languages')->each(function ($lang) { $lang->name = ctrans('texts.lang_'.$lang->name); })->sortBy(function ($lang) { return $lang->name; }); - } + } - public static function getCurrencies() - { - return Cache::get('currencies')->each(function ($currency) { + public static function getCurrencies() + { + return Cache::get('currencies')->each(function ($currency) { $currency->name = ctrans('texts.currency_' . Str::slug($currency->name, '_')); })->sortBy(function ($currency) { return $currency->name; }); - } + } - public static function getPaymentTerms() - { - return PaymentTerm::getCompanyTerms()->map(function ($term){ + public static function getPaymentTerms() + { + return PaymentTerm::getCompanyTerms()->map(function ($term) { $term['name'] = ctrans('texts.payment_terms_net') . ' ' . $term['num_days']; return $term; }); - } -} \ No newline at end of file + } +} diff --git a/composer.json b/composer.json index dd49d2b97cf2..e67625d3d4fd 100644 --- a/composer.json +++ b/composer.json @@ -28,11 +28,11 @@ "hashids/hashids": "^3.0", "intervention/image": "^2.4", "laracasts/presenter": "^0.2.1", - "laravel/framework": "6.0.*", + "laravel/framework": "^6", "laravel/slack-notification-channel": "^2.0", "laravel/socialite": "^4.0", "laravel/tinker": "^1.0", - "laravelcollective/html": "6.0.*", + "laravelcollective/html": "^6", "league/fractal": "^0.17.0", "league/omnipay": "^3.0", "maennchen/zipstream-php": "^1.2", diff --git a/routes/api.php b/routes/api.php index c9eb7e7f04f4..fec3de34761c 100644 --- a/routes/api.php +++ b/routes/api.php @@ -69,9 +69,11 @@ Route::group(['middleware' => ['api_db','api_secret_check','token_auth','locale' Route::post('payments/bulk', 'PaymentController@bulk')->name('payments.bulk'); // Route::resource('users', 'UserController')->middleware('password_protected'); // name = (users. index / create / show / update / destroy / edit - Route::resource('users', 'UserController'); // name = (users. index / create / show / update / destroy / edit - Route::post('users/{user}/attach_to_company', 'UserController@attach'); - Route::delete('users/{user}/detach_from_company','UserController@detach'); + Route::get('users', 'UserController@index'); + Route::put('users/{user}', 'UserController@update')->middleware('password_protected'); + Route::post('users', 'UserController@store')->middleware('password_protected'); + Route::post('users/{user}/attach_to_company', 'UserController@attach')->middleware('password_protected'); + Route::delete('users/{user}/detach_from_company','UserController@detach')->middleware('password_protected'); Route::post('users/bulk', 'UserController@bulk')->name('users.bulk')->middleware('password_protected'); diff --git a/tests/Feature/ClientTest.php b/tests/Feature/ClientTest.php index 7ca483f04c74..255a0a1d6400 100644 --- a/tests/Feature/ClientTest.php +++ b/tests/Feature/ClientTest.php @@ -182,6 +182,19 @@ class ClientTest extends TestCase $response->assertStatus(200); + $client->is_deleted = true; + $client->save(); + + + $client_update = [ + 'name' => 'Double Funk' + ]; + + $response = $this->withHeaders([ + 'X-API-SECRET' => config('ninja.api_secret'), + 'X-API-TOKEN' => $token, + ])->put('/api/v1/clients/'.$this->encodePrimaryKey($client->id), $client_update) + ->assertStatus(400); } diff --git a/tests/Feature/UserTest.php b/tests/Feature/UserTest.php index 209cd320e2e2..93c00e969d6a 100644 --- a/tests/Feature/UserTest.php +++ b/tests/Feature/UserTest.php @@ -56,7 +56,8 @@ class UserTest extends TestCase $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, - ])->get('/api/v1/users'); + 'X-API-PASSWORD' => 'ALongAndBriliantPassword', + ])->get('/api/v1/users'); $response->assertStatus(200); @@ -78,7 +79,8 @@ class UserTest extends TestCase $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, - ])->post('/api/v1/users?include=company_user', $data); + 'X-API-PASSWORD' => 'ALongAndBriliantPassword', + ])->post('/api/v1/users?include=company_user', $data); $response->assertStatus(200); @@ -97,7 +99,8 @@ class UserTest extends TestCase $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, - ])->post('/api/v1/users/'.$this->encodePrimaryKey($user->id).'/attach_to_company?include=company_user'); + 'X-API-PASSWORD' => 'ALongAndBriliantPassword', + ])->post('/api/v1/users/'.$this->encodePrimaryKey($user->id).'/attach_to_company?include=company_user'); $response->assertStatus(200); @@ -108,7 +111,8 @@ class UserTest extends TestCase $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, - ])->delete('/api/v1/users/'.$this->encodePrimaryKey($user->id).'/detach_from_company?include=company_user'); + 'X-API-PASSWORD' => 'ALongAndBriliantPassword', + ])->delete('/api/v1/users/'.$this->encodePrimaryKey($user->id).'/detach_from_company?include=company_user'); $response->assertStatus(200); @@ -213,6 +217,7 @@ class UserTest extends TestCase $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $user_1_company_token->token, + 'X-API-PASSWORD' => 'ALongAndBriliantPassword', ])->put('/api/v1/users/'.$this->encodePrimaryKey($user->id).'?include=company_user', $data); $response->assertStatus(200); diff --git a/tests/Integration/CheckCacheTest.php b/tests/Integration/CheckCacheTest.php index a4e771185e5c..00c15d37015b 100644 --- a/tests/Integration/CheckCacheTest.php +++ b/tests/Integration/CheckCacheTest.php @@ -34,6 +34,6 @@ class CheckCacheTest extends TestCase { $date_formats = Cache::get('date_formats'); - $this->assertEquals(13, count($date_formats)); + $this->assertEquals(14, count($date_formats)); } } \ No newline at end of file diff --git a/tests/Integration/MultiDBUserTest.php b/tests/Integration/MultiDBUserTest.php index ee8ef9c2366e..05c8016ed1f3 100644 --- a/tests/Integration/MultiDBUserTest.php +++ b/tests/Integration/MultiDBUserTest.php @@ -62,7 +62,7 @@ class MultiDBUserTest extends TestCase 'last_name' => 'user_db_1-s', 'phone' => '55555', 'email_verified_at' => now(), - 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret + 'password' => 'ALongAndBriliantPassword', // secret 'remember_token' => \Illuminate\Support\Str::random(10), 'email' => 'db1@example.com', 'oauth_user_id' => '123', @@ -75,7 +75,7 @@ class MultiDBUserTest extends TestCase 'last_name' => 'user_db_2-s', 'phone' => '55555', 'email_verified_at' => now(), - 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret + 'password' => 'ALongAndBriliantPassword', // secret 'remember_token' => \Illuminate\Support\Str::random(10), 'email' => 'db2@example.com', 'oauth_user_id' => 'abc', @@ -165,7 +165,7 @@ class MultiDBUserTest extends TestCase 'last_name' => 'you', 'email' => 'db2@example.com', 'company_user' => [ - 'is_admin' => false, + 'is_admin' => true, 'is_owner' => false, 'permissions' => 'create_client,create_invoice' ], @@ -175,9 +175,9 @@ class MultiDBUserTest extends TestCase $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, + 'X-API-PASSWORD' => 'ALongAndBriliantPassword', ])->post('/api/v1/users?include=company_user', $data); - } catch(ValidationException $e) { \Log::error('in the validator'); diff --git a/tests/MockAccountData.php b/tests/MockAccountData.php index 114bfedaabe7..1c6ba421d3d9 100644 --- a/tests/MockAccountData.php +++ b/tests/MockAccountData.php @@ -101,7 +101,7 @@ trait MockAccountData if(!$this->user){ $this->user = factory(\App\Models\User::class)->create([ - // 'account_id' => $account->id, + 'password' => 'ALongAndBriliantPassword', 'confirmation_code' => $this->createDbHash(config('database.default')) ]); }